text:
/*
 * kappa_goniometer.cc
 *
 *  Copyright (C) 2013 Diamond Light Source
 *
 *  Author: James Parkhurst
 *
 *  This code is distributed under the BSD license, a copy of which is
 *  included in the root directory of this package.
 */
#include <boost/python.hpp>
#include <boost/python/def.hpp>
#include <boost/algorithm/string.hpp>
#include <boost/shared_ptr.hpp>
#include <string>
#include <sstream>
#include <dxtbx/model/goniometer.h>
#include <dxtbx/model/kappa_goniometer.h>

namespace dxtbx { namespace model { namespace boost_python {

  using namespace boost::python;

  std::string kappa_goniometer_to_string(const KappaGoniometer &goniometer) {
    std::stringstream ss;
    ss << goniometer;
    return ss.str();
  }

  struct KappaGoniometerPickleSuite : boost::python::pickle_suite {
    static
    boost::python::tuple getinitargs(const KappaGoniometer &obj) {
      KappaGoniometer::Direction direction(obj.get_direction());
      std::string direction_str;
      if (direction == KappaGoniometer::PlusY) {
        direction_str = "+y";
      } else if (direction == KappaGoniometer::PlusZ) {
        direction_str = "+z";
      } else if (direction == KappaGoniometer::MinusY) {
        direction_str = "-y";
      } else if (direction == KappaGoniometer::MinusZ) {
        direction_str = "-y";
      } else {
        direction_str = "";
      }

      KappaGoniometer::ScanAxis scan_axis(obj.get_scan_axis());
      std::string scan_axis_str;

      if (scan_axis == KappaGoniometer::Omega) {
        scan_axis_str = "omega";
      } else if (scan_axis == KappaGoniometer::Phi) {
        scan_axis_str = "phi";
      } else {
        scan_axis_str = "";
      }

      return boost::python::make_tuple(
        obj.get_alpha_angle(),
        obj.get_omega_angle(),
        obj.get_kappa_angle(),
        obj.get_phi_angle(),
        direction_str,
        scan_axis_str);
    }
  };

  static boost::shared_ptr<KappaGoniometer> make_kappa_goniometer(
      double alpha, double omega, double kappa, double phi,
      std::string direction_str, std::string scan_axis_str)
  {
    KappaGoniometer::Direction direction = KappaGoniometer::NoDirection;
    boost::algorithm::to_lower(direction_str);
    if (direction_str == "+y") {
      direction = KappaGoniometer::PlusY;
    } else if (direction_str == "+z") {
      direction = KappaGoniometer::PlusZ;
    } else if (direction_str == "-y")  {
      direction = KappaGoniometer::MinusY;
    } else if (direction_str == "-z") {
      direction = KappaGoniometer::MinusZ;
    } else {
      direction = KappaGoniometer::NoDirection;
    }

    KappaGoniometer::ScanAxis scan_axis = KappaGoniometer::NoAxis;
    boost::algorithm::to_lower(scan_axis_str);
    if (scan_axis_str == "omega") {
      scan_axis = KappaGoniometer::Omega;
    } else if (scan_axis_str == "phi") {
      scan_axis = KappaGoniometer::Phi;
    } else {
      scan_axis = KappaGoniometer::NoAxis;
    }

    return boost::shared_ptr<KappaGoniometer>(new KappaGoniometer(
      alpha, omega, kappa, phi, direction, scan_axis));
  }

  void export_kappa_goniometer()
  {
    enum_ <KappaGoniometer::Direction> ("KappaDirection")
      .value("PlusY", KappaGoniometer::PlusY)
      .value("PlusZ", KappaGoniometer::PlusZ)
      .value("MinusY", KappaGoniometer::MinusY)
      .value("MinusZ", KappaGoniometer::MinusZ)
      .export_values();

    enum_ <KappaGoniometer::ScanAxis> ("KappaScanAxis")
      .value("Omega", KappaGoniometer::Omega)
      .value("Phi", KappaGoniometer::Phi)
      .export_values();

    class_ <KappaGoniometer, bases <Goniometer> > ("KappaGoniometer")
      .def(init <double,
                 double,
                 double,
                 double,
                 KappaGoniometer::Direction,
                 KappaGoniometer::ScanAxis> ((
          arg("alpha"),
          arg("omega"),
          arg("kappa"),
          arg("phi"),
          arg("direction"),
          arg("scan_axis"))))
      .def("__init__", make_constructor(&make_kappa_goniometer))
      .def("get_alpha_angle",
        &KappaGoniometer::get_alpha_angle)
      .def("get_omega_angle",
        &KappaGoniometer::get_omega_angle)
      .def("get_kappa_angle",
        &KappaGoniometer::get_kappa_angle)
      .def("get_phi_angle",
        &KappaGoniometer::get_phi_angle)
      .def("get_direction",
        &KappaGoniometer::get_direction)
      .def("get_scan_axis",
        &KappaGoniometer::get_scan_axis)
      .def("get_omega_axis",
        &KappaGoniometer::get_omega_axis)
      .def("get_kappa_axis",
        &KappaGoniometer::get_kappa_axis)
      .def("get_phi_axis",
        &KappaGoniometer::get_phi_axis)
      .def("__str__", &kappa_goniometer_to_string)
      .def_pickle(KappaGoniometerPickleSuite());
  }

}}} // namespace dxtbx::model::boost_python

ext: cc


text:
#include <boost/test/unit_test.hpp>

#include "st_tree.h"
#include "ut_common.h"

BOOST_AUTO_TEST_SUITE(ut_exception)

BOOST_AUTO_TEST_CASE(exceptions) {
    parent_exception px("a");
    orphan_exception ox("b");
    cycle_exception cx("c");
    empty_exception ex("d");
    missing_exception mx("e");

    string t;

    t = px.what();
    BOOST_CHECK_EQUAL(t, "a");

    t = ox.what();
    BOOST_CHECK_EQUAL(t, "b");

    t = cx.what();
    BOOST_CHECK_EQUAL(t, "c");

    t = ex.what();
    BOOST_CHECK_EQUAL(t, "d");

    t = mx.what();
    BOOST_CHECK_EQUAL(t, "e");
}

BOOST_AUTO_TEST_SUITE_END() // ut_exception

ext: cpp


text:
//==============================================================================
//         Copyright 2003 - 2011   LASMEA UMR 6602 CNRS/Univ. Clermont II
//         Copyright 2009 - 2011   LRI    UMR 8623 CNRS/Univ Paris Sud XI
//         Copyright 2012 - 2015   Domagoj Saric, Little Endian Ltd.
//
//          Distributed under the Boost Software License, Version 1.0.
//                 See accompanying file LICENSE.txt or copy at
//                     http://www.boost.org/LICENSE_1_0.txt
//==============================================================================
#ifndef MISSING_FUNCTIONALITY_HPP_INCLUDED
#define MISSING_FUNCTIONALITY_HPP_INCLUDED
//------------------------------------------------------------------------------
#include "operators_lite.hpp" // for compiler_vector()

#include <boost/simd/memory/functions/extract.hpp>
#include <boost/simd/memory/functions/insert.hpp>
#include <boost/simd/memory/functions/load.hpp>
#include <boost/simd/memory/functions/make.hpp>
#include <boost/simd/memory/functions/splat.hpp>
#include <boost/simd/memory/functions/store.hpp>
#include <boost/simd/operator/functions/bitwise_and.hpp>
#include <boost/simd/operator/functions/bitwise_or.hpp>
#include <boost/simd/operator/functions/bitwise_xor.hpp>
#include <boost/simd/operator/functions/complement.hpp>
#include <boost/simd/operator/functions/divides.hpp>
#include <boost/simd/operator/functions/is_less.hpp>
#include <boost/simd/operator/functions/is_greater_equal.hpp>
#include <boost/simd/operator/functions/minus.hpp>
#include <boost/simd/operator/functions/modulo.hpp>
#include <boost/simd/operator/functions/multiplies.hpp>
#include <boost/simd/operator/functions/plus.hpp>
#include <boost/simd/operator/functions/shift_left.hpp>
#include <boost/simd/operator/functions/shift_right.hpp>
#include <boost/simd/operator/functions/unary_minus.hpp>
#include <boost/simd/preprocessor/make_helper.hpp>
#include <boost/simd/swar/functions/details/shuffle.hpp>
#include <boost/simd/swar/functions/deinterleave_first.hpp>
#include <boost/simd/swar/functions/deinterleave_second.hpp>
#include <boost/simd/swar/functions/interleave_first.hpp>
#include <boost/simd/swar/functions/interleave_second.hpp>
#include <boost/simd/swar/functions/reverse.hpp>

#include <boost/simd/memory/iterator.hpp>
#include <boost/simd/sdk/config/arch.hpp>
#include <boost/simd/sdk/simd/extensions.hpp>
#include <boost/simd/sdk/simd/native.hpp>

#include <boost/type_traits/is_const.hpp>

#if defined( __ARM_NEON__ ) || defined( BOOST_SIMD_ARCH_ARM_64 )
#include "arm_neon.h"
#endif // ARM Neon
//------------------------------------------------------------------------------
#if defined( _MSC_VER )

    #define BOOST_NOTHROW_NOALIAS __declspec( nothrow noalias )
    #if ( _MSC_VER >= 1800 ) && ( defined( _M_X64 ) || ( _M_IX86_FP >= 2 ) )
        #define BOOST_FASTCALL __vectorcall
    #else
        #define BOOST_FASTCALL __fastcall
    #endif // _MSC_VER
    #define BOOST_UNREACHABLE_CODE()  BOOST_ASSERT_MSG( false    , "This code should not be reached." ); __assume( false     )
    #define BOOST_ASSUME( condition ) BOOST_ASSERT_MSG( condition, "Assumption broken."               ); __assume( condition )

#elif defined( __GNUC__ )

    /// \note The 'pure' (and especially 'const') attribute(s) seem to be too
    /// strict to mimic the MSVC 'noalias' attribute (which allows first level
    /// indirections).
    ///                                       (09.07.2012.) (Domagoj Saric)
    #define BOOST_NOTHROW_NOALIAS __attribute__(( nothrow ))
    #if defined( BOOST_SIMD_ARCH_X86 ) && !defined( BOOST_SIMD_ARCH_X86_64 )
        #if defined( BOOST_SIMD_HAS_SSE_SUPPORT ) && !defined( __clang__ )
            #define BOOST_FASTCALL __attribute__(( regparm( 3 ), sseregparm ))
        #else
            #define BOOST_FASTCALL __attribute__(( regparm( 3 ) ))
        #endif // __clang__
    #endif // BOOST_SIMD_ARCH_X86

    // http://en.chys.info/2010/07/counterpart-of-assume-in-gcc
    // http://nondot.org/sabre/LLVMNotes/BuiltinUnreachable.txt
    #if ( __clang_major__ >= 2 ) || ( ( ( __GNUC__ * 10 ) + __GNUC_MINOR__ ) >= 45 )
        #define BOOST_UNREACHABLE_CODE()  BOOST_ASSERT_MSG( false    , "This code should not be reached." ); __builtin_unreachable()
        #if defined( __clang__ ) || ( ( ( __GNUC__ * 10 ) + __GNUC_MINOR__ ) < 46 ) || ( ( ( __GNUC__ * 10 ) + __GNUC_MINOR__ ) > 47 )
            // Broken/pessimization in GCC 4.6:
            //  https://bugs.launchpad.net/gcc-linaro/+bug/1020601
            //  http://gcc.gnu.org/bugzilla/show_bug.cgi?id=50385
            //  http://gcc.gnu.org/ml/gcc-patches/2012-07/msg00254.html
            //  http://gcc.gnu.org/bugzilla/show_bug.cgi?id=49054
            #define BOOST_ASSUME( condition ) BOOST_ASSERT_MSG( condition, "Assumption broken." ); do { if ( !( condition ) ) __builtin_unreachable(); } while ( 0 )
        #endif
    #endif

    #define BOOST_HOT  __attribute__(( hot  ))
    #define BOOST_COLD __attribute__(( cold ))

#endif // compiler

#ifndef BOOST_NOTHROW_NOALIAS
    #define BOOST_NOTHROW_NOALIAS
#endif // BOOST_NOTHROW_NOALIAS

#ifndef BOOST_FASTCALL
    #define BOOST_FASTCALL
#endif // BOOST_FASTCALL

#ifndef BOOST_HOT
    #define BOOST_HOT
    #define BOOST_COLD
#endif // BOOST_HOT&COLD

#ifndef BOOST_UNREACHABLE_CODE
    #define BOOST_UNREACHABLE_CODE() BOOST_ASSERT_MSG( false, "This code should not be reached." )
#endif // BOOST_UNREACHABLE_CODE

/// \note We want assume to have verify semantics (i.e. the condition expression
/// should be evaluated in all builds.
///                                           (13.11.2012.) (Domagoj Saric)
#ifndef BOOST_ASSUME
    #define BOOST_ASSUME( condition ) BOOST_VERIFY( condition && "Assumption broken." )
