text:
/*

Copyright (c) 2006, Arvid Norberg, Magnus Jonsson
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 author 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.

*/

#include "libtorrent/pch.hpp"

#include <ctime>
#include <iterator>
#include <algorithm>
#include <set>
#include <cctype>
#include <algorithm>

#ifdef _MSC_VER
#pragma warning(push, 1)
#endif

#include <boost/filesystem/convenience.hpp>
#include <boost/filesystem/exception.hpp>
#include <boost/limits.hpp>
#include <boost/bind.hpp>

#ifdef _MSC_VER
#pragma warning(pop)
#endif

#include "libtorrent/extensions/ut_pex.hpp"
#include "libtorrent/extensions/ut_metadata.hpp"
#include "libtorrent/extensions/lt_trackers.hpp"
#include "libtorrent/extensions/smart_ban.hpp"
#include "libtorrent/peer_id.hpp"
#include "libtorrent/torrent_info.hpp"
#include "libtorrent/tracker_manager.hpp"
#include "libtorrent/bencode.hpp"
#include "libtorrent/hasher.hpp"
#include "libtorrent/entry.hpp"
#include "libtorrent/session.hpp"
#include "libtorrent/fingerprint.hpp"
#include "libtorrent/entry.hpp"
#include "libtorrent/alert_types.hpp"
#include "libtorrent/invariant_check.hpp"
#include "libtorrent/file.hpp"
#include "libtorrent/bt_peer_connection.hpp"
#include "libtorrent/ip_filter.hpp"
#include "libtorrent/socket.hpp"
#include "libtorrent/aux_/session_impl.hpp"
#include "libtorrent/kademlia/dht_tracker.hpp"
#include "libtorrent/natpmp.hpp"
#include "libtorrent/upnp.hpp"

using boost::shared_ptr;
using boost::weak_ptr;
using libtorrent::aux::session_impl;

#ifdef TORRENT_MEMDEBUG
void start_malloc_debug();
void stop_malloc_debug();
#endif

namespace libtorrent
{

	TORRENT_EXPORT void TORRENT_LINK_TEST_NAME() {}

	std::string log_time()
	{
		static const ptime start = time_now_hires();
		char ret[200];
		std::sprintf(ret, "%d", total_milliseconds(time_now() - start));
		return ret;
	}

	namespace aux
	{
		filesystem_init::filesystem_init()
		{
#if BOOST_VERSION < 103400
			using namespace boost::filesystem;
			if (path::default_name_check_writable())
				path::default_name_check(no_check);
#endif
		}
	}

	// this function returns a session_settings object
	// which will optimize libtorrent for minimum memory
	// usage, with no consideration of performance.
	session_settings min_memory_usage()
	{
		session_settings set;
		// setting this to a low limit, means more
		// peers are more likely to request from the
		// same piece. Which means fewer partial
		// pieces and fewer entries in the partial
		// piece list
		set.whole_pieces_threshold = 2;
		set.use_parole_mode = false;
		set.prioritize_partial_pieces = true;

		// be extra nice on the hard drive when running
		// on embedded devices. This might slow down
		// torrent checking
		set.file_checks_delay_per_block = 5;

		// only have 4 files open at a time
		set.file_pool_size = 4;

		// we want to keep the peer list as small as possible
		set.allow_multiple_connections_per_ip = false;
		set.max_failcount = 2;
		set.inactivity_timeout = 120;

		// whenever a peer has downloaded one block, write
		// it to disk, and don't read anything from the
		// socket until the disk write is complete
		set.max_queued_disk_bytes = 1;

		// don't keep track of all upnp devices, keep
		// the device list small
		set.upnp_ignore_nonrouters = true;

		// never keep more than one 16kB block in
		// the send buffer
		set.send_buffer_watermark = 9;

		// don't use any disk cache
		set.cache_size = 0;
		set.cache_buffer_chunk_size = 1;
		set.use_read_cache = false;

		set.close_redundant_connections = true;

		set.max_peerlist_size = 500;
		set.max_paused_peerlist_size = 50;

		// udp trackers are cheaper to talk to
		set.prefer_udp_trackers = true;

		set.max_rejects = 10;

		set.recv_socket_buffer_size = 16 * 1024;
		set.send_socket_buffer_size = 16 * 1024;

		// use less memory when checking pieces
		set.optimize_hashing_for_speed = false;

		// use less memory when reading and writing
		// whole pieces
		set.coalesce_reads = false;
		set.coalesce_writes = false;

		return set;
	}

	session_settings high_performance_seed()
	{
		session_settings set;

		// allow 500 files open at a time
		set.file_pool_size = 500;

		// as a seed box, we must accept multiple peers behind
		// the same NAT
		set.allow_multiple_connections_per_ip = true;

		// use 512 MB of cache
		set.cache_size = 32768;
		set.use_read_cache = true;
		set.cache_buffer_chunk_size = 128;
		set.read_cache_line_size = 512;
		set.write_cache_line_size = 512;
		set.low_prio_disk = false;
		// one hour expiration
		set.cache_expiry = 60 * 60;

		set.close_redundant_connections = true;

		set.max_rejects = 10;

		set.optimize_hashing_for_speed = true;

		// don't let connections linger for too long
		set.request_timeout = 10;
		set.peer_timeout = 20;
		set.inactivity_timeout = 20;

		set.active_limit = 2000;
		set.active_seeds = 2000;

		set.auto_upload_slots = false;

		// in order to be able to deliver very high
		// upload rates, this should be able to cover
		// the bandwidth delay product. Assuming an RTT
		// of 500 ms, and a send rate of 10 MB/s, the upper
		// limit should be 5 MB
		set.send_buffer_watermark = 5 * 1024 * 1024;

		// don't retry peers if they fail once. Let them
		// connect to us if they want to
		set.max_failcount = 1;

		return set;
	}

	session::session(
		fingerprint const& id
		, std::pair<int, int> listen_port_range
		, char const* listen_interface
		, int flags
		, int alert_mask
#if defined TORRENT_VERBOSE_LOGGING || defined TORRENT_LOGGING || defined TORRENT_ERROR_LOGGING
		, fs::path logpath
#endif
		)
		: m_impl(new session_impl(listen_port_range, id, listen_interface
#if defined TORRENT_VERBOSE_LOGGING || defined TORRENT_LOGGING || defined TORRENT_ERROR_LOGGING
		, logpath
#endif
		))
	{
#ifdef TORRENT_MEMDEBUG
		start_malloc_debug();
#endif
		// turn off the filename checking in boost.filesystem
		TORRENT_ASSERT(listen_port_range.first > 0);
		TORRENT_ASSERT(listen_port_range.first < listen_port_range.second);
#ifdef TORRENT_DEBUG
		// this test was added after it came to my attention
		// that devstudios managed c++ failed to generate
		// correct code for boost.function
		boost::function0<void> test = boost::ref(*m_impl);
		TORRENT_ASSERT(!test.empty());
#endif
		set_alert_mask(alert_mask);
#ifndef TORRENT_DISABLE_EXTENSIONS
		if (flags & add_default_plugins)
		{
			add_extension(create_ut_pex_plugin);
			add_extension(create_ut_metadata_plugin);
			add_extension(create_lt_trackers_plugin);
			add_extension(create_smart_ban_plugin);
		}
#endif
		if (flags & start_default_features)
		{
			start_upnp();
			start_natpmp();
#ifndef TORRENT_DISABLE_DHT
			start_dht();
#endif
			start_lsd();
		}
	}

	session::session(fingerprint const& id
		, int flags
		, int alert_mask
#if defined TORRENT_VERBOSE_LOGGING || defined TORRENT_LOGGING || defined TORRENT_ERROR_LOGGING
		, fs::path logpath
#endif
		)
#if defined TORRENT_VERBOSE_LOGGING || defined TORRENT_LOGGING || defined TORRENT_ERROR_LOGGING
		: m_impl(new session_impl(std::make_pair(0, 0), id, "0.0.0.0", logpath))
#else
		: m_impl(new session_impl(std::make_pair(0, 0), id, "0.0.0.0"))
#endif
	{
#ifdef TORRENT_MEMDEBUG
		start_malloc_debug();
#endif
#ifdef TORRENT_DEBUG
		boost::function0<void> test = boost::ref(*m_impl);
		TORRENT_ASSERT(!test.empty());
#endif
		set_alert_mask(alert_mask);
#ifndef TORRENT_DISABLE_EXTENSIONS
		if (flags & add_default_plugins)
		{
			add_extension(create_ut_pex_plugin);
			add_extension(create_ut_metadata_plugin);
			add_extension(create_lt_trackers_plugin);
			add_extension(create_smart_ban_plugin);
		}
#endif
		if (flags & start_default_features)
		{
			start_upnp();
			start_natpmp();
#ifndef TORRENT_DISABLE_DHT
			start_dht();
#endif
			start_lsd();
		}
	}

	session::~session()
	{
		session_impl::mutex_t::scoped_lock l(m_impl->m_mutex);
#ifdef TORRENT_MEMDEBUG
		stop_malloc_debug();
#endif
		TORRENT_ASSERT(m_impl);
		// if there is at least one destruction-proxy
		// abort the session and let the destructor
		// of the proxy to syncronize
		if (!m_impl.unique())
			m_impl->abort();
	}

	void session::save_state(entry& e, boost::uint32_t flags) const
	{
		session_impl::mutex_t::scoped_lock l(m_impl->m_mutex);
		m_impl->save_state(e, flags, l);
	}

	void session::load_state(lazy_entry const& e)
	{
		session_impl::mutex_t::scoped_lock l(m_impl->m_mutex);
		m_impl->load_state(e);
	}

#ifndef TORRENT_DISABLE_EXTENSIONS
	void session::add_extension(boost::function<boost::shared_ptr<torrent_plugin>(torrent*, void*)> ext)
	{
		session_impl::mutex_t::scoped_lock l(m_impl->m_mutex);
		m_impl->add_extension(ext);
	}
#endif

#ifndef TORRENT_DISABLE_GEO_IP
	bool session::load_asnum_db(char const* file)
	{
		session_impl::mutex_t::scoped_lock l(m_impl->m_mutex);
		return m_impl->load_asnum_db(file);
	}

	bool session::load_country_db(char const* file)
	{
		session_impl::mutex_t::scoped_lock l(m_impl->m_mutex);
		return m_impl->load_country_db(file);
	}

	int session::as_for_ip(address const& addr)
	{
		aux::session_impl::mutex_t::scoped_lock l(m_impl->m_mutex);
		return m_impl->as_for_ip(addr);
	}

#ifndef BOOST_FILESYSTEM_NARROW_ONLY
	bool session::load_asnum_db(wchar_t const* file)
	{
		session_impl::mutex_t::scoped_lock l(m_impl->m_mutex);
		return m_impl->load_asnum_db(file);
	}

	bool session::load_country_db(wchar_t const* file)
	{
		session_impl::mutex_t::scoped_lock l(m_impl->m_mutex);
		return m_impl->load_country_db(file);
	}
#endif
#endif

#ifndef TORRENT_NO_DEPRECATE
	void session::load_state(entry const& ses_state)
	{
		std::vector<char> buf;
		bencode(std::back_inserter(buf), ses_state);
		lazy_entry e;
		int ret = lazy_bdecode(&buf[0], &buf[0] + buf.size(), e);
		TORRENT_ASSERT(ret == 0);
		session_impl::mutex_t::scoped_lock l(m_impl->m_mutex);
		m_impl->load_state(e);
	}

	entry session::state() const
	{
		entry ret;
		session_impl::mutex_t::scoped_lock l(m_impl->m_mutex);
		m_impl->save_state(ret, 0xffffffff, l);
		return ret;
	}
#endif

	void session::set_ip_filter(ip_filter const& f)
	{
		session_impl::mutex_t::scoped_lock l(m_impl->m_mutex);
		m_impl->set_ip_filter(f);
	}

	ip_filter const& session::get_ip_filter() const
	{
		session_impl::mutex_t::scoped_lock l(m_impl->m_mutex);
		return m_impl->get_ip_filter();
	}

