text:
#ifndef BOOST_TEXT_TRANSCODE_VIEW_HPP
#define BOOST_TEXT_TRANSCODE_VIEW_HPP

#include <boost/text/transcode_algorithm.hpp>
#include <boost/text/detail/unpack.hpp>

#include <boost/stl_interfaces/view_interface.hpp>

namespace boost { namespace text { inline namespace v1 {

    namespace detail {

        // UTF-8
        template<typename Iter, typename Sentinel>
        constexpr auto make_utf8_range_(utf8_tag, Iter f, Sentinel l) noexcept
        {
            return tagged_range<utf8_tag, Iter, Sentinel>{f, l};
        }
        template<typename Iter, typename Sentinel>
        constexpr auto make_utf8_range_(utf16_tag, Iter f_, Sentinel l) noexcept
        {
            auto f = make_utf_16_to_8_iterator(f_, f_, l);
            return tagged_range<utf8_tag, decltype(f), Sentinel>{f, l};
        }
        template<typename Iter>
        constexpr auto make_utf8_range_(utf16_tag, Iter f_, Iter l_) noexcept
        {
            auto f = make_utf_16_to_8_iterator(f_, f_, l_);
            auto l = make_utf_16_to_8_iterator(f_, l_, l_);
            return tagged_range<utf8_tag, decltype(f)>{f, l};
        }
        template<typename Iter, typename Sentinel>
        constexpr auto make_utf8_range_(utf32_tag, Iter f_, Sentinel l) noexcept
        {
            auto f = make_utf_32_to_8_iterator(f_, f_, l);
            return tagged_range<utf8_tag, decltype(f), Sentinel>{f, l};
        }
        template<typename Iter>
        constexpr auto make_utf8_range_(utf32_tag, Iter f_, Iter l_) noexcept
        {
            auto f = make_utf_32_to_8_iterator(f_, f_, l_);
            auto l = make_utf_32_to_8_iterator(f_, l_, l_);
            return tagged_range<utf8_tag, decltype(f)>{f, l};
        }

        // UTF-16
        template<typename Iter, typename Sentinel>
        constexpr auto make_utf16_range_(utf8_tag, Iter f_, Sentinel l) noexcept
        {
            auto f = make_utf_8_to_16_iterator(f_, f_, l);
            return tagged_range<utf16_tag, decltype(f), Sentinel>{f, l};
        }
        template<typename Iter>
        constexpr auto make_utf16_range_(utf8_tag, Iter f_, Iter l_) noexcept
        {
            auto f = make_utf_8_to_16_iterator(f_, f_, l_);
            auto l = make_utf_8_to_16_iterator(f_, l_, l_);
            return tagged_range<utf16_tag, decltype(f)>{f, l};
        }
        template<typename Iter, typename Sentinel>
        constexpr auto make_utf16_range_(utf16_tag, Iter f, Sentinel l) noexcept
        {
            return tagged_range<utf16_tag, Iter, Sentinel>{f, l};
        }
        template<typename Iter, typename Sentinel>
        constexpr auto
        make_utf16_range_(utf32_tag, Iter f_, Sentinel l) noexcept
        {
            auto f = make_utf_32_to_16_iterator(f_, f_, l);
            return tagged_range<utf16_tag, decltype(f), Sentinel>{f, l};
        }
        template<typename Iter>
        constexpr auto make_utf16_range_(utf32_tag, Iter f_, Iter l_) noexcept
        {
            auto f = make_utf_32_to_16_iterator(f_, f_, l_);
            auto l = make_utf_32_to_16_iterator(f_, l_, l_);
            return tagged_range<utf16_tag, decltype(f)>{f, l};
        }

        // UTF-32
        template<typename Iter, typename Sentinel>
        constexpr auto make_utf32_range_(utf8_tag, Iter f_, Sentinel l) noexcept
        {
            auto f = make_utf_8_to_32_iterator(f_, f_, l);
            return tagged_range<utf32_tag, decltype(f), Sentinel>{f, l};
        }
        template<typename Iter>
        constexpr auto make_utf32_range_(utf8_tag, Iter f_, Iter l_) noexcept
        {
            auto f = make_utf_8_to_32_iterator(f_, f_, l_);
            auto l = make_utf_8_to_32_iterator(f_, l_, l_);
            return tagged_range<utf32_tag, decltype(f)>{f, l};
        }
        template<typename Iter, typename Sentinel>
        constexpr auto
        make_utf32_range_(utf16_tag, Iter f_, Sentinel l) noexcept
        {
            auto f = make_utf_16_to_32_iterator(f_, f_, l);
            return tagged_range<utf32_tag, decltype(f), Sentinel>{f, l};
        }
        template<typename Iter>
        constexpr auto make_utf32_range_(utf16_tag, Iter f_, Iter l_) noexcept
        {
            auto f = make_utf_16_to_32_iterator(f_, f_, l_);
            auto l = make_utf_16_to_32_iterator(f_, l_, l_);
            return tagged_range<utf32_tag, decltype(f)>{f, l};
        }
        template<typename Iter, typename Sentinel>
        constexpr auto make_utf32_range_(utf32_tag, Iter f, Sentinel l) noexcept
        {
            return tagged_range<utf32_tag, Iter, Sentinel>{f, l};
        }

        template<typename ResultType, typename Iterator, typename Sentinel>
        constexpr auto
        make_iter(Iterator first, Iterator it, Sentinel last) noexcept
            -> decltype(ResultType(first, it, last))
        {
            return ResultType(first, it, last);
        }
        template<typename ResultType>
        constexpr auto
        make_iter(ResultType first, ResultType it, ResultType last) noexcept
            -> decltype(ResultType(it))
        {
            return it;
        }
        template<typename ResultType, typename Sentinel>
        constexpr auto
        make_iter(ResultType first, ResultType it, Sentinel last) noexcept
            -> decltype(ResultType(it))
        {
            return it;
        }
        template<typename ResultType, typename Iterator>
        constexpr auto
        make_iter(Iterator first, ResultType it, ResultType last) noexcept
            -> decltype(ResultType(it))
        {
            return it;
        }
    }

    /** A view over UTF-8 code units.  The set of operations available depends
        on types `Iter` and `Sentinel`.  See [view.interface] in the C++20 or
        later standard for details. */
    template<typename Iter, typename Sentinel = Iter>
    struct utf8_view : stl_interfaces::view_interface<utf8_view<Iter, Sentinel>>
    {
        using iterator = Iter;
        using sentinel = Sentinel;

        constexpr utf8_view() noexcept {}
        constexpr utf8_view(iterator first, sentinel last) noexcept :
            first_(detail::unpack_iterator_and_sentinel(first, last).f_),
            last_(detail::unpack_iterator_and_sentinel(first, last).l_)
        {}

        constexpr iterator begin() const noexcept
        {
            return detail::make_iter<iterator>(first_, first_, last_);
        }
        constexpr sentinel end() const noexcept
        {
            return detail::make_iter<sentinel>(first_, last_, last_);
        }

        friend constexpr bool operator==(utf8_view lhs, utf8_view rhs)
        {
            return lhs.begin() == rhs.begin() && lhs.end() == rhs.end();
        }
        friend constexpr bool operator!=(utf8_view lhs, utf8_view rhs)
        {
            return !(lhs == rhs);
        }

        friend std::ostream & operator<<(std::ostream & os, utf8_view v)
        {
            auto out = std::ostreambuf_iterator<char>(os);
            for (auto it = v.begin(); it != v.end(); ++it, ++out) {
                *out = *it;
            }
            return os;
        }
#if defined(_MSC_VER)
        friend std::wostream & operator<<(std::wostream & os, utf8_view v)
        {
            boost::text::v1::transcode_utf_8_to_16(
                v.begin(), v.end(), std::ostreambuf_iterator<wchar_t>(os));
            return os;
        }
#endif

    private:
        using iterator_t =
            decltype(detail::unpack_iterator_and_sentinel(
                         std::declval<Iter>(), std::declval<Sentinel>())
                         .f_);
        using sentinel_t =
            decltype(detail::unpack_iterator_and_sentinel(
                         std::declval<Iter>(), std::declval<Sentinel>())
                         .l_);

        iterator_t first_;
        sentinel_t last_;
    };

    /** Returns a `utf8_view` over the data in `[first, last)`, transcoding
        the data if necessary. */
    template<typename Iter, typename Sentinel>
    constexpr auto as_utf8(Iter first, Sentinel last) noexcept
    {
        auto unpacked = detail::unpack_iterator_and_sentinel(first, last);
        auto r =
            detail::make_utf8_range_(unpacked.tag_, unpacked.f_, unpacked.l_);
        return utf8_view<decltype(r.f_), decltype(r.l_)>(r.f_, r.l_);
    }

    namespace detail {
        template<
            typename Range,
            bool Pointer = char_ptr<Range>::value || _16_ptr<Range>::value ||
                           cp_ptr<Range>::value>
        struct as_utf8_dispatch
        {
            static constexpr auto call(Range const & r) noexcept
                -> decltype(as_utf8(std::begin(r), std::end(r)))
            {
                return as_utf8(std::begin(r), std::end(r));
            }
        };

        template<typename Ptr>
        struct as_utf8_dispatch<Ptr, true>
        {
            static constexpr auto call(Ptr p) noexcept
                -> decltype(as_utf8(p, null_sentinel{}))
            {
                return as_utf8(p, null_sentinel{});
            }
        };
    }

    /** Returns a `utf8_view` over the data in `r`, transcoding the data if
        necessary. */
    template<typename Range>
    constexpr auto as_utf8(Range const & r) noexcept
        -> decltype(detail::as_utf8_dispatch<Range>::call(r))
    {
        return detail::as_utf8_dispatch<Range>::call(r);
    }

    /** A view over UTF-16 code units.  The set of operations available
        depends on types `Iter` and `Sentinel`.  See [view.interface] in the
        C++20 or later standard for details. */
    template<typename Iter, typename Sentinel = Iter>
    struct utf16_view
        : stl_interfaces::view_interface<utf16_view<Iter, Sentinel>>
    {
        using iterator = Iter;
        using sentinel = Sentinel;

        constexpr utf16_view() noexcept {}
        constexpr utf16_view(iterator first, sentinel last) noexcept :
            first_(detail::unpack_iterator_and_sentinel(first, last).f_),
            last_(detail::unpack_iterator_and_sentinel(first, last).l_)
        {}

        constexpr iterator begin() const noexcept
        {
            return detail::make_iter<iterator>(first_, first_, last_);
        }
        constexpr sentinel end() const noexcept
        {
            return detail::make_iter<sentinel>(first_, last_, last_);
        }

        friend constexpr bool operator==(utf16_view lhs, utf16_view rhs)
        {
            return lhs.begin() == rhs.begin() && lhs.end() == rhs.end();
        }
        friend constexpr bool operator!=(utf16_view lhs, utf16_view rhs)
        {
            return !(lhs == rhs);
        }

        friend std::ostream & operator<<(std::ostream & os, utf16_view v)
        {
            boost::text::v1::transcode_utf_16_to_8(
                v.begin(), v.end(), std::ostreambuf_iterator<char>(os));
            return os;
        }
#if defined(_MSC_VER)
        friend std::wostream & operator<<(std::wostream & os, utf16_view v)
        {
            auto out = std::ostreambuf_iterator<wchar_t>(os);
            for (auto it = v.begin(); it != v.end(); ++it, ++out) {
                *out = *it;
            }
            return os;
        }
#endif

    private:
        using iterator_t =
            decltype(detail::unpack_iterator_and_sentinel(
                         std::declval<Iter>(), std::declval<Sentinel>())
                         .f_);
        using sentinel_t =
            decltype(detail::unpack_iterator_and_sentinel(
                         std::declval<Iter>(), std::declval<Sentinel>())
                         .l_);

        iterator_t first_;
        sentinel_t last_;
    };

    /** Returns a `utf16_view` over the data in `[first, last)`, transcoding
        the data if necessary. */
    template<typename Iter, typename Sentinel>
    constexpr auto as_utf16(Iter first, Sentinel last) noexcept
    {
        auto unpacked = detail::unpack_iterator_and_sentinel(first, last);
        auto r =
            detail::make_utf16_range_(unpacked.tag_, unpacked.f_, unpacked.l_);
        return utf16_view<decltype(r.f_), decltype(r.l_)>(r.f_, r.l_);
    }

