text:
// Copyright Oleg Maximenko 2014.
// 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)
//
// See http://github.com/svgpp/svgpp for library home page.

#pragma once

#include <boost/array.hpp>
#include <boost/spirit/include/qi.hpp>
#include <boost/spirit/include/phoenix.hpp>
#include <svgpp/parser/detail/common.hpp>
#include <svgpp/policy/transform_events.hpp>

namespace svgpp
{

namespace qi = boost::spirit::qi;

template <
  class Iterator,
  class Context,
  class Number = double,
  class EventsPolicy = policy::transform_events::default_policy<Context> >
class transform_grammar: public qi::grammar<Iterator, void (Context &), detail::character_encoding_namespace::space_type>
{
  typedef transform_grammar<Iterator, Context, Number, EventsPolicy> this_type;
public:
  transform_grammar()
    : this_type::base_type(transforms)
  {
    namespace phx = boost::phoenix;
    using qi::_1;
    using qi::_2;
    using qi::_3;
    using qi::_4;
    using qi::_5;
    using qi::_6;
    using qi::_a;
    using qi::_b;
    using qi::_c;
    using qi::_r1;
    using qi::lit;
    using qi::no_skip;

    transforms
        =  -( ( matrix(_r1)
              | translate(_r1)
              | scale(_r1)
              | rotate(_r1)
              | skewX(_r1)
              | skewY(_r1)
              )
              %
#ifdef SVGPP_STRICT_TRANSFORM_SEPARATOR
                (+no_skip[comma_wsp])
#else
                (*lit(','))
#endif
            );

    matrix
        =   ( lit("matrix")
              >> lit('(')
              >> number >> no_skip[comma_wsp]
              >> number >> no_skip[comma_wsp]
              >> number >> no_skip[comma_wsp]
              >> number >> no_skip[comma_wsp]
              >> number >> no_skip[comma_wsp]
              >> number >> lit(')')
            ) [phx::bind(&call_matrix, _r1, _1, _2, _3, _4, _5, _6)];
    translate
        =   lit("translate")
            >> lit('(')
            >> number [_a = _1]
            >> ( ( no_skip[comma_wsp]
                  >> number [_b = _1]
                  >> lit(')') [phx::bind(&transform_grammar::call_translate, _r1, _a, _b)]
                )
                | lit(')') [phx::bind(&transform_grammar::call_translate_x, _r1, _a)]
              );
    scale
        =   lit("scale")
            >> lit('(')
            >> number [_a = _1]
            >> ( ( no_skip[comma_wsp]
                  >> number [_b = _1]
                  >> lit(')') [phx::bind(&transform_grammar::call_scale, _r1, _a, _b)]
                )
                | lit(')') [phx::bind(&transform_grammar::call_scale_uniform, _r1, _a)]
              );
    rotate
        =   lit("rotate")
            >> lit('(')
            >> number[_a = _1]
            >> ( ( no_skip[comma_wsp]
                  >> number [_b = _1]
                  >> no_skip[comma_wsp]
                  >> number [_c = _1]
                  >> lit(')') [phx::bind(&transform_grammar::call_rotate_about_point, _r1, _a, _b, _c)]
                )
                | lit(')') [phx::bind(&transform_grammar::call_rotate, _r1, _a)]
              );
    skewX
        =   ( lit("skewX")
              >> lit('(')
              >> number
              >> lit(')') ) [phx::bind(&transform_grammar::call_skew_x, _r1, _1)];
    skewY
        =   ( lit("skewY")
              >> lit('(')
              >> number
              >> lit(')') ) [phx::bind(&transform_grammar::call_skew_y, _r1, _1)];
  }

private:
  typename this_type::start_type transforms;
  qi::rule<Iterator, void (Context &), typename this_type::skipper_type>
    matrix, skewX, skewY;
  qi::rule<Iterator, void (Context &), qi::locals<Number, Number>, typename this_type::skipper_type>
    translate, scale;
  qi::rule<Iterator, void (Context &), qi::locals<Number, Number, Number>, typename this_type::skipper_type>
    rotate;
  detail::comma_wsp_rule<Iterator> comma_wsp;
  qi::real_parser<Number, detail::svg_real_policies<Number> > number;

  static void call_matrix(Context & context, Number a, Number b, Number c, Number d, Number e, Number f)
  {
    boost::array<Number, 6> const matrix = {{a, b, c, d, e, f}};
    EventsPolicy::transform_matrix(context, matrix);
  }

  static void call_translate(Context & context, Number tx, Number ty)
  {
    EventsPolicy::transform_translate(context, tx, ty);
  }

  static void call_translate_x(Context & context, Number tx)
  {
    EventsPolicy::transform_translate(context, tx);
  }

  static void call_scale(Context & context, Number sx, Number sy)
  {
    EventsPolicy::transform_scale(context, sx, sy);
  }

  static void call_scale_uniform(Context & context, Number scale)
  {
    EventsPolicy::transform_scale(context, scale);
  }

  static void call_rotate(Context & context, Number angle)
  {
    EventsPolicy::transform_rotate(context, angle);
  }

  static void call_rotate_about_point(Context & context, Number angle, Number cx, Number cy)
  {
    EventsPolicy::transform_rotate(context, angle, cx, cy);
  }

  static void call_skew_x(Context & context, Number angle)
  {
    EventsPolicy::transform_skew_x(context, angle);
  }

  static void call_skew_y(Context & context, Number angle)
  {
    EventsPolicy::transform_skew_y(context, angle);
  }
};

}

max_stars_repo_name: RichardCory/svgpp


text:
/******************************************************************************
* @file Contains widely usable defines and macros and
* generic utility/convenience functions.
*
* @author barn
* @version 160118
******************************************************************************/
#pragma once

///////////////////////////////////////////////////////////////////////////////
// DEFINES and MACROS

/// enhanced delete call
#define DESTROY( pointer) \
    if(pointer) { \
        delete pointer; \
        pointer=0; \
    }

/// a classical exit macro for console applications
#define CONSOLE_EXIT( return_value) \
    getch(); \
    exit(return_value);

/// EXIT macro
#define EXIT(return_value) CONSOLE_EXIT(return_value)

/// ultra short things only for private usage ;)
#ifdef HELLO

    #pragma warning(disable:4244) // Konvertierung 'Konvertierung' von 'Typ1' nach 'Typ2', Datenverlust möglich

    #define $ std::cout << std::endl <<
    #define $e std::cout << std::endl;

    /// cout with preceeding endl command
    #define coutl std::cout << std::endl

    /// TAB like std::endl
    #define TAB "\t"
    #define TAB2 "\t\t"
    #define TAB3 "\t\t\t"
    #define TAB4 "\t\t\t\t"

    // shortcut for loop
    #define FORTO( a, b)        for( int i = a; i < b; ++i)
    #define FORALL( CONTAINER)  for( auto it = CONTAINER.begin(); it != CONTAINER.end(); ++it)

#endif

///////////////////////////////////////////////////////////////////////////////
// NAMESPACE, CONSTANTS, TYPE DECLARATIONS/IMPLEMENTATIONS and FUNCTIONS

typedef unsigned int uint;

#include <limits>
/** Checks if a given number is bigger than the type boundaries,
 *  e.g. if a number is infinite..
 *  With C++11 consider using std::isinf.
 * @param v The value to be checked.
 * @return TRUE, if the number is infinite,
 *        FALSE if the given value is not.
 */
template<typename T>
inline bool is_inf( const T &v ) {
    return ! ( -std::numeric_limits<T>::max() <= v &&
                std::numeric_limits<T>::max() >= v );
}

/** Checks whether a given number not a number.
 * With C++11 consider using std::isnan.
 * @param v The value to be checked.
 * @return TRUE, if the number is NaN,
 *        FALSE if the given value is not.
 */
template<typename T>
inline bool is_nan( const T &v) {
    return v != v; // yep
}

/** Checks wethers a given number is a valid number,
 * e.g. is finite and is not NaN.
 * With C++11 consider using std::isnan and std::isinf.
 * @param v The value to be checked.
 * @return TRUE if the given value is a valid number,
 *         FALSE if it is not.
 */
template<typename T>
inline bool is_valid( const T &v) {
    return ! is_inf(v) && ! is_nan(v);
}

/** Wraps the value of val into the range [0;upper_limit].
 * You could use it for e.g. wrapping degrees like 721° to a [0;360]° range.
 * @param val The value to be wrapped.
 * @param upper_limit The upper limit to which to wrap.
 * Values bigger than upper_limit will be wrapped.
 * @return The wrapped value.
 */
inline double wrap( double val, double upper_limit=360 ) {
    return abs( val - upper_limit * floor( val / upper_limit ));
}

/** Retrieves the smallest signed distance between two angles.
 * @param angle 1 An angle.
 * @param angle 2 An angle.
 * @return The smallest signed distance between the two angles.
 */
inline double angle_diff( double angle1, double angle2) {
     return wrap(angle1 - angle2 + 180) - 180;
}

#include <conio.h>
/** Convenience function for non-blocking getch().
 * @return The value that would be returned by getch()
 */
inline int nb_getch() {
    return _kbhit() ? _getch() : 0;
}

#include <fstream>
/** Checks, whether a file exists or not.
 * It uses an fstream to open & close a file
 * and checks the fail bit of the fstream.
 * Doesn't consider capital letters/non-capital letters.
 * Don't use it if you just want to check whether a file
 * exists to open it.
 * ! If you do more stuff with the file system consider
 * using Boost.Filesystem or if Cpp x11 is available
 * the filesystem module of the STL !
 * @param fname The filename.
 * @return
 * Returns TRUE, if the file exists,
 * returns FALSE if the file does not exist.
 */
inline bool file_exists( const char* fname) {
    std::fstream file;
    file.open( fname, std::ios::in);
    file.close();
    return !file.fail();
}

#include <fstream>
/** Checks, whether a file exists or not.
 * It uses an fstream to open & close a file
 * and checks the fail bit of the fstream.
 * Doesn't consider capital letters/non-capital letters.
 * Don't use it if you just want to check whether a file
 * exists to open it.
 * ! If you do more stuff with the file system consider
 * using Boost.Filesystem or if Cpp x11 is available
 * the filesystem module of the STL !
 * @param fname The filename.
 * @return
 * Returns TRUE, if the file exists,
 * returns FALSE if the file does not exist.
 */
