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

#include <boost/random/mersenne_twister.hpp>
#include <boost/random/uniform_int.hpp>

#include <arith_uint256.h>
#include <chain.h>
#include <dogecoin.h>
#include <logging.h>

#ifdef __clang__
__attribute__((no_sanitize("unsigned-integer-overflow")))
#endif // __clang__
int static generateMTRandom(unsigned int s, int range)
{
    boost::mt19937 gen(s);
    boost::uniform_int<> dist(1, range);
    return dist(gen);
}

CAmount GetDogecoinBlockSubsidy(int nHeight, const Consensus::Params& consensusParams, uint256 prevHash)
{
    int halvings = nHeight / consensusParams.nSubsidyHalvingInterval;

    if (nHeight < 145000 && !consensusParams.fSimplifiedRewards)
    {
        // Old-style rewards derived from the previous block hash

        // This extracts 7*4 bits out of the middle of the previous block hash to use as a seed.
        // It's longer than the 1.14 code, but avoids the locale-sensitive strtol() function.
        const int bitsPerNibble = 4;
        const int totalNibbles = 256 / bitsPerNibble;
        const int nibblesToClear = 7;
        const int nibblesToKeep = 7;
        arith_uint256 upperBits = UintToArith256(prevHash) << (nibblesToClear * bitsPerNibble);
        arith_uint256 cleanedBits = upperBits >> ((totalNibbles - nibblesToKeep) * bitsPerNibble);
        uint64_t seed = ArithToUint256(cleanedBits).GetUint64(0);

        // Convert the seed into a subsidy value.
        CAmount maxReward = (1000000 >> halvings) - 1;
        int rand = generateMTRandom(seed, maxReward);

        return (1 + rand) * COIN;
    } else if (nHeight < (6 * consensusParams.nSubsidyHalvingInterval)) {
        // New-style constant rewards for each halving interval
        return (500000 * COIN) >> halvings;
    } else {
        // Constant inflation
        return 10000 * COIN;
    }
}

// Dogecoin: Normally minimum difficulty blocks can only occur in between
// retarget blocks. However, once we introduce Digishield every block is
// a retarget, so we need to handle minimum difficulty on all blocks.
bool AllowDigishieldMinDifficultyForBlock(const CBlockIndex* pindexLast, const CBlockHeader *pblock, const Consensus::Params& params)
{
    // check if the chain allows minimum difficulty blocks
    if (!params.fPowAllowMinDifficultyBlocks)
        return false;

    // check if the chain allows minimum difficulty blocks on recalc blocks
    if (pindexLast->nHeight < 157500)
    // if (!params.fPowAllowDigishieldMinDifficultyBlocks)
        return false;

    // Allow for a minimum block time if the elapsed time > 2*nTargetSpacing
    return (pblock->GetBlockTime() > pindexLast->GetBlockTime() + params.nPowTargetSpacing*2);
}

unsigned int CalculateDogecoinNextWorkRequired(const CBlockIndex* pindexLast, int64_t nFirstBlockTime, const Consensus::Params& params)
{
    if (params.fPowNoRetargeting)
        return pindexLast->nBits;

    int nHeight = pindexLast->nHeight + 1;
    bool fNewDifficultyProtocol = (nHeight >= 145000);
    // bool fNewDifficultyProtocol = (nHeight >= params.GetDigiShieldForkBlock());
    const int64_t nRetargetTimespan = fNewDifficultyProtocol
                             ? 60 // params.DigiShieldTargetTimespan()
                             : params.nPowTargetTimespan;

    int64_t nTimespan = pindexLast->GetBlockTime() - nFirstBlockTime;
    int64_t nMaxTimespan;
    int64_t nMinTimespan;

    if (fNewDifficultyProtocol) //DigiShield implementation - thanks to RealSolid & WDC for this code
    {
        // amplitude filter - thanks to daft27 for this code
        nTimespan = nRetargetTimespan + (nTimespan - nRetargetTimespan) / 8;

        nMinTimespan = nRetargetTimespan - (nRetargetTimespan / 4);
        nMaxTimespan = nRetargetTimespan + (nRetargetTimespan / 2);
    } else if (nHeight > 10000) {
        nMinTimespan = nRetargetTimespan / 4;
        nMaxTimespan = nRetargetTimespan * 4;
    } else if (nHeight > 5000) {
        nMinTimespan = nRetargetTimespan / 8;
        nMaxTimespan = nRetargetTimespan * 4;
    } else {
        nMinTimespan = nRetargetTimespan / 16;
        nMaxTimespan = nRetargetTimespan * 4;
    }

    // Limit adjustment step
    if (nTimespan < nMinTimespan)
        nTimespan = nMinTimespan;
    else if (nTimespan > nMaxTimespan)
        nTimespan = nMaxTimespan;

    // Retarget
    const arith_uint256 bnPowLimit = UintToArith256(params.powLimit);
    arith_uint256 bnNew;
    bnNew.SetCompact(pindexLast->nBits);
    bnNew *= nTimespan;
    bnNew /= nRetargetTimespan;

    if (bnNew > bnPowLimit)
        bnNew = bnPowLimit;

    return bnNew.GetCompact();
}

max_stars_repo_name: rnicoll/dogecoin

max_issues_repo_name: rnicoll/dogecoin

max_forks_repo_name: rnicoll/dogecoin


text:
/*
 *
 * Copyright (c) Toon Knapen & Kresimir Fresl 2003
 *
 * 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)
 *
 * KF acknowledges the support of the Faculty of Civil Engineering,
 * University of Zagreb, Croatia.
 *
 */

#ifndef BOOST_NUMERIC_BINDINGS_LAPACK_GESV_HPP
#define BOOST_NUMERIC_BINDINGS_LAPACK_GESV_HPP

#include <boost/numeric/bindings/traits/type_traits.hpp>
#include <boost/numeric/bindings/traits/traits.hpp>
#include <boost/numeric/bindings/lapack/lapack.h>
#include <boost/numeric/bindings/traits/detail/array.hpp>
#include <boost/numeric/bindings/lapack/workspace.hpp>
#include <boost/numeric/bindings/lapack/ilaenv.hpp>

#ifndef BOOST_NUMERIC_BINDINGS_NO_STRUCTURE_CHECK
#  include <boost/static_assert.hpp>
#  include <boost/type_traits/is_same.hpp>
#endif

#include <cassert>

namespace boost { namespace numeric { namespace bindings {

  namespace lapack {

    ///////////////////////////////////////////////////////////////////
    //
    // general system of linear equations A * X = B
    //
    ///////////////////////////////////////////////////////////////////

    /*
     * gesv() computes the solution to a system of linear equations
     * A * X = B, where A is an N-by-N matrix and X and B are N-by-NRHS
     * matrices.
     *
     * The LU decomposition with partial pivoting and row interchanges
     * is used to factor A as A = P * L * U, where P is a permutation
     * matrix, L is unit lower triangular, and U is upper triangular.
     * The factored form of A is then used to solve the system of
     * equations A * X = B.
     */

    namespace detail {

      inline
      void gesv (integer_t const n, integer_t const nrhs,
                 float* a, integer_t const lda, integer_t* ipiv,
                 float* b, integer_t const ldb, integer_t* info)
      {
        LAPACK_SGESV (&n, &nrhs, a, &lda, ipiv, b, &ldb, info);
      }

      inline
      void gesv (integer_t const n, integer_t const nrhs,
                 double* a, integer_t const lda, integer_t* ipiv,
                 double* b, integer_t const ldb, integer_t* info)
      {
        LAPACK_DGESV (&n, &nrhs, a, &lda, ipiv, b, &ldb, info);
      }

      inline
      void gesv (integer_t const n, integer_t const nrhs,
                 traits::complex_f* a, integer_t const lda, integer_t* ipiv,
                 traits::complex_f* b, integer_t const ldb, integer_t* info)
      {
        LAPACK_CGESV (&n, &nrhs,
                      traits::complex_ptr (a), &lda, ipiv,
                      traits::complex_ptr (b), &ldb, info);
      }

      inline
      void gesv (integer_t const n, integer_t const nrhs,
                 traits::complex_d* a, integer_t const lda, integer_t* ipiv,
                 traits::complex_d* b, integer_t const ldb, integer_t* info)
      {
        LAPACK_ZGESV (&n, &nrhs,
                      traits::complex_ptr (a), &lda, ipiv,
                      traits::complex_ptr (b), &ldb, info);
      }

    } //namespace detail

    template <typename MatrA, typename MatrB, typename IVec>
    int gesv (MatrA& a, IVec& ipiv, MatrB& b) {

#ifndef BOOST_NUMERIC_BINDINGS_NO_STRUCTURE_CHECK
      BOOST_STATIC_ASSERT((boost::is_same<
        typename traits::matrix_traits<MatrA>::matrix_structure,
        traits::general_t
      >::value));
      BOOST_STATIC_ASSERT((boost::is_same<
        typename traits::matrix_traits<MatrB>::matrix_structure,
        traits::general_t
      >::value));
#endif

      integer_t const n = traits::matrix_size1 (a);
      assert (n == traits::matrix_size2 (a));
      assert (n == traits::matrix_size1 (b));
      assert (n == traits::vector_size (ipiv));

      integer_t info;
      detail::gesv (n, traits::matrix_size2 (b),
                    traits::matrix_storage (a),
                    traits::leading_dimension (a),
                    traits::vector_storage (ipiv),
                    traits::matrix_storage (b),
                    traits::leading_dimension (b),
                    &info);
      return info;
    }

    template <typename MatrA, typename MatrB>
    int gesv (MatrA& a, MatrB& b) {
      // with 'internal' pivot vector

      // gesv() errors:
      //   if (info == 0), successful
      //   if (info < 0), the -info argument had an illegal value
      //   -- we will use -101 if allocation fails
      //   if (info > 0), U(i-1,i-1) is exactly zero
      integer_t info = -101;
      traits::detail::array<integer_t> ipiv (traits::matrix_size1 (a));
      if (ipiv.valid())
        info = gesv (a, ipiv, b);
      return info;
    }

    /*
     * getrf() computes an LU factorization of a general M-by-N matrix A
     * using partial pivoting with row interchanges. The factorization
     * has the form A = P * L * U, where P is a permutation matrix,
     * L is lower triangular with unit diagonal elements (lower
     * trapezoidal if M > N), and U is upper triangular (upper
     * trapezoidal if M < N).
     */

    namespace detail {

      inline
      void getrf (integer_t const n, integer_t const m,
                  float* a, integer_t const lda, integer_t* ipiv, integer_t* info)
      {
        LAPACK_SGETRF (&n, &m, a, &lda, ipiv, info);
      }

      inline
      void getrf (integer_t const n, integer_t const m,
                  double* a, integer_t const lda, integer_t* ipiv, integer_t* info)
      {
        LAPACK_DGETRF (&n, &m, a, &lda, ipiv, info);
      }

      inline
      void getrf (integer_t const n, integer_t const m,
                  traits::complex_f* a, integer_t const
                  lda, integer_t* ipiv, integer_t* info)
      {
        LAPACK_CGETRF (&n, &m, traits::complex_ptr (a), &lda, ipiv, info);
      }

      inline
      void getrf (integer_t const n, integer_t const m,
                  traits::complex_d* a, integer_t const lda,
                  integer_t* ipiv, integer_t* info)
      {
        LAPACK_ZGETRF (&n, &m, traits::complex_ptr (a), &lda, ipiv, info);
      }

    } //namespace detail