    namespace detail {
        template<
            typename Range,
            bool Pointer = char_ptr<Range>::value || _16_ptr<Range>::value ||
                           cp_ptr<Range>::value>
        struct as_utf16_dispatch
        {
            static constexpr auto call(Range const & r) noexcept
                -> decltype(as_utf16(std::begin(r), std::end(r)))
            {
                return as_utf16(std::begin(r), std::end(r));
            }
        };

        template<typename Ptr>
        struct as_utf16_dispatch<Ptr, true>
        {
            static constexpr auto call(Ptr p) noexcept
                -> decltype(as_utf16(p, null_sentinel{}))
            {
                return as_utf16(p, null_sentinel{});
            }
        };
    }

    /** Returns a `utf16_view` over the data in `r`, transcoding the data if
        necessary. */
    template<typename Range>
    constexpr auto as_utf16(Range const & r) noexcept
        -> decltype(detail::as_utf16_dispatch<Range>::call(r))
    {
        return detail::as_utf16_dispatch<Range>::call(r);
    }

    /** A view over UTF-32 code units.  The set of operations available
        depends on types `Iter` and `Sentinel`.  See [view.interface] in the
        C++20 or later standard for details. */
    template<typename Iter, typename Sentinel = Iter>
    struct utf32_view
        : stl_interfaces::view_interface<utf32_view<Iter, Sentinel>>
    {
        using iterator = Iter;
        using sentinel = Sentinel;

        constexpr utf32_view() noexcept {}
        constexpr utf32_view(iterator first, sentinel last) noexcept :
            first_(detail::unpack_iterator_and_sentinel(first, last).f_),
            last_(detail::unpack_iterator_and_sentinel(first, last).l_)
        {}

        constexpr iterator begin() const noexcept
        {
            return detail::make_iter<iterator>(first_, first_, last_);
        }
        constexpr sentinel end() const noexcept
        {
            return detail::make_iter<sentinel>(first_, last_, last_);
        }

        friend constexpr bool operator==(utf32_view lhs, utf32_view rhs)
        {
            return lhs.begin() == rhs.begin() && lhs.end() == rhs.end();
        }
        friend constexpr bool operator!=(utf32_view lhs, utf32_view rhs)
        {
            return !(lhs == rhs);
        }

        friend std::ostream & operator<<(std::ostream & os, utf32_view v)
        {
            boost::text::v1::transcode_utf_32_to_8(
                v.begin(), v.end(), std::ostreambuf_iterator<char>(os));
            return os;
        }
#if defined(_MSC_VER)
        friend std::wostream & operator<<(std::wostream & os, utf32_view v)
        {
            boost::text::v1::transcode_utf_32_to_16(
                v.begin(), v.end(), std::ostreambuf_iterator<wchar_t>(os));
            return os;
        }
#endif

    private:
        using iterator_t =
            decltype(detail::unpack_iterator_and_sentinel(
                         std::declval<Iter>(), std::declval<Sentinel>())
                         .f_);
        using sentinel_t =
            decltype(detail::unpack_iterator_and_sentinel(
                         std::declval<Iter>(), std::declval<Sentinel>())
                         .l_);

        iterator_t first_;
        sentinel_t last_;
    };

    /** Returns a `utf32_view` over the data in `[first, last)`, transcoding
        the data if necessary. */
    template<typename Iter, typename Sentinel>
    constexpr auto as_utf32(Iter first, Sentinel last) noexcept
    {
        auto unpacked = detail::unpack_iterator_and_sentinel(first, last);
        auto r =
            detail::make_utf32_range_(unpacked.tag_, unpacked.f_, unpacked.l_);
        return utf32_view<decltype(r.f_), decltype(r.l_)>(r.f_, r.l_);
    }

    namespace detail {
        template<
            typename Range,
            bool Pointer = char_ptr<Range>::value || _16_ptr<Range>::value ||
                           cp_ptr<Range>::value>
        struct as_utf32_dispatch
        {
            static constexpr auto call(Range const & r) noexcept
                -> decltype(as_utf32(std::begin(r), std::end(r)))
            {
                return as_utf32(std::begin(r), std::end(r));
            }
        };

        template<typename Ptr>
        struct as_utf32_dispatch<Ptr, true>
        {
            static constexpr auto call(Ptr p) noexcept
                -> decltype(as_utf32(p, null_sentinel{}))
            {
                return as_utf32(p, null_sentinel{});
            }
        };
    }

    /** Returns a `utf32_view` over the data in `r`, transcoding the data if
        necessary. */
    template<typename Range>
    constexpr auto as_utf32(Range const & r) noexcept
        -> decltype(detail::as_utf32_dispatch<Range>::call(r))
    {
        return detail::as_utf32_dispatch<Range>::call(r);
    }

}}}

#endif

max_stars_repo_name: eightysquirrels/text

max_issues_repo_name: eightysquirrels/text

max_forks_repo_name: eightysquirrels/text


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

#if !defined(BOOST_TTI_DETAIL_STATIC_MEM_FUN_HPP)
#define BOOST_TTI_DETAIL_STATIC_MEM_FUN_HPP

#include <boost/function_types/is_function.hpp>
#include <boost/function_types/property_tags.hpp>
#include <boost/mpl/and.hpp>
#include <boost/mpl/bool.hpp>
#include <boost/mpl/eval_if.hpp>
#include <boost/mpl/identity.hpp>
#include <boost/mpl/vector.hpp>
#include <boost/preprocessor/cat.hpp>
#include <boost/tti/detail/dnullptr.hpp>
#include <boost/tti/detail/dtfunction.hpp>
#include <boost/tti/gen/namespace_gen.hpp>
#include <boost/type_traits/is_class.hpp>
#include <boost/type_traits/is_same.hpp>
#include <boost/type_traits/detail/yes_no_type.hpp>

#if defined(__SUNPRO_CC)

#define BOOST_TTI_DETAIL_TRAIT_IMPL_HAS_STATIC_MEMBER_FUNCTION(trait,name) \
  template<class BOOST_TTI_DETAIL_TP_T,class BOOST_TTI_DETAIL_TP_TYPE> \
  struct BOOST_PP_CAT(trait,_detail_ihsmf) \
    { \
    template<BOOST_TTI_DETAIL_TP_TYPE *> \
    struct helper {}; \
    \
    template<class BOOST_TTI_DETAIL_TP_U> \
    static ::boost::type_traits::yes_type chkt(helper<&BOOST_TTI_DETAIL_TP_U::name> *); \
    \
    template<class BOOST_TTI_DETAIL_TP_U> \
    static ::boost::type_traits::no_type chkt(...); \
    \
    typedef boost::mpl::bool_<sizeof(chkt<BOOST_TTI_DETAIL_TP_T>(BOOST_TTI_DETAIL_NULLPTR))==sizeof(::boost::type_traits::yes_type)> type; \
    }; \
/**/

#else

#define BOOST_TTI_DETAIL_TRAIT_IMPL_HAS_STATIC_MEMBER_FUNCTION(trait,name) \
  template<class BOOST_TTI_DETAIL_TP_T,class BOOST_TTI_DETAIL_TP_TYPE> \
  struct BOOST_PP_CAT(trait,_detail_ihsmf) \
    { \
    template<BOOST_TTI_DETAIL_TP_TYPE *> \
    struct helper; \
    \
    template<class BOOST_TTI_DETAIL_TP_U> \
    static ::boost::type_traits::yes_type chkt(helper<&BOOST_TTI_DETAIL_TP_U::name> *); \
    \
    template<class BOOST_TTI_DETAIL_TP_U> \
    static ::boost::type_traits::no_type chkt(...); \
    \
    typedef boost::mpl::bool_<sizeof(chkt<BOOST_TTI_DETAIL_TP_T>(BOOST_TTI_DETAIL_NULLPTR))==sizeof(::boost::type_traits::yes_type)> type; \
    }; \
/**/

#endif

#define BOOST_TTI_DETAIL_TRAIT_HAS_STATIC_MEMBER_FUNCTION_OP(trait,name) \
  BOOST_TTI_DETAIL_TRAIT_IMPL_HAS_STATIC_MEMBER_FUNCTION(trait,name) \
  template<class BOOST_TTI_DETAIL_TP_T,class BOOST_TTI_DETAIL_TP_R,class BOOST_TTI_DETAIL_TP_FS,class BOOST_TTI_DETAIL_TP_TAG> \
  struct BOOST_PP_CAT(trait,_detail_hsmf_op) : \
    BOOST_PP_CAT(trait,_detail_ihsmf) \
      < \
      BOOST_TTI_DETAIL_TP_T, \
      typename \
      boost::mpl::eval_if \
        < \
        boost::mpl::and_ \
          < \
          boost::function_types::is_function<BOOST_TTI_DETAIL_TP_R>, \
          boost::is_same<BOOST_TTI_DETAIL_TP_FS,boost::mpl::vector<> >, \
          boost::is_same<BOOST_TTI_DETAIL_TP_TAG,boost::function_types::null_tag> \
          >, \
        boost::mpl::identity<BOOST_TTI_DETAIL_TP_R>, \
        BOOST_TTI_NAMESPACE::detail::tfunction_seq<BOOST_TTI_DETAIL_TP_R,BOOST_TTI_DETAIL_TP_FS,BOOST_TTI_DETAIL_TP_TAG> \
        >::type \
      > \
    { \
    }; \
/**/

#define BOOST_TTI_DETAIL_TRAIT_HAS_STATIC_MEMBER_FUNCTION(trait,name) \
  BOOST_TTI_DETAIL_TRAIT_HAS_STATIC_MEMBER_FUNCTION_OP(trait,name) \
  template<class BOOST_TTI_DETAIL_TP_T,class BOOST_TTI_DETAIL_TP_R,class BOOST_TTI_DETAIL_TP_FS,class BOOST_TTI_DETAIL_TP_TAG> \
  struct BOOST_PP_CAT(trait,_detail_hsmf) : \
	boost::mpl::eval_if \
		< \
		boost::is_class<BOOST_TTI_DETAIL_TP_T>, \
		BOOST_PP_CAT(trait,_detail_hsmf_op)<BOOST_TTI_DETAIL_TP_T,BOOST_TTI_DETAIL_TP_R,BOOST_TTI_DETAIL_TP_FS,BOOST_TTI_DETAIL_TP_TAG>, \
		boost::mpl::false_ \
		> \
    { \
    }; \
/**/

#endif // BOOST_TTI_DETAIL_STATIC_MEM_FUN_HPP

ext: hpp


text:
/*-----------------------------------------------------------------------------+
Copyright (c) 2008-2009: Joachim Faulhaber
+------------------------------------------------------------------------------+
   Distributed under the Boost Software License, Version 1.0.
      (See accompanying file LICENCE.txt or copy at
           http://www.boost.org/LICENSE_1_0.txt)
+-----------------------------------------------------------------------------*/
#ifndef BOOST_ICL_IS_COMBINABLE_HPP_JOFA_090115
#define BOOST_ICL_IS_COMBINABLE_HPP_JOFA_090115

#include <boost/mpl/bool.hpp>
#include <boost/mpl/if.hpp>
#include <boost/mpl/and.hpp>
#include <boost/mpl/or.hpp>
#include <boost/mpl/not.hpp>
#include <boost/type_traits/is_same.hpp>
#include <boost/icl/type_traits/is_concept_equivalent.hpp>
#include <boost/icl/type_traits/is_interval_container.hpp>