#endif // BOOST_ASSUME
//------------------------------------------------------------------------------
namespace boost
{
//------------------------------------------------------------------------------
namespace simd
{
//------------------------------------------------------------------------------
namespace ext
{
//------------------------------------------------------------------------------

////////////////////////////////////////////////////////////////////////////////
//
// GCC/Clang native vector operators for emulation
//
////////////////////////////////////////////////////////////////////////////////

/// \note Using the below native specializations with Clang 3.3 and 3.4 when
/// targeting the x86 architecture causes assertion failures in mask2logical()
/// during FFT twiddle factor calculation (might have 'something' to do with the
/// complement and/or extract operations). For this reason we skip/disable these
/// specializations when Boost.SIMD/NT2 already provides its own
/// (BOOST_SIMD_DETECTED is defined).
///                                           (05.05.2014.) (Domagoj Saric)
#if !defined( BOOST_SIMD_DETECTED )

#if ( __GNUC__ >= 4 )

#if ( __GNUC_MINOR__ >= 5 ) || defined( __clang__ )
  #define BOOST_SIMD_HAS_VECTORIZABLE_EMULATION

  BOOST_DISPATCH_IMPLEMENT( minus_      , tag::cpu_, (A0), ((simd_<arithmetic_<A0>, BOOST_SIMD_DEFAULT_EXTENSION >))((simd_<arithmetic_<A0>, BOOST_SIMD_DEFAULT_EXTENSION >)) )
  {
    typedef A0 result_type; BOOST_SIMD_FUNCTOR_CALL_REPEAT(2) { return compiler_vector( a0 ) - compiler_vector( a1 ); }
  };
  BOOST_DISPATCH_IMPLEMENT( plus_       , tag::cpu_, (A0), ((simd_<arithmetic_<A0>, BOOST_SIMD_DEFAULT_EXTENSION >))((simd_<arithmetic_<A0>, BOOST_SIMD_DEFAULT_EXTENSION >)) )
  {
    typedef A0 result_type; BOOST_SIMD_FUNCTOR_CALL_REPEAT(2) { return compiler_vector( a0 ) + compiler_vector( a1 ); }
  };
  BOOST_DISPATCH_IMPLEMENT( multiplies_ , tag::cpu_, (A0), ((simd_<arithmetic_<A0>, BOOST_SIMD_DEFAULT_EXTENSION >))((simd_<arithmetic_<A0>, BOOST_SIMD_DEFAULT_EXTENSION >)) )
  {
    typedef A0 result_type; BOOST_SIMD_FUNCTOR_CALL_REPEAT(2) { return compiler_vector( a0 ) * compiler_vector( a1 ); }
  };
  BOOST_DISPATCH_IMPLEMENT( divides_    , tag::cpu_, (A0), ((simd_<arithmetic_<A0>, BOOST_SIMD_DEFAULT_EXTENSION >))((simd_<arithmetic_<A0>, BOOST_SIMD_DEFAULT_EXTENSION >)) )
  {
    typedef A0 result_type; BOOST_SIMD_FUNCTOR_CALL_REPEAT(2) { return compiler_vector( a0 ) / compiler_vector( a1 ); }
  };
  BOOST_DISPATCH_IMPLEMENT( modulo_     , tag::cpu_, (A0), ((simd_<arithmetic_<A0>, BOOST_SIMD_DEFAULT_EXTENSION >))((simd_<arithmetic_<A0>, BOOST_SIMD_DEFAULT_EXTENSION >)) )
  {
    typedef A0 result_type; BOOST_SIMD_FUNCTOR_CALL_REPEAT(2) { return compiler_vector( a0 ) % compiler_vector( a1 ); }
  };
  BOOST_DISPATCH_IMPLEMENT( unary_minus_, tag::cpu_, (A0), ((simd_<arithmetic_<A0>, BOOST_SIMD_DEFAULT_EXTENSION >)) )
  {
    typedef A0 result_type; BOOST_SIMD_FUNCTOR_CALL(1) { return -compiler_vector( a0 ); }
  };
  //...mrmlj....
  typedef native<unsigned int, BOOST_SIMD_DEFAULT_EXTENSION>::native_type _ivec;
  BOOST_DISPATCH_IMPLEMENT( bitwise_and_, tag::cpu_, (A0), ((simd_<arithmetic_<A0>, BOOST_SIMD_DEFAULT_EXTENSION >))((simd_<arithmetic_<A0>, BOOST_SIMD_DEFAULT_EXTENSION >)) )
  {
    typedef A0 result_type; BOOST_SIMD_FUNCTOR_CALL_REPEAT(2) { _ivec const result( (_ivec const &)compiler_vector( a0 ) & (_ivec const &)compiler_vector( a1 ) ); return (result_type const &)result; }
  };
  BOOST_DISPATCH_IMPLEMENT( bitwise_or_ , tag::cpu_, (A0), ((simd_<arithmetic_<A0>, BOOST_SIMD_DEFAULT_EXTENSION >))((simd_<arithmetic_<A0>, BOOST_SIMD_DEFAULT_EXTENSION >)) )
  {
    typedef A0 result_type; BOOST_SIMD_FUNCTOR_CALL_REPEAT(2) { _ivec const result( (_ivec const &)compiler_vector( a0 ) | (_ivec const &)compiler_vector( a1 ) ); return (result_type const &)result; }
  };
  BOOST_DISPATCH_IMPLEMENT( bitwise_xor_, tag::cpu_, (A0), ((simd_<arithmetic_<A0>, BOOST_SIMD_DEFAULT_EXTENSION >))((simd_<arithmetic_<A0>, BOOST_SIMD_DEFAULT_EXTENSION >)) )
  {
    typedef A0 result_type; BOOST_SIMD_FUNCTOR_CALL_REPEAT(2) { _ivec const result( (_ivec const &)compiler_vector( a0 ) ^ (_ivec const &)compiler_vector( a1 ) ); return (result_type const &)result; }
  };
  BOOST_DISPATCH_IMPLEMENT( complement_ , tag::cpu_, (A0), ((simd_<arithmetic_<A0>, BOOST_SIMD_DEFAULT_EXTENSION >)) )
  {
    typedef A0 result_type; BOOST_SIMD_FUNCTOR_CALL(1) { _ivec const result( ~( (_ivec const &)compiler_vector( a0 ) ) ); return (result_type const &)result; }
  };
  BOOST_DISPATCH_IMPLEMENT( make_       , tag::cpu_, (A0), ((target_<simd_<single_<A0>, BOOST_SIMD_DEFAULT_EXTENSION > >)) )
  {
    BOOST_SIMD_MAKE_BODY(4) { return (typename result_type::native_type){ a0, a1, a2, a3 }; }
  };
#endif // GCC 4.5+

#if ( __GNUC_MINOR__ >= 6 ) || defined( __clang__ )
  // shifts by scalar
  BOOST_DISPATCH_IMPLEMENT( shift_left_ , tag::cpu_, (A0), ((simd_<arithmetic_<A0>, BOOST_SIMD_DEFAULT_EXTENSION >))((simd_<arithmetic_<A0>, BOOST_SIMD_DEFAULT_EXTENSION >)) )
  {
    typedef A0 result_type; BOOST_SIMD_FUNCTOR_CALL_REPEAT(2) { return compiler_vector( a0 ) << compiler_vector( a1 ); }
  };
  BOOST_DISPATCH_IMPLEMENT( shift_right_, tag::cpu_, (A0), ((simd_<arithmetic_<A0>, BOOST_SIMD_DEFAULT_EXTENSION >))((simd_<arithmetic_<A0>, BOOST_SIMD_DEFAULT_EXTENSION >)) )
  {
    typedef A0 result_type; BOOST_SIMD_FUNCTOR_CALL_REPEAT(2) { return compiler_vector( a0 ) >> compiler_vector( a1 ); }
  };
#endif // GCC 4.6+

#if ( __GNUC_MINOR__ >= 7 ) || defined( __clang__ )
  // operators ==, !=, <, <=, >, >=
  // splat
#endif // GCC 4.7+

#if ( __GNUC_MINOR__ >= 8 ) || ( defined( __clang__ ) && !defined( BOOST_SIMD_ARCH_ARM ) )
  // subscript access
  /// \note GCC should support subscript access since version 4.6 but they
  /// "forgot" to add this to the C++ frontend:
  /// http://gcc.gnu.org/bugzilla/show_bug.cgi?id=51033
  /// http://gcc.gnu.org/bugzilla/show_bug.cgi?id=53094
  ///                                         (17.12.2012.) (Domagoj Saric)
  /// \note Clang has subscript operator support but not for ARM NEON. It does
  /// not seem to work even when the __vector_size__ syntax is used. ...mrmlj...it does not seem to work at all (even for x86)...
  /// http://clang.llvm.org/docs/LanguageExtensions.html#vectors-and-extended-vectors
  /// http://clang-developers.42468.n3.nabble.com/Native-vectors-types-GCC-vs-NEON-td4035283.html
  ///                                         (28.10.2013.) (Domagoj Saric)

  BOOST_DISPATCH_IMPLEMENT( extract_, tag::cpu_, (A0)(A1), ((simd_<single_<A0>, BOOST_SIMD_DEFAULT_EXTENSION>))(scalar_< integer_<A1> >) )
  {
    typedef float result_type;
    BOOST_FORCEINLINE result_type operator()( A0 const & a0, A1 const a1 ) const { return compiler_vector( a0 )[ static_cast<unsigned int>( a1 ) ]; }
  };
  BOOST_DISPATCH_IMPLEMENT( extract_, tag::cpu_, (A0)(A1), ((simd_<uint32_<A0>, BOOST_SIMD_DEFAULT_EXTENSION>))(scalar_< integer_<A1> >) )
  {
    typedef boost::uint32_t result_type;
    BOOST_FORCEINLINE result_type operator()( A0 const & a0, A1 const a1 ) const { return compiler_vector( a0 )[ static_cast<unsigned int>( a1 ) ]; }
  };
  BOOST_DISPATCH_IMPLEMENT( extract_, tag::cpu_, (A0)(A1), ((simd_<int32_<A0>, BOOST_SIMD_DEFAULT_EXTENSION>))(scalar_< integer_<A1> >) )
  {
    typedef boost::int32_t result_type;
    BOOST_FORCEINLINE result_type operator()( A0 const & a0, A1 const a1 ) const { return compiler_vector( a0 )[ static_cast<unsigned int>( a1 ) ]; }
  };

