text:
/**
 * \copyright
 * Copyright (c) 2012-2019, OpenGeoSys Community (http://www.opengeosys.org)
 *            Distributed under a Modified BSD License.
 *              See accompanying file LICENSE.txt or
 *              http://www.opengeosys.org/project/license
 *
 */

#include "ConfigTreeUtil.h"

#include <boost/property_tree/xml_parser.hpp>
#include <logog/include/logog.hpp>

#include "Error.h"

namespace BaseLib
{

ConfigTreeTopLevel::ConfigTreeTopLevel(
        const std::string& filepath,
        const bool be_ruthless,
        ConfigTree::PTree&& ptree)
    : _ptree(std::move(ptree))
    , _ctree(_ptree, filepath,
             ConfigTree::onerror,
             be_ruthless ? ConfigTree::onerror : ConfigTree::onwarning)
{
}

ConfigTree const&
ConfigTreeTopLevel::operator*() const
{
    return _ctree;
}

ConfigTree const*
ConfigTreeTopLevel::operator->() const
{
    return &_ctree;
}

void
ConfigTreeTopLevel::checkAndInvalidate()
{
    ::BaseLib::checkAndInvalidate(_ctree);
}

ConfigTreeTopLevel
makeConfigTree(const std::string& filepath, const bool be_ruthless,
               const std::string& toplevel_tag)
{
    ConfigTree::PTree ptree;

    // note: Trimming whitespace and ignoring comments is crucial in order
    //       for our configuration tree implementation to work!
    try
    {
        read_xml(filepath, ptree,
                 boost::property_tree::xml_parser::no_comments |
                     boost::property_tree::xml_parser::trim_whitespace);
    }
    catch (boost::property_tree::xml_parser_error const& e)
    {
        OGS_FATAL("Error while parsing XML file `%s' at line %lu: %s.",
                  e.filename().c_str(), e.line(), e.message().c_str());
    }

    DBUG("Project configuration from file '%s' read.", filepath.c_str());

    if (auto child = ptree.get_child_optional(toplevel_tag)) {
        return ConfigTreeTopLevel(filepath, be_ruthless, std::move(*child));
    }
    OGS_FATAL("Tag <%s> has not been found in file `%s'.", toplevel_tag.c_str(),
              filepath.c_str());
}

}

ext: cpp

max_stars_repo_name: mjamoein/ogs

max_issues_repo_name: mjamoein/ogs

max_forks_repo_name: mjamoein/ogs


text:
//
// Copyright (C) 2013 Karol Roslaniec <llog@roslaniec.net>
//
#ifndef LINKO_LOG_SINK_IMPL_HPP
#define LINKO_LOG_SINK_IMPL_HPP

#include "log_cfg.hpp"
#include "loglevel.hpp"
#include "log_sink.hpp"
#include "spinlock.hpp"
#include <ctime>
#include <iosfwd>
#include <string>
#include <boost/atomic.hpp>
#include <boost/noncopyable.hpp>

#ifdef LINKO_LOG_MT
# if LINKO_LOG_BOOST_THREAD
#  include <boost/thread/thread.hpp>
# else
#  include <thread>
# endif
#include "mutex.hpp"
#include "condition.hpp"
#include <queue>
#include <stack>
#endif

namespace linko {

class LogTimestamp;

class LogSinkImpl : private boost::noncopyable
{
public:
    static LogSink create(const std::string &dir, const std::string &prog);

    void level (LogLevel level) { _fileLevel = level; }

    LogLevel level() const { return _fileLevel; }

    const LogLevel &level_ref() const { return _fileLevel; }

    bool silent(LogLevel level) const { return _fileLevel < level; }

    void rotate(std::time_t time);

    bool write(const char* s, size_t n);

#   ifdef LINKO_LOG_THREAD
    void start(); // Start logging thread
#   endif

    // DEPRECATED
    // bool write_direct(char lvl, const char *prefix, const char *str);

private:
    LogSinkImpl(const std::string &dir, const std::string &prog);

    ~LogSinkImpl();

    bool mx_open(const char *filename, LogLevel fileLevel = LogInfo);

    void mx_close();

    bool mx_write(const void* s, size_t n);

    bool mx_print(char lvl, const char* s);

    bool mx_print(const LogTimestamp &ts, const char* s);

    void mx_rotate(bool print_msg);

    LogLevel _fileLevel;
    std::string _dir;
    std::string _prog;
    std::time_t _time;
    struct tm _tm;
    int _fd;
    boost::atomic<unsigned> _refs;

#   ifdef LINKO_LOG_MT
    typedef linko::mutex mutex_t;
    mutex_t _mutex;
#   endif

#   ifdef LINKO_LOG_THREAD
    void run();
    void stop(); // Stop logging thread
    inline bool thr_write(const void* s, size_t n);
#   if LINKO_LOG_BOOST_THREAD
    boost::thread *_thread;
#   else
    std::thread *_thread;
#   endif
    linko::condition _cond;
    struct Buffer;
    std::queue<Buffer> _queue; // free
    volatile bool _running;
    volatile bool _terminate;
    static const unsigned FREE_SIZE = 10;
    std::stack<Buffer, std::vector<Buffer> > _free; // free
    spinlock _free_lck;
#   endif

    friend void intrusive_ptr_add_ref(LogSinkImpl *ptr);
    friend void intrusive_ptr_release(LogSinkImpl *ptr);
};

}
#endif

ext: hpp

max_stars_repo_name: Roslaniec/LLog

max_issues_repo_name: Roslaniec/LLog

max_forks_repo_name: Roslaniec/LLog


text:
// Copyright (c) 2015-2021 Daniel Cooke
// Use of this source code is governed by the MIT license that can be found in the LICENSE file.

#ifndef vcf_reader_hpp
#define vcf_reader_hpp

#include <vector>
#include <string>
#include <cstddef>
#include <memory>
#include <mutex>
#include <iterator>
#include <typeindex>
#include <utility>
#include <functional>

#include <boost/filesystem.hpp>

#include "vcf_reader_impl.hpp"

namespace octopus {

class VcfHeader;
class VcfRecord;
class GenomicRegion;
class ReferenceGenome;

class VcfReader
{
public:
    using Path = boost::filesystem::path;
    using UnpackPolicy = IVcfReaderImpl::UnpackPolicy;
    using RecordContainer = IVcfReaderImpl::RecordContainer;

    class RecordIterator;
    using RecordIteratorPair = std::pair<RecordIterator, RecordIterator>;

    VcfReader() = default;

    VcfReader(Path file_path);
    VcfReader(Path file_path, const ReferenceGenome& reference);

    VcfReader(const VcfReader&)            = delete;
    VcfReader& operator=(const VcfReader&) = delete;
    VcfReader(VcfReader&&);
    VcfReader& operator=(VcfReader&&);

    ~VcfReader() = default;

    friend void swap(VcfReader& lhs, VcfReader& rhs) noexcept;

    bool is_open() const noexcept;
    void open() noexcept;
    void close() noexcept;

    const Path& path() const noexcept;

    VcfHeader fetch_header() const;

    std::size_t count_records() const;
    std::size_t count_records(const std::string& contig) const;
    std::size_t count_records(const GenomicRegion& region) const;

    RecordContainer fetch_records(UnpackPolicy level = UnpackPolicy::all) const;
    RecordContainer fetch_records(const std::string& contig, UnpackPolicy level = UnpackPolicy::all) const;
    RecordContainer fetch_records(const GenomicRegion& region, UnpackPolicy level = UnpackPolicy::all) const;

    RecordIteratorPair iterate(UnpackPolicy level = UnpackPolicy::all) const;
    RecordIteratorPair iterate(const std::string& contig, UnpackPolicy level = UnpackPolicy::all) const;
    RecordIteratorPair iterate(const GenomicRegion& region, UnpackPolicy level = UnpackPolicy::all) const;

private:
    Path file_path_;
    std::unique_ptr<IVcfReaderImpl> reader_;

    mutable std::mutex mutex_;
};

bool operator==(const VcfReader& lhs, const VcfReader& rhs);

class VcfReader::RecordIterator
{
public:
    using iterator_category = std::input_iterator_tag;
    using value_type        = VcfRecord;
    using difference_type   = std::ptrdiff_t;
    using pointer           = VcfRecord*;
    using reference         = VcfRecord&;

    RecordIterator(IVcfReaderImpl::RecordIteratorPtr itr);

    RecordIterator(const RecordIterator&);
    RecordIterator& operator=(const RecordIterator&) = delete;
    RecordIterator(RecordIterator&&)                 = default;
    RecordIterator& operator=(RecordIterator&&)      = default;

    reference operator*() const;
    pointer operator->() const;

    RecordIterator& operator++();

    friend bool operator==(const RecordIterator& lhs, const RecordIterator& rhs);

private:
    IVcfReaderImpl::RecordIteratorPtr itr_;
    std::type_index type_;
};

bool operator!=(const VcfReader::RecordIterator& lhs, const VcfReader::RecordIterator& rhs);

} // namespace octopus

namespace std {

template <> struct hash<octopus::VcfReader>
{
    size_t operator()(const octopus::VcfReader& reader) const
    {
        return hash<string>()(reader.path().string());
    }
};

template <> struct hash<reference_wrapper<octopus::VcfReader>>
{
    size_t operator()(reference_wrapper<octopus::VcfReader> reader) const
    {
        return hash<octopus::VcfReader>()(reader);
    }
};

template <> struct hash<reference_wrapper<const octopus::VcfReader>>
{
    size_t operator()(reference_wrapper<const octopus::VcfReader> reader) const
    {
        return hash<octopus::VcfReader>()(reader);
    }
};

} // namespace std

#endif

max_stars_repo_name: Schaudge/octopus

max_issues_repo_name: Schaudge/octopus

max_forks_repo_name: Schaudge/octopus


text:
#include <set>
#include <memory>
#include <cassert>

#include <boost/iterator/iterator_facade.hpp>

namespace tiny
{

template <typename T, int S, typename TSize, typename... Args>
bool emplace(T (&data)[S], TSize& size, Args&&... args)
{
    assert(S > size);
    new (&data[size]) T{std::forward<Args>(args)...};
    for (int i = 0; i != size; ++i)
    {
        if (data[i] == data[size])
        {
            data[size].~T();
            return false;
        }
    }
    size++;
    return true;
}

template <typename T, int S>
bool contains(const T (&data)[S], uint8_t size, const T& needle)
{
    for (int i = 0; i != size; ++i)
    {
        if (data[i] == needle) { return true; }
    }
    return false;
}

template <typename T, int S, typename TSize>
void erase(T (&data)[S], TSize& size, const T& element)
{
    for (int i = 0; i != size; ++i)
    {
        if (data[i] == element)
        {
            data[i].~T();
            std::swap(data[i], data[size-1]); // TODO: what if last element is removed?
            size--;
            return;
        }
    }
}

template <
    typename T,
    typename C = std::less<T>,
    typename A = std::allocator<T>>
struct const_iterator : boost::iterator_facade<
                  const_iterator<T,C,A>, const T, boost::forward_traversal_tag>
{
    using setIt = typename std::set<T,C,A>::const_iterator;

    const_iterator(const T* it) : pointer(it) {}
    const_iterator(setIt it) : iterator(it) {}

    template <typename U>
    bool equal(const const_iterator<U,C,A>& other) const
    {
        if (pointer != nullptr)
        {
            assert(other.pointer != nullptr);
            return pointer == other.pointer;
        }
        assert(other.pointer == nullptr);
        return iterator == other.iterator;
    }

    void increment()
    {
        if (pointer != nullptr)
        {
            pointer++;
        }
        else
        {
            iterator++;
        }
    }

    const T& dereference() const
    {
        if (pointer != nullptr)
        {
            return *pointer;
        }
        return *iterator;
    }

private:
    const T* pointer = nullptr;
    setIt iterator;
};

template <
    typename T,
    typename C = std::less<T>,
    typename A = std::allocator<T>,
    int S = 4>
struct set
{
    using Self = set<T,C,A,S>;

    set()
        : m_data{T{}}
        , m_size(0)
    {
    }

    ~set()
    {
        if (is_tiny())
        {
            clean_tiny();
        }
        else
        {
            m_data.full.reset();
        }
    }

    set(const Self& other)
        : m_data{T{}}
        , m_size{0}
    {
        *this = other;
    }

    set(Self&& other)
        : m_data{T{}}
        , m_size{0}
    {
        *this = std::move(other);
    }