namespace boost{namespace icl
{

template<class Type>
struct is_overloadable
{
    typedef is_overloadable<Type> type;
    BOOST_STATIC_CONSTANT(bool, value =
        (boost::is_same<Type, typename Type::overloadable_type>::value)
        );
};

//------------------------------------------------------------------------------
template<class LeftT, class RightT>
struct is_codomain_equal
{
    typedef is_codomain_equal<LeftT, RightT> type;
    BOOST_STATIC_CONSTANT(bool, value =
        (boost::is_same<typename LeftT::codomain_type,
                        typename RightT::codomain_type>::value)
        );
};

//NOTE: Equality of compare order implies the equality of the domain_types
template<class LeftT, class RightT>
struct is_key_compare_equal
{
    typedef is_key_compare_equal<LeftT, RightT> type;
    BOOST_STATIC_CONSTANT(bool, value =
        (boost::is_same<typename LeftT::key_compare,
                        typename RightT::key_compare>::value)
        );
};

template<class LeftT, class RightT>
struct is_codomain_type_equal
{
    typedef is_codomain_type_equal<LeftT, RightT> type;
    BOOST_STATIC_CONSTANT(bool, value =
        (mpl::and_<is_key_compare_equal<LeftT, RightT>,
                   is_codomain_equal<LeftT, RightT> >::value)
        );
};

// For equal containers concepts, domain order and codomain type must match.
template<template<class>class IsConcept, class LeftT, class RightT>
struct is_concept_compatible
{
    typedef is_concept_compatible<IsConcept, LeftT, RightT> type;
    BOOST_STATIC_CONSTANT(bool, value =
        (mpl::and_<
            IsConcept<LeftT>
          , IsConcept<RightT>
          , is_codomain_type_equal<LeftT, RightT>
        >::value)
        );
};

template<template<class>class LeftConcept,
         template<class>class RightConcept,
         class LeftT, class RightT>
struct is_concept_combinable
{
    typedef is_concept_combinable<LeftConcept, RightConcept, LeftT, RightT> type;
    BOOST_STATIC_CONSTANT(bool, value =
        (mpl::and_<
            LeftConcept<LeftT>
          , RightConcept<RightT>
          , is_key_compare_equal<LeftT, RightT>
        >::value)
        );
};

template<class LeftT, class RightT>
struct is_intra_combinable
{
    typedef is_intra_combinable<LeftT, RightT> type;
    BOOST_STATIC_CONSTANT(bool, value =
        (mpl::or_<
            is_concept_compatible<is_interval_set, LeftT, RightT>
          , is_concept_compatible<is_interval_map, LeftT, RightT>
        >::value)
        );
};

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

//------------------------------------------------------------------------------
template<class LeftT, class RightT>
struct is_cross_combinable
{
    typedef is_cross_combinable<LeftT, RightT> type;
    BOOST_STATIC_CONSTANT(bool, value =
        (mpl::or_<
            is_concept_combinable<is_interval_set, is_interval_map, LeftT, RightT>
          , is_concept_combinable<is_interval_map, is_interval_set, LeftT, RightT>
        >::value)
        );
};

template<class LeftT, class RightT>
struct is_inter_combinable
{
    typedef is_inter_combinable<LeftT, RightT> type;
    BOOST_STATIC_CONSTANT(bool, value =
        (mpl::or_<is_intra_combinable<LeftT,RightT>,
                  is_cross_combinable<LeftT,RightT> >::value)
        );
};

//------------------------------------------------------------------------------
// is_fragment_of
//------------------------------------------------------------------------------
template<class FragmentT, class Type>
struct is_fragment_of
{
    typedef is_fragment_of type;
    BOOST_STATIC_CONSTANT(bool, value = false);
};

template<class Type>
struct is_fragment_of<typename Type::element_type, Type>
{
    typedef is_fragment_of type;
    BOOST_STATIC_CONSTANT(bool, value = true);
};

template<class Type>
struct is_fragment_of<typename Type::segment_type, Type>
{
    typedef is_fragment_of type;
    BOOST_STATIC_CONSTANT(bool, value = true);
};

//------------------------------------------------------------------------------
// is_key_of
//------------------------------------------------------------------------------
template<class KeyT, class Type>
struct is_key_of
{
    typedef is_key_of type;
    BOOST_STATIC_CONSTANT(bool, value = false);
};

template<class Type>
struct is_key_of<typename Type::domain_type, Type>
{
    typedef is_key_of type;
    BOOST_STATIC_CONSTANT(bool, value = true);
};

template<class Type>
struct is_key_of<typename Type::interval_type, Type>
{
    typedef is_key_of type;
    BOOST_STATIC_CONSTANT(bool, value = true);
};

//------------------------------------------------------------------------------
// is_interval_set_derivative
//------------------------------------------------------------------------------
template<class Type, class AssociateT>
struct is_interval_set_derivative;

template<class Type>
struct is_interval_set_derivative<Type, typename Type::domain_type>
{
    typedef is_interval_set_derivative type;
    BOOST_STATIC_CONSTANT(bool, value = (is_interval_container<Type>::value));
};

template<class Type>
struct is_interval_set_derivative<Type, typename Type::interval_type>
{
    typedef is_interval_set_derivative type;
    BOOST_STATIC_CONSTANT(bool, value = (is_interval_container<Type>::value));
};

template<class Type, class AssociateT>
struct is_interval_set_derivative
{
    typedef is_interval_set_derivative<Type, AssociateT> type;
    BOOST_STATIC_CONSTANT(bool, value = false);
};

//------------------------------------------------------------------------------
// is_interval_map_derivative
//------------------------------------------------------------------------------
template<class Type, class AssociateT>
struct is_interval_map_derivative;

template<class Type>
struct is_interval_map_derivative<Type, typename Type::domain_mapping_type>
{
    typedef is_interval_map_derivative type;
    BOOST_STATIC_CONSTANT(bool, value = (is_interval_container<Type>::value));
};

template<class Type>
struct is_interval_map_derivative<Type, typename Type::interval_mapping_type>
{
    typedef is_interval_map_derivative type;
    BOOST_STATIC_CONSTANT(bool, value = (is_interval_container<Type>::value));
};

template<class Type>
struct is_interval_map_derivative<Type, typename Type::value_type>
{
    typedef is_interval_map_derivative type;
    BOOST_STATIC_CONSTANT(bool, value = (is_interval_container<Type>::value));
};

template<class Type, class AssociateT>
struct is_interval_map_derivative
{
    typedef is_interval_map_derivative<Type, AssociateT> type;
    BOOST_STATIC_CONSTANT(bool, value = false);
};

//------------------------------------------------------------------------------
// is_intra_derivative
//------------------------------------------------------------------------------
template<class Type, class AssociateT>
struct is_intra_derivative
{
    typedef is_intra_derivative<Type, AssociateT> type;
    BOOST_STATIC_CONSTANT(bool, value =
        (mpl::or_
        <
            mpl::and_<is_interval_set<Type>,
                      is_interval_set_derivative<Type, AssociateT> >
          , mpl::and_<is_interval_map<Type>,
                      is_interval_map_derivative<Type, AssociateT> >
        >::value)
        );
};

template<class Type, class AssociateT>
struct is_cross_derivative
{
    typedef is_cross_derivative<Type, AssociateT> type;
    BOOST_STATIC_CONSTANT(bool, value =
        (mpl::and_<
            is_interval_map<Type>
          , is_interval_set_derivative<Type, AssociateT>
        >::value)
        );
};

template<class Type, class AssociateT>
struct is_inter_derivative
{
    typedef is_inter_derivative<Type, AssociateT> type;
    BOOST_STATIC_CONSTANT(bool, value =
        (mpl::or_<
            is_intra_derivative<Type, AssociateT>
          , is_cross_derivative<Type, AssociateT>
        >::value)
        );
};

//------------------------------------------------------------------------------
//- right combinable
//------------------------------------------------------------------------------

template<class GuideT, class CompanionT>
struct is_interval_set_right_combinable
{
    typedef is_interval_set_right_combinable<GuideT, CompanionT> type;
    BOOST_STATIC_CONSTANT(bool, value =
        (mpl::and_
        <
            is_interval_set<GuideT>
          , mpl::or_
            <
                is_interval_set_derivative<GuideT, CompanionT>
              , is_concept_compatible<is_interval_set, GuideT, CompanionT>
            >
        >::value)
        );
};

template<class GuideT, class CompanionT>
struct is_interval_map_right_intra_combinable //NOTE equivalent to is_fragment_type_of
{
    typedef is_interval_map_right_intra_combinable<GuideT, CompanionT> type;
    BOOST_STATIC_CONSTANT(bool, value =
        (mpl::and_
        <
            is_interval_map<GuideT>
          , mpl::or_
            <
                is_interval_map_derivative<GuideT, CompanionT>
              , is_concept_compatible<is_interval_map, GuideT, CompanionT>
            >
        >::value)
        );
};

template<class GuideT, class CompanionT>
struct is_interval_map_right_cross_combinable //NOTE equivalent to key_type_of<Comp, Guide>
{
    typedef is_interval_map_right_cross_combinable<GuideT, CompanionT> type;
    BOOST_STATIC_CONSTANT(bool, value =
        (mpl::and_
        <
            is_interval_map<GuideT>
          , mpl::or_
            <
                is_cross_derivative<GuideT, CompanionT>
              , is_concept_combinable<is_interval_map, is_interval_set, GuideT, CompanionT>
            >
        >::value)
        );
};

template<class GuideT, class CompanionT>
struct is_interval_map_right_inter_combinable
{
    typedef is_interval_map_right_inter_combinable<GuideT, CompanionT> type;
    BOOST_STATIC_CONSTANT(bool, value =
        (mpl::or_<
            is_interval_map_right_intra_combinable<GuideT, CompanionT>
          , is_interval_map_right_cross_combinable<GuideT, CompanionT>
        >::value)
        );
};

template<class GuideT, class CompanionT>
struct is_right_intra_combinable
{
    typedef is_right_intra_combinable<GuideT, CompanionT> type;
    BOOST_STATIC_CONSTANT(bool, value =
        (mpl::or_
        <
            is_interval_set_right_combinable<GuideT, CompanionT>
          , is_interval_map_right_intra_combinable<GuideT, CompanionT>
        >::value)
        );
};

template<class GuideT, class CompanionT>
struct is_right_inter_combinable
{
    typedef is_right_inter_combinable<GuideT, CompanionT> type;
    BOOST_STATIC_CONSTANT(bool, value =
        (mpl::or_
        <
            is_interval_set_right_combinable<GuideT, CompanionT>
          , is_interval_map_right_inter_combinable<GuideT, CompanionT>
        >::value)
        );
};

template<class GuideT, class IntervalSetT>
struct combines_right_to_interval_set
{
    typedef combines_right_to_interval_set<GuideT, IntervalSetT> type;
    BOOST_STATIC_CONSTANT(bool, value =
        (is_concept_combinable<is_interval_container, is_interval_set,
                               GuideT, IntervalSetT>::value)
        );
};

template<class GuideT, class IntervalMapT>
struct combines_right_to_interval_map
{
    typedef combines_right_to_interval_map<GuideT, IntervalMapT> type;
    BOOST_STATIC_CONSTANT(bool, value =
        (is_concept_compatible<is_interval_map, GuideT, IntervalMapT>::value) );
};

template<class GuideT, class IntervalContainerT>
struct combines_right_to_interval_container
{
    typedef combines_right_to_interval_container<GuideT, IntervalContainerT> type;
    BOOST_STATIC_CONSTANT(bool, value =
        (mpl::or_<combines_right_to_interval_set<GuideT, IntervalContainerT>,
                  combines_right_to_interval_map<GuideT, IntervalContainerT> >::value)
        );
};

//------------------------------------------------------------------------------
//- segmentational_fineness
//------------------------------------------------------------------------------
template<class Type> struct unknown_fineness
{
    typedef unknown_fineness<Type> type;
    static const int value = 0;
};

template<class Type> struct known_fineness
{
    typedef known_fineness<Type> type;
    static const int value = Type::fineness;
};

template<class Type>struct segmentational_fineness
{
    typedef segmentational_fineness<Type> type;
    static const int value =
        mpl::if_<is_interval_container<Type>,
                        known_fineness<Type>,
                      unknown_fineness<Type>
                >::type::value;
};

//------------------------------------------------------------------------------
// is_interval_set_companion
//------------------------------------------------------------------------------

// CompanionT is either an interval_set or a derivative of set level:
// element_type=domain_type, segment_type=interval_type
template<class GuideT, class CompanionT> struct is_interval_set_companion
{
    typedef is_interval_set_companion<GuideT,CompanionT> type;
    BOOST_STATIC_CONSTANT(bool, value =
        (mpl::or_
        <
            combines_right_to_interval_set<GuideT,CompanionT>
          , is_interval_set_derivative<GuideT,CompanionT>
        >::value)
        );
};

//------------------------------------------------------------------------------
// is_interval_map_companion
//------------------------------------------------------------------------------

template<class GuideT, class CompanionT> struct is_interval_map_companion
{
    typedef is_interval_map_companion<GuideT,CompanionT> type;
    BOOST_STATIC_CONSTANT(bool, value =
        (mpl::or_
        <
            combines_right_to_interval_map<GuideT,CompanionT>
          , is_interval_map_derivative<GuideT,CompanionT>
        >::value)
        );
};

//------------------------------------------------------------------------------
//- is_coarser_interval_{set,map}_companion
//------------------------------------------------------------------------------
template<class GuideT, class CompanionT>
struct is_coarser_interval_set_companion
{
    typedef is_coarser_interval_set_companion<GuideT, CompanionT> type;
    BOOST_STATIC_CONSTANT(bool, value =
        (mpl::and_
        <
           is_interval_set_companion<GuideT, CompanionT>
         , mpl::bool_<(  segmentational_fineness<GuideT>::value
                       > segmentational_fineness<CompanionT>::value)>
        >::value)
        );
};

template<class GuideT, class CompanionT>
struct is_coarser_interval_map_companion
{
    typedef is_coarser_interval_map_companion<GuideT, CompanionT> type;
    BOOST_STATIC_CONSTANT(bool, value =
        (mpl::and_
        <
           is_interval_map_companion<GuideT, CompanionT>
         , mpl::bool_<(  segmentational_fineness<GuideT>::value
                       > segmentational_fineness<CompanionT>::value)>
        >::value)
        );
};

//------------------------------------------------------------------------------
// is_binary_interval_{set,map}_combinable
//------------------------------------------------------------------------------
template<class GuideT, class CompanionT>
struct is_binary_interval_set_combinable
{
    typedef is_binary_interval_set_combinable<GuideT,CompanionT> type;
    static const int value =
        mpl::and_<  is_interval_set<GuideT>
                  , is_coarser_interval_set_companion<GuideT, CompanionT>
                 >::value;
};

template<class GuideT, class CompanionT>
struct is_binary_interval_map_combinable
{
    typedef is_binary_interval_map_combinable<GuideT,CompanionT> type;
    static const int value =
        mpl::and_<  is_interval_map<GuideT>
                  , is_coarser_interval_map_companion<GuideT, CompanionT>
                 >::value;
};

template<class GuideT, class CompanionT>
struct is_binary_intra_combinable
{
    typedef is_binary_intra_combinable<GuideT,CompanionT> type;
    BOOST_STATIC_CONSTANT(bool, value =
        (mpl::or_<is_binary_interval_set_combinable<GuideT, CompanionT>,
                 is_binary_interval_map_combinable<GuideT, CompanionT>
                >::value)
        );
};

template<class GuideT, class CompanionT>
struct is_binary_cross_combinable
{
    typedef is_binary_cross_combinable<GuideT,CompanionT> type;
    BOOST_STATIC_CONSTANT(bool, value =
        (mpl::and_
        <     is_interval_map<GuideT>
            , mpl::or_<  is_coarser_interval_map_companion<GuideT, CompanionT>
                       ,         is_interval_set_companion<GuideT, CompanionT> >
        >::value)
        );
};

template<class GuideT, class CompanionT>
struct is_binary_inter_combinable
{
    typedef is_binary_inter_combinable<GuideT,CompanionT> type;
    BOOST_STATIC_CONSTANT(bool, value =
        (mpl::or_
        <
            mpl::and_<is_interval_map<GuideT>,
                      is_binary_cross_combinable<GuideT, CompanionT> >
          , mpl::and_<is_interval_set<GuideT>,
                      is_binary_intra_combinable<GuideT, CompanionT> >
        >::value)
        );
};

}} // namespace icl boost