  BOOST_DISPATCH_IMPLEMENT( insert_, tag::cpu_, (A0)(A1)(A2), (scalar_< arithmetic_<A0> >)((simd_< single_<A1>, BOOST_SIMD_DEFAULT_EXTENSION >))(scalar_< integer_<A2> >) )
  {
    typedef void result_type;
    BOOST_FORCEINLINE result_type operator()( A0 const a0, A1 & a1, A2 const a2 ) const { compiler_vector( a1 )[ static_cast<unsigned int>( a2 ) ] = a0; }
  };
  BOOST_DISPATCH_IMPLEMENT( insert_, tag::cpu_, (A0)(A1)(A2), (scalar_< arithmetic_<A0> >)((simd_< uint32_<A1>, BOOST_SIMD_DEFAULT_EXTENSION >))(scalar_< integer_<A2> >) )
  {
    typedef void result_type;
    BOOST_FORCEINLINE result_type operator()( A0 const a0, A1 & a1, A2 const a2 ) const { compiler_vector( a1 )[ static_cast<unsigned int>( a2 ) ] = a0; }
  };
  BOOST_DISPATCH_IMPLEMENT( insert_, tag::cpu_, (A0)(A1)(A2), (scalar_< arithmetic_<A0> >)((simd_< int32_<A1>, BOOST_SIMD_DEFAULT_EXTENSION >))(scalar_< integer_<A2> >) )
  {
    typedef void result_type;
    BOOST_FORCEINLINE result_type operator()( A0 const a0, A1 & a1, A2 const a2 ) const { compiler_vector( a1 )[ static_cast<unsigned int>( a2 ) ] = a0; }
  };
#endif // GCC 4.8+

#endif // __GNUC__

#endif // !defined( BOOST_SIMD_DETECTED )

////////////////////////////////////////////////////////////////////////////////
//
// ARM NEON
//
// http://software.intel.com/en-us/blogs/2012/12/12/from-arm-neon-to-intel-mmxsse-automatic-porting-solution-tips-and-tricks
// http://software.intel.com/en-us/blogs/2011/08/18/understanding-x86-vs-arm-memory-alignment-on-android
//
////////////////////////////////////////////////////////////////////////////////

#if defined( __ARM_NEON__ ) || defined( BOOST_SIMD_ARCH_ARM_64 )
  BOOST_DISPATCH_IMPLEMENT( reverse_, tag::cpu_, (A0), ((simd_<arithmetic_<A0>, BOOST_SIMD_DEFAULT_EXTENSION >)) )
  {
      typedef A0 result_type;
      BOOST_SIMD_FUNCTOR_CALL(1)
      {
          float32x4_t const half_reversed_vector( vrev64q_f32  ( a0 )                   );
          float32x2_t const result_hi           ( vget_low_f32 ( half_reversed_vector ) );
          float32x2_t const result_lo           ( vget_high_f32( half_reversed_vector ) );
          float32x4_t const result              ( vcombine_f32 ( result_lo, result_hi ) );
          return result;
      }
  };
  BOOST_DISPATCH_IMPLEMENT( deinterleave_first_ , tag::cpu_, (A0)(A1), ((simd_<single_<A0>,BOOST_SIMD_DEFAULT_EXTENSION>))((simd_<single_<A1>,BOOST_SIMD_DEFAULT_EXTENSION>)) )
  {
    typedef A0 result_type;
    //...mrmlj...assume that (de)interleave will always be called in first+second
    //...mrmlj...pairs and that the compiler will issue only a single instruction
    //...mrmlj...(GCC 4.6 does but does not quite generate optimal code for
    //...mrmlj..."N-element vectors/structs")
    //...mrmlj...http://gcc.gnu.org/bugzilla/show_bug.cgi?id=48941
    //...mrmlj...http://gcc.gnu.org/bugzilla/show_bug.cgi?id=51980
    result_type operator()(float32x4_t const a0, float32x4_t const a1) const { return vuzpq_f32( a0, a1 ).val[ 0 ]; }
  };
  BOOST_DISPATCH_IMPLEMENT( deinterleave_second_, tag::cpu_, (A0)(A1), ((simd_<single_<A0>,BOOST_SIMD_DEFAULT_EXTENSION>))((simd_<single_<A1>,BOOST_SIMD_DEFAULT_EXTENSION>)) )
  {
    typedef A0 result_type;
    result_type operator()(float32x4_t const a0, float32x4_t const a1) const { return vuzpq_f32( a0, a1 ).val[ 1 ]; }
  };
  BOOST_DISPATCH_IMPLEMENT( interleave_first_   , tag::cpu_, (A0)(A1), ((simd_<single_<A0>,BOOST_SIMD_DEFAULT_EXTENSION>))((simd_<single_<A1>,BOOST_SIMD_DEFAULT_EXTENSION>)) )
  {
    typedef A0 result_type;
    result_type operator()(float32x4_t const a0, float32x4_t const a1) const { return vzipq_f32( a0, a1 ).val[ 0 ]; }
  };
  BOOST_DISPATCH_IMPLEMENT( interleave_second_  , tag::cpu_, (A0)(A1), ((simd_<single_<A0>,BOOST_SIMD_DEFAULT_EXTENSION>))((simd_<single_<A1>,BOOST_SIMD_DEFAULT_EXTENSION>)) )
  {
    typedef A0 result_type;
    result_type operator()(float32x4_t const a0, float32x4_t const a1) const { return vzipq_f32( a0, a1 ).val[ 1 ]; }
  };
  // ** splat **
  BOOST_DISPATCH_IMPLEMENT( splat_, tag::cpu_, (A0)(A1), (scalar_< fundamental_<A0> >)((target_< simd_< single_<A1>, BOOST_SIMD_DEFAULT_EXTENSION > >)) )
  {
    typedef typename A1::type result_type;
    result_type operator()(A0 const a0, A1) const { return vmovq_n_f32( a0 ); }
  };
  BOOST_DISPATCH_IMPLEMENT( splat_, tag::cpu_, (A0)(A1), (scalar_< fundamental_<A0> >)((target_< simd_< uint32_<A1>, BOOST_SIMD_DEFAULT_EXTENSION > >)) )
  {
    typedef typename A1::type result_type;
    result_type operator()(A0 const a0, A1) const { return vmovq_n_u32( a0 ); }
  };
  BOOST_DISPATCH_IMPLEMENT( splat_, tag::cpu_, (A0)(A1), (scalar_< fundamental_<A0> >)((target_< simd_< int32_<A1>, BOOST_SIMD_DEFAULT_EXTENSION > >)) )
  {
    typedef typename A1::type result_type;
    result_type operator()(A0 const a0, A1) const { return vmovq_n_s32( a0 ); }
  };
  // ** is_less **
  BOOST_DISPATCH_IMPLEMENT( is_less_, tag::cpu_, (A0), ((simd_<single_<A0>,BOOST_SIMD_DEFAULT_EXTENSION>))((simd_<single_<A0>,BOOST_SIMD_DEFAULT_EXTENSION>)) )
  {
    typedef typename meta::as_logical<A0>::type result_type;
    //...mrmlj...see the note in as_simd around the as_integer<> meta-call...
    BOOST_SIMD_FUNCTOR_CALL_REPEAT(2) { return vreinterpretq_s32_u32( vcltq_f32( a0, a1 ) ); }
  };
  // ** is_greater **
  BOOST_DISPATCH_IMPLEMENT( is_greater_equal_, tag::cpu_, (A0), ((simd_<single_<A0>,BOOST_SIMD_DEFAULT_EXTENSION>))((simd_<single_<A0>,BOOST_SIMD_DEFAULT_EXTENSION>)) )
  {
    typedef typename meta::as_logical<A0>::type result_type;
    BOOST_SIMD_FUNCTOR_CALL_REPEAT(2) { return vreinterpretq_s32_u32( vcgeq_f32( a0, a1 ) ); }
  };
  // ** load **
  BOOST_DISPATCH_IMPLEMENT( load_, tag::cpu_, (A0)(A1), (iterator_< scalar_< single_<A0> > >)((target_< simd_< single_<A1>, BOOST_SIMD_DEFAULT_EXTENSION > >)) )
  {
    typedef typename A1::type result_type;
    result_type operator()( A0 const a0, A1 ) const { return vld1q_f32( a0 ); }
  };
  BOOST_DISPATCH_IMPLEMENT( load_, tag::cpu_, (A0)(A1)(A2), (iterator_< scalar_< single_<A0> > >)(scalar_< fundamental_<A1> >)((target_< simd_< single_<A2>, BOOST_SIMD_DEFAULT_EXTENSION > >)) )
  {
    typedef typename A2::type result_type;
    inline result_type operator()( A0 const a0, A1 const a1, A2 ) const { return vld1q_f32( a0 + a1 ); }
  };
  // ** store **
  BOOST_DISPATCH_IMPLEMENT( store_, tag::cpu_, (A0)(A1), ((simd_<single_<A0>, BOOST_SIMD_DEFAULT_EXTENSION>))(iterator_< scalar_< single_<A1> > >) )
  {
    typedef A0 result_type;
    BOOST_SIMD_FUNCTOR_CALL(2) { vst1q_f32( a1, a0 ); return a0; }
  };
  // ** extract **
  BOOST_DISPATCH_IMPLEMENT( extract_, tag::cpu_, (A0)(A1), ((simd_<single_<A0>, BOOST_SIMD_DEFAULT_EXTENSION>))(mpl_integral_< scalar_< integer_<A1> > >) )
  {
    typedef float result_type;
    BOOST_FORCEINLINE result_type operator()( A0 const & a0, A1 ) const { return vgetq_lane_f32( a0, A1::value ); }
  };
  BOOST_DISPATCH_IMPLEMENT( extract_, tag::cpu_, (A0)(A1), ((simd_<uint32_<A0>, BOOST_SIMD_DEFAULT_EXTENSION>))(mpl_integral_< scalar_< integer_<A1> > >) )
  {
    typedef boost::uint32_t result_type;
    BOOST_FORCEINLINE result_type operator()( A0 const & a0, A1 ) const { return vgetq_lane_u32( a0, A1::value ); }
  };
  BOOST_DISPATCH_IMPLEMENT( extract_, tag::cpu_, (A0)(A1), ((simd_<int32_<A0>, BOOST_SIMD_DEFAULT_EXTENSION>))(mpl_integral_< scalar_< integer_<A1> > >) )
  {
    typedef boost::int32_t result_type;
    BOOST_FORCEINLINE result_type operator()( A0 const & a0, A1 ) const { return vgetq_lane_s32( a0, A1::value ); }
  };
  // ** insert **
  BOOST_DISPATCH_IMPLEMENT( insert_, tag::cpu_, (A0)(A1)(A2), (scalar_< arithmetic_<A0> >)((simd_< single_<A1>, BOOST_SIMD_DEFAULT_EXTENSION >))(mpl_integral_< scalar_< integer_<A2> > >) )
  {
    typedef void result_type;
    BOOST_FORCEINLINE result_type operator()( A0 const a0, A1 & a1, A2 ) const { a1 = vsetq_lane_f32( a0, a1, A2::value ); }
  };
  BOOST_DISPATCH_IMPLEMENT( insert_, tag::cpu_, (A0)(A1)(A2), (scalar_< arithmetic_<A0> >)((simd_< uint32_<A1>, BOOST_SIMD_DEFAULT_EXTENSION >))(mpl_integral_< scalar_< integer_<A2> > >) )
  {
    typedef void result_type;
    BOOST_FORCEINLINE result_type operator()( A0 const a0, A1 & a1, A2 ) const { a1 = vsetq_lane_u32( a0, a1, A2::value ); }
  };
  BOOST_DISPATCH_IMPLEMENT( insert_, tag::cpu_, (A0)(A1)(A2), (scalar_< arithmetic_<A0> >)((simd_< int32_<A1>, BOOST_SIMD_DEFAULT_EXTENSION >))(mpl_integral_< scalar_< integer_<A2> > >) )
  {
    typedef void result_type;
    BOOST_FORCEINLINE result_type operator()( A0 const a0, A1 & a1, A2 ) const { a1 = vsetq_lane_s32( a0, a1, A2::value ); }
  };

#endif // __ARM_NEON__

//------------------------------------------------------------------------------
} // namespace ext
//------------------------------------------------------------------------------
namespace details
{
//------------------------------------------------------------------------------

    ////////////////////////////////////////////////////////////////////////////
    // Shuffles
    ////////////////////////////////////////////////////////////////////////////

#if defined( BOOST_SIMD_HAS_SSE_SUPPORT )
    template <> BOOST_FORCEINLINE __m128 shuffle<0, 1, 0, 1>( __m128 const lower, __m128 const upper ) { return _mm_movelh_ps( lower, upper ); }
    template <> BOOST_FORCEINLINE __m128 shuffle<2, 3, 2, 3>( __m128 const lower, __m128 const upper ) { return _mm_movehl_ps( upper, lower ); }

    template <> BOOST_FORCEINLINE __m128 shuffle<0, 0, 1, 1>( __m128 const single_vector ) { return _mm_unpacklo_ps( single_vector, single_vector ); }
    template <> BOOST_FORCEINLINE __m128 shuffle<2, 2, 3, 3>( __m128 const single_vector ) { return _mm_unpackhi_ps( single_vector, single_vector ); }
    template <> BOOST_FORCEINLINE __m128 shuffle<2, 3, 0, 1>( __m128 const single_vector ) { return _mm_movelh_ps( _mm_movehl_ps( single_vector, single_vector ), single_vector ); } // swap halves

    #ifdef BOOST_SIMD_HAS_SSE2_SUPPORT
    template <> BOOST_FORCEINLINE __m128 shuffle<0, 1, 2, 3>( __m128 const lower, __m128 const upper ) { return _mm_castpd_ps( _mm_move_sd( _mm_castps_pd( upper ), _mm_castps_pd( lower ) ) ); }
    #endif // BOOST_SIMD_HAS_SSE2_SUPPORT

    #ifdef BOOST_SIMD_HAS_SSE3_SUPPORT
    template <> BOOST_FORCEINLINE __m128 shuffle<0, 1, 0, 1>( __m128 const single_vector ) { return _mm_castpd_ps( _mm_movedup_pd( _mm_castps_pd( single_vector ) ) ); }
    template <> BOOST_FORCEINLINE __m128 shuffle<0, 0, 2, 2>( __m128 const single_vector ) { return _mm_moveldup_ps( single_vector ); }
    template <> BOOST_FORCEINLINE __m128 shuffle<1, 1, 3, 3>( __m128 const single_vector ) { return _mm_movehdup_ps( single_vector ); }
    #endif // BOOST_SIMD_HAS_SSE3_SUPPORT

    //...zzz...to be continued...
    //_mm_insert_* + _mm_extract_*
    //_mm_blend_*
    //_mm_move_s*
    //_mm_unpackhi_*
    //_mm_unpacklo_*
#elif defined( __clang__ )
    // Clang's builtin shuffle
    template
    <
        unsigned int lower_i0, unsigned int lower_i1,
        unsigned int upper_i0, unsigned int upper_i1,
        typename Vector
    >
    BOOST_FORCEINLINE Vector shuffle( Vector const & __restrict lower, Vector const & __restrict upper )
    {
        return __builtin_shufflevector( compiler_vector( lower ), compiler_vector( upper ), 0 + lower_i0, 0 + lower_i1, 4 + upper_i0, 4 + upper_i1 );
    }

    template
    <
        unsigned int i0, unsigned int i1, unsigned int i2, unsigned int i3,
        typename Vector
    >
    BOOST_FORCEINLINE Vector shuffle( Vector const & __restrict vector )
    {
        return shuffle<i0, i1, i2, i3>( vector, vector );
    }
#elif defined( __GNUC__ ) && ( ( ( __GNUC__ * 10 ) + __GNUC_MINOR__ ) >= 47 ) && !defined( __clang__ )
    // GCC's builtin shuffle
    typedef int shuffle_mask_t __attribute__(( vector_size( 16 ) ));
    template
    <
        unsigned int lower_i0, unsigned int lower_i1,
        unsigned int upper_i0, unsigned int upper_i1,
        typename Vector
    >
    BOOST_FORCEINLINE Vector shuffle( Vector const & __restrict lower, Vector const & __restrict upper )
    {
        /// \note GCC4.8 can crash here.
        /// https://gcc.gnu.org/bugzilla/show_bug.cgi?id=57509
        ///                                   (01.10.2014.) (Domagoj Saric)
        shuffle_mask_t constexpr mask = { 0 + lower_i0, 0 + lower_i1, 4 + upper_i0, 4 + upper_i1 };
        return __builtin_shuffle( compiler_vector( lower ), compiler_vector( upper ), mask );
    }

