text:
/*=============================================================================
    Copyright (c) 2001-2011 Joel de Guzman

    Distributed under the Boost Software License, Version 1.0. (See accompanying
    file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
=============================================================================*/
#if !defined(BOOST_SPIRIT_MINIC_EXPRESSION_HPP)
#define BOOST_SPIRIT_MINIC_EXPRESSION_HPP

///////////////////////////////////////////////////////////////////////////////
// Spirit v2.5 allows you to suppress automatic generation
// of predefined terminals to speed up complation. With
// BOOST_SPIRIT_NO_PREDEFINED_TERMINALS defined, you are
// responsible in creating instances of the terminals that
// you need (e.g. see qi::uint_type uint_ below).
#define BOOST_SPIRIT_NO_PREDEFINED_TERMINALS
///////////////////////////////////////////////////////////////////////////////

///////////////////////////////////////////////////////////////////////////////
// Uncomment this if you want to enable debugging
// #define BOOST_SPIRIT_QI_DEBUG
///////////////////////////////////////////////////////////////////////////////

#include <boost/spirit/include/qi.hpp>
#include "ast.hpp"
#include "error_handler.hpp"
#include "skipper.hpp"
#include <vector>

namespace client { namespace parser
{
    namespace qi = boost::spirit::qi;
    namespace ascii = boost::spirit::ascii;

    ///////////////////////////////////////////////////////////////////////////////
    //  The expression grammar
    ///////////////////////////////////////////////////////////////////////////////
    template <typename Iterator>
    struct expression : qi::grammar<Iterator, ast::expression(), skipper<Iterator> >
    {
        expression(error_handler<Iterator>& error_handler);

        qi::rule<Iterator, ast::expression(), skipper<Iterator> >
            expr, equality_expr, relational_expr,
            logical_or_expr, logical_and_expr,
            additive_expr, multiplicative_expr
            ;

        qi::rule<Iterator, ast::operand(), skipper<Iterator> >
            unary_expr, primary_expr
            ;

        qi::rule<Iterator, ast::function_call(), skipper<Iterator> >
            function_call
            ;

        qi::rule<Iterator, std::list<ast::expression>(), skipper<Iterator> >
            argument_list
            ;

        qi::rule<Iterator, std::string(), skipper<Iterator> >
            identifier
            ;

        qi::symbols<char, ast::optoken>
            logical_or_op, logical_and_op,
            equality_op, relational_op,
            additive_op, multiplicative_op, unary_op
            ;

        qi::symbols<char>
            keywords
            ;
    };
}}

#endif

max_stars_repo_name: randolphwong/mcsema

max_issues_repo_name: randolphwong/mcsema

max_forks_repo_name: randolphwong/mcsema


text:
//---------------------------------------------------------------------------//
//!
//! \file   tstScatteringCenterDefinitionDatabase.cpp
//! \author Alex Robinson
//! \brief  Scattering center definition database unit tests.
//!
//---------------------------------------------------------------------------//

// Std Lib Includes
#include <iostream>

// Boost Includes
#include <boost/filesystem.hpp>

// FRENSIE Includes
#include "MonteCarlo_ScatteringCenterDefinitionDatabase.hpp"
#include "Data_NativeEPRPhotoatomicDataProperties.hpp"
#include "Data_NativeEPRAdjointPhotoatomicDataProperties.hpp"
#include "Data_NativeEPRElectroatomicDataProperties.hpp"
#include "Data_NativeEPRAdjointElectroatomicDataProperties.hpp"
#include "Data_ACENuclearDataProperties.hpp"
#include "Data_ACEThermalNuclearDataProperties.hpp"
#include "Data_ACEPhotonuclearDataProperties.hpp"
#include "Utility_PhysicalConstants.hpp"
#include "Utility_UnitTestHarnessWithMain.hpp"
#include "ArchiveTestHelpers.hpp"

//---------------------------------------------------------------------------//
// Testing Types.
//---------------------------------------------------------------------------//

using Utility::Units::MeV;
using Utility::Units::amu;

typedef TestArchiveHelper::TestArchives TestArchives;

//---------------------------------------------------------------------------//
// Tests.
//---------------------------------------------------------------------------//
// Check that a scattering center definition can be created
FRENSIE_UNIT_TEST( ScatteringCenterDefinitionDatabase,
                   createDefinition )
{
  MonteCarlo::ScatteringCenterDefinitionDatabase database;

  database.createDefinition( 1000 );

  FRENSIE_CHECK( database.doesDefinitionExist( "H" ) );

  database.createDefinition( "H1 @ 293.1K", 1001 );

  FRENSIE_CHECK( database.doesDefinitionExist( "H1 @ 293.1K" ) );

  FRENSIE_CHECK_THROW( database.createDefinition( "H" ),
                       std::runtime_error );
  FRENSIE_CHECK_THROW( database.createDefinition( "H1 @ 293.1K" ),
                       std::runtime_error );
}

//---------------------------------------------------------------------------//
// Check that a scattering center definition alias can be created
FRENSIE_UNIT_TEST( ScatteringCenterDefinitionDatabase,
                   createDefinitionAlias )
{
  MonteCarlo::ScatteringCenterDefinitionDatabase database;

  FRENSIE_CHECK_THROW( database.createDefinitionAlias( "H1 @ 293.1K", "H1" ),
                       std::runtime_error );

  database.createDefinition( "H1 @ 293.1K", 1001 );
  database.createDefinitionAlias( "H1 @ 293.1K", "H1" );

  FRENSIE_CHECK( !database.isDefinitionNameAnAlias( "dummy" ) );
  FRENSIE_CHECK( !database.isDefinitionNameAnAlias( "H1 @ 293.1K" ) );
  FRENSIE_CHECK( database.isDefinitionNameAnAlias( "H1" ) );
}

//---------------------------------------------------------------------------//
// Check that a scattering center definition alias can be resolved
FRENSIE_UNIT_TEST( ScatteringCenterDefinitionDatabase,
                   resolveDefinitionAlias )
{
  MonteCarlo::ScatteringCenterDefinitionDatabase database;

  FRENSIE_CHECK_THROW( database.resolveDefinitionAlias( "H1" ),
                       std::runtime_error );

  database.createDefinition( "H1 @ 293.1K", 1001 );
  database.createDefinitionAlias( "H1 @ 293.1K", "H1" );

  FRENSIE_CHECK_EQUAL( database.resolveDefinitionAlias( "H1" ),
                       "H1 @ 293.1K" );
}

//---------------------------------------------------------------------------//
// Check that a scattering center definition can be returned
FRENSIE_UNIT_TEST( ScatteringCenterDefinitionDatabase, getDefinition )
{
  MonteCarlo::ScatteringCenterDefinitionDatabase database;

  FRENSIE_CHECK_THROW( database.getDefinition( "H1 @ 293.1K" ),
                       std::runtime_error );

  MonteCarlo::ScatteringCenterDefinition& definition =
    database.createDefinition( "H1 @ 293.1K", 1001 );

  FRENSIE_CHECK( &definition == &database.getDefinition( "H1 @ 293.1K" ) );

  database.createDefinitionAlias( "H1 @ 293.1K", "H1" );

  // Access the definition through an alias
  FRENSIE_CHECK( &definition == &database.getDefinition( "H1" ) );
}

//---------------------------------------------------------------------------//
// Check that a scattering center definition can be removed
FRENSIE_UNIT_TEST( ScatteringCenterDefinitionDatabase, removeDefinition )
{
  MonteCarlo::ScatteringCenterDefinitionDatabase database;

  FRENSIE_CHECK_NO_THROW( database.removeDefinition( "H1 @ 293.1K" ) );

  database.createDefinition( "H1 @ 293.1K", 1001 );
  database.createDefinitionAlias( "H1 @ 293.1K", "H1" );

  FRENSIE_CHECK( database.doesDefinitionExist( "H1 @ 293.1K" ) );
  FRENSIE_CHECK( database.doesDefinitionExist( "H1" ) );

  database.removeDefinition( "H1" );

  FRENSIE_CHECK( database.doesDefinitionExist( "H1 @ 293.1K" ) );
  FRENSIE_CHECK( !database.doesDefinitionExist( "H1" ) );

  database.removeDefinition( "H1 @ 293.1K" );

  FRENSIE_CHECK( !database.doesDefinitionExist( "H1 @ 293.1K" ) );
  FRENSIE_CHECK( !database.doesDefinitionExist( "H1" ) );
}

//---------------------------------------------------------------------------//
// Check that a database can be placed in a stream
FRENSIE_UNIT_TEST( ScatteringCenterDefinitionDatabase, toStream )
{
  MonteCarlo::ScatteringCenterDefinitionDatabase database;

  database.createDefinition( 1000 );
  database.createDefinition( "H1 @ 293.1K", 1001 );
  database.createDefinitionAlias( "H1 @ 293.1K", "H1" );

  FRENSIE_CHECK_NO_THROW( std::cout << "\n" << database << std::endl );
}