#endif

max_stars_repo_name: randolphwong/mcsema

max_issues_repo_name: randolphwong/mcsema

max_forks_repo_name: randolphwong/mcsema


text:
#include <MeshFEM/MeshIO.hh>
#include <MeshFEM/MSHFieldWriter.hh>
#include <MeshFEM/LinearElasticity.hh>
#include <MeshFEM/Materials.hh>
#include <MeshFEM/PeriodicHomogenization.hh>
#include <MeshFEM/OrthotropicHomogenization.hh>
#include <MeshFEM/GlobalBenchmark.hh>
#include <MeshFEM/TensorProjection.hh>
#include <vector>

#include <queue>
#include <iostream>
#include <iomanip>
#include <memory>
#include <cmath>

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

namespace po = boost::program_options;
using namespace std;
using namespace PeriodicHomogenization;

[[ noreturn ]] void usage(int exitVal, const po::options_description &visible_opts) {
    cout << "Usage: OptimizeLinkage_cli [options] mesh" << endl;
    cout << visible_opts << endl;
    exit(exitVal);
}

po::variables_map parseCmdLine(int argc, const char *argv[])
{
    po::options_description hidden_opts("Hidden Arguments");
    hidden_opts.add_options()
        ("mesh",       po::value<string>(),                     "input mesh")
        ;
    po::positional_options_description p;
    p.add("mesh",                1);

    po::options_description visible_opts;
    visible_opts.add_options()("help", "Produce this help message")
        ("material,m", po::value<string>(),                 "base material")
        ("degree,d",   po::value<int>()->default_value(2), "degree of finite elements")
        ("fieldOutput,o",po::value<string>(),              "Dump fluctuation stress and strain fields to specified msh file")
        ("centerFluctuationDisplacements,c",               "Shift each fluctuation displacement so that it averages to zero")
        ("fullDegreeFieldOutput,D",                        "Output full-degree nodal fields (don't do piecewise linear subsample)")
        ("distanceToIsotropy",                             "Output the distance to the closest isotropic tensor")
        ("distanceToMaterial", po::value<string>(),        "Output the distance to a particular material")
        ("ignorePeriodicMismatch",                         "Ignore mismatched nodes on the periodic faces (useful for voxel grids)")
        ("manualPeriodicVertices", po::value<string>(),    "Manually specify identified periodic vertices using a hacky file format (see PeriodicCondition constructor)")
        ("orthotropicCell,O",                              "Analyze the orthotropic symmetry base cell only")
        ;

    po::options_description cli_opts;
    cli_opts.add(visible_opts).add(hidden_opts);

    po::variables_map vm;
    try {
        po::store(po::command_line_parser(argc, argv).
                  options(cli_opts).positional(p).run(), vm);
        po::notify(vm);
    }
    catch (std::exception &e) {
        cout << "Error: " << e.what() << endl << endl;
        usage(1, visible_opts);
    }

    bool fail = false;
    if (vm.count("mesh") == 0) {
        cout << "Error: must specify input mesh" << endl;
        fail = true;
    }

    int d = vm["degree"].as<int>();
    if (d < 1 || d > 2) {
        cout << "Error: FEM Degree must be 1 or 2" << endl;
        fail = true;
    }

    if (fail || vm.count("help"))
        usage(fail, visible_opts);

    return vm;
}

// Sum the values appearing on periodically-identified vertices.
// First sum onto the reduced DoFs, then redistribute.
template<class Sim, class VField>
VField sumIdentifiedValues(const Sim &sim, VField v) {
    const auto &mesh = sim.mesh();
    if (v.domainSize() != mesh.numNodes())
        throw std::runtime_error("Expected per-node vector field");

    VField dofField(sim.numDoFs());
    dofField.clear();
    for (size_t i = 0; i < mesh.numNodes(); ++i)
        dofField(sim.DoF(i)) +=  v(i);
    for (size_t i = 0; i < mesh.numNodes(); ++i)
        v(i) = dofField(sim.DoF(i));

    return v;
}

template<size_t _N>
using HMG = LinearElasticity::HomogenousMaterialGetter<Materials::Constant>::template Getter<_N>;

