text:
/**
 * Copyright (C) Omar Thor <omarthoro@gmail.com> - All Rights Reserved
 * Unauthorized copying of this file, via any medium is strictly prohibited
 * Proprietary and confidential
 *
 * Written by Omar Thor <omarthoro@gmail.com>, 2017
 */

#ifndef SP_ALGO_TESTING_GRADIENT_CHECK_HPP
#define	SP_ALGO_TESTING_GRADIENT_CHECK_HPP

#include <cmath>
#include <limits>
#include <random>
#include <vector>
#include <iterator>
#include <utility>
#include <memory>

#include <boost/assert.hpp>

#include "sp/config.hpp"
#include "random.hpp"
#include "sp/algo/nn/matrix.hpp"
#include "sp/algo/nn/types.hpp"
#include "sp/algo/nn/layer/detail/layers.hpp"
#include "layer/layer.hpp"

/**
 * @file Gradient check and validations
 *
 *
 * References:
 * - http://ufldl.stanford.edu/wiki/index.php/Gradient_checking_and_advanced_optimization
 * - http://cs231n.github.io/neural-networks-3/#gradcheck
 */

SP_ALGO_NN_NAMESPACE_BEGIN

namespace detail {

    /**
     * Helper
     * @param res
     */
    template<typename Tensor>
    void generate_uniform_into(Tensor& res) {
        auto& gen = random_generator::get();
        std:: uniform_real_distribution<float_t> dist(-1.0f, 1.0);
        std::for_each(res.data(), res.data() + res.size(), [&](auto& v) {
            v = dist(gen);
        });
    }

    template<typename T>
    void zero_range(T* start, T* end) {
        std::for_each(start, end, [](auto& v) { v = 0.0f; });
    }
}

/**
 * \brief Generate a random input_type
 */
template<typename Layer>
tensor_4 generate_inputs_for(const Layer& layer, const size_t& batch_size = 1) {
    using dims = typename Layer::input_dims;
    tensor_4 res(batch_size, dims::d, dims::h, dims::w);
    detail::generate_uniform_into(res);
    return res;
}

namespace detail {

    template<typename Container, typename TensorOrLayer>
    void layer_raw_data_vector_helper(Container& cont, TensorOrLayer& tol) {
        if constexpr (detail::is_layer_v<TensorOrLayer>) {
            if constexpr(detail::has_weight_and_delta_v<TensorOrLayer>) {
                BOOST_ASSERT(tol.w.size() > 0);
                cont.emplace_back(tol.w.data(), tol.w.data() + tol.w.size());
            }
            if constexpr(detail::has_bias_and_delta_v<TensorOrLayer>) {
                BOOST_ASSERT(tol.b.size() > 0);
                cont.emplace_back(tol.b.data(), tol.b.data() + tol.b.size());
            }
        } else {
            BOOST_ASSERT(tol.size() > 0);
            cont.emplace_back(tol.data(), tol.data() + tol.size());
        }
    }
}

/**
 * \brief A vector of pairs containing pointers to the range which the element
 *        of a layer, such as input, weight, bias are defined for.
 */
using layer_raw_data_vector_type = std::vector<std::pair<float_t*, float_t*>>;

/**
 * \brief Helper function that converts a layer and its data to a vector of
 *        pairwise range of pointers representing each tensor of different ranks
 *        such that they can be accessed index-wise regardless of dimensionality.
 */
template<typename ... TensorOrLayers>
layer_raw_data_vector_type
layer_raw_data_vector(TensorOrLayers& ... tols) {
   layer_raw_data_vector_type data;
   data.reserve(1 + sizeof...(TensorOrLayers));
   (detail::layer_raw_data_vector_helper(data, tols),  ...);
   return data;
}

/**
 * \brief Calculate the numerical gradient
 *
 *
 * Procedure is outlined in https://github.com/amaas/stanford_dl_ex/blob/master/ex1/grad_check.m
 * \param get_perturb_ref Returns a reference to the location to perturb.
 *        Function is invoked as get_perturb_ref(layer, in, out).
 * \param get_result Retrieves the output of the f(x). Same arguments as before.
 */
template<typename Layer>
float_t numerical_gradient(         Layer                               layer,
                                    tensor_4                          in,
                                    const std::pair<size_t, size_t>&    in_indexes,
                                    const size_t&                       out_index) {
    /**
     * sqrt(epsilon)
     * https://scicomp.stackexchange.com/questions/14355/choosing-epsilons
     */
    constexpr float_t h = std::sqrt(std::numeric_limits<float_t>::epsilon());
    const size_t batch_size = in.dimension(0);

    tensor_4 out;
    detail::prepare_and_zero_tensor<typename Layer::output_dims>(batch_size, out);

    /* retrieve array of pairs of pointers to floats, */
    auto in_data = layer_raw_data_vector(in);
    auto out_data = layer_raw_data_vector(out);

    auto& preturb = in_data[in_indexes.first].first[in_indexes.second];
    auto prev = preturb;

    preturb = prev - h;
    layer.forward_prop(in, out);
    float_t fx1 = out_data[0].first[out_index];

    //reset
    out.setZero();

    preturb = prev + h;
    layer.forward_prop(in, out);
    float_t fx2 = out_data[0].first[out_index];

    return (fx2 - fx1) / ( float_t(2.0f) * h);
}

/**
 * \brief Calculate the analytical gradient
 *
 * \param get_result Retrieves the output of the f'(x). Invoked as
 *        '''get_result(layer, in_delta,
 */
template<typename Layer>
float_t analytical_gradient(    Layer                               layer,
                                tensor_4                          prev_out,
                                const std::pair<size_t, size_t>&    in_indexes,
                                const size_t&                       out_index) {
    const size_t batch_size = prev_out.dimension(0);

    tensor_4 prev_delta;
    tensor_4 curr_out;
    tensor_4 curr_delta;

    /* initialize parameters */
    detail::prepare_and_zero_tensor<typename Layer::input_dims>(batch_size, prev_delta);
    detail::prepare_and_zero_tensor<typename Layer::output_dims>(batch_size, curr_out);
    detail::prepare_and_zero_tensor<typename Layer::output_dims>(batch_size, curr_delta);

    /* retrieve array of pairs of pointers to floats */
    auto in_grad= layer_raw_data_vector(prev_delta);
    auto out_grad = layer_raw_data_vector(curr_delta);

    out_grad[0].first[out_index] = 1.0f;

    layer.forward_prop(prev_out, curr_out);

    layer.backward_prop(prev_out, prev_delta, curr_out, curr_delta);

    return in_grad[in_indexes.first].first[in_indexes.second];
}

/**
 * \brief Calculates the relative error given the numerical gradient and the
 *        analytical gradient.
 */
float_t relative_error(float_t numerical_gradient, float_t analytical_gradient) {
    return (
            std::abs(numerical_gradient - analytical_gradient)
            /
            (std::max(std::abs(numerical_gradient), std::abs(analytical_gradient)))
    );
}

/**
 * \brief Selects a random element n out of Layer::output_dims::size
 */
template<typename Layer>
size_t gradient_random_output(const Layer& layer) {
    auto& rand = random_generator::get();
    return rand() % Layer::output_dims::size;
}

/**
 * \brief Selects a random input tensor and a random element n
 *        out of that
 */
template<typename Layer>
std::pair<size_t, size_t> gradient_random_input(const Layer& layer) {
    auto& rand = random_generator::get();
    size_t in_data_size = 1;
//    if constexpr(detail::has_weight_and_delta_v<Layer>) { ++in_data_size; }
    //    if constexpr(detail::has_bias_and_delta_v<Layer>)   { ++in_data_size; }
    auto data_idx = rand() % in_data_size;
    auto element_idx = rand() % Layer::input_dims::size;
    return {data_idx, element_idx};
}

SP_ALGO_NN_NAMESPACE_END

#endif	/* SP_ALGO_TESTING_GRADIENT_CHECK_HPP */

ext: hpp

max_stars_repo_name: thorigin/sp

max_issues_repo_name: thorigin/sp

max_forks_repo_name: thorigin/sp


text:
/*=============================================================================
    Copyright (c) 2003 Joel de Guzman

    Use, modification and distribution is subject to the Boost Software
    License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at
    http://www.boost.org/LICENSE_1_0.txt)
==============================================================================*/
#include <boost/detail/lightweight_test.hpp>
#include <boost/spirit/fusion/sequence/tuple.hpp>
#include <boost/spirit/fusion/sequence/io.hpp>
#include <boost/spirit/fusion/sequence/equal_to.hpp>
#include <boost/spirit/fusion/sequence/make_tuple.hpp>
#include <boost/spirit/fusion/algorithm/insert.hpp>
#include <boost/mpl/vector_c.hpp>
#include <boost/mpl/begin_end.hpp>
#include <boost/mpl/advance.hpp>
#include <boost/mpl/int.hpp>
#include <string>

int
main()
{
    using namespace boost::fusion;
    using boost::mpl::vector_c;
    using boost::mpl::advance;
    using boost::mpl::int_;
    namespace fusion = boost::fusion;
    namespace mpl = boost::mpl;

    std::cout << tuple_open('[');
    std::cout << tuple_close(']');
    std::cout << tuple_delimiter(", ");

/// Testing insert

    {
        char const* s = "Ruby";
        typedef tuple<int, char, double, char const*> tuple_type;
        tuple_type t1(1, 'x', 3.3, s);
        tuple_iterator<2, tuple_type> pos(t1);

        std::cout << insert(t1, pos, 123456) << std::endl;
        BOOST_TEST((insert(t1, pos, 123456)
            == make_tuple(1, 'x', 123456, 3.3, s)));

        std::cout << insert(t1, end(t1), 123456) << std::endl;
        BOOST_TEST((insert(t1, end(t1), 123456)
            == make_tuple(1, 'x', 3.3, s, 123456)));

        std::cout << insert(t1, begin(t1), "glad") << std::endl;
        BOOST_TEST((insert(t1, begin(t1), "glad")
            == make_tuple(std::string("glad"), 1, 'x', 3.3, s)));
    }

    {
        typedef vector_c<int, 1, 2, 3, 4, 5> mpl_vec;
        typedef mpl::begin<mpl_vec>::type mpl_vec_begin;
        typedef advance<mpl_vec_begin, int_<3> >::type mpl_vec_at3;

        std::cout << fusion::insert(mpl_vec(), mpl_vec_at3(), int_<66>()) << std::endl;
        BOOST_TEST((fusion::insert(mpl_vec(), mpl_vec_at3(), int_<66>())
            == make_tuple(1, 2, 3, 66, 4, 5)));
    }

    return boost::report_errors();
}

ext: cpp

max_stars_repo_name: spxuw/RFIM

max_issues_repo_name: spxuw/RFIM

max_forks_repo_name: spxuw/RFIM


