text:
// =============================================================================
// Copyright 2017 National Technology & Engineering Solutions of Sandia, LLC
// (NTESS). Under the terms of Contract DE-NA0003525 with NTESS, the U.S.
// Government retains certain rights in this software.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
// =============================================================================
// Maintained by Sandia National Laboratories <Netmeld@sandia.gov>
// =============================================================================

#define BOOST_TEST_DYN_LINK
#define BOOST_TEST_MAIN

#include <typeinfo>

#include <boost/test/unit_test.hpp>

#include <netmeld/datastore/objects/IpAddress.hpp>

namespace nmdo = netmeld::datastore::objects;

class TestIpAddress : public nmdo::IpAddress {
  public:
    TestIpAddress() : IpAddress() {};
    TestIpAddress(const std::string& _ip, const std::string& _desc) :
        IpAddress(_ip, _desc) {};

  public:
    IpAddr getAddress() const
    { return address; }

    uint8_t getPrefix() const
    { return prefix; }

    bool getIsResponding() const
    { return isResponding; }

    std::string getReason() const
    { return reason; }

    double getExtraWeight() const
    { return extraWeight; }
};

BOOST_AUTO_TEST_CASE(testConstructors)
{
  {
    TestIpAddress ipAddr;

    BOOST_TEST(IpAddr() == ipAddr.getAddress());
    BOOST_TEST(UINT8_MAX == ipAddr.getPrefix());
    BOOST_TEST(false == ipAddr.getIsResponding());
    BOOST_TEST(ipAddr.getReason().empty());
    BOOST_TEST(0.0 == ipAddr.getExtraWeight());
    BOOST_TEST(ipAddr.getAliases().empty());
  }

  {
    TestIpAddress ipAddr {"10.0.0.1/24", "Some Description"};

    BOOST_TEST(IpAddr::from_string("10.0.0.1") == ipAddr.getAddress());
    BOOST_TEST(24 == ipAddr.getPrefix());
    BOOST_TEST(false == ipAddr.getIsResponding());
    BOOST_TEST("Some Description" == ipAddr.getReason());
    BOOST_TEST(0.0 == ipAddr.getExtraWeight());
    BOOST_TEST(ipAddr.getAliases().empty());
  }
}

BOOST_AUTO_TEST_CASE(testSetters)
{
  {
    TestIpAddress ipAddr;

    BOOST_TEST(!ipAddr.getIsResponding());
    ipAddr.setResponding(true);
    BOOST_TEST(ipAddr.getIsResponding());
    ipAddr.setResponding(false);
    BOOST_TEST(!ipAddr.getIsResponding());
  }

  {
    TestIpAddress ipAddr;

    ipAddr.addAlias("Alias1", "Reason1");
    BOOST_TEST(ipAddr.getAliases().count("alias1"));
    BOOST_TEST("reason1" == ipAddr.getReason());

    ipAddr.addAlias("Alias2", "Reason2");
    BOOST_TEST(ipAddr.getAliases().count("alias1"));
    BOOST_TEST(ipAddr.getAliases().count("alias2"));
    BOOST_TEST("reason2" == ipAddr.getReason());
  }
}

BOOST_AUTO_TEST_CASE(testValidity)
{
  {
    TestIpAddress ipAddr;

    BOOST_TEST(!ipAddr.isValid());

    ipAddr.setAddress("127.0.0.1");
    BOOST_TEST(!ipAddr.isValid());
    ipAddr.setAddress("::1");
    BOOST_TEST(!ipAddr.isValid());

    ipAddr.setAddress("224.0.0.0");
    BOOST_TEST(!ipAddr.isValid());
    ipAddr.setAddress("ff00::");
    BOOST_TEST(!ipAddr.isValid());

    ipAddr.setAddress("0.0.0.0");
    BOOST_TEST(!ipAddr.isValid());
    ipAddr.setAddress("::");
    BOOST_TEST(!ipAddr.isValid());
  }

  {
    TestIpAddress ipAddr;

    BOOST_TEST(!ipAddr.isValid());
    ipAddr.setAddress("1.2.3.4");
    BOOST_TEST(ipAddr.isValid());
    ipAddr.setPrefix(0);
    BOOST_TEST(ipAddr.isValid());
    ipAddr.setPrefix(31);
    BOOST_TEST(ipAddr.isValid());
    ipAddr.setPrefix(32);
    BOOST_TEST(ipAddr.isValid());
    ipAddr.setPrefix(33);
    BOOST_TEST(!ipAddr.isValid());
  }

  {
    TestIpAddress ipAddr;

    BOOST_TEST(!ipAddr.isValid());
    ipAddr.setAddress("1234::0123");
    BOOST_TEST(ipAddr.isValid());
    ipAddr.setPrefix(0);
    BOOST_TEST(ipAddr.isValid());
    ipAddr.setPrefix(127);
    BOOST_TEST(ipAddr.isValid());
    ipAddr.setPrefix(128);
    BOOST_TEST(ipAddr.isValid());
    ipAddr.setPrefix(129);
    BOOST_TEST(!ipAddr.isValid());
  }
}

BOOST_AUTO_TEST_CASE(testOperatorEquality)
{
  nmdo::IpAddress ipAddr1;
  nmdo::IpAddress ipAddr2;

  ipAddr1.setAddress("192.168.1.20");
  ipAddr1.setExtraWeight(1.0);
  ipAddr2.setAddress("192.168.1.20");
  ipAddr2.setExtraWeight(1.0);
  BOOST_TEST(ipAddr1 == ipAddr2);

  // Very small (epsilon) differences in extraWeight are treated as still equal.
  ipAddr2.setExtraWeight(1.0 - (std::numeric_limits<double>::epsilon() * 128));
  BOOST_TEST(ipAddr1 == ipAddr2);
  ipAddr2.setExtraWeight(1.0 + (std::numeric_limits<double>::epsilon() * 128));
  BOOST_TEST(ipAddr1 == ipAddr2);

  // Larger (but still small) differences in extraWeight are treated as not equal.
  ipAddr2.setExtraWeight(0.999999999);
  BOOST_TEST(!(ipAddr1 == ipAddr2));
  ipAddr2.setExtraWeight(1.000000001);
  BOOST_TEST(!(ipAddr1 == ipAddr2));
}

max_stars_repo_name: cmwill/netmeld

max_issues_repo_name: cmwill/netmeld

max_forks_repo_name: cmwill/netmeld


text:
// Copyright 2015-2019 Hans Dembinski
//
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt
// or copy at http://www.boost.org/LICENSE_1_0.txt)

#ifndef BOOST_HISTOGRAM_DETAIL_RELAXED_EQUAL_HPP
#define BOOST_HISTOGRAM_DETAIL_RELAXED_EQUAL_HPP

#include <boost/histogram/detail/priority.hpp>
#include <type_traits>

namespace boost {
namespace histogram {
namespace detail {

struct relaxed_equal {
  template <class T, class U>
  constexpr auto impl(const T& t, const U& u, priority<1>) const noexcept
      -> decltype(t == u) const {
    return t == u;
  }

  // consider T and U not equal, if there is no operator== defined for them
  template <class T, class U>
  constexpr bool impl(const T&, const U&, priority<0>) const noexcept {
    return false;
  }

  // consider two T equal if they are stateless
  template <class T>
  constexpr bool impl(const T&, const T&, priority<0>) const noexcept {
    return std::is_empty<T>::value;
  }

  template <class T, class U>
  constexpr bool operator()(const T& t, const U& u) const noexcept {
    return impl(t, u, priority<1>{});
  }
};

} // namespace detail
} // namespace histogram
} // namespace boost

#endif

ext: hpp

max_stars_repo_name: kindlychung/mediasoup-sfu-cpp

max_issues_repo_name: kindlychung/mediasoup-sfu-cpp

max_forks_repo_name: kindlychung/mediasoup-sfu-cpp


text:
/*
 * 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)
 *
 * Copyright (c) 2009 Helge Bahmann
 * Copyright (c) 2012 Tim Blechmann
 * Copyright (c) 2013 - 2020 Andrey Semashev
 */
/*!
 * \file   atomic/detail/storage_traits.hpp
 *
 * This header defines underlying types used as storage
 */

#ifndef BOOST_ATOMIC_DETAIL_STORAGE_TRAITS_HPP_INCLUDED_
#define BOOST_ATOMIC_DETAIL_STORAGE_TRAITS_HPP_INCLUDED_

#include <cstddef>
#include <boost/cstdint.hpp>
#include <boost/atomic/detail/config.hpp>
#include <boost/atomic/detail/string_ops.hpp>
#include <boost/atomic/detail/aligned_variable.hpp>
#include <boost/atomic/detail/type_traits/alignment_of.hpp>
#include <boost/atomic/detail/header.hpp>

#ifdef BOOST_HAS_PRAGMA_ONCE
#pragma once
#endif

namespace boost {
namespace atomics {
namespace detail {

template< typename T >
BOOST_FORCEINLINE void non_atomic_load(T const volatile& from, T& to) BOOST_NOEXCEPT
{
    to = from;
}

template< std::size_t Size, std::size_t Alignment = 1u >
struct BOOST_ATOMIC_DETAIL_MAY_ALIAS buffer_storage
{
    typedef unsigned char data_type[Size];
    BOOST_ATOMIC_DETAIL_ALIGNED_VAR_TPL(Alignment, data_type, data);

    BOOST_FORCEINLINE bool operator! () const BOOST_NOEXCEPT
    {
        return (data[0] == 0u && BOOST_ATOMIC_DETAIL_MEMCMP(data, data + 1, Size - 1u) == 0);
    }

    BOOST_FORCEINLINE bool operator== (buffer_storage const& that) const BOOST_NOEXCEPT
    {
        return BOOST_ATOMIC_DETAIL_MEMCMP(data, that.data, Size) == 0;
    }

    BOOST_FORCEINLINE bool operator!= (buffer_storage const& that) const BOOST_NOEXCEPT
    {
        return BOOST_ATOMIC_DETAIL_MEMCMP(data, that.data, Size) != 0;
    }
};

template< std::size_t Size, std::size_t Alignment >
BOOST_FORCEINLINE void non_atomic_load(buffer_storage< Size, Alignment > const volatile& from, buffer_storage< Size, Alignment >& to) BOOST_NOEXCEPT
{
    BOOST_ATOMIC_DETAIL_MEMCPY(to.data, const_cast< unsigned char const* >(from.data), Size);
}

template< std::size_t Size >
struct storage_traits
{
    typedef buffer_storage< Size, 1u > type;

    static BOOST_CONSTEXPR_OR_CONST std::size_t native_alignment = 1u;

    // By default, prefer the maximum supported alignment
    static BOOST_CONSTEXPR_OR_CONST std::size_t alignment = 16u;
};

template< >
struct storage_traits< 1u >
{
    typedef boost::uint8_t BOOST_ATOMIC_DETAIL_MAY_ALIAS type;

