text:
#include <vban/boost/asio/ip/address_v6.hpp>
#include <vban/lib/config.hpp>
#include <vban/lib/jsonconfig.hpp>
#include <vban/lib/rpcconfig.hpp>
#include <vban/lib/tomlconfig.hpp>

#include <boost/dll/runtime_symbol_info.hpp>

vban::error vban::rpc_secure_config::serialize_json (vban::jsonconfig & json) const
{
	json.put ("enable", enable);
	json.put ("verbose_logging", verbose_logging);
	json.put ("server_key_passphrase", server_key_passphrase);
	json.put ("server_cert_path", server_cert_path);
	json.put ("server_key_path", server_key_path);
	json.put ("server_dh_path", server_dh_path);
	json.put ("client_certs_path", client_certs_path);
	return json.get_error ();
}

vban::error vban::rpc_secure_config::deserialize_json (vban::jsonconfig & json)
{
	json.get_required<bool> ("enable", enable);
	json.get_required<bool> ("verbose_logging", verbose_logging);
	json.get_required<std::string> ("server_key_passphrase", server_key_passphrase);
	json.get_required<std::string> ("server_cert_path", server_cert_path);
	json.get_required<std::string> ("server_key_path", server_key_path);
	json.get_required<std::string> ("server_dh_path", server_dh_path);
	json.get_required<std::string> ("client_certs_path", client_certs_path);
	return json.get_error ();
}

vban::error vban::rpc_secure_config::serialize_toml (vban::tomlconfig & toml) const
{
	toml.put ("enable", enable, "Enable or disable TLS support.\ntype:bool");
	toml.put ("verbose_logging", verbose_logging, "Enable or disable verbose logging.\ntype:bool");
	toml.put ("server_key_passphrase", server_key_passphrase, "Server key passphrase.\ntype:string");
	toml.put ("server_cert_path", server_cert_path, "Directory containing certificates.\ntype:string,path");
	toml.put ("server_key_path", server_key_path, "Path to server key PEM file.\ntype:string,path");
	toml.put ("server_dh_path", server_dh_path, "Path to Diffie-Hellman params file.\ntype:string,path");
	toml.put ("client_certs_path", client_certs_path, "Directory containing client certificates.\ntype:string");
	return toml.get_error ();
}

vban::error vban::rpc_secure_config::deserialize_toml (vban::tomlconfig & toml)
{
	toml.get<bool> ("enable", enable);
	toml.get<bool> ("verbose_logging", verbose_logging);
	toml.get<std::string> ("server_key_passphrase", server_key_passphrase);
	toml.get<std::string> ("server_cert_path", server_cert_path);
	toml.get<std::string> ("server_key_path", server_key_path);
	toml.get<std::string> ("server_dh_path", server_dh_path);
	toml.get<std::string> ("client_certs_path", client_certs_path);
	return toml.get_error ();
}

vban::rpc_config::rpc_config () :
	address (boost::asio::ip::address_v6::loopback ().to_string ())
{
}

vban::rpc_config::rpc_config (uint16_t port_a, bool enable_control_a) :
	address (boost::asio::ip::address_v6::loopback ().to_string ()),
	port (port_a),
	enable_control (enable_control_a)
{
}

vban::error vban::rpc_config::serialize_json (vban::jsonconfig & json) const
{
	json.put ("version", json_version ());
	json.put ("address", address);
	json.put ("port", port);
	json.put ("enable_control", enable_control);
	json.put ("max_json_depth", max_json_depth);
	json.put ("max_request_size", max_request_size);

	vban::jsonconfig rpc_process_l;
	rpc_process_l.put ("version", rpc_process.json_version ());
	rpc_process_l.put ("io_threads", rpc_process.io_threads);
	rpc_process_l.put ("ipc_address", rpc_process.ipc_address);
	rpc_process_l.put ("ipc_port", rpc_process.ipc_port);
	rpc_process_l.put ("num_ipc_connections", rpc_process.num_ipc_connections);
	json.put_child ("process", rpc_process_l);
	return json.get_error ();
}

vban::error vban::rpc_config::deserialize_json (bool & upgraded_a, vban::jsonconfig & json)
{
	if (!json.empty ())
	{
		auto rpc_secure_l (json.get_optional_child ("secure"));
		if (rpc_secure_l)
		{
			secure.deserialize_json (*rpc_secure_l);
		}

		boost::asio::ip::address_v6 address_l;
		json.get_required<boost::asio::ip::address_v6> ("address", address_l, boost::asio::ip::address_v6::loopback ());
		address = address_l.to_string ();
		json.get_optional<uint16_t> ("port", port);
		json.get_optional<bool> ("enable_control", enable_control);
		json.get_optional<uint8_t> ("max_json_depth", max_json_depth);
		json.get_optional<uint64_t> ("max_request_size", max_request_size);

		auto rpc_process_l (json.get_optional_child ("process"));
		if (rpc_process_l)
		{
			rpc_process_l->get_optional<unsigned> ("io_threads", rpc_process.io_threads);
			rpc_process_l->get_optional<uint16_t> ("ipc_port", rpc_process.ipc_port);
			boost::asio::ip::address_v6 ipc_address_l;
			rpc_process_l->get_optional<boost::asio::ip::address_v6> ("ipc_address", ipc_address_l);
			rpc_process.ipc_address = ipc_address_l.to_string ();
			rpc_process_l->get_optional<unsigned> ("num_ipc_connections", rpc_process.num_ipc_connections);
		}
	}
	else
	{
		upgraded_a = true;
		serialize_json (json);
	}

	return json.get_error ();
}

vban::error vban::rpc_config::serialize_toml (vban::tomlconfig & toml) const
{
	toml.put ("address", address, "Bind address for the RPC server.\ntype:string,ip");
	toml.put ("port", port, "Listening port for the RPC server.\ntype:uint16");
	toml.put ("enable_control", enable_control, "Enable or disable control-level requests.\nWARNING: Enabling this gives anyone with RPC access the ability to stop the node and access wallet funds.\ntype:bool");
	toml.put ("max_json_depth", max_json_depth, "Maximum number of levels in JSON requests.\ntype:uint8");
	toml.put ("max_request_size", max_request_size, "Maximum number of bytes allowed in request bodies.\ntype:uint64");

	vban::tomlconfig rpc_process_l;
	rpc_process_l.put ("io_threads", rpc_process.io_threads, "Number of threads used to serve IO.\ntype:uint32");
	rpc_process_l.put ("ipc_address", rpc_process.ipc_address, "Address of IPC server.\ntype:string,ip");
	rpc_process_l.put ("ipc_port", rpc_process.ipc_port, "Listening port of IPC server.\ntype:uint16");
	rpc_process_l.put ("num_ipc_connections", rpc_process.num_ipc_connections, "Number of IPC connections to establish.\ntype:uint32");
	toml.put_child ("process", rpc_process_l);

	vban::tomlconfig rpc_logging_l;
	rpc_logging_l.put ("log_rpc", rpc_logging.log_rpc, "Whether to log RPC calls.\ntype:bool");
	toml.put_child ("logging", rpc_logging_l);
	return toml.get_error ();
}

vban::error vban::rpc_config::deserialize_toml (vban::tomlconfig & toml)
{
	if (!toml.empty ())
	{
		auto rpc_secure_l (toml.get_optional_child ("secure"));
		if (rpc_secure_l)
		{
			secure.deserialize_toml (*rpc_secure_l);
		}

		boost::asio::ip::address_v6 address_l;
		toml.get_optional<boost::asio::ip::address_v6> ("address", address_l, boost::asio::ip::address_v6::loopback ());
		address = address_l.to_string ();
		toml.get_optional<uint16_t> ("port", port);
		toml.get_optional<bool> ("enable_control", enable_control);
		toml.get_optional<uint8_t> ("max_json_depth", max_json_depth);
		toml.get_optional<uint64_t> ("max_request_size", max_request_size);

		auto rpc_logging_l (toml.get_optional_child ("logging"));
		if (rpc_logging_l)
		{
			rpc_logging_l->get_optional<bool> ("log_rpc", rpc_logging.log_rpc);
		}

		auto rpc_process_l (toml.get_optional_child ("process"));
		if (rpc_process_l)
		{
			rpc_process_l->get_optional<unsigned> ("io_threads", rpc_process.io_threads);
			rpc_process_l->get_optional<uint16_t> ("ipc_port", rpc_process.ipc_port);
			boost::asio::ip::address_v6 ipc_address_l;
			rpc_process_l->get_optional<boost::asio::ip::address_v6> ("ipc_address", ipc_address_l, boost::asio::ip::address_v6::loopback ());
			rpc_process.ipc_address = address_l.to_string ();
			rpc_process_l->get_optional<unsigned> ("num_ipc_connections", rpc_process.num_ipc_connections);
		}
	}

	return toml.get_error ();
}

vban::rpc_process_config::rpc_process_config () :
	ipc_address (boost::asio::ip::address_v6::loopback ().to_string ())
{
}

namespace vban
{
vban::error read_rpc_config_toml (boost::filesystem::path const & data_path_a, vban::rpc_config & config_a, std::vector<std::string> const & config_overrides)
{
	vban::error error;
	auto json_config_path = vban::get_rpc_config_path (data_path_a);
	auto toml_config_path = vban::get_rpc_toml_config_path (data_path_a);
	if (boost::filesystem::exists (json_config_path))
	{
		if (boost::filesystem::exists (toml_config_path))
		{
			error = "Both json and toml rpc configuration files exists. "
					"Either remove the config.json file and restart, or remove "
					"the config-rpc.toml file to start migration on next launch.";
		}
		else
		{
			// Migrate
			vban::rpc_config config_json_l;
			error = read_and_update_rpc_config (data_path_a, config_json_l);

			if (!error)
			{
				vban::tomlconfig toml_l;
				config_json_l.serialize_toml (toml_l);

				// Only write out non-default values
				vban::rpc_config config_defaults_l;
				vban::tomlconfig toml_defaults_l;
				config_defaults_l.serialize_toml (toml_defaults_l);

				toml_l.erase_default_values (toml_defaults_l);
				if (!toml_l.empty ())
				{
					toml_l.write (toml_config_path);
					boost::system::error_code error_chmod;
					vban::set_secure_perm_file (toml_config_path, error_chmod);
				}

				auto backup_path = data_path_a / "rpc_config_backup_toml_migration.json";
				boost::filesystem::rename (json_config_path, backup_path);
			}
		}
	}

	// Parse and deserialize
	vban::tomlconfig toml;

	std::stringstream config_overrides_stream;
	for (auto const & entry : config_overrides)
	{
		config_overrides_stream << entry << std::endl;
	}
	config_overrides_stream << std::endl;

	// Make sure we don't create an empty toml file if it doesn't exist. Running without a toml file is the default.
	if (!error)
	{
		if (boost::filesystem::exists (toml_config_path))
		{
			error = toml.read (config_overrides_stream, toml_config_path);
		}
		else
		{
			error = toml.read (config_overrides_stream);
		}
	}

	if (!error)
	{
		error = config_a.deserialize_toml (toml);
	}

	return error;
}

vban::error read_and_update_rpc_config (boost::filesystem::path const & data_path, vban::rpc_config & config_a)
{
	boost::system::error_code error_chmod;
	vban::jsonconfig json;
	auto config_path = vban::get_rpc_config_path (data_path);
	auto error (json.read_and_update (config_a, config_path));
	vban::set_secure_perm_file (config_path, error_chmod);
	return error;
}

std::string get_default_rpc_filepath ()
{
	boost::system::error_code err;
	auto running_executable_filepath = boost::dll::program_location (err);

	// Construct the vban_rpc executable file path based on where the currently running executable is found.
	auto rpc_filepath = running_executable_filepath.parent_path () / "vban_rpc";
	if (running_executable_filepath.has_extension ())
	{
		rpc_filepath.replace_extension (running_executable_filepath.extension ());
	}

	return rpc_filepath.string ();
}
}