    Self& operator=(Self&& other)
    {
        if (other.is_tiny())
        {
            if (!is_tiny())
            {
                m_data.full.reset();
            }
            for (int i = 0; i != other.m_size; ++i)
            {
                new (&m_data.tiny[i]) T(std::move(other.m_data.tiny[i]));
            }
        }
        else
        {
            if (is_tiny())
            {
                clean_tiny();
            }
            new (&m_data.full) std::unique_ptr<std::set<T>>(
                std::move(other.m_data.full));
        }

        m_size = other.m_size;
        return *this;
    }

    Self& operator=(const Self& other)
    {
        if (other.is_tiny())
        {
            if (!is_tiny())
            {
                m_data.full.reset();
            }
            for (int i = 0; i != other.m_size; ++i)
            {
                new (&m_data.tiny[i]) T(other.m_data.tiny[i]);
            }
        }
        else
        {
            if (is_tiny())
            {
                clean_tiny();
            }
            new (&m_data.full) std::unique_ptr<std::set<T>>(
                new std::set<T>(*other.m_data.full.get()));
        }
        m_size = other.m_size;
        return *this;
    }

    const_iterator<T,C,A> begin() const
    {
        if (is_tiny())
        {
            return const_iterator<T,C,A>(&m_data.tiny[0]);
        }
        return const_iterator<T,C,A>(m_data.full->cbegin());
    }

    const_iterator<T,C,A> end() const
    {
        if (is_tiny())
        {
            return const_iterator<T,C,A>(&m_data.tiny[m_size]);
        }
        return const_iterator<T,C,A>(m_data.full->cend());
    }

    size_t size() const
    {
        if (is_tiny()) { return m_size; }
        return m_data.full->size();
    }

    template <typename... Args>
    bool emplace(Args&&... args)
    {
        if (is_tiny())
        {
            if (m_size == S)
            {
                T tmp{std::forward<Args>(args)...};
                if (contains(tmp)) { return false; }

                auto set = std::unique_ptr<std::set<T>>(new std::set<T>);
                set->insert(&m_data.tiny[0], &m_data.tiny[S]);
                const auto ret = set->emplace(std::move(tmp)).second;

                clean_tiny();

                new (&m_data.full) std::unique_ptr<std::set<T>>();
                m_data.full = std::move(set);

                m_size = -1;
                return ret;
            }
            return tiny::emplace<T, S, decltype(m_size), Args...>(m_data.tiny, m_size, std::forward<Args>(args)...);
        }
        return m_data.full->emplace(std::forward<Args>(args)...).second;
    }

    bool contains(const T& needle) const
    {
        if (is_tiny()) { return tiny::contains<T, S>(m_data.tiny, m_size, needle); }
        return m_data.full->find(needle) != m_data.full->end();
    }

    void erase(const T& element)
    {
        if (is_tiny())
        {
            tiny::erase<T, S, decltype(m_size)>(m_data.tiny, m_size, element);
            return;
        }
        m_data.full->erase(element);
    }

    void clear()
    {
        if (is_tiny())
        {
            clean_tiny();
            m_size = 0;
            return;
        }
        m_data.full->clear();
    }

    std::set<T,C,A> to_std_set() const
    {
        if (is_tiny())
        {
            std::set<T,C,A> ret{begin(), end()};
            return ret;
        }
        return *m_data.full;
    }

    bool is_tiny() const
    {
        return m_size != -1;
    }
private:

    void clean_tiny()
    {
        assert(is_tiny());
        for (int i = 0; i != m_size; ++i)
        {
            m_data.tiny[i].~T();
        }
    }

    union Data
    {
        T tiny[S];
        std::unique_ptr<std::set<T,C,A>> full;
        ~Data() {}
    };
    Data m_data;
    int8_t m_size; // >= 0 when tiny, -1 when full
};

static_assert(sizeof(set<uint32_t,std::less<uint32_t>, std::allocator<uint32_t>, 4>) < sizeof(std::set<uint32_t>), "");

}


text:
/*
 * Copyright 2009-2020 The VOTCA Development Team (http://www.votca.org)
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */

#include <boost/test/tools/old/interface.hpp>
#include <stdexcept>
#define BOOST_TEST_MAIN

#define BOOST_TEST_MODULE name_test

// Standard includes
#include <exception>
#include <string>

// Third party includes
#include <boost/test/unit_test.hpp>

// Local VOTCA includes
#include "votca/tools/objectfactory.h"

using namespace std;
using namespace votca::tools;

BOOST_AUTO_TEST_SUITE(objectfactory_test)

class base {

 public:
  base() = default;
  virtual ~base() = default;

  virtual std::string identify() = 0;
};

class A : public base {
 public:
  std::string identify() override { return "A"; }
};

class B : public base {
 public:
  std::string identify() override { return "B"; }
};

BOOST_AUTO_TEST_CASE(construction_test) {

  ObjectFactory<std::string, base> factory;

  factory.Register<A>("A");
  factory.Register<B>("B");

  std::unique_ptr<base> A = factory.Create("A");
  BOOST_REQUIRE_EQUAL(A->identify(), "A");

  BOOST_REQUIRE(factory.IsRegistered("A"));

  std::unique_ptr<base> B = factory.Create("B");
  BOOST_REQUIRE_EQUAL(B->identify(), "B");
  std::vector<std::string> keys = factory.getKeys();
  bool A_present = (std::find(keys.begin(), keys.end(), "A") != keys.end());
  bool B_present = (std::find(keys.begin(), keys.end(), "B") != keys.end());

  BOOST_REQUIRE(A_present);
  BOOST_REQUIRE(B_present);
  BOOST_REQUIRE_THROW(factory.Create("C"), std::runtime_error);
  BOOST_REQUIRE_EQUAL(factory.IsRegistered("D"), false);
}

BOOST_AUTO_TEST_SUITE_END()

ext: cc

max_stars_repo_name: ipelupessy/votca

max_issues_repo_name: ipelupessy/votca

max_forks_repo_name: ipelupessy/votca


