text:
#ifndef NOMINMAX
#define NOMINMAX
#endif

#include <iostream>
#include <sstream>
#include <random>
#include <cstdint>

#include <functional>
#include "taus88.hpp"
// #include <boost/random/taus88.hpp>
#include <boost/random/mersenne_twister.hpp>
#include <boost/random/seed_seq.hpp>
#include <boost/random/random_device.hpp>
#include "seed_seq_fe.hpp"
#include "xoroshiro.hpp"
#include "complementary_multiply_with_carry.hpp"

#include <pcg/pcg_random.hpp>
#include "xoroshiro_meo.hpp"

#define PCG_USE_ZEROCHECK_ROTATE_IDIOM 1

#include "autotimer.hpp"

std::uint64_t integer_hash ( std::uint64_t x )
{
    x = ( ( x >> 32 ) ^ x ) * std::uint64_t { 0xDE17C195AA959A81 };
    x = ( ( x >> 32 ) ^ x ) * std::uint64_t { 0xDE17C195AA959A81 };
    x = ( ( x >> 32 ) ^ x ) * std::uint64_t { 0xDE17C195AA959A81 };
    return ( x >> 32 ) ^ x;
}

#define VOLATILE volatile

template<typename Generator>
struct GeneratorCache : private Generator {

    using result_type = typename Generator::result_type;
    using size_type = std::size_t;

    GeneratorCache ( ) : Generator ( ) { }
    GeneratorCache ( result_type v_ ) : Generator ( v_ ) { }
    template<typename SeedSeq>
    GeneratorCache ( const SeedSeq & seq_ ) : Generator ( seq_ ) { }
    template<typename It>
    GeneratorCache ( It & first_, It last_ ) : Generator ( first_, last_ ) { }

    result_type operator ( ) ( ) noexcept {

        if ( m_index == data_size ( ) ) {

            Generator::generate ( std::begin ( m_data ), std::end ( m_data ) );
            // std::generate ( std::begin ( m_data ), std::end ( m_data ), [ this ] ( ) { return Generator::operator ( ) ( ); } );
            m_index = 1;

            return m_data [ 0 ];
        }

        return m_data [ m_index++ ];
    }

    static constexpr result_type min ( ) noexcept { return Generator::min ( ); }
    static constexpr result_type max ( ) noexcept { return Generator::max ( ); }
    static constexpr std::size_t data_size ( ) noexcept { return 64 / sizeof ( result_type ); }

    result_type m_data [ data_size ( ) ];
    size_type m_index = data_size ( );
};

int main ( ) {

    boost::random::seed_seq_fe256 seq_fe { INT32_MAX, 3466, 456454, 23423 };

    std::uint64_t cnt = 1;

    xoroshiro128plus64 gen1 ( 0xBE1C0467EBA5FAC1 );
    xoroshiro128plus64 gen2 ( 0xBE2C0467EBA5FAC2 );
    xoroshiro128plus64 gen3 ( 0xBE3C0467EBA5FAC3 );
    xoroshiro128plus64 gen4 ( 0xBE4C0467EBA5FAC4 );
    xoroshiro128plus64 gen5 ( 0xBE5C0467EBA5FAC5 );

    while ( cnt-- ) {

        std::int64_t cnt1 = 1'000'000'000, cnt2 = cnt1, cnt3 = cnt1, cnt4 = cnt1, cnt5 = cnt1;

        VOLATILE std::uint64_t acc1 = 0;

        {
            degski::AutoTimer t ( degski::milliseconds );

            while ( cnt1-- )
                acc1 += std::uniform_int_distribution<std::uint64_t> ( ) ( gen1 );
        }

        VOLATILE std::uint64_t acc2 = 0;

        {
            degski::AutoTimer t ( degski::milliseconds );

            while ( cnt2-- )
                acc2 += std::uniform_int_distribution<std::uint64_t> ( ) ( gen2 );
        }

        VOLATILE std::uint64_t acc3 = 0;

        {
            degski::AutoTimer t ( degski::milliseconds );

            while ( cnt3-- )
                acc3 += std::uniform_int_distribution<std::uint64_t> ( ) ( gen3 );
        }

        VOLATILE std::uint64_t acc4 = 0;

        {
            degski::AutoTimer t ( degski::milliseconds );

            while ( cnt4-- )
                acc4 += std::uniform_int_distribution<std::uint64_t> ( ) ( gen4 );
        }

        VOLATILE std::uint64_t acc5 = 0;

        {
            degski::AutoTimer t ( degski::milliseconds );

            while ( cnt5-- )
                acc5 += std::uniform_int_distribution<std::uint64_t> ( ) ( gen5 );
        }

        std::cout << std::boolalpha << !( ( acc2 == acc1 ) && ( acc3 == acc2 ) && ( acc4 == acc3 ) && ( acc5 == acc4 ) ) << '\n';
    }

    exit ( 0 );

#if 0

    std::cout << std::boolalpha << ( gen1 == gen2 ) << "\n";

    std::stringstream s;

    gen1 ( );
    gen1 ( );
    gen1 ( );
    gen1 ( );
    gen1 ( );
    gen1 ( );
    gen1 ( );
    gen1 ( );
    gen1 ( );
    gen1 ( );
    gen1 ( );
    gen1 ( );
    gen1 ( );
    gen1 ( );
    gen1 ( );
    gen1 ( );
    gen1 ( );
    gen1 ( );
    gen1 ( );
    gen1 ( );
    gen1 ( );
    gen1 ( );
    gen1 ( );

    s << gen1;

    std::cout << gen1 << '\n';
    std::cout << gen2 << '\n';

    s >> gen2;

    std::cout << gen2 << '\n';

    std::cout << std::boolalpha << ( gen1 == gen2 ) << "\n";

    std::seed_seq seq { INT32_MAX,0,0,0,0,0,0,346,456454,23423 };

    boost::random::xoroshiro128plus gen4 ( seq );

    std::vector<int> inp { 0, 5, 0, 0, 1, 3,4,43,3,4,4,4,45,43,463,63,63,356,36,25,141,144,0, 5, 0, 0, 1, 3,4,43,3,4,4,4,45,43,463,63,63,356,36,25,141,144 };

    auto start = std::begin ( inp );

    boost::random::xoroshiro128plus gen5 ( start, std::end(inp) );

    std::uint64_t seed = 0;

    std::vector<seq::result_type> v;
    v.reserve ( seq.size ( ) );
    seq.param ( std::back_inserter ( v ) );

    int shift = 32;

    for ( auto i : v ) {
        // std::cout << seed << '\n';
        seed ^= boost::random::detail::xoroshiro_integer_hash ( ( static_cast<std::uint64_t>( i ) << ( shift ^= int { 32 } ) ) );
    }

    seed = 0;

    for ( std::uint32_t i = 1; i < 1025; ++i ) {
        seed ^= boost::random::detail::xoroshiro_integer_hash ( ( static_cast<std::uint64_t>( i ) << ( shift ^= int { 32 } ) ) ^ seed );
        std::cout << seed << '\n';
    }

#endif

}

std::uint32_t Q1 [ 256 ], c1 = 362436;

std::uint32_t MWC256 ( ) {

    std::uint64_t t, a = 1540315826LL;
    static std::size_t i = 255;
    unsigned long x;
    i = ( i + 1 ) & 255;
    t = a * Q1 [ i ] + c1;
    c1 = ( t >> 32 );
    x = t + c1;
    if (x < c1) { x++; c1++; }
    return ( Q1 [ i ] = x );
}

std::uint32_t Q2 [ 4096 ], c2 = 362436;

std::uint32_t CMWC4096 ( ) {

    std::uint64_t t, a = 18782LL;
    static std::size_t i = 4095;
    std::uint32_t x, r = 0xfffffffe;
    i = ( i + 1 ) & 4095;
    t = a*Q2 [ i ] + c2;
    c2 = ( t >> 32 );
    x = t + c2;
    if ( x < c2 ) { x++; c2++; }
    return ( Q2 [ i ] = r - x );
}

int main436463466 ( ) {

    std::seed_seq seq { INT32_MAX, 3466, 456454, 23423 };

    boost::random::taus88 gen ( seq );

    std::cout << gen << "\n\n";

    return 0;
}

int main34342 ( ) {

    typedef boost::random::taus88 Engine;
    // typedef std::ranlux48 Engine;

    boost::random::random_device rng1;
    Engine eng1 ( rng1 );

    std::cout << eng1 << '\n';

    //std::random_device rng2;
    //Engine eng2 ( rng2 );

    //std::cout << eng2 << '\n';

    boost::random::mt19937 rng3;
    Engine eng3 ( rng3 );

    std::cout << eng3 << '\n';

    //std::mt19937 rng4;
    //Engine eng4 ( rng4 );

    //std::cout << eng4 << '\n';

    boost::random::seed_seq seq5 { INT32_MAX, 3466, 456454, 23423 };
    Engine eng5 ( seq5 );

    std::cout << eng5 << '\n';

    boost::random::seed_seq_fe256 seq6 { INT32_MAX, 3466, 456454, 23423 };
    Engine eng6 ( seq6 );

    std::cout << eng6 << '\n';

    std::seed_seq seq7 { INT32_MAX, 3466, 456454, 23423 };
    Engine eng7 ( seq7 );

    std::cout << eng7 << '\n';

    Engine eng8 ( eng7 ); // Copy constructor...

    std::cout << eng8 << '\n';

    Engine eng9 ( 4563546 );

    std::cout << eng9 << '\n';

#if 0

    exit ( 0 );

    boost::random::seed_seq seq { INT32_MAX, 3466, 456454, 23423 };

    boost::random::cmwc4 gen ( 6568 );

    std::int64_t cnt = 1'000'000'000;

    std::uint64_t acc = 0;

    {
        degski::AutoTimer t ( degski::milliseconds );

        while ( cnt-- )
        acc += std::uniform_int_distribution<std::uint32_t> ( ) ( gen );
    }

    std::cout << gen << '\n';

#endif
    return 0;
}

// https://genix.wordpress.com/2014/07/29/detecting-the-presence-of-a-member-function/

