text:
#ifndef AQUILA_TYPES_PIXELS_HPP
#define AQUILA_TYPES_PIXELS_HPP
#include <Eigen/Core>
#include <ct/enum.hpp>
#include <ct/reflect_macros.hpp>
#include <type_traits>
#include <utility>
namespace aq
{
    ENUM_BEGIN(PixelFormat, uint8_t)
        ENUM_VALUE(kUNCHANGED, 0)
        ENUM_VALUE(kGRAY, 1)
        ENUM_VALUE(kRGB, kGRAY + 1)
        ENUM_VALUE(kBGR, kRGB + 1)
        ENUM_VALUE(kHSV, kRGB + 1)
        ENUM_VALUE(kHSL, kHSV + 1)
        ENUM_VALUE(kLUV, kHSL + 1)
        ENUM_VALUE(kARGB, kLUV + 1)
        ENUM_VALUE(kRGBA, kARGB + 1)
        ENUM_VALUE(kBGRA, kRGBA + 1)
        ENUM_VALUE(kABGR, kBGRA + 1)
        ENUM_VALUE(kBAYER_BGGR, kABGR + 1)
        ENUM_VALUE(kBAYER_RGGB, kBAYER_BGGR + 1)

        constexpr uint8_t numChannels() const;
    ENUM_END;

    template <class T>
    struct GRAY;
    template <class T>
    struct RGB;
    template <class T>
    struct BGR;
    template <class T>
    struct HSV;
    template <class T>
    struct HSL;
    template <class T>
    struct LUV;
    template <class T>
    struct ARGB;
    template <class T>
    struct RGBA;
    template <class T>
    struct BGRA;
    template <class T>
    struct ABGR;

    template <class DERIVED, class SCALAR, uint8_t CHANNELS>
    struct PackedPixelBase
    {
        using Scalar_t = SCALAR;
        static constexpr const uint8_t num_channels = CHANNELS;

        template <class... ARGS>
        PackedPixelBase(ARGS&&... args)
            : m_data{std::forward<ARGS>(args)...}
        {
        }

        GRAY<Scalar_t> gray() const;
        RGB<Scalar_t> rgb() const;
        BGR<Scalar_t> bgr() const;
        HSV<Scalar_t> hsv() const;
        HSL<Scalar_t> hsl() const;
        LUV<Scalar_t> luv() const;
        ARGB<Scalar_t> argb() const;
        RGBA<Scalar_t> rgba() const;
        BGRA<Scalar_t> bgra() const;
        ABGR<Scalar_t> abgr() const;

        // Returns h,s,v in terms of bgr values implemented in derived
        // Override by derived that can just return these values
        Scalar_t h() const;
        Scalar_t s() const;
        Scalar_t v() const;

        Scalar_t& operator()(size_t i)
        {
            return m_data[i];
        }

        const Scalar_t& operator()(size_t i) const
        {
            return m_data[i];
        }

        Scalar_t& operator[](size_t i)
        {
            return m_data[i];
        }

        const Scalar_t& operator[](size_t i) const
        {
            return m_data[i];
        }

      private:
        DERIVED* derived();
        const DERIVED* derived() const;
        SCALAR m_data[CHANNELS];
    };

    template <class T>
    struct GRAY : PackedPixelBase<GRAY<T>, T, 1>
    {
        using Super_t = PackedPixelBase<GRAY<T>, T, 1>;
        static constexpr const auto pixel_format = PixelFormat::kGRAY;
        GRAY(T v = 0)
            : PackedPixelBase<GRAY<T>, T, 1>(v)
        {
        }

        const T& r() const
        {
            return (*this)(0);
        }
        const T& g() const
        {
            return (*this)(0);
        }
        const T& b() const
        {
            return (*this)(0);
        }
        T a() const
        {
            return std::is_floating_point<T>::value ? 1 : 255;
        }

        T& r()
        {
            return (*this)(0);
        }
        T& g()
        {
            return (*this)(0);
        }
        T& b()
        {
            return (*this)(0);
        }
    };

    template <class T>
    struct RGB : PackedPixelBase<RGB<T>, T, 3>
    {
        using Super_t = PackedPixelBase<RGB<T>, T, 3>;
        static constexpr const auto pixel_format = PixelFormat::kRGB;
        RGB(const RGB&) = default;
        RGB(T r = 0, T g = 0, T b = 0)
            : Super_t(r, g, b)
        {
        }

        const T& r() const
        {
            return (*this)(0);
        }
        const T& g() const
        {
            return (*this)(1);
        }
        const T& b() const
        {
            return (*this)(2);
        }
        T a() const
        {
            return std::is_floating_point<T>::value ? 1 : 255;
        }

        T& r()
        {
            return (*this)(0);
        }
        T& g()
        {
            return (*this)(1);
        }
        T& b()
        {
            return (*this)(2);
        }
    };

    template <class T>
    struct ARGB : PackedPixelBase<ARGB<T>, T, 4>
    {
        using Super_t = PackedPixelBase<ARGB<T>, T, 4>;
        static constexpr const auto pixel_format = PixelFormat::kARGB;
        ARGB(T a = 0, T r = 0, T g = 0, T b = 0)
            : Super_t(a, r, g, b)
        {
        }
        const T& a() const
        {
            return (*this)(0);
        }
        const T& r() const
        {
            return (*this)(1);
        }
        const T& g() const
        {
            return (*this)(2);
        }
        const T& b() const
        {
            return (*this)(3);
        }

        T& a()
        {
            return (*this)(0);
        }
        T& r()
        {
            return (*this)(1);
        }
        T& g()
        {
            return (*this)(2);
        }
        T& b()
        {
            return (*this)(3);
        }
    };

    template <class T>
    struct RGBA : PackedPixelBase<RGBA<T>, T, 4>
    {
        using Super_t = PackedPixelBase<RGBA<T>, T, 4>;
        static constexpr const auto pixel_format = PixelFormat::kRGBA;
        RGBA(T r = 0, T g = 0, T b = 0, T a = 0)
            : Super_t(r, g, b, a)
        {
        }

        const T& r() const
        {
            return (*this)(0);
        }

        const T& g() const
        {
            return (*this)(1);
        }

        const T& b() const
        {
            return (*this)(2);
        }

        const T& a() const
        {
            return (*this)(3);
        }

        T& r()
        {
            return (*this)(0);
        }

        T& g()
        {
            return (*this)(1);
        }

        T& b()
        {
            return (*this)(2);
        }

        T& a()
        {
            return (*this)(3);
        }
    };

    template <class T>
    struct BGR : PackedPixelBase<BGR<T>, T, 3>
    {
        using Super_t = PackedPixelBase<BGR<T>, T, 3>;
        static constexpr const auto pixel_format = PixelFormat::kBGR;
        BGR(T b = 0, T g = 0, T r = 0)
            : Super_t(b, g, r)
        {
        }

        const T& b() const
        {
            return (*this)(0);
        }

        const T& g() const
        {
            return (*this)(1);
        }

        const T& r() const
        {
            return (*this)(2);
        }

        T a() const
        {
            return std::is_floating_point<T>::value ? 1 : 255;
        }

        T& b()
        {
            return (*this)(0);
        }

        T& g()
        {
            return (*this)(1);
        }

        T& r()
        {
            return (*this)(2);
        }
    };

    template <class T>
    struct ABGR : PackedPixelBase<ABGR<T>, T, 4>
    {
        using Super_t = PackedPixelBase<ABGR<T>, T, 4>;
        static constexpr const auto pixel_format = PixelFormat::kABGR;
        ABGR(T a = 0, T b = 0, T g = 0, T r = 0)
            : Super_t(a, b, g, r)
        {
        }

        const T& a() const
        {
            return (*this)(0);
        }

        const T& b() const
        {
            return (*this)(1);
        }

        const T& g() const
        {
            return (*this)(2);
        }

        const T& r() const
        {
            return (*this)(3);
        }

        T& a()
        {
            return (*this)(0);
        }

        T& b()
        {
            return (*this)(1);
        }

        T& g()
        {
            return (*this)(2);
        }

        T& r()
        {
            return (*this)(3);
        }
    };

    template <class T>
    struct BGRA : PackedPixelBase<BGRA<T>, T, 4>
    {
        using Super_t = PackedPixelBase<BGRA<T>, T, 4>;
        static constexpr const auto pixel_format = PixelFormat::kBGRA;
        BGRA(T b = 0, T g = 0, T r = 0, T a = 0)
            : Super_t(b, g, r, a)
        {
        }

        const T& b() const
        {
            return (*this)(0);
        }

        const T& g() const
        {
            return (*this)(1);
        }

        const T& r() const
        {
            return (*this)(2);
        }

        const T& a() const
        {
            return (*this)(3);
        }

        T& b()
        {
            return (*this)(0);
        }

        T& g()
        {
            return (*this)(1);
        }

        T& r()
        {
            return (*this)(2);
        }

        T& a()
        {
            return (*this)(3);
        }
    };

    template <class T>
    struct HSV : PackedPixelBase<HSV<T>, T, 3>
    {
        using Super_t = PackedPixelBase<HSV<T>, T, 3>;
        static constexpr const auto pixel_format = PixelFormat::kHSV;
        HSV(T h = 0, T s = 0, T v = 0)
            : Super_t(h, s, v)
        {
        }

        const T& h() const
        {
            return (*this)(0);
        }

        const T& s() const
        {
            return (*this)(1);
        }

        const T& v() const
        {
            return (*this)(2);
        }

        T a() const
        {
            return std::is_floating_point<T>::value ? 1 : 255;
        }

        T& h()
        {
            return (*this)(0);
        }

        T& s()
        {
            return (*this)(1);
        }

        T& v()
        {
            return (*this)(2);
        }

        // TODO Calculate r, g, b values from hsv
        T r() const;

        T g() const;

        T b() const;
    };

    template <class T>
    struct HSL : PackedPixelBase<HSL<T>, T, 3>
    {
        using Super_t = PackedPixelBase<HSL<T>, T, 3>;
        static constexpr const auto pixel_format = PixelFormat::kHSL;
        HSL(T h = 0, T s = 0, T l = 0)
            : Super_t(h, s, l)
        {
        }

        const T& h() const
        {
            return (*this)(0);
        }

        const T& s() const
        {
            return (*this)(1);
        }

        const T& l() const
        {
            return (*this)(2);
        }

        T a() const
        {
            return std::is_floating_point<T>::value ? 1 : 255;
        }

        T& h()
        {
            return (*this)(0);
        }

        T& s()
        {
            return (*this)(1);
        }

        T& l()
        {
            return (*this)(2);
        }

        // TODO Calculate r, g, b values from hsl
        T r();
        T g();
        T b();
    };

    template <class T>
    struct LUV : PackedPixelBase<LUV<T>, T, 3>
    {
        using Super_t = PackedPixelBase<LUV<T>, T, 3>;
        static constexpr const auto pixel_format = PixelFormat::kLUV;
        LUV(T h = 0, T s = 0, T l = 0)
            : Super_t(h, s, l)
        {
        }

        const T& l() const
        {
            return (*this)(0);
        }

        const T& u() const
        {
            return (*this)(1);
        }

        const T& v() const
        {
            return (*this)(2);
        }

        T a() const
        {
            return std::is_floating_point<T>::value ? 1 : 255;
        }

        T& l()
        {
            return (*this)(0);
        }

        T& u()
        {
            return (*this)(1);
        }

        T& v()
        {
            return (*this)(2);
        }

        // TODO Calculate r, g, b values from luv
        T r();
        T g();
        T b();
    };

    template <class DERIVED, class SCALAR, uint8_t CHANNELS>
    GRAY<SCALAR> PackedPixelBase<DERIVED, SCALAR, CHANNELS>::gray() const
    {
        return {0.2989 * derived()->r() + 0.5870 * derived()->g() + 0.1140 * derived()->b()};
    }

    template <class DERIVED, class SCALAR, uint8_t CHANNELS>
    RGB<SCALAR> PackedPixelBase<DERIVED, SCALAR, CHANNELS>::rgb() const
    {
        return {derived()->r(), derived()->g(), derived()->b()};
    }

    template <class DERIVED, class SCALAR, uint8_t CHANNELS>
    BGR<SCALAR> PackedPixelBase<DERIVED, SCALAR, CHANNELS>::bgr() const
    {
        return {derived()->b(), derived()->g(), derived()->r()};
    }

    template <class DERIVED, class SCALAR, uint8_t CHANNELS>
    HSV<SCALAR> PackedPixelBase<DERIVED, SCALAR, CHANNELS>::hsv() const
    {
        return {derived()->h(), derived()->s(), derived()->v()};
    }

    template <class DERIVED, class SCALAR, uint8_t CHANNELS>
    HSL<SCALAR> PackedPixelBase<DERIVED, SCALAR, CHANNELS>::hsl() const
    {
        return {derived()->h(), derived()->s(), derived()->l()};
    }

    template <class DERIVED, class SCALAR, uint8_t CHANNELS>
    LUV<SCALAR> PackedPixelBase<DERIVED, SCALAR, CHANNELS>::luv() const
    {
        // TODO
    }