template<size_t _N, size_t _FEMDegree>
void execute(const po::variables_map &args,
             const vector<MeshIO::IOVertex> &inVertices,
             const vector<MeshIO::IOElement> &inElements) {
    auto &mat = HMG<_N>::material;
    if (args.count("material")) mat.setFromFile(args["material"].as<string>());

    typedef LinearElasticity::Mesh<_N, _FEMDegree, HMG> Mesh;
    typedef LinearElasticity::Simulator<Mesh> Simulator;
    Simulator sim(inElements, inVertices);
    typedef typename Simulator::ETensor ETensor;
    typedef typename Simulator::VField  VField;

    BENCHMARK_START_TIMER_SECTION("Cell Problems");
    std::vector<VField> w_ij;
    std::unique_ptr<PeriodicCondition<_N>> pc;
    ETensor Eh;
    for (size_t it = 0; it < 20; ++it) {
        if (args.count("manualPeriodicVertices"))
            pc = Future::make_unique<PeriodicCondition<_N>>(sim.mesh(), args["manualPeriodicVertices"].as<string>());
        if (args.count("orthotropicCell") == 0) {
            solveCellProblems(w_ij, sim, 1e-7, args.count("ignorePeriodicMismatch"), std::move(pc));
        }
        else {
            auto systems = PeriodicHomogenization::Orthotropic::solveCellProblems(w_ij, sim, 1e-7);
            cout << systems.size() << endl;
        }

        BENCHMARK_STOP_TIMER_SECTION("Cell Problems");

        BENCHMARK_START_TIMER_SECTION("Compute Tensor");
        // ETensor Eh = homogenizedElasticityTensor(w_ij, sim);
        if (args.count("orthotropicCell") == 0)   Eh = homogenizedElasticityTensorDisplacementForm(w_ij, sim);
        else Eh = PeriodicHomogenization::Orthotropic::homogenizedElasticityTensorDisplacementForm(w_ij, sim);
        BENCHMARK_STOP_TIMER_SECTION("Compute Tensor");

        cout << setprecision(16);
        cout << "Homogenized elasticity tensor:" << endl;
        cout << Eh << endl << endl;

        auto eigs = Eh.computeEigenstrains();
        // Make all eigenstrains positive
        if (eigs.strains(0, 0) < 0) eigs.strains.col(0) *= -1;
        if (eigs.strains(0, 1) < 0) eigs.strains.col(1) *= -1;
        if (eigs.strains(0, 2) < 0) eigs.strains.col(2) *= -1;

        cout << "Minimum Eh eigenvalue " << eigs.lambdas[0] << " for eigenstrain: "
             << eigs.strains.col(0).transpose() << endl;

        SymmetricMatrixValue<Real, _N> minEigenstrain(eigs.strains.col(0));
        SymmetricMatrixValue<Real, _N> midEigenstrain(eigs.strains.col(1));
        SymmetricMatrixValue<Real, _N> maxEigenstrain(eigs.strains.col(2));

        ETensor Eh_pinv = Eh.pseudoinverse();
        // cout << "Eh : Eh_pinv: " << endl << Eh.doubleContract(Eh_pinv) << endl << endl;
        // cout << "Eh : Eh_pinv : Eh " << endl << Eh.doubleContract(Eh_pinv).doubleContract(Eh) << endl << endl;

        // Compute discrete shape derivative of minimum eigenvalue and
        // one of the eigenstrain components
        // (to steer away from the uniform expansion mode).
        auto dEh = homogenizedElasticityTensorDiscreteDifferential(w_ij, sim);
        // Work with vector fields instead of OneForms; we probably can't compute a
        // proper Riesz representative on non-manifold meshes anyway, so don't
        // worry about distinction between one-forms and vector fields.
        VField dMinEigenvalue = sumIdentifiedValues(sim, compose([&](const ETensor &E) { return minEigenstrain.doubleContract(E.doubleContract(minEigenstrain)); }, dEh).asVectorField());
        VField dMidEigenvalue = sumIdentifiedValues(sim, compose([&](const ETensor &E) { return midEigenstrain.doubleContract(E.doubleContract(midEigenstrain)); }, dEh).asVectorField());
        VField dMaxEigenvalue = sumIdentifiedValues(sim, compose([&](const ETensor &E) { return maxEigenstrain.doubleContract(E.doubleContract(maxEigenstrain)); }, dEh).asVectorField());

        VField dMinEigenstrainC0 = sumIdentifiedValues(sim, compose([&](const ETensor &E) { return -Eh_pinv.doubleContract(E.doubleContract(minEigenstrain))(0, 0); }, dEh).asVectorField());
        VField dMinEigenstrainC1 = sumIdentifiedValues(sim, compose([&](const ETensor &E) { return -Eh_pinv.doubleContract(E.doubleContract(minEigenstrain))(1, 1); }, dEh).asVectorField());
        VField dMinEigenstrainC2 = sumIdentifiedValues(sim, compose([&](const ETensor &E) { return -Eh_pinv.doubleContract(E.doubleContract(minEigenstrain))(0, 1); }, dEh).asVectorField());

        bool linearSubsampleFields = args.count("fullDegreeFieldOutput") == 0;
        MSHFieldWriter writer("vertical_linkage_it" + std::to_string(it) + ".msh", sim.mesh(), linearSubsampleFields);
        writer.addField("dE00", sumIdentifiedValues(sim, compose([&](const ETensor &E) { return E.D(0,0); }, dEh).asVectorField()), DomainType::PER_NODE);
        writer.addField("dE01", sumIdentifiedValues(sim, compose([&](const ETensor &E) { return E.D(0,1); }, dEh).asVectorField()), DomainType::PER_NODE);
        writer.addField("dE11", sumIdentifiedValues(sim, compose([&](const ETensor &E) { return E.D(1,1); }, dEh).asVectorField()), DomainType::PER_NODE);
        writer.addField("dE22", sumIdentifiedValues(sim, compose([&](const ETensor &E) { return E.D(2,2); }, dEh).asVectorField()), DomainType::PER_NODE);

        writer.addField("dMinEigenvalue", dMinEigenvalue, DomainType::PER_NODE);
        writer.addField("dMidEigenvalue", dMidEigenvalue, DomainType::PER_NODE);
        writer.addField("dMaxEigenvalue", dMaxEigenvalue, DomainType::PER_NODE);

        writer.addField("dMinEigenstrainC0", dMinEigenstrainC0, DomainType::PER_NODE);
        writer.addField("dMinEigenstrainC1", dMinEigenstrainC1, DomainType::PER_NODE);
        writer.addField("dMinEigenstrainC2", dMinEigenstrainC2, DomainType::PER_NODE);

        VField descentStep = dMinEigenstrainC1;
        descentStep.maxColumnNormalize();
        descentStep *= 0.01;
        std::vector<MeshIO::IOVertex> pts(sim.mesh().numVertices());
        for (auto v : sim.mesh().vertices()) {
            pts[v.index()] = v.node()->p;
            pts[v.index()].point += padTo3D(PointND<_N>(descentStep(v.index())));
        }
        sim.updateMeshNodePositions(pts);
    }

    ETensor S = Eh.inverse();
    cout << "Homogenized compliance tensor:" << endl;
    cout << S << endl;
    vector<Real> moduli(flatLen(_N));

    // Shear moduli are multiplied by 4 in flattened compliance tensor...
    for (size_t i = 0; i < flatLen(_N); ++i)
        moduli[i] = ((i < _N) ? 1.0 : 0.25) / S.D(i, i);

    vector<Real> poisson;
    if (_N == 2) poisson = { -S.D(0, 1) / S.D(1, 1),   // v_yx
                             -S.D(1, 0) / S.D(0, 0) }; // v_xy
    else         poisson = { -S.D(0, 1) / S.D(1, 1),   // v_yx
                             -S.D(0, 2) / S.D(2, 2),   // v_zx
                             -S.D(1, 2) / S.D(2, 2),   // v_zy
                             -S.D(1, 0) / S.D(0, 0),   // v_xy
                             -S.D(2, 0) / S.D(0, 0),   // v_xz
                             -S.D(2, 1) / S.D(1, 1) }; // v_zy

    if (_N == 2)  {
        cout << "Approximate Young moduli:\t"  << moduli[0] << "\t" << moduli[1] << endl;
        cout << "Approximate shear modulus:\t" << moduli[2] << endl;

        cout << "v_yx, v_xy:\t" << poisson[0] << "\t" << poisson[1] << endl;
    }
    else {
        cout << "Approximate Young moduli:\t" << moduli[0] << "\t" << moduli[1] << "\t"
             << moduli[2] << endl;
        cout << "Approximate shear moduli:\t" << moduli[3] << "\t" << moduli[4] << "\t"
             << moduli[5] << endl;

        cout << "v_yx, v_zx, v_zy:\t" << poisson[0] << "\t" << poisson[1] << "\t" << poisson[2] << endl;
        cout << "v_xy, v_xz, v_yz:\t" << poisson[3] << "\t" << poisson[4] << "\t" << poisson[5] << endl;
    }

    cout << "Anisotropy:\t" << Eh.anisotropy() << endl;

    if (args.count("fieldOutput")) {
        bool linearSubsampleFields = args.count("fullDegreeFieldOutput") == 0;
        MSHFieldWriter writer(args["fieldOutput"].as<string>(), sim.mesh(),
                              linearSubsampleFields);
        if (args.count("centerFluctuationDisplacements")) {
            for (size_t i = 0; i < w_ij.size(); ++i) {
                auto &w = w_ij[i];
                VectorND<_N> total(VectorND<_N>::Zero());
                for (size_t ii = 0; ii < w.domainSize(); ++ii) total += w(ii);
                total *= 1.0 / w.domainSize();
                for (size_t ii = 0; ii < w.domainSize(); ++ii) w(ii) -= total;
            }
        }
        for (size_t i = 0; i < w_ij.size(); ++i) {
            writer.addField("load_ij " + to_string(i), sim.dofToNodeField(sim.constantStrainLoad(-Simulator::SMatrix::CanonicalBasis(i))), DomainType::PER_NODE);
            writer.addField("w_ij " + to_string(i), w_ij[i], DomainType::PER_NODE);
            if ((Simulator::Strain::Deg == 0) || linearSubsampleFields) {
                // Output constant (average) strain when we're outputting piecewise
                // linear solutions.
                writer.addField("strain w_ij " + to_string(i),
                        sim.averageStrainField(w_ij[i]), DomainType::PER_ELEMENT);
            }
            else {
                // Output full-degree per-element strain. (Wasteful since
                // strain fields are of degree - 1, but Gmsh/MSHFieldWriter
                // only supports full-degree ElementNodeData).
                auto strainField = sim.strainField(w_ij[i]);
                typedef SymmetricMatrixInterpolant<typename Simulator::SMatrix,
                                               _N, _FEMDegree> UpsampledStrain;
                vector<UpsampledStrain> upsampledStrainField;
                upsampledStrainField.reserve(strainField.size());
                for (const auto s: strainField)
                    upsampledStrainField.emplace_back(s);
                writer.addField("strain w_ij " + to_string(i),
                                upsampledStrainField, DomainType::PER_ELEMENT);
            }
        }
    }

    if (args.count("distanceToIsotropy")) {
        auto isoFit = closestIsotropicTensor(Eh);
        cout << endl;
        cout << "(Sq Rel Frob) Distance to Isotropy:\t" << (isoFit - Eh).frobeniusNormSq() / isoFit.frobeniusNormSq() << endl;
        cout << "Closest isotropic tensor:" << endl << isoFit << endl;
        cout << endl;
    }

    if (args.count("distanceToMaterial")) {
        Materials::Constant<_N> targetMat(args.at("distanceToMaterial").as<string>());
        auto tgtE = targetMat.getTensor();
        cout << "(Sq Rel Frob) Distance to Specified Tensor:\t" << (Eh - tgtE).frobeniusNormSq() / tgtE.frobeniusNormSq() << endl;
    }

    BENCHMARK_REPORT();
}

////////////////////////////////////////////////////////////////////////////////
/*! Program entry point
//  @param[in]  argc    Number of arguments
//  @param[in]  argv    Argument strings
//  @return     status  (0 on success)
*///////////////////////////////////////////////////////////////////////////////
int main(int argc, const char *argv[])
{
    po::variables_map args = parseCmdLine(argc, argv);

    vector<MeshIO::IOVertex>  inVertices;
    vector<MeshIO::IOElement> inElements;
    string meshPath = args["mesh"].as<string>();
    auto type = load(meshPath, inVertices, inElements, MeshIO::FMT_GUESS,
                     MeshIO::MESH_GUESS);

    // Infer dimension from mesh type.
    size_t dim;
    if      (type == MeshIO::MESH_TET) dim = 3;
    else if (type == MeshIO::MESH_TRI) dim = 2;
    else    throw std::runtime_error("Mesh must be triangle or tet.");

    // Look up and run appropriate homogenizer instantiation.
    int deg = args["degree"].as<int>();
    auto exec = (dim == 3) ? ((deg == 2) ? execute<3, 2> : execute<3, 1>)
                           : ((deg == 2) ? execute<2, 2> : execute<2, 1>);

    exec(args, inVertices, inElements);

    return 0;
}

ext: cc

max_stars_repo_name: pbedenbaugh/MeshFEM

max_issues_repo_name: pbedenbaugh/MeshFEM

max_forks_repo_name: pbedenbaugh/MeshFEM


text:
#include <boost/detail/lightweight_test.hpp>
#include <boost/python.hpp>
#include <boost/date_time/gregorian/gregorian.hpp>

int main()
{
  namespace bd = boost::date_time;
  namespace bg = boost::gregorian;
  namespace python = boost::python;
  typedef bd::year_based_generator<bg::date> ybd_t;

  Py_Initialize();

  try
  {
    //extract the ppf.date_time.nth_imm_of_year class
    //object
    python::object main_module = python::import("__main__");
    python::object global(main_module.attr("__dict__"));
    python::object result =
      python::exec("from ppf.date_time import *\n", global, global);
    python::object nth_imm_of_year_class = global["nth_imm_of_year"];

    //use the class object to create instances of
    //nth_imm_of_year
    python::object first_imm_ = nth_imm_of_year_class(bg::Mar);
    python::object second_imm_ = nth_imm_of_year_class(bg::Jun);
    python::object third_imm_ = nth_imm_of_year_class(bg::Sep);
    python::object fourth_imm_ = nth_imm_of_year_class(bg::Dec);

    //get references to boost date_time year_based_generators
    //from the newly created objects
    ybd_t& first_imm =  python::extract<ybd_t&>(first_imm_);
    ybd_t& second_imm = python::extract<ybd_t&>(second_imm_);
    ybd_t& third_imm =  python::extract<ybd_t&>(third_imm_);
    ybd_t& fourth_imm = python::extract<ybd_t&>(fourth_imm_);

    //check imm dates for 2005
    BOOST_TEST(first_imm.get_date  (2005) == bg::date(2005, bg::Mar, 16));
    BOOST_TEST(second_imm.get_date (2005) == bg::date(2005, bg::Jun, 15));
    BOOST_TEST(third_imm.get_date  (2005) == bg::date(2005, bg::Sep, 21));
    BOOST_TEST(fourth_imm.get_date (2005) == bg::date(2005, bg::Dec, 21));
  }
  catch(python::error_already_set const&)
  {
    PyErr_Print();
  }
  catch(std::runtime_error const& e)
  {
    std::cerr << e.what() << std::endl;
  }
  catch(...)
  {
    std::cerr << "unexpected exception" << std::endl;
  }

  return boost::report_errors();
}

ext: cpp

max_stars_repo_name: iamaris/ppf

max_issues_repo_name: iamaris/ppf

max_forks_repo_name: iamaris/ppf


text:
/*
 * @name BookFiler Module - HTTP w/ Curl
 * @author Branden Lee
 * @version 1.00
 * @license MIT
 * @brief HTTP module for BookFiler™ applications.
 */

#ifndef BOOKFILER_MODULE_HTTP_TEMPLATE_H
#define BOOKFILER_MODULE_HTTP_TEMPLATE_H

// config
#include "config.hpp"

// C++17
#include <filesystem>
#include <fstream>
#include <functional>
#include <iostream>
#include <map>
#include <memory>
#include <string>
#include <vector>

/* boost 1.72.0
 * License: Boost Software License (similar to BSD and MIT)
 */
#include <boost/config.hpp>
#include <boost/unordered_map.hpp>

/* Mustache 4.1
 * License: Boost Software License (similar to BSD and MIT)
 */
#include <Mustache/mustache.hpp>

// Local Project
#include "Util.hpp"
#include "json.hpp"
#include <BookFiler-Module-HTTP/Interface.hpp>

/*
 * bookfiler - Template
 */
namespace bookfiler {

class TemplateImpl : public Template {
private:
  std::shared_ptr<rapidjson::Value> settingsDoc;
  kainjow::mustache::data data;
  std::string templateStr, parsedStr;

public:
  TemplateImpl();
  ~TemplateImpl();
  int setSettingsDoc(std::shared_ptr<rapidjson::Value>);
  int readFile(std::string);
  int mergeData(object);
  int mergeData(rapidjson::Document &);
  int addContext(std::string, std::string);
  int parse();
  std::string toString();
};

} // namespace bookfiler