	void session::set_port_filter(port_filter const& f)
	{
		session_impl::mutex_t::scoped_lock l(m_impl->m_mutex);
		m_impl->set_port_filter(f);
	}

	void session::set_peer_id(peer_id const& id)
	{
		session_impl::mutex_t::scoped_lock l(m_impl->m_mutex);
		m_impl->set_peer_id(id);
	}

	peer_id session::id() const
	{
		session_impl::mutex_t::scoped_lock l(m_impl->m_mutex);
		return m_impl->get_peer_id();
	}

	io_service& session::get_io_service()
	{
		session_impl::mutex_t::scoped_lock l(m_impl->m_mutex);
		return m_impl->m_io_service;
	}

	void session::set_key(int key)
	{
		session_impl::mutex_t::scoped_lock l(m_impl->m_mutex);
		m_impl->set_key(key);
	}

	std::vector<torrent_handle> session::get_torrents() const
	{
		session_impl::mutex_t::scoped_lock l(m_impl->m_mutex);
		return m_impl->get_torrents();
	}

	torrent_handle session::find_torrent(sha1_hash const& info_hash) const
	{
		session_impl::mutex_t::scoped_lock l(m_impl->m_mutex);
		return m_impl->find_torrent_handle(info_hash);
	}

#ifndef BOOST_NO_EXCEPTIONS
	torrent_handle session::add_torrent(add_torrent_params const& params)
	{
		session_impl::mutex_t::scoped_lock l(m_impl->m_mutex);

		error_code ec;
		torrent_handle ret = m_impl->add_torrent(params, ec);
		if (ec) throw libtorrent_exception(ec);
		return ret;
	}
#endif

	torrent_handle session::add_torrent(add_torrent_params const& params, error_code& ec)
	{
		ec.clear();
		session_impl::mutex_t::scoped_lock l(m_impl->m_mutex);
		return m_impl->add_torrent(params, ec);
	}

#ifndef BOOST_NO_EXCEPTIONS
#ifndef TORRENT_NO_DEPRECATE
	// if the torrent already exists, this will throw duplicate_torrent
	torrent_handle session::add_torrent(
		torrent_info const& ti
		, fs::path const& save_path
		, entry const& resume_data
		, storage_mode_t storage_mode
		, bool paused
		, storage_constructor_type sc)
	{
		boost::intrusive_ptr<torrent_info> tip(new torrent_info(ti));
		add_torrent_params p(sc);
		p.ti = tip;
		p.save_path = save_path;
		std::vector<char> buf;
		if (resume_data.type() != entry::undefined_t)
		{
			bencode(std::back_inserter(buf), resume_data);
			p.resume_data = &buf;
		}
		p.storage_mode = storage_mode;
		p.paused = paused;
		return add_torrent(p);
	}

	torrent_handle session::add_torrent(
		boost::intrusive_ptr<torrent_info> ti
		, fs::path const& save_path
		, entry const& resume_data
		, storage_mode_t storage_mode
		, bool paused
		, storage_constructor_type sc
		, void* userdata)
	{
		add_torrent_params p(sc);
		p.ti = ti;
		p.save_path = save_path;
		std::vector<char> buf;
		if (resume_data.type() != entry::undefined_t)
		{
			bencode(std::back_inserter(buf), resume_data);
			p.resume_data = &buf;
		}
		p.storage_mode = storage_mode;
		p.paused = paused;
		p.userdata = userdata;
		return add_torrent(p);
	}

	torrent_handle session::add_torrent(
		char const* tracker_url
		, sha1_hash const& info_hash
		, char const* name
		, fs::path const& save_path
		, entry const& e
		, storage_mode_t storage_mode
		, bool paused
		, storage_constructor_type sc
		, void* userdata)
	{
		add_torrent_params p(sc);
		p.tracker_url = tracker_url;
		p.info_hash = info_hash;
		p.save_path = save_path;
		p.paused = paused;
		p.userdata = userdata;
		return add_torrent(p);
	}
#endif // TORRENT_NO_DEPRECATE
#endif // BOOST_NO_EXCEPTIONS

	void session::remove_torrent(const torrent_handle& h, int options)
	{
		session_impl::mutex_t::scoped_lock l(m_impl->m_mutex);
		m_impl->remove_torrent(h, options);
	}

	bool session::listen_on(
		std::pair<int, int> const& port_range
		, const char* net_interface)
	{
		session_impl::mutex_t::scoped_lock l(m_impl->m_mutex);
		return m_impl->listen_on(port_range, net_interface);
	}

	unsigned short session::listen_port() const
	{
		session_impl::mutex_t::scoped_lock l(m_impl->m_mutex);
		return m_impl->listen_port();
	}

	session_status session::status() const
	{
		session_impl::mutex_t::scoped_lock l(m_impl->m_mutex);
		return m_impl->status();
	}

	void session::pause()
	{
		session_impl::mutex_t::scoped_lock l(m_impl->m_mutex);
		m_impl->pause();
	}

	void session::resume()
	{
		session_impl::mutex_t::scoped_lock l(m_impl->m_mutex);
		m_impl->resume();
	}

	bool session::is_paused() const
	{
		session_impl::mutex_t::scoped_lock l(m_impl->m_mutex);
		return m_impl->is_paused();
	}

	void session::get_cache_info(sha1_hash const& ih
		, std::vector<cached_piece_info>& ret) const
	{
		session_impl::mutex_t::scoped_lock l(m_impl->m_mutex);
		m_impl->m_disk_thread.get_cache_info(ih, ret);
	}

	cache_status session::get_cache_status() const
	{
		session_impl::mutex_t::scoped_lock l(m_impl->m_mutex);
		return m_impl->m_disk_thread.status();
	}

#ifndef TORRENT_DISABLE_DHT

	void session::start_dht()
	{
		session_impl::mutex_t::scoped_lock l(m_impl->m_mutex);
		// the state is loaded in load_state()
		m_impl->start_dht();
	}

	void session::stop_dht()
	{
		session_impl::mutex_t::scoped_lock l(m_impl->m_mutex);
		m_impl->stop_dht();
	}

	void session::set_dht_settings(dht_settings const& settings)
	{
		session_impl::mutex_t::scoped_lock l(m_impl->m_mutex);
		m_impl->set_dht_settings(settings);
	}

#ifndef TORRENT_NO_DEPRECATE
	void session::start_dht(entry const& startup_state)
	{
		session_impl::mutex_t::scoped_lock l(m_impl->m_mutex);
		m_impl->start_dht(startup_state);
	}

	entry session::dht_state() const
	{
		session_impl::mutex_t::scoped_lock l(m_impl->m_mutex);
		return m_impl->dht_state(l);
	}
#endif

	void session::add_dht_node(std::pair<std::string, int> const& node)
	{
		session_impl::mutex_t::scoped_lock l(m_impl->m_mutex);
		m_impl->add_dht_node(node);
	}

	void session::add_dht_router(std::pair<std::string, int> const& node)
	{
		session_impl::mutex_t::scoped_lock l(m_impl->m_mutex);
		m_impl->add_dht_router(node);
	}

	bool session::is_dht_running() const
	{
		session_impl::mutex_t::scoped_lock l(m_impl->m_mutex);
		return m_impl->m_dht;
	}

#endif

#ifndef TORRENT_DISABLE_ENCRYPTION
	void session::set_pe_settings(pe_settings const& settings)
	{
		session_impl::mutex_t::scoped_lock l(m_impl->m_mutex);
		m_impl->set_pe_settings(settings);
	}

	pe_settings const& session::get_pe_settings() const
	{
		session_impl::mutex_t::scoped_lock l(m_impl->m_mutex);
		return m_impl->get_pe_settings();
	}
#endif

	bool session::is_listening() const
	{
		session_impl::mutex_t::scoped_lock l(m_impl->m_mutex);
		return m_impl->is_listening();
	}

	void session::set_settings(session_settings const& s)
	{
		session_impl::mutex_t::scoped_lock l(m_impl->m_mutex);
		m_impl->set_settings(s);
	}

	session_settings const& session::settings()
	{
		session_impl::mutex_t::scoped_lock l(m_impl->m_mutex);
		return m_impl->settings();
	}

	void session::set_proxy(proxy_settings const& s)
	{
		session_impl::mutex_t::scoped_lock l(m_impl->m_mutex);
		m_impl->set_proxy(s);
	}

	proxy_settings const& session::proxy() const
	{
		session_impl::mutex_t::scoped_lock l(m_impl->m_mutex);
		return m_impl->proxy();
	}

#ifndef TORRENT_NO_DEPRECATE
	void session::set_peer_proxy(proxy_settings const& s)
	{
		session_impl::mutex_t::scoped_lock l(m_impl->m_mutex);
		m_impl->set_peer_proxy(s);
	}

	void session::set_web_seed_proxy(proxy_settings const& s)
	{
		session_impl::mutex_t::scoped_lock l(m_impl->m_mutex);
		m_impl->set_web_seed_proxy(s);
	}

	void session::set_tracker_proxy(proxy_settings const& s)
	{
		session_impl::mutex_t::scoped_lock l(m_impl->m_mutex);
		m_impl->set_tracker_proxy(s);
	}

	proxy_settings const& session::peer_proxy() const
	{
		session_impl::mutex_t::scoped_lock l(m_impl->m_mutex);
		return m_impl->peer_proxy();
	}

	proxy_settings const& session::web_seed_proxy() const
	{
		session_impl::mutex_t::scoped_lock l(m_impl->m_mutex);
		return m_impl->web_seed_proxy();
	}

	proxy_settings const& session::tracker_proxy() const
	{
		session_impl::mutex_t::scoped_lock l(m_impl->m_mutex);
		return m_impl->tracker_proxy();
	}

#ifndef TORRENT_DISABLE_DHT
	void session::set_dht_proxy(proxy_settings const& s)
	{
		session_impl::mutex_t::scoped_lock l(m_impl->m_mutex);
		m_impl->set_dht_proxy(s);
	}

	proxy_settings const& session::dht_proxy() const
	{
		session_impl::mutex_t::scoped_lock l(m_impl->m_mutex);
		return m_impl->dht_proxy();
	}
#endif
#endif // TORRENT_NO_DEPRECATE

	int session::max_uploads() const
	{
		session_impl::mutex_t::scoped_lock l(m_impl->m_mutex);
		return m_impl->max_uploads();
	}

	void session::set_max_uploads(int limit)
	{
		session_impl::mutex_t::scoped_lock l(m_impl->m_mutex);
		m_impl->set_max_uploads(limit);
	}

	int session::max_connections() const
	{
		session_impl::mutex_t::scoped_lock l(m_impl->m_mutex);
		return m_impl->max_connections();
	}

	void session::set_max_connections(int limit)
	{
		session_impl::mutex_t::scoped_lock l(m_impl->m_mutex);
		m_impl->set_max_connections(limit);
	}

	int session::max_half_open_connections() const
	{
		session_impl::mutex_t::scoped_lock l(m_impl->m_mutex);
		return m_impl->max_half_open_connections();
	}

	void session::set_max_half_open_connections(int limit)
	{
		session_impl::mutex_t::scoped_lock l(m_impl->m_mutex);
		m_impl->set_max_half_open_connections(limit);
	}

	int session::local_upload_rate_limit() const
	{
		session_impl::mutex_t::scoped_lock l(m_impl->m_mutex);
		return m_impl->local_upload_rate_limit();
	}

	int session::local_download_rate_limit() const
	{
		session_impl::mutex_t::scoped_lock l(m_impl->m_mutex);
		return m_impl->local_download_rate_limit();
	}

	int session::upload_rate_limit() const
	{
		session_impl::mutex_t::scoped_lock l(m_impl->m_mutex);
		return m_impl->upload_rate_limit();
	}

	int session::download_rate_limit() const
	{
		session_impl::mutex_t::scoped_lock l(m_impl->m_mutex);
		return m_impl->download_rate_limit();
	}

	void session::set_local_upload_rate_limit(int bytes_per_second)
	{
		session_impl::mutex_t::scoped_lock l(m_impl->m_mutex);
		m_impl->set_local_upload_rate_limit(bytes_per_second);
	}