namespace boost {
namespace random {

template<typename G, std::enable_if_t<boost::random::traits::is_generator<G>::value>* = nullptr>
using generator = G;
template<typename D, std::enable_if_t<boost::random::traits::is_random_device<D>::value>* = nullptr>
using device = D;
template<typename S, std::enable_if_t<boost::random::traits::is_seed_seq<S>::value>* = nullptr>
using sequence = S;

} // namespace random
} // namespace boost

auto main4543543 ( ) -> int {

    std::cout << std::boolalpha
        << '\n'
        << boost::random::traits::is_generator<int>::value
        << '\n'
        << boost::random::traits::is_generator<boost::random::taus88>::value
        << '\n'
        << boost::random::traits::is_random_device<std::random_device>::value
        << '\n'
        << boost::random::traits::is_random_device<boost::random::random_device>::value
        << '\n'
        << boost::random::traits::is_seed_seq<std::seed_seq>::value
        << '\n';

    return 0;
}

#if 0
template <typename...>
using void_t = void;

// We have our base case:

template<class T, class Index, typename = void>
struct has_subscript_operator : std::false_type { };

// And our expression SFINAE valid case:

template<class T, class Index>
struct has_subscript_operator<T, Index, void_t<
    decltype(std::declval<T>( )[std::declval<Index>( )])
    >> : std::true_type { };

namespace details {
    template<class...>struct voider { using type = void; };
    template<class...Ts>using void_t = typename voider<Ts...>::type;

    template<template<class...>class Z, class, class...Ts>
    struct can_apply :
        std::false_type
    {};
    template<template<class...>class Z, class...Ts>
    struct can_apply<Z, void_t<Z<Ts...>>, Ts...> :
        std::true_type
    {};
}
template<template<class...>class Z, class...Ts>
using can_apply = details::can_apply<Z, void, Ts...>;

// You can then simply write properties :

template <class T, class Index>
using subscript_t = decltype(std::declval<T>()[std::declval<Index> ( )]);

template <class T, class Index>
using has_subscript = can_apply<subscript_t, T, Index>;

template <class T>
using call_t = decltype(std::declval<T>()());

template <class T>
using has_call_operator = can_apply<call_t, T>;

template <class T>
using has_seed_t = decltype(std::declval<T>().seed());

template <class T>
using has_seed = can_apply<has_seed_t, T>;

template <class T>
using has_max_t = decltype(std::declval<T> ( ).max());

template <class T>
using has_max = can_apply<has_max_t, T>;

template<typename T, typename R, typename RT = typename T::result_type>
struct has_method_max : boost::random::traits::has_method_max<T, R> {};
#endif

struct Foo {

    typedef int result_type;

    result_type i;

#if 1
    static result_type max ( int ) { return INT_MAX; }
#else
    result_type max ( int ) { return INT_MAX; }
#endif

    Foo ( int i_ ) : i ( i_ ) {}

    result_type get ( ) { return i; }
    result_type get ( int ) { return i; }
};

#define DEFINE_HAS_STATIC(func_name)                                                                            \
template <typename U, typename return_type, typename... args>                                                   \
class has_trait_static_##func_name                                                                              \
{                                                                                \
private:                                                                                \
    template<typename T, T> struct helper;                                                                      \
    template<typename check_type, typename... check_args>                                                       \
    static decltype(std::declval<helper<return_type(*)(check_args...), &check_type::func_name>>()) check(int);  \
    template<typename check_type, typename... check_args>                                                       \
    static boost::random::traits::oops check(...);                                                              \
public:                                                                                \
    static constexpr bool value = !std::is_same_v<decltype(check<U, args...>(0)), boost::random::traits::oops>; \
};

DEFINE_HAS_STATIC ( max )

#include <boost/tti/has_type.hpp>
#include <boost/tti/has_static_member_function.hpp>

BOOST_TTI_HAS_TYPE(result_type)

template<typename... Ts> struct make_void { typedef void type; };
template<typename... Ts> using void_t = typename make_void<Ts...>::type;

struct nonesuch {
    nonesuch ( ) = delete;
    ~nonesuch ( ) = delete;
    nonesuch ( nonesuch const& ) = delete;
    void operator=( nonesuch const& ) = delete;
};

template<class Default, class AlwaysVoid, template<class...> class Op, class... Args>
struct detector {
    using value_t = std::false_type;
    using type = Default;
};

template<class Default, template<class...> class Op, class... Args>
struct detector<Default, void_t<Op<Args...>>, Op, Args...> {
    using value_t = std::true_type;
    using type = Op<Args...>;
};

template<template<class...> class Op, class... Args>
using is_detected = typename detector<nonesuch, void, Op, Args...>::value_t;
template<template<class...> class Op, class... Args>
using detected_t = typename detector<nonesuch, void, Op, Args...>::type;
template <class Default, template<class...> class Op, class... Args>
using detected_or = detector<Default, void, Op, Args...>;

template< template<class...> class Op, class... Args >
constexpr bool is_detected_v = is_detected<Op, Args...>::value;
template< class Default, template<class...> class Op, class... Args >
using detected_or_t = typename detected_or<Default, Op, Args...>::type;
template <class Expected, template<class...> class Op, class... Args>
using is_detected_exact = std::is_same<Expected, detected_t<Op, Args...>>;
template <class Expected, template<class...> class Op, class... Args>
constexpr bool is_detected_exact_v = is_detected_exact<Expected, Op, Args...>::value;
template <class To, template<class...> class Op, class... Args>
using is_detected_convertible = std::is_convertible<detected_t<Op, Args...>, To>;
template <class To, template<class...> class Op, class... Args>
constexpr bool is_detected_convertible_v = is_detected_convertible<To, Op, Args...>::value;

template <typename T, template <typename> class Expression, typename AlwaysVoid = void_t<>>
struct compiles : std::false_type {};
template <typename T, template <typename> class Expression>
struct compiles<T, Expression, void_t<Expression<T>>> : std::true_type {};

template <typename ResultType, typename CheckType, template <typename> class... Values>
using requires = std::enable_if_t<std::conjunction<Values<CheckType>...>::value, ResultType>;

auto main3253523 ( ) -> int {

    std::cout << std::boolalpha
        << true
        << '\n'
        << true
        << '\n';

    return 0;
}

class A {};

template <typename T, typename = void>
struct is_iterable : std::false_type {};
template <typename T>
struct is_iterable<T, std::void_t<decltype( std::declval<T> ( ).begin ( ) ),
    decltype( std::declval<T> ( ).end ( ) )>>
    : std::true_type {};

int main34242 ( )
{
    std::cout << std::boolalpha;
    std::cout << is_iterable<std::vector<double>>::value << '\n';
    std::cout << is_iterable<double>::value << '\n';
    std::cout << is_iterable<A>::value << '\n';

    return 0;
}

//decltype(return_type(refval<check_args>()...))
//template<typename check_type, typename... check_args>
//static std::uint16_t check ( ... );

#include <iostream>
#include <string>

using namespace std;

template<typename ...Args> auto sum ( Args ...args )
{
    return ( args + ... + 0 );
}

template<typename ...Args> auto sum2 ( Args ...args )
{
    return ( args * ... );
}

template <auto ... vs> struct HeterogenousValueList {};

using MyList = HeterogenousValueList<'a', 100, 'b'>;

int main325245 ( )
{
    cout << sum ( 1, 2, 3, 4, 5, 6, 7 ) << "\n";
    cout << sum2 ( 1, 2, 3, 4, 5, 6, 7 ) << "\n";

    // std::pair<int, double> p ( 10, 0.0 );
    // same as
    std::pair p ( 10, 0.0 ); // deduced automatically!

    return 0;
}

template< typename s, typename t, typename u, typename = void >
struct is_product_serializable : std::false_type {};

template< typename s, typename t, typename u >
struct is_product_serializable< s, t, u, typename std::conditional< true, void,
    decltype( std::declval< s > ( ) << std::declval< t > ( ) * std::declval< u > ( ) )
>::type >
    : std::true_type {};

max_stars_repo_name: degski/xoroshiro

max_issues_repo_name: degski/xoroshiro

max_forks_repo_name: degski/xoroshiro


text:
/*
* CoilReductionGadget.cpp
*
*  Created on: Dec 5, 2011
*      Author: hansenms
*/

#include "CoilReductionGadget.h"
#include <boost/algorithm/string.hpp>
#include <boost/algorithm/string/split.hpp>
#include "ismrmrd/xml.h"

namespace Gadgetron{

    CoilReductionGadget::CoilReductionGadget() {
    }

    CoilReductionGadget::~CoilReductionGadget() {
    }

    int CoilReductionGadget::process_config(ACE_Message_Block *mb)
    {
      ISMRMRD::IsmrmrdHeader h;
      ISMRMRD::deserialize(mb->rd_ptr(),h);

      coils_in_ = h.acquisitionSystemInformation->receiverChannels ? *h.acquisitionSystemInformation->receiverChannels : 128;

      std::string coil_mask_int = coil_mask.value();

      if (coil_mask_int.compare(std::string("")) == 0) {
	if (coils_out.value() <= 0) {
	  GDEBUG("Invalid number of output coils %d\n", coils_out.value());
	  return GADGET_FAIL;
	}
	coil_mask_ = std::vector<unsigned short>(coils_out.value(),1);
      } else {
	std::vector<std::string> chm;
	boost::split(chm, coil_mask_int, boost::is_any_of(" "));
	for (size_t i = 0; i < chm.size(); i++) {
	  std::string ch = boost::algorithm::trim_copy(chm[i]);
	  if (ch.size() > 0) {
	    size_t mv = static_cast<size_t>(std::stoi(ch));
	    //GDEBUG("Coil mask value: %d\n", mv);
	    if (mv > 0) {
	      coil_mask_.push_back(1);
	    } else {
	      coil_mask_.push_back(0);
	    }
	  }
	}
      }

      while (coil_mask_.size() < coils_in_) coil_mask_.push_back(0);
      while (coil_mask_.size() > coils_in_) coil_mask_.pop_back();

      if (coil_mask_.size() != coils_in_) {
	GDEBUG("Error configuring coils for coil reduction\n");
	return GADGET_FAIL;
      }

      coils_out_ = 0;
      for (size_t i = 0; i < coil_mask_.size(); i++) {
	if (coil_mask_[i]) coils_out_++;
      }

      GDEBUG("Coil reduction from %d to %d\n", coils_in_, coils_out_);

      return GADGET_OK;
    }