text:
/*
 * This file is part of bogus, a C++ sparse block matrix library.
 *
 * Copyright 2013 Gilles Daviet <gdaviet@gmail.com>
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/

#ifndef BOGUS_EIGEN_LINEAR_SOLVERS
#define BOGUS_EIGEN_LINEAR_SOLVERS

#include "../Utils/LinearSolverBase.hpp"

#include <Eigen/LU>
#include <Eigen/Cholesky>

namespace bogus {

template<typename Decomposition, typename RhsType>
struct EigenSolveResult
{
#if EIGEN_VERSION_AT_LEAST(3,2,90)
	  typedef const Eigen::Solve< Decomposition, RhsType > Type ;
#else
	  typedef Eigen::internal::solve_retval< Decomposition, RhsType > Type ;
#endif
};

template < typename Derived >
struct LinearSolverTraits< LU< Eigen::MatrixBase< Derived > > >
{
	typedef typename Derived::PlainObject MatrixType ;
	typedef Eigen::FullPivLU< MatrixType > FactType ;

	template < typename RhsT > struct Result {
		typedef typename EigenSolveResult< FactType, RhsT >::Type Type ;
	} ;
	template < typename RhsT >
	struct Result< Eigen::MatrixBase< RhsT > > {
		typedef typename Result< RhsT >::Type Type ;
	} ;
} ;

template < typename Derived >
struct LU< Eigen::MatrixBase< Derived > >
		: public LinearSolverBase< LU< Eigen::MatrixBase< Derived > > >
{
	typedef Eigen::MatrixBase< Derived > MatrixType ;
	typedef LinearSolverTraits< LU< MatrixType > > Traits ;

	LU() {}
	template< typename OtherDerived >
	explicit LU ( const Eigen::MatrixBase< OtherDerived >& mat )
		: m_fact( mat )
	{}

	template< typename OtherDerived >
	LU< Eigen::MatrixBase< Derived > >& compute ( const Eigen::MatrixBase< OtherDerived >& mat )
	{
		m_fact.compute( mat ) ;
		return *this ;
	}

	template < typename RhsT, typename ResT >
	void solve( const Eigen::MatrixBase< RhsT >& rhs, ResT& res ) const
	{
		res = m_fact.solve( rhs ) ;
	}

	template < typename RhsT >
	typename Traits::template Result< Eigen::MatrixBase< RhsT > >::Type
	solve( const Eigen::MatrixBase< RhsT >& rhs ) const
	{
		return m_fact.solve( rhs ) ;
	}

  private:
	typename Traits::FactType m_fact ;
} ;

template < typename Scalar, int Rows, int Cols = Rows, int Options = 0 >
struct DenseLU : public LU< Eigen::MatrixBase< Eigen::Matrix< Scalar, Rows, Cols, Options > > >
{
	DenseLU() {}
	template< typename OtherDerived >
	explicit DenseLU ( const Eigen::MatrixBase< OtherDerived >& mat )
		: LU< Eigen::MatrixBase< Eigen::Matrix< Scalar, Rows, Cols, Options > > >( mat )
	{}
} ;

template < typename Derived >
struct LinearSolverTraits< LDLT< Eigen::MatrixBase< Derived > > >
{
	typedef typename Derived::PlainObject MatrixType ;
	typedef Eigen::LDLT< MatrixType > FactType ;

	template < typename RhsT > struct Result {
		typedef typename EigenSolveResult< FactType, RhsT >::Type Type ;
	} ;
	template < typename RhsT >
	struct Result< Eigen::MatrixBase< RhsT > > {
		typedef typename Result< RhsT >::Type Type ;
	} ;
} ;

template < typename Derived >
struct LDLT< Eigen::MatrixBase< Derived > >
		: public LinearSolverBase< LDLT< Eigen::MatrixBase< Derived > > >
{
	typedef Eigen::MatrixBase< Derived > MatrixType ;
	typedef LinearSolverTraits< LDLT< MatrixType > > Traits ;

	LDLT() {}
	template< typename OtherDerived >
	explicit LDLT ( const Eigen::MatrixBase< OtherDerived >& mat )
		: m_fact( mat )
	{}

	template< typename OtherDerived >
	LDLT< Eigen::MatrixBase< Derived > >& compute ( const Eigen::MatrixBase< OtherDerived >& mat )
	{
		m_fact.compute( mat ) ;
		return *this ;
	}

	template < typename RhsT, typename ResT >
	void solve( const Eigen::MatrixBase< RhsT >& rhs, ResT& res ) const
	{
		res = m_fact.solve( rhs ) ;
	}

	template < typename RhsT >
	typename Traits::template Result< Eigen::MatrixBase< RhsT > >::Type
	solve( const Eigen::MatrixBase< RhsT >& rhs ) const
	{
		return m_fact.solve( rhs ) ;
	}

  private:
	typename Traits::FactType m_fact ;
} ;

template < typename Scalar, int Rows, int Options = 0 >
struct DenseLDLT : public LDLT< Eigen::MatrixBase< Eigen::Matrix< Scalar, Rows, Rows, Options > > >
{
	DenseLDLT() {}
	template< typename OtherDerived >
	explicit DenseLDLT ( const Eigen::MatrixBase< OtherDerived >& mat )
		: LDLT< Eigen::MatrixBase< Eigen::Matrix< Scalar, Rows, Rows, Options > > >( mat )
	{}
} ;

template < typename Derived, typename RhsT >
typename LinearSolverTraits< Derived >::template Result< Eigen::MatrixBase< RhsT > >::Type operator*
	( const LinearSolverBase< Derived >& solver, const Eigen::MatrixBase< RhsT >& rhs )
{
  return solver.solve( rhs ) ;
}

} //namespace bogus

#endif

max_stars_repo_name: sjokic/WallDestruction

max_issues_repo_name: sjokic/WallDestruction

max_forks_repo_name: sjokic/WallDestruction


text:
// Copyright 2004-present Facebook. All Rights Reserved.

#include <fstream>

#include <boost/filesystem/operations.hpp>

#include "osquery/config/plugin.h"
#include "osquery/flags.h"

namespace fs = boost::filesystem;
using osquery::Status;

namespace osquery {

DEFINE_osquery_flag(string,
                    config_path,
                    "/var/osquery/osquery.conf",
                    "Path to config file");

class FilesystemConfigPlugin : public ConfigPlugin {
 public:
  virtual std::pair<osquery::Status, std::string> genConfig() {
    std::string config;
    if (!fs::exists(FLAGS_config_path)) {
      return std::make_pair(Status(1, "config file does not exist"), config);
    }

    std::ifstream config_stream(FLAGS_config_path);

    config_stream.seekg(0, std::ios::end);
    config.reserve(config_stream.tellg());
    config_stream.seekg(0, std::ios::beg);

    config.assign((std::istreambuf_iterator<char>(config_stream)),
                  std::istreambuf_iterator<char>());
    return std::make_pair(Status(0, "OK"), config);
  }
};

REGISTER_CONFIG_PLUGIN("filesystem",
                       std::make_shared<osquery::FilesystemConfigPlugin>());
}

max_stars_repo_name: bowlofstew/osquery

max_issues_repo_name: bowlofstew/osquery

max_forks_repo_name: bowlofstew/osquery


text:
/*
 *    Copyright (C) 2014 MongoDB Inc.
 *
 *    This program is free software: you can redistribute it and/or  modify
 *    it under the terms of the GNU Affero General Public License, version 3,
 *    as published by the Free Software Foundation.
 *
 *    This program 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 Affero General Public License for more details.
 *
 *    You should have received a copy of the GNU Affero General Public License
 *    along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *
 *    As a special exception, the copyright holders give permission to link the
 *    code of portions of this program with the OpenSSL library under certain
 *    conditions as described in each individual source file and distribute
 *    linked combinations including the program with the OpenSSL library. You
 *    must comply with the GNU Affero General Public License in all respects for
 *    all of the code used other than as permitted herein. If you modify file(s)
 *    with this exception, you may extend this exception to your version of the
 *    file(s), but you are not obligated to do so. If you do not wish to do so,
 *    delete this exception statement from your version. If you delete this
 *    exception statement from all source files in the program, then also delete
 *    it in the license file.
 */

#define MONGO_LOG_DEFAULT_COMPONENT ::mongo::logger::LogComponent::kAccessControl

#include "mongo/platform/basic.h"

#include "mongo/db/auth/sasl_scram_server_conversation.h"

#include <boost/algorithm/string/join.hpp>
#include <boost/algorithm/string/replace.hpp>

#include "mongo/base/disallow_copying.h"
#include "mongo/base/init.h"
#include "mongo/base/status.h"
#include "mongo/base/string_data.h"
#include "mongo/crypto/mechanism_scram.h"
#include "mongo/crypto/sha1_block.h"
#include "mongo/db/auth/sasl_mechanism_policies.h"
#include "mongo/db/auth/sasl_mechanism_registry.h"
#include "mongo/db/auth/sasl_options.h"
#include "mongo/platform/random.h"
#include "mongo/util/base64.h"
#include "mongo/util/log.h"
#include "mongo/util/mongoutils/str.h"
#include "mongo/util/sequence_util.h"
#include "mongo/util/text.h"