	void session::set_local_download_rate_limit(int bytes_per_second)
	{
		session_impl::mutex_t::scoped_lock l(m_impl->m_mutex);
		m_impl->set_local_download_rate_limit(bytes_per_second);
	}

	void session::set_upload_rate_limit(int bytes_per_second)
	{
		session_impl::mutex_t::scoped_lock l(m_impl->m_mutex);
		m_impl->set_upload_rate_limit(bytes_per_second);
	}

	void session::set_download_rate_limit(int bytes_per_second)
	{
		session_impl::mutex_t::scoped_lock l(m_impl->m_mutex);
		m_impl->set_download_rate_limit(bytes_per_second);
	}

	int session::num_uploads() const
	{
		session_impl::mutex_t::scoped_lock l(m_impl->m_mutex);
		return m_impl->num_uploads();
	}

	int session::num_connections() const
	{
		session_impl::mutex_t::scoped_lock l(m_impl->m_mutex);
		return m_impl->num_connections();
	}

	std::auto_ptr<alert> session::pop_alert()
	{
		session_impl::mutex_t::scoped_lock l(m_impl->m_mutex);
		return m_impl->pop_alert();
	}

	void session::set_alert_dispatch(boost::function<void(alert const&)> const& fun)
	{
		// this function deliberately doesn't acquire the mutex
		return m_impl->set_alert_dispatch(fun);
	}

	alert const* session::wait_for_alert(time_duration max_wait)
	{
		// this function deliberately doesn't acquire the mutex
		return m_impl->wait_for_alert(max_wait);
	}

	void session::set_alert_mask(int m)
	{
		session_impl::mutex_t::scoped_lock l(m_impl->m_mutex);
		m_impl->set_alert_mask(m);
	}

	size_t session::set_alert_queue_size_limit(size_t queue_size_limit_)
	{
		session_impl::mutex_t::scoped_lock l(m_impl->m_mutex);
		return m_impl->set_alert_queue_size_limit(queue_size_limit_);
	}

#ifndef TORRENT_NO_DEPRECATE
	void session::set_severity_level(alert::severity_t s)
	{
		session_impl::mutex_t::scoped_lock l(m_impl->m_mutex);
		int m = 0;
		switch (s)
		{
			case alert::debug: m = alert::all_categories; break;
			case alert::info: m = alert::all_categories & ~(alert::debug_notification
				| alert::progress_notification | alert::dht_notification); break;
			case alert::warning: m = alert::all_categories & ~(alert::debug_notification
				| alert::status_notification | alert::progress_notification
				| alert::dht_notification); break;
			case alert::critical: m = alert::error_notification | alert::storage_notification; break;
			case alert::fatal: m = alert::error_notification; break;
			default: break;
		}

		m_impl->set_alert_mask(m);
	}
#endif

	void session::start_lsd()
	{
		session_impl::mutex_t::scoped_lock l(m_impl->m_mutex);
		m_impl->start_lsd();
	}

	natpmp* session::start_natpmp()
	{
		session_impl::mutex_t::scoped_lock l(m_impl->m_mutex);
		if (m_impl->m_natpmp) return m_impl->m_natpmp.get();

		// the natpmp constructor may fail and call the callbacks
		// into the session_impl. We cannot hold the mutex then
		l.unlock();
		natpmp* n = new (std::nothrow) natpmp(m_impl->m_io_service
			, m_impl->m_listen_interface.address()
			, boost::bind(&session_impl::on_port_mapping
				, m_impl.get(), _1, _2, _3, 0)
			, boost::bind(&session_impl::on_port_map_log
				, m_impl.get(), _1, 0));
		l.lock();

		if (n == 0) return 0;

		m_impl->start_natpmp(n);
		return n;
	}

	upnp* session::start_upnp()
	{
		session_impl::mutex_t::scoped_lock l(m_impl->m_mutex);

		if (m_impl->m_upnp) return m_impl->m_upnp.get();

		// the upnp constructor may fail and call the callbacks
		// into the session_impl. We cannot hold the mutex then
		l.unlock();
		upnp* u = new (std::nothrow) upnp(m_impl->m_io_service
			, m_impl->m_half_open
			, m_impl->m_listen_interface.address()
			, m_impl->m_settings.user_agent
			, boost::bind(&session_impl::on_port_mapping
				, m_impl.get(), _1, _2, _3, 1)
			, boost::bind(&session_impl::on_port_map_log
				, m_impl.get(), _1, 1)
			, m_impl->m_settings.upnp_ignore_nonrouters);
		l.lock();

		if (u == 0) return 0;

		m_impl->start_upnp(u);
		return u;
	}

	void session::stop_lsd()
	{
		session_impl::mutex_t::scoped_lock l(m_impl->m_mutex);
		m_impl->stop_lsd();
	}

	void session::stop_natpmp()
	{
		session_impl::mutex_t::scoped_lock l(m_impl->m_mutex);
		m_impl->stop_natpmp();
	}

	void session::stop_upnp()
	{
		session_impl::mutex_t::scoped_lock l(m_impl->m_mutex);
		m_impl->stop_upnp();
	}

	connection_queue& session::get_connection_queue()
	{
		session_impl::mutex_t::scoped_lock l(m_impl->m_mutex);
		return m_impl->m_half_open;
	}
}

max_stars_repo_name: CarysT/medusa

max_issues_repo_name: CarysT/medusa

max_forks_repo_name: CarysT/medusa


text:
/*
 * value_output.hpp
 *
 *  Created on: 19.02.2016
 *      Author: mike_gresens
 */

#pragma once

#include <boost/date_time/posix_time/time_formatters.hpp>
#include <boost/algorithm/hex.hpp>

namespace hessian {

class output_visitor
:
	public boost::static_visitor<>
{
public:
	output_visitor(std::ostream& stream);
	result_type operator()(const null_t& value);
	result_type operator()(const bool_t& value);
	result_type operator()(const int_t& value);
	result_type operator()(const long_t& value);
	result_type operator()(const double_t& value);
	result_type operator()(const date_t& value);
	result_type operator()(const string_t& value);
	result_type operator()(const binary_t& value);
	result_type operator()(const list_t& value);
	result_type operator()(const map_t& value);
	result_type operator()(const object_t& value);

private:
	std::ostream& _stream;
};

output_visitor::output_visitor(std::ostream& stream)
:
	boost::static_visitor<>(),
	_stream(stream)
{
}

output_visitor::result_type
output_visitor::operator()(const null_t& value)
{
	_stream << "null";
}

output_visitor::result_type
output_visitor::operator()(const bool_t& value)
{
	_stream << "bool(" << std::boolalpha << value << std::noboolalpha << ')';
}

output_visitor::result_type
output_visitor::operator()(const int_t& value)
{
	_stream << "int(" << value << ')';
}

output_visitor::result_type
output_visitor::operator()(const long_t& value)
{
	_stream << "long(" << value << ')';
}

output_visitor::result_type
output_visitor::operator()(const double_t& value)
{
	_stream << "double(" << value << ')';
}

output_visitor::result_type
output_visitor::operator()(const date_t& value)
{
	_stream << "date(" << boost::posix_time::to_iso_extended_string(value) << ')';
}

output_visitor::result_type
output_visitor::operator()(const string_t& value)
{
	_stream << "string('" << value << "')";
}

output_visitor::result_type
output_visitor::operator()(const binary_t& value)
{
	_stream << "binary('";
	boost::algorithm::hex(value, std::ostream_iterator<char>(_stream));
	_stream << "')";
}

output_visitor::result_type
output_visitor::operator()(const list_t& value)
{
	_stream << "list(";
	for (list_t::const_iterator element = value.begin(); element != value.end(); ++element)
	{
		if (element != value.begin())
			_stream << ", ";
		boost::apply_visitor(*this, *element);
	}
	_stream << ')';
}

output_visitor::result_type
output_visitor::operator()(const map_t& value)
{
	_stream << "map(";
	for (map_t::const_iterator element = value.begin(); element != value.end(); ++element)
	{
		if (element != value.begin())
			_stream << ", ";
		boost::apply_visitor(*this, element->first);
		_stream << " = ";
		boost::apply_visitor(*this, element->second);
	}
	_stream << ')';
}

output_visitor::result_type
output_visitor::operator()(const object_t& value)
{
	_stream << "object(";
	for (object_t::const_iterator element = value.begin(); element != value.end(); ++element)
	{
		if (element != value.begin())
			_stream << ", ";
		(*this)(element->first);
		_stream << " = ";
		boost::apply_visitor(*this, element->second);
	}
	_stream << ')';
}

}

ext: hpp


text:
#include "libsnark/gadgetlib1/gadgets/basic_gadgets.hpp"
#include "libsnark/zk_proof_systems/ppzksnark/r1cs_ppzksnark/r1cs_ppzksnark.hpp"
#include "libsnark/common/default_types/r1cs_ppzksnark_pp.hpp"
#include "libsnark/common/utils.hpp"
#include <boost/optional.hpp>

using namespace libsnark;
using namespace std;

#include "gadget.hpp"
#include "gadget_neg.hpp"

template<typename ppzksnark_ppT>
r1cs_ppzksnark_keypair<ppzksnark_ppT> generate_keypair(const int jw[32])
{
    typedef Fr<ppzksnark_ppT> FieldT;

    //根据预先定义的计算门和约束生成公共参数秘钥对
    //证明生成端若需要采用对应的公共秘钥生成证明数据成功，则必须使两端的数据符合预先定于的计算约束(R1=R2+R3+X)
    //如此，当验证端根据对应的验证秘钥验证证明数据为真时，验证者就能够相信对应的交易中是符合预定义的计算约束的，而不是生成假证明以通过检查
    protoboard<FieldT> pb;
    l_gadget<FieldT> g(pb);
    g.generate_r1cs_constraints();
    const r1cs_constraint_system<FieldT> constraint_system = pb.get_constraint_system();

    cout << "Number of R1CS constraints: " << constraint_system.num_constraints() << endl;

    return r1cs_ppzksnark_generator<ppzksnark_ppT>(constraint_system);
}

template<typename ppzksnark_ppT>
r1cs_ppzksnark_keypair<ppzksnark_ppT> generate_keypair_neg(const int jw[2][32])
{
    typedef Fr<ppzksnark_ppT> FieldT;

    //根据预先定义的计算门和约束生成公共参数秘钥对
    //证明生成端若需要采用对应的公共秘钥生成证明数据成功，则必须使两端的数据符合预先定于的计算约束(R1+X=R2+R3)
    //如此，当验证端根据对应的验证秘钥验证证明数据为真时，验证者就能够相信对应的交易中是符合预定义的计算约束的，而不是生成假证明以通过检查
    protoboard<FieldT> pb;
    l_gadget_neg<FieldT> g(pb);
    g.generate_r1cs_constraints();
    const r1cs_constraint_system<FieldT> constraint_system = pb.get_constraint_system();

    cout << "Number of R1CS constraints: " << constraint_system.num_constraints() << endl;

    return r1cs_ppzksnark_generator<ppzksnark_ppT>(constraint_system);
}

template<typename ppzksnark_ppT>
boost::optional<r1cs_ppzksnark_proof<ppzksnark_ppT>> generate_proof(r1cs_ppzksnark_proving_key<ppzksnark_ppT> proving_key,
                                                                   const bit_vector &h1,
                                                                   const bit_vector &h2,
                                                                   const bit_vector &h3,
                                                                   const bit_vector &r1,
                                                                   const bit_vector &r2,
                                                                   const bit_vector &r3,
																   const bit_vector &x,
																   const int jw[32]
                                                                   )
{
    typedef Fr<ppzksnark_ppT> FieldT;

    protoboard<FieldT> pb;
    l_gadget<FieldT> g(pb);
    g.generate_r1cs_constraints();
    g.generate_r1cs_witness(h1, h2, h3, r1, r2, r3,x);

    if (!pb.is_satisfied()) {
      std::cout << "System not satisfied!" << std::endl;
        return boost::none;
    }

    return r1cs_ppzksnark_prover<ppzksnark_ppT>(proving_key, pb.primary_input(), pb.auxiliary_input());
}