max_stars_repo_name: EduardAl/vban-node

max_issues_repo_name: EduardAl/vban-node

max_forks_repo_name: EduardAl/vban-node


text:
/*
 * The MIT License (MIT)
 *
 * Copyright (c) 2015 Microsoft Corporation
 *
 * -=- Robust Distributed System Nucleus (rDSN) -=-
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */

/*
 * Description:
 *     meta state service implemented with zookeeper
 *
 * Revision history:
 *     2015-12-04, @shengofsun (sunweijie@xiaomi.com)
 */
#include <dsn/tool-api/async_calls.h>
#include <dsn/dist/replication/replication.codes.h>

#include <boost/algorithm/string.hpp>
#include <boost/lexical_cast.hpp>

#include "meta_state_service_zookeeper.h"
#include "zookeeper_session_mgr.h"
#include "zookeeper_session.h"
#include "zookeeper_error.h"

namespace dsn {
namespace dist {

class zoo_transaction : public meta_state_service::transaction_entries
{
public:
    zoo_transaction(unsigned int capacity);
    virtual ~zoo_transaction() override {}
    virtual error_code create_node(const std::string &name, const blob &value = blob()) override;
    virtual error_code set_data(const std::string &name, const blob &value = blob()) override;
    virtual error_code delete_node(const std::string &name) override;
    virtual error_code get_result(unsigned int entry_index) override;

    std::shared_ptr<zookeeper_session::zoo_atomic_packet> packet() { return _pkt; }
private:
    std::shared_ptr<zookeeper_session::zoo_atomic_packet> _pkt;
};

zoo_transaction::zoo_transaction(unsigned int capacity)
{
    _pkt.reset(new zookeeper_session::zoo_atomic_packet(capacity));
}

error_code zoo_transaction::create_node(const std::string &path, const blob &value)
{
    if (_pkt->_count >= _pkt->_capacity)
        return ERR_ARRAY_INDEX_OUT_OF_RANGE;

    unsigned int &offset = _pkt->_count;
    std::string &p = (_pkt->_paths)[offset];
    blob &b = (_pkt->_datas)[offset];

    p = path;
    b = value;

    zoo_op_t &op = _pkt->_ops[offset];
    op.type = ZOO_CREATE_OP;
    op.create_op.path = p.c_str();
    op.create_op.flags = 0;
    op.create_op.acl = &ZOO_OPEN_ACL_UNSAFE;
    op.create_op.data = b.data();
    op.create_op.datalen = b.length();

    /* output path is either same with path(for non-sequencial node)
     * or 10 bytes more than the path(for sequencial node) */
    int buffer_length = path.size() + 20;

    op.create_op.buf = _pkt->alloc_buffer(buffer_length);
    op.create_op.buflen = buffer_length;

    ++offset;
    return ERR_OK;
}

error_code zoo_transaction::delete_node(const std::string &path)
{
    if (_pkt->_count >= _pkt->_capacity)
        return ERR_ARRAY_INDEX_OUT_OF_RANGE;
    unsigned int &offset = _pkt->_count;
    std::string &p = (_pkt->_paths)[offset];

    p = path;

    zoo_op_t &op = _pkt->_ops[offset];
    op.type = ZOO_DELETE_OP;
    op.delete_op.path = p.c_str();
    op.delete_op.version = -1;

    ++offset;
    return ERR_OK;
}

error_code zoo_transaction::set_data(const std::string &name, const blob &value)
{
    if (_pkt->_count >= _pkt->_capacity)
        return ERR_ARRAY_INDEX_OUT_OF_RANGE;
    unsigned int &offset = _pkt->_count;
    std::string &p = (_pkt->_paths)[offset];
    blob &b = (_pkt->_datas[offset]);
    p = name;
    b = value;

    zoo_op_t &op = _pkt->_ops[offset];
    op.type = ZOO_SETDATA_OP;
    op.set_op.path = p.c_str();
    op.set_op.data = value.data();
    op.set_op.datalen = value.length();
    op.set_op.version = -1;
    op.set_op.stat = (struct Stat *)_pkt->alloc_buffer(sizeof(struct Stat));

    ++offset;
    return ERR_OK;
}

error_code zoo_transaction::get_result(unsigned int entry_index)
{
    if (entry_index >= _pkt->_count)
        return ERR_ARRAY_INDEX_OUT_OF_RANGE;
    return from_zerror(_pkt->_results[entry_index].err);
}

meta_state_service_zookeeper::meta_state_service_zookeeper() : ref_counter() { _first_call = true; }

meta_state_service_zookeeper::~meta_state_service_zookeeper()
{
    _tracker.wait_outstanding_tasks();
    if (_session) {
        _session->detach(this);
        _session = nullptr;
    }
}

error_code meta_state_service_zookeeper::initialize(const std::vector<std::string> &)
{
    _session =
        zookeeper_session_mgr::instance().get_session(service_app::current_service_app_info());
    _zoo_state = _session->attach(this,
                                  std::bind(&meta_state_service_zookeeper::on_zoo_session_evt,
                                            ref_this(this),
                                            std::placeholders::_1));
    if (_zoo_state != ZOO_CONNECTED_STATE) {
        _notifier.wait_for(zookeeper_session_mgr::instance().timeout());
        if (_zoo_state != ZOO_CONNECTED_STATE)
            return ERR_TIMEOUT;
    }

    ddebug("init meta_state_service_zookeeper succeed");

    // Notice: this reference is released in finalize
    add_ref();
    return ERR_OK;
}

error_code meta_state_service_zookeeper::finalize()
{
    release_ref();
    return ERR_OK;
}

std::shared_ptr<meta_state_service::transaction_entries>
meta_state_service_zookeeper::new_transaction_entries(unsigned int capacity)
{
    std::shared_ptr<zoo_transaction> t(new zoo_transaction(capacity));
    return t;
}

#define VISIT_INIT(tsk, op_type, node)                                                             \
    zookeeper_session::zoo_opcontext *op = zookeeper_session::create_context();                    \
    zookeeper_session::zoo_input *input = &op->_input;                                             \
    op->_callback_function = std::bind(&meta_state_service_zookeeper::visit_zookeeper_internal,    \
                                       ref_this(this),                                             \
                                       tsk,                                                        \
                                       std::placeholders::_1);                                     \
    op->_optype = op_type;                                                                         \
    input->_path = node;

task_ptr meta_state_service_zookeeper::create_node(const std::string &node,
                                                   task_code cb_code,
                                                   const err_callback &cb_create,
                                                   const blob &value,
                                                   dsn::task_tracker *tracker)
{
    error_code_future_ptr tsk(new error_code_future(cb_code, cb_create, 0));
    tsk->set_tracker(tracker);
    dinfo("call create, node(%s)", node.c_str());
    VISIT_INIT(tsk, zookeeper_session::ZOO_OPERATION::ZOO_CREATE, node);
    input->_value = value;
    input->_flags = 0;

    _session->visit(op);
    return tsk;
}

task_ptr meta_state_service_zookeeper::submit_transaction(
    const std::shared_ptr<transaction_entries> &entries,
    task_code cb_code,
    const err_callback &cb_transaction,
    dsn::task_tracker *tracker)
{
    error_code_future_ptr tsk(new error_code_future(cb_code, cb_transaction, 0));
    tsk->set_tracker(tracker);
    dinfo("call submit batch");
    zookeeper_session::zoo_opcontext *op = zookeeper_session::create_context();
    zookeeper_session::zoo_input *input = &op->_input;
    op->_callback_function = std::bind(&meta_state_service_zookeeper::visit_zookeeper_internal,
                                       ref_this(this),
                                       tsk,
                                       std::placeholders::_1);
    op->_optype = zookeeper_session::ZOO_OPERATION::ZOO_TRANSACTION;

    zoo_transaction *t = dynamic_cast<zoo_transaction *>(entries.get());
    input->_pkt = t->packet();

    _session->visit(op);
    return tsk;
}

task_ptr meta_state_service_zookeeper::delete_empty_node(const std::string &node,
                                                         task_code cb_code,
                                                         const err_callback &cb_delete,
                                                         dsn::task_tracker *tracker)
{
    error_code_future_ptr tsk(new error_code_future(cb_code, cb_delete, 0));
    tsk->set_tracker(tracker);
    dinfo("call delete, node(%s)", node.c_str());
    VISIT_INIT(tsk, zookeeper_session::ZOO_OPERATION::ZOO_DELETE, node);
    _session->visit(op);
    return tsk;
}

task_ptr meta_state_service_zookeeper::delete_node(const std::string &node,
                                                   bool recursively_delete,
                                                   task_code cb_code,
                                                   const err_callback &cb_delete,
                                                   dsn::task_tracker *tracker)
{
    error_code_future_ptr tsk(new error_code_future(cb_code, cb_delete, 0));
    tsk->set_tracker(tracker);
    err_stringv_callback after_get_children = [node, recursively_delete, cb_code, tsk, this](
        error_code err, const std::vector<std::string> &children) {
        if (ERR_OK != err)
            tsk->enqueue_with(err);
        else if (children.empty())
            delete_empty_node(
                node, cb_code, [tsk](error_code err) { tsk->enqueue_with(err); }, &_tracker);
        else if (!recursively_delete)
            tsk->enqueue_with(ERR_INVALID_PARAMETERS);
        else {
            std::atomic_int *child_count = new std::atomic_int();
            std::atomic_int *error_count = new std::atomic_int();

            child_count->store((int)children.size());
            error_count->store(0);

            for (auto &child : children) {
                delete_node(node + "/" + child,
                            true,
                            cb_code,
                            [=](error_code err) {
                                if (ERR_OK != err)
                                    ++(*error_count);
                                int result = --(*child_count);
                                if (0 == result) {
                                    if (0 == *error_count)
                                        delete_empty_node(
                                            node,
                                            cb_code,
                                            [tsk](error_code err) { tsk->enqueue_with(err); },
                                            &_tracker);
                                    else
                                        tsk->enqueue_with(ERR_FILE_OPERATION_FAILED);
                                    delete child_count;
                                    delete error_count;
                                }
                            },
                            &_tracker);
            }
        }
    };

    get_children(node, cb_code, after_get_children, &_tracker);
    return tsk;
}

task_ptr meta_state_service_zookeeper::get_data(const std::string &node,
                                                task_code cb_code,
                                                const err_value_callback &cb_get_data,
                                                dsn::task_tracker *tracker)
{
    err_value_future_ptr tsk(new err_value_future(cb_code, cb_get_data, 0));
    tsk->set_tracker(tracker);
    dinfo("call get, node(%s)", node.c_str());
    VISIT_INIT(tsk, zookeeper_session::ZOO_OPERATION::ZOO_GET, node);
    input->_is_set_watch = 0;
    _session->visit(op);
    return tsk;
}

task_ptr meta_state_service_zookeeper::set_data(const std::string &node,
                                                const blob &value,
                                                task_code cb_code,
                                                const err_callback &cb_set_data,
                                                dsn::task_tracker *tracker)
{
    error_code_future_ptr tsk(new error_code_future(cb_code, cb_set_data, 0));
    tsk->set_tracker(tracker);
    dinfo("call set, node(%s)", node.c_str());
    VISIT_INIT(tsk, zookeeper_session::ZOO_OPERATION::ZOO_SET, node);

    input->_value = value;
    _session->visit(op);
    return tsk;
}

task_ptr meta_state_service_zookeeper::node_exist(const std::string &node,
                                                  task_code cb_code,
                                                  const err_callback &cb_exist,
                                                  dsn::task_tracker *tracker)
{
    error_code_future_ptr tsk(new error_code_future(cb_code, cb_exist, 0));
    tsk->set_tracker(tracker);
    dinfo("call node_exist, node(%s)", node.c_str());
    VISIT_INIT(tsk, zookeeper_session::ZOO_OPERATION::ZOO_EXISTS, node);
    input->_is_set_watch = 0;
    _session->visit(op);
    return tsk;
}

task_ptr meta_state_service_zookeeper::get_children(const std::string &node,
                                                    task_code cb_code,
                                                    const err_stringv_callback &cb_get_children,
                                                    dsn::task_tracker *tracker)
{
    err_stringv_future_ptr tsk(new err_stringv_future(cb_code, cb_get_children, 0));
    tsk->set_tracker(tracker);
    dinfo("call get children, node(%s)", node.c_str());
    VISIT_INIT(tsk, zookeeper_session::ZOO_OPERATION::ZOO_GETCHILDREN, node);
    input->_is_set_watch = 0;
    _session->visit(op);
    return tsk;
}

/*static*/
/* this function runs in zookeeper do-completion thread */
void meta_state_service_zookeeper::on_zoo_session_evt(ref_this _this, int zoo_state)
{
    _this->_zoo_state = zoo_state;

    if (ZOO_CONNECTING_STATE == zoo_state) {
        // TODO: support the switch of zookeeper session
        dwarn("the zk session is reconnecting");
    } else if (_this->_first_call && ZOO_CONNECTED_STATE == zoo_state) {
        _this->_first_call = false;
        _this->_notifier.notify();
    } else {
        // ignore
    }
}
/*static*/
/*this function runs in zookeper do-completion thread*/
void meta_state_service_zookeeper::visit_zookeeper_internal(ref_this,
                                                            task_ptr callback,
                                                            void *result)
{
    zookeeper_session::zoo_opcontext *op =
        reinterpret_cast<zookeeper_session::zoo_opcontext *>(result);
    dinfo(
        "visit zookeeper internal: ans(%s), call type(%d)", zerror(op->_output.error), op->_optype);

    switch (op->_optype) {
    case zookeeper_session::ZOO_OPERATION::ZOO_CREATE:
    case zookeeper_session::ZOO_OPERATION::ZOO_DELETE:
    case zookeeper_session::ZOO_OPERATION::ZOO_EXISTS:
    case zookeeper_session::ZOO_OPERATION::ZOO_SET:
    case zookeeper_session::ZOO_OPERATION::ZOO_TRANSACTION: {
        auto tsk = reinterpret_cast<error_code_future *>(callback.get());
        tsk->enqueue_with(from_zerror(op->_output.error));
    } break;
    case zookeeper_session::ZOO_OPERATION::ZOO_GET: {
        auto tsk = reinterpret_cast<err_value_future *>(callback.get());
        blob data;
        if (ZOK == op->_output.error) {
            std::shared_ptr<char> buf(
                dsn::utils::make_shared_array<char>(op->_output.get_op.value_length));
            memcpy(buf.get(), op->_output.get_op.value, op->_output.get_op.value_length);
            data.assign(buf, 0, op->_output.get_op.value_length);
        }
        tsk->enqueue_with(from_zerror(op->_output.error), data);
    } break;
    case zookeeper_session::ZOO_OPERATION::ZOO_GETCHILDREN: {
        auto tsk = reinterpret_cast<err_stringv_future *>(callback.get());
        std::vector<std::string> result;
        if (ZOK == op->_output.error) {
            const String_vector *vec = op->_output.getchildren_op.strings;
            result.resize(vec->count);
            for (int i = 0; i != vec->count; ++i)
                result[i].assign(vec->data[i]);
        }
        tsk->enqueue_with(from_zerror(op->_output.error), std::move(result));
    } break;
    default:
        break;
    }
}
}
}