inline bool file_exists( const std::string& fname ) {
    std::fstream file;
    file.open( fname, std::ios::in);
    file.close();
    return !file.fail();
}

#include <ostream>
/** Stream out oparator on pairs.
 * @param os An ostream.
 * @param float_pair A std::pair.
 * @return The ostream that was the first parameter.
 */
template< class T>
inline std::ostream& operator<<(std::ostream& os, const std::pair<T,T>& float_pair) {
    os << float_pair.first << ";\t" << float_pair.second;
    return os;
}

#include <sstream>
/** from_stream for stl containers.
 * Containers should implement push_back in order to work correctly.
 * @param in_stream The container in an istream form, spaces are supposed to be the delimeters.
 * @return A container consisting of the elements found in the stream.
 */
template< typename F, template<class T, class = std::allocator<T> > class container_type >
container_type<F> from_stream( std::istream& in_stream ) {
    container_type<F> ret;
    std::copy( std::istream_iterator<F>(in_stream),
               std::istream_iterator<F>(),
               std::back_inserter(ret));
    if( in_stream.fail() && !in_stream.eof())
        std::cerr << "Error: " << __FILE__ << "::from_stream(): could not parse read stream until end.";
    return ret;
}

#include <string>
#include <sstream>
/** Puts all numbers in a given string into an stl container.
 * The container type must be able to perform push_back().
 * @param str The string that is to be converted into a container.
 * @return An stl container of a given numerical type.
 */
template< typename F, template<class T, class = std::allocator<T> > class container_type >
inline container_type<F> from_string( const std::string& str) {
    return from_stream<F, container_type>( std::istringstream(str));
}

#include <algorithm>
#include <iterator>
#include <ostream>
/** Stream out operator on stl compliant containers such as lists and vectors.
* @param os An ostream.
* @param container An stl compliant container.
* @return The ostream that was the first parameter.
*/
template< typename F, template<class T, class = std::allocator<T> > class container_type >
std::ostream& operator<<(std::ostream& os, const container_type<F>& container) {
    copy(container.begin(), std::prev(container.end()), std::ostream_iterator<F>(os, ", "));
    os << container.back();
    return os;
}

#include <string>
/** Trims a string from and only from white spaces, tabs and newlines.
 * @param str Reference to the string that is to be trimmed.
 * @return Returns the given (trimmed) string.
 */
inline std::string& trim( std::string& str) {
    size_t last_char;
    str.erase(0,str.find_first_not_of(" \t\n"));
    last_char = str.find_last_not_of(" \t\n")+1;
    str.erase(last_char, str.size()-last_char);
    return str;
}

#include <algorithm>
#include <iterator>
#include <sstream>
/** to-string for stl containers like vectors and stacks.
 * @param The container to be converted to a string.
 * @param The delimeter of the list elements.
 * @return A string consisting of the elements of the container.
 */
template< typename F, template<class T, class = std::allocator<T> > class container_type >
inline std::string to_string( const container_type<F>& container, const char* delimeter = "; ") {
    std::stringstream ss;
    for(auto it = container.begin(); std::next(it)!=container.end(); ++it)
        ss << *it << delimeter;
    ss << container.back();
    return ss.str();
}

#include <algorithm>
#include <string>
/** Converts all capital letters in a to lower case.
 * @param s The input string.
 * @return The input string for the sake of inline usage.
 */
inline std::string& to_lower( std::string& s) {
    std::transform(s.begin(), s.end(), s.begin(), ::tolower);
    return s;
}

#include <algorithm>
#include <string>
/** Copies the given string in a new lower case string.
 * @param s The input string.
 * @return The input string for the sake of inline usage.
 */
inline std::string to_lower( const std::string& s) {
    std::string ret = s;
    return to_lower( ret);
}

#include <sstream>
/** Converts an integer value into a string.
 * !!! better use stdlib.h itoa(int value, char* str, int base) if available !!!
 * @param an arbitrary integer value.
 * @return The specified integer value as a string.
 */
inline std::string itos( int i) {
        std::stringstream s;
        s << i;
        return s.str();
}

/** Returns the next bigger number that is a power of two.
 * @param num The input number
 * @return A number greater or equal to the input number that is a power of two.
 */
uint next_pow_two( uint num) {

    uint ret = num > 0 ? num - 1 : 0;
    ret |= ret >> 1;
    ret |= ret >> 2;
    ret |= ret >> 4;
    ret |= ret >> 8;
    ret |= ret >> 16;

    return ++ret;
}

/** Fills an given array with the digits of a given number.
 * TODO: not tested yet!!
 * @param out_array The array to be filled.
 * Must at least have digit_count slots.
 * The highest digit will be stored into the first slot and so on.
 * E.g. the number 1236 will be stored in the following way:
 * out_array[0] = 1
 * out_array[1] = 2
 * out_array[2] = 3
 * out_array[3] = 6
 * @param i The number to be decomposed.
 * @param digit_count The number of digits in i.
 * Usually something like floor(log10(i)+1) or less.
 */
template<typename T>
void get_digits(int* out_array, T i, int digit_count) {
    do {
        int digit = i % 10;
        i /= 10;
        out_array[--digit_count] = digit;
    } while (i > 0);
}

/** Returns the nearest power of two to the given number.
 * @param num the number.
 * @return The next nearest power of two.
 * In this implementation, when num=0, the return value will be 0,
 * if num is already power of two, the next bigger power of 2 will be
 * returned.
 */
uint next_pow_two_fast(uint num) {
    uint j, k;
    (j = num & 0xFFFF0000) || (j = num);
    (k = j   & 0xFF00FF00) || (k = j);
    (j = k   & 0xF0F0F0F0) || (j = k);
    (k = j   & 0xCCCCCCCC) || (k = j);
    (j = k   & 0xAAAAAAAA) || (j = k);
    return j << 1;
}

#include <algorithm> // all_of
#include <string>
/** Checks if all characters of the given string are digits.
 * @param str A string
 * @return Returns TRUE, if all characters in str are digits
 *                 FALSE, if any character is no digit.
 */
inline bool is_digits(const std::string &str) {
    return std::all_of(str.begin(), str.end(), ::isdigit); // C++11
}

#include <string>
#include <conio.h>
/**
 * Captures the input until ENTER is pressed or the maximum string buffer size (1024)
 * is reached. DEL deletes the last character.
 * @return The string that is captured until ENTER is pressed
 * or the maximum string buffer size is reached.
 */
std::string read_line() {
    const unsigned int max_buffer_length = 1024;
    char ret[max_buffer_length]("\0");
    unsigned int cursor(0);

    // non-blocking getch
    int kbval ( _kbhit() ? _getch() : 0);

    while( 13!=kbval ) {
        // until ENTER is pressed

        if(0==kbval) {
            // NOTHING
        } else if( 8==kbval && cursor > 0) {
            // DEL
            ret[--cursor] = '\0';
        } else if(cursor < max_buffer_length) {
            // ORDINARY CHARACTERS
            ret[cursor++] = unsigned char(kbval);
        }
        kbval = _kbhit() ? _getch() : 0;
    }
    return std::string(ret);
}

#include <iostream>
#include <string>
/** Open file error callback function originally for getlines_from_file().
 * @param fname The filename.
 * @see getlines_from_file()
 * @see to_file()
 */
inline void on_open_file_error( const std::string& fname) {
    std::cerr << "Error opening file \"" << fname << "\".\n";
}

#include <iostream>
#include <string>
/** Read line error callback function originally for getlines_from_file().
 * @param fname The filename.
 * @see getlines_from_file()
 */
inline void on_read_file_error( const std::string& fname) {
    std::cerr << "Error while reading file \"" << fname << "\".\n";
}

#include <iostream>
#include <string>
/** Read line error callback function originally for getlines_from_file().
 * @param fname The filename.
 * @param line The line number (0-based indexing) [sic].
 * @see getlines_from_file()
 */
inline void on_read_file_line_error( const std::string& fname, unsigned int line) {
    std::cerr << "Error while reading file \"" << fname << "\" at line " << line+1 << " (1-based indexing).";
}

#include <iostream>
#include <string>
/** Write error callback function originally for to_file().
 * @param fname The filename.
 * @see to_file()
 */
inline void on_write_file_error(const std::string& fname) {
    std::cerr << "Error writing to file \"" << fname << "\".\n";
}

#include <fstream>
#include <functional>
#include <string>
/** Convenience function that reads and processes every line in a file.
 * It opens the file, reads, and processes every line via a specified callback and then closes the file.
 * It does proper opening and error handling with help of the specified callback functions for the two error cases.
 * @param filename The path of the file to be read.
 * @param callback The function that is to be called for every line.
 *        It takes a string as an argument which will be set to the line read.
 * @param error_open_callback The function that is to be called when the file could not be openend.
 *        It takes a string as an argument which will be set to the original given filename.
 * @param error_read_callback The function that is called when there occured an error while reading the file.
 *        It takes a string as an argument which will be set to the original given filename.
 * @return TRUE in case of success,
 *         FALSE in case of error.
 */
bool getlines_from_file( const std::string& filename,
                std::function< void(std::string&) > callback,
                std::function< void(const std::string&) > error_open_callback = on_open_file_error,
                std::function< void(const std::string&) > error_read_callback = on_read_file_error) {
    bool ret(true);
    std::ifstream in_stream( filename);
    if( !in_stream.is_open()) {
        error_open_callback( filename);
        ret = false;
    }
    std::string line;
    while( getline(in_stream, line))
        callback(line);
    if(in_stream.bad()) {
        error_read_callback(filename);
        ret = false;
    }
    in_stream.close();
    return ret;
}

#include <fstream>
#include <functional>
#include <string>
/** Convenience function that writes the contents of a container to a specified file.
 * Truncates all old entries in that given file.
 * Also does error handling via callbacks.
 * @param filename The name of the file to be written to.
 * @param container The stl-compliant container to be written to file.
 * @param delimeter The delimeter between each entry in the container.
 * @param error_open_callback The function that is called when opening the file fails.
 *        It takes a string (the filename) as an argument.
 * @param error_write_callback The function that is called when writing to the file fails.
 *        It takes a string (the filename) as an argument.
 * @return TRUE in case of success,
 *         FALSE in case of error.
 */