template<typename ppzksnark_ppT>
boost::optional<r1cs_ppzksnark_proof<ppzksnark_ppT>> generate_proof_neg(r1cs_ppzksnark_proving_key<ppzksnark_ppT> proving_key,
                                                                   const bit_vector &h1,
                                                                   const bit_vector &h2,
                                                                   const bit_vector &h3,
                                                                   const bit_vector &r1,
                                                                   const bit_vector &r2,
                                                                   const bit_vector &r3,
																   const bit_vector &x,
																   const int jw[2][32]
                                                                   )
{
    typedef Fr<ppzksnark_ppT> FieldT;

    protoboard<FieldT> pb;
    l_gadget_neg<FieldT> g(pb);
    g.generate_r1cs_constraints();
    g.generate_r1cs_witness(h1, h2, h3, r1, r2, r3,x);

    if (!pb.is_satisfied()) {
      std::cout << "System not satisfied!" << std::endl;
        return boost::none;
    }

    return r1cs_ppzksnark_prover<ppzksnark_ppT>(proving_key, pb.primary_input(), pb.auxiliary_input());
}

template<typename ppzksnark_ppT>
bool verify_proof(r1cs_ppzksnark_verification_key<ppzksnark_ppT> verification_key,
                  r1cs_ppzksnark_proof<ppzksnark_ppT> proof,
                  const bit_vector &h1,
                  const bit_vector &h2,
                  const bit_vector &h3,
				  const bit_vector &x
                 )
{
    typedef Fr<ppzksnark_ppT> FieldT;

    const r1cs_primary_input<FieldT> input = l_input_map<FieldT>(h1, h2, h3,x);

    std::cout << "**** After l_input_map *****" << std::endl;

    return r1cs_ppzksnark_verifier_strong_IC<ppzksnark_ppT>(verification_key, input, proof);

}


text:
#ifndef ZOMBIE_CTRL_HPP_
#define ZOMBIE_CTRL_HPP_
/////////1/////////2/////////3/////////4/////////5/////////6/////////7/////////8
// Name        :
// Author      : Avi
// Revision    : $Revision: #23 $
//
// Copyright 2009- ECMWF.
// This software is licensed under the terms of the Apache Licence version 2.0
// which can be obtained at http://www.apache.org/licenses/LICENSE-2.0.
// In applying this licence, ECMWF does not waive the privileges and immunities
// granted to it by virtue of its status as an intergovernmental organisation
// nor does it submit to any jurisdiction.
//
// Description : manages the zombies
/////////1/////////2/////////3/////////4/////////5/////////6/////////7/////////8

#include <boost/core/noncopyable.hpp>
#include <boost/date_time/posix_time/posix_time_types.hpp>
#include "Zombie.hpp"
#include "NodeFwd.hpp"
#include "Cmd.hpp"
class TaskCmd;
class AbstractServer;

/// All zombies are auto deleted after a period of time. See Zombie::allowed_age()
class ZombieCtrl : private boost::noncopyable {
public:
	ZombieCtrl() = default;

	/// Handle the zombie, and return back to the client
	bool handle_zombie(
	                   Submittable*,            // Must be NON NULL
	                   const TaskCmd* task_cmd, // The child command
	                   std::string& action_taken,// action taken
	                   STC_Cmd_ptr& theReply    // Reply varies according to User Action
	                   );

	bool handle_path_zombie(
	                   AbstractServer* as,       // Find closest matching node
	                   const TaskCmd* task_cmd,  // The child command
                      std::string& action_taken,// action taken
	                   STC_Cmd_ptr& theReply     // Reply varies according to User Action
	                   );

	/// Find all *Tasks* beneath the input Node, that are in active or submitted states
	/// We deliberately ignore aliases (This was requested by Axel)
	/// Then add as 'USER' zombies. This should be called when commands like, delete, requeue,
	/// run, are using the force option, and will create zombies.
	void add_user_zombies(Node*,const std::string& user_cmd);
	void add_user_zombies(defs_ptr,const std::string& user_cmd);
   void add_user_zombies(const std::vector<Submittable*>& tasks,const std::string& user_cmd);

	/// Returns the list of zombies, **updated** with seconds since creation
	/// To avoid sending attr to client, we copy over its setting, if in effect
 	void get(std::vector<Zombie>&)  ;

	/// remove all zombies, older than their allowed age
 	/// Server typically checks every 60 seconds
	void remove_stale_zombies(const boost::posix_time::ptime& time_now);

	/// Will ask the child command to terminate, *without* the child command raising any errors
	/// Since we can have many child commands(init,event,meter, label,complete) in a job
	/// This fob must stay around, since we don't know how long the job will last for.
	/// Will override, fail,recover,remove
	/// For Command Line Interface only the task_path is provided. Just have to make do.
	void fob(const std::string& path_to_task, const std::string& process_or_remote_id, const std::string& password);
	void fobCli(const std::string& path_to_task, Submittable*);

	/// Similar to a fob, But will ask the child command to terminate, with an error.
	/// Typically this will raise a trap in the job file, and hence raise an abort
	/// However the abort will also be a zombie, and will also be auto-terminated
	/// Hence the job file must be careful to use 'set -e' to avoid infinite recursion
	/// Since we can have many child commands(init,event,meter, label,complete) in a job
	/// This fob must stay around, since we don't know how long the job will last for.
	/// Will override, fob,recover,remove
	/// For Command Line Interface only the task_path is provided. Just have to make do.
	void fail( const std::string& path_to_task, const std::string& process_or_remote_id, const std::string& password);
	void failCli(const std::string& path_to_task, Submittable*);

	/// Find the task node, corresponding to the zombie, and copy over
	/// the password. Then remove the zombie. Next time the child commands
	/// communicate with the server, all will be ok
	/// Will override, fail,fob,remove
	/// For Command Line Interface only the task_path is provided. Just have to make do.
	void adopt(const std::string& path_to_task, const std::string& process_or_remote_id, const std::string& password);
	void adoptCli(const std::string& path_to_task, Submittable*);
	void block(const std::string& path_to_task, const std::string& process_or_remote_id, const std::string& password);
	void blockCli(const std::string& path_to_task, Submittable*);
   void kill(const std::string& path_to_task, const std::string& process_or_remote_id, const std::string& password);
   void killCli(const std::string& path_to_task, Submittable*);

	/// Remove the zombie corresponding to the Task path. Should only be one
	/// Since we can have many child commands(init,event,meter, label,complete) in a job
	/// the zombies may get re-added, should we rember this.
	/// If path not found does nothing.
	/// For Command Line Interface only the task_path is provided. Just have to make do.
	bool remove(Submittable*);
	bool remove(const std::string& path_to_task, const std::string& process_or_remote_id, const std::string& password);
	void removeCli(const std::string& path_to_task, Submittable*);
    bool remove_by_path(const std::string& path_to_task);

	/// Query
 	const Zombie& find(const std::string& path_to_task, const std::string& process_or_remote_id, const std::string& password) const;
	const Zombie& find_by_path_only(const std::string& path_to_task) const;

private:

	bool handle_existing_zombie(
	                   Zombie &,                // The server already knows about the zombie
	                   Submittable*,            // This NULL for path zombies
	                   node_ptr closest_matching_node, // only set for path zombies
	                   const TaskCmd* task_cmd, // The child command
                      std::string& action_taken,// User action taken
	                   STC_Cmd_ptr& theReply    // Reply varies according to User Action
	                   );

	bool handle_user_actions(
	                   Zombie &,                 // The server already knows about the zombie
	                   Submittable*,             // This NULL for path zombies
	                   const TaskCmd* task_cmd,  // The child command
                      std::string& action_taken,// User action taken
	                   STC_Cmd_ptr& theReply     // Reply varies according to User Action
	                   );

	Zombie& find_zombie(const std::string& path_to_task, const std::string& process_or_remote_id, const std::string& password);
	Zombie& find(Submittable*);
	const Zombie& find(Submittable*) const;
	Zombie& find_by_path(const std::string& path_to_task);

private:
	std::vector<Zombie> zombies_;
};
#endif

max_stars_repo_name: mpartio/ecflow

max_issues_repo_name: mpartio/ecflow

max_forks_repo_name: mpartio/ecflow


text:
#include <elementSpec.h>
#include <boost/python.hpp>

using namespace boost::python;

BOOST_PYTHON_MEMBER_FUNCTION_OVERLOADS(add_inputs, add_input, 0, 1)
BOOST_PYTHON_MEMBER_FUNCTION_OVERLOADS(add_outputs, add_output, 0, 1)

int (ElementSpec::*ri_i)(int)      = &ElementSpec::remove_input;
int (ElementSpec::*ri_v)(ValuePtr) = &ElementSpec::remove_input;
int (ElementSpec::*ro_i)(int)      = &ElementSpec::remove_output;
int (ElementSpec::*ro_v)(ValuePtr) = &ElementSpec::remove_output;

void export_elementSpec()
{
scope outer =
  class_<ElementSpec, boost::shared_ptr<ElementSpec> >
        ("ElementSpec", init<ElementPtr>())
     .def("element",  &ElementSpec::element)
     .def("toString", &ElementSpec::toString)

     .def("add_input", &ElementSpec::add_input, add_inputs())
     .def("add_output", &ElementSpec::add_output, add_outputs())

     .def("remove_input",  ri_i)
     .def("remove_input",  ri_v)
     .def("remove_output", ri_i)
     .def("remove_output", ri_v)
  ;

  class_<ElementSpec::Hookup, ElementSpec::HookupPtr>
        ("Hookup", init<ElementSpecPtr, int, ElementSpecPtr, int>())
  ;
}

ext: cpp


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

/*
 * FakeLinkProber.cpp
 *
 *  Created on: Oct 23, 2020
 *      Author: tamer
 */

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

#include "FakeLinkProber.h"
#include "common/MuxLogger.h"

namespace test
{

FakeLinkProber::FakeLinkProber(
    link_prober::LinkProberStateMachineBase *linkProberStateMachine
) :
    mLinkProberStateMachine(linkProberStateMachine)
{
}

template<class E>
void FakeLinkProber::postLinkProberEvent(E &e)
{
    boost::asio::io_service::strand& strand = mLinkProberStateMachine->getStrand();
    boost::asio::io_service &ioService = strand.context();
    ioService.post(
        strand.wrap(
            [this, &e]() { mLinkProberStateMachine->processEvent(e); }
        )
    );
}

template
void FakeLinkProber::postLinkProberEvent<link_prober::IcmpSelfEvent&>(link_prober::IcmpSelfEvent &event);

template
void FakeLinkProber::postLinkProberEvent<link_prober::IcmpPeerEvent&>(link_prober::IcmpPeerEvent &event);

template
void FakeLinkProber::postLinkProberEvent<link_prober::IcmpUnknownEvent&>(link_prober::IcmpUnknownEvent &event);

template
void FakeLinkProber::postLinkProberEvent<link_prober::IcmpPeerActiveEvent&>(link_prober::IcmpPeerActiveEvent &event);

template
void FakeLinkProber::postLinkProberEvent<link_prober::IcmpPeerUnknownEvent&>(link_prober::IcmpPeerUnknownEvent &event);

void FakeLinkProber::postSuspendTimerExpiredEvent()
{
    // inform the composite state machine about Suspend timer expiry
    boost::asio::io_service::strand& strand = mLinkProberStateMachine->getStrand();
    boost::asio::io_service &ioService = strand.context();
    ioService.post(strand.wrap(boost::bind(
        static_cast<void (link_prober::LinkProberStateMachineBase::*) (link_prober::SuspendTimerExpiredEvent&)>
            (&link_prober::LinkProberStateMachineBase::processEvent),
        mLinkProberStateMachine,
        link_prober::LinkProberStateMachineBase::getSuspendTimerExpiredEvent()
    )));
}

void FakeLinkProber::initialize()
{
    MUXLOGINFO("");

    mInitializeCallCount++;
}

void FakeLinkProber::startProbing()
{
    MUXLOGINFO("");

    mStartProbingCallCount++;
}

void FakeLinkProber::updateEthernetFrame()
{
    MUXLOGINFO("");

    mUpdateEthernetFrameCallCount++;
}

void FakeLinkProber::probePeerTor()
{
    MUXLOGINFO("");

    mProbePeerTorCallCount++;
}

void FakeLinkProber::suspendTxProbes(uint32_t suspendTime_msec)
{
    MUXLOGINFO("");

    mSuspendTxProbeCallCount++;
}

void FakeLinkProber::resumeTxProbes()
{
    MUXLOGINFO("");

    mResumeTxProbeCallCount++;
}

void FakeLinkProber::sendPeerSwitchCommand()
{
    MUXLOGINFO("");

    mSendPeerSwitchCommand++;
}

void FakeLinkProber::resetIcmpPacketCounts()
{
    MUXLOGINFO("");

    mIcmpUnknownEventCount = 0;
    mIcmpPacketCount = 0;

    boost::asio::io_service::strand &strand = mLinkProberStateMachine->getStrand();
    boost::asio::io_service &ioService = strand.context();
    ioService.post(strand.wrap(boost::bind(
        &link_prober::LinkProberStateMachineBase::handlePckLossRatioUpdate,
        mLinkProberStateMachine,
        mIcmpUnknownEventCount,
        mIcmpPacketCount
    )));
}

void FakeLinkProber::shutdownTxProbes()
{
    MUXLOGINFO("");

    mShutdownTxProbeCallCount++;
}

void FakeLinkProber::restartTxProbes()
{
    MUXLOGINFO("");

    mRestartTxProbeCallCount++;
}

void FakeLinkProber::decreaseProbeIntervalAfterSwitch(uint32_t switchTime_msec)
{
    MUXLOGINFO("");

    mDecreaseIntervalCallCount++;
}

void FakeLinkProber::revertProbeIntervalAfterSwitchComplete()
{
    MUXLOGINFO("");

    mRevertIntervalCallCount++;
}

} /* namespace test */