    template
    <
        unsigned int i0, unsigned int i1, unsigned int i2, unsigned int i3,
        typename Vector
    >
    BOOST_FORCEINLINE Vector shuffle( Vector const & __restrict vector )
    {
        shuffle_mask_t constexpr mask = { i0, i1, i2, i3 };
        return __builtin_shuffle( compiler_vector( vector ), mask );
    }
#elif defined( __ARM_NEON__ ) || defined( BOOST_SIMD_ARCH_ARM_64 )
    // NEON shuffle
    typedef native<float, BOOST_SIMD_DEFAULT_EXTENSION>::native_type builtin_vector_t;
    template
    <
        unsigned int lower_i0, unsigned int lower_i1,
        unsigned int upper_i0, unsigned int upper_i1
    >
    BOOST_FORCEINLINE
    builtin_vector_t shuffle( builtin_vector_t const lower, builtin_vector_t const upper )
    {
        static uint8x8_t const indices_lower =
        {
            lower_i0 * 4 + 0, lower_i0  * 4 + 1, lower_i0  * 4 + 2, lower_i0  * 4 + 3,
            lower_i1 * 4 + 0, lower_i1  * 4 + 1, lower_i1  * 4 + 2, lower_i1  * 4 + 3,
        };
        static uint8x8_t const indices_upper =
        {
            upper_i0 * 4 + 0, upper_i0  * 4 + 1, upper_i0  * 4 + 2, upper_i0  * 4 + 3,
            upper_i1 * 4 + 0, upper_i1  * 4 + 1, upper_i1  * 4 + 2, upper_i1  * 4 + 3,
        };

        uint8x8_t const result_lower_bits( vtbl2_u8( (uint8x8x2_t const &)/*vreinterpretq_u8_f32*/( lower ), indices_lower ) );
        uint8x8_t const result_upper_bits( vtbl2_u8( (uint8x8x2_t const &)/*vreinterpretq_u8_f32*/( upper ), indices_upper ) );

        return vcombine_f32( vreinterpret_f32_u8( result_lower_bits ), vreinterpret_f32_u8( result_upper_bits ) );
    }
    template <unsigned int i0, unsigned int i1, unsigned int i2, unsigned int i3>
    BOOST_FORCEINLINE
    builtin_vector_t shuffle( builtin_vector_t const vector )
    {
        return shuffle<i0, i1, i2, i3>( vector, vector );
    }
    template <>
    builtin_vector_t shuffle<1, 0, 3, 2>( builtin_vector_t const vector ) { return vrev64q_f32( vector ); }
#else // generic shuffle
    template
    <
        unsigned int lower_i0, unsigned int lower_i1,
        unsigned int upper_i0, unsigned int upper_i1,
        typename Vector
    >
    BOOST_FORCEINLINE
    Vector shuffle( Vector const & __restrict lower, Vector const & __restrict upper )
    {
        return make<Vector>
        (
            lower[ lower_i0 ],
            lower[ lower_i1 ],
            upper[ upper_i0 ],
            upper[ upper_i1 ]
        );
    }

    template
    <
        unsigned int i0, unsigned int i1, unsigned int i2, unsigned int i3,
        typename Vector
    >
    BOOST_FORCEINLINE
    Vector shuffle( Vector const & __restrict vector )
    {
        return shuffle<i0, i1, i2, i3>( vector, vector );
    }
#endif // BOOST_SIMD_HAS_SSE_SUPPORT

//------------------------------------------------------------------------------
} // namespace details
//------------------------------------------------------------------------------
} // namespace simd
//------------------------------------------------------------------------------
} // namespace boost
//------------------------------------------------------------------------------

#endif // MISSING_FUNCTIONALITY_HPP_INCLUDED

ext: hpp


text: #include <boost/geometry/geometries/pointing_segment.hpp>

max_stars_repo_name: miathedev/BoostForArduino

max_issues_repo_name: miathedev/BoostForArduino

max_forks_repo_name: miathedev/BoostForArduino


text:
// GMTL is (C) Copyright 2001-2010 by Allen Bierbaum
// Distributed under the GNU Lesser General Public License 2.1 with an
// addendum covering inlined code. (See accompanying files LICENSE and
// LICENSE.addendum or http://www.gnu.org/copyleft/lesser.txt)

// This file was originally part of PyJuggler.

// PyJuggler is (C) Copyright 2002, 2003 by Patrick Hartling
// Distributed under the GNU Lesser General Public License 2.1.  (See
// accompanying file COPYING.txt or http://www.gnu.org/copyleft/lesser.txt)

// Includes ====================================================================
#include <boost/python.hpp>
#include <gmtl/Sphere.h>
#include <gmtl/SphereOps.h>
#include <gmtl/Output.h>
#include <gmtl-pickle.h>

// Using =======================================================================
using namespace boost::python;

// Module ======================================================================
void _Export_Sphere_double()
{
    class_< gmtl::Sphere<double> >("Sphered", init<  >())
        .def(init< const gmtl::Point<double,3> &, const double & >())
        .def(init< const gmtl::Sphere<double> & >())
        .def_readwrite("center", &gmtl::Sphere<double>::mCenter)
        .def_readwrite("radius", &gmtl::Sphere<double>::mRadius)
        .def("getCenter", &gmtl::Sphere<double>::getCenter, return_value_policy< copy_const_reference >())
        .def("getRadius", &gmtl::Sphere<double>::getRadius, return_value_policy< copy_const_reference >())
        .def("setCenter", &gmtl::Sphere<double>::setCenter)
        .def("setRadius", &gmtl::Sphere<double>::setRadius)
        .def("set",
             (gmtl::Sphere<double>& (gmtl::Sphere<double>::*)(const gmtl::Sphere<double>&)) &gmtl::Sphere<double>::operator=,
             return_internal_reference<1>())
        .def_pickle(gmtlPickle::Sphere_pickle<double>())
        .def(self == self)
        .def(self != self)
        .def(self_ns::str(self))
    ;

}


text:
//StandardDeviation_StandardError.hpp
//purpose: header file for standard deriation
//author: bondxue
//version: 1.0 11/22/2017

#ifndef STANDARDDEVIATION_STANDARDERROR_HPP
#define STANDARDDEVIATION_STANDARDERROR_HPP

#include <iostream>
#include <cmath>
#include <vector>

#include <boost/tuple/tuple.hpp> // include tuple class
#include <boost/tuple/tuple_io.hpp> // include I/O for tuple

using namespace std;
using boost::tuple;

// function to obtain standard deviation and standard error
boost::tuple <double, double> get_SD_SE(vector<double> price_vec, double r, double T)
{
	int price_size = price_vec.size();
	double sum_price = 0.0;
	double square_sum_price = 0.0;

	for (int i = 0; i < price_size; i++)
	{
		sum_price += price_vec[i];
		square_sum_price += pow(price_vec[i], 2);
	}

	double temp = sqrt((square_sum_price - pow(sum_price, 2)/double(price_size))/(double(price_size)-1.0)); // use temp to store the square root part in SD formula
	double SD = temp * exp(-r*T);
	double SE = SD / sqrt(double(price_size));

	return boost::tuple<double, double>(SD, SE);
}

#endif

max_stars_repo_path: Part D Monte Carlo Pricing Methods/Exericse D Monte Carlo Pricing Methods/StandardDeviation_StandardError.hpp

max_stars_repo_name: bondxue/Option-Pricing-Model

max_issues_repo_name: bondxue/Option-Pricing-Model

max_forks_repo_name: bondxue/Option-Pricing-Model


text:
// Backup related functions are placed here to keep vital sections of
// code contained while maintaining clean code.

#include "walletdb.h"
#include "wallet.h"
#include "util.h"

#include <boost/filesystem.hpp>
#include <boost/filesystem/fstream.hpp>

#include <fstream>
#include <string>

boost::filesystem::path GetBackupPath();

using namespace boost;

boost::filesystem::path GetBackupPath()
{
    filesystem::path defaultDir = GetDataDir() / "walletbackups";
    return GetArg("-backupdir", defaultDir.string());
}

std::string GetBackupFilename(const std::string& basename, const std::string& suffix = "")
{
    time_t biTime;
    struct tm * blTime;
    time (&biTime);
    blTime = localtime(&biTime);
    char boTime[200];
    strftime(boTime, sizeof(boTime), "%Y-%m-%dT%H-%M-%S", blTime);
    std::string sBackupFilename;
    filesystem::path rpath;
    sBackupFilename = basename + "-" + std::string(boTime);
    if (!suffix.empty())
        sBackupFilename = sBackupFilename + "-" + suffix;
    rpath = GetBackupPath() / sBackupFilename;
    return rpath.string();
}

bool BackupConfigFile(const std::string& strDest)
{
    // Check to see if there is a parent_path in strDest to support custom locations by ui - bug fix

    filesystem::path ConfigSource = GetDataDir() / "gridcoinresearch.conf";
    filesystem::path ConfigTarget = strDest;
    filesystem::create_directories(ConfigTarget.parent_path());
    try
    {
        #if BOOST_VERSION >= 104000
            filesystem::copy_file(ConfigSource, ConfigTarget, filesystem::copy_option::overwrite_if_exists);
        #else
            filesystem::copy_file(ConfigSource, ConfigTarget);
        #endif
        LogPrintf("BackupConfigFile: Copied gridcoinresearch.conf to %s", ConfigTarget.string());
        return true;
    }
    catch(const filesystem::filesystem_error &e)
    {
        LogPrintf("BackupConfigFile: Error copying gridcoinresearch.conf to %s - %s", ConfigTarget.string(), e.what());
        return false;
    }
    return false;
}

bool BackupWallet(const CWallet& wallet, const std::string& strDest)
{
    if (!wallet.fFileBacked)
        return false;

    LOCK(bitdb.cs_db);
    if (!bitdb.mapFileUseCount.count(wallet.strWalletFile) || bitdb.mapFileUseCount[wallet.strWalletFile] == 0)
    {
        // Flush log data to the dat file
        bitdb.CloseDb(wallet.strWalletFile);
        bitdb.CheckpointLSN(wallet.strWalletFile);
        LogPrintf("Issuing lsn_reset for backup file portability.");
        bitdb.lsn_reset(wallet.strWalletFile);
        bitdb.mapFileUseCount.erase(wallet.strWalletFile);

        // Copy wallet.dat
        filesystem::path WalletSource = GetDataDir() / wallet.strWalletFile;
        filesystem::path WalletTarget = strDest;
        filesystem::create_directories(WalletTarget.parent_path());
        if (filesystem::is_directory(WalletTarget))
            WalletTarget /= wallet.strWalletFile;
        try
        {
#if BOOST_VERSION >= 104000
            filesystem::copy_file(WalletSource, WalletTarget, filesystem::copy_option::overwrite_if_exists);
#else
            filesystem::copy_file(WalletSource, WalletTarget);
#endif
            LogPrintf("BackupWallet: Copied wallet.dat to %s", WalletTarget.string());
            return true;
        }
        catch(const filesystem::filesystem_error &e) {
            LogPrintf("BackupWallet: Error copying wallet.dat to %s - %s", WalletTarget.string(), e.what());
            return false;
        }
    }

    return false;
}

bool BackupPrivateKeys(const CWallet& wallet, std::string& sTarget, std::string& sErrors)
{
    if (wallet.IsLocked() || fWalletUnlockStakingOnly)
    {
        sErrors = "Wallet needs to be fully unlocked to backup private keys.";
        return false;
    }
    filesystem::path PrivateKeysTarget = GetBackupFilename("keys.dat");
    filesystem::create_directories(PrivateKeysTarget.parent_path());
    sTarget = PrivateKeysTarget.string();
    std::ofstream myBackup;
    myBackup.open (PrivateKeysTarget.string().c_str());
    std::string sError;
    for(const auto& keyPair : wallet.GetAllPrivateKeys(sError))
    {
        if (!sError.empty())
        {
            sErrors = sError;
            return false;
        }
        myBackup << "Address: " << keyPair.first.ToString() << ", Secret: " << keyPair.second.ToString() << std::endl;
    }
    LogPrintf("BackupPrivateKeys: Backup made to %s", PrivateKeysTarget.string());
    myBackup.close();
    return true;
}

max_stars_repo_name: smoe/Gridcoin-Research

max_issues_repo_name: smoe/Gridcoin-Research

max_forks_repo_name: smoe/Gridcoin-Research


text:
#define BOOST_TEST_MODULE "test_get_or"
#ifdef UNITTEST_FRAMEWORK_LIBRARY_EXIST
#include <boost/test/unit_test.hpp>
#else
#define BOOST_TEST_NO_LIB
#include <boost/test/included/unit_test.hpp>
#endif
#include <toml.hpp>
#include <map>
#include <unordered_map>
#include <list>
#include <deque>
#include <array>