template< typename F, template<class T, class = std::allocator<T> > class container_type > /* for vectors and stuff */
bool to_file( const std::string& filename,
              const container_type<F>& container,
              const std::string& delimeter = "\n",
              std::function< void(const std::string&) > error_open_callback = on_open_file_error,
              std::function< void(const std::string&) > error_write_callback = on_write_file_error) {
    bool ret(true);
    std::ofstream fstream( filename, std::ios::out | std::ios::trunc);
    if(!fstream.is_open() || fstream.bad()) {
        error_open_callback(filename);
        ret = false;
    } else {
        for( auto it=container.begin(); it!=container.end(); ++it) {
            fstream << *it;
            if( std::next(it) != container.end())
                    fstream << delimeter;

            if( fstream.bad()) {
                error_write_callback(filename);
                ret = false;
                break;
            }
        }
    }
    return ret;
}

#include <fstream>
#include <functional>
#include <string>
/** Convenience function that writes the contents of a container to a specified file.
 * Truncates all old entries in that given file.
 * Also does error handling via callbacks.
 * @param filename The name of the file to be written to.
 * @param container The stl-compliant container to be written to file.
 * @param delimeter The delimeter between each entry in the container.
 * @param error_open_callback The function that is called when opening the file fails.
 *        It takes a string (the filename) as an argument.
 * @param error_write_callback The function that is called when writing to the file fails.
 *        It takes a string (the filename) as an argument.
 * @return TRUE in case of success,
 *         FALSE in case of error.
 */
template< typename F, template<class T, class = std::less<T>, class = std::allocator<T> > class container_type > /* for sets and stuff */
bool to_file( const std::string& filename,
              const container_type<F>& container,
              const std::string& delimeter = "\n",
              std::function< void(const std::string&) > error_open_callback = on_open_file_error,
              std::function< void(const std::string&) > error_write_callback = on_write_file_error) {
    bool ret(true);
    std::ofstream fstream( filename, std::ios::out | std::ios::trunc);
    if(!fstream.is_open() || fstream.bad()) {
        error_open_callback(filename);
        ret = false;
    } else {
        for( auto it=container.begin(); it!=container.end(); ++it) {
            fstream << *it;
            if( std::next(it) != container.end())
                    fstream << delimeter;

            if( fstream.bad()) {
                error_write_callback(filename);
                ret = false;
                break;
            }
        }
    }
    return ret;
}

#include <fstream>
#include <functional>
#include <string>
/** Convenience function that writes the contents of an array to a specified file.
 * Truncates all old entries in that given file.
 * Also does error handling via callbacks.
 * @param filename The name of the file to be written to.
 * @param array The array to be written to file.
 * @param array_size The number of array elements.
 * @param delimeter The delimeter between each entry in the container.
 * @param error_open_callback The function that is called when opening the file fails.
 *        It takes a string (the filename) as an argument.
 * @param error_write_callback The function that is called when writing to the file fails.
 *        It takes a string (the filename) as an argument.
 * @return TRUE in case of success,
 *         FALSE in case of error.
 */
template< typename T>
bool to_file( const std::string& filename,
              const T* array,
              const unsigned int array_size,
              const std::string& delimeter = "\n",
              std::function< void(const std::string&) > error_open_callback  = on_open_file_error,
              std::function< void(const std::string&) > error_write_callback = on_write_file_error) {
    bool ret(true);
    std::ofstream fstream( filename, std::ios::out | std::ios::trunc);
    if(!fstream.is_open() || fstream.bad()) {
        error_open_callback(filename);
        ret = false;
    } else {
        for( int i=0; i<array_size;) {
            fstream << array[i];
            if( ++i != array_size)
                fstream << delimeter;

            if( fstream.bad()) {
                error_write_callback(filename);
                ret = false;
                break;
            }
        }
    }
    return ret;
}

/** Convenience function that appends the given stl compliant container of type string
 * with the lines found in the given file. In error case it calls the given callbacks.
 * @param fname The path to the file to be read.
 * @param out_container The stl compliant container of in which the read found lines
 *        shall be written. The container must support push_back().
 * @param error_open_callback The function that is to be called when the file could not be openend.
 *        It takes a string as an argument which will be set to the original given filename.
 * @param error_read_callback The function that is called when there occured an error while reading the file.
 *        It takes a string as an argument which will be set to the original given filename.
 * @return TRUE in case of success,
 *         FALSE in case of error.
 */
template< template<class T, class = std::allocator<T> > class container_type >
inline bool from_file( const std::string& fname,
                       container_type<std::string>& out_container,
                       std::function<void(const std::string&)> error_open_callback = on_open_file_error,
                       std::function<void(const std::string&)> error_read_callback = on_read_file_error ) {

    return getlines_from_file( fname,
                               [&out_container](std::string& line) { out_container.push_back(line); },
                               error_open_callback,
                               error_read_callback );
}

#include <fstream>
#include <functional>
#include <string>
/** Convenience function that appends the given stl compliant container with the elements
 * found in the lines of the given file. In error case it calls the given callbacks.
 * @param fname The path to the file to be read.
 * @param out_container The stl compliant container of in which the read found lines
 *        shall be written. The container must support push_back().
 * @param error_open_callback The function that is to be called when the file could not be openend.
 *        It takes a string as an argument which will be set to the original given filename.
 * @param error_read_callback The function that is called when there occured an error while reading the file.
 *        It takes a string as an argument which will be set to the original given filename and an unsigned
 *        int that represents the error-provoking line in the file (0-based indexing).
 * @return TRUE in case of success,
 *         FALSE in case of error.
 */
template< typename F, template<class T, class = std::allocator<T> > class container_type > /* for sets and stuff */
inline bool from_file( const std::string& fname,
                    container_type<F>& out_container,
                    std::function<void(const std::string&)> error_open_callback = on_open_file_error,
                    std::function<void(const std::string&, unsigned int)> error_read_callback = on_read_file_line_error ) {
    bool ret(true);

    std::ifstream in_file( fname);
    if( !in_file.is_open()) {
        error_open_callback( fname);
        ret = false;
    } else {

        std::string line;
        unsigned int line_nr(0);
        while( getline(in_file, line)) {
            std::stringstream ss;
            ss << line;
            std::copy( std::istream_iterator<F>(ss),
                        std::istream_iterator<F>(),
                        std::back_inserter(out_container));
            line_nr++;
        }
        if(in_file.bad()) {
            error_read_callback(fname, line_nr);
            ret = false;
        }
    }
    in_file.close();
    return ret;
}

#ifdef BL_BOOST_FILESYSTEM

#include <iostream>
#include <boost/filesystem.hpp>
/** filesystem_error exception callback function originally for for_each_file_in_direcory_tree().
 * @see for_each_file_in_direcory_tree()
 */
void on_filesystem_exception( boost::filesystem::filesystem_error& e) {
    std::cerr << "Exception with for_each_file_in_direcory_tree(): " << e.what() << "\n";
}

#include <boost/filesystem.hpp>
/** Performs a callback for every directory entry in a directory tree.
 * Also performs exception handling. If a filesystem_exception occurs,
 * it will be caught and the iteration will be aborted.
 * @param p The root directory path in which to start the iteration.
 * @param callback The callback to perform on every directory entry.
 *        It takes a boost::filesystem::directory_entry as an argument,
 *        also an unsigned int that will provide the iteration level
 *        and returns a bool. When the return value is FALSE,
 *        the whole iteration will be aborted and the function returns false.
 * @param exception_callback The function that is called when an exception occurs.
 *        Takes a boost::filesystem::filesystem_error as an argument.
 * @param max_level The maximum level to iterate into the directory tree starting where 0 is the base level.
 *        If max_level is set to -1, the function iterates into every file-tree depth.
 * @return TRUE in case of complete success.
 *         FALSE in case of an exception of kind boost::filesystem::filesystem_error.
 */
bool for_each_file_in_direcory_tree( boost::filesystem::path& p,
                                     std::function<bool( boost::filesystem::directory_entry&, uint level)> callback,
                                     std::function<void( boost::filesystem::filesystem_error&)> exception_callback = on_filesystem_exception,
                                     int max_level = -1) {
    namespace bfs = boost::filesystem;
    bool ret(true);
    try {
        for( bfs::recursive_directory_iterator it(p); it!=bfs::recursive_directory_iterator(); ++it)
            if( max_level == -1 || it.level() <= max_level ) {
                ret = callback(*it, it.level());
                if( ret == false)
                    break;
            }
    } catch (bfs::filesystem_error& e) {
        exception_callback(e);
        ret = false;
    }
    return ret;
}

#endif //defined BL_BOOST_FILESYSTEM

#include <Windows.h>
/** Retrieves current full path of the application.
TODO: currently works on windows only. Make it multi-platform maybe.

@param append_app_name Specifies, whether the executable name
shall be on the returned string or not.
TRUE - retrieve full path with application file name.
FALSE - retrieve full path without application file name.
@return The full path of the running application.
*/
std::string app_path( bool append_app_name=false) {
    char buffer[512];
    std::string ret;

    GetModuleFileName( NULL, buffer, MAX_PATH );
    ret = std::string(buffer);

    if( !append_app_name) {
        std::string::size_type pos = ret.find_last_of( "\\/" );
        ret = ret.substr( 0, pos);
    }
    return ret;
}

/** Gives a bool into a "yes"/"no" string representation.
 * @param b A boolean value.
 * @return The string representation of the input parameter.
 * true - returns "yes"
 * false - returns "no"
 */
inline std::string yes_no( bool b) {
    return b ? "yes" : "no";
}

#include <fstream>
/** Saves a pixel array as an ppm image. Overwrites an existing image.
 * @param name the name of the file (extensions may be included).
 * @param pixels ideally, the pixel-array should be like unsigned char[3*(width)*(height)+3].
 * @param width the width of the picture to save.
 * @param width the height of the picture to save.
 * @param max_color
 * the maximum value, a color entry can have according to ppm specification.
 * the value 255 is appropriate in most cases.
 * @param adaptive_max_color
 * if set to true, scales the brightness of the picture to maximum,
 * otherwise the specified max_color value will be considered as the maximum value.
 *
 * CAUTION: THIS FUNCTION IS UNTESTED
 *
 * @return returns TRUE, if the operation was successful, returns FALSE in case of error.
 */
