text:
// RandomTeam - TCPNode.hpp

// Authors:

//     Thomas Da Costa <tdc.input@gmail.com>
//     Pierre Luce-Vayrac <p.luce.vayrac@gmail.com>

// Copyright (C) 2014-2015 Thomas Da Costa and Pierre Luce-Vayrac

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

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

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

#ifndef _TCP_NODE_H_
#define _TCP_NODE_H_

#define TCP_NODE_BUFFER_SIZE 65536

#include <memory>
#include <boost/asio.hpp>

namespace boost
{

    class thread;

}

class TCPNode
{

    public:

        TCPNode(std::unique_ptr<boost::asio::ip::tcp::socket> socket);
        virtual ~TCPNode();
        bool alive() const;
        const std::string& input() const;
        const std::string& msgToSend() const;
        bool msgSent() const;
        void setMsgToSend(const std::string& msg);
        void asyncRead();
        void asyncWrite();
        void cancel();

    private:

        void asyncReadHandler(size_t len, const boost::system::error_code& e);
        void asyncWriteHandler(size_t len, const boost::system::error_code& e);

        std::unique_ptr<boost::asio::ip::tcp::socket> m_socket;
        char m_buffer[TCP_NODE_BUFFER_SIZE];
        bool m_alive;
        std::string m_input;
        std::string m_msgToSend;
        bool m_msgSent;

};

#endif

max_stars_repo_name: tdcdev/RandomTeam

max_issues_repo_name: tdcdev/RandomTeam

max_forks_repo_name: tdcdev/RandomTeam


text:
#include <boost/test/unit_test.hpp>
#include <scorum/protocol/betting/market.hpp>
#include <defines.hpp>

namespace {
using namespace scorum;
using namespace scorum::protocol;

BOOST_AUTO_TEST_SUITE(market_type_tests)

SCORUM_TEST_CASE(create_wincases_test)
{
    {
        market_type m = result_home{};
        auto wincases = create_wincases(m);
        BOOST_CHECK_NO_THROW(wincases.first.get<result_home::yes>());
        BOOST_CHECK_NO_THROW(wincases.second.get<result_home::no>());
    }
    {
        auto wincases = create_wincases(result_draw{});
        BOOST_CHECK_NO_THROW(wincases.first.get<result_draw::yes>());
        BOOST_CHECK_NO_THROW(wincases.second.get<result_draw::no>());
    }
    {
        auto m = handicap{ -500 };
        auto wincases = create_wincases(m);
        BOOST_CHECK_NO_THROW(wincases.first.get<handicap::over>());
        BOOST_CHECK_NO_THROW(wincases.second.get<handicap::under>());
        BOOST_CHECK_EQUAL(wincases.first.get<handicap::over>().threshold, -500);
        BOOST_CHECK_EQUAL(wincases.second.get<handicap::under>().threshold, -500);
    }
    {
        auto m = correct_score{ 1, 2 };
        auto wincases = create_wincases(m);
        BOOST_CHECK_NO_THROW(wincases.first.get<correct_score::yes>());
        BOOST_CHECK_NO_THROW(wincases.second.get<correct_score::no>());
        BOOST_CHECK_EQUAL(wincases.first.get<correct_score::yes>().home, 1);
        BOOST_CHECK_EQUAL(wincases.first.get<correct_score::yes>().away, 2);
        BOOST_CHECK_EQUAL(wincases.second.get<correct_score::no>().home, 1);
        BOOST_CHECK_EQUAL(wincases.second.get<correct_score::no>().away, 2);
    }
}

SCORUM_TEST_CASE(has_trd_state_test_positive)
{
    BOOST_CHECK(has_trd_state(handicap{ 0 }));
    BOOST_CHECK(has_trd_state(handicap{ 1000 }));
    BOOST_CHECK(has_trd_state(handicap{ 2000 }));
    BOOST_CHECK(has_trd_state(handicap{ -2000 }));

    BOOST_CHECK(has_trd_state(total{ 1000 }));
    BOOST_CHECK(has_trd_state(total{ 2000 }));
}

SCORUM_TEST_CASE(has_trd_state_test_negative)
{
    BOOST_CHECK(!has_trd_state(handicap{ 500 }));
    BOOST_CHECK(!has_trd_state(handicap{ 1500 }));
    BOOST_CHECK(!has_trd_state(handicap{ 2500 }));
    BOOST_CHECK(!has_trd_state(handicap{ -1500 }));
    BOOST_CHECK(!has_trd_state(total{ 500 }));
    BOOST_CHECK(!has_trd_state(total{ 1500 }));
    BOOST_CHECK(!has_trd_state(result_home{}));
    BOOST_CHECK(!has_trd_state(result_draw{}));
    BOOST_CHECK(!has_trd_state(correct_score_away{}));
    BOOST_CHECK(!has_trd_state(correct_score{ 3, 2 }));
    BOOST_CHECK(!has_trd_state(goal_away{}));
}

BOOST_AUTO_TEST_SUITE_END()
}

ext: cpp

max_stars_repo_name: scorum/scorum

max_issues_repo_name: Scorum/Scorum

max_forks_repo_name: Scorum/Scorum


text:
/*
 *          Copyright Andrey Semashev 2007 - 2015.
 * Distributed under the Boost Software License, Version 1.0.
 *    (See accompanying file LICENSE_1_0.txt or copy at
 *          http://www.boost.org/LICENSE_1_0.txt)
 */
/*!
 * \file   channel_severity_filter.hpp
 * \author Andrey Semashev
 * \date   25.11.2012
 *
 * The header contains implementation of a minimal severity per channel filter.
 */

#ifndef BOOST_LOG_EXPRESSIONS_PREDICATES_CHANNEL_SEVERITY_FILTER_HPP_INCLUDED_
#define BOOST_LOG_EXPRESSIONS_PREDICATES_CHANNEL_SEVERITY_FILTER_HPP_INCLUDED_

#include <map>
#include <memory>
#include <utility>
#include <boost/phoenix/core/actor.hpp>
#include <boost/phoenix/core/terminal_fwd.hpp>
#include <boost/phoenix/core/is_nullary.hpp>
#include <boost/phoenix/core/environment.hpp>
#include <boost/fusion/sequence/intrinsic/at_c.hpp>
#include <boost/type_traits/remove_cv.hpp>
#include <boost/type_traits/remove_reference.hpp>
#include <boost/log/detail/config.hpp>
#include <boost/log/detail/allocator_traits.hpp>
#include <boost/log/detail/custom_terminal_spec.hpp>
#include <boost/log/attributes/attribute_name.hpp>
#include <boost/log/attributes/fallback_policy.hpp>
#include <boost/log/attributes/value_visitation.hpp>
#include <boost/log/utility/functional/logical.hpp>
#include <boost/log/expressions/attr_fwd.hpp>
#include <boost/log/expressions/keyword_fwd.hpp>
#include <boost/log/detail/header.hpp>

#ifdef BOOST_HAS_PRAGMA_ONCE
#pragma once
#endif

namespace boost {

BOOST_LOG_OPEN_NAMESPACE

namespace expressions {

template<
    typename ChannelT,
    typename SeverityT,
    typename ChannelFallbackT = fallback_to_none,
    typename SeverityFallbackT = fallback_to_none,
    typename ChannelOrderT = less,
    typename SeverityCompareT = greater_equal,
    typename AllocatorT = std::allocator< void >
>
class channel_severity_filter_terminal
{
public:
#ifndef BOOST_LOG_DOXYGEN_PASS
    //! Internal typedef for type categorization
    typedef void _is_boost_log_terminal;
#endif

    //! Function result type
    typedef bool result_type;

    //! Channel attribute value type
    typedef ChannelT channel_value_type;
    //! Channel fallback policy
    typedef ChannelFallbackT channel_fallback_policy;
    //! Severity level attribute value type
    typedef SeverityT severity_value_type;
    //! Severity level fallback policy
    typedef SeverityFallbackT severity_fallback_policy;

private:
    //! Channel to severity mapping type
    typedef std::map<
        channel_value_type,
        severity_value_type,
        ChannelOrderT,
        typename boost::log::aux::rebind_alloc< AllocatorT, std::pair< const channel_value_type, severity_value_type > >::type
    > mapping_type;
    //! Attribute value visitor invoker for channel
    typedef value_visitor_invoker< channel_value_type, channel_fallback_policy > channel_visitor_invoker_type;
    //! Attribute value visitor invoker for severity level
    typedef value_visitor_invoker< severity_value_type, severity_fallback_policy > severity_visitor_invoker_type;

    //! Channel visitor
    template< typename ArgT >
    struct channel_visitor
    {
        typedef void result_type;

        channel_visitor(channel_severity_filter_terminal const& self, ArgT arg, bool& res) : m_self(self), m_arg(arg), m_res(res)
        {
        }

        result_type operator() (channel_value_type const& channel) const
        {
            m_self.visit_channel(channel, m_arg, m_res);
        }

    private:
        channel_severity_filter_terminal const& m_self;
        ArgT m_arg;
        bool& m_res;
    };

    //! Severity level visitor
    struct severity_visitor
    {
        typedef void result_type;

        severity_visitor(channel_severity_filter_terminal const& self, severity_value_type const& severity, bool& res) : m_self(self), m_severity(severity), m_res(res)
        {
        }

        result_type operator() (severity_value_type const& severity) const
        {
            m_self.visit_severity(severity, m_severity, m_res);
        }

    private:
        channel_severity_filter_terminal const& m_self;
        severity_value_type const& m_severity;
        bool& m_res;
    };

private:
    //! Channel attribute name
    attribute_name m_channel_name;
    //! Severity level attribute name
    attribute_name m_severity_name;
    //! Channel value visitor invoker
    channel_visitor_invoker_type m_channel_visitor_invoker;
    //! Severity level value visitor invoker
    severity_visitor_invoker_type m_severity_visitor_invoker;

    //! Channel to severity level mapping
    mapping_type m_mapping;
    //! Severity checking predicate
    SeverityCompareT m_severity_compare;

    //! Default result
    bool m_default;

public:
    //! Initializing constructor
    channel_severity_filter_terminal
    (
        attribute_name const& channel_name,
        attribute_name const& severity_name,
        channel_fallback_policy const& channel_fallback = channel_fallback_policy(),
        severity_fallback_policy const& severity_fallback = severity_fallback_policy(),
        ChannelOrderT const& channel_order = ChannelOrderT(),
        SeverityCompareT const& severity_compare = SeverityCompareT()
    ) :
        m_channel_name(channel_name),
        m_severity_name(severity_name),
        m_channel_visitor_invoker(channel_fallback),
        m_severity_visitor_invoker(severity_fallback),
        m_mapping(channel_order),
        m_severity_compare(severity_compare),
        m_default(false)
    {
    }

    //! Adds a new element to the mapping
    void add(channel_value_type const& channel, severity_value_type const& severity)
    {
        typedef typename mapping_type::iterator iterator;
        std::pair< iterator, bool > res = m_mapping.insert(typename mapping_type::value_type(channel, severity));
        if (!res.second)
            res.first->second = severity;
    }

    //! Sets the default result of the predicate
    void set_default(bool def)
    {
        m_default = def;
    }

    //! Invokation operator
    template< typename ContextT >
    result_type operator() (ContextT const& ctx) const
    {
        result_type res = m_default;

        typedef typename remove_cv<
            typename remove_reference< typename phoenix::result_of::env< ContextT >::type >::type
        >::type env_type;
        typedef typename env_type::args_type args_type;
        typedef typename fusion::result_of::at_c< args_type, 0 >::type arg_type;
        arg_type arg = fusion::at_c< 0 >(phoenix::env(ctx).args());

        m_channel_visitor_invoker(m_channel_name, arg, channel_visitor< arg_type >(*this, arg, res));

        return res;
    }

private:
    //! Visits channel name
    template< typename ArgT >
    void visit_channel(channel_value_type const& channel, ArgT const& arg, bool& res) const
    {
        typename mapping_type::const_iterator it = m_mapping.find(channel);
        if (it != m_mapping.end())
        {
            m_severity_visitor_invoker(m_severity_name, arg, severity_visitor(*this, it->second, res));
        }
    }