    template <class DERIVED, class SCALAR, uint8_t CHANNELS>
    ARGB<SCALAR> PackedPixelBase<DERIVED, SCALAR, CHANNELS>::argb() const
    {
        return {derived()->a(), derived()->r(), derived()->g(), derived()->b()};
    }

    template <class DERIVED, class SCALAR, uint8_t CHANNELS>
    RGBA<SCALAR> PackedPixelBase<DERIVED, SCALAR, CHANNELS>::rgba() const
    {
        return {derived()->r(), derived()->g(), derived()->b(), derived()->a()};
    }

    template <class DERIVED, class SCALAR, uint8_t CHANNELS>
    BGRA<SCALAR> PackedPixelBase<DERIVED, SCALAR, CHANNELS>::bgra() const
    {
        return {derived()->b(), derived()->g(), derived()->r(), derived()->a()};
    }

    template <class DERIVED, class SCALAR, uint8_t CHANNELS>
    ABGR<SCALAR> PackedPixelBase<DERIVED, SCALAR, CHANNELS>::abgr() const
    {
        return {derived()->a(), derived()->b(), derived()->g(), derived()->r()};
    }

    // Returns h,s,v in terms of bgr values implemented in derived
    // Override by derived that can just return these values
    template <class DERIVED, class SCALAR, uint8_t CHANNELS>
    SCALAR PackedPixelBase<DERIVED, SCALAR, CHANNELS>::h() const
    {
        // TODO
    }

    template <class DERIVED, class SCALAR, uint8_t CHANNELS>
    SCALAR PackedPixelBase<DERIVED, SCALAR, CHANNELS>::s() const
    {
    }

    template <class DERIVED, class SCALAR, uint8_t CHANNELS>
    SCALAR PackedPixelBase<DERIVED, SCALAR, CHANNELS>::v() const
    {
    }

    template <class DERIVED, class SCALAR, uint8_t CHANNELS>
    DERIVED* PackedPixelBase<DERIVED, SCALAR, CHANNELS>::derived()
    {
        return static_cast<DERIVED*>(this);
    }

    template <class DERIVED, class SCALAR, uint8_t CHANNELS>
    const DERIVED* PackedPixelBase<DERIVED, SCALAR, CHANNELS>::derived() const
    {
        return static_cast<const DERIVED*>(this);
    }

    template <class T>
    using AvailablePixelFormats_t =
        ct::VariadicTypedef<GRAY<T>, RGB<T>, BGR<T>, HSV<T>, HSL<T>, LUV<T>, ARGB<T>, RGBA<T>, BGRA<T>, ABGR<T>>;

    template <class T>
    constexpr uint8_t numChannelsHelper(PixelFormat fmt, ct::VariadicTypedef<T>)
    {
        return fmt == T::pixel_format ? T::num_channels : 0;
    }

    template <class T, class... ARGS>
    constexpr uint8_t numChannelsHelper(PixelFormat fmt, ct::VariadicTypedef<T, ARGS...>)
    {
        return fmt == T::pixel_format ? T::num_channels : numChannelsHelper(fmt, ct::VariadicTypedef<ARGS...>{});
    }

    constexpr uint8_t PixelFormat::numChannels() const
    {
        return numChannelsHelper(*this, AvailablePixelFormats_t<uint8_t>{});
    }
} // namespace aq

#endif // AQUILA_TYPES_PIXELS_HPP

ext: hpp

max_stars_repo_name: dtmoodie/Acquilla

max_issues_repo_name: dtmoodie/Acquilla

max_forks_repo_name: dtmoodie/Acquilla


text:
/*
 *          Copyright Andrey Semashev 2007 - 2010.
 * 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)
 */
/*!
 * \file   scoped_attribute.hpp
 * \author Andrey Semashev
 * \date   13.05.2007
 *
 * The header contains definition of facilities to define scoped attributes.
 */

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

#ifndef BOOST_LOG_UTILITY_SCOPED_ATTRIBUTE_HPP_INCLUDED_
#define BOOST_LOG_UTILITY_SCOPED_ATTRIBUTE_HPP_INCLUDED_

#include <boost/shared_ptr.hpp>
#include <boost/utility/addressof.hpp>
#include <boost/preprocessor/seq/enum.hpp>
#include <boost/log/detail/prologue.hpp>
#include <boost/log/core/core.hpp>
#include <boost/log/sources/basic_logger.hpp>
#include <boost/log/attributes/attribute_set.hpp>
#include <boost/log/attributes/constant.hpp>
#include <boost/log/utility/empty_deleter.hpp>
#include <boost/log/utility/no_unused_warnings.hpp>
#include <boost/log/utility/unique_identifier_name.hpp>

namespace boost {

namespace BOOST_LOG_NAMESPACE {

namespace aux {

    //! A base class for all scoped attribute classes
    class attribute_scope_guard
    {
    };

} // namespace aux

//! Scoped attribute guard type
typedef aux::attribute_scope_guard const& scoped_attribute;

namespace aux {

    //! A scoped logger attribute guard
    template< typename LoggerT >
    class scoped_logger_attribute :
        public attribute_scope_guard
    {
    private:
        //! Logger type
        typedef LoggerT logger_type;

    private:
        //! A reference to the logger
        mutable logger_type* m_pLogger;
        //! An iterator to the added attribute
        typename logger_type::attribute_set_type::iterator m_itAttribute;

    public:
        //! Constructor
        scoped_logger_attribute(
            logger_type& l,
            typename logger_type::string_type const& name,
            shared_ptr< attribute > const& attr
        ) :
            m_pLogger(boost::addressof(l))
        {
            std::pair<
                typename logger_type::attribute_set_type::iterator,
                bool
            > res = l.add_attribute(name, attr);
            if (res.second)
                m_itAttribute = res.first;
            else
                m_pLogger = 0; // if there already is a same-named attribute, don't register anything
        }
        //! Copy constructor (implemented as move)
        scoped_logger_attribute(scoped_logger_attribute const& that) :
            m_pLogger(that.m_pLogger),
            m_itAttribute(that.m_itAttribute)
        {
            that.m_pLogger = 0;
        }

        //! Destructor
        ~scoped_logger_attribute()
        {
            if (m_pLogger)
            {
                m_pLogger->remove_attribute(m_itAttribute);
            }
        }

    private:
        //! Assignment (closed)
        scoped_logger_attribute& operator= (scoped_logger_attribute const&);
    };

} // namespace aux

//  Generator helper functions
/*!
 * Registers an attribute in the logger
 *
 * \param l Logger to register the attribute in
 * \param name Attribute name
 * \param attr Pointer to the attribute. Must not be NULL.
 * \return An unspecified guard object that may be used to initialize \c scoped_attribute variable.
 */
template< typename LoggerT >
inline aux::scoped_logger_attribute< LoggerT > add_scoped_logger_attribute(
    LoggerT& l, typename LoggerT::string_type const& name, shared_ptr< attribute > const& attr)
{
    return aux::scoped_logger_attribute< LoggerT >(l, name, attr);
}

#ifndef BOOST_LOG_DOXYGEN_PASS

template< typename LoggerT >
inline aux::scoped_logger_attribute< LoggerT > add_scoped_logger_attribute(
    LoggerT& l, typename LoggerT::char_type const* name, shared_ptr< attribute > const& attr)
{
    return aux::scoped_logger_attribute< LoggerT >(l, name, attr);
}

template< typename LoggerT, typename AttributeT >
inline aux::scoped_logger_attribute< LoggerT > add_scoped_logger_attribute(
    LoggerT& l, typename LoggerT::string_type const& name, AttributeT& attr)
{
    return aux::scoped_logger_attribute< LoggerT >(
        l, name, shared_ptr< attribute >(boost::addressof(attr), empty_deleter()));
}

template< typename LoggerT, typename AttributeT >
inline aux::scoped_logger_attribute< LoggerT > add_scoped_logger_attribute(
    LoggerT& l, typename LoggerT::char_type const* name, AttributeT& attr)
{
    return aux::scoped_logger_attribute< LoggerT >(
        l, name, shared_ptr< attribute >(boost::addressof(attr), empty_deleter()));
}

#endif // BOOST_LOG_DOXYGEN_PASS

//! \cond

#define BOOST_LOG_SCOPED_LOGGER_ATTR_CTOR_INTERNAL(logger, attr_name, attr_type, attr_ctor_args, attr_var_name, sentry_var_name)\
    attr_type attr_var_name(BOOST_PP_SEQ_ENUM(attr_ctor_args));\
    ::boost::log::scoped_attribute sentry_var_name =\
        ::boost::log::add_scoped_logger_attribute(logger, attr_name, attr_var_name);\
    BOOST_LOG_NO_UNUSED_WARNINGS(sentry_var_name)

#define BOOST_LOG_SCOPED_LOGGER_ATTR_INTERNAL(logger, attr_name, attr_type, attr_var_name, sentry_var_name)\
    attr_type attr_var_name;\
    ::boost::log::scoped_attribute sentry_var_name =\
        ::boost::log::add_scoped_logger_attribute(logger, attr_name, attr_var_name);\
    BOOST_LOG_NO_UNUSED_WARNINGS(sentry_var_name)

//! \endcond

//! The macro sets a scoped logger-wide attribute with constructor arguments in a more compact way
#define BOOST_LOG_SCOPED_LOGGER_ATTR_CTOR(logger, attr_name, attr_type, attr_ctor_args)\
    BOOST_LOG_SCOPED_LOGGER_ATTR_CTOR_INTERNAL(\
        logger,\
        attr_name,\
        attr_type,\
        attr_ctor_args,\
        BOOST_LOG_UNIQUE_IDENTIFIER_NAME(_boost_log_scoped_logger_attr_),\
        BOOST_LOG_UNIQUE_IDENTIFIER_NAME(_boost_log_scoped_logger_attr_sentry_))

//! The macro sets a scoped logger-wide attribute in a more compact way
#define BOOST_LOG_SCOPED_LOGGER_ATTR(logger, attr_name, attr_type)\
    BOOST_LOG_SCOPED_LOGGER_ATTR_INTERNAL(\
        logger,\
        attr_name,\
        attr_type,\
        BOOST_LOG_UNIQUE_IDENTIFIER_NAME(_boost_log_scoped_logger_attr_),\
        BOOST_LOG_UNIQUE_IDENTIFIER_NAME(_boost_log_scoped_logger_attr_sentry_))

//! The macro sets a scoped logger-wide tag in a more compact way
#define BOOST_LOG_SCOPED_LOGGER_TAG(logger, attr_name, attr_type, attr_value)\
    BOOST_LOG_SCOPED_LOGGER_ATTR_CTOR(logger, attr_name, ::boost::log::attributes::constant< attr_type >, (attr_value))

namespace aux {