ext: cpp

max_stars_repo_name: Smityz/rdsn

max_issues_repo_name: Skysheepwang/rdsn

max_forks_repo_name: Skysheepwang/rdsn


text:
#pragma once

#define BOOST_SPIRIT_DEBUG

#include "dateGrammar.hpp"
#include "userGrammar.hpp"

#include <boost/fusion/include/io.hpp>
#include <boost/spirit/include/phoenix_object.hpp>

#include <boost/fusion/adapted/std_pair.hpp>

#include <iostream>

#include "../date.h"

namespace Grawitas {

	template<typename Iterator, typename Skipper>
		struct SignatureGrammar : boost::spirit::qi::grammar<Iterator, std::pair<std::string, Date>(), Skipper>	{

			SignatureGrammar();

			boost::spirit::qi::rule<Iterator, std::pair<std::string, Date>(), Skipper> signature;

			UserGrammar<Iterator, Skipper> user_grammar;
			DateGrammar<Iterator, Skipper> date_grammar;

		};

}

ext: hpp

max_stars_repo_name: lewishamulton/grawitas

max_issues_repo_name: lewishamulton/grawitas

max_forks_repo_name: lewishamulton/grawitas


text:
#include <math.h>
#include <stdlib.h>
#include <string>

#include <opencv2/highgui/highgui.hpp>
#include <opencv2/opencv.hpp>
//#include <opencv2/legacy/compat.hpp>

#include "dlib/opencv.h"
#include "dlib/image_processing/frontal_face_detector.h"
#include "dlib/image_processing/render_face_detections.h"
#include "dlib/gui_widgets.h"
#include <dlib/image_processing.h>

#include "util.h"
#include "faceDetection.h"

double get_conversion_factor (dlib::full_object_detection shape, FacePose* face_pose, double magnitude_normal, int mode) {
	cv::Point p1, p2;
    //mode : 1 for left eye, 2 for right eye
	if(mode == 1) {
		p1 = cv::Point(shape.part(42).x(), shape.part(42).y());
		p2 = cv::Point(shape.part(45).x(), shape.part(45).y());
	}
	else if(mode == 2) {
		p1 = cv::Point(shape.part(36).x(), shape.part(36).y());
		p2 = cv::Point(shape.part(39).x(), shape.part(39).y());
	}

	double dx = p1.x - p2.x, dy = p1.y - p2.y;
	double temp1, temp2, beta;
	double n1 = face_pose->normal[0], n2 = face_pose->normal[1], n3 = face_pose->normal[2];
	double beta_old = sqrt(dx*dx + dy*dy)/magnitude_normal;

	temp1 = dx*dx*(1.0 - n2*n2);
	temp2 = dy*dy*(1.0 - n1*n1);

	beta = sqrt(temp1 + temp2)/((double)(magnitude_normal*fabs(n3)));
	beta = 1.0/((double) beta);

	//std::cout<<"Beta : "<<beta<<std::endl;
	return beta;
}

void compute_vec_LR (cv::Point p1, cv::Point p2, FacePose* face_pose, std::vector<double>& LR) {
	double scale = 20.784/30.0;

	LR[0] = p1.x - p2.x;
	LR[1] = p1.y - p2.y;
	LR[0] = LR[0]*scale;
	LR[1] = LR[1]*scale;
	LR[2] = -(LR[0]*face_pose->normal[0] + LR[1]*face_pose->normal[1])/face_pose->normal[3];
}

void get_quadratic_solution (std::vector<double> coeff, double& solution, int mode) {
	solution = (-coeff[1] + mode*sqrt(coeff[1]*coeff[1] - 4*coeff[0]*coeff[2]))/(2*coeff[0]);
	std::cout<<"soln : "<<solution<<std::endl;
}

void get_quadratic_equation (std::vector<double> coeff, std::vector<double>& quad_eqn) {
	quad_eqn[0] = coeff[0]*coeff[0];
	quad_eqn[1] = 2*coeff[0]*coeff[1];
	quad_eqn[2] = coeff[1]*coeff[1];
}

void solve(std::vector<double> coeff_1, double const_1, std::vector<double> coeff_2, double const_2, double mag, std::vector<double>& vec, int mode) {
	double det = coeff_1[0]*coeff_2[1] - coeff_1[1]*coeff_2[0];

	std::vector<double> linear_eqn_1(2), linear_eqn_2(2);
	linear_eqn_1[0] = (coeff_1[1]*coeff_2[2] - coeff_1[2]*coeff_2[1])/det;
	linear_eqn_1[1] = (const_1*coeff_2[1] - coeff_1[1]*const_2)/det;
	linear_eqn_2[0] = (coeff_1[2]*coeff_2[0] - coeff_1[0]*coeff_2[2])/det;
	linear_eqn_2[1] = (coeff_1[0]*const_2 - coeff_2[0]*const_1)/det;

	std::vector<double> quad_eqn_1(3), quad_eqn_2(3), quad_eqn_final(3);
	get_quadratic_equation(linear_eqn_1, quad_eqn_1);
	get_quadratic_equation(linear_eqn_2, quad_eqn_2);

	quad_eqn_final[0] = quad_eqn_1[0] + quad_eqn_2[0] + 1;
	quad_eqn_final[1] = quad_eqn_1[1] + quad_eqn_2[1];
	quad_eqn_final[2] = quad_eqn_1[2] + quad_eqn_2[2] - mag*mag;

	//std::cout<<"const_1 : "<<const_1<<" const_2 : "<<const_2<<std::endl;
	std::vector<double> coeff = quad_eqn_final;
	std::cout<<"Discriminant : "<<coeff[1]*coeff[1] - 4*coeff[0]*coeff[2]<<std::endl;
	log_vec("quad_eqn_final", quad_eqn_final);
	get_quadratic_solution (quad_eqn_final, vec[2], mode);
	vec[0] = linear_eqn_1[0]*vec[2] + linear_eqn_1[1];
	vec[1] = linear_eqn_2[0]*vec[2] + linear_eqn_2[1];
}

void get_section(cv::Point p1, cv::Point p2, cv::Point pupil, double& Y1, double& Y2, double& h) {
	std::vector<double> line(3);

	line[0] = p2.y - p1.y;
	line[1] = -(p2.x - p1.x);
	line[2] =  p1.y*(p2.x - p1.x) - p1.x*(p2.y - p1.y);

	cv::Point pupil_proj;
	pupil_proj.x = -(line[0]*pupil.x + line[1]*pupil.y + line[2])*line[0]/(line[0]*line[0] + line[1]*line[1]) + pupil.x;
	pupil_proj.y = -(line[0]*pupil.x + line[1]*pupil.y + line[2])*line[1]/(line[0]*line[0] + line[1]*line[1]) + pupil.y;

	Y1 = get_distance (p1, pupil_proj);
	Y2 = get_distance (p2, pupil_proj);
	h = get_distance (pupil, pupil_proj);
}

//List : Y1, Y2 can be interchanged. Magnitudes of the vectors in real world may be wrong.
//		 mag_LR square changed to just mag_LR.

void compute_vec_CP(cv::Point p1, cv::Point p2, cv::Point pupil, cv::Rect rect, FacePose* face_pose,
	std::vector<double> vec_CR_u, double mag_CR, std::vector<double> vec_LR_u, double mag_LR,
	std::vector<double> vec_UD_u, double mag_CP, std::vector<double>& vec_CP, double S2R, int mode) {
	double Y1, Y2, H;
	get_section(p1, p2, cv::Point(pupil.x + rect.x, pupil.y + rect.y), Y1, Y2, H);

	double const_1, const_2;
	const_1 = (S2R*H);///std::cos(face_pose->pitch);
	if(mode == 1) {
		const_2 = mag_CR*(scalar_product(vec_CR_u, vec_LR_u)) + ((mag_LR*Y1)/((double) (Y1 + Y2)));
	}
	else if(mode == 2) {
		const_2 = mag_CR*(scalar_product(vec_CR_u, vec_LR_u)) + ((mag_LR*Y2)/((double) (Y1 + Y2)));
	}

	//std::cout<<"Y1 : "<<Y1<<" Y2 : "<<Y2<<" H : "<<H<<std::endl;
	std::cout<<"CP - constants : "<<const_1<<" "<<const_2<<std::endl;

	solve(vec_UD_u, const_1, vec_LR_u, const_2, mag_CP, vec_CP, 1);
}