text:
/*!
@file
Defines the @ref group-core module.

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

#ifndef BOOST_HANA_CORE_HPP
#define BOOST_HANA_CORE_HPP

#include <boost/hana/core/common.hpp>
#include <boost/hana/core/to.hpp>
#include <boost/hana/core/default.hpp>
#include <boost/hana/core/dispatch.hpp>
#include <boost/hana/core/is_a.hpp>
#include <boost/hana/core/make.hpp>
#include <boost/hana/core/tag_of.hpp>
#include <boost/hana/core/when.hpp>

#endif // !BOOST_HANA_CORE_HPP

max_stars_repo_name: EuroLine/nheqminer


text: #include <boost/fusion/sequence/comparison/not_equal_to.hpp>

max_stars_repo_name: miathedev/BoostForArduino

max_issues_repo_name: miathedev/BoostForArduino

max_forks_repo_name: miathedev/BoostForArduino


text:
// Copyright (2014) JDSU T&M Pte Ltd.  All rights reserved.

#include <stdlib.h>
#include <sstream>
#include <fstream>
#include <iostream>
#include <boost/spirit/include/karma.hpp>
#include "timer.hpp"
#include "xtreme/cpp/param_value_types.h"

// Set SHOW_RANDOM_IMSI to 1 to confirm that the create_random_imsi() is correct.
#ifndef SHOW_RANDOM_IMSI
#  define SHOW_RANDOM_IMSI  0
#endif

struct mcc_mnc_pair
{
    const char* const mcc_;
    const char* const mnc_;
};

const struct mcc_mnc_pair g_some_mcc_mnc_pairs[] =
{
    // The following are some random entries from http://en.wikipedia.org/wiki/Mobile_country_code
    { "001", "01"  }    // Test
  , { "505", "01"  }    // Australia Telstra
  , { "505", "02"  }    // Australia Optus
  , { "505", "03"  }    // Australia Vodafone
  , { "505", "08"  }    // Australia One Tel
  , { "505", "13"  }    // Australia Railcorp
  , { "505", "14"  }    // Australia AAPT
  , { "505", "18"  }    // Australia Pactel
  , { "302", "220" }    // Canada Telus
  , { "302", "270" }    // Canada EastLink
  , { "302", "290" }    // Canada Airtel Wireless
  , { "302", "320" }    // Canada Mobilicity
  , { "302", "370" }    // Canada Fido
  , { "302", "610" }    // Canada Bell
  , { "302", "656" }    // Canada TBay
  , { "302", "710" }    // Canada GlobalStar
  , { "302", "720" }    // Canada Rogers Wireless
  , { "460", "00"  }    // China Mobile
  , { "460", "01"  }    // China Unicom
  , { "460", "03"  }    // China Telecom
  , { "460", "20"  }    // China Tietong
  , { "262", "01"  }    // Germany T-Mobile
  , { "262", "01"  }    // Germany T-Mobile
  , { "262", "02"  }    // Germany Vodafone
  , { "262", "03"  }    // Germany E-Plus
  , { "262", "07"  }    // Germany O2
  , { "262", "20"  }    // Germany OnePhone
  , { "262", "43"  }    // Germany LYCA
  , { "262", "92"  }    // Germany Nash Technologies
  , { "262", "901" }    // Germany Debitel
  , { "510", "00"  }    // Indonesia PSN
  , { "510", "01"  }    // Indonesia INDOSAT
  , { "510", "03"  }    // Indonesia StarOne
  , { "510", "07"  }    // Indonesia TelkomFlexi
  , { "440", "00"  }    // Japan eMobile
  , { "440", "01"  }    // Japan NTT docomo
  , { "440", "04"  }    // Japan SoftBank
  , { "440", "07"  }    // Japan KDDI
  , { "440", "70"  }    // Japan au
  , { "440", "80"  }    // Japan TU-KA
  , { "502", "01"  }    // Malaysia ATUR 450
  , { "502", "11"  }    // Malaysia TM Homeline
  , { "502", "12"  }    // Malaysia Maxis
  , { "502", "13"  }    // Malaysia Celcom
  , { "502", "16"  }    // Malaysia DiGi
  , { "502", "17"  }    // Malaysia Hotlink
  , { "502", "18"  }    // Malaysia U Mobile
  , { "502", "150" }    // Malaysia Tune Talk
  , { "502", "152" }    // Malaysia Yes
  , { "502", "156" }    // Malaysia Altel
  , { "525", "01"  }    // Singapore SingTel
  , { "525", "02"  }    // Singapore SingTel-G18
  , { "525", "03"  }    // Singapore M1
  , { "525", "05"  }    // Singapore StarHub
  , { "525", "12"  }    // Singapore Grid
  , { "234", "00"  }    // United Kingdom BT
  , { "234", "01"  }    // United Kingdom Vectone Mobile
  , { "234", "02"  }    // United Kingdom O2 (UK)
  , { "234", "03"  }    // United Kingdom Airtel-Vodafone
  , { "234", "04"  }    // United Kingdom FMS Solutions Ltd
  , { "234", "15"  }    // United Kingdom Vodafone UK
  , { "234", "16"  }    // United Kingdom Talk Talk (Opal Tel Ltd)
  , { "234", "18"  }    // United Kingdom Cloud9
  , { "234", "19"  }    // United Kingdom Private Mobile Networks
  , { "234", "24"  }    // United Kingdom Greenfone
  , { "234", "25"  }    // United Kingdom Truphone
  , { "234", "26"  }    // United Kingdom Lycamobile
  , { "234", "30"  }    // United Kingdom T-Mobile UK
  , { "234", "31"  }    // United Kingdom Virgin Mobile UK
  , { "234", "33"  }    // United Kingdom Orange UK
  , { "234", "51"  }    // United Kingdom Broadband Limited
  , { "310", "004" }    // USA Verizon
  , { "310", "013" }    // USA MobileTel
  , { "310", "016" }    // USA Cricket Communications
  , { "310", "026" }    // USA T-Mobile
  , { "310", "030" }    // USA AT&T
  , { "310", "034" }    // USA Airpeak
  , { "310", "040" }    // USA Concho
  , { "310", "046" }    // USA SIMMETRY
  , { "310", "080" }    // USA Corr
  , { "310", "100" }    // USA Plateau Wireless
  , { "310", "110" }    // USA PTI Pacifica
  , { "310", "120" }    // USA Sprint
  , { "310", "180" }    // USA West Central
  , { "310", "190" }    // USA Dutch Harbor
  , { "310", "300" }    // USA Blue Sky Mobile
  , { "310", "320" }    // USA Cellular One
  , { "310", "340" }    // USA Westlink
  , { "310", "400" }    // USA i CAN_GSM
  , { "310", "420" }    // USA Cincinnati Bell
  , { "310", "450" }    // USA Viaero
  , { "310", "470" }    // USA nTelos
  , { "310", "520" }    // USA VeriSign
  , { "310", "540" }    // USA Oklahoma Western
  , { "310", "610" }    // USA Epic Touch
  , { "310", "620" }    // USA Coleman County Telecom
  , { "310", "630" }    // USA AmeriLink PCS
  , { "310", "640" }    // USA Airadigm
  , { "310", "670" }    // USA Northstar
  , { "310", "870" }    // USA PACE
  , { "311", "480" }    // USA Verizon
  , { "311", "490" }    // USA Sprint
  , { "311", "660" }    // USA metroPCS
  , { "316", "010" }    // USA Nextel
};

const size_t g_mcc_mnc_count = sizeof g_some_mcc_mnc_pairs / sizeof g_some_mcc_mnc_pairs[0];

Timer g_timer;
const size_t g_count = 1000 * 1000;
xtreme::cpp::IMSIType g_random_imsi[g_count];

void create_random_imsi()
{
    for (size_t i = 0; i < g_count; ++i)
    {
        size_t n = lrand48() % g_mcc_mnc_count;
        const struct mcc_mnc_pair& one_mcc_mnc_pair = g_some_mcc_mnc_pairs[n];

        std::stringstream stream;
        stream << one_mcc_mnc_pair.mcc_ << one_mcc_mnc_pair.mnc_;

        // An IMSI is 15 digits long.
        size_t remaining = 15 - stream.str().length();
        for (size_t j = 0; j < remaining; ++j)
        {
            n = lrand48() % 10;
            stream << "0123456789"[n];
        }

        uint64_t imsi;
        stream >> std::hex >> imsi;
        g_random_imsi[i] = imsi;

#if SHOW_RANDOM_IMSI
        std::cout << '0' << stream.str() << '\n';
        xtreme::cpp::operator<<(std::cout, g_random_imsi[i]);
        std::cout << '\n';
#endif
    }
}

class Printer : private boost::noncopyable
{
  public:
    Printer(const char* const file_name)
      : stream_(file_name)
      , ostream_inserter_(stream_)
    {
        stream_.rdbuf()->pubsetbuf(buffer_, buf_size_);
        // clear the unitbuf flag, which if set, will flush the stream on each output operation.
        stream_ << std::nounitbuf;
    }

    // Writes imsi to disk via cpp::operator<<() with a temporary ostringstream.
    void output_via_tmp_ss(const xtreme::cpp::IMSIType& imsi)
    {
        std::ostringstream stream;
        xtreme::cpp::operator<<(stream, imsi);
        stream_ << stream.str() << '\n';
    }

    // Writes imsi by calling cpp::operator<<() to write the imsi directly to disk.
    void output_directly(const xtreme::cpp::IMSIType& imsi)
    {
        xtreme::cpp::operator<<(stream_, imsi);
        stream_ << '\n';
    }

    // Writes imsi to disk by using iostream manipulators.
    void output_via_iomanip(const xtreme::cpp::IMSIType& imsi)
    {
        stream_ << '0'
                << std::hex << std::setw(15) << std::setfill('0') << imsi.t << '\n';
    }

    // Writes imsi to disk by using boost::spirit::karma.
    void output_via_karma(const xtreme::cpp::IMSIType& imsi)
    {
        using boost::spirit::karma::generate;
        using boost::spirit::karma::lit;
        using boost::spirit::karma::hex;
        using boost::spirit::karma::right_align;
        generate(ostream_inserter_,
                 lit('0') << right_align(15, lit('0'))[hex] << lit('\n'), imsi.t);
    }

  private:
    std::ofstream stream_;
    static const size_t buf_size_ = 32768;
    char buffer_[buf_size_];
    std::ostream_iterator<char> ostream_inserter_;
};

void time_temporary_stringstream(const char* const file_name)
{
    Printer printer(file_name);
    g_timer.start();
    for (size_t i = 0; i < g_count; ++i)
    {
        printer.output_via_tmp_ss(g_random_imsi[i]);
    }
    uint64_t elapsed = g_timer.stop();
    std::cout << "cpp::operator<<() with temporary ostringstream took " << elapsed << " usecs\n";
}

void time_direct_output(const char* const file_name)
{
    Printer printer(file_name);
    g_timer.start();
    for (size_t i = 0; i < g_count; ++i)
    {
        printer.output_directly(g_random_imsi[i]);
    }
    uint64_t elapsed = g_timer.stop();
    std::cout << "cpp::operator<<() directly took " << elapsed << " usecs\n";
}

void time_iomanip(const char* const file_name)
{
    Printer printer(file_name);
    g_timer.start();
    for (size_t i = 0; i < g_count; ++i)
    {
        printer.output_via_iomanip(g_random_imsi[i]);
    }
    uint64_t elapsed = g_timer.stop();
    std::cout << "iomanip took " << elapsed << " usecs\n";
}

void time_karma(const char* const file_name)
{
    Printer printer(file_name);
    g_timer.start();
    for (size_t i = 0; i < g_count; ++i)
    {
        printer.output_via_karma(g_random_imsi[i]);
    }
    uint64_t elapsed = g_timer.stop();
    std::cout << "karma took " << elapsed << " usecs\n";
}

int
main()
{
    create_random_imsi();

    time_temporary_stringstream("tmp-ss.txt");
    time_direct_output("direct.txt");
    time_iomanip("iomanip.txt");
    time_karma("karma.txt");
    time_temporary_stringstream("tmp-ss.txt");
    time_direct_output("direct.txt");
    time_iomanip("iomanip.txt");
    time_karma("karma.txt");
}


text:
//===--------------------------------------------------------------------------------*- C++ -*-===//
//                         _____                        _
//                        / ____|                      (_)
//                       | (___   ___  __ _ _   _  ___  _  __ _
//                        \___ \ / _ \/ _` | | | |/ _ \| |/ _` |
//                        ____) |  __/ (_| | |_| | (_) | | (_| |
//                       |_____/ \___|\__, |\__,_|\___/|_|\__,_| - Game Engine (2016-2017)
//                                       | |
//                                       |_|
//
// This file is distributed under the MIT License (MIT).
// See LICENSE.txt for details.
//
//===------------------------------------------------------------------------------------------===//

#include "sequoia-engine/Core/Assert.h"
#include "sequoia-engine/Core/Casting.h"
#include "sequoia-engine/Core/Logging.h"
#include "sequoia-engine/Core/StringRef.h"
#include "sequoia-engine/Render/Exception.h"
#include "sequoia-engine/Render/GL/GL.h"
#include "sequoia-engine/Render/GL/GLFragmentData.h"
#include "sequoia-engine/Render/GL/GLProgramManager.h"
#include "sequoia-engine/Render/GL/GLRenderSystem.h"
#include "sequoia-engine/Render/GL/GLRenderer.h"
#include "sequoia-engine/Render/GL/GLShaderManager.h"
#include "sequoia-engine/Render/GL/GLVertexAttribute.h"
#include <algorithm>
#include <boost/functional/hash.hpp>

namespace sequoia {

namespace render {

GLProgramManager::~GLProgramManager() {}

void GLProgramManager::makeValid(GLProgram* program) {
  SEQUOIA_ASSERT_MSG(!program->isValid(), "program already initialized");

  program->id_ = glCreateProgram();

  if(program->id_ == 0)
    SEQUOIA_THROW(RenderSystemException, "failed to create program");

  Log::debug("Created program (ID={})", program->id_);

  Log::debug("Linking program (ID={}) ...", program->id_);

  for(const std::shared_ptr<Shader>& shader : program->getShaders()) {
    auto glshader = core::dyn_pointer_cast<GLShader>(shader);

    // TODO: if at some point we have multiple ressource threads, we need to wait here
    SEQUOIA_ASSERT_MSG(glshader->isValid(), "shader not valid");

    Log::debug("Attaching shader (ID={}) to program (ID={})", glshader->getID(), program->id_);
    glAttachShader(program->id_, glshader->getID());
  }

  // Set location of the vertex attributes and fragment data
  setVertexAttributes(program);
  setFragmentData(program);

  auto checkStatus = [&program](GLenum statusParam, const char* action) {
    GLint status = 0;
    glGetProgramiv(program->id_, statusParam, &status);
    if(!status) {
      GLint infoLogLength = 0;
      glGetProgramiv(program->id_, GL_INFO_LOG_LENGTH, &infoLogLength);

      std::vector<char> infoLog(infoLogLength + 1);
      glGetProgramInfoLog(program->id_, infoLogLength, NULL, &infoLog[0]);
      std::string reason(infoLog.data(), infoLog.size());

      SEQUOIA_THROW(RenderSystemException, "failed to {} program (ID={}):\n{}", action,
                    program->id_, reason);
    }
  };

  // Link the program
  glLinkProgram(program->id_);
  checkStatus(GL_LINK_STATUS, "link");

  // Validate program
  glValidateProgram(program->id_);
  checkStatus(GL_VALIDATE_STATUS, "validate");

  for(const auto& shader : program->getShaders()) {
    GLShader* glshader = core::dyn_cast<GLShader>(shader.get());
    glDetachShader(program->id_, glshader->getID());
  }

  // Get the uniform variables
  getUniforms(program);

  // Check all vertex attributes and fragment data
  SEQUOIA_ASSERT(checkVertexAttributes(program));
  SEQUOIA_ASSERT(checkFragmentData(program));

  Log::debug("Successfully linked program (ID={})", program->id_);
}

std::shared_ptr<GLProgram>
GLProgramManager::create(const std::set<std::shared_ptr<Shader>>& shaders) {
  SEQUOIA_LOCK_GUARD(mutex_);

  std::size_t hash = GLProgramManager::hash(shaders);
  auto it = shaderSetLookupMap_.find(hash);

  if(it != shaderSetLookupMap_.end())
    return programList_[it->second];

  programList_.emplace_back(std::make_shared<GLProgram>(shaders));
  shaderSetLookupMap_[hash] = programList_.size() - 1;
  return programList_.back();
}

void GLProgramManager::remove(const std::shared_ptr<GLProgram>& program) noexcept {
  SEQUOIA_LOCK_GUARD(mutex_);

  programList_.erase(std::remove(programList_.begin(), programList_.end(), program),
                     programList_.end());
  shaderSetLookupMap_.erase(GLProgramManager::hash(program->getShaders()));
}

std::size_t GLProgramManager::hash(const std::set<std::shared_ptr<Shader>>& shaders) noexcept {
  std::size_t seed = 0;
  std::for_each(shaders.begin(), shaders.end(), [&seed](const std::shared_ptr<Shader>& shader) {
    boost::hash_combine(seed, std::hash<Shader*>()(shader.get()));
  });
  return seed;
}

void GLProgramManager::getUniforms(GLProgram* program) const {
  Log::debug("Getting uniform variables of program (ID={}) ...", program->id_);

  program->uniformInfoMap_.clear();
  program->textureSamplers_.clear();
  program->allUniformVariablesSet_ = false;

  int numActiveUniforms = 0;
  glGetProgramiv(program->id_, GL_ACTIVE_UNIFORMS, &numActiveUniforms);
  Log::debug("Program has {} active uniform variables", numActiveUniforms);

  int activeUniformMaxLength = 0;
  glGetProgramiv(program->id_, GL_ACTIVE_UNIFORM_MAX_LENGTH, &activeUniformMaxLength);
  auto name = std::make_unique<char[]>(activeUniformMaxLength);

  for(int index = 0; index < numActiveUniforms; ++index) {
    GLenum type;
    GLint rank, length;
    glGetActiveUniform(program->id_, index, activeUniformMaxLength, &length, &rank, &type,
                       name.get());

    GLint location = glGetUniformLocation(program->id_, name.get());

    // Does the variable correspond to a texture sampler?
    int textureUnit = -1;
    StringRef nameRef(name.get());
    if(nameRef.startswith("tex")) {
      // extract 0 from `tex0_XXX`
      std::string textureUnitStr = nameRef.substr(3, nameRef.find_first_of('_', 3)).str();

      try {
        textureUnit = std::stoi(textureUnitStr.c_str());
      } catch(std::invalid_argument& e) {
        Log::warn("Failed to extract texture unit from uniform variable \"{}\": {}", name.get(),
                  e.what());
        textureUnit = -1;
      }
    }

    Log::debug("Active uniform variable: name={}, type={}{}{}, location={}", name.get(), type,
               (rank != 1 ? core::format(", size={}", rank) : ""),
               (textureUnit != -1 ? core::format(", textureUnit={}", textureUnit) : ""), location);

    if(location != -1) {
      program->uniformInfoMap_.emplace(
          name.get(), GLProgram::GLUniformInfo{type, rank, location, false, textureUnit});

      if(textureUnit != -1) {
        auto ret = program->textureSamplers_.emplace(textureUnit, name.get());
        if(!ret.second)
          Log::warn("Texture sampler \"{}\" mapped to already existing texture unit '{}' which is "
                    "mapped to \"{}\"",
                    name.get(), textureUnit, ret.first->second);
      }
    }
  }

  Log::debug("Successfully got uniform variables of program (ID={})", program->id_);
}

void GLProgramManager::setVertexAttributes(GLProgram* program) const {
  Log::debug("Setting vertex attributes of program (ID={}) ...", program->id_);

  GLVertexAttribute::forEach([&program](unsigned int index, const char* name) {
    glBindAttribLocation(program->id_, index, name);
  });

  Log::debug("Successfully set vertex attributes of program (ID={})", program->id_);
}

bool GLProgramManager::checkVertexAttributes(GLProgram* program) const {
  Log::debug("Checking vertex attributes of program (ID={}) ...", program->id_);

  int numActiveAttrs = 0;
  glGetProgramiv(program->id_, GL_ACTIVE_ATTRIBUTES, &numActiveAttrs);
  Log::debug("Program has {} active vertex attributes", numActiveAttrs);

  int activeAttrMaxLength = 0;
  glGetProgramiv(program->id_, GL_ACTIVE_ATTRIBUTE_MAX_LENGTH, &activeAttrMaxLength);
  auto name = std::make_unique<char[]>(activeAttrMaxLength);

  for(unsigned int index = 0; index < numActiveAttrs; ++index) {
    GLenum type;
    GLint rank, length;
    glGetActiveAttrib(program->id_, index, activeAttrMaxLength, &length, &rank, &type, name.get());
    GLint location = glGetAttribLocation(program->id_, name.get());

    Log::debug("Active vertex attribute: name={}, type={}, location={}", name.get(), type,
               location);

    // We don't check attributes which start with `frag_`
    if(!StringRef(name.get()).startswith("frag_") && !GLVertexAttribute::isValid(name.get())) {
      SEQUOIA_THROW(RenderSystemException, "invalid vertex attribute '{}'", name.get());
    }
  }

  Log::debug("Successfully checked vertex attributes of program (ID={})", program->id_);
  return true;
}

void GLProgramManager::setFragmentData(GLProgram* program) const {
  Log::debug("Setting fragment data of program (ID={}) ...", program->id_);

  GLFragmentData::forEach([&program](unsigned int index, const char* name) {
    glBindFragDataLocation(program->id_, index, name);
  });

  Log::debug("Successfully set fragment data of program (ID={})", program->id_);
}

bool GLProgramManager::checkFragmentData(GLProgram* program) const {
  if(getGLRenderer().isExtensionSupported(GLextension::GL_ARB_program_interface_query)) {
    Log::debug("Checking fragment data of program (ID={}) ...", program->id_);

    int numFragData = 0;
    glGetProgramInterfaceiv(program->id_, GL_PROGRAM_OUTPUT, GL_ACTIVE_RESOURCES, &numFragData);
    Log::debug("Program has {} ouput fragment data", numFragData);

    std::array<GLenum, 2> properties = {{GL_NAME_LENGTH, GL_LOCATION}};
    std::array<GLint, 2> values;

    for(unsigned int index = 0; index < numFragData; ++index) {
      glGetProgramResourceiv(program->id_, GL_PROGRAM_OUTPUT, index, properties.size(),
                             properties.data(), values.size(), nullptr, values.data());

      std::vector<char> nameData(values[0]);
      glGetProgramResourceName(program->id_, GL_PROGRAM_OUTPUT, index, nameData.size(), NULL,
                               nameData.data());
      std::string name(nameData.begin(), nameData.end() - 1);
      GLint location = values[1];

      Log::debug("Output fragment data: name={}, location={}", name, location);

      // We only check variables which are explicitly tagged as `out_*`
      if(StringRef(name).startswith("out_") && !GLFragmentData::isValid(name.c_str()))
        SEQUOIA_THROW(RenderSystemException, "invalid output fragment data '{}'", name);
    }

    Log::debug("Successfully checked fragment data of program (ID={})", program->id_);
  }
  return true;
}

} // namespace render

} // namespace sequoia

max_stars_repo_name: thfabian/sequoia

max_issues_repo_name: thfabian/sequoia

max_forks_repo_name: thfabian/sequoia


text:
#ifndef HTML_INLINE_GENERATOR_HPP
#define HTML_INLINE_GENERATOR_HPP

#include <boost/fusion/include/nview.hpp>

#include <boost/spirit/include/karma.hpp>

#include "dom/inlineForwards.hpp"
#include "dom/referenceMap.hpp"

namespace HTML {

namespace karma = boost::spirit::karma;
namespace phx = boost::phoenix;

template <typename Iterator>
struct InlineGenerator : public karma::grammar<Iterator, DOM::Inline()>
{
    InlineGenerator(const DOM::ReferenceMap& refmap_);

    typedef boost::fusion::result_of::as_nview<DOM::ExplicitLink const, 0, 2, 3, 1, 0>::type ExplicitLinkReordered;
    typedef boost::fusion::result_of::as_nview<DOM::ReferenceLink const, 0, 2, 2, 1, 0>::type ReferenceLinkReordered;

    karma::symbols<char, char const*> normalEscapes;
    karma::symbols<char, char const*> quotedEscapes;

    karma::rule<Iterator, DOM::Emph()> emph;
    karma::rule<Iterator, DOM::Strong()> strong;
    karma::rule<Iterator, DOM::InlineHTML()> inlineHTML;
    karma::rule<Iterator, DOM::Code()> code;

    karma::rule<Iterator, bool()> linkOpen, linkClose;

    karma::rule<Iterator, ExplicitLinkReordered()> explicitLinkReordered;
    karma::rule<Iterator, DOM::ExplicitLink()> explicitLink;
    karma::rule<Iterator, ReferenceLinkReordered()> referenceLinkReordered;
    karma::rule<Iterator, DOM::ReferenceLink()> referenceLink, referenceLinkRaw;

    karma::rule<Iterator, DOM::AutoLinkEmail()> autoLinkEmail;
    karma::rule<Iterator, DOM::AutoLinkURL()> autoLinkURL;

    karma::rule<Iterator, std::string()> text, quotedText;

    karma::rule<Iterator, DOM::Inline()> inline_;

    const DOM::ReferenceMap& refmap;

    struct HasRefImpl
    {
        HasRefImpl(const DOM::ReferenceMap& refmap_)
        : refmap(refmap_) {}
        const DOM::ReferenceMap& refmap;

        template <typename Arg>
        struct result
        {
            typedef bool type;
        };

        bool operator()(const DOM::ReferenceLink& rl) const
        {
            using boost::fusion::at_c;

            const std::string& ref(at_c<2>(rl)? *at_c<2>(rl) : at_c<1>(rl));
            return refmap.find(ref) != refmap.end();
        }
    };
    phx::function<HasRefImpl> HasRef;

    struct SourceForImpl
    {
        SourceForImpl(const DOM::ReferenceMap& refmap_)
        : refmap(refmap_) {}
        const DOM::ReferenceMap& refmap;

        template <typename Arg>
        struct result
        {
            typedef std::string type;
        };

        std::string operator()(const ReferenceLinkReordered& rl) const
        {
            using boost::fusion::at_c;

            const std::string& ref(at_c<1>(rl)? *at_c<1>(rl) : at_c<3>(rl));
            DOM::ReferenceMap::const_iterator ri = refmap.find(ref);
            //assert(ri != refmap.end());
            if (ri != refmap.end())
                return at_c<2>(*ri);
            else
                return "##notfound##";
        }
    };

    phx::function<SourceForImpl> SourceFor;

    struct TitleForImpl
    {
        TitleForImpl(const DOM::ReferenceMap& refmap_)
        : refmap(refmap_) {}
        const DOM::ReferenceMap& refmap;

        template <typename Arg>
        struct result
        {
            typedef boost::optional<std::string> type;
        };

        boost::optional<std::string> operator()(const ReferenceLinkReordered& rl) const
        {
            using boost::fusion::at_c;

            const std::string& ref(at_c<1>(rl)? *at_c<1>(rl) : at_c<3>(rl));
            DOM::ReferenceMap::const_iterator ri = refmap.find(ref);
            if(ri != refmap.end())
                return at_c<3>(*ri);
            else
                return std::string("##notfound##");
        }
    };

    phx::function<TitleForImpl> TitleFor;
};

} // namespace HTML {

#endif // INLINE_HTML_GENERATOR_HPP

max_stars_repo_name: rockola/spirit-markdown

max_issues_repo_name: rockola/spirit-markdown

max_forks_repo_name: rockola/spirit-markdown


text:
#include "linemod_detector_Tool.h"

#include <eigen3/Eigen/Dense>
#include <opencv2/core/eigen.hpp>
#include <iostream>
#include <boost/format.hpp>
#include <boost/tokenizer.hpp>
#include <boost/algorithm/string.hpp>
#include <boost/foreach.hpp>
#include <fstream>
#include <opencv2/core.hpp>
#include <opencv2/highgui/highgui.hpp>

#define DEBUG
#include <idebug.h>

LinemodDetector::LinemodDetector(){
    icp_dist_min_ = 0.04f;
    px_match_min_ = 0.25;
    renderer_iterator_s = std::map <std::string, RendererIterator*>();
    initParam();
}

LinemodDetector::~LinemodDetector(){

}

void LinemodDetector::initParam(){

    //目标 点云距离
    th_obj_dist_ = 0.02f;//0.04
    verbose_ = true;

    static const int T_LVLS[] = {4, 8};
    std::vector< cv::Ptr<cv::linemod::Modality> > modalities;
    modalities.push_back(new cv::linemod::ColorGradient());
    modalities.push_back(new cv::linemod::DepthNormal());

    //Detector m默认构造函数 的话 第一个是形态 modalities 参数输入是彩色图或者是深度图 后面的是具体的形态的量化等级
    detector_ = new cv::linemod::Detector(modalities, std::vector<int>(T_LVLS, T_LVLS +2));
}

int LinemodDetector::loadData(const std::string path, const std::string &objectName, const std::string &type){

    IDebug("%s", "LinemodDetector loading data");
    if(Rs_.count(objectName)){
        IDebug("The %s object data alreadly loaded", objectName.c_str());
        return 0;
    }
    meshPath = path +"/mesh."+ type;
    std::string RsFileName= path + "/RS.txt";
    std::string TsFileName= path + "/TS.txt";
    std::string KsFileName= path + "/KS.txt";
    std::string DistancesFileName= path + "/distances.txt";
    std::string yamlConfigureName = path + "/settings.yaml";

    renderer_ = new Renderer3d(meshPath);
    renderer_->set_parameters(param_width_, param_height_,\
                              param_focal_length_x_, param_focal_length_y_, param_near_, param_far_);

    renderer_iterator_ = new RendererIterator(renderer_, param_n_points_);
    renderer_iterator_->angle_step_ = param_angle_step_;
    renderer_iterator_->radius_min_ = float(param_radius_min_);
    renderer_iterator_->radius_max_ = float(param_radius_max_);
    renderer_iterator_->radius_step_ = float(param_radius_step_);
    renderer_iterator_s.insert(std::pair<std::string, RendererIterator*>(objectName, renderer_iterator_));

    // 加载平移选择矩阵表
    std::vector<cv::Mat> Rs_tmp, Ts_tmp, Ks_tmp;

    loadVectorMat(RsFileName, Rs_tmp, 3, 3);
    loadVectorMat(TsFileName, Ts_tmp, 1, 3);
    loadVectorMat(KsFileName, Ks_tmp, 3, 3);

    //std::cout << "load Mat "<<std::endl;
    Rs_.insert(std::pair<std::string, std::vector<cv::Mat>>(objectName, Rs_tmp));
    Ts_.insert(std::pair<std::string, std::vector<cv::Mat>>(objectName, Ts_tmp));
    Ks_.insert(std::pair<std::string, std::vector<cv::Mat>>(objectName, Ks_tmp));

    // 加载距离表
    std::vector<float> distances_tmp;
    std::ifstream distancesIf(DistancesFileName);
    std::string disTmp;
    size_t disIndex = 0;
    while(distancesIf >> disTmp){
        distances_tmp.push_back(std::stof(disTmp));
        disIndex ++;
    }
    distances_.insert(std::pair<std::string, std::vector<float> >(objectName, distances_tmp));

    /**
    *   加载Detector
    */
    cv::linemod::Detector *detector = new cv::linemod::Detector();
    loadDetctor(path + "/detector.xml", detector);

    std::string object_id_in_db = detector->classIds()[0];
    for (size_t template_id = 0; template_id < detector->numTemplates();
         ++template_id) {
        //加载器 加载
        const std::vector<cv::linemod::Template> &templates_original = detector->getTemplates(object_id_in_db, template_id);
        //synthetic 合成的
        detector_->addSyntheticTemplate(templates_original, objectName);
    }

    if(detector_->classIds().empty())
        return -1;
    IDebug("%s", "LinemodDetector load  ok");
    return 0;
}