    template <typename MatrA, typename IVec>
    int getrf (MatrA& a, IVec& ipiv) {

#ifndef BOOST_NUMERIC_BINDINGS_NO_STRUCTURE_CHECK
      BOOST_STATIC_ASSERT((boost::is_same<
        typename traits::matrix_traits<MatrA>::matrix_structure,
        traits::general_t
      >::value));
#endif

      integer_t const n = traits::matrix_size1 (a);
      integer_t const m = traits::matrix_size2 (a);
      assert (traits::vector_size (ipiv) == (m < n ? m : n));

      integer_t info;
      detail::getrf (n, m,
                     traits::matrix_storage (a),
                     traits::leading_dimension (a),
                     traits::vector_storage (ipiv),
                     &info);
      return info;
    }

    /*
     * getrs() solves a system of linear equations A * X = B
     * or A^T * X = B with a general N-by-N matrix A using
     * the LU factorization computed by getrf().
     */

    namespace detail {

      inline
      void getrs (char const trans, integer_t const n, integer_t const nrhs,
                  float const* a, integer_t const lda, integer_t const* ipiv,
                  float* b, integer_t const ldb, integer_t* info)
      {
        LAPACK_SGETRS (&trans, &n, &nrhs, a, &lda, ipiv, b, &ldb, info);
      }

      inline
      void getrs (char const trans, integer_t const n, integer_t const nrhs,
                  double const* a, integer_t const lda, integer_t const* ipiv,
                  double* b, integer_t const ldb, integer_t* info)
      {
        LAPACK_DGETRS (&trans, &n, &nrhs, a, &lda, ipiv, b, &ldb, info);
      }

      inline
      void getrs (char const trans, integer_t const n, integer_t const nrhs,
                  traits::complex_f const* a, integer_t const lda,
                  integer_t const* ipiv,
                  traits::complex_f* b, integer_t const ldb, integer_t* info)
      {
        LAPACK_CGETRS (&trans, &n, &nrhs,
                       traits::complex_ptr (a), &lda, ipiv,
                       traits::complex_ptr (b), &ldb, info);
      }

      inline
      void getrs (char const trans, integer_t const n, integer_t const nrhs,
                  traits::complex_d const* a, integer_t const lda,
                  integer_t const* ipiv,
                  traits::complex_d* b, integer_t const ldb, integer_t* info)
      {
        LAPACK_ZGETRS (&trans, &n, &nrhs,
                       traits::complex_ptr (a), &lda, ipiv,
                       traits::complex_ptr (b), &ldb, info);
      }

    } // namespace detail

    template <typename MatrA, typename MatrB, typename IVec>
    int getrs (char const trans, MatrA const& a, IVec const& ipiv, MatrB& b)
    {
      assert (trans == 'N' || trans == 'T' || trans == 'C');

#ifndef BOOST_NUMERIC_BINDINGS_NO_STRUCTURE_CHECK
      BOOST_STATIC_ASSERT((boost::is_same<
        typename traits::matrix_traits<MatrA>::matrix_structure,
        traits::general_t
      >::value));
      BOOST_STATIC_ASSERT((boost::is_same<
        typename traits::matrix_traits<MatrB>::matrix_structure,
        traits::general_t
      >::value));
#endif

      integer_t const n = traits::matrix_size1 (a);
      assert (n == traits::matrix_size2 (a));
      assert (n == traits::matrix_size1 (b));
      assert (n == traits::vector_size (ipiv));

      integer_t info;
      detail::getrs (trans, n, traits::matrix_size2 (b),
#ifndef BOOST_NO_FUNCTION_TEMPLATE_ORDERING
                     traits::matrix_storage (a),
#else
                     traits::matrix_storage_const (a),
#endif
                     traits::leading_dimension (a),
#ifndef BOOST_NO_FUNCTION_TEMPLATE_ORDERING
                     traits::vector_storage (ipiv),
#else
                     traits::vector_storage_const (ipiv),
#endif
                     traits::matrix_storage (b),
                     traits::leading_dimension (b),
                     &info);
      return info;
    }

    template <typename MatrA, typename MatrB, typename IVec>
    inline
    int getrs (MatrA const& a, IVec const& ipiv, MatrB& b) {
      char const no_transpose = 'N';
      return getrs (no_transpose, a, ipiv, b);
    }

    /*
     * getri() computes the inverse of a matrix using
     * the LU factorization computed by getrf().
     */

    namespace detail {

      inline
      void getri (integer_t const n, float* a, integer_t const lda, integer_t const* ipiv,
                  float* work, integer_t const lwork, integer_t* info)
      {
        LAPACK_SGETRI (&n, a, &lda, ipiv, work, &lwork, info);
      }

      inline
      void getri (integer_t const n, double* a, integer_t const lda, integer_t const* ipiv,
                  double* work, integer_t const lwork, integer_t* info)
      {
        LAPACK_DGETRI (&n, a, &lda, ipiv, work, &lwork, info);
      }

      inline
      void getri (integer_t const n, traits::complex_f* a, integer_t const lda,
          integer_t const* ipiv, traits::complex_f* work, integer_t const lwork,
          integer_t* info)
      {
        LAPACK_CGETRI (&n, traits::complex_ptr (a), &lda, ipiv,
            traits::complex_ptr (work), &lwork, info);
      }

      inline
      void getri (integer_t const n, traits::complex_d* a, integer_t const lda,
          integer_t const* ipiv, traits::complex_d* work, integer_t const lwork,
          integer_t* info)
      {
        LAPACK_ZGETRI (&n, traits::complex_ptr (a), &lda, ipiv,
            traits::complex_ptr (work), &lwork, info);
      }

      template <typename MatrA, typename IVec, typename Work>
      int getri (MatrA& a, IVec const& ipiv, Work& work)
      {
        #ifndef BOOST_NUMERIC_BINDINGS_NO_STRUCTURE_CHECK
        BOOST_STATIC_ASSERT((boost::is_same<
              typename traits::matrix_traits<MatrA>::matrix_structure,
              traits::general_t
              >::value));
        #endif

        integer_t const n = traits::matrix_size1 (a);
        assert (n > 0);
        assert (n <= traits::leading_dimension (a));
        assert (n == traits::matrix_size2 (a));
        assert (n == traits::vector_size (ipiv));
        assert (n <= traits::vector_size (work)); //Minimal workspace size

        integer_t info;
        //double* dummy = traits::matrix_storage (a);
        detail::getri (n, traits::matrix_storage (a),
            traits::leading_dimension (a),
#ifndef BOOST_NO_FUNCTION_TEMPLATE_ORDERING
            traits::vector_storage (ipiv),
#else
            traits::vector_storage_const (ipiv),
#endif
            traits::vector_storage (work),
            traits::vector_size (work),
            &info);
        return info;
      }

      inline
      integer_t getri_block(float)
      {
        return lapack::ilaenv(1, "sgetri", "");
      }

      inline
      integer_t getri_block(double)
      {
        return lapack::ilaenv(1, "dgetri", "");
      }

      inline
      integer_t getri_block(traits::complex_f)
      {
        return lapack::ilaenv(1, "cgetri", "");
      }

      inline
      integer_t getri_block(traits::complex_d)
      {
        return lapack::ilaenv(1, "zgetri", "");
      }

    } // namespace detail

    template <typename MatrA, typename IVec>
    int getri(MatrA& a, IVec& ipiv, minimal_workspace)
    {
      typedef typename MatrA::value_type value_type;

      std::ptrdiff_t n = traits::matrix_size1(a);
      traits::detail::array<value_type> work(std::max<std::ptrdiff_t>(1,n));

      return detail::getri(a, ipiv, work);

    }

    // optimal workspace allocation
    template <typename MatrA, typename IVec>
    int getri(MatrA& a, IVec& ipiv, optimal_workspace)
    {
      typedef typename MatrA::value_type value_type;

      std::ptrdiff_t n = traits::matrix_size1(a);
      std::ptrdiff_t nb = detail::getri_block(value_type());
      traits::detail::array<value_type> work(std::max<std::ptrdiff_t>(1,n*nb));

      return detail::getri(a, ipiv, work);
    }

    template <typename MatrA, typename IVec>
    inline
    int getri(MatrA& a, IVec& ipiv)
    {
      return getri(a, ipiv, optimal_workspace());
    }

    template <typename MatrA, typename IVec, typename Work>
    inline
    int getri(MatrA& a, IVec& ipiv, Work& work)
    {
      return detail::getri(a, ipiv, work);
    }

  } // namespace lapack

}}} // namespace boost::numeric::bindings

#endif

ext: hpp

max_stars_repo_name: diku-dk/PROX

max_issues_repo_name: diku-dk/PROX

max_forks_repo_name: diku-dk/PROX


text: #include <boost/hana/range.hpp>

max_stars_repo_name: miathedev/BoostForArduino

max_issues_repo_name: miathedev/BoostForArduino

max_forks_repo_name: miathedev/BoostForArduino


text:
// --------------------------------------------------------------------------
//                   OpenMS -- Open-Source Mass Spectrometry
// --------------------------------------------------------------------------
// Copyright The OpenMS Team -- Eberhard Karls University Tuebingen,
// ETH Zurich, and Freie Universitaet Berlin 2002-2015.
//
// This software is released under a three-clause BSD license:
//  * Redistributions of source code must retain the above copyright
//    notice, this list of conditions and the following disclaimer.
//  * 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.
//  * Neither the name of any author or any participating institution
//    may be used to endorse or promote products derived from this software
//    without specific prior written permission.
// For a full list of authors, refer to the file AUTHORS.
// --------------------------------------------------------------------------
// 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 ANY OF THE AUTHORS OR THE CONTRIBUTING
// INSTITUTIONS 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.
//
// --------------------------------------------------------------------------
// $Maintainer: Clemens Groepl $
// $Authors: $
// --------------------------------------------------------------------------

#include <OpenMS/TRANSFORMATIONS/FEATUREFINDER/EmgFitter1D.h>
#include <OpenMS/TRANSFORMATIONS/FEATUREFINDER/InterpolationModel.h>
#include <OpenMS/MATH/STATISTICS/StatisticFunctions.h>
#include <OpenMS/CONCEPT/Constants.h>
#include <OpenMS/CONCEPT/Factory.h>

#include <boost/math/special_functions/fpclassify.hpp>

namespace OpenMS
{
  int EmgFitter1D::EgmFitterFunctor::operator()(const Eigen::VectorXd& x, Eigen::VectorXd& fvec)
  {
    Size n = m_data->n;
    EmgFitter1D::RawDataArrayType set = m_data->set;

    EmgFitter1D::CoordinateType h = x(0);
    EmgFitter1D::CoordinateType w = x(1);
    EmgFitter1D::CoordinateType s = x(2);
    EmgFitter1D::CoordinateType z = x(3);

    EmgFitter1D::CoordinateType Yi = 0.0;

    // iterate over all points of the signal
    for (Size i = 0; i < n; i++)
    {
      double t = set[i].getPos();

      // Simplified EMG
      Yi = (h * w / s) * sqrt(2.0 * Constants::PI) * exp((pow(w, 2) / (2 * pow(s, 2))) - ((t - z) / s)) / (1 + exp((-2.4055 / sqrt(2.0)) * (((t - z) / w) - w / s)));

      fvec(i) = Yi - set[i].getIntensity();
    }
    return 0;
  }