    static BOOST_CONSTEXPR_OR_CONST std::size_t native_alignment = 1u;
    static BOOST_CONSTEXPR_OR_CONST std::size_t alignment = 1u;
};

template< >
struct storage_traits< 2u >
{
    typedef boost::uint16_t BOOST_ATOMIC_DETAIL_MAY_ALIAS type;

    static BOOST_CONSTEXPR_OR_CONST std::size_t native_alignment = atomics::detail::alignment_of< boost::uint16_t >::value;
    static BOOST_CONSTEXPR_OR_CONST std::size_t alignment = 2u;
};

template< >
struct storage_traits< 4u >
{
    typedef boost::uint32_t BOOST_ATOMIC_DETAIL_MAY_ALIAS type;

    static BOOST_CONSTEXPR_OR_CONST std::size_t native_alignment = atomics::detail::alignment_of< boost::uint32_t >::value;
    static BOOST_CONSTEXPR_OR_CONST std::size_t alignment = 4u;
};

template< >
struct storage_traits< 8u >
{
    typedef boost::uint64_t BOOST_ATOMIC_DETAIL_MAY_ALIAS type;

    static BOOST_CONSTEXPR_OR_CONST std::size_t native_alignment = atomics::detail::alignment_of< boost::uint64_t >::value;
    static BOOST_CONSTEXPR_OR_CONST std::size_t alignment = 8u;
};

#if defined(BOOST_HAS_INT128)

template< >
struct storage_traits< 16u >
{
    typedef boost::uint128_type BOOST_ATOMIC_DETAIL_MAY_ALIAS type;

    static BOOST_CONSTEXPR_OR_CONST std::size_t native_alignment = atomics::detail::alignment_of< boost::uint128_type >::value;
    static BOOST_CONSTEXPR_OR_CONST std::size_t alignment = 16u;
};

#else

#if (__cplusplus >= 201103L || (defined(_MSVC_LANG) && _MSVC_LANG >= 201103L)) &&\
    (!defined(BOOST_GCC_VERSION) || BOOST_GCC_VERSION >= 40900)
using std::max_align_t;
#else

#if defined(BOOST_MSVC)
#pragma warning(push)
// alignment is sensitive to packing
#pragma warning(disable: 4121)
#endif

class max_align_helper;
union max_align_t
{
    void* ptr;
    void (*fun_ptr)();
    int max_align_helper::*mem_ptr;
    void (max_align_helper::*mem_fun_ptr)();
    long long ll;
    long double ld;
#if defined(BOOST_HAS_INT128)
    boost::int128_type i128;
#endif
#if defined(BOOST_HAS_FLOAT128)
    boost::float128_type f128;
#endif
};

#if defined(BOOST_MSVC)
#pragma warning(pop)
#endif

#endif // __cplusplus >= 201103L || (defined(_MSVC_LANG) && _MSVC_LANG >= 201103L)

template< >
struct storage_traits< 16u >
{
    typedef buffer_storage< 16u, atomics::detail::alignment_of< atomics::detail::max_align_t >::value > type;

    static BOOST_CONSTEXPR_OR_CONST std::size_t native_alignment = atomics::detail::alignment_of< atomics::detail::max_align_t >::value;
    static BOOST_CONSTEXPR_OR_CONST std::size_t alignment = 16u;
};

#endif

template< typename T >
struct storage_size_of
{
    static BOOST_CONSTEXPR_OR_CONST std::size_t size = sizeof(T);
    static BOOST_CONSTEXPR_OR_CONST std::size_t value = (size == 3u ? 4u : (size >= 5u && size <= 7u ? 8u : (size >= 9u && size <= 15u ? 16u : size)));
};

} // namespace detail
} // namespace atomics
} // namespace boost

#include <boost/atomic/detail/footer.hpp>

#endif // BOOST_ATOMIC_DETAIL_STORAGE_TRAITS_HPP_INCLUDED_


text:
#ifndef NETWORK_POSTSESSION_HPP
#define NETWORK_POSTSESSION_HPP

#include <cstdlib>

#include <iostream>
#include <deque>
#include <functional>
#include <memory>
#include <set>
#include <string>
#include <utility>

#include <boost/assert.hpp>
#include <boost/asio.hpp>
#include <boost/bind.hpp>

#include "Message.hpp"
#include "SessionManager.hpp"

namespace network{

using boost::asio::ip::tcp;

class PostSession : public Session,
                    public std::enable_shared_from_this<PostSession>
{
public:
    PostSession(tcp::socket socket_, SessionManager& manager_, std::string id_,
                std::function<void(std::stringstream&)>callback_) :
        callback(callback_), socket(std::move(socket_)), manager(manager_), read_msg(nullptr)
    {
        id = id_;
    }

    void start();
    void close();
    void send_message(const Message);

    std::function<void(std::stringstream&)> callback;

private:
    void do_read_header();
    void do_read_body();

    tcp::socket socket;
    SessionManager& manager;
    Message* read_msg;
    char msg_header[Message::header_length+1];
};

} // end of namespace network

#endif


text:
/*
@copyright Louis Dionne 2015
Distributed under the Boost Software License, Version 1.0.
(See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)
 */

#include <test/cnumeric.hpp>

#include <boost/hana/assert.hpp>
#include <boost/hana/comparable.hpp>
#include <boost/hana/core/operators.hpp>
#include <boost/hana/functional/curry.hpp>
#include <boost/hana/tuple.hpp>
#include <boost/hana/type.hpp>

#include <test/auto/base.hpp>
#include <test/injection.hpp>

// tested instances
#include <test/auto/constant.hpp>
#include <test/auto/logical.hpp>
using namespace boost::hana;

namespace boost { namespace hana { namespace test {
    template <typename T>
    auto instances<CNumeric<T>> = make<Tuple>(
        type<Constant>,
        type<Logical>
    );

    template <typename T>
    auto objects<CNumeric<T>> = make<Tuple>(
        cnumeric<T, 0>,
        cnumeric<T, 1>,
        cnumeric<T, 2>,
        cnumeric<T, 3>
    );
}}}

namespace boost { namespace hana {
    template <typename T>
    struct operators::of<test::CNumeric<T>>
        : operators::of<Logical>
    { };
}}

int main() {
    test::check_datatype<test::CNumeric<int>>();

    // Constant
    {
        // value
        {
            static_assert(value(test::cnumeric<int, 0>) == 0, "");
            static_assert(value(test::cnumeric<int, 1>) == 1, "");
        }
    }

    // Logical
    {
        struct invalid { };
        constexpr auto true_ = test::cnumeric<bool, true>;
        constexpr auto false_ = test::cnumeric<bool, false>;
        constexpr auto x = test::cnumeric<int, 1>;
        constexpr auto y = test::cnumeric<int, 2>;

        // not_
        {
            BOOST_HANA_CONSTANT_CHECK(equal(not_(true_), false_));
        }

        // and_
        {
            BOOST_HANA_CONSTANT_CHECK(equal(
                and_(true_),
                true_
            ));
            BOOST_HANA_CONSTANT_CHECK(equal(
                and_(false_),
                false_
            ));

            BOOST_HANA_CONSTANT_CHECK(equal(
                and_(true_, true_),
                true_
            ));
            BOOST_HANA_CONSTANT_CHECK(equal(
                and_(true_, false_),
                false_
            ));
            BOOST_HANA_CONSTANT_CHECK(equal(
                and_(false_, invalid{}),
                false_
            ));

            BOOST_HANA_CONSTANT_CHECK(equal(
                and_(true_, true_, true_),
                true_
            ));
            BOOST_HANA_CONSTANT_CHECK(equal(
                and_(true_, true_, false_),
                false_
            ));
            BOOST_HANA_CONSTANT_CHECK(equal(
                and_(true_, false_, invalid{}),
                false_
            ));
            BOOST_HANA_CONSTANT_CHECK(equal(
                and_(false_, invalid{}, invalid{}),
                false_
            ));
        }

        // or_
        {
            BOOST_HANA_CONSTANT_CHECK(equal(
                or_(true_),
                true_
            ));
            BOOST_HANA_CONSTANT_CHECK(equal(
                or_(false_),
                false_
            ));

            BOOST_HANA_CONSTANT_CHECK(equal(
                or_(false_, false_),
                false_
            ));
            BOOST_HANA_CONSTANT_CHECK(equal(
                or_(false_, true_),
                true_
            ));
            BOOST_HANA_CONSTANT_CHECK(equal(
                or_(true_, invalid{}),
                true_
            ));

            BOOST_HANA_CONSTANT_CHECK(equal(
                or_(false_, false_, false_),
                false_
            ));
            BOOST_HANA_CONSTANT_CHECK(equal(
                or_(false_, false_, true_),
                true_
            ));
            BOOST_HANA_CONSTANT_CHECK(equal(
                or_(false_, true_, invalid{}),
                true_
            ));
            BOOST_HANA_CONSTANT_CHECK(equal(
                or_(true_, invalid{}, invalid{}),
                true_
            ));
        }

        // if_
        {
            BOOST_HANA_CONSTANT_CHECK(equal(
                if_(true_, x, y), x
            ));

            BOOST_HANA_CONSTANT_CHECK(equal(
                if_(false_, x, y), y
            ));
        }

        // eval_if
        {
            auto t = [=](auto) { return x; };
            auto e = [=](auto) { return y; };

            BOOST_HANA_CONSTANT_CHECK(equal(
                eval_if(true_, t, invalid{}), x
            ));

            BOOST_HANA_CONSTANT_CHECK(equal(
                eval_if(false_, invalid{}, e), y
            ));
        }

        // while_
        {
            //! @todo implement this
        }

        // until
        {
            using test::x;
            auto equal_to = curry<2>(equal);

            struct { } invalid{};
            auto f = test::injection([]{});

            BOOST_HANA_CONSTANT_CHECK(equal(
                until(equal_to(x<0>), x<0>, invalid),
                x<0>
            ));

            BOOST_HANA_CONSTANT_CHECK(equal(
                until(equal_to(f(x<0>)), x<0>, f),
                f(x<0>)
            ));

            BOOST_HANA_CONSTANT_CHECK(equal(
                until(equal_to(f(f(x<0>))), x<0>, f),
                f(f(x<0>))
            ));

            BOOST_HANA_CONSTANT_CHECK(equal(
                until(equal_to(f(f(f(x<0>)))), x<0>, f),
                f(f(f(x<0>)))
            ));

            BOOST_HANA_CONSTANT_CHECK(equal(
                until(equal_to(f(f(f(f(x<0>))))), x<0>, f),
                f(f(f(f(x<0>))))
            ));

            // Make sure it can be called with an lvalue state:
            auto state = x<0>;
            BOOST_HANA_CONSTANT_CHECK(equal(
                until(equal_to(f(f(f(f(x<0>))))), state, f),
                f(f(f(f(x<0>))))
            ));
        }

        // operators
        {
            using namespace boost::hana::operators;
            BOOST_HANA_CONSTANT_CHECK(equal(
                !true_,
                not_(true_)
            ));

            BOOST_HANA_CONSTANT_CHECK(equal(
                true_ && true_,
                and_(true_, true_)
            ));

            BOOST_HANA_CONSTANT_CHECK(equal(
                false_ || false_,
                or_(false_, false_)
            ));
        }
    }
}