    int CoilReductionGadget::process(GadgetContainerMessage<ISMRMRD::AcquisitionHeader> *m1, GadgetContainerMessage<hoNDArray<std::complex<float> > > *m2)
    {
        std::vector<size_t> dims_out(2);
        dims_out[0] = m1->getObjectPtr()->number_of_samples;
        dims_out[1] = coils_out_;

        GadgetContainerMessage< hoNDArray<std::complex<float> > >* m3 =
            new GadgetContainerMessage< hoNDArray<std::complex<float> > >();

        try{ m3->getObjectPtr()->create(dims_out);}
        catch (std::runtime_error &err){
            GEXCEPTION(err,"Unable to create storage for reduced dataset size\n");
            return GADGET_FAIL;
        }

        std::complex<float>* s = m2->getObjectPtr()->get_data_ptr();
        std::complex<float>* d = m3->getObjectPtr()->get_data_ptr();
        size_t samples =  m1->getObjectPtr()->number_of_samples;
        size_t coils_copied = 0;
        for (int c = 0; c < m1->getObjectPtr()->active_channels; c++) {
            if (c > coil_mask_.size()) {
                GDEBUG("Fatal error, too many coils for coil mask\n");
                m3->release();
                return GADGET_FAIL;
            }
            if (coil_mask_[c]) {
                memcpy(d+coils_copied*samples,s+c*samples,sizeof(std::complex<float>)*samples);
                coils_copied++;
            }
        }

        m1->cont(m3);

	//In case trajectories are attached
	m3->cont(m2->cont());
	m2->cont(0);

        m2->release();

        m1->getObjectPtr()->active_channels = coils_out_;

        if( this->next()->putq(m1) < 0 ){
	  GDEBUG("Failed to put message on queue\n");
	  return GADGET_FAIL;
	}

	return GADGET_OK;
    }

    GADGET_FACTORY_DECLARE(CoilReductionGadget)
}

ext: cpp

max_stars_repo_name: roopchansinghv/gadgetron


text:
/**TODO:  Add copyright*/

#define BOOST_TEST_MODULE ModelErrorData test suite
#include <boost/test/included/unit_test.hpp>
#include <EvoNet/ml/ModelErrorData.h>

#include <iostream>

using namespace EvoNet;
using namespace std;

BOOST_AUTO_TEST_SUITE(ModelErrorData1)

BOOST_AUTO_TEST_CASE(constructor)
{
	ModelErrorDataCpu<float>* ptr = nullptr;
	ModelErrorDataCpu<float>* nullPointer = nullptr;
	ptr = new ModelErrorDataCpu<float>();
  BOOST_CHECK_NE(ptr, nullPointer);
  delete ptr;
}

BOOST_AUTO_TEST_CASE(destructor)
{
	ModelErrorDataCpu<float>* ptr = nullptr;
	ptr = new ModelErrorDataCpu<float>();
  delete ptr;
}

BOOST_AUTO_TEST_CASE(comparison)
{
	ModelErrorDataCpu<float> error, error_test;
	BOOST_CHECK(error == error_test);
}

#if COMPILE_WITH_CUDA
BOOST_AUTO_TEST_CASE(gettersAndSetters2)
{
	ModelErrorDataGpu<float> error;
	error.setBatchSize(2);
	error.setMemorySize(3);
	error.setNMetrics(4);

  Eigen::Tensor<float, 2> error_tensor(2, 3), metric(4, 3);
  error_tensor.setConstant(3); metric.setConstant(4);

	error.setError(error_tensor);
	error.setMetric(metric);

	BOOST_CHECK_EQUAL(error.getBatchSize(), 2);
	BOOST_CHECK_EQUAL(error.getMemorySize(), 3);
	BOOST_CHECK_EQUAL(error.getNMetrics(), 4);
	BOOST_CHECK_EQUAL(error.getError()(0, 0), 3);
	BOOST_CHECK(error.getErrorStatus().first);
	BOOST_CHECK(!error.getErrorStatus().second);
	BOOST_CHECK_EQUAL(error.getMetric()(0, 0), 4);
	BOOST_CHECK(error.getMetricStatus().first);
	BOOST_CHECK(!error.getMetricStatus().second);

	// Test mutability
	error.getError()(0, 0) = 8;
	error.getMetric()(0, 0) = 9;

	BOOST_CHECK_EQUAL(error.getError()(0, 0), 8);
	BOOST_CHECK_EQUAL(error.getMetric()(0, 0), 9);
}

BOOST_AUTO_TEST_CASE(syncHAndD2)
{
	ModelErrorDataGpu<float> error;
	error.setBatchSize(2);
	error.setMemorySize(3);
	error.setNMetrics(4);

  Eigen::Tensor<float, 2> error_tensor(2, 3), metric(4, 3);
  error_tensor.setConstant(3); metric.setConstant(4);

	error.setError(error_tensor);
	error.setMetric(metric);

	Eigen::GpuStreamDevice stream_device;
	Eigen::GpuDevice device(&stream_device);
	error.syncHAndDError(device);
	error.syncHAndDMetric(device);

	BOOST_CHECK(!error.getErrorStatus().first);
	BOOST_CHECK(error.getErrorStatus().second);
	BOOST_CHECK(!error.getMetricStatus().first);
	BOOST_CHECK(error.getMetricStatus().second);

	error.syncHAndDError(device);
	error.syncHAndDMetric(device);

	BOOST_CHECK(error.getErrorStatus().first);
	BOOST_CHECK(!error.getErrorStatus().second);
	BOOST_CHECK(error.getMetricStatus().first);
	BOOST_CHECK(!error.getMetricStatus().second);
}
#endif

BOOST_AUTO_TEST_CASE(gettersAndSetters)
{
	ModelErrorDataCpu<float> error;
	error.setBatchSize(2);
	error.setMemorySize(3);
	error.setNMetrics(4);
	size_t test_error = 2 * 3 * sizeof(float);
  size_t test_metric = 3 * 4 * sizeof(float);
	BOOST_CHECK_EQUAL(error.getErrorTensorSize(), test_error);
  BOOST_CHECK_EQUAL(error.getMetricTensorSize(), test_metric);
}

BOOST_AUTO_TEST_CASE(gettersAndSetters1)
{
	ModelErrorDataCpu<float> error;
	error.setBatchSize(2);
	error.setMemorySize(3);
	error.setNMetrics(4);

	Eigen::Tensor<float, 2> error_tensor(2, 3), metric(4, 3);
  error_tensor.setConstant(3); metric.setConstant(4);

	error.setError(error_tensor);
	error.setMetric(metric);

	BOOST_CHECK_EQUAL(error.getBatchSize(), 2);
	BOOST_CHECK_EQUAL(error.getMemorySize(), 3);
	BOOST_CHECK_EQUAL(error.getNMetrics(), 4);
	BOOST_CHECK_EQUAL(error.getError()(0, 0), 3);
	BOOST_CHECK(error.getErrorStatus().first);
	BOOST_CHECK(error.getErrorStatus().second);
	BOOST_CHECK_EQUAL(error.getMetric()(0, 0), 4);
	BOOST_CHECK(error.getMetricStatus().first);
	BOOST_CHECK(error.getMetricStatus().second);

	// Test mutability
	error.getError()(0, 0) = 8;
	error.getMetric()(0, 0) = 9;

	BOOST_CHECK_EQUAL(error.getError()(0, 0), 8);
	BOOST_CHECK_EQUAL(error.getMetric()(0, 0), 9);
}

BOOST_AUTO_TEST_CASE(syncHAndD)
{
	ModelErrorDataCpu<float> error;
	error.setBatchSize(2);
	error.setMemorySize(3);
	error.setNMetrics(4);

  Eigen::Tensor<float, 2> error_tensor(2, 3), metric(4, 3);
  error_tensor.setConstant(3); metric.setConstant(4);

	error.setError(error_tensor);
	error.setMetric(metric);

	Eigen::DefaultDevice device;;
	error.syncHAndDError(device);
	error.syncHAndDMetric(device);

	BOOST_CHECK(error.getErrorStatus().first);
	BOOST_CHECK(error.getErrorStatus().second);
	BOOST_CHECK(error.getMetricStatus().first);
	BOOST_CHECK(error.getMetricStatus().second);

	error.syncHAndDError(device);
	error.syncHAndDMetric(device);

	BOOST_CHECK(error.getErrorStatus().first);
	BOOST_CHECK(error.getErrorStatus().second);
	BOOST_CHECK(error.getMetricStatus().first);
	BOOST_CHECK(error.getMetricStatus().second);
}

BOOST_AUTO_TEST_CASE(initModelErrorData)
{
	ModelErrorDataCpu<float> error;
	error.initModelErrorData(2, 5, 4);

	// Test the batch and memory sizes
	BOOST_CHECK_EQUAL(error.getBatchSize(), 2);
	BOOST_CHECK_EQUAL(error.getMemorySize(), 5);
	BOOST_CHECK_EQUAL(error.getNMetrics(), 4);

	BOOST_CHECK_EQUAL(error.getError()(0, 0), 0.0);
	BOOST_CHECK_EQUAL(error.getError()(1, 4), 0.0);
	BOOST_CHECK_EQUAL(error.getMetric()(0, 0), 0.0);
	BOOST_CHECK_EQUAL(error.getMetric()(3, 4), 0.0);
}

BOOST_AUTO_TEST_SUITE_END()


text:
#include <boost/interprocess/managed_shared_memory.hpp>
#include <boost/interprocess/containers/map.hpp>
#include <boost/interprocess/allocators/allocator.hpp>
#include <functional>
#include <utility>