  // compute Jacobian matrix for the different parameters
  int EmgFitter1D::EgmFitterFunctor::df(const Eigen::VectorXd& x, Eigen::MatrixXd& J)
  {
    Size n =  m_data->n;
    EmgFitter1D::RawDataArrayType set = m_data->set;

    EmgFitter1D::CoordinateType h = x(0);
    EmgFitter1D::CoordinateType w = x(1);
    EmgFitter1D::CoordinateType s = x(2);
    EmgFitter1D::CoordinateType z = x(3);

    const EmgFitter1D::CoordinateType emg_const = 2.4055;
    const EmgFitter1D::CoordinateType sqrt_2pi = sqrt(2 * Constants::PI);
    const EmgFitter1D::CoordinateType sqrt_2 = sqrt(2.0);

    EmgFitter1D::CoordinateType exp1, exp2, exp3 = 0.0;
    EmgFitter1D::CoordinateType derivative_height, derivative_width, derivative_symmetry, derivative_retention = 0.0;

    // iterate over all points of the signal
    for (Size i = 0; i < n; i++)
    {
      EmgFitter1D::CoordinateType t = set[i].getPos();

      exp1 = exp(((w * w) / (2 * s * s)) - ((t - z) / s));
      exp2 = (1 + exp((-emg_const / sqrt_2) * (((t - z) / w) - w / s)));
      exp3 = exp((-emg_const / sqrt_2) * (((t - z) / w) - w / s));

      // f'(h)
      derivative_height = w / s * sqrt_2pi * exp1 / exp2;

      // f'(h)
      derivative_width = h / s * sqrt_2pi * exp1 / exp2 + (h * w * w) / (s * s * s) * sqrt_2pi * exp1 / exp2 + (emg_const * h * w) / s * sqrt_2pi * exp1 * (-(t - z) / (w * w) - 1 / s) * exp3 / ((exp2 * exp2) * sqrt_2);

      // f'(s)
      derivative_symmetry = -h * w / (s * s) * sqrt_2pi * exp1 / exp2 + h * w / s * sqrt_2pi * (-(w * w) / (s * s * s) + (t - z) / (s * s)) * exp1 / exp2 + (emg_const * h * w * w) / (s * s * s) * sqrt_2pi * exp1 * exp3 / ((exp2 * exp2) * sqrt_2);

      // f'(z)
      derivative_retention = h * w / (s * s) * sqrt_2pi * exp1 / exp2 - (emg_const * h) / s * sqrt_2pi * exp1 * exp3 / ((exp2 * exp2) * sqrt_2);

      // set the jacobian matrix
      J(i, 0) = derivative_height;
      J(i, 1) = derivative_width;
      J(i, 2) = derivative_symmetry;
      J(i, 3) = derivative_retention;
    }
    return 0;
  }

  EmgFitter1D::EmgFitter1D() :
    LevMarqFitter1D()
  {
    setName(getProductName());
    defaults_.setValue("statistics:variance", 1.0, "Variance of the model.", ListUtils::create<String>("advanced"));
    defaultsToParam_();
  }

  EmgFitter1D::EmgFitter1D(const EmgFitter1D& source) :
    LevMarqFitter1D(source)
  {
    setParameters(source.getParameters());
    updateMembers_();
  }

  EmgFitter1D::~EmgFitter1D()
  {
  }

  EmgFitter1D& EmgFitter1D::operator=(const EmgFitter1D& source)
  {
    if (&source == this)
      return *this;

    LevMarqFitter1D::operator=(source);
    setParameters(source.getParameters());
    updateMembers_();

    return *this;
  }

  EmgFitter1D::QualityType EmgFitter1D::fit1d(const RawDataArrayType& set, InterpolationModel*& model)
  {
    // Calculate bounding box
    CoordinateType min_bb = set[0].getPos(), max_bb = set[0].getPos();
    for (Size pos = 1; pos < set.size(); ++pos)
    {
      CoordinateType tmp = set[pos].getPos();
      if (min_bb > tmp)
        min_bb = tmp;
      if (max_bb < tmp)
        max_bb = tmp;
    }

    // Enlarge the bounding box by a few multiples of the standard deviation
    const CoordinateType stdev = sqrt(statistics_.variance()) * tolerance_stdev_box_;
    min_bb -= stdev;
    max_bb += stdev;

    // Set advanced parameters for residual_  und jacobian_ method
    EmgFitter1D::Data d;
    d.n = set.size();
    d.set = set;

    // Compute start parameters
    setInitialParameters_(set);

    // Optimize parameter with Levenberg-Marquardt algorithm
//    CoordinateType x_init[4] = { height_, width_, symmetry_, retention_ };
    Eigen::VectorXd x_init(4);
    x_init(0) = height_;
    x_init(1) = width_;
    x_init(2) = symmetry_;
    x_init(3) = retention_;
    if (symmetric_ == false)
    {
      EgmFitterFunctor functor(4, &d);
      optimize_(x_init, functor);
    }

    // Set optimized parameters
    height_ = x_init[0];
    width_ = x_init[1];
    symmetry_ = x_init[2];
    retention_ = x_init[3];

#ifdef DEBUG_FEATUREFINDER
    if (getGslStatus_() != "success")
    {
      std::cout << "status: " << getGslStatus_() << std::endl;
    }
#endif

    // build model
    model = static_cast<InterpolationModel*>(Factory<BaseModel<1> >::create("EmgModel"));
    model->setInterpolationStep(interpolation_step_);

    Param tmp;
    tmp.setValue("bounding_box:min", min_bb);
    tmp.setValue("bounding_box:max", max_bb);
    tmp.setValue("statistics:variance", statistics_.variance());
    tmp.setValue("statistics:mean", statistics_.mean());
    tmp.setValue("emg:height", height_);
    tmp.setValue("emg:width", width_);
    tmp.setValue("emg:symmetry", symmetry_);
    tmp.setValue("emg:retention", retention_);
    model->setParameters(tmp);

    // calculate pearson correlation
    std::vector<float> real_data;
    real_data.reserve(set.size());
    std::vector<float> model_data;
    model_data.reserve(set.size());

    for (Size i = 0; i < set.size(); ++i)
    {
      real_data.push_back(set[i].getIntensity());
      model_data.push_back(model->getIntensity(DPosition<1>(set[i].getPosition())));
    }

    QualityType correlation = Math::pearsonCorrelationCoefficient(real_data.begin(), real_data.end(), model_data.begin(), model_data.end());
    if (boost::math::isnan(correlation))
      correlation = -1.0;

    return correlation;
  }

  void EmgFitter1D::setInitialParameters_(const RawDataArrayType& set)
  {
    // sum over all intensities
    CoordinateType sum = 0.0;
    for (Size i = 0; i < set.size(); ++i)
      sum += set[i].getIntensity();

    // calculate the median
    Size median = 0;
    float count = 0.0;
    for (Size i = 0; i < set.size(); ++i)
    {
      count += set[i].getIntensity();
      if (count <= sum / 2)
        median = i;
    }

    // calculate the height of the peak
    height_ = set[median].getIntensity();

    // calculate retention time
    retention_ = set[median].getPos();

    // default is an asymmetric peak
    symmetric_ = false;

    // calculate the symmetry (fronted peak: s<1 , tailed peak: s>1)
    symmetry_ = fabs(set[set.size() - 1].getPos() - set[median].getPos()) / fabs(set[median].getPos() - set[0].getPos());

    // check the symmetry
    if (boost::math::isinf(symmetry_) || boost::math::isnan(symmetry_))
    {
      symmetric_ = true;
      symmetry_ = 10;
    }

    // optimize the symmetry
    // The computations can lead to an overflow error at very low values of symmetry (s~0).
    // For s~5 the parameter can be approximated by the Levenberg-Marquardt algorithms.
    // (the other parameters are much greater than one)
    if (symmetry_ < 1)
      symmetry_ += 5;

    // calculate the width of the peak
    // rt-values with intensity zero are not allowed for calculation of the width
    // normally: width_ = fabs( set[set.size() - 1].getPos() - set[0].getPos() );
    // but its better for the emg function to proceed from narrow peaks
    width_ = symmetry_;
  }

  void EmgFitter1D::updateMembers_()
  {
    LevMarqFitter1D::updateMembers_();
    statistics_.setVariance(param_.getValue("statistics:variance"));
  }

}

ext: cpp

max_stars_repo_name: tomas-pluskal/openms

max_issues_repo_name: tomas-pluskal/openms

max_forks_repo_name: tomas-pluskal/openms


text:
////////////////////////////////////////////////////////////////////////////
// Name:         Lion.hpp
// Description:  Interface for class that represents a lion
// Created:      09/01/2004 09:23:56 Eastern Daylight Time
// Last Updated: $Date: 2004/09/18 22:23:06 $
// Revision:     $Revision: 1.1 $
// Author:       John Weathers
// Email:        hotanguish@hotmail.com
// Copyright:    (c) 2004 John Weathers
////////////////////////////////////////////////////////////////////////////

#ifndef __Lion_HPP__
#define __Lion_HPP__

// Boost header files
#include <boost/dynamic_bitset.hpp>

// mShogi header files
#include "PieceType.hpp"
#include "common.hpp"

// Forward declarations
class Board;

class Lion : public PieceType
{
public:
   // ==========================================================================
   // Construction
   // ==========================================================================
   Lion(Board* board, int value, int typevalue);
   virtual ~Lion();

   // ==========================================================================
   // Operations
   // ==========================================================================
   bool ThreatensSquare(Piece* piece, int square);
   void GenerateCaptures(std::vector<Move>& movelist, Piece* piece);
   void GenerateNonCaptures(std::vector<Move>& movelist, Piece* piece);

   // ==========================================================================
   // Class Variables
   // ==========================================================================
   static bool sLionCaptureRules;
private:
   // ==========================================================================
   // Constants
   // ==========================================================================
   enum { TYPE_A = 0, TYPE_B };

   // ==========================================================================
   // Data
   // ==========================================================================
   Board* mpBoard;                 // Pointer to the game's board
   int    mSize;                   // Board size
   Bitboard* mAttackBitboards[2];  // Array of bitboards for calculating moves
};

#endif