ext: cpp

max_stars_repo_name: josephwinston/hana

max_issues_repo_name: josephwinston/hana

max_forks_repo_name: josephwinston/hana


text:
#include "landmark.h"
#include <iostream>
#include <boost/algorithm/string.hpp>
#include <boost/lexical_cast.hpp>
#include <boost/filesystem.hpp>

cIBug::cIBug(sParams *params)
{
	m_TrainData.__dbsizes = 0;

	m_Params = params;
	m_Pictures  = 0;
	m_TrainData.__numlandmarks = 0;
	m_Identity = NULL;
}

cIBug::~cIBug()
{
	if (m_Identity) delete m_Identity;
}

void cIBug::GetMaterial()
{
	__init();
	__load();

	if (m_Params->__isflip) {
		__flip();
	}
}

void  cIBug::__init()
{
	int init_number = 0;
	if (m_Params->__landmark_type == std::string("LANDMARK_TYPE_51")){
		m_TrainData.__numlandmarks = 51;
		m_Identity = new int[51];
		init_number = 18;

		for (int i = 0; i < 51; i++){
			m_Identity[i] = init_number;
			init_number++;
		}
	}
	else if (m_Params->__landmark_type == std::string("LANDMARK_TYPE_68")){
		m_TrainData.__numlandmarks = 68;
		m_TrainData.__numlandmarks = 68;
		m_Identity = new int[68];
		init_number = 1;

		for (int i = 0; i < 68; i++){
			m_Identity[i] = init_number;
			init_number++;
		}
	}
}

void cIBug::__load()
{
	std::vector<std::string> paths_trainset(0);

	for (int i = 0; i < m_Params->__images_path.size();i++){
		try{
			std::ifstream fin(m_Params->__images_path[i]);
			if (fin.is_open()){
				while (!fin.eof()){
					std::string image_name;
					std::getline(fin, image_name);
					if (!image_name.empty()){
						paths_trainset.push_back(image_name);
					}
				}
			}
			fin.close();
		}catch (std::exception &e){
			std::cout << e.what() << std::endl;
		}
	}

	std::cout << "training set: " << paths_trainset.size() << std::endl;
	__parase(paths_trainset);
}

void cIBug::__parase(const std::vector<std::string>& paths)
{
	m_TrainData.__data.resize(paths.size());
// #pragma omp parallel for
	for (int ns = 0; ns < paths.size(); ++ns) {
		//try{
			//be sure
			std::vector<std::string> img_split;
			boost::split(img_split, paths[ns], boost::is_any_of("."));
			std::string landname = img_split[0] + std::string(".pts");
			if (!boost::filesystem::exists(paths[ns]) || !boost::filesystem::exists(landname)){
				continue;
			}

			//read images
			cv::Mat_<uchar> img = cv::imread(paths[ns], 0);

			//read groundtruths
			std::ifstream fin(landname);
			std::string line;
			std::vector<std::string>container;
			std::getline(fin, line);
			std::getline(fin, line);
			boost::split(container, line, boost::is_any_of(" "));
			int landmarks = boost::lexical_cast<int>(container[2]);
			cv::Mat_<double> land = cv::Mat::zeros(landmarks, 2, CV_64FC1);

			//get all
			int x_tl(RAND_MAX), y_tl(RAND_MAX), x_br(0), y_br(0);
			std::getline(fin, line);
			for (int i = 0; i < landmarks; i++){
				std::getline(fin, line);
				boost::split(container, line, boost::is_any_of(" "));
				land(i, 0) = (boost::lexical_cast<double>(container[0]) - 1.0);
				land(i, 1) = (boost::lexical_cast<double>(container[1]) - 1.0);
				x_tl = MIN(x_tl, land(i, 0));
				y_tl = MIN(y_tl, land(i, 1));
				x_br = MAX(x_br, land(i, 0));
				y_br = MAX(y_br, land(i, 1));
			}
			fin.close();

			cv::Rect bbox_land = cv::Rect(x_tl, y_tl, x_br - x_tl + 1, y_br - y_tl + 1);

			std::vector<cv::Rect> detectedFaces(0);
			m_Params->__facecascade.detectMultiScale(img, detectedFaces, 1.2, 2, 0, cv::Size(50, 50));
			if (detectedFaces.size() == 0) {
				detectedFaces.push_back(bbox_land);
			}
			else {
				bool is_valid = false;
				for (int i = 0; i < detectedFaces.size(); i++){
					cv::Rect bbox = detectedFaces[i];
					if (bbox.contains(cv::Point((int)land(36, 0), (int)land(36, 1))) && bbox.contains(cv::Point((int)land(45, 0), (int)land(45, 1)))
						&& bbox.contains(cv::Point((int)land(57, 0), (int)land(57, 1)))){
						is_valid = true;
						break;
					}
				}
				if (!is_valid) {
					detectedFaces.clear();
					detectedFaces.push_back(bbox_land);
				}
			}

			//cv::rectangle(img,, CV_RGB(255, 0, 0), 2);
			//cv::imshow("img", img);
			//cv::waitKey(0);

			for (int i = 0; i < detectedFaces.size(); i++){
				cv::Rect bbox = detectedFaces[i];
				if (bbox.contains(cv::Point((int)land(36, 0), (int)land(36, 1))) && bbox.contains(cv::Point((int)land(45, 0), (int)land(45, 1)))
					&& bbox.contains(cv::Point((int)land(57, 0), (int)land(57, 1)))){

					/* to save memory, we crop a roi from original image which is 2 times of face bounding box*/
					cv::Rect roi;
					__clip(bbox, roi, land, img.cols, img.rows, 2.0);
					cv::Mat img_roi(img(roi));

					// resize materials
					double ratio = MAX(1.0, double(bbox.width * bbox.height) / (200 * 200));

					cv::resize(img_roi, img_roi, cv::Size(int(img_roi.cols / ratio), int(img_roi.rows / ratio)));
					bbox = cv::Rect(bbox.x / ratio, bbox.y / ratio, bbox.width / ratio, bbox.height / ratio);
					// cv::rectangle(img_roi, bbox, 255, 2);
					m_TrainData.__data[ns].__width = img_roi.cols;
					m_TrainData.__data[ns].__height = img_roi.rows;
					m_TrainData.__data[ns].__bbox_gt = bbox;

					//get a part of points
					cv::Mat_<double> groundtruth = cv::Mat::zeros(m_TrainData.__numlandmarks, 2, CV_64FC1);
					for (int j = 0; j < m_TrainData.__numlandmarks; j++){
						int land_x = (int)(land(m_Identity[j] - 1, 0) + 0.5);
						int land_y = (int)(land(m_Identity[j] - 1, 1) + 0.5);
						groundtruth(j, 0) = (double)land_x / ratio;
						groundtruth(j, 1) = (double)land_y / ratio;
						// cv::circle(img_roi, cv::Point(groundtruth(j, 0), groundtruth(j, 1)), 2, 255);
					}

					groundtruth.copyTo(m_TrainData.__data[ns].__shape_gt);
					// std::cout << "width: [" << roi.width << "], height: [" << roi.height << "]" << std::endl;
					// cv::imshow("roi", img_roi);
					// cv::waitKey(0);

					img_roi.copyTo(m_TrainData.__data[ns].__img_gray);

					m_TrainData.__data[ns].__intermediate_shapes.resize(m_Params->__max_numstage + 1);
					m_TrainData.__data[ns].__intermediate_bboxes.resize(m_Params->__max_numstage + 1);

					break;
					// if (m_Pictures % 100 == 0)
					// std::cout << "Loaded [" << m_Pictures << "] pictures" << std::endl;
				}//end if(bbox)

			}//end for
		//}
		//catch (std::exception &e){
			//std::cout << e.what() << std::endl;
		//}
	}

	m_Pictures = paths.size();
	m_TrainData.__dbsizes = m_Pictures;
}

cv::Rect cIBug::__enlargebox(const cv::Rect &rect)
{
	cv::Rect region;
	region.x = (int)floor(rect.x - 0.5 * rect.width);
	region.y = (int)floor(rect.y - 0.5 * rect.height);
	region.width = (int)floor(float(2 * rect.width));
	region.height = (int)floor(float(2 * rect.height));
	return region;
}

void cIBug::__clip(cv::Rect& box, cv::Rect& roi, cv::Mat_<double> &land, int width, int height, double scale)
{
	roi = __enlargebox(box); // enlarge box to be 2 times of origin one

	// regularize box
	roi.x = MAX(roi.x, 0);
	roi.y = MAX(roi.y, 0);
	int right_x  = MIN(roi.width  + roi.x, width);
	int bottom_y = MIN(roi.height + roi.y, height);

	roi.width  = right_x  - roi.x;
	roi.height = bottom_y - roi.y;

	land.col(0) -= (double)roi.x;
	land.col(1) -= (double)roi.y;

	// shift face region accordingly
	box.x -= roi.x;
	box.y -= roi.y;
}

void cIBug::__flip()
{
// #pragma omp parallel for
	for (int i = 0; i < m_Pictures; i++){
		cv::Mat_<uchar> img;
		// flip image
		cv::flip(m_TrainData.__data[i].__img_gray, img, 1);

		// flip shape
		cv::Mat_<double> land = m_TrainData.__data[i].__shape_gt.clone();
		__flipshape(land, img.cols);
		/*
		for (int j = 0; j < m_TrainData.__numlandmarks; ++j) {
			cv::circle(img, cv::Point(land(j, 0), land(j, 1)), 2, 255);
			cv::imshow("flip", img);
			cv::waitKey(0);
		}
		*/
		// flip bbox
		cv::Rect bbox_flip = m_TrainData.__data[i].__bbox_gt;
		bbox_flip.x = img.cols - bbox_flip.x - bbox_flip.width;

		/*
		cv::rectangle(img, bbox_flip, 255, 2);
		cv::imshow("flip", img);
		cv::waitKey(0);
		*/

		sData data;

		data.__width = img.cols;
		data.__height = img.rows;
		data.__bbox_gt = bbox_flip;

		data.__shape_gt = land.clone();
		data.__img_gray = img.clone();

		data.__intermediate_shapes.resize(m_Params->__max_numstage + 1);
		data.__intermediate_bboxes.resize(m_Params->__max_numstage + 1);

		m_TrainData.__data.push_back(data);
	}//end for (int i=0;)
	m_TrainData.__dbsizes += m_Pictures;
}