int main ()
{
    using namespace boost::interprocess;

    // remove earlier existing SHM
    shared_memory_object::remove("SharedMemoryName");

    // create new
    managed_shared_memory segment(create_only,"SharedMemoryName",65536);

    //Note that map<Key, MappedType>'s value_type is std::pair<const Key, MappedType>,
    //so the allocator must allocate that pair.
    typedef int    KeyType;
    typedef float  MappedType;
    typedef std::pair<const int, float> ValueType;

    //allocator of for the map.
    typedef allocator<ValueType, managed_shared_memory::segment_manager> ShmemAllocator;

    //third parameter argument is the ordering function is used to compare the keys.
    typedef map<KeyType, MappedType, std::less<KeyType>, ShmemAllocator> MySHMMap;

    //Initialize the shared memory STL-compatible allocator
    ShmemAllocator alloc_inst (segment.get_segment_manager());

    // offset ptr within SHM for map
    offset_ptr<MySHMMap> m_pmap = segment.construct<MySHMMap>("MySHMMapName")(std::less<int>(), alloc_inst);

    //Insert data in the map
    for(int i = 0; i < 10; ++i)
    {
            m_pmap->insert(std::pair<const int, float>(i, (float)i));
    }

    return 0;
}

max_stars_repo_name: pshoben/llexp

max_issues_repo_name: pshoben/llexp

max_forks_repo_name: pshoben/llexp


text: #include <boost/phoenix/statement/sequence.hpp>

ext: hpp

max_stars_repo_name: miathedev/BoostForArduino

max_issues_repo_name: miathedev/BoostForArduino

max_forks_repo_name: miathedev/BoostForArduino


text:
/* Copyright 2017 Ramakrishnan Kannan */

#ifndef COMMON_TENSOR_HPP_
#define COMMON_TENSOR_HPP_

#include <cblas.h>
#include <armadillo>
#include <fstream>
#include <ios>
#include <random>
#include <string>
#include <type_traits>
#include <utility>
#include <vector>
#include "common/utils.h"

namespace planc {
/**
 * Data is stored such that the unfolding \f$Y_0\f$ is column
 * major.  This means the flattening \f$Y_{N-1}\f$ is row-major,
 * and any other flattening \f$Y_n\f$ can be represented as a set
 * of \f$\prod\limits_{k=n+1}^{N-1}I_k\f$ row major matrices, each
 * of which is \f$I_n \times \prod\limits_{k=0}^{n-1}I_k\f$.
 */

// sgemm (TRANSA, TRANSB, M, N, K, ALPHA, A, LDA, B, LDB, BETA, C, LDC)
// extern "C" void dgemm_(const char*, const char*, const int*,
//                      const int*, const int*, const double*, const double*,
//                      const int*, const double*, const int*, const double*,
//                      double*, const int*);

class Tensor {
 private:
  int m_modes;
  UVEC m_dimensions;
  UWORD m_numel;
  UVEC m_global_idx;
  unsigned int rand_seed;

  // for the time being it is used for debugging purposes
  size_t sub2ind(UVEC sub, UVEC dimensions) {
    assert(sub.n_rows == dimensions.n_rows);
    UVEC cumprod_dims = arma::cumprod(dimensions);
    UVEC cumprod_dims_shifted = arma::shift(cumprod_dims, 1);
    cumprod_dims_shifted(0) = 1;
    size_t idx = arma::dot(cumprod_dims_shifted, sub);
    return idx;
  }
  UVEC ind2sub(UVEC dimensions, size_t idx) {
    //   k = [1 cumprod(siz(1 : end - 1))];
    //   n = length(siz);
    //   idx = idx - 1;
    // for i = n : -1 : 1
    //   div = floor(idx / k(i));
    //   subs( :, i) = div + 1;
    //   idx = idx - k(i) * div;
    // end
    UVEC cumprod_dims = arma::cumprod(dimensions);
    UVEC cumprod_dims_shifted = arma::shift(cumprod_dims, 1);
    cumprod_dims_shifted(0) = 1;
    int modes = dimensions.n_elem;
    UVEC sub = arma::zeros<UVEC>(modes);
    float temp;
    for (int i = modes - 1; i >= 0; i--) {
      temp = std::floor((idx * 1.0) / (cumprod_dims_shifted(i) * 1.0));
      sub(i) = temp;
      idx = idx - cumprod_dims_shifted(i) * temp;
    }
    return sub;
  }

 public:
  std::vector<double> m_data;

  Tensor() {
    this->m_modes = 0;
    this->m_numel = 0;
  }
  /**
   * Constructor that takes only dimensions of every mode as a vector
   */
  explicit Tensor(const UVEC &i_dimensions)
      : m_modes(i_dimensions.n_rows),
        m_dimensions(i_dimensions),
        m_numel(arma::prod(i_dimensions)),
        rand_seed(103) {
    m_data.resize(m_numel);
    randu();
  }
  Tensor(const UVEC &i_dimensions, const UVEC &i_start_idx)
      : m_modes(i_dimensions.n_rows),
        m_dimensions(i_dimensions),
        m_numel(arma::prod(i_dimensions)),
        m_global_idx(i_start_idx),
        rand_seed(103) {
    m_data.resize(m_numel);
    randu();
  }
  /**
   * Need when copying from matrix to Tensor. otherwise copy constructor
   * will be called. The data will be passed in row major order
   *
   */
  Tensor(const UVEC &i_dimensions, double *i_data)
      : m_modes(i_dimensions.n_rows),
        m_dimensions(i_dimensions),
        m_numel(arma::prod(i_dimensions)),
        rand_seed(103) {
    m_data.resize(m_numel);
    memcpy(&this->m_data[0], i_data, sizeof(double) * this->m_numel);
  }
  ~Tensor() {}

  /**
   *  copy constructor
   */
  Tensor(const Tensor &src) {
    clear();
    this->m_numel = src.numel();
    this->m_modes = src.modes();
    this->m_dimensions = src.dimensions();
    this->m_global_idx = src.global_idx();
    this->rand_seed = 103;
    this->m_data = src.m_data;
  }

  Tensor &operator=(const Tensor &other) {  // copy assignment
    if (this != &other) {                   // self-assignment check expected
      clear();
      // this->m_data = new double[other.numel()];  // create storage in this
      this->m_numel = other.numel();
      this->m_modes = other.modes();
      this->m_dimensions = other.dimensions();
      this->m_global_idx = other.global_idx();
      this->m_data = other.m_data;
    }
    return *this;
  }

  void swap(Tensor &in) {
    using std::swap;
    swap(m_numel, in.m_numel);
    swap(m_modes, in.m_modes);
    swap(m_dimensions, in.m_dimensions);
    swap(m_global_idx, in.m_global_idx);
    swap(rand_seed, in.rand_seed);
    swap(m_data, in.m_data);
  }
  /**
   * Clears the data and also destroys the storage
   */

  void clear() {
    this->m_numel = 0;
    this->m_data.clear();
  }

  /// Return the number of modes. It is a scalar value.
  int modes() const { return m_modes; }
  /// Returns a vector of dimensions on every mode
  UVEC dimensions() const { return m_dimensions; }
  UVEC global_idx() const { return m_global_idx; }

  /**
   * Returns the dimension of the input mode.
   * @param[in] a mode of the tensor.
   * @return dimension of ith mode
   */

  int dimension(int i) const { return m_dimensions[i]; }
  /// Returns total number of elements
  UWORD numel() const { return m_numel; }

  void set_idx(const UVEC &i_start_idx) { m_global_idx = i_start_idx; }
  /**
   * Return the product of dimensions except mode i
   * @param[in] mode i
   * @return product of dimensions except mode i
   */
  UWORD dimensions_leave_out_one(int i) const {
    UWORD rc = arma::prod(this->m_dimensions);
    return rc - this->m_dimensions(i);
  }
  /// Zeros out the entire tensor
  void zeros() {
    for (UWORD i = 0; i < this->m_numel; i++) {
      this->m_data[i] = 0;
    }
  }
  /// set the tensor with uniform random.
  void rand() {
#pragma omp parallel for
    for (UWORD i = 0; i < this->m_numel; i++) {
      unsigned int *temp = const_cast<unsigned int *>(&rand_seed);
      this->m_data[i] =
          static_cast<double>(rand_r(temp)) / static_cast<double>(RAND_MAX);
    }
  }
  /// set the tensor with uniform int values
  void randi() {
    std::random_device rd;
    std::mt19937 gen(rd());
    int max_randi = this->m_numel;
    std::uniform_int_distribution<> dis(0, max_randi);
#pragma omp parallel for
    for (UWORD i = 0; i < this->m_numel; i++) {
      this->m_data[i] = dis(gen);
    }
  }
  /**
   * set the tensor with uniform random values starting with a seed.
   * can be used to generate the same tensor again and again.
   * @param[in] an integer seed value preferrably a relative prime number
   */
  void randu(const int i_seed = -1) {
    std::random_device rd;
    std::uniform_real_distribution<> dis(0, 1);
    if (i_seed == -1) {
      std::mt19937 gen(rand_seed);
#pragma omp parallel for
      for (unsigned int i = 0; i < this->m_numel; i++) {
        m_data[i] = dis(gen);
      }
    } else {
      std::mt19937 gen(i_seed);
#pragma omp parallel for
      for (unsigned int i = 0; i < this->m_numel; i++) {
        m_data[i] = dis(gen);
      }
    }
  }

  /**
   * size of krp must be product of all dimensions leaving out nxk.
   * o_mttkrp will be of size dimension[n]xk.
   * Memory must be allocated and freed by the caller
   * @param[in]  i_n mode number
   * @param[in]  i_krp Khatri-rao product matrix leaving out mode i_n
   * @param[out] o_mttkrp pointer to the mttkrp matrix.
   */