text:
/**
 * Copyright Soramitsu Co., Ltd. 2017 All Rights Reserved.
 * http://soramitsu.co.jp
 *
 * 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 <boost/algorithm/string.hpp>
#include <fstream>

#include "client.hpp"
#include "common/byteutils.hpp"
#include "crypto/keys_manager_impl.hpp"
#include "cryptography/ed25519_sha3_impl/internal/ed25519_impl.hpp"
#include "datetime/time.hpp"
#include "grpc_response_handler.hpp"
#include "interactive/interactive_query_cli.hpp"
#include "model/converters/json_query_factory.hpp"
#include "model/model_crypto_provider.hpp"  // for ModelCryptoProvider
#include "model/queries/get_asset_info.hpp"
#include "model/queries/get_roles.hpp"
#include "model/sha3_hash.hpp"

using namespace iroha::model;

namespace iroha_cli {
  namespace interactive {

    void InteractiveQueryCli::create_queries_menu() {
      description_map_ = {
          {GET_ACC, "Get Account Information"},
          {GET_ACC_AST, "Get Account's Assets"},
          {GET_ACC_TX, "Get Account's Transactions"},
          {GET_TX, "Get Transactions by transactions' hashes"},
          {GET_ACC_SIGN, "Get Account's Signatories"},
          {GET_ROLES, "Get all current roles in the system"},
          {GET_AST_INFO, "Get information about asset"},
          {GET_ROLE_PERM, "Get all permissions related to role"}
          // description_map_
      };

      const auto acc_id = "Requested account Id";
      const auto ast_id = "Requested asset Id";
      const auto role_id = "Requested role name";
      const auto tx_hashes = "Requested tx hashes";

      query_params_descriptions_ = {
          {GET_ACC, {acc_id}},
          {GET_ACC_AST, {acc_id, ast_id}},
          {GET_ACC_TX, {acc_id}},
          {GET_TX, {tx_hashes}},
          {GET_ACC_SIGN, {acc_id}},
          {GET_ROLES, {}},
          {GET_AST_INFO, {ast_id}},
          {GET_ROLE_PERM, {role_id}}
          // query_params_descriptions_
      };

      query_handlers_ = {
          {GET_ACC, &InteractiveQueryCli::parseGetAccount},
          {GET_ACC_AST, &InteractiveQueryCli::parseGetAccountAssets},
          {GET_ACC_TX, &InteractiveQueryCli::parseGetAccountTransactions},
          {GET_TX, &InteractiveQueryCli::parseGetTransactions},
          {GET_ACC_SIGN, &InteractiveQueryCli::parseGetSignatories},
          {GET_ROLE_PERM, &InteractiveQueryCli::parseGetRolePermissions},
          {GET_ROLES, &InteractiveQueryCli::parseGetRoles},
          {GET_AST_INFO, &InteractiveQueryCli::parseGetAssetInfo}
          // query_handlers_
      };

      menu_points_ = formMenu(
          query_handlers_, query_params_descriptions_, description_map_);
      // Add "go back" option
      addBackOption(menu_points_);
    }

    void InteractiveQueryCli::create_result_menu() {
      result_handlers_ = {{SAVE_CODE, &InteractiveQueryCli::parseSaveFile},
                          {SEND_CODE, &InteractiveQueryCli::parseSendToIroha}};
      result_params_descriptions_ =
          getCommonParamsMap(default_peer_ip_, default_port_);

      result_points_ = formMenu(result_handlers_,
                                result_params_descriptions_,
                                getCommonDescriptionMap());
      addBackOption(result_points_);
    }

    InteractiveQueryCli::InteractiveQueryCli(
        const std::string &account_name,
        const std::string &default_peer_ip,
        int default_port,
        uint64_t query_counter,
        const std::shared_ptr<iroha::model::ModelCryptoProvider> &provider)
        : current_context_(MAIN),
          creator_(account_name),
          default_peer_ip_(default_peer_ip),
          default_port_(default_port),
          counter_(query_counter),
          provider_(provider) {
      log_ = logger::log("InteractiveQueryCli");
      create_queries_menu();
      create_result_menu();
    }

    static void printMenu(const MenuPoints &menu) {
      printMenu("Choose query: ", menu);
    }

    void InteractiveQueryCli::run() {
      bool is_parsing = true;
      current_context_ = MAIN;
      printMenu(menu_points_);
      // Creating a new query, increment local counter
      ++counter_;
      // Init timestamp for a new query
      local_time_ = iroha::time::now();

      while (is_parsing) {
        auto line = promptString("> ");
        if (not line) {
          // The promtSting returns error, terminating symbol
          is_parsing = false;
          break;
        }
        switch (current_context_) {
          case MAIN:
            is_parsing = parseQuery(line.value());
            break;
          case RESULT:
            is_parsing = parseResult(line.value());
            break;
          default:
            BOOST_ASSERT_MSG(false, "not implemented");
        }
      }
    }

    bool InteractiveQueryCli::parseQuery(std::string line) {
      if (isBackOption(line)) {
        // Stop parsing
        return false;
      }

      auto res = handleParse<std::shared_ptr<iroha::model::Query>>(
          this, line, query_handlers_, query_params_descriptions_);
      if (not res) {
        // Continue parsing
        return true;
      }

      query_ = res.value();
      current_context_ = RESULT;
      printMenu("Query is formed. Choose what to do:", result_points_);
      // Continue parsing
      return true;
    }

    std::shared_ptr<iroha::model::Query> InteractiveQueryCli::parseGetAccount(
        QueryParams params) {
      auto account_id = params[0];
      return generator_.generateGetAccount(
          local_time_, creator_, counter_, account_id);
    }

    std::shared_ptr<iroha::model::Query>
    InteractiveQueryCli::parseGetAccountAssets(QueryParams params) {
      auto account_id = params[0];
      auto asset_id = params[1];
      return generator_.generateGetAccountAssets(
          local_time_, creator_, counter_, account_id, asset_id);
    }

    std::shared_ptr<iroha::model::Query>
    InteractiveQueryCli::parseGetAccountTransactions(QueryParams params) {
      auto account_id = params[0];
      return generator_.generateGetAccountTransactions(
          local_time_, creator_, counter_, account_id);
    }

    std::shared_ptr<iroha::model::Query>
    InteractiveQueryCli::parseGetTransactions(QueryParams params) {
      // Parser definition: hash1 hash2 ...
      GetTransactions::TxHashCollectionType tx_hashes;
      std::for_each(
          params.begin(), params.end(), [&tx_hashes](auto const &hex_hash) {
            if (auto opt = iroha::
                    hexstringToArray<GetTransactions::TxHashType::size()>(
                        hex_hash)) {
              tx_hashes.push_back(*opt);
            }
          });
      return generator_.generateGetTransactions(
          local_time_, creator_, counter_, tx_hashes);
    }

    std::shared_ptr<iroha::model::Query>
    InteractiveQueryCli::parseGetSignatories(QueryParams params) {
      auto account_id = params[0];
      return generator_.generateGetSignatories(
          local_time_, creator_, counter_, account_id);
    }

    std::shared_ptr<iroha::model::Query> InteractiveQueryCli::parseGetAssetInfo(
        QueryParams params) {
      auto asset_id = params[0];
      auto query = std::make_shared<GetAssetInfo>(asset_id);
      // TODO 26/09/17 grimadas: remove duplicated code and move
      // setQueryMetaData calls to private method IR-508 #goodfirstissue
      generator_.setQueryMetaData(query, local_time_, creator_, counter_);
      return query;
    }

    std::shared_ptr<iroha::model::Query> InteractiveQueryCli::parseGetRoles(
        QueryParams params) {
      auto query = std::make_shared<GetRoles>();
      generator_.setQueryMetaData(query, local_time_, creator_, counter_);
      return query;
    }

    std::shared_ptr<iroha::model::Query>
    InteractiveQueryCli::parseGetRolePermissions(QueryParams params) {
      auto role_name = params[0];
      auto query = std::make_shared<GetRolePermissions>(role_name);
      generator_.setQueryMetaData(query, local_time_, creator_, counter_);
      return query;
    }

    bool InteractiveQueryCli::parseResult(std::string line) {
      if (isBackOption(line)) {
        // Give up the last query and start a new one
        current_context_ = MAIN;
        printEnd();
        printMenu(menu_points_);
        // Continue parsing
        return true;
      }

      auto res = handleParse<bool>(
          this, line, result_handlers_, result_params_descriptions_);

      return res.get_value_or(true);
    }

    bool InteractiveQueryCli::parseSendToIroha(QueryParams params) {
      auto address =
          parseIrohaPeerParams(params, default_peer_ip_, default_port_);
      if (not address) {
        return true;
      }

      provider_->sign(*query_);

      CliClient client(address.value().first, address.value().second);
      GrpcResponseHandler{}.handle(client.sendQuery(query_));
      printEnd();
      // Stop parsing
      return false;
    }

    bool InteractiveQueryCli::parseSaveFile(QueryParams params) {
      provider_->sign(*query_);

      auto path = params[0];
      iroha::model::converters::JsonQueryFactory json_factory;
      auto json_string = json_factory.serialize(query_);
      std::ofstream output_file(path);
      if (not output_file) {
        std::cout << "Cannot create file" << std::endl;
        // Continue parsing
        return true;
      }
      output_file << json_string;
      std::cout << "Successfully saved!" << std::endl;
      printEnd();
      // Stop parsing
      return false;
    }

  }  // namespace interactive
}  // namespace iroha_cli

max_stars_repo_name: steephengeorge/iroha

max_issues_repo_name: steephengeorge/iroha

max_forks_repo_name: steephengeorge/iroha


text:
#include "WFCDungeonGenInterface.h"
#include "WaveFunctionCollapse.h"
#include "Map.h"
#include "DRandom.h"
#include <boost/filesystem.hpp>

extern Map m;

namespace WFC
{

WFCDungeonGenInterface::WFCDungeonGenInterface(std::string_view load_disk_path)
{
	std::string patterns_path = std::string(load_disk_path) + "\\Patterns";
	boost::filesystem::directory_iterator end_iter;
	for (boost::filesystem::directory_iterator itr(patterns_path); itr != end_iter; itr++)
	{
		if (boost::filesystem::is_regular_file(itr->path()) && boost::filesystem::extension(itr->path()) == ".json")
		{
			pattern_paths.push_back(itr->path().string());
		}
	}
}

int WFCDungeonGenInterface::Place(int x, int y, int width, int height)
{
	const std::string& path = pattern_paths[DRandom::instance->GetInt(0, pattern_paths.size() - 1)];

	int placed = 0;
	//Could alternatively use the Map to fill up WFC output with pre-collapsed values
	WaveFunctionCollapse wfc(path, width, height);
	auto output = wfc.Run();
	for (int j = y; j < y + height; j++)
	{
		for (int i = x; i < x + width; i++)
		{
			if (m.Get(i, j).type == TileType::Nothing)
			{
				auto outputTile = output[j - y][i - x];
				if (outputTile == WFCTileType::Wall || outputTile == WFCTileType::Asteroid)
				{
					m.Set(i, j, Tile(TileType::WFCWall));
				}
				else if (outputTile == WFCTileType::Empty || outputTile == WFCTileType::Floor || outputTile == WFCTileType::NonRoomFloor)
				{
					m.Set(i, j, Tile(TileType::WFCFloor));
				}

				placed++;
			}
		}
	}

	return placed;
}

int WFCDungeonGenInterface::PlaceConstantVisualisation(int x, int y, int width, int height)
{
	const std::string& path = pattern_paths[DRandom::instance->GetInt(0, pattern_paths.size() - 1)];

	//Could alternatively use the Map to fill up WFC output with pre-collapsed values
	WaveFunctionCollapse wfc(path, width, height);

	int drawStep = 0;

	auto apply_to_map =
		[&](const boost::multi_array<WFCTileType::WFCTile, 2>& wfc)
	{
		int placed = 0;
		for (int j = y; j < y + height; j++)
		{
			for (int i = x; i < x + width; i++)
			{
				if (m.Get(i, j).type == TileType::Nothing || m.Get(i, j).type == TileType::WFCWall || m.Get(i, j).type == TileType::WFCFloor)
				{
					auto outputTile = wfc[j - y][i - x];
					if (outputTile == WFCTileType::Wall || outputTile == WFCTileType::Asteroid)
					{
						m.Set(i, j, Tile(TileType::WFCWall));
					}
					else if (outputTile == WFCTileType::Empty || outputTile == WFCTileType::Floor || outputTile == WFCTileType::NonRoomFloor)
					{
						m.Set(i, j, Tile(TileType::WFCFloor));
					}

					placed++;
				}
			}
		}
		if (drawStep++ % 20 == 0)
		{
			m.Display(false);
		}
		return placed;
	};

	auto output = wfc.RunVisualiseContinuous(apply_to_map);

	return apply_to_map(output);
}

}

max_stars_repo_name: RedBreadcat/SpaghettiDungeonGenerator

max_issues_repo_name: RedBreadcat/SpaghettiDungeonGenerator

max_forks_repo_name: RedBreadcat/SpaghettiDungeonGenerator


text:
#include <catch2/catch.hpp>
#include <Euclid/Math/Numeric.h>

#include <iostream>
#include <boost/math/constants/constants.hpp>

TEST_CASE("Math, Numeric", "[math][numeric]")
{
    SECTION("equality check")
    {
        float zerof = 0.0f;
        float almost_zerof = std::sin(boost::math::double_constants::pi);
        float onef = 1.0f;
        float almost_onef = 0.0f;
        for (int i = 0; i < 10; ++i) {
            almost_onef += 0.1f;
        }
        double smalld = 1.0e-8;
        double almost_smalld = smalld + 1.0e-16;
        double larged = 1.0e8;
        double almost_larged = larged + 1.0e-8;
        REQUIRE(zerof != almost_zerof);
        REQUIRE(onef != almost_onef);
        REQUIRE(smalld != almost_smalld);
        REQUIRE(larged != almost_larged);

        SECTION("eq_almost is robust in most cases")
        {
            REQUIRE(Euclid::eq_almost(zerof, almost_zerof));
            REQUIRE(Euclid::eq_almost(smalld, almost_smalld));
            REQUIRE(Euclid::eq_almost(onef, almost_onef));
            REQUIRE(Euclid::eq_almost(larged, almost_larged));

            double fail = 1.0e-8;
            double almost_fail = fail + 1.0e-14;
            REQUIRE(!Euclid::eq_almost(fail, almost_fail));
            REQUIRE(Euclid::eq_almost(fail, almost_fail, 1.0e-13));
        }

        SECTION("eq_rel_err is valid when not comparing to small values")
        {
            REQUIRE(!Euclid::eq_rel_err(zerof, almost_zerof));
            REQUIRE(Euclid::eq_rel_err(
                zerof,
                almost_zerof,
                1.0e10f * std::numeric_limits<float>::epsilon()));
            REQUIRE(!Euclid::eq_rel_err(smalld, almost_smalld));
            REQUIRE(Euclid::eq_rel_err(
                smalld,
                almost_smalld,
                1.0e8 * std::numeric_limits<double>::epsilon()));
            REQUIRE(Euclid::eq_rel_err(onef, almost_onef));
            REQUIRE(Euclid::eq_rel_err(larged, almost_larged));
        }

        SECTION("eq_abs_err is only valid when the bound is known")
        {
            REQUIRE(Euclid::eq_abs_err(zerof, almost_zerof));
            REQUIRE(Euclid::eq_abs_err(smalld, almost_smalld));
            REQUIRE(!Euclid::eq_abs_err(onef, almost_onef));
            REQUIRE(Euclid::eq_abs_err(onef, almost_onef, 1.0e-6f));
            REQUIRE(!Euclid::eq_abs_err(larged, almost_larged));
            REQUIRE(Euclid::eq_abs_err(larged, almost_larged, 1.0e-7));
        }

        SECTION("eq_ulp is also robust when not comparing to small values")
        {
            REQUIRE(!Euclid::eq_ulp(zerof, almost_zerof));
            REQUIRE(!Euclid::eq_ulp(smalld, almost_smalld));
            REQUIRE(Euclid::eq_ulp(onef, almost_onef, 1));
            REQUIRE(!Euclid::eq_ulp(onef, almost_onef, 0));
            REQUIRE(Euclid::eq_ulp(larged, almost_larged, 1));
        }
    }

    SECTION("inequality check")
    {
        float small = 0.1f;
        float large = 1000.0f;
        float margin = 1.0e-15f;

        REQUIRE(!(small + margin < small));
        REQUIRE(Euclid::less_safe(small + margin, small, 1.0e-14f));
        REQUIRE(!(large + margin < large));
        REQUIRE(Euclid::less_safe(large + margin, large));
        REQUIRE(!(small > small + margin));
        REQUIRE(Euclid::greater_safe(small, small + margin, 1.0e-14f));
        REQUIRE(!(large > large + margin));
        REQUIRE(Euclid::greater_safe(large, large + margin));
    }
}

max_stars_repo_name: unclejimbo/euclid

max_issues_repo_name: unclejimbo/euclid

max_forks_repo_name: unclejimbo/euclid


text:
//#include <dirent.h>
//#include <iostream>
//#include <vector>
//#include <string>
//#include <utility>
//
//#include <Eigen/Core>
//#include <Eigen/LU>
//#include <Eigen/Geometry>
//
//#include <opencv2/opencv.hpp>
//const int G_land_num = 73;
//const int G_train_pic_id_num = 3300;
//const int G_nShape = 47;
//const int G_nVerts = 11510;
//const int G_nFaces = 11540;
//const int G_test_num = 77;
//const int G_iden_num = 77;
//const int G_inner_land_num = 58;
//
//
////#define normalization
//#define perspective
//
//struct Target_type {
//	Eigen::VectorXf exp;
//	Eigen::RowVector3f tslt;
//	Eigen::Matrix3f rot;
//	Eigen::MatrixX2f dis;
//
//};
//
//struct DataPoint
//{
//	cv::Mat image;
//	cv::Rect face_rect;
//	std::vector<cv::Point2d> landmarks;
//	//std::vector<cv::Point2d> init_shape;
//	Target_type shape, init_shape;
//	Eigen::VectorXf user;
//	Eigen::RowVector2f center;
//	Eigen::MatrixX2f land_2d;
//
//#ifdef perspective
//
//	float fcs;
//#endif // posit
//#ifdef normalization
//	Eigen::MatrixX3f s;
//#endif
//
//	Eigen::VectorXi land_cor;
//};
//void data_err_cnt_one(std::string name, Eigen::VectorXi &err_cnt) {
//	std::cout << "load coefficients...file:" << name << "\n";
//	FILE *fp;
//	fopen_s(&fp, name.c_str(), "rb");
//	DataPoint temp;
//	temp.user.resize(G_iden_num);
//	for (int j = 0; j < G_iden_num; j++)
//		fread(&temp.user(j), sizeof(float), 1, fp);
//
//	temp.land_2d.resize(G_land_num, 2);
//	for (int i_v = 0; i_v < G_land_num; i_v++) {
//		fread(&temp.land_2d(i_v, 0), sizeof(float), 1, fp);
//		fread(&temp.land_2d(i_v, 1), sizeof(float), 1, fp);
//	}
//
//
//	fread(&temp.center(0), sizeof(float), 1, fp);
//	fread(&temp.center(1), sizeof(float), 1, fp);
//
//	temp.shape.exp.resize(G_nShape);
//	for (int i_shape = 0; i_shape < G_nShape; i_shape++)
//		fread(&temp.shape.exp(i_shape), sizeof(float), 1, fp);
//
//	for (int i = 0; i < 3; i++) for (int j = 0; j < 3; j++)
//		fread(&temp.shape.rot(i, j), sizeof(float), 1, fp);
//
//	for (int i = 0; i < 3; i++) fread(&temp.shape.tslt(i), sizeof(float), 1, fp);
//
//	temp.land_cor.resize(G_land_num);
//	for (int i_v = 0; i_v < G_land_num; i_v++) fread(&temp.land_cor(i_v), sizeof(int), 1, fp);
//
//#ifdef normalization
//	temp.s.resize(2, 3);
//	for (int i = 0; i < 2; i++) for (int j = 0; j < 3; j++)
//		fread(&temp.s(i, j), sizeof(float), 1, fp);
//#endif // normalization
//
//#ifdef perspective
//	fread(&temp.fcs, sizeof(float), 1, fp);
//	std::cout << "f/tslt_z: " << temp.fcs / temp.shape.tslt(2) << " " << temp.shape.tslt(2) / temp.fcs << "\n";
//
//	//temp.fcs = temp.fcs / temp.shape.tslt(2) * 10;
//	//temp.shape.tslt(2) = 10;
//
//#endif // perspective
//
//	temp.shape.dis.resize(G_land_num, 2);
//	for (int i_v = 0; i_v < G_land_num; i_v++) {
//		fread(&temp.shape.dis(i_v, 0), sizeof(float), 1, fp);
//		fread(&temp.shape.dis(i_v, 1), sizeof(float), 1, fp);
//	}
//
//	fclose(fp);
//
//	puts("load successfully");
//
//
//	float err = sqrt(temp.shape.dis.squaredNorm() / G_land_num / 2);
//	//float err = temp.user.sum()*10;
//
//	printf("err %.5f\n", err);
//	if (err<50) err_cnt((int)(err))++;
//	else {
//		err_cnt(49)++;
//		std::cout << temp.shape.dis << "\n";
//		exit(9);
//	}
//
//}
//
////
//int cnt = 0;
//void data_err_cnt(std::string path, Eigen::VectorXi &err_cnt) {
//
//	struct dirent **namelist;
//	int n;
//	n = scandir(path.c_str(), &namelist, 0, alphasort);
//	if (n < 0)
//	{
//		std::cout << "scandir return " << n << "\n";
//		perror("Cannot open .");
//		exit(1);
//	}
//	else
//	{
//		int index = 0;
//		struct dirent *dp;
//		while (index < n)
//		{
//			dp = namelist[index];
//			std::cout << dp->d_name << ' ' << strlen(dp->d_name) << "\n";
//			if (dp->d_name[0] == '.') {
//				free(namelist[index]);
//				index++;
//				continue;
//			}
//			if (dp->d_type == DT_DIR) {
//				data_err_cnt(path + "/" + dp->d_name, err_cnt);
//			}
//			else {
//				int len = strlen(dp->d_name);
//				if (dp->d_name[len - 3] == 'p' && dp->d_name[len - 4] == 's' &&
//					dp->d_name[len - 1] == 'f' && dp->d_name[len - 2] == '_') {
//					////
//					std::string p = path + "/" + dp->d_name;
//					data_err_cnt_one(p, err_cnt);
//					std::cout << "cnt" << cnt << "\n";
//					cnt++;
//				}
//			}
//			free(namelist[index]);
//			index++;
//		}
//		free(namelist);
//	}
//
//}
//
//
//
//
//std::string fwhs_path = "./fw";
////std::string fwhs_path_p = "./data_me/fw_p1";
//std::string lfw_path = "./lfw_image";
//std::string gtav_path = "./GTAV_image";
//std::string test_path = "D:/sydney/first/data_me/test_lv";
//
//
//
//
//int main() {
//	Eigen::VectorXi err_cnt(50);
//	err_cnt.setZero();
//	data_err_cnt(fwhs_path, err_cnt);
//
//	//data_err_cnt(lfw_path,err_cnt);
//	//data_err_cnt(gtav_path,err_cnt);
//
//	std::cout << "cnt" << cnt << "\n";
//	std::cout << "err cnt" << err_cnt.transpose() << "\n";
//	return 0;
//}
////g++ -Wall -std=c++11 `pkg-config --cflags opencv` -o deal deal_falut.cpp `pkg-config --libs opencv`
//

max_stars_repo_name: sublimationAC/DDE

max_issues_repo_name: sublimationAC/DDE

max_forks_repo_name: sublimationAC/DDE


text:
/////////////////////////////////////////////////////////////////////////////////
// distribution::toolkit::distributions::chi_squared::os.hpp 				   //
//                                                                             //
//  (C) Copyright 2009 Erwann Rogard                                           //
//  Use, modification and distribution are 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)           //
/////////////////////////////////////////////////////////////////////////////////
#ifndef BOOST_STATISTICS_DETAIL_DISTRIBUTION_TOOLKIT_CHI_SQUARED_OS_HPP_ER_2009
#define BOOST_STATISTICS_DETAIL_DISTRIBUTION_TOOLKIT_CHI_SQUARED_OS_HPP_ER_2009
#include <boost/statistics/detail/distribution_toolkit/distributions/chi_squared/description.hpp>

namespace boost{
namespace math{

    template<typename T,typename P>
	std::ostream&
    operator<<(
    	std::ostream& os,
        const boost::math::chi_squared_distribution<T,P>& dist
    )
    {
        return (os << description(dist));
    }

}// math
}// boost

#endif


text:
// combination_iterator.hpp
//
// Produces all k-combinations of the universe {0,...,n-1} in
// lexicographical order. The algorithm is a tuned-up version
// of a simple generation method ("Algorithm T") described in:
//
//   Knuth, Donald E.
//   The Art of Computer Programming, Volume 4A: Combinatorial Algorithms,
//   Part 1. Pearson Education Inc., 2011.

#ifndef COMBINATION_ITERATOR_HPP
#define COMBINATION_ITERATOR_HPP

// This code was produced by Juho Lauri (euler314).

#include <cassert>
#include <cstdint>
#include <numeric>
#include <vector>

#include <boost/iterator/iterator_facade.hpp>

template <typename T>
class combination_iterator
    : public boost::iterator_facade<combination_iterator<T>, const std::vector<T>&, boost::forward_traversal_tag>
{
public:
    combination_iterator() : comb_() {}

    explicit combination_iterator(T n, T k)
        : end_(false), n_(n), k_(k), comb_(k)
    {
        assert(k != 0 && n_ > k);
        std::iota(comb_.begin(), comb_.end(), 0);
        assert(!end_);
    }

private:
    friend class boost::iterator_core_access;

    void increment()
    {
        std::int64_t j = k_ - 1;

        for (const T end = n_ - k_; j >= 0 && comb_[j] >= end + j; --j) {}

        if (j < 0)
        {
            assert(comb_.front() == n_ - k_);
            end_ = true;
            return;
        }

        ++comb_[j];

        for (const std::int64_t end = k_ - 1; j < end; ++j)
        {
            comb_[j + 1] = comb_[j] + 1;
        }
    }

    bool equal(const combination_iterator& other) const
    {
        return end_ == other.end_;
    }

    const std::vector<T>& dereference() const { return comb_; }

    bool end_{true};
    const int n_{0};
    const int k_{0};
    std::vector<T> comb_;
};

template <typename T>
class combination_iterator_minimax_order
    : public boost::iterator_facade<combination_iterator_minimax_order<T>,
                                    const std::vector<T>&,
                                    boost::forward_traversal_tag>
{
public:
    combination_iterator_minimax_order() : comb_() {}

    explicit combination_iterator_minimax_order(T n, T k)
        : end_(false), n_(n), k_(k), hint_(k), comb_(k)
    {
        assert(k != 0 && n_ > k);
        std::iota(comb_.begin(), comb_.end(), 0);
        assert(!end_);
    }

private:
    friend class boost::iterator_core_access;

    void increment()
    {
        // The following code was copied from the discreture library:
        // http://github.com/mraggi/discreture
        if (k_ == 0)
            return;

        if (hint_ > 0)
        {
            --hint_;
            ++comb_[hint_];
            return;
        }

        T i = 0;
        for (const T last = comb_.size() - 1;
             (i < last) && (comb_[i] + 1 == comb_[i + 1]);
             ++i)
        {
            comb_[i] = i;
        }

        ++comb_[i];

        if (comb_[i] == n_)
            end_ = true;
        else
            hint_ = i;
    }

    bool equal(const combination_iterator_minimax_order& other) const
    {
        return end_ == other.end_;
    }

    const std::vector<T>& dereference() const { return comb_; }

    bool end_{true};
    const int n_{0};
    const int k_{0};
    int hint_{};
    std::vector<T> comb_;
};

#endif


text:
//  Copyright (c) 2007-2014 Hartmut Kaiser
//
//  Distributed under the Boost Software License, Version 1.0. (See accompanying
//  file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)

#if !defined(HPX_TRAITS_SERIALIZE_AS_FUTURE_AUG_08_2014_0853PM)
#define HPX_TRAITS_SERIALIZE_AS_FUTURE_AUG_08_2014_0853PM

#include <hpx/traits.hpp>
#include <hpx/traits/is_future.hpp>
#include <hpx/traits/is_future_range.hpp>

#include <hpx/lcos/wait_all.hpp>

#include <boost/mpl/bool.hpp>
#include <boost/utility/enable_if.hpp>
#include <boost/fusion/include/for_each.hpp>
#include <boost/preprocessor/cat.hpp>
#include <boost/preprocessor/arithmetic/inc.hpp>
#include <boost/preprocessor/repetition/enum_params.hpp>
#include <boost/preprocessor/repetition/repeat.hpp>
#include <boost/preprocessor/repetition/repeat_from_to.hpp>

namespace hpx { namespace traits
{
    ///////////////////////////////////////////////////////////////////////////
    template <typename Future, typename Enable>
    struct serialize_as_future
      : boost::mpl::false_
    {
        static void call(Future& f) {}
    };

    template <typename T>
    struct serialize_as_future<T const>
      : serialize_as_future<T>
    {};

    template <typename T>
    struct serialize_as_future<T&>
      : serialize_as_future<T>
    {};

    template <typename T>
    struct serialize_as_future<T&&>
      : serialize_as_future<T>
    {};

    ///////////////////////////////////////////////////////////////////////////
    template <typename Future>
    struct serialize_as_future<Future
        , typename boost::enable_if<is_future<Future> >::type>
      : boost::mpl::true_
    {
        static void call(Future& f)
        {
            hpx::lcos::wait_all(f);
        }
    };

    template <typename Range>
    struct serialize_as_future<Range
        , typename boost::enable_if<is_future_range<Range> >::type>
      : boost::mpl::true_
    {
        static void call(Range& r)
        {
            hpx::lcos::wait_all(r);
        }
    };

    ///////////////////////////////////////////////////////////////////////////
    namespace detail
    {
        struct serialize_as_future_helper
        {
            template <typename T>
            void operator()(T& t) const
            {
                serialize_as_future<T>::call(t);
            }
        };
    }

    template <>
    struct serialize_as_future<util::tuple<> >
      : boost::mpl::false_
    {
        static void call(util::tuple<>& t) {}
    };

#define HPX_TRAITS_SERIALIZE_AS_FUTURE_TUPLE_ELEM(Z, N, D)                    \
     || serialize_as_future<BOOST_PP_CAT(T, N)>::value                        \
    /**/