void cIBug::__flipshape(cv::Mat_<double> &land, int width)
{
	int p = 0, q = 0;
	if (m_TrainData.__numlandmarks == 51){
		for (p = 0, q = 9; p < q; p++,q--){
			__exchange(land, p, q);
		}

		for (p = 14, q = 18; p < q; p++, q--){
			__exchange(land, p, q);
		}

		__exchange(land, 19, 28);
		__exchange(land, 20, 27);
		__exchange(land, 21, 26);
		__exchange(land, 22, 25);
		__exchange(land, 23, 30);
		__exchange(land, 24, 29);

		for (p = 31, q = 37; p < q; p++, q--){
			__exchange(land, p, q);
		}

		for (p = 38, q = 42; p < q; p++, q--){
			__exchange(land, p, q);
		}

		for (p = 43, q = 47; p < q; p++, q--){
			__exchange(land, p, q);
		}

		for (p = 48, q = 50; p < q; p++, q--){
			__exchange(land, p, q);
		}

		for (int i = 0; i < land.rows; i++){
			land(i, 0) = width - land(i, 0);
		}

	}
	else if (m_TrainData.__numlandmarks == 68) {

		// flip 1-17
		for (p = 0, q = 16; p < q; p++, q--){
			__exchange(land, p, q);
		}

		// flip eyebow
		for (p = 17, q = 26; p < q; p++, q--){
			__exchange(land, p, q);
		}

		// flip left eye
		for (p = 31, q = 35; p < q; p++, q--){
			__exchange(land, p, q);
		}

		__exchange(land, 36, 45);
		__exchange(land, 37, 44);
		__exchange(land, 38, 43);
		__exchange(land, 39, 42);

		__exchange(land, 40, 47);
		__exchange(land, 41, 46);

		for (p = 48, q = 54; p < q; p++, q--){
			__exchange(land, p, q);
		}
		for (p = 55, q = 59; p < q; p++, q--){
			__exchange(land, p, q);
		}
		for (p = 60, q = 64; p < q; p++, q--){
			__exchange(land, p, q);
		}
		for (p = 65, q = 67; p < q; p++, q--){
			__exchange(land, p, q);
		}
		for (int i = 0; i < land.rows; i++){
			land(i, 0) = width - land(i, 0);
		}
	}
}

void cIBug::__exchange(cv::Mat_<double> &land, int index1, int index2)
{
	double tmp_x = land(index1, 0);
	double tmp_y = land(index1, 1);

	land(index1, 0) = land(index2, 0);
	land(index1, 1) = land(index2, 1);

	land(index2, 0) = tmp_x;
	land(index2, 1) = tmp_y;
}

max_stars_repo_name: MichaelXin/face-alignment-cpp

max_issues_repo_name: MichaelXin/face-alignment-cpp

max_forks_repo_name: jwyang/face-alignment-cpp


text: #include <boost/graph/distributed/compressed_sparse_row_graph.hpp>

max_stars_repo_name: miathedev/BoostForArduino

max_issues_repo_name: miathedev/BoostForArduino

max_forks_repo_name: miathedev/BoostForArduino


text:
//==============================================================================
//         Copyright 2003 - 2012   LASMEA UMR 6602 CNRS/Univ. Clermont II
//         Copyright 2009 - 2012   LRI    UMR 8623 CNRS/Univ Paris Sud XI
//
//          Distributed under the Boost Software License, Version 1.0.
//                 See accompanying file LICENSE.txt or copy at
//                     http://www.boost.org/LICENSE_1_0.txt
//==============================================================================
#ifndef BOOST_SIMD_SDK_SIMD_EXTENSIONS_HPP_INCLUDED
#define BOOST_SIMD_SDK_SIMD_EXTENSIONS_HPP_INCLUDED

////////////////////////////////////////////////////////////////////////////////
// Regular SIMD extensions
////////////////////////////////////////////////////////////////////////////////
#if !defined(BOOST_SIMD_DISABLE_SIMD) && !defined(NVCC)
#include <boost/simd/sdk/simd/extensions/extensions.hpp>
#endif

#include <boost/simd/sdk/simd/extensions/common/common.hpp>
#include <boost/simd/sdk/simd/extensions/meta/tags.hpp>

#include <boost/dispatch/functor/forward.hpp>

BOOST_DISPATCH_COMBINE_SITE( BOOST_SIMD_DEFAULT_SITE )

#endif


text:
/*
 * openRatSLAM
 *
 * utils - General purpose utility helper functions mainly for angles and readings settings
 *
 * Copyright (C) 2012
 * David Ball (david.ball@qut.edu.au) (1), Scott Heath (scott.heath@uqconnect.edu.au) (2)
 *
 * modify by feixiao (feixiao5566@gmail.com) 5 Aug 2015 V1.0
 * Tarsbot Xi`An
 * RatSLAM algorithm by:
 * Michael Milford (1) and Gordon Wyeth (1) ([michael.milford, gordon.wyeth]@qut.edu.au)
 *
 * 1. Queensland University of Technology, Australia
 * 2. The University of Queensland, Australia
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

#include "local_view_match.h"
#include "../utils/utils.h"

#include <stdlib.h>
#include <string.h>
#include <assert.h>
#include <iostream>
#include <iomanip>
using namespace std;
#include <boost/foreach.hpp>
#include <algorithm>

#include <stdio.h>
#include <fcntl.h>

int i_id = 0;
int myitoa(char *buf);

namespace ratslam
{
LocalViewMatch::LocalViewMatch(ptree settings)
{
  get_setting_from_ptree(VT_MIN_PATCH_NORMALISATION_STD, settings, "vt_min_patch_normalisation_std", (double)0);
  get_setting_from_ptree(VT_PATCH_NORMALISATION, settings, "vt_patch_normalise", 0);
  get_setting_from_ptree(VT_NORMALISATION, settings, "vt_normalisation", (double) 0);
  get_setting_from_ptree(VT_SHIFT_MATCH, settings, "vt_shift_match", 25);
  get_setting_from_ptree(VT_STEP_MATCH, settings, "vt_step_match", 5);
  get_setting_from_ptree(VT_PANORAMIC, settings, "vt_panoramic", 0);

  get_setting_from_ptree(VT_MATCH_THRESHOLD, settings, "vt_match_threshold", 0.00);
  get_setting_from_ptree(TEMPLATE_X_SIZE, settings, "template_x_size", 1);
  get_setting_from_ptree(TEMPLATE_Y_SIZE, settings, "template_y_size", 1);
  get_setting_from_ptree(IMAGE_VT_X_RANGE_MIN, settings, "image_crop_x_min", 0);
  get_setting_from_ptree(IMAGE_VT_X_RANGE_MAX, settings, "image_crop_x_max", -1);
  get_setting_from_ptree(IMAGE_VT_Y_RANGE_MIN, settings, "image_crop_y_min", 0);
  get_setting_from_ptree(IMAGE_VT_Y_RANGE_MAX, settings, "image_crop_y_max", -1);

  TEMPLATE_SIZE = 24;//TEMPLATE_X_SIZE * TEMPLATE_Y_SIZE;

  templates.reserve(10000);

  current_view.resize(TEMPLATE_SIZE);

  current_vt = 0;
  prev_vt = 0;
}

LocalViewMatch::~LocalViewMatch()
{

}

void LocalViewMatch::on_image(const unsigned char *view_rgb)
{
  if (view_rgb == NULL)
    return;
  this->view_rgb = view_rgb;
//  cout<<view_rgb<<endl;
  convert_view_to_view_template(true);
  prev_vt = get_current_vt();
  unsigned int vt_match_id;
  compare(vt_error, vt_match_id);
  if (vt_error <= VT_MATCH_THRESHOLD)
  {
    set_current_vt((int)vt_match_id);
//    cout << "VTM[" << setw(4) << get_current_vt()+1 << "] " << endl;
//    cout.flush();
  }
  else
  {
    vt_relative_rad = 0;
    set_current_vt(create_template());
//    cout << "VTN[" << setw(4) << get_current_vt()+1 << "] " << endl;
//    cout.flush();
  }
}
void LocalViewMatch::convert_view_to_view_template(bool grayscale)
{
  int counter = 0;
  current_view.clear();
  vector<double>(current_view).swap(current_view);
  for (int pos = 0; pos < 24; pos++)//24
  {
    current_view.push_back(view_rgb[pos]);
  }
}

// create and add a visual template to the collection
int LocalViewMatch::create_template()
{
  int n = 0, c_id = 0;
  char str_epc[25] ;
  char tagname[6] = "0";
  float x = 0.0;
  float y = 0.0;
//  int tagname = 0;

  memcpy(str_epc, view_rgb, 25);//it`s wrong
  templates.resize(templates.size() + 1);
  VisualTemplate * new_template = &(*(templates.end() - 1));
//  n = access("./src/uhf_rfid_api/config/template_config.ini", F_OK);//相对路径无法访问
//  n = access(argv[3], W_OK);
//  if(-1 == n)
//    cout<<"creat_file: "<<n<<endl;
    boost::property_tree::ptree m_pt, tag_setting;

//  c_id = templates.size() - 1;
  new_template->id = templates.size() - 1;
  double * data_ptr = &current_view[0];
  new_template->data.reserve(TEMPLATE_SIZE);
  for (int i = 0; i < TEMPLATE_SIZE; i++)
  {
    new_template->data.push_back(*(view_rgb++));
  }

//  tagname += c_id;
  i_id = templates.size() - 1;

  //tagname = myitoa(new_template->id, tagname);
 myitoa(tagname);

  read_ini(str, m_pt);
//  read_ini("/home/feixiao/catkin_ws/src/uhf_rfid_api/config/template_config.ini", m_pt);
//  tagname = templates.size() - 1;
//------------------>然后写配置文件
tag_setting.clear(); //不清除的话新的标签默认会继承上一个标签中的内容
//tag_setting.put<int>(tagename,g_id);
tag_setting.put<char*>("epc",str_epc);
tag_setting.put<int>("pos_x",x);
tag_setting.put<int>("pos_y",y);
//tag_setting.put<int>(tagename,g_id);

m_pt.put_child(tagname,tag_setting); //写入新的标签，如果标签名一样，会修改你前一个的内容，如果不一样就会在下面新加一个
write_ini(str, m_pt);
  return templates.size() - 1;
}

// compare a visual template to all the stored templates, allowing for
// slen pixel shifts in each direction
// returns the matching template and the MSE
void LocalViewMatch::compare(double &vt_err, unsigned int &vt_match_id)
{
  if (templates.size() == 0)
  {
    vt_err = DBL_MAX;
    vt_error = vt_err;
    return;
  }
  vector<double>::iterator iter = current_view.begin();
  double *data = &current_view[0];
  size_t i=0;
  double mindiff, cdiff;
  mindiff = DBL_MAX;
  vt_err = DBL_MAX;
  int min_template = 0;
  double *template_ptr;
  double *column_ptr;
  double *template_row_ptr;
  double *column_row_ptr;
  double *template_start_ptr;
  double *column_start_ptr;
  int row_size;
  int sub_row_size;
  double *column_end_ptr;
  VisualTemplate vt;
  int min_offset;

  int offset;
  double epsilon = 0.005;
	BOOST_FOREACH(vt, templates)
	{
	  int ii = 0;
    if(vt.data[ii] == data[ii])
    {
      for(int i = 0; i<24; i++)
      {
        if(vt.data[ii+i] == data[ii+i])
        {
          if(23 == i)
          {
            vt_error = 0;
            vt_match_id = vt.id;
            return;
          }
        }
        else
        {
          break;
        }
      }
    }
    vt_err = 1;
    vt_match_id = 0;
    vt_error = vt_err;
	}
}
//stop 0 ------> stop 1------>continue
void LocalViewMatch::find_my(const unsigned char *my_tag)
{
  if (templates.size() == 0)
  {
    stop = 1;
    return;
  }

  VisualTemplate vt;
  std::vector<double> find_tag;
  find_tag.clear();
  vector<double>(find_tag).swap(find_tag);
  for (int pos = 0; pos < 24; pos++)//24
  {
    find_tag.push_back(my_tag[pos]);
  }
  size_t i=0;
  int counter = 0;
  double *tagdata = &find_tag[0];
  double *data = &current_view[0];

//  BOOST_FOREACH(vt, templates)
	{
	  int ii = 0;
    if(data[ii] == tagdata[ii])
    {
      for(int i = 0; i<24; i++)
      {
        if(data[ii+i] == tagdata[ii+i])
        {
          if(23 == i)
          {
            stop = 1;
//            cout<<"find:"<<stop<<endl;
 //           cout.flush();
//            cout<<"i return "<<endl;
            return;
          }
        }
        else
        {
          stop = 0;
//          cout<<"not find:"<<stop<<endl;
//          cout.flush();
          break;
        }
      }
    }
  }
  stop = 0;
}
}

/*turn the Decimal id to a char[],don`t use itoa*/
int myitoa(char* buff)
{
	int i = 0;
  int n = 0;
  int i_g = 0;
  int i_s = 0;
  int i_b = 0;
  int i_q = 0;
  int i_w = 0;
	unsigned int checktmp = 0;
	unsigned char epcbuff[13] = {'\0'};
	unsigned char chepc = '\0';
//  把i_id变成字符串

	i_g = i_id%10;
  n = i_id/10;
  if(n>9)
  {
    i_s = n;
    n = n/10;
    if(n>9)
    {
      i_b = n;
      n = n/10;
      if(n>9)
      {
        i_q = n;
        n = n/10;
        if(n>9)
        {
          i_w = n;
          n = n/10;
        }
        else
        {
          i_w = n;
        }
      }
      else
      {
        i_q = n;
      }
    }
    else
    {
      i_b = n;
    }
  }
  else
  {
    i_s = n;
  }
  buff[0] = i_w+'0';
  buff[1] = i_q+'0';
  buff[2] = i_b+'0';
  buff[3] = i_s+'0';
  buff[4] = i_g+'0';
  buff[5] = '\0';

  return 0;
}