namespace mongo {

template <typename Policy>
StatusWith<std::tuple<bool, std::string>> SaslSCRAMServerMechanism<Policy>::stepImpl(
    OperationContext* opCtx, StringData inputData) {
    _step++;

    if (_step > 3 || _step <= 0) {
        return Status(ErrorCodes::AuthenticationFailed,
                      str::stream() << "Invalid SCRAM authentication step: " << _step);
    }

    if (_step == 1) {
        return _firstStep(opCtx, inputData);
    }
    if (_step == 2) {
        return _secondStep(opCtx, inputData);
    }

    return std::make_tuple(true, std::string{});
}

/*
 * RFC 5802 specifies that in SCRAM user names characters ',' and '=' are encoded as
 * =2C and =3D respectively.
 */
static void decodeSCRAMUsername(std::string& user) {
    boost::replace_all(user, "=2C", ",");
    boost::replace_all(user, "=3D", "=");
}

/*
 * Parse client-first-message of the form:
 * n,a=authzid,n=encoded-username,r=client-nonce
 *
 * Generate server-first-message on the form:
 * r=client-nonce|server-nonce,s=user-salt,i=iteration-count
 *
 * NOTE: we are ignoring the authorization ID part of the message
 */
template <typename Policy>
StatusWith<std::tuple<bool, std::string>> SaslSCRAMServerMechanism<Policy>::_firstStep(
    OperationContext* opCtx, StringData inputData) {
    const auto badCount = [](int got) {
        return Status(ErrorCodes::BadValue,
                      str::stream()
                          << "Incorrect number of arguments for first SCRAM client message, got "
                          << got
                          << " expected at least 3");
    };

    /**
     * gs2-cbind-flag := ("p=" cb-name) / 'y' / 'n'
     * gs2-header := gs2-cbind-flag ',' [ authzid ] ','
     * reserved-mext := "m=" 1*(value-char)
     * client-first-message-bare := [reserved-mext  ','] username ',' nonce [',' extensions]
     * client-first-message := gs2-header client-first-message-bare
     */
    const auto gs2_cbind_comma = inputData.find(',');
    if (gs2_cbind_comma == std::string::npos) {
        return badCount(1);
    }
    const auto gs2_cbind_flag = inputData.substr(0, gs2_cbind_comma);
    if (gs2_cbind_flag.startsWith("p=")) {
        return Status(ErrorCodes::BadValue, "Server does not support channel binding");
    }

    if ((gs2_cbind_flag != "y") && (gs2_cbind_flag != "n")) {
        return Status(ErrorCodes::BadValue,
                      str::stream() << "Incorrect SCRAM client message prefix: " << gs2_cbind_flag);
    }

    const auto gs2_header_comma = inputData.find(',', gs2_cbind_comma + 1);
    if (gs2_header_comma == std::string::npos) {
        return badCount(2);
    }
    auto authzId = inputData.substr(gs2_cbind_comma + 1, gs2_header_comma - (gs2_cbind_comma + 1));
    if (authzId.size()) {
        if (authzId.startsWith("a=")) {
            authzId = authzId.substr(2);
        } else {
            return Status(ErrorCodes::BadValue,
                          str::stream() << "Incorrect SCRAM authzid: " << authzId);
        }
    }

    const auto client_first_message_bare = inputData.substr(gs2_header_comma + 1);
    if (client_first_message_bare.startsWith("m=")) {
        return Status(ErrorCodes::BadValue, "SCRAM mandatory extensions are not supported");
    }

    /* StringSplitter::split() will ignore consecutive delimiters.
     * e.g. "foo,,bar" => {"foo","bar"}
     * This makes our implementation of SCRAM *slightly* more generous
     * in what it will accept than the standard calls for.
     *
     * This does not impact _authMessage, as it's composed from the raw
     * string input, rather than the output of the split operation.
     */
    const auto input = StringSplitter::split(client_first_message_bare.toString(), ",");

    if (input.size() < 2) {
        // gs2-header is not included in this count, so add it back in.
        return badCount(input.size() + 2);
    }

    if (!str::startsWith(input[0], "n=") || input[0].size() < 3) {
        return Status(ErrorCodes::BadValue,
                      str::stream() << "Invalid SCRAM user name: " << input[0]);
    }
    ServerMechanismBase::_principalName = input[0].substr(2);
    decodeSCRAMUsername(ServerMechanismBase::_principalName);

    if (!authzId.empty() && ServerMechanismBase::_principalName != authzId) {
        return Status(ErrorCodes::BadValue,
                      str::stream() << "SCRAM user name " << ServerMechanismBase::_principalName
                                    << " does not match authzid "
                                    << authzId);
    }

    if (!str::startsWith(input[1], "r=") || input[1].size() < 6) {
        return Status(ErrorCodes::BadValue,
                      str::stream() << "Invalid SCRAM client nonce: " << input[1]);
    }
    const auto clientNonce = input[1].substr(2);

    // SERVER-16534, SCRAM-SHA-1 must be enabled for authenticating the internal user, so that
    // cluster members may communicate with each other. Hence ignore disabled auth mechanism
    // for the internal user.
    UserName user(ServerMechanismBase::ServerMechanismBase::_principalName,
                  ServerMechanismBase::getAuthenticationDatabase());
    if (!sequenceContains(saslGlobalParams.authenticationMechanisms, "SCRAM-SHA-1") &&
        user != internalSecurity.user->getName()) {
        return Status(ErrorCodes::BadValue, "SCRAM-SHA-1 authentication is disabled");
    }

    // The authentication database is also the source database for the user.
    User* userObj;
    auto authManager = AuthorizationManager::get(opCtx->getServiceContext());

    Status status = authManager->acquireUser(opCtx, user, &userObj);
    if (!status.isOK()) {
        return status;
    }

    User::CredentialData credentials = userObj->getCredentials();
    UserName userName = userObj->getName();

    authManager->releaseUser(userObj);

    _scramCredentials = credentials.scram<HashBlock>();

    if (!_scramCredentials.isValid()) {
        // Check for authentication attempts of the __system user on
        // systems started without a keyfile.
        if (userName == internalSecurity.user->getName()) {
            return Status(ErrorCodes::AuthenticationFailed,
                          "It is not possible to authenticate as the __system user "
                          "on servers started without a --keyFile parameter");
        } else {
            return Status(ErrorCodes::AuthenticationFailed,
                          "Unable to perform SCRAM authentication for a user with missing "
                          "or invalid SCRAM credentials");
        }
    }

    _secrets = scram::Secrets<HashBlock>("",
                                         base64::decode(_scramCredentials.storedKey),
                                         base64::decode(_scramCredentials.serverKey));

    // Generate server-first-message
    // Create text-based nonce as base64 encoding of a binary blob of length multiple of 3
    const int nonceLenQWords = 3;
    uint64_t binaryNonce[nonceLenQWords];

    std::unique_ptr<SecureRandom> sr(SecureRandom::create());

    binaryNonce[0] = sr->nextInt64();
    binaryNonce[1] = sr->nextInt64();
    binaryNonce[2] = sr->nextInt64();

    _nonce =
        clientNonce + base64::encode(reinterpret_cast<char*>(binaryNonce), sizeof(binaryNonce));
    StringBuilder sb;
    sb << "r=" << _nonce << ",s=" << _scramCredentials.salt
       << ",i=" << _scramCredentials.iterationCount;
    std::string outputData = sb.str();

    // add client-first-message-bare and server-first-message to _authMessage
    _authMessage = client_first_message_bare.toString() + "," + outputData;

    return std::make_tuple(false, std::move(outputData));
}

/**
 * Parse client-final-message of the form:
 * c=channel-binding(base64),r=client-nonce|server-nonce,p=ClientProof
 *
 * Generate successful authentication server-final-message on the form:
 * v=ServerSignature
 *
 * or failed authentication server-final-message on the form:
 * e=message
 *
 * NOTE: we are ignoring the channel binding part of the message
**/
template <typename Policy>
StatusWith<std::tuple<bool, std::string>> SaslSCRAMServerMechanism<Policy>::_secondStep(
    OperationContext* opCtx, StringData inputData) {
    const auto badCount = [](int got) {
        return Status(ErrorCodes::BadValue,
                      str::stream()
                          << "Incorrect number of arguments for second SCRAM client message, got "
                          << got
                          << " expected at least 3");
    };

    /**
     * client-final-message-without-proof := cbind ',' nonce ',' [ ',' extensions ]
     * client-final-message := client-final-message-without-proof ',' proof
     */
    const auto last_comma = inputData.rfind(',');
    if (last_comma == std::string::npos) {
        return badCount(1);
    }

    // add client-final-message-without-proof to authMessage
    const auto client_final_message_without_proof = inputData.substr(0, last_comma);
    _authMessage += "," + client_final_message_without_proof.toString();

    const auto last_field = inputData.substr(last_comma + 1);
    if ((last_field.size() < 3) || !last_field.startsWith("p=")) {
        return Status(ErrorCodes::BadValue,
                      str::stream() << "Incorrect SCRAM ClientProof: " << last_field);
    }
    const auto proof = last_field.substr(2);

    const auto input = StringSplitter::split(client_final_message_without_proof.toString(), ",");
    if (input.size() < 2) {
        // Add count for proof back on.
        return badCount(input.size() + 1);
    }

    if (!str::startsWith(input[0], "c=") || input[0].size() < 3) {
        return Status(ErrorCodes::BadValue,
                      str::stream() << "Incorrect SCRAM channel binding: " << input[0]);
    }
    const auto cbind = input[0].substr(2);

    if (!str::startsWith(input[1], "r=") || input[1].size() < 6) {
        return Status(ErrorCodes::BadValue,
                      str::stream() << "Incorrect SCRAM client|server nonce: " << input[1]);
    }
    const auto nonce = input[1].substr(2);

    // Concatenated nonce sent by client should equal the one in server-first-message
    if (nonce != _nonce) {
        return Status(ErrorCodes::BadValue,
                      str::stream()
                          << "Unmatched SCRAM nonce received from client in second step, expected "
                          << _nonce
                          << " but received "
                          << nonce);
    }

    // Do server side computations, compare storedKeys and generate client-final-message
    // AuthMessage     := client-first-message-bare + "," +
    //                    server-first-message + "," +
    //                    client-final-message-without-proof
    // ClientSignature := HMAC(StoredKey, AuthMessage)
    // ClientKey := ClientSignature XOR ClientProof
    // ServerSignature := HMAC(ServerKey, AuthMessage)

    if (!_secrets.verifyClientProof(_authMessage, base64::decode(proof.toString()))) {
        return Status(ErrorCodes::AuthenticationFailed,
                      "SCRAM authentication failed, storedKey mismatch");
    }

    StringBuilder sb;
    // ServerSignature := HMAC(ServerKey, AuthMessage)
    sb << "v=" << _secrets.generateServerSignature(_authMessage);

    return std::make_tuple(false, sb.str());
}

template class SaslSCRAMServerMechanism<SCRAMSHA1Policy>;
template class SaslSCRAMServerMechanism<SCRAMSHA256Policy>;

MONGO_INITIALIZER_WITH_PREREQUISITES(SASLSCRAMServerMechanism,
                                     ("CreateSASLServerMechanismRegistry"))
(::mongo::InitializerContext* context) {
    auto& registry = SASLServerMechanismRegistry::get(getGlobalServiceContext());
    registry.registerFactory<SCRAMSHA1ServerFactory>();
    registry.registerFactory<SCRAMSHA256ServerFactory>();
    return Status::OK();
}

}  // namespace mongo

max_stars_repo_name: qconner/mongo

max_issues_repo_name: qconner/mongo

max_forks_repo_name: qconner/mongo


text:
/*
   Copyright 2018 Simon Vogl <svogl@voxel.at>
                  Angel Merino-Sastre <amerino@voxel.at>

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
*/
#include <sstream>
#include <boost/log/trivial.hpp>

#include <boost/lexical_cast.hpp>
#include <boost/format.hpp>

#if OCV_VERSION_MAJOR >= 3
#include <opencv2/highgui.hpp>
#else
#  include <opencv2/highgui/highgui.hpp>
#endif

#include <toffy/detection/detectedObject.hpp>
#include <toffy/detection/objectTrack.hpp>

using namespace toffy;
using namespace toffy::detection;
//using namespace cv;
using namespace std;

#ifdef CM_DEBUG
const bool dbg=true;
#else
const bool dbg=false;
#endif

std::size_t ObjectTrack::_filter_counter = 1;
const std::string ObjectTrack::id_name = "objectTrack";

ObjectTrack::ObjectTrack(): Filter(ObjectTrack::id_name,_filter_counter),
			    _in_img("img"), _in_vec("objects"), _out_vec("dect"), cnt(0), numObjects(0), updateScript("updateCount.sh")
{
    _filter_counter++;

}

boost::property_tree::ptree ObjectTrack::getConfig() const {
    BOOST_LOG_TRIVIAL(debug) << __FUNCTION__ <<  " " << id();
    boost::property_tree::ptree pt;

    pt = Filter::getConfig();
    //pt.put("options.max_x", _max_x);

    pt.put("inputs.img", _in_img);
    pt.put("inputs.vec", _in_vec);
    pt.put("outputs.vec", _out_vec);

    return pt;
}

void ObjectTrack::updateConfig(const boost::property_tree::ptree &pt) {
    BOOST_LOG_TRIVIAL(debug) << __FUNCTION__ <<  " " << id();

    using namespace boost::property_tree;

    Filter::updateConfig(pt);

    //_max_x = pt.get<float>("options.max_x",_max_x);

    _in_img = pt.get<string>("inputs.img",_in_img);
    _in_vec = pt.get<string>("inputs.vec",_in_vec);
    _out_vec = pt.get<string>("outputs.vec",_out_vec);

    updateScript = pt.get<string>("options.script", updateScript);

}

bool ObjectTrack::filter(const Frame& in, Frame& out) {
    BOOST_LOG_TRIVIAL(debug) << __FUNCTION__ << " " << id();

    toffy::Filter::setLoggingLvl();

    //List of detected objects
    BOOST_LOG_TRIVIAL(debug) << "Getting _in_vec: " << _in_vec;
    boost::shared_ptr<std::vector<detection::DetectedObject*> > detObjs;
    try {
        detObjs = boost::any_cast<boost::shared_ptr<std::vector<detection::DetectedObject*> > >(in.getData(_in_vec));
    } catch(const boost::bad_any_cast &) {
        BOOST_LOG_TRIVIAL(warning) << "Could not find object vector: " <<
                                      _in_vec << ". " << id();
        return true;
    }

    BOOST_LOG_TRIVIAL(debug) << "Got _in_vec(" << _in_vec << "): " << detObjs->size();

    // TODO Where come img from?, why we mask it with the objects.
    BOOST_LOG_TRIVIAL(debug) << "Getting got _in_img: " << _in_img;
    boost::shared_ptr<cv::Mat> img;
    try {
        img = in.getMatPtr(_in_img);
    } catch(const boost::bad_any_cast &) {
        BOOST_LOG_TRIVIAL(warning) <<
                                      "Could not cast input " << _in_img <<
                                      ", filter  " << id() <<" does not show objects.";
    }

    //Define zones!!!
    cv::Rect z1(0,0,img->cols, (img->rows/2)-1);

    cv::Rect z2(0,0,img->cols, (img->rows/2)-1);

    cv::Mat color;

    double max, min;
    minMaxIdx(*img, &min, &max);
    img->convertTo(color,CV_8U,255.0/(max-min),-255.0*min/(max-min));
    cvtColor(color,color, cv::COLOR_GRAY2RGB);

    vector<detection::DetectedObject*>::iterator objDetIter = detObjs->begin();
    while ( objDetIter != detObjs->end() ) {
        detection::DetectedObject* obj = *objDetIter;
        if (obj->record->empty()) {
            objDetIter++;
            continue;
        }

        if (z1.contains(obj->firstCenter)) {
           if (z1.contains(obj->massCenter))
            BOOST_LOG_TRIVIAL(debug) << "IN ZONE 1";
           else {
               obj->firstCenter = obj->massCenter;
               BOOST_LOG_TRIVIAL(debug) << "Change to zone 2";
               cnt++;
	       publishCount();
           }
        } else {
            if (!z1.contains(obj->massCenter))
             BOOST_LOG_TRIVIAL(debug) << "IN ZONE 2";
            else {
                obj->firstCenter = obj->massCenter;
                BOOST_LOG_TRIVIAL(debug) << "Change to zone 1";
                cnt--;
 	        publishCount();
            }
        }

        BOOST_LOG_TRIVIAL(debug) << "Old: " << obj->record->back()->massCenter3D;
        BOOST_LOG_TRIVIAL(debug) << "New: " << obj->massCenter3D;
        double dis = cv::norm(obj->massCenter3D - obj->record->front()->massCenter3D );
        BOOST_LOG_TRIVIAL(debug) << "dis: " << dis;
        boost::posix_time::time_duration time = obj->record->front()->ts - obj->ts;
        BOOST_LOG_TRIVIAL(debug) << "time: " << time.seconds();
        double speed = dis/time.seconds();
        BOOST_LOG_TRIVIAL(debug) << "speed: " << speed;

        cv::arrowedLine(color, obj->record->back()->massCenter, obj->massCenter, CV_RGB(255, 255, 0));

        cv::line(color,cv::Point(z1.x,z1.height),z1.br(),CV_RGB(255, 0, 0),1);

        cv::putText	(color, boost::str(boost::format("%.4f") % speed) + " m/s", cv::Point(10,20),
                 cv::FONT_HERSHEY_SIMPLEX, 0.5, CV_RGB(255, 255, 0));

        cv::putText	(color, boost::lexical_cast<std::string>(cnt), cv::Point(10,50),
                 cv::FONT_HERSHEY_SIMPLEX, 0.5, CV_RGB(255, 255, 0));

        objDetIter++;

	cv::namedWindow("objectTrack", cv::WINDOW_NORMAL);
	imshow("objectTrack", color);

    }
    if (numObjects!= detObjs->size())
      publishCount();

    numObjects = detObjs->size();

    return true;
}