bool savePPM( const char* name, unsigned char *pixels, unsigned int width, unsigned int height, unsigned int max_color = 255, bool adaptive_max_color = false) {
    // style header
    std::fstream file;
    file.open(  name, std::ios::out);
    file << "P3\n" << width << " " << height << std::endl;

    // max color part
    auto max_color_cursor_pos = file.tellp();
    file << "000" << std::endl;

    if( adaptive_max_color)
        max_color = 0;

    // style pixmap
    for( int y=height-1; y>=0; y--)
        for( unsigned int x=0; x<3*width; x++) {
            unsigned int pixel_index = y*(3*width) + x;
            file << (int)pixels[pixel_index] << "\t";
            if(pixel_index % (3*width) == 0)
                file << std::endl;
            if( adaptive_max_color && (int)pixels[pixel_index] > max_color)
                max_color = (int)pixels[pixel_index];
        }

    // set max color
    file.seekp( max_color_cursor_pos, std::ios::beg );
    file << max_color;
    file.close();

    return true;
}

#include <cassert>
#include <vector>
/** Retrieves a vector of all sub-vectors with a specific length consisting elements of the given vector.
 * Elements in the subvectors do not need to be neighbours in the original vector; the subvectors are like subsets,
 * with the difference that they are vectors and the order of the elements will not be changed.
 * XXX maybe make it more efficient.
 * @param v The vector from which to retrieve subvectors.
 * @param length The length of the subvectors to retrieve.
 * @return A vector of all subvectors with the given length.
 */
template< typename T>
std::vector<std::vector<T>> subvectors( std::vector<T> v, uint length) {
    using namespace std;

    vector<vector<T>> ret;
    assert( v.size() >= length);

    vector<int> indices;
    for( int i=0; i<length; ++i) {
        indices.push_back(i);
    }

    int off;
    do {
        vector<T> ret_element;
        for( int i=0; i<length; ++i) {
            ret_element.push_back( v[indices[i]]);
        }
        ret.push_back( ret_element);

        off = 1;
        while( off <= length && indices[length-off] == v.size()-off)
            ++off;
        // *** off at the right position to raise ***

        if(off <= length) {
            int index_to_raise = length - off;
            indices[index_to_raise]++;
            for( int i=1; i<off; ++i) {
                indices[index_to_raise + i] = indices[index_to_raise] + i;
            }
        }
    } while(off <= length);

    return ret;
}

#include <cassert>
#include <vector>
/** Retrieves a vector of all given-length sub-vectors indices of a vector with given length.
 * Elements in the subvectors do not need to be neighbouring indices; the index-subvectors are like subsets,
 * with the difference that they are vectors and the order of the elements will be changed lexicographic.
 * XXX maybe make it more efficient.
 * @param vector_length The length of the vector from which to retrieve the subvectors-indices.
 * @param subvectors_length The length of the index-subvectors to retrieve.
 * @return A vector of all subvectors with the given length containing indices from 0 to vector_length-1.
 */
std::vector<std::vector<size_t>> subvector_indices( size_t vector_length, size_t subvectors_length) {
    using namespace std;
    vector<vector<size_t>> ret;
    assert( vector_length >= subvectors_length);

    vector<size_t> indices;
    for(size_t i=0; i<subvectors_length; ++i) {
        indices.push_back(i);
    }

    size_t off;
    do {
        ret.push_back( indices);

        off = 1;
        while( off <= subvectors_length && indices[subvectors_length-off] == vector_length-off)
            ++off;
        // *** off at the right position to raise ***
        if(off <= subvectors_length) {
            size_t index_to_raise = subvectors_length - off;
            indices[index_to_raise]++;
            for(size_t i=1; i<off; ++i) {
                indices[index_to_raise + i] = indices[index_to_raise] + i;
            }
        }
    } while(off <= subvectors_length);

    return ret;
}

/** Resizes a vector and linearly interpolates the vector elements when  upscaling/downscaling.
 * @param v The vector of type T that is to be resized. Type T must understand operations
 * like addition T+T and multiplication with a floating point value.
 * @param new_size The size of the new output vector.
 * @return An resized, linearly interpolated version of the given vector with the given new length.
 */
template< typename T>
std::vector<T> resize_interpolated( const std::vector<T>& v, uint new_size) {
    std::vector<T> ret;
    double factor = double(v.size()) / new_size;

    for( int i=0; i<new_size; ++i) {
        double index = i * factor;
        int integer_part = (int)index;
        double fractional_part = index - integer_part;
        if( index+1 >= v.size())
            ret.push_back( v[integer_part]);
        else
            ret.push_back( v[integer_part] * (1 - fractional_part) + v[integer_part + 1] * fractional_part);
    }
    return ret;
}

/** Retrieves the normalized circular delayed cross correlatipon series of two given vectors.
 * The function calculates means and deviations under the hood, so maybe, if you have
 * these values beforehand you should rather calculate your own correlation series inline.
 * @param a The first vector.
 * @param b The second vector. Must have the same length as vector a.
 * @return The cross correlation series for both vectors with the index defining the delay.
 * Since cross_correllation(vector, delay) = cross_correllation(vector, vector.size-delay),
 * or, in other words, the cross correlation series is symmetric to delay = vector.size()/2,
 * The resulting vector will be half the size of the input vectors.
 * The vector elements are within [-1;1].
 */
template<typename R>
std::vector<R> circular_cross_correlation_series( const std::vector<R>& a, const std::vector<R>& b) {
    assert( a.size() == b.size() && "a and b must have same length");
    std::vector<R> ret;
    unsigned int size = static_cast<unsigned int>(a.size()/2) + (a.size()%2 == 0 ? 0 : 1);
    ret.reserve( size);

    register R mean_a = 0;
    register R mean_b = 0;
    R variance_a = 0;
    R variance_b = 0;
    register R denom;

    // calculate means
    for( int i=0; i<a.size(); ++i) {
        mean_a += a[i];
        mean_b += b[i];
    }
    mean_a /= a.size();
    mean_b /= a.size();
    // calculate variances
    for( int i=0; i<a.size(); ++i) {
        variance_a += (a[i] - mean_a) * (a[i] - mean_a);
        variance_b += (b[i] - mean_b) * (b[i] - mean_b);
    }
    denom = sqrt( variance_a * variance_b);

    // calculate correlation series
    if( denom == 0) {
        for( unsigned int delay=0; delay<size; ++delay) {
            ret.push_back(1);
        }
    } else {
        for( unsigned int delay=0; delay<size; ++delay) {
            R cross_correlation = 0;
            for( int idx_a=0; idx_a<a.size(); ++idx_a) {
                int idx_b = (idx_a+delay) % a.size();
                cross_correlation += (a[idx_a] - mean_a) * (b[idx_b] - mean_b);
            }
            ret.push_back( cross_correlation / denom);
        }
    }
    return ret;
}

/** Checks whether a given value is zero or a power of two. Takes constant time.
 * @param n The number to be checked.
 * @return TRUE when n is a power of two or n==0,
 *         FALSE otherwise.
 */
template< typename N>
inline bool is_zero_or_power_of_2( N n) {
    return (n & (n - 1)) == 0;
}

#include <chrono>
/** Helper function that calculates the duration between a given time point in the past and now.
@param clock_start A time point that should be in the past.
@return the time duration (e.g. milliseconds) between clock_start and now().
*/
template< typename T = std::chrono::milliseconds>
inline T time_since(std::chrono::steady_clock::time_point& clock_start) {
    return std::chrono::duration_cast< T>(std::chrono::steady_clock::now() - clock_start);
}

#include <algorithm>
#include <iterator>
#include <map>
/** Flips an associative container of A,B pairs to B,A pairs.
Solution inspired by: http://stackoverflow.com/questions/5056645/sorting-stdmap-using-value
@param src The source container.
@return A std::multimap whose keys are the values of src and whose corresponding values are the keys of src.
*/
template<typename A, typename B, template<class, class, class...> class M, class... Args>
std::multimap<B, A> flip_map(const M<A, B, Args...> &src) {
    std::multimap<B, A> ret;
    std::transform(
        src.begin(),
        src.end(),
        std::inserter(ret, ret.begin()),
        [](auto& p) { return std::make_pair(p.second, p.first); }
    );
    return ret;
}

/** Binary search on sorted, non-empty stl compliant containers with random-access iterators, like vectors.
Internally, it stores the indices as signed ints, so beware of huge containers.
XXX make it more general with comparator functors for complex types
XXX make it stable for big containers
@param container An stl compliant container. Must be non-empty and sorted.
@param value The value to be looked for in the container.
@return The index position of the element in the container or -1 if the element could not be found.
*/
template< typename F, template<class T, class = std::allocator<T> > class container_type >
int binary_search(const container_type<F>& container, const F value) {

    int idx = static_cast<int>(container.size()) / 2;
    int stepsize = idx;

    do {
        if (container[idx] == value)
            return idx;

        stepsize /= 2;
        idx += container[idx] > value ? -stepsize : +stepsize;
    } while (stepsize > 0);

    idx += container[idx] > value ? -1 : +1;
    if (container[idx] == value)
        return idx;

    return -1;
}

/** Calculates the overlap of two given one-dimensional ranges.
For example, for the ranges (1, 3.6) and (2,4) the returned value is 1.6.
@param lower1 The lower end of the first range.
@param upper1 The upper end of the first range. Must be >= lower1.
@param lower2 The lower end of the second range.
@param upper2 The upper end of the second range. Must be >= lower2.
@return Returns the overlap between the ranges or 0 when the ranges do not overlap.
*/
template< typename T>
constexpr inline T range_intersection(const T lower1, const T upper1, const T lower2, const T upper2) {

    return std::max(
        static_cast<T>(0),
        std::min(upper1, upper2) - std::max(lower1, lower2)
        );
}

ext: hpp


text:
//   GAMBIT: Global and Modular BSM Inference Tool
//   *********************************************
///  \file
///
///  This class is used to wrap the QedQcd object used by SoftSUSY
///  and FlexibleSUSY in a Gambit SubSpectrum object. This is to enable
///  access to the parameters of the SM defined as a low-energy effective theory
///  (as opposed to correspending information defined in a UV model).
///  Parameters defined this way are often used as input to a physics calculator.
///
///  *********************************************
///
///  Authors:
///  <!-- add name and date if you modify -->
///
///  \author Ben Farmer
///          (benjamin.farmer@fysik.su.se)
///  \date 2015 Mar
///
///  *********************************************