  void mttkrp(const int i_n, const MAT &i_krp, MAT *o_mttkrp) const {
    (*o_mttkrp).zeros();
    if (i_n == 0) {
      // if n == 1
      // Ur = khatrirao(U{2: N}, 'r');
      // Y = reshape(X.data, szn, szr);
      // V =  Y * Ur;
      // Compute number of columns of Y_n
      // Technically, we could divide the total number of entries by n,
      // but that seems like a bad decision
      // size_t ncols = arma::prod(this->m_dimensions);
      // ncols /= this->m_dimensions[0];
      // Call matrix matrix multiply
      // call dgemm (TRANSA, TRANSB, M, N, K, ALPHA, A, LDA, B, LDB, BETA, C,
      // LDC) C := alpha*op( A )*op( B ) + beta*C A, B and C are matrices, with
      // op( A ) an m by k matrix, op( B ) a k by n matrix and C an m by n
      // matrix. matricized tensor is m x k is in column major format krp is k x
      // n is in column major format output is m x n in column major format
      // char transa = 'N';
      // char transb = 'N';
      int m = this->m_dimensions[0];
      int n = i_krp.n_cols;
      int k = i_krp.n_rows;
      // int lda = m;
      // int ldb = k;
      // int ldc = m;
      double alpha = 1;
      double beta = 0;
      // sgemm (TRANSA, TRANSB, M, N, K, ALPHA, A, LDA, B, LDB, BETA, C, LDC)
      // dgemm_(&transa, &transb, &m, &n, &k, &alpha, this->m_data,
      // &lda, i_krp.memptr(), &ldb, &beta, o_mttkrp->memptr() , &ldc);
      // printf("mode=%d,i=%d,m=%d,n=%d,k=%d,alpha=%lf,T_stride=%d,lda=%d,krp_stride=%d,ldb=%d,beat=%lf,mttkrp=!!!,ldc=%d\n",0,
      // 0, m, n, k,alpha,0*k*m,m,0*n*k,i_krp.n_rows,beta,n);
      cblas_dgemm(CblasRowMajor, CblasTrans, CblasTrans, m, n, k, alpha,
                  &this->m_data[0], m, i_krp.memptr(), k, beta,
                  o_mttkrp->memptr(), n);

    } else {
      int ncols = 1;
      int nmats = 1;
      int lowrankk = i_krp.n_cols;

      // Count the number of columns
      for (int i = 0; i < i_n; i++) {
        ncols *= this->m_dimensions[i];
      }

      // Count the number of matrices
      for (int i = i_n + 1; i < this->m_modes; i++) {
        nmats *= this->m_dimensions[i];
      }
      // For each matrix...
      for (int i = 0; i < nmats; i++) {
        // char transa = 'T';
        // char transb = 'N';
        int m = this->m_dimensions[i_n];
        int n = lowrankk;
        int k = ncols;
        // int lda = k;  // not sure. could be m. higher confidence on k.
        // int ldb = i_krp.n_rows;
        // int ldc = m;
        double alpha = 1;
        double beta = (i == 0) ? 0 : 1;
        // double *A = this->m_data + i * k * m;
        // double *B = const_cast<double *>(i_krp.memptr()) + i * k;

        // for KRP move ncols*lowrankk
        // for tensor X move as n_cols*blas_n
        // For output matrix don't move anything as beta=1;
        // for reference from gram while moving input tensor like
        // Y->data()+i*nrows*ncols sgemm (TRANSA, TRANSB, M, N, K, ALPHA, A,
        // LDA, B, LDB, BETA, C, LDC)
        // dgemm_(&transa, &transb, &m, &n, &k, &alpha, A,
        // &lda, B , &ldb, &beta, (*o_mttkrp).memptr() , &ldc);
        // printf("mode=%d,i=%d,m=%d,n=%d,k=%d,alpha=%lf,T_stride=%d,lda=%d,krp_stride=%d,ldb=%d,beat=%lf,mttkrp=!!!,ldc=%d\n",i_n,
        // i, m, n, k,alpha,i*k*m,k,i*n*k,nmats*ncols,beta,n);
        cblas_dgemm(CblasRowMajor, CblasNoTrans, CblasTrans, m, n, k, alpha,
                    &this->m_data[0] + i * k * m, ncols, i_krp.memptr() + i * k,
                    ncols * nmats, beta, o_mttkrp->memptr(), n);
      }
    }
  }
  /// prints the value of the tensor.
  void print() const {
    INFO << "Dimensions: " << this->m_dimensions;
    for (unsigned int i = 0; i < this->m_numel; i++) {
      std::cout << i << " : " << this->m_data[i] << std::endl;
    }
  }

  void print(const UVEC &global_dims, const UVEC &global_start_sub) {
    UVEC local_sub = arma::zeros<UVEC>(global_dims.n_elem);
    // UVEC global_start_sub = ind2sub(global_dims, global_start_idx);
    UVEC global_sub = arma::zeros<UVEC>(global_dims.n_elem);
    int global_idx;
    for (unsigned int i = 0; i < this->m_numel; i++) {
      local_sub = ind2sub(this->m_dimensions, i);
      global_sub = global_start_sub + local_sub;
      global_idx = sub2ind(global_sub, global_dims);
      std::cout << i << " : " << global_idx << " : " << this->m_data[i]
                << std::endl;
    }
  }
  /// returns the frobenius norm of the tensor
  double norm() const {
    double norm_fro = 0;
    for (unsigned int i = 0; i < this->m_numel; i++) {
      norm_fro += (this->m_data[i] * this->m_data[i]);
    }
    return norm_fro;
  }
  /**
   * Computes the squared error with the input tensor
   * @param[in] b an input tensor
   */
  double err(const Tensor &b) const {
    double norm_fro = 0;
    double err_diff;
    for (unsigned int i = 0; i < this->m_numel; i++) {
      err_diff = this->m_data[i] - b.m_data[i];
      norm_fro += err_diff * err_diff;
    }
    return norm_fro;
  }
  /**
   * Scales the tensor with the constant value.
   * @param[in] scale can be an int, float or double value
   */

  template <typename NumericType>
  void scale(NumericType scale) {
    // static_assert(std::is_arithmetic<NumericType>::value,
    //               "NumericType for scale operation must be numeric");
    for (unsigned int i = 0; i < this->m_numel; i++) {
      this->m_data[i] = this->m_data[i] * scale;
    }
  }
  /**
   * Shifts (add or subtract) the tensor with the constant value.
   * If the i_shift is negative it subtracts, otherwise it adds.
   * @param[in] i_shift can be an int, float or double value
   */
  template <typename NumericType>
  void shift(NumericType i_shift) {
    // static_assert(std::is_arithmetic<NumericType>::value,
    //               "NumericType for shift operation must be numeric");
    for (unsigned int i = 0; i < this->m_numel; i++) {
      this->m_data[i] = this->m_data[i] + i_shift;
    }
  }
  /**
   * Truncate all the value between min and max. Any value beyond
   * the min and max will be truncated to min and max.
   * @param[in] min - any value less than min will be set to min
   * @param[in] max - any value greater than max will be set to max
   */
  template <typename NumericType>
  void bound(NumericType min, NumericType max) {
    // static_assert(std::is_arithmetic<NumericType>::value,
    //               "NumericType for bound operation must be numeric");
    for (unsigned int i = 0; i < this->m_numel; i++) {
      if (this->m_data[i] < min) this->m_data[i] = min;
      if (this->m_data[i] > max) this->m_data[i] = max;
    }
  }
  /**
   * Sets only the lower bound
   * @param[in] min - any value less than min will be set to min
   */

  template <typename NumericType>
  void lower_bound(NumericType min) {
    // static_assert(std::is_arithmetic<NumericType>::value,
    //               "NumericType for bound operation must be numeric");
    for (unsigned int i = 0; i < this->m_numel; i++) {
      if (this->m_data[i] < min) this->m_data[i] = min;
    }
  }

  /**
   * Write the tensor to the given filename. Compile with
   * -D_FILE_OFFSET_BITS=64 to support large files greater than 2GB
   * @param[in] filename as std::string
   */
  void write(std::string filename,
             std::ios_base::openmode mode = std::ios_base::out) {
    std::string filename_no_extension =
        filename.substr(0, filename.find_last_of("."));
    // info file always in text mode
    filename_no_extension.append(".info");
    std::ofstream ofs;
    ofs.open(filename_no_extension, std::ios_base::out);
    // write modes
    ofs << this->m_modes << std::endl;
    // dimension of modes
    for (int i = 0; i < this->m_modes; i++) {
      ofs << this->m_dimensions[i] << std::endl;
    }
    ofs << std::endl;
    ofs.close();
    FILE *fp = fopen(filename.c_str(), "wb");
    INFO << "size of the outputfile in GB "
         << (this->m_numel * 8.0) / (1024 * 1024 * 1024) << std::endl;
    size_t nwrite =
        fwrite(&this->m_data[0], sizeof(std::vector<double>::value_type),
               this->numel(), fp);
    if (nwrite != this->numel()) {
      WARN << "something wrong ::write::" << nwrite
           << "::numel::" << this->numel() << std::endl;
    }
    fclose(fp);
  }
  /**
   * Reads a tensor from the file. Compile with
   * -D_FILE_OFFSET_BITS=64 to support large files greater than 2GB
   * @param[in] filename as std::string
   */

  void read(std::string filename,
            std::ios_base::openmode mode = std::ios_base::in) {
    // clear existing tensor
    if (this->m_numel > 0) {
      this->m_data.clear();  // destroy storage in this
      this->m_numel = 0;
    }
    std::string filename_no_extension =
        filename.substr(0, filename.find_last_of("."));
    filename_no_extension.append(".info");

    std::ifstream ifs;
    // info file always in text mode
    ifs.open(filename_no_extension, std::ios_base::in);
    // write modes
    ifs >> this->m_modes;
    // dimension of modes
    this->m_dimensions = arma::zeros<UVEC>(this->m_modes);
    for (int i = 0; i < this->m_modes; i++) {
      ifs >> this->m_dimensions[i];
    }
    ifs.close();
    // ifs.open(filename, mode);
    FILE *fp = fopen(filename.c_str(), "rb");
    this->m_numel = arma::prod(this->m_dimensions);
    this->m_data.resize(this->m_numel);
    // for (int i = 0; i < this->m_numel; i++) {
    //   ifs >> this->m_data[i];
    // }
    // ifs.read(reinterpret_cast<char *>(this->m_data), sizeof(this->m_data));
    size_t nread =
        fread(&this->m_data[0], sizeof(std::vector<double>::value_type),
              this->numel(), fp);
    if (nread != this->numel()) {
      WARN << "something wrong ::write::" << nread
           << "::numel::" << this->numel() << std::endl;
    }
    // Close the file
    fclose(fp);
  }