    //! A scoped thread-specific attribute guard
    template< typename CharT >
    class scoped_thread_attribute :
        public attribute_scope_guard
    {
    private:
        //! Logging core type
        typedef basic_core< CharT > core_type;

    private:
        //! A pointer to the logging core
        mutable shared_ptr< core_type > m_pCore;
        //! An iterator to the added attribute
        typename core_type::attribute_set_type::iterator m_itAttribute;

    public:
        //! Constructor
        scoped_thread_attribute(
            typename core_type::string_type const& name, shared_ptr< attribute > const& attr) :
            m_pCore(core_type::get())
        {
            std::pair<
                typename core_type::attribute_set_type::iterator,
                bool
            > res = m_pCore->add_thread_attribute(name, attr);
            if (res.second)
                m_itAttribute = res.first;
            else
                m_pCore.reset(); // if there already is a same-named attribute, don't register anything
        }
        //! Copy constructor (implemented as move)
        scoped_thread_attribute(scoped_thread_attribute const& that) : m_itAttribute(that.m_itAttribute)
        {
            m_pCore.swap(that.m_pCore);
        }

        //! Destructor
        ~scoped_thread_attribute()
        {
            if (m_pCore)
            {
                m_pCore->remove_thread_attribute(m_itAttribute);
            }
        }

    private:
        //! Assignment (closed)
        scoped_thread_attribute& operator= (scoped_thread_attribute const&);
    };

} // namespace aux

//  Generator helper functions
/*!
 * Registers a thread-specific attribute
 *
 * \param name Attribute name
 * \param attr Pointer to the attribute. Must not be NULL.
 * \return An unspecified guard object that may be used to initialize \c scoped_attribute variable.
 */
template< typename CharT >
inline aux::scoped_thread_attribute< CharT > add_scoped_thread_attribute(
    std::basic_string< CharT > const& name, shared_ptr< attribute > const& attr)
{
    return aux::scoped_thread_attribute< CharT >(name, attr);
}

#ifndef BOOST_LOG_DOXYGEN_PASS

template< typename CharT >
inline aux::scoped_thread_attribute< CharT > add_scoped_thread_attribute(
    const CharT* name, shared_ptr< attribute > const& attr)
{
    return aux::scoped_thread_attribute< CharT >(name, attr);
}

template< typename CharT, typename AttributeT >
inline aux::scoped_thread_attribute< CharT > add_scoped_thread_attribute(
    std::basic_string< CharT > const& name, AttributeT& attr)
{
    return aux::scoped_thread_attribute< CharT >(
        name, shared_ptr< attribute >(boost::addressof(attr), empty_deleter()));
}

template< typename CharT, typename AttributeT >
inline aux::scoped_thread_attribute< CharT > add_scoped_thread_attribute(
    const CharT* name, AttributeT& attr)
{
    return aux::scoped_thread_attribute< CharT >(
        name, shared_ptr< attribute >(boost::addressof(attr), empty_deleter()));
}

#endif // BOOST_LOG_DOXYGEN_PASS

//! \cond

#define BOOST_LOG_SCOPED_THREAD_ATTR_CTOR_INTERNAL(attr_name, attr_type, attr_ctor_args, attr_var_name, sentry_var_name)\
    attr_type attr_var_name(BOOST_PP_SEQ_ENUM(attr_ctor_args));\
    ::boost::log::scoped_attribute sentry_var_name =\
        ::boost::log::add_scoped_thread_attribute(attr_name, attr_var_name);\
    BOOST_LOG_NO_UNUSED_WARNINGS(sentry_var_name)

#define BOOST_LOG_SCOPED_THREAD_ATTR_INTERNAL(attr_name, attr_type, attr_var_name, sentry_var_name)\
    attr_type attr_var_name;\
    ::boost::log::scoped_attribute sentry_var_name =\
        ::boost::log::add_scoped_thread_attribute(attr_name, attr_var_name);\
    BOOST_LOG_NO_UNUSED_WARNINGS(sentry_var_name)

//! \endcond

//! The macro sets a scoped thread-wide attribute with constructor arguments in a more compact way
#define BOOST_LOG_SCOPED_THREAD_ATTR_CTOR(attr_name, attr_type, attr_ctor_args)\
    BOOST_LOG_SCOPED_THREAD_ATTR_CTOR_INTERNAL(\
        attr_name,\
        attr_type,\
        attr_ctor_args,\
        BOOST_LOG_UNIQUE_IDENTIFIER_NAME(_boost_log_scoped_thread_attr_),\
        BOOST_LOG_UNIQUE_IDENTIFIER_NAME(_boost_log_scoped_thread_attr_sentry_))

//! The macro sets a scoped thread-wide attribute in a more compact way
#define BOOST_LOG_SCOPED_THREAD_ATTR(attr_name, attr_type)\
    BOOST_LOG_SCOPED_THREAD_ATTR_INTERNAL(\
        attr_name,\
        attr_type,\
        BOOST_LOG_UNIQUE_IDENTIFIER_NAME(_boost_log_scoped_thread_attr_),\
        BOOST_LOG_UNIQUE_IDENTIFIER_NAME(_boost_log_scoped_thread_attr_sentry_))

//! The macro sets a scoped thread-wide tag in a more compact way
#define BOOST_LOG_SCOPED_THREAD_TAG(attr_name, attr_type, attr_value)\
    BOOST_LOG_SCOPED_THREAD_ATTR_CTOR(attr_name, ::boost::log::attributes::constant< attr_type >, (attr_value))

} // namespace log

} // namespace boost

#endif // BOOST_LOG_UTILITY_SCOPED_ATTRIBUTE_HPP_INCLUDED_


text:
/*

*

*	Author: Philipp Zschoche

*

*/
#ifndef __ANDROID__
#ifndef __FILE_LOGGER_HPP__
#define __FILE_LOGGER_HPP__

#include "logger.hpp"
#include <string>
#include <fstream>
#include <boost/filesystem.hpp>
#include "thread_safe.hpp"

typedef std::size_t mlog_bytes;

/*

constexpr mlog_bytes operator"" _KB(int kb)

{

	return kb * 1024;

}

constexpr mlog_bytes operator"" _MB(std::size_t mb)

{

	return mb * 1024 * 1024;

}

constexpr mlog_bytes operator"" _GB(std::size_t bg)

{

	return gb * 1024 * 1024 * 1024;

}

*/

namespace mlog {

class file_logger : public logger<file_logger> {
      public:

	file_logger(std::string log_name, std::string log_directory = ".",
		    mlog_bytes max_file_size = 5 * 1024 * 1024 /*5_MB*/);
	virtual ~file_logger();

	template <typename M, typename T>
	void write_to_log(M &&metadata, T &&log_text) {
		std::string str =
		    metadata.to_string(std::forward<T>(log_text), true);
		m_stream.write(str.c_str(), str.size());
		m_offset += str.size();

		if (m_flush_immediately)
			flush();

		if (m_max_file_size != 0 && m_offset > max_file_size()) {
			m_stream.open(
			    get_next_logfile(m_log_directory, m_log_name,
					     max_file_size(), &m_offset),
			    std::ios::binary);
		}
	}

	template <typename T> inline void max_file_size(T value) {
		m_max_file_size = std::forward<T>(value);
	}

	inline unsigned int max_file_size() const { return m_max_file_size; }

	inline bool is_open() const { return m_stream.is_open(); }

	void flush();

	inline bool flush_immediately() const { return m_flush_immediately; }

	template <typename T> void flush_immediately(T &&value) {
		m_flush_immediately = value;
	}

      private:

	bool m_flush_immediately;

	std::ofstream m_stream;
	std::string m_log_name;
	std::string m_log_directory;
	unsigned int m_max_file_size;
	mlog_bytes m_offset;

	static std::string get_next_logfile(const std::string &directory,
					    const std::string name,
					    mlog_bytes max_file_size,
					    mlog_bytes *offset = 0);
};

typedef thread_safe<file_logger> file_logger_thread_safe;

} /* mlog */

#endif /* __FILE_LOGGER_HPP__ */

#ifdef MLOG_NO_LIB
#include "impl/file_logger.hpp"
#endif
#endif /* __ANDROID__ */

max_stars_repo_name: urstripathi/mlog

max_issues_repo_name: urstripathi/mlog

max_forks_repo_name: urstripathi/mlog


text:
#include "Fireworks/FWInterface/src/FWPathsPopup.h"
#include "Fireworks/FWInterface/src/FWPSetTableManager.h"
#include "Fireworks/FWInterface/src/FWPSetCellEditor.h"

#include "Fireworks/FWInterface/interface/FWFFLooper.h"
#include "Fireworks/TableWidget/interface/FWTableWidget.h"

#include "Fireworks/Core/src/FWDialogBuilder.h"
#include "Fireworks/Core/interface/FWGUIManager.h"
#include "Fireworks/Core/interface/fwLog.h"

#include "FWCore/Framework/interface/ScheduleInfo.h"
#include "FWCore/Framework/interface/Event.h"
#include "FWCore/Framework/interface/EventSetup.h"
#include "FWCore/Common/interface/TriggerNames.h"

#include "FWCore/Utilities/interface/Exception.h"

#include "DataFormats/Provenance/interface/ModuleDescription.h"
#include "DataFormats/Provenance/interface/ProcessHistory.h"
#include "DataFormats/Common/interface/TriggerResults.h"

#include "FWCore/ServiceRegistry/interface/ModuleCallingContext.h"
#include "FWCore/ServiceRegistry/interface/StreamContext.h"

#include "FWCore/PythonParameterSet/src/PythonWrapper.h"
#include <boost/python/errors.hpp>
#include "TGLabel.h"
#include "KeySymbols.h"

void
FWPathsPopup::windowIsClosing()
{
   UnmapWindow();
   DontCallClose();
}

FWPathsPopup::FWPathsPopup(FWFFLooper *looper, FWGUIManager *guiManager)
   : TGMainFrame(gClient->GetRoot(), 400, 600),
     m_info(nullptr),
     m_looper(looper),
     m_hasChanges(false),
     m_moduleLabel(nullptr),
     m_moduleName(nullptr),
     m_apply(nullptr),
     m_psTable(new FWPSetTableManager()),
     m_guiManager(guiManager)
{
   gVirtualX->SelectInput(GetId(), kKeyPressMask | kKeyReleaseMask | kExposureMask |
                          kPointerMotionMask | kStructureNotifyMask | kFocusChangeMask |
                          kEnterWindowMask | kLeaveWindowMask);
   this->Connect("CloseWindow()","FWPathsPopup",this,"windowIsClosing()");

   FWDialogBuilder builder(this);
   builder.indent(4)
      .spaceDown(10)
      .addLabel("Filter:").floatLeft(4).expand(false, false)
      .addTextEntry("", &m_search).expand(true, false)
      .spaceDown(10)
      .addTable(m_psTable, &m_tableWidget).expand(true, true)
      .addTextButton("Apply changes and reload", &m_apply);

   FWPSetCellEditor *editor = new  FWPSetCellEditor(m_tableWidget->body(), "");
   editor->SetBackgroundColor(gVirtualX->GetPixel(kYellow-7));
   editor->SetFrameDrawn(false);
   m_psTable->setCellValueEditor(editor);
   m_psTable->m_editor->Connect("ReturnPressed()", "FWPathsPopup", this, "applyEditor()");

   m_apply->Connect("Clicked()", "FWPathsPopup", this, "scheduleReloadEvent()");
   m_apply->SetEnabled(false);
   m_search->SetEnabled(true);
   m_search->Connect("TextChanged(const char *)", "FWPathsPopup",
                     this, "updateFilterString(const char *)");
   m_tableWidget->SetBackgroundColor(0xffffff);
   m_tableWidget->SetLineSeparatorColor(0x000000);
   m_tableWidget->SetHeaderBackgroundColor(0xececec);
   m_tableWidget->Connect("cellClicked(Int_t,Int_t,Int_t,Int_t,Int_t,Int_t)",
                          "FWPathsPopup",this,
                          "cellClicked(Int_t,Int_t,Int_t,Int_t,Int_t,Int_t)");
   m_tableWidget->disableGrowInWidth();

   SetWindowName("CMSSW Configuration Editor");
   MapSubwindows();
   editor->UnmapWindow();

   Layout();
}

/** Handle pressing of esc.
 */
Bool_t
FWPathsPopup::HandleKey(Event_t*event)
{
   UInt_t keysym = event->fCode;

   if (keysym == (UInt_t) gVirtualX->KeysymToKeycode(kKey_Escape))
   {
      // called from FWPSetCellEditor
      m_psTable->cancelEditor();
      m_psTable->setSelection(-1, -1, 0);
   }
   return TGMainFrame::HandleKey(event);
}

/** Proxies the applyEditor() method in the model so that it can be connected to GUI, signals.
  */
void
FWPathsPopup::applyEditor()
{
   bool applied = m_psTable->applyEditor();
   if (applied)
      m_apply->SetEnabled(true);
}

/** Handles clicking on the table cells.

    * Clicking on a cell in the first column opens / closes a given node.
    * Clicking on a cell in the second column moves the editor to that cell.

  */
void
FWPathsPopup::cellClicked(Int_t iRow, Int_t iColumn, Int_t iButton, Int_t iKeyMod, Int_t, Int_t)
{
   if (iButton != kButton1)
      return;

   if (iColumn == 0 || iColumn == 1)
   {
      // Save and close the previous editor, if required.
      if (m_psTable->selectedColumn() == 1
          && m_psTable->selectedRow() != -1)
      {
         int oldIndex = m_psTable->rowToIndex()[m_psTable->selectedRow()];
         FWPSetTableManager::PSetData& oldData = m_psTable->data()[oldIndex];

         if (oldData.editable)
            applyEditor();
      }

      m_psTable->setSelection(iRow, iColumn, iKeyMod);

      if (iColumn == 0)
         m_psTable->setExpanded(iRow);
   }
}

void
FWPathsPopup::updateFilterString(const char *str)
{
   m_psTable->applyEditor();
   m_psTable->setSelection(-1, -1, 0);
   m_psTable->updateFilter(str);
}

/** Finish the setup of the GUI */
void
FWPathsPopup::setup(const edm::ScheduleInfo *info)
{
   assert(info);
   m_info = info;
}

/** Gets called by CMSSW as modules are about to be processed. **/
void
FWPathsPopup::postModuleEvent(edm::StreamContext const &s, edm::ModuleCallingContext const &mcc)
{
   m_guiManager->updateStatus((mcc.moduleDescription()->moduleName() + " processed.").c_str());
   gSystem->ProcessEvents();
}

/** Gets called by CMSSW as we process modules. **/
void
FWPathsPopup::preModuleEvent(edm::StreamContext const &s, edm::ModuleCallingContext const &mcc)
{
   m_guiManager->updateStatus(("Processing " + mcc.moduleDescription()->moduleName()  + "...").c_str());
   gSystem->ProcessEvents();
}