max_stars_repo_name: lolyu/sonic-linkmgrd

max_issues_repo_name: lolyu/sonic-linkmgrd

max_forks_repo_name: lolyu/sonic-linkmgrd


text:
// ==========================================================================
// Hugin User Interface
//
// Copyright (C) 2010 Matthew Chaplain, All Rights Reserved.
//
// Permission to reproduce, distribute, perform, display, and to prepare
// derivitive works from this file under the following conditions:
//
// 1. Any copy, reproduction or derivitive work of any part of this file
//    contains this copyright notice and licence in its entirety.
//
// 2. The rights granted to you under this license automatically terminate
//    should you attempt to assert any patent claims against the licensor
//    or contributors, which in any way restrict the ability of any party
//    from using this software or portions thereof in any form under the
//    terms of this license.
//
// Disclaimer: 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 HUGIN_USER_INTERFACE_HPP_
#define HUGIN_USER_INTERFACE_HPP_

#include "hugin/export.hpp"
#include "munin/composite_component.hpp"
#include "paradice/active_encounter.hpp"
#include <boost/asio/strand.hpp>

namespace terminalpp {
    class string;
}

namespace paradice {
    class beast;
    class encounter;
}

namespace hugin {

BOOST_STATIC_CONSTANT(std::string, FACE_INTRO            = "Intro");
BOOST_STATIC_CONSTANT(std::string, FACE_ACCOUNT_CREATION = "AcctCreate");
BOOST_STATIC_CONSTANT(std::string, FACE_CHAR_SELECTION   = "CharSelect");
BOOST_STATIC_CONSTANT(std::string, FACE_CHAR_CREATION    = "CharCreate");
BOOST_STATIC_CONSTANT(std::string, FACE_PASSWORD_CHANGE  = "PwdChange");
BOOST_STATIC_CONSTANT(std::string, FACE_MAIN             = "Main");
BOOST_STATIC_CONSTANT(std::string, FACE_GM_TOOLS         = "GM Tools");

//* =========================================================================
/// \brief An abstraction of the primary user interface for the Paradice
/// application.
//* =========================================================================
class HUGIN_EXPORT user_interface
    : public munin::composite_component
{
public :
    //* =====================================================================
    /// \brief Constructor
    //* =====================================================================
    user_interface(boost::asio::strand &strand);

    //* =====================================================================
    /// \brief Clears the intro screen.
    //* =====================================================================
    void clear_intro_screen();

    //* =====================================================================
    /// \brief Clears the account creation screen.
    //* =====================================================================
    void clear_account_creation_screen();

    //* =====================================================================
    /// \brief Clears the character selection screen.
    //* =====================================================================
    void clear_character_selection_screen();

    //* =====================================================================
    /// \brief Clears the character creation screen.
    //* =====================================================================
    void clear_character_creation_screen();

    //* =====================================================================
    /// \brief Clears the main screen.
    //* =====================================================================
    void clear_main_screen();

    //* =====================================================================
    /// \brief Clears the password change screen.
    //* =====================================================================
    void clear_password_change_screen();

    //* =====================================================================
    /// \brief Set a function to be called when the user inputs the details
    /// for the change of a password.
    //* =====================================================================
    boost::signal<
        void (std::string const &old_password,
              std::string const &new_password,
              std::string const &new_password_verify)> on_password_changed;

    //* =====================================================================
    /// \brief Set a function to be called when the user cancels the change
    /// of a password.
    //* =====================================================================
    boost::signal<void ()> on_password_change_cancelled;

    //* =====================================================================
    /// \brief Set a function to be called when the user inputs a name
    /// and password on the intro screen.
    //* =====================================================================
    boost::signal<
        void (std::string const &username,
              std::string const &hashed_password)> on_login;

    //* =====================================================================
    /// \brief Set a function to be called when the user wants to create
    /// a new account.
    //* =====================================================================
    boost::signal<void ()> on_new_account;

    //* =====================================================================
    /// \brief Set a function to be called when the user inputs the details
    /// for the creation of an account.
    //* =====================================================================
    boost::signal<
        void (std::string const &account_name,
              std::string const &password,
              std::string const &password_verify)> on_account_created;

    //* =====================================================================
    /// \brief Set a function to be called when the user cancels the creation
    /// of an account.
    //* =====================================================================
    boost::signal<void ()> on_account_creation_cancelled;

    //* =====================================================================
    /// \brief Set a function to be called when the user inputs a command
    /// on the main screen.
    //* =====================================================================
    boost::signal<void (std::string const &input)> on_input_entered;

    //* =====================================================================
    /// \brief Provide a function to be called if the user opts to create
    /// a new character.o
    //* =====================================================================
    boost::signal<void ()> on_new_character;

    //* =====================================================================
    /// \brief Provide a function to be called if the user opts to use an
    /// existing character.
    //* =====================================================================
    boost::signal<void (std::string const &name)> on_character_selected;

    //* =====================================================================
    /// \brief Provide a function to be called if the user creates a new
    /// character.
    //* =====================================================================
    boost::signal<
        void (std::string const &name, bool is_gm)> on_character_created;

    //* =====================================================================
    /// \brief Provide a function to be called if the user decides to cancel
    /// the creation of a character.
    //* =====================================================================
    boost::signal<void ()> on_character_creation_cancelled;

    //* =====================================================================
    /// \brief Provide a function to be called if the user hits the 'back'
    /// button on the GM Tools screen
    //* =====================================================================
    boost::signal<void ()> on_gm_tools_back;

    //* =====================================================================
    /// \brief Provide a function to be called if the user inserts a
    /// beast into the current encounter.
    //* =====================================================================
    boost::signal<
        void (std::shared_ptr<paradice::beast> const &)> on_gm_fight_beast;

    //* =====================================================================
    /// \brief Provide a function to be called if the user inserts an
    /// encounter into the current encounter.
    //* =====================================================================
    boost::signal<
        void (std::shared_ptr<paradice::encounter> const &)
    > on_gm_fight_encounter;

    //* =====================================================================
    /// \brief Shows the active encounter window.
    //* =====================================================================
    void show_active_encounter_window();

    //* =====================================================================
    /// \brief Hides the active encounter window.
    //* =====================================================================
    void hide_active_encounter_window();

    //* =====================================================================
    /// \brief Sets the Active Encounter.
    //* =====================================================================
    void set_active_encounter(
        std::shared_ptr<paradice::active_encounter> const &active_encounter);

    //* =====================================================================
    /// \brief Sets the character names belonging to this account.
    //* =====================================================================
    void set_character_names(
        std::vector<
            std::pair<std::string, std::string>
        > const &names);

    //* =====================================================================
    /// \brief Sets the beasts to be used by the user interface
    //* =====================================================================
    void set_beasts(
        std::vector<std::shared_ptr<paradice::beast>> const &beasts);

    //* =====================================================================
    /// \brief Returns the beasts used by the user interface
    //* =====================================================================
    std::vector<std::shared_ptr<paradice::beast>> get_beasts() const;

    //* =====================================================================
    /// \brief Sets the encounters to be used by the user interface
    //* =====================================================================
    void set_encounters(
        std::vector<std::shared_ptr<paradice::encounter>> const &encounters);

    //* =====================================================================
    /// \brief Returns the encounters used by the user interface
    //* =====================================================================
    std::vector<std::shared_ptr<paradice::encounter>> get_encounters() const;

    //* =====================================================================
    /// \brief Select a user interface screen to be shown.
    //* =====================================================================
    void select_face(std::string const &face_name);

    //* =====================================================================
    /// \brief Adds output to the output text area on the main screen.
    //* =====================================================================
    void add_output_text(terminalpp::string const &text);

    //* =====================================================================
    /// \brief Sets the content of the status bar on the intro screen.
    //* =====================================================================
    void set_statusbar_text(terminalpp::string const &text);

    //* =====================================================================
    /// \brief Updates the who list on the main screen.
    //* =====================================================================
    void update_wholist(std::vector<std::string> const &names);

    //* =====================================================================
    /// \brief Adds a line of command history to the input pane.
    //* =====================================================================
    void add_command_history(std::string const &history);

    //* =====================================================================
    /// \brief Shows the Help window.
    //* =====================================================================
    void show_help_window();

    //* =====================================================================
    /// \brief Hides the Help window.
    //* =====================================================================
    void hide_help_window();

    //* =====================================================================
    /// \brief Set up a callback for when the close icon on the help
    /// window is clicked.
    //* =====================================================================
    boost::signal<void ()> on_help_closed;

    //* =====================================================================
    /// \brief Sets the text contained in the Help window.
    //* =====================================================================
    void set_help_window_text(terminalpp::string const &text);

private :
    struct impl;
    std::shared_ptr<impl> pimpl_;
};

}

#endif


text:
#include <cstdlib>

#include <deque>
#include <iostream>
#include <string>
#include <utility>

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

#include "Message.hpp"
#include "PostSession.hpp"
#include "slide/Answer.hpp"

namespace network{

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

void PostSession::start()
{
    std::cerr << "[PostSession::start] (" << id << ") session start" << std::endl;
    manager.add_session(shared_from_this());
    do_read_header();
}

void PostSession::send_message(const Message /*msg*/)
{
}

void PostSession::do_read_header()
{
    std::cerr << "[PostSession::start] (" << id << ") read header" << std::endl;
    auto self(shared_from_this());
    boost::asio::async_read(socket,
        boost::asio::buffer(&msg_header[0], Message::header_length),
        [this,self](boost::system::error_code error, std::size_t length)
        {
            if(!error){
                msg_header[Message::header_length] = '\0';
                std::size_t len = (std::size_t)std::atoi(msg_header);
                std::cerr << "[PostSession::handle_do_read_header] (" << id << "): "
                          << length << "," << len << std::endl;
                delete read_msg;
                read_msg = new Message(len);
                do_read_body();
            }else{
                std::cerr << "[PostSession::do_read_header] Error:" << std::endl;
                std::cerr << error.message() << std::endl;
            }
        });
}

void PostSession::do_read_body()
{
    std::cerr << "[PostSession::start] (" << id << ") read body" << std::endl;
    auto self(shared_from_this());
    boost::asio::async_read(socket,
        boost::asio::buffer(read_msg->body(), read_msg->body_length()),
        [this,self](boost::system::error_code error, std::size_t length)
        {
            if(!error){
                //std::cout.write(read_msg->body(), read_msg->body_length());
                //std::cout << std::endl;
                std::cerr << "[PostSession::handle_do_read_body] (" << id << "): " << length << std::endl;
                std::stringstream ss;
                ss.rdbuf()->sputn(read_msg->body(), read_msg->body_length());
                callback(ss);
                do_read_header();
            }else{
                std::cerr << "[PostSession::do_read_body] Error:" << std::endl;
                std::cerr << error.message() << std::endl;
            }
        });
}

void PostSession::close()
{
    socket.close();
}

} // end of namespace network


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