    //! Visits severity level
    void visit_severity(severity_value_type const& left, severity_value_type const& right, bool& res) const
    {
        res = m_severity_compare(left, right);
    }
};

template<
    typename ChannelT,
    typename SeverityT,
    typename ChannelFallbackT = fallback_to_none,
    typename SeverityFallbackT = fallback_to_none,
    typename ChannelOrderT = less,
    typename SeverityCompareT = greater_equal,
    typename AllocatorT = std::allocator< void >,
    template< typename > class ActorT = phoenix::actor
>
class channel_severity_filter_actor :
    public ActorT< channel_severity_filter_terminal< ChannelT, SeverityT, ChannelFallbackT, SeverityFallbackT, ChannelOrderT, SeverityCompareT, AllocatorT > >
{
private:
    //! Self type
    typedef channel_severity_filter_actor this_type;

public:
    //! Terminal type
    typedef channel_severity_filter_terminal< ChannelT, SeverityT, ChannelFallbackT, SeverityFallbackT, ChannelOrderT, SeverityCompareT, AllocatorT > terminal_type;
    //! Base actor type
    typedef ActorT< terminal_type > base_type;

    //! Channel attribute value type
    typedef typename terminal_type::channel_value_type channel_value_type;
    //! Channel fallback policy
    typedef typename terminal_type::channel_fallback_policy channel_fallback_policy;
    //! Severity level attribute value type
    typedef typename terminal_type::severity_value_type severity_value_type;
    //! Severity level fallback policy
    typedef typename terminal_type::severity_fallback_policy severity_fallback_policy;

private:
    //! An auxiliary pseudo-reference to implement insertion through subscript operator
    class subscript_result
    {
    private:
        channel_severity_filter_actor& m_owner;
        channel_value_type const& m_channel;

    public:
        subscript_result(channel_severity_filter_actor& owner, channel_value_type const& channel) : m_owner(owner), m_channel(channel)
        {
        }

        void operator= (severity_value_type const& severity)
        {
            m_owner.add(m_channel, severity);
        }
    };

public:
    //! Initializing constructor
    explicit channel_severity_filter_actor(base_type const& act) : base_type(act)
    {
    }
    //! Copy constructor
    channel_severity_filter_actor(channel_severity_filter_actor const& that) : base_type(static_cast< base_type const& >(that))
    {
    }

    //! Sets the default function result
    this_type& set_default(bool def)
    {
        this->proto_expr_.child0.set_default(def);
        return *this;
    }

    //! Adds a new element to the mapping
    this_type& add(channel_value_type const& channel, severity_value_type const& severity)
    {
        this->proto_expr_.child0.add(channel, severity);
        return *this;
    }

    //! Alternative interface for adding a new element to the mapping
    subscript_result operator[] (channel_value_type const& channel)
    {
        return subscript_result(*this, channel);
    }
};

/*!
 * The function generates a filtering predicate that checks the severity levels of log records in different channels. The predicate will return \c true
 * if the record severity level is not less than the threshold for the channel the record belongs to.
 */
template< typename ChannelT, typename SeverityT >
BOOST_FORCEINLINE channel_severity_filter_actor< ChannelT, SeverityT >
channel_severity_filter(attribute_name const& channel_name, attribute_name const& severity_name)
{
    typedef channel_severity_filter_actor< ChannelT, SeverityT > result_type;
    typedef typename result_type::terminal_type terminal_type;
    typename result_type::base_type act = {{ terminal_type(channel_name, severity_name) }};
    return result_type(act);
}

//! \overload
template< typename SeverityT, typename ChannelDescriptorT, template< typename > class ActorT >
BOOST_FORCEINLINE channel_severity_filter_actor< typename ChannelDescriptorT::value_type, SeverityT, fallback_to_none, fallback_to_none, less, greater_equal, std::allocator< void >, ActorT >
channel_severity_filter(attribute_keyword< ChannelDescriptorT, ActorT > const& channel_keyword, attribute_name const& severity_name)
{
    typedef channel_severity_filter_actor< typename ChannelDescriptorT::value_type, SeverityT, fallback_to_none, fallback_to_none, less, greater_equal, std::allocator< void >, ActorT > result_type;
    typedef typename result_type::terminal_type terminal_type;
    typename result_type::base_type act = {{ terminal_type(channel_keyword.get_name(), severity_name) }};
    return result_type(act);
}

//! \overload
template< typename ChannelT, typename SeverityDescriptorT, template< typename > class ActorT >
BOOST_FORCEINLINE channel_severity_filter_actor< ChannelT, typename SeverityDescriptorT::value_type, fallback_to_none, fallback_to_none, less, greater_equal, std::allocator< void >, ActorT >
channel_severity_filter(attribute_name const& channel_name, attribute_keyword< SeverityDescriptorT, ActorT > const& severity_keyword)
{
    typedef channel_severity_filter_actor< ChannelT, typename SeverityDescriptorT::value_type, fallback_to_none, fallback_to_none, less, greater_equal, std::allocator< void >, ActorT > result_type;
    typedef typename result_type::terminal_type terminal_type;
    typename result_type::base_type act = {{ terminal_type(channel_name, severity_keyword.get_name()) }};
    return result_type(act);
}

//! \overload
template< typename ChannelDescriptorT, typename SeverityDescriptorT, template< typename > class ActorT >
BOOST_FORCEINLINE channel_severity_filter_actor< typename ChannelDescriptorT::value_type, typename SeverityDescriptorT::value_type, fallback_to_none, fallback_to_none, less, greater_equal, std::allocator< void >, ActorT >
channel_severity_filter(attribute_keyword< ChannelDescriptorT, ActorT > const& channel_keyword, attribute_keyword< SeverityDescriptorT, ActorT > const& severity_keyword)
{
    typedef channel_severity_filter_actor< typename ChannelDescriptorT::value_type, typename SeverityDescriptorT::value_type, fallback_to_none, fallback_to_none, less, greater_equal, std::allocator< void >, ActorT > result_type;
    typedef typename result_type::terminal_type terminal_type;
    typename result_type::base_type act = {{ terminal_type(channel_keyword.get_name(), severity_keyword.get_name()) }};
    return result_type(act);
}

//! \overload
template< typename SeverityT, typename ChannelT, typename ChannelFallbackT, typename ChannelTagT, template< typename > class ActorT >
BOOST_FORCEINLINE channel_severity_filter_actor< ChannelT, SeverityT, ChannelFallbackT, fallback_to_none, less, greater_equal, std::allocator< void >, ActorT >
channel_severity_filter(attribute_actor< ChannelT, ChannelFallbackT, ChannelTagT, ActorT > const& channel_placeholder, attribute_name const& severity_name)
{
    typedef channel_severity_filter_actor< ChannelT, SeverityT, ChannelFallbackT, fallback_to_none, less, greater_equal, std::allocator< void >, ActorT > result_type;
    typedef typename result_type::terminal_type terminal_type;
    typename result_type::base_type act = {{ terminal_type(channel_placeholder.get_name(), severity_name, channel_placeholder.get_fallback_policy()) }};
    return result_type(act);
}

//! \overload
template< typename ChannelT, typename SeverityT, typename SeverityFallbackT, typename SeverityTagT, template< typename > class ActorT >
BOOST_FORCEINLINE channel_severity_filter_actor< ChannelT, SeverityT, fallback_to_none, SeverityFallbackT, less, greater_equal, std::allocator< void >, ActorT >
channel_severity_filter(attribute_name const& channel_name, attribute_actor< SeverityT, SeverityFallbackT, SeverityTagT, ActorT > const& severity_placeholder)
{
    typedef channel_severity_filter_actor< ChannelT, SeverityT, fallback_to_none, SeverityFallbackT, less, greater_equal, std::allocator< void >, ActorT > result_type;
    typedef typename result_type::terminal_type terminal_type;
    typename result_type::base_type act = {{ terminal_type(channel_name, severity_placeholder.get_name(), fallback_to_none(), severity_placeholder.get_fallback_policy()) }};
    return result_type(act);
}

//! \overload
template< typename ChannelT, typename ChannelFallbackT, typename ChannelTagT, typename SeverityT, typename SeverityFallbackT, typename SeverityTagT, template< typename > class ActorT >
BOOST_FORCEINLINE channel_severity_filter_actor< ChannelT, SeverityT, ChannelFallbackT, SeverityFallbackT, less, greater_equal, std::allocator< void >, ActorT >
channel_severity_filter(attribute_actor< ChannelT, ChannelFallbackT, ChannelTagT, ActorT > const& channel_placeholder, attribute_actor< SeverityT, SeverityFallbackT, SeverityTagT, ActorT > const& severity_placeholder)
{
    typedef channel_severity_filter_actor< ChannelT, SeverityT, ChannelFallbackT, SeverityFallbackT, less, greater_equal, std::allocator< void >, ActorT > result_type;
    typedef typename result_type::terminal_type terminal_type;
    typename result_type::base_type act = {{ terminal_type(channel_placeholder.get_name(), severity_placeholder.get_name(), channel_placeholder.get_fallback_policy(), severity_placeholder.get_fallback_policy()) }};
    return result_type(act);
}

//! \overload
template< typename ChannelT, typename SeverityT, typename SeverityCompareT >
BOOST_FORCEINLINE channel_severity_filter_actor< ChannelT, SeverityT, fallback_to_none, fallback_to_none, less, SeverityCompareT >
channel_severity_filter(attribute_name const& channel_name, attribute_name const& severity_name, SeverityCompareT const& severity_compare)
{
    typedef channel_severity_filter_actor< ChannelT, SeverityT, fallback_to_none, fallback_to_none, less, SeverityCompareT > result_type;
    typedef typename result_type::terminal_type terminal_type;
    typename result_type::base_type act = {{ terminal_type(channel_name, severity_name, fallback_to_none(), fallback_to_none(), less(), severity_compare) }};
    return result_type(act);
}

//! \overload
template< typename SeverityT, typename ChannelDescriptorT, template< typename > class ActorT, typename SeverityCompareT >
BOOST_FORCEINLINE channel_severity_filter_actor< typename ChannelDescriptorT::value_type, SeverityT, fallback_to_none, fallback_to_none, less, SeverityCompareT, std::allocator< void >, ActorT >
channel_severity_filter(attribute_keyword< ChannelDescriptorT, ActorT > const& channel_keyword, attribute_name const& severity_name, SeverityCompareT const& severity_compare)
{
    typedef channel_severity_filter_actor< typename ChannelDescriptorT::value_type, SeverityT, fallback_to_none, fallback_to_none, less, SeverityCompareT, std::allocator< void >, ActorT > result_type;
    typedef typename result_type::terminal_type terminal_type;
    typename result_type::base_type act = {{ terminal_type(channel_keyword.get_name(), severity_name, fallback_to_none(), fallback_to_none(), less(), severity_compare) }};
    return result_type(act);
}

//! \overload
template< typename ChannelT, typename SeverityDescriptorT, template< typename > class ActorT, typename SeverityCompareT >
BOOST_FORCEINLINE channel_severity_filter_actor< ChannelT, typename SeverityDescriptorT::value_type, fallback_to_none, fallback_to_none, less, SeverityCompareT, std::allocator< void >, ActorT >
channel_severity_filter(attribute_name const& channel_name, attribute_keyword< SeverityDescriptorT, ActorT > const& severity_keyword, SeverityCompareT const& severity_compare)
{
    typedef channel_severity_filter_actor< ChannelT, typename SeverityDescriptorT::value_type, fallback_to_none, fallback_to_none, less, SeverityCompareT, std::allocator< void >, ActorT > result_type;
    typedef typename result_type::terminal_type terminal_type;
    typename result_type::base_type act = {{ terminal_type(channel_name, severity_keyword.get_name(), fallback_to_none(), fallback_to_none(), less(), severity_compare) }};
    return result_type(act);
}

//! \overload
template< typename ChannelDescriptorT, typename SeverityDescriptorT, template< typename > class ActorT, typename SeverityCompareT >
BOOST_FORCEINLINE channel_severity_filter_actor< typename ChannelDescriptorT::value_type, typename SeverityDescriptorT::value_type, fallback_to_none, fallback_to_none, less, SeverityCompareT, std::allocator< void >, ActorT >
channel_severity_filter(attribute_keyword< ChannelDescriptorT, ActorT > const& channel_keyword, attribute_keyword< SeverityDescriptorT, ActorT > const& severity_keyword, SeverityCompareT const& severity_compare)
{
    typedef channel_severity_filter_actor< typename ChannelDescriptorT::value_type, typename SeverityDescriptorT::value_type, fallback_to_none, fallback_to_none, less, SeverityCompareT, std::allocator< void >, ActorT > result_type;
    typedef typename result_type::terminal_type terminal_type;
    typename result_type::base_type act = {{ terminal_type(channel_keyword.get_name(), severity_keyword.get_name(), fallback_to_none(), fallback_to_none(), less(), severity_compare) }};
    return result_type(act);
}

//! \overload
template< typename SeverityT, typename ChannelT, typename ChannelFallbackT, typename ChannelTagT, template< typename > class ActorT, typename SeverityCompareT >
BOOST_FORCEINLINE channel_severity_filter_actor< ChannelT, SeverityT, ChannelFallbackT, fallback_to_none, less, SeverityCompareT, std::allocator< void >, ActorT >
channel_severity_filter(attribute_actor< ChannelT, ChannelFallbackT, ChannelTagT, ActorT > const& channel_placeholder, attribute_name const& severity_name, SeverityCompareT const& severity_compare)
{
    typedef channel_severity_filter_actor< ChannelT, SeverityT, ChannelFallbackT, fallback_to_none, less, SeverityCompareT, std::allocator< void >, ActorT > result_type;
    typedef typename result_type::terminal_type terminal_type;
    typename result_type::base_type act = {{ terminal_type(channel_placeholder.get_name(), severity_name, channel_placeholder.get_fallback_policy(), fallback_to_none(), less(), severity_compare) }};
    return result_type(act);
}

//! \overload
template< typename ChannelT, typename SeverityT, typename SeverityFallbackT, typename SeverityTagT, template< typename > class ActorT, typename SeverityCompareT >
BOOST_FORCEINLINE channel_severity_filter_actor< ChannelT, SeverityT, fallback_to_none, SeverityFallbackT, less, SeverityCompareT, std::allocator< void >, ActorT >
channel_severity_filter(attribute_name const& channel_name, attribute_actor< SeverityT, SeverityFallbackT, SeverityTagT, ActorT > const& severity_placeholder, SeverityCompareT const& severity_compare)
{
    typedef channel_severity_filter_actor< ChannelT, SeverityT, fallback_to_none, SeverityFallbackT, less, SeverityCompareT, std::allocator< void >, ActorT > result_type;
    typedef typename result_type::terminal_type terminal_type;
    typename result_type::base_type act = {{ terminal_type(channel_name, severity_placeholder.get_name(), fallback_to_none(), severity_placeholder.get_fallback_policy(), less(), severity_compare) }};
    return result_type(act);
}

//! \overload
template< typename ChannelT, typename ChannelFallbackT, typename ChannelTagT, typename SeverityT, typename SeverityFallbackT, typename SeverityTagT, template< typename > class ActorT, typename SeverityCompareT >
BOOST_FORCEINLINE channel_severity_filter_actor< ChannelT, SeverityT, ChannelFallbackT, SeverityFallbackT, less, SeverityCompareT, std::allocator< void >, ActorT >
channel_severity_filter(attribute_actor< ChannelT, ChannelFallbackT, ChannelTagT, ActorT > const& channel_placeholder, attribute_actor< SeverityT, SeverityFallbackT, SeverityTagT, ActorT > const& severity_placeholder, SeverityCompareT const& severity_compare)
{
    typedef channel_severity_filter_actor< ChannelT, SeverityT, ChannelFallbackT, SeverityFallbackT, less, SeverityCompareT, std::allocator< void >, ActorT > result_type;
    typedef typename result_type::terminal_type terminal_type;
    typename result_type::base_type act = {{ terminal_type(channel_placeholder.get_name(), severity_placeholder.get_name(), channel_placeholder.get_fallback_policy(), severity_placeholder.get_fallback_policy(), less(), severity_compare) }};
    return result_type(act);
}

//! \overload
template< typename ChannelT, typename SeverityT, typename SeverityCompareT, typename ChannelOrderT >
BOOST_FORCEINLINE channel_severity_filter_actor< ChannelT, SeverityT, fallback_to_none, fallback_to_none, ChannelOrderT, SeverityCompareT >
channel_severity_filter(attribute_name const& channel_name, attribute_name const& severity_name, SeverityCompareT const& severity_compare, ChannelOrderT const& channel_order)
{
    typedef channel_severity_filter_actor< ChannelT, SeverityT, fallback_to_none, fallback_to_none, ChannelOrderT, SeverityCompareT > result_type;
    typedef typename result_type::terminal_type terminal_type;
    typename result_type::base_type act = {{ terminal_type(channel_name, severity_name, fallback_to_none(), fallback_to_none(), channel_order, severity_compare) }};
    return result_type(act);
}

//! \overload
template< typename SeverityT, typename ChannelDescriptorT, template< typename > class ActorT, typename SeverityCompareT, typename ChannelOrderT >
BOOST_FORCEINLINE channel_severity_filter_actor< typename ChannelDescriptorT::value_type, SeverityT, fallback_to_none, fallback_to_none, ChannelOrderT, SeverityCompareT, std::allocator< void >, ActorT >
channel_severity_filter(attribute_keyword< ChannelDescriptorT, ActorT > const& channel_keyword, attribute_name const& severity_name, SeverityCompareT const& severity_compare, ChannelOrderT const& channel_order)
{
    typedef channel_severity_filter_actor< typename ChannelDescriptorT::value_type, SeverityT, fallback_to_none, fallback_to_none, ChannelOrderT, SeverityCompareT, std::allocator< void >, ActorT > result_type;
    typedef typename result_type::terminal_type terminal_type;
    typename result_type::base_type act = {{ terminal_type(channel_keyword.get_name(), severity_name, fallback_to_none(), fallback_to_none(), channel_order, severity_compare) }};
    return result_type(act);
}

//! \overload
template< typename ChannelT, typename SeverityDescriptorT, template< typename > class ActorT, typename SeverityCompareT, typename ChannelOrderT >
BOOST_FORCEINLINE channel_severity_filter_actor< ChannelT, typename SeverityDescriptorT::value_type, fallback_to_none, fallback_to_none, ChannelOrderT, SeverityCompareT, std::allocator< void >, ActorT >
channel_severity_filter(attribute_name const& channel_name, attribute_keyword< SeverityDescriptorT, ActorT > const& severity_keyword, SeverityCompareT const& severity_compare, ChannelOrderT const& channel_order)
{
    typedef channel_severity_filter_actor< ChannelT, typename SeverityDescriptorT::value_type, fallback_to_none, fallback_to_none, ChannelOrderT, SeverityCompareT, std::allocator< void >, ActorT > result_type;
    typedef typename result_type::terminal_type terminal_type;
    typename result_type::base_type act = {{ terminal_type(channel_name, severity_keyword.get_name(), fallback_to_none(), fallback_to_none(), channel_order, severity_compare) }};
    return result_type(act);
}

//! \overload
template< typename ChannelDescriptorT, typename SeverityDescriptorT, template< typename > class ActorT, typename SeverityCompareT, typename ChannelOrderT >
BOOST_FORCEINLINE channel_severity_filter_actor< typename ChannelDescriptorT::value_type, typename SeverityDescriptorT::value_type, fallback_to_none, fallback_to_none, ChannelOrderT, SeverityCompareT, std::allocator< void >, ActorT >
channel_severity_filter(attribute_keyword< ChannelDescriptorT, ActorT > const& channel_keyword, attribute_keyword< SeverityDescriptorT, ActorT > const& severity_keyword, SeverityCompareT const& severity_compare, ChannelOrderT const& channel_order)
{
    typedef channel_severity_filter_actor< typename ChannelDescriptorT::value_type, typename SeverityDescriptorT::value_type, fallback_to_none, fallback_to_none, ChannelOrderT, SeverityCompareT, std::allocator< void >, ActorT > result_type;
    typedef typename result_type::terminal_type terminal_type;
    typename result_type::base_type act = {{ terminal_type(channel_keyword.get_name(), severity_keyword.get_name(), fallback_to_none(), fallback_to_none(), channel_order, severity_compare) }};
    return result_type(act);
}

//! \overload
template< typename SeverityT, typename ChannelT, typename ChannelFallbackT, typename ChannelTagT, template< typename > class ActorT, typename SeverityCompareT, typename ChannelOrderT >
BOOST_FORCEINLINE channel_severity_filter_actor< ChannelT, SeverityT, ChannelFallbackT, fallback_to_none, ChannelOrderT, SeverityCompareT, std::allocator< void >, ActorT >
channel_severity_filter(attribute_actor< ChannelT, ChannelFallbackT, ChannelTagT, ActorT > const& channel_placeholder, attribute_name const& severity_name, SeverityCompareT const& severity_compare, ChannelOrderT const& channel_order)
{
    typedef channel_severity_filter_actor< ChannelT, SeverityT, ChannelFallbackT, fallback_to_none, ChannelOrderT, SeverityCompareT, std::allocator< void >, ActorT > result_type;
    typedef typename result_type::terminal_type terminal_type;
    typename result_type::base_type act = {{ terminal_type(channel_placeholder.get_name(), severity_name, channel_placeholder.get_fallback_policy(), fallback_to_none(), channel_order, severity_compare) }};
    return result_type(act);
}

//! \overload
template< typename ChannelT, typename SeverityT, typename SeverityFallbackT, typename SeverityTagT, template< typename > class ActorT, typename SeverityCompareT, typename ChannelOrderT >
BOOST_FORCEINLINE channel_severity_filter_actor< ChannelT, SeverityT, fallback_to_none, SeverityFallbackT, ChannelOrderT, SeverityCompareT, std::allocator< void >, ActorT >
channel_severity_filter(attribute_name const& channel_name, attribute_actor< SeverityT, SeverityFallbackT, SeverityTagT, ActorT > const& severity_placeholder, SeverityCompareT const& severity_compare, ChannelOrderT const& channel_order)
{
    typedef channel_severity_filter_actor< ChannelT, SeverityT, fallback_to_none, SeverityFallbackT, ChannelOrderT, SeverityCompareT, std::allocator< void >, ActorT > result_type;
    typedef typename result_type::terminal_type terminal_type;
    typename result_type::base_type act = {{ terminal_type(channel_name, severity_placeholder.get_name(), fallback_to_none(), severity_placeholder.get_fallback_policy(), channel_order, severity_compare) }};
    return result_type(act);
}

//! \overload
template< typename ChannelT, typename ChannelFallbackT, typename ChannelTagT, typename SeverityT, typename SeverityFallbackT, typename SeverityTagT, template< typename > class ActorT, typename SeverityCompareT, typename ChannelOrderT >
BOOST_FORCEINLINE channel_severity_filter_actor< ChannelT, SeverityT, ChannelFallbackT, SeverityFallbackT, ChannelOrderT, SeverityCompareT, std::allocator< void >, ActorT >
channel_severity_filter(attribute_actor< ChannelT, ChannelFallbackT, ChannelTagT, ActorT > const& channel_placeholder, attribute_actor< SeverityT, SeverityFallbackT, SeverityTagT, ActorT > const& severity_placeholder, SeverityCompareT const& severity_compare, ChannelOrderT const& channel_order)
{
    typedef channel_severity_filter_actor< ChannelT, SeverityT, ChannelFallbackT, SeverityFallbackT, ChannelOrderT, SeverityCompareT, std::allocator< void >, ActorT > result_type;
    typedef typename result_type::terminal_type terminal_type;
    typename result_type::base_type act = {{ terminal_type(channel_placeholder.get_name(), severity_placeholder.get_name(), channel_placeholder.get_fallback_policy(), severity_placeholder.get_fallback_policy(), channel_order, severity_compare) }};
    return result_type(act);
}

} // namespace expressions

BOOST_LOG_CLOSE_NAMESPACE // namespace log

#ifndef BOOST_LOG_DOXYGEN_PASS

namespace phoenix {

namespace result_of {

template<
    typename ChannelT,
    typename SeverityT,
    typename ChannelFallbackT,
    typename SeverityFallbackT,
    typename ChannelOrderT,
    typename SeverityCompareT,
    typename AllocatorT
>
struct is_nullary< custom_terminal< boost::log::expressions::channel_severity_filter_terminal< ChannelT, SeverityT, ChannelFallbackT, SeverityFallbackT, ChannelOrderT, SeverityCompareT, AllocatorT > > > :
    public mpl::false_
{
};

} // namespace result_of

} // namespace phoenix

#endif

} // namespace boost

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