  /**
   * Given a vector of subscripts, it return the linear index
   * in the tensor.
   * @param[in] vector of subscript
   * @return linear index within the tensor
   */

  UWORD sub2ind(UVEC sub) {
    assert(sub.n_cols == this->m_dimensions.n_cols);
    UVEC cumprod_dims = arma::cumprod(this->m_dimensions);
    UVEC cumprod_dims_shifted = arma::shift(cumprod_dims, 1);
    cumprod_dims_shifted(0) = 1;
    size_t idx = arma::dot(cumprod_dims_shifted, sub);
    return idx;
  }
  double at(UVEC sub) { return m_data[sub2ind(sub)]; }
};  // class Tensor
}  // namespace planc

void swap(planc::Tensor &x, planc::Tensor &y) { x.swap(y); }

#endif  // COMMON_TENSOR_HPP_

max_stars_repo_name: lanl/DnMFkCPP

max_issues_repo_name: rvangara/DnMFk

max_forks_repo_name: rvangara/DnMFk


text:
#ifndef STACK_HANDLER_ALLOCATOR_HPP
#define STACK_HANDLER_ALLOCATOR_HPP

#include <array>
#include <cstdlib>
#include <mutex>
#include <new>
#include <thread>

#if defined(ASYNC_UTILS_STACK_HANDLER_ALLOCATOR_DEBUG)
#include <boost/format.hpp>
#include <iostream>
#endif

namespace async_utils {

class stack_handler_memory_base {
  public:
    virtual void *allocate(std::size_t size) = 0;
    virtual void deallocate(void *ptr) noexcept = 0;
};

// The memory manager used by stack_handler_allocator.
// It maintains a fixed number of storage slots each of a fixed size.
// Once all the slots are used, any additional allocation is delegated to the global heap.
template <std::size_t storage_count = 4, std::size_t storage_size = 1024>
class stack_handler_memory : public stack_handler_memory_base {
  public:
    stack_handler_memory() : m_storage{}, m_in_use{false} {}
    stack_handler_memory(stack_handler_memory const &) = delete;
    stack_handler_memory(stack_handler_memory &&) noexcept = delete;
    stack_handler_memory &operator=(stack_handler_memory const &) = delete;
    stack_handler_memory &operator=(stack_handler_memory &&) noexcept = delete;
    ~stack_handler_memory() = default;

    void *allocate(std::size_t size) final {
        lock_guard lock(m_mutex);
        void *ptr = nullptr;
        if (size > 0 && size < sizeof(m_storage[0])) {
            for (std::size_t i = 0; i < m_in_use.size(); ++i) {
                // NOLINTNEXTLINE(cppcoreguidelines-pro-bounds-constant-array-index)
                if (!m_in_use[i]) {
#if defined(ASYNC_UTILS_STACK_HANDLER_ALLOCATOR_DEBUG)
                    std::cout << boost::format("[tid: %d] handler: allocated[%d]: size: %d") %
                                     std::this_thread::get_id() % i % size
                              << std::endl;
#endif
                    m_in_use[i] = true;  // NOLINT(cppcoreguidelines-pro-bounds-constant-array-index)
                    ptr = &m_storage[i]; // NOLINT(cppcoreguidelines-pro-bounds-constant-array-index)
                    break;
                }
            }
        }

        if (ptr == nullptr) {
#if defined(ASYNC_UTILS_STACK_HANDLER_ALLOCATOR_DEBUG)
            std::cout << boost::format("[tid: %d] handler: global new: size: %d") % std::this_thread::get_id() % size
                      << std::endl;
#endif
            ptr = ::operator new(size);
        }

        return ptr;
    }

    void deallocate(void *ptr) noexcept final {
        lock_guard lock(m_mutex);
        for (std::size_t i = 0; i < m_storage.size(); ++i) {
            // NOLINTNEXTLINE(cppcoreguidelines-pro-bounds-constant-array-index)
            if (ptr == &m_storage[i]) {
#if defined(ASYNC_UTILS_STACK_HANDLER_ALLOCATOR_DEBUG)
                try {
                    std::cout << boost::format("[tid: %d] handler: deallocated[%d]") % std::this_thread::get_id() % i
                              << std::endl;
                } catch (...) {
                }
#endif
                m_in_use[i] = false; // NOLINT(cppcoreguidelines-pro-bounds-constant-array-index)
                ptr = nullptr;
                break;
            }
        }
        ::operator delete(ptr); // no-op for nullptr
    }

    // Returns the number of slots in use.
    std::size_t use_count() const {
        lock_guard lock(m_mutex);
        std::size_t count = 0;
        for (auto b : m_in_use) {
            count += b ? 1 : 0;
        }
        return count;
    }

  private:
    // Storage
    std::array<std::aligned_storage_t<storage_size>, storage_count> m_storage;
    // Usage flag for each storage slot.
    std::array<bool, storage_count> m_in_use;

    using lock_guard = std::lock_guard<std::mutex>;
    mutable std::mutex m_mutex;
};

// A basic allocator that allocates from a fixed number of storage slots each of a fixed size.
// Once all the slots are used, any additional allocation is delegated to the global heap.
template <typename T> struct stack_handler_allocator {
    using value_type = T;
    explicit stack_handler_allocator(stack_handler_memory_base &storage) noexcept : m_storage{storage} {}
    template <typename U> // NOLINTNEXTLINE(google-explicit-constructor,hicpp-explicit-conversions)
    stack_handler_allocator(stack_handler_allocator<U> const &other) noexcept : m_storage{other.m_storage} {}

    template <typename U> bool operator==(stack_handler_allocator<U> const &other) const noexcept {
        return &m_storage == &other.m_storage;
    }
    template <typename U> bool operator!=(stack_handler_allocator<U> const &other) const noexcept {
        return &m_storage != &other.m_storage;
    }

    T *allocate(std::size_t count) const { return static_cast<T *>(m_storage.allocate(count * sizeof(T))); }
    void deallocate(T *const ptr, std::size_t /*unused*/) const noexcept { m_storage.deallocate(ptr); }

  private:
    template <typename> friend struct stack_handler_allocator;
    stack_handler_memory_base &m_storage;
};

} // namespace async_utils

#endif

max_stars_repo_name: sorf/cpp-playground

max_issues_repo_name: sorf/cpp-playground

max_forks_repo_name: sorf/cpp-playground


text:
#include <boost/log/core.hpp>
#include "gtest/gtest.h"

int main(int argc, char** argv)
{
    auto core = boost::log::core::get();
    core->set_logging_enabled(false);

    ::testing::InitGoogleTest(&argc, argv);
    return RUN_ALL_TESTS();
}

max_stars_repo_name: rmcolq/pandora

max_issues_repo_name: rmcolq/pandora


text:
#pragma once

#include <crab/common/os.hpp>
#include <crab/common/debug.hpp>

#include <iosfwd>
#include <boost/optional.hpp>
#include <memory>

/* Basic type definitions */

namespace crab {

   enum variable_type {
     BOOL_TYPE,
     INT_TYPE,
     REAL_TYPE,
     PTR_TYPE,
     ARR_BOOL_TYPE,
     ARR_INT_TYPE,
     ARR_REAL_TYPE,
     ARR_PTR_TYPE,
     UNK_TYPE};

  inline crab_os& operator<<(crab_os& o, variable_type t) {
    switch (t) {
       case BOOL_TYPE: o << "bool"; break;
       case INT_TYPE: o << "int"; break;
       case REAL_TYPE: o << "real"; break;
       case PTR_TYPE: o << "ptr"; break;
       case ARR_BOOL_TYPE: o << "arr_bool"; break;
       case ARR_INT_TYPE: o << "arr_int"; break;
       case ARR_REAL_TYPE: o << "arr_real"; break;
       case ARR_PTR_TYPE: o << "arr_ptr"; break;
       default: o << "unknown"; break;
     }
     return o;
   }

   typedef enum {
     BINOP_ADD, BINOP_SUB, BINOP_MUL,
     BINOP_SDIV, BINOP_UDIV, BINOP_SREM, BINOP_UREM,
     BINOP_AND, BINOP_OR, BINOP_XOR, BINOP_SHL, BINOP_LSHR, BINOP_ASHR,
     BINOP_FUNCTION
   } binary_operation_t;

   typedef enum {
     BINOP_BAND, BINOP_BOR, BINOP_BXOR
   } bool_binary_operation_t;

   typedef enum {
     CAST_TRUNC, CAST_SEXT, CAST_ZEXT
   } cast_operation_t;

   inline crab::crab_os& operator<<(crab::crab_os&o, binary_operation_t op) {
     switch (op) {
     case BINOP_ADD: o << "+"; break;
     case BINOP_SUB: o << "-"; break;
     case BINOP_MUL: o << "*"; break;
     case BINOP_SDIV: o << "/"; break;
     case BINOP_UDIV: o << "/_u"; break;
     case BINOP_SREM: o << "%"; break;
     case BINOP_UREM: o << "%_u"; break;
     case BINOP_AND: o << "&"; break;
     case BINOP_OR: o << "|"; break;
     case BINOP_XOR: o << "^"; break;
     case BINOP_SHL: o << "<<"; break;
     case BINOP_LSHR: o << ">>_l"; break;
     case BINOP_ASHR: o << ">>_r"; break;
     case BINOP_FUNCTION: o << "uf"; break;
     default: CRAB_ERROR("unexpected binary operation ", op);
     }
     return o;
   }