#ifndef NODE_LIB_HTTP_CONTENT_DISPOSITION_PARSER_HPP
#define NODE_LIB_HTTP_CONTENT_DISPOSITION_PARSER_HPP

#include <smf/http/srv/parser/content_parser.h>

#include <boost/fusion/include/std_pair.hpp>
#include <boost/spirit/include/phoenix.hpp>
#include <boost/fusion/adapted.hpp>
#include <boost/fusion/adapted/struct.hpp>

namespace node
{
	namespace http
	{
		namespace
		{	//	*anonymous*
			struct cdv_parser
				: boost::spirit::qi::symbols<char, rfc2183::values>
			{
				cdv_parser()
				{
					/**
					*	Only lower case entries are valid. See remark below.
					*/
					add
					("inline", rfc2183::cdv_inline)
						("attachment", rfc2183::cdv_attachment)
						("form-data", rfc2183::cdv_form_data)
						("signal", rfc2183::cdv_signal)
						("alert", rfc2183::cdv_alert)
						("icon", rfc2183::cdv_icon)
						("render", rfc2183::cdv_render)
						("recipient-list-history", rfc2183::cdv_recipient_list_history)
						("session", rfc2183::cdv_session)
						("aib", rfc2183::cdv_aib)
						("early-session", rfc2183::cdv_early_session)
						("recipient-list", rfc2183::cdv_recipient_list)
						("notification", rfc2183::cdv_notification)
						("by-reference", rfc2183::cdv_by_reference)
						("info-package", rfc2183::cdv_info_package)
						("recording-session", rfc2183::cdv_recording_session)
						;

				}
			}	content_disposition_values;
		}	//	*anonymous*

		template <typename Iterator>
		content_disposition_parser< Iterator > ::content_disposition_parser()
			: content_disposition_parser::base_type(r_start)
		{
			r_start
				= *r_ws
				>> content_disposition_values
				>> *r_phrase
				;

			r_phrase
				%= boost::spirit::qi::lit(';')
				>> +r_ws
				>> r_token	//.alias()
				>> '='
				>> r_value
				>> *r_ws
				;

			r_token
				= +(boost::spirit::qi::alnum | boost::spirit::qi::char_("-*"))
				;

			r_value
				= r_ut8_filename	//	utf-8''%e2%82%ac%20rates
				| r_quoted_string	//	"demo.jpg"
				| r_token
				;

		}

		template <typename Iterator>
		quoted_string<Iterator>::quoted_string()
			: quoted_string::base_type(r_start)
		{
			//	quoted string(filename = "EURO rates";)

			r_start
				= boost::spirit::qi::lexeme['"' >> r_name >> '"'];
			;

			r_name
				= *(r_esc_ | (boost::spirit::ascii::char_ - '"'))
				;

		}

		template <typename Iterator>
		escape_parser<Iterator>::escape_parser()
			: escape_parser::base_type(r_start)
		{
			//  this statement requires to include the phoenix library
			r_start
				= ('%' >> r_hex)[boost::spirit::_val = boost::spirit::_1]
				;
		}

		template <typename Iterator>
		white_space<Iterator>::white_space()
			: white_space::base_type(r_start)
		{
			//	same as boost::spirit::ascii::blank
			r_start
				= boost::spirit::qi::lit(' ')
				| boost::spirit::qi::lit('\t')
				;
		}

		template <typename Iterator>
		line_separator<Iterator>::line_separator()
			: line_separator::base_type(r_start)
		{

			r_start
				= boost::spirit::qi::lexeme[boost::spirit::qi::lit("\015\012")]
				;
		}

		namespace
		{	//	*anonymous*
			struct esc_symbols : boost::spirit::qi::symbols<char const, char const>
			{
				/**
				* same escape symbols as in C/C++
				* HTTP supports some addiotional characters.
				*/
				esc_symbols()
				{
					add
						//	C/C++
						("\\a", '\a')
						("\\b", '\b')
						("\\f", '\f')
						("\\n", '\n')
						("\\r", '\r')
						("\\t", '\t')
						("\\v", '\v')
						("\\\\", '\\')
						("\\\'", '\'')
						("\\\"", '\"')

						//	rfc822
						("\\(", '(')
						("\\)", ')')
						("\\<", '<')
						("\\>", '>')
						("\\@", '@')
						("\\;", ';')
						("\\,", ',')
						("\\.", '.')
						("\\[", '[')
						("\\]", ']')
						;
				}
			}	r_quoted;
		}	//	*anonymous*

		template <typename Iterator>
		quoted_pair<Iterator>::quoted_pair()
			: quoted_pair::base_type(r_start)
		{
			r_start
				= r_quoted
				;
		}

		template <typename Iterator>
		utf8_filename<Iterator>::utf8_filename()
			: utf8_filename::base_type(r_start)
		{
			//	utf-8 encoded file name (filename*=utf-8''%e2%82%ac%20rates)

			r_start
				= boost::spirit::qi::lit("utf-8''")
				>> r_name
				;

			r_name
				= +(boost::spirit::qi::alnum | r_esc_)
				;

		}

		template <typename Iterator>
		comment<Iterator>::comment()
			: comment::base_type(r_start)
		{
			r_start
				= boost::spirit::qi::lit('(') >> r_string >> boost::spirit::qi::lit(')')
				;

			r_string
				= boost::spirit::qi::lit('(') >> r_string.alias() >> boost::spirit::qi::lit(')')
				| r_ctext
				//| *r_qp
				;

			//	any printable character except '(' and ')'
			r_ctext
				= boost::spirit::qi::hold[*(r_printable - boost::spirit::qi::char_("()"))]
				;
		}

		template <typename Iterator>
		printable<Iterator>::printable()
			: printable::base_type(r_start)
		{

			r_start
				= boost::spirit::qi::char_(" -~")
				;
		}

		//	examples:
		//	multipart/form-data; boundary=----WebKitFormBoundaryBStJolBqHji2FoKK
		template <typename Iterator>
		mime_content_type_parser< Iterator > ::mime_content_type_parser()
			: mime_content_type_parser::base_type(content_type_header)
		{
			content_type_header
				= *boost::spirit::qi::lit(' ')
				>> part
				>> '/'
				>> sub_part
				>> *r_phrase
				;

			part
				= r_token
				| extension_token
				;

			sub_part
				= r_token
				| extension_token
				;

			r_phrase
				= boost::spirit::qi::lit(';')
				>> +ws_
				>> r_attr
				>> '='
				>> value
				>> *ws_
				;

			ws_
				= r_white_space
				| r_line_sep
				| r_comment
				;

			r_attr = r_token.alias();

			value
				= +(r_qp | boost::spirit::qi::char_(" -~"))
				;

			r_token
				= +(boost::spirit::qi::alnum | boost::spirit::qi::char_("-"))
				;

			extension_token
				= boost::spirit::qi::char_("Xx")
				>> boost::spirit::qi::lit('-')
				>> r_token
				;
		}

	}
}

BOOST_FUSION_ADAPT_STRUCT(
	node::http::content_disposition,
	(node::http::rfc2183::values, type_)
	(node::http::param_container_t, params_)
	)

BOOST_FUSION_ADAPT_STRUCT(
	node::http::mime_content_type,
	(std::string, type_)
	(std::string, sub_type_)
	(node::http::param_container_t, phrases_)
)

#endif

max_stars_repo_name: solosTec/node

max_issues_repo_name: solosTec/node

max_forks_repo_name: solosTec/node


text:
//==============================================================================
//         Copyright 2003 - 2011   LASMEA UMR 6602 CNRS/Univ. Clermont II
//         Copyright 2009 - 2011   LRI    UMR 8623 CNRS/Univ Paris Sud XI
//
//          Distributed under the Boost Software License, Version 1.0.
//                 See accompanying file LICENSE.txt or copy at
//                     http://www.boost.org/LICENSE_1_0.txt
//==============================================================================
#include <boost/simd/memory/aligned_object.hpp>
#include <boost/simd/memory/is_aligned.hpp>

#include <nt2/sdk/unit/module.hpp>
#include <nt2/sdk/unit/tests/basic.hpp>
#include <nt2/sdk/unit/tests/relation.hpp>

class foo : public boost::simd::aligned_object<16>
{
  public:
  int  member;
};

////////////////////////////////////////////////////////////////////////////////
// Test foo allocation using the aligned new/delete
////////////////////////////////////////////////////////////////////////////////
NT2_TEST_CASE(overload_new_delete)
{
  using boost::simd::is_aligned;

  foo* ptr = new foo;

  NT2_TEST( is_aligned(ptr,16) );
  ptr->member = 42;
  NT2_TEST_EQUAL( ptr->member, 42 );
  delete ptr;
}

////////////////////////////////////////////////////////////////////////////////
// Test foo allocation using the aligned new/delete
////////////////////////////////////////////////////////////////////////////////
NT2_TEST_CASE(overload_new_delete_array)
{
  using boost::simd::is_aligned;

  foo* ptr = new foo[5];

  NT2_TEST( is_aligned(ptr,16) );

  for(int i=0;i<5;++i) ptr[i].member = 10*i;
  for(int i=0;i<5;++i) NT2_TEST_EQUAL( ptr[i].member, 10*i );

  delete[] ptr;
}

// Clang bug, doesn't deal properly with alignment in empty base classes
// http://llvm.org/bugs/show_bug.cgi?id=14564
// fixed in clang 3.4
#if !defined(__clang__) || (__clang_major__ >= 3 && __clang_minor__ >= 4)
NT2_TEST_CASE(static_alignment)
{
  using boost::simd::is_aligned;

  foo f;

  NT2_TEST_GREATER_EQUAL(sizeof(foo), 16u);
  NT2_TEST( is_aligned(&f, 16) );
}
#endif


text:
#include "examples/Cassie/input_supervisor.h"

#include <Eigen/Dense>
#include <dairlib/lcmt_controller_failure.hpp>
#include <gtest/gtest.h>

#include "dairlib/lcmt_controller_switch.hpp"
#include "examples/Cassie/cassie_utils.h"

#include "drake/multibody/plant/multibody_plant.h"

namespace dairlib {
namespace systems {

using Eigen::VectorXd;

class InputSupervisorTest : public ::testing::Test {
 protected:
  InputSupervisorTest()
      : plant_(drake::multibody::MultibodyPlant<double>(0.0)) {
    addCassieMultibody(&plant_, nullptr, true /*floating base*/,
                       "examples/Cassie/urdf/cassie_v2.urdf",
                       true /*spring model*/, false /*loop closure*/);
    plant_.Finalize();
    VectorXd input_limit = 20.0 * VectorXd::Ones(10);
    supervisor_ = std::make_unique<InputSupervisor>(
        plant_, "DEFAULT_CONTROL_CHANNEL", 10.0, 0.01, input_limit, min_consecutive_failures);
    context_ = supervisor_->CreateDefaultContext();
    status_output_ = std::make_unique<dairlib::lcmt_input_supervisor_status>();
    cassie_out_ = std::make_unique<dairlib::lcmt_cassie_out>();
    motor_output_ =
        std::make_unique<TimestampedVector<double>>(plant_.num_actuators());
    command_input_ =
        std::make_unique<TimestampedVector<double>>(plant_.num_actuators());
    state_input_ = std::make_unique<OutputVector<double>>(
        plant_.num_positions(), plant_.num_velocities(),
        plant_.num_actuators());

    state_input_port_ = supervisor_->get_input_port_state().get_index();
  }