BOOST_AUTO_TEST_CASE(test_get_or_exist)
{
    toml::Boolean  raw_v1(true);
    toml::Integer  raw_v2(42);
    toml::Float    raw_v3(3.14);
    toml::String   raw_v4("hoge");
    toml::Array    raw_v5{2,7,1,8,2};
    toml::Table    raw_v6{{"key", 42}};

    toml::value v1(raw_v1);
    toml::value v2(raw_v2);
    toml::value v3(raw_v3);
    toml::value v4(raw_v4);
    toml::value v5(raw_v5);
    toml::value v6(raw_v6);

    toml::Table table{
        {"value1", v1},
        {"value2", v2},
        {"value3", v3},
        {"value4", v4},
        {"value5", v5},
        {"value6", v6}
    };

    toml::Boolean u1 = toml::get_or(table, "value1", raw_v1);
    toml::Integer u2 = toml::get_or(table, "value2", raw_v2);
    toml::Float   u3 = toml::get_or(table, "value3", raw_v3);
    toml::String  u4 = toml::get_or(table, "value4", raw_v4);
    toml::Array   u5 = toml::get_or(table, "value5", raw_v5);
    toml::Table   u6 = toml::get_or(table, "value6", raw_v6);

    BOOST_CHECK_EQUAL(u1, raw_v1);
    BOOST_CHECK_EQUAL(u2, raw_v2);
    BOOST_CHECK_EQUAL(u3, raw_v3);
    BOOST_CHECK_EQUAL(u4, raw_v4);
    BOOST_CHECK_EQUAL(u5.at(0).cast<toml::value_t::Integer>(), raw_v5.at(0).cast<toml::value_t::Integer>());
    BOOST_CHECK_EQUAL(u5.at(1).cast<toml::value_t::Integer>(), raw_v5.at(1).cast<toml::value_t::Integer>());
    BOOST_CHECK_EQUAL(u5.at(2).cast<toml::value_t::Integer>(), raw_v5.at(2).cast<toml::value_t::Integer>());
    BOOST_CHECK_EQUAL(u5.at(3).cast<toml::value_t::Integer>(), raw_v5.at(3).cast<toml::value_t::Integer>());
    BOOST_CHECK_EQUAL(u5.at(4).cast<toml::value_t::Integer>(), raw_v5.at(4).cast<toml::value_t::Integer>());
    BOOST_CHECK_EQUAL(u6.at("key").cast<toml::value_t::Integer>(), 42);
}

BOOST_AUTO_TEST_CASE(test_get_or_empty)
{
    toml::Boolean  raw_v1(true);
    toml::Integer  raw_v2(42);
    toml::Float    raw_v3(3.14);
    toml::String   raw_v4("hoge");
    toml::Array    raw_v5{2,7,1,8,2};
    toml::Table    raw_v6{{"key", 42}};

    toml::Table    table; // empty!

    toml::Boolean  u1 = toml::get_or(table, std::string("value1"), raw_v1);
    toml::Integer  u2 = toml::get_or(table, std::string("value2"), raw_v2);
    toml::Float    u3 = toml::get_or(table, std::string("value3"), raw_v3);
    toml::String   u4 = toml::get_or(table, std::string("value4"), raw_v4);
    toml::Array    u5 = toml::get_or(table, std::string("value5"), raw_v5);
    toml::Table    u6 = toml::get_or(table, std::string("value6"), raw_v6);

    BOOST_CHECK_EQUAL(u1, raw_v1);
    BOOST_CHECK_EQUAL(u2, raw_v2);
    BOOST_CHECK_EQUAL(u3, raw_v3);
    BOOST_CHECK_EQUAL(u4, raw_v4);
    BOOST_CHECK_EQUAL(u5.at(0).cast<toml::value_t::Integer>(), raw_v5.at(0).cast<toml::value_t::Integer>());
    BOOST_CHECK_EQUAL(u5.at(1).cast<toml::value_t::Integer>(), raw_v5.at(1).cast<toml::value_t::Integer>());
    BOOST_CHECK_EQUAL(u5.at(2).cast<toml::value_t::Integer>(), raw_v5.at(2).cast<toml::value_t::Integer>());
    BOOST_CHECK_EQUAL(u5.at(3).cast<toml::value_t::Integer>(), raw_v5.at(3).cast<toml::value_t::Integer>());
    BOOST_CHECK_EQUAL(u5.at(4).cast<toml::value_t::Integer>(), raw_v5.at(4).cast<toml::value_t::Integer>());
    BOOST_CHECK_EQUAL(u6.at("key").cast<toml::value_t::Integer>(), 42);
}

max_issues_repo_name: giangrocker/wrinkledface

max_forks_repo_name: giangrocker/wrinkledface


text:
// Boost.Geometry (aka GGL, Generic Geometry Library)

// Copyright (c) 2007-2014 Barend Gehrels, Amsterdam, the Netherlands.
// Copyright (c) 2008-2014 Bruno Lalande, Paris, France.
// Copyright (c) 2009-2014 Mateusz Loskot, London, UK.

// This file was modified by Oracle on 2014-2020.
// Modifications copyright (c) 2014-2020, Oracle and/or its affiliates.

// Contributed and/or modified by Menelaos Karavelas, on behalf of Oracle

// Parts of Boost.Geometry are redesigned from Geodan's Geographic Library
// (geolib/GGL), copyright (c) 1995-2010 Geodan, Amsterdam, the Netherlands.

// 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_STRATEGIES_DEFAULT_LENGTH_RESULT_HPP
#define BOOST_GEOMETRY_STRATEGIES_DEFAULT_LENGTH_RESULT_HPP

#include <boost/variant/variant_fwd.hpp>

#include <boost/geometry/core/coordinate_type.hpp>
#include <boost/geometry/util/select_most_precise.hpp>
#include <boost/geometry/util/type_traits.hpp>

namespace boost { namespace geometry
{

namespace resolve_strategy
{

// NOTE: The implementation was simplified greately preserving the old
//   behavior. In general case the result types of Strategies should be
//   taken into account.
// It would probably be enough to use distance_result and
//   default_distance_result here.

// Workaround for VS2015
#if defined(_MSC_VER) && (_MSC_VER < 1910)
template
<
    typename Geometry,
    bool IsGeometry = util::is_geometry<Geometry>::value
>
struct coordinate_type
    : geometry::coordinate_type<Geometry>
{};
template <typename Geometry>
struct coordinate_type<Geometry, false>
{
    typedef long double type;
};
#endif

template <typename ...Geometries>
struct default_length_result
{
    typedef typename select_most_precise
        <
            typename coordinate_type<Geometries>::type...,
            long double
        >::type type;
};

} // namespace resolve_strategy

namespace resolve_variant
{

template <typename Geometry>
struct default_length_result
    : resolve_strategy::default_length_result<Geometry>
{};

template <BOOST_VARIANT_ENUM_PARAMS(typename T)>
struct default_length_result<boost::variant<BOOST_VARIANT_ENUM_PARAMS(T)> >
    : resolve_strategy::default_length_result<BOOST_VARIANT_ENUM_PARAMS(T)>
{};

} // namespace resolve_variant

/*!
    \brief Meta-function defining return type of length function
    \ingroup length
    \note Length of a line of integer coordinates can be double.
        So we take at least a double. If Big Number types are used,
        we take that type.

 */
template <typename Geometry>
struct default_length_result
    : resolve_variant::default_length_result<Geometry>
{};

}} // namespace boost::geometry

#endif // BOOST_GEOMETRY_STRATEGIES_DEFAULT_LENGTH_RESULT_HPP


text:
#include <Eigen/Dense>
#include <opencv2/opencv.hpp>

#define CVUI_IMPLEMENTATION

#include "cvui.h"

#define WINDOW_NAME "CVUI Hello World!"

typedef Eigen::Array<bool,Eigen::Dynamic,1> ArrayXb;

int main(void)
{
    cv::Mat lena = cv::imread("../data/sss.png");
    cv::Mat frame = lena.clone();
    int low_threshold = 50, high_threshold = 150;

    cv::namedWindow(WINDOW_NAME);
    cvui::init(WINDOW_NAME);

    ArrayXb modes = ArrayXb::Constant(3,false);

    bool& ANNOTATE = modes(0);
    bool& DELETE = modes(1);
    bool& MERGE = modes(2);

    ANNOTATE = true;

    std::vector<cv::Point> points;

    while (true)
    {

        bool a_mode = ANNOTATE;
        bool d_mode = DELETE;
        bool m_mode = MERGE;

        bool undo_flag = false, redo_flag = false;

        cvui::window(frame, 10, 50, 180, 180, "Mode");
        cvui::checkbox(frame, 15, 80, "Annotate", &a_mode);
        cvui::checkbox(frame, 15, 120, "Delete", &d_mode);
        cvui::checkbox(frame, 15, 160, "Merge", &m_mode);

        cvui::window(frame, 10, 200, 180, 180, "Revert");
        cvui::checkbox(frame, 15, 240, "Undo", &undo_flag);
        cvui::checkbox(frame, 80, 240, "Redo", &redo_flag);

        cvui::printf(frame, 15, 280, 0.4, 0xff0000, "Button click count: %d", 3);

        cvui::update();
        cv::imshow(WINDOW_NAME, frame);

        if (cv::waitKey(30) == 27) {
            break;
        }

        if (undo_flag)
        {
            printf("UNDO!\n");
            continue;
        } else if (redo_flag)
        {
            printf("REDO!\n");
            continue;
        } else if (a_mode && !ANNOTATE)
        {
            modes = ArrayXb::Constant(3,false);
            ANNOTATE = true;
        }
        else if (d_mode && !DELETE)
        {
            modes = ArrayXb::Constant(3,false);
            DELETE = true;
        }
        else if (m_mode && !MERGE)
        {
            modes = ArrayXb::Constant(3,false);
            MERGE = true;
        }

        if (ANNOTATE)
        {
            if (cvui::mouse(cvui::DOWN)) {
                // Position the rectangle at the mouse pointer.
                cv::Point pt;
                pt.x = cvui::mouse().x;
                pt.y = cvui::mouse().y;
                cv::circle( frame, pt, 3, cv::Scalar(0,0,255), 3, 8, 0 );
            }
        } else if (DELETE) {

        } else if (MERGE) {

        }
        // cvui::trackbar(frame, 15, 110, 165, &low_threshold, 5, 150);
        // cvui::trackbar(frame, 15, 180, 165, &high_threshold, 80, 300);

    }
    return 0;
}


text:
// Copyright 2013-2020 Lawrence Livermore National Security, LLC and other
// HavoqGT Project Developers. See the top-level LICENSE file for details.
//
// SPDX-License-Identifier: MIT

#ifndef HAVOQGT_MPI_GEN_PREFERENTIAL_ATTACHMENT_EDGE_LIST_HPP_INCLUDED
#define HAVOQGT_MPI_GEN_PREFERENTIAL_ATTACHMENT_EDGE_LIST_HPP_INCLUDED

#include <havoqgt/mpi.hpp>
#include <havoqgt/detail/hash.hpp>
#include <havoqgt/detail/preferential_attachment.hpp>
#include <boost/random.hpp>
#include <algorithm>