void ObjectTrack::publishCount()
{
    std::stringstream sb;
    sb <<  updateScript << " " << cnt << " " << numObjects << "&";

    BOOST_LOG_TRIVIAL(debug) << "publ: " << sb.str();

    system ( sb.str().c_str() );
}

max_stars_repo_name: voxel-dot-at/toffy

max_issues_repo_name: voxel-dot-at/toffy

max_forks_repo_name: voxel-dot-at/toffy


text:
#include "PS2VM.h"
#include <boost/filesystem.hpp>
#include "StdStream.h"
#include "StdStreamUtils.h"
#include "iop/IopBios.h"
#include "JUnitTestReportWriter.h"
#include "gs/GSH_Null.h"
#ifdef _WIN32
#include "ui_win32/GSH_OpenGLWin32.h"
#include "ui_win32/GSH_Direct3D9/GSH_Direct3D9.h"
#endif

#define GS_HANDLER_NAME_NULL "null"
#define GS_HANDLER_NAME_OGL "ogl"
#define GS_HANDLER_NAME_D3D9 "d3d9"

#define DEFAULT_GS_HANDLER_NAME GS_HANDLER_NAME_NULL

static std::set<std::string> g_validGsHandlersNames =
    {
        GS_HANDLER_NAME_NULL,
#ifdef _WIN32
        GS_HANDLER_NAME_OGL,
        GS_HANDLER_NAME_D3D9,
#endif
};

#ifdef _WIN32

class CTestWindow : public Framework::Win32::CWindow, public CSingleton<CTestWindow>
{
public:
	CTestWindow()
	{
		Create(0, Framework::Win32::CDefaultWndClass::GetName(), _T(""), WS_OVERLAPPED, Framework::Win32::CRect(0, 0, 100, 100), NULL, NULL);
		SetClassPtr();
	}
};

#endif

CGSHandler::FactoryFunction GetGsHandlerFactoryFunction(const std::string& gsHandlerName)
{
	if(gsHandlerName == GS_HANDLER_NAME_NULL)
	{
		return CGSH_Null::GetFactoryFunction();
	}
#ifdef _WIN32
	else if(gsHandlerName == GS_HANDLER_NAME_OGL)
	{
		return CGSH_OpenGLWin32::GetFactoryFunction(&CTestWindow::GetInstance());
	}
	else if(gsHandlerName == GS_HANDLER_NAME_D3D9)
	{
		return CGSH_Direct3D9::GetFactoryFunction(&CTestWindow::GetInstance());
	}
#endif
	else
	{
		throw std::runtime_error("Unknown GS handler name.");
	}
}

std::vector<std::string> ReadLines(Framework::CStream& inputStream)
{
	std::vector<std::string> lines;
	lines.push_back(inputStream.ReadLine());
	while(!inputStream.IsEOF())
	{
		lines.push_back(inputStream.ReadLine());
	}
	return lines;
}

TESTRESULT GetTestResult(const boost::filesystem::path& testFilePath)
{
	TESTRESULT result;
	result.succeeded = false;
	try
	{
		auto resultFilePath = testFilePath;
		resultFilePath.replace_extension(".result");
		auto expectedFilePath = testFilePath;
		expectedFilePath.replace_extension(".expected");
		auto resultStream = Framework::CreateInputStdStream(resultFilePath.string());
		auto expectedStream = Framework::CreateInputStdStream(expectedFilePath.string());

		auto resultLines = ReadLines(resultStream);
		auto expectedLines = ReadLines(expectedStream);

		if(resultLines.size() != expectedLines.size()) return result;

		for(unsigned int i = 0; i < resultLines.size(); i++)
		{
			if(resultLines[i] != expectedLines[i])
			{
				LINEDIFF lineDiff;
				lineDiff.expected = expectedLines[i];
				lineDiff.result = resultLines[i];
				result.lineDiffs.push_back(lineDiff);
			}
		}

		result.succeeded = result.lineDiffs.empty();
		return result;
	}
	catch(...)
	{
	}
	return result;
}

void ExecuteEeTest(const boost::filesystem::path& testFilePath, const std::string& gsHandlerName)
{
	auto resultFilePath = testFilePath;
	resultFilePath.replace_extension(".result");
	auto resultStream = new Framework::CStdStream(resultFilePath.string().c_str(), "wb");

	bool executionOver = false;

	//Setup virtual machine
	CPS2VM virtualMachine;
	virtualMachine.Initialize();
	virtualMachine.Reset();
	virtualMachine.CreateGSHandler(GetGsHandlerFactoryFunction(gsHandlerName));
	virtualMachine.m_ee->m_os->OnRequestExit.connect(
	    [&executionOver]() {
		    executionOver = true;
	    });
	virtualMachine.m_ee->m_os->BootFromFile(testFilePath);
	{
		auto iopOs = dynamic_cast<CIopBios*>(virtualMachine.m_iop->m_bios.get());
		iopOs->GetIoman()->SetFileStream(Iop::CIoman::FID_STDOUT, resultStream);
	}
	virtualMachine.Resume();

	while(!executionOver)
	{
		std::this_thread::sleep_for(std::chrono::milliseconds(100));
	}

	virtualMachine.Pause();
	virtualMachine.DestroyGSHandler();
	virtualMachine.Destroy();
}

void ExecuteIopTest(const boost::filesystem::path& testFilePath)
{
	//Read in the module data
	std::vector<uint8> moduleData;
	{
		auto moduleStream = Framework::CreateInputStdStream(testFilePath.native());
		auto length = moduleStream.GetLength();
		moduleData.resize(length);
		moduleStream.Read(moduleData.data(), length);
	}

	auto resultFilePath = testFilePath;
	resultFilePath.replace_extension(".result");
	auto resultStream = new Framework::CStdStream(resultFilePath.string().c_str(), "wb");

	bool executionOver = false;

	//Setup virtual machine
	CPS2VM virtualMachine;
	virtualMachine.Initialize();
	virtualMachine.Reset();
	{
		auto iopOs = dynamic_cast<CIopBios*>(virtualMachine.m_iop->m_bios.get());
		int32 rootModuleId = iopOs->LoadModuleFromHost(moduleData.data());
		iopOs->OnModuleStarted.connect(
		    [&executionOver, &rootModuleId](uint32 moduleId) {
			    if(rootModuleId == moduleId)
			    {
				    executionOver = true;
			    }
		    });
		iopOs->StartModule(rootModuleId, "", nullptr, 0);
		iopOs->GetIoman()->SetFileStream(Iop::CIoman::FID_STDOUT, resultStream);
	}
	virtualMachine.Resume();

	while(!executionOver)
	{
		std::this_thread::sleep_for(std::chrono::milliseconds(100));
	}

	virtualMachine.Pause();
	virtualMachine.Destroy();
}

void ScanAndExecuteTests(const boost::filesystem::path& testDirPath, const TestReportWriterPtr& testReportWriter, const std::string& gsHandlerName)
{
	boost::filesystem::directory_iterator endIterator;
	for(auto testPathIterator = boost::filesystem::directory_iterator(testDirPath);
	    testPathIterator != endIterator; testPathIterator++)
	{
		auto testPath = testPathIterator->path();
		if(boost::filesystem::is_directory(testPath))
		{
			ScanAndExecuteTests(testPath, testReportWriter, gsHandlerName);
			continue;
		}
		if(testPath.extension() == ".elf")
		{
			printf("Testing '%s': ", testPath.string().c_str());
			ExecuteEeTest(testPath, gsHandlerName);
			auto result = GetTestResult(testPath);
			printf("%s.\r\n", result.succeeded ? "SUCCEEDED" : "FAILED");
			if(testReportWriter)
			{
				testReportWriter->ReportTestEntry(testPath.string(), result);
			}
		}
		else if(testPath.extension() == ".irx")
		{
			printf("Testing '%s': ", testPath.string().c_str());
			ExecuteIopTest(testPath);
			auto result = GetTestResult(testPath);
			printf("%s.\r\n", result.succeeded ? "SUCCEEDED" : "FAILED");
			if(testReportWriter)
			{
				testReportWriter->ReportTestEntry(testPath.string(), result);
			}
		}
	}
}

int main(int argc, const char** argv)
{
	if(argc < 2)
	{
		auto validGsHandlerNamesString =
		    []() {
			    std::string result;
			    for(auto nameIterator = g_validGsHandlersNames.begin();
			        nameIterator != g_validGsHandlersNames.end(); ++nameIterator)
			    {
				    if(nameIterator != g_validGsHandlersNames.begin())
				    {
					    result += "|";
				    }
				    result += *nameIterator;
			    }
			    return result;
		    }();

		printf("Usage: AutoTest [options] testDir\r\n");
		printf("Options: \r\n");
		printf("\t --junitreport <path>\t Writes JUnit format report at <path>.\r\n");
		printf("\t --gshandler <%s>\tSelects which GS handler to instantiate (default is '%s').\r\n",
		       validGsHandlerNamesString.c_str(), DEFAULT_GS_HANDLER_NAME);
		return -1;
	}

	TestReportWriterPtr testReportWriter;
	boost::filesystem::path autoTestRoot;
	boost::filesystem::path reportPath;
	std::string gsHandlerName = DEFAULT_GS_HANDLER_NAME;
	assert(g_validGsHandlersNames.find(gsHandlerName) != std::end(g_validGsHandlersNames));

	for(int i = 1; i < argc; i++)
	{
		if(!strcmp(argv[i], "--junitreport"))
		{
			if((i + 1) >= argc)
			{
				printf("Error: Path must be specified for --junitreport option.\r\n");
				return -1;
			}
			testReportWriter = std::make_shared<CJUnitTestReportWriter>();
			reportPath = boost::filesystem::path(argv[i + 1]);
			i++;
		}
		else if(!strcmp(argv[i], "--gshandler"))
		{
			if((i + 1) >= argc)
			{
				printf("Error: GS handler name must be specified for --gshandler option.\r\n");
				return -1;
			}
			gsHandlerName = argv[i + 1];
			if(g_validGsHandlersNames.find(gsHandlerName) == std::end(g_validGsHandlersNames))
			{
				printf("Error: Invalid GS handler name '%s'.\r\n", gsHandlerName.c_str());
				return -1;
			}
			i++;
		}
		else
		{
			autoTestRoot = argv[i];
			break;
		}
	}

	if(autoTestRoot.empty())
	{
		printf("Error: No test directory specified.\r\n");
		return -1;
	}

	try
	{
		ScanAndExecuteTests(autoTestRoot, testReportWriter, gsHandlerName);
	}
	catch(const std::exception& exception)
	{
		printf("Error: Failed to execute tests: %s\r\n", exception.what());
		return -1;
	}

	if(testReportWriter)
	{
		try
		{
			testReportWriter->Write(reportPath);
		}
		catch(const std::exception& exception)
		{
			printf("Error: Failed to write test report: %s\r\n", exception.what());
			return -1;
		}
	}

	return 0;
}

max_stars_repo_name: jeremybris/Play-

max_issues_repo_name: jeremybris/Play-

max_forks_repo_name: jeremybris/Play-


text:
#ifndef TM_KIT_TRANSPORT_BCL_COMPAT_DURATION_HPP_
#define TM_KIT_TRANSPORT_BCL_COMPAT_DURATION_HPP_

#include <chrono>
#include <type_traits>
#include <tm_kit/basic/ProtoInterop.hpp>
#include <tm_kit/basic/SerializationHelperMacros.hpp>
#include <tm_kit/basic/ConvertibleWithString.hpp>
#include <tm_kit/basic/PrintHelper.hpp>
#include <boost/lexical_cast.hpp>

namespace dev { namespace cd606 { namespace tm { namespace transport { namespace bcl_compat {