#define HPX_TRAITS_SERIALIZE_AS_FUTURE_TUPLE(Z, N, D)                         \
    template <BOOST_PP_ENUM_PARAMS(N, typename T)>                            \
    struct serialize_as_future<util::tuple<BOOST_PP_ENUM_PARAMS(N, T)> >      \
      : boost::mpl::bool_<false                                               \
            BOOST_PP_REPEAT(N, HPX_TRAITS_SERIALIZE_AS_FUTURE_TUPLE_ELEM, _)  \
        >                                                                     \
    {                                                                         \
        static void call(util::tuple<BOOST_PP_ENUM_PARAMS(N, T)>& t)          \
        {                                                                     \
            boost::fusion::for_each(t, detail::serialize_as_future_helper()); \
        }                                                                     \
    };                                                                        \
    /**/

    BOOST_PP_REPEAT_FROM_TO(
        1, BOOST_PP_INC(HPX_TUPLE_LIMIT),
        HPX_TRAITS_SERIALIZE_AS_FUTURE_TUPLE, _
    )

#undef HPX_TRAITS_SERIALIZE_AS_FUTURE_TUPLE
#undef HPX_TRAITS_SERIALIZE_AS_FUTURE_TUPLE_ELEM
}}

#endif


text:
#pragma once
#include <eosio/chain/controller.hpp>
#include <boost/filesystem.hpp>