#endif
// end BOOKFILER_MODULE_HTTP_TEMPLATE_H

max_stars_repo_name: bradosia/BookFiler-Module-HTTP-Curl

max_issues_repo_name: bradosia/BookFiler-Module-HTTP-Curl

max_forks_repo_name: bradosia/BookFiler-Module-HTTP-Curl


text:
/**
 * @file numpdesetup_main.cc
 * @brief NPDE homework NumPDESetup code
 * @author Ralf Hiptmair
 * @date 17.02.2021
 * @copyright Developed at ETH Zurich
 */

#include <Eigen/Core>
#include <iostream>

#include "numpdesetup.h"

/* SAM_LISTING_BEGIN_2 */
int main(int /*argc*/, char** /*argv*/) {
  std::cout << "Dummy \"homework problem\" for NumPDE course" << std::endl;
  Eigen::VectorXd v = NumPDESetup::dummyFunction(42.0, 10);

  const static Eigen::IOFormat CSVFormat(Eigen::FullPrecision,
                                         Eigen::DontAlignCols, ", ", "\n");
  std::cout << v.transpose().format(CSVFormat) << std::endl;
  return 0;
}
/* SAM_LISTING_END_2 */


text:
//
// Copyright (c) 2003-2013 Christopher M. Kohlhoff (chris at kohlhoff dot com)
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//

#include <fstream>
#include <algorithm>
#include <boost/asio.hpp>
#include <boost/thread.hpp>
#include <bounded_buffer.h>

#include "fps.h"
#include "monitor.h"
#include "params.h"
#include "config.h"

#include "NV_encoding.hpp"

using namespace std;
using namespace boost::asio;
using ip::tcp;

const int max_length = 1024;

LPCSTR lpSharedMemoryFileName = "FalconTexturesSharedMemoryArea";
HANDLE hMapFile;

typedef boost::shared_ptr<tcp::socket> socket_ptr;

bounded_buffer<RGBQUAD*> screenToSendQueue(2);

void copyRect(char* src, char* dest, int srcW, int x, int y, int w, int h) {
	int ws = srcW * 4;
	int wd = w * 4;
	int xd = x * 4;

	long cnt = 0;
	for (int n = 0; n < h; n++) {
		memcpy(dest + n * wd, src + (n + y) * ws + xd, wd);
	}
}

void threadCapture(int width, int height) {

	RGBQUAD* pPixels;
	FPS fps;

	hMapFile = OpenFileMapping(SECTION_MAP_READ, FALSE, lpSharedMemoryFileName);
	char* pBuf = (char*)MapViewOfFile(hMapFile, SECTION_MAP_READ, 0, 0, NULL);

	while(true){
			RGBQUAD* pixCopy = new RGBQUAD[width * height];
		//memcpy(pixCopy, pBuf + 128, width * height * sizeof(RGBQUAD));
		copyRect(pBuf + 128, (char*)pixCopy, 1200, 750, 750, 450, 450);
			screenToSendQueue.push_front(pixCopy);
		Sleep(20);
			fps.newFrame();
		}

	UnmapViewOfFile(pBuf);
	CloseHandle(hMapFile);
}

void sessionVideo(socket_ptr sock)
{
	// get the height and width of the screen
	int height = 450;
	int width = 450;

	NV_encoding nv_encoding;
	nv_encoding.load(width, height, sock, 0);

	boost::thread t(boost::bind(threadCapture, width, height));

	FPS fps;
	RGBQUAD* pPixels;
	while(true){
		screenToSendQueue.pop_back(&pPixels);
		nv_encoding.write(width, height, pPixels);
		free(pPixels);
	}
	nv_encoding.close();
}

void session(socket_ptr sock)
{
	try
	{
		sock->set_option(tcp::no_delay(true));
		char data[max_length];

		boost::system::error_code error;
		size_t length = sock->read_some(buffer(data), error);
		if (error == error::eof)
			return; // Connection closed cleanly by peer.
		else if (error)
			throw boost::system::system_error(error); // Some other error.

		if (data[0] == 'a'){
			sessionVideo(sock);
		} else {
			cout << "Received a connection with a wrong identification buffer " << string(data, length) << endl;
		}
	}
	catch (exception& e)
	{
		cerr << "Exception in thread: " << e.what() << "\n";
	}
}

void server(io_service& io_service, short port)
{
	tcp::acceptor a(io_service, tcp::endpoint(tcp::v4(), port));
	for (;;)
	{
		socket_ptr sock(new tcp::socket(io_service));
		a.accept(*sock);
		boost::thread t(boost::bind(session, sock));
	}
}

int main(int argc, const char* argv[])
{
    cout << "Version 0.99 BMS" << endl;

	//socket_ptr sock;
	//sessionVideo(sock, params.monitor, screenCoordinates); // TODO test

	try
	{
		io_service io_service;
		server(io_service, 8080);
	}
	catch (exception& e)
	{
		cerr << "Exception: " << e.what() << "\n";
	}
	return 0;
}

max_stars_repo_name: chrisi/BMS-MFD-Transfer-POC

max_issues_repo_name: chrisi/BMS-MFD-Transfer-POC

max_forks_repo_name: chrisi/BMS-MFD-Transfer-POC


text:
#include <Eigen/Core>
#include <iostream>

#include "nlmatode.h"

int main() {
  double T = 1;
  unsigned int n = 3;

  Eigen::MatrixXd Y0(n, n);
  Y0 << 1, 1, 0, 0, 3, 2, 1, 5, 2;

  Eigen::MatrixXd YT = NLMatODE::matode(Y0, T);

  std::cout << YT << std::endl << std::endl;
  Eigen::MatrixXd M0(n, n);
  M0 << 1, 1, 0, 1, 3, 1, 0, 1, 1;
  // check whether invariant is perserved or not
  bool is_invariant = NLMatODE::checkinvariant(Y0, T);
  bool is_invar_sym = NLMatODE::checkinvariant(M0, T);
  std::cout << "Test whether invariant was preserved or not..." << std::endl;

  if (is_invariant) {
    std::cout << "Invariant for Y0 preserved." << std::endl;
  } else {
    std::cout << "Invariant for Y0 NOT preserved." << std::endl;
  }
  if (is_invar_sym) {
    std::cout << "Invariant for M0 preserved." << std::endl;
  } else {
    std::cout << "Invariant for M0 NOT preserved." << std::endl;
  }

  double rate = NLMatODE::cvgDiscreteGradientMethod();
  std::cout << "\nThe fitted rate for the discrete gradient method is:\n"
            << rate << std::endl;
  return 0;
}


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

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

#include <boost/config/no_tr1/utility.hpp>
#include <boost/fusion/support/config.hpp>
#include <boost/fusion/support/detail/is_mpl_sequence.hpp>
#include <boost/fusion/support/tag_of_fwd.hpp>
#include <boost/mpl/assert.hpp>
#include <boost/mpl/bool.hpp>
#include <boost/mpl/has_xxx.hpp>
#include <boost/mpl/identity.hpp>
#include <boost/mpl/if.hpp>
#include <boost/type_traits/remove_const.hpp>
#include <boost/utility/enable_if.hpp>

namespace boost {
template <typename T, std::size_t N> class array; // forward

namespace tuples {
struct null_type;

template <class T0, class T1, class T2, class T3, class T4, class T5, class T6,
          class T7, class T8, class T9>
class tuple;

template <class Head, class Tail> struct cons;
} // namespace tuples
} // namespace boost

namespace boost {
namespace fusion {
struct non_fusion_tag;
struct mpl_sequence_tag;

namespace detail {
BOOST_MPL_HAS_XXX_TRAIT_DEF(fusion_tag)

template <typename Sequence, typename Active>
struct tag_of_impl : mpl::if_<fusion::detail::is_mpl_sequence<Sequence>,
                              mpl::identity<mpl_sequence_tag>,
                              mpl::identity<non_fusion_tag>>::type {};

template <typename Sequence>
struct tag_of_impl<Sequence, typename boost::enable_if<
                                 detail::has_fusion_tag<Sequence>>::type> {
  typedef typename Sequence::fusion_tag type;
};
} // namespace detail

namespace traits {
template <typename Sequence, typename Active>
struct tag_of : boost::fusion::detail::tag_of_impl<Sequence, Active> {};
} // namespace traits

namespace detail {
template <typename T>
struct tag_of : traits::tag_of<typename remove_const<T>::type> {};
} // namespace detail
} // namespace fusion
} // namespace boost
#endif

max_stars_repo_name: henrywarhurst/matrix

max_issues_repo_name: henrywarhurst/matrix

max_forks_repo_name: henrywarhurst/matrix


text:
#include "tut/ch3.hpp"

#include <math.h>
#include <cmath>
#include <random>
#include <ctime>
#include <iostream>
#include <chrono>

#include "boost/date_time/gregorian/gregorian.hpp"
#include <boost/log/trivial.hpp>

using namespace boost::gregorian;

namespace tut {
  namespace ch3 {
    double exe_3_01(double a, double b, double c);

    double FirstRoot(double a, double b, double c)
    {
      double r1 {(-b + sqrt(exe_3_01(a,b,c))) / (2 * a) };
      BOOST_LOG_TRIVIAL(debug) << "The first root: " << r1;
      return std::round( (r1 / 100000) * 10000000000 ) / 100000 ;
    }
    double SecondRoot(double a, double b, double c) {
      double r2 { (-b - sqrt(exe_3_01(a,b,c))) / (2 * a)};
      BOOST_LOG_TRIVIAL(debug) << "The second root: " << r2;
      return std::round( (r2 / 100000) * 10000000000 ) / 100000;
    }

    double exe_3_01(double a, double b, double c) {
      double discriminant { pow(b, 2) - (4 * a * c)};
      discriminant = std::round( (discriminant / 100000) * 10000000000 ) / 100000;
      if (discriminant > 0 ) {
          BOOST_LOG_TRIVIAL(debug) << "The equation has 2 real roots\n";
          return discriminant;
        }
      if (discriminant == 0) {
          BOOST_LOG_TRIVIAL(debug) << "The equation has one root\n";
          return discriminant;
        }
      if (discriminant < 0) {
          BOOST_LOG_TRIVIAL(debug) << "The equation has no real roots\n";
          return discriminant;
        }
      return discriminant;
    }

    void exe_3_02() {
      // Initialize our mersenne twister with a random seed based on the clock
      std::mt19937 mersenne{ static_cast<std::mt19937::result_type>(std::time(nullptr)) };
      // Create a reusable random number generator that generates uniform numbers between 1 and 6
      std::uniform_int_distribution random_number{ 1, 10 };
      int num1 {random_number(mersenne)};
      int num2 {random_number(mersenne)};
      int num3 {random_number(mersenne)};
      std::cout << "what is : " << num1 << " + " << num2 << " + " << num3 <<"\n";
      std::cout << "Enter your answer: ";
      int answer{0};
      std::cin >> answer;
      int sum{ num1 + num2 + num3 };
      if (answer == sum ) {
          std::cout << "Correct , the answer is: "<< sum <<"\n";
        } else {
          std::cout << "Incorrect , the answer is: " << sum << "\n";
        }
    }

    std::vector<double> exe_3_03(double x1, double y1, double z1, double x2, double y2,double z2) {
      double x {( ((z1*y2) - (y1*z2)) / ((x1*y2) - (y1*x2)) )};
      x = std::round( (x / 10) * 100 ) / 10;
      double y { ( ((x1*z2) - (z1*x2)) / ((x1*y2) - (y1*x1)) ) };
      y = std::round( (y / 10) * 100 ) / 10;
      std::vector<double> sol;
      double exp {x1*y2 - y1*x2};
      if (exp == 0) {
          BOOST_LOG_TRIVIAL(debug) << "The equation has no solution \n";
          BOOST_LOG_TRIVIAL(debug) << "x is : " << x << " and y is: " << y << "\n";
          sol.push_back(x);
          sol.push_back(y);
          return sol;
        } else {
          BOOST_LOG_TRIVIAL(debug) << "x is : " << x << " and y is: " << y << "\n";
          sol.push_back(x);
          sol.push_back(y);
          return sol;
        }
      return sol;
    }