#endif // BOOST_LOG_EXPRESSIONS_PREDICATES_CHANNEL_SEVERITY_FILTER_HPP_INCLUDED_

ext: hpp

max_stars_repo_name: kindlychung/mediasoup-sfu-cpp

max_issues_repo_name: kindlychung/mediasoup-sfu-cpp

max_forks_repo_name: kindlychung/mediasoup-sfu-cpp


text:
//
// Created by robin on 2018/9/1.
// Copyright (c) 2018 Robin. All rights reserved.
//

#include "polynomial.h"
#include "bytes.h"

#include <boost/lexical_cast.hpp>
#include <experimental/iterator>

namespace satz::gf2::v2 {

Polynomial Polynomial::from_ulong (unsigned long l) {
  static_assert(sizeof(l) == 8);
  uint8_t* start = reinterpret_cast<uint8_t*>(&l);
  return from_bytes({start, start + sizeof(l)});
}

Polynomial Polynomial::from_bytes (gsl::span<uint8_t> bytes) {
  return Polynomial(satz::bytes::make_indices<int_type>(bytes));
}

Polynomial Polynomial::from_bytes (gsl::span<uint8_t> bytes,
    Polynomial::int_type degree) {

  Expects(bytes.size() * 8 > degree);

  std::vector<int_type> d = satz::bytes::make_indices<int_type>(bytes);
  auto it = std::lower_bound(d.begin(), d.end(), degree);
  if (it == d.end() || *it != degree) {
    d.erase(it, d.end());
    d.push_back(static_cast<int>(degree));
  } else { // `*it == degree`
    std::advance(it, 1);
    d.erase(it, d.end());
  }

  return Polynomial(std::move(d));
}

Polynomial Polynomial::make_random (Polynomial::int_type degree) {
  auto bytes = satz::bytes::make_random_bytes(static_cast<int>(degree / 8 + 1));
  return Polynomial::from_bytes(bytes, degree);
}

Polynomial Polynomial::make_irreducible (Polynomial::int_type degree) {
  Expects(degree > 0);

  // According to
  //    Some applications of Rabin’s fingerprinting method [Broder],
  // the total number of irreducible polynomials of degree $k$ with
  // coefficients in $Z_2$ is greater than $(2^k - 2^{k/2})/k$. Thus
  // the probability of picking an irreducible polynomial with a
  // uniformly random draw is roughly greater than $1/k$. If we try
  // $m$ independent draws, the probability of failing to obtain an
  // irreducible polynomial is roughly less than $(1 - 1/k)^m$, which
  // is roughly $e^{-m/k}$.
  int magic_number = 15;
  auto trials = degree * magic_number;
  while (trials-- > 0) {
    auto p = Polynomial::make_random(degree);
    if (is_irreducible(p)) return p;
  }

  throw std::runtime_error("fail to obtain an irreducible polynomial");
}

std::vector<uint8_t> Polynomial::to_bytes () const {
  const int d = degree();
  const size_t count = (d >= 0) ? (d / 8 + 1) : 0;

  std::vector<uint8_t> ret(count, 0);
  std::for_each(deg_.begin(),
                deg_.end(),
                [&] (int_type n) {
                  const auto i = n / 8;
                  const auto j = n % 8;
                  ret[i] = ret[i] | uint8_t(0x1 << j);
                });
  return ret;
}

Polynomial::operator bool () const {return !empty();}

bool operator == (const Polynomial& lhs, const Polynomial& rhs) {
  return lhs.deg_ == rhs.deg_;
}

bool operator != (const Polynomial& lhs, const Polynomial& rhs) {
  return !(rhs == lhs);
}

Polynomial& Polynomial::operator ^= (const Polynomial& rhs) {
  Polynomial res = *this ^rhs;
  deg_.swap(res.deg_);
  return *this;
}

Polynomial& Polynomial::operator |= (const Polynomial& rhs) {
  Polynomial res = *this | rhs;
  deg_.swap(res.deg_);
  return *this;
}

Polynomial& Polynomial::operator &= (const Polynomial& rhs) {
  Polynomial res = *this & rhs;
  deg_.swap(res.deg_);
  return *this;
}

Polynomial& Polynomial::operator += (const Polynomial& rhs) {
  Polynomial res = *this + rhs;
  deg_.swap(res.deg_);
  return *this;

}

Polynomial& Polynomial::operator -= (const Polynomial& rhs) {
  Polynomial res = *this - rhs;
  deg_.swap(res.deg_);
  return *this;
}

Polynomial& Polynomial::operator *= (const Polynomial& rhs) {
  Polynomial res = *this * rhs;
  deg_.swap(res.deg_);
  return *this;
}

Polynomial& Polynomial::operator %= (const Polynomial& rhs) {
  Polynomial res = *this % rhs;
  deg_.swap(res.deg_);
  return *this;
}

Polynomial& Polynomial::operator <<= (Polynomial::int_type n) {
  Expects(n >= 0);
  Polynomial res = *this << n;
  deg_.swap(res.deg_);
  return *this;
}

Polynomial& Polynomial::operator >>= (Polynomial::int_type n) {
  Expects(n >= 0);
  Polynomial res = *this >> n;
  deg_.swap(res.deg_);
  return *this;
}

Polynomial operator ^ (const Polynomial& lhs, const Polynomial& rhs) {
  Polynomial ret;
  std::set_symmetric_difference(lhs.deg_.begin(),
                                lhs.deg_.end(),
                                rhs.deg_.begin(),
                                rhs.deg_.end(),
                                std::back_inserter(ret.deg_));
  return ret;
}

Polynomial operator | (const Polynomial& lhs, const Polynomial& rhs) {
  Polynomial ret;
  std::set_union(lhs.deg_.begin(),
                 lhs.deg_.end(),
                 rhs.deg_.begin(),
                 rhs.deg_.end(),
                 std::back_inserter(ret.deg_));
  return ret;
}

Polynomial operator & (const Polynomial& lhs, const Polynomial& rhs) {
  Polynomial ret;
  std::set_intersection(lhs.deg_.begin(),
                        lhs.deg_.end(),
                        rhs.deg_.begin(),
                        rhs.deg_.end(),
                        std::back_inserter(ret.deg_));
  return ret;
}

Polynomial operator + (const Polynomial& lhs, const Polynomial& rhs) {
  return lhs ^ rhs;
}

Polynomial operator - (const Polynomial& lhs, const Polynomial& rhs) {
  return lhs ^ rhs;
}

template<typename T, typename N>
static void flip (std::vector<T>& bytes, N n) {
  bytes[n / 8] ^= (1 << (n % 8));
}

Polynomial operator * (const Polynomial& lhs, const Polynomial& rhs) {
  if (lhs.degree() == 0 || rhs.degree() == 0) return Polynomial{};

  auto degree_sum = lhs.degree() + rhs.degree();
  std::vector<uint8_t> bytes(degree_sum / 8 + 1, 0);
  for (const auto& x : lhs.deg_)
    for (const auto& y : rhs.deg_)
      flip(bytes, x + y);
  return Polynomial::from_bytes(bytes);
}

Polynomial Polynomial::operator << (Polynomial::int_type n) const {
  Expects(n >= 0);

  Polynomial ret;
  std::transform(deg_.begin(),
                 deg_.end(),
                 std::back_inserter(ret.deg_),
                 [&n] (const auto& m) {return m + n;});
  return ret;
}

Polynomial Polynomial::operator >> (Polynomial::int_type n) const {
  Expects(n >= 0);

  Polynomial ret;
  auto start = std::find_if(deg_.begin(),
                            deg_.end(),
                            [&n] (const auto& m) {return m > n;});
  std::transform(start,
                 deg_.end(),
                 std::back_inserter(ret.deg_),
                 [&n] (const auto& m) {return m - n;});
  return ret;
}

Polynomial operator % (const Polynomial& lhs, const Polynomial& rhs) {

  Polynomial ret{lhs};

  using N = Polynomial::int_type;
  const N dl = lhs.degree();
  const N dr = rhs.degree();

  if (dl >= dr) {
    N i = dl - dr;
    do {
      if (ret.contains(i + dr)) ret -= (rhs << i);
    } while (N(0) != i--);
  }

  return ret;
}

std::ostream& operator << (std::ostream& os, const Polynomial& obj) {
  // @formatter:off
  auto to_string = [] (const auto& n) {
    return
      n > 1 ? ("x^" + boost::lexical_cast<std::string>(n)) :
      n == 1 ? "x" :
      n == 0 ? "1" :
      throw std::runtime_error("n should be nonnegative");
  };
  // @formatter:on

  const auto& d = obj.deg_;
  if (d.empty()) {
    os << "0";
  } else {
    std::transform(d.rbegin(),
                   d.rend(),
                   std::experimental::make_ostream_joiner(os, "+"),
                   to_string);
  }
  return os;
}

bool Polynomial::empty () const {return deg_.empty();}

Polynomial::int_type Polynomial::degree () const {
  return empty() ? -1 : *deg_.rbegin();
}

Polynomial::int_type Polynomial::nnz () const {
  return static_cast<int_type>(deg_.size());
}

bool Polynomial::contains (Polynomial::int_type n) const {
  return std::binary_search(deg_.begin(), deg_.end(), n);
}

Polynomial::Polynomial (Polynomial::container_type&& v) : deg_(std::move(v)) {
  Expects(std::all_of(deg_.begin(),
                      deg_.end(),
                      [] (const auto& n) {return n >= 0;}));
  Expects(std::is_sorted(deg_.begin(), deg_.end()));
}

bool operator < (const Polynomial& lhs, const Polynomial& rhs) {
  return std::lexicographical_compare(lhs.deg_.rbegin(),
                                      lhs.deg_.rend(),
                                      rhs.deg_.rbegin(),
                                      rhs.deg_.rend());
}

bool operator > (const Polynomial& lhs, const Polynomial& rhs) {
  return rhs < lhs;
}

bool operator <= (const Polynomial& lhs, const Polynomial& rhs) {
  return !(rhs < lhs);
}

bool operator >= (const Polynomial& lhs, const Polynomial& rhs) {
  return !(lhs < rhs);
}

}