//---------------------------------------------------------------------------//
// Check that a database can be archived
FRENSIE_UNIT_TEST_TEMPLATE_EXPAND( ScatteringCenterDefinitionDatabase,
                                   archive,
                                   TestArchives )
{
  FETCH_TEMPLATE_PARAM( 0, RawOArchive );
  FETCH_TEMPLATE_PARAM( 1, RawIArchive );

  typedef typename std::remove_pointer<RawOArchive>::type OArchive;
  typedef typename std::remove_pointer<RawIArchive>::type IArchive;

  std::string archive_base_name( "test_scattering_center_definition_database" );
  std::ostringstream archive_ostream;

  {
    std::unique_ptr<OArchive> oarchive;

    createOArchive( archive_base_name, archive_ostream, oarchive );

    MonteCarlo::ScatteringCenterDefinitionDatabase database;

    database.createDefinition( 1000 );
    database.createDefinition( "H1 @ 293.1K", 1001 );

    MonteCarlo::ScatteringCenterDefinition& h_definition =
      database.getDefinition( "H" );

    MonteCarlo::ScatteringCenterDefinition& h1_definition =
      database.getDefinition( "H1 @ 293.1K" );

    {
      std::shared_ptr<const Data::PhotoatomicDataProperties> properties(
               new Data::NativeEPRPhotoatomicDataProperties(
                                             1.0*amu,
                                             boost::filesystem::current_path(),
                                             0,
                                             Data::H_ATOM ) );

      h_definition.setDataProperties( properties );
      h1_definition.setDataProperties( properties );
    }

    {
      std::shared_ptr<const Data::AdjointPhotoatomicDataProperties> properties(
               new Data::NativeEPRAdjointPhotoatomicDataProperties(
                                             1.0*amu,
                                             boost::filesystem::current_path(),
                                             0,
                                             Data::H_ATOM ) );

      h_definition.setDataProperties( properties );
      h1_definition.setDataProperties( properties );
    }

    {
      std::shared_ptr<const Data::ElectroatomicDataProperties> properties(
               new Data::NativeEPRElectroatomicDataProperties(
                                             1.0*amu,
                                             boost::filesystem::current_path(),
                                             0,
                                             Data::H_ATOM ) );

      h_definition.setDataProperties( properties );
      h1_definition.setDataProperties( properties );
    }

    {
      std::shared_ptr<const Data::AdjointElectroatomicDataProperties> properties(
               new Data::NativeEPRAdjointElectroatomicDataProperties(
                                             1.0*amu,
                                             boost::filesystem::current_path(),
                                             0,
                                             Data::H_ATOM ) );

      h_definition.setDataProperties( properties );
      h1_definition.setDataProperties( properties );
    }

    {
      std::shared_ptr<const Data::NuclearDataProperties> properties(
               new Data::ACENuclearDataProperties(
                                             1.0,
                                             2.52574e-8*MeV,
                                             boost::filesystem::current_path(),
                                             0,
                                             "1001.71c" ) );

      h1_definition.setDataProperties( properties );
    }

    {
      std::shared_ptr<const Data::ThermalNuclearDataProperties> properties(
               new Data::ACEThermalNuclearDataProperties(
                                             {1001, 1002, 8016},
                                             2.52574e-8*MeV,
                                             boost::filesystem::current_path(),
                                             0,
                                             "ltwtr.71t" ) );

      h1_definition.setDataProperties( properties );
    }

    {
      std::shared_ptr<const Data::PhotonuclearDataProperties> properties(
               new Data::ACEPhotonuclearDataProperties(
                                             1.0*amu,
                                             boost::filesystem::current_path(),
                                             0,
                                             "1001.10u" ) );

      h1_definition.setDataProperties( properties );
    }

    database.createDefinitionAlias( "H1 @ 293.1K", "H1" );

    FRENSIE_REQUIRE_NO_THROW( (*oarchive) << BOOST_SERIALIZATION_NVP( database ) );
  }

  // Copy the archive ostream to an istream
  std::istringstream archive_istream( archive_ostream.str() );

  // Load the archived distributions
  std::unique_ptr<IArchive> iarchive;

  createIArchive( archive_istream, iarchive );

  MonteCarlo::ScatteringCenterDefinitionDatabase database;

  FRENSIE_REQUIRE_NO_THROW( (*iarchive) >> BOOST_SERIALIZATION_NVP( database ) );

  iarchive.reset();

  FRENSIE_REQUIRE( database.doesDefinitionExist( "H" ) );

  MonteCarlo::ScatteringCenterDefinition& h_definition =
    database.getDefinition( "H" );

  FRENSIE_CHECK_EQUAL( h_definition.getName(), "H" );
  FRENSIE_CHECK_EQUAL( h_definition.getZAID(), Data::ZAID(1000) );
  FRENSIE_CHECK( h_definition.hasPhotoatomicDataProperties() );
  FRENSIE_CHECK( h_definition.hasAdjointPhotoatomicDataProperties() );
  FRENSIE_CHECK( h_definition.hasElectroatomicDataProperties() );
  FRENSIE_CHECK( h_definition.hasAdjointElectroatomicDataProperties() );
  FRENSIE_CHECK( !h_definition.hasNuclearDataProperties() );
  FRENSIE_CHECK( !h_definition.hasAdjointNuclearDataProperties() );
  FRENSIE_CHECK( !h_definition.hasThermalNuclearDataProperties() );
  FRENSIE_CHECK( !h_definition.hasAdjointThermalNuclearDataProperties() );
  FRENSIE_CHECK( !h_definition.hasPhotonuclearDataProperties() );
  FRENSIE_CHECK( !h_definition.hasAdjointPhotonuclearDataProperties() );

  FRENSIE_REQUIRE( database.doesDefinitionExist( "H1 @ 293.1K" ) );

  MonteCarlo::ScatteringCenterDefinition& h1_definition =
    database.getDefinition( "H1" );

  FRENSIE_CHECK_EQUAL( h1_definition.getName(), "H1 @ 293.1K" );
  FRENSIE_CHECK_EQUAL( h1_definition.getZAID(), Data::ZAID(1001) );
  FRENSIE_CHECK( h1_definition.hasPhotoatomicDataProperties() );
  FRENSIE_CHECK( h1_definition.hasAdjointPhotoatomicDataProperties() );
  FRENSIE_CHECK( h1_definition.hasElectroatomicDataProperties() );
  FRENSIE_CHECK( h1_definition.hasAdjointElectroatomicDataProperties() );
  FRENSIE_CHECK( h1_definition.hasNuclearDataProperties() );
  FRENSIE_CHECK( !h1_definition.hasAdjointNuclearDataProperties() );
  FRENSIE_CHECK( h1_definition.hasThermalNuclearDataProperties() );
  FRENSIE_CHECK( !h1_definition.hasAdjointThermalNuclearDataProperties() );
  FRENSIE_CHECK( h1_definition.hasPhotonuclearDataProperties() );
  FRENSIE_CHECK( !h1_definition.hasAdjointPhotonuclearDataProperties() );

  FRENSIE_REQUIRE( database.doesDefinitionExist( "H1" ) );
  FRENSIE_REQUIRE( database.isDefinitionNameAnAlias( "H1" ) );
  FRENSIE_CHECK_EQUAL( database.resolveDefinitionAlias( "H1" ),
                       "H1 @ 293.1K" );
}

//---------------------------------------------------------------------------//
// end tstScatteringCenterDefinitionDatabase.cpp
//---------------------------------------------------------------------------//

ext: cpp


text:
// Boost.Geometry

// Copyright (c) 2017-2019, Oracle and/or its affiliates.
// Contributed and/or modified by Adam Wulkiewicz, on behalf of Oracle

// 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)

#ifndef BOOST_GEOMETRY_TEST_SRS_PROJ4_HPP
#define BOOST_GEOMETRY_TEST_SRS_PROJ4_HPP

#include <string>

#include <boost/geometry/core/access.hpp>
#include <boost/geometry/core/radian_access.hpp>

#if defined(TEST_WITH_PROJ6)
#define TEST_WITH_PROJ5
#endif

#if defined(TEST_WITH_PROJ5)
#define TEST_WITH_PROJ4

#include <proj.h>

#endif

#if defined(TEST_WITH_PROJ4)
#define ACCEPT_USE_OF_DEPRECATED_PROJ_API_H

#include <proj_api.h>

struct pj_ptr
{
    explicit pj_ptr(projPJ ptr = NULL)
        : m_ptr(ptr)
    {}

#ifndef BOOST_NO_CXX11_RVALUE_REFERENCES
    pj_ptr(pj_ptr && other)
        : m_ptr(other.m_ptr)
    {
        other.m_ptr = NULL;
    }

    pj_ptr & operator=(pj_ptr && other)
    {
        if (m_ptr)
            pj_free(m_ptr);
        m_ptr = other.m_ptr;
        other.m_ptr = NULL;
        return *this;
    }
#endif

    projPJ get() const
    {
        return m_ptr;
    }

    ~pj_ptr()
    {
        if (m_ptr)
            pj_free(m_ptr);
    }

private:
    pj_ptr(pj_ptr const&);
    pj_ptr & operator=(pj_ptr const&);

    projPJ m_ptr;
};
/*
struct pj_projection
{
    pj_projection(std::string const& prj)
        : m_ptr(pj_init_plus(prj.c_str()))
    {}

    template <typename In, typename Out>
    void forward(In const& in, Out & out) const
    {
        double x = boost::geometry::get_as_radian<0>(in);
        double y = boost::geometry::get_as_radian<1>(in);

        projUV p1;
        projUV p2;

        p1.u = x;
        p1.v = y;

        p2 = pj_fwd(p1, m_ptr.get());

        boost::geometry::set_from_radian<0>(out, p2.u);
        boost::geometry::set_from_radian<1>(out, p2.v);
    }

    template <typename In, typename Out>
    void inverse(In const& in, Out & out) const
    {
        double lon = boost::geometry::get_as_radian<0>(in);
        double lat = boost::geometry::get_as_radian<1>(in);

        projUV p1;
        projUV p2;

        p1.u = lon;
        p1.v = lat;

        p2 = pj_inv(p1, m_ptr.get());

        boost::geometry::set_from_radian<0>(out, p2.u);
        boost::geometry::set_from_radian<1>(out, p2.v);
    }

private:
    pj_ptr m_ptr;
};*/

struct pj_transformation
{
    pj_transformation(std::string const& from, std::string const& to)
        : m_from(pj_init_plus(from.c_str()))
        , m_to(pj_init_plus(to.c_str()))
    {}

    void forward(std::vector<double> in_x,
                 std::vector<double> in_y,
                 std::vector<double> & out_x,
                 std::vector<double> & out_y) const
    {
        assert(in_x.size() == in_y.size());
        pj_transform(m_from.get(), m_to.get(), (long)in_x.size(), 1, &in_x[0], &in_y[0], NULL);
        out_x = std::move(in_x);
        out_y = std::move(in_y);
    }

    void forward(std::vector<double> in_xy,
                 std::vector<double> & out_xy) const
    {
        assert(in_xy.size() % 2 == 0);
        pj_transform(m_from.get(), m_to.get(), (long)in_xy.size() / 2, 2, &in_xy[0], &in_xy[1], NULL);
        out_xy = std::move(in_xy);
    }

    void forward(std::vector<std::vector<double> > const& in_xy,
                 std::vector<std::vector<double> > & out_xy) const
    {
        out_xy.resize(in_xy.size());
        for (size_t i = 0 ; i < in_xy.size(); ++i)
            forward(in_xy[i], out_xy[i]);
    }

    template <typename In, typename Out>
    void forward(In const& in, Out & out,
                 typename boost::enable_if_c
                    <
                        boost::is_same
                            <
                                typename boost::geometry::tag<In>::type,
                                boost::geometry::point_tag
                            >::value
                    >::type* dummy = 0) const
    {
        transform_point(in, out, m_from, m_to);
    }

    template <typename In, typename Out>
    void inverse(In const& in, Out & out,
                 typename boost::enable_if_c
                    <
                        boost::is_same
                            <
                                typename boost::geometry::tag<In>::type,
                                boost::geometry::point_tag
                            >::value
                    >::type* dummy = 0) const
    {
        transform_point(in, out, m_to, m_from);
    }

private:
    template <typename In, typename Out>
    static void transform_point(In const& in, Out & out,
                                pj_ptr const& from, pj_ptr const& to)
    {
        double x = boost::geometry::get_as_radian<0>(in);
        double y = boost::geometry::get_as_radian<1>(in);

        pj_transform(from.get(), to.get(), 1, 0, &x, &y, NULL);

        boost::geometry::set_from_radian<0>(out, x);
        boost::geometry::set_from_radian<1>(out, y);
    }

    pj_ptr m_from;
    pj_ptr m_to;
};

#endif // TEST_WITH_PROJ4

#if defined(TEST_WITH_PROJ5)

struct proj5_ptr
{
    explicit proj5_ptr(PJ *ptr = NULL)
        : m_ptr(ptr)
    {}

#ifndef BOOST_NO_CXX11_RVALUE_REFERENCES
    proj5_ptr(proj5_ptr && other)
        : m_ptr(other.m_ptr)
    {
        other.m_ptr = NULL;
    }

    proj5_ptr & operator=(proj5_ptr && other)
    {
        if (m_ptr)
            proj_destroy(m_ptr);
        m_ptr = other.m_ptr;
        other.m_ptr = NULL;
        return *this;
    }
#endif

    PJ *get() const
    {
        return m_ptr;
    }

    ~proj5_ptr()
    {
        if (m_ptr)
            proj_destroy(m_ptr);
    }

private:
    proj5_ptr(proj5_ptr const&);
    proj5_ptr & operator=(proj5_ptr const&);

    PJ *m_ptr;
};

struct proj5_transformation
{
    proj5_transformation(std::string const& to)
        : m_proj(proj_create(PJ_DEFAULT_CTX, to.c_str()))
    {}

    void forward(std::vector<PJ_COORD> in,
                 std::vector<PJ_COORD> & out) const
    {
        proj_trans_array(m_proj.get(), PJ_FWD, in.size(), &in[0]);
        out = std::move(in);
    }

    template <typename In, typename Out>
    void forward(In const& in, Out & out,
                 typename boost::enable_if_c
                    <
                        boost::is_same
                            <
                                typename boost::geometry::tag<In>::type,
                                boost::geometry::point_tag
                            >::value
                    >::type* dummy = 0) const
    {
        PJ_COORD c;
        c.lp.lam = boost::geometry::get_as_radian<0>(in);
        c.lp.phi = boost::geometry::get_as_radian<1>(in);

        c = proj_trans(m_proj.get(), PJ_FWD, c);

        boost::geometry::set_from_radian<0>(out, c.xy.x);
        boost::geometry::set_from_radian<1>(out, c.xy.y);
    }

private:
    proj5_ptr m_proj;
};

#endif // TEST_WITH_PROJ5

#if defined(TEST_WITH_PROJ6)

struct proj6_transformation
{
    proj6_transformation(std::string const& from, std::string const& to)
        : m_proj(proj_create_crs_to_crs(PJ_DEFAULT_CTX, from.c_str(), to.c_str(), NULL))
    {
        //proj_normalize_for_visualization(0, m_proj.get());
    }

    void forward(std::vector<PJ_COORD> in,
                 std::vector<PJ_COORD> & out) const
    {
        proj_trans_array(m_proj.get(), PJ_FWD, in.size(), &in[0]);
        out = std::move(in);
    }