#include "gambit/Elements/sminputs.hpp"
#include "gambit/Elements/spectrum.hpp"
#include "gambit/Elements/slhaea_helpers.hpp"
#include "gambit/SpecBit/QedQcdWrapper.hpp"
#include "gambit/Utils/util_functions.hpp"

#include <boost/preprocessor/tuple/to_seq.hpp>
#include <boost/preprocessor/seq/elem.hpp>
#include <boost/preprocessor/seq/for_each_product.hpp>

#include "lowe.h" ///TODO: wrap using BOSS at some point, i.e. get this from FlexibleSUSY or SoftSUSY

/// Macro to help assign the same function pointers to multiple string keys
// Relies on "tmp_map" being used as the variable name for the temporary maps
// inside the fill_map functions.
#define addtomap_EL(r, PRODUCT)                                         \
{                                                                       \
   str key      = BOOST_PP_SEQ_ELEM(0,PRODUCT); /* string map key */    \
   tmp_map[key] = BOOST_PP_SEQ_ELEM(1,PRODUCT); /* function pointer */  \
}

#define addtomap(__KEYS,FPTR) BOOST_PP_SEQ_FOR_EACH_PRODUCT(addtomap_EL, (BOOST_PP_TUPLE_TO_SEQ(__KEYS))((FPTR)) )

namespace Gambit
{

   namespace SpecBit
   {

      /// @{ QedQcdWrapper member functions

      ///   @{ Constructors
      QedQcdWrapper::QedQcdWrapper()
         : qedqcd()
         , sminputs()
      {}

      QedQcdWrapper::QedQcdWrapper(const softsusy::QedQcd& model, const SMInputs& input)
         : qedqcd(model)
         , sminputs(input)        /***/
         , hardup(get(Par::Pole_Mass,"u_3")) // QedQcd object will throw an error if we try to run above this, so set this as the limit /***/
         , softup(get(Par::Pole_Mass,"u_3")) // Set top quark pole mass as soft upper limit of  /***/
         , softlow(2) // (GeV) QedQcd object sets beta functions to zero below here anyway
         , hardlow(2) // (GeV) QedQcd object sets beta functions to zero below here anyway
      {}

      ///   @}

      /// Destructor
      QedQcdWrapper::~QedQcdWrapper() {}

      /// Currently unused virtual functions
      ///     @{
      int QedQcdWrapper::get_numbers_stable_particles() const {return -1;}
      ///     @}

      /// Add QED x QCD information to an SLHAea object
      void QedQcdWrapper::add_to_SLHAea(int, SLHAstruct& slha) const
      {
        // Here we assume that all SMINPUTS defined in SLHA2 are provided by the
        // SMINPUTS object, so we don't bother repeating them here.  We also assume
        // that the HE spectrum is going to provide the gauge couplings, so we don't
        // bother with those either.  We ignore the first parameter, as it doesn't matter
        // if we're helping make an SLHA1 or SLHA2 file.

        // Add the b pole mass
        SLHAea_add_from_subspec(slha, LOCAL_INFO, *this, Par::Pole_Mass,"d_3","MASS",5,"# mb (pole)");
      }

      /// Run masses and couplings to end_scale
      void QedQcdWrapper::RunToScaleOverride(double end_scale)
      {
        const double tol = 1.0e-5; // Value used internally in QedQcd methods
        double begin_scale = GetScale();
        qedqcd.run(begin_scale, end_scale, tol);  // Run masses and couplings
      }

      /// Retrieve the current renormalisation scale at which running parameters are defined
      double QedQcdWrapper::GetScale() const { return qedqcd.displayMu(); }

      /// Manually define the current renormalisation scale (do this at own risk!)
      void QedQcdWrapper::SetScale(double scale) { qedqcd.setMu(scale); }

      /// @}

      /// Plain C-function wrappers for QedQcd running mass getters
      double get_mUp      (const softsusy::QedQcd& model) { return model.displayMass(softsusy::mUp); }
      double get_mCharm   (const softsusy::QedQcd& model) { return model.displayMass(softsusy::mCharm); }
      double get_mTop     (const softsusy::QedQcd& model) { return model.displayMass(softsusy::mTop); }
      double get_mDown    (const softsusy::QedQcd& model) { return model.displayMass(softsusy::mDown); }
      double get_mStrange (const softsusy::QedQcd& model) { return model.displayMass(softsusy::mStrange); }
      double get_mBottom  (const softsusy::QedQcd& model) { return model.displayMass(softsusy::mBottom); }
      double get_mElectron(const softsusy::QedQcd& model) { return model.displayMass(softsusy::mElectron); }
      double get_mMuon    (const softsusy::QedQcd& model) { return model.displayMass(softsusy::mMuon); }
      double get_mTau     (const softsusy::QedQcd& model) { return model.displayMass(softsusy::mTau); }
      // Might as well add photon and gluon for good measure, someone might need them for a loop or something.
      double get_mPhoton  (const softsusy::QedQcd&) { return 0.; }
      double get_mGluon   (const softsusy::QedQcd&) { return 0.; }

      /// Plain C-function wrappers for QedQcd running coupling getters
      // Note: often people want 1/alpha, but here we return alpha itself
      // Might want to change these to g1,g3, to be consistent with MSSMSpec
      double get_alpha  (const softsusy::QedQcd& model) { return model.displayAlpha(softsusy::ALPHA); }
      double get_alphaS (const softsusy::QedQcd& model) { return model.displayAlpha(softsusy::ALPHAS); }

      /// All 3 SM gauge couplings.
      /// The QedQcd documenation has the following to say about this calculations:
      /// {
      /// This will calculate the three gauge couplings of the Standard Model at
      /// the scale m2.
      /// It's a simple one-loop calculation only and no
      /// thresholds are assumed. Range of validity is electroweak to top scale.
      // alpha1 is in the GUT normalisation. sinth = sin^2 thetaW(Q) in MSbar
      // scheme
      //  }
      // Note that it computes that couplings at scale "m2". I think other quantities
      // are taken as calculated more accurately at some initial scale, and then this
      // simple 1-loop computation is used just to get these couplings at a nearby
      // scale m2.

      double get_a1 (const softsusy::QedQcd&)
      {
         // We need sin^2 thetaW(Q) for this; i.e. I think it is supposed to be
         // supplied at whatever scale the rest of the parameters are currently
         // defined at. Not sure how to handle this.
         //QedQcd::getGaugeMu(const double m2, const double sinth)
         return 0.;
      }

      /// Plain C-function wrappers for extra pole mass getters (manually specified masses)
      //  Note: model object not needed for these, but required by function signature
      double get_Pole_mElectron(const SMInputs& inputs) { return inputs.mE; }
      double get_Pole_mMuon    (const SMInputs& inputs) { return inputs.mMu; }
      double get_Pole_mNu1    (const SMInputs& inputs) { return inputs.mNu1; }
      double get_Pole_mNu2    (const SMInputs& inputs) { return inputs.mNu2; }
      double get_Pole_mNu3    (const SMInputs& inputs) { return inputs.mNu3; }
      // for good measure.
      double get_Pole_mPhoton  (const SMInputs&) { return 0.; }
      double get_Pole_mGluon   (const SMInputs&) { return 0.; }

      double get_sinthW2_pole(const softsusy::QedQcd &qedqcd)
      {
        return (1 - Utils::sqr(qedqcd.displayPoleMW()) / Utils::sqr(qedqcd.displayPoleMZ()));
      }

      // Filler function for getter function pointer maps
      QedQcdWrapper::GetterMaps QedQcdWrapper::fill_getter_maps()
      {
         GetterMaps map_collection;

         /// @{ mass1 - mass dimension 1 parameters
         //
         // Functions utilising the "extraM" function signature
         // (Zero index, model object as argument)
         {  // scope so we can reuse the name 'tmp_map' several times, so that our macro works.
            // could make a better macro, or an actual function, but I'm in a hurry
            MTget::fmap0_extraM tmp_map;

            tmp_map["u_1"] = &get_mUp; // u
            tmp_map["u_2"] = &get_mCharm; // c
            tmp_map["u_3"] = &get_mTop; // t
            tmp_map["d_1"] = &get_mDown; // d
            tmp_map["d_2"] = &get_mStrange; // s
            tmp_map["d_3"] = &get_mBottom; // b
            tmp_map["e-_1"]  = &get_mElectron; // e-
            tmp_map["e-_2"] = &get_mMuon; // mu-
            tmp_map["e-_3"]= &get_mTau; // tau-

            tmp_map["gamma"] = &get_mPhoton;
            tmp_map["g"]     = &get_mGluon;

            map_collection[Par::mass1].map0_extraM = tmp_map;
         }
         /// @}

         /// @{ dimensionless - mass dimension 0 parameters
         {
            // Functions utilising the "extraM" function signature
            // (Zero index, model object as argument)

            MTget::fmap0_extraM tmp_map;

            tmp_map["alpha"]  = &get_alpha;
            tmp_map["alphaS"] = &get_alphaS;

            map_collection[Par::dimensionless].map0_extraM = tmp_map;
         }
         /// @}

         /// @{ Pole_Mass - Pole mass parameters
         //
         // Functions utilising the plain-vanilla function signature ("fmap")
         // (Zero-argument member functions of model object)
         {
            // String names correspond to those defined in particle_database.cpp. If
            // there is a mismatch, please change the ones here!
            MTget::fmap0 tmp_map;

            tmp_map["Z0"]  = &softsusy::QedQcd::displayPoleMZ;
            tmp_map["W+"]  = &softsusy::QedQcd::displayPoleMW;
            tmp_map["u_3"] = &softsusy::QedQcd::displayPoleMt; // t
            // "Pole" for b quark is quoted in SoftSUSY (lowe.h) documentation, so I guess this is an approximation; need to check details.
            tmp_map["d_3"] = &softsusy::QedQcd::displayPoleMb; // b
            tmp_map["e-_3"]= &softsusy::QedQcd::displayPoleMtau; // tau

            // Nearest flavour 'aliases' for the SM mass eigenstates
            tmp_map["t"] = &softsusy::QedQcd::displayPoleMt;
            tmp_map["b"] = &softsusy::QedQcd::displayPoleMb;
            tmp_map["tau-"]= &softsusy::QedQcd::displayPoleMtau;

            map_collection[Par::Pole_Mass].map0 = tmp_map;
         }

         /// Functions utilising the "extraI" signature
         /// (Zero-index, "Inputs" object used as argument)
         /// "Inputs" is intended as a generic container for anything needed to
         /// compute the function results. Could have used this exclusively, rather
         /// than having "extraM" and "extraI" versions of these functions, but it
         /// seemed nicer to have a version dedicated to the host Model class.
         {
            MTget::fmap0_extraI tmp_map;

            tmp_map["e-_1"] = &get_Pole_mElectron; // e-
            tmp_map["e-_2"] = &get_Pole_mMuon; // mu-
            tmp_map["nu_1"] = &get_Pole_mNu1;
            tmp_map["nu_2"] = &get_Pole_mNu2;
            tmp_map["nu_3"] = &get_Pole_mNu3;

            // Nearest flavour 'aliases' for the SM mass eigenstates
            tmp_map["e-"]  = &get_Pole_mElectron; // e-
            tmp_map["mu-"] = &get_Pole_mMuon; // mu-

            tmp_map["gamma"] = &get_Pole_mPhoton;
            tmp_map["g"]     = &get_Pole_mGluon;

            map_collection[Par::Pole_Mass].map0_extraI = tmp_map;
         }

         // Functions utilising the "extraM" function signature
         // (Zero index, model object as argument)
         {

            MTget::fmap0_extraM tmp_map;

            tmp_map["sinW2"] = &get_sinthW2_pole;

            map_collection[Par::Pole_Mixing].map0_extraM = tmp_map;
         }

         /// @}

         return map_collection;
      }