bool vec_isnan(std::vector<double>& vec) {
	int f = 0;
	for(int i=0; i<vec.size(); i++) {
		if(std::isnan(vec[i])) {
			f=1;
			break;
		}
	}

	if(f) {
		for(int i=0; i<vec.size(); i++) {
			vec[i] = 0.0;
		}
	}

	return (1-f);
}

void compute_eye_gaze (FacePose* face_pose, dlib::full_object_detection shape, cv::Rect rect, cv::Point pupil, double mag_CP, double mag_LR, double mag_CR, double mag_CM, double theta, int mode, std::vector<double>& vec_CP) {

	std::vector<double> vec_LR_u(3), vec_RP(3), vec_CR_u(3), vec_CM_u(3), vec_UD_u(3);
	std::vector<double> vec_CP_l(3), vec_CP_r(3);
	double S2R = get_conversion_factor(shape, face_pose, mag_CM, mode);

	cv::Point p1, p2;
    //mode : 1 for left eye, 2 for right eye
	if(mode == 1) {
		p1 = cv::Point(shape.part(42).x(), shape.part(42).y());
		p2 = cv::Point(shape.part(45).x(), shape.part(45).y());
	}
	else if(mode == 2) {
		p1 = cv::Point(shape.part(36).x(), shape.part(36).y());
		p2 = cv::Point(shape.part(39).x(), shape.part(39).y());
	}

	vec_CP[0] = 1.0;
	vec_CP[1] = 1.0;
	vec_CP[2] = 1.0;

	compute_vec_LR(p1, p2, face_pose, vec_LR_u);
	make_unit_vector(vec_LR_u, vec_LR_u);

	//log_vec("LR", vec_LR_u);

	vec_CM_u[0] = face_pose->normal[0];
	vec_CM_u[1] = face_pose->normal[1];
	vec_CM_u[2] = face_pose->normal[2];

	cross_product(vec_CM_u, vec_LR_u, vec_UD_u);
	make_unit_vector(vec_UD_u, vec_UD_u);

	//log_vec("UD", vec_UD_u);

	double const_1 = std::cos(theta/2.0);
	double const_2 = 0.0;

	solve(vec_UD_u, const_1, vec_CM_u, const_2, 1.0, vec_CR_u, -1);
	make_unit_vector(vec_CR_u, vec_CR_u);

	//log_vec("CR", vec_CR_u);

	compute_vec_CP(p1, p2, pupil, rect, face_pose, vec_CR_u, mag_CR, vec_LR_u, mag_LR,
		vec_UD_u, mag_CP, vec_CP_l, S2R, 2);

	compute_vec_CP(p1, p2, pupil, rect, face_pose, vec_CR_u, mag_CR, vec_LR_u, mag_LR,
		vec_UD_u, mag_CP, vec_CP_r, S2R, 1);

	double f1 = vec_isnan(vec_CP_l);
	double f2 = vec_isnan(vec_CP_r);

	if(f1 || f2) {
			vec_CP[0] = (vec_CP_l[0] + vec_CP_r[0]);
			vec_CP[1] = (vec_CP_l[1] + vec_CP_r[1]);
			vec_CP[2] = (vec_CP_l[2] + vec_CP_r[2]);
	}
	else {
		vec_CP[0] = (vec_CP_l[0] + vec_CP_r[0])/2.0;
		vec_CP[1] = (vec_CP_l[1] + vec_CP_r[1])/2.0;
		vec_CP[2] = (vec_CP_l[2] + vec_CP_r[2])/2.0;
	}

	log_vec("CP_l", vec_CP_l);
	log_vec("CP_r", vec_CP_r);
	log_vec("CP", vec_CP);
}

max_stars_repo_name: vmthanh/Eye-Tracking

max_issues_repo_name: vmthanh/Eye-Tracking

max_forks_repo_name: vmthanh/Eye-Tracking


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

#ifndef BOOST_ASIO_EXECUTION_CONTEXT2_HPP
#define BOOST_ASIO_EXECUTION_CONTEXT2_HPP

#if defined(_MSC_VER) && (_MSC_VER >= 1200)
# pragma once
#endif // defined(_MSC_VER) && (_MSC_VER >= 1200)

#include <boost/asio/detail/config.hpp>
#include <boost/asio/detail/type_traits.hpp>
#include <boost/asio/execution/executor.hpp>
#include <boost/asio/execution/scheduler.hpp>
#include <boost/asio/execution/sender.hpp>
#include <boost/asio/is_applicable_property.hpp>
#include <boost/asio/traits/query_static_constexpr_member.hpp>
#include <boost/asio/traits/static_query.hpp>

#if defined(BOOST_ASIO_HAS_STD_ANY)
# include <any>
#endif // defined(BOOST_ASIO_HAS_STD_ANY)

#include <boost/asio/detail/push_options.hpp>

namespace boost {
namespace asio {

#if defined(GENERATING_DOCUMENTATION)

namespace execution {

/// A property that is used to obtain the execution context that is associated
/// with an executor.
struct context_t
{
  /// The context_t property applies to executors, senders, and schedulers.
  template <typename T>
  static constexpr bool is_applicable_property_v =
    is_executor_v<T> || is_sender_v<T> || is_scheduler_v<T>;

  /// The context_t property cannot be required.
  static constexpr bool is_requirable = false;

  /// The context_t property cannot be preferred.
  static constexpr bool is_preferable = false;

  /// The type returned by queries against an @c any_executor.
  typedef std::any polymorphic_query_result_type;
};

/// A special value used for accessing the context_t property.
constexpr context_t context;

} // namespace execution

#else // defined(GENERATING_DOCUMENTATION)

namespace execution {
namespace detail {

template <int I = 0>
struct context_t
{
#if defined(BOOST_ASIO_HAS_VARIABLE_TEMPLATES)
  template <typename T>
  BOOST_ASIO_STATIC_CONSTEXPR(bool,
    is_applicable_property_v = is_executor<T>::value
      || is_sender<T>::value || is_scheduler<T>::value);
#endif // defined(BOOST_ASIO_HAS_VARIABLE_TEMPLATES)

  BOOST_ASIO_STATIC_CONSTEXPR(bool, is_requirable = false);
  BOOST_ASIO_STATIC_CONSTEXPR(bool, is_preferable = false);

#if defined(BOOST_ASIO_HAS_STD_ANY)
  typedef std::any polymorphic_query_result_type;
#endif // defined(BOOST_ASIO_HAS_STD_ANY)

  BOOST_ASIO_CONSTEXPR context_t()
  {
  }

#if defined(BOOST_ASIO_HAS_DEDUCED_STATIC_QUERY_TRAIT) \
  && defined(BOOST_ASIO_HAS_SFINAE_VARIABLE_TEMPLATES)
  template <typename T>
  static BOOST_ASIO_CONSTEXPR
  typename traits::query_static_constexpr_member<T, context_t>::result_type
  static_query()
    BOOST_ASIO_NOEXCEPT_IF((
      traits::query_static_constexpr_member<T, context_t>::is_noexcept))
  {
    return traits::query_static_constexpr_member<T, context_t>::value();
  }

  template <typename E, typename T = decltype(context_t::static_query<E>())>
  static BOOST_ASIO_CONSTEXPR const T static_query_v
    = context_t::static_query<E>();
#endif // defined(BOOST_ASIO_HAS_DEDUCED_STATIC_QUERY_TRAIT)
       //   && defined(BOOST_ASIO_HAS_SFINAE_VARIABLE_TEMPLATES)

#if !defined(BOOST_ASIO_HAS_CONSTEXPR)
  static const context_t instance;
#endif // !defined(BOOST_ASIO_HAS_CONSTEXPR)
};

#if defined(BOOST_ASIO_HAS_DEDUCED_STATIC_QUERY_TRAIT) \
  && defined(BOOST_ASIO_HAS_SFINAE_VARIABLE_TEMPLATES)
template <int I> template <typename E, typename T>
const T context_t<I>::static_query_v;
#endif // defined(BOOST_ASIO_HAS_DEDUCED_STATIC_QUERY_TRAIT)
       //   && defined(BOOST_ASIO_HAS_SFINAE_VARIABLE_TEMPLATES)

#if !defined(BOOST_ASIO_HAS_CONSTEXPR)
template <int I>
const context_t<I> context_t<I>::instance;
#endif

} // namespace detail

typedef detail::context_t<> context_t;

#if defined(BOOST_ASIO_HAS_CONSTEXPR) || defined(GENERATING_DOCUMENTATION)
constexpr context_t context;
#else // defined(BOOST_ASIO_HAS_CONSTEXPR) || defined(GENERATING_DOCUMENTATION)
namespace { static const context_t& context = context_t::instance; }
#endif

} // namespace execution

#if !defined(BOOST_ASIO_HAS_VARIABLE_TEMPLATES)

template <typename T>
struct is_applicable_property<T, execution::context_t>
  : integral_constant<bool,
      execution::is_executor<T>::value
        || execution::is_sender<T>::value
        || execution::is_scheduler<T>::value>
{
};

#endif // !defined(BOOST_ASIO_HAS_VARIABLE_TEMPLATES)

namespace traits {

#if !defined(BOOST_ASIO_HAS_DEDUCED_STATIC_QUERY_TRAIT) \
  || !defined(BOOST_ASIO_HAS_SFINAE_VARIABLE_TEMPLATES)

template <typename T>
struct static_query<T, execution::context_t,
  typename enable_if<
    traits::query_static_constexpr_member<T,
      execution::context_t>::is_valid
  >::type>
{
  BOOST_ASIO_STATIC_CONSTEXPR(bool, is_valid = true);
  BOOST_ASIO_STATIC_CONSTEXPR(bool, is_noexcept = true);

  typedef typename traits::query_static_constexpr_member<T,
    execution::context_t>::result_type result_type;

  static BOOST_ASIO_CONSTEXPR result_type value()
  {
    return traits::query_static_constexpr_member<T,
      execution::context_t>::value();
  }
};

#endif // !defined(BOOST_ASIO_HAS_DEDUCED_STATIC_QUERY_TRAIT)
       //   || !defined(BOOST_ASIO_HAS_SFINAE_VARIABLE_TEMPLATES)

} // namespace traits

#endif // defined(GENERATING_DOCUMENTATION)

} // namespace asio
} // namespace boost

#include <boost/asio/detail/pop_options.hpp>

#endif // BOOST_ASIO_EXECUTION_CONTEXT2_HPP

max_stars_repo_name: kindlychung/mediasoup-sfu-cpp

max_issues_repo_name: kindlychung/mediasoup-sfu-cpp

max_forks_repo_name: kindlychung/mediasoup-sfu-cpp


text:
//==============================================================================
//         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
//==============================================================================
#ifndef NT2_CORE_UTILITY_OF_SIZE_FUSION_HPP_INCLUDED
#define NT2_CORE_UTILITY_OF_SIZE_FUSION_HPP_INCLUDED

#include <nt2/core/settings/size.hpp>
#include <boost/simd/sdk/details/at_iterator.hpp>
#include <boost/fusion/sequence/intrinsic.hpp>
#include <boost/fusion/support.hpp>
#include <boost/mpl/at.hpp>
#include <boost/version.hpp>
#include <boost/mpl/size_t.hpp>
#include <boost/type_traits/remove_reference.hpp>
#include <boost/type_traits/is_const.hpp>

namespace boost { namespace fusion { namespace extension
{
  //============================================================================
  // Register of_size_ as fusion random access sequence
  //============================================================================
  template<> struct is_sequence_impl<nt2::tag::of_size_>
  {
    template<typename Seq> struct apply : boost::mpl::true_ {};
  };

  template<> struct is_view_impl<nt2::tag::of_size_>
  {
    template<typename Seq> struct apply : boost::mpl::false_ {};
  };