    template <typename In, typename Out>
    void forward(In const& in, Out & out,
                 typename boost::enable_if_c
                    <
                        boost::is_same
                            <
                                typename boost::geometry::tag<In>::type,
                                boost::geometry::point_tag
                            >::value
                    >::type* dummy = 0) const
    {
        PJ_COORD c;
        c.lp.lam = boost::geometry::get_as_radian<0>(in);
        c.lp.phi = boost::geometry::get_as_radian<1>(in);

        c = proj_trans(m_proj.get(), PJ_FWD, c);

        boost::geometry::set_from_radian<0>(out, c.xy.x);
        boost::geometry::set_from_radian<1>(out, c.xy.y);
    }

private:
    proj5_ptr m_proj;
};

#endif // TEST_WITH_PROJ6

#endif // BOOST_GEOMETRY_TEST_SRS_PROJ4_HPP

ext: hpp

max_stars_repo_name: jkerkela/geometry

max_issues_repo_name: jkerkela/geometry

max_forks_repo_name: jkerkela/geometry


text:
// Copyright GREYC - UMR 6072 ; Université de Caen Normandie
// Esplanade de la paix
// CS 14032
// 14032 Caen CEDEX 5
// contributeur :
// Jean Creusefond, 2015
//
// jean.creusefond@unicaen.fr
//
// Ce logiciel est un programme informatique servant à la comparaison et à l'analyse d'outils de détection de communauté.
//
// Ce logiciel est régi par la licence CeCILL-B soumise au droit français et respectant les principes de diffusion des logiciels libres. Vous pouvez utiliser, modifier et/ou redistribuer ce programme sous les conditions de la licence CeCILL-B telle que diffusée par le CEA, le CNRS et l'INRIA sur le site "http://www.cecill.info".
//
// En contrepartie de l'accessibilité au code source et des droits de copie, de modification et de redistribution accordés par cette licence, il n'est offert aux utilisateurs qu'une garantie limitée.  Pour les mêmes raisons, seule une responsabilité restreinte pèse sur l'auteur du programme, le titulaire des droits patrimoniaux et les concédants successifs.
//
// A cet égard  l'attention de l'utilisateur est attirée sur les risques
// associés au chargement,  à l'utilisation,  à la modification et/ou au
// développement et à la reproduction du logiciel par l'utilisateur étant
// donné sa spécificité de logiciel libre, qui peut le rendre complexe à
// manipuler et qui le réserve donc à des développeurs et des professionnels avertis possédant  des  connaissances  informatiques approfondies.  Les utilisateurs sont donc invités à charger  et  tester  l'adéquation  du logiciel à leurs besoins dans des conditions permettant d'assurer la sécurité de leurs systèmes et ou de leurs données et, plus généralement, à l'utiliser et l'exploiter dans les mêmes conditions de sécurité.
//
// Le fait que vous puissiez accéder à cet en-tête signifie que vous avez
// pris connaissance de la licence CeCILL-B, et que vous en avez accepté les termes.
//
// ==========================================================================
//
// Copyright GREYC - UMR 6072 ; Université de Caen Normandie
// Esplanade de la paix
// CS 14032
// 14032 Caen CEDEX 5
// contributor(s) :
// Jean Creusefond, 2015
//
// jean.creusefond@unicaen.fr
//
// This software is a computer program whose purpose is to compare and analyse community detection tools.
//
// This software is governed by the CeCILL-B license under French law and
// abiding by the rules of distribution of free software.  You can  use,
// modify and/ or redistribute the software under the terms of the CeCILL-B
// license as circulated by CEA, CNRS and INRIA at the following URL
// "http://www.cecill.info".
//
// As a counterpart to the access to the source code and  rights to copy,
// modify and redistribute granted by the license, users are provided only
// with a limited warranty  and the software's author,  the holder of the
// economic rights,  and the successive licensors  have only  limited
// liability.
//
// In this respect, the user's attention is drawn to the risks associated
// with loading,  using,  modifying and/or developing or reproducing the
// software by the user in light of its specific status of free software,
// that may mean  that it is complicated to manipulate,  and  that  also
// therefore means  that it is reserved for developers  and  experienced
// professionals having in-depth computer knowledge. Users are therefore
// encouraged to load and test the software's suitability as regards their
// requirements in conditions enabling the security of their systems and/or
// data to be ensured and,  more generally, to use and operate it in the
// same conditions as regards security.
//
// The fact that you are presently reading this means that you have had
// knowledge of the CeCILL-B license and that you accept its terms.
//#include <boost/lambda/lambda.hpp>
#include <iostream>
// #include <iterator>
// #include <algorithm>
#include<fstream>
//#include <boost/graph/graphml.hpp>
//#include <boost/graph/graphviz.hpp>
#include <boost/config.hpp>
#include <boost/version.hpp>
#include <boost/graph/graph_utility.hpp>
#include <boost/property_map/property_map.hpp>
#include <boost/static_assert.hpp>
#include <boost/graph/property_maps/null_property_map.hpp>
#include <boost/graph/random.hpp>
#include <boost/random/linear_congruential.hpp>
#include <boost/date_time/posix_time/posix_time.hpp>
//#include <boost/graph/dijkstra_shortest_paths.hpp>
//#include <boost/graph/betweenness_centrality.hpp>

using namespace boost;

#include "search/Graph.hpp"
#include "search/LexDFS.hpp"
#include "search/CommunityDetection.hpp"
#include "search/Parameters.hpp"
#include "search/CommonIntervalDetection.hpp"
#include "search/EdgeWeightDetection.hpp"

void mark_connected_components(Graph& g, long edge_iteration_threshold) {
  std::list<vertex_t> vertices;
  std::map<vertex_t, std::list<vertex_t>::iterator> v_to_p;
  std::pair<vertex_iter, vertex_iter> vp;
  for (vp = boost::vertices(g); vp.first != vp.second; ++vp.first) {
    vertex_t v = *vp.first;
    vertices.push_back(v);
    v_to_p[v] = --vertices.end();
    g[v].tmp1 = -1;
  }

  long i = 0;
  while(!vertices.empty()) {
    std::deque<vertex_t> q;
    q.push_back(vertices.back());
    vertices.pop_back();

    while(!q.empty()) {
      vertex_t v = q.back();
      q.pop_back();
      g[v].tmp1 = i;

      typedef boost::graph_traits<Graph>::adjacency_iterator adjacency_iterator;
      std::pair<adjacency_iterator, adjacency_iterator> it;
      it = boost::adjacent_vertices(v, g);
      for( ; it.first != it.second; ++it.first) {
	vertex_t u = *it.first;
	edge_t e = boost::edge(u,v,g).first;
	if(g[u].tmp1 < 0 && g[e].iteration <= edge_iteration_threshold) {
	  q.push_back(u);
	  g[u].tmp1 = i;
	  vertices.erase(v_to_p[u]);
	}
      }
    }
    i++;
  }
}

long triangles = 0;
double clust(vertex_t v, Graph& g) {
  std::vector<vertex_t> neis;
  typedef boost::graph_traits<Graph>::adjacency_iterator adjacency_iterator;
  std::pair<adjacency_iterator, adjacency_iterator> it = boost::adjacent_vertices(v, g);
  for( ; it.first != it.second; ++it.first) {
    vertex_t neigh = *(it.first);
    neis.push_back(neigh);
  }
  long tr = 0;
  for (long i = 0; i < neis.size(); i++) {
    for(long j = i+1; j < neis.size(); j++) {
      if(boost::edge(neis[i], neis[j], g).second) {
	tr++;
      }
    }
  }
  triangles += tr;
  if(neis.size() > 1)
    return ((double)(tr*2))/(neis.size()*(neis.size() - 1));
  else
    return 0.0;
}

/*
  Command-line arguments (must be written in this order):
  -model (c: cascade, t:threshold)
  -options (options specific to the model, namely the probability of the cascade and the threshold)
  -start (r: random, integer_id:the id of the starting node)
 */
int main(int argc, char* argv[])
{
  Parameters::analyse_args(argc, argv);

  /*
    Read file
   */
  std::ifstream infile;
  infile.open(Parameters::getInputGraphFile(), std::ifstream::in);
  Graph g;
  //Reads edgelist file
  read_edgelist(infile, g);
  infile.close();

  g[boost::graph_bundle].m = num_edges(g);
  g[boost::graph_bundle].n = num_vertices(g);
  //std::cout << "n : " << g[boost::graph_bundle].n << " m : " << g[boost::graph_bundle].m << std::endl;

  /*
    Apply processing
   */
  //Finds a random node
  boost::minstd_rand gen(posix_time::microsec_clock::local_time().time_of_day().total_milliseconds());
  lexdfs(g, boost::random_vertex(g, gen), true);

  if(Parameters::getAnalyser() == EdgeWeight)
    compute_edge_order_difference(g, 1);

  for(int i=1; i<=Parameters::getNbIters(); i++) {
    lexdfs(g, boost::random_vertex(g, gen), Parameters::getMethod() == LexDFS);
    if(Parameters::getAnalyser() == EdgeWeight) {
      compute_edge_order_difference(g, i+1);
    }
  }

  long imax = 0;
  if(Parameters::getAnalyser() == CommonIntervals)
    common_intervals_clustering(g);
  if(Parameters::getAnalyser() == EdgeWeight)
    imax = lexdfs_clustering(g, true, Parameters::getQfToMax());

  mark_connected_components(g, imax);

  //Should we output the membership?
  double sum_clust = 0;
  if(false) {
    std::pair<vertex_iter, vertex_iter> vp;
    for (vp = vertices(g); vp.first != vp.second; ++vp.first) {
      std::cout << *vp.first << " " << g[*vp.first].tmp1 << std::endl;
    }
  }

  //Prints lexDFS score and betweenness centrality for every edge
  // std::map<vertex_t, float> tmp1;
  // boost::associative_property_map<std::map<vertex_t, float> > v_betw_map(tmp1);
  // std::map<edge_t, float> tmp2;
  // boost::associative_property_map<std::map<edge_t, float> > e_betw_map(tmp2);
  // brandes_betweenness_centrality(g, v_betw_map, e_betw_map);

  // typedef boost::graph_traits<Graph>::edge_iterator edge_iter;
  // std::pair<edge_iter, edge_iter> iter;
  // for (iter = edges(g); iter.first != iter.second; ++iter.first)
  //   std::cout << g[*(iter.first)].lexDFS_score << " " << get(e_betw_map, *(iter.first)) << std::endl;

  // typedef boost::graph_traits<Graph>::vertex_iterator vertex_iter;
  // std::pair<vertex_iter, vertex_iter> vp;
  // for (vp = vertices(g); vp.first != vp.second; ++vp.first) {
  //   std::cout << g[*vp.first].visited << std::endl;
  // }

  /*
    Write file
   */
  // std::ofstream outfile;
  // outfile.open(Parameters::getOutputGraphFile());

  // write_graphml(outfile, g, dp, true);
  // outfile.close();

  return EXIT_SUCCESS;
}

max_stars_repo_name: ix-labs/codacom

max_issues_repo_name: ix-labs/codacom

max_forks_repo_name: ix-labs/codacom


text:
#define BOOST_TEST_MODULE client file test
#include <boost/test/included/unit_test.hpp>

BOOST_AUTO_TEST_SUITE(ClientFileTest);

BOOST_AUTO_TEST_CASE(testGetPeFileInfo) {
  BOOST_TEST(true /* test assertion */);
}

BOOST_AUTO_TEST_SUITE_END();

max_stars_repo_name: ATsahikian/PeProtector

max_issues_repo_name: ATsahikian/pe-protector

max_forks_repo_name: ATsahikian/pe-protector