  int state_input_port_;
  drake::multibody::MultibodyPlant<double> plant_;
  const int min_consecutive_failures = 5;
  std::unique_ptr<InputSupervisor> supervisor_;
  std::unique_ptr<dairlib::lcmt_input_supervisor_status> status_output_;
  std::unique_ptr<dairlib::lcmt_cassie_out> cassie_out_;
  std::unique_ptr<TimestampedVector<double>> motor_output_;
  std::unique_ptr<TimestampedVector<double>> command_input_;
  std::unique_ptr<OutputVector<double>> state_input_;
  std::unique_ptr<drake::systems::Context<double>> context_;
};

TEST_F(InputSupervisorTest, BlendEffortsTest) {
  VectorXd prev_input = VectorXd::Zero(plant_.num_actuators());
  VectorXd desired_input = 10 * VectorXd::Ones(plant_.num_actuators());
  double blend_start_time = 0.5;
  double timestamp = 1.0;
  double blend_duration = 1.0;
  std::unique_ptr<drake::Value<lcmt_controller_switch>> switch_msg =
      std::make_unique<drake::Value<lcmt_controller_switch>>();
  std::unique_ptr<drake::Value<lcmt_controller_failure>> controller_failure =
      std::make_unique<drake::Value<lcmt_controller_failure>>();
  cassie_out_->pelvis.radio.channel[15] = 0;
  switch_msg->get_mutable_value().blend_duration = blend_duration;
  switch_msg->get_mutable_value().utime = blend_start_time * 1e6;
  command_input_->get_mutable_value() = desired_input;
  command_input_->set_timestamp(timestamp);
  supervisor_->get_input_port_state().FixValue(context_.get(), *state_input_);
  supervisor_->get_input_port_cassie().FixValue(context_.get(), *cassie_out_);
  supervisor_->get_input_port_safety_controller().FixValue(context_.get(),
                                                           *command_input_);
  supervisor_->get_input_port_controller_switch().FixValue(
      context_.get(), (drake::AbstractValue&)*switch_msg);
  supervisor_->get_input_port_controller_error().FixValue(
      context_.get(), (drake::AbstractValue&)*controller_failure);
  supervisor_->get_input_port_command().FixValue(context_.get(),
                                                 *command_input_);
  supervisor_->UpdateErrorFlag(*context_,
                               &context_->get_mutable_discrete_state());
  supervisor_->SetMotorTorques(*context_, motor_output_.get());

  VectorXd output_from_supervisor = motor_output_->get_value();
  double alpha = (timestamp - blend_start_time) / blend_duration;

  EXPECT_EQ(output_from_supervisor, alpha * desired_input);
}

}  // namespace systems
}  // namespace dairlib

int main(int argc, char** argv) {
  ::testing::InitGoogleTest(&argc, argv);
  return RUN_ALL_TESTS();
}

ext: cc

max_stars_repo_name: HaoxiangYou/dairlib

max_issues_repo_name: HaoxiangYou/dairlib

max_forks_repo_name: HaoxiangYou/dairlib


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

#include <iostream>
#include <string>

#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/imgproc/imgproc.hpp>

#include <boost/compute/system.hpp>
#include <boost/compute/interop/opencv/core.hpp>
#include <boost/compute/interop/opencv/highgui.hpp>
#include <boost/compute/utility/source.hpp>

#include <boost/program_options.hpp>

namespace compute = boost::compute;
namespace po = boost::program_options;

// Create naive optical flow program
const char source[] = BOOST_COMPUTE_STRINGIZE_SOURCE (
    const sampler_t sampler = CLK_ADDRESS_CLAMP_TO_EDGE;

    __kernel void optical_flow (
                                read_only
                                image2d_t current_image,
                                read_only image2d_t previous_image,
                                write_only image2d_t optical_flow,
                                const float scale,
                                const float offset,
                                const float lambda,
                                const float threshold )
    {
        int2 coords = (int2)(get_global_id(0), get_global_id(1));
        float4 current_pixel    = read_imagef(current_image,
                                              sampler,
                                              coords);
        float4 previous_pixel   = read_imagef(previous_image,
                                              sampler,
                                              coords);
        int2 x1     = (int2)(offset, 0.f);
        int2 y1     = (int2)(0.f, offset);

        //get the difference
        float4 curdif = previous_pixel - current_pixel;

        //calculate the gradient
        //Image 2 first
        float4 gradx = read_imagef(previous_image,
                                   sampler,
                                   coords+x1) -
                       read_imagef(previous_image,
                                   sampler,
                                   coords-x1);
        //Image 1
        gradx += read_imagef(current_image,
                             sampler,
                             coords+x1) -
                 read_imagef(current_image,
                             sampler,
                             coords-x1);
        //Image 2 first
        float4 grady = read_imagef(previous_image,
                                   sampler,
                                   coords+y1) -
                       read_imagef(previous_image,
                                   sampler,
                                   coords-y1);
        //Image 1
        grady += read_imagef(current_image,
                             sampler,
                             coords+y1) -
                 read_imagef(current_image,
                             sampler,
                             coords-y1);

        float4 sqr = (gradx*gradx) + (grady*grady) +
                     (float4)(lambda,lambda, lambda, lambda);
        float4 gradmag = sqrt(sqr);

        ///////////////////////////////////////////////////
        float4 vx = curdif * (gradx / gradmag);
        float vxd = vx.x;//assumes greyscale

        //format output for flowrepos, out(-x,+x,-y,+y)
        float2 xout = (float2)(fmax(vxd,0.f),fabs(fmin(vxd,0.f)));
        xout *= scale;
        ///////////////////////////////////////////////////
        float4 vy = curdif*(grady/gradmag);
        float vyd = vy.x;//assumes greyscale

        //format output for flowrepos, out(-x,+x,-y,+y)
        float2 yout = (float2)(fmax(vyd,0.f),fabs(fmin(vyd,0.f)));
        yout *= scale;
        ///////////////////////////////////////////////////

        float4 out = (float4)(xout, yout);
        float cond = (float)isgreaterequal(length(out), threshold);
        out *= cond;

        write_imagef(optical_flow, coords, out);
    }
);

// This example shows how to read two images or use camera
// with OpenCV, transfer the frames to the GPU,
// and apply a naive optical flow algorithm
// written in OpenCL
int main(int argc, char *argv[])
{
    // setup the command line arguments
    po::options_description desc;
    desc.add_options()
            ("help",  "show available options")
            ("camera", po::value<int>()->default_value(-1),
                                 "if not default camera, specify a camera id")
            ("image1", po::value<std::string>(), "path to image file 1")
            ("image2", po::value<std::string>(), "path to image file 2");

    // Parse the command lines
    po::variables_map vm;
    po::store(po::parse_command_line(argc, argv, desc), vm);
    po::notify(vm);

    //check the command line arguments
    if(vm.count("help"))
    {
        std::cout << desc << std::endl;
        return 0;
    }

    //OpenCV variables
    cv::Mat previous_cv_image;
    cv::Mat current_cv_image;
    cv::VideoCapture cap; //OpenCV camera handle

    //check for image paths
    if(vm.count("image1") && vm.count("image2"))
    {
        // Read image 1 with OpenCV
        previous_cv_image = cv::imread(vm["image1"].as<std::string>(),
                                       CV_LOAD_IMAGE_COLOR);
        if(!previous_cv_image.data){
            std::cerr << "Failed to load image" << std::endl;
            return -1;
        }

        // Read image 2 with opencv
        current_cv_image = cv::imread(vm["image2"].as<std::string>(),
                                      CV_LOAD_IMAGE_COLOR);
        if(!current_cv_image.data){
            std::cerr << "Failed to load image" << std::endl;
            return -1;
        }
    }
    else //by default use camera
    {
        //open camera
        cap.open(vm["camera"].as<int>());
        // read first frame
        cap >> previous_cv_image;
        if(!previous_cv_image.data){
            std::cerr << "failed to capture frame" << std::endl;
            return -1;
        }

        // read second frame
        cap >> current_cv_image;
        if(!current_cv_image.data){
            std::cerr << "failed to capture frame" << std::endl;
            return -1;
        }

    }

    // Get default device and setup context
    compute::device gpu = compute::system::default_device();
    compute::context context(gpu);
    compute::command_queue queue(context, gpu);

    // Convert image to BGRA (OpenCL requires 16-byte aligned data)
    cv::cvtColor(previous_cv_image, previous_cv_image, CV_BGR2BGRA);
    cv::cvtColor(current_cv_image, current_cv_image, CV_BGR2BGRA);

    // Transfer image to gpu
    compute::image2d dev_previous_image =
            compute::opencv_create_image2d_with_mat(
                previous_cv_image, compute::image2d::read_write, queue
                );
    // Transfer image to gpu
    compute::image2d dev_current_image =
            compute::opencv_create_image2d_with_mat(
                current_cv_image, compute::image2d::read_write, queue
                );

    // Create output image
    compute::image2d dev_output_image(
                context,
                dev_previous_image.width(),
                dev_previous_image.height(),
                dev_previous_image.format(),
                compute::image2d::write_only
                );

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

    // create flip kernel and set arguments
    compute::kernel optical_kernel(optical_program, "optical_flow");
    float scale = 10;
    float offset = 1;
    float lambda = 0.0025;
    float threshold = 1.0;

    optical_kernel.set_arg(0, dev_previous_image);
    optical_kernel.set_arg(1, dev_current_image);
    optical_kernel.set_arg(2, dev_output_image);
    optical_kernel.set_arg(3, scale);
    optical_kernel.set_arg(4, offset);
    optical_kernel.set_arg(5, lambda);
    optical_kernel.set_arg(6, threshold);

    // run flip kernel
    size_t origin[2] = { 0, 0 };
    size_t region[2] = { dev_previous_image.width(),
                         dev_previous_image.height() };
    queue.enqueue_nd_range_kernel(optical_kernel, 2, origin, region, 0);

    //check for image paths
    if(vm.count("image1") && vm.count("image2"))
    {
        // show host image
        cv::imshow("Previous Frame", previous_cv_image);
        cv::imshow("Current Frame", current_cv_image);

        // show gpu image
        compute::opencv_imshow("filtered image", dev_output_image, queue);

        // wait and return
        cv::waitKey(0);
    }
    else
    {
        char key = '\0';
        while(key != 27) //check for escape key
        {
            cap >> current_cv_image;

            // Convert image to BGRA (OpenCL requires 16-byte aligned data)
            cv::cvtColor(current_cv_image, current_cv_image, CV_BGR2BGRA);

            // Update the device image memory with current frame data
            compute::opencv_copy_mat_to_image(previous_cv_image,
                                              dev_previous_image,
                                              queue);
            compute::opencv_copy_mat_to_image(current_cv_image,
                                              dev_current_image,
                                              queue);

            // Run the kernel on the device
            queue.enqueue_nd_range_kernel(optical_kernel, 2, origin, region, 0);

            // Show host image
            cv::imshow("Previous Frame", previous_cv_image);
            cv::imshow("Current Frame", current_cv_image);

            // Show GPU image
            compute::opencv_imshow("filtered image", dev_output_image, queue);

            // Copy current frame container to previous frame container
            current_cv_image.copyTo(previous_cv_image);

            // wait
            key = cv::waitKey(10);
        }

    }
    return 0;
}


text:
#include <replay/planar_direction.hpp>
#include <boost/math/constants/constants.hpp>
#include <replay/matrix2.hpp>
#include <replay/vector_math.hpp>

using namespace replay;

planar_direction planar_direction::move(planar_direction from, planar_direction to, float max_angle_delta)
{
    auto const relative_move = (to - from).normalized();

    if (std::abs(relative_move.angle()) < max_angle_delta)
        return to;

    return planar_direction{ from.angle() + math::clamp_absolute(relative_move.angle(), max_angle_delta) };
}

planar_direction planar_direction::normalized() const
{
    auto angle = m_angle;
    constexpr auto pi = boost::math::constants::pi<float>();
    constexpr auto two_pi = boost::math::constants::two_pi<float>();

    while (angle > pi)
        angle -= two_pi;
    while (angle <= -pi)
        angle += two_pi;
    return planar_direction(angle);
}

planar_direction planar_direction::average(planar_direction from, planar_direction to)
{
    return planar_direction::from_vector(from.as_vector() + to.as_vector());
}

max_stars_repo_name: ltjax/replay