void LinemodDetector::loadVectorMat(std::string &fileName, std::vector<cv::Mat> &out, int rows, int cols){

    std::ifstream in(fileName);
    std::string tmpLine;
    std::vector<std::string> rss;

    while(std::getline(in, tmpLine, '|')){
        // 删除所有换行
        tmpLine = boost::algorithm::erase_all_copy(tmpLine, "\n");
        tmpLine.erase(0, 1);

        boost::split(rss, tmpLine, boost::is_any_of("  "));

        cv::Mat_<double> tmpMat_(rows,cols);

        for(int i = 0; i < rows; i ++)
            for(int j = 0; j < cols; j ++)
                tmpMat_(i,j) = std::stod(rss[i * cols + j].erase(rss[i * cols + j].length()-1));

        cv::Mat tmpMat = tmpMat_;

        out.push_back(tmpMat);
    }
    in.close();
}

void LinemodDetector::loadDetctor(const std::string file_name, cv::linemod::Detector *value){

    cv::FileStorage fs(file_name, cv::FileStorage::READ);
    value->read(fs.root());

    cv::FileNode fn = fs["classes"];
    for (cv::FileNodeIterator i = fn.begin(), iend = fn.end(); i != iend; ++i)
        value->readClass(*i);
}

int LinemodDetector::detection(){

    objs_.clear();
    poses.clear();

    IDebug("the pyramidLevels is %d ", detector_->pyramidLevels());
    IDebug("depth_ is %d ", depth_.depth());
    // 构建检测输入源
    std::vector<cv::Mat> sources;

    // 转换源深度图的格式
    cv::Mat depth;
    if (depth_.depth() == CV_32F)
        depth_.convertTo(depth, CV_16UC1, 1000.0);
    else if(depth_.depth() == CV_8U){
        depth_.convertTo(depth, CV_16UC1, 1000.0);
    } else if(depth_.depth() == CV_16U){
        depth = depth_;
    }

    cv::Mat color;
    if( color_.empty() ){
        IErrorPrint("%s","color_ non");
    }else{

    }

    color_.copyTo(color);
    // 将深度图作为检测源  不输入彩色图会出现 assert dept和dim >0
    IDebug("the color_ size is %d %d " , color.rows, color.cols);
    IDebug("the depth size is %d %d " , depth.rows, color_.cols);

    sources.push_back(color);
    sources.push_back(depth);

    /**
     * @brief matches 保存匹配成功的匹配对象
     */
    std::vector<cv::linemod::Match> matches;
    IDebug("%s","detector_->match ...............");
    detector_->match(sources, 81.0f, matches);
    IDebug("%s","detector_->match end........");
    IDebug("%s %d","detector size: ", matches.size());
    //将深度图转换为点云
    cv::Mat_<cv::Vec3f> depth_real_ref_raw;
    // cv::Mat depth_show;
    cv::Mat_<float> K, K_depth_;
    cv::Mat_<double> tmpMat_(3,3);
    //tmpMat_ <<  617.94, 0, 325.894, 0, 614.1937, 247.2789, 0, 0, 1;
    for( int i =0; i< tmpMat_.cols *tmpMat_.rows; i++){
        tmpMat_ << tmpMat_.at<float>(i);
    }

    K_depth_ = tmpMat_;
    K_depth_.convertTo(K, CV_32F);

#if CV_MAJOR_VERSION == 3
    std::cout << "depthTo3d : "<<depth.depth()<<" "<<depth.channels()<<std::endl;
    cv::rgbd::depthTo3d(depth, K, depth_real_ref_raw);
#else
    cv::depthTo3d(depth, K, depth_real_ref_raw);
#endif

    /**
     * @brief BOOST_FOREACH 遍历刚刚使用linemod模板匹配到所有匹配对象
     */
    BOOST_FOREACH(const cv::linemod::Match & match, matches){
         const std::vector<cv::linemod::Template>& templates =
                detector_->getTemplates(match.class_id, match.template_id);
        cv::Matx33d R_match;
        cv::Vec3d T_match;
        float D_match;
        cv::Mat K_match;

        R_match =  Rs_.at(match.class_id)[match.template_id].clone();
        T_match = Ts_.at(match.class_id)[match.template_id].clone();
        D_match = distances_.at(match.class_id)[match.template_id];
        K_match = Ks_.at(match.class_id)[match.template_id];
        //std::cout << match.x <<" "<< match.y<< " id :"<< match.template_id<<" "<<match.similarity<<std::endl;
        // cv::circle(color, cv::Point(match.x, match.y), 5,cv::Scalar(255,0,255));

        /**
         * 填充位姿，训练过程中，一个物体代表一个claas_id，因此在识别过程中detctor_只能识别一个物体
         * 而在识别过程中的，每渲染一张图片，代表的是一个template_id，因此，我们通过识别匹配中得到的template_id来对应训练过程中
         * 对应的渲染图片，由于渲染过程中，每个图片[template_id]的位姿都是已知的，所以我们就可以获取到当前匹配的位姿态
         */

        // cv::Matx33d R_match = Rs_.at(match.class_id)[match.template_id].clone();
        // cv::Vec3d T_match = Ts_.at(match.class_id)[match.template_id].clone();
        // float D_match = distances_.at(match.class_id)[match.template_id];
        // cv::Mat K_match = Ks_.at(match.class_id)[match.template_id];

        /**
         * 将通过模板匹配得到的粗略位姿 放到渲染器进行重新渲染，得到深度图，然后将得到的深度图转换为点云
         */
        cv::Mat mask ,rendorcolor;
        cv::Rect rect;
        cv::Matx33d R_temp(R_match.inv());
        cv::Vec3d up(-R_temp(0,1), -R_temp(1,1), -R_temp(2,1));
        cv::Mat depth_ref_;
        renderer_iterator_s.at(match.class_id)->renderDepthOnly(depth_ref_, mask, rect, -T_match, up);
        // renderer_iterator_s.at(match.class_id)->render(rendorcolor, depth_ref_, mask, rect, -T_match, up);
        // renderer_iterator_s.at(match.class_id)->renderImageOnly(renderColor,rectColor,tColor, upColor );
        // cv::imshow("renderColor",rendorcolor);
        // cv::waitKey(0);
        /**
         * @brief depth_real_model_raw  保存通过渲染器得到的深度图转换的点云
         */
        cv::Mat_<cv::Vec3f> depth_real_model_raw;
        cv::Mat renderK;
        K_match.convertTo(renderK, CV_32F);
        // IDebug("%s","depthTo3d ready ...............");
#if CV_MAJOR_VERSION == 3
        // try{
        cv::rgbd::depthTo3d(depth_ref_, renderK, depth_real_model_raw);
        // }catch(ex){
            // return -1;
        // }

#else
        cv::depthTo3d(depth_ref_, renderK, depth_real_model_raw);
#endif
        // cv::depthTo3d(depth_ref_, renderK, depth_real_model_raw);
        // IDebug("%s","depthTo3d ok ...............");
        /**
         * 生成点云和模型的包围矩形，<包围整个深度图>？
         */
        cv::Rect_<int> rect_model(0, 0, depth_real_model_raw.cols, depth_real_model_raw.rows);
        // 根据匹配得到的数据 修改包围矩形的X，Y
        cv::Rect_<int> rect_ref(rect_model);
        rect_ref.x += match.x;
        rect_ref.y += match.y;
        // IDebug("%s %d %d","rect_ref width heigh ", rect_ref.width, rect_ref.height);
        //cv::Mat testImg = color.clone();
        //imshow("testImg",testImg(rect_ref));
        //cv::waitKey(0);
        /**
         *  求图像深度图与rect_ref两个矩形的相交
         */
        rect_ref = rect_ref & cv::Rect(0, 0, depth_real_ref_raw.cols, depth_real_ref_raw.rows);

        // 当相交的区域宽小于5 或者长小于5时，跳过当前匹配
        if ((rect_ref.width < 5) || (rect_ref.height < 5))
            continue;

        // 得到两个矩形的最小
        if (rect_ref.width > rect_model.width)
            rect_ref.width = rect_model.width;
        if (rect_ref.height > rect_model.height)
            rect_ref.height = rect_model.height;
        if (rect_model.width > rect_ref.width)
            rect_model.width = rect_ref.width;
        if (rect_model.height > rect_ref.height)
            rect_model.height = rect_ref.height;

        //  全局点云
        cv::Mat_<cv::Vec3f> depth_real_ref = depth_real_ref_raw(rect_ref);
        // 局部 模板点云
        cv::Mat_<cv::Vec3f> depth_real_model = depth_real_model_raw(rect_model);

        // 获取裁剪过后的点云的中心点
        cv::Vec3f T_crop = depth_real_ref(depth_real_ref.rows / 2.0f, depth_real_ref.cols / 2.0f);
        // 加上物体的中心点到表面的距离
        T_crop(2) += D_match;

        // 检测得到的中心点坐标是否是正常的
        if (!cv::checkRange(T_crop))
            continue;

        //
        cv::Vec3f T_real_icp(T_crop);

        if (!cv::checkRange(R_match))
            continue;

        // 将匹配得到的模板用来获取训练时的旋转矩阵来当作icp算法的旋转矩阵
        cv::Matx33f R_real_icp(R_match);

        //  将之前生成的点云[mat对象]转为vector的点云对象
        std::vector<cv::Vec3f> pts_real_model_temp;
        std::vector<cv::Vec3f> pts_real_ref_temp;

        /**
         * @brief px_ratio_missing  传感器深度图转的点云比渲染得到的点云缺少的点云比
         */
        float px_ratio_missing = matToVec(depth_real_ref, depth_real_model,\
                                          pts_real_ref_temp, pts_real_model_temp);
        if (px_ratio_missing > (1.0f-px_match_min_))
            continue;

        // 执行第一次近似ICP
        float px_ratio_match_inliers = 0.0f;
        float icp_dist = icpCloudToCloud(pts_real_ref_temp, pts_real_model_temp,\
                                         R_real_icp, T_real_icp, px_ratio_match_inliers, 1);
        if (icp_dist > icp_dist_min_)
            continue;

        //执行最佳icp配准
        icp_dist = icpCloudToCloud(pts_real_ref_temp, pts_real_model_temp,\
                                   R_real_icp, T_real_icp, px_ratio_match_inliers, 2);

        // 保存相关的结果
        objs_.push_back(ObjData(pts_real_ref_temp, pts_real_model_temp, \
                                match.class_id, match.similarity, icp_dist, px_ratio_match_inliers, R_real_icp, T_crop));
    }

    //local non-maxima supression to find the best match at each position  非极大抑制
    int count_pass = 0;
    std::vector<ObjData>::iterator it_o = objs_.begin();
    for (; it_o != objs_.end(); ++it_o)
        if (!it_o->check_done)
        {

            //initialize the object to publishT_real_icp
            ObjData *o_match = &(*it_o);
            int size_th = static_cast<int>((float)o_match->pts_model.size()*0.85);
            //find the best object match among near objects
            std::vector <ObjData>::iterator it_o2 = it_o;
            ++it_o2;
            for (; it_o2 != objs_.end(); ++it_o2)
                if (!it_o2->check_done)
                    if (cv::norm(o_match->t, it_o2->t) < th_obj_dist_)
                    {
                        it_o2->check_done = true;
                        if ((it_o2->pts_model.size() > size_th) && (it_o2->icp_dist < o_match->icp_dist))
                            o_match = &(*it_o2);
                    }

            //perform the final precise icp
            float icp_px_match = 0.0f;
            float icp_dist = icpCloudToCloud(o_match->pts_ref, o_match->pts_model, o_match->r, o_match->t, icp_px_match, 0);

            if (verbose_)
                std::cout << o_match->match_class <<  " similar: " << o_match->match_sim << " icp_dist " << icp_dist << ", ";
            //icp_dist in the same units as the sensor data
            //this distance is used to compute the ratio of inliers (points laying within this distance between the point clouds)
            icp_dist = 0.007f; //0.007
            float px_inliers_ratio = getL2distClouds(o_match->pts_model, o_match->pts_ref, icp_dist);
            if (verbose_)
                std::cout << " ratio " << o_match->icp_px_match << " or " << px_inliers_ratio << std::endl;

            pose p;
            p.objectName = o_match->match_class;

            RT2Pose(o_match->r, o_match->t, p);
            this->poses.push_back(p);

            ++count_pass;
        }

    if (verbose_ && (matches.size()>0)){
        IDebug("%s","depthTo3d ok ...............");
        std::cout << "matches size: " << objs_.size() << " / " << count_pass << " / " << matches.size() << std::endl;
        return 0;
    }

    IErrorPrint("%s","nothing detection   ");
    return -1;

}