text:
//==================================================================================================
/**
  Copyright 2016 Numscale SAS

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

#include <boost/simd/detail/overload.hpp>
#include <boost/simd/function/bitwise_cast.hpp>
#include <boost/simd/function/genmask.hpp>

namespace boost { namespace simd { namespace ext
{
   namespace bd = boost::dispatch;
   namespace bs = boost::simd;

   BOOST_DISPATCH_OVERLOAD( if_else_
                          , (typename A0, typename A1)
                          , bs::avx2_
                          , bs::pack_<bs::logical_<A0>, bs::avx_>
                          , bs::pack_<bd::integer_<A1>, bs::avx_>
                          , bs::pack_<bd::integer_<A1>, bs::avx_>
                          )
   {
      A1 operator()(A0 const& a0,A1 const& a1,A1 const& a2) const
      {
        return _mm256_blendv_epi8(a2, a1, bitwise_cast<A1>(genmask(a0)));
      }
   };

   BOOST_DISPATCH_OVERLOAD( if_else_
                          , (typename A0, typename A1)
                          , bs::avx2_
                          , bs::pack_<bs::logical_<A0>, bs::avx_>
                          , bs::pack_<bd::ints32_<A1>, bs::avx_>
                          , bs::pack_<bd::ints32_<A1>, bs::avx_>
                          )
   {
      A1 operator()(A0 const& a0,A1 const& a1,A1 const& a2) const
      {
        return _mm256_blendv_epi8(a2, a1, bitwise_cast<A1>(genmask(a0)));
      }
   };

   BOOST_DISPATCH_OVERLOAD( if_else_
                          , (typename A0, typename A1)
                          , bs::avx2_
                          , bs::pack_<bs::logical_<A0>, bs::avx_>
                          , bs::pack_<bd::ints64_<A1>, bs::avx_>
                          , bs::pack_<bd::ints64_<A1>, bs::avx_>
                          )
   {
      A1 operator()(A0 const& a0,A1 const& a1,A1 const& a2) const
      {
        return _mm256_blendv_epi8(a2, a1, bitwise_cast<A1>(genmask(a0)));
      }
   };
} } }

#endif

max_stars_repo_name: xmar/pythran

max_issues_repo_name: xmar/pythran

max_forks_repo_name: xmar/pythran


text:
#include "stdafx.h"
#include "NaiveGumballMachine.h"
#include <boost/format.hpp>

namespace
{
const unsigned MAX_COINS_COUNT = 5;
}

using namespace naive;

GumballMachine::GumballMachine(std::ostream& output, unsigned gumballs /* = 0 */)
	: m_gumballs(gumballs)
	, m_state(gumballs > 0 ? State::NoCoin : State::SoldOut)
	, m_coins(0)
	, m_output(output)
{
}

void GumballMachine::InsertCoin()
{
	switch (m_state)
	{
	case State::SoldOut:
		m_output << "You can't insert a coin, the machine is sold out\n";
		break;
	case State::NoCoin:
		assert(m_coins == 0);
		++m_coins;
		m_output << "You inserted a coin\n";
		m_state = State::HasCoin;
		break;
	case State::HasCoin:
		if (m_coins < MAX_COINS_COUNT)
		{
			++m_coins;
			m_output << "You inserted a coin\n";
		}
		else
		{
			m_output << "You can't insert more than " << MAX_COINS_COUNT << " coins\n";
		}
		break;
	case State::Sold:
		m_output << "Please wait, we're already giving you a gumball\n";
		break;
	}
}

void GumballMachine::EjectCoin()
{
	switch (m_state)
	{
	case State::SoldOut:
		if (m_coins == 0)
		{
			m_output << "You can't eject, you haven't inserted a coin yet\n";
		}
		else
		{
			while (m_coins != 0)
			{
				--m_coins;
			}
			m_output << "All coins returned\n";
		}
		break;
	case State::NoCoin:
		m_output << "You haven't inserted a coin\n";
		break;
	case State::HasCoin:
		while (m_coins != 0)
		{
			--m_coins;
		}
		m_output << "All coins returned\n";
		m_state = State::NoCoin;
		break;
	case State::Sold:
		m_output << "Sorry you already turned the crank\n";
		break;
	}
}

void GumballMachine::TurnCrank()
{
	switch (m_state)
	{
	case State::SoldOut:
		m_output << "You turned but there's no gumballs\n";
		break;
	case State::NoCoin:
		m_output << "You turned but there's no coin\n";
		break;
	case State::HasCoin:
		assert(m_coins != 0);
		if (m_gumballs != 0)
		{
			m_output << "You turned...\n";
			--m_coins;
			m_state = State::Sold;
		}
		break;
	case State::Sold:
		m_output << "Turning twice doesn't give you another gumball\n";
		break;
	}
	Dispense();
}

void GumballMachine::Refill(unsigned count)
{
	switch (m_state)
	{
	case GumballMachine::State::NoCoin:
		m_gumballs = count;
		if (count == 0)
		{
			m_state = State::SoldOut;
		}
		break;
	case GumballMachine::State::HasCoin:
		m_gumballs = count;
		if (count == 0)
		{
			m_state = State::SoldOut;
		}
		break;
	case GumballMachine::State::Sold:
		m_output << "Can't refill gumballs in sold state\n";
		break;
	case GumballMachine::State::SoldOut:
		m_gumballs = count;
		if (count != 0)
		{
			if (m_coins == 0)
			{
				m_state = State::NoCoin;
			}
			else
			{
				m_state = State::HasCoin;
			}
		}
		break;
	}
}

std::string GumballMachine::ToString() const
{
	std::string state =
		(m_state == State::SoldOut) ? "sold out" :
		(m_state == State::NoCoin) ? "waiting for coin" :
		(m_state == State::HasCoin) ? "waiting for turn of crank"
		: "delivering a gumball";

	auto fmt = boost::format(R"(Mighty Gumball, Inc.
C++-enabled Standing Gumball Model #2016
Inventory: %1% gumball%2%, %3% coin%4%
Machine is %5%)");

	return (fmt % m_gumballs % (m_gumballs != 1 ? "s" : "")
		% m_coins % (m_coins != 1 ? "s" : "") % state).str();
}

void GumballMachine::Dispense()
{
	switch (m_state)
	{
	case State::SoldOut:
		m_output << "No gumball dispensed\n";
		break;
	case State::NoCoin:
		m_output << "You need to pay first\n";
		break;
	case State::HasCoin:
		m_output << "No gumball dispensed\n";
		break;
	case State::Sold:
		assert(m_gumballs != 0);
		--m_gumballs;
		m_output << "A gumball comes rolling out the slot...\n";

		if (m_gumballs == 0)
		{
			m_output << "Oops, out of gumballs\n";
			m_state = State::SoldOut;
		}
		else if (m_coins == 0)
		{
			m_state = State::NoCoin;
		}
		else
		{
			m_state = State::HasCoin;
		}
		break;
	}
}


text:
// Copyright 2018 The Beam Team
//
// 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 "stratum_server.h"
#include "utility/helpers.h"
#include "utility/io/sslserver.h"
#include <boost/filesystem.hpp>
#include <boost/algorithm/string/trim.hpp>
#include <fstream>

#define LOG_VERBOSE_ENABLED 1
#include "utility/logger.h"

#include <assert.h>

namespace beam {

std::unique_ptr<IExternalPOW> IExternalPOW::create(
    const IExternalPOW::Options& o, io::Reactor& reactor, io::Address listenTo, unsigned noncePrefixDigits
) {
    return std::make_unique<stratum::Server>(o, reactor, listenTo, noncePrefixDigits);
}

namespace stratum {

static const uint64_t SERVER_RESTART_TIMER = 1;
static const uint64_t ACL_REFRESH_TIMER = 2;
static const unsigned SERVER_RESTART_INTERVAL = 1000;
static const unsigned ACL_REFRESH_INTERVAL = 5000;

static const char STS[] = "stratum server ";

Server::Server(const IExternalPOW::Options& o, io::Reactor& reactor, io::Address listenTo, unsigned noncePrefixDigits) :
    _options(o),
    _reactor(reactor),
    _bindAddress(listenTo),
    _timers(reactor, 100),
    _fw(4096, 0, [this](io::SharedBuffer&& buf){ _currentMsg.push_back(buf); }),
    _acl(o.apiKeysFile),
    _prefixDigits(noncePrefixDigits),
    _prefixSeed(0)
{
    assert(_prefixDigits <= 6);
    _timers.set_timer(SERVER_RESTART_TIMER, 0, BIND_THIS_MEMFN(start_server));
    if (!o.apiKeysFile.empty()) {
        _timers.set_timer(ACL_REFRESH_TIMER, 0, BIND_THIS_MEMFN(refresh_acl));
    }
    if (_prefixDigits > 0) {
        ECC::GenRandom(&_prefixSeed, 8);
    }
}

void Server::start_server() {
    try {
        if (_options.privKeyFile.empty() || _options.certFile.empty()) {
            LOG_WARNING() << STS << "TLS disabled!";
            _server = io::TcpServer::create(
                _reactor,
                _bindAddress,
                BIND_THIS_MEMFN(on_stream_accepted)
            );
        } else {
            _server = io::SslServer::create(
                _reactor,
                _bindAddress,
                BIND_THIS_MEMFN(on_stream_accepted),
                _options.certFile.c_str(),
                _options.privKeyFile.c_str()
            );
        }
        LOG_INFO() << STS << "listens to " << _bindAddress;
    } catch (const std::exception& e) {
        LOG_ERROR() << STS << "cannot start server: " << e.what() << " restarting in  " << SERVER_RESTART_INTERVAL << " msec";
        _timers.set_timer(SERVER_RESTART_TIMER, SERVER_RESTART_INTERVAL, BIND_THIS_MEMFN(start_server));
    }
}

void Server::refresh_acl() {
    _acl.refresh();
    _timers.set_timer(ACL_REFRESH_TIMER, ACL_REFRESH_INTERVAL, BIND_THIS_MEMFN(refresh_acl));
}

void Server::on_stream_accepted(io::TcpStream::Ptr&& newStream, io::ErrorCode errorCode) {
    if (errorCode == 0) {
        auto peer = newStream->peer_address();
        LOG_DEBUG() << STS << "+peer " << peer;
        _connections[peer.u64()] = std::make_unique<Connection>(
            *this,
            peer.u64(),
            gen_nonceprefix(peer.u64()),
            std::move(newStream)
        );
    } else {
        LOG_ERROR() << STS << io::error_str(errorCode) << ", restarting server in  " << SERVER_RESTART_INTERVAL << " msec";
        _timers.set_timer(SERVER_RESTART_TIMER, SERVER_RESTART_INTERVAL, BIND_THIS_MEMFN(start_server));
    }
}

std::string Server::gen_nonceprefix(uint64_t connId) {
    std::string x;
    if (_prefixDigits > 0) {
        ECC::Hash::Processor p;
        ECC::Hash::Value v;
        p << _prefixSeed << connId;
        p >> v;
        x = to_hex(v.m_pData, 3);
        x = x.substr(0, _prefixDigits);
    }
    return x;
}

bool Server::on_login(uint64_t from, const Login& login) {
    assert(_connections.count(from) > 0);

    auto& conn = _connections[from];
    bool loginSuccess = false;
    if (_acl.check(login.api_key)) {
        conn->set_logged_in();
        loginSuccess = true;
    } else {
        LOG_INFO() << STS << "peer login failed, key=" << login.api_key;
    }

    Result res(login.id, loginSuccess ? stratum::no_error : stratum::login_failed);
    res.nonceprefix = conn->get_nonceprefix();
    res.forkheight = Rules::get().pForks[1].m_Height;
    std::cout << "Fork Height: " << Rules::get().pForks[1].m_Height << std::endl;
    append_json_msg(_fw, res);
    bool sent = conn->send_msg(_currentMsg, false, !loginSuccess);
    _currentMsg.clear();

    if (!sent || !loginSuccess)
        return false;

    return _connections[from]->send_msg(_recentJob.msg, true);
}

bool Server::on_solution(uint64_t from, const Solution& sol) {
	LOG_DEBUG() << TRACE(sol.nonce) << TRACE(sol.output);

	if (_prefixDigits > 0) {
	    const std::string& nonceprefix = _connections[from]->get_nonceprefix();
	    if (
	        sol.nonce.size() < _prefixDigits ||
	        memcmp(sol.nonce.c_str(), nonceprefix.c_str(), _prefixDigits) != 0
	    ) {
            Result res(sol.id, stratum::solution_rejected);
            //res.nonceprefix = nonceprefix;
            append_json_msg(_fw, res);
            _connections[from]->send_msg(_currentMsg, true, true);
            _currentMsg.clear();
            return false;
	    }
	}

	_recentResult.id = sol.id;
    sol.fill_pow(_recentResult.pow);

    LOG_INFO() << STS << "solution to " << sol.id << " from " << io::Address::from_u64(from);
	IExternalPOW::BlockFoundResult result = _recentResult.onBlockFound();
    stratum::ResultCode stratumCode = stratum::solution_rejected;
    if (result == IExternalPOW::solution_accepted) {
        stratumCode = stratum::solution_accepted;
    } else if (result == IExternalPOW::solution_expired) {
        stratumCode = stratum::solution_expired;
    }
    Result res(sol.id, stratumCode);
    append_json_msg(_fw, res);
    bool sent = _connections[from]->send_msg(_currentMsg, true);
    _currentMsg.clear();
    return sent;
}

void Server::on_bad_peer(uint64_t from) {
    LOG_INFO() << STS << "-peer " << io::Address::from_u64(from);
    _connections.erase(from);
}

void Server::new_job(
    const std::string& id,
    const Merkle::Hash& input,
    const Block::PoW& pow,
    const Height& height,
    const BlockFound& callback,
    const CancelCallback& /* cancelCallback */
) {
    _recentJob.id = id;
    _recentResult.onBlockFound = callback;
    _recentResult.height = height;

    LOG_INFO() << STS << "new job " << id << " will be sent to " << _connections.size() << " connected peers";

    Job jobMsg(id, input, pow, height);
    append_json_msg(_fw, jobMsg);
	_recentJob.msg.swap(_currentMsg);
    _currentMsg.clear();

    for (auto& p : _connections) {
        if (!p.second->send_msg(_recentJob.msg, true)) {
            _deadConnections.push_back(p.first);
        }
    }

    for (auto c : _deadConnections) {
        _connections.erase(c);
    }
    _deadConnections.clear();

    // TODO job cancel policy - timer
}

void Server::get_last_found_block(std::string& jobID, Height& jobHeight, Block::PoW& pow) {
    jobID = _recentResult.id;
    jobHeight = _recentResult.height;
    pow = _recentResult.pow;
}

void Server::stop_current() {
    _recentJob.id.clear();
}

void Server::stop() {
    stop_current();
    _server.reset();
}

Server::AccessControl::AccessControl(const std::string &keysFileName) :
    _enabled(!keysFileName.empty()),
    _keysFileName(keysFileName),
    _lastModified(0)
{
    refresh();
}

void Server::AccessControl::refresh() {
    using namespace boost::filesystem;

    if (!_enabled) return;

    try {
        path p(_keysFileName);
        auto t = last_write_time(p);
        if (t <= _lastModified) {
            return;
        }
        _lastModified = t;
        std::ifstream file(_keysFileName);
        std::string line;
        std::set<std::string> keys;
        while (std::getline(file, line)) {
            boost::algorithm::trim(line);

            //TODO 1) min key length as a parameter 2) storing hashes in the file

            if (line.size() < 8) continue;
            keys.insert(line);
        }
        _keys.swap(keys);
    } catch (std::exception& e) {
        LOG_ERROR() << STS << e.what();
    }
}

bool Server::AccessControl::check(const std::string& key) {
    if (!_enabled) return true;
    return _keys.count(key) > 0;
}

Server::Connection::Connection(
    ConnectionToServer& owner, uint64_t id, std::string nonceprefix, io::TcpStream::Ptr&& newStream
) :
    _owner(owner),
    _id(id),
    _nonceprefix(std::move(nonceprefix)),
    _stream(std::move(newStream)),
    _lineReader(BIND_THIS_MEMFN(on_raw_message)),
    _loggedIn(false)
{
    _stream->enable_keepalive(2);
    _stream->enable_read(BIND_THIS_MEMFN(on_stream_data));
}

bool Server::Connection::on_stream_data(io::ErrorCode errorCode, void* data, size_t size) {
    if (errorCode != 0) {
        LOG_INFO() << STS << "peer disconnected, code=" << io::error_str(errorCode);
        _owner.on_bad_peer(_id);
        return false;
    }
    if (!_lineReader.new_data_from_stream(data, size)) {
        _owner.on_bad_peer(_id);
        return false;
    }
    return true;
}

bool Server::Connection::send_msg(const io::SerializedMsg& msg, bool onlyIfLoggedIn, bool shutdown) {
    if (onlyIfLoggedIn && !_loggedIn) return true;
    bool sent = _stream && _stream->write(msg);
    if (sent && shutdown) {
        _stream->shutdown();
    }
    return sent;
}

bool Server::Connection::on_message(const stratum::Login& login) {
    return _owner.on_login(_id, login);
}

bool Server::Connection::on_message(const stratum::Solution& solution) {
    return _owner.on_solution(_id, solution);
}

bool Server::Connection::on_raw_message(void* data, size_t size) {
    LOG_VERBOSE() << "got " << std::string((char*)data, size-1);
    return stratum::parse_json_msg(data, size, *this);
}

bool Server::Connection::on_stratum_error(stratum::ResultCode code) {
    // TODO what to do with other errors
    LOG_ERROR() << STS << "got stratum error: " << code << " " << stratum::get_result_msg(code);
    return true;
}

bool Server::Connection::on_unsupported_stratum_method(stratum::Method method) {
    LOG_INFO() << STS << "ignoring unsupported stratum method: " << stratum::get_method_str(method);
    return true;
}

}} //namespaces