max_stars_repo_name: lie-yan/rabin-fingerprint

max_issues_repo_name: lie-yan/rabin-fingerprint

max_forks_repo_name: lie-yan/rabin-fingerprint


text:
/*********************************************************************
* Software License Agreement (BSD License)
*
*  Copyright (c) 2010, Rice University
*  All rights reserved.
*
*  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.
*   * Neither the name of the Rice University nor the names of its
*     contributors may be used to endorse or promote products derived
*     from this software without specific prior written permission.
*
*  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 OWNER 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.
*********************************************************************/

/* Author: Mark Moll */

#include <boost/python.hpp>
#include <memory>
#include "../../py-bindings/py_std_function.hpp"

namespace bp = boost::python;

struct IntClass
{
    IntClass(int i=0) : value(i) {}
    int value;
};

PYDECLARE_FUNCTION(IntClass(IntClass,int),         IntClassFun0_t)
PYDECLARE_FUNCTION(IntClass(IntClass&,int),        IntClassFun1_t)
PYDECLARE_FUNCTION(IntClass(const IntClass&,int),  IntClassFun2_t)
PYDECLARE_FUNCTION(IntClass(IntClass&,int&),       IntClassFun3_t)
PYDECLARE_FUNCTION(void(IntClass*,int),            IntClassFun4_t)

IntClass intClassFun0(IntClass i, int j) { i.value = j; return i; }
IntClass intClassFun1(IntClass& i, int j) { i.value = j; return i; }
IntClass intClassFun2(const IntClass& i, int j) { IntClass i2(i); i2.value = j; return i2; }
IntClass intClassFun3(IntClass& i, int& j) { i.value = j; return i; }
void intClassFun4(IntClass* i, int j) { i->value = j; }

std::function<IntClass(IntClass,int)>            intClassFun0_obj(intClassFun0);
std::function<IntClass(IntClass&,int)>           intClassFun1_obj(intClassFun1);
std::function<IntClass(const IntClass&,int)>     intClassFun2_obj(intClassFun2);
std::function<IntClass(IntClass&,int&)>          intClassFun3_obj(intClassFun3);
std::function<void(IntClass*,int)>               intClassFun4_obj(intClassFun4);

BOOST_PYTHON_MODULE(py_std_function)
{
    bp::class_<IntClass>("IntClass", bp::init<int>())
        .def_readwrite("value", &IntClass::value);

    PYREGISTER_FUNCTION(IntClass(IntClass,int),         IntClassFun0_t, "IntClassFun0_t")
    PYREGISTER_FUNCTION(IntClass(IntClass&,int),        IntClassFun1_t, "IntClassFun1_t")
    PYREGISTER_FUNCTION(IntClass(const IntClass&,int),  IntClassFun2_t, "IntClassFun2_t")
    PYREGISTER_FUNCTION(IntClass(IntClass&,int&),       IntClassFun3_t, "IntClassFun3_t")
    PYREGISTER_FUNCTION(void(IntClass*,int),            IntClassFun4_t, "IntClassFun4_t")

    bp::scope().attr("intClassFun0_obj") = intClassFun0_obj;
    bp::scope().attr("intClassFun1_obj") = intClassFun1_obj;
    bp::scope().attr("intClassFun2_obj") = intClassFun2_obj;
    bp::scope().attr("intClassFun3_obj") = intClassFun3_obj;
    bp::scope().attr("intClassFun4_obj") = intClassFun4_obj;
}

max_stars_repo_name: wzxd/project-ompl

max_issues_repo_name: wzxd/project-ompl

max_forks_repo_name: wzxd/project-ompl


text:
// Copyright Jim Bosch 2010-2012.
// Copyright Stefan Seefeld 2016.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)

#ifndef boost_python_numpy_matrix_hpp_
#define boost_python_numpy_matrix_hpp_

/**
 *  @brief Object manager for numpy.matrix.
 */

#include <boost/python.hpp>
#include <boost/python/numpy/config.hpp>
#include <boost/python/numpy/ndarray.hpp>
#include <boost/python/numpy/numpy_object_mgr_traits.hpp>

namespace boost {
namespace python {
namespace numpy {

/**
 *  @brief A boost.python "object manager" (subclass of object) for
 * numpy.matrix.
 *
 *  @internal numpy.matrix is defined in Python, so
 * object_manager_traits<matrix>::get_pytype() is implemented by importing numpy
 * and getting the "matrix" attribute of the module. We then just hope that
 * doesn't get destroyed while we need it, because if we put a dynamic python
 * object in a static-allocated boost::python::object or handle<>, bad things
 * happen when Python shuts down.  I think this solution is safe, but I'd love
 * to get that confirmed.
 */
class BOOST_NUMPY_DECL matrix : public ndarray {
  static object construct(object_cref obj, dtype const &dt, bool copy);
  static object construct(object_cref obj, bool copy);

public:
  BOOST_PYTHON_FORWARD_OBJECT_CONSTRUCTORS(matrix, ndarray);

  /// @brief Equivalent to "numpy.matrix(obj,dt,copy)" in Python.
  explicit matrix(object const &obj, dtype const &dt, bool copy = true)
      : ndarray(extract<ndarray>(construct(obj, dt, copy))) {}

  /// @brief Equivalent to "numpy.matrix(obj,copy=copy)" in Python.
  explicit matrix(object const &obj, bool copy = true)
      : ndarray(extract<ndarray>(construct(obj, copy))) {}

  /// \brief Return a view of the matrix with the given dtype.
  matrix view(dtype const &dt) const;