void
FWPathsPopup::postEvent(edm::Event const &event)
{
   m_guiManager->updateStatus("Done processing.");
   gSystem->ProcessEvents();

   // Get the last process name from the process history:
   // this should be the one specified in the cfg file

   if (event.processHistory().empty()) {
      fwLog(fwlog::kInfo) << "Path GUI:: no process history available.\n";
      return;
   }
   edm::ProcessHistory::const_iterator pi = event.processHistory().end() - 1;
   std::string processName = pi->processName();

   // It's called TriggerResults but actually contains info on all paths
   edm::InputTag tag("TriggerResults", "", processName);
   edm::Handle<edm::TriggerResults> triggerResults;
   event.getByLabel(tag, triggerResults);

   std::vector<FWPSetTableManager::PathUpdate> pathUpdates;

   if (triggerResults.isValid())
   {
      const edm::TriggerNames& triggerNames = event.triggerNames(*triggerResults);

      for (size_t i = 0, e = triggerResults->size(); i != e; ++i)
      {
         FWPSetTableManager::PathUpdate update;
         update.pathName = triggerNames.triggerName(i);
         update.passed = triggerResults->accept(i);
         update.choiceMaker = triggerResults->index(i);
         pathUpdates.push_back(update);
      }
   }
   m_psTable->updateSchedule(m_info);
   m_psTable->update(pathUpdates);
   m_psTable->dataChanged();
   m_tableWidget->body()->DoRedraw();
}

/** Modifies the module and asks the looper to reload the event.

    1. Read the configuration snippet from the GUI,
    2. Use the python interpreter to parse it and get the new
      parameter set.
    3. Notify the looper about the changes.

    FIXME: implement 2 and 3.
  */
void
FWPathsPopup::scheduleReloadEvent()
{
   applyEditor();
   try
   {
      for (size_t mni = 0, mne = m_psTable->modules().size(); mni != mne; ++mni)
      {
         FWPSetTableManager::ModuleInfo &module = m_psTable->modules()[mni];
         if (module.dirty == false)
            continue;
         FWPSetTableManager::PSetData &data = m_psTable->entries()[module.entry];
         m_looper->requestChanges(data.label, * module.current_pset);
      }
      m_hasChanges = true;
      m_apply->SetEnabled(false);
      gSystem->ExitLoop();
   }
   catch (boost::python::error_already_set const&)
   {
      edm::pythonToCppException("Configuration");
      Py_Finalize();
   }
   catch (cms::Exception &exception)
   {
      std::cout << exception.what() << std::endl;
   }
   // Return control to the FWFFLooper so that it can decide what to do next.
}

ext: cc

max_stars_repo_name: trackerpro/cmssw

max_issues_repo_name: trackerpro/cmssw

max_forks_repo_name: trackerpro/cmssw


text:
#include <catch.hpp>
#include <libral/ral.hpp>
#include <iostream>
#include <memory>

#include <boost/optional/optional_io.hpp>
#include "boost/filesystem.hpp"

#include "fixtures.hpp"

namespace libral {
  SCENARIO("json_provider harness") {
    auto aral = ral::create({ TEST_DATA_DIR });
    auto json_prov = *aral->find_provider("json");

    SECTION("behaves with invalid error messages") {
      auto all = json_prov->get();
      REQUIRE(all.is_ok());

      for(const auto &r0 : all.ok()) {
        auto res = json_prov->find(r0.name());
        REQUIRE(res.is_err());

        // Every error message needs to contain the provider name
        REQUIRE_THAT(res.err().detail, Catch::Contains("[json::json]"));
        // The resources tell us in "message" if there are specific things
        // we should look for in the error message
        auto msg = r0.lookup<std::string>("message");
        if (msg) {
          REQUIRE_THAT(res.err().detail, Catch::Contains(*msg));
        }
      }

      // Now tickle the same error via an update
      for(const auto &r0 : all.ok()) {
        // The resource names for set need to be prefixed with 'set_' so we
        // do not trip the provider's get which happens before set is
        // called
        auto should = json_prov->create("set_" + r0.name());
        should["ensure"] = "absent";
        auto res = json_prov->set({ should });
        REQUIRE(res.is_err());
        REQUIRE_THAT(res.err().detail, Catch::Contains("[json::json]"));
        auto msg = r0.lookup<std::string>("message");
        if (msg) {
          REQUIRE_THAT(res.err().detail, Catch::Contains(*msg));
        }
      }
    }

  }
}

max_stars_repo_name: puppetlabs/libral

max_issues_repo_name: puppetlabs-toy-chest/libral

max_forks_repo_name: puppetlabs-toy-chest/libral


text:
#define NOMINMAX

#include <opencv2/text.hpp>
#include <opencv2/core/utility.hpp>
#include <opencv2/highgui.hpp>
#include <opencv2/imgproc.hpp>
#include <tesseract/baseapi.h>
#include <leptonica/allheaders.h>
#include <boost/format.hpp>
#include <boost/algorithm/string.hpp>
#include <iostream>
#include <fstream>
#include <vector>
#include <math.h>
#include <algorithm>
#include <array>
#include <random>
#include <vector>
#include <numeric>

using std::cout;
using std::cerr;
using std::endl;

struct TelemetryPoint {
    unsigned int velocity;
    unsigned int altitude;

    TelemetryPoint(unsigned int velocity, unsigned int altitude)
        : velocity(velocity), altitude(altitude)
    {}
};

struct Telemetry {
    unsigned int fps;
    unsigned long frames;
    std::vector<TelemetryPoint> data;

    Telemetry(unsigned int fps, unsigned long frames)
        : fps(fps), frames(frames)
    {
        data.reserve(frames);
    }

    void write_data(std::ostream& out) {
        for (size_t x = 0; x < data.size(); x++) {
            const TelemetryPoint& point = data[x];
            out << x/(double)fps << "," << point.velocity << "," << point.altitude << endl;
        }
    }
};

void onMouse(int event, int x, int y, int, void* userdata)
{
    if (event != CV_EVENT_LBUTTONDOWN)
        return;

    cv::Mat* frame = static_cast<cv::Mat*>(userdata);

    cout << "(" << x << ", " << y << "): " << (int)frame->at<uchar>(y, x) << endl;
}

int count_digits(int n) {
    int digits = 1;
    for (int x = 10; ; x *= 10) {
        if (n / x > 0) {
            digits++;
        } else {
            break;
        }
    }
    return digits;
}

class Trainer {
private:
    std::array<int, 10> counts;
    std::vector<cv::Mat> training_data;
    int width, height, count, total_count;

public:
    Trainer(int width, int height, int count)
        : width(width), height(height), count(count), total_count(count*10)
    {
        std::fill(counts.begin(), counts.end(), 0);
        counts[5] -= 3;
        counts[6] -= 3;
    }

    void seen_digit(int digit, const cv::Mat& mat)
    {
        if (counts[digit] < count) {
            cv::Mat copy;
            mat.copyTo(copy);

            training_data.push_back(std::move(copy));
            counts[digit]++;
        }
    }

    bool is_ready() const {
        return training_data.size() == total_count;
    }

    cv::Mat generate_training_image() const {

        int vertical_padding = 10;
        int horizontal_padding = 0;

        cv::Mat training_mat(cv::Size(width + (horizontal_padding*2), (height + vertical_padding) * total_count), CV_8UC1);
        training_mat.setTo(cv::Scalar(0));

        std::vector<int> order(training_data.size());
        std::iota(order.begin(), order.end(), 0);
        std::random_shuffle(order.begin(), order.end());

        cv::Rect next_place(horizontal_padding, vertical_padding, width, height);
        for (size_t x = 0; x < order.size(); x++) {
            const cv::Mat& mat = training_data[order[x]];
            mat.copyTo(training_mat(next_place));

            next_place.y += height + vertical_padding;
        }

        return training_mat;
    }
};

struct MinimumInt {
    int x;

    MinimumInt(int x)
        : x(x)
    {}

    bool operator==(const MinimumInt& other) {
        return other.x >= x;
    }
};

class SpaceXOCR {
private:
    tesseract::TessBaseAPI tess;
    cv::VideoCapture cap;
    cv::Mat frame;
    cv::Rect velocity_rect;
    cv::Rect altitude_rect;
    cv::Mat velocity_mat, altitude_mat;
    Trainer trainer;

    double fps;
    unsigned long frame_count;
    unsigned int width, height;

    void configure_for_velocity() {
        tess.SetVariable("tessedit_char_whitelist", "0123456789");
    }

    void configure_for_altitude() {
       tess.SetVariable("tessedit_char_whitelist", "0123456789.");
    }

    template <typename T> T as_number(const char* str);

    template <>
    int as_number(const char* str) {
        return atoi(str);
    }

    template <>
    double as_number(const char* str) {
        return atof(str);
    }

    template <typename T>
    T recognize(const cv::Mat& frame, const cv::Rect& roi, cv::Mat& mat)
    {
        resize(frame(roi), mat, roi.size() * 2, 0.0, 0.0, cv::INTER_CUBIC);
        cv::cvtColor(mat, mat, CV_BGR2GRAY);

        // accuracy is very dependent on this threshold value
        cv::threshold(mat, mat, 130, 255, cv::THRESH_BINARY);

        tess.SetImage((uchar*)mat.data, mat.size().width, mat.size().height, mat.channels(), mat.step1());
        tess.Recognize(0);

        return as_number<T>(tess.GetUTF8Text());
    }

    bool get_velocity(const cv::Rect& roi, cv::Mat& mat, char* result)
    {
        resize(frame(roi), mat, roi.size() * 2, 0.0, 0.0, cv::INTER_CUBIC);
        cv::cvtColor(mat, mat, CV_BGR2GRAY);

        // accuracy is very dependent on this threshold value
        cv::threshold(mat, mat, 130, 255, cv::THRESH_BINARY);

        tess.SetImage((uchar*)mat.data, mat.size().width, mat.size().height, mat.channels(), mat.step1());

        int boxes[] = { 7, 33, 60, 89, 114 };

        for (int i = 0; i < 5; i++) {
            int x = boxes[i] - 1;
            int y = 3;
            int w = 23 + 1;
            int h = 32;

            tess.SetRectangle(x, y, w, h);
            char c = tess.GetUTF8Text()[0];

            if (c < '0' || c > '9') {
                return false;
            }
            result[i] = c;
            int int_value = c - '0';

            //int conf = tess.MeanTextConf();
            //fprintf(stdout, "Box[%d]: x=%d, y=%d, w=%d, h=%d, confidence: %d, text: %d\n",
            //        i, x, y, w, h, conf, int_value);
        }

        result[5] = 0;
        return true;
        //for (int i = 0; i < 5; i++) {
        //    cv::line(mat, cv::Point(boxes[i]-1, 0), cv::Point(boxes[i]-1, 36), cv::Scalar(255, 255, 255));
        //}
    }

    void display(cv::Mat& velocity, cv::Rect& velocity_rect, cv::Mat& altitude, cv::Rect& altitude_rect) {
        cv::Mat velocity3, altitude3;

        cv::cvtColor(velocity, velocity3, CV_GRAY2BGR);
        velocity3.copyTo(frame(velocity_rect));

        cv::cvtColor(altitude, altitude3, CV_GRAY2BGR);
        altitude3.copyTo(frame(altitude_rect));

        imshow("JCSAT-14", frame);
        cv::waitKey();
    }

    bool skip_to_approx_telemetry_start(int frame_step)
    {
        unsigned long current_frame = cap.get(cv::CAP_PROP_POS_FRAMES);
        char velocity_str[6];

        cap >> frame;

        while (!frame.empty()) {
            imshow("JCSAT-14", frame);
            cv::waitKey(1);

            if (get_velocity(velocity_rect, velocity_mat, velocity_str)) {
                cap.set(cv::CAP_PROP_POS_FRAMES, std::max(0ul, current_frame - frame_step));
                return true;
            }

            current_frame += frame_step;
            cap.set(cv::CAP_PROP_POS_FRAMES, current_frame);

            cap >> frame;
        }

        return false;
    }

    template <typename Itr>
    bool skip_to_telemetry_start(const Itr expected_start, const Itr expected_end) {
        int frame_step = roundl(fps * 30);
        char velocity_str[6];

        if (skip_to_approx_telemetry_start(frame_step)) {
            auto itr = expected_start;
            while (itr != expected_end) {

                cap >> frame;

                if (frame.empty()) {
                    return false;
                }

                if (!get_velocity(velocity_rect, velocity_mat, velocity_str)) {
                    continue;
                }

                int velocity = atoi(velocity_str);

                if (*itr == velocity) {
                    ++itr;
                } else {
                    itr = expected_start;
                }
            }

            return true;
        } else {
            return false;
        }
    }