namespace cyberway { namespace genesis {

using namespace eosio::chain;
namespace bfs = boost::filesystem;

class genesis_import final {
public:
    genesis_import() = delete;
    genesis_import(const genesis_import&) = delete;

    genesis_import(const bfs::path& genesis_file, controller& ctrl);
    ~genesis_import();

    void import(block_state_ptr &block);

private:
    struct impl;
    std::unique_ptr<impl> _impl;
};

}} // cyberway::genesis

max_stars_repo_name: GolosChain/eos

max_issues_repo_name: GolosChain/eos

max_forks_repo_name: GolosChain/eos


text:
#pragma once

// Eigen
#include <Eigen/Core>
#include <Eigen/Dense>

// offset from center of laser rotation
#define AXIS_OFFSET 0.0 //-0.015

using namespace Eigen;

/**
 * get the 3D minimum distance between 2 lines
 * following http://geomalgorithms.com/a07-_distance.html#Distance-between-Lines
 * @param pos0 origin line0
 * @param dir1 direction line0
 * @param pos1 origin line1
 * @param dir2 direction line1
 * @param tri0 point on line0 closest to line1
 * @param tri1 point on line1 closest to line0
 * @return distance between the lines
 */
double dist3D_Line_to_Line( Vector3d &pos0, Vector3d &dir1,
                            Vector3d &pos1, Vector3d &dir2,
                            Vector3d &tri0, Vector3d &tri1);

/**
    * This function triangulates the position of a sensor using the horizontal and vertical angles from two ligthouses
    * @param angles0 vertical/horizontal angles form first lighthouse
    * @param angles1 vertical/horizontal angles form second lighthouse
    * @param RT_0 pose matrix of first lighthouse
    * @param RT_1 pose matrix of second lighthouses
    * @param triangulated_position the triangulated position
    * @param ray0 ligthhouse ray
    * @param ray1 ligthhouse ray
    */
double triangulateFromLighthouseAngles(Vector2d &angles0, Vector2d &angles1, Matrix4d &RT_0, Matrix4d &RT_1,
                                     Vector3d &triangulated_position, Vector3d &ray0, Vector3d &ray1);

double triangulateFromRays(Vector3d &ray0, Vector3d &ray1, Matrix4d &RT_0, Matrix4d &RT_1, Vector3d &triangulated_position);

void rayFromLighthouseAngles(Vector2d &angles, Vector3d &ray);


text:
/*
 * boost::property_tree tutorial
 *
 * zdd / zddhub@gmail.com
 * https://github.com/zddhub/boost_tutorial
 */

#include <iostream>
#include <vector>
using namespace std;

#include <boost/any.hpp>

class Customer {
public:
    Customer(const std::string& name) : _name(name) {}
    std::string toString() {
        return _name;
    }
private:
    std::string _name;
};

int main()
{
    cout << "boost::any: " << endl;

    //boost::any可以存放任意类型的对象
    typedef std::vector<boost::any> vector_any;
    vector_any va;

    va.push_back(100); //存放常数
    va.push_back(std::string("zddhub.com")); //存放string，注意vector_any.push_back("zddhub.com")会被当成字符数组
    va.push_back(new Customer("zdd"));//自定义类型
    va.push_back(Customer("zddhub"));

    //根据类型进行显示
    for(vector_any::iterator it = va.begin(); it != va.end(); ++it) {
        if(it->type() == typeid(int)) {
            cout << "int: " << boost::any_cast<int>(*it)<<endl;
        } else if(it->type() == typeid(std::string)) {
            cout << "string: " << boost::any_cast<std::string>(*it).c_str() <<endl;
        } else if(it->type() == typeid(Customer*)) {
            Customer *c = boost::any_cast<Customer*>(*it);
            cout << "Custormer* : " << c->toString().c_str()<<endl;
            delete c;
        } else if(it->type() == typeid(Customer)) {
            cout << "Custormer : " << boost::any_cast<Customer>(*it).toString().c_str()<<endl;
        }
    }

    return 0;
}