  template<> struct category_of_impl<nt2::tag::of_size_>
  {
    template<typename Seq>
    struct apply
    {
      typedef unbounded_tag type;
    };
  };

  //============================================================================
  // Size of of_size_ is given by its static_size member
  //============================================================================
  template<> struct size_impl<nt2::tag::of_size_>
  {
    template<typename Seq> struct apply : boost::mpl::size_t<Seq::static_size> {};
  };

  //============================================================================
  // at_c value of of_size_ is given by its static size or dynamic size if negative
  // always return 1 if accessed past-the-end
  //============================================================================
  template<> struct at_impl<nt2::tag::of_size_>
  {
    template<class Seq, class Index, std::size_t S, bool B = !(std::size_t(Index::value) >= S)>
    struct select_apply;

    template<class Seq, class Index, std::ptrdiff_t N, bool IsStatic = (N >= 0)>
    struct apply_impl;

    template<class Seq, class Index>
    struct  apply
          : select_apply<Seq, Index, Seq::static_size>
    {};

    template<class Seq, class Index, std::size_t S>
    struct  select_apply<Seq, Index, S, true>
          : apply_impl< Seq, Index
                      , boost::mpl::at<typename Seq::values_type, Index>::type::value
                      >
    {};

    template<class Seq, class Index, std::size_t S>
    struct select_apply<Seq, Index, S, false>
    {
      typedef boost::mpl::size_t<1> type;
      static type call(Seq&) { return type(); }
    };

    template<class Seq, class Index, std::ptrdiff_t N>
    struct apply_impl<Seq, Index, N, false>
    {
      typedef typename boost::mpl::if_ < is_const<Seq>
                                , std::size_t const&
                                , std::size_t&
                                >::type               type;

      static type call(Seq& seq) { return seq.data()[Index::value]; }
    };

    template<class Seq, class Index, std::ptrdiff_t N, bool IsStatic>
    struct apply_impl
    {
      typedef boost::mpl::size_t<N> type;
      static type call(Seq&) { return type(); }
    };
  };

  template<> struct value_at_impl<nt2::tag::of_size_>
  {
    template<class Seq, class Index>
    struct apply
    {
      typedef typename  at_impl<nt2::tag::of_size_>
                        ::template apply<Seq, Index>::type  base;
      typedef typename remove_reference<base>::type         type;
    };
  };

  //==========================================================================
  // begin returns the inner data_type begin as it is itself a Fusion Sequence
  //==========================================================================
  template<> struct begin_impl<nt2::tag::of_size_>
  {
    template<typename Sequence> struct apply
    {
      typedef boost::simd::at_iterator<Sequence, 0, Sequence::static_size> type;
      static type call(Sequence& seq) { return type(seq); }
    };
  };

  //==========================================================================
  // end returns the inner data_type end as it is itself a Fusion Sequence
  //==========================================================================
  template<> struct end_impl<nt2::tag::of_size_>
  {
    template<typename Sequence>
    struct apply
    {
      typedef boost::simd::at_iterator<Sequence, Sequence::static_size, Sequence::static_size> type;
      static type call(Sequence& seq) { return type(seq); }
    };
  };
} } }

#endif


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

#ifndef HTTP_SERVER3_CONNECTION_HPP
#define HTTP_SERVER3_CONNECTION_HPP

#include <boost/asio.hpp>
#include <boost/array.hpp>
#include <boost/noncopyable.hpp>
#include <boost/shared_ptr.hpp>
#include <boost/enable_shared_from_this.hpp>

#include <boost/asio/deadline_timer.hpp>
#include <boost/date_time/posix_time/posix_time.hpp>

#include "request.hpp"
#include "reply.hpp"
#include "request_handler.hpp"
#include "request_parser.hpp"

namespace http {
namespace server3 {

class base_connection
{
public:
	/// Construct a connection with the given io_service.
	explicit base_connection(boost::asio::io_service& io_service, request_handler& handler) : strand_(io_service), request_handler_(handler) {
	}

	/// Remote peer
	boost::asio::ip::tcp::endpoint peer;

protected:
	/// Log HTTP request
	void log_request();

	/// Strand to ensure the connection's handlers are not called concurrently.
	boost::asio::io_service::strand strand_;

	/// The handler used to process the incoming request.
	request_handler& request_handler_;

	/// Buffer for incoming data.
	boost::array<char, 8192> buffer_;

	/// The incoming request.
	request request_;

	/// The outgoing reply.
	reply reply_;

	/// The parser for the incoming request.
	request_parser request_parser_;

	/// HTTP/1.1 keepalive enabled?
	bool keepalive_;

	void reset()
	{
		request_.clear();
		reply_.clear();
		request_parser_.reset();
	}
};

/// Represents a single connection from a client.
class connection
	: public boost::enable_shared_from_this<connection>,
		public base_connection,
		private boost::noncopyable
{
public:
	/// Construct a connection with the given io_service.
	explicit connection(boost::asio::io_service& io_service, request_handler& handler) : base_connection(io_service, handler), socket_(io_service) {
	}

	/// Get the socket associated with the connection.
	boost::asio::ip::tcp::socket& socket();

	/// Start the first asynchronous operation for the connection.
	void start();

private:
	/// Initiate asynchronous read
	void read_more();

	/// Handle completion of a read operation.
	void handle_read(const boost::system::error_code& e, std::size_t bytes_transferred);

	/// Handle completion of a write operation.
	void handle_write(const boost::system::error_code& e);

	/// Socket for the connection.
	boost::asio::ip::tcp::socket socket_;
	//boost::asio::deadline_timer read_timer_;

};

typedef boost::shared_ptr<connection> connection_ptr;

} // namespace server3
} // namespace http

#endif // HTTP_SERVER3_CONNECTION_HPP


text:
#pragma once

#include <boost/python.hpp>

#include "corridor/basic_types.h"
#include "corridor/cartesian_types.h"
#include "corridor/cubic_spline/cubic_spline_coefficients.h"
#include "corridor/frenet_types.h"

namespace py = boost::python;
namespace cs = corridor::cubic_spline;

// /////////////////////////////////////////////////////////////////////////////
// Utility functions
// /////////////////////////////////////////////////////////////////////////////

template <typename T>
inline std::vector<T> to_std_vector(const py::object& iterable) {
  return std::vector<T>(py::stl_input_iterator<T>(iterable),
                        py::stl_input_iterator<T>());
}

inline corridor::CartesianVector2D to_cartesian_vector(
    const py::list& py_list) {
  using namespace corridor;
  std::vector<RealType> std_vec = to_std_vector<RealType>(py_list);
  return CartesianVector2D(std_vec.front(), std_vec.back());
}

inline corridor::CartesianPoints2D toCartesianPoints(const py::list& node_x,
                                                     const py::list& node_y) {
  using namespace corridor;
  std::vector<RealType> x_vec = to_std_vector<RealType>(node_x);
  std::vector<RealType> y_vec = to_std_vector<RealType>(node_y);

  corridor::CartesianPoints2D points;
  for (int i = 0, n = x_vec.size(); i < n; i++) {
    points.emplace_back(x_vec[i], y_vec[i]);
  }
  return points;
}

inline py::dict to_py_dict(const cs::SplineCoefficients2d& coeffs) {
  py::dict dict;

  py::list a_x, b_x, c_x, d_x;
  py::list a_y, b_y, c_y, d_y;
  for (const auto& c : coeffs) {
    a_x.append(c.a_x);
    b_x.append(c.b_x);
    c_x.append(c.c_x);
    d_x.append(c.d_x);

    a_y.append(c.a_y);
    b_y.append(c.b_y);
    c_y.append(c.c_y);
    d_y.append(c.d_y);
  }
  dict["a_x"] = a_x;
  dict["b_x"] = b_x;
  dict["c_x"] = c_x;
  dict["d_x"] = d_x;

  dict["a_y"] = a_y;
  dict["b_y"] = b_y;
  dict["c_y"] = c_y;
  dict["d_y"] = d_y;

  return dict;
}

inline py::dict to_py_dict(const corridor::CartesianPoint2D& vector2d) {
  py::dict py_dict;
  py_dict["x"] = vector2d.x();
  py_dict["y"] = vector2d.y();
  return py_dict;
}

inline py::dict to_py_dict(const corridor::FrenetFrame2D& frenet_frame) {
  py::dict py_frenet_frame;
  py_frenet_frame["segm_index"] = frenet_frame.frenet_base().segment_info.idx;
  py_frenet_frame["segm_arc_length"] =
      frenet_frame.frenet_base().segment_info.relative_arc_length;
  py_frenet_frame["origin"] = to_py_dict(frenet_frame.origin());
  py_frenet_frame["tangent"] = to_py_dict(frenet_frame.tangent());
  py_frenet_frame["normal"] = to_py_dict(frenet_frame.normal());
  return py_frenet_frame;
}

inline py::list to_py_list(const corridor::FrenetFrames2D& frenet_frames) {
  py::list py_frenet_frames;
  for (const auto& ff : frenet_frames) {
    py_frenet_frames.append(to_py_dict(ff));
  }
  return py_frenet_frames;
}

inline std::pair<py::list, py::list> to_py_lists(
    const corridor::CartesianPoints2D& points) {
  py::list point_x;
  py::list point_y;
  for (const corridor::CartesianPoint2D& p : points) {
    point_x.append(p.x());
    point_y.append(p.y());
  }
  return std::make_pair(point_x, point_y);
}

corridor::CartesianStateVector2D convert(
    const py::list& cartesian_state_vector) {
  using namespace corridor;
  return CartesianStateVector2D(
      py::extract<RealType>(cartesian_state_vector[0]),
      py::extract<RealType>(cartesian_state_vector[1]),
      py::extract<RealType>(cartesian_state_vector[2]),
      py::extract<RealType>(cartesian_state_vector[3]));
}

py::list convert(const corridor::FrenetStateVector2D& frenet_state_vector) {
  py::list py_frenet_state_vector;
  py_frenet_state_vector.append(frenet_state_vector.l());
  py_frenet_state_vector.append(frenet_state_vector.d());
  py_frenet_state_vector.append(frenet_state_vector.vl());
  py_frenet_state_vector.append(frenet_state_vector.vd());
  return py_frenet_state_vector;
}

struct FlatCartesianPositionAndCovMat2D {
  corridor::RealType x;
  corridor::RealType y;
  corridor::RealType var_x;
  corridor::RealType var_y;
  corridor::RealType cov_xy;
};

struct FlatCartesianStateAndCovMat2D {
  corridor::RealType x;
  corridor::RealType y;
  corridor::RealType vx;
  corridor::RealType vy;

  corridor::RealType var_x;
  corridor::RealType var_y;
  corridor::RealType var_vx;
  corridor::RealType var_vy;

  corridor::RealType cov_xy;
  corridor::RealType cov_xvx;
  corridor::RealType cov_xvy;
  corridor::RealType cov_yvx;
  corridor::RealType cov_yvy;
  corridor::RealType cov_vxvy;
};

struct FlatPolarPositionAndCovMat2D {
  corridor::RealType r;
  corridor::RealType phi;
  corridor::RealType var_r;
  corridor::RealType var_phi;
  corridor::RealType cov_rphi;
};

struct FlatFrenetStateAndCovMat2D {
  corridor::RealType l;
  corridor::RealType d;
  corridor::RealType vl;
  corridor::RealType vd;

  corridor::RealType var_l;
  corridor::RealType var_d;
  corridor::RealType var_vl;
  corridor::RealType var_vd;

  corridor::RealType cov_ld;
  corridor::RealType cov_lvl;
  corridor::RealType cov_lvd;
  corridor::RealType cov_dvl;
  corridor::RealType cov_dvd;
  corridor::RealType cov_vlvd;
};