text:
#include "coord.h"

#include "adler32.h"
#include "composite-imp.h"
#include "float.h"

#include <boost/static_assert.hpp>

using namespace std;

class Coords {
public:
  typedef Coord T1;
  typedef Coord2 T2;
  typedef Coord4 T4;

  static Coord atan2(Coord a, Coord b) { return Coord(float(::atan2(a.toFloat(), b.toFloat()))); }
  static Coord sin(Coord a) { return cfsin(a); };
  static Coord cos(Coord a) { return cfcos(a); };

  static const Coord tPI;
};
const Coord Coords::tPI = COORDPI;

string Coord::rawstr() const {
  return StringPrintf("%08x%08x", (unsigned int)(d >> 32), (unsigned int)d);
}

Coord coordFromRawstr(const string &lhs) {
  if(lhs.size() != 16) {
    dprintf("%s\n", lhs.c_str());
    CHECK(lhs.size() == 16);
  }
  for(int i = 0; i < lhs.size(); i++)
    CHECK(isdigit(lhs[i]) || (lhs[i] >= 'a' && lhs[i] <= 'f'));
  long long dd = 0;
  for(int i = 0; i < 16; i++) {
    dd *= 16;
    if(isdigit(lhs[i]))
      dd += lhs[i] - '0';
    else
      dd += lhs[i] - 'a' + 10;
  }
  CHECK(coordExplicit(dd).rawstr() == lhs);
  return coordExplicit(dd);
}

Float2 Coord2::toFloat() const { return Float2(x.toFloat(), y.toFloat()); }
Coord2::Coord2(const Float2 &rhs) : x(rhs.x), y(rhs.y) { };
string Coord2::rawstr() const {
  return StringPrintf("%s %s", x.rawstr().c_str(), y.rawstr().c_str());
}

Float4 Coord4::toFloat() const { return Float4(sx.toFloat(), sy.toFloat(), ex.toFloat(), ey.toFloat()); }
string Coord4::rawstr() const {
  return StringPrintf("%s %s %s %s", sx.rawstr().c_str(), sy.rawstr().c_str(), ex.rawstr().c_str(), ey.rawstr().c_str());
}

Coord4::Coord4(const Float4 &rhs) : sx(rhs.sx), sy(rhs.sy), ex(rhs.ex), ey(rhs.ey) { }

/*************
 * Computational geometry
 */

Coord len(const Coord2 &in) { return Coord(len(in.toFloat())); };
Coord2 normalize(const Coord2 &in) { return imp_normalize<Coords>(in); };
Coord dot(const Coord2 &lhs, const Coord2 &rhs) { return lhs.x * rhs.x + lhs.y * rhs.y; };

Coord getAngle(const Coord2 &in) { return imp_getAngle<Coords>(in); };
Coord2 makeAngle(const Coord &in) { return imp_makeAngle<Coords>(in); };

int whichSide(const Coord4 &f4, const Coord2 &pta) { return imp_whichSide<Coords>(f4, pta); };

Coord distanceFromLine(const Coord4 &line, const Coord2 &pt) {
  Coord u = ((pt.x - line.sx) * (line.ex - line.sx) + (pt.y - line.sy) * (line.ey - line.sy)) / ((line.ex - line.sx) * (line.ex - line.sx) + (line.ey - line.sy) * (line.ey - line.sy));
  if(u < 0 || u > 1)
    return min(len(pt - Coord2(line.sx, line.sy)), len(pt - Coord2(line.ex, line.ey)));
  Coord2 ipt = Coord2(line.sx, line.sy) + Coord2(line.ex - line.sx, line.ey - line.sy) * u;
  return len(ipt - pt);
}

int inPath(const Coord2 &point, const vector<Coord2> &path) {
  return imp_inPath<Coords>(point, path);
};

bool roughInPath(const Coord2 &point, const vector<Coord2> &path, int goal) {
  int dx[] = {0, 0, 0, 1, -1, 1, 1, -1, -1};
  int dy[] = {0, 1, -1, 0, 0, 1, -1, 1, -1};
  for(int i = 0; i < 9; i++)
    if((bool)inPath(point + Coord2(dx[i], dy[i]) / 65536, path) == goal)
      return true;
  return false;
}

Coord2 getPointIn(const vector<Coord2> &path) {
  // TODO: find a point inside the polygon in a better fashion
  //GetDifferenceHandler CrashHandler(path, path);
  Coord2 pt;
  bool found = false;
  for(int j = 0; j < path.size() && !found; j++) {
    Coord2 pospt = (path[j] + path[(j + 1) % path.size()] + path[(j + 2) % path.size()]) / 3;
    if(inPath(pospt, path)) {
      pt = pospt;
      found = true;
    }
  }
  CHECK(found);
  return pt;
}

bool pathReversed(const vector<Coord2> &path) {
  return imp_pathReversed<Coords>(path);
}

int getPathRelation(const vector<Coord2> &lhs, const vector<Coord2> &rhs) {
  for(int i = 0; i < lhs.size(); i++) {
    int i2 = (i + 1) % lhs.size();
    for(int j = 0; j < rhs.size(); j++) {
      int j2 = (j + 1) % rhs.size();
      if(linelineintersect(Coord4(lhs[i], lhs[i2]), Coord4(rhs[j], rhs[j2])))
        return PR_INTERSECT;
    }
  }
  bool lir = inPath(getPointIn(lhs), rhs);
  bool ril = inPath(getPointIn(rhs), lhs);
  if(!lir && !ril) {
    return PR_SEPARATE;
  } else if(lir && !ril) {
    return PR_RHSENCLOSE;
  } else if(!lir && ril) {
    return PR_LHSENCLOSE;
  } else if(lir && ril && abs(getArea(lhs)) < abs(getArea(rhs))) {
    return PR_RHSENCLOSE;
  } else if(lir && ril && abs(getArea(lhs)) > abs(getArea(rhs))) {
    return PR_LHSENCLOSE;
  } else {
    // dammit, don't send the same two paths! we deny!
    CHECK(0);
  }
}

Coord getArea(const vector<Coord2> &are) { return imp_getArea<Coords>(are); }
Coord2 getCentroid(const vector<Coord2> &are) { return imp_getCentroid<Coords>(are); }
Coord getPerimeter(const vector<Coord2> &are) {
  Coord totperi = 0;
  for(int i = 0; i < are.size(); i++) {
    int j = (i + 1) % are.size();
    totperi += len(are[i] - are[j]);
  }
  return totperi;
}
Coord4 getBoundBox(const vector<Coord2> &are) {
  Coord4 bbox = startCBoundBox();
  for(int i = 0; i < are.size(); i++)
    addToBoundBox(&bbox, are[i]);
  CHECK(bbox.isNormalized());
  return bbox;
}

bool colinear(const Coord4 &line, const Coord2 &pt) {
  Coord koord = distanceFromLine(line, pt);
  return koord < Coord(0.00001f);
}

Coord2 reflect(const Coord2 &incoming, Coord normal) {
  return imp_reflect<Coords>(incoming, normal);
}
Coord reflect(Coord incoming, Coord normal) {
  return imp_reflect<Coords>(incoming, normal);
}

Coord ang_dist(Coord lhs, Coord rhs) {
  lhs = mod(lhs, COORDPI * 2);
  rhs = mod(rhs, COORDPI * 2);
  Coord v = abs(lhs - rhs);
  if(v > COORDPI)
    return COORDPI * 2 - v;
  else
    return v;
}
Coord ang_approach(const Coord &cur, const Coord &goal, const Coord &amount) {
  Coord jcur = mod(cur, COORDPI * 2);
  Coord jgoal = mod(goal, COORDPI * 2);
  if(abs(jcur - jgoal) > abs(jcur - (jgoal - COORDPI * 2))) {
    jgoal -= COORDPI * 2;
  } else if(abs(jcur - jgoal) > abs(jcur - (jgoal + COORDPI * 2))) {
    jgoal += COORDPI * 2;
  }
  CHECK(ang_dist(cur, goal) >= ang_dist(approach(jcur, jgoal, amount), goal));
  return approach(jcur, jgoal, amount);
}

/*************
 * Bounding box
 */

Coord4 startCBoundBox() { return imp_startBoundBox<Coords>(); };