text:
/*
 * @name BookFiler Module - HTTP w/ Curl
 * @author Branden Lee
 * @version 1.00
 * @license MIT
 * @brief HTTP module for BookFiler™ applications.
 */

#ifndef BOOKFILER_MODULE_HTTP_HTTP_URL_H
#define BOOKFILER_MODULE_HTTP_HTTP_URL_H

// config
#include "config.hpp"

// C++17
//#include <filesystem>
#include <fstream>
#include <iomanip>
#include <iostream>
#include <memory>
#include <string>
#include <thread>
#include <map>
#include <utility>

/* rapidjson v1.1 (2016-8-25)
 * Developed by Tencent
 * License: MITs
 */
#include <rapidjson/document.h>
#include <rapidjson/filewritestream.h>
#include <rapidjson/ostreamwrapper.h>
#include <rapidjson/reader.h> // rapidjson::ParseResult
#include <rapidjson/stringbuffer.h>
#include <rapidjson/writer.h>

/* boost 1.72.0
 * License: Boost Software License (similar to BSD and MIT)
 */
#include <boost/algorithm/string.hpp>
#define BOOST_URL_HEADER_ONLY 1
#include <boost/url.hpp>

// Local Project
#include "UrlQuery.hpp"
#include <BookFiler-Module-HTTP/Interface.hpp>

/*
 * bookfiler - HTTP
 */
namespace bookfiler {
namespace HTTP {

class UrlImpl : public Url, public QueryImpl, public boost::url {
private:
  int setEncodedQueryBase(std::string);

public:
  UrlImpl();
  UrlImpl(std::map<std::string, newUrlVariantType>);
  ~UrlImpl();
  // Query Methods
  int setQuery(std::map<std::string, std::string>);
  int setQuery(std::shared_ptr<rapidjson::Document>);
  int setEncodedQuery(std::string);
  std::string getEncodedQuery();
  std::optional<std::string> getQuery(std::string);
  // Url Methods
  std::string_view url();
  std::string_view getEncodedHost();
  std::string target();
};

} // namespace HTTP
} // namespace bookfiler

#endif
// end BOOKFILER_MODULE_MYSQL_HTTP_H

max_stars_repo_name: bradosia/BookFiler-Module-HTTP-Curl

max_issues_repo_name: bradosia/BookFiler-Module-HTTP-Curl

max_forks_repo_name: bradosia/BookFiler-Module-HTTP-Curl


text:
///////////////////////////////////////////////////////////////
//  Copyright 2012 John Maddock. Distributed under the Boost
//  Software License, Version 1.0. (See accompanying file
//  LICENSE_1_0.txt or copy at https://www.boost.org/LICENSE_1_0.txt

#ifndef BOOST_MP_CPP_INT_CORE_HPP
#define BOOST_MP_CPP_INT_CORE_HPP

#include <boost/integer.hpp>
#include <boost/integer_traits.hpp>
#include <boost/mpl/if.hpp>
#include <boost/mpl/int.hpp>
#include <boost/static_assert.hpp>
#include <boost/assert.hpp>

namespace nil {
    namespace crypto3 {
        namespace multiprecision {

            namespace detail {

                //
                // These traits calculate the largest type in the list
                // [unsigned] boost::long_long_type, long, int, which has the specified number
                // of bits.  Note that intN_t and boost::int_t<N> find the first
                // member of the above list, not the last.  We want the last in the
                // list to ensure that mixed arithmetic operations are as efficient
                // as possible.
                //
                template<unsigned N>
                struct largest_signed_type {
                    typedef typename boost::mpl::if_c<
                        1 + std::numeric_limits<boost::long_long_type>::digits == N, boost::long_long_type,
                        typename boost::mpl::if_c<
                            1 + std::numeric_limits<long>::digits == N, long,
                            typename boost::mpl::if_c<1 + std::numeric_limits<int>::digits == N, int,
                                                      typename boost::int_t<N>::exact>::type>::type>::type type;
                };

                template<unsigned N>
                struct largest_unsigned_type {
                    typedef typename boost::mpl::if_c<
                        std::numeric_limits<boost::ulong_long_type>::digits == N, boost::ulong_long_type,
                        typename boost::mpl::if_c<
                            std::numeric_limits<unsigned long>::digits == N, unsigned long,
                            typename boost::mpl::if_c<std::numeric_limits<unsigned int>::digits == N, unsigned int,
                                                      typename boost::uint_t<N>::exact>::type>::type>::type type;
                };

            }    // namespace detail

#if defined(BOOST_HAS_INT128)

            typedef detail::largest_unsigned_type<64>::type limb_type;
            typedef detail::largest_signed_type<64>::type signed_limb_type;
            typedef boost::uint128_type double_limb_type;
            typedef boost::int128_type signed_double_limb_type;
            static const limb_type max_block_10 = 1000000000000000000uLL;
            static const limb_type digits_per_block_10 = 18;

            inline BOOST_MP_CXX14_CONSTEXPR limb_type block_multiplier(unsigned count) {
#ifdef BOOST_NO_CXX14_CONSTEXPR
                static
#else
                constexpr
#endif
                    const limb_type values[digits_per_block_10] = {10,
                                                                   100,
                                                                   1000,
                                                                   10000,
                                                                   100000,
                                                                   1000000,
                                                                   10000000,
                                                                   100000000,
                                                                   1000000000,
                                                                   10000000000,
                                                                   100000000000,
                                                                   1000000000000,
                                                                   10000000000000,
                                                                   100000000000000,
                                                                   1000000000000000,
                                                                   10000000000000000,
                                                                   100000000000000000,
                                                                   1000000000000000000};
                BOOST_ASSERT(count < digits_per_block_10);
                return values[count];
            }

// Can't do formatted IO on an __int128
#define BOOST_MP_NO_DOUBLE_LIMB_TYPE_IO

            // Need to specialise integer_traits for __int128 as it's not a normal native type:
        }    // namespace multiprecision
    }
}

namespace boost {
    template<>
    class integer_traits<nil::crypto3::multiprecision::double_limb_type>
        : public std::numeric_limits<nil::crypto3::multiprecision::double_limb_type>,
          public detail::integer_traits_base<nil::crypto3::multiprecision::double_limb_type, 0,
                                             ~static_cast<nil::crypto3::multiprecision::double_limb_type>(0)> { };
    template<>
    class integer_traits<nil::crypto3::multiprecision::signed_double_limb_type>
        : public std::numeric_limits<nil::crypto3::multiprecision::signed_double_limb_type>,
          public detail::integer_traits_base<
              nil::crypto3::multiprecision::signed_double_limb_type,
              static_cast<nil::crypto3::multiprecision::signed_double_limb_type>(
                  (static_cast<nil::crypto3::multiprecision::double_limb_type>(1) << 127)),
              static_cast<nil::crypto3::multiprecision::signed_double_limb_type>(
                  ((~static_cast<nil::crypto3::multiprecision::double_limb_type>(0)) >> 1))> { };
}    // namespace boost

namespace nil {
    namespace crypto3 {
        namespace multiprecision {

#else

            typedef detail::largest_unsigned_type<32>::type limb_type;
            typedef detail::largest_signed_type<32>::type signed_limb_type;
            typedef detail::largest_unsigned_type<64>::type double_limb_type;
            typedef detail::largest_signed_type<64>::type signed_double_limb_type;
            static const limb_type max_block_10 = 1000000000;
            static const limb_type digits_per_block_10 = 9;

            inline limb_type block_multiplier(unsigned count) {
#ifdef BOOST_NO_CXX14_CONSTEXPR
                static
#else
                constexpr
#endif
                    const limb_type values[digits_per_block_10] = {10,      100,      1000,      10000,     100000,
                                                                   1000000, 10000000, 100000000, 1000000000};
                BOOST_ASSERT(count < digits_per_block_10);
                return values[count];
            }

#endif

            static const unsigned bits_per_limb = sizeof(limb_type) * CHAR_BIT;

            template<class T>
            inline BOOST_MP_CXX14_CONSTEXPR void minmax(const T& a, const T& b, T& aa, T& bb) {
                if (a < b) {
                    aa = a;
                    bb = b;
                } else {
                    aa = b;
                    bb = a;
                }
            }

            enum cpp_integer_type {
                signed_magnitude = 1,
                unsigned_magnitude = 0,
                signed_packed = 3,
                unsigned_packed = 2
            };

            enum cpp_int_check_type { checked = 1, unchecked = 0 };

        }    // namespace multiprecision
    }        // namespace crypto3
}    // namespace nil

//
// Figure out whether to support user-defined-literals or not:
//
#if !defined(BOOST_NO_CXX11_VARIADIC_TEMPLATES) && !defined(BOOST_NO_CXX11_USER_DEFINED_LITERALS) && \
    !defined(BOOST_NO_CXX11_CONSTEXPR)
#define BOOST_MP_USER_DEFINED_LITERALS
#endif

#endif    // BOOST_MP_CPP_INT_CORE_HPP


text:
/**
 *    Copyright (C) 2013-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.
 */

/**
 * This file tests db/exec/fetch.cpp.  Fetch goes to disk so we cannot test outside of a dbtest.
 */

#include <boost/shared_ptr.hpp>

#include "mongo/client/dbclientcursor.h"
#include "mongo/db/catalog/collection.h"
#include "mongo/db/catalog/database.h"
#include "mongo/db/db_raii.h"
#include "mongo/db/dbdirectclient.h"
#include "mongo/db/exec/fetch.h"
#include "mongo/db/exec/plan_stage.h"
#include "mongo/db/exec/queued_data_stage.h"
#include "mongo/db/json.h"
#include "mongo/db/matcher/expression_parser.h"
#include "mongo/db/operation_context_impl.h"
#include "mongo/dbtests/dbtests.h"

namespace QueryStageFetch {

    using boost::shared_ptr;
    using std::auto_ptr;
    using std::set;

    class QueryStageFetchBase {
    public:
        QueryStageFetchBase() : _client(&_txn) {

        }

        virtual ~QueryStageFetchBase() {
            _client.dropCollection(ns());
        }

        void getLocs(set<RecordId>* out, Collection* coll) {
            RecordIterator* it = coll->getIterator(&_txn);
            while (!it->isEOF()) {
                RecordId nextLoc = it->getNext();
                out->insert(nextLoc);
            }
            delete it;
        }

        void insert(const BSONObj& obj) {
            _client.insert(ns(), obj);
        }

        void remove(const BSONObj& obj) {
            _client.remove(ns(), obj);
        }

        static const char* ns() { return "unittests.QueryStageFetch"; }

    protected:
        OperationContextImpl _txn;
        DBDirectClient _client;
    };