max_stars_repo_name: Lolliedieb/beam

max_issues_repo_name: qmutz/beam

max_forks_repo_name: qmutz/beam


text: #include <boost/type_traits/make_signed.hpp>

max_stars_repo_name: miathedev/BoostForArduino

max_issues_repo_name: miathedev/BoostForArduino

max_forks_repo_name: miathedev/BoostForArduino


text:
#include <iostream>
#include <sstream>
#include <locale>
#include <boost/algorithm/string.hpp>

#include "display3r/Solid.hpp"
#include "display3r/Exception.hpp"
#include "display3r/Renderer.hpp"

using namespace std;
using namespace display3r;

namespace display3r {

static inline double strtod(string const &s)
{
    istringstream istr(s);
    double d;

    istr.imbue(locale("C"));
    istr >> d;
    return d;
}
static inline int atoi(string const &s)
{
    return ::atoi(s.c_str());
}

}; // end namespace display3r

void Solid::ParseVertex(vector<string> const &s, vector<vec3> &vertex)
{
    vec3 v;
    if (s.size() != 4)
        throw exception("invalid vertex");
    v.x = strtod(s[1]);
    v.y = strtod(s[2]);
    v.z = strtod(s[3]);

    vertex.push_back(v);
}

void Solid::ParseNormal(vector<string> const &s, vector<vec3> &normal)
{
    vec3 n;
    if (s.size() != 4)
        throw exception("invalid normal");
    n.x = strtod(s[1]);
    n.y = strtod(s[2]);
    n.z = strtod(s[3]);

    normal.push_back(n);
}

void Solid::ParseTexCoord(vector<string> const &s, vector<vec2> &texcoord)
{
    vec2 t;
    if (s.size() != 3)
        throw exception("invalid texcoord");
    t.x = strtod(s[1]);
    t.y = strtod(s[2]);
    t.y = 1 - t.y;

    texcoord.push_back(t);
}

Vertex Solid::ParseVertexIndex(string rep,
                               vector<vec3>const &vertex,
                               vector<vec3>const &normal,
                               vector<vec2>const &texcoord)
{
    Vertex v;
    vector<string> s;
    boost::trim(rep);
    boost::split(s, rep, boost::is_any_of("/"));

    if (!s.size() || s.size() > 3)
        throw exception("bad face element");

    v.position = vertex[atoi(s[0])-1];
    if (s.size() >= 2 && s[1] != "")
        v.texcoord = texcoord[atoi(s[1])-1];
    if (s.size() == 3)
        v.normal = normal[atoi(s[2])-1];
    return v;
}

void Solid::ParseFace(vector<string> const &s,
                      vector<vec3>const &v/*ertex*/,
                      vector<vec3>const &n/*ormal*/,
                      vector<vec2>const &t/*excoord*/)
{
    if (s.size() < 4)
        throw exception("invalid face");

    Face f(ParseVertexIndex(s[1], v, n, t),
           ParseVertexIndex(s[2], v, n, t),
           ParseVertexIndex(s[3], v, n, t));
    m_faces.push_back(f);

    // triangle fan if more than 3 points:
    Vertex last = f.C;
    for (unsigned i = 4; i < s.size(); ++i) {
        Face g(f.A, last, ParseVertexIndex(s[i], v, n, t));
        last = g.C;
        m_faces.push_back(g);
    }
}

void Solid::LoadOBJ(ifstream &file)
{
    m_faces.clear();
    vector<vec3> normals;
    vector<vec3> vertex;
    vector<vec2> texcoords;

    string line;
    int line_count = 1;
    while (getline(file, line)) {
        boost::trim(line);
        vector<string> s;
        boost::split(s, line, boost::is_any_of(" "));
        string const &type = s[0];

        try {
            if (type == "v")
                ParseVertex(s, vertex);
            else if (type == "vn")
                ParseNormal(s, normals);
            else if (type == "vt")
                ParseTexCoord(s, texcoords);
            else if (type == "f")
                ParseFace(s, vertex, normals, texcoords);
            else if (type == "o" && s.size() >= 2)
                m_name = s[1];

        } catch (exception &e) {
            throw exception( string(e.what())+
                             " line "+to_string(line_count));
        }
        ++ line_count;
    }
}

Solid::Solid(string filepath, Texture *texture):
    m_texture(texture), m_name("Unnamed")
{
    ifstream f(filepath);

    if (!f.is_open())
	throw exception(filepath+": "+strerror(errno));

    LoadOBJ(f);
    cout << "Object " << filepath <<":"<<m_name<< " LOADED." << endl;
    cout << "texture pointer" << texture << endl;
    f.close();
}

void Solid::DrawHandler(Renderer &renderer)
{
    renderer.BindTexture(m_texture);
    for (auto &f : m_faces)
        renderer.DrawFace(f);

    renderer.BindTexture(NULL); // unbind texture
}

Solid::Solid(Equation const&, Texture*)
{
    throw display3r::exception("equation loading not implemented, sorry");
}

// Solid::Solid(Equation &eq, string texpath)
// {
//     float minS, maxS, minT, maxT;
//     int precisionS, precisionT;
//     char x[MAXLENGTH];
//     char y[MAXLENGTH];
//     char z[MAXLENGTH];

//     if (!initEquation(&minS, &maxS, &precisionS,
// 		      &minT, &maxT, &precisionT,
// 		      x, y, z, MAXLENGTH, eqName)) {
// 	fprintf(stderr, "Error loading equation\n");
// 	return NULL;
//     } else
// 	printf("Equation successfully initialized\n");

//     Solid *solid = malloc(sizeof(Solid));
//     int p, f = 0;
//     float s = minS, t = minT;
//     float ds = (maxS - minS) / (precisionS - 1);
//     float dt = (maxT - minT) / (precisionT - 1);

//     solid->numVertices = precisionS * precisionT;
//     solid->numNormals = solid->numVertices;
//     solid->numCoords = 4;
//     solid->numFaces = 2 * (precisionS - 1) * (precisionT - 1);

//     solid->vertices = malloc(solid->numVertices * sizeof(Point));
//     solid->normals = malloc(solid->numNormals * sizeof(Point));
//     solid->coords = malloc(solid->numCoords * sizeof(Texture));
//     solid->faces = malloc(solid->numFaces * sizeof(Face));

//     setTexture(&solid->coords[0], 0., 0.);
//     setTexture(&solid->coords[1], 0., 1.);
//     setTexture(&solid->coords[2], 1., 0.);
//     setTexture(&solid->coords[3], 1., 1.);

//     if ((solid->texture = SDL_LoadBMP(texpath.c_str())) == NULL)
// 	fprintf(stderr, "%s\n", SDL_GetError());

//     if (solid->numVertices > 0)
// 	getValueFromEquation(x, y, z, s, t, &solid->vertices[0]);

//     for (p = 0; p < solid->numVertices; p++) {
// 	Point *A;
// 	Point *B;
// 	Point *O = &solid->vertices[p];
// 	Point *normal = &solid->normals[p];
// 	Point u;
// 	Point v;

// 	printf("%d => s: %f, t: %f\n", p, s, t);
// 	printf("%d => x: %f, y: %f, z: %f\n", p, O->x, O->y, O->z);