namespace havoqgt {

template <typename EdgeType>
void gen_preferential_attachment_edge_list(std::vector<EdgeType>& local_edges,
                                           uint64_t in_base_seed,
                                           uint64_t in_node_scale,
                                           uint64_t in_edge_scale,
                                           double in_beta,
                                           double in_prob_rewire,
                                           MPI_Comm in_comm)
{
  namespace ad = havoqgt::detail;
  int mpi_rank, mpi_size;
  CHK_MPI( MPI_Comm_rank(in_comm, &mpi_rank) );
  CHK_MPI( MPI_Comm_size(in_comm, &mpi_size) );

  //
  // Calc global number of nodes and edges
  uint64_t global_num_nodes = uint64_t(1) << in_node_scale;
  uint64_t global_num_edges = uint64_t(1) << in_edge_scale;
  uint64_t k = global_num_edges / global_num_nodes;
  uint64_t edges_per_rank = global_num_edges / mpi_size;

  ad::preferential_attachment_helper<uint64_t> pa(k, global_num_edges, in_beta,
                                             in_base_seed*mpi_rank + mpi_rank);

  //
  // Generate inital pa edges.  Includes unresolved links
  double init_time_start = MPI_Wtime();
  local_edges.resize(edges_per_rank);
  for(uint64_t i=0; i<edges_per_rank; ++i) {
    uint64_t edge_index = uint64_t(mpi_rank) + i*uint64_t(mpi_size);
    local_edges[i] = pa.gen_edge(edge_index);
  }
  double init_time_end = MPI_Wtime();
  if(mpi_rank == 0) {
    std::cout << "Initial rng for edges took " << init_time_end - init_time_start
              << " seconds. " << std::endl;
  }

  //
  // We loop until all edges are resolved
  uint64_t iteration_count(1), count_missing(0), count_total_mising(0);
  do {
    //
    // Count number still missing
    for(uint64_t i=0; i<edges_per_rank; ++i) {
      if(pa.is_pointer(local_edges[i].second)) {
        ++count_total_mising;
      }
    }

    count_missing = 0;
    double time_start = MPI_Wtime();
    //
    // Generate vectors to exchange
    std::vector<std::vector<uint64_t> > tmp_send_to_rank(mpi_size);
    std::vector<std::vector<uint64_t> > tmp_mark_send_to_rank(mpi_size);
    uint64_t count_to_send(0);
    for(uint64_t i=0; i<local_edges.size(); ++i) {
      if(pa.is_pointer(local_edges[i].second)) {
        int owner = pa.value_of_pointer(local_edges[i].second) % mpi_size;
        tmp_mark_send_to_rank[owner].push_back(i);
        tmp_send_to_rank[owner].push_back(pa.value_of_pointer(local_edges[i].second));
        ++count_to_send;
      }
    }
    //
    // Combine send/recv vectors
    std::vector<uint64_t> to_send(count_to_send); to_send.reserve(1);
    std::vector<uint64_t> mark_to_send(count_to_send);
    std::vector<int>      sendcnts(mpi_size,0); sendcnts.reserve(1);
    to_send.clear(); mark_to_send.clear();
    for(int i = 0; i < mpi_size; ++i) {
      for(size_t j = 0; j < tmp_send_to_rank[i].size(); ++j) {
        to_send.push_back(tmp_send_to_rank[i][j]);
        mark_to_send.push_back(tmp_mark_send_to_rank[i][j]);
      }
      sendcnts[i] = tmp_send_to_rank[i].size();
    }
    //
    // Release memory from temp vectors
    {
      std::vector<std::vector<uint64_t> > empty;
      tmp_send_to_rank.swap(empty);
    }
    {
      std::vector<std::vector<uint64_t> > empty;
      tmp_mark_send_to_rank.swap(empty);
    }
    //
    // Exchange vectors
    std::vector<uint64_t> to_recv; // not sized
    std::vector<int>      recvcnts; // not sized
    mpi_all_to_all(to_send, sendcnts, to_recv, recvcnts, MPI_COMM_WORLD);
    //
    // Look up pointers, pointer jump!
    for(size_t i=0; i<to_recv.size(); ++i) {
      uint64_t local_index = to_recv[i]/mpi_size;
      to_recv[i] = local_edges[local_index].second;
    }
    //
    // Return exchange vectors
    mpi_all_to_all(to_recv, recvcnts, to_send, sendcnts, MPI_COMM_WORLD);
    //
    // Return new pointers to marked location
    for(size_t i=0; i<to_send.size(); ++i) {
        local_edges[ mark_to_send[i] ].second = to_send[i];;
    }
    //
    // Count number still missing
    for(uint64_t i=0; i<edges_per_rank; ++i) {
      if(pa.is_pointer(local_edges[i].second)) {
        ++count_missing;
      }
    }
    count_missing = mpi_all_reduce(count_missing, std::plus<uint64_t>(), MPI_COMM_WORLD);

    //
    // Iteration ouput
    double time_end = MPI_Wtime();
    if(mpi_rank == 0) {
      std::cout << "Iteration " << iteration_count << " took "
                << time_end - time_start << " seconds.   "
                << count_missing << " still missing. " << std::endl;
    }
    ++iteration_count;
  } while(count_missing > 0);
  //
  // Output total nuumber of global exchanges
  count_total_mising = mpi_all_reduce(count_total_mising, std::plus<uint64_t>(), MPI_COMM_WORLD);
  if(mpi_rank == 0) {
    std::cout << "Total missing (how much data globally exchanged) = " << count_total_mising << std::endl;
  }

  //
  // Randomly rewire
  if(in_prob_rewire > double(0)) {
    boost::mt19937 rng(in_base_seed + uint64_t(mpi_rank) * 3ULL);
    boost::random::uniform_int_distribution<> rand_node(0,global_num_nodes-1);
    boost::random::uniform_01<> rand_real;
    for(size_t i=0; i<local_edges.size(); ++i) {
      if(rand_real(rng) < in_prob_rewire) {
        EdgeType rand_edge(rand_node(rng), rand_node(rng));
        local_edges[i] = rand_edge;
      }
    }
  }

  //
  // Scramble edges
  for(size_t i=0; i<local_edges.size(); ++i) {
    //TODO:  This needs a mod because we never exactly make the correct
    //number of vertices.   We need a better solution!
    local_edges[i].first  %= global_num_nodes;
    local_edges[i].second %= global_num_nodes;
    local_edges[i].first  = ad::hash_nbits(local_edges[i].first,  in_node_scale);
    local_edges[i].second = ad::hash_nbits(local_edges[i].second, in_node_scale);
  }

  // //
  // // Symmetrizing b/c PA is always undirected.
  // uint64_t old_size = local_edges.size();
  // local_edges.reserve(old_size * 2);
  // for(uint64_t i=0; i<old_size; ++i) {
  //   EdgeType edge;
  //   edge.first = local_edges[i].second;
  //   edge.second = local_edges[i].first;
  //   local_edges.push_back( edge );
  // }

  // //
  // // Shuffle edges because we need to mix the hubs in for future partitioning
  // std::random_shuffle(local_edges.begin(), local_edges.end());
}

} //end namespace havoqgt

#endif //end HAVOQGT_MPI_GEN_PREFERENTIAL_ATTACHMENT_EDGE_LIST_HPP_INCLUDED

max_stars_repo_name: niklas-uhl/havoqgt

max_issues_repo_name: niklas-uhl/havoqgt

max_forks_repo_name: niklas-uhl/havoqgt


text:
//
// ip/impl/network_v6.ipp
// ~~~~~~~~~~~~~~~~~~~~~~
//
// Copyright (c) 2003-2019 Christopher M. Kohlhoff (chris at kohlhoff dot com)
// Copyright (c) 2014 Oliver Kowalke (oliver dot kowalke at gmail dot com)
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//

#ifndef BOOST_ASIO_IP_IMPL_NETWORK_V6_IPP
#define BOOST_ASIO_IP_IMPL_NETWORK_V6_IPP

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

#include <boost/asio/detail/config.hpp>
#include <climits>
#include <cstdio>
#include <cstdlib>
#include <stdexcept>
#include <boost/asio/error.hpp>
#include <boost/asio/detail/throw_error.hpp>
#include <boost/asio/detail/throw_exception.hpp>
#include <boost/asio/ip/network_v6.hpp>

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

namespace boost {
namespace asio {
namespace ip {

network_v6::network_v6(const address_v6& addr, unsigned short prefix_len)
  : address_(addr),
    prefix_length_(prefix_len)
{
  if (prefix_len > 128)
  {
    std::out_of_range ex("prefix length too large");
    boost::asio::detail::throw_exception(ex);
  }
}

BOOST_ASIO_DECL address_v6 network_v6::network() const BOOST_ASIO_NOEXCEPT
{
  address_v6::bytes_type bytes(address_.to_bytes());
  for (std::size_t i = 0; i < 16; ++i)
  {
    if (prefix_length_ <= i * 8)
      bytes[i] = 0;
    else if (prefix_length_ < (i + 1) * 8)
      bytes[i] &= 0xFF00 >> (prefix_length_ % 8);
  }
  return address_v6(bytes, address_.scope_id());
}

address_v6_range network_v6::hosts() const BOOST_ASIO_NOEXCEPT
{
  address_v6::bytes_type begin_bytes(address_.to_bytes());
  address_v6::bytes_type end_bytes(address_.to_bytes());
  for (std::size_t i = 0; i < 16; ++i)
  {
    if (prefix_length_ <= i * 8)
    {
      begin_bytes[i] = 0;
      end_bytes[i] = 0xFF;
    }
    else if (prefix_length_ < (i + 1) * 8)
    {
      begin_bytes[i] &= 0xFF00 >> (prefix_length_ % 8);
      end_bytes[i] |= 0xFF >> (prefix_length_ % 8);
    }
  }
  return address_v6_range(
      address_v6_iterator(address_v6(begin_bytes, address_.scope_id())),
      ++address_v6_iterator(address_v6(end_bytes, address_.scope_id())));
}

bool network_v6::is_subnet_of(const network_v6& other) const
{
  if (other.prefix_length_ >= prefix_length_)
    return false; // Only real subsets are allowed.
  const network_v6 me(address_, other.prefix_length_);
  return other.canonical() == me.canonical();
}

std::string network_v6::to_string() const
{
  boost::system::error_code ec;
  std::string addr = to_string(ec);
  boost::asio::detail::throw_error(ec);
  return addr;
}

std::string network_v6::to_string(boost::system::error_code& ec) const
{
  using namespace std; // For sprintf.
  ec = boost::system::error_code();
  char prefix_len[16];
#if defined(BOOST_ASIO_HAS_SECURE_RTL)
  sprintf_s(prefix_len, sizeof(prefix_len), "/%u", prefix_length_);
#else // defined(BOOST_ASIO_HAS_SECURE_RTL)
  sprintf(prefix_len, "/%u", prefix_length_);
#endif // defined(BOOST_ASIO_HAS_SECURE_RTL)
  return address_.to_string() + prefix_len;
}

network_v6 make_network_v6(const char* str)
{
  return make_network_v6(std::string(str));
}

network_v6 make_network_v6(const char* str, boost::system::error_code& ec)
{
  return make_network_v6(std::string(str), ec);
}

network_v6 make_network_v6(const std::string& str)
{
  boost::system::error_code ec;
  network_v6 net = make_network_v6(str, ec);
  boost::asio::detail::throw_error(ec);
  return net;
}

network_v6 make_network_v6(const std::string& str,
    boost::system::error_code& ec)
{
  std::string::size_type pos = str.find_first_of("/");

  if (pos == std::string::npos)
  {
    ec = boost::asio::error::invalid_argument;
    return network_v6();
  }

  if (pos == str.size() - 1)
  {
    ec = boost::asio::error::invalid_argument;
    return network_v6();
  }

  std::string::size_type end = str.find_first_not_of("0123456789", pos + 1);
  if (end != std::string::npos)
  {
    ec = boost::asio::error::invalid_argument;
    return network_v6();
  }

  const address_v6 addr = make_address_v6(str.substr(0, pos), ec);
  if (ec)
    return network_v6();

  const int prefix_len = std::atoi(str.substr(pos + 1).c_str());
  if (prefix_len < 0 || prefix_len > 128)
  {
    ec = boost::asio::error::invalid_argument;
    return network_v6();
  }

  return network_v6(addr, static_cast<unsigned short>(prefix_len));
}

#if defined(BOOST_ASIO_HAS_STRING_VIEW)

network_v6 make_network_v6(string_view str)
{
  return make_network_v6(static_cast<std::string>(str));
}

network_v6 make_network_v6(string_view str,
    boost::system::error_code& ec)
{
  return make_network_v6(static_cast<std::string>(str), ec);
}

#endif // defined(BOOST_ASIO_HAS_STRING_VIEW)

} // namespace ip
} // namespace asio
} // namespace boost

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

#endif // BOOST_ASIO_IP_IMPL_NETWORK_V6_IPP

ext: ipp

max_stars_repo_name: Netis/packet-agent

max_issues_repo_name: Netis/packet-agent

max_forks_repo_name: Netis/packet-agent


text:
//
// server.cpp
// ~~~~~~~~~~

#if 1
#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
#include <stdlib.h>

#include <boost/bind.hpp>
#include <boost/array.hpp>
#include <boost/shared_ptr.hpp>
#include <boost/enable_shared_from_this.hpp>
#include <boost/asio.hpp>
#include <boost/thread.hpp>

#include <timer.h>
#include <MocaSocket.h>
#include <opencv2/opencv.hpp>
using boost::asio::ip::tcp;

//================
// Sensor
//================
class Sensor {
public:
	std::string	serial;

	int			sensorID;
	int			serverID;				// node computer ID
	int			deviceID;				// local device ID

	bool		connected;

	Sensor() : sensorID(-1), serverID(-1), deviceID(-1), connected(false){
	}
};

//================
// Server
//================
class Server {
public:
	int									portID;
	int									serverID;
	std::vector<int>					connectedSensorIDs;

	boost::shared_ptr<tcp::acceptor>	acceptor;

	Socket								socket;

	std::string							recorded_timestep;

public:
	Server() : portID(-1), serverID(-1) {
	}

	void start_accept(boost::asio::io_service& io_service)
	{
		acceptor.reset(new tcp::acceptor(io_service, tcp::endpoint(tcp::v4(), portID)));
		socket.socket.reset(new tcp::socket(io_service));

		acceptor->async_accept(
			*socket.socket,
			boost::bind(
			&Server::handle_accept,
			this,
			socket.socket,
			boost::asio::placeholders::error
			)
			);
	}

	void handle_accept(boost::shared_ptr<tcp::socket> &socket, const boost::system::error_code &error)
	{
		std::cout << "[SYSTEM] :: SERVER - CLIENT connection has been set up !!!!" << std::endl;
		std::cout << "[SYSTEM] :: Client connected from << " << socket->remote_endpoint().address().to_string().c_str() << " >>" << std::endl;

		if (error) {
			return;
		}

		//image_session_->teststart();
		// Maybe put time sychronization code here...
		boost::asio::ip::tcp::no_delay option(true);
		socket->set_option(option);

		//DEBUG
		std::cout << "COMMAND DEBUG INSTRUCTION..." << std::endl;
		std::cout << "request device" << std::endl;
		std::cout << "start cap" << std::endl;
		std::cout << "rframe ID" << std::endl;
	}

	void wait_new_connection(boost::asio::io_service& io_service) {
		socket.close();
		while (!socket.socket->is_open()) {
			start_accept(io_service);
		}
	}
};

//================
// SensorNetwork
//================
class SensorNetwork {
public:
	std::vector<Sensor>			sensors;
	std::vector<Server>			servers;
	Timer						timer;

	int							withRGB;
public:
	SensorNetwork() {
		// server
		servers.resize(4);
		for (int i = 0; i < servers.size(); i++) {
			servers[i].serverID = i;
		}

		servers[0].portID = 1113;
		servers[1].portID = 1114;
		servers[2].portID = 1115;
		servers[3].portID = 1116;

		// sensor
		sensors.resize(24);
		for (int i = 0; i < sensors.size(); i++) {
			sensors[i].sensorID = i;
		}

		sensors[0].serial = "506904442542";
		sensors[1].serial = "008427750247";
		sensors[2].serial = "501778742542";
		sensors[3].serial = "006039350247";
		sensors[4].serial = "501916642542";
		sensors[5].serial = "026340651247";
		sensors[6].serial = "007697650247";
		sensors[7].serial = "025150151247";

		withRGB = 0;
	}