      /// Plain C-function wrappers for extra pole mass setters (manually specified masses)
      void set_Pole_mElectron(SMInputs& inputs, double set_value) { inputs.mE = set_value; }

      // Filler function for setter function pointer maps
      QedQcdWrapper::SetterMaps QedQcdWrapper::fill_setter_maps()
      {
         SetterMaps map_collection;

         /// @{ Pole_Mass - Pole mass parameters
         //
         // Functions utilising the plain-vanilla function signature ("fmap")
         // (Zero-argument member functions of model object)
         {
            MTset::fmap0 tmp_map;

            // Do something like this, though the demo function here is a getter
            // not a setter so you can't use that one of course :). If the
            // function signature doesn't match what you need I can change it,
            // otherwise need to use one of the "extra" map fillers, see e.g.
            // below (there is also one that takes the model object as an
            // input, as in the getter case)
            tmp_map["Z0"] = &softsusy::QedQcd::setPoleMZ;
            tmp_map["W+"] = &softsusy::QedQcd::setPoleMW;
            map_collection[Par::Pole_Mass].map0 = tmp_map;
         }

         /// Functions utilising the "extraI" signature
         /// (Zero-index, "Inputs" object used as argument)
         {
            MTset::fmap0_extraI tmp_map;

            tmp_map["e-_1"] = &set_Pole_mElectron;

            map_collection[Par::Pole_Mass].map0_extraI = tmp_map;
         }
         /// @}
         return map_collection;
      }

   } // end SpecBit namespace
} // end Gambit namespace

ext: cpp


text:
#ifndef __APPLE__
#define BOOST_THREAD_HAS_CONDATTR_SET_CLOCK_MONOTONIC
#endif

#include "ros/callback_queue.h"
#include <assert.h>
#include <boost/scope_exit.hpp>

// check if we have really included the backported boost condition variable
// just in case someone messes with the include order...
#if BOOST_VERSION < 106100
#ifndef USING_BACKPORTED_BOOST_CONDITION_VARIABLE
//#error "needs boost version >= 1.61 or the backported headers!"
#endif
#endif

namespace xcros
{
CallbackQueue::CallbackQueue(bool enabled)
: calling_(0)
, enabled_(enabled)
{
}

CallbackQueue::~CallbackQueue()
{
  disable();
}

void CallbackQueue::enable()
{
  boost::mutex::scoped_lock lock(mutex_);
  enabled_ = true;

  condition_.notify_all();
}

void CallbackQueue::disable()
{
  boost::mutex::scoped_lock lock(mutex_);
  enabled_ = false;

  condition_.notify_all();
}

void CallbackQueue::clear()
{
  boost::mutex::scoped_lock lock(mutex_);

  callbacks_.clear();
}

bool CallbackQueue::isEmpty()
{
  boost::mutex::scoped_lock lock(mutex_);

  return callbacks_.empty() && calling_ == 0;
}

bool CallbackQueue::isEnabled()
{
  boost::mutex::scoped_lock lock(mutex_);

  return enabled_;
}

void CallbackQueue::setupTLS()
{
  if (!tls_.get())
  {
    tls_.reset(new TLS);
  }
}

void CallbackQueue::addCallback(const CallbackInterfacePtr& callback, uint64_t removal_id)
{
  CallbackInfo info;
  info.callback = callback;
  info.removal_id = removal_id;

  {
    boost::mutex::scoped_lock lock(id_info_mutex_);

    M_IDInfo::iterator it = id_info_.find(removal_id);
    if (it == id_info_.end())
    {
      IDInfoPtr id_info(boost::make_shared<IDInfo>());
      id_info->id = removal_id;
      id_info_.insert(std::make_pair(removal_id, id_info));
    }
  }

  {
    boost::mutex::scoped_lock lock(mutex_);

    if (!enabled_)
    {
      return;
    }

    callbacks_.push_back(info);
  }

  condition_.notify_one();
}

CallbackQueue::IDInfoPtr CallbackQueue::getIDInfo(uint64_t id)
{
  boost::mutex::scoped_lock lock(id_info_mutex_);
  M_IDInfo::iterator it = id_info_.find(id);
  if (it != id_info_.end())
  {
    return it->second;
  }

  return IDInfoPtr();
}

void CallbackQueue::removeByID(uint64_t removal_id)
{
  setupTLS();

  {
    IDInfoPtr id_info;
    {
      boost::mutex::scoped_lock lock(id_info_mutex_);
      M_IDInfo::iterator it = id_info_.find(removal_id);
      if (it != id_info_.end())
      {
        id_info = it->second;
      }
      else
      {
        return;
      }
    }

    // If we're being called from within a callback from our queue, we must unlock the shared lock we already own
    // here so that we can take a unique lock.  We'll re-lock it later.
    if (tls_->calling_in_this_thread == id_info->id)
    {
      id_info->calling_rw_mutex.unlock_shared();
    }

    {
      boost::unique_lock<boost::shared_mutex> rw_lock(id_info->calling_rw_mutex);
      boost::mutex::scoped_lock lock(mutex_);
      D_CallbackInfo::iterator it = callbacks_.begin();
      for (; it != callbacks_.end();)
      {
        CallbackInfo& info = *it;
        if (info.removal_id == removal_id)
        {
          it = callbacks_.erase(it);
        }
        else
        {
          ++it;
        }
      }
    }

    if (tls_->calling_in_this_thread == id_info->id)
    {
      id_info->calling_rw_mutex.lock_shared();
    }
  }

  // If we're being called from within a callback, we need to remove the callbacks that match the id that have already been
  // popped off the queue
  {
    D_CallbackInfo::iterator it = tls_->callbacks.begin();
    D_CallbackInfo::iterator end = tls_->callbacks.end();
    for (; it != end; ++it)
    {
      CallbackInfo& info = *it;
      if (info.removal_id == removal_id)
      {
        info.marked_for_removal = true;
      }
    }
  }

  {
    boost::mutex::scoped_lock lock(id_info_mutex_);
    id_info_.erase(removal_id);
  }
}

CallbackQueue::CallOneResult CallbackQueue::callOne(xcros::WallDuration timeout)
{
  setupTLS();
  TLS* tls = tls_.get();

  CallbackInfo cb_info;

  {
    boost::mutex::scoped_lock lock(mutex_);

    if (!enabled_)
    {
      return Disabled;
    }

    if (callbacks_.empty())
    {
      if (!timeout.isZero())
      {
        condition_.wait_for(lock, boost::chrono::nanoseconds(timeout.toNSec()));
      }

      if (callbacks_.empty())
      {
        return Empty;
      }

      if (!enabled_)
      {
        return Disabled;
      }
    }

    D_CallbackInfo::iterator it = callbacks_.begin();
    for (; it != callbacks_.end();)
    {
      CallbackInfo& info = *it;

      if (info.marked_for_removal)
      {
        it = callbacks_.erase(it);
        continue;
      }

      if (info.callback->ready())
      {
        cb_info = info;
        it = callbacks_.erase(it);
        break;
      }

      ++it;
    }

    if (!cb_info.callback)
    {
      return TryAgain;
    }

    ++calling_;
  }

  bool was_empty = tls->callbacks.empty();
  tls->callbacks.push_back(cb_info);
  if (was_empty)
  {
    tls->cb_it = tls->callbacks.begin();
  }

  CallOneResult res = callOneCB(tls);
  if (res != Empty)
  {
    boost::mutex::scoped_lock lock(mutex_);
    --calling_;
  }
  return res;
}

void CallbackQueue::callAvailable(xcros::WallDuration timeout)
{
  setupTLS();
  TLS* tls = tls_.get();

  {
    boost::mutex::scoped_lock lock(mutex_);

    if (!enabled_)
    {
      return;
    }

    if (callbacks_.empty())
    {
      if (!timeout.isZero())
      {
        condition_.wait_for(lock, boost::chrono::nanoseconds(timeout.toNSec()));
      }

      if (callbacks_.empty() || !enabled_)
      {
        return;
      }
    }

    bool was_empty = tls->callbacks.empty();

    tls->callbacks.insert(tls->callbacks.end(), callbacks_.begin(), callbacks_.end());
    callbacks_.clear();

    calling_ += tls->callbacks.size();

    if (was_empty)
    {
      tls->cb_it = tls->callbacks.begin();
    }
  }

  size_t called = 0;

  while (!tls->callbacks.empty())
  {
    if (callOneCB(tls) != Empty)
    {
      ++called;
    }
  }

  {
    boost::mutex::scoped_lock lock(mutex_);
    calling_ -= called;
  }
}

CallbackQueue::CallOneResult CallbackQueue::callOneCB(TLS* tls)
{
  // Check for a recursive call.  If recursive, increment the current iterator.  Otherwise
  // set the iterator it the beginning of the thread-local callbacks
  if (tls->calling_in_this_thread == 0xffffffffffffffffULL)
  {
    tls->cb_it = tls->callbacks.begin();
  }

  if (tls->cb_it == tls->callbacks.end())
  {
    return Empty;
  }

  assert(!tls->callbacks.empty());
  assert(tls->cb_it != tls->callbacks.end());

  CallbackInfo info = *tls->cb_it;
  CallbackInterfacePtr& cb = info.callback;

  IDInfoPtr id_info = getIDInfo(info.removal_id);
  if (id_info)
  {
    boost::shared_lock<boost::shared_mutex> rw_lock(id_info->calling_rw_mutex);

    uint64_t last_calling = tls->calling_in_this_thread;
    tls->calling_in_this_thread = id_info->id;

    CallbackInterface::CallResult result = CallbackInterface::Invalid;

    {
      // Ensure that thread id gets restored, even if callback throws.
      // This is done with RAII rather than try-catch so that the source
      // of the original exception is not masked in a crash report.
      BOOST_SCOPE_EXIT(&tls, &last_calling)
      {
        tls->calling_in_this_thread = last_calling;
      }
      BOOST_SCOPE_EXIT_END

      if (info.marked_for_removal)
      {
        tls->cb_it = tls->callbacks.erase(tls->cb_it);
      }
      else
      {
        tls->cb_it = tls->callbacks.erase(tls->cb_it);
        result = cb->call();
      }
    }

    // Push TryAgain callbacks to the back of the shared queue
    if (result == CallbackInterface::TryAgain && !info.marked_for_removal)
    {
      boost::mutex::scoped_lock lock(mutex_);
      callbacks_.push_back(info);

      return TryAgain;
    }

    return Called;
  }
  else
  {
    tls->cb_it = tls->callbacks.erase(tls->cb_it);
  }

  return Called;
}
}