corridor::StateMeanAndCovarianceMatrix Convert(
    const FlatCartesianPositionAndCovMat2D& flat_cartesian_state) {
  corridor::StateMeanAndCovarianceMatrix state(2);
  state.mean << flat_cartesian_state.x, flat_cartesian_state.y;
  state.covMat(0, 0) = flat_cartesian_state.var_x;
  state.covMat(1, 1) = flat_cartesian_state.var_y;
  state.covMat(1, 0) = flat_cartesian_state.cov_xy;
  state.covMat(0, 1) = flat_cartesian_state.cov_xy;
  return state;
}

corridor::CartesianState2D Convert(
    const FlatCartesianStateAndCovMat2D& flat_cartesian_state) {
  using namespace corridor;
  const CartesianPoint2D position(flat_cartesian_state.x,
                                  flat_cartesian_state.y);
  const CartesianVector2D velocity(flat_cartesian_state.vx,
                                   flat_cartesian_state.vy);
  const CovarianceMatrix2D cm_position(flat_cartesian_state.var_x,
                                       flat_cartesian_state.var_y,
                                       flat_cartesian_state.cov_xy);
  const CovarianceMatrix2D cm_velocity(flat_cartesian_state.var_vx,
                                       flat_cartesian_state.var_vy,
                                       flat_cartesian_state.cov_vxvy);
  const CovarianceMatrix2D cm_pos_vel(
      flat_cartesian_state.cov_xvx, flat_cartesian_state.cov_yvy,
      flat_cartesian_state.cov_xvy, flat_cartesian_state.cov_yvx);
  return CartesianState2D(position, velocity, cm_position, cm_velocity,
                          cm_pos_vel);
}

FlatFrenetStateAndCovMat2D Convert(
    const corridor::FrenetState2D& frenet_state) {
  FlatFrenetStateAndCovMat2D flat_frenet_state;
  flat_frenet_state.l = frenet_state.l();
  flat_frenet_state.d = frenet_state.d();
  flat_frenet_state.vl = frenet_state.vl();
  flat_frenet_state.vd = frenet_state.vd();

  const corridor::FrenetStateCovarianceMatrix2D& cov_mat =
      frenet_state.covarianceMatrix();

  flat_frenet_state.var_l = cov_mat.ll();
  flat_frenet_state.var_d = cov_mat.dd();
  flat_frenet_state.cov_ld = cov_mat.ld();

  flat_frenet_state.var_vl = cov_mat.vlvl();
  flat_frenet_state.var_vd = cov_mat.vdvd();
  flat_frenet_state.cov_vlvd = cov_mat.vlvd();

  flat_frenet_state.cov_lvl = cov_mat.lvl();
  flat_frenet_state.cov_lvd = cov_mat.lvd();
  flat_frenet_state.cov_dvl = cov_mat.dvl();
  flat_frenet_state.cov_dvd = cov_mat.dvd();

  return flat_frenet_state;
}

FlatPolarPositionAndCovMat2D Convert(
    const corridor::StateMeanAndCovarianceMatrix& polar_state) {
  FlatPolarPositionAndCovMat2D flat_polar_state;
  flat_polar_state.r = polar_state.mean(0);
  flat_polar_state.phi = polar_state.mean(1);
  flat_polar_state.var_r = polar_state.covMat(0, 0);
  flat_polar_state.var_phi = polar_state.covMat(1, 1);
  flat_polar_state.cov_rphi = polar_state.covMat(1, 0);
  return flat_polar_state;
};

max_stars_repo_name: m-naumann/corridor

max_issues_repo_name: m-naumann/corridor

max_forks_repo_name: m-naumann/corridor


text:
#define BOOST_TEST_DYN_LINK
#define BOOST_TEST_MAIN
#include <boost/test/unit_test.hpp>

#include <utility>
#include <vector>

#include <revdoor.hpp>

using namespace std;

BOOST_AUTO_TEST_CASE(test_combinations) {
  int n = 5;
  int t = 3;
  revdoor::combinations combs(n, t);
  vector<vector<int>> states;
  vector<int> init_state = combs.state();
  states.push_back(init_state);
  vector<int> expected_init_state = {0, 1, 2};
  BOOST_CHECK_EQUAL_COLLECTIONS(
      init_state.begin(),
      init_state.end(),
      expected_init_state.begin(),
      expected_init_state.end());
  vector<pair<int,int>> swaps;
  vector<pair<int,int>> expected_swaps = {
    {1, 3}, {0, 1}, {2, 0}, {1, 4}, {0, 1},
    {1, 2}, {3, 0}, {0, 1}, {2, 0}
  };
  int out, in;
  while (combs.step(&out, &in)) {
    swaps.push_back({out, in});
    states.push_back(combs.state());
  }
  BOOST_REQUIRE_EQUAL(swaps.size(), expected_swaps.size());
  for (int i = 0; i < (int)swaps.size(); ++i) {
    BOOST_CHECK_EQUAL(swaps[i].first, expected_swaps[i].first);
    BOOST_CHECK_EQUAL(swaps[i].second, expected_swaps[i].second);
  }
  vector<int> end_state = states[states.size() - 1];
  vector<int> expected_end_state = {0, 1, 4};
  BOOST_CHECK_EQUAL_COLLECTIONS(
      end_state.begin(),
      end_state.end(),
      expected_end_state.begin(),
      expected_end_state.end());
  for (int i = 0; i < (int)states.size(); ++i) {
    combs.set_state(states[i]);
    swaps.clear();
    while (combs.step(&out, &in)) {
      swaps.push_back({out, in});
    }
    BOOST_REQUIRE_EQUAL(swaps.size(), expected_swaps.size() - i);
    for (int j = 0; j < (int)swaps.size(); ++j) {
      BOOST_CHECK_EQUAL(swaps[j].first, expected_swaps[i + j].first);
      BOOST_CHECK_EQUAL(swaps[j].second, expected_swaps[i + j].second);
    }
    end_state = states[states.size() - 1];
    BOOST_CHECK_EQUAL_COLLECTIONS(
        end_state.begin(),
        end_state.end(),
        expected_end_state.begin(),
        expected_end_state.end());
  }
}

BOOST_AUTO_TEST_CASE(test_combinations_with_replacement) {
  int n = 5;
  int t = 3;
  revdoor::combinations_with_replacement combs(n, t);
  vector<vector<int>> states;
  vector<int> init_state = combs.state();
  states.push_back(init_state);
  vector<int> expected_init_state = {0, 0, 0};
  BOOST_CHECK_EQUAL_COLLECTIONS(
      init_state.begin(),
      init_state.end(),
      expected_init_state.begin(),
      expected_init_state.end());
  vector<vector<int>> swaps;
  vector<vector<int>> expected_swaps = {
    {0, 1, 0, 1}, {0, 1}, {1, 0, 1, 0}, {0, 2, 1, 2}, {0, 1},
    {1, 2}, {2, 1, 2, 0}, {0, 1}, {1, 0, 1, 0}, {0, 3, 2, 3},
    {0, 1}, {1, 2}, {2, 3}, {3, 2, 3, 0}, {0, 1}, {1, 2},
    {2, 1, 2, 0}, {0, 1}, {1, 0, 1, 0}, {0, 4, 3, 4}, {0, 1},
    {1, 2}, {2, 3}, {3, 4}, {4, 3, 4, 0}, {0, 1}, {1, 2},
    {2, 3}, {3, 2, 3, 0}, {0, 1}, {1, 2}, {2, 1, 2, 0}, {0, 1},
    {1, 0, 1, 0}
  };
  int out1, in1, out2, in2;
  while (combs.step(&out1, &in1, &out2, &in2)) {
    vector<int> v;
    if (out1 != in1) {
      v.push_back(out1);
      v.push_back(in1);
    }
    v.push_back(out2);
    v.push_back(in2);
    swaps.push_back(v);
    states.push_back(combs.state());
  }
  BOOST_REQUIRE_EQUAL(swaps.size(), expected_swaps.size());
  for (int i = 0; i < (int)swaps.size(); ++i) {
    BOOST_CHECK_EQUAL_COLLECTIONS(
        swaps[i].begin(),
        swaps[i].end(),
        expected_swaps[i].begin(),
        expected_swaps[i].end());
  }
  vector<int> end_state = combs.state();
  vector<int> expected_end_state = {0, 0, 4};
  BOOST_CHECK_EQUAL_COLLECTIONS(
      end_state.begin(),
      end_state.end(),
      expected_end_state.begin(),
      expected_end_state.end());
  for (int i = 0; i < (int)states.size(); ++i) {
    combs.set_state(states[i]);
    swaps.clear();
    while (combs.step(&out1, &in1, &out2, &in2)) {
      vector<int> v;
      if (out1 != in1) {
        v.push_back(out1);
        v.push_back(in1);
      }
      v.push_back(out2);
      v.push_back(in2);
      swaps.push_back(v);
    }
    BOOST_REQUIRE_EQUAL(swaps.size(), expected_swaps.size() - i);
    for (int j = 0; j < (int)swaps.size(); ++j) {
      BOOST_CHECK_EQUAL_COLLECTIONS(
          swaps[j].begin(),
          swaps[j].end(),
          expected_swaps[i + j].begin(),
          expected_swaps[i + j].end());
    }
    end_state = states[states.size() - 1];
    BOOST_CHECK_EQUAL_COLLECTIONS(
        end_state.begin(),
        end_state.end(),
        expected_end_state.begin(),
        expected_end_state.end());
  }
}


text:
//#include <bits/stdc++.h>
#include <armadillo>

using namespace std;

class Probability_table{
public:
    int rows,cols;
    arma::mat table;

    //Member functions
    Probability_table(int rows,int cols);
    void view();
};


text:
////////////////////////////////////////////////////////////////////////////////
//  Copyright (c) 2007-2012 Hartmut Kaiser
//  Copyright (c) 2012 Bryce Adelstein-Lelbach
//
//  Distributed under the Boost Software License, Version 1.0. (See accompanying
//  file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
////////////////////////////////////////////////////////////////////////////////

#if !defined(HPX_725569E7_7AF4_4276_AF43_5713635DD598)
#define HPX_725569E7_7AF4_4276_AF43_5713635DD598

#include <hpx/lcos/detail/future_data.hpp>
#include <hpx/lcos/local/packaged_continuation.hpp>

#include <boost/thread/locks.hpp>

namespace hpx { namespace lcos { namespace detail
{

template <typename Result>
struct channel_future_data : future_data<Result>
{
  public:
    typedef typename future_data<Result>::mutex_type mutex_type;
    typedef typename future_data<Result>::result_type result_type;

  public:
    result_type move_data(error_code& ec = throws)
    {
        typedef typename future_data<Result>::data_type data_type;
        // yields control if needed
        data_type d;
        {
            boost::unique_lock<mutex_type> l(this->mtx_);
            // moves the data from the store
            this->data_.read_and_empty(d, l, ec);
            if (ec) return result_type();
        }

        if (d.is_empty()) {
            // the value has already been moved out of this future
            HPX_THROWS_IF(ec, no_state,
                "future_data::move_data",
                "this future has not been initialized");
            return result_type();
        }

        // the thread has been re-activated by one of the actions
        // supported by this promise (see \a promise::set_event
        // and promise::set_exception).
        if (d.stores_error())
            return handle_error(d, ec);

        // no error has been reported, return the result
        return d.move_value();
    }
};

} // namespace detail

namespace local
{

/// An asynchronous, single value channel
template <typename T>
struct channel
{
  private:
    typedef hpx::lcos::detail::channel_future_data<T> future_data;

    boost::intrusive_ptr<future_data> data_;

    (channel<T>);

  public:
    typedef typename future_data::completed_callback_type
        completed_callback_type;

    channel() : data_(new future_data()) {}

    channel(channel const& other) : data_(other.data_) {}

    channel(channel && other) : data_(std::move(other.data_)) {}

    explicit channel(T && init) : data_(new future_data())
    {
        data_->set_data(init);
    }

    explicit channel(T const& init) : data_(new future_data())
    {
        data_->set_data(init);
    }