	void StartAccept(boost::asio::io_service &io_service) {
		for (int i = 0; i < servers.size(); i++) {
			servers[i].start_accept(io_service);
		}
	}

	void WaitForNewConnection(boost::asio::io_service &io_service) {
		for (int i = 0; i < servers.size(); i++) {
			servers[i].wait_new_connection(io_service);
		}
	}

	int FindSensor(const std::string &serial) {
		for (int i = 0; i < sensors.size(); i++) {
			if (sensors[i].serial == serial) {
				return i;
			}
		}
		return -1;
	}

	int FindServer(int port) {
		for (int i = 0; i < servers.size(); i++) {
			if (servers[i].portID == port) {
				return i;
			}
		}
		return -1;
	}

	template<class T>
	bool RequestFrame(int sensorID, std::vector<T> &buffer){
		// locate
		int serverID = sensors[sensorID].serverID;
		int deviceID = sensors[sensorID].deviceID;

		if (serverID == -1 || deviceID == -1){
			return false;
		}
		Server *server = &servers[serverID];

		// request frame on
		if (!server->socket.write("rfo", 4)) {
			return false;
		}

		// send deviceID
		if (!server->socket.write(&deviceID, 4)) {
			return false;
		}

		//read frame
		server->socket.read_buffer(buffer);

		//send
		server->socket.write("rcv", 4);
	}

	void RequestFramesPeriod(int serverID, float start, float end) {
		Server *server = &servers[serverID];

		// request frame : rpf : start : end
		if (!server->socket.write("rpf", 4)) {
			std::cout << "[ERROR IN TRANS] :: send to port" << server->portID << " failed..." << std::endl;
		}
		if (!server->socket.write(&start, sizeof(float))){
			std::cout << "[ERROR IN TRANS] :: send to port" << server->portID << " failed..." << std::endl;
		}
		if (!server->socket.write(&end, sizeof(float))){
			std::cout << "[ERROR IN TRANS] :: send to port" << server->portID << " failed..." << std::endl;
		}

		for (int i = 0; i < server->connectedSensorIDs.size(); ++i) {
			//////////////////////////////////////////////////////
			int targetSensorID = server->connectedSensorIDs[i];
			if (sensors[targetSensorID].serverID != serverID || sensors[targetSensorID].deviceID != i) {
				std::cout << "[REQUEST PERIOD FRAMES] :: can't find sensorID in current node com device info buffer @NODE PORT: " << serverID << std::endl;
				continue;
			}
			std::cout
				<< "sensor : " << sensors[targetSensorID].sensorID << ", "
				<< "server : " << sensors[targetSensorID].serverID << ", "
				<< "device : " << sensors[targetSensorID].deviceID << std::endl;

			//////////////////////////////////////////////////////
			{
				char data[4];
				if (!server->socket.read(&data, 4)) {
					std::cout << "[Error:REQUEST PERIOD FRAMES] read tag" << std::endl;
				}

				if (std::string(data) != "kin") {
					std::cout << "[Error:REQUEST PERIOD FRAMES] data tag" << data << std::endl;
					continue;
				}
			}

			//////////////////////////////////////////////////////
			// read index buffer
			std::vector<double> index_data;
			if (!server->socket.read_buffer(index_data)) {
				std::cout << "[ERROR IN read_buffer] :: read from port " << server->portID << "failed..." << std::endl;
			}
			std::cout << "[TotalFrame] :: " << index_data.size() << std::endl;
			if (index_data.empty()) {
				std::cout << "[ERROR IN data_index buffer] :: index_Data size is empty... " << std::endl;
			}

			//////////////////////////////////////////////////////
			// save index buffer to file
			{
				char saveDepIdx_path[MAX_PATH];
				sprintf(saveDepIdx_path, "ReceivedData/%s", server->recorded_timestep);
				CreateDirectory(saveDepIdx_path, NULL);
				sprintf(saveDepIdx_path, "ReceivedData/%s/K%d", server->recorded_timestep, targetSensorID);
				CreateDirectory(saveDepIdx_path, NULL);
				sprintf(saveDepIdx_path, "ReceivedData/%s/K%d/tIdx.txt", server->recorded_timestep, targetSensorID);

				std::filebuf fb;
				fb.open(saveDepIdx_path, std::ios::out);

				char timestr[128];
				for (int k = 0; k < index_data.size(); ++k) {
					std::ostream os(&fb);
					sprintf(timestr, "%.2f", index_data[k]);
					os << timestr << std::endl;
				}

				fb.close();
			}

#if 1
			//////////////////////////////////////////////////////
			// recv images
			{

				std::vector<char> image_buffer;

				std::cout << "[index data] :: " << index_data.size() << std::endl;
				for (int j = 0; j < index_data.size() * 2; ++j) {  //for jpeg+bin
				//for (int j = 0; j < index_data.size(); ++j) {
					// read filename
					std::vector<char> filename;
					server->socket.read_buffer(filename);
					std::cout << "[DEBUG :: RECV IMGS] :: Current file name is: " << filename.data() << std::endl;

					// read image buffer
					server->socket.read_buffer(image_buffer);

					// open file
					char openpath[MAX_PATH];
					sprintf(openpath, "ReceivedData/%s/K%d/%s", server->recorded_timestep, targetSensorID, filename.data());
					std::ofstream output_file(openpath, std::ios_base::binary); //output_file.open();
					if (!output_file)
					{
						std::cout << "[OFSTREAM OUTPUT] :: failed to open " << openpath << std::endl;
						return;
					}

					// save image buffer to file
					output_file.write(image_buffer.data(), image_buffer.size());
					if (output_file.tellp() == (std::fstream::pos_type)(std::streamsize)image_buffer.size()) {
						std::cout << "[OFSTREAM OUTPUT] :: received " << output_file.tellp() << " bytes.\n";
					}
				}
			}
#endif
			// send rcv tag
			server->socket.write("rcv", 4);
		}
	}

	// Request all frames
	void RequestFramesOnClip(int serverID) {
		Server *server = &servers[serverID];

		// request frame : rpf : start : end
		if (!server->socket.write("gis", 4)) {
			std::cout << "[ERROR IN GIS] :: send to port" << server->portID << " failed..." << std::endl;
		}

		for (int i = 0; i < server->connectedSensorIDs.size(); ++i) {
			//////////////////////////////////////////////////////
			int targetSensorID = server->connectedSensorIDs[i];
			if (sensors[targetSensorID].serverID != serverID || sensors[targetSensorID].deviceID != i) {
				std::cout << "[REQUEST PERIOD FRAMES] :: can't find sensorID in current node com device info buffer @NODE PORT: " << serverID << std::endl;
				continue;
			}
			std::cout
				<< "sensor : " << sensors[targetSensorID].sensorID << ", "
				<< "server : " << sensors[targetSensorID].serverID << ", "
				<< "device : " << sensors[targetSensorID].deviceID << std::endl;

			//////////////////////////////////////////////////////
			{
				char data[4];
				if (!server->socket.read(&data, 4)) {
					std::cout << "[Error:REQUEST PERIOD FRAMES] read tag" << std::endl;
				}

				if (std::string(data) != "kin") {
					std::cout << "[Error:REQUEST PERIOD FRAMES] data tag" << data << std::endl;
					continue;
				}
			}

			//////////////////////////////////////////////////////
			// read index buffer
			std::vector<double> index_data;
			if (!server->socket.read_buffer(index_data)) {
				std::cout << "[ERROR IN read_buffer] :: read from port " << server->portID << "failed..." << std::endl;
			}
			std::cout << "[TotalFrame] :: " << index_data.size() << std::endl;
			if (index_data.empty()) {
				std::cout << "[ERROR IN data_index buffer] :: index_Data size is empty... " << std::endl;
			}

			//////////////////////////////////////////////////////
			// save index buffer to file
			{
				char saveDepIdx_path[MAX_PATH];
				sprintf(saveDepIdx_path, "ReceivedData/%s", server->recorded_timestep);
				CreateDirectory(saveDepIdx_path, NULL);
				sprintf(saveDepIdx_path, "ReceivedData/%s/K%d", server->recorded_timestep, targetSensorID);
				CreateDirectory(saveDepIdx_path, NULL);
				sprintf(saveDepIdx_path, "ReceivedData/%s/K%d/tIdx.txt", server->recorded_timestep, targetSensorID);

				std::filebuf fb;
				fb.open(saveDepIdx_path, std::ios::out);

				char timestr[128];
				for (int k = 0; k < index_data.size(); ++k) {
					std::ostream os(&fb);
					sprintf(timestr, "%.2f", index_data[k]);
					os << timestr << std::endl;
				}

				fb.close();
			}

			//////////////////////////////////////////////////////
			// recv images
			{

				std::vector<char> image_buffer;

				std::cout << "[index data] :: " << index_data.size() << std::endl;
				for (int j = 0; j < index_data.size() * withRGB; ++j) {  //for jpeg+bin
				//for (int j = 0; j < index_data.size(); ++j) {
					// read filename
					std::vector<char> filename;
					server->socket.read_buffer(filename);
					std::cout << "[DEBUG :: RECV IMGS] :: Current file name is: " << filename.data() << std::endl;

					// read image buffer
					server->socket.read_buffer(image_buffer);

					// open file
					char openpath[MAX_PATH];
					sprintf(openpath, "ReceivedData/%s/K%d/%s", server->recorded_timestep, targetSensorID, filename.data());
					std::ofstream output_file(openpath, std::ios_base::binary); //output_file.open();
					if (!output_file)
					{
						std::cout << "[OFSTREAM OUTPUT] :: failed to open " << openpath << std::endl;
						return;
					}

					// save image buffer to file
					output_file.write(image_buffer.data(), image_buffer.size());
					if (output_file.tellp() == (std::fstream::pos_type)(std::streamsize)image_buffer.size()) {
						std::cout << "[OFSTREAM OUTPUT] :: received " << output_file.tellp() << " bytes.\n";
					}
				}
			}
			// send rcv tag
			//server->socket.write("rcv", 4);
		}
	}

	void RequestDevices(int serverID) {
		std::cout << "Request Devices : on NODE COM " << serverID << std::endl;

		Server *server = &servers[serverID];

		// request
		if (!server->socket.write("rdv", 4)) {
			return;
		}

		// num of sensors
		int numLocalSensors = 0;
		if (!server->socket.read(&numLocalSensors, 4)) {
			return;
		}
		std::cout << "[ :: ] TOTAL DEV NUM IS " << numLocalSensors << std::endl;

		// sensor info
		std::vector<char> buffer(numLocalSensors * 16);
		if (!server->socket.read(buffer.data(), buffer.size())) {
			return;
		}

		// parse serial and device id
		const char *ptr = buffer.data();
		for (int i = 0; i < numLocalSensors; ++i) {
			int deviceID;
			memcpy(&deviceID, ptr, 4);
			ptr += 4;

			char serial[16];
			memcpy(serial, ptr, 12);
			serial[12] = 0;
			ptr += 12;

			int sensorID = FindSensor(serial);
			if (sensorID >= 0) {
				sensors[sensorID].serverID = serverID;
				sensors[sensorID].deviceID = deviceID;
				// store current node com avaliable sensorID for fast indexing
				server->connectedSensorIDs.push_back(sensorID);

				printf("%d : ( %d, %d ) : %s\n", sensorID, serverID, deviceID, serial);
			}
		}
	}

	void StartRecord(int serverID) {
		std::cout << "Start Capture : " << serverID << std::endl;
		servers[serverID].socket.write("scp", 4);
		tm ct;
		_getsystime(&ct);
		char time[MAX_PATH];
		sprintf(time, "%d%d%d%d%d%d", ct.tm_year + 1900, ct.tm_mon + 1, ct.tm_mday, ct.tm_hour, ct.tm_min, ct.tm_sec);
		servers[serverID].socket.write_string(time);

		servers[serverID].recorded_timestep = time;
	}

	void StartRecordDepthOnly(int serverID) {
		std::cout << "Start Capture <<Depth Only>>: " << serverID << std::endl;
		servers[serverID].socket.write("sdp", 4);
		tm ct;
		_getsystime(&ct);
		char time[MAX_PATH];
		sprintf(time, "%d%d%d%d%d%d", ct.tm_year + 1900, ct.tm_mon + 1, ct.tm_mday, ct.tm_hour, ct.tm_min, ct.tm_sec);
		servers[serverID].socket.write_string(time);

		servers[serverID].recorded_timestep = time;
	}

	void StopRecord(int serverID) {
		std::cout << "Stop Capture : " << serverID << std::endl;
		servers[serverID].socket.write("stp", 4);
	}

	void MeasureLatecy(int serverID){
		Server *server = &servers[serverID];
		// request
		if (!server->socket.write("syn", 4)) {
			return;
		}

		for (int i = 0; i < 450; i++) {
			double readti = 0.0;
			server->socket.read(&readti, 8);
			//std::cout << ".........test.................." << readti << std::endl;
			server->socket.write(&readti, 8);
		}
		double cur_origin = timer.start;
		server->socket.write(&cur_origin, 8);
		//server->socket.read(&c_send_timestep, 8);
		//std::cout << "[SERVER :: MEASURE LATENCY] :: client -> server latency is: " << latency / 500 << std::endl;

	}
};