    void begin_processing_telemetry(Telemetry& result)
    {
        cv::Rect display_rect(541, 142, 144, 40);
        cv::Rect altitude_display_rect(541, 342, 144, 40);

        int prev_digits = 0;
        int prev_velocity = 0;

        bool do_show = false;
        int empty_count = 0;

        for (int x = 0; ; ++x)
        {
            cap >> frame;

            cv::Size size = frame.size();
            if (frame.empty())
                break;

            configure_for_velocity();

            char velocity_str[6];
            int boxes[] = { 7, 33, 60, 89, 114 };
            if (!get_velocity(velocity_rect, velocity_mat, velocity_str)) {

                ++empty_count;
                //imshow("JCSAT-14", frame);
                //cv::waitKey();

                if (empty_count >= 5) {
                    unsigned long current = cap.get(cv::CAP_PROP_POS_FRAMES);
                    std::array<MinimumInt, 3> expected_mins{ prev_velocity - 1000, prev_velocity - 1000, prev_velocity - 1000 };

                    if (skip_to_telemetry_start(expected_mins.begin(), expected_mins.end())) {
                        unsigned long skipped = cap.get(cv::CAP_PROP_POS_FRAMES) - current;
                        for (unsigned long i = 0; i < skipped; i++) {
                            result.data.emplace_back(0, 0);
                        }

                        empty_count = 0;
                    } else {
                        break;
                    }
                }
            } else {
                empty_count = 0;
            }

           /* for (int i = 0; i < 5; i++) {
                int x1 = boxes[i] - 1;
                int y1 = 3;
                int w = 23 + 1;
                int h = 32;

                trainer.seen_digit(velocity_str[i] - '0', velocity_mat(cv::Rect(x1, y1, w, h)));

                if (trainer.is_ready()) {
                    cv::imwrite("training1.tif", trainer.generate_training_image());
                    throw std::runtime_error("finish");
                    //imshow("JCSAT-14", trainer.generate_training_image());
                    //cv::waitKey();
                }
            }*/

            int ocr_velocity = atoi(velocity_str);
            //if (ocr_velocity >= 9177) {
            //    cout << "Break" << endl;
            //    do_show = true;
            //}

            configure_for_altitude();
            double ocr_altitude = recognize<double>(frame, altitude_rect, altitude_mat);

            printf("%.5f, v = %5d, d = %.2f\n", (x / (double)fps), ocr_velocity, ocr_altitude);

            if (ocr_velocity < prev_velocity && (ocr_velocity > 8135 || ocr_velocity < 8210)) {
               // display(velocity_mat, display_rect, altitude_mat, altitude_display_rect);
            }

            if (do_show) {
                display(velocity_mat, display_rect, altitude_mat, altitude_display_rect);
            }

            //find_component_wise(velocity_mat);
            //display(velocity_mat, display_rect, altitude_mat, altitude_display_rect);

            result.data.emplace_back(ocr_velocity, ocr_altitude * 1000);

            prev_velocity = ocr_velocity;

            //if (ocr_velocity >=27106) { // crs8
            //if (ocr_velocity >= 26980) { // ses9
            //if (ocr_velocity >= 26720) { // jcsat14
            //    break;
            //}
        }
    }

public:

    SpaceXOCR(const std::string& file)
        : tess(), cap(file), velocity_rect(1041, 142, 72, 20), altitude_rect(1178, 140, 72, 20),
          velocity_mat(velocity_rect.size() * 2, CV_BGR2GRAY), altitude_mat(altitude_rect.size() * 2, CV_BGR2GRAY),
          trainer(24, 32, 10)
    {
        if (!cap.isOpened()) {
            throw std::runtime_error("Cannot open file: " + file);
        }

        fps = cap.get(cv::CAP_PROP_FPS);
        frame_count = cap.get(cv::CAP_PROP_FRAME_COUNT);
        width = (int)cap.get(cv::CAP_PROP_FRAME_WIDTH);
        height = (int)cap.get(cv::CAP_PROP_FRAME_HEIGHT);

        cout << boost::format("Opened %1% (%2% fps, %3%x%4%)") % file % fps % width % height << endl;

        if (width != 1280 || height != 720) {
            throw std::runtime_error("720p video expected");
        }

        //if (tess.Init("C:\\Program Files (x86)\\Tesseract-OCR", "spacex")) {
        if (tess.Init("D:\\dev\\spacex-ocr\\spacex-telemetry\\spacex-telemetry", "spacex")) {
            throw std::runtime_error("Couldn't initialize tesseract");
        }
    }

    Telemetry process() {
        Telemetry result(fps, frame_count);

        //cap.set(cv::CAP_PROP_POS_MSEC, 603 * 1000 + 2000);// +221000);
        //cap.set(cv::CAP_PROP_POS_MSEC, 1786 * 1000);
        cv::namedWindow("JCSAT-14", cv::WINDOW_AUTOSIZE);
        cv::setMouseCallback("JCSAT-14", onMouse, &frame);

        cout << "Searching for liftoff.." << endl;

        std::array<int, 2> start_seq{ 0, 1 };
        if (!skip_to_telemetry_start(start_seq.begin(), start_seq.end())) {
            throw std::runtime_error("Couldn't locate start of telemetry");
        }

        begin_processing_telemetry(result);
        return std::move(result);
        cout << "Found approximate liftoff time.. Searching for T-0..." << endl;

        if (tess.Init("D:\\dev\\spacex-ocr\\spacex-telemetry\\spacex-telemetry", "spacex")) {
            throw std::runtime_error("Couldn't initialize tesseract for digits");
        }

        // Get our first reading..
        configure_for_velocity();
        int prev_velocity = 0;

        for (int x = 0; x < fps * 20; x++) {
            cap >> frame;

            if (frame.empty()) {
                break;
            }

            char velocity_str[6];
            if (!get_velocity(velocity_rect, velocity_mat, velocity_str))// recognize<int>(frame, velocity_rect, velocity_mat);
                continue;
            int ocr_velocity = atoi(velocity_str);
            cout << ocr_velocity << endl;

            if (prev_velocity == 0 && ocr_velocity == 1) {
                double liftoff = cap.get(cv::CAP_PROP_POS_MSEC) / 1000;
                printf("Liftoff at %.2f seconds into video\n", liftoff);

                imshow("JCSAT-14", frame);
                cv::waitKey();

                begin_processing_telemetry(result);
                return std::move(result);
            }

            prev_velocity = ocr_velocity;
        }

        throw std::runtime_error("Couldn't find precise liftoff frame");
    }

};

int main(int argc, char* argv[])
{
    try {
        //SpaceXOCR ocr("D:\\dev\\spacex-ocr\\ses9.mp4");
        //SpaceXOCR ocr("D:\\dev\\spacex-ocr\\crs8.mp4");
        SpaceXOCR ocr("E:\\jcsat14.mp4");
        Telemetry telemetry = ocr.process();

        std::ofstream myfile;
        myfile.open("velocity.csv");
        telemetry.write_data(myfile);
    } catch (std::exception& e) {
        cerr << "Failed: " << e.what() << endl;
    }

     return 0;
}

ext: cpp

max_stars_repo_name: camnbear/spacex-ocr

max_issues_repo_name: camnbear/spacex-ocr

max_forks_repo_name: camnbear/spacex-ocr


text:
/*
 * return the category of the RigidBodyConstraint. Can be SingleTimeKinematicConstraint, MultipleTimeKinematicConstraint, QuasiStaticConstraint, PostureConstraint, SingleTimeLinearPostureConstraint and MultipleTimeLinearPostureConstraint
 */

#include "mex.h"
#include <iostream>
#include "drakeUtil.h"
#include <Eigen/Dense>
#include "RigidBodyConstraint.h"
#include "RigidBodyManipulator.h"
#include <cstdio>

using namespace Eigen;
using namespace std;

void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])
{
  if(nrhs!= 1)
  {
    mexErrMsgIdAndTxt("Drake:constraintCategorymex:BadInputs","Usage constraint_category = constraintCategorymex(constraint_ptr)");
  }
  RigidBodyConstraint* cnst = (RigidBodyConstraint*) getDrakeMexPointer(prhs[0]);
  int category = cnst->getCategory();
  switch(category)
  {
    case RigidBodyConstraint::SingleTimeKinematicConstraintCategory:
      plhs[0] = mxCreateString("SingleTimeKinematicConstraint");
      break;
    case RigidBodyConstraint::MultipleTimeKinematicConstraintCategory:
      plhs[0] = mxCreateString("MultipleTimeKinematicConstraint");
      break;
    case RigidBodyConstraint::QuasiStaticConstraintCategory:
      plhs[0] = mxCreateString("QuasiStaticConstraint");
      break;
    case RigidBodyConstraint::PostureConstraintCategory:
      plhs[0] = mxCreateString("PostureConstraint");
      break;
    case RigidBodyConstraint::MultipleTimeLinearPostureConstraintCategory:
      plhs[0] = mxCreateString("MultipleTimeLinearPostureConstraint");
      break;
    case RigidBodyConstraint::SingleTimeLinearPostureConstraintCategory:
      plhs[0] = mxCreateString("SingleTimeLinearPostureConstraint");
      break;
    default:
      mexErrMsgIdAndTxt("Drake:constraintCategorymex:BadInputs","The constraint category is not supported");
      break;
  }
}

max_stars_repo_name: jacob-izr/drake

max_issues_repo_name: jacob-izr/drake

max_forks_repo_name: jacob-izr/drake


text:
// vim:ts=2:sw=2:expandtab:autoindent:filetype=cpp:
/*
The MIT License

Copyright (c) 2008, 2009 Flusspferd contributors (see "CONTRIBUTORS" or
                                       http://flusspferd.org/contributors.txt)

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/

#include <flusspferd/io/stream.hpp>
#include <flusspferd/binary.hpp>

#include <boost/format.hpp>
#include <fstream>
#include <sstream>

#include "parser.hpp"
#include "document.hpp"
#include "dom_implementation.hpp"

#include <SAX/helpers/CatchErrorHandler.hpp>
#include <DOM/io/Stream.hpp>
#include <Taggle/Taggle.hpp>

using boost::format;

using namespace flusspferd;
using namespace xml_plugin;

namespace xml_plugin {
  void load_parsers(object &exports) {
    load_class<xml_parser>(exports);
    load_class<html_parser>(exports);
  }
}

base_parser::base_parser(flusspferd::object const &proto)
  : base_type(proto)
{ }

object base_parser::parse(value source) {
  if (source.is_object()) {
    object o = source.get_object();

    if (is_native<io::stream>(o)) {
      io::stream &s = flusspferd::get_native<io::stream>(o);

      // TODO: Work out if the stream is readable or not!
      std::ifstream stream;
      dynamic_cast<std::ios&>(stream).rdbuf( s.streambuf() );
      sax_source is;
      is.setByteStream(stream);
      return parse_source(is);
    }
    /*else if (is_native<binary>(o)) {
      // Couldn't get this working. Compile errors
      binary &b = flusspferd::get_native<flusspferd::binary>(o);

      call_context c;
      c.arg.push_back(b);
      create<io::binary_stream>(c);
      root_object s(b_s);

      std::ifstream stream;
      dynamic_cast<std::ios&>(stream).rdbuf( b_s.streambuf() );
      sax_source is;
      is.setByteStream(stream);
      return parse_source(is);
    }*/
  }

  std::string str = source.to_std_string();

  security &sec = security::get();
  if (!sec.check_path(str, security::READ)) {
    throw exception(
      format("xml.Parser#parse: could not open file: 'denied by security' (%s)")
             % str
    );
  }

  sax_source is;
  is.setSystemId(str);

  return parse_source(is);
}

object base_parser::parse_string(std::string &str) {

  std::istringstream sb(str);
  sax_source is;
  is.setByteStream(sb);
  return parse_source(is);
}

#include <DOM/io/Stream.hpp>

object base_parser::parse_source(sax_source &is) {

  arabica_document const& doc = _parse(is);

  node_map_ptr map = dom_implementation::get_node_map().lock();
  if (!map)
    throw exception("Internal error: node_map has gone away");
  return map->get_node(doc);
}

xml_parser::xml_parser(flusspferd::object const &proto, flusspferd::call_context &)
  : base_type(proto)
{ }

xml_parser::xml_parser(flusspferd::object const &proto)
  : base_type(proto)
{ }

object xml_parser::static_parse(value source) {
  // Helper method. Create a parser and call the `parse` method
  return create<xml_parser>().parse(source);
}

object xml_parser::static_parse_string(std::string &source) {
  // Helper method. Create a parser and call the `parse` method
  return create<xml_parser>().parse_string(source);
}

arabica_document xml_parser::_parse(sax_source &is) {
  Arabica::SAX2DOM::Parser<string_type> parser;
  Arabica::SAX::CatchErrorHandler<string_type> eh;
  parser.setErrorHandler(eh);

  parser.parse(is);

  if (eh.errorsReported()) {
      throw exception( eh.errors() );
  }

  return parser.getDocument();
}

html_parser::html_parser(flusspferd::object const &proto, flusspferd::call_context &)
  : base_type(proto)
{ }

html_parser::html_parser(flusspferd::object const &proto)
  : base_type(proto)
{ }

object html_parser::static_parse(value source) {
  // Helper method. Create a parser and call the `parse` method
  return create<html_parser>().parse(source);
}

object html_parser::static_parse_string(std::string &source) {
  // Helper method. Create a parser and call the `parse` method
  return create<html_parser>().parse_string(source);
}

arabica_document html_parser::_parse(sax_source &is) {
  typedef Arabica::SAX::Taggle<string_type> Taggle;
  Arabica::SAX2DOM::Parser<string_type, Taggle> parser;
  Arabica::SAX::CatchErrorHandler<string_type> eh;
  parser.setErrorHandler(eh);

  // Dont explicitly set default attributes.
  // Without this:
  //   bar
  // gets turned into
  //   bar
  parser.setFeature(Taggle::defaultAttributesFeature, false);

  // This one disabled the xmlns attr on the html element
  parser.setFeature(Taggle::useSchemaNSFeature, false);

  // This one lets 'inline' contain blocks:
foo

  parser.setFeature(Taggle::flexibleElementHierarchyFeautre, true);

  parser.parse(is);

  if (eh.errorsReported()) {
      throw exception( eh.errors() );
  }

  return parser.getDocument();
}