    ~channel()
    {}

    channel& operator=(channel const & other)
    {
        HPX_ASSERT(data_);

        if (this != &other)
        {
            data_ = other.data_;
        }

        return *this;
    }

    channel& operator=(channel && other)
    {
        HPX_ASSERT(data_);

        if (this != &other)
        {
            data_ = std::move(other.data_);
            other.data_.reset();
        }

        return *this;
    }

    void swap(channel& other)
    {
        data_.swap(other.data_);
    }

    void reset()
    {
        HPX_ASSERT(data_);

        data_->reset();
   }

    hpx::future<T> get_future()
    {
        HPX_ASSERT(data_);

        using traits::future_access;
        return future_access<hpx::future<T> >::create(data_);
    }

    T get(hpx::error_code& ec = hpx::throws) const
    {
        HPX_ASSERT(data_);
        T tmp = data_->get_data(ec);
        return tmp;
    }

    T move(hpx::error_code& ec = hpx::throws) const
    {
        HPX_ASSERT(data_);
        T tmp = data_->move_data(ec);
        return tmp;
    }

    void post(T && result)
    {
        HPX_ASSERT(data_);
        //if (data_->is_ready())
        //    data_->move_data();
        data_->set_data(result);
    }

    void post(T const& result)
    {
        HPX_ASSERT(data_);
        //if (data_->is_ready())
        //    data_->move_data();
        data_->set_data(result);
    }

    template <typename F>
    hpx::future<typename util::result_of<F(hpx::future<T>)>::type>
    then(F && f)
    {
        HPX_ASSERT(data_);

        using traits::future_access;
        return future_access<hpx::future<T> >::create(data_).then
            (std::forward<F>(f));
    }

    bool is_ready() const
    {
        HPX_ASSERT(data_);
        return data_->is_ready();
    }
};

template <>
struct channel<void>
{
  private:
    typedef hpx::lcos::detail::channel_future_data<void> future_data;

    boost::intrusive_ptr<future_data> data_;

    (channel<void>);

  public:
    typedef future_data::completed_callback_type
        completed_callback_type;

    channel() : data_(new future_data()) {}

    channel(channel const& other) : data_(other.data_) {}

    channel(channel && other) : data_(std::move(other.data_)) {}

    ~channel()
    {}

    channel& operator=(channel const & other)
    {
        HPX_ASSERT(data_);

        if (this != &other)
        {
            data_ = other.data_;
        }

        return *this;
    }

    channel& operator=(channel && other)
    {
        HPX_ASSERT(data_);

        if (this != &other)
        {
            data_ = std::move(other.data_);
            other.data_.reset();
        }

        return *this;
    }

    void swap(channel& other)
    {
        data_.swap(other.data_);
    }

    void reset()
    {
        HPX_ASSERT(data_);

        data_->reset();
   }

    hpx::future<void> get_future()
    {
        HPX_ASSERT(data_);

        using traits::future_access;
        return future_access<hpx::future<void> >::create(data_);
    }

    void get(hpx::error_code& ec = hpx::throws) const
    {
        HPX_ASSERT(data_);
        hpx::util::unused_type tmp = data_->get_data(ec);
    }

    void move(hpx::error_code& ec = hpx::throws) const
    {
        HPX_ASSERT(data_);
        hpx::util::unused_type tmp = data_->move_data(ec);
    }

    void post()
    {
        HPX_ASSERT(data_);
        //if (data_->is_ready())
        //    data_->move_data();
        data_->set_data(hpx::util::unused);
    }

    template <typename F>
    hpx::future<typename util::result_of<F(hpx::future<void>)>::type>
    then(F && f)
    {
        HPX_ASSERT(data_);

        using traits::future_access;
        return future_access<hpx::future<void> >::create(data_).then
            (std::forward<completed_callback_type>(f));
    }

    bool is_ready() const
    {
        HPX_ASSERT(data_);
        return data_->is_ready();
    }
};

}}}

#endif // HPX_725569E7_7AF4_4276_AF43_5713635DD598

max_stars_repo_name: kempj/hpx

max_issues_repo_name: kempj/hpx

max_forks_repo_name: kempj/hpx


text:
#define BOOST_TEST_MAIN
#define BOOST_TEST_DYN_LINK

#define BOOST_AUTO_TEST_MAIN
#include <boost/test/auto_unit_test.hpp>

#include "jml/utils/string_functions.h"
#include "jml/arch/exception.h"

using namespace ML;

BOOST_AUTO_TEST_CASE( test_antoi )
{
    const char * c = "12";
    BOOST_CHECK(antoi(c, c + 2) == 12);

    const char * d  = "-1";
    BOOST_CHECK(antoi(d, d + 2) == -1);

    const char * p = "patate";
    BOOST_CHECK_THROW(antoi(p, p + 6), ML::Exception);
}

ext: cc

max_stars_repo_name: etnrlz/rtbkit

max_issues_repo_name: TuanTranEngineer/rtbkit

max_forks_repo_name: TuanTranEngineer/rtbkit


text:
/*
 * shell_parser.hpp - Parser designed to emulate a very simple shell
 *
 *   Copyright 2010-2011 Jesús Torres <jmtorres@ull.es>
 *
 * 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.
 */

#ifndef SHELL_PARSER_HPP_
#define SHELL_PARSER_HPP_

#include <iostream>
#include <string>
#include <vector>

#include <boost/algorithm/string/join.hpp>
#include <boost/spirit/include/qi.hpp>

#include <cli/auxiliary.hpp>
#include <cli/boost_parser_base.hpp>
#include <cli/callbacks.hpp>
#include <cli/glob.hpp>

namespace cli { namespace parser { namespace shellparser
{
    namespace qi = boost::spirit::qi;
    namespace iso8859_1 = boost::spirit::iso8859_1;

    //
    // Class CommandArguments
    //
    // Stores the information provided by the parser ShellParser about the
    // command specified.
    //

    struct VariableAssignment
    {
        std::string name;
        std::string value;
    };

    struct StdioRedirection
    {
        enum TypeOfRedirection
        {
            TRUNCATED_INPUT,    // command <filename
            TRUNCATED_OUTPUT,   // command >filename
            APPENDED_OUTPUT     // command >>filename
        };

        TypeOfRedirection type;
        std::string argument;
    };

    struct CommandArguments
    {
        enum TypeOfTerminator
        {
            NORMAL,             // command ;
            BACKGROUNDED,       // command &
            PIPED               // command1 | command2
        };

        std::vector<VariableAssignment> variables;
        std::vector<std::string> arguments;
        std::vector<StdioRedirection> redirections;
        TypeOfTerminator terminator;

        CommandArguments() : terminator(NORMAL) {}

        std::string getCommandName() const
            { return arguments.empty() ? std::string() : arguments[0]; }
    };

    //
    // Overload insertion operator (<<) for class CommandArguments.
    // It is required to debug the parser rules.
    //

    template <typename CharT, typename Traits>
    std::basic_ostream<CharT, Traits>&
    operator<<(std::basic_ostream<CharT, Traits>& out,
        const CommandArguments& arguments)
    {
        return out << "{variables: "    << arguments.variables
                  << ", arguments: "    << arguments.arguments
                  << ", redirections: " << arguments.redirections
                  << ", terminator: "   << arguments.terminator << '}';
    }

    template <typename CharT, typename Traits>
    std::basic_ostream<CharT, Traits>&
    operator<<(std::basic_ostream<CharT, Traits>& out,
        const StdioRedirection& redirection)
    {
        return out << "{type: "     << redirection.type
                  << ", argument: " << redirection.argument << '}';
    }

    template <typename CharT, typename Traits>
    std::basic_ostream<CharT, Traits>&
    operator<<(std::basic_ostream<CharT, Traits>& out,
        const VariableAssignment& variable)
    {
        return out << "{name: "  << variable.name
                  << ", value: " << variable.value << '}';
    }

    //
    // Class ShellParser
    //
    // The parser uses ISO-8859 encoding to avoid problems with UTF-8 strings
    // because the Boost.Spirit support of ASCII encoding launches an
    // exceptions when finds 8-bit characters.
    //

    struct ShellParser
        : BoostParserBase<std::string, CommandArguments, iso8859_1::space_type>
    {
        ShellParser();

        //
        // Parser rules
        //

        struct Redirections
            : qi::symbols<char, StdioRedirection::TypeOfRedirection>
        {
            Redirections()
            {
                add
                    ("<",  StdioRedirection::TRUNCATED_INPUT)
                    (">",  StdioRedirection::TRUNCATED_OUTPUT)
                    (">>", StdioRedirection::APPENDED_OUTPUT)
                ;
            }
        } redirectors;

        struct Terminators
            : qi::symbols<char, CommandArguments::TypeOfTerminator>
        {
            Terminators()
            {
                add
                    (";", CommandArguments::NORMAL)
                    ("&", CommandArguments::BACKGROUNDED)
                ;
            }
        } terminators;

        struct Pipe
            : qi::symbols<char, CommandArguments::TypeOfTerminator>
        {
            Pipe()
            {
                add
                    ("|", CommandArguments::PIPED)
                ;
            }
        } pipe;

        qi::rule<IteratorType> eol;
        qi::rule<IteratorType> neol;
        qi::rule<IteratorType, char()> character;
        qi::rule<IteratorType, char()> dereference;
        qi::rule<IteratorType, char()> special;
        qi::rule<IteratorType, char()> escape;
        qi::rule<IteratorType, std::string()> name;
        qi::rule<IteratorType, std::string(), qi::locals<bool> > variable;
        qi::rule<IteratorType, std::string()> quotedString;
        qi::rule<IteratorType, std::string()> doubleQuotedString;
        qi::rule<IteratorType, std::string()> word;
        qi::rule<IteratorType, std::vector<std::string>()> expandedWord;
        qi::rule<IteratorType, std::string()> variableValue;
        qi::rule<IteratorType, void(bool)> unambiguousRedirection;
        qi::rule<IteratorType, std::string(),
            qi::locals<int> > redirectionArgument;
        qi::rule<IteratorType, VariableAssignment()> assignment;
        qi::rule<IteratorType, StdioRedirection(),
            iso8859_1::space_type> redirection;
        qi::rule<IteratorType, CommandArguments(),
            iso8859_1::space_type> command;
        qi::rule<IteratorType, ShellParser::sig_type,
            iso8859_1::space_type> start;

        protected:

            //
            // Hook methods
            //

            std::string variableLookup(const std::string& name);
            std::vector<std::string> pathnameExpansion(
                const std::string& pattern);

        private:

            CLI_DECLARE_CALLBACKS(
                ShellParser,
                (VariableLookupCallback, variableLookupCallback_)
                (PathnameExpansionCallback, pathnameExpansionCallback_)
            )

            //
            // Auxiliary methods
            //

            static std::string globEscape(const std::string& pattern)
                { return glob::Glob::escape(pattern); }

            static std::string stringsJoin(const std::vector<std::string>& v)
                { return boost::algorithm::join(v, std::string(1, ' ')); }

            static void throwParserError(IteratorType const& first,
                IteratorType const& last, IteratorType const& error,
                const boost::spirit::info& info);
    };
}}}

namespace cli { namespace parser
{
    using shellparser::ShellParser;
}}

#endif /* SHELL_PARSER_HPP_ */

max_stars_repo_name: JonathanTrEs/Shell

max_issues_repo_name: JonathanTrEs/Shell

max_forks_repo_name: JonathanTrEs/Shell


text:
#define BOOST_TEST_MODULE "odbc/Mongo.shell.hpp tests"

#include <boost/test/unit_test.hpp>
#include <string>

#include "Shared.hpp"
#include "odbc/Mongo.shell.hpp"

BOOST_AUTO_TEST_SUITE(MongoShell)