    //
    // Test that a WSM with an obj is passed through verbatim.
    //
    class FetchStageAlreadyFetched : public QueryStageFetchBase {
    public:
        void run() {
            OldClientWriteContext ctx(&_txn, ns());
            Database* db = ctx.db();
            Collection* coll = db->getCollection(ns());
            if (!coll) {
                WriteUnitOfWork wuow(&_txn);
                coll = db->createCollection(&_txn, ns());
                wuow.commit();
            }

            WorkingSet ws;

            // Add an object to the DB.
            insert(BSON("foo" << 5));
            set<RecordId> locs;
            getLocs(&locs, coll);
            ASSERT_EQUALS(size_t(1), locs.size());

            // Create a mock stage that returns the WSM.
            auto_ptr<QueuedDataStage> mockStage(new QueuedDataStage(&ws));

            // Mock data.
            {
                WorkingSetMember mockMember;
                mockMember.state = WorkingSetMember::LOC_AND_UNOWNED_OBJ;
                mockMember.loc = *locs.begin();
                mockMember.obj = coll->docFor(&_txn, mockMember.loc);
                // Points into our DB.
                mockStage->pushBack(mockMember);

                mockMember.state = WorkingSetMember::OWNED_OBJ;
                mockMember.loc = RecordId();
                mockMember.obj = Snapshotted<BSONObj>(SnapshotId(), BSON("foo" << 6));
                ASSERT_TRUE(mockMember.obj.value().isOwned());
                mockStage->pushBack(mockMember);
            }

            auto_ptr<FetchStage> fetchStage(new FetchStage(&_txn, &ws, mockStage.release(),
                                                           NULL, coll));

            WorkingSetID id = WorkingSet::INVALID_ID;
            PlanStage::StageState state;

            // Don't bother doing any fetching if an obj exists already.
            state = fetchStage->work(&id);
            ASSERT_EQUALS(PlanStage::ADVANCED, state);
            state = fetchStage->work(&id);
            ASSERT_EQUALS(PlanStage::ADVANCED, state);

            // No more data to fetch, so, EOF.
            state = fetchStage->work(&id);
            ASSERT_EQUALS(PlanStage::IS_EOF, state);
        }
    };

    //
    // Test matching with fetch.
    //
    class FetchStageFilter : public QueryStageFetchBase {
    public:
        void run() {
            ScopedTransaction transaction(&_txn, MODE_IX);
            Lock::DBLock lk(_txn.lockState(), nsToDatabaseSubstring(ns()), MODE_X);
            OldClientContext ctx(&_txn, ns());
            Database* db = ctx.db();
            Collection* coll = db->getCollection(ns());
            if (!coll) {
                WriteUnitOfWork wuow(&_txn);
                coll = db->createCollection(&_txn, ns());
                wuow.commit();
            }

            WorkingSet ws;

            // Add an object to the DB.
            insert(BSON("foo" << 5));
            set<RecordId> locs;
            getLocs(&locs, coll);
            ASSERT_EQUALS(size_t(1), locs.size());

            // Create a mock stage that returns the WSM.
            auto_ptr<QueuedDataStage> mockStage(new QueuedDataStage(&ws));

            // Mock data.
            {
                WorkingSetMember mockMember;
                mockMember.state = WorkingSetMember::LOC_AND_IDX;
                mockMember.loc = *locs.begin();

                // State is loc and index, shouldn't be able to get the foo data inside.
                BSONElement elt;
                ASSERT_FALSE(mockMember.getFieldDotted("foo", &elt));
                mockStage->pushBack(mockMember);
            }

            // Make the filter.
            BSONObj filterObj = BSON("foo" << 6);
            StatusWithMatchExpression swme = MatchExpressionParser::parse(filterObj);
            verify(swme.isOK());
            auto_ptr<MatchExpression> filterExpr(swme.getValue());

            // Matcher requires that foo==6 but we only have data with foo==5.
            auto_ptr<FetchStage> fetchStage(
                     new FetchStage(&_txn, &ws, mockStage.release(), filterExpr.get(), coll));

            // First call should return a fetch request as it's not in memory.
            WorkingSetID id = WorkingSet::INVALID_ID;
            PlanStage::StageState state;

            // Normally we'd return the object but we have a filter that prevents it.
            state = fetchStage->work(&id);
            ASSERT_EQUALS(PlanStage::NEED_TIME, state);

            // No more data to fetch, so, EOF.
            state = fetchStage->work(&id);
            ASSERT_EQUALS(PlanStage::IS_EOF, state);
        }
    };

    class All : public Suite {
    public:
        All() : Suite( "query_stage_fetch" ) { }

        void setupTests() {
            add<FetchStageAlreadyFetched>();
            add<FetchStageFilter>();
        }
    };

    SuiteInstance<All> queryStageFetchAll;

}  // namespace QueryStageFetch

max_stars_repo_name: leifwalsh/mongo

max_issues_repo_name: leifwalsh/mongo

max_forks_repo_name: leifwalsh/mongo


text:
#include "cliquesolver/algorithms/algorithms.hpp"

#include <boost/program_options.hpp>

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

Output cliquesolver::run(
        std::string algorithm,
        const Instance& instance,
        std::mt19937_64& generator,
        optimizationtools::Info info)
{
    (void)generator;

    std::vector<std::string> algorithm_args = po::split_unix(algorithm);
    std::vector<char*> algorithm_argv;
    for (Counter i = 0; i < (Counter)algorithm_args.size(); ++i)
        algorithm_argv.push_back(const_cast<char*>(algorithm_args[i].c_str()));

    if (algorithm.empty() || algorithm_args[0].empty()) {
        std::cerr << "\033[32m" << "ERROR, missing algorithm." << "\033[0m" << std::endl;
        return Output(instance, info);

    } else if (algorithm_args[0] == "greedy_gwmin") {
        return greedy_gwmin(instance, info);
    } else if (algorithm_args[0] == "greedy_strong") {
        return greedy_strong(instance, info);

#if CPLEX_FOUND
    } else if (algorithm_args[0] == "milp_cplex") {
        MilpCplexOptionalParameters parameters;
        parameters.info = info;
        return milp_cplex(instance, parameters);
#endif

    } else {
        std::cerr << "\033[31m" << "ERROR, unknown algorithm: " << algorithm_argv[0] << "\033[0m" << std::endl;
        assert(false);
        return Output(instance, info);
    }
}

max_stars_repo_name: fontanf/stablesolver

max_issues_repo_name: fontanf/stablesolver

max_forks_repo_name: fontanf/stablesolver


text:
#ifndef SIM_PLUS
#include "simFlavor.h"
#include "app.h"
#include "simConst.h"
#include "ttUtil.h"
#include "ser.h"
#include "simStringTable.h"
#include <boost/format.hpp>
#include <boost/algorithm/string/predicate.hpp>

int CSimFlavor::ver()
{
    return(-1);
}

bool CSimFlavor::init()
{
    return(true);
}

void CSimFlavor::getAboutStr(std::string& title,std::string& txt)
{
    title=IDS_ABOUT_SIM;
    txt="Custom CoppeliaSim";
}

int CSimFlavor::handleReadOpenFile(int f,char* b)
{
    if ( (f<=CSer::filetype_csim_bin_thumbnails_file)||(f==CSer::filetype_csim_bin_scene_buff)||(f==CSer::filetype_csim_bin_model_buff)||(f==CSer::filetype_csim_bin_ui_file) )
        return(1);
    return(-1);
}

void CSimFlavor::setHld(void* w)
{
}

void CSimFlavor::ekd()
{
}

void CSimFlavor::ifl(const char* s,int p)
{
}

bool CSimFlavor::hflm()
{
    return(false);
}

void CSimFlavor::run(int w)
{
}

int CSimFlavor::getIntVal(int w)
{
    if (w==0)
        return(0);
    if (w==1)
        return(CSer::filetype_csim_bin_scene_file);
    if (w==2)
        return(-1);
    return(-1);
}

int CSimFlavor::getIntVal_2int(int w,int v1,int v2)
{
    if (w==0)
        return(1);
    return(-1);
}

int CSimFlavor::getIntVal_str(int w,const char* n)
{
    if (w==0)
    {
        std::string ext(".");
        ext+=SIM_SCENE_EXTENSION;
        if (boost::algorithm::ends_with(n,ext.c_str()))
            return(CSer::filetype_csim_bin_scene_file);
        ext=".";
        ext+=SIM_MODEL_EXTENSION;
        if (boost::algorithm::ends_with(n,ext.c_str()))
            return(CSer::filetype_csim_bin_model_file);
        ext=".";
        ext+=SIM_XML_SCENE_EXTENSION;
        if (boost::algorithm::ends_with(n,ext.c_str()))
            return(CSer::filetype_csim_xml_simplescene_file);
        ext=".";
        ext+=SIM_XML_MODEL_EXTENSION;
        if (boost::algorithm::ends_with(n,ext.c_str()))
            return(CSer::filetype_csim_xml_simplemodel_file);
        return(CSer::filetype_unspecified_file);
    }
    if (w==1)
        return(0);
    if (w==2)
        return(0);
    return(-1);
}

bool CSimFlavor::getBoolVal(int w)
{
    if (w==0)
        return(false);
    if (w==1)
        return(false);
    if (w==2)
        return(true);
    if (w==3)
        return(true);
    if (w==4)
        return(true);
    if (w==5)
        return(true);
    if (w==6)
        return(true);
    if (w==7)
        return(true);
    if (w==8)
        return(false);
    if (w==9)
        return(true);
    if (w==10)
        return(true);
    if (w==11)
        return(true);
    if (w==12)
        return(true);
    if (w==13)
        return(false);
    if (w==14)
        return(true);
    if (w==15)
        return(false);
    if (w==16)
        return(true);
    if (w==17)
        return(false);
    return(false);
}

bool CSimFlavor::getBoolVal_int(int w,int v)
{
    if (w==0)
        return(false);
    return(false);
}

bool CSimFlavor::getBoolVal_str(int w,const char* str)
{
    if (w==0)
        return(boost::algorithm::ends_with(str,std::string(".")+SIM_MODEL_EXTENSION));
    return(false);
}

std::string CSimFlavor::getStringVal(int w)
{
    if (w==0)
        return("");
    if (w==1)
        return(":/imageFiles/splashBasic.png");
    if (w==2)
        return("CoppeliaSim (customized)");
    if (w==3)
    {
        std::string v(CSimFlavor::getStringVal(2));
        v+=boost::str(boost::format(" V%s %s") % SIM_PROGRAM_VERSION % SIM_PROGRAM_REVISION);
        return(v);
    }
    if (w==4)
        return(":/imageFiles/icon.png");
    if (w==5)
        return(IDS_HELP_TOPICS_MENU_ITEM);
    if (w==6)
        return(std::string(IDS_ABOUT_SIM)+"...");
    if (w==7)
        return(std::string(IDSN_CREDITS)+"...");
    if (w==8)
        return("");
    if (w==11)
        return("CoppeliaSim Crash");
    if (w==12)
    {
        #ifdef MAC_SIM
            return("It seems that CoppeliaSim crashed in last session. If CoppeliaSim didn't crash, you might be running several instances of CoppeliaSim in parallel, or you might have quit CoppeliaSim not correctly (<File --> Quit> is correct). Would you like to try to recover auto-saved scenes? (see also CoppeliaSim's installation folder for backuped scenes)");
        #else
            return("It seems that CoppeliaSim crashed in last session (or you might be running several instances of CoppeliaSim in parallel). Would you like to try to recover auto-saved scenes? (see also CoppeliaSim's installation folder for backuped scenes)");
        #endif
    }
    if (w==13)
        return("scenes");
    if (w==14)
        return("models");
    if (w==15)
        return("non-mobile");
    if (w==16)
        return("dfltscn.ttt");
    return("");
}

std::string CSimFlavor::getStringVal_int(int w,int v)
{
    if (w==0)
        return("");
    if (w==1)
    {
        if (v==0)
            return(SIM_SCENE_EXTENSION);
        if (v==1)
            return(SIM_XML_SCENE_EXTENSION);
        return("");
    }
    if (w==2)
    {
        if (v==0)
            return(SIM_MODEL_EXTENSION);
        if (v==1)
            return(SIM_XML_MODEL_EXTENSION);
        return("");
    }
    return("");
}
#endif

max_stars_repo_name: mdecourse/CoppeliaSimLib

max_issues_repo_name: mdecourse/CoppeliaSimLib

max_forks_repo_name: mdecourse/CoppeliaSimLib