max_stars_repo_name: dogchenya/xc-ros

max_issues_repo_name: dogchenya/xc-ros

max_forks_repo_name: dogchenya/xc-ros


text:
//  (C) Copyright Edward Diener 2011
//  Use, modification and distribution are subject to the Boost Software License,
//  Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at
//  http://www.boost.org/LICENSE_1_0.txt).

#include "test_has_static_mem_fun.hpp"
#include <boost/detail/lightweight_test.hpp>

int main()
  {

  BOOST_TEST((HaveTheSIntFunction<AType,int (long,double)>::value));
  BOOST_TEST((!TheTIntFunction<AType,AType (long,double)>::value));
  BOOST_TEST((TheTIntFunction<AnotherType,AType (long,double)>::value));
  BOOST_TEST((BOOST_TTI_HAS_STATIC_MEMBER_FUNCTION_GEN(TSFunction)<AnotherType,AType::AStructType (AType::AnIntType,double)>::value));
  BOOST_TEST((!Pickedname<AnotherType,void ()>::value));

  return boost::report_errors();

  }

max_stars_repo_name: ballisticwhisper/boost

max_issues_repo_name: ballisticwhisper/boost

max_forks_repo_name: ballisticwhisper/boost


text:
///////////////////////////////////////////////////////////////////////////////
// distribution.hpp                                                          //
//                                                                           //
//  Copyright 2010 Erwann Rogard. 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_ACCUMULATORS_DETAIL_PARAMETERS_DISTRIBUTION_HPP_ER_2010
#define BOOST_ACCUMULATORS_DETAIL_PARAMETERS_DISTRIBUTION_HPP_ER_2010
#include <boost/parameter/name.hpp>

namespace boost{
namespace accumulators{
namespace detail{

    BOOST_PARAMETER_NAME((_distribution, keyword) distribution)

}// detail
}// statistics
}// boost

#endif


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

#include "delegatedb.h"

#include <boost/range/adaptor/reversed.hpp>

#include "leveldbeng.h"

using namespace std;
using namespace xengine;

namespace ibrio
{
namespace storage
{

//////////////////////////////
// CDelegateDB

bool CDelegateDB::Initialize(const boost::filesystem::path& pathData)
{
    CLevelDBArguments args;
    args.path = (pathData / "delegate").string();
    args.syncwrite = false;
    CLevelDBEngine* engine = new CLevelDBEngine(args);

    if (!Open(engine))
    {
        delete engine;
        return false;
    }

    return true;
}

void CDelegateDB::Deinitialize()
{
    cacheDelegate.Clear();
    Close();
}

void CDelegateDB::Clear()
{
    cacheDelegate.Clear();
    RemoveAll();
}

bool CDelegateDB::AddNew(const uint256& hashBlock, const CDelegateContext& ctxtDelegate)
{
    if (!Write(hashBlock, ctxtDelegate))
    {
        return false;
    }

    cacheDelegate.AddNew(hashBlock, ctxtDelegate);
    return true;
}

bool CDelegateDB::Remove(const uint256& hashBlock)
{
    cacheDelegate.Remove(hashBlock);
    return Erase(hashBlock);
}

bool CDelegateDB::Retrieve(const uint256& hashBlock, CDelegateContext& ctxtDelegate)
{
    if (cacheDelegate.Retrieve(hashBlock, ctxtDelegate))
    {
        return true;
    }

    if (!Read(hashBlock, ctxtDelegate))
    {
        return false;
    }

    cacheDelegate.AddNew(hashBlock, ctxtDelegate);
    return true;
}

bool CDelegateDB::RetrieveDelegatedVote(const uint256& hashBlock, map<CDestination, int64>& mapVote)
{
    CDelegateContext ctxtDelegate;
    if (!Retrieve(hashBlock, ctxtDelegate))
    {
        return false;
    }
    mapVote = ctxtDelegate.mapVote;
    return true;
}

bool CDelegateDB::RetrieveDelegatedEnrollTx(const uint256& hashBlock, std::map<int, std::map<CDestination, CDiskPos>>& mapEnrollTxPos)
{
    CDelegateContext ctxtDelegate;
    if (!Retrieve(hashBlock, ctxtDelegate))
    {
        return false;
    }
    mapEnrollTxPos = ctxtDelegate.mapEnrollTx;
    return true;
}

bool CDelegateDB::RetrieveEnrollTx(int height, const vector<uint256>& vBlockRange, map<CDestination, CDiskPos>& mapEnrollTxPos)
{
    for (const uint256& hash : boost::adaptors::reverse(vBlockRange))
    {
        CDelegateContext ctxtDelegate;
        if (!Retrieve(hash, ctxtDelegate))
        {
            return false;
        }

        map<int, map<CDestination, CDiskPos>>::iterator it = ctxtDelegate.mapEnrollTx.find(height);
        if (it != ctxtDelegate.mapEnrollTx.end())
        {
            mapEnrollTxPos.insert((*it).second.begin(), (*it).second.end());
        }
    }
    return true;
}

} // namespace storage
} // namespace ibrio

max_stars_repo_name: IBnetCouncil/ibrio

max_issues_repo_name: IBnetCouncil/ibrio

max_forks_repo_name: IBnetCouncil/ibrio


text:
/**************************************************************
 *
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 *
 *************************************************************/

#ifndef INCLUDED_SLIDESHOW_GDIMTFTOOLS_HXX
#define INCLUDED_SLIDESHOW_GDIMTFTOOLS_HXX

#include <com/sun/star/uno/Reference.hxx>
#include <com/sun/star/uno/XComponentContext.hpp>
#include <com/sun/star/lang/XComponent.hpp>
#include <com/sun/star/drawing/XDrawPage.hpp>

#include <basegfx/range/b2drectangle.hxx>
#include <boost/shared_ptr.hpp>

#include "tools.hxx"

#include <vector>

class MetaAction;
class GDIMetaFile;
class Graphic;

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

namespace slideshow
{
    namespace internal
    {
        /// meta file loading specialities:
        enum mtf_load_flags {
            /// no flags
            MTF_LOAD_NONE = 0,
            /// annotate text actions with verbose comments,
            /// denoting logical and physical text entities.
            MTF_LOAD_VERBOSE_COMMENTS = 1,
            /// the source of the metafile might be a foreign
            /// application. The metafile is checked against unsupported
            /// content, and, if necessary, returned as a pre-rendererd
            /// bitmap.
            MTF_LOAD_FOREIGN_SOURCE = 2,
            /// retrieve a meta file for the page background only
            MTF_LOAD_BACKGROUND_ONLY = 4,
            /// retrieve the drawing layer scroll text metafile
            MTF_LOAD_SCROLL_TEXT_MTF = 8
        };

        // Animation info
        // ==============

        struct MtfAnimationFrame
        {
            MtfAnimationFrame( const GDIMetaFileSharedPtr& rMtf,
                               double					   nDuration ) :
                mpMtf( rMtf ),
                mnDuration( nDuration )
            {
            }

            /// Enables STL algos to be used for duration extraction
            double getDuration() const
            {
                return mnDuration;
            }

            GDIMetaFileSharedPtr	mpMtf;
            double					mnDuration;
        };

        typedef ::std::vector< MtfAnimationFrame > VectorOfMtfAnimationFrames;

        /** Retrieve a meta file for the given shape

			@param xShape
            XShape to retrieve a metafile for.

            @param xContainingPage
            The page that contains this shape. Needed for proper
            import (currently, the UnoGraphicExporter needs this
            information).

            @param o_rMtf
            Metafile to extract shape content into
        */
        bool getMetaFile( const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XComponent >&     xSource,
                          const ::com::sun::star::uno::Reference< ::com::sun::star::drawing::XDrawPage >&	xContainingPage,
                          GDIMetaFile& 							                                    		o_rMtf,
                          int                                                                               mtfLoadFlags,
                          const ::com::sun::star::uno::Reference<
                              ::com::sun::star::uno::XComponentContext >&                                   rxContext );

        /** Remove all text actions from the given metafile.
         */
        void removeTextActions( GDIMetaFile& io_rMtf );

        /** Gets the next action offset for iterating meta actions which is most
            often returns 1.
        */
        sal_Int32 getNextActionOffset( MetaAction * pCurrAct );