max_stars_repo_name: Flusspferd/flusspferd

max_issues_repo_name: Flusspferd/flusspferd

max_forks_repo_name: Flusspferd/flusspferd


text:
//          Copyright Dean Michael Berris 2008.
// 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_NETWORK_PROTOCOL_HTTP_MESSAGE_TRAITS_DELIMITERS_IPP
#define BOOST_NETWORK_PROTOCOL_HTTP_MESSAGE_TRAITS_DELIMITERS_IPP

#include <boost/network/protocol/http/tags.hpp>

namespace boost { namespace network { namespace http {

    // specialize on the tags::http_default_8bit_tcp_resolve type
    template <>
        struct delimiters<tags::http_default_8bit_tcp_resolve> {
            static char const * string_crlf() {
                static char const * const CRLF = "\x0D\x0A";
                return CRLF;
            };

            static char const * string_http_version() {
                static char const * const HTTP_VERSION = "HTTP/1.1";
                return HTTP_VERSION;
            };

            static char const * header_name_value_delimiter() {
                static char const * const HEADER_NAME_VALUE_DELIMITER = ": ";
                return HEADER_NAME_VALUE_DELIMITER;
            };
        };

} // namespace http

} // namespace network

} // namespace boost

#endif // BOOST_NETWORK_PROTOCOL_HTTP_MESSAGE_TRAITS_DELIMITERS_IPP

ext: ipp

max_stars_repo_name: antoinelefloch/cpp-netlib

max_issues_repo_name: waTeim/boost

max_forks_repo_name: waTeim/boost


text:
/**
   \file aga.hpp
   \brief asexual genetic algorithm method
   \author Junhua Gu
*/

#ifndef AGA_METHOD
#define AGA_METHOD
#define OPT_HEADER
#include <core/optimizer.hpp>
//#include <blitz/array.h>
#include <limits>
#include <cstdlib>
#include <core/opt_traits.hpp>
#include <cassert>
#include <cmath>
#include <ctime>
#include <vector>
#include <algorithm>
/*
 *
*/
#include <iostream>
using std::cout;
using std::endl;

namespace opt_utilities
{

  template <typename rT,typename pT>
  struct vp_pair
  {
    rT v;
    pT p;
  };

  template <typename rT,typename pT>
  class vp_comp
  {
  public:
    bool operator()(const vp_pair<rT,pT>& x1,
		    const vp_pair<rT,pT>& x2)
    {
      return x1.v<x2.v;
    }
  };

  /**
     \brief Implement of the asexual genetic algorithm
     2009A&A...501.1259C
     http://adsabs.harvard.edu/abs/2009arXiv0905.3712C
     \tparam rT return type of the object function
     \tparam pT parameter type of the object function
   */
  template <typename rT,typename pT>
  class aga_method
    :public opt_method<rT,pT>
  {
  public:
    typedef pT array1d_type;
  private:
    int n1,n2,n0;
    func_obj<rT,pT>* p_fo;
    optimizer<rT,pT>* p_optimizer;
    rT threshold;
    pT lower_bound;
    pT upper_bound;

    typename element_type_trait<pT>::element_type decay_factor;
    pT reproduction_box;
    std::vector<vp_pair<rT,pT> > samples;
    std::vector<pT> buffer;
    mutable bool bstop;
  private:
    typename element_type_trait<pT>::element_type uni_rand
    (typename element_type_trait<pT>::element_type x1,
     typename element_type_trait<pT>::element_type x2)
    {
      return rand()/(double)RAND_MAX*(x2-x1)+x1;
    }

  private:
    const char* do_get_type_name()const
    {
      return "asexual genetic algorithm";
    }

    rT func(const pT& x)
    {
      assert(p_fo!=0);
      return p_fo->eval(x);
    }

  public:
    aga_method(int _n1,int _n2)
      :n1(_n1),n2(_n2),n0(n1*n2+n1),
       p_fo(0),p_optimizer(0),threshold(1e-4),
       decay_factor(.999),
       samples(n1*n2+n1)
    {
    }

    aga_method()
      :n1(50),n2(20),n0(n1*n2+n1),
       p_fo(0),p_optimizer(0),threshold(1e-4),
       decay_factor(.999),
       samples(n1*n2+n1)
    {
    }

    virtual ~aga_method()
    {
    };

    aga_method(const aga_method<rT,pT>& rhs)
      :n1(rhs.n1),n2(rhs.n2),n0(rhs.n0),
       p_fo(rhs.p_fo),p_optimizer(rhs.p_optimizer),
       threshold(rhs.threshold),
       decay_factor(rhs.decay_factor),
       samples(rhs.samples)
    {
    }

    aga_method<rT,pT>& operator=(const aga_method<rT,pT>& rhs)
    {
      threshold=rhs.threshold;
      p_fo=rhs.p_fo;
      p_optimizer=rhs.p_optimizer;
      samples=rhs.samples;
      n1=rhs.n1;
      n2=rhs.n2;
      n0=rhs.n0;
    }

    void set_decay_factor(typename element_type_trait<pT>::element_type _decay_factor)
    {
      decay_factor=_decay_factor;
    }

    opt_method<rT,pT>* do_clone()const
    {
      return new aga_method<rT,pT>(*this);
    }

    void do_set_start_point(const array1d_type& p)
    {
      for(size_t i=0;i<samples.size();++i)
	{
	  //  cout<<i<<" ";
	  resize(samples[i].p,get_size(p));
	  //	  std::cout<<samples[i].p.size()<<std::endl;;
	  for(size_t j=0;j<get_size(p);++j)
	    {
	      set_element(samples[i].p,j,
			  uni_rand(get_element(lower_bound,j),
				   get_element(upper_bound,j))
			  );
	    }
	}

    }

    array1d_type do_get_start_point()const
    {
      return array1d_type();
    }

    void do_set_lower_limit(const array1d_type& p)
    {
      opt_eq(lower_bound,p);
    }

    array1d_type do_get_lower_limit()const
    {
      return lower_bound;
    }

    void do_set_upper_limit(const array1d_type& p)
    {
      opt_eq(upper_bound,p);
    }

    array1d_type do_get_upper_limit()const
    {
      return upper_bound;
    }

    void do_set_precision(rT t)
    {
      threshold=t;
    }

    rT do_get_precision()const
    {
      return threshold;
    }

    void do_set_optimizer(optimizer<rT,pT>& o)
    {
      p_optimizer=&o;
      p_fo=p_optimizer->ptr_func_obj();
    }

    bool iter()
    {
      rT sum2=0;
      rT sum=0;
      for(size_t i=0;i<samples.size();++i)
	{
	  samples[i].v=func(samples[i].p);
	  sum2+=samples[i].v*samples[i].v;
	  sum+=samples[i].v;
	}

      std::sort(samples.begin(),samples.end(),vp_comp<rT,pT>());
      if(sum2/samples.size()-pow(sum/samples.size(),2)<threshold)
	{
	  return false;
	}
      pT lb(get_size(samples[0].p));
      pT ub(get_size(samples[0].p));
      for(int i=0;i<n2&&!bstop;++i)
	{
	  pT p(samples[i].p);
	  for(size_t j=0;j<get_size(p);++j)
	    {
	      if(i==0)
		{
		  ub[j]=p[j];
		  lb[j]=p[j];
		}
	      ub[j]=std::max(ub[j],p[j]);
	      lb[j]=std::min(lb[j],p[j]);

	      set_element(p,j,
			  get_element(p,j)+
			  uni_rand(-get_element(reproduction_box,j),
				   get_element(reproduction_box,j)));
	      if(get_element(p,j)>get_element(upper_bound,j))
		{
		  set_element(p,j,get_element(upper_bound,j));
		}
	      if(get_element(p,j)<get_element(lower_bound,j))
		{
		  set_element(p,j,get_element(lower_bound,j));
		}
	    }
	  buffer[i]=p;
	}
      if(bstop)
	{
	  return false;
	}
      for(int i=0;i<n1&&!bstop;++i)
	{
	  for(int j=0;j<n2&&!bstop;++j)
	    {
	      pT p(samples[i].p);
	      for(size_t k=0;k<get_size(p);++k)
		{
		  set_element(samples[i*n2+j+n1].p,k,
			      (get_element(samples[i].p,k)+
			       get_element(buffer[j],k))/2.);

		  ub[k]=std::max(ub[k],samples[i*n2+j+n1].p[k]);
		  lb[k]=std::min(lb[k],samples[i*n2+j+n1].p[k]);
		}
	    }
	}
      if(bstop)
	{
	  return false;
	}
      double n_per_dim=pow((double)n0,1./get_size(lower_bound));
      for(size_t i=0;i<get_size(reproduction_box);++i)
	{
	  //	  set_element(reproduction_box,i,
	  //get_element(reproduction_box,i)*decay_factor);
	  set_element(reproduction_box,i,
		      (get_element(ub,i)-
		       get_element(ub,i))/n_per_dim);

	}
      return true;
    }

    pT do_optimize()
    {
      bstop=false;
      srand(time(0));
      buffer.resize(n2);
      double n_per_dim=pow((double)n0,1./get_size(lower_bound));
      resize(reproduction_box,get_size(lower_bound));

      for(size_t i=0;i<get_size(lower_bound);++i)
	{

	  set_element(reproduction_box,i,
		      (get_element(upper_bound,i)-
		       get_element(lower_bound,i))/n_per_dim);
	}

      while(iter()&&!bstop){}

      return samples.begin()->p;
    }

    void do_stop()
    {
      bstop=true;
    }

  };

}

#endif
//EOF


text:
/*
 * main.cpp
 *
 *  Created on: 2011-12-4
 *      Author: fasiondog
 */

#include <cstdint>
#include <boost/python.hpp>
#include <hikyuu/hikyuu.h>
#include <hikyuu/realtime/receive.h>

namespace py = boost::python;
using namespace hku;

void export_DataType();
void export_Constant();
void export_util();
void export_log();
void export_Datetime();
void export_TimeDelta();
void export_StockManager();
void export_Stock();
void export_Block();
void export_MarketInfo();
void export_StockTypeInfo();
void export_StockWeight();
void export_KQuery();
void export_KReord();
void export_TimeLineReord();
void export_TransRecord();
void export_KData();
void export_Parameter();
void export_save_load();
void export_io_redirect();

void export_data_driver_main();
void export_indicator_main();
void export_instance_main();
void export_trade_manage_main();
void export_trade_sys_main();

KData Py_GetKData(const string& market_code, py::object start = py::long_(0),
                  py::object end = py::long_(Null<int64_t>()), KQuery::KType ktype = KQuery::DAY,
                  KQuery::RecoverType recovertType = KQuery::NO_RECOVER) {
    py::extract<KQuery> query_x(start);
    if (query_x.check()) {
        return getKData(market_code, query_x());
    }

    py::extract<int64_t> int_x(start);
    if (int_x.check()) {
        int64_t start_ix = 0, end_ix = 0;
        if (end.is_none()) {
            end_ix = Null<int64_t>();
        } else {
            py::extract<int64_t> int_y(end);
            if (!int_y.check()) {
                HKU_THROW_EXCEPTION(
                  std::invalid_argument,
                  "The input parameters start and end must be of the same type (Datetime or int)!");
            }
            end_ix = int_y();
        }
        start_ix = int_x();
        return getKData(market_code, start_ix, end_ix, ktype, recovertType);
    }

    py::extract<Datetime> date_x(start);
    if (!date_x.check()) {
        HKU_THROW_EXCEPTION(std::invalid_argument,
                            "The type of input parameter start must be Datetime or int!");
    }

    Datetime start_date, end_date;
    if (end.is_none()) {
        end_date = Null<Datetime>();
    } else {
        py::extract<Datetime> date_y(end);
        if (!date_y.check()) {
            HKU_THROW_EXCEPTION(
              std::invalid_argument,
              "The input parameters start and end must be of the same type (Datetime or int)!");
        }
        end_date = date_y();
    }

    start_date = date_x();
    return getKData(market_code, start_date, end_date, ktype, recovertType);
}