    TM_BASIC_CBOR_CAPABLE_ENUM_AS_STRING(
        TimeSpanScale
        , (DAYS) (HOURS) (MINUTES) (SECONDS) (MILLISECONDS) (TICKS) (MINMAX)
    );

#define BCL_COMPAT_BCL_TIME_SPAN_PROTO_FIELDS \
    ((dev::cd606::tm::basic::proto_interop::SInt64, value)) \
    ((dev::cd606::tm::transport::bcl_compat::TimeSpanScale, scale))

    TM_BASIC_CBOR_CAPABLE_STRUCT(BclTimeSpanProto, BCL_COMPAT_BCL_TIME_SPAN_PROTO_FIELDS);

    class DurationConverter {
    public:
        template <class ProtoType, class Rep, class Period>
        static void write(ProtoType &p, std::chrono::duration<Rep,Period> const &data) {
            if constexpr (std::is_same_v<ProtoType, BclTimeSpanProto>) {
                if constexpr (std::is_same_v<Period, std::ratio<1>>) {
                    p.value = static_cast<int64_t>(data.count());
                    p.scale = transport::bcl_compat::TimeSpanScale::SECONDS;
                } else if constexpr (std::is_same_v<Period, std::milli>) {
                    p.value = static_cast<int64_t>(data.count());
                    p.scale = transport::bcl_compat::TimeSpanScale::MILLISECONDS;
                } else if constexpr (std::is_same_v<Period, std::micro>) {
                    p.value = static_cast<int64_t>(data.count()*10);
                    p.scale = transport::bcl_compat::TimeSpanScale::TICKS;
                } else if constexpr (std::is_same_v<Period, std::nano>) {
                    p.value = static_cast<int64_t>(data.count()/100);
                    p.scale = transport::bcl_compat::TimeSpanScale::TICKS;
                } else if constexpr (std::is_same_v<Period, std::ratio<60>>) {
                    p.value = static_cast<int64_t>(data.count());
                    p.scale = transport::bcl_compat::TimeSpanScale::MINUTES;
                } else if constexpr (std::is_same_v<Period, std::ratio<3600>>) {
                    p.value = static_cast<int64_t>(data.count());
                    p.scale = transport::bcl_compat::TimeSpanScale::HOURS;
                } else if constexpr (std::is_same_v<Period, std::ratio<86400>>) {
                    p.value = static_cast<int64_t>(data.count());
                    p.scale = transport::bcl_compat::TimeSpanScale::DAYS;
                } else if constexpr (std::is_same_v<Period, std::ratio<604800>>) {
                    p.value = static_cast<int64_t>(data.count()*7);
                    p.scale = transport::bcl_compat::TimeSpanScale::DAYS;
                } else if constexpr (std::is_same_v<Period, std::ratio<2629746>>) {
                    p.value = static_cast<int64_t>(data.count()*2629746/86400);
                    p.scale = transport::bcl_compat::TimeSpanScale::DAYS;
                } else if constexpr (std::is_same_v<Period, std::ratio<31556952>>) {
                    p.value = static_cast<int64_t>(data.count()*31556952/86400);
                    p.scale = transport::bcl_compat::TimeSpanScale::DAYS;
                } else if constexpr (Period::num > 1) {
                    auto sec = std::chrono::duration_cast<std::chrono::seconds>(data);
                    p.value = static_cast<int64_t>(sec.count());
                    p.scale = transport::bcl_compat::TimeSpanScale::SECONDS;
                } else {
                    auto nsec = std::chrono::duration_cast<std::chrono::nanoseconds>(data);
                    p.value = static_cast<int64_t>(nsec.count()/100);
                    p.scale = transport::bcl_compat::TimeSpanScale::TICKS;
                }
            } else {
                using ScaleType = std::decay_t<decltype(p.scale())>;
                if constexpr (std::is_same_v<Period, std::ratio<1>>) {
                    p.set_value(static_cast<int64_t>(data.count()));
                    p.set_scale(static_cast<ScaleType>(static_cast<int32_t>(transport::bcl_compat::TimeSpanScale::SECONDS)));
                } else if constexpr (std::is_same_v<Period, std::milli>) {
                    p.set_value(static_cast<int64_t>(data.count()));
                    p.set_scale(static_cast<ScaleType>(static_cast<int32_t>(transport::bcl_compat::TimeSpanScale::MILLISECONDS)));
                } else if constexpr (std::is_same_v<Period, std::micro>) {
                    p.set_value(static_cast<int64_t>(data.count()*10));
                    p.set_scale(static_cast<ScaleType>(static_cast<int32_t>(transport::bcl_compat::TimeSpanScale::TICKS)));
                } else if constexpr (std::is_same_v<Period, std::nano>) {
                    p.set_value(static_cast<int64_t>(data.count()/100));
                    p.set_scale(static_cast<ScaleType>(static_cast<int32_t>(transport::bcl_compat::TimeSpanScale::TICKS)));
                } else if constexpr (std::is_same_v<Period, std::ratio<60>>) {
                    p.set_value(static_cast<int64_t>(data.count()));
                    p.set_scale(static_cast<ScaleType>(static_cast<int32_t>(transport::bcl_compat::TimeSpanScale::MINUTES)));
                } else if constexpr (std::is_same_v<Period, std::ratio<3600>>) {
                    p.set_value(static_cast<int64_t>(data.count()));
                    p.set_scale(static_cast<ScaleType>(static_cast<int32_t>(transport::bcl_compat::TimeSpanScale::HOURS)));
                } else if constexpr (std::is_same_v<Period, std::ratio<86400>>) {
                    p.set_value(static_cast<int64_t>(data.count()));
                    p.set_scale(static_cast<ScaleType>(static_cast<int32_t>(transport::bcl_compat::TimeSpanScale::DAYS)));
                } else if constexpr (std::is_same_v<Period, std::ratio<604800>>) {
                    p.set_value(static_cast<int64_t>(data.count()*7));
                    p.set_scale(static_cast<ScaleType>(static_cast<int32_t>(transport::bcl_compat::TimeSpanScale::DAYS)));
                } else if constexpr (std::is_same_v<Period, std::ratio<2629746>>) {
                    p.set_value(static_cast<int64_t>(data.count()*2629746/86400));
                    p.set_scale(static_cast<ScaleType>(static_cast<int32_t>(transport::bcl_compat::TimeSpanScale::DAYS)));
                } else if constexpr (std::is_same_v<Period, std::ratio<31556952>>) {
                    p.set_value(static_cast<int64_t>(data.count()*31556952/86400));
                    p.set_scale(static_cast<ScaleType>(static_cast<int32_t>(transport::bcl_compat::TimeSpanScale::DAYS)));
                } else if constexpr (Period::num > 1) {
                    auto sec = std::chrono::duration_cast<std::chrono::seconds>(data);
                    p.set_value(static_cast<int64_t>(sec.count()));
                    p.set_scale(static_cast<ScaleType>(static_cast<int32_t>(transport::bcl_compat::TimeSpanScale::SECONDS)));
                } else {
                    auto nsec = std::chrono::duration_cast<std::chrono::nanoseconds>(data);
                    p.set_value(static_cast<int64_t>(nsec.count()/100));
                    p.set_scale(static_cast<ScaleType>(static_cast<int32_t>(transport::bcl_compat::TimeSpanScale::TICKS)));
                }
            }
        }
        template <class ProtoType, class Rep, class Period>
        static bool read(std::chrono::duration<Rep,Period> &output, ProtoType const &p) {
            if constexpr (std::is_same_v<ProtoType, BclTimeSpanProto>) {
                switch (p.scale) {
                case transport::bcl_compat::TimeSpanScale::DAYS:
#if __cplusplus > 201703L
                    output = std::chrono::duration_cast<std::chrono::duration<Rep,Period>>(
                        std::chrono::days(p.value)
                    );
#else
                    output = std::chrono::duration_cast<std::chrono::duration<Rep,Period>>(
                        std::chrono::hours(p.value*24)
                    );
#endif
                    break;
                case transport::bcl_compat::TimeSpanScale::HOURS:
                    output = std::chrono::duration_cast<std::chrono::duration<Rep,Period>>(
                        std::chrono::hours(p.value)
                    );
                    break;
                case transport::bcl_compat::TimeSpanScale::MINUTES:
                    output = std::chrono::duration_cast<std::chrono::duration<Rep,Period>>(
                        std::chrono::minutes(p.value)
                    );
                    break;
                case transport::bcl_compat::TimeSpanScale::SECONDS:
                    output = std::chrono::duration_cast<std::chrono::duration<Rep,Period>>(
                        std::chrono::seconds(p.value)
                    );
                    break;
                case transport::bcl_compat::TimeSpanScale::MILLISECONDS:
                    output = std::chrono::duration_cast<std::chrono::duration<Rep,Period>>(
                        std::chrono::milliseconds(p.value)
                    );
                    break;
                case transport::bcl_compat::TimeSpanScale::TICKS:
                    output = std::chrono::duration_cast<std::chrono::duration<Rep,Period>>(
                        std::chrono::nanoseconds(p.value*100)
                    );
                    break;
                default:
                    return false;
                    break;
                }
                return true;
            } else {
                switch (static_cast<transport::bcl_compat::TimeSpanScale>(static_cast<int32_t>(p.scale()))) {
                case transport::bcl_compat::TimeSpanScale::DAYS:
    #if __cplusplus > 201703L
                    output = std::chrono::duration_cast<std::chrono::duration<Rep,Period>>(
                        std::chrono::days(p.value())
                    );
    #else
                    output = std::chrono::duration_cast<std::chrono::duration<Rep,Period>>(
                        std::chrono::hours(p.value()*24)
                    );
    #endif
                    break;
                case transport::bcl_compat::TimeSpanScale::HOURS:
                    output = std::chrono::duration_cast<std::chrono::duration<Rep,Period>>(
                        std::chrono::hours(p.value())
                    );
                    break;
                case transport::bcl_compat::TimeSpanScale::MINUTES:
                    output = std::chrono::duration_cast<std::chrono::duration<Rep,Period>>(
                        std::chrono::minutes(p.value())
                    );
                    break;
                case transport::bcl_compat::TimeSpanScale::SECONDS:
                    output = std::chrono::duration_cast<std::chrono::duration<Rep,Period>>(
                        std::chrono::seconds(p.value())
                    );
                    break;
                case transport::bcl_compat::TimeSpanScale::MILLISECONDS:
                    output = std::chrono::duration_cast<std::chrono::duration<Rep,Period>>(
                        std::chrono::milliseconds(p.value())
                    );
                    break;
                case transport::bcl_compat::TimeSpanScale::TICKS:
                    output = std::chrono::duration_cast<std::chrono::duration<Rep,Period>>(
                        std::chrono::nanoseconds(p.value()*100)
                    );
                    break;
                default:
                    return false;
                    break;
                }
                return true;
            }
        }
    };

} } } } }

TM_BASIC_CBOR_CAPABLE_STRUCT_SERIALIZE(dev::cd606::tm::transport::bcl_compat::BclTimeSpanProto, BCL_COMPAT_BCL_TIME_SPAN_PROTO_FIELDS);

#undef BCL_COMPAT_BCL_TIME_SPAN_PROTO_FIELDS