void addToBoundBox(Coord4 *bbox, const Coord4 &rect) { return imp_addToBoundBox<Coords>(bbox, rect); };
void addToBoundBox(Coord4 *bbox, const vector<Coord2> &line) { return imp_addToBoundBox<Coords>(bbox, line); };

void expandBoundBox(Coord4 *bbox, Coord factor) { return imp_expandBoundBox<Coords>(bbox, factor); };

/*************
 * Math
 */

bool linelineintersect(const Coord4 &lhs, const Coord4 &rhs) { return imp_linelineintersect<Coords>(lhs, rhs); };
Coord linelineintersectpos(const Coord4 &lhs, const Coord4 &rhs) { return imp_linelineintersectpos<Coords>(lhs, rhs); };

Coord approach(Coord start, Coord target, Coord delta, Coord drag) {
  if(!(((start < 0) == (target < 0)) && start < target))
    delta += drag;
  return approach(start, target, delta);
}
Coord2 approach(Coord2 start, Coord2 target, Coord delta) {
  CHECK(delta >= 0);
  Coord2 diff = target - start;
  if(len(diff) <= delta)
    return target;
  return start + diff / len(diff) * delta;
}
Coord2 approach(Coord2 start, Coord2 target, Coord delta, Coord drag) {
  if(target == start)
    return target;
  if(len(start) == 0)
    return approach(start, target, delta);
  return approach(start, target, delta + drag * max(Coord(0), -dot(normalize(start), normalize(target - start))));
}

Coord2 rotate(const Coord2 &in, Coord ang) {
  return imp_rotate<Coords>(in, ang);
}

Coord mod(const Coord &a, const Coord &b) {
  if(a < Coord(0))
    return b - mod(-a, b);
  return coordExplicit(a.d % b.d);
}

Coord2 lerp(const Coord2 &lhs, const Coord2 &rhs, Coord dist) {
  return lhs + (rhs - lhs) * dist;
}
Coord2 lerp(const Coord4 &movement, Coord dist) {
  return lerp(movement.s(), movement.e(), dist);
}
Coord4 lerp(const Coord4 &lhs, const Coord4 &rhs, Coord dist) {
  return lhs + (rhs - lhs) * dist;
}

BOOST_STATIC_ASSERT(sizeof(Coord) == 8);
BOOST_STATIC_ASSERT(sizeof(Coord2) == 16);
BOOST_STATIC_ASSERT(sizeof(Coord4) == 32);

void adler(Adler32 *adl, const Coord &val) { adl->addBytes(&val, sizeof(val)); }
void adler(Adler32 *adl, const Coord2 &val) { adl->addBytes(&val, sizeof(val)); }
void adler(Adler32 *adl, const Coord4 &val) { adl->addBytes(&val, sizeof(val)); }
void adler(Adler32 *adl, const CPosInfo &val) {
  adler(adl, val.pos);
  adler(adl, val.d);
}

max_stars_repo_name: zorbathut/d-net

max_issues_repo_name: zorbathut/d-net

max_forks_repo_name: zorbathut/d-net


text:
// Andrew Naplavkov

#ifndef BARK_PROJ_NORMALIZE_HPP
#define BARK_PROJ_NORMALIZE_HPP

#include <bark/proj/detail/utility.hpp>
#include <boost/algorithm/string.hpp>

namespace bark::proj {

inline std::string normalize(std::string pj)
{
    auto impl = [](std::string pj) -> std::string {
        ctx_holder ctx{proj_context_create()};
        if (!ctx)
            return pj;
        proj_log_func(ctx.get(), nullptr, [](void*, int, const char*) {});
        pj_holder tf{proj_create(ctx.get(), pj.c_str())};
        if (!tf)
            return pj;
        return proj_pj_info(tf.get()).definition;
    };
    return boost::trim_copy(impl(std::move(pj)));
}

}  // namespace bark::proj

#endif  // BARK_PROJ_NORMALIZE_HPP

max_stars_repo_name: storm-ptr/bark

max_issues_repo_name: storm-ptr/bark

max_forks_repo_name: storm-ptr/bark


text:
/*****************************************************************************
 * array.cpp        Blitz++ Array stencilling example
 *****************************************************************************/

#include <blitz/array.h>

BZ_USING_NAMESPACE(blitz)

int main()
{
    int N = 64;

    // Create three-dimensional arrays of float
    Array<float,3> A(N,N,N), B(N,N,N);

    // Set up initial conditions: +30 C over an interior block,
    // and +22 C elsewhere
    A = 22.0;

    Range interior(N/4,3*N/4);
    A(interior,interior,interior) = 30.0;

    int numIters = 301;

    Range I(1,N-2), J(1,N-2), K(1,N-2);

#ifdef BZ_HAVE_STD
#ifdef BZ_ARRAY_SPACE_FILLING_TRAVERSAL
    generateFastTraversalOrder(TinyVector<int,2>(N-2,N-2));
#endif
#endif

    for (int i=0; i < numIters; ++i)
    {
        double c = 1/6.5;

        B(I,J,K) = c * (.5 * A(I,J,K) + A(I+1,J,K) + A(I-1,J,K)
            + A(I,J+1,K) + A(I,J-1,K) + A(I,J,K+1) + A(I,J,K-1));

        A(I,J,K) = c * (.5 * B(I,J,K) + B(I+1,J,K) + B(I-1,J,K)
            + B(I,J+1,K) + B(I,J-1,K) + B(I,J,K+1) + B(I,J,K-1));

        // Output the result along a line through the centre
        for (int j=0; j < 8; ++j)
            cout << setprecision(2) << A(N/2,N/2,j*N/8) << " ";

        cout << endl;
        cout.flush();
    }

    return 0;
}

max_stars_repo_name: fraguela/depspawn

max_issues_repo_name: MSV-Project/IBAMR

max_forks_repo_name: MSV-Project/IBAMR


text:
//
// Copyright (c) 2016-2019 Vinnie Falco (vinnie dot falco at gmail dot com)
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//
// Official repository: https://github.com/boostorg/beast
//

#ifndef BOOST_BEAST_CORE_ASYNC_BASE_HPP
#define BOOST_BEAST_CORE_ASYNC_BASE_HPP

#include <boost/beast/core/detail/config.hpp>
#include <boost/beast/core/bind_handler.hpp>
#include <boost/beast/core/detail/allocator.hpp>
#include <boost/beast/core/detail/async_base.hpp>
#include <boost/beast/core/detail/work_guard.hpp>
#include <boost/asio/associated_allocator.hpp>
#include <boost/asio/associated_executor.hpp>
#include <boost/asio/bind_executor.hpp>
#include <boost/asio/handler_alloc_hook.hpp>
#include <boost/asio/handler_continuation_hook.hpp>
#include <boost/asio/handler_invoke_hook.hpp>
#include <boost/asio/post.hpp>
#include <boost/core/exchange.hpp>
#include <boost/core/empty_value.hpp>
#include <utility>