BOOST_PYTHON_MODULE(core) {
    py::docstring_options doc_options;
    doc_options.disable_signatures();

    export_DataType();
    export_Constant();
    export_util();
    export_log();
    export_Datetime();
    export_TimeDelta();
    export_MarketInfo();
    export_StockTypeInfo();
    export_StockWeight();
    export_StockManager();
    export_KQuery();
    export_KReord();
    export_TimeLineReord();
    export_TransRecord();
    export_KData();
    export_Stock();
    export_Block();
    export_Parameter();
    export_save_load();

    export_data_driver_main();
    export_indicator_main();
    export_instance_main();

    export_trade_sys_main();
    export_trade_manage_main();  // must after export_trade_sys_main

    export_io_redirect();

    py::def("hikyuu_init", hikyuu_init, (py::arg("filename"), py::arg("ignore_preload") = false));
    py::def("get_version", getVersion, R"(getVersion()

    :return: hikyuu 当前版本
    :rtype: str)");

    py::def("get_stock", getStock,
            R"(get_stock(market_code)

    根据"市场简称证券代码"获取对应的证券实例

    :param str market_code: 格式：“市场简称证券代码”，如"sh000001"
    :return: 对应的证券实例，如果实例不存在，则返回空实例，即Stock()，不抛出异常
    :rtype: Stock)");

    py::def(
      "get_kdata", Py_GetKData,
      (py::arg("market_code"), py::arg("start") = py::long_(0), py::arg("end") = py::object(),
       py::arg("ktype") = KQuery::DAY, py::arg("recover_type") = KQuery::NO_RECOVER),
      R"(get_kdata(market_code[, start=0, end=None, ktype=Query.DAY, recover_type=Query.NO_RECOVER])

    or get_kdata(market_code, query)

    获取K线数据，其中 start 和 end 需同时为 int 或 同时为 Datetime。

    :param str market_code: 格式：“市场简称证券代码”，如"sh000001"
    :param int or Datetime start: 起始索引或起始日期
    :param int or Datetime end: 终止索引或终止日期
    :param Query query: 查询条件
    :return: 满足查询条件的K线数据
    :rtype: KData)");

    py::def("start_receive", start_receive);
}

max_stars_repo_name: scanfyu/hikyuu

max_issues_repo_name: scanfyu/hikyuu

max_forks_repo_name: scanfyu/hikyuu


text:
// Author(s): Wieger Wesselink
// Copyright: see the accompanying file COPYING or copy at
// https://github.com/mCRL2org/mCRL2/blob/master/COPYING
//
// 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)
//
/// \file constelm_test.cpp
/// \brief Add your file description here.

#define BOOST_TEST_MODULE constelm_test
#include <boost/test/included/unit_test_framework.hpp>
#include "mcrl2/pbes/constelm.h"
#include "mcrl2/pbes/detail/pbes_property_map.h"
#include "mcrl2/pbes/remove_equations.h"
#include "mcrl2/pbes/rewriter.h"
#include "mcrl2/pbes/txt2pbes.h"

using namespace mcrl2;
using namespace mcrl2::pbes_system;

std::string t1 =
  "% simple test, n is constant \n"
  "                             \n"
  "pbes nu X(n: Nat) =          \n"
  "       X(n);                 \n"
  "                             \n"
  "init X(0);                   \n"
  ;
std::string x1 = "binding_variables = X";

std::string t2 =
  "% simple test, n is NOT constant \n"
  "                                 \n"
  "pbes nu X(n: Nat) =              \n"
  "       X(n + 1);                 \n"
  "                                 \n"
  "init X(0);                       \n"
  ;
std::string x2 = "binding_variables = X(n: Nat)";

std::string t3 =
  "% multiple parameters: n1 is constant, n2 is not \n"
  "                                                 \n"
  "pbes nu X(n1,n2: Nat) =                          \n"
  "       X(n1, n2 + 1);                            \n"
  "                                                 \n"
  "init X(0, 1);                                    \n"
  ;
std::string x3 = "binding_variables = X(n2: Nat)";

std::string t4 =
  "% conditions: n is not constant, even if conditions are enabled\n"
  "                                                               \n"
  "pbes nu X(n: Nat) =                                            \n"
  "       val(2 < n) || X(n + 1);                                 \n"
  "                                                               \n"
  "init X(0);                                                     \n"
  ;
std::string x4 = "binding_variables = X(n: Nat)";

std::string t5 =
  "% conditions: n is constant if conditions are enabled \n"
  "                                                      \n"
  "pbes nu X(n: Nat) =                                   \n"
  "       val(2 < n) || X(n + 1);                        \n"
  "                                                      \n"
  "init X(5);                                            \n"
  ;
std::string x5 = "binding_variables = X";

std::string t6 =
  "% reachability: n1 is not constant, equation Y is not reachable and should be removed \n"
  "                                                                                \n"
  "pbes nu X(n1: Nat) = X(n1+1);                                                         \n"
  "     mu Y(n2: Nat) = Y(n2+1);                                                         \n"
  "                                                                                \n"
  "init X(5);                                                                            \n"
  ;
std::string x6 = "binding_variables = X(n1: Nat)";

std::string t7 =
  "% multiple edges from one vertex, one edge invalidates the assertion of the other: no constants should be found \n"
  "                                                                                \n"
  "pbes                                                                                \n"
  "   mu X1(n1,m1:Nat) = X2(n1) || X2(m1);                                                                         \n"
  "   mu X2(n2:Nat)     = X1(n2,n2);                                                                               \n"
  "init                                                                                \n"
  "   X1(2,1);                                                                                \n"
  ;
std::string x7 = "binding_variables = X1(n1,m1: Nat), X2(n2: Nat)";

std::string t8 =
  "% conditions: parameters b,c and d will always be removed, with conditions on, parameter \n"
  "% n will NOT be removed. changing b,c or d to false or n to a bigger number              \n"
  "% then 5 WILL result in the removal of n                                                 \n"
  "                                                                                \n"
  "pbes nu X(b,c,d:Bool, n:Nat) =                                                           \n"
  "    val(b) || ( val(c) && ( val(d) && (val(n > 5) || X(b,c,d,n+1))));                    \n"
  "                                                                                \n"
  "init                                                                                \n"
  "X(false,true,true,5);                                                                    \n"
  ;
std::string x8 = "binding_variables = X(n: Nat)";

std::string t9 =
  "% conditions: universal quantification which can be solved, n1 and n2 are \n"
  "% constants if conditions are enabled                                     \n"
  "                                                                          \n"
  "pbes mu X(n1,n2:Nat) =                                                    \n"
  "    forall m:Nat. (val(n1>n2) && X(n1+1,n2+1));                           \n"
  "                                                                          \n"
  "init X(1,2);                                                              \n"
  ;
std::string x9 = "binding_variables = X";

std::string t10 =
  "% conditions: existential quantification which can be solved, n1 and n2 \n"
  "% are constants if conditions are enabled                               \n"
  "                                                                        \n"
  "pbes mu X(n1,n2:Nat) =                                                  \n"
  "    exists m:Nat. (val(n1>n2) && X(n1+1,n2+1));                         \n"
  "                                                                        \n"
  "init X(1,2);                                                            \n"
  ;
std::string x10 = "binding_variables = X";

std::string t11 =
  "pbes mu X(n1,n2:Nat) =                                        \n"
  "    forall m:Nat. (val(m>n2) && X(n1+1,n2+1));                \n"
  "                                                              \n"
  "init X(1,2);                                                  \n"
  ;
std::string x11 = "binding_variables = X";

std::string t12 =
  "% example 4.2.1 from \"Tools for PBES\" report                                     \n"
  "% constants without conditions: o4, n2, n4, o4                                     \n"
  "% constants with conditions: everything (equations X1,X2,X3 and X4 are removed)    \n"
  "                                                                                \n"
  "pbes                                                                               \n"
  "   mu X1(n1,m1,o1,p1:Nat) = (val(n1<m1) || X2(o1,p1)) && X3(n1) && X1(n1,m1,4,p1); \n"
  "   mu X2(n2,m2:Nat)       = X5(n2,m2) || X5(m2,n2);                                \n"
  "   nu X3(n3:Nat)          = val(n3<3) || X1(n3,n3,4,n3+1);                         \n"
  "   nu X4(n4,m4,o4:Nat)    = val(n4 <= m4+o4) || (X3(n4) && X4(n4,m4+1,n4));        \n"
  "   mu X5(n5,m5:Nat)       = val(n5>m5) || X3(n5);                                  \n"
  "                                                                                \n"
  "init                                                                               \n"
  "   X4(0,0,0);                                                                      \n"
  ;
std::string x12 = "binding_variables = X1(n1,m1,p1: Nat), X2(m2: Nat), X3(n3: Nat), X4(m4: Nat), X5(n5,m5: Nat)";

std::string t13 =
  "pbes nu X =           \n"
  "        Y(true);      \n"
  "      mu Y(b: Bool) = \n"
  "        X;            \n"
  "                      \n"
  "init X;               \n"
  ;
std::string x13 = "binding_variables = X, Y";

std::string t14 =
  "pbes nu X(m:Nat) =           \n"
  "        forall n:Nat . X(n); \n"
  "                             \n"
  "init X(0);                   \n"
  ;
std::string x14 = "binding_variables = X(m: Nat)";

std::string t15 =
  "pbes                 \n"
  "nu X0(n:Nat) = X1;   \n"
  "mu X1 = X0(0) || X1; \n"
  "                     \n"
  "init X0(0);          \n"
  ;
std::string x15 = "binding_variables = X0, X1";

std::string t16 =
  "pbes                      \n"
  " nu X(n:Nat) = Y && X(n); \n"
  " mu Y = Z;                \n"
  " nu Z = Y;                \n"
  "                          \n"
  " init X(0);               \n"
  ;
std::string x16 = "binding_variables = X, Y, Z";

std::string t17 =
  "sort D = struct d1 | d2 | d3 | d4;\n"
  "pbes nu X1 =\n"
  "       X(2);\n"
  "     mu X(s3_X: Pos) =\n"
  "       val(s3_X == 4) || val(s3_X == 2) && X(3) || val(s3_X == 2) && X(4) || val(s3_X == 3) && X(1) || val(s3_X == 4) && X(1);\n"
  "init X1;\n";

std::string x17 = "binding_variables = X1, X(s3_X: Pos)";

std::string t18 =
  "% conditions: quantifications which cannot be solved, n1 and n2 are *not* \n"
  "% constants even if conditions are enabled.                               \n"
  "                                                                          \n"
  "pbes mu X(n1,n2:Nat) =                                                    \n"
  "    forall m1:Nat. exists m2:Nat. (val(m2 > n2 + m1) && X(n1+1,n2+1));    \n"
  "                                                                          \n"
  "init X(1,2);                                                              \n"
  ;

std::string x18 = "binding_variables = X(n1,n2: Nat)";

void test_pbes(const std::string& pbes_spec, const std::string& expected_result, bool compute_conditions, bool remove_equations = true)
{
  typedef simplify_data_rewriter<data::rewriter> my_pbes_rewriter;

  pbes p = txt2pbes(pbes_spec);
  pbes q = p;

  // data rewriter
  data::rewriter datar(q.data());

  // pbes rewriter
  my_pbes_rewriter pbesr(datar);

  // constelm algorithm
  pbes_constelm_algorithm<data::rewriter, my_pbes_rewriter> algorithm(datar, pbesr);

  // run the algorithm
  algorithm.run(q, compute_conditions);
  if (remove_equations)
  {
    remove_unreachable_variables(q);
  }
  BOOST_CHECK(q.is_well_typed());
  std::cout << "\n--- q ---\n" << pbes_system::pp(q) << std::endl;

  pbes_system::detail::pbes_property_map info1(q);
  pbes_system::detail::pbes_property_map info2(expected_result);
  std::string diff = info1.compare(info2);
  if (!diff.empty())
  {
    std::cerr << "\n------ FAILED TEST ------" << std::endl;
    std::cout << pbes_spec << std::endl;
    std::cerr << "--- expected result" << std::endl;
    std::cerr << expected_result << std::endl;
    std::cerr << "--- found result" << std::endl;
    std::cerr << info1.to_string() << std::endl;
    std::cerr << "--- differences" << std::endl;
    std::cerr << diff << std::endl;
  }
  BOOST_CHECK(diff.empty());

}

BOOST_AUTO_TEST_CASE(test_constelm)
{
  test_pbes(t1 , x1 , false);
  test_pbes(t2 , x2 , false);
  test_pbes(t3 , x3 , false);
  test_pbes(t4 , x4 , true);
  test_pbes(t5 , x5 , true);
  test_pbes(t6 , x6 , false);
  test_pbes(t7 , x7 , false);
  test_pbes(t8 , x8 , true);
  test_pbes(t9 , x9 , true);
  test_pbes(t10, x10, true);
  test_pbes(t11, x11, true);
  test_pbes(t12, x12, false);
  test_pbes(t13, x13, false);
  test_pbes(t14, x14, false);
  test_pbes(t15, x15, false);
  test_pbes(t16, x16, true);
  test_pbes(t17, x17, false);
  test_pbes(t18, x18, true);
}


text:
//
// Copyright (c) 2021 Richard Hodges (hodges.r@gmail.com)
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//
// Official repository: https://github.com/madmongo1/boost_connector
//

#ifndef BOOST_CONNECTOR_OPS_PRICE_GREATER_HPP
#define BOOST_CONNECTOR_OPS_PRICE_GREATER_HPP

#include <boost/connector/ops/get_price_value.hpp>

namespace boost::connector
{
/// @brief A general purpose function object to compare the price levels of two
/// objects of any compatible type
struct price_greater
{
    /// @brief Call operator
    /// @tparam L is the type of the left hand argument.
    /// @tparam R is the type of the right hand argument
    /// @param l is the left hand side of the comparison
    /// @param r is the right hand side of the comparison
    /// @note the following expressions must be well formed:
    /// @code {.cpp}
    /// price_value get_price_value(L const& l);
    /// price_value get_price_value(R const& r);
    /// @endcode