namespace dev { namespace cd606 { namespace tm { namespace basic {
    template <class Rep, class Period>
    class ConvertibleWithString<std::chrono::duration<Rep,Period>> {
    public:
        static constexpr bool value = true;
        static std::string toString(std::chrono::duration<Rep,Period> const &data) {
            std::ostringstream oss;
            if constexpr (std::is_same_v<Period, std::ratio<1>>) {
                oss << data.count() << 's';
            } else if constexpr (std::is_same_v<Period, std::milli>) {
                oss << data.count() << "ms";
            } else if constexpr (std::is_same_v<Period, std::micro>) {
                oss << data.count() << "us";
            } else if constexpr (std::is_same_v<Period, std::nano>) {
                oss << data.count() << "ns";
            } else if constexpr (std::is_same_v<Period, std::ratio<60>>) {
                oss << data.count() << "min";
            } else if constexpr (std::is_same_v<Period, std::ratio<3600>>) {
                oss << data.count() << "hr";
            } else if constexpr (std::is_same_v<Period, std::ratio<86400>>) {
                oss << data.count() << "d";
            } else if constexpr (std::is_same_v<Period, std::ratio<604800>>) {
                oss << data.count() << "wk";
            } else if constexpr (std::is_same_v<Period, std::ratio<2629746>>) {
                oss << data.count() << "mon";
            } else if constexpr (std::is_same_v<Period, std::ratio<31556952>>) {
                oss << data.count() << "yr";
            } else if constexpr (Period::num > 1) {
                auto sec = std::chrono::duration_cast<std::chrono::seconds>(data);
                oss << sec.count() << "s";
            } else {
                auto nsec = std::chrono::duration_cast<std::chrono::nanoseconds>(data);
                oss << nsec.count() << "ns";
            }
            return oss.str();
        }
        static std::chrono::duration<Rep,Period> fromString(std::string_view const &s) {
            if (s.length() == 0) {
                return std::chrono::duration<Rep,Period> {};
            }
            int ii = s.length()-1;
            while (ii >= 0 && std::isalpha(s[ii])) {
                --ii;
            }
            if (ii == s.length()-1) {
                return std::chrono::duration<Rep,Period> {};
            }
            if (ii < 0) {
                return std::chrono::duration<Rep,Period> {};
            }
            auto unit = s.substr(ii+1);
            auto countStr = s.substr(0, ii+1);
            Rep count;
            try {
                count = boost::lexical_cast<Rep>(std::string {countStr});
            } catch (boost::bad_lexical_cast const &) {
                return std::chrono::duration<Rep,Period> {};
            }
            if (unit == "s") {
                return std::chrono::duration_cast<std::chrono::duration<Rep,Period>>(
                    std::chrono::seconds(count)
                );
            } else if (unit == "ms") {
                return std::chrono::duration_cast<std::chrono::duration<Rep,Period>>(
                    std::chrono::milliseconds(count)
                );
            } else if (unit == "us") {
                return std::chrono::duration_cast<std::chrono::duration<Rep,Period>>(
                    std::chrono::microseconds(count)
                );
            } else if (unit == "ns") {
                return std::chrono::duration_cast<std::chrono::duration<Rep,Period>>(
                    std::chrono::nanoseconds(count)
                );
            } else if (unit == "min") {
                return std::chrono::duration_cast<std::chrono::duration<Rep,Period>>(
                    std::chrono::minutes(count)
                );
            } else if (unit == "hr") {
                return std::chrono::duration_cast<std::chrono::duration<Rep,Period>>(
                    std::chrono::hours(count)
                );
#if __cplusplus > 201703L
            } else if (unit == "d") {
                return std::chrono::duration_cast<std::chrono::duration<Rep,Period>>(
                    std::chrono::days(count)
                );
            } else if (unit == "wk") {
                return std::chrono::duration_cast<std::chrono::duration<Rep,Period>>(
                    std::chrono::weeks(count)
                );
            } else if (unit == "mon") {
                return std::chrono::duration_cast<std::chrono::duration<Rep,Period>>(
                    std::chrono::months(count)
                );
            } else if (unit == "yr") {
                return std::chrono::duration_cast<std::chrono::duration<Rep,Period>>(
                    std::chrono::years(count)
                );
#else
            } else if (unit == "d") {
                return std::chrono::duration_cast<std::chrono::duration<Rep,Period>>(
                    std::chrono::hours(count*24)
                );
            } else if (unit == "wk") {
                return std::chrono::duration_cast<std::chrono::duration<Rep,Period>>(
                    std::chrono::hours(count*24*7)
                );
            } else if (unit == "mon") {
                return std::chrono::duration_cast<std::chrono::duration<Rep,Period>>(
                    std::chrono::hours(count*2629646/3600)
                );
            } else if (unit == "yr") {
                return std::chrono::duration_cast<std::chrono::duration<Rep,Period>>(
                    std::chrono::hours(count*31556952/3600)
                );
#endif
            } else {
                return std::chrono::duration<Rep,Period> {};
            }
        }
    };

    template <class Rep, class Period>
    class PrintHelper<std::chrono::duration<Rep,Period>> {
    public:
        static void print(std::ostream &os, std::chrono::duration<Rep,Period> const &value) {
            os << ConvertibleWithString<std::chrono::duration<Rep,Period>>::toString(value);
        }
    };

    namespace proto_interop {
        template <class Rep, class Period>
        class ProtoEncoder<std::chrono::duration<Rep,Period>, void> {
        public:
            static constexpr uint64_t thisFieldNumber(uint64_t inputFieldNumber) {
                return inputFieldNumber;
            }
            static constexpr uint64_t nextFieldNumber(uint64_t inputFieldNumber) {
                return inputFieldNumber+1;
            }
            static void write(std::optional<uint64_t> fieldNumber, std::chrono::duration<Rep,Period> const &data, std::ostream &os, bool writeDefaultValue) {
                transport::bcl_compat::BclTimeSpanProto p;
                transport::bcl_compat::DurationConverter::write(p, data);
                ProtoEncoder<transport::bcl_compat::BclTimeSpanProto>::write(fieldNumber, p, os, false);
            }
        };
        template <class Rep, class Period>
        struct ProtoWrappable<std::chrono::duration<Rep,Period>, void> {
            static constexpr bool value = true;
        };
        template <class Rep, class Period>
        class ProtoDecoder<std::chrono::duration<Rep,Period>, void> final : public IProtoDecoder<std::chrono::duration<Rep,Period>> {
        private:
            uint64_t baseFieldNumber_;
        public:
            ProtoDecoder(std::chrono::duration<Rep,Period> *output, uint64_t baseFieldNumber) : IProtoDecoder<std::chrono::duration<Rep,Period>>(output), baseFieldNumber_(baseFieldNumber) {}
            static std::vector<uint64_t> responsibleForFieldNumbers(uint64_t baseFieldNumber) {
                return {baseFieldNumber};
            }
            std::optional<std::size_t> read(std::chrono::duration<Rep,Period> &output, internal::FieldHeader const &fh, std::string_view const &input, std::size_t start) override final {
                transport::bcl_compat::BclTimeSpanProto p;
                ProtoDecoder<transport::bcl_compat::BclTimeSpanProto> subDec(&p, baseFieldNumber_);
                auto res = subDec.handle(fh, input, start);
                if (res) {
                    if (!transport::bcl_compat::DurationConverter::read(output, p)) {
                        return std::nullopt;
                    }
                }
                return res;
            }
        };
    }
    namespace bytedata_utils {
        template <class Rep, class Period>
        struct RunCBORSerializer<std::chrono::duration<Rep,Period>, void> {
            static std::string apply(std::chrono::duration<Rep,Period> const &d) {
                return RunCBORSerializer<std::string>::apply(ConvertibleWithString<std::chrono::duration<Rep,Period>>::toString(d));
            }
            static std::size_t apply(std::chrono::duration<Rep,Period> const &d, char *output) {
                return RunCBORSerializer<std::string>::apply(ConvertibleWithString<std::chrono::duration<Rep,Period>>::toString(d), output);
            }
            static std::size_t calculateSize(std::chrono::duration<Rep,Period> const &d) {
                return RunCBORSerializer<std::string>::calculateSize(ConvertibleWithString<std::chrono::duration<Rep,Period>>::toString(d));
            }
        };
        template <class Rep, class Period>
        struct RunCBORDeserializer<std::chrono::duration<Rep,Period>, void> {
            static std::optional<std::tuple<std::chrono::duration<Rep,Period>,size_t>> apply(std::string_view const &s, size_t start) {
                auto durationStr = RunCBORDeserializer<std::string>::apply(s, start);
                if (!durationStr) {
                    return std::nullopt;
                }
                return std::tuple<std::chrono::duration<Rep,Period>,size_t> {ConvertibleWithString<std::chrono::duration<Rep,Period>>::fromString(std::get<0>(*durationStr)), std::get<1>(*durationStr)};
            }
            static std::optional<size_t> applyInPlace(std::chrono::duration<Rep,Period> &output, std::string_view const &s, size_t start) {
                auto durationStr = RunCBORDeserializer<std::string>::apply(s, start);
                if (!durationStr) {
                    return std::nullopt;
                }
                output = ConvertibleWithString<std::chrono::duration<Rep,Period>>::fromString(std::get<0>(*durationStr));
                return std::get<1>(*durationStr);
            }
        };
    }
} } } }

#endif


text:
// Copyright 2010 Christophe Henry
// henry UNDERSCORE christophe AT hotmail DOT com
// This is an extended version of the state machine available in the boost::mpl library
// Distributed under the same license as the original.
// Copyright for the original version:
// Copyright 2005 David Abrahams and Aleksey Gurtovoy. Distributed
// under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)

#include <iostream>
// back-end
#include <boost/msm/back/state_machine.hpp>
//front-end
#include <boost/msm/front/state_machine_def.hpp>
// functors
#include <boost/msm/front/functor_row.hpp>
#include <boost/msm/front/euml/common.hpp>
// for And_ operator
#include <boost/msm/front/euml/operator.hpp>

#include <boost/test/unit_test.hpp>

using namespace std;
namespace msm = boost::msm;
namespace mpl = boost::mpl;
using namespace msm::front;
// for And_ operator
using namespace msm::front::euml;

namespace
{
    // events
    struct event1 {};
    struct event2 {};

    // front-end: define the FSM structure
    struct my_machine_ : public msm::front::state_machine_def<my_machine_>
    {

        // The list of FSM states
        struct State1 : public msm::front::state<>
        {
            template <class Event,class FSM>
            void on_entry(Event const&,FSM& ) {++entry_counter;}
            template <class Event,class FSM>
            void on_exit(Event const&,FSM& ) {++exit_counter;}
            int entry_counter;
            int exit_counter;
        };
        struct State2 : public msm::front::state<>
        {
            template <class Event,class FSM>
            void on_entry(Event const&,FSM& ) {++entry_counter;}
            template <class Event,class FSM>
            void on_exit(Event const&,FSM& ) {++exit_counter;}
            int entry_counter;
            int exit_counter;
        };

        struct State3 : public msm::front::state<>
        {
            template <class Event,class FSM>
            void on_entry(Event const&,FSM& ) {++entry_counter;}
            template <class Event,class FSM>
            void on_exit(Event const&,FSM& ) {++exit_counter;}
            int entry_counter;
            int exit_counter;
        };

        struct State1b : public msm::front::state<>
        {
            template <class Event,class FSM>
            void on_entry(Event const&,FSM& ) {++entry_counter;}
            template <class Event,class FSM>
            void on_exit(Event const&,FSM& ) {++exit_counter;}
            int entry_counter;
            int exit_counter;
        };
        struct State2b : public msm::front::state<>
        {
            template <class Event,class FSM>
            void on_entry(Event const&,FSM& ) {++entry_counter;}
            template <class Event,class FSM>
            void on_exit(Event const&,FSM& ) {++exit_counter;}
            int entry_counter;
            int exit_counter;
        };

        struct always_true
        {
            template <class EVT,class FSM,class SourceState,class TargetState>
            bool operator()(EVT const&  ,FSM&,SourceState& ,TargetState& )
            {
                return true;
            }
        };
        struct always_false
        {
            template <class EVT,class FSM,class SourceState,class TargetState>
            bool operator()(EVT const&  ,FSM&,SourceState& ,TargetState& )
            {
                return false;
            }
        };

        // the initial state of the player SM. Must be defined
        typedef boost::mpl::vector2<State1,State1b> initial_state;

        // Transition table for player
        struct transition_table : boost::mpl::vector<
            //    Start     Event         Next      Action               Guard
            //  +---------+-------------+---------+---------------------+----------------------+
            Row < State1  , event1      , State2  , none                , always_true          >,
            Row < State2  , none        , State3                                               >,
            //  +---------+-------------+---------+---------------------+----------------------+
            Row < State1b , event1      , State2b , none                , always_false         >
            //  +---------+-------------+---------+---------------------+----------------------+
        > {};
        // Replaces the default no-transition response.
        template <class FSM,class Event>
        void no_transition(Event const&, FSM&,int)
        {
            BOOST_FAIL("no_transition called!");
        }
        // init counters
        template <class Event,class FSM>
        void on_entry(Event const&,FSM& fsm)
        {
            fsm.template get_state<my_machine_::State1&>().entry_counter=0;
            fsm.template get_state<my_machine_::State1&>().exit_counter=0;
            fsm.template get_state<my_machine_::State2&>().entry_counter=0;
            fsm.template get_state<my_machine_::State2&>().exit_counter=0;
            fsm.template get_state<my_machine_::State3&>().entry_counter=0;
            fsm.template get_state<my_machine_::State3&>().exit_counter=0;
            fsm.template get_state<my_machine_::State1b&>().entry_counter=0;
            fsm.template get_state<my_machine_::State1b&>().exit_counter=0;
            fsm.template get_state<my_machine_::State2b&>().entry_counter=0;
            fsm.template get_state<my_machine_::State2b&>().exit_counter=0;
        }
    };
    // Pick a back-end
    typedef msm::back::state_machine<my_machine_> my_machine;