//         if (p == solid->numVertices - 1) { // north-east
// 	    A = &solid->vertices[p - 1];
// 	    B = &solid->vertices[p - precisionS];
// 	} else if (p % precisionS == precisionS - 1) { // east
// 	    A = &solid->vertices[p + precisionS];
// 	    B = &solid->vertices[p - 1];

// 	    getValueFromEquation(x, y, z, s, t + dt, A);
// 	    s = minS;
// 	    t += dt;
// 	} else if (p >= (solid->numVertices - precisionS)) { // north
// 	    A = &solid->vertices[p - precisionS];
// 	    B = &solid->vertices[p + 1];

// 	    s += ds;
// 	} else if (p < precisionS) { // south
// 	    A = &solid->vertices[p + 1];
// 	    B = &solid->vertices[p + precisionS];

// 	    getValueFromEquation(x, y, z, s + ds, t, A);
// 	    getValueFromEquation(x, y, z, s, t + dt, B);
// 	    s += ds;
// 	} else { // elsewhere
// 	    A = &solid->vertices[p + 1];
// 	    B = &solid->vertices[p + precisionS];

// 	    getValueFromEquation(x, y, z, s, t + dt, B);
// 	    s += ds;
// 	}
// 	diffPoint(A, O, &u);
// 	diffPoint(B, O, &v);
// 	pointProduct(&u, &v, normal);
// 	normalizePoint(normal, normal);
//     }

//     p = 0;
//     while (f < solid->numFaces) {
// 	if (p % precisionS != precisionS - 1) {
// 	    solid->faces[f].vertices[0].point = p;
// 	    solid->faces[f].vertices[1].point = p + 1;
// 	    solid->faces[f].vertices[2].point = p + precisionS;
// 	    solid->faces[f].vertices[0].normal = p;
// 	    solid->faces[f].vertices[1].normal = p + 1;
// 	    solid->faces[f].vertices[2].normal = p + precisionS;
// 	    solid->faces[f].vertices[0].coord = 1;
// 	    solid->faces[f].vertices[1].coord = 3;
// 	    solid->faces[f].vertices[2].coord = 0;

// 	    f++;

// 	    solid->faces[f].vertices[0].point = p + precisionS;
// 	    solid->faces[f].vertices[1].point = p + 1;
// 	    solid->faces[f].vertices[2].point = p + 1 + precisionS;
// 	    solid->faces[f].vertices[0].normal = p + precisionS;
// 	    solid->faces[f].vertices[1].normal = p + 1;
// 	    solid->faces[f].vertices[2].normal = p + 1 + precisionS;
// 	    solid->faces[f].vertices[0].coord = 0;
// 	    solid->faces[f].vertices[1].coord = 3;
// 	    solid->faces[f].vertices[2].coord = 2;

// 	    f++;
// 	}
// 	p++;
//     }
//     solid->computeOrigin();
//     freeEquation();
//     printf("Equation successfully loaded\n");
//     return solid;
// }


text:
// this is for emacs file handling -*- mode: c++; indent-tabs-mode: nil -*-

// -- BEGIN LICENSE BLOCK ----------------------------------------------
// Copyright (c) 2018, FZI Forschungszentrum Informatik
//
// 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 the copyright holder 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 HOLDER 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.
// -- END LICENSE BLOCK ------------------------------------------------

//----------------------------------------------------------------------
/*!\file
 *
 * \author  Philipp Bender <philipp.bender@fzi.de>
 * \date    2014-01-01
 *
 */
//----------------------------------------------------------------------

#pragma once

#include <boost/math/special_functions.hpp>
#include <cmath>
#include <boost/tuple/tuple.hpp>
#include <boost/variant/get.hpp>
#include "LocalGeographicCS.hpp"
#include "normalize_angle.hpp"
#include "Attribute.hpp"

namespace LLet
{

enum LATLON_COORDS
{
    LAT = 0,
    LON = 1,
    ID = 2
};

enum XY_COORDS
{
    X = 0,
    Y = 1
};

class point_with_id_t : public boost::tuple<double, double, int64_t>, public HasAttributes {
public:
  point_with_id_t(const boost::tuple<double, double, int64_t> &tuple = boost::tuple<double, double, int64_t>(0.0, 0.0, -1)) :
    boost::tuple<double, double, int64_t>(tuple)
  {
    // nothing to do
  }

#ifdef _WIN32 // The tuple implementation of MSVC10 fails on the auto-generated copy ctor
    point_with_id_t(const point_with_id_t &other) :
      HasAttributes(other)
    {
        boost::get<LLet::LAT>(*this) = boost::get<LLet::LAT>(other);
        boost::get<LLet::LON>(*this) = boost::get<LLet::LON>(other);
        boost::get<LLet::ID>(*this) = boost::get<LLet::ID>(other);
    }
#endif

};

inline bool operator==(const point_with_id_t& lhs, const point_with_id_t& rhs)
{
  return boost::get<0>(lhs) == boost::get<0>(rhs)
      && boost::get<1>(lhs) == boost::get<1>(rhs)
      && boost::get<2>(lhs) == boost::get<2>(rhs);
}
inline bool operator!=(const point_with_id_t& lhs, const point_with_id_t& rhs){return !(lhs == rhs);}

typedef boost::tuple< double, double > point_xy_t;
typedef std::vector<point_xy_t> vertex_container_t;

inline
boost::tuple< double, double > vec( const point_with_id_t& a, const point_with_id_t& b )
{
    using boost::get;

    LocalGeographicCS cs(get<LAT>(a), get<LON>(a));

    double ax, ay, bx, by;
    boost::tie(ax, ay) = cs.ll2xy(get<LAT>(a), get<LON>(a));
    boost::tie(bx, by) = cs.ll2xy(get<LAT>(b), get<LON>(b));

    double dx = bx -  ax;
    double dy = by -  ay;

    return boost::make_tuple(dx, dy);
}

//! Calculate the absolute point from absolute point \a a with relative offset \a vec and the given id \a id
inline point_with_id_t from_vec(const point_with_id_t& a, const point_xy_t& vec, const int64_t id = -1)
{
  using boost::get;

  LocalGeographicCS cs(get<LAT>(a), get<LON>(a));
  const boost::tuple<double, double>& ll = cs.xy2ll(get<X>(vec), get<Y>(vec));
  return boost::make_tuple(get<LAT>(ll), get<LON>(ll), id);
}

inline
double abs( const boost::tuple< double, double > &v )
{
    using boost::get;
    using boost::math::hypot;
    return hypot( get<X>(v), get<Y>(v) );
}

//! Calculate the distance between (metric) a and b
inline double dist(const point_xy_t& a, const point_xy_t& b)
{
  using boost::get;
  return abs(boost::make_tuple(get<X>(b) - get<X>(a), get<Y>(b) - get<Y>(a)));
}

//! Normalize the vector \a vec
inline void normalize(boost::tuple<double, double>& vec)
{
  using boost::get;
  const double length = abs(vec);
  assert(length != 0 && "The given vector's length is 0.");
  vec = boost::make_tuple(get<X>(vec) / length, get<Y>(vec) / length);
}

//! Calculate the distance between (gnss) a and b
inline double dist( const point_with_id_t& a, const point_with_id_t& b )
{
    return abs(vec(a, b));
}

inline
double scalar_product( const boost::tuple< double, double >& a, const boost::tuple< double, double >& b )
{
    using boost::get;
    return get<X>(a) * get<X>(b) + get<Y>(a) * get<Y>(b);
}

//! Project p on line
inline
point_xy_t projected(const point_xy_t& p, const vertex_container_t &line, double* angle=0, std::size_t* index=0, std::size_t* previous_index=0, std::size_t* subsequent_index=0)
{
  double min_distance = -1.0;
  double const px = boost::get<LLet::X>(p);
  double const py = boost::get<LLet::Y>(p);
  point_xy_t min_point = p;
  size_t const size = line.size();
  for (std::size_t i=1; i<size; ++i)
  {
    const double& ax = boost::get<LLet::X>(line[i-1]);
    const double& ay = boost::get<LLet::Y>(line[i-1]);
    const double& bx = boost::get<LLet::X>(line[i]);
    const double& by = boost::get<LLet::Y>(line[i]);

    point_xy_t const AP = point_xy_t(px-ax, py-ay);
    point_xy_t const AB = point_xy_t(bx-ax, by-ay);
    double const scalar_product_ab = scalar_product(AB, AB);
    double const lambda = scalar_product(AP, AB) / ( scalar_product_ab == 0.0 ? 1.0 : scalar_product_ab );

    double distance = 0.0;
    point_xy_t c;
    if (lambda <= 0.0)
    {
      c = line[i-1];
    }
    else if (lambda < 1.0)
    {
      c = point_xy_t(ax + lambda*(bx-ax), ay + lambda*(by-ay));
    }
    else
    {
      c = line[i];
    }
    distance = dist(p, c);
    if (min_distance < 0.0 || distance < min_distance)
    {
      min_distance = distance;
      min_point = c;
      if (angle)
      {
        *angle = atan2(boost::get<Y>(line[i])-boost::get<Y>(line[i-1]), boost::get<X>(line[i])-boost::get<X>(line[i-1]));
      }
      if (index)
      {
        *index = lambda < 0.5? i-1 : i;
      }
      if (subsequent_index)
      {
        *subsequent_index = i;
      }
      if (previous_index)
      {
        *previous_index = i-1;
      }
    }
  }

  return min_point;
}

inline
double angle( const boost::tuple< double, double >& a, const boost::tuple< double, double >& b )
{
    using boost::get;

    double sp = scalar_product(a, b);
    double cos_phi = sp / (abs(a) * abs(b));

    // sign for angle: test cross product
    double crossp_z = get<X>(a) * get<Y>(b) - get<Y>(a) * get<X>(b);
    double signum = boost::math::sign(crossp_z);
    double phi = normalize_angle(signum * std::acos(cos_phi));
    return phi;
}

template< typename T1, typename T2 >
inline
bool inrange(const T1& val, const T2& lo, const T2& hi)
{
    return val >= lo && val <= hi;
}

/*! Interpolate the given points using a Catmull-Rom polygon.
 *  Any \a ratio between 0 and 1 will interpolate in between \a p1 and \a p2.
 */
inline point_xy_t interpolate_spline(const point_xy_t& p0, const point_xy_t& p1,
                                     const point_xy_t& p2, const point_xy_t& p3, double ratio)
{
  /* Catmull-Rom coefficients:
   *
   * a0 = -0.5*p0 + 1.5*p1 - 1.5*p2 + 0.5*p3
   * a1 = p0 - 2.5*p1 + 2*p2 - 0.5*p3
   * a2 = -0.5*p0 + 0.5*p2
   */

  const point_xy_t a0 = boost::make_tuple(-0.5 * boost::get<X>(p0) + 1.5 * boost::get<X>(p1) - 1.5 * boost::get<X>(p2) + 0.5 * boost::get<X>(p3),
                                       -0.5 * boost::get<Y>(p0) + 1.5 * boost::get<Y>(p1) - 1.5 * boost::get<Y>(p2) + 0.5 * boost::get<Y>(p3));

  const point_xy_t a1 = boost::make_tuple(boost::get<X>(p0) - 2.5 * boost::get<X>(p1) + 2. * boost::get<X>(p2) - 0.5 * boost::get<X>(p3),
                                       boost::get<Y>(p0) - 2.5 * boost::get<Y>(p1) + 2. * boost::get<Y>(p2) - 0.5 * boost::get<Y>(p3));

  const point_xy_t a2 = boost::make_tuple(-0.5 * boost::get<X>(p0) + 0.5 * boost::get<X>(p2),
                                       -0.5 * boost::get<Y>(p0) + 0.5 * boost::get<Y>(p2));
  const double ratio_square = ratio * ratio;

  // Catmull-Rom polynom: result = a0 * ratio³ + a1 * ratio² + a2 * ratio + p1
  return boost::make_tuple(boost::get<X>(a0) * ratio * ratio_square + boost::get<X>(a1) * ratio_square + boost::get<X>(a2) * ratio + boost::get<X>(p1),
                        boost::get<Y>(a0) * ratio * ratio_square + boost::get<Y>(a1) * ratio_square + boost::get<Y>(a2) * ratio + boost::get<Y>(p1));
}

//! Calculate the dot product for vector \a and vector \b
inline double dot(const point_xy_t& a, const point_xy_t& b)
{
  return boost::get<LLet::X>(a) * boost::get<LLet::X>(b) +
      boost::get<LLet::Y>(a) * boost::get<LLet::Y>(b);
}

}