BOOST_AUTO_TEST_CASE(MongoShellInsertOne) {

    web::json::value data;
    data["data"] = web::json::value("hello world");

    auto task = yungmongo::insertOne("test", data);
    bool success = task.get();

    BOOST_CHECK_EQUAL(success, false);
}

BOOST_AUTO_TEST_CASE(MongoShellInsertMany) {

    web::json::value data;
    data[0]["data"] = web::json::value("hello world");
    data[1]["data"] = web::json::value("hello world");

    auto task = yungmongo::insertMany("test", data);
    bool success = task.get();

    BOOST_CHECK_EQUAL(success, false);
}

BOOST_AUTO_TEST_CASE(MongoShellUpdateOne) {

    web::json::value filter;
    filter["data"] = web::json::value("hello world");
    web::json::value data;
    data["updated"] = web::json::value(true);
    web::json::value options;
    options["upsert"] = web::json::value(true);

    auto task = yungmongo::updateOne("test", filter, data, options);
    bool success = task.get();

    BOOST_CHECK_EQUAL(success, false);
}

BOOST_AUTO_TEST_CASE(MongoShellUpdateMany) {

    web::json::value filter;
    filter["data"] = web::json::value("hello world");
    web::json::value data;
    data["updated"] = web::json::value(true);
    web::json::value options;
    options["upsert"] = web::json::value(true);

    auto task = yungmongo::updateMany("test", filter, data, options);
    bool success = task.get();

    BOOST_CHECK_EQUAL(success, false);
}

BOOST_AUTO_TEST_CASE(MongoShellFindOne) {

    web::json::value filter = web::json::value::parse("{}");
    web::json::value options = web::json::value::parse("{}");

    auto task = yungmongo::findOne("test", filter, options);
    web::json::value data = task.get();

    web::json::value compare = web::json::value::parse("{}");

    BOOST_CHECK_EQUAL(data.is_object(), compare.is_object());
}

BOOST_AUTO_TEST_CASE(MongoShellFindMany) {

    web::json::value filter = web::json::value::parse("{}");
    web::json::value options = web::json::value::parse("{}");

    auto task = yungmongo::findMany("test", filter, options);
    web::json::value data = task.get();

    BOOST_CHECK_EQUAL(data.is_array(), true);
    BOOST_CHECK_EQUAL(data.as_array().size(), 0);
}

BOOST_AUTO_TEST_CASE(MongoShellDeleteOne) {

    web::json::value filter;
    filter["data"] = web::json::value("hello world");

    auto task = yungmongo::deleteOne("test", filter);
    bool success = task.get();

    BOOST_CHECK_EQUAL(success, false);
}

BOOST_AUTO_TEST_CASE(MongoShellDeleteMany) {

    web::json::value filter;
    filter["data"] = web::json::value("hello world");

    auto task = yungmongo::deleteMany("test", filter);
    bool success = task.get();

    BOOST_CHECK_EQUAL(success, false);
}

BOOST_AUTO_TEST_SUITE_END()

max_stars_repo_name: ChrisCates/YungPOCO

max_issues_repo_name: ChrisCates/YungCPP

max_forks_repo_name: ChrisCates/YungCPP


text:
/**
 *  @file
 *  @copyright defined in eos/LICENSE.txt
 */
#include <boost/test/unit_test.hpp>

#include "../../common/database_fixture.hpp"

#include <rate_limit_auth/rate_limit_auth.wast.hpp>
#include <currency/currency.wast.hpp>

using namespace eos;
using namespace chain;

BOOST_AUTO_TEST_SUITE(wasm_tests)

//Test rate limiting with single authority
BOOST_FIXTURE_TEST_CASE(rate_limit_single_authority_test, testing_fixture)
{ try {
      Make_Blockchain(chain);
      chain.produce_blocks(10);
      Make_Account(chain, currency);
      Make_Account(chain, test1);
      Make_Account(chain, test2);
      chain.produce_blocks(1);

      types::setcode handler;
      handler.account = "currency";

      auto wasm = testing_blockchain::assemble_wast( currency_wast );
      handler.code.resize(wasm.size());
      memcpy( handler.code.data(), wasm.data(), wasm.size() );

      {
         eos::chain::SignedTransaction trx;
         trx.scope = {"currency"};
         trx.messages.resize(1);
         trx.messages[0].code = config::EosContractName;
         trx.messages[0].authorization.emplace_back(types::AccountPermission{"currency","active"});
         transaction_set_message(trx, 0, "setcode", handler);
         trx.expiration = chain.head_block_time() + 100;
         transaction_set_reference_block(trx, chain.head_block_id());
         chain.push_transaction(trx);
         chain.produce_blocks(1);

         trx.scope = sort_names({"test1","currency"});
         trx.messages.clear();
         transaction_emplace_message(trx, "currency",
                            vector<types::AccountPermission>{ {"currency","active"} },
                            "transfer", types::transfer{"currency", "test1", 10000000,""});
         chain.push_transaction(trx);

         trx.scope = sort_names({"test2","currency"});
         trx.messages.clear();
         transaction_emplace_message(trx, "currency",
                            vector<types::AccountPermission>{ {"currency","active"} },
                            "transfer", types::transfer{"currency", "test2", 10000000,""});
         chain.push_transaction(trx);
         chain.produce_blocks(1);
      }

      eos::chain::SignedTransaction trx;
      trx.scope = sort_names({"test1","inita"});
      trx.expiration = chain.head_block_time() + 100;
      transaction_set_reference_block(trx, chain.head_block_id());

      eos::chain::SignedTransaction trx2;
      trx2.scope = sort_names({"test2","inita"});
      trx2.expiration = chain.head_block_time() + 100;
      transaction_set_reference_block(trx2, chain.head_block_id());

      for (uint32_t i = 0; i < 1800; ++i)
      {
         trx.messages.clear();
         transaction_emplace_message(trx, "currency",
                            vector<types::AccountPermission>{ {"test1","active"} },
                            "transfer", types::transfer{"test1", "inita", 1+i,""});
         chain.push_transaction(trx);

         trx2.messages.clear();
         transaction_emplace_message(trx2, "currency",
                            vector<types::AccountPermission>{ {"test2","active"} },
                            "transfer", types::transfer{"test2", "inita", 1+i,""});
         chain.push_transaction(trx2);
      }

      try
      {
         transaction_emplace_message(trx, "currency",
                            vector<types::AccountPermission>{ {"inita","active"} },
                            "transfer", types::transfer{"inita", "test1", 10,""});
         chain.push_transaction(trx);
         BOOST_FAIL("Should have gotten tx_msgs_exceeded exception.");
      }
      catch (const tx_msgs_exceeded& ex)
      {
      }

      try
      {
         transaction_emplace_message(trx2, "currency",
                            vector<types::AccountPermission>{ {"inita","active"} },
                            "transfer", types::transfer{"inita", "test2", 10,""});
         chain.push_transaction(trx2);
         BOOST_FAIL("Should have gotten tx_msgs_exceeded exception.");
      }
      catch (const tx_msgs_exceeded& ex)
      {
      }

} FC_LOG_AND_RETHROW() }

/*
//Test rate limiting with multiple authorities
BOOST_FIXTURE_TEST_CASE(rate_limit_multi_authority_test, testing_fixture)
{
   struct Auths2
   {
      AccountName       acct1;
      AccountName       acct2;
   };

   struct Auths3
   {
      AccountName       acct1;
      AccountName       acct2;
      AccountName       acct3;
   };

   const char* struct_abi = R"=====(
   {
       "types": [],
       "structs": [{
          "name": "Auths2",
          "fields": {
            "acct1": "UInt64",
            "acct2": "UInt64"
          }
       },{
          "name": "Auths23",
          "fields": {
            "acct1": "UInt64",
            "acct2": "UInt64",
            "acct3": "UInt64"
          }
       }],
       "actions": [],
       "tables": []
   }
   )=====";

   Make_Blockchain(chain);
   chain.produce_blocks(10);
   Make_Account(chain, currency);
   Make_Account(chain, test1);
   Make_Account(chain, test2);
   Make_Account(chain, test3);
   Make_Account(chain, test4);
   chain.produce_blocks(1);

   types::setcode handler;
   handler.account = "currency";

   auto wasm = testing_blockchain::assemble_wast( currency_wast );
   handler.code.resize(wasm.size());
   memcpy( handler.code.data(), wasm.data(), wasm.size() );

   types::setcode handler2;
   handler2.account = "test1";
   handler2.abi = fc::json::from_string(struct_abi).as<types::Abi>();

   auto wasm2 = testing_blockchain::assemble_wast( rate_limit_auth_wast );
   handler2.code.resize(wasm2.size());
   memcpy( handler2.code.data(), wasm2.data(), wasm2.size() );

   {
      eos::chain::SignedTransaction trx;
      trx.scope = {"currency"};
      trx.messages.resize(1);
      trx.messages[0].code = config::EosContractName;
      trx.messages[0].authorization.emplace_back(types::AccountPermission{"currency","active"});
      transaction_set_message(trx, 0, "setcode", handler);
      trx.expiration = chain.head_block_time() + 100;
      transaction_set_reference_block(trx, chain.head_block_id());
      chain.push_transaction(trx);
      chain.produce_blocks(1);
      trx.scope = sort_names({"test1","currency"});
      trx.messages.clear();
      transaction_emplace_message(trx, "currency",
                         vector<types::AccountPermission>{ {"currency","active"} },
                         "transfer", types::transfer{"currency", "test1", 10000000,""});
      chain.push_transaction(trx);

      trx.scope = sort_names({"test2","currency"});
      trx.messages.clear();
      transaction_emplace_message(trx, "currency",
                         vector<types::AccountPermission>{ {"currency","active"} },
                         "transfer", types::transfer{"currency", "test2", 10000000,""});
      chain.push_transaction(trx);

      trx.scope = sort_names({"test3","currency"});
      trx.messages.clear();
      transaction_emplace_message(trx, "currency",
                         vector<types::AccountPermission>{ {"currency","active"} },
                         "transfer", types::transfer{"currency", "test2", 10000000,""});
      chain.push_transaction(trx);
      chain.produce_blocks(1);
   }

   {
      eos::chain::SignedTransaction trx;
      trx.scope = {"test1"};
      trx.messages.resize(1);
      trx.messages[0].code = config::EosContractName;
      trx.messages[0].authorization.emplace_back(types::AccountPermission{"test1","active"});
      transaction_set_message(trx, 0, "setcode", handler2);
      trx.expiration = chain.head_block_time() + 100;
      transaction_set_reference_block(trx, chain.head_block_id());
      chain.push_transaction(trx);
      chain.produce_blocks(1);
   }

   eos::chain::SignedTransaction trx;
   trx.scope = sort_names({"test1","test2"});
   trx.expiration = chain.head_block_time() + 100;
   transaction_set_reference_block(trx, chain.head_block_id());

   eos::chain::SignedTransaction trx2;
   trx2.scope = sort_names({"test1","test2","test3"});
   trx2.expiration = chain.head_block_time() + 100;
   transaction_set_reference_block(trx2, chain.head_block_id());

   eos::chain::SignedTransaction trx3;
   trx3.scope = sort_names({"test3","test4"});
   trx3.expiration = chain.head_block_time() + 100;
   transaction_set_reference_block(trx3, chain.head_block_id());

   for (uint32_t i = 0; i < 1; ++i)
   {
      trx.messages.clear();
      transaction_emplace_message(trx, "test1",
                         vector<types::AccountPermission>{ {"test1","active"},{"test2","active"} },
                         "auths2", Auths2{"test1", "test2"});
      chain.push_transaction(trx);

      trx2.messages.clear();
      transaction_emplace_message(trx2, "currency",
                         vector<types::AccountPermission>{ {"test1","active"},{"test2","active"},{"test3","active"} },
                         "auths3", Auths3{"test1", "test2", "test3"});
      chain.push_transaction(trx2);
   }
}
*/

BOOST_AUTO_TEST_SUITE_END()