    BOOST_AUTO_TEST_CASE( my_test )
    {
        my_machine p;

        p.start();
        BOOST_CHECK_MESSAGE(p.current_state()[0] == 0,"State1 should be active");
        BOOST_CHECK_MESSAGE(p.current_state()[1] == 2,"State1b should be active");

        p.process_event(event1());
        BOOST_CHECK_MESSAGE(p.current_state()[0] == 3,"State3 should be active");
        BOOST_CHECK_MESSAGE(p.current_state()[1] == 2,"State1b should be active");

        BOOST_CHECK_MESSAGE(p.get_state<my_machine_::State1&>().exit_counter == 1,"State1 exit not called correctly");
        BOOST_CHECK_MESSAGE(p.get_state<my_machine_::State1&>().entry_counter == 1,"State1 entry not called correctly");
        BOOST_CHECK_MESSAGE(p.get_state<my_machine_::State2&>().exit_counter == 1,"State2 exit not called correctly");
        BOOST_CHECK_MESSAGE(p.get_state<my_machine_::State2&>().entry_counter == 1,"State2 entry not called correctly");
        BOOST_CHECK_MESSAGE(p.get_state<my_machine_::State3&>().exit_counter == 0,"State3 exit not called correctly");
        BOOST_CHECK_MESSAGE(p.get_state<my_machine_::State3&>().entry_counter == 1,"State3 entry not called correctly");
        BOOST_CHECK_MESSAGE(p.get_state<my_machine_::State1b&>().entry_counter == 1,"State1b entry not called correctly");
        BOOST_CHECK_MESSAGE(p.get_state<my_machine_::State1b&>().exit_counter == 0,"State1b exit not called correctly");
        BOOST_CHECK_MESSAGE(p.get_state<my_machine_::State2b&>().entry_counter == 0,"State2b entry not called correctly");
        BOOST_CHECK_MESSAGE(p.get_state<my_machine_::State2b&>().exit_counter == 0,"State2b exit not called correctly");

    }
}

max_issues_repo_name: qingkouwei/mediaones

max_forks_repo_name: qingkouwei/mediaones


text:
#include <boost/date_time/posix_time/posix_time.hpp>
#include <boost/date_time/posix_time/time_parsers.hpp>
#include <csugar.h>
#include <ctime>

std::string csugar::utc_datetime(const time_t &time) {
  char buf[80];
  std::strftime(buf, sizeof buf, "%Y-%m-%dT%H:%M:%SZ", gmtime(&time));
  return buf;
}

time_t csugar::utc_strtotime(const std::string &utc_datetime) {
  struct tm tm {};
  strptime(utc_datetime.c_str(), "%Y-%m-%dT%H:%M:%SZ", &tm);
  time_t t = timegm(&tm);
  return boost::lexical_cast<long long>(t);
}

long csugar::timestamp() {
  return static_cast<long int>(time(nullptr));
}

std::string csugar::datetime(const std::string &format, long timestamp) {
  time_t t = timestamp;
  ctime(&t);
  char buf[80];
  std::strftime(buf, sizeof buf, format.c_str(), gmtime(&t));
  return buf;
}

max_stars_repo_name: AxiosCros/cpp-suger

max_issues_repo_name: AxiosCros/cpp-suger

max_forks_repo_name: AxiosCros/cpp-sugar


text:
#ifndef TINYREFL_EXAMPLES_FUSION_HPP
#define TINYREFL_EXAMPLES_FUSION_HPP

#include <boost/fusion/adapted.hpp>
#include <type_traits>

#ifndef TINYREFL_PP_UNWRAP
#define TINYREFL_PP_UNWRAP(...) __VA_ARGS__
#endif // TINYREFL_PP_UNWRAP

namespace tinyrefl
{

namespace examples
{

namespace detail
{

template<typename MemberPtr>
struct member_type;

template<typename T, typename Class>
struct member_type<T Class::*>
{
    using type = T;
};

template<typename MemberPtr>
using member_type_t = typename member_type<MemberPtr>::type;

}

}

}

// Boost Fusion backend for tinyrefl metadata
#define TINYREFL_GODMODE(...) // No Gods here
#define TINYREFL_SEQUENCE(...) __VA_ARGS__
#define TINYREFL_STRING(...) __VA_ARGS__
#define TINYREFL_TYPE(name, fullname) fullname
#define TINYREFL_VALUE(type, value) // We don't care about values (pointers to members, enums, etc)
#define TINYREFL_ATTRIBUTE(name, namespace_, full_attribute, args) // We don't care about attributes
#define TINYREFL_CONSTRUCTOR(name, fullname, class_type, signature, attributes) // We don't care about ctors
#define TINYREFL_MEMBER_FUNCTION(name, fullname, parent_class_type, return_type, signature, pointer, attributes) // we don't care about member functions
#define TINYREFL_MEMBER_VARIABLE(name, fullname, parent_class_type, value_type, pointer, attributes) (value_type, name)
#define TINYREFL_ENUM_VALUE(name, fullname, type, value, attributes) // we don't care about enums
#define TINYREFL_REFLECT_MEMBER(member) // We don't care about metadata definitions of members
#define TINYREFL_REFLECT_ENUM_VALUE(value) // we don't care about enums
#define TINYREFL_REFLECT_ENUM(name, type, values, attributes) // we don't care about enums
#define TINYREFL_REFLECT_CLASS(classname, classtype, bases, constructors, member_functions, member_variables, classes, enums, attributes) \
    BOOST_FUSION_ADAPT_STRUCT(classname, TINYREFL_PP_UNWRAP member_variables);

#endif // TINYREFL_EXAMPLES_FUSION_HPP

max_stars_repo_name: fesily/tinyrefl

max_issues_repo_name: fesily/tinyrefl

max_forks_repo_name: fesily/tinyrefl


text:
#include <iostream>
#include <csignal>
#include <string>
#include <asio.hpp>
#include <boost/bind.hpp>
#include <boost/function.hpp>
#include <boost/lexical_cast.hpp>
#include <rutil/Data.hxx>
#include "reTurnServer.hxx"
#include "TcpServer.hxx"
#include "TlsServer.hxx"
#include "UdpServer.hxx"
#include "ReTurnConfig.hxx"
#include "RequestHandler.hxx"
#include "TurnManager.hxx"
#include <rutil/WinLeakCheck.hxx>
#include <rutil/Log.hxx>
#include <rutil/Logger.hxx>
#include "ReTurnSubsystem.hxx"

#define RESIPROCATE_SUBSYSTEM ReTurnSubsystem::RETURN

#if defined(_WIN32)

boost::function0<void> console_ctrl_function;

BOOL WINAPI console_ctrl_handler(DWORD ctrl_type)
{
  switch (ctrl_type)
  {
  case CTRL_C_EVENT:
  case CTRL_BREAK_EVENT:
  case CTRL_CLOSE_EVENT:
  case CTRL_SHUTDOWN_EVENT:
    console_ctrl_function();
    return TRUE;
  default:
    return FALSE;
  }
}
#endif // defined(_WIN32)

int main(int argc, char* argv[])
{
   reTurn::ReTurnServerProcess proc;
   return proc.main(argc, argv);
}

reTurn::ReTurnServerProcess::ReTurnServerProcess()
{
}

reTurn::ReTurnServerProcess::~ReTurnServerProcess()
{
}

int
reTurn::ReTurnServerProcess::main(int argc, char* argv[])
{
#if defined(WIN32) && defined(_DEBUG) && defined(LEAK_CHECK)
   resip::FindMemoryLeaks fml;
#endif

   resip::Data defaultConfig("reTurnServer.config");
   reTurn::ReTurnConfig reTurnConfig;
   try
   {
      reTurnConfig.parseConfig(argc, argv, defaultConfig);
   }
   catch(std::exception& e)
   {
      ErrLog(<< "Exception parsing configuration: " << e.what());
      exit(-1);
   }

   setPidFile(reTurnConfig.mPidFile);
   // Daemonize if necessary
   if(reTurnConfig.mDaemonize)
   {
      daemonize();
   }

   try
   {
      // Initialize Logging
      resip::Log::initialize(reTurnConfig.mLoggingType, reTurnConfig.mLoggingLevel, "reTurnServer", reTurnConfig.mLoggingFilename.c_str());
      resip::GenericLogImpl::MaxLineCount = reTurnConfig.mLoggingFileMaxLineCount;

      // Initialize server.
      asio::io_service ioService;                                // The one and only ioService for the stunServer
      reTurn::TurnManager turnManager(ioService, reTurnConfig);  // The one and only Turn Manager

      boost::shared_ptr<reTurn::UdpServer> udpTurnServer;  // also a1p1StunUdpServer
      boost::shared_ptr<reTurn::TcpServer> tcpTurnServer;
      boost::shared_ptr<reTurn::TlsServer> tlsTurnServer;
      boost::shared_ptr<reTurn::UdpServer> a1p2StunUdpServer;
      boost::shared_ptr<reTurn::UdpServer> a2p1StunUdpServer;
      boost::shared_ptr<reTurn::UdpServer> a2p2StunUdpServer;

#ifdef USE_IPV6
      boost::shared_ptr<reTurn::UdpServer> udpV6TurnServer;
      boost::shared_ptr<reTurn::TcpServer> tcpV6TurnServer;
      boost::shared_ptr<reTurn::TlsServer> tlsV6TurnServer;
#endif

      // The one and only RequestHandler - if altStunPort is non-zero, then assume RFC3489 support is enabled and pass settings to request handler
      reTurn::RequestHandler requestHandler(turnManager,
         reTurnConfig.mAltStunPort != 0 ? &reTurnConfig.mTurnAddress : 0,
         reTurnConfig.mAltStunPort != 0 ? &reTurnConfig.mTurnPort : 0,
         reTurnConfig.mAltStunPort != 0 ? &reTurnConfig.mAltStunAddress : 0,
         reTurnConfig.mAltStunPort != 0 ? &reTurnConfig.mAltStunPort : 0);

      udpTurnServer.reset(new reTurn::UdpServer(ioService, requestHandler, reTurnConfig.mTurnAddress, reTurnConfig.mTurnPort));
      tcpTurnServer.reset(new reTurn::TcpServer(ioService, requestHandler, reTurnConfig.mTurnAddress, reTurnConfig.mTurnPort));
      if(reTurnConfig.mTlsTurnPort != 0)
      {
         tlsTurnServer.reset(new reTurn::TlsServer(ioService, requestHandler, reTurnConfig.mTurnAddress, reTurnConfig.mTlsTurnPort));
      }

#ifdef USE_IPV6
      udpV6TurnServer.reset(new reTurn::UdpServer(ioService, requestHandler, reTurnConfig.mTurnV6Address, reTurnConfig.mTurnPort));
      tcpV6TurnServer.reset(new reTurn::TcpServer(ioService, requestHandler, reTurnConfig.mTurnV6Address, reTurnConfig.mTurnPort));
      if(reTurnConfig.mTlsTurnPort != 0)
      {
         tlsV6TurnServer.reset(new reTurn::TlsServer(ioService, requestHandler, reTurnConfig.mTurnV6Address, reTurnConfig.mTlsTurnPort));
      }
#endif

      if(reTurnConfig.mAltStunPort != 0) // if alt stun port is non-zero, then RFC3489 support is enabled
      {
         a1p2StunUdpServer.reset(new reTurn::UdpServer(ioService, requestHandler, reTurnConfig.mTurnAddress, reTurnConfig.mAltStunPort));
         a2p1StunUdpServer.reset(new reTurn::UdpServer(ioService, requestHandler, reTurnConfig.mAltStunAddress, reTurnConfig.mTurnPort));
         a2p2StunUdpServer.reset(new reTurn::UdpServer(ioService, requestHandler, reTurnConfig.mAltStunAddress, reTurnConfig.mAltStunPort));
         udpTurnServer->setAlternateUdpServers(a1p2StunUdpServer.get(), a2p1StunUdpServer.get(), a2p2StunUdpServer.get());
         a1p2StunUdpServer->setAlternateUdpServers(udpTurnServer.get(), a2p2StunUdpServer.get(), a2p1StunUdpServer.get());
         a2p1StunUdpServer->setAlternateUdpServers(a2p2StunUdpServer.get(), udpTurnServer.get(), a1p2StunUdpServer.get());
         a2p2StunUdpServer->setAlternateUdpServers(a2p1StunUdpServer.get(), a1p2StunUdpServer.get(), udpTurnServer.get());
         a1p2StunUdpServer->start();
         a2p1StunUdpServer->start();
         a2p2StunUdpServer->start();
      }

      udpTurnServer->start();
      tcpTurnServer->start();
      if(tlsTurnServer)
      {
         tlsTurnServer->start();
      }

#ifdef USE_IPV6
      udpV6TurnServer->start();
      tcpV6TurnServer->start();
      if(tlsV6TurnServer)
      {
         tlsV6TurnServer->start();
      }
#endif

      // Drop privileges (can do this now that sockets are bound)
      if(!reTurnConfig.mRunAsUser.empty())
      {
         InfoLog( << "Trying to drop privileges, configured uid = " << reTurnConfig.mRunAsUser << " gid = " << reTurnConfig.mRunAsGroup);
         dropPrivileges(reTurnConfig.mRunAsUser, reTurnConfig.mRunAsGroup);
      }

      ReTurnUserFileScanner userFileScanner(ioService, reTurnConfig);
      userFileScanner.start();

#ifdef _WIN32
      // Set console control handler to allow server to be stopped.
      console_ctrl_function = boost::bind(&asio::io_service::stop, &ioService);
      SetConsoleCtrlHandler(console_ctrl_handler, TRUE);
#else
      // Block all signals for background thread.
      sigset_t new_mask;
      sigfillset(&new_mask);
      sigset_t old_mask;
      pthread_sigmask(SIG_BLOCK, &new_mask, &old_mask);
#endif

      // Run the ioService until stopped.
      // Create a pool of threads to run all of the io_services.
      boost::shared_ptr<asio::thread> thread(new asio::thread(
         boost::bind(&asio::io_service::run, &ioService)));

#ifndef _WIN32
      // Restore previous signals.
      pthread_sigmask(SIG_SETMASK, &old_mask, 0);

      // Wait for signal indicating time to shut down.
      sigset_t wait_mask;
      sigemptyset(&wait_mask);
      sigaddset(&wait_mask, SIGINT);
      sigaddset(&wait_mask, SIGQUIT);
      sigaddset(&wait_mask, SIGTERM);
      pthread_sigmask(SIG_BLOCK, &wait_mask, 0);
      int sig = 0;
      sigwait(&wait_mask, &sig);
      ioService.stop();
#endif

      // Wait for thread to exit
      thread->join();
   }
   catch (std::exception& e)
   {
      ErrLog(<< "exception: " << e.what());
   }

   return 0;
}