namespace boost {
namespace beast {

/** Base class to assist writing composed operations.

    A function object submitted to intermediate initiating functions during
    a composed operation may derive from this type to inherit all of the
    boilerplate to forward the executor, allocator, and legacy customization
    points associated with the completion handler invoked at the end of the
    composed operation.

    The composed operation must be typical; that is, associated with one
    executor of an I/O object, and invoking a caller-provided completion
    handler when the operation is finished. Classes derived from
    @ref async_base will acquire these properties:

    @li Ownership of the final completion handler provided upon construction.

    @li If the final handler has an associated allocator, this allocator will
        be propagated to the composed operation subclass. Otherwise, the
        associated allocator will be the type specified in the allocator
        template parameter, or the default of `std::allocator<void>` if the
        parameter is omitted.

    @li If the final handler has an associated executor, then it will be used
        as the executor associated with the composed operation. Otherwise,
        the specified `Executor1` will be the type of executor associated
        with the composed operation.

    @li An instance of `net::executor_work_guard` for the instance of `Executor1`
        shall be maintained until either the final handler is invoked, or the
        operation base is destroyed, whichever comes first.

    @li Calls to the legacy customization points
        `asio_handler_invoke`,
        `asio_handler_allocate`,
        `asio_handler_deallocate`, and
        `asio_handler_is_continuation`,
        which use argument-dependent lookup, will be forwarded to the
        legacy customization points associated with the handler.

    @par Example

    The following code demonstrates how @ref async_base may be be used to
    assist authoring an asynchronous initiating function, by providing all of
    the boilerplate to manage the final completion handler in a way that
    maintains the allocator and executor associations:

    @code

    // Asynchronously read into a buffer until the buffer is full, or an error occurs
    template<class AsyncReadStream, class ReadHandler>
    typename net::async_result<ReadHandler, void(error_code, std::size_t)>::return_type
    async_read(AsyncReadStream& stream, net::mutable_buffer buffer, ReadHandler&& handler)
    {
        using handler_type = BOOST_ASIO_HANDLER_TYPE(ReadHandler, void(error_code, std::size_t));
        using base_type = async_base<handler_type, typename AsyncReadStream::executor_type>;

        struct op : base_type
        {
            AsyncReadStream& stream_;
            net::mutable_buffer buffer_;
            std::size_t total_bytes_transferred_;

            op(
                AsyncReadStream& stream,
                net::mutable_buffer buffer,
                handler_type& handler)
                : base_type(std::move(handler), stream.get_executor())
                , stream_(stream)
                , buffer_(buffer)
                , total_bytes_transferred_(0)
            {
                (*this)({}, 0, false); // start the operation
            }

            void operator()(error_code ec, std::size_t bytes_transferred, bool is_continuation = true)
            {
                // Adjust the count of bytes and advance our buffer
                total_bytes_transferred_ += bytes_transferred;
                buffer_ = buffer_ + bytes_transferred;

                // Keep reading until buffer is full or an error occurs
                if(! ec && buffer_.size() > 0)
                    return stream_.async_read_some(buffer_, std::move(*this));

                // Call the completion handler with the result. If `is_continuation` is
                // false, which happens on the first time through this function, then
                // `net::post` will be used to call the completion handler, otherwise
                // the completion handler will be invoked directly.

                this->complete(is_continuation, ec, total_bytes_transferred_);
            }
        };

        net::async_completion<ReadHandler, void(error_code, std::size_t)> init{handler};
        op(stream, buffer, init.completion_handler);
        return init.result.get();
    }

    @endcode

    Data members of composed operations implemented as completion handlers
    do not have stable addresses, as the composed operation object is move
    constructed upon each call to an initiating function. For most operations
    this is not a problem. For complex operations requiring stable temporary
    storage, the class @ref stable_async_base is provided which offers
    additional functionality:

    @li The free function @ref allocate_stable may be used to allocate
    one or more temporary objects associated with the composed operation.

    @li Memory for stable temporary objects is allocated using the allocator
    associated with the composed operation.

    @li Stable temporary objects are automatically destroyed, and the memory
    freed using the associated allocator, either before the final completion
    handler is invoked (a Networking requirement) or when the composed operation
    is destroyed, whichever occurs first.

    @par Temporary Storage Example

    The following example demonstrates how a composed operation may store a
    temporary object.

    @code

    @endcode

    @tparam Handler The type of the completion handler to store.
    This type must meet the requirements of CompletionHandler.

    @tparam Executor1 The type of the executor used when the handler has no
    associated executor. An instance of this type must be provided upon
    construction. The implementation will maintain an executor work guard
    and a copy of this instance.

    @tparam Allocator The allocator type to use if the handler does not
    have an associated allocator. If this parameter is omitted, then
    `std::allocator<void>` will be used. If the specified allocator is
    not default constructible, an instance of the type must be provided
    upon construction.

    @see stable_async_base
*/
template<
    class Handler,
    class Executor1,
    class Allocator = std::allocator<void>
>
class async_base
#if ! BOOST_BEAST_DOXYGEN
    : private boost::empty_value<Allocator>
#endif
{
    static_assert(
        net::is_executor<Executor1>::value || net::execution::is_executor<Executor1>::value,
        "Executor type requirements not met");

    Handler h_;
    detail::select_work_guard_t<Executor1> wg1_;

public:
    /** The type of executor associated with this object.

    If a class derived from @ref async_base is a completion
    handler, then the associated executor of the derived class will
    be this type.
*/
    using executor_type =
#if BOOST_BEAST_DOXYGEN
        __implementation_defined__;
#else
        typename
        net::associated_executor<
            Handler,
            typename detail::select_work_guard_t<Executor1>::executor_type
                >::type;
#endif

private:

    virtual
    void
    before_invoke_hook()
    {
    }

public:
    /** Constructor

        @param handler The final completion handler.
        The type of this object must meet the requirements of CompletionHandler.
        The implementation takes ownership of the handler by performing a decay-copy.

        @param ex1 The executor associated with the implied I/O object
        target of the operation. The implementation shall maintain an
        executor work guard for the lifetime of the operation, or until
        the final completion handler is invoked, whichever is shorter.

        @param alloc The allocator to be associated with objects
        derived from this class. If `Allocator` is default-constructible,
        this parameter is optional and may be omitted.
    */
#if BOOST_BEAST_DOXYGEN
    template<class Handler_>
    async_base(
        Handler&& handler,
        Executor1 const& ex1,
        Allocator const& alloc = Allocator());
#else
    template<
        class Handler_,
        class = typename std::enable_if<
            ! std::is_same<typename
                std::decay<Handler_>::type,
                async_base
            >::value>::type
    >
    async_base(
        Handler_&& handler,
        Executor1 const& ex1)
        : h_(std::forward<Handler_>(handler))
        , wg1_(detail::make_work_guard(ex1))
    {
    }

    template<class Handler_>
    async_base(
        Handler_&& handler,
        Executor1 const& ex1,
        Allocator const& alloc)
        : boost::empty_value<Allocator>(
            boost::empty_init_t{}, alloc)
        , h_(std::forward<Handler_>(handler))
        , wg1_(ex1)
    {
    }
#endif

    /// Move Constructor
    async_base(async_base&& other) = default;

    virtual ~async_base() = default;
    async_base(async_base const&) = delete;
    async_base& operator=(async_base const&) = delete;

    /** The type of allocator associated with this object.

        If a class derived from @ref async_base is a completion
        handler, then the associated allocator of the derived class will
        be this type.
    */
    using allocator_type =
        net::associated_allocator_t<Handler, Allocator>;

    /** Returns the allocator associated with this object.

        If a class derived from @ref async_base is a completion
        handler, then the object returned from this function will be used
        as the associated allocator of the derived class.
    */
    allocator_type
    get_allocator() const noexcept
    {
        return net::get_associated_allocator(h_,
            boost::empty_value<Allocator>::get());
    }

    /** Returns the executor associated with this object.

        If a class derived from @ref async_base is a completion
        handler, then the object returned from this function will be used
        as the associated executor of the derived class.
    */
    executor_type
    get_executor() const noexcept
    {
        return net::get_associated_executor(
            h_, wg1_.get_executor());
    }

    /// Returns the handler associated with this object
    Handler const&
    handler() const noexcept
    {
        return h_;
    }

    /** Returns ownership of the handler associated with this object

        This function is used to transfer ownership of the handler to
        the caller, by move-construction. After the move, the only
        valid operations on the base object are move construction and
        destruction.
    */
    Handler
    release_handler()
    {
        return std::move(h_);
    }

    /** Invoke the final completion handler, maybe using post.

        This invokes the final completion handler with the specified
        arguments forwarded. It is undefined to call either of
        @ref complete or @ref complete_now more than once.

        Any temporary objects allocated with @ref beast::allocate_stable will
        be automatically destroyed before the final completion handler
        is invoked.

        @param is_continuation If this value is `false`, then the
        handler will be submitted to the executor using `net::post`.
        Otherwise the handler will be invoked as if by calling
        @ref complete_now.

        @param args A list of optional parameters to invoke the handler
        with. The completion handler must be invocable with the parameter
        list, or else a compilation error will result.
    */
    template<class... Args>
    void
    complete(bool is_continuation, Args&&... args)
    {
        this->before_invoke_hook();
        if(! is_continuation)
        {
            auto const ex = get_executor();
            net::post(net::bind_executor(
                ex,
                beast::bind_front_handler(
                    std::move(h_),
                    std::forward<Args>(args)...)));
            wg1_.reset();
        }
        else
        {
            wg1_.reset();
            h_(std::forward<Args>(args)...);
        }
    }

    /** Invoke the final completion handler.

        This invokes the final completion handler with the specified
        arguments forwarded. It is undefined to call either of
        @ref complete or @ref complete_now more than once.

        Any temporary objects allocated with @ref beast::allocate_stable will
        be automatically destroyed before the final completion handler
        is invoked.

        @param args A list of optional parameters to invoke the handler
        with. The completion handler must be invocable with the parameter
        list, or else a compilation error will result.
    */
    template<class... Args>
    void
    complete_now(Args&&... args)
    {
        this->before_invoke_hook();
        wg1_.reset();
        h_(std::forward<Args>(args)...);
    }

#if ! BOOST_BEAST_DOXYGEN
    Handler*
    get_legacy_handler_pointer() noexcept
    {
        return std::addressof(h_);
    }
#endif
};

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

/** Base class to provide completion handler boilerplate for composed operations.

    A function object submitted to intermediate initiating functions during
    a composed operation may derive from this type to inherit all of the
    boilerplate to forward the executor, allocator, and legacy customization
    points associated with the completion handler invoked at the end of the
    composed operation.

    The composed operation must be typical; that is, associated with one
    executor of an I/O object, and invoking a caller-provided completion
    handler when the operation is finished. Classes derived from
    @ref async_base will acquire these properties:

    @li Ownership of the final completion handler provided upon construction.

    @li If the final handler has an associated allocator, this allocator will
        be propagated to the composed operation subclass. Otherwise, the
        associated allocator will be the type specified in the allocator
        template parameter, or the default of `std::allocator<void>` if the
        parameter is omitted.

    @li If the final handler has an associated executor, then it will be used
        as the executor associated with the composed operation. Otherwise,
        the specified `Executor1` will be the type of executor associated
        with the composed operation.

    @li An instance of `net::executor_work_guard` for the instance of `Executor1`
        shall be maintained until either the final handler is invoked, or the
        operation base is destroyed, whichever comes first.

    @li Calls to the legacy customization points
        `asio_handler_invoke`,
        `asio_handler_allocate`,
        `asio_handler_deallocate`, and
        `asio_handler_is_continuation`,
        which use argument-dependent lookup, will be forwarded to the
        legacy customization points associated with the handler.

    Data members of composed operations implemented as completion handlers
    do not have stable addresses, as the composed operation object is move
    constructed upon each call to an initiating function. For most operations
    this is not a problem. For complex operations requiring stable temporary
    storage, the class @ref stable_async_base is provided which offers
    additional functionality:

    @li The free function @ref beast::allocate_stable may be used to allocate
    one or more temporary objects associated with the composed operation.

    @li Memory for stable temporary objects is allocated using the allocator
    associated with the composed operation.

    @li Stable temporary objects are automatically destroyed, and the memory
    freed using the associated allocator, either before the final completion
    handler is invoked (a Networking requirement) or when the composed operation
    is destroyed, whichever occurs first.

    @par Example

    The following code demonstrates how @ref stable_async_base may be be used to
    assist authoring an asynchronous initiating function, by providing all of
    the boilerplate to manage the final completion handler in a way that maintains
    the allocator and executor associations. Furthermore, the operation shown
    allocates temporary memory using @ref beast::allocate_stable for the timer and
    message, whose addresses must not change between intermediate operations:

    @code

    // Asynchronously send a message multiple times, once per second
    template <class AsyncWriteStream, class T, class WriteHandler>
    auto async_write_messages(
        AsyncWriteStream& stream,
        T const& message,
        std::size_t repeat_count,
        WriteHandler&& handler) ->
            typename net::async_result<
                typename std::decay<WriteHandler>::type,
                void(error_code)>::return_type
    {
        using handler_type = typename net::async_completion<WriteHandler, void(error_code)>::completion_handler_type;
        using base_type = stable_async_base<handler_type, typename AsyncWriteStream::executor_type>;

        struct op : base_type, boost::asio::coroutine
        {
            // This object must have a stable address
            struct temporary_data
            {
                // Although std::string is in theory movable, most implementations
                // use a "small buffer optimization" which means that we might
                // be submitting a buffer to the write operation and then
                // moving the string, invalidating the buffer. To prevent
                // undefined behavior we store the string object itself at
                // a stable location.
                std::string const message;

                net::steady_timer timer;

                temporary_data(std::string message_, net::io_context& ctx)
                    : message(std::move(message_))
                    , timer(ctx)
                {
                }
            };

            AsyncWriteStream& stream_;
            std::size_t repeats_;
            temporary_data& data_;

            op(AsyncWriteStream& stream, std::size_t repeats, std::string message, handler_type& handler)
                : base_type(std::move(handler), stream.get_executor())
                , stream_(stream)
                , repeats_(repeats)
                , data_(allocate_stable<temporary_data>(*this, std::move(message), stream.get_executor().context()))
            {
                (*this)(); // start the operation
            }

            // Including this file provides the keywords for macro-based coroutines
            #include <boost/asio/yield.hpp>

            void operator()(error_code ec = {}, std::size_t = 0)
            {
                reenter(*this)
                {
                    // If repeats starts at 0 then we must complete immediately. But
                    // we can't call the final handler from inside the initiating
                    // function, so we post our intermediate handler first. We use
                    // net::async_write with an empty buffer instead of calling
                    // net::post to avoid an extra function template instantiation, to
                    // keep compile times lower and make the resulting executable smaller.
                    yield net::async_write(stream_, net::const_buffer{}, std::move(*this));
                    while(! ec && repeats_-- > 0)
                    {
                        // Send the string. We construct a `const_buffer` here to guarantee
                        // that we do not create an additional function template instantation
                        // of net::async_write, since we already instantiated it above for
                        // net::const_buffer.

                        yield net::async_write(stream_,
                            net::const_buffer(net::buffer(data_.message)), std::move(*this));
                        if(ec)
                            break;

                        // Set the timer and wait
                        data_.timer.expires_after(std::chrono::seconds(1));
                        yield data_.timer.async_wait(std::move(*this));
                    }
                }

                // The base class destroys the temporary data automatically,
                // before invoking the final completion handler
                this->complete_now(ec);
            }

            // Including this file undefines the macros for the coroutines
            #include <boost/asio/unyield.hpp>
        };

        net::async_completion<WriteHandler, void(error_code)> completion(handler);
        std::ostringstream os;
        os << message;
        op(stream, repeat_count, os.str(), completion.completion_handler);
        return completion.result.get();
    }

    @endcode

    @tparam Handler The type of the completion handler to store.
    This type must meet the requirements of CompletionHandler.

    @tparam Executor1 The type of the executor used when the handler has no
    associated executor. An instance of this type must be provided upon
    construction. The implementation will maintain an executor work guard
    and a copy of this instance.

    @tparam Allocator The allocator type to use if the handler does not
    have an associated allocator. If this parameter is omitted, then
    `std::allocator<void>` will be used. If the specified allocator is
    not default constructible, an instance of the type must be provided
    upon construction.

    @see allocate_stable, async_base
*/
template<
    class Handler,
    class Executor1,
    class Allocator = std::allocator<void>
>
class stable_async_base
    : public async_base<
        Handler, Executor1, Allocator>
{
    detail::stable_base* list_ = nullptr;

    void
    before_invoke_hook() override
    {
        detail::stable_base::destroy_list(list_);
    }

public:
    /** Constructor

        @param handler The final completion handler.
        The type of this object must meet the requirements of CompletionHandler.
        The implementation takes ownership of the handler by performing a decay-copy.

        @param ex1 The executor associated with the implied I/O object
        target of the operation. The implementation shall maintain an
        executor work guard for the lifetime of the operation, or until
        the final completion handler is invoked, whichever is shorter.

        @param alloc The allocator to be associated with objects
        derived from this class. If `Allocator` is default-constructible,
        this parameter is optional and may be omitted.
    */
#if BOOST_BEAST_DOXYGEN
    template<class Handler>
    stable_async_base(
        Handler&& handler,
        Executor1 const& ex1,
        Allocator const& alloc = Allocator());
#else
    template<
        class Handler_,
        class = typename std::enable_if<
            ! std::is_same<typename
                std::decay<Handler_>::type,
                stable_async_base
            >::value>::type
    >
    stable_async_base(
        Handler_&& handler,
        Executor1 const& ex1)
        : async_base<
            Handler, Executor1, Allocator>(
                std::forward<Handler_>(handler), ex1)
    {
    }

    template<class Handler_>
    stable_async_base(
        Handler_&& handler,
        Executor1 const& ex1,
        Allocator const& alloc)
        : async_base<
            Handler, Executor1, Allocator>(
                std::forward<Handler_>(handler), ex1, alloc)
    {
    }
#endif

    /// Move Constructor
    stable_async_base(stable_async_base&& other)
        : async_base<Handler, Executor1, Allocator>(
            std::move(other))
        , list_(boost::exchange(other.list_, nullptr))
    {
    }

    /** Destructor

        If the completion handler was not invoked, then any
        state objects allocated with @ref allocate_stable will
        be destroyed here.
    */
    ~stable_async_base()
    {
        detail::stable_base::destroy_list(list_);
    }

    /** Allocate a temporary object to hold operation state.

        The object will be destroyed just before the completion
        handler is invoked, or when the operation base is destroyed.
    */
    template<
        class State,
        class Handler_,
        class Executor1_,
        class Allocator_,
        class... Args>
    friend
    State&
    allocate_stable(
        stable_async_base<
            Handler_, Executor1_, Allocator_>& base,
        Args&&... args);
};

/** Allocate a temporary object to hold stable asynchronous operation state.

    The object will be destroyed just before the completion
    handler is invoked, or when the base is destroyed.

    @tparam State The type of object to allocate.

    @param base The helper to allocate from.

    @param args An optional list of parameters to forward to the
    constructor of the object being allocated.

    @see stable_async_base
*/
template<
    class State,
    class Handler,
    class Executor1,
    class Allocator,
    class... Args>
State&
allocate_stable(
    stable_async_base<
        Handler, Executor1, Allocator>& base,
    Args&&... args);

} // beast
} // boost