        /** Extract a vector of animation frames from given Graphic.

        	@param o_rFrames
            Resulting vector of animated metafiles

            @param o_rLoopCount
            Number of times the bitmap animation shall be repeated

            @param o_eCycleMode
            Repeat mode (normal, or ping-pong mode)

            @param rGraphic
            Input graphic object, to extract animations from
         */
        bool getAnimationFromGraphic( VectorOfMtfAnimationFrames& o_rFrames,
                                      ::std::size_t&              o_rLoopCount,
                                      CycleMode&                  o_eCycleMode,
                                      const Graphic&              rGraphic );

        /** Retrieve scroll text animation rectangles from given metafile

            @return true, if both rectangles have been found, false
            otherwise.
         */
        bool getRectanglesFromScrollMtf( ::basegfx::B2DRectangle&       o_rScrollRect,
                                         ::basegfx::B2DRectangle&       o_rPaintRect,
                                         const GDIMetaFileSharedPtr&    rMtf );
    }
}

#endif /* INCLUDED_SLIDESHOW_GDIMTFTOOLS_HXX */

ext: hxx

max_stars_repo_name: Grosskopf/openoffice

max_issues_repo_name: Grosskopf/openoffice

max_forks_repo_name: Grosskopf/openoffice


text:
// Software License for MTL
//
// Copyright (c) 2007 The Trustees of Indiana University.
//               2008 Dresden University of Technology and the Trustees of Indiana University.
//               2010 SimuNova UG (haftungsbeschränkt), www.simunova.com.
// All rights reserved.
// Authors: Peter Gottschling and Andrew Lumsdaine
//
// This file is part of the Matrix Template Library
//
// See also license.mtl.txt in the distribution.

#ifndef MTL__OPERATION_COMPUTE_SUMMAND_INCLUDE
#define MTL__OPERATION_COMPUTE_SUMMAND_INCLUDE

#include <boost/numeric/mtl/mtl_fwd.hpp>
#include <boost/numeric/mtl/utility/copy_expression_const_ref_container.hpp>
#include <boost/numeric/mtl/interface/vpt.hpp>

namespace mtl { namespace operation {

/// Compute a summand in an expression
/** For instance matrix vector products are transformed into mult function calls
    when assigned to a column vector. Adding such a vector to other vector expressions
    requires to compute (evaluate) the summand first and then add the resulting
    vector. The current implementation assumes that the result of the operation
    can be represented by the multiplied column vector. This is for instance wrong
    when the matrix is complex and the vector real. To handle this is signifantly
    more complicated and is planned for the future.
**/
template <typename Expr>
struct compute_summand
{
    typedef Expr type;
    compute_summand(const Expr& expr) : value(expr) {}
    // value is a const& if Expr is a true vector and a copy if it is an expression
    typename mtl::traits::copy_expression_const_ref_container<Expr>::type value;
};

/// Specialization for matrix vector products
template <typename Matrix, typename CVector>
struct compute_summand< mat_cvec_times_expr<Matrix, CVector> >
{
    typedef CVector    type;

    compute_summand(const mat_cvec_times_expr<Matrix, CVector>& expr)
      : value(num_rows(expr.first))
#ifndef NDEBUG // might be helpful, e.g. for generating AST
      , first(expr.first), second(expr.second)
#endif
    {
	vampir_trace<3005> tracer;
	value= expr.first * expr.second;
    }

    CVector value;
#ifndef NDEBUG
    const Matrix&  first;
    const CVector& second;
#endif
};

/// Specialization for matrix vector products
template <typename Matrix, typename CVector>
struct compute_summand< vector::mat_cvec_multiplier<Matrix, CVector> >
{
    typedef CVector    type;

    compute_summand(const vector::mat_cvec_multiplier<Matrix, CVector>& expr)
      : value(num_rows(expr.A))
    {
	vampir_trace<3005> tracer;
	expr.assign_to(value);
    }

    CVector value;
};

}} // namespace mtl::operation

#endif // MTL__OPERATION_COMPUTE_SUMMAND_INCLUDE


text:
#pragma once

#include <Eigen/Eigen>

#include <istream>
#include <memory>
#include <ostream>
#include <utility>
#include <vector>

#include "nanoflann.hpp"
#include "py4dgeo.hpp"

namespace py4dgeo {

// Forward declaration of Epoch
class Epoch;

/** @brief Efficient KDTree data structure for nearest neighbor/radius searches
 *
 * This data structure allows efficient radius searches in 3D point cloud data.
 * It is based on NanoFLANN: https://github.com/jlblancoc/nanoflann
 */
class KDTree
{
public:
  //! Return type used for radius searches
  using RadiusSearchResult = std::vector<IndexType>;

  //! Return type used for radius searches that export calculated distances
  using RadiusSearchDistanceResult = std::vector<std::pair<IndexType, double>>;

private:
  /** @brief An adaptor between our Eigen data structures and NanoFLANN */
  struct Adaptor
  {
    EigenPointCloudRef cloud;

    inline std::size_t kdtree_get_point_count() const { return cloud.rows(); }

    float kdtree_get_pt(const IndexType idx, const IndexType dim) const
    {
      return cloud(idx, dim);
    }

    template<class BBOX>
    bool kdtree_get_bbox(BBOX&) const
    {
      return false;
    }
  };

  /** @brief A structure to perform efficient radius searches with NanoFLANN
   *
   * The built-in return set of NanoFLANN does automatically export the
   * distances as well, which we want to omit if we already know that we do not
   * need the distance information.
   */
  struct NoDistancesReturnSet
  {
    double radius;
    RadiusSearchResult& indices;

    inline std::size_t size() const { return indices.size(); }

    inline bool full() const { return true; }

    inline bool addPoint(double dist, IndexType idx)
    {
      if (dist < radius)
        indices.push_back(idx);
      return true;
    }

    inline double worstDist() const { return radius; }
  };

  //! The NanoFLANN index implementation that we use
  using KDTreeImpl = nanoflann::KDTreeSingleIndexAdaptor<
    nanoflann::L2_Simple_Adaptor<float, Adaptor, double>,
    Adaptor,
    3,
    IndexType>;

  // We allow the Epoch class to directly call below constructor
  friend Epoch;

  //! Private constructor from pointcloud - use through @ref KDTree::create
  KDTree(const EigenPointCloudRef&);

public:
  /** @brief Construct instance of KDTree from a given point cloud
   *
   * This is implemented as a static function instead of a public constructor
   * to ease the implementation of Python bindings.
   *
   * @param cloud The point cloud to construct the search tree for
   */
  static KDTree create(const EigenPointCloudRef& cloud);

  /** @brief Build the KDTree index
   *
   * This initializes the KDTree search index. Calling this method is required
   * before performing any nearest neighbors or radius searches.
   *
   * @param leaf The threshold parameter definining at what size the search
   *             tree is cutoff. Below the cutoff, a brute force search is
   * performed. This parameter controls a trade off decision between search tree
   *             build time and query time.
   */
  void build_tree(int leaf);

  /** @brief Peform radius search around given query point
   *
   * This method determines all the points from the point cloud within the given
   * radius of the query point. It returns only the indices and the result is
   * not sorted according to distance.
   *
   * @param[in] querypoint A pointer to the 3D coordinate of the query point
   * @param[in] radius The radius to search within
   * @param[out] result A data structure to hold the result. It will be cleared
   * during application.
   *
   * @return The amount of points in the return set
   */
  std::size_t radius_search(const float* querypoint,
                            double radius,
                            RadiusSearchResult& result) const;

  /** @brief Perform radius search around given query point exporting distance
   * information
   *
   * This method determines all the points from the point cloud within the given
   * radius of the query point. It returns their indices and their distances
   * from the query point. The result is sorted by ascending distance from the
   * query point.
   *
   * @param[in] querypoint A pointer to the 3D coordinate of the query point
   * @param[in] radius The radius to search within
   * @param[out] result A data structure to hold the result. It will be cleared
   * during application.
   *
   * @return The amount of points in the return set
   */
  std::size_t radius_search_with_distances(
    const float* querypoint,
    double radius,
    RadiusSearchDistanceResult& result) const;

  /** @brief Return the leaf parameter this KDTree has been built with */
  int get_leaf_parameter() const;

private:
  Adaptor adaptor;
  std::shared_ptr<KDTreeImpl> search;
  int leaf_parameter = 0;
};

} // namespace py4dgeo


text:
#include <boost/python.hpp>

char const* hello()
{
    return "Hello world from pyvot!\n";
}

// python-c++ internal module is _libvot, will be further wrapped in python-style
BOOST_PYTHON_MODULE(_libvot)
{
    using namespace boost::python;
    def("hello", hello);
}

max_stars_repo_name: centosrhel/libvot

max_issues_repo_name: centosrhel/libvot

max_forks_repo_name: centosrhel/libvot


text:
//////////////////////////////////////////////////////////////////////////////
//
// (C) Copyright Ion Gaztanaga 2015-2015. 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)
//
// See http://www.boost.org/libs/container for documentation.
//
//////////////////////////////////////////////////////////////////////////////

#include <boost/container/map.hpp>

struct empty
{
   friend bool operator == (const empty &, const empty &){ return true; }
   friend bool operator <  (const empty &, const empty &){ return true; }
};

template class ::boost::container::map<empty, empty>;
template class ::boost::container::multimap<empty, empty>;

volatile ::boost::container::map<empty, empty> dummy;
volatile ::boost::container::multimap<empty, empty> dummy2;

#include <boost/container/allocator.hpp>
#include <boost/container/adaptive_pool.hpp>
#include "movable_int.hpp"
#include "dummy_test_allocator.hpp"

namespace boost {
namespace container {

typedef std::pair<const test::movable_and_copyable_int, test::movable_and_copyable_int> pair_t;

//Explicit instantiation to detect compilation errors

//map
template class map
   < test::movable_and_copyable_int
   , test::movable_and_copyable_int
   , std::less<test::movable_and_copyable_int>
   , test::simple_allocator< pair_t >
   >;

template class map
   < test::movable_and_copyable_int
   , test::movable_and_copyable_int
   , std::less<test::movable_and_copyable_int>
   , adaptive_pool< pair_t >
   >;
}} //boost::container

int main()
{
   return 0;
}

max_stars_repo_name: Jackarain/tinyrpc

max_issues_repo_name: avplayer/cxxrpc

max_forks_repo_name: avplayer/cxxrpc