max_issues_repo_name: ltjax/replay

max_forks_repo_name: ltjax/replay


text:
#ifndef AYLA_GL_TEXT_RENDERER_HPP
#define AYLA_GL_TEXT_RENDERER_HPP

#include "ayla_gl/config.hpp"

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

namespace ayla_gl {

/**
 * It knows how to draw 2D text on the screen.
 */
class AYLA_GL_API TextRenderer final : boost::noncopyable {
public:
	TextRenderer(const std::string& fontTextureFile);
	~TextRenderer();

public:
	void drawText2D(const std::string& text, float x, float y, float size) const;

private:
	GLuint _vao = GLuint(0); // vertex array object
	GLuint _texture = GLuint(0);
	GLuint _vertexBuffer = GLuint(0);
	GLuint _uvBuffer = GLuint(0);
	GLuint _program = GLuint(0);
	GLuint _uniform = GLuint(0);
};

}

#endif // AYLA_GL_TEXT_RENDERER_HPP

max_stars_repo_name: oprogramadorreal/vize

max_issues_repo_name: oprogramadorreal/vize

max_forks_repo_name: oprogramadorreal/vize


text:
// Copyright (c) 2019 The Ohmcoin Developers
// Copyright (c) 2018 The Curium developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.

#if defined(HAVE_CONFIG_H)
#include "config/ohmcoin-config.h"
#endif

#include "configurekarmanodepage.h"
#include "ui_configurekarmanodepage.h"

#include "activekarmanode.h"
#include "bitcoingui.h"
#include "csvmodelwriter.h"
#include "editaddressdialog.h"
#include "guiutil.h"
#include "karmanode-budget.h"
#include "karmanode-payments.h"
#include "karmanodeconfig.h"
#include "karmanodeman.h"
#include "karmanodelist.h"
#include "wallet/wallet.h"

#include <univalue.h>
#include <QIcon>
#include <QMenu>
#include <QString>
#include <QMessageBox>
#include <QSortFilterProxyModel>
#include <boost/tokenizer.hpp>
#include <fstream>
#include <iostream>
#include <string>

ConfigureKarmanodePage::ConfigureKarmanodePage(Mode mode, QWidget* parent) : QDialog(parent),
                                                                   ui(new Ui::ConfigureKarmanodePage),
                                                                   mapper(0),
                                                                   mode(mode)
{
    ui->setupUi(this);

	GUIUtil::setupAliasWidget(ui->aliasEdit, this);
	GUIUtil::setupIPWidget(ui->vpsIpEdit, this);
	GUIUtil::setupPrivKeyWidget(ui->privKeyEdit, this);
	GUIUtil::setupTXIDWidget(ui->outputEdit, this);
	GUIUtil::setupTXIDIndexWidget(ui->outputIdEdit, this);

    switch (mode) {
    case NewConfigureKarmanode:
        setWindowTitle(tr("New Karmanode Alias"));
        break;
    case EditConfigureKarmanode:
        setWindowTitle(tr("Edit Karmanode Alias"));
        break;
    }

}

ConfigureKarmanodePage::~ConfigureKarmanodePage()
{
    delete ui;
}

void ConfigureKarmanodePage::loadAlias(QString strAlias)
{
   ui->aliasEdit->setText(strAlias);
}

void ConfigureKarmanodePage::counter(int counter)
{
   setCounters(counter);
}

void ConfigureKarmanodePage::MNAliasCache(QString MnAliasCache)
{
   setMnAliasCache(MnAliasCache);
}

void ConfigureKarmanodePage::loadIP(QString strIP)
{
   ui->vpsIpEdit->setText(strIP);
}

void ConfigureKarmanodePage::loadPrivKey(QString strPrivKey)
{
   ui->privKeyEdit->setText(strPrivKey);
}

void ConfigureKarmanodePage::loadTxHash(QString strTxHash)
{
   ui->outputEdit->setText(strTxHash);
}

void ConfigureKarmanodePage::loadOutputIndex(QString strOutputIndex)
{
   ui->outputIdEdit->setText(strOutputIndex);
}

void ConfigureKarmanodePage::saveCurrentRow()
{

    switch (mode) {
    case NewConfigureKarmanode:
		if(ui->aliasEdit->text().toStdString().empty() || ui->vpsIpEdit->text().toStdString().empty() || ui->privKeyEdit->text().toStdString().empty() || ui->outputEdit->text().toStdString().empty() || ui->outputIdEdit->text().toStdString().empty()) {
			break;
		}
		karmanodeConfig.add(ui->aliasEdit->text().toStdString(), ui->vpsIpEdit->text().toStdString(), ui->privKeyEdit->text().toStdString(), ui->outputEdit->text().toStdString(), ui->outputIdEdit->text().toStdString());
		karmanodeConfig.writeToKarmanodeConf();
        break;
    case EditConfigureKarmanode:
		if(ui->aliasEdit->text().toStdString().empty() || ui->vpsIpEdit->text().toStdString().empty() || ui->privKeyEdit->text().toStdString().empty() || ui->outputEdit->text().toStdString().empty() || ui->outputIdEdit->text().toStdString().empty()) {
			break;
		}

	    QString MnAlias = getMnAliasCache();
		ConfigureKarmanodePage::updateAlias(ui->aliasEdit->text().toStdString(), ui->vpsIpEdit->text().toStdString(), ui->privKeyEdit->text().toStdString(), ui->outputEdit->text().toStdString(), ui->outputIdEdit->text().toStdString(), MnAlias.toStdString());
		break;
    }
}

void ConfigureKarmanodePage::accept()
{
	saveCurrentRow();
	emit accepted();
    QDialog::accept();
}

void ConfigureKarmanodePage::updateAlias(std::string Alias, std::string IP, std::string PrivKey, std::string TxHash, std::string OutputIndex, std::string mnAlias)
{
	for (CKarmanodeConfig::CKarmanodeEntry mne : karmanodeConfig.getEntries()) {
		if(mnAlias == mne.getAlias()) {
			int count = 0;
			count = getCounters();
			vector<COutPoint> confLockedCoins;
			uint256 mnTxHash;
			mnTxHash.SetHex(mne.getTxHash());
			int nIndex;
			if(!mne.castOutputIndex(nIndex))
				continue;
			COutPoint outpoint = COutPoint(mnTxHash, nIndex);
			confLockedCoins.push_back(outpoint);
			pwalletMain->UnlockCoin(outpoint);

			karmanodeConfig.deleteAlias(count);
			karmanodeConfig.add(Alias, IP, PrivKey, TxHash, OutputIndex);
			// write to karmanode.conf
			karmanodeConfig.writeToKarmanodeConf();
			return;
		}
	}

}

void ConfigureKarmanodePage::on_AutoFillPrivKey_clicked()
{
    CKey secret;
    secret.MakeNewKey(false);

	ui->privKeyEdit->setText(QString::fromStdString(CBitcoinSecret(secret).ToString()));
}

void ConfigureKarmanodePage::on_AutoFillOutputs_clicked()
{
    // Find possible candidates
    vector<COutput> possibleCoins = activeKarmanode.SelectCoinsKarmanode();
        int test = 0;
    for (COutput& out : possibleCoins) {
        std::string TXHash = out.tx->GetHash().ToString();
        std::string OutputID = std::to_string(out.i);
                for (CKarmanodeConfig::CKarmanodeEntry mne : karmanodeConfig.getEntries()) {
                        if(OutputID == mne.getOutputIndex() && TXHash == mne.getTxHash()) {
                                test = 1;

                        }
                }

                if(test == 0) {
                        ui->outputEdit->setText(QString::fromStdString(out.tx->GetHash().ToString()));
                        ui->outputIdEdit->setText(QString::fromStdString(std::to_string(out.i)));

                        break;
                }
                test = 0;
    }
}

max_stars_repo_name: MichaelHDesigns/ohmcoin

max_issues_repo_name: MichaelHDesigns/ohmcoin

max_forks_repo_name: MichaelHDesigns/ohmcoin


text:
/*
 * Copyright (c) 2020 Andrew Price
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * 1. Redistributions of source code must retain the above copyright notice,
 *    this list of conditions and the following disclaimer.
 * 2. 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.
 * 3. Neither the name of the copyright holder 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.
 */

#include "mps_voxels/video_graph.h"
#include "mps_voxels/util/assert.h"

#include <boost/graph/dijkstra_shortest_paths.hpp>
#include <boost/property_map/transform_value_property_map.hpp>

#include <deque>

struct found_goal {}; // exception for termination

// visitor that terminates when we find the goal
template <class Vertex>
class goal_visitor : public boost::default_dijkstra_visitor
{
public:
	explicit
	goal_visitor(Vertex goal) : m_goal(goal) {}

	template <class Graph>
	void examine_vertex(Vertex u, Graph&)
	{
		if(u == m_goal)
			throw found_goal();
	}
private:
	Vertex m_goal;
};

template <SEGMENT_TYPE T>
std::deque<SegmentIndex<T>> getObjectPath(const VideoSegmentationGraph<T>& G, const SegmentLookup<T>& segmentToNode, const SegmentIndex<T>& from, const SegmentIndex<T>& to)
{
	using Vertex = typename VideoSegmentationGraph<T>::vertex_descriptor;
	// Setup storage for intermediate values in A*
	std::vector<Vertex> predecessor(boost::num_vertices(G));
	std::vector<double> distance(boost::num_vertices(G));

	// Tell boost about the distance function and temporary storage
	auto wmap = boost::make_transform_value_property_map([](const EdgeProperties& e) { return e.distance(); }, get(boost::edge_bundle, G));
	auto pmap = boost::make_iterator_property_map(predecessor.begin(), boost::get(boost::vertex_index, G));
	auto dmap = boost::make_iterator_property_map(distance.begin(), boost::get(boost::vertex_index, G));

	Vertex start = segmentToNode.at(from);
	Vertex goal = segmentToNode.at(to);

	MPS_ASSERT(start < boost::num_vertices(G));
	MPS_ASSERT(goal < boost::num_vertices(G));

//	try
//	{
//		boost::astar_search(G, start, distance_heuristic<VideoSegmentationGraph, double>(G, goal),
//		    boost::weight_map(wmap).predecessor_map(pmap).distance_map(dmap).
//		    visitor(astar_goal_visitor<VideoSegmentationGraph::vertex_descriptor>(segmentToNode.at(to))));
//	}
//	catch (found_goal fg)
//	{
//		std::deque<SegmentIndex> res;
//		for(VideoSegmentationGraph::vertex_descriptor v = goal;; v = predecessor[v])
//		{
//			const NodeProperties& np = G[v];
//			res.push_front({np.t, np.leafID});
//			if(predecessor[v] == v)
//				break;
//		}
//		return res;
//	}

	try
	{
		boost::dijkstra_shortest_paths(G, start,
		                               boost::weight_map(wmap).predecessor_map(pmap).distance_map(dmap).
			                               visitor(goal_visitor<Vertex>(goal)));
	}
	catch (found_goal fg)
	{
		std::deque<SegmentIndex<T>> res;
		for(Vertex v = goal;; v = predecessor[v])
		{
			const NodeProperties<T>& np = G[v];
			res.push_front({np.t, np.leafID});
			if(predecessor[v] == v)
				break;
		}
		return res;
	}

//	throw std::logic_error("Failed to find path.");
	return {};
}

template
std::deque<SegmentIndex<SEGMENT_TYPE::UCM>> getObjectPath(const VideoSegmentationGraph<SEGMENT_TYPE::UCM>& G, const SegmentLookup<SEGMENT_TYPE::UCM>& segmentToNode, const SegmentIndex<SEGMENT_TYPE::UCM>& from, const SegmentIndex<SEGMENT_TYPE::UCM>& to);

template
std::deque<SegmentIndex<SEGMENT_TYPE::BODY>> getObjectPath(const VideoSegmentationGraph<SEGMENT_TYPE::BODY>& G, const SegmentLookup<SEGMENT_TYPE::BODY>& segmentToNode, const SegmentIndex<SEGMENT_TYPE::BODY>& from, const SegmentIndex<SEGMENT_TYPE::BODY>& to);