/* ====================================================================

 Copyright (c) 2007-2008, Plantronics, Inc.
 All rights reserved.

 Redistribution and use in source and binary forms, with or without
 modification, are permitted provided that the following conditions are
 met:

 1. Redistributions of source code must retain the above copyright
    notice, this list of conditions and the following disclaimer.

 2. Redistributions in binary form must reproduce the above copyright
    notice, this list of conditions and the following disclaimer in the
    documentation and/or other materials provided with the distribution.

 3. Neither the name of Plantronics nor the names of its contributors
    may be used to endorse or promote products derived from this
    software without specific prior written permission.

 THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

 ==================================================================== */

ext: cxx

max_stars_repo_name: dulton/reSipServer

max_issues_repo_name: dulton/reSipServer

max_forks_repo_name: dulton/reSipServer


text:
#include <iostream>
#include <fstream>
#include <vector>
#include <string>
#include <boost/program_options.hpp>

#include "BloomFilter.hpp"
#include "utils/Helpers.hpp"

namespace po = boost::program_options;

int main(int argc, char **argv)
{
    std::ios_base::sync_with_stdio(false);
    std::cin.tie(nullptr);

    po::options_description desc;
    po::variables_map vm;
    desc.add_options()
        ("file-with-saved-data", po::value<std::string>()->required(), "Path to file with data to save in bloom filter")
        ("hash-size", po::value<uint32_t>()->required(), "Hash size for bloom filter")
        ("hash-count", po::value<uint32_t>()->required(), "Hash count for bloom filter")
        ("hash-start", po::value<uint32_t>()->default_value(0), "Start using hashes from bit");

    try
    {
        po::store(po::parse_command_line(argc, argv, desc), vm);
        po::notify(vm);
    }
    catch (const po::error &e)
    {
        desc.print(std::cerr);
        throw std::runtime_error(e.what());
    }

    auto hashSize = vm["hash-size"].as<uint32_t>();
    auto hashCount = vm["hash-count"].as<uint32_t>();
    auto hashStart = vm["hash-start"].as<uint32_t>();
    auto fileName = vm["file-with-saved-data"].as<std::string>();

    hobf::BloomFilter bf(hashSize, hashCount, hashStart);

    std::ifstream dataStream(fileName, std::ios::in);
    if (!dataStream)
    {
        throw std::runtime_error("Could not open file with saved data '" + fileName + "'");
    }

    auto toCompute = (hashStart + hobf::utils::getPower(hashSize) * hashCount + 127) / 128;

    std::vector<uint32_t> seeds(toCompute);
    for (uint32_t i = 0; i < seeds.size(); ++i)
    {
        seeds[i] = i + 1;
    }

    std::string elem;
    std::vector<uint64_t> hashes;
    hashes.reserve(seeds.size() * 2);

    while(std::getline(dataStream, elem))
    {
        hashes.clear();
        for (auto seed: seeds)
        {
            auto hash = hobf::utils::hash(elem, seed);
            hashes.push_back(hash.first);
            hashes.push_back(hash.second);
        }
        bf.add(hashes);
    }

    while(std::getline(std::cin, elem))
    {
        hashes.clear();
        for (auto seed: seeds)
        {
            auto hash = hobf::utils::hash(elem, seed);
            hashes.push_back(hash.first);
            hashes.push_back(hash.second);
        }
        if (bf.lookup(hashes))
        {
            std::cout << elem << "\n";
        }
    }
}

ext: cc

max_stars_repo_name: Ravengg/HashOptimizedBloomFilter

max_issues_repo_name: Ravengg/HashOptimizedBloomFilter

max_forks_repo_name: Ravengg/HashOptimizedBloomFilter


text:
#include "gmp_factorial.h"

#include <boost/python/module.hpp>
#include <boost/python/def.hpp>
using namespace boost::python;

BOOST_PYTHON_MODULE(my_booster) {
    def("factorial", fact);
}

max_stars_repo_name: YnkDK/python-boost-factorial

max_issues_repo_name: YnkDK/python-boost-factorial

max_forks_repo_name: YnkDK/python-boost-factorial


text:
#include "BackgroundThread.hpp"

#include <boost/date_time/posix_time/posix_time.hpp>
#include <cstdarg>
#include <cstdio>
#include "Werk/Logging/Log.hpp"
#include "Werk/OS/Time.hpp"

namespace Werk {

void BackgroundTask::execute() {

	if(!_active.value()) {
		return;
	}
	_profile.start(Werk::epochTime());
	_action->execute();
	_profile.stop(Werk::epochTime());
}

void BackgroundThread::logTo(Log* log) const {
	log->log(LogLevel::INFO, "<BackgroundThread> Frequency (ns) : %" PRIu64, _frequencyNs);
	log->log(LogLevel::INFO, "<BackgroundThread> Tasks (%zu):", _tasks.size());
	for(BackgroundTask* task : _tasks) {
		log->log(LogLevel::INFO, "  %24s    %8s    Count=%" PRIu64,
			task->action()->name().c_str(), task->active().value() ? "Active" : "Inactive", task->profile().count());
	}
}

/*
this method is the actual background thread
*/
void BackgroundThread::backgroundThread() {

	while(true) {
		//execute all tasks
		//update the time
		_mainClock.setTime(_mainClockTime);
		_backgroundClock.setEpochTime();
		for(size_t i=0; i < _tasks.size(); ++i) {
			_tasks[i]->execute();
		}

		if(!_running) break;

		const uint64_t nanosPerSecond = 10000000001;
		_delay.tv_sec = _frequencyNs/nanosPerSecond;
		_delay.tv_nsec = _frequencyNs % nanosPerSecond;
		nanosleep(&_delay, nullptr);
	}
}

}


text:
#pragma once

#include <vector>
#include <unordered_map>

#include <elle/reactor/asio.hh>
#include <boost/optional.hpp>

#include <elle/das/Symbol.hh>
#include <elle/das/model.hh>
#include <elle/das/serializer.hh>

#include <memo/serialization.hh>

namespace memo
{
  namespace mount_options
  {
    ELLE_DAS_SYMBOL(as);
    ELLE_DAS_SYMBOL(async);
    ELLE_DAS_SYMBOL(cache);
    ELLE_DAS_SYMBOL(cache_disk_size);
    ELLE_DAS_SYMBOL(cache_ram_invalidation);
    ELLE_DAS_SYMBOL(cache_ram_size);
    ELLE_DAS_SYMBOL(cache_ram_ttl);
#ifndef ELLE_WINDOWS
    ELLE_DAS_SYMBOL(enable_monitoring); // aka monitoring.
#endif
    ELLE_DAS_SYMBOL(fetch);             // aka fetch_endpoints.
    ELLE_DAS_SYMBOL(fuse_options);      // aka fuse_option.
    ELLE_DAS_SYMBOL(hub_url);
    ELLE_DAS_SYMBOL(listen_address);    // aka listen
    ELLE_DAS_SYMBOL(mountpoint);
    ELLE_DAS_SYMBOL(peers);             // aka peer.
    ELLE_DAS_SYMBOL(poll_beyond);       // aka fetch_endpoints_interval.
    ELLE_DAS_SYMBOL(push);              // aka push_endpoints.
    ELLE_DAS_SYMBOL(publish);           // aka push && fetch.
    ELLE_DAS_SYMBOL(rdv);
    ELLE_DAS_SYMBOL(readonly);
  }

  struct MountOptions
  {
    using Strings = std::vector<std::string>;
    using Environ = std::unordered_map<std::string, std::string>;

    void
    to_commandline(Strings& arguments, Environ& env) const;
    Strings
    to_commandline() const;
    void
    merge(MountOptions const& other);
    boost::optional<std::string> hub_url;
    boost::optional<std::string> rdv;
    boost::optional<Strings> fuse_options;
    boost::optional<std::string> as;
    boost::optional<bool> fetch;
    boost::optional<bool> push;
    boost::optional<bool> publish;
    boost::optional<bool> cache;
    boost::optional<bool> async;
    boost::optional<bool> readonly;
    boost::optional<int> cache_ram_size;
    boost::optional<int> cache_ram_ttl;
    boost::optional<int> cache_ram_invalidation;
    boost::optional<uint64_t> cache_disk_size;
    boost::optional<std::string> mountpoint;
    boost::optional<Strings> peers;
    boost::optional<int> poll_beyond;
    boost::optional<boost::asio::ip::address> listen_address;
#ifndef ELLE_WINDOWS
    boost::optional<bool> enable_monitoring;
#endif
    using serialization_tag = memo::serialization_tag;
    using Model = elle::das::Model<
      MountOptions,
      decltype(elle::meta::list(
                 mount_options::hub_url,
                 mount_options::rdv,
                 mount_options::fuse_options,
                 mount_options::fetch,
                 mount_options::push,
                 mount_options::publish,
                 mount_options::cache,
                 mount_options::async,
                 mount_options::readonly,
                 mount_options::cache_ram_size,
                 mount_options::cache_ram_ttl,
                 mount_options::cache_ram_invalidation,
                 mount_options::cache_disk_size,
                 mount_options::mountpoint,
                 mount_options::as,
                 mount_options::peers,
                 mount_options::poll_beyond
                 // mount_options::listen_address,
#ifndef ELLE_WINDOWS
                 , mount_options::enable_monitoring
#endif
                 ))>;
  };

  /// Print for debugging.
  std::ostream&
  operator<<(std::ostream& os, MountOptions const& mo);
}

ELLE_DAS_SERIALIZE(memo::MountOptions);

ext: hh

max_stars_repo_name: infinit/memo

max_issues_repo_name: infinit/memo

max_forks_repo_name: infinit/memo