    void exe_3_04() {
      // Initialize our mersenne twister with a random seed based on the clock
      std::mt19937 mersenne{ static_cast<std::mt19937::result_type>(std::time(nullptr)) };
      // Create a reusable random number generator that generates uniform numbers between 1 and 6
      std::uniform_int_distribution random_number{ 1, 12 };
      BOOST_LOG_TRIVIAL(debug) << "The english month name: " << greg_month(random_number(mersenne));
    }

    void exe_3_05() {
      std::cout << "Enter today's day[ 0 - 6]: ";
      int today;
      std::cin >> today;
      if (today > 6) {
          std::cout << "Incorrect date, enter again: ";
          std::cin >> today;
        }
      std::cout << "Enter the number of days elapsed since today[1 - 31]: ";
      int elapsed_days;
      std::cin >> elapsed_days;
      if (elapsed_days > 31) {
          std::cout << "Incorrect date, enter again: ";
          std::cin >> elapsed_days;
        }
      days future_day{ days{today} + days {elapsed_days} };
      /// todo:: solution incomplete.
      std::cout << "Today is " << greg_weekday(today) << " and the future day is: "<< future_day.days() <<std::endl;
      BOOST_LOG_TRIVIAL(warning) << " The furture date is incorrect.\n";
    }

    void exe_3_06() {
      std::cout << "Enter the weight in pounds: ";
      double weight{0.0};
      std::cin >> weight;
      std::cout << "Enter feet: ";
      double feet{0.0};
      std::cin >> feet;
      std::cout << "Enter inches: ";
      double height{0.0};
      std::cin >> height;

      constexpr double KILOGRAMS_PER_POUND = 0.45359237; // Constant
      constexpr double METERS_PER_INCH = 0.0254;

      double weightInKilograms = weight * KILOGRAMS_PER_POUND;
      double heightInMeters = height * METERS_PER_INCH;
      double bmi = weightInKilograms /
          (heightInMeters * heightInMeters);

      std::cout << "BMI is : " << bmi << std::endl;
      if (bmi < 18.5) {
          std::cout << "Underweight\n";
        } else if(bmi < 25) {
          std::cout << "Normal\n";
        } else if(bmi < 30) {
          std::cout << "Overweight\n";
        } else {
          std::cout << "Obese\n";
        }
    }

    void exe_3_07() {
      std::cout << "Enter an amount, for example 11.56:";
      double ammount;
      std::cin >> ammount;
      int remainingAmmount{ static_cast<int>(ammount * 100)};
      int numberOfDollars { static_cast<int>(remainingAmmount / 100) };
      remainingAmmount = remainingAmmount % 100;
      int numberOfQuarters = remainingAmmount / 25;
      remainingAmmount = remainingAmmount % 25;
      int numberOfDimes = remainingAmmount / 10;
      remainingAmmount = remainingAmmount % 10;
      int numberOfNickels = remainingAmmount / 5;
      remainingAmmount = remainingAmmount % 5;
      int numberOfPenies = remainingAmmount;
      std::cout << "The ammount " << ammount << std::endl;

      if (numberOfDollars > 0) {
          std::cout << "Number of dollars: " << numberOfDollars << "s\n";
        } else {
          std::cout << "Number of dollar: " << numberOfDollars << std::endl;
        }
      if (numberOfQuarters > 0) {
          std::cout << "Number of quarters: " << numberOfQuarters << "s\n";
        } else {
          std::cout << "Number of quarter: " << numberOfQuarters << std::endl;
        }
      if (numberOfDimes > 0) {
          std::cout << "Number of dimes: " << numberOfDimes << "s\n";
        } else {
          std::cout << "Number of dime: " << numberOfDimes << std::endl;
        }
      if (numberOfNickels > 0) {
          std::cout << "Number of nickels: " << numberOfNickels << "s\n";
        } else {
          std::cout << "Number of nickel: " << numberOfNickels << std::endl;
        }
      if (numberOfPenies > 0) {
          std::cout << "Number of penies: " << numberOfPenies << "s\n";
        } else {
          std::cout << "Number of penies: " << numberOfPenies << std::endl;
        }

    }

    void exe_3_08() {
      int numbers, thousands, hundreds, tens;
      std::cout << "Enter the 3 numbers: ";
      std::cin >> numbers; // 432

      tens = numbers % 10; // 2
      int hundredsAndThousands = numbers / 10; // 43
      hundreds = hundredsAndThousands % 10; // 3
      thousands = hundredsAndThousands / 10;
      BOOST_LOG_TRIVIAL(debug) << "Thousands: " << thousands << " hundreds: " << hundreds << " tens: " << tens <<"\n";
      if (thousands == hundreds && hundreds == tens
          && thousands == tens) {
          std::cout << "Numbers already sorted\n";
        }
      std::vector<int> sort; // 345 435
      int temp;
      if (hundreds < thousands || tens < thousands) // 259
        {
          if (hundreds < thousands)
            {
              temp = thousands;
              thousands = hundreds;
              hundreds = temp;
            }
          if (tens < thousands)
            {
              temp = thousands;
              thousands = tens;
              tens = temp;
            }
        }
      if (tens < hundreds)
        {
          temp = hundreds;
          hundreds = tens;
          tens = temp;
        }
      std::cout << "Sort : " << tens << " " << hundreds << " " << thousands << std::endl;
    }

    void exe_3_09()
    {
      std::cout << "Enter the first 9 digits of an ISBN: ";
      int isbn{0};
      std::cin >> isbn;
      int d9{ isbn % 10 };
      int rem {isbn / 10};
      int d8{ rem % 10 };
      rem = rem / 10;
      int d7{ rem % 10 };
      rem =rem / 10;
      int d6{rem % 10};
      rem = rem / 10;
      int d5{rem % 10};
      rem = rem / 10;
      int d4{rem % 10};
      rem = rem / 10;
      int d3{rem % 10};
      rem = rem / 10;
      int d2{ rem % 10};
      rem = rem /10;
      int d1{ rem };
      int d10{ (d1*1) + (d2*2) + (d3*3) + (d4*4) + (d5*5) + (d6*6) + (d7*7) + (d8*8) + (d9*9) };
      d10 = d10 % 11;

      std::string s{ std::to_string(isbn)};

      if (d10 == 10) {
          s.append("X");
          std::cout << "The ISBN-10 number is: "<< s << std::endl;
        } else {
          s.append(std::to_string(d10));
          std::cout << "The ISBN-10 number is: "<< s << std::endl;
        }
    }

    void exe_3_10() {
      auto seed = std::chrono::system_clock::now().time_since_epoch().count();
      auto mtgen = std::mt19937{static_cast<unsigned int>(seed) };
      auto ud = std::uniform_int_distribution<>{1, 100};
      auto number1 = ud(mtgen);
      auto number2 = ud(mtgen);
      std::cout << "What is " << number1 << " + " << number2 << "? ";
      int answer{0};
      std::cin >> answer;
      if (number1+number2 == answer) {
          std::cout << "You are correct !\n";
        } else {
          std::cout << "Your answer is wrong, "<< number1 << " + " << number2 << " should be " << number1 + number2 << std::endl;

        }
    }

    void exe_3_11() {
      std::cout << "Enter a month [1 -12]: ";
      int month{0};
      std::cin >> month;
      std::cout << "Enter a year, i,e 2022: ";
      int year;
      std::cin >> year;
      using namespace boost::gregorian;
      auto end_of_month_day = gregorian_calendar::end_of_month_day(year, month);
      std::cout << " "<< greg_month(month) << " had " << end_of_month_day << " days." << std::endl;
    }

    void exe_3_12() {
      std::cout << "Enter a three digit integer: ";
      int number;
      std::cin >> number;
      int number3 { number % 10 } ;
      int rem { rem / 10 };
      int number2{ rem % 10 };
      rem =rem / 10;
      int number1{ rem % 10 };
      if (number1 == number3) {
          std::cout << " " << number << " is a palindrome\n";
        } else {
          std::cout << number << " is not a palindrome\n";
        }

    }

    void exe_3_13() {

      // Prompt the user to enter filing status
      std::cout << "(0-single filter, 1-married jointly or " <<
                   "qualifying widow(er), 2-married separately, 3-head of " <<
                   "houshold) Enter the filing status: ";
      int status{0};
      std::cin >> status;

      // Prompt the user to enter taxable income
      std::cout << "Enter the taxable income: ";
      double income{0};
      std::cin >> income;

      // Compute tax
      double tax = 0;
      switch (status)
        {
        case 0 : // Compute tax for single filers
          tax += (income <= 8350) ? income * 0.10 : 8350 * 0.10;
          if (income > 8350)
            tax += (income <= 33950) ? (income - 8350) * 0.15 :
                                       25600 * 0.15;
          if (income > 33950)
            tax += (income <= 82250) ? (income - 33950) * 0.25 :
                                       48300 * 0.25;
          if (income > 82250)
            tax += (income <= 171550) ? (income - 82250) * 0.28 :
                                        89300 * 0.28;
          if (income > 171550)
            tax += (income <= 372950) ? (income - 171550) * 0.33 :
                                        201400 * 0.33;
          if (income > 372950)
            tax += (income - 372950) * 0.35;
          break;
        case 1 : // Compute tax for married file jointly or qualifying widow(er)
          tax += (income <= 16700) ? income * 0.10 : 16700 * 0.10;
          if (income > 16700)
            tax += (income <= 67900) ? (income - 16700) * 0.15 :
                                       (67900 - 16700) * 0.15;
          if (income > 67900)
            tax += (income <= 137050) ? (income - 67900) * 0.25 :
                                        (137050 - 67900) * 0.25;
          if (income > 137050)
            tax += (income <= 208850) ? (income - 137050) * 0.28 :
                                        (208850 - 137050) * 0.28;
          if (income > 208850)
            tax += (income <= 372950) ? (income - 208850) * 0.33 :
                                        (372950 - 208850) * 0.33;
          if (income > 372950)
            tax += (income - 372950) * 0.35;
          break;
        case 2 : // Compute tax for married separately
          tax += (income <= 8350) ? income * 0.10 : 8350 * 0.10;
          if (income > 8350)
            tax += (income <= 33950) ? (income - 8350) * 0.15 :
                                       (33950 - 8350) * 0.15;
          if (income > 33950)
            tax += (income <= 68525) ? (income - 33950) * 0.25 :
                                       (68525 - 33950) * 0.25;
          if (income > 68525)
            tax += (income <= 104425) ? (income - 68525) * 0.28 :
                                        (104425 - 68525) * 0.28;
          if (income > 104425)
            tax += (income <= 186475) ? (income - 104425) * 0.33 :
                                        (186475 - 104425) * 0.33;
          if (income > 186475)
            tax += (income - 186475) * 0.35;
          break;
        case 3 : // Compute tax for head of household
          tax += (income <= 11950) ? income * 0.10 : 11950 * 0.10;
          if (income > 11950)
            tax += (income <= 45500) ? (income - 11950) * 0.15 :
                                       (45500 - 11950) * 0.15;
          if (income > 45500)
            tax += (income <= 117450) ? (income - 45500) * 0.25 :
                                        (117450 - 45500) * 0.25;
          if (income > 117450)
            tax += (income <= 190200) ? (income - 117450) * 0.28 :
                                        (190200 - 117450) * 0.28;
          if (income > 190200)
            tax += (income <= 372950) ? (income - 190200) * 0.33 :
                                        (372950 - 190200) * 0.33;
          if (income > 372950)
            tax += (income - 372950) * 0.35;
          break;
        default : std::cout << "Error: invalid status\n";
          quick_exit(1);
        }
      // Display the result
      std::cout << "Tax is " << (int)(tax * 100) / 100.0 << std::endl;
    }

    void exe_3_14() {
      auto seed = std::chrono::system_clock::now().time_since_epoch().count();
      auto mtgen = std::mt19937{static_cast<unsigned int>(seed)};
      auto ud = std::uniform_int_distribution<>{0, 1};
      auto coin_side { ud(mtgen) };
      std::cout << "Guess the coin flip [ 0= heads, 1=Tails ]: ";
      int guess{0};
      std::cin >> guess;

      if (guess == 0 && coin_side == 0) {
          std::cout << "Correct guess, Heads\n";
        } else {
          std::cout << "Incorrect guess, Tails\n";
        }
    }