#include <boost/beast/core/impl/async_base.hpp>

#endif


text:
#ifndef CLP_COMPRESSION_HPP
#define CLP_COMPRESSION_HPP

// C++ standard libraries
#include <string>
#include <vector>

// Boost libraries
#include <boost/filesystem/path.hpp>

// Project headers
#include "CommandLineArguments.hpp"
#include "FileToCompress.hpp"
#include "StructuredFileToCompress.hpp"

namespace clp {
    /**
     * Compresses all given paths into an archive
     * @param command_line_args
     * @param files_to_compress
     * @param empty_directory_paths
     * @param grouped_files_to_compress
     * @param target_encoded_file_size
     * @return true if compression was successful, false otherwise
     */
    bool compress (CommandLineArguments& command_line_args, std::vector<FileToCompress>& files_to_compress,
                   const std::vector<std::string>& empty_directory_paths, std::vector<FileToCompress>& grouped_files_to_compress,
                   size_t target_encoded_file_size);

    /**
     * Reads a list of grouped files and a list of their IDs
     * @param path_prefix_to_remove
     * @param list_path Path of the list of grouped files
     * @param grouped_files
     * @return true on success, false otherwise
     */
    bool read_and_validate_grouped_file_list (const boost::filesystem::path& path_prefix_to_remove, const std::string& list_path,
                                              std::vector<FileToCompress>& grouped_files);
}

#endif // CLP_COMPRESSION_HPP

max_stars_repo_name: kirkrodrigues/clp

max_issues_repo_name: kirkrodrigues/clp

max_forks_repo_name: kirkrodrigues/clp


text:
#ifndef SERVER_API_ROUTE_PARAMETERS_PARSER_HPP
#define SERVER_API_ROUTE_PARAMETERS_PARSER_HPP

#include "engine/api/base_parameters.hpp"
#include "engine/api/tile_parameters.hpp"

#include <boost/optional/optional.hpp>

#include <type_traits>

namespace osrm
{
namespace server
{
namespace api
{

// Note: this file provides only the interface for the generic parseParameters function.
// The actual implementations for each concrete parameter type live in the cpp file.

namespace detail
{
template <typename T>
using is_parameter_t =
    std::integral_constant<bool,
                           std::is_base_of<engine::api::BaseParameters, T>::value ||
                               std::is_same<engine::api::TileParameters, T>::value>;
} // ns detail

// Starts parsing and iter and modifies it until iter == end or parsing failed
template <typename ParameterT,
          typename std::enable_if<detail::is_parameter_t<ParameterT>::value, int>::type = 0>
boost::optional<ParameterT> parseParameters(std::string::iterator &iter,
                                            const std::string::iterator end);

// Copy on purpose because we need mutability
template <typename ParameterT,
          typename std::enable_if<detail::is_parameter_t<ParameterT>::value, int>::type = 0>
boost::optional<ParameterT> parseParameters(std::string options_string)
{
    auto first = options_string.begin();
    const auto last = options_string.end();
    return parseParameters<ParameterT>(first, last);
}

} // ns api
} // ns server
} // ns osrm

#endif

max_stars_repo_name: jhermsmeier/osrm-backend

max_issues_repo_name: serarca/osrm-backend

max_forks_repo_name: serarca/osrm-backend


text:
/*
 * The MIT License (MIT)
 *
 * Copyright (c) 2018 Sylko Olzscher
 *
 */

#include "session.h"
#include <cyng/vm/domain/log_domain.h>
#include <cyng/io/serializer.h>
#include <cyng/tuple_cast.hpp>

#include <boost/uuid/random_generator.hpp>
#include <boost/uuid/nil_generator.hpp>

namespace node
{
	namespace sml
	{
		session::session(cyng::async::mux& mux
			, cyng::logging::log_ptr logger
			, status& status_word
			, cyng::store::db& config_db
			, node::ipt::master_config_t const& cfg
			, std::string const& account
			, std::string const& pwd
			, std::string manufacturer
			, std::string model
			, std::uint32_t serial
			, cyng::mac48 mac
			, bool accept_all)
		: mux_(mux)
			, logger_(logger)
			, vm_(mux.get_io_service(), boost::uuids::random_generator()())
			, parser_([this](cyng::vector_t&& prg) {
				CYNG_LOG_INFO(logger_, prg.size() << " instructions received");
				CYNG_LOG_TRACE(logger_, cyng::io::to_str(prg));
				vm_.async_run(std::move(prg));
			}, false, false)
			, core_(logger_
				, vm_
				, status_word
				, config_db
				, cfg
				, true	//	server mode
				, account
				, pwd
				, manufacturer
				, model
				, serial
				, mac
				, accept_all)	//	check credendials
		{
			//
			//	this external interface
			//
			core_.status_word_.set_ext_if_available(true);

			//
			//	register logger domain
			//
			cyng::register_logger(logger_, vm_);
			vm_.async_run(cyng::generate_invoke("log.msg.info", "log domain is running"));
		}

		std::size_t session::hash() const noexcept
		{
			return vm_.hash();
		}

		cyng::object make_session(cyng::async::mux& mux
			, cyng::logging::log_ptr logger
			, status& status_word
			, cyng::store::db& config_db
			, node::ipt::master_config_t const& cfg
			, std::string const& account
			, std::string const& pwd
			, std::string manufacturer
			, std::string model
			, std::uint32_t serial
			, cyng::mac48 mac
			, bool accept_all)
		{
			return cyng::make_object<session>(mux, logger, status_word, config_db, cfg, account, pwd, manufacturer, model, serial, mac, accept_all);
		}

	}
}

namespace cyng
{
	namespace traits
	{

#if defined(CYNG_LEGACY_MODE_ON)
		const char type_tag<node::sml::session>::name[] = "session";
#endif
	}	// traits
}

namespace std
{
	size_t hash<node::sml::session>::operator()(node::sml::session const& s) const noexcept
	{
		return s.hash();
	}

	bool equal_to<node::sml::session>::operator()(node::sml::session const& s1, node::sml::session const& s2) const noexcept
	{
		return s1.hash() == s2.hash();
	}

	bool less<node::sml::session>::operator()(node::sml::session const& s1, node::sml::session const& s2) const noexcept
	{
		return s1.hash() < s2.hash();
	}

}

max_stars_repo_name: solosTec/node

max_issues_repo_name: solosTec/node

max_forks_repo_name: solosTec/node