void LinemodDetector::RT2Pose(const cv::Matx33f &R, const cv::Vec3f &T, pose &pose){

    Eigen::Matrix3d t_R;
    cv::cv2eigen((cv::Matx33d)R, t_R);
    Eigen::Quaterniond q(t_R);
    Eigen::Vector4d q_tmp = q.coeffs();

    //pose.quaternion.x = q_tmp[0];
    //pose.quaternion.y = q_tmp[1];
    //pose.quaternion.z = q_tmp[2];
    //pose.quaternion.w = q_tmp[3];

    pose.quaternion.x = 0;
    pose.quaternion.y = 0;
    pose.quaternion.z = 0;
    pose.quaternion.w = 1;
    pose.position.x = T(0);
    pose.position.y = T(1);
    pose.position.z = T(2);

}

int LinemodDetector::readYamlData(const YAML::Node &node)
{
    try{
      this->param_n_points_ = node["linemod"]["param_n_points_"].as<int>();
      this->param_angle_step_ = node["linemod"]["param_angle_step_"].as<int>();
      this->param_radius_min_ = node["linemod"]["param_radius_min_"].as<float>();
      this->param_radius_max_ = node["linemod"]["param_radius_max_"].as<float>();
      this->param_radius_step_ = node["linemod"]["param_radius_step_"].as<float>();
      this->param_width_ = node["linemod"]["param_width_"].as<int>();
      this->param_height_ = node["linemod"]["param_height_"].as<int>();
      this->param_focal_length_x_ = node["linemod"]["param_focal_length_x_"].as<float>();
      this->param_focal_length_y_ = node["linemod"]["param_focal_length_y_"].as<float>();
      this->param_near_ = node["linemod"]["param_near_"].as<float>();
      this->param_far_ = node["linemod"]["param_far_"].as<int>();
      float temp3[9];
      this->tmpMat_ = cv::Mat(cv::Size(3,3), CV_32FC1);
      for(int i =0; i< 3;i++){
          for(int j =0; j< 3;j++){
          temp3[i*3+j]= node["linemod"]["tmpMat_"][i*3+j].as<float>();
          this->tmpMat_.at<float>(i,j) = temp3[i*3+j];
            }
        }
    }catch(YAML::Exception e)
    {
        std::cerr<<"Linemod YAML:" << e.msg<<std::endl;
        return -1;
    }

    return 0;
//      std::cout<<tmpMat_<<std::endl;

}