    std::string exe_3_15(int digits) {
      auto seed {std::chrono::steady_clock::now().time_since_epoch().count()};
      auto mtgen {std::mt19937{static_cast<unsigned int >(seed)}};
      auto ud {std::uniform_int_distribution<>(100, 999)};

      std::string response1{"Exact match: you win $10,000"};
      std::string response2{"Match all digits: you win $3,000"};
      std::string response3{"Match one digit: you win $1,000"};
      std::string response4{"Sorry, no match"};

      int lottery { ud(mtgen) }; // genereate the lottery number
      int lottery1{}, lottery2{}, lottery3{}, lrem{};
      lottery3 = lottery % 10;
      lrem = lottery / 10;
      lottery2 = lrem % 10;
      lottery3 = lrem / 10;

      int guess1{}, guess2{}, guess3{}, rem{};
      guess3 = digits % 10;
      rem = digits / 10;
      guess2 = rem % 10;
      guess1 = rem / 10;

      if (guess1 == lottery1 && guess2 == lottery2 && guess3 == lottery3) {
          BOOST_LOG_TRIVIAL(debug) << "Lottery: "<< lottery << " guess: "<< response1;
          return response1;
        } else if(digits == lottery) {
          BOOST_LOG_TRIVIAL(debug) << "Lottery: "<< lottery << " guess: "<< response2;
          return response2;
        } else if(guess1 == lottery1 || guess2 == lottery2 || guess3 == lottery3) {
          BOOST_LOG_TRIVIAL(debug) << "Lottery: "<< lottery << " guess: "<< response3;
          return response3;
        } else {
          BOOST_LOG_TRIVIAL(debug) << "Lottery: "<< lottery << " guess: "<< response4;
          return response4;
        }

      return response4;
    }

    void exe_3_16() {
      auto seed = std::chrono::system_clock::now().time_since_epoch().count();
      auto mtgen = std::mt19937{ static_cast<unsigned int >(seed)};
      auto ud = std::uniform_int_distribution<>(0, 100);
      auto ud1 = std::uniform_int_distribution<>(0, 200);
      int x{ ud(mtgen) }, y{ ud1(mtgen) };
      std::cout << "The random coordinate of the recatangle start: x1=" << x << " y1=" << y << std::endl;
    }

    void exe_3_17() {
      auto seed = std::chrono::system_clock::now().time_since_epoch().count();
      auto mtgen = std::mt19937{static_cast<unsigned int >(seed)};
      auto ud = std::uniform_int_distribution(1,2);
      int guess = ud(mtgen);

      std::cout << "scissor (0), rock (1), paper (2): ";
      int ans{};
      std::cin >> ans;

      if (ans == 1 && guess == 0) {
          std::cout << "The computer is scissor. You are rock. You won\n";
        }
      if (ans == 1 && guess == 1) {
          std::cout << "The computer is rock. You are rock too. It is a draw\n";
        }
      if (ans == 0 && guess == 2){
          std::cout << "The computer is paper. You are scissor. You won\n";
        }
      if(ans == 0 && guess == 0) {
          std::cout << "The computer is scissor. You are scissor too. It is a draw.\n";
        }
      if (ans == 2 && guess == 1) {
          std::cout << "The computer is rock. You are paper. You win\n.";
        }
      if (ans == 2 && guess == 2) {
          std::cout << "The computer is paper. You are paper. It is a draw\n";
        }
    }

    double exe_3_18(int x1, int y1, int x2, int y2, int x3, int y3)
    {
      if (x1 + y1 > x3 && x3 + y3 > x2 + y2 ||
          (x1 + y1 > x2 + y2 && x3 + y3 > x2 + y2) ||
          (x3 + y3 > x1 + y1 && x2 + y2 > x1 + y1)) {
          std::cout << "The input is valid \n";
        } else {
          std::cout << "The inputs are invalid!\n";
          std::exit(0);
        }
      double perimeter{0.0};
      double l1 = sqrt(pow((x2-x1), 2) + pow(y2-y1, 2));
      double l2 = sqrt(pow(x3 - x2, 2) + pow(y3 -y2, 2));
      double l3 = sqrt(pow(x3 - x1, 2) + pow(y3 -y1, 2));
      std::cout << " The perimeter is: " << l1 + l2 + l3;
      perimeter = l1 + l2 + l3;
      return std::round(perimeter * 1000) / 1000.0;
    }

    void exe_3_20()
    {
      // Prompt the user to enter a temperature and a wind speed
      std::cout << "Enter the temperature in Fahrenheit "
                   "between -58F and 41F: ";
      double temperature{0.0};
      std::cin >> temperature;
      std::cout << "Enter the wind speed (>= 2) in miles per hour: ";
      double speed{0.0};
      std::cin >> speed;

      if (temperature <= -58 || temperature >= 41 || speed < 2)
        {
          std::cout << "The ";
          if (temperature <= -58 || temperature >= 41)
            std::cout << "temperature ";
          if ((temperature <= -58 || temperature >= 41) && speed < 2)
            std::cout << "and ";
          if (speed < 2)
            std::cout << "wind speed ";
          std::cout << "is invalid";
          std::exit(1);
        }

      // Compute the wind chill index
      double windChill = 35.74 + 0.6215 * temperature -
          35.75 * pow(speed, 0.16) +
          0.4275 * temperature * pow(speed, 0.16);

      // Display result
      std::cout << "The wind chill index is " << windChill;
    }

    int exe_3_21(int k, int m, int q)
    {
      int h{0};
      int j = (k / 100 );
      k = k % 100;

      if (m <= 0 || m > 12) {
          std::cerr << "Month is out of range [ 1 - 12]\n";
          std::exit(EXIT_FAILURE);
        }
      if(q <=0 || q > 31) {
          std::cerr << "Day of the month is out of range[ 1 - 31]\n";
          std::exit(EXIT_FAILURE);
        }

      if (m == 1 || m == 2)
        {
          m = (m == 1) ? 13 : 14;
          k--;
        }

      h = ( q + ( (26 * (m + 1)) / 10 ) + k +  (k / 4) + (j / 4) + 5 * j ) % 7;
      return h;
    }

    bool exe_3_22(double x, double y)
    {
      double d{ sqrt(pow(x - 0.0, 2) + pow(y - 0.0, 2) ) };
      if ( d <= 10.0)
        return true; /// the point is in the circle
      return false;
    }

    bool exe_3_23(double x, double y)
    {
      if (sqrt(pow(x, 2) + pow(y, 2)) <= (10 / 5) || sqrt(pow(y, 2)) <=(5.0 / 2) )
        return true;
      return false;
    }

    void exe_3_24()
    {
      long seed = std::chrono::system_clock::now().time_since_epoch().count();
      auto mtgen = std::mt19937{ static_cast<unsigned int>(seed) };
      auto ud = std::uniform_int_distribution(1, 13);
      int rank = ud(mtgen);
      auto ud_1_4 = std::uniform_int_distribution(1, 4);
      int suit = ud_1_4(mtgen);

      std::cout << "The card picked from 52 card deck ";
      switch (rank) {
        case 1:
          std::cout << "Ace";
          break;
        case 2:
          std::cout << rank;
          break;
        case 3:
          std::cout << rank;
          break;
        case 4:
          std::cout << rank;
          break;
        case 5:
          std::cout << rank;
          break;
        case 6:
          std::cout << rank;
          break;
        case 7:
          std::cout << rank;
          break;
        case 8:
          std::cout << rank;
          break;
        case 9:
          std::cout << rank;
          break;
        case 10:
          std::cout << rank;
          break;
        case 11:
          std::cout << "Jack";
          break;
        case 12:
          std::cout << "Queen";
          break;
        case 13:
          std::cout << "King";
          break;

        }

      std::cout << " of ";
      switch(suit) {
        case 0:
          std::cout << "clubs\n";
          break;
        case 1:
          std::cout << "diamonds\n";
          break;
        case 2:
          std::cout << "hearts\n";
          break;
        case 3:
          std::cout << "spades\n";
          break;

        }
    }

    void exe_3_25(int x1, int y1, int x2, int y2, int x3, int y3, int x4, int y4)
    {
      // Calculate the intersecting point
      // Get a, b, c, d, e, f
      double a = y1 - y2;
      double b = -1 * (x1 - x2);
      double c = y3 - y4;
      double d = -1 * (x3 - x4);
      double e = (y1 - y2) * x1 - (x1 - x2) * y1;
      double f = (y3 - y4) * x3 - (x3 - x4) * y3;

      // Display results
      if (a * d - b * c == 0)
        {
          std::cout << "The two lines are parallel.\n";
        }
      else
        {
          double x = (e * d - b * f) / (a * d - b * c);
          double y = (a * f - e * c) / (a * d - b * c);
          std::cout << "The intersecting point is at (" << x << ", " << y << ") \n";
        }
    }

    void exe_3_26()
    {
      std::cout << "Enter an interger: ";
      int number{};
      std::cin >> number;
      // Determine whether it is divisible by 5 and 6
      // Display results
      std::cout << "Is 10 divisible by 5 and 6? " <<
                   ((number % 5 == 0) && (number % 6 == 0)) << std::endl;
      std::cout << "Is 10 divisible by 5 or 6? " <<
                   ((number % 5 == 0) || (number % 6 == 0)) << std::endl;
      std::cout << "Is 10 divisible by 5 of 6, but not both? " <<
                   ((number % 5 == 0) ^ (number % 6 == 0)) << std::endl;
    }

    void exe_3_27()
    {
      std::cout << "Enter a point's x- and y- coordinates: ";
      double x{}, y{};
      std::cin >> x >> y;
      // Determine whether the point is inside the triangle
      // getting the point of ina line that starts at point

      // Get the intersecting point with the hypotenuse side of the triangle
      // of a line that starts and points (0, 0) and touches the user points
      double intersectx = (-x * (200 * 100)) / (-y * 200 - x * 100);
      double intersecty = (-y * (200 * 100)) / (-y * 200 - x * 100);

      // Display results
      std::cout << "The point " << ((x > intersectx || y > intersecty)
                                    ? "is not " : "is " ) << " in the triangle. " << std::endl;
    }

  }
}


text:
// test_maximum.cpp
// (c) Tivole

#include <boost/test/unit_test.hpp>
#include "../src/numerary.hpp"

namespace numerary
{

    BOOST_AUTO_TEST_SUITE(TestMaximum)

    BOOST_AUTO_TEST_CASE(test_maximum_bisection)
    {
        const double eps = 1.e-9;
        double answer;
        double expected_answer;
        short int result;
        short int expected_result;

        // Testing sin function
        expected_result = 1;
        expected_answer = M_PI_2;
        result = Numerary::maximum(sin, -3, 3, &answer, "bisection", eps);
        BOOST_CHECK_EQUAL(result, expected_result);
        BOOST_CHECK(fabs(answer - expected_answer) < 1.e-7);

	    // Testing log function
        expected_result = 1;
        expected_answer = 4.0;
        result = Numerary::maximum(log, 0.5, 4, &answer, "bisection", eps);
        BOOST_CHECK_EQUAL(result, expected_result);
        BOOST_CHECK(fabs(answer - expected_answer) < 1.e-7);
    }

    BOOST_AUTO_TEST_CASE(test_maximum_golden_ratio)
    {
        const double eps = 1.e-9;
        double answer;
        double expected_answer;
        short int result;
        short int expected_result;

        // Testing sin function
        expected_result = 1;
        expected_answer = M_PI_2;
        result = Numerary::maximum(sin, -3, 3, &answer, "golden_ratio", eps);
        BOOST_CHECK_EQUAL(result, expected_result);
        BOOST_CHECK(fabs(answer - expected_answer) < 1.e-7);

	    // Testing cos function
        expected_result = 1;
        expected_answer = 4.0;
        result = Numerary::maximum(log, 0.5, 4, &answer, "golden_ratio", eps);
        BOOST_CHECK_EQUAL(result, expected_result);
        BOOST_CHECK(fabs(answer - expected_answer) < 1.e-7);
    }

    BOOST_AUTO_TEST_SUITE_END()
}

max_stars_repo_name: tivole/Numerary


text: #include <boost/hana/fwd/equal.hpp>

max_stars_repo_name: miathedev/BoostForArduino

max_issues_repo_name: miathedev/BoostForArduino

max_forks_repo_name: miathedev/BoostForArduino