    template < class L, class R >
    bool
    operator()(L const &l, R const &r) const
    {
        return get_price_value(l) > get_price_value(r);
    }
};

}   // namespace boost::connector

#endif


text:
#pragma once
#include <Eigen/Core>

//! Makes a coordinate transform that maps
//!
//! e1 to a1
//! e2 to a2
//!
//! where {e1, e2} is the standard basis for R^2.
template<class Point>
Eigen::Matrix2d makeCoordinateTransform(const Point& a1, const Point& a2) {
    Eigen::Matrix2d coordinateTransform;

    coordinateTransform << a1(0), a2(0),
                           a1(1), a2(1);

    return coordinateTransform;
}


text:
//---------------------------------------------------------------------------//
// Copyright (c) 2013-2014 Kyle Lutz <kyle.r.lutz@gmail.com>
//
// Distributed under the Boost Software License, Version 1.0
// See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt
//
// See http://kylelutz.github.com/compute for more information.
//---------------------------------------------------------------------------//

#include <iostream>
#include <algorithm>

#include <GL/gl.h>

#include <vtkActor.h>
#include <vtkCamera.h>
#include <vtkgl.h>
#include <vtkInteractorStyleSwitch.h>
#include <vtkMapper.h>
#include <vtkObjectFactory.h>
#include <vtkOpenGLExtensionManager.h>
#include <vtkOpenGLRenderWindow.h>
#include <vtkProperty.h>
#include <vtkRenderer.h>
#include <vtkRenderWindow.h>
#include <vtkRenderWindowInteractor.h>
#include <vtkSmartPointer.h>

#include <boost/compute/system.hpp>
#include <boost/compute/algorithm/iota.hpp>
#include <boost/compute/interop/opengl.hpp>
#include <boost/compute/interop/vtk.hpp>
#include <boost/compute/utility/dim.hpp>
#include <boost/compute/utility/source.hpp>

namespace compute = boost::compute;

// tesselates a sphere with radius, phi_slices, and theta_slices. returns
// a shared opencl/opengl buffer containing the vertex data.
compute::opengl_buffer tesselate_sphere(float radius,
                                        size_t phi_slices,
                                        size_t theta_slices,
                                        compute::command_queue &queue)
{
    using compute::dim;

    const compute::context &context = queue.get_context();

    const size_t vertex_count = phi_slices * theta_slices;

    // create opengl buffer
    GLuint vbo;
    vtkgl::GenBuffersARB(1, &vbo);
    vtkgl::BindBufferARB(vtkgl::ARRAY_BUFFER, vbo);
    vtkgl::BufferDataARB(vtkgl::ARRAY_BUFFER,
                         sizeof(float) * 4 * vertex_count,
                         NULL,
                         vtkgl::STREAM_DRAW);
    vtkgl::BindBufferARB(vtkgl::ARRAY_BUFFER, 0);

    // create shared opengl/opencl buffer
    compute::opengl_buffer vertex_buffer(context, vbo);

    // tesselate_sphere kernel source
    const char source[] = BOOST_COMPUTE_STRINGIZE_SOURCE(
        __kernel void tesselate_sphere(float radius,
                                       uint phi_slices,
                                       uint theta_slices,
                                       __global float4 *vertex_buffer)
        {
            const uint phi_i = get_global_id(0);
            const uint theta_i = get_global_id(1);

            const float phi = phi_i * 2.f * M_PI_F / phi_slices;
            const float theta = theta_i * 2.f * M_PI_F / theta_slices;

            float4 v;
            v.x = radius * cos(theta) * cos(phi);
            v.y = radius * cos(theta) * sin(phi);
            v.z = radius * sin(theta);
            v.w = 1.f;

            vertex_buffer[phi_i*phi_slices+theta_i] = v;
        }
    );

    // build tesselate_sphere program
    compute::program program =
        compute::program::create_with_source(source, context);
    program.build();

    // setup tesselate_sphere kernel
    compute::kernel kernel(program, "tesselate_sphere");
    kernel.set_arg<compute::float_>(0, radius);
    kernel.set_arg<compute::uint_>(1, phi_slices);
    kernel.set_arg<compute::uint_>(2, theta_slices);
    kernel.set_arg(3, vertex_buffer);

    // acqurire buffer so that it is accessible to OpenCL
    compute::opengl_enqueue_acquire_buffer(vertex_buffer, queue);

    // execute tesselate_sphere kernel
    queue.enqueue_nd_range_kernel(
        kernel, dim(0, 0), dim(phi_slices, theta_slices), dim(1, 1)
    );

    // release buffer so that it is accessible to OpenGL
    compute::opengl_enqueue_release_buffer(vertex_buffer, queue);

    return vertex_buffer;
}

// simple vtkMapper subclass to render the tesselated sphere on the gpu.
class gpu_sphere_mapper : public vtkMapper
{
public:
    vtkTypeMacro(gpu_sphere_mapper, vtkMapper)

    static gpu_sphere_mapper* New()
    {
        return new gpu_sphere_mapper;
    }

    void Render(vtkRenderer *renderer, vtkActor *actor)
    {
        if(!m_initialized){
            Initialize(renderer, actor);
            m_initialized = true;
        }

        if(!m_tesselated){
            m_vertex_count = m_phi_slices * m_theta_slices;

            // tesselate sphere
            m_vertex_buffer = tesselate_sphere(
                m_radius, m_phi_slices, m_theta_slices, m_command_queue
            );

            // ensure tesselation is finished (seems to be required on AMD)
            m_command_queue.finish();

            // set tesselated flag to true
            m_tesselated = true;
        }

        // draw sphere
        glEnableClientState(GL_VERTEX_ARRAY);
        vtkgl::BindBufferARB(vtkgl::ARRAY_BUFFER, m_vertex_buffer.get_opengl_object());
        glVertexPointer(4, GL_FLOAT, sizeof(float)*4, 0);
        glDrawArrays(GL_POINTS, 0, m_vertex_count);
    }

    void Initialize(vtkRenderer *renderer, vtkActor *actor)
    {
        // initialize opengl extensions
        vtkOpenGLExtensionManager *extensions =
            static_cast<vtkOpenGLRenderWindow *>(renderer->GetRenderWindow())
                ->GetExtensionManager();
        extensions->LoadExtension("GL_ARB_vertex_buffer_object");

        // initialize opencl/opengl shared context
        m_context = compute::opengl_create_shared_context();
        compute::device device = m_context.get_device();
        std::cout << "device: " << device.name() << std::endl;

        // create command queue for the gpu device
        m_command_queue = compute::command_queue(m_context, device);
    }

    double* GetBounds()
    {
        static double bounds[6];
        bounds[0] = -m_radius; bounds[1] = m_radius;
        bounds[2] = -m_radius; bounds[3] = m_radius;
        bounds[4] = -m_radius; bounds[5] = m_radius;
        return bounds;
    }

protected:
    gpu_sphere_mapper()
    {
        m_radius = 5.0f;
        m_phi_slices = 100;
        m_theta_slices = 100;
        m_initialized = false;
        m_tesselated = false;
    }

private:
    float m_radius;
    int m_phi_slices;
    int m_theta_slices;
    int m_vertex_count;
    bool m_initialized;
    bool m_tesselated;
    compute::context m_context;
    compute::command_queue m_command_queue;
    compute::opengl_buffer m_vertex_buffer;
};

int main(int argc, char *argv[])
{
    // create gpu sphere mapper
    vtkSmartPointer<gpu_sphere_mapper> mapper =
        vtkSmartPointer<gpu_sphere_mapper>::New();

    // create actor for gpu sphere mapper
    vtkSmartPointer<vtkActor> actor =
        vtkSmartPointer<vtkActor>::New();
    actor->GetProperty()->LightingOff();
    actor->GetProperty()->SetInterpolationToFlat();
    actor->SetMapper(mapper);

    // create render window
    vtkSmartPointer<vtkRenderer> renderer =
        vtkSmartPointer<vtkRenderer>::New();
    renderer->SetBackground(.1, .2, .31);
    vtkSmartPointer<vtkRenderWindow> renderWindow =
        vtkSmartPointer<vtkRenderWindow>::New();
    renderWindow->SetSize(800, 600);
    renderWindow->AddRenderer(renderer);
    vtkSmartPointer<vtkRenderWindowInteractor> renderWindowInteractor =
        vtkSmartPointer<vtkRenderWindowInteractor>::New();
    vtkInteractorStyleSwitch *interactorStyle =
        vtkInteractorStyleSwitch::SafeDownCast(
            renderWindowInteractor->GetInteractorStyle()
        );
    interactorStyle->SetCurrentStyleToTrackballCamera();
    renderWindowInteractor->SetRenderWindow(renderWindow);
    renderer->AddActor(actor);

    // render
    renderer->ResetCamera();
    vtkCamera *camera = renderer->GetActiveCamera();
    camera->Elevation(-90.0);
    renderWindowInteractor->Initialize();
    renderWindow->Render();
    renderWindowInteractor->Start();

    return 0;
}

max_stars_repo_name: bastiankoe/compute

max_issues_repo_name: bastiankoe/compute

max_forks_repo_name: bastiankoe/compute


text:
/* Copyright (C) 2010 Ion Torrent Systems, Inc. All Rights Reserved */
#include <gtest/gtest.h>
#include <armadillo>
#include <stdexcept>
#include <time.h>
#include <sys/time.h>
#include "ZeromerDiff.h"
#include "KeyClassifier.h"
#include "Utils.h"

using namespace std;

TEST(KeyClassifier_Test, ProjectionTest) {
  Col<double> well;
  well << 1 << 1;
  Col<double> incorporation;
  incorporation << 1 << 0;
  double p = KeyClassifier::GetProjection(incorporation, well);
  ASSERT_NEAR(p, 1, .0001);// 1.110721
  well <<  0.2193781 <<  1.9257150 <<  -0.0256586 <<  0.3911019;
  incorporation <<   0.7616795 <<  -0.8993396 << -0.1143299 << -1.3601566;
  p = KeyClassifier::GetProjection(well, incorporation);
  ASSERT_NEAR(-2.0938, p , .0001);

}

TEST(KeyClassifier_Test, Classify_Test) {
  //                                    0 1 2 3 4 5 6 7
  //                                    T A C G T A C G
    vector<int> libKey = char2Vec<int>("1 0 1 0 0 1 0", ' ');
    vector<int> tfKey = char2Vec<int> ("0 1 0 0 1 0 1", ' ');
    vector<KeySeq> keys;
    KeySeq lKey, tKey;
    lKey.name = "lib";
    lKey.flows = libKey;
    lKey.zeroFlows.set_size(4);
    lKey.zeroFlows << 1 << 3 << 4 << 6 ;
    keys.push_back(lKey);
    tKey.name = "tf";
    tKey.flows = tfKey;
    tKey.zeroFlows.set_size(4);
    tKey.zeroFlows << 0 << 2 << 3 << 5;
    keys.push_back(tKey);

    ZeromerDiff<double> bg;
    Mat<double> wellFlows;
    wellFlows.load("traces.txt",raw_ascii);
    wellFlows = trans(wellFlows);
    Mat<double> refFlows;
    refFlows.load("reference.txt", raw_ascii);
    refFlows = trans(refFlows);
    Col<double> time(refFlows.n_rows);
    for (size_t i = 0; i < time.n_rows; i++) {
      time[i] = i;
    }
    KeyFit fit;
    Mat<double> predicted(wellFlows.n_rows, wellFlows.n_cols);
    vector<float> reference;
    vector<float> signal;
		//    KeyClassifier::PrintVec(wellFlows);
		//    KeyClassifier::PrintVec(refFlows);
    //KeyClassifier::Classify(keys, bg, wellFlows, refFlows, reference, signal, time, 4, fit, predicted);
    KeyClassifier kClass;
    kClass.Classify(keys, bg, wellFlows, refFlows, time, 4, fit, predicted);
    Mat<double> diff = wellFlows - predicted;
    // cout << "Diff is: " << endl;
    // diff.raw_print();
    uvec zeroFlows(2);
    zeroFlows(0) = 0;
    zeroFlows(1) = 1;
    //    cout << "Index is: " <<  fit.keyIndex << " is: " << fit.snr << endl;
    Col<double> param;
    Mat<double> subW = wellFlows.submat(0,3,49,4);
    Mat<double> subR = refFlows.submat(0,3,49,4);
    bg.FitZeromer(subW, subR,zeroFlows, time, param);
    Col<double> z;
    bg.PredictZeromer(refFlows.col(1), time, param, z);
    Col<double> d = wellFlows.col(1) - z;
		//    cout << "diff is: " << endl;
    //    d.raw_print();
    bg.PredictZeromer(refFlows.col(3), time, param, z);
    d = wellFlows.col(3) - z;
		//    cout << "diff is: " << endl;
    //    d.raw_print();
}

max_stars_repo_name: konradotto/TS

max_issues_repo_name: konradotto/TS

max_forks_repo_name: konradotto/TS