int LinemodDetector::getResult(std::vector<pose> &poses){
    // for( int i = 0; i < poses.size(); i++){
    //     Eigen::Quaterniond CubeRotationShow =  Eigen::Quaterniond(poses[i].quaternion.w, poses[i].quaternion.x,\
    //                                                           poses[i].quaternion.y,poses[i].quaternion.z);
    //     //"输出 Z-Y-X，即RPY  "
    //     Eigen::Vector3d eulerAngle= CubeRotationShow.matrix().eulerAngles(2,1,0);
    //     CubeRotationShow = Eigen::AngleAxisd(eulerAngle[0]-1.57, Eigen::Vector3d::UnitX()) *
    //             Eigen::AngleAxisd(eulerAngle[1], Eigen::Vector3d::UnitY()) *
    //             Eigen::AngleAxisd(eulerAngle[2], Eigen::Vector3d::UnitY());
    //     poses[i].quaternion.x = CubeRotationShow.x();
    //     poses[i].quaternion.y = CubeRotationShow.y();
    //     poses[i].quaternion.z = CubeRotationShow.z();
    //     poses[i].quaternion.x = CubeRotationShow.w();
    // }

    poses = this->poses;

    if(poses.empty())
        return -1;

    IDebug("x = %lf, y = %lf, z = %lf, qx = %lf, qy = %lf, qz = %lf, qw = %lf", \
           this->poses[0].position.x, this->poses[0].position.y, this->poses[0].position.z,\
            this->poses[0].quaternion.x, this->poses[0].quaternion.y, this->poses[0].quaternion.z, this->poses[0].quaternion.w);

    return 0;
}

void LinemodDetector::setDepthImg(const cv::Mat &inputImg){
    // 保存输入的图像
    if( inputImg.cols != param_width_ || param_height_ != inputImg.rows){
        cv::resize(inputImg, depth_, cv::Size(param_width_, param_height_));
    }else{
        depth_ = inputImg;
    }
}

void LinemodDetector::setColorImg(const cv::Mat &inputImg){
    // 保存输入的图像
    if( inputImg.cols != param_width_ || param_height_ != inputImg.rows){
        cv::resize(inputImg, color_, cv::Size(param_width_, param_height_));
    }else{
        color_ = inputImg;
    }

}

float LinemodDetector::icpCloudToCloud(const std::vector<cv::Vec3f> &pts_ref,\
                                       std::vector<cv::Vec3f> &pts_model, \
                                       cv::Matx33f &R, cv::Vec3f &T, float &px_inliers_ratio, int mode){

    //optimal rotation matrix
    cv::Matx33f R_optimal;
    //optimal transformation
    cv::Vec3f T_optimal;

    //the number of desired iterations defined depending on the mode
    int icp_it_th = 40; //maximal number of iterations 35
    if (mode == 1)
        icp_it_th = 10; //minimal number of iterations 4
    else if (mode == 2)
        icp_it_th = 4;

    // 两个点云之间所需的最小距离
    // const float dist_th = 0.012f;
    const float dist_th = 0.008f;
    // 两个点云距离之间的平均值
    float dist_mean = 0.0f;

    // 计算两个点云的欧式距离
    px_inliers_ratio = getL2distClouds(pts_model, pts_ref, dist_mean, mode);
    //The difference between two previously obtained mean distances between the reference and the model point clouds
    float dist_diff = std::numeric_limits<float>::max();

    //the number of performed iterations
    int iter = 0;
    while (( ((dist_mean > dist_th) && (dist_diff > 0.0001f)) || (mode == 1) ) && (iter < icp_it_th))
    {
        ++iter;

        //subsample points from the match and ref clouds
        if (pts_model.empty() || pts_ref.empty())
            continue;

        // 为每个点云计算中心点
        //compute centroids of each point subset
        cv::Vec3f m_centroid, r_centroid;
        getMean(pts_model, m_centroid);
        getMean(pts_ref, r_centroid);

        //compute the covariance matrix
        cv::Matx33f covariance (0,0,0, 0,0,0, 0,0,0);
        std::vector<cv::Vec3f>::iterator it_s = pts_model.begin();
        std::vector<cv::Vec3f>::const_iterator it_ref = pts_ref.begin();
        for (; it_s < pts_model.end(); ++it_s, ++it_ref)
            covariance += (*it_s) * (*it_ref).t();

        // 通过SVD求解最优解
        cv::Mat w, u, vt;
        cv::SVD::compute(covariance, w, u, vt);
        //compute the optimal rotation
        R_optimal = cv::Mat(vt.t() * u.t());

        //compute the optimal translation
        T_optimal = r_centroid - R_optimal * m_centroid;
        if (!cv::checkRange(R_optimal) || !cv::checkRange(T_optimal))
            continue;

        //transform the point cloud
        transformPoints(pts_model, pts_model, R_optimal, T_optimal);

        //compute the distance between the transformed and ref point clouds
        dist_diff = dist_mean;
        px_inliers_ratio = getL2distClouds(pts_model, pts_ref, dist_mean, mode);
        dist_diff -= dist_mean;

        //update the translation matrix: turn to opposite direction at first and then do translation
        T = R_optimal * T;
        //do translation
        cv::add(T, T_optimal, T);
        //update the rotation matrix
        R = R_optimal * R;
        //std::cout << " it " << iter << "/" << icp_it_th << " : " << std::fixed << dist_mean << " " << d_diff << " " << px_inliers_ratio << " " << pts_model.size() << std::endl;
    }

    return dist_mean;

}

/** Computes the L2 distance between two vectors of 3D points of the same size */
float LinemodDetector::getL2distClouds(const std::vector<cv::Vec3f> &model, const std::vector<cv::Vec3f> &ref, \
                                        float &dist_mean, const float mode)
{
    int nbr_inliers = 0;
    int counter = 0;
    float ratio_inliers = 0.0f;

    float dist_expected = dist_mean * 3.0f;
    dist_mean = 0.0f;

    //use the whole region
    std::vector<cv::Vec3f>::const_iterator it_match = model.begin();
    std::vector<cv::Vec3f>::const_iterator it_ref = ref.begin();
    for(; it_match != model.end(); ++it_match, ++it_ref)
    {
        if (!cv::checkRange(*it_ref))
            continue;

        if (cv::checkRange(*it_match))
        {
            float dist = cv::norm(*it_match - *it_ref);
            if ((dist < dist_expected) || (mode == 0))
                dist_mean += dist;
            if (dist < dist_expected)
                ++nbr_inliers;
        }
        ++counter;
    }

    if (counter > 0)
    {
        dist_mean /= float(nbr_inliers);
        ratio_inliers = float(nbr_inliers) / float(counter);
    }
    else
        dist_mean = std::numeric_limits<float>::max();

    return ratio_inliers;
}

void LinemodDetector::transformPoints(const std::vector<cv::Vec3f> &src, \
                                      std::vector<cv::Vec3f>& dst, const cv::Matx33f &R, const cv::Vec3f &T)
{
    std::vector<cv::Vec3f>::const_iterator it_src = src.begin();
    std::vector<cv::Vec3f>::iterator it_dst = dst.begin();
    for (; it_src != src.end(); ++it_src, ++it_dst) {
        if (!cv::checkRange(*it_src))
            continue;
        (*it_dst) = R * (*it_src) + T;
    }
}

void LinemodDetector::getMean(const std::vector<cv::Vec3f> &pts, cv::Vec3f& centroid)
{
    centroid = cv::Vec3f(0.0f, 0.0f, 0.0f);
    size_t n_points = 0;
    for (std::vector<cv::Vec3f>::const_iterator it = pts.begin(); it != pts.end(); ++it) {
        if (!cv::checkRange(*it))
            continue;
        centroid += (*it);
        ++n_points;
    }

    if (n_points > 0)
    {
        centroid(0) /= float(n_points);
        centroid(1) /= float(n_points);
        centroid(2) /= float(n_points);
    }
}

float LinemodDetector::matToVec(const cv::Mat_<cv::Vec3f> &src_ref, const cv::Mat_<cv::Vec3f> &src_mod, \
                                std::vector<cv::Vec3f>& pts_ref, std::vector<cv::Vec3f>& pts_mod)
{
    pts_ref.clear();
    pts_mod.clear();
    int px_missing = 0;

    cv::MatConstIterator_<cv::Vec3f> it_ref = src_ref.begin();
    cv::MatConstIterator_<cv::Vec3f> it_mod = src_mod.begin();
    for (; it_ref != src_ref.end(); ++it_ref, ++it_mod)
    {
        if (!cv::checkRange(*it_ref))
            continue;

        pts_ref.push_back(*it_ref);
        if (cv::checkRange(*it_mod))
        {
            pts_mod.push_back(*it_mod);
        }
        else
        {
            pts_mod.push_back(cv::Vec3f(0.0f, 0.0f, 0.0f));
            ++px_missing;
        }
    }

    float ratio = 0.0f;
    if (pts_ref.size() > 0)
        ratio = static_cast<float>(px_missing) /static_cast<float>(pts_ref.size());
    return ratio;
}