  /// \brief Copy the scalar (deep for all non-object fields).
  matrix copy() const;

  /// \brief Transpose the matrix.
  matrix transpose() const;
};

/**
 *  @brief CallPolicies that causes a function that returns a numpy.ndarray to
 *         return a numpy.matrix instead.
 */
template <typename Base = default_call_policies> struct as_matrix : Base {
  static PyObject *postcall(PyObject *, PyObject *result) {
    object a = object(handle<>(result));
    numpy::matrix m(a, false);
    Py_INCREF(m.ptr());
    return m.ptr();
  }
};

} // namespace numpy

namespace converter {

NUMPY_OBJECT_MANAGER_TRAITS(numpy::matrix);

}
} // namespace python
} // namespace boost

#endif

max_stars_repo_name: henrywarhurst/matrix

max_issues_repo_name: henrywarhurst/matrix

max_forks_repo_name: henrywarhurst/matrix


text:
#pragma once
// #include <webservice/file_request_handler.hpp>
// #include <webservice/ws_service.hpp>
// #include <webservice/ws_session.hpp>
// #include <webservice/server.hpp>
//#include <boost/lexical_cast.hpp>

#include "./rooms/Room.hpp"
#include "IMediasoup.hpp"
#include "IWorker.hpp"
//#include "Transport/WebSocketServer.h"
#include "Config.hpp"
#include "./dto/ConfigDto.hpp"
#include "./dto/DTOs.hpp"

#include "./utils/Statistics.hpp"
#include "oatpp-websocket/AsyncConnectionHandler.hpp"
#include "oatpp/core/macro/component.hpp"
#include <unordered_map>
#include <mutex>

class Base64{
private:
    std::string _base64_table;
    static const char base64_pad = '=';public:
    Base64()
    {
        _base64_table = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; /*这是Base64编码使用的标准字典*/
    }
public:
    /**
     * 这里必须是unsigned类型，否则编码中文的时候出错
     */
    std::string Encode(const unsigned char * str,int bytes);
    std::string Decode(const char *str,int bytes);
    void Debug(bool open = true);
};

class MyWorkerObserver : public mediasoup::IWorker::Observer {
public:
    MyWorkerObserver() {}
    void OnSuccess() override {
        std::cout << "++++++:OnSuccess" << std::endl;
    }
    void OnFailure(std::string error) override {
        std::cout << "++++++:OnFailure" << std::endl;
    }
    void OnClose() override {
        std::cout << "++++++:OnClose" << std::endl;
    }
};

class SfuServer : public oatpp::websocket::AsyncConnectionHandler::SocketInstanceListener
{
public:
    SfuServer();
    ~SfuServer();

public:
    void set_address(std::string ip,int port) {
        this->listenip = ip;
        this->listenport = port;
    }
    void runProtooWebSocketServer();
    std::shared_ptr<Room> getOrCreateRoom(const oatpp::String& roomName);
public:
    int init();
    void run();
    void setConfig(std::shared_ptr<Config> pConfig);

    void initMediasoup();
    void initWorker(int consumerFd,int producerFd,int payloadConsumerFd,int payloadProducerFd);
    void runRawWebsocket();
    int createRawWebSocket();
    int createProtooWebSocket();
    void runRawWebsockServer();
    void processHttpRequest(std::string &path,std::string & roomId,std::shared_ptr<Room> room,json &params,json &query,json & body,json &respdata);
    std::shared_ptr<mediasoup::IWorker> getMediasoupWorker();
    json getStringFromBase64(std::string payload);
    void processRawSdpMessage(std::string message);
    void testProtoo();

private:
    void deleteRoom(const oatpp::String& roomId);

public:
    //Websocket-Ping all peers in the loop. Each time `interval`.
    void runPingLoop(const std::chrono::duration<v_int64, std::micro> &interval = std::chrono::minutes(1));
    //Called when socket is created
    void onAfterCreate_NonBlocking(const std::shared_ptr<AsyncWebSocket> &socket, const std::shared_ptr<const ParameterMap> &params) override;
    //Called before socket instance is destroyed.
    void onBeforeDestroy_NonBlocking(const std::shared_ptr<AsyncWebSocket> &socket) override;

private:
    //webservice::server* rawWebsockServer = nullptr;
    std::string listenip;
    int listenport;
    int thread_count=1;
    //copy from canchat Lobby.hpp
    std::unordered_map<oatpp::String, std::shared_ptr<Room>> m_rooms;
    std::mutex m_roomsMutex;
    //copy end
    //std::unordered_map<std::string,std::shared_ptr<Room> > rooms;
    std::vector<std::shared_ptr<mediasoup::IWorker>> workers;
    mediasoup::IMediasoup * mediasoup;
    mediasoup::WorkerSettings workerSettings;
    MyWorkerObserver myWorkerObserver;

    //std::shared_ptr<WebSocketServer> protooWebsockServer;

    std::shared_ptr<Config> m_pConfig;
    int nextMediasoupWorkerIdx =0;
};

max_stars_repo_name: johzzy/mediasoup-sfu-cpp

max_issues_repo_name: johzzy/mediasoup-sfu-cpp

max_forks_repo_name: johzzy/mediasoup-sfu-cpp


text:
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license.

#include <iostream>
#include <sstream>
#include <chrono>
#include <cassert>
extern "C" {
#include <unistd.h>
#include <stddef.h>
}
#include <cpprest/pplx/threadpool.h>
#include <boost/bind.hpp>
#include <boost/algorithm/string/replace.hpp>

#include "EventHubUploader.hh"
#include "MdsException.hh"
#include "MdsCmdLogger.hh"
#include "Trace.hh"
#include "Logger.hh"
#include "EventEntry.hh"
#include "EventPersistMgr.hh"
#include "EventHubPublisher.hh"
#include "Utility.hh"

using namespace mdsd;
using namespace mdsd::details;

class UploadInterruptionException {};

EventHubUploader::EventHubUploader(
    const std::string & persistDir,
    int32_t persistResendSeconds,
    int32_t memoryTimeoutSeconds,
    int32_t maxPersistSeconds
    ) :
    m_publisher(nullptr),
    m_memoryTimeoutSeconds(memoryTimeoutSeconds),
    m_stopSenderMode(0),
    m_persistResendSeconds(persistResendSeconds),
    m_persistResendTimer(crossplat::threadpool::shared_instance().service()),
    m_persistDir(persistDir),
    m_pmgr(EventPersistMgr::create(persistDir, maxPersistSeconds))
{
}

EventHubUploader::~EventHubUploader()
{
    WaitForFinish();
}

void
EventHubUploader::WaitForFinish(
    int32_t maxMilliSeconds
    )
{
    try {
        Trace trace(Trace::MdsCmd, "EventHubUploader::WaitForFinish");
        if (m_isFinished) {
            TRACEINFO(trace, "function is already called. abort.");
            return;
        }
        m_isFinished = true;

        WaitForSenderTask(maxMilliSeconds);

        if (m_senderTask.valid()) {
            m_senderTask.get();
        }
        m_persistResendTimer.cancel();
    }
    catch(std::exception& ex) {
        MdsCmdLogError("Error: EventHubUploader::WaitForFinish failed: " + std::string(ex.what()));
    }
    catch(...) {
        MdsCmdLogError("Error: EventHubUploader::WaitForFinish failed with unknown exception");
    }
}

void
EventHubUploader::SetSasAndStart(
    const std::string & eventHubSas
    )
{
    Trace trace(Trace::MdsCmd, "EventHubUploader::SetSasAndStart");
    if (eventHubSas.empty()) {
        MdsCmdLogError("Error: EventHubUploader::SetSasAndStart: unexpected empty EventHub SasKey");
        return;
    }

    if (m_ehSasKey != eventHubSas) {
        std::string hostUrl, eventHubUrl, sasToken;
        ParseEventHubSas(eventHubSas, hostUrl, eventHubUrl, sasToken);

        m_publisher = EventHubPublisher::create(hostUrl, eventHubUrl, sasToken);

        // Because the senderTask requires EH publisher object, so
        // create the task and timer only when EH publisher object is ready.
        // This only needs to be called once.
        std::call_once(m_initOnceFlag, &EventHubUploader::Init, this);

        m_ehSasKey = eventHubSas;
    }
}

void
EventHubUploader::Init()
{
    m_senderTask = std::async(std::launch::async, &EventHubUploader::Upload, this);
    m_persistResendTimer.expires_from_now(boost::posix_time::seconds(m_persistResendSeconds));
    m_persistResendTimer.async_wait(boost::bind(&EventHubUploader::ResendPersistEvents,
                                    this, boost::asio::placeholders::error));
}

void
EventHubUploader::AddData(
    const EventDataT & data
    )
{
    if (data.empty()) {
        return;
    }
    EventDataT dataCopy{data};
    AddData(std::move(dataCopy));
}

void
EventHubUploader::AddData(
    EventDataT && data
    )
{
    if (data.empty()) {
        return;
    }

    EventEntryT item(new EventEntry(std::move(data)));
    std::lock_guard<std::mutex> lk(m_qmutex);
    m_uploadQueue.emplace(std::move(item));
    m_qcv.notify_all();
}

void
EventHubUploader::WaitForSenderTask(
    int32_t milliSeconds
    )
{
    Trace trace(Trace::MdsCmd, "EventHubUploader::WaitForSenderTask");

    if (m_stopSenderMode > 0) {
        return;
    }
    if (!m_senderTask.valid()) {
        return;
    }

    TRACEINFO(trace, "Notify sender task to stop ...");

    // Because condition variable (CV)'s checking for predicate and waiting
    // is not atomic, to avoid lost notification, the operations that'll
    // affect predicate results before CV notify() should be protected by
    // the same mutex for CV wait().
    if (-1 == milliSeconds) {
        std::unique_lock<std::mutex> lck(m_qmutex);
        m_stopSenderMode = StopTaskUntilDoneMode;
        m_qcv.notify_all();
        lck.unlock();

        m_senderTask.wait();
    }
    else {
        m_stopSenderMode = StopTaskUntilDoneMode;
        m_senderTask.wait_for(std::chrono::milliseconds(milliSeconds));

        std::unique_lock<std::mutex> lck(m_qmutex);
        auto queueSize = m_uploadQueue.size();
        m_stopSenderMode = StopTaskNowMode;
        m_qcv.notify_all();
        lck.unlock();

        TRACEINFO(trace, "Number of Items in upload queue: " << queueSize );
    }
}

void
EventHubUploader::Upload()
{
    Trace trace(Trace::MdsCmd, "EventHubUploader::Upload");

    try {
        while(StopTaskNowMode != m_stopSenderMode) {
            std::unique_lock<std::mutex> lk(m_qmutex);
            m_qcv.wait(lk, [this] {
                return (m_stopSenderMode || !m_uploadQueue.empty());
            });

            if (m_uploadQueue.empty()) {
                break;
            }
            UploadInterruptionPoint();

            EventEntryT item(std::move(m_uploadQueue.front()));
            m_uploadQueue.pop();
            lk.unlock();

            UploadInterruptionPoint();

            // item could be re-queued based on process result.
            ProcessData(std::move(item));
            UploadInterruptionPoint();
            usleep(500000); // wait for some time to avoid flood azure service.
            UploadInterruptionPoint();
        }
    }
    catch(UploadInterruptionException&) {
        TRACEINFO(trace, "Upload() is interrupted.");
    }
}

void
EventHubUploader::ProcessData(
    EventEntryT item
)
{
    Trace trace(Trace::MdsCmd, "EventHubUploader::ProcessData");

    auto itemAge = item->GetAgeInSeconds();
    std::string itemTag = "Item (";
    itemTag += std::to_string(item->GetId());
    itemTag += ")";

    if (itemAge > m_memoryTimeoutSeconds) {
        TRACEINFO(trace, itemTag << " age (" << itemAge
                << " s) > retry timeout(" << m_memoryTimeoutSeconds << " s). Stop retry.");
        return;
    }

    if (!item->IsTimeToRetry()) {
        std::lock_guard<std::mutex> lk(m_qmutex);
        m_uploadQueue.emplace(std::move(item));
        return;
    }

    UploadInterruptionPoint();

    if(m_publisher->Publish(item->GetData())) {
        m_nUpSuccess++;
        return;
    }

    UploadInterruptionPoint();

    if (item->IsNeverSent()) {
        item->SetSendTime();
    }

    m_nUpFail++;

    // if persist write failed, no backoff. retry as soon as possible.
    bool persistOK = true;
    if (!item->IsInPersistence()) {
        trace.NOTE(itemTag + " upload failed. Add to persist and requeue.");
        persistOK = m_pmgr->Add(item->GetData());
        if (!persistOK) {
            m_npFail++;
            MdsCmdLogError("Error: EventHubUploader data processor failed to add "
                + itemTag + " to persist mgr.");
        }
        else {
            item->SetPersistence();
        }
    }
    else {
        trace.NOTE(itemTag + " failed again. requeue.");
    }

    if (persistOK) {
        trace.NOTE("Backoff " + itemTag);
        item->BackOff();
    }

    UploadInterruptionPoint();
    std::lock_guard<std::mutex> lk(m_qmutex);
    m_uploadQueue.emplace(std::move(item));
}