   inline crab::crab_os& operator<<(crab::crab_os&o, bool_binary_operation_t op) {
     switch (op) {
     case BINOP_BAND: o << "&"; break;
     case BINOP_BOR: o << "|"; break;
     case BINOP_BXOR: o << "^"; break;
     default: CRAB_ERROR("unexpected boolean binary operation ", op);
     }
     return o;
   }

   inline crab::crab_os& operator<<(crab::crab_os&o, cast_operation_t op) {
     switch (op) {
     case CAST_TRUNC: o << "trunc"; break;
     case CAST_SEXT: o << "sext"; break;
     case CAST_ZEXT: o << "zext"; break;
     default: CRAB_ERROR("unexpected cast operation", op);
     }
     return o;
   }

  template<typename T>
  inline boost::optional<T> conv_op(binary_operation_t op);

  template<typename T>
  inline boost::optional<T> conv_op(bool_binary_operation_t op);

  template<typename T>
  inline boost::optional<T> conv_op(cast_operation_t op);

  // toy language for pointer constraints
  typedef enum  { PTR_EQUALITY, PTR_DISEQUALITY } ptr_cst_kind_t;

  template<typename Variable>
  class pointer_constraint {
   public:

    typedef pointer_constraint <Variable> ptr_cst_t;
    typedef boost::optional<Variable> opt_var_t;

   private:

    opt_var_t _lhs;
    opt_var_t _rhs;
    ptr_cst_kind_t _kind;

    /*
       We can only express constraints of the form p {==,!=} q where
       p,q can be either null or a variable.

       !lhs, !rhs, kind == PTR_EQUALITY    -> null == null -> true
       !lhs, !rhs, kind == PTR_DISEQUALITY -> null != null -> false
       !lhs, rhs, kind == PTR_EQUALITY     -> *rhs == null
       lhs, !rhs, kind == PTR_EQUALITY     -> *lhs == null
       !lhs, rhs, kind == PTR_DISEQUALITY  -> *rhs != null
       lhs, !rhs, kind == PTR_DISEQUALITY  -> *lhs != nul
       lhs, rhs, kind == PTR_EQUALITY      -> *lhs == *rhs
       lhs, rhs, kind == PTR_DISEQUALITY   -> *lhs != *rhs
    */

    pointer_constraint(opt_var_t lhs, opt_var_t rhs, ptr_cst_kind_t kind):
        _lhs(lhs), _rhs(rhs), _kind(kind) {
      if (!_lhs && _rhs){ // normalize
        std::swap(_lhs,_rhs);
      }
    }

   public:

    pointer_constraint() : _kind(PTR_EQUALITY) { }

    // return true iff null != null
    bool is_contradiction() const {
      return (!_lhs && !_rhs && _kind == PTR_DISEQUALITY);
    }

    // return true iff null == null
    bool is_tautology() const {
      return (!_lhs && !_rhs && _kind == PTR_EQUALITY);
    }

    bool is_equality() const {
      return (_kind == PTR_EQUALITY);
    }

    bool is_disequality() const {
      return (_kind == PTR_DISEQUALITY);
    }

    // return true iff  p == null or p != null
    bool is_unary() const {
      return (_lhs && !_rhs);
    }

    // return true iff p == q or p != q
    bool is_binary() const {
      return (_lhs && _rhs);
    }

    Variable lhs() const {
      if (!_lhs) CRAB_ERROR("pointer constraint lhs is null");
      return *_lhs;
    }

    Variable rhs() const {
      if (!_rhs) CRAB_ERROR("pointer constraint rhs is null");
      return *_rhs;
    }

    static ptr_cst_t mk_true() {
      return ptr_cst_t();
    }

    static ptr_cst_t mk_false() {
      return ptr_cst_t(opt_var_t(), opt_var_t(), PTR_DISEQUALITY);
    }

    static ptr_cst_t mk_eq_null(Variable v)  {
      return ptr_cst_t(opt_var_t(v), opt_var_t(), PTR_EQUALITY);
    }

    static ptr_cst_t mk_diseq_null(Variable v) {
      return ptr_cst_t(opt_var_t(v), opt_var_t(), PTR_DISEQUALITY);
    }

    static ptr_cst_t mk_eq(Variable v1, Variable v2)  {
      return ptr_cst_t(opt_var_t(v1), opt_var_t(v2), PTR_EQUALITY);
    }

    static ptr_cst_t mk_diseq(Variable v1, Variable v2)  {
      return ptr_cst_t(opt_var_t(v1), opt_var_t(v2), PTR_DISEQUALITY);
    }

    void write(crab::crab_os& o) const {
      if (is_contradiction() ) {
        o << "false";
      } else if (is_tautology()) {
        o << "true";
      } else {
        assert(_lhs);

        o << lhs();

        if(_kind == PTR_EQUALITY)
          o << " == ";
        else
          o << " != ";

        if (!_rhs)
          o << "NULL";
        else
          o <<  rhs();
      }
    }
  };

  inline crab::crab_os& operator<<(crab::crab_os& o, const ptr_cst_kind_t &k) {
    if (k == PTR_EQUALITY )
      o << " == ";
    else
      o << " != ";
    return o;
  }

  template<typename Variable>
  inline crab::crab_os& operator<<(crab::crab_os& o,
                                   const pointer_constraint<Variable> &cst) {
    cst.write(o);
    return o;
  }
} // end namespace crab

namespace ikos {
  // Numerical type for indexed objects
  typedef uint64_t index_t;

  // Interface for writeable objects
  class writeable {
   public:
    virtual void write(crab::crab_os& o) = 0;
    virtual ~writeable() {}
  }; // class writeable

  inline crab::crab_os& operator<<(crab::crab_os& o, writeable& x) {
    x.write(o);
    return o;
  }

  // Container for typed variables used by the crab abstract domains
  // and linear_constraints.
  template< typename Number, typename VariableName >
  class variable {
    // XXX: template parameter Number is required even if the class
    // does not use it.  This allows, e.g., linear_constraint to
    // deduce the kind of Number from constraints like x < y.

   public:

    typedef variable< Number, VariableName > variable_t;
    typedef typename VariableName::index_t index_t;
    typedef unsigned bitwidth_t;
    typedef crab::variable_type type_t;
    typedef Number number_t;
    typedef VariableName varname_t;

  private:

    VariableName _n;
    type_t _type;
    bitwidth_t _width;

   public:

    /**
     * DO NOT USE this constructor to create a CFG since all CFG
     * statements must be strongly typed.  This constructor is
     * intended to be used only abstract domains to generate temporary
     * variables.
     **/
    explicit variable(const VariableName& n)
      : _n(n), _type(crab::UNK_TYPE), _width(0) { }

   public:

    variable(const VariableName& n, type_t type)
      : _n(n), _type(type), _width(0) { }

    variable(const VariableName& n, type_t type, bitwidth_t width)
      : _n(n), _type(type), _width(width) { }

    variable(const variable_t& o)
      : _n(o._n), _type(o._type), _width(o._width) { }

    variable(variable_t &&o)
      : _n(std::move(o._n)), _type(std::move(o._type)), _width(std::move(o._width)) { }

    variable_t& operator=(const variable_t &o) {
      if (this != &o) {
        _n = o._n;
	_type = o._type;
	_width = o._width;
      }
      return *this;
    }

    bool is_typed() const { return _type != crab::UNK_TYPE; }

    bool is_array_type() const {
      return is_typed() && _type >= crab::ARR_BOOL_TYPE;
    }

    bool is_int_type() const {
      return _type == crab::INT_TYPE;
    }

    bool is_bool_type() const {
      return _type == crab::BOOL_TYPE;
    }

    bool is_ptr_type() const {
      return _type == crab::PTR_TYPE;
    }

    type_t get_type() const { return _type;}

    bool has_bitwidth() const { return _width > 0; }

    bitwidth_t get_bitwidth() const { return _width;}

    const VariableName& name() const { return _n; }

    // Cannot be const because from VariableName we might want to
    // access to its variable factory to create e.g., new
    // VariableName's.
    VariableName& name() { return _n;}

    index_t index() const { return _n.index(); }

    std::size_t hash() const {
      return (size_t) _n.index();
    }

    bool operator==(const variable_t& o) const {
      return _n.index() == o._n.index();
    }

    bool operator!=(const variable_t& o) const {
      return (!(operator==(o)));
    }

    bool operator<(const variable_t& o) const {
      return _n.index() < o._n.index();
    }

    void write(crab::crab_os& o) const {
      o << _n;
    }

  }; // class variable

  template< typename Number, typename VariableName >
  class variable_ref {
   public:

    typedef variable< Number, VariableName > variable_t;
    typedef typename variable_t::index_t index_t;
    typedef typename variable_t::bitwidth_t bitwidth_t;
    typedef typename variable_t::type_t type_t;
    typedef variable_ref<Number, VariableName> variable_ref_t;
    typedef Number number_t;
    typedef VariableName varname_t;

  private:

    std::shared_ptr<variable_t> m_v;

   public:

    variable_ref(): m_v(nullptr) {}

    variable_ref(variable_t v): m_v(std::make_shared<variable_t>(v)) { }

    bool is_null() const {
      return !m_v;
    }

    variable_t get() const {
      assert(!is_null());
      return *m_v;
    }

    bool is_typed() const {
      assert(!is_null());
      return m_v->is_typed();
    }

    bool is_array_type() const {
      assert(!is_null());
      return m_v->is_array_type();
    }

    bool is_int_type() const {
      assert(!is_null());
      return m_v->is_int_type();
    }

    bool is_bool_type() const {
      assert(!is_null());
      return m_v->is_bool_type();
    }

    bool is_ptr_type() const {
      assert(!is_null());
      return m_v->is_ptr_type();
    }

    type_t get_type() const {
      assert(!is_null());
      return m_v->get_type();
    }

    bool has_bitwidth() const {
      assert(!is_null());
      return m_v->has_bitwidth();
    }

    bitwidth_t get_bitwidth() const {
      assert(!is_null());
      return m_v->get_bitwidth();
    }

    const VariableName& name() const {
      assert(!is_null());
      return m_v->name();
    }

    VariableName& name() {
      assert(!is_null());
      return m_v->name();
    }