text:
#ifndef NETKET_COMMON_TYPES_HPP
#define NETKET_COMMON_TYPES_HPP
/**
 * This header contains standard type aliases to be used throughout the NetKet
 * codebase.
 */

#include <complex>
#include <cstddef>

#include <Eigen/Core>

namespace netket {

using Index = std::ptrdiff_t;
using Complex = std::complex<double>;

using VectorXd = Eigen::VectorXd;
using VectorXcd = Eigen::VectorXcd;
using MatrixXd = Eigen::MatrixXd;
using MatrixXcd = Eigen::MatrixXcd;

}  // namespace netket

#endif  // NETKET_COMMON_TYPES_HPP

max_stars_repo_name: tvieijra/netket

max_issues_repo_name: tvieijra/netket

max_forks_repo_name: tvieijra/netket


text:
/**
 * Copyright (c) 2017 Melown Technologies SE
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * *  Redistributions of source code must retain the above copyright notice,
 *    this list of conditions and the following disclaimer.
 *
 * *  Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 */
#include <set>
#include <map>
#include <memory>

#include <boost/noncopyable.hpp>
#include <boost/format.hpp>

#include "utility/runnable.hpp"

#include "imgproc/png.hpp"

#include "../../../registry.hpp"
#include "../../../storage/sstreams.hpp"

#include "../../io.hpp"
#include "../../2d.hpp"
#include "../../tileset.hpp"
#include "../../debug.hpp"
#include "../../qtree-rasterize.hpp"

#include "../delivery.hpp"
#include "../driver.hpp"
#include "../tilesetindex.hpp"
#include "../config.hpp"

#include "runcallback.hpp"

namespace vtslibs { namespace vts {

namespace fs = boost::filesystem;
namespace vs = vtslibs::storage;

namespace {

std::shared_ptr<tileset::Index>
indexFromDriver(const FullTileSetProperties &properties
                , const Driver::pointer &driver)
{
    if (auto *i = driver->getTileIndex()) {
        // driver provides tile index, reuse with empty deleter
        return { i, [](void*) {} };
    }

    // no tileindex available -> load
    auto index(std::make_shared<tileset::Index>
               (registry::system.referenceFrames
                (properties.referenceFrame).metaBinaryOrder));

    tileset::loadTileSetIndex(*index, *driver);
    return index;
}

std::string filename(const fs::path &root, const TileId &tileId, TileFile type)
{
    return (root / str(boost::format("%s.%s") % tileId % type)).string();
}

IStream::pointer meta2d(const Driver &driver
                        , const tileset::Index &index
                        , const TileId &tileId
                        , bool noSuchFile)
{
    if (!Meta2d::isMetaId(tileId)) {
        if (noSuchFile) {
            LOGTHROW(err1, storage::NoSuchFile)
                << "Tile ID " << tileId << " is not valid for 2d metatile.";
        }
        return {};
    }

    // generate mask image from tileindex, serialize it as a png and wrap in
    // input stream
    return vs::memIStream(TileFile::mask
                          , imgproc::png::serialize
                          (meta2d(index.tileIndex, tileId), 9)
                          , driver.lastModified()
                          , filename(driver.root(), tileId, TileFile::meta2d));
}

void meta2d(const Driver &driver, const tileset::Index &index
            , const TileId &tileId, const InputCallback &cb)
{
    // no driver access, can be called immediately
    runCallback([&]() { return meta2d(driver, index, tileId, true); }, cb);
}

namespace constants {

const auto EmptyMask = imgproc::png::serialize(emptyDebugMask(), 9);

} // namespace constants

IStream::pointer maskStream(const IStream::pointer &is
                            , const Driver::pointer &pdriver
                            , const TileId &tileId, bool debug)
{
    const auto &driver(*pdriver);

    if (!is) {
        if (debug) {
            // no data and debug mode -> return transparent tile
            return vs::memIStream
                (TileFile::mask, constants::EmptyMask
                 , -1, filename(driver.root(), tileId, TileFile::mask));
        }

        // not found
        return {};
    }

    // generate mask image from mask, serialize it as a png and wrap in input
    // stream

    const auto meshMask(loadMeshMask(is));
    const auto png(debug
                   ? imgproc::png::serialize
                   (debugMask(meshMask, driver.capabilities().flattener), 9)
                   : imgproc::png::serialize
                   (mask2d(meshMask, driver.capabilities().flattener), 9));
    return vs::memIStream(TileFile::mask
                          , png, is->stat().lastModified
                          , filename(driver.root(), tileId, TileFile::mask));
}

IStream::pointer mask(const Driver::pointer &driver, const TileId &tileId
                      , FileFlavor flavor, bool noSuchFile)
{
    const auto debug(flavor == FileFlavor::debug);

    return maskStream((noSuchFile && !debug)
                      ? driver->input(tileId, TileFile::mesh)
                      : driver->input(tileId, TileFile::mesh, NullWhenNotFound)
                      , driver, tileId, debug);
}

void mask(const Driver::pointer &driver, const TileId &tileId
          , FileFlavor flavor, const InputCallback &cb)
{
    const auto debug(flavor == FileFlavor::debug);

    driver->input(tileId, TileFile::mesh, [=](const EIStream &eis)
        mutable -> void
    {
        if (const auto &is = eis.get(cb, utility::ExpectedAsSink{})) {
            runCallback([&]() {
                return maskStream(is, driver, tileId, debug);
            }, cb);
        }
    });
}

IStream::pointer meta(const Driver &driver, const tileset::Index &index
                      , const FullTileSetProperties&
                      , const TileId &tileId, FileFlavor flavor
                      , bool noSuchFile)
{
    if (flavor != FileFlavor::debug) {
        return (noSuchFile
                ? driver.input(tileId, TileFile::meta)
                : driver.input(tileId, TileFile::meta, NullWhenNotFound));
    }

    // generate debug metanode
    const auto debugNode(getNodeDebugInfo(index.tileIndex, tileId));

    std::ostringstream os;
    saveDebug(os, debugNode);
    return vs::memIStream("application/json; charset=utf-8"
                          , os.str(), -1 // where to get last modified?
                          , filename(driver.root(), tileId, TileFile::meta));
}

void meta(const Driver &driver, const tileset::Index &index
          , const FullTileSetProperties&
          , const TileId &tileId, FileFlavor flavor
          , const InputCallback &cb)
{
    if (flavor != FileFlavor::debug) {
        return driver.input(tileId, TileFile::meta, cb);
    }

    // generate debug metanode from tile index
    const auto debugNode(getNodeDebugInfo(index.tileIndex, tileId));

    std::ostringstream os;
    saveDebug(os, debugNode);

    cb(vs::memIStream("application/json; charset=utf-8"
                      , os.str(), -1 // where to get last modified?
                      , filename(driver.root(), tileId, TileFile::meta)));
}

/** TODO: make asynchronous version that launches metatile fetch for all
 *  metatiles needed and collects info in callback.
 *
 *  Since 2D interface was never used... do we need it?
 */
bool creditsFromMetatiles(const Driver &driver
                          , const tileset::Index &index
                          , const TileId &creditsId
                          , bool noSuchFile
                          , registry::IdSet &credits
                          , std::size_t maxCount
                          , std::time_t &lastModified)
{
    auto metaOrder(index.metaBinaryOrder());
    if (CreditTile::binaryOrder < metaOrder) {
        LOGTHROW(err3, storage::Error)
            << "unimplemented: cannot create credit tile from bigger "
            "3D metatiles";
    }

    int depthDiff(CreditTile::binaryOrder - metaOrder);
    int count(1 << depthDiff);
    int skip(1 << metaOrder);
    for (int j(0); j < count; ++j) {
        int row(creditsId.y + j * skip);
        for (int i(0); i < count; ++i) {
            TileId metaId(creditsId.lod, creditsId.x + i * skip, row);
            if (!index.meta(metaId)) { continue; }

            auto is(noSuchFile
                    ? driver.input(metaId, TileFile::meta)
                    : driver.input(metaId, TileFile::meta, NullWhenNotFound));
            if (!is) { return false; }
            loadCreditsFromMetaTile(is->get(), credits, is->name());

            // update last modified
            auto lm(is->stat().lastModified);
            if (lm > lastModified) { lastModified = lm; }
            is->close();

            // all credits seen
            if (credits.size() >= maxCount) { return true; }
        }
    }

    return true;
}

IStream::pointer credits(const Driver &driver
                         , const tileset::Index &index
                         , const FullTileSetProperties &properties
                         , const TileId &tileId
                         , bool noSuchFile)
{
    if (!CreditTile::isCreditId(tileId)) {
        if (noSuchFile) {
            LOGTHROW(err1, storage::NoSuchFile)
                << "Tile ID " << tileId << " is not valid for 2d credit tile.";
        }
        return {};
    }

    CreditTile tile;

    std::time_t lastModified(-1);

    auto extract([&](const registry::IdSet &credits)
    {
        for (const auto &cid : credits) {
            if (const auto *credit = registry::system.credits
                (cid, std::nothrow))
            {
                tile.credits.set(credit->id, boost::none);
            }
        }
    });

    if (properties.credits.size() <= 1) {
        extract(properties.credits);
    } else {
        registry::IdSet credits;
        if (!creditsFromMetatiles(driver, index, CreditTile::creditsId(tileId)
                                  , noSuchFile, credits
                                  , properties.credits.size()
                                  , lastModified))
        {
            return {};
        }

        extract(credits);
        if (lastModified <= 0) {
            lastModified = driver.lastModified();
        }
    }

    auto s(std::make_shared<StringIStream>
           (TileFile::credits
            , filename(driver.root(), tileId, TileFile::credits)
            , lastModified));

    // serialize credit tile
    saveCreditTile(s->sink(), tile, false);
    s->updateSize();

    // done
    return s;
}

IStream::pointer filterConfig(const IStream::pointer &raw)
{
    // load config and reset driver
    auto props(tileset::loadConfig(raw->get(), raw->name()));
    props.driverOptions = boost::any();
    auto s(std::make_shared<storage::StringIStream>(*raw));
    tileset::saveConfig(s->sink(), props);
    s->updateSize();
    return s;
}

} // namespace

Delivery::Delivery(AccessToken, const boost::filesystem::path &root
                   , const OpenOptions &openOptions)
    : driver_(Driver::open(root, openOptions))
    , properties_(tileset::loadConfig(*driver_))
    , index_(indexFromDriver(properties_, driver_))
    , async_(driver_->ccapabilities().async)
{}

Delivery::Delivery(AccessToken, std::shared_ptr<Driver> driver)
    : driver_(std::move(driver))
    , properties_(tileset::loadConfig(*driver_))
    , index_(indexFromDriver(properties_, driver_))
    , async_(driver_->ccapabilities().async)
{}

Delivery::pointer
Delivery::open(const boost::filesystem::path &root
               , const OpenOptions &openOptions)
{
    return std::make_shared<Delivery>(AccessToken{}, root, openOptions);
}

Delivery::pointer
Delivery::open(std::shared_ptr<Driver> driver)
{
    return std::make_shared<Delivery>(AccessToken{}, std::move(driver));
}

IStream::pointer Delivery::input(File type) const
{
    switch (type) {
    case File::config:
        return filterConfig(driver_->input(type));
    default: break;
    }
    return driver_->input(type);
}

IStream::pointer Delivery::input(File type, const NullWhenNotFound_t&) const
{
    switch (type) {
    case File::config:
        return filterConfig(driver_->input(type, NullWhenNotFound));
    default: break;
    }
    return driver_->input(type, NullWhenNotFound);
}

namespace {

inline void fixmeAsync() {
    LOGTHROW(err4, std::runtime_error)
        << "FIXME: make me async!";
}

} // namespace

IStream::pointer Delivery::input(const TileId &tileId, TileFile type
                                 , FileFlavor flavor) const
{
    switch (type) {
    case TileFile::meta2d:
        return meta2d(*driver_, *index_, tileId, true);

    case TileFile::mask:
        return mask(driver_, tileId, flavor, true);

    case TileFile::credits:
        return credits(*driver_, *index_, properties_, tileId, true);

    case TileFile::meta:
        return meta(*driver_, *index_, properties_, tileId, flavor, true);

    default:
        return driver_->input(tileId, type);
    }
}

IStream::pointer Delivery::input(const TileId &tileId, TileFile type
                                 , FileFlavor flavor
                                 , const NullWhenNotFound_t&) const
{
    switch (type) {
    case TileFile::meta2d:
        return meta2d(*driver_, *index_, tileId, false);

    case TileFile::mask:
        return mask(driver_, tileId, flavor, false);

    case TileFile::credits:
        return credits(*driver_, *index_, properties_, tileId, false);

    case TileFile::meta:
        return meta(*driver_, *index_, properties_, tileId, flavor, false);

    default:
        return driver_->input(tileId, type, NullWhenNotFound);
    }
}

void Delivery::input(const TileId &tileId, TileFile type, FileFlavor flavor
                     , const InputCallback &cb) const
{
    switch (type) {
    case TileFile::meta2d:
        return meta2d(*driver_, *index_, tileId, cb);

    case TileFile::mask:
        return mask(driver_, tileId, flavor, cb);

    case TileFile::credits:
        fixmeAsync();
        return cb(credits(*driver_, *index_, properties_, tileId, true));

    case TileFile::meta:
        return meta(*driver_, *index_, properties_, tileId, flavor, cb);

    default:
        // forward
        return driver_->input(tileId, type, cb);
    }
}

FileStat Delivery::stat(File type) const
{
    return driver_->stat(type);
}

FileStat Delivery::stat(const TileId &tileId, TileFile type) const
{
    return driver_->stat(tileId, type);
}

void Delivery::stat(const TileId &tileId, TileFile type
                    , const StatCallback &cb) const
{
    return driver_->stat(tileId, type, cb);
}

IStream::pointer Delivery::input(const std::string &name) const
{
    return driver_->input(name);
}

IStream::pointer Delivery::input(const std::string &name
                                 , const NullWhenNotFound_t&) const
{
    return driver_->input(name, NullWhenNotFound);
}

FileStat Delivery::stat(const std::string &name) const
{
    return driver_->stat(name);
}

Resources Delivery::resources() const
{
    return driver_->resources();
}

bool Delivery::externallyChanged() const
{
    return driver_->externallyChanged();
}

std::time_t Delivery::lastModified() const
{
    return driver_->lastModified();
}

MapConfig Delivery::mapConfig(bool includeExtra) const
{
    return TileSet::mapConfig(*driver_, includeExtra);
}

MeshTilesConfig Delivery::meshTilesConfig(bool includeExtra) const
{
    return TileSet::meshTilesConfig(*driver_, includeExtra);
}

} } // namespace vtslibs::vts