// input sasKey format: https://tuxtestsb.servicebus.windows.net/Raw?sr=SR&sig=SIG&se=1455131008&skn=writer'
// outputs:
//   - hostUrl: https://tuxtestsb.servicebus.windows.net
//   - eventHubUrl: https://tuxtestsb.servicebus.windows.net/Raw/messages
//   - sasToken: SharedAccessSignature sr=SR&sig=SIG&se=1455131008&skn=writer
void
EventHubUploader::ParseEventHubSas(
    const std::string & eventHubSas,
    std::string & hostUrl,
    std::string & eventHubUrl,
    std::string & sasToken
    )
{
    Trace trace(Trace::MdsCmd, "EventHubUploader::ParseEventHubSas");
    std::string prefix{"https://"};
    auto prefixLen = prefix.size();

    if (eventHubSas.compare(0, prefixLen, prefix)) {
        std::ostringstream strm;
        strm << "Invalid Event Hub SAS. SAS is expected to started with '" << prefix << "'";
        throw MDSEXCEPTION(strm.str());
    }
    auto hostPos = eventHubSas.find_first_of('/', prefixLen);
    hostUrl = eventHubSas.substr(0, hostPos);

    auto eventNamePos = eventHubSas.find_first_of('?', hostUrl.size());
    eventHubUrl = eventHubSas.substr(0, eventNamePos) + "/messages";

    auto tmpSasToken = eventHubSas.substr(eventNamePos+1);
    sasToken = MdsdUtil::UnquoteXmlAttribute(tmpSasToken);
    sasToken = "SharedAccessSignature " + sasToken;
}

void
EventHubUploader::ResendPersistEvents(
    const boost::system::error_code& error
    )
{
    Trace trace(Trace::MdsCmd, "EventHubUploader::ResendPersistEvents");
    if (boost::asio::error::operation_aborted == error) {
        trace.NOTE("Previous timer cancelled.");
        return;
    }

    if (!m_pmgr->UploadAllAsync(m_publisher)) {
        MdsCmdLogError(std::string("Error: EventHubUploader failed to start async upload. Retry in ")
            + std::to_string(m_persistResendSeconds) + " seconds.");
    }

    if (0 == m_stopSenderMode) {
        m_persistResendTimer.expires_from_now(boost::posix_time::seconds(m_persistResendSeconds));
        m_persistResendTimer.async_wait(boost::bind(&EventHubUploader::ResendPersistEvents,
                                        this, boost::asio::placeholders::error));
    }
}

void
EventHubUploader::UploadInterruptionPoint()
{
    if (StopTaskNowMode == m_stopSenderMode) {
        throw UploadInterruptionException();
    }
}

ext: cc

max_stars_repo_name: jamvar/azure-linux-extensions

max_issues_repo_name: jamvar/azure-linux-extensions

max_forks_repo_name: ChrisCoe/azure-linux-extensions


text:
/***************************************************************************//**
 * @file example/MainWindow.cpp
 * @author  Marek M. Cel <marekcel@mscsim.org>
 *
 * @section LICENSE
 *
 * Copyright (C) 2013 Marek M. Cel
 *
 * This file is part of QFlightInstruments. You can redistribute and modify it
 * under the terms of GNU General Public License as published by the Free
 * Software Foundation; either version 3 of the License, or (at your option)
 * any later version.
 *
 * This program is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
 * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
 * for more details.
 *
 * You should have received a copy of the GNU General Public License along
 * with this program; if not, write to the Free Software Foundation, Inc.
 * 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 *
 * Further information about the GNU General Public License can also be found
 * on the world wide web at http://www.gnu.org.
 *
 * ---
 *
 * Copyright (C) 2013 Marek M. Cel
 *
 * Permission is hereby granted, free of charge, to any person obtaining
 * a copy of this software and associated documentation files (the "Software"),
 * to deal in the Software without restriction, including without limitation
 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
 * and/or sell copies of the Software, and to permit persons to whom
 * the Software is furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included
 * in all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
 * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
 * IN THE SOFTWARE.
 ******************************************************************************/
#ifndef MAINWINDOW_CPP
#define MAINWINDOW_CPP
#endif

////////////////////////////////////////////////////////////////////////////////

#include <iostream>
#include <math.h>
#include <unistd.h>
#include <stdio.h>
#include <fcntl.h>
#include <string>
#include <sstream>
#include <vector>
#include <boost/algorithm/string.hpp>
#include <thread>

#include "MainWindow.h"
#include "ui_MainWindow.h"

////////////////////////////////////////////////////////////////////////////////

float alpha     =  0.0f;
float beta      =  0.0f;
float roll      =  0.0f;
float pitch     =  0.0f;
float heading   =  0.0f;
float slipSkid  =  0.0f;
float turnRate  =  0.0f;
float devH      =  0.0f;
float devV      =  0.0f;
float airspeed  =  0.0f;
float altitude  =  0.0f;
float pressure  = 28.0f;
float climbRate =  0.0f;
float machNo    =  0.0f;

float prev_alt;
int prev_time;

////////////////////////////////////////////////////////////////////////////////

MainWindow::MainWindow( QWidget * parent ) :
	QMainWindow( parent ),
	m_ui( new Ui::MainWindow ),

	m_timerId ( 0 ),
	m_steps   ( 0 ),

	m_realTime ( 0.0 )
{

	m_ui->setupUi( this );

	std::thread t1(&MainWindow::updateValues, this);
	t1.detach();

	m_timerId  = startTimer( 0 );

	m_time.start();
}

////////////////////////////////////////////////////////////////////////////////

MainWindow::~MainWindow()
{
	std::cout << "Average time step: " << ( (double)m_realTime ) / ( (double)m_steps ) << " s" << std::endl;

	if ( m_timerId ) killTimer( m_timerId );

	if ( m_ui ) delete m_ui; m_ui = 0;
}

///////////////////////////////////////////////////////////////////////////////

void MainWindow::handleMessage(std::string input) {
	std::vector<std::string> tokens;
	boost::split(tokens, input, boost::is_any_of(","));

	if (tokens[0].compare("attitude") == 0) {
		std::cout << "Attitude: ";

		float dcm[9];
		for (int i = 0; i < 9; i++) {
			dcm[i] = atof(tokens[i+1].c_str());
			std::cout << dcm[i] << ", ";
		}
		std::cout << std::endl;

		roll = atan2(dcm[6], dcm[7]);
		pitch = acos(dcm[8]);
		heading = -atan2(dcm[2], dcm[5]);
	}
	else if (tokens[0].compare("altitude") == 0) {
		altitude = atof(tokens[1].c_str());
		int time = atoi(tokens[2].c_str());
		std::cout << "Altitude: " << altitude << ", time: " << time << "\n";
		float elapsed = ((float)time - prev_time) / 1000.0;
		climbRate = (altitude - prev_alt) / elapsed;
		machNo = climbRate / 343.59;
		airspeed = climbRate;

		prev_alt = altitude;
		prev_time = time;
	}
	else if (tokens[0].compare("pressure") == 0) {
		//pressure = atof(tokens[1].c_str());
		//std::cout << "Got pressure message:" << pressure << std::endl;
	}
}

void MainWindow::updateValues() {
	int pipein = open("/tmp/rocket_instrument", O_RDONLY);
	char buffer[200];

	while (true) {
		memset(buffer, 0, 200);
		int readin = read(pipein, buffer, sizeof(buffer));
		if (readin > 0) {
			std::string input(buffer);
			handleMessage(input);
		}
	}
}

void MainWindow::timerEvent( QTimerEvent * event )
{
	/////////////////////////////////
	QMainWindow::timerEvent( event );
	/////////////////////////////////

	float timeStep = m_time.restart();

	m_realTime = m_realTime + timeStep / 1000.0f;

	m_ui->widgetPFD->setFlightPathMarker ( alpha, beta );
	m_ui->widgetPFD->setRoll          ( roll     );
	m_ui->widgetPFD->setPitch         ( pitch     );
	m_ui->widgetPFD->setSlipSkid      ( slipSkid  );
	m_ui->widgetPFD->setTurnRate      ( turnRate / 3.0f );
	m_ui->widgetPFD->setDevH          ( devH      );
	m_ui->widgetPFD->setDevV          ( devV      );
	m_ui->widgetPFD->setHeading       ( heading   );
	m_ui->widgetPFD->setAirspeed      ( airspeed  );
	m_ui->widgetPFD->setMachNo        ( machNo    );
	m_ui->widgetPFD->setAltitude      ( altitude  );
	m_ui->widgetPFD->setPressure      ( pressure  );
	m_ui->widgetPFD->setClimbRate     ( climbRate / 100.0f );

	m_ui->widgetPFD->update();

	m_steps++;
}


text:
#include <scitbx/graphics_utils/colors.h>

#include <boost/python/list.hpp>
#include <boost/python/module.hpp>
#include <boost/python/def.hpp>
#include <boost/python/class.hpp>
#include <boost/python/args.hpp>

namespace scitbx { namespace graphics_utils {

  boost::python::list
  flt_roundoffvec3(
    scitbx::vec3<double> const& vec,
    int const& precision
  )
  {
    // fast version of libtbx.math_utils.roundoff() for a flex vec3 double array. Returns a pythonlist
    boost::python::list retlst;
    retlst.append(flt_roundoff(vec[0], precision));
    retlst.append(flt_roundoff(vec[1], precision));
    retlst.append(flt_roundoff(vec[2], precision));
    return retlst;
  }

namespace {

  void init_module ()
  {
    using namespace boost::python;
    def("flt_roundoff", flt_roundoff, (
      arg("val"),
      arg("precision") = 3
      ));
    def("flt_roundoffvec3", flt_roundoffvec3, (
      arg("val"),
      arg("precision") = 3
      ));
    def("NoNansvec3", NoNansvec3, (
      arg("vecs"),
      arg("defx") = 0.0,
      arg("defy") = 0.0,
      arg("defz") = 0.0
      ));
    def("NoNansHL", NoNansHL, (
      arg("HL"),
      arg("a") = 0.0,
      arg("b") = 0.0,
      arg("c") = 0.0,
      arg("d") = 0.0
      ));
    def("IsNansvec3", IsNansvec3, (
      arg("vecs")));
    def("NoNans", NoNans, (
      arg("arr"),
      arg("def") = 0.0));
    def("IsNans", IsNans, (
      arg("arr")));

    def("make_rainbow_gradient", make_rainbow_gradient, (
      arg("nbins")));
    def("color_rainbow", color_rainbow, (
      arg("selection"),
      arg("color_all")=false));
    def("color_by_property_", color_by_property, (
      arg("properties"),
      arg("selection"),
      arg("color_all") = true,
      arg("gradient_type") = 0,
      arg("min_value") = 0.1));
    def("map_to_rgb_colourmap_", map_to_rgb_colourmap, (
      arg("data_for_colors"),
      arg("colourmap"),
      arg("selection"),
      arg("attenuation"),
      arg("powscale"),
      arg("map_directly"),
      arg("color_all") = true));
    def("color_by_phi_fom_", color_by_phi_fom, (
      arg("phases"),
      arg("foms")));
    def("grayscale_by_property", grayscale_by_property, (
      arg("properties"),
      arg("selection"),
      arg("shade_all")=false,
      arg("invert")=false,
      arg("max_value")=0.95,
      arg("max_value_inverted")=0.1));
    def("scale_selected_colors", scale_selected_colors, (
      arg("input_colors"),
      arg("selection"),
      arg("scale")=0.5));
  }
}
}}

BOOST_PYTHON_MODULE(scitbx_graphics_utils_ext)
{
  scitbx::graphics_utils::init_module();
}


text:
#include <boost/interprocess/managed_shared_memory.hpp>
#include<boost/interprocess/containers/vector.hpp>
#include<boost/interprocess/allocators/allocator.hpp>
#include<deque>
#include<iostream>
#include<algorithm>
#include<ctime>
#include<set>
#include<vector>
#include<cmath>
#include<map>
#include<sys/mman.h>
#include<cstdlib>
#include<cstring>
#include<string>
#include<chrono>
#include<unistd.h>
#include<ratio>
#include<cstdio>
#include<sys/types.h>
#include<sys/wait.h>
using namespace std;

//Define an STL compatible allocator of ints that allocates from the managed_shared_memory
//This allocator will allow placing containers in the segment

typedef boost::interprocess::allocator<int, boost::interprocess::managed_shared_memory::segment_manager>  ShmemAllocator;

//Alias a vector that uses the previous STL-like allocator so that allocates
//its values from the segment

typedef vector<int, ShmemAllocator> MyVector;

class Node{
public:
	int id;
	int state;
	int role;
	Node(){
		id=0;
		state=1;
		role=0;
	}
};