text:
//---------------------------------------------------------------------------//
//!
//! \file   MonteCarlo_ParticleSimulationManager.hpp
//! \author Alex Robinson
//! \brief  Particle simulation manager class declaration
//!
//---------------------------------------------------------------------------//

#ifndef MONTE_CARLO_PARTICLE_SIMULATION_MANAGER_HPP
#define MONTE_CARLO_PARTICLE_SIMULATION_MANAGER_HPP

// Std Lib Includes
#include <memory>

// Boost Includes
#include <boost/filesystem/path.hpp>

// FRENSIE Includes
#include "MonteCarlo_EventHandler.hpp"
#include "MonteCarlo_PopulationControl.hpp"
#include "MonteCarlo_CollisionForcer.hpp"
#include "MonteCarlo_StandardWeightCutoffRoulette.hpp"
#include "MonteCarlo_ParticleSource.hpp"
#include "MonteCarlo_FilledGeometryModel.hpp"
#include "MonteCarlo_CollisionKernel.hpp"
#include "MonteCarlo_TransportKernel.hpp"
#include "MonteCarlo_SimulationProperties.hpp"
#include "Utility_Communicator.hpp"

extern "C" void __custom_signal_handler__( int signal );

namespace MonteCarlo{

//! The particle simulation manager base class
class ParticleSimulationManager : public std::enable_shared_from_this<ParticleSimulationManager>
{

public:

  //! Destructor
  virtual ~ParticleSimulationManager()
  { /* ... */ }

  //! Return the next history that will be completed
  uint64_t getNextHistory() const;

  //! Return the number of rendezvous
  uint64_t getNumberOfRendezvous() const;

  //! Return the rendezvous batch size
  uint64_t getRendezvousBatchSize() const;

  //! Return the batch size
  uint64_t getBatchSize() const;

  //! Return the model
  const FilledGeometryModel& getModel() const;

  //! Return the source
  const ParticleSource& getSource() const;

  //! Return the event handler
  const EventHandler& getEventHandler() const;

  //! Return the event handler
  EventHandler& getEventHandler();

  //! Return the simulation properties
  const SimulationProperties& getSimulationProperties() const;

  //! Set the simulation name
  void setSimulationName( const std::string& new_name );

  //! Get the simulation name
  const std::string& getSimulationName() const;

  //! Set the simulation archive type
  void setSimulationArchiveType( const std::string& archive_type );

  //! Get the simulation archive type
  const std::string& getSimulationArchiveType() const;

  //! Set the simulation name and archive type
  void setSimulationNameAndArchiveType( const std::string& new_name,
                                        const std::string& archive_type );

  //! Initialize the manager
  void initialize();

  //! Use a single rendezvous file
  void useSingleRendezvousFile();

  //! Use multiple rendezvous files
  void useMultipleRendezvousFiles();

  //! Check if a single rendezvous file will be used
  bool isSingleRendezvousFileUsed() const;

  //! Run the simulation set up by the user
  virtual void runSimulation();

  //! Run the simulation set up by the user with the ability to interrupt
  virtual void runInterruptibleSimulation();

  //! Print the simulation data to the desired stream
  virtual void printSimulationSummary( std::ostream& os ) const;

  //! Log the simulation data
  virtual void logSimulationSummary() const;

protected:

  //! Constructor
  ParticleSimulationManager(
                 const std::string& simulation_name,
                 const std::string& archive_type,
                 const std::shared_ptr<const FilledGeometryModel>& model,
                 const std::shared_ptr<ParticleSource>& source,
                 const std::shared_ptr<EventHandler>& event_handler,
                 const std::shared_ptr<PopulationControl> population_controller,
                 const std::shared_ptr<const CollisionForcer> collision_forcer,
                 const std::shared_ptr<const SimulationProperties>& properties,
                 const uint64_t next_history,
                 const uint64_t rendezvous_number,
                 const bool use_single_rendezvous_file );

  //! Set the batch size
  void setBatchSize( const uint64_t batch_size );

  //! Increment the next history
  void incrementNextHistory( const uint64_t increment_size );

  //! Check if the simulation has been ended by the user
  bool hasEndSimulationRequestBeenMade() const;

  //! Run the simulation batch
  void runSimulationBatch( const uint64_t batch_start_history,
                           const uint64_t batch_end_history );

  //! Simulate an unresolved particle
  virtual void simulateUnresolvedParticle(
                                        ParticleState& unresolved_particle,
                                        ParticleBank& bank,
                                        const bool source_particle ) = 0;

  //! Simulate a resolved particle
  template<typename State>
  void simulateParticle( ParticleState& unresolved_particle,
                         ParticleBank& bank,
                         const bool source_particle );

  //! Simulate a resolved particle using the "alternative" tracking method
  template<typename State>
  void simulateParticleAlternative( ParticleState& unresolved_particle,
                                    ParticleBank& bank,
                                    const bool source_particle );

  //! Get the collision forcer
  const CollisionForcer& getCollisionForcer() const;

  //! Enable thread support
  void enableThreadSupport();

  //! Reset data
  void resetData();

  //! Reduce distributed data
  void reduceData( const Utility::Communicator& comm,
                   const int root_process );

  //! Register simulation started event
  void registerSimulationStartedEvent();

  //! Register simulation stopped event
  void registerSimulationStoppedEvent();

  //! Check if the simulation is complete
  bool isSimulationComplete();

  //! Rendezvous (cache state)
  virtual void rendezvous();

  //! The signal handler
  virtual void signalHandler( int signal );

  //! Check if a signal type is handled by the manager
  static bool isSignalTypeHandled( const int signal );

private:

  // Set the cutoff weight roulette
  void setCutoffWeightRoulette();

  // Set the neutron cutoff weight roulette
  void setNeutronCutoffWeightRoulette();

  // Set the photon cutoff weight roulette
  void setPhotonCutoffWeightRoulette();

  // Set the adjoint photon cutoff weight roulette
  void setAdjointPhotonCutoffWeightRoulette();

  // Set the electron cutoff weight roulette
  void setElectronCutoffWeightRoulette();

  // Set the adjoint electron cutoff weight roulette
  void setAdjointElectronCutoffWeightRoulette();

  //! Run the simulation batch
  void runSimulationMicroBatch( const uint64_t batch_start_history,
                                const uint64_t batch_end_history );

  // Simulate a resolved particle implementation
  template<typename State, typename SimulateParticleTrackMethod>
  void simulateParticleImpl( ParticleState& unresolved_particle,
                             ParticleBank& bank,
                             const bool source_particle,
                             const SimulateParticleTrackMethod&
                             simulate_particle_track );

  // Simulate an unresolved particle track
  template<typename State>
  void simulateUnresolvedParticleTrack(
                                       ParticleState& unresolved_particle,
                                       ParticleBank& bank,
                                       const double optical_path,
                                       const bool starting_from_source );

  // Simulate a resolved particle track
  template<typename State>
  void simulateParticleTrack( State& particle,
                              ParticleBank& bank,
                              const double optical_path,
                              const bool starting_from_source );

  // Simulate an unresolved particle track using the "alternative" method
  template<typename State>
  void simulateUnresolvedParticleTrackAlternative(
                                            ParticleState& unresolved_particle,
                                            ParticleBank& bank,
                                            const double optical_path,
                                            const bool starting_from_source );

  // Simulate an resolved particle track using the "alternative" method
  template<typename State>
  void simulateParticleTrackAlternative( State& unresolved_particle,
                                         ParticleBank& bank,
                                         const double optical_path,
                                         const bool starting_from_source );

  // Advance a particle to the cell boundary
  template<typename State>
  void advanceParticleToCellBoundary(
                              State& particle,
                              const Geometry::Model::EntityId surface_to_cross,
                              const double distance_to_surface );

  // Advance a particle to a collision site
  template<typename State>
  void advanceParticleToCollisionSite(
                               State& particle,
                               const double op_to_collision_site,
                               const double distance_to_collision_site,
                               const double track_start_position[3],
                               bool& global_subtrack_ending_event_dispatched );

  // Collide with the cell material
  template<typename State>
  void collideWithCellMaterial( State& particle,
                                ParticleBank& bank );

  // Conduct a basic rendezvous
  void basicRendezvous() const;

  // Declare the custom signal handler as a friend
  friend void ::__custom_signal_handler__( int );

  // The simulation name
  std::string d_simulation_name;

  // The archive type
  std::string d_archive_type;

  // The filled geometry model
  std::shared_ptr<const FilledGeometryModel> d_model;

  // The collision kernel
  std::unique_ptr<const CollisionKernel> d_collision_kernel;

  // The transport kernel
  std::unique_ptr<const TransportKernel> d_transport_kernel;

  // The particle source
  std::shared_ptr<ParticleSource> d_source;

  // The event handler
  std::shared_ptr<EventHandler> d_event_handler;

  // The weight windows
  std::shared_ptr<PopulationControl> d_population_controller;

  // The collision forcer
  std::shared_ptr<const CollisionForcer> d_collision_forcer;

  // The weight cutoff roulette
  std::shared_ptr<StandardWeightCutoffRoulette> d_weight_roulette;

  // The simulation properties
  std::shared_ptr<const SimulationProperties> d_properties;

  // The next history to run
  uint64_t d_next_history;

  // The rendezvous number (counter)
  uint64_t d_rendezvous_number;

  // The rendezvous batch size
  uint64_t d_rendezvous_batch_size;

  // The batch size
  uint64_t d_batch_size;

  // Use a single rendezvous file
  bool d_use_single_rendezvous_file;

  // Flag for ending simulation early
  bool d_end_simulation;

  // Flag for exiting the simulation immediately
  bool d_exit_simulation;
};

} // end MonteCarlo namespace

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

#include "MonteCarlo_ParticleSimulationManager_def.hpp"

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

#endif // end MONTE_CARLO_PARTICLE_SIMULATION_MANAGER_HPP

//---------------------------------------------------------------------------//
// end MonteCarlo_ParticleSimulationManager.hpp
//---------------------------------------------------------------------------//

max_stars_repo_name: psbritt/FRENSIE

max_issues_repo_name: psbritt/FRENSIE

max_forks_repo_name: psbritt/FRENSIE


text:
//****************************************************************************
// (c) 2008 - 2010 by the openOR Team
//****************************************************************************
// The contents of this file are available under the GPL v2.0 license
// or under the openOR commercial license. see
//   /Doc/openOR_free_license.txt or
//   /Doc/openOR_comercial_license.txt
// for Details.
//****************************************************************************
//! OPENOR_INTERFACE_FILE(openOR_core)
//****************************************************************************
//! @file
//! @ingroup openOR_core

#ifndef openOR_Plugin_interface_cast_hpp
#define openOR_Plugin_interface_cast_hpp

#include <string>
#include <typeinfo>

#include <boost/tr1/memory.hpp>
#include <boost/mpl/assert.hpp>
#include <boost/type_traits/is_polymorphic.hpp>
#include <boost/type_traits/is_base_of.hpp>

#include <openOR/Plugin/detail/cast.hpp>
#include <openOR/Plugin/exception.hpp>
#include <openOR/Log/Logger.hpp>

namespace openOR {
   namespace Plugin {

      //----------------------------------------------------------------------------
      //! \brief Casting of an object to a supported interface.
      //!
      //! The requested interface can be supported via direct inheritance and via registered adapter classes.
      //!
      //! \tparam InterfaceTo type of the interface class the pointer should be casted to.
      //! \tparam InterfaceFrom type of the input interface
      //! \param pFrom smart pointer which has to be casted to the 'InterfaceTo' interface class.
      //! \warning The object has to be created using the function 'createInstanceOf'.
      //! \ingroup openOR_core
      //----------------------------------------------------------------------------
      template<class InterfaceTo, class InterfaceFrom>
      std::tr1::shared_ptr<InterfaceTo> interface_cast(const std::tr1::shared_ptr<InterfaceFrom>& pFrom) {

         return Detail::Caster<InterfaceTo, InterfaceFrom, boost::is_base_of<InterfaceTo, InterfaceFrom>::value>::cast(pFrom, false);
      }