max_stars_repo_name: melowntech/vts-libs

max_issues_repo_name: melowntech/vts-libs

max_forks_repo_name: melowntech/vts-libs


text:
#include <stdio.h>
#include <boost/program_options.hpp>
#include <iostream>
#include <string>
#include <unistd.h>

#include "dds_robot.hh"

namespace po = boost::program_options;

//  ---------------------------------------------------------------------
/// \brief Function is called everytime a topic update is received.
void cb(const std::string &_topic, const std::string &_data)
{
  assert(_topic != "");
  std::cout << "\nCallback [" << _topic << "][" << _data << "]" << std::endl;
}

//  ---------------------------------------------------------------------
/// \brief Print program usage.
void PrintUsage(const po::options_description &_options)
{
  std::cout << "Usage: publisher [options] <topic> <data> <numMessages>\n"
            << "Positional arguments:\n"
            << "  <topic>               Topic to publish\n"
            << "  <data>                Data\n"
            << "  <numMessages>         Number of messages to send\n"
            << _options << "\n";
}

//  ---------------------------------------------------------------------
/// \brief Read the command line arguments.
int ReadArgs(int argc, char *argv[], bool &_verbose, bool &_selfSubscribe,
  std::string &_master, std::string &_topic, std::string &_data,
  int &_numMessages)
{
  // Optional arguments
  po::options_description visibleDesc("Options");
  visibleDesc.add_options()
    ("help,h", "Produce help message")
    ("verbose,v", "Enable verbose mode")
    ("self-subscribe,s", "Self-subscribe to the topic")
    ("master,m", po::value<std::string>(&_master)->default_value(""),
       "Set the master endpoint");

  // Positional arguments
  po::options_description hiddenDesc("Hidden options");
  hiddenDesc.add_options()
    ("topic", po::value<std::string>(&_topic), "Topic to publish")
    ("data", po::value<std::string>(&_data), "Data")
    ("num", po::value<int>(&_numMessages), "Number of messages to send");

  // All the arguments
  po::options_description desc("Options");
  desc.add(visibleDesc).add(hiddenDesc);

  // One value per positional argument
  po::positional_options_description positionalDesc;
  positionalDesc.add("topic", 1).add("data", 1).add("num", 1);

  po::variables_map vm;

  try
  {
    po::store(po::command_line_parser(argc, argv).
              options(desc).positional(positionalDesc).run(), vm);
    po::notify(vm);
  }
  catch(boost::exception &_e)
  {
    PrintUsage(visibleDesc);
    return -1;
  }

  if (vm.count("help")  || !vm.count("topic") ||
      !vm.count("data") || !vm.count("num"))
  {
    PrintUsage(visibleDesc);
    return -1;
  }

  _verbose = false;
  if (vm.count("verbose"))
    _verbose = true;

  if (vm.count("master"))
    _master = vm["master"].as<std::string>();

  _selfSubscribe = false;
  if (vm.count("self-subscribe"))
    _selfSubscribe = true;

  return 0;
}

//  ---------------------------------------------------------------------
int main(int argc, char *argv[])
{
  // Read the command line arguments
  std::string master, topic, data;
  int numMessages, rc;
  bool verbose, selfSubscribe;
  if (ReadArgs(argc, argv, verbose, selfSubscribe, master, topic, data,
               numMessages) != 0)
    return -1;

  // Transport node
  Node node(master, verbose);

  // Advertise a topic
  rc = node.Advertise(topic);
  if (rc != 0)
    std::cout << "Advertise did not work" << std::endl;

  if (selfSubscribe)
  {
    // Self-subscribe to the topic
    rc = node.Subscribe(topic, cb);
    if (rc != 0)
      std::cout << "Subscribe did not work" << std::endl;
  }

  // Publish data
  for (int i = 0; i < numMessages; ++i)
  {
    node.Publish(topic, data);
    usleep(10000);
  }

  // Zzzzzz Zzzzzz
  std::cout << "\nPress any key to exit" << std::endl;
  getchar();

  return 0;
}


text:
//===----------------------------------------------------------------------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is dual licensed under the MIT and the University of Illinois Open
// Source Licenses. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//

// Copyright (C) 2013 Vicente J. Botet Escriba
//
//  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)

// <boost/thread/future.hpp>

// class shared_future<R>

// template <class Rep, class Period>
//   future_status
//   wait_until(const chrono::time_point<Clock, Duration>& abs_time) const;

//#define BOOST_THREAD_VERSION 3
#define BOOST_THREAD_VERSION 4
//#define BOOST_THREAD_USES_LOG
#define BOOST_THREAD_USES_LOG_THREAD_ID
#include <boost/thread/detail/log.hpp>

#include <boost/thread/future.hpp>
#include <boost/thread/thread.hpp>
#include <boost/chrono/chrono_io.hpp>
#include <boost/detail/lightweight_test.hpp>
#include "../../../timming.hpp"

#if defined BOOST_THREAD_USES_CHRONO

#ifdef BOOST_MSVC
#pragma warning(disable: 4127) // conditional expression is constant
#endif

typedef boost::chrono::milliseconds ms;
typedef boost::chrono::nanoseconds ns;

namespace boost
{
  template <typename OStream>
  OStream& operator<<(OStream& os , boost::future_status st )
  {
    os << underlying_cast<int>(st) << " ";
    return os;
  }
  template <typename T>
  struct wrap
  {
    wrap(T const& v) :
      value(v)
    {
    }
    T value;

  };

  template <typename T>
  exception_ptr make_exception_ptr(T v)
  {
    return copy_exception(wrap<T> (v));
  }
}

void func1(boost::promise<int> p)
{
  boost::this_thread::sleep_for(ms(500));
  p.set_value(3);
}

int j = 0;

void func3(boost::promise<int&> p)
{
  boost::this_thread::sleep_for(ms(500));
  j = 5;
  p.set_value(j);
}

void func5(boost::promise<void> p)
{
  boost::this_thread::sleep_for(ms(500));
  p.set_value();
}

const ms max_diff(BOOST_THREAD_TEST_TIME_MS);

int main()
{
  BOOST_THREAD_LOG << BOOST_THREAD_END_LOG;
  {
    typedef boost::chrono::high_resolution_clock Clock;
    {
      typedef int T;
      boost::promise<T> p;
      boost::shared_future<T> f((p.get_future()));
#if defined BOOST_THREAD_PROVIDES_SIGNATURE_PACKAGED_TASK && defined(BOOST_THREAD_PROVIDES_VARIADIC_THREAD)
      boost::thread(func1, boost::move(p)).detach();
#endif
      BOOST_TEST(f.valid());
      BOOST_TEST_EQ(f.wait_until(Clock::now() + ms(250)) , boost::future_status::timeout);
#if defined BOOST_THREAD_PROVIDES_SIGNATURE_PACKAGED_TASK && defined(BOOST_THREAD_PROVIDES_VARIADIC_THREAD)
#else
      func1(boost::move(p));
#endif
      BOOST_TEST(f.valid());
      BOOST_TEST_EQ(f.wait_until(Clock::now() + ms(750)) , boost::future_status::ready);
      BOOST_TEST(f.valid());
      Clock::time_point t0 = Clock::now();
      f.wait();
      Clock::time_point t1 = Clock::now();
      BOOST_TEST(f.valid());
      ns d = t1 - t0;
      BOOST_THREAD_TEST_IT(d, ns(max_diff));
    }
    {
      typedef int& T;
      boost::promise<T> p;
      boost::shared_future<T> f((p.get_future()));
#if defined BOOST_THREAD_PROVIDES_SIGNATURE_PACKAGED_TASK && defined(BOOST_THREAD_PROVIDES_VARIADIC_THREAD)
      boost::thread(func3, boost::move(p)).detach();
#endif
      BOOST_TEST(f.valid());
      BOOST_TEST_EQ(f.wait_until(Clock::now() + ms(250)) , boost::future_status::timeout);
      BOOST_TEST(f.valid());
#if defined BOOST_THREAD_PROVIDES_SIGNATURE_PACKAGED_TASK && defined(BOOST_THREAD_PROVIDES_VARIADIC_THREAD)
#else
      func3(boost::move(p));
#endif
      BOOST_TEST_EQ(f.wait_until(Clock::now() + ms(750)) , boost::future_status::ready);
      BOOST_TEST(f.valid());
      Clock::time_point t0 = Clock::now();
      f.wait();
      Clock::time_point t1 = Clock::now();
      BOOST_TEST(f.valid());
      ns d = t1 - t0;
      BOOST_THREAD_TEST_IT(d, ns(max_diff));
    }
    {
      typedef void T;
      boost::promise<T> p;
      boost::shared_future<T> f((p.get_future()));
#if defined BOOST_THREAD_PROVIDES_SIGNATURE_PACKAGED_TASK && defined(BOOST_THREAD_PROVIDES_VARIADIC_THREAD)
      boost::thread(func5, boost::move(p)).detach();
#endif
      BOOST_TEST(f.valid());
      BOOST_TEST_EQ(f.wait_until(Clock::now() + ms(250)) , boost::future_status::timeout);
      BOOST_TEST(f.valid());
#if defined BOOST_THREAD_PROVIDES_SIGNATURE_PACKAGED_TASK && defined(BOOST_THREAD_PROVIDES_VARIADIC_THREAD)
#else
      func5(boost::move(p));
#endif
      BOOST_TEST_EQ(f.wait_until(Clock::now() + ms(750)) , boost::future_status::ready);
      BOOST_TEST(f.valid());
      Clock::time_point t0 = Clock::now();
      f.wait();
      Clock::time_point t1 = Clock::now();
      BOOST_TEST(f.valid());
      ns d = t1 - t0;
      BOOST_THREAD_TEST_IT(d, ns(max_diff));
    }
  }
  BOOST_THREAD_LOG << BOOST_THREAD_END_LOG;

  return boost::report_errors();
}

#else
#error "Test not applicable: BOOST_THREAD_USES_CHRONO not defined for this platform as not supported"
#endif