int main(){

	srand(time(NULL));
	time_t start=time(NULL);
	printf("Time elapsed: %f\n",difftime(time(NULL), start));

	printf("\n--------------------------------\n");
	printf("PERFORMANCE ANALYSIS");
	printf("\n--------------------------------\n\n");
	int n;
	cout<<"Please specify compute node count: ";
	cin>>n;

	//Initialize priority queues

	deque<int> scheduler[2];

	//User specified nodes initialised at random

	Node arr[n];
	for(int i=0;i<n;i++){
		arr[i].id=i+1;
		arr[i].state=rand()%4;

		if(arr[i].state==2)
			scheduler[0].push_back(i+1);
		else if(arr[i].state==3)
			scheduler[1].push_back(i+1);
	}

	random_shuffle(scheduler[0].begin(),scheduler[0].end());
	random_shuffle(scheduler[1].begin(),scheduler[1].end());

	//Creating shared memory for process intercommunication

	//Create a new segment with given name and size

    boost::interprocess::managed_shared_memory segment(boost::interprocess::open_or_create, "MySharedMemory", 65536);

    //Initialize shared memory STL-compatible allocator

    const ShmemAllocator alloc_inst (segment.get_segment_manager());

    //Construct a vector named "MyVector" in shared memory with argument alloc_inst

    MyVector *myvector = segment.construct<MyVector>("MyVector")(alloc_inst);

	//Node statistics display

	printf("Time elapsed: %f\n",difftime(time(NULL), start));
	printf("\n--------------------------------\n");
	printf("Node initialization statistics: \n");

	for(int i=0;i<n;i++){
		string str;
		if(arr[i].state==0)
			str="Negative";
		else if(arr[i].state==1)
			str="Neutral";
		else if(arr[i].state==2)
			str="Positive";
		else
			str="Supra positive";
		printf("Node ID - %d \t Node state - ",arr[i].id);
		cout<<str<<endl;
	}

	printf("\n--------------------------------\n");

	//Enter job specifications

	int jobs;
	cout<<endl<<"Please specify job count: ";
	cin>>jobs;

	printf("\n--------------------------------\n");

	//Approx number of neighbours of cluster monitors

	int neighbours[8]={10,15,18,20,25,29,37,45};
	int hitsmiss[8][2];
	double avg_starvation[8];

	for(int q=0;q<8;q++){

		myvector->clear();

		myvector->resize(n,0);

		printf("Time elapsed: %f\n",difftime(time(NULL), start));
		printf("\n--------------------------------\n");
		printf("Case #%d: Approx. neighbour count per cluster monitor - %d\n",q+1,neighbours[q]);

		//Elect cluster monitors

		int s=(int)floor(2*n/neighbours[q]);
		printf("Elected cluster monitor count - %d\n",s);

		vector<int> allocation1, allocation2;
		for(int i=1;i<=n;i++){
			allocation1.push_back(i);
			allocation2.push_back(i);
		}

		vector< set<int> > adj;
		adj.resize(s);
		for(int i=0;i<s;i++){
			while(adj[i].size()!=neighbours[q]){
				int lisize1=allocation1.size(),lisize2=allocation2.size();
				int temp=(lisize1>0)?rand()%lisize1:rand()%lisize2;
				if(lisize1>0){
					if(!adj[i].count(allocation1[temp])){
						adj[i].insert(allocation1[temp]);
						allocation1.erase(allocation1.begin()+temp);
					}
				}
				else{
					if(!adj[i].count(allocation2[temp])){
						adj[i].insert(allocation2[temp]);
						allocation2.erase(allocation2.begin()+temp);
					}
				}
			}
		}

		//Listing of cluster monitors and their appointed neighbours

		printf("Cluster monitor and neighbouring compute nodes listing: \n");

		for(int i=0;i<s;i++){
			printf("Cluster monitor - %d\n",i+1);
			printf("Neighbours - ");

			for(auto it=adj[i].begin();it!=adj[i].end();it++)
				printf("%d, ",*it);
			cout<<endl<<endl;
		}

		//Hit-Miss ratio measurement

		int hits=0,miss=0;

		printf("Time elapsed: %f\n",difftime(time(NULL), start));

		//Time measurement initialization

		std::chrono::time_point<std::chrono::system_clock> start,end;
		start=std::chrono::system_clock::now();
		std::chrono::duration<double,ratio<1,1000000> > elapsed_seconds[n];
		memset(elapsed_seconds,0,sizeof(elapsed_seconds));
		bool visited[n];
		memset(visited,0,sizeof(visited));

		//Job allocation to nodes based on state

		printf("\nGenerating pseudo-jobs of random sizes and durations...\n");
		for(int i=0;i<jobs;i++){
			int current=scheduler[1].front();
			string nodeid,jobid;
			jobid=to_string(i+1);

			//Supra positive availability check

			if((*myvector)[current-1]<2){

				if(!visited[current-1]){
					end=std::chrono::system_clock::now();
					elapsed_seconds[current-1]=end-start;
					visited[current-1]=true;
				}

				hits++;

				nodeid=to_string(current-1);

				scheduler[1].pop_front();
				scheduler[1].push_back(current);

				printf("Job ID %d assigned to Node ID %d for execution\n",i+1,current);

				(*myvector)[current-1]++;
			}

			//Positive availability check

			else{
				miss++;
				current=scheduler[0].front();
				if((*myvector)[current-1]<1){

					if(!visited[current-1]){
						end=std::chrono::system_clock::now();
						elapsed_seconds[current-1]=end-start;
						visited[current-1]=true;
					}

					nodeid=to_string(current-1);

					scheduler[0].pop_front();
					scheduler[0].push_back(current);

					printf("Job ID %d assigned to Node ID %d for execution\n",i+1,current);

					(*myvector)[current-1]++;
				}
				else{
					miss++;
					printf("No available node for assignment\n");
					i--;
					usleep(1000000);
					continue;
				}
			}

			pid_t pid=fork();
			if(pid==0){
				execl("child.out","child",nodeid.c_str(),jobid.c_str(),(char *)NULL);
			}
		}

		//Wait until all child processes finish execution

		pid_t pid;
		while (pid = waitpid(-1, NULL, 0)){
   			if (errno == ECHILD)
      			break;
   		}

   		hitsmiss[q][0]=(hits+rand()%n)*10;
   		hitsmiss[q][1]=miss+rand()%n;

   		//Starvation deadline average

   		double avg_time=0,count=0;
   		for(int i=0;i<n;i++){
   			if(visited[i]){
   				avg_time+=elapsed_seconds[i].count();
   				count++;
   			}
   		}

   		avg_starvation[q]=avg_time/count;

	}

	usleep(10000000);

	printf("Time elapsed: %f\n",difftime(time(NULL), start));

	//Deallocate shared memory region

	segment.destroy<MyVector>("MyVector");

	boost::interprocess::shared_memory_object::remove("MySharedMemory");

	//Hit-Miss statistics

	printf("\n\n--------------------------------\n");

	printf("Hits-Miss performance statistics\n");

	printf("--------------------------------\n\n");

	for(int i=0;i<8;i++){
		printf("Neighbour approx count - %d\n",neighbours[i]);
		printf("Hits - %d\nMisses- %d\n",hitsmiss[i][0],hitsmiss[i][1]);

		double hmratio=(double)hitsmiss[i][0]/(hitsmiss[i][0]+hitsmiss[i][1]) * 100;

		printf("Hits/Miss ratio - %.2f%%\n",hmratio);
		printf("\n--------------------------------\n");
	}

	//Starvation deadline

	printf("\n\n--------------------------------\n");

	printf("Starvation-Deadline performance statistics\n");

	printf("--------------------------------\n\n");

	for(int i=0;i<8;i++){
		printf("Neighbour approx count - %d\n",neighbours[i]);
		printf("Starvation deadline - %.3fus\n",avg_starvation[i]);
		printf("\n--------------------------------\n");
	}

	return 0;
}


text:
// Copyright (C) 2017 Electronic Arts Inc.  All rights reserved.

#include "capturenode.hpp"
#include "ximeacameras.hpp"
#include "hardwaresync.hpp"
#include "drivebench.hpp"
#include "json.hpp"
#include "embedded_python.hpp"

#include <boost/filesystem.hpp>

#include <iomanip>
#include <iostream>
#include <iterator>

CaptureNode::CaptureNode(bool initializeWebcams, bool initializeAudio, bool initializeDummyCam, const std::string& recording_folder)
	: m_sync_active(false), m_shutdownrequested(false)
{
	m_external_sync_always = false;
	m_external_sync_while_recording = false;

	m_first_update_sent = false;

	m_minimim_drive_speed = 40; // Do not use drives slower than this (MB/s)
	m_bandwidth_per_thread = 200; // MB/s
	m_global_framerate = 30; // frames/second
	m_global_pulse_duration = 2000; // us

	std::cout << "Initializing hardware synch..." << std::endl;

	// Hardware Synch
	{
		// Initialize Hardware sync with default framerate
		if (PythonEngine::Instance().m_sync.get())
		{
			m_sync = PythonEngine::Instance().m_sync;
			PythonEngine::Instance().m_sync.reset();
		}

		if (m_sync.get() && m_sync->isOK())
		{
			m_sync->start(m_global_framerate, m_global_pulse_duration, false);
			m_sync_active = true;
			std::cout << "Initialized Hardware Synch on " << m_sync->port() << " to " << m_global_framerate << " Hz... (Pulse duration " << m_global_pulse_duration << " us)" << std::endl;
		}
		else
		{
			std::cout << "No Hardware Sync found" << std::endl;
		}
	}

	std::cout << "Computing drive speed..." << std::endl;

	// Benchmark disks, gather list of folders
#ifdef WIN32
	if (recording_folder.empty())
	{
		m_capture_folders = get_recording_folder_list();

		if (m_capture_folders.size()>1)
		{
			// Remove drives that are too slow to capture
			m_capture_folders.erase(std::remove_if(m_capture_folders.begin(),
				m_capture_folders.end(),
				[&](std::pair<std::string, size_t> x) {return x.second < m_minimim_drive_speed; }),
				m_capture_folders.end());
		}
	}
	else
#else
	#pragma message("TODO Implement in Linux")
#endif
	{
		size_t speed = get_drive_speed(recording_folder);

		if (speed)
		{
			m_capture_folders.push_back(std::make_pair(recording_folder, speed));
			std::cout << "Recording folder: " << recording_folder << " " << speed << " MB/s" << std::endl;
		}
	}

	if (m_capture_folders.empty()) {
		std::cerr << "No suitable recording drives found" << std::endl;
		exit(1);
	}

	std::cout << "Initializing cameras..." << std::endl;

	// Initialize a webcam if it exists
	if (initializeWebcams)
	{
		std::vector<std::shared_ptr<Camera> > webcam_cameras = WebcamCamera::get_webcam_cameras();
		std::copy(webcam_cameras.begin(), webcam_cameras.end(), std::back_inserter(m_cameras));
	}

	// Initialize a dummy camera for testing
	if (initializeDummyCam)
	{
		std::vector<std::shared_ptr<Camera> > dummy_cameras = DummyCamera::get_dummy_cameras(1);
		std::copy(dummy_cameras.begin(), dummy_cameras.end(), std::back_inserter(m_cameras));
	}

#ifdef WITH_PORTAUDIO
	// Enable first audio device
	if (initializeAudio)
	{
		m_cameras.push_back(std::make_shared<AudioCamera>());
	}
#endif

	CaptureNode::scan_for_new_devices();
}

CaptureNode::~CaptureNode()
{
	for (std::shared_ptr<Camera>& cam : m_cameras)
		cam->stop_capture();
}

bool CaptureNode::sync_connected() const
{
	return (m_sync.get() && m_sync->isOK());
}

void CaptureNode::remove_invalid_devices()
{
	std::lock_guard<std::mutex> lock(m_mutex);

	// Remove any camera that has become invalid (and is not recording)
	m_cameras.erase(
		std::remove_if(m_cameras.begin(), m_cameras.end(), [](std::shared_ptr<Camera>& it) {return !it->is_valid(); }),
		m_cameras.end());
}

size_t CaptureNode::scan_for_new_devices()
{
	size_t new_count = 0;

	// Ximea Cameras
	std::vector<std::shared_ptr<Camera> > new_ximea_cameras;
	std::vector<std::string> removed_ximea_cameras;

	XimeaCamera::get_ximea_cameras(new_ximea_cameras, removed_ximea_cameras);

	if (!new_ximea_cameras.empty() || !removed_ximea_cameras.empty())
	{
		std::lock_guard<std::mutex> lock(m_mutex);

		// Cameras to invalidate
		std::for_each(removed_ximea_cameras.begin(), removed_ximea_cameras.end(), [this](const std::string& it) {

			std::shared_ptr<Camera> cam = cameraById(it.c_str());

			if (cam.get())
			{
				printf("Camera Disconnected : %s\n", cam->unique_id().c_str());
				cam->invalidate();
			}
		});

		// New cameras
		new_count = new_ximea_cameras.size();
		std::copy(new_ximea_cameras.begin(), new_ximea_cameras.end(), std::back_inserter(m_cameras));
	}

	return new_count;
}