      //----------------------------------------------------------------------------
      //! \brief Casting of an object to a supported interface.
      //!
      //! The requested interface can be supported via direct inheritance and via registered adapter classes.
      //!
      //! \tparam InterfaceTo type of the interface class the pointer should be casted to.
      //! \tparam InterfaceFrom type of the input interface
      //! \param pFrom smart pointer which has to be casted to the 'InterfaceTo' interface class.
      //! \warning The object has to be created using the function 'createInstanceOf'.
      //! \throw std::bad_cast in case of failure
      //! \ingroup openOR_core
      //----------------------------------------------------------------------------
      template<class InterfaceTo, class InterfaceFrom>
      std::tr1::shared_ptr<InterfaceTo> try_interface_cast(const std::tr1::shared_ptr<InterfaceFrom>& pFrom) {

         return Detail::Caster<InterfaceTo, InterfaceFrom, boost::is_base_of<InterfaceTo, InterfaceFrom>::value>::cast(pFrom, true);
      }

   } // end NS

   using Plugin::interface_cast;
   using Plugin::try_interface_cast;
}

#endif //openOR_Plugin_interface_cast_hpp

max_stars_repo_name: avinfinity/UnmanagedCodeSnippets

max_issues_repo_name: avinfinity/UnmanagedCodeSnippets

max_forks_repo_name: avinfinity/UnmanagedCodeSnippets


text:
// All content Copyright (C) 2018 Genomics plc
#define BOOST_TEST_DYN_LINK
#include <boost/test/unit_test.hpp>
#include "io/read.hpp"
#include "io/readIntervalTree.hpp"
#include "io/readRange.hpp"

using Read = wecall::io::Read;
using Cigar = wecall::alignment::Cigar;
using Interval = wecall::utils::Interval;
using wecall::utils::BasePairSequence;
using wecall::io::RegionsReads;
using wecall::caller::SetRegions;
using wecall::caller::Region;

BOOST_AUTO_TEST_CASE( shouldFilterReadsWithLowMappingQuality )
{
    wecall::io::readIntervalTree_t readContainer( 0, 100 );

    std::string qname = "test";
    auto refSequence =
        std::make_shared< wecall::utils::ReferenceSequence >( Region( "1", 0, 10 ), std::string( 10, 'A' ) );

    uint8_t mappingQuality = 10;
    readContainer.insert( std::make_shared< Read >( std::string( 2, 'A' ), std::string( 2, 'Q' ), qname, Cigar( "2M" ),
                                                    0, 1, 0, mappingQuality, 0, 0, 0, refSequence ) );

    SetRegions setRegions( refSequence->region() );
    const auto readRange = readContainer.getFullRange();

    {
        const RegionsReads range( setRegions, readRange, mappingQuality );
        BOOST_CHECK_EQUAL( std::distance( range.begin(), range.end() ), 1 );

        const auto subReads = range.getSubRegionReads( setRegions );
        BOOST_CHECK_EQUAL( std::distance( subReads.begin(), subReads.end() ), 1 );
    }
    {
        const RegionsReads range( setRegions, readRange, mappingQuality + 1 );
        BOOST_CHECK_EQUAL( std::distance( range.begin(), range.end() ), 0 );

        const auto subReads = range.getSubRegionReads( setRegions );
        BOOST_CHECK_EQUAL( std::distance( subReads.begin(), subReads.end() ), 0 );
    }
}

BOOST_AUTO_TEST_CASE( shouldGetCorrectSubrangesOneReadWithMatches )
{
    wecall::io::readIntervalTree_t readContainer( 0, 100 );
    std::string qname = "test";
    auto refSequence =
        std::make_shared< wecall::utils::ReferenceSequence >( Region( "1", 0, 10 ), std::string( 10, 'A' ) );

    readContainer.insert( std::make_shared< Read >( std::string( 2, 'A' ), std::string( 2, 'Q' ), qname, Cigar( "2M" ),
                                                    0, 1, 0, 0, 0, 0, 0, refSequence ) );

    auto range0 = readContainer.getFullRange();
    BOOST_CHECK_EQUAL( std::distance( range0.first, range0.second ), 1 );

    auto range1 = readContainer.getSubRange( Interval( 0, 1 ) );
    BOOST_CHECK_EQUAL( std::distance( range1.first, range1.second ), 0 );

    auto range2 = readContainer.getSubRange( Interval( 1, 2 ) );
    BOOST_CHECK_EQUAL( std::distance( range2.first, range2.second ), 1 );

    auto range3 = readContainer.getSubRange( Interval( 2, 9 ) );
    BOOST_CHECK_EQUAL( std::distance( range3.first, range3.second ), 1 );

    auto range4 = readContainer.getSubRange( Interval( 3, 10 ) );
    BOOST_CHECK_EQUAL( std::distance( range4.first, range4.second ), 0 );

    for ( const auto & read : readContainer )
    {
        BOOST_CHECK_EQUAL( read.getReadGroupID(), qname );
    }
}

BOOST_AUTO_TEST_CASE( shouldGetCorrectSubrangesOneReadWithPureInsertion )
{
    auto refSequence =
        std::make_shared< wecall::utils::ReferenceSequence >( Region( "1", 0, 10 ), std::string( 10, 'A' ) );
    wecall::io::readIntervalTree_t readContainer( 0, 100 );
    readContainer.insert( std::make_shared< Read >( std::string( 0, 'A' ), std::string( 0, 'Q' ), "0", Cigar( "0I" ), 0,
                                                    1, 0, 0, 0, 0, 0, refSequence ) );

    auto range0 = readContainer.getFullRange();
    BOOST_CHECK_EQUAL( std::distance( range0.first, range0.second ), 1 );

    auto range1 = readContainer.getSubRange( Interval( 0, 1 ) );
    BOOST_CHECK_EQUAL( std::distance( range1.first, range1.second ), 0 );

    auto range2 = readContainer.getSubRange( Interval( 1, 2 ) );
    BOOST_CHECK_EQUAL( std::distance( range2.first, range2.second ), 0 );

    auto range3 = readContainer.getSubRange( Interval( 0, 2 ) );
    BOOST_CHECK_EQUAL( std::distance( range3.first, range3.second ), 1 );

    auto range4 = readContainer.getSubRange( Interval( 1, 1 ) );
    BOOST_CHECK_EQUAL( std::distance( range4.first, range4.second ), 1 );

    auto range5 = readContainer.getSubRange( Interval( 2, 3 ) );
    BOOST_CHECK_EQUAL( std::distance( range5.first, range5.second ), 0 );
}

BOOST_AUTO_TEST_CASE( shouldGetCorrectSubrangesOneReadWithInsertionAtStart )
{
    auto refSequence =
        std::make_shared< wecall::utils::ReferenceSequence >( Region( "1", 0, 10 ), std::string( 10, 'A' ) );
    wecall::io::readIntervalTree_t readContainer( 0, 100 );
    readContainer.insert( std::make_shared< Read >( std::string( 8, 'A' ), std::string( 8, 'Q' ), "0", Cigar( "7I1M" ),
                                                    0, 1, 0, 0, 0, 0, 0, refSequence ) );

    auto range0 = readContainer.getFullRange();
    BOOST_CHECK_EQUAL( std::distance( range0.first, range0.second ), 1 );

    auto range1 = readContainer.getSubRange( Interval( 0, 1 ) );
    BOOST_CHECK_EQUAL( std::distance( range1.first, range1.second ), 1 );

    auto range2 = readContainer.getSubRange( Interval( 1, 2 ) );
    BOOST_CHECK_EQUAL( std::distance( range2.first, range2.second ), 1 );

    auto range3 = readContainer.getSubRange( Interval( 0, 2 ) );
    BOOST_CHECK_EQUAL( std::distance( range3.first, range3.second ), 1 );

    auto range4 = readContainer.getSubRange( Interval( 1, 1 ) );
    BOOST_CHECK_EQUAL( std::distance( range4.first, range4.second ), 1 );

    auto range5 = readContainer.getSubRange( Interval( 2, 3 ) );
    BOOST_CHECK_EQUAL( std::distance( range5.first, range5.second ), 0 );
}

BOOST_AUTO_TEST_CASE( testRegionSetReadsIteration )
{
    auto refSequence =
        std::make_shared< wecall::utils::ReferenceSequence >( Region( "1", 0, 10 ), std::string( 10, 'A' ) );
    wecall::io::readIntervalTree_t readContainer( 0, 100 );
    const int64_t startPos = 1;
    readContainer.insert( std::make_shared< Read >( BasePairSequence( 8, 'A' ), std::string( 8, 'Q' ), "0",
                                                    Cigar( "8M" ), 0, startPos, 0, 0, 0, 0, 0, refSequence ) );

    const auto readRange = readContainer.getFullRange();
    SetRegions setRegions;
    setRegions.insert( Region( "1", 1, 2 ) );

    RegionsReads regionSetReads( setRegions, readRange, 0 );
    for ( const auto & read : regionSetReads )
    {
        BOOST_CHECK_EQUAL( read.sequence(), BasePairSequence( 8, 'A' ) );
    }
    BOOST_CHECK_EQUAL( 1, std::distance( regionSetReads.begin(), regionSetReads.end() ) );
}

BOOST_AUTO_TEST_CASE( testShouldOnlyRetrieveReadsThatOverlapARegion )
{
    wecall::io::readIntervalTree_t readContainer( 0, 100 );
    const int64_t startPos1 = 1;
    const std::size_t length = 8;
    auto refSequence =
        std::make_shared< wecall::utils::ReferenceSequence >( Region( "1", 0, 20 ), std::string( 20, 'A' ) );
    readContainer.insert( std::make_shared< Read >( BasePairSequence( length, 'A' ), std::string( length, 'Q' ), "0",
                                                    Cigar( std::to_string( length ) + "M" ), 0, startPos1, 0, 0, 0, 0,
                                                    0, refSequence ) );
    const int64_t startPos2 = 10;
    readContainer.insert( std::make_shared< Read >( BasePairSequence( length, 'A' ), std::string( length, 'Q' ), "0",
                                                    Cigar( std::to_string( length ) + "M" ), 0, startPos2, 0, 0, 0, 0,
                                                    0, refSequence ) );

    const auto readRange = readContainer.getFullRange();
    SetRegions setRegions;
    setRegions.insert( Region( "1", 0, 1 ) );
    setRegions.insert( Region( "1", 9, 10 ) );
    setRegions.insert( Region( "1", 18, 20 ) );

    RegionsReads regionSetReads( setRegions, readRange, 0 );

    BOOST_CHECK_EQUAL( 0, std::distance( regionSetReads.begin(), regionSetReads.end() ) );
}

BOOST_AUTO_TEST_CASE( testGetSubRegionReadsShouldThrowIfSubRegionIsNotInContained )
{
    wecall::io::readIntervalTree_t readContainer( 0, 100 );
    const int64_t startPos1 = 1;
    const std::size_t length = 8;
    auto refSequence =
        std::make_shared< wecall::utils::ReferenceSequence >( Region( "1", 0, 20 ), std::string( 20, 'A' ) );
    readContainer.insert( std::make_shared< Read >( BasePairSequence( length, 'A' ), std::string( length, 'Q' ), "0",
                                                    Cigar( std::to_string( length ) + "M" ), 0, startPos1, 0, 0, 0, 0,
                                                    0, refSequence ) );
    const int64_t startPos2 = 10;
    readContainer.insert( std::make_shared< Read >( BasePairSequence( length, 'A' ), std::string( length, 'Q' ), "0",
                                                    Cigar( std::to_string( length ) + "M" ), 0, startPos2, 0, 0, 0, 0,
                                                    0, refSequence ) );

    const auto readRange = readContainer.getFullRange();
    SetRegions setRegions;
    setRegions.insert( Region( "1", 9, 10 ) );
    setRegions.insert( Region( "1", 18, 20 ) );

    SetRegions setRegions2;
    setRegions2.insert( Region( "1", 8, 10 ) );
    setRegions2.insert( Region( "1", 18, 20 ) );

    RegionsReads regionSetReads( setRegions, readRange, 0 );

    BOOST_CHECK_THROW( regionSetReads.getSubRegionReads( setRegions2 ), wecall::utils::wecall_exception );
}

max_stars_repo_name: dylex/wecall

max_issues_repo_name: dylex/wecall

max_forks_repo_name: dylex/wecall