const int TEST_NODE = 1;
int main()
{
	try
	{
		// Maybe need 2 io_services, one for client func, one for server func
		boost::asio::io_service io_service;
		// Idea from http://thisthread.blogspot.com/2011/04/multithreading-with-asio.html
		boost::asio::io_service::work work(io_service);
		//boost::asio::strand strand(io_service);

		SensorNetwork sn;
		sn.timer.Start();
		sn.StartAccept(io_service);

		boost::thread_group threads;
		// Service must be run before detecting cmd input
		for (int i = 0; i < 4; i++) {
			threads.create_thread(boost::bind(&boost::asio::io_service::run, &io_service));
		}

		char cmd_buf[1024];
		std::vector<char> recv_buf; size_t buf_size;
		while (std::cin.getline(cmd_buf, 1024)) {
			std::string cmd_ = cmd_buf;
			if (cmd_.find("rframe") < cmd_.size()){
				std::string num_str = cmd_.substr(cmd_.find("rframe") + 7, cmd_.size() - cmd_.find("rframe") - 7);
				int globalID = std::atoi(num_str.c_str());
				std::cout << "[SYSTEM] :: SENDING 'REQUEST FRAME ON' GLOBAL ID: " << globalID << std::endl;
				sn.RequestFrame(globalID, recv_buf);
			}
			else if (cmd_.find("rpframe") < cmd_.size()){
				if (cmd_.size() > 8){
					std::string num_str = cmd_.substr(cmd_.find("rpframe") + 8, cmd_.size() - cmd_.find("rpframe") - 8);
					size_t space = num_str.find_first_of(",");
					std::string start_str = num_str.substr(0, space);
					std::cout << start_str << std::endl;
					std::string end_str = num_str.substr(space + 1, num_str.size());
					std::cout << end_str << std::endl;
					float start = (float)std::atof(start_str.c_str());
					float end = (float)std::atof(end_str.c_str());
					std::cout << "[SYSTEM] :: SENDING 'REQUEST FRAME ON PERIOD'  Period time: " << space << std::endl;
					for (int i = 0; i < TEST_NODE; i++){
						sn.RequestFramesPeriod(i, start, end);
					}
				}
				else{
					std::cout << "[USAGE] :: rpframe start-time,end-time " << std::endl;
				}
			}
			else if (cmd_ == "getimgs") {
				std::cout << "[SYSTEM] :: SENDING 'GET IMAGES' COMMAND... " << std::endl;
				sn.RequestFramesOnClip(0);
				sn.withRGB = 0;  // reset
			}
			else if (cmd_ == "request frame"){
				// io_service.post(boost::bind(&SensorNetwork::RequestFrame, &sn, 0));
			}
			else if (cmd_ == "rd"){
				sn.RequestDevices(0);
				//sn.MeasureLatecy(0);
				//sn.RequestDevices(1);
				//double readti = 0.0;
				//sn.servers[0].socket.read(&readti, 8);
				//std::cout << ".........test.................." << readti << std::endl;
				//sn.servers[0].socket.write(&readti, 8);
			}
			else if (cmd_ == "start cap") {
				std::cout << "[SYSTEM] :: SENDING 'START CAP' COMMAND... " << std::endl;
				sn.StartRecord(0);
				sn.withRGB = 2;
			}
			else if (cmd_ == "sdp") {
				std::cout << "[SYSTEM] :: SENDING 'START CAP' COMMAND... " << std::endl;
				sn.StartRecordDepthOnly(0);
				sn.withRGB = 1;
			}
			else if (cmd_ == "stop cap") {
				std::cout << "[SYSTEM] :: SENDING 'STOP CAPTURE' COMMAND... " << std::endl;
				// stp
				sn.StopRecord(0);
			}
			else if (cmd_ == "sc") {
				std::cout << "[SYSTEM] :: SENDING 'SET CONFIG' COMMAND... " << std::endl;
				//checkcmd.Print("Set config time is...");
				// cnf
				//image_session_->send_config(id_);
				sn.timer.Print("dfdksajfkkdsaf");
			}
			else if (cmd_ == "sn") {
				//std::cout << "[SYSTEM] :: SENDING 'SYNCHRONIZE NODES' COMMAND... " << std::endl;
				//checkcmd.Print("Synchronize nodes cmd time is...");
				// syn
				sn.MeasureLatecy(0);

			}
			else {
				std::cout << "[SYSTEM] :: [Port]" << " :: INVALID COMMAND.. Please enter command again..." << std::endl;

			}
			//io_service.post(boost::bind(&tcp_server::parsing_cmd, &server0, cmd_line));
		}

		io_service.stop();
		threads.join_all();
	}

	catch (std::exception& e)
	{
		std::cerr << e.what() << std::endl;
	}

	return 0;
}
#endif

max_stars_repo_name: Edwinzero/Fusion

max_issues_repo_name: icg-moca/MOCA

max_forks_repo_name: icg-moca/MOCA


text:
/*=========================================================================

 VectorField.hpp
 GeoShoot

 Author: Alexandre Martin, Laurent Risser
 Copyright © 2016 scalexm, lrisser. All rights reserved.

 Disclaimer: This software has been developed for research purposes only, and hence should
 not be used as a diagnostic tool. In no event shall the authors or distributors
 be liable to any direct, indirect, special, incidental, or consequential
 damages arising of the use of this software, its documentation, or any
 derivatives thereof, even if the authors have been advised of the possibility
 of such damage.

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

#ifndef VECTOR_FIELD_HPP
#define VECTOR_FIELD_HPP

#define BOOST_COMPUTE_DEBUG_KERNEL_COMPILATION
#include <boost/compute.hpp>
#include <vector>
#include <array>
#include <type_traits>

template<size_t Row, size_t Col>
using Matrix = std::array<std::array<float, Col>, Row>;

namespace compute = boost::compute;

struct CPUPolicy {
    using Container = std::vector<float>;

    template<class... Args>
    static Container MakeContainer(const compute::context &, Args && ... args) {
        return Container(std::forward<Args>(args)...);
    }
};

struct GPUPolicy {
    using Container = compute::vector<float>;

    template<class... Args>
    static Container MakeContainer(const compute::context & ctx, Args && ... args) {
        return Container(std::forward<Args>(args)..., ctx);
    }
};

template<size_t Dim, class DevicePolicy>
class GenericVectorField {
private:
    template<size_t OtherDim, class OtherDevicePolicy>
    friend class GenericVectorField;

    int NX_ = 0, NY_ = 0, NZ_ = 0;
    int NXtY_ = 0, NXtYtZ_ = 0;
    Matrix<4, 4> Image2World_, World2Image_;

    size_t Channel_ = 0;

    std::vector<typename DevicePolicy::Container> VecField_;

    template<size_t Direction>
    size_t Index(int x, int y, int z) const {
        return Direction * NXtYtZ_ + z * NXtY_ + y * NX_ + x;
    }

public:
    using Iterator = typename DevicePolicy::Container::iterator;
    using ConstIterator = typename DevicePolicy::Container::const_iterator;

    GenericVectorField() = default;

    GenericVectorField(int NX, int NY, int NZ, int NT = 1,
                       const compute::context & ctx = compute::system::default_context())
                       : NX_ { NX }, NY_ { NY }, NZ_ { NZ },
                         NXtY_ { NX * NY }, NXtYtZ_ { NX * NY * NZ },
                         VecField_(NT) {
        for (auto t = 0; t < NT; ++t)
            VecField_[t] = DevicePolicy::MakeContainer(ctx, Dim * NX * NY * NZ);

        memset(&Image2World_[0], 0, 16 * sizeof(float));
        Image2World_[0][0] = Image2World_[1][1] = Image2World_[2][2] = Image2World_[3][3] = 1;
        World2Image_ = Image2World_;
    }

    const Matrix<4, 4> & Image2World() const {
        return Image2World_;
    }

    const Matrix<4, 4> & World2Image() const {
        return World2Image_;
    }

    void ChangeChannel(size_t c) {
        Channel_ = c;
    }

    // emplace a vector at point (x, y, z)
    void P(std::array<float, Dim> values, int x, int y, int z) {
        auto index = Index<0>(x, y, z);
        for (auto dir = 0; dir < Dim; ++dir)
            VecField_[Channel_][dir * NXtYtZ_ + index] = values[dir];
    }

    // add a vector at point (x, y, z)
    void Add(std::array<float, Dim> values, int x, int y, int z) {
        auto index = Index<0>(x, y, z);
        for (auto dir = 0; dir < Dim; ++dir)
            VecField_[Channel_][dir * NXtYtZ_ + index] += values[dir];
    }

    // get value at point (x, y, z) and at direction Direction
    template<size_t Direction>
    float G(int x, int y, int z) const {
        static_assert(Direction < Dim, "Direction should be less than Dim");
        return VecField_[Channel_][Index<Direction>(x, y, z)];
    }

    // set all voxels to value given by cst
    void Fill(float cst) {
        static_assert(std::is_same<DevicePolicy, CPUPolicy>::value, "only on CPU");
        std::fill(Begin(), End(), cst);
    }

    void Fill(float cst, compute::command_queue & queue) {
        compute::fill(Begin(), End(), cst, queue);
    }

    float MaxAbsVal() const {
        static_assert(std::is_same<DevicePolicy, CPUPolicy>::value, "only on CPU");
        auto max = 0.f;
        for (auto && x : VecField_) {
            auto xa = fabs(x);
            if (xa > max)
                max = xa;
        }
        return max;
    }

    float MaxAbsVal(compute::command_queue & queue) const {
        auto it = compute::minmax_element(Begin(), End(), compute::less<float>(), queue);
        return std::max(fabs(it.first.read(queue)), fabs(it.second.read(queue)));
    }

    int NX() const {
        return NX_;
    }

    int NY() const {
        return NY_;
    }

    int NZ() const {
        return NZ_;
    }

    int NT() const {
        return VecField_.size();
    }

    compute::int4_ Dims() const {
        return { NX_, NY_, NZ_, 0 };
    }

    Iterator Begin() {
        return VecField_[Channel_].begin();
    }

    ConstIterator Begin() const {
        return VecField_[Channel_].begin();
    }

    Iterator End() {
        return VecField_[Channel_].end();
    }

    ConstIterator End() const {
        return VecField_[Channel_].end();
    }

    typename DevicePolicy::Container & Buffer() {
        return VecField_[Channel_];
    }

    const typename DevicePolicy::Container & Buffer() const {
        return VecField_[Channel_];
    }

    /* not perfect regarding memory efficiency, should be rewritten if needed */
    static GenericVectorField Read(const std::array<const char *, Dim> & paths) {
        static_assert(std::is_same<DevicePolicy, CPUPolicy>::value, "only on CPU");
        GenericVectorField<Dim, DevicePolicy> field;

        for (auto dim = 0; dim < Dim; ++dim) {
            auto dir = GenericVectorField<1, CPUPolicy>::Read({ paths[dim] });

            if (dim != 0) {
                auto eq_x = dir.NX() == field.NX();
                auto eq_y = dir.NY() == field.NY();
                auto eq_z = dir.NZ() == field.NZ();
                auto eq_t = dir.NT() == field.NT();
                if (!eq_x || !eq_y || !eq_z || !eq_t)
                    throw std::invalid_argument { "directions do not have the same dimensions" };
            }

            if (dim == 0) {
                field = GenericVectorField<Dim, DevicePolicy> {
                    dir.NX(),
                    dir.NY(),
                    dir.NZ(),
                    dir.NT()
                };
                field.Image2World_ = std::move(dir.Image2World_);
                field.World2Image_ = std::move(dir.World2Image_);
            }

            for (auto t = 0; t < dir.NT(); ++t) {
                dir.ChangeChannel(t);
                std::copy(dir.Begin(), dir.End(), &field.VecField_[t][dim * field.NXtYtZ_]);
            }
        }

        return field;
    }

    void Write(const std::array<const char *, Dim> & paths) const {
        static_assert(std::is_same<DevicePolicy, CPUPolicy>::value, "only on CPU");
        for (auto dim = 0; dim < Dim; ++dim) {
            GenericVectorField<1, CPUPolicy> dir { NX_, NY_, NZ_, NT() };

            for (auto t = 0; t < NT(); ++t) {
                dir.ChangeChannel(t);
                std::copy(
                    &VecField_[t][dim * NXtYtZ_],
                    &VecField_[t][dim * NXtYtZ_] + NXtYtZ_,
                    dir.Begin()
                );
            }
            dir.Image2World_ = Image2World_;
            dir.Write({ paths[dim] });
        }
    }
};

template<size_t Dim>
using GPUVectorField = GenericVectorField<Dim, GPUPolicy>;

template<size_t Dim>
using VectorField = GenericVectorField<Dim, CPUPolicy>;

using GPUScalarField = GPUVectorField<1>;
using ScalarField = VectorField<1>;

template<>
ScalarField ScalarField::Read(const std::array<const char *, 1> & path);

template<>
void ScalarField::Write(const std::array<const char *, 1> & path) const;

#endif

max_stars_repo_name: scalexm/GeoShoot

max_issues_repo_name: scalexm/GeoShoot

max_forks_repo_name: scalexm/GeoShoot