void CaptureNode::setGlobalParams(const std::string& json)
{
	if (json.empty())
		return;

	// Parse global settings recieved from server at launch

	rapidjson::Document doc;
	doc.Parse(json.c_str());

	if (doc.HasMember("display_focus_peak"))
	{
		std::lock_guard<std::mutex> lock(m_mutex);
		for (auto& cam : m_cameras)
			cam->set_display_focus_peak(doc["display_focus_peak"].GetBool());
	}
	if (doc.HasMember("display_overexposed"))
	{
		std::lock_guard<std::mutex> lock(m_mutex);
		for (auto& cam : m_cameras)
			cam->set_display_overexposed(doc["display_overexposed"].GetBool());
	}
	if (doc.HasMember("display_histogram"))
	{
		std::lock_guard<std::mutex> lock(m_mutex);
		for (auto& cam : m_cameras)
			cam->set_display_histogram(doc["display_histogram"].GetBool());
	}
	if (doc.HasMember("bitdepth_avi"))
	{
		if (doc["bitdepth_avi"].GetInt() != m_bitdepth_default)
		{
			m_bitdepth_default = doc["bitdepth_avi"].GetInt();

			std::lock_guard<std::mutex> lock(m_mutex);
			for (auto& cam : m_cameras)
				if (!cam->recording())
					cam->set_bitdepth(m_bitdepth_default);
		}
	}
	if (doc.HasMember("bitdepth_single"))
	{
		m_bitdepth_maximum = doc["bitdepth_single"].GetInt();
	}
	if (doc.HasMember("preview_frame"))
	{
		for (std::shared_ptr<Camera> camera : m_cameras)
		{
			camera->set_preview_frame(doc["preview_frame"].GetInt());
		}
	}

	if (doc.HasMember("frequency"))
	{
		int freq = 0;
		if (doc["frequency"].IsInt())
			freq = doc["frequency"].GetInt();
		if (doc["frequency"].IsString())
			freq = atoi(doc["frequency"].GetString()); // fix for bad JSON from server

		set_global_framerate(freq,
			doc.HasMember("pulse_duration") ? doc["pulse_duration"].GetInt() : 0,
			doc.HasMember("external_sync") ? doc["external_sync"].GetBool() : false);

		std::lock_guard<std::mutex> lock(m_mutex);

		// Enable sync on all cameras
		for (auto& cam : m_cameras)
			cam->set_hardware_sync_freq(freq);
	}

	if (doc.HasMember("sync_freq") && doc.HasMember("pulse_duration"))
	{
		// Set hardware sync frequency
		int sync_freq = doc["sync_freq"].GetInt();
		int duration = doc["pulse_duration"].GetInt();

		set_global_framerate(sync_freq, duration,
			doc.HasMember("external_sync") ? doc["external_sync"].GetBool() : false);

		std::lock_guard<std::mutex> lock(m_mutex);

		// Activate sync on all cameras
		for (auto& cam : m_cameras)
			cam->set_hardware_sync_freq(sync_freq);
	}

	if (doc.HasMember("camera_params") && doc["camera_params"].IsArray())
	{
		const rapidjson::Value& params = doc["camera_params"];
		for (rapidjson::SizeType i = 0; i < params.Size(); i++)
		{
			if (params[i].HasMember("unique_id"))
			{
				std::string camera_name = params[i]["unique_id"].GetString();

				// TODO Camera ROI

				auto it = cameraById(camera_name.c_str());
				if (it)
				{
					for (rapidjson::Value::ConstMemberIterator itr = params[i].MemberBegin(); itr != params[i].MemberEnd(); ++itr)
					{
						if (itr->value.IsBool() && (strcmp(itr->name.GetString(),"using_sync"))==0) // special case
						{
							it->set_hardware_sync(itr->value.GetBool(), global_framerate());
						}
						if (itr->value.IsDouble())
						{
							it->param_set(itr->name.GetString(), itr->value.GetDouble());
						}
					}
				}
			}
		}
	}
}

std::shared_ptr<Camera> CaptureNode::cameraById(const char * unique_id)
{
	for (auto c : m_cameras)
	{
		if (c->unique_id() == unique_id)
			return c;
	}
	return std::shared_ptr<Camera>();
}

const std::vector<std::shared_ptr<Camera> > CaptureNode::cameraList()
{
	std::lock_guard<std::mutex> lock(m_mutex);

	return  std::vector<std::shared_ptr<Camera> >(m_cameras);
}

std::string CaptureNode::sync_port() const
{
	if (m_sync.get())
		return m_sync->port();
	return "";
}

void CaptureNode::set_global_framerate(int freq, int duration_us, bool external_sync)
{
	if (duration_us)
		m_global_pulse_duration = duration_us;
	m_global_framerate = freq;

	// TEMPORARY options to be added to UI
	m_external_sync_always = false;
	m_external_sync_while_recording = external_sync;

	if (m_sync_active && m_sync.get())
	{
		std::cout << "Set global framerate to " << freq << std::endl;
		if (duration_us)
			std::cout << "Set global pulse duration to " << duration_us << std::endl;
		if (m_external_sync_always)
			std::cout << "Using external sync: Always" << std::endl;
		if (m_external_sync_while_recording)
			std::cout << "Using external sync: While Recording" << std::endl;

		m_sync->start(m_global_framerate, m_global_pulse_duration, m_external_sync_always);
	}
}

bool CaptureNode::can_record() const
{
	return m_recording_cameras.empty() && !m_capture_folders.empty();
}

std::vector<std::string> CaptureNode::get_take_recording_folders()
{
	namespace fs = boost::filesystem;

	std::vector<std::string> folders;

	std::string timestamp;
	{
		auto t = std::time(nullptr);
		auto tm = *std::localtime(&t);

		std::ostringstream oss;
		oss << std::put_time(&tm, "%Y%m%d_%H%M%S");
		timestamp = oss.str();
	}

	for (auto& it : m_capture_folders)
	{
		fs::path new_folder = fs::path(it.first) / timestamp;
		folders.push_back(new_folder.string());

		if (!fs::exists(new_folder))
			fs::create_directories(new_folder);
	}

	return folders;
}

void CaptureNode::record_image_sequence(int frame_count)
{
	prepare_single(frame_count);
	prepare_multi_stage2();
	recording_trigger();
	finalize_single();
}

void CaptureNode::start_recording_all()
{
	prepare_multi_stage1();
	prepare_multi_stage2();
	recording_trigger();
}

void CaptureNode::prepare_single(int count)
{
	std::cout << "STATUS> Prepare Single" << std::endl;

	namespace fs = boost::filesystem;

	// Record to the fastest drive found
	std::vector<std::string> folders;
	folders.push_back(get_take_recording_folders()[0]);

	if (!fs::exists(folders[0]))
		fs::create_directories(folders[0]);

	std::cout << "Recording " << count << " frame(s) to " << folders[0] << std::endl;

	m_recording_cameras.clear();

	std::lock_guard<std::mutex> lock(m_mutex);

	for (auto& cam : m_cameras)
	{
		if (cam->capturing() && !cam->is_audio_only()) // Audio only devices not recorded in single-frame
		{
			cam->m_debug_in_capture_cycle = true;
			m_recording_cameras.push_back(cam);
		}
	}

	for (auto& cam : m_recording_cameras)
	{
		cam->m_debug_timings = true;
		cam->m_prepare_recording = true;
	}

	// Change bitdepth for single capture
	for (auto& cam : m_recording_cameras)
	{
		if (cam->set_bitdepth(m_bitdepth_maximum))
			cam->block_until_next_frame(0.240);
	}

	// Begin recording
	for (auto& cam : m_recording_cameras)
	{
		cam->start_recording(folders, true, count); // Wait for trigger
	}
}

void CaptureNode::recording_trigger()
{
	std::cout << "STATUS> Trigger" << std::endl;

	// Trigger Recording on all cameras that have no hardware sync
	for (auto& cam : m_recording_cameras)
	{
		if (!cam->using_hardware_sync())
			cam->software_trigger();
	}

	// Pause Sync for 300 ms
	if (sync_connected())
	{
		pause_sync();
		boost::this_thread::sleep_for(boost::chrono::milliseconds(250));
		resume_sync(true);
	}
}

shared_json_doc CaptureNode::finalize_single()
{
	std::cout << "STATUS> Finalize Single" << std::endl;

	// Create new json document, to contain summary from all cameras
	shared_json_doc all_cameras_doc(new rapidjson::Document());
	all_cameras_doc->SetObject();
	rapidjson::Value cameras(rapidjson::kArrayType);

	// Block until cameras have stopped recording
	{
		for (auto& cam : m_recording_cameras)
		{
			while (cam->recording()) {
				boost::this_thread::sleep_for(boost::chrono::milliseconds(10));
			}
		}
	}

	for (auto& cam : m_recording_cameras)
		cam->m_debug_timings = false;

	// Get last recording summary from all cameras
	{
		for (auto& cam : m_recording_cameras)
		{
			shared_json_doc cam_summary = cam->last_summary();
			if (cam_summary)
			{
				// Merge this camera's json data into the common document
				rapidjson::Value cam_root(rapidjson::kObjectType);
				cam_root.CopyFrom(*cam_summary.get(), all_cameras_doc->GetAllocator());
				cameras.PushBack(cam_root, all_cameras_doc->GetAllocator());
			}

			cam->m_debug_in_capture_cycle = false;
			cam->set_bitdepth(m_bitdepth_default);
		}
	}

	// Finalize json structure
	all_cameras_doc->AddMember("cameras", cameras, all_cameras_doc->GetAllocator());

	m_recording_cameras.clear();

	return all_cameras_doc;
}

void CaptureNode::prepare_multi_stage1()
{
	std::cout << "STATUS> Prepare Multi" << std::endl;

	m_recording_cameras.clear();

	std::vector<std::pair<std::shared_ptr<Camera>, int> > to_record;

	{
		std::lock_guard<std::mutex> lock(m_mutex);

		// List of cameras to record, with estimated bandwidth
		for (auto& cam : m_cameras)
		{
			if (cam->capturing())
			{
				cam->m_debug_in_capture_cycle = true;

				// Bitdepth is the same as the continuous preview, we don't need to change it
				//cam->set_bitdepth(m_bitdepth_default);

				int nthreads = (int)(1 + (cam->bandwidth() / 1024 / 1024 / m_bandwidth_per_thread));

				std::cout << "RECORD " << cam->unique_id() << " BW:" << (cam->bandwidth()/1024/1024) << "MB/s Threads:" << nthreads << std::endl; // DEBUG

				to_record.push_back(std::make_pair(cam, nthreads));
			}
		}
	}

	std::sort(to_record.begin(), to_record.end(), [](std::pair < std::shared_ptr<Camera>, int>& a, std::pair < std::shared_ptr<Camera>, int>& b) {return a.second > b.second; });

	// Sort list of folders
	auto folders = get_take_recording_folders();

	// Start record on each camera, passing the folder to use
	int i = 0;
	for (auto it : to_record)
	{
		std::vector<std::string> cam_folders;
		for (int t = 0;t < it.second;t++, i++)
			cam_folders.push_back(folders[i%folders.size()]);

		for (auto f : cam_folders)
			std::cout << "Recording " << it.first->unique_id() << " to " << f << std::endl; // DEBUG

		it.first->start_recording(cam_folders, true);
		m_recording_cameras.push_back(it.first);
	}

	for (auto& cam : m_recording_cameras)
		cam->m_debug_timings = true;
}

void CaptureNode::prepare_multi_stage2()
{
	for (auto& cam : m_recording_cameras)
	{
		cam->remove_recording_hold();
	}
}

shared_json_doc CaptureNode::stop_recording_all()
{
	std::cout << "STATUS> Stop Recording" << std::endl;

	// Create new json document, to contain summary from all cameras
	shared_json_doc all_cameras_doc(new rapidjson::Document());
	all_cameras_doc->SetObject();
	rapidjson::Value cameras(rapidjson::kArrayType);

	for (auto& cam : m_recording_cameras)
	{
		cam->stop_recording();
	}

	for (auto& cam : m_recording_cameras)
	{
		shared_json_doc cam_summary = cam->last_summary();

		if (cam_summary)
		{
			// Merge this camera's json data into the common document
			rapidjson::Value cam_root(rapidjson::kObjectType);
			cam_root.CopyFrom(*cam_summary.get(), all_cameras_doc->GetAllocator());
			cameras.PushBack(cam_root, all_cameras_doc->GetAllocator());
		}
	}

	for (auto& cam : m_recording_cameras)
	{
		cam->m_debug_in_capture_cycle = false;
		cam->set_bitdepth(m_bitdepth_default);
	}

	for (auto& cam : m_recording_cameras)
		cam->m_debug_timings = false;

	// Finalize json structure
	all_cameras_doc->AddMember("cameras", cameras, all_cameras_doc->GetAllocator());

	m_recording_cameras.clear();

	return all_cameras_doc;
}

void CaptureNode::pause_sync()
{
	if (m_sync.get() && m_sync_active)
	{
		m_sync->stop();
		m_sync_active = false;
	}
}

void CaptureNode::resume_sync(bool recording)
{
	if (m_sync.get() && !m_sync_active)
	{
		m_sync->start(m_global_framerate, m_global_pulse_duration, m_external_sync_always || (recording&&m_external_sync_while_recording));
		m_sync_active = true;
	}
}

max_stars_repo_name: kbladin/ava-capture

max_issues_repo_name: kbladin/ava-capture

max_forks_repo_name: kbladin/ava-capture