    index_t index() const {
      assert(!is_null());
      return m_v->index();
    }

    std::size_t hash() const {
      assert(!is_null());
      return m_v->hash();
    }

    bool operator==(const variable_ref_t& o) const {
      assert(!is_null());
      return m_v->operator==(o);
    }

    bool operator!=(const variable_ref_t& o) const {
      assert(!is_null());
      return m_v->operator!=(o);
    }

    bool operator<(const variable_ref_t& o) const {
      assert(!is_null());
      return m_v->operator<(o);
    }

    void write(crab::crab_os& o) const {
      return m_v->write(o);
    }
  }; // class variable_ref

  /* used by boost::hash_combine */
  template< typename Number, typename VariableName >
  inline size_t hash_value(const variable<Number, VariableName> &v) {
    return v.hash();
  }

  /* used by boost::hash_combine */
  template< typename Number, typename VariableName >
  inline size_t hash_value(const variable_ref<Number, VariableName> &v) {
    return v.hash();
  }

  template<typename Number, typename VariableName>
  inline crab::crab_os& operator<<(crab::crab_os& o,
				   const variable<Number, VariableName> &v) {
    v.write(o);
    return o;
  }

  template<typename Number, typename VariableName>
  inline crab::crab_os& operator<<(crab::crab_os& o,
				   const variable_ref<Number, VariableName> &v) {
    v.write(o);
    return o;
  }
} // end namespace ikos

namespace crab {
  namespace domains {
    using namespace ikos;
  }
}

#ifdef BOOST_NO_EXCEPTIONS
namespace boost {
template<class E>
void throw_exception(E const &e) {
  std::exit(1);
}
}
#endif

/** specialization for std::hash for variables **/
namespace std {
template<typename Number, typename VariableName>
struct hash<ikos::variable<Number, VariableName>> {
  using variable_t = ikos::variable<Number, VariableName>;
  size_t operator()(const variable_t& v) const {
    return v.hash();
  }
};

template<typename Number, typename VariableName>
struct hash<ikos::variable_ref<Number, VariableName>> {
  using variable_ref_t = ikos::variable_ref<Number, VariableName>;
  size_t operator()(const variable_ref_t& v) const {
    return v.hash();
  }
};
}


text: #include <boost/spirit/home/support/nonterminal/expand_arg.hpp>


text:
//
// Copyright 2018 Pixar
//
// Licensed under the Apache License, Version 2.0 (the "Apache License")
// with the following modification; you may not use this file except in
// compliance with the Apache License and the following modification to it:
// Section 6. Trademarks. is deleted and replaced with:
//
// 6. Trademarks. This License does not grant permission to use the trade
//    names, trademarks, service marks, or product names of the Licensor
//    and its affiliates, except as required to comply with Section 4(c) of
//    the License and to reproduce the content of the NOTICE file.
//
// You may obtain a copy of the Apache License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the Apache License with the above modification is
// distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the Apache License for the specific
// language governing permissions and limitations under the Apache License.
//

#include "pxr/pxr.h"
#include "pxr/base/tf/declarePtrs.h"
#include "pxr/base/tf/pyPtrHelpers.h"
#include "pxr/base/tf/pyResultConversions.h"
#include "pxr/base/tf/pyStaticTokens.h"
#include "pxr/base/tf/weakPtr.h"
#include "pxr/usd/sdr/shaderNode.h"
#include "pxr/usd/sdr/shaderProperty.h"

#include <boost/python.hpp>
#include <boost/python/return_internal_reference.hpp>

using namespace boost::python;

PXR_NAMESPACE_USING_DIRECTIVE

// Boost treats a const ptr differently than a non-const ptr, so a custom
// converter is needed to deal with the const-ness
struct SdrShaderNodeConstPtrToPythonConverter
{
    static PyObject* convert(SdrShaderNodeConstPtr shaderNode) {
        object shaderNodeObject(ptr(shaderNode));

        return incref(shaderNodeObject.ptr());
    }
};

void wrapShaderNode()
{
    typedef SdrShaderNode This;
    typedef SdrShaderNodePtr ThisPtr;

    TF_PY_WRAP_PUBLIC_TOKENS(
        "NodeMetadata", SdrNodeMetadata, SDR_NODE_METADATA_TOKENS
    );
    TF_PY_WRAP_PUBLIC_TOKENS(
        "NodeContext", SdrNodeContext, SDR_NODE_CONTEXT_TOKENS
    );

    TF_PY_WRAP_PUBLIC_TOKENS(
        "NodeRole", SdrNodeRole, SDR_NODE_ROLE_TOKENS
    );

    return_value_policy<copy_const_reference> copyRefPolicy;
    to_python_converter<SdrShaderNodeConstPtr,
                        SdrShaderNodeConstPtrToPythonConverter>();

    class_<This, ThisPtr, bases<NdrNode>, boost::noncopyable>("ShaderNode", no_init)
        .def("GetShaderInput", &This::GetShaderInput,
            return_internal_reference<>())
        .def("GetShaderOutput", &This::GetShaderOutput,
            return_internal_reference<>())
        .def("GetAssetIdentifierInputNames", &This::GetAssetIdentifierInputNames,
            return_value_policy<TfPySequenceToList>())
        .def("GetDefaultInput", &This::GetDefaultInput,
            return_internal_reference<>())
        .def("GetLabel", &This::GetLabel, copyRefPolicy)
        .def("GetCategory", &This::GetCategory, copyRefPolicy)
        .def("GetHelp", &This::GetHelp)
        .def("GetDepartments", &This::GetDepartments, copyRefPolicy)
        .def("GetPages", &This::GetPages, copyRefPolicy)
        .def("GetPrimvars", &This::GetPrimvars, copyRefPolicy)
        .def("GetAdditionalPrimvarProperties",
            &This::GetAdditionalPrimvarProperties, copyRefPolicy)
        .def("GetImplementationName", &This::GetImplementationName)
        .def("GetRole", &This::GetRole)
        .def("GetPropertyNamesForPage", &This::GetPropertyNamesForPage)
        .def("GetAllVstructNames", &This::GetAllVstructNames)
        ;
}

max_stars_repo_name: DougRogers-DigitalFish/USD

max_issues_repo_name: DougRogers-DigitalFish/USD

max_forks_repo_name: DougRogers-DigitalFish/USD


text:
/*!
 @file   LFW.cpp
 @author David Hirvonen
 @brief  High level routines for parsing LFW data.

 \copyright Copyright 2014-2016 Elucideye, Inc. All rights reserved.
 \license{This project is released under the 3 Clause BSD License.}

 */

//#define BOOST_SPIRIT_DEBUG

#include "landmarks/LFW.h"

#include <fstream>

#include <boost/spirit/include/qi.hpp>
#include <boost/spirit/include/phoenix.hpp>

namespace ph = boost::phoenix;
namespace qi = boost::spirit::qi;
namespace ascii = boost::spirit::ascii;

DRISHTI_BEGIN_NAMESPACE(LFW)

struct record
{
    std::string filename;
    cv::Rect roi;
    std::vector<cv::Point2f> points;
};

struct Table
{
    std::vector<record> lines;
};

DRISHTI_END_NAMESPACE(LFW)

// clang-format off
BOOST_FUSION_ADAPT_STRUCT(
    cv::Rect,
    (int, x)
    (int, y)
    (int, width)
    (int, height)
 )
// clang-format on

// clang-format off
BOOST_FUSION_ADAPT_STRUCT(
    LFW::Table,
    (std::vector<LFW::record>, lines)
)
// clang-format on

// clang-format off
BOOST_FUSION_ADAPT_STRUCT(
    LFW::record,
    (std::string, filename)
    (cv::Rect, roi)(std::vector<cv::Point2f>, points)
)
// clang-format on

DRISHTI_BEGIN_NAMESPACE(LFW)

template <typename Iterator, typename Skipper = qi::blank_type>
struct lfw_parser : qi::grammar<Iterator, LFW::Table(), Skipper>
{
    lfw_parser()
        : lfw_parser::base_type(start)
    {
        point = qi::float_ >> qi::float_;
        points = qi::repeat(5)[point];
        roi = qi::int_ >> qi::int_ >> qi::int_ >> qi::int_;
        filename = qi::lexeme[+(qi::char_ - qi::blank)];
        line = filename >> roi >> points >> qi::eol;
        start = +line >> qi::eoi;

        //BOOST_SPIRIT_DEBUG_NODES( (start)(line)(filename)(roi)(point)(points) )
    }

    qi::rule<Iterator, cv::Point2f(), Skipper> point;
    qi::rule<Iterator, std::vector<cv::Point2f>(), Skipper> points;
    qi::rule<Iterator, cv::Rect(), Skipper> roi;
    qi::rule<Iterator, std::string(), Skipper> filename;
    qi::rule<Iterator, LFW::record(), Skipper> line;
    qi::rule<Iterator, LFW::Table(), Skipper> start;
};

DRISHTI_END_NAMESPACE(LFW)

FACE::Table parseLFW(const std::string& filename)
{
    FACE::Table table;
    table.eyeR = { 0 };
    table.eyeL = { 1 };
    table.nose = { 2 };
    table.mouth = { 3, 4 };
    table.mouthR = { 3 };
    table.mouthL = { 4 };

    // open file, disable skipping of whitespace
    std::ifstream file(filename);

    if (file)
    {
        file.unsetf(std::ios::skipws);
        boost::spirit::istream_iterator begin(file), end;
        LFW::lfw_parser<decltype(begin)> parser;

        LFW::Table result;
        bool success = qi::phrase_parse(begin, end, parser, qi::blank, result);

        table.lines.resize(result.lines.size());
        for (int i = 0; i < result.lines.size(); i++)
        {
            table.lines[i].roi = result.lines[i].roi;
            table.lines[i].filename = result.lines[i].filename;
            table.lines[i].points = result.lines[i].points;
        }
    }

    return table;
}

max_stars_repo_name: roscopecoltran/SniperKit-Core

max_issues_repo_name: roscopecoltran/SniperKit-Core

max_forks_repo_name: roscopecoltran/SniperKit-Core