text:
#include <utility>

/**
 *  @file
 *  @copyright defined in eos/LICENSE
 */
#include <eosio/http_plugin/http_plugin.hpp>
#include <eosio/http_plugin/local_endpoint.hpp>
#include <eosio/chain/exceptions.hpp>

#include <fc/network/ip.hpp>
#include <fc/log/logger_config.hpp>
#include <fc/reflect/variant.hpp>
#include <fc/io/json.hpp>
#include <fc/crypto/openssl.hpp>

#include <boost/optional.hpp>

#include <thread>
#include <memory>
#include <regex>

namespace eosio {

   static appbase::abstract_plugin& _http_plugin = app().register_plugin<http_plugin>();

   namespace asio = boost::asio;

   using std::unordered_map;
   using std::vector;
   using std::unordered_set;
   using std::string;
   using std::regex;
   using boost::optional;
   using boost::asio::ip::tcp;
   using boost::asio::ip::address_v4;
   using boost::asio::ip::address_v6;
   using std::shared_ptr;
   using websocketpp::connection_hdl;
   using namespace websocketpp::close;
   using local_socket_endpoint = asio::local::stream_protocol::endpoint;

   static http_plugin_defaults current_http_plugin_defaults;

   void http_plugin::set_defaults(const http_plugin_defaults config) {
      current_http_plugin_defaults = config;
   }

   namespace http_config {
       struct asio_local_with_stub_log : public websocketpp::config::asio {
           typedef asio_local_with_stub_log type;
           typedef asio base;

           typedef base::concurrency_type concurrency_type;

           typedef base::request_type request_type;
           typedef base::response_type response_type;

           typedef base::message_type message_type;
           typedef base::con_msg_manager_type con_msg_manager_type;
           typedef base::endpoint_msg_manager_type endpoint_msg_manager_type;

           typedef websocketpp::log::stub elog_type;
           typedef websocketpp::log::stub alog_type;

           typedef base::rng_type rng_type;

           struct transport_config : public base::transport_config {
               typedef type::concurrency_type concurrency_type;
               typedef type::alog_type alog_type;
               typedef type::elog_type elog_type;
               typedef type::request_type request_type;
               typedef type::response_type response_type;
               typedef websocketpp::transport::asio::basic_socket::local_endpoint socket_type;
           };

           typedef websocketpp::transport::asio::local_endpoint<transport_config> transport_type;
       };
   }

   using websocket_server_type = websocketpp::server<http_config::asio_with_stub_log<basic_socket_endpoint>>;
   using websocket_server_tls_type = websocketpp::server<http_config::asio_with_stub_log<tls_socket_endpoint>>;
   using websocket_local_server_type = websocketpp::server<http_config::asio_local_with_stub_log>;
   using ssl_context_ptr = websocketpp::lib::shared_ptr<websocketpp::lib::asio::ssl::context>;

#define DEFINE_ENABLE_IF_TEMPLATE_GETTERS(first, second, getter_name)                                       \
   template<typename SocketType>                                                                            \
   typename std::enable_if<std::is_same<SocketType, basic_socket_endpoint>::value, decltype(first) &>::type \
   getter_name() {                                                                                \
      return first;                                                                                \
   }                                                                                \
                                                                                \
   template<typename SocketType>                                                                            \
   typename std::enable_if<std::is_same<SocketType, tls_socket_endpoint>::value, decltype(second) &>::type  \
   getter_name() {                                                                                \
      return second;                                                                                \
   }                                                                                \

   static bool verbose_http_errors = false;

   class http_plugin_impl {
      template<typename SocketType>
      struct ws_connection_equal {
         bool operator()(const ws_connection<SocketType> &lhs, const ws_connection<SocketType> &rhs) const {
            return lhs.get() == rhs.get();
         }
      };

      template<typename SocketType>
      struct ws_connection_hash {
         size_t operator()(const ws_connection<SocketType> &conn) const {
            return reinterpret_cast<size_t>(conn.get());
         }
      };

      template<typename SocketType>
      using ws_connection_to_message_handler_map =
              std::unordered_map<ws_connection<SocketType>, ws_message_handler<SocketType>,
                                 ws_connection_hash<SocketType>, ws_connection_equal<SocketType>>;

      public:
         unordered_map<string, ws_message_handler<basic_socket_endpoint>> ws_message_handlers;
         unordered_map<string, ws_message_handler<tls_socket_endpoint>> wss_message_handlers;
         DEFINE_ENABLE_IF_TEMPLATE_GETTERS(ws_message_handlers, wss_message_handlers, get_websocket_msghandler_map);

         ws_connection_to_message_handler_map<basic_socket_endpoint> ws_connection_to_msgh_map;
         ws_connection_to_message_handler_map<tls_socket_endpoint> wss_connection_to_msgh_map;
         DEFINE_ENABLE_IF_TEMPLATE_GETTERS(ws_connection_to_msgh_map, wss_connection_to_msgh_map, get_ws_connection_to_msghandler_map);

         ws_connection_termination_handler<basic_socket_endpoint> plain_ws_connection_term_handler;
         ws_connection_termination_handler<tls_socket_endpoint> tls_ws_connection_term_handler;
         DEFINE_ENABLE_IF_TEMPLATE_GETTERS(plain_ws_connection_term_handler, tls_ws_connection_term_handler, get_ws_connection_termination_handler);

         unordered_map<string, url_handler> url_handlers;
         optional<tcp::endpoint>  listen_endpoint;
         string                   access_control_allow_origin;
         string                   access_control_allow_headers;
         string                   access_control_max_age;
         bool                     access_control_allow_credentials = false;
         size_t                   max_body_size;

         websocket_server_type    server;

         optional<tcp::endpoint>  https_listen_endpoint;
         string                   https_cert_chain;
         string                   https_key;

         websocket_server_tls_type https_server;

         optional<local_socket_endpoint> unix_endpoint;
         websocket_local_server_type unix_server;

         bool                     validate_host;
         unordered_set<string>    valid_hosts;

         unordered_set<ws_connection<basic_socket_endpoint>> http_connections;
         unordered_set<ws_connection<tls_socket_endpoint>> https_connections;
         DEFINE_ENABLE_IF_TEMPLATE_GETTERS(http_connections, https_connections, get_connection_set);

         /* just for compile purpose */
         unordered_set<websocketpp::server<http_config::asio_local_with_stub_log>::connection_ptr> local_connections;
         template<typename SocketType>
         typename std::enable_if<std::is_same<SocketType, local_socket_endpoint>::value, decltype(local_connections) &>::type
         get_connection_set() {
            return local_connections;
         }

         uint32_t                 idle_connection_timeout_ms;
         uint32_t                 max_connections;

         bool is_max_connections_reached() {
            return max_connections > 0 &&
                   (http_connections.size() + https_connections.size() + ws_connection_to_msgh_map.size() + wss_connection_to_msgh_map.size())
                    >= max_connections;
         }

         template <typename HttpConfigType, typename SocketType>
         bool is_already_connected(typename websocketpp::server<HttpConfigType>::connection_ptr ws_conn) {
            if (std::is_same<SocketType, local_socket_endpoint>::value) return true;
            if (max_connections == 0) return true;

            auto &connection_set = get_connection_set<SocketType>();
            return connection_set.find(ws_conn) != connection_set.end();
         }

         template <typename HttpConfigType, typename SocketType>
         void register_keep_alive_http_connection(typename websocketpp::server<HttpConfigType>::connection_ptr ws_conn) {
            if (std::is_same<SocketType, local_socket_endpoint>::value) return;
            if (max_connections == 0) return;

            auto &connection_set = get_connection_set<SocketType>();
            connection_set.insert(ws_conn);
         }

         template <typename HttpConfigType, typename SocketType>
         void unregister_keep_alive_http_connection(typename websocketpp::server<HttpConfigType>::connection_ptr ws_conn) {
            if (std::is_same<SocketType, local_socket_endpoint>::value) return;
            if (max_connections == 0) return;

            auto &connection_set = get_connection_set<SocketType>();
            connection_set.erase(ws_conn);
         }

         string                   unix_socket_path_option_name     = "unix-socket-path";
         string                   http_server_address_option_name  = "http-server-address";
         string                   https_server_address_option_name = "https-server-address";

         bool host_port_is_valid( const std::string& header_host_port, const string& endpoint_local_host_port ) {
            return !validate_host || header_host_port == endpoint_local_host_port || valid_hosts.find(header_host_port) != valid_hosts.end();
         }

         bool host_is_valid( const std::string& host, const string& endpoint_local_host_port, bool secure) {
            if (!validate_host) {
               return true;
            }

            // normalise the incoming host so that it always has the explicit port
            static auto has_port_expr = regex("[^:]:[0-9]+$"); /// ends in :<number> without a preceeding colon which implies ipv6
            if (std::regex_search(host, has_port_expr)) {
               return host_port_is_valid( host, endpoint_local_host_port );
            } else {
               // according to RFC 2732 ipv6 addresses should always be enclosed with brackets so we shouldn't need to special case here
               return host_port_is_valid( host + ":" + std::to_string(secure ? websocketpp::uri_default_secure_port : websocketpp::uri_default_port ), endpoint_local_host_port);
            }
         }

         ssl_context_ptr on_tls_init(const websocketpp::connection_hdl &hdl) {
            ssl_context_ptr ctx = websocketpp::lib::make_shared<websocketpp::lib::asio::ssl::context>(asio::ssl::context::sslv23_server);

            try {
               ctx->set_options(asio::ssl::context::default_workarounds |
                                asio::ssl::context::no_sslv2 |
                                asio::ssl::context::no_sslv3 |
                                asio::ssl::context::no_tlsv1 |
                                asio::ssl::context::no_tlsv1_1 |
                                asio::ssl::context::single_dh_use);

               ctx->use_certificate_chain_file(https_cert_chain);
               ctx->use_private_key_file(https_key, asio::ssl::context::pem);

               //going for the A+! Do a few more things on the native context to get ECDH in use

               fc::ec_key ecdh = EC_KEY_new_by_curve_name(NID_secp384r1);
               if (!ecdh)
                  EOS_THROW(chain::http_exception, "Failed to set NID_secp384r1");
               if(SSL_CTX_set_tmp_ecdh(ctx->native_handle(), (EC_KEY*)ecdh) != 1)
                  EOS_THROW(chain::http_exception, "Failed to set ECDH PFS");

               if(SSL_CTX_set_cipher_list(ctx->native_handle(), \
                  "EECDH+ECDSA+AESGCM:EECDH+aRSA+AESGCM:EECDH+ECDSA+SHA384:EECDH+ECDSA+SHA256:AES256:" \
                  "!DHE:!RSA:!AES128:!RC4:!DES:!3DES:!DSS:!SRP:!PSK:!EXP:!MD5:!LOW:!aNULL:!eNULL") != 1)
                  EOS_THROW(chain::http_exception, "Failed to set HTTPS cipher list");
            } catch (const fc::exception& e) {
               elog("https server initialization error: ${w}", ("w", e.to_detail_string()));
               throw;
            } catch(std::exception& e) {
               elog("https server initialization error: ${w}", ("w", e.what()));
               throw;
            }

            return ctx;
         }

         template<class HttpConfigType>
         static void handle_exception(typename websocketpp::server<HttpConfigType>::connection_ptr con) {
            string err = "Internal Service error, http: ";
            try {
               con->set_status( websocketpp::http::status_code::internal_server_error );
               try {
                  throw;
               } catch (const fc::exception& e) {
                  err += e.to_detail_string();
                  elog( "${e}", ("e", err));
                  error_results results{websocketpp::http::status_code::internal_server_error,
                                        "Internal Service Error", error_results::error_info(e, verbose_http_errors )};
                  con->set_body( fc::json::to_string( results ));
               } catch (const std::exception& e) {
                  err += e.what();
                  elog( "${e}", ("e", err));
                  error_results results{websocketpp::http::status_code::internal_server_error,
                                        "Internal Service Error", error_results::error_info(fc::exception( FC_LOG_MESSAGE( error, e.what())), verbose_http_errors )};
                  con->set_body( fc::json::to_string( results ));
               } catch (...) {
                  err += "Unknown Exception";
                  error_results results{websocketpp::http::status_code::internal_server_error,
                                        "Internal Service Error",
                                        error_results::error_info(fc::exception( FC_LOG_MESSAGE( error, "Unknown Exception" )), verbose_http_errors )};
                  con->set_body( fc::json::to_string( results ));
               }
            } catch (...) {
               con->set_body( R"xxx({"message": "Internal Server Error"})xxx" );
               std::cerr << "Exception attempting to handle exception: " << err << std::endl;
            }
         }

         template<class HttpConfigType>
         bool allow_host(const typename HttpConfigType::request_type& req, typename websocketpp::server<HttpConfigType>::connection_ptr con) {
            bool is_secure = con->get_uri()->get_secure();
            const auto& local_endpoint = con->get_socket().lowest_layer().local_endpoint();
            auto local_socket_host_port = local_endpoint.address().to_string() + ":" + std::to_string(local_endpoint.port());

            const auto& host_str = req.get_header("Host");
            if (host_str.empty() || !host_is_valid(host_str, local_socket_host_port, is_secure)) {
               con->set_status(websocketpp::http::status_code::bad_request);
               return false;
            }
            return true;
         }

         template<class T, class SocketType> // T == HttpConfigType
         void handle_http_request(typename websocketpp::server<T>::connection_ptr con) {
            try {
               bool is_already_keep_alive = is_already_connected<T, SocketType>(con);
               if (!is_already_keep_alive && is_max_connections_reached()) {
                  con->set_status(websocketpp::http::status_code::too_many_requests);
                  return;
               }

               auto& req = con->get_request();

               if(!allow_host<T>(req, con))
                  return;

               if( !access_control_allow_origin.empty()) {
                  con->append_header( "Access-Control-Allow-Origin", access_control_allow_origin );
               }
               if( !access_control_allow_headers.empty()) {
                  con->append_header( "Access-Control-Allow-Headers", access_control_allow_headers );
               }
               if( !access_control_max_age.empty()) {
                  con->append_header( "Access-Control-Max-Age", access_control_max_age );
               }
               if( access_control_allow_credentials ) {
                  con->append_header( "Access-Control-Allow-Credentials", "true" );
               }

               if (!is_already_keep_alive) {
                  register_keep_alive_http_connection<T, SocketType>(con);
               }

               if(req.get_method() == "OPTIONS") {
                  con->set_status(websocketpp::http::status_code::ok);
                  return;
               }

               con->append_header( "Content-type", "application/json" );
               auto body = con->get_request_body();
               auto resource = con->get_resource();
               auto handler_itr = url_handlers.find( resource );
               if( handler_itr != url_handlers.end()) {
                  con->defer_http_response();
                  handler_itr->second( resource, body, [con]( auto code, auto&& body ) {
                     con->set_body( std::move( body ));
                     con->set_status( websocketpp::http::status_code::value( code ));
                     con->send_http_response();
                  } );

               } else {
                  error_results results{websocketpp::http::status_code::not_found,
                                        "Not Found", error_results::error_info(fc::exception( FC_LOG_MESSAGE( error, "Unknown Endpoint" )), verbose_http_errors )};
                  con->set_body( fc::json::to_string( results ));
                  con->set_status( websocketpp::http::status_code::not_found );
               }
            } catch( ... ) {
               handle_exception<T>( con );
            }
         }

         template<typename HttpConfigType, typename T>
         void handle_websocket_open(ws_connection<T> conn) {
            auto resource = conn->get_resource();

            auto handler_map = get_websocket_msghandler_map<T>();
            auto handler_itr = handler_map.find(resource);
            if (handler_itr != handler_map.end()) {
               bool is_connected = is_already_connected<HttpConfigType, T>(conn);
               if (!is_connected && is_max_connections_reached()) {
                  error_results results{websocketpp::http::status_code::too_many_requests,
                                        "Too many connections",
                                        error_results::error_info(fc::exception(FC_LOG_MESSAGE(error, "Too many connections")),
                                                                  verbose_http_errors)};
                  conn->close(status::internal_endpoint_error, fc::json::to_string(results));
                  return;
               }

               auto &conn_to_handler_map = get_ws_connection_to_msghandler_map<T>();
               conn_to_handler_map.insert(std::make_pair(conn, handler_itr->second));
            } else {
               error_results results{websocketpp::http::status_code::not_found,
                                     "Not Found",
                                     error_results::error_info(fc::exception(FC_LOG_MESSAGE(error, "Unknown Endpoint")),
                                                               verbose_http_errors)};
               conn->close(status::internal_endpoint_error, fc::json::to_string(results));
            }
         }

         template<typename HttpConfigType, typename T>
         void handle_websocket_close_or_fail(ws_connection<T> conn) {
            if (conn->is_http_connection()) {
               unregister_keep_alive_http_connection<HttpConfigType, T>(conn);
            } else {
               auto &conn_to_handler_map = get_ws_connection_to_msghandler_map<T>();
               conn_to_handler_map.erase(conn);

               auto &term_handler = get_ws_connection_termination_handler<T>();
               if (term_handler) {
                  term_handler(conn);
               }
            }
         }

         template<typename T>
         void handle_websocket_message(ws_connection<T> conn, ws_message<T> msg) {
            //dlog("websocket message handler called for ${h} with ${uri}", ("h", conn->get_host())("uri", conn->get_resource()));

            auto &conn_to_handler_map = get_ws_connection_to_msghandler_map<T>();
            try {
               auto handler_itr = conn_to_handler_map.find(conn);
               if (handler_itr != conn_to_handler_map.end()) {
                  handler_itr->second(conn, msg);
               }
            } catch (const fc::exception& e) {
               auto err = e.to_detail_string();
               elog("${e}", ("e", err));
               conn->close(status::internal_endpoint_error, err);
            } catch (const std::exception &e) {
               elog("${e}", ("e", e.what()));
               conn->close(status::internal_endpoint_error, e.what());
            } catch (...) {
               elog("${e}", ("e", "Unknown error"));
               conn->close(status::internal_endpoint_error, "Unknown error");
            }
         }

         template<class T>
         void create_server_for_endpoint(const tcp::endpoint& ep, websocketpp::server<http_config::asio_with_stub_log<T>>& ws) {
            ws.clear_access_channels(websocketpp::log::alevel::all);
            ws.init_asio(&app().get_io_service());
            ws.set_reuse_addr(true);
            ws.set_max_http_body_size(max_body_size);
            ws.set_open_handshake_timeout(idle_connection_timeout_ms);
            ws.set_http_handler([&](connection_hdl hdl) {
               handle_http_request<http_config::asio_with_stub_log<T>, T>(ws.get_con_from_hdl(hdl));
            });
            ws.set_open_handler([&](connection_hdl hdl) {
               handle_websocket_open<http_config::asio_with_stub_log<T>, T>(ws.get_con_from_hdl(hdl));
            });
            ws.set_close_handler([&](connection_hdl hdl) {
               handle_websocket_close_or_fail<http_config::asio_with_stub_log<T>, T>(ws.get_con_from_hdl(hdl));
            });
            ws.set_fail_handler([&](connection_hdl hdl) {
               handle_websocket_close_or_fail<http_config::asio_with_stub_log<T>, T>(ws.get_con_from_hdl(hdl));
            });
            ws.set_message_handler([&](connection_hdl hdl, ws_message<T> msg) {
               handle_websocket_message<T>(ws.get_con_from_hdl(hdl), msg);
            });
         }

         void add_aliases_for_endpoint( const tcp::endpoint& ep, const string &host, const string &port ) {
            auto resolved_port_str = std::to_string(ep.port());
            valid_hosts.emplace(host + ":" + port);
            valid_hosts.emplace(host + ":" + resolved_port_str);
         }

         void mangle_option_names() {
            if(current_http_plugin_defaults.address_config_prefix.empty())
               return;
            unix_socket_path_option_name.insert(0, current_http_plugin_defaults.address_config_prefix+"-");
            http_server_address_option_name.insert(0, current_http_plugin_defaults.address_config_prefix+"-");
            https_server_address_option_name.insert(0, current_http_plugin_defaults.address_config_prefix+"-");
         }
   };

   template<>
   bool http_plugin_impl::allow_host<http_config::asio_local_with_stub_log>(
           const http_config::asio_local_with_stub_log::request_type& req,
           websocketpp::server<http_config::asio_local_with_stub_log>::connection_ptr con) {
      return true;
   }

   http_plugin::http_plugin():my(new http_plugin_impl()){}
   http_plugin::~http_plugin(){}

   void http_plugin::set_program_options(options_description&, options_description& cfg) {
      my->mangle_option_names();
      if(current_http_plugin_defaults.default_unix_socket_path.length())
         cfg.add_options()
            (my->unix_socket_path_option_name.c_str(), bpo::value<string>()->default_value(current_http_plugin_defaults.default_unix_socket_path),
             "The filename (relative to data-dir) to create a unix socket for HTTP RPC; set blank to disable.");

      if(current_http_plugin_defaults.default_http_port)
         cfg.add_options()
            (my->http_server_address_option_name.c_str(), bpo::value<string>()->default_value("127.0.0.1:" + std::to_string(current_http_plugin_defaults.default_http_port)),
             "The local IP and port to listen for incoming http connections; set blank to disable.");
      else
         cfg.add_options()
            (my->http_server_address_option_name.c_str(), bpo::value<string>(),
             "The local IP and port to listen for incoming http connections; leave blank to disable.");

      cfg.add_options()
            (my->https_server_address_option_name.c_str(), bpo::value<string>(),
             "The local IP and port to listen for incoming https connections; leave blank to disable.")

            ("https-certificate-chain-file", bpo::value<string>(),
             "Filename with the certificate chain to present on https connections. PEM format. Required for https.")

            ("https-private-key-file", bpo::value<string>(),
             "Filename with https private key in PEM format. Required for https")

            ("access-control-allow-origin", bpo::value<string>()->notifier([this](const string& v) {
                my->access_control_allow_origin = v;
                ilog("configured http with Access-Control-Allow-Origin: ${o}", ("o", my->access_control_allow_origin));
             }),
             "Specify the Access-Control-Allow-Origin to be returned on each request.")

            ("access-control-allow-headers", bpo::value<string>()->notifier([this](const string& v) {
                my->access_control_allow_headers = v;
                ilog("configured http with Access-Control-Allow-Headers : ${o}", ("o", my->access_control_allow_headers));
             }),
             "Specify the Access-Control-Allow-Headers to be returned on each request.")

            ("access-control-max-age", bpo::value<string>()->notifier([this](const string& v) {
                my->access_control_max_age = v;
                ilog("configured http with Access-Control-Max-Age : ${o}", ("o", my->access_control_max_age));
             }),
             "Specify the Access-Control-Max-Age to be returned on each request.")

            ("access-control-allow-credentials",
             bpo::bool_switch()->notifier([this](bool v) {
                my->access_control_allow_credentials = v;
                if (v) ilog("configured http with Access-Control-Allow-Credentials: true");
             })->default_value(false),
             "Specify if Access-Control-Allow-Credentials: true should be returned on each request.")
            ("max-body-size", bpo::value<uint32_t>()->default_value(1024*1024), "The maximum body size in bytes allowed for incoming RPC requests")
            ("verbose-http-errors", bpo::bool_switch()->default_value(false), "Append the error log to HTTP responses")
            ("http-validate-host", boost::program_options::value<bool>()->default_value(true), "If set to false, then any incoming \"Host\" header is considered valid")
            ("http-alias", bpo::value<std::vector<string>>()->composing(), "Additionaly acceptable values for the \"Host\" header of incoming HTTP requests, can be specified multiple times.  Includes http/s_server_address by default.")
            ("idle-connection-timeout-ms", bpo::value<uint32_t>()->default_value(5000), "Timeout in milliseconds to cut idle HTTP connections out; 0 means infinite")
            ("max-connections", bpo::value<uint32_t>()->default_value(100), "The maximum number of HTTP and WebSocket connections which is allowed to connect and keep alive; 0 means unlimited")
            ;
   }

   void http_plugin::plugin_initialize(const variables_map& options) {
      try {
         my->idle_connection_timeout_ms = options.at("idle-connection-timeout-ms").as<uint32_t>();
         my->max_connections = options.at("max-connections").as<uint32_t>();

         my->validate_host = options.at("http-validate-host").as<bool>();
         if( options.count( "http-alias" )) {
            const auto& aliases = options["http-alias"].as<vector<string>>();
            my->valid_hosts.insert(aliases.begin(), aliases.end());
         }

         tcp::resolver resolver( app().get_io_service());
         if( options.count( my->http_server_address_option_name ) && options.at( my->http_server_address_option_name ).as<string>().length()) {
            string lipstr = options.at( my->http_server_address_option_name ).as<string>();
            string host = lipstr.substr( 0, lipstr.find( ':' ));
            string port = lipstr.substr( host.size() + 1, lipstr.size());
            tcp::resolver::query query( tcp::v4(), host.c_str(), port.c_str());
            try {
               my->listen_endpoint = *resolver.resolve( query );
               ilog( "configured http to listen on ${h}:${p}", ("h", host)( "p", port ));
            } catch ( const boost::system::system_error& ec ) {
               elog( "failed to configure http to listen on ${h}:${p} (${m})",
                     ("h", host)( "p", port )( "m", ec.what()));
               throw;
            }

            // add in resolved hosts and ports as well
            if (my->listen_endpoint) {
               my->add_aliases_for_endpoint(*my->listen_endpoint, host, port);
            }
         }

         if( options.count( my->unix_socket_path_option_name ) && !options.at( my->unix_socket_path_option_name ).as<string>().empty()) {
            boost::filesystem::path sock_path = options.at(my->unix_socket_path_option_name).as<string>();
            if (sock_path.is_relative())
               sock_path = app().data_dir() / sock_path;
            my->unix_endpoint = asio::local::stream_protocol::endpoint(sock_path.string());
         }

         if( options.count( "https-server-address" ) && options.at( "https-server-address" ).as<string>().length()) {
            EOS_ASSERT(options.count("https-certificate-chain-file") &&
                       !options.at("https-certificate-chain-file").as<string>().empty(),
                       chain::plugin_config_exception,
                       "https-certificate-chain-file is required for HTTPS");
            EOS_ASSERT(options.count("https-private-key-file") &&
                       !options.at("https-private-key-file").as<string>().empty(),
                       chain::plugin_config_exception,
                       "https-private-key-file is required for HTTPS");

            string lipstr = options.at( my->https_server_address_option_name ).as<string>();
            string host = lipstr.substr( 0, lipstr.find( ':' ));
            string port = lipstr.substr( host.size() + 1, lipstr.size());
            tcp::resolver::query query( tcp::v4(), host.c_str(), port.c_str());
            try {
               my->https_listen_endpoint = *resolver.resolve( query );
               ilog( "configured https to listen on ${h}:${p} (TLS configuration will be validated momentarily)",
                     ("h", host)( "p", port ));
               my->https_cert_chain = options.at( "https-certificate-chain-file" ).as<string>();
               my->https_key = options.at( "https-private-key-file" ).as<string>();
            } catch ( const boost::system::system_error& ec ) {
               elog( "failed to configure https to listen on ${h}:${p} (${m})",
                     ("h", host)( "p", port )( "m", ec.what()));
               throw;
            }

            // add in resolved hosts and ports as well
            if (my->https_listen_endpoint) {
               my->add_aliases_for_endpoint(*my->https_listen_endpoint, host, port);
            }
         }

         my->max_body_size = options.at( "max-body-size" ).as<uint32_t>();
         verbose_http_errors = options.at( "verbose-http-errors" ).as<bool>();

         my->http_connections.clear();
         my->https_connections.clear();
         my->ws_connection_to_msgh_map.clear();
         my->wss_connection_to_msgh_map.clear();
      } FC_LOG_AND_RETHROW()
   }

   void http_plugin::plugin_startup() {
      if(my->listen_endpoint) {
         try {
            my->create_server_for_endpoint(*my->listen_endpoint, my->server);

            ilog("start listening for http requests");
            my->server.listen(*my->listen_endpoint);
            my->server.start_accept();
         } catch ( const fc::exception& e ){
            elog( "http service failed to start: ${e}", ("e",e.to_detail_string()));
            throw;
         } catch ( const std::exception& e ){
            elog( "http service failed to start: ${e}", ("e",e.what()));
            throw;
         } catch (...) {
            elog("error thrown from http io service");
            throw;
         }
      }

      if(my->unix_endpoint) {
         try {
            my->unix_server.clear_access_channels(websocketpp::log::alevel::all);
            my->unix_server.init_asio(&app().get_io_service());
            my->unix_server.set_max_http_body_size(my->max_body_size);
            my->unix_server.listen(*my->unix_endpoint);
            my->unix_server.set_http_handler([&](connection_hdl hdl) {
               my->handle_http_request<http_config::asio_local_with_stub_log, local_socket_endpoint>(my->unix_server.get_con_from_hdl(hdl));
            });
            my->unix_server.start_accept();
         } catch ( const fc::exception& e ){
            elog( "unix socket service failed to start: ${e}", ("e",e.to_detail_string()));
            throw;
         } catch ( const std::exception& e ){
            elog( "unix socket service failed to start: ${e}", ("e",e.what()));
            throw;
         } catch (...) {
            elog("error thrown from unix socket io service");
            throw;
         }
      }

      if(my->https_listen_endpoint) {
         try {
            my->create_server_for_endpoint(*my->https_listen_endpoint, my->https_server);
            my->https_server.set_tls_init_handler([this](websocketpp::connection_hdl hdl) -> ssl_context_ptr{
               return my->on_tls_init(hdl);
            });

            ilog("start listening for https requests");
            my->https_server.listen(*my->https_listen_endpoint);
            my->https_server.start_accept();
         } catch ( const fc::exception& e ){
            elog( "https service failed to start: ${e}", ("e",e.to_detail_string()));
            throw;
         } catch ( const std::exception& e ){
            elog( "https service failed to start: ${e}", ("e",e.what()));
            throw;
         } catch (...) {
            elog("error thrown from https io service");
            throw;
         }
      }
   }

   void http_plugin::plugin_shutdown() {
      if(my->server.is_listening())
         my->server.stop_listening();
      if(my->https_server.is_listening())
         my->https_server.stop_listening();
      if(my->unix_server.is_listening())
         my->unix_server.stop_listening();
   }

   void http_plugin::add_handler(const string& url, const url_handler& handler) {
      ilog( "add api url: ${c}", ("c",url) );
      app().get_io_service().post([=](){
        my->url_handlers.insert(std::make_pair(url,handler));
      });
   }

   void http_plugin::handle_exception( const char *api_name, const char *call_name, const string& body, url_response_callback cb ) {
      try {
         try {
            throw;
         } catch (chain::unknown_block_exception& e) {
            error_results results{400, "Unknown Block", error_results::error_info(e, verbose_http_errors)};
            cb( 400, fc::json::to_string( results ));
         } catch (chain::unsatisfied_authorization& e) {
            error_results results{401, "UnAuthorized", error_results::error_info(e, verbose_http_errors)};
            cb( 401, fc::json::to_string( results ));
         } catch (chain::tx_duplicate& e) {
            error_results results{409, "Conflict", error_results::error_info(e, verbose_http_errors)};
            cb( 409, fc::json::to_string( results ));
         } catch (fc::eof_exception& e) {
            error_results results{422, "Unprocessable Entity", error_results::error_info(e, verbose_http_errors)};
            cb( 422, fc::json::to_string( results ));
            elog( "Unable to parse arguments to ${api}.${call}", ("api", api_name)( "call", call_name ));
            dlog("Bad arguments: ${args}", ("args", body));
         } catch (fc::exception& e) {
            error_results results{500, "Internal Service Error", error_results::error_info(e, verbose_http_errors)};
            cb( 500, fc::json::to_string( results ));
            if (e.code() != chain::greylist_net_usage_exceeded::code_value && e.code() != chain::greylist_cpu_usage_exceeded::code_value) {
               elog( "FC Exception encountered while processing ${api}.${call}",
                     ("api", api_name)( "call", call_name ));
               dlog( "Exception Details: ${e}", ("e", e.to_detail_string()));
            }
         } catch (std::exception& e) {
            error_results results{500, "Internal Service Error", error_results::error_info(fc::exception( FC_LOG_MESSAGE( error, e.what())), verbose_http_errors)};
            cb( 500, fc::json::to_string( results ));
            elog( "STD Exception encountered while processing ${api}.${call}",
                  ("api", api_name)( "call", call_name ));
            dlog( "Exception Details: ${e}", ("e", e.what()));
         } catch (...) {
            error_results results{500, "Internal Service Error",
               error_results::error_info(fc::exception( FC_LOG_MESSAGE( error, "Unknown Exception" )), verbose_http_errors)};
            cb( 500, fc::json::to_string( results ));
            elog( "Unknown Exception encountered while processing ${api}.${call}",
                  ("api", api_name)( "call", call_name ));
         }
      } catch (...) {
         std::cerr << "Exception attempting to handle exception for " << api_name << "." << call_name << std::endl;
      }
   }

   bool http_plugin::is_on_loopback() const {
      return (!my->listen_endpoint || my->listen_endpoint->address().is_loopback()) && (!my->https_listen_endpoint || my->https_listen_endpoint->address().is_loopback());
   }

   bool http_plugin::is_secure() const {
      return (!my->listen_endpoint || my->listen_endpoint->address().is_loopback());
   }

   void http_plugin::add_ws_handler(const string& url, ws_message_handler<basic_socket_endpoint> handler) {
      ilog("add websocket handler: ${c}", ("c", url));
      app().get_io_service().post([=]() {
          my->ws_message_handlers.insert(std::make_pair(url, handler));
      });
   }

   void http_plugin::add_wss_handler(const string& url, ws_message_handler<tls_socket_endpoint> handler) {
      ilog("add secure websocket handler: ${c}", ("c", url));
      app().get_io_service().post([=]() {
          my->wss_message_handlers.insert(std::make_pair(url, handler));
      });
   }

   void http_plugin::set_ws_connection_termination_handler(ws_connection_termination_handler<basic_socket_endpoint> handler) {
      my->plain_ws_connection_term_handler = handler;
   }

   void http_plugin::set_wss_connection_termination_handler(ws_connection_termination_handler<tls_socket_endpoint> handler) {
      my->tls_ws_connection_term_handler = handler;
   }

   bool http_plugin::verbose_errors()const {
      return verbose_http_errors;
   }

}

max_stars_repo_name: InfraBlockchain/infrablockchain

max_issues_repo_name: InfraBlockchain/infrablockchain


text:
// This file is part of libigl, a simple c++ geometry processing library.
//
// Copyright (C) 2014 Daniele Panozzo <daniele.panozzo@gmail.com>, Olga Diamanti <olga.diam@gmail.com>
//
// This Source Code Form is subject to the terms of the Mozilla Public License
// v. 2.0. If a copy of the MPL was not distributed with this file, You can
// obtain one at http://mozilla.org/MPL/2.0/.

#include "comb_cross_field.h"

#include <vector>
#include <deque>
#include <Eigen/Geometry>
#include "per_face_normals.h"
#include "is_border_vertex.h"
#include "rotation_matrix_from_directions.h"

#include "triangle_triangle_adjacency.h"

namespace igl {
  template <typename DerivedV, typename DerivedF>
  class Comb
  {
  public:

    const Eigen::PlainObjectBase<DerivedV> &V;
    const Eigen::PlainObjectBase<DerivedF> &F;
    const Eigen::PlainObjectBase<DerivedV> &PD1;
    const Eigen::PlainObjectBase<DerivedV> &PD2;
    Eigen::PlainObjectBase<DerivedV> N;

  private:
    // internal
    Eigen::PlainObjectBase<DerivedF> TT;
    Eigen::PlainObjectBase<DerivedF> TTi;

  private:

    static inline double Sign(double a){return (double)((a>0)?+1:-1);}

  private:

    // returns the 90 deg rotation of a (around n) most similar to target b
    /// a and b should be in the same plane orthogonal to N
    static inline Eigen::Matrix<typename DerivedV::Scalar, 3, 1> K_PI_new(const Eigen::Matrix<typename DerivedV::Scalar, 3, 1>& a,
                                                                   const Eigen::Matrix<typename DerivedV::Scalar, 3, 1>& b,
                                                                   const Eigen::Matrix<typename DerivedV::Scalar, 3, 1>& n)
    {
      Eigen::Matrix<typename DerivedV::Scalar, 3, 1> c = (a.cross(n)).normalized();
      typename DerivedV::Scalar scorea = a.dot(b);
      typename DerivedV::Scalar scorec = c.dot(b);
      if (fabs(scorea)>=fabs(scorec))
        return a*Sign(scorea);
      else
        return c*Sign(scorec);
    }

  public:
    inline Comb(const Eigen::PlainObjectBase<DerivedV> &_V,
         const Eigen::PlainObjectBase<DerivedF> &_F,
         const Eigen::PlainObjectBase<DerivedV> &_PD1,
         const Eigen::PlainObjectBase<DerivedV> &_PD2
         ):
    V(_V),
    F(_F),
    PD1(_PD1),
    PD2(_PD2)
    {
      igl::per_face_normals(V,F,N);
      igl::triangle_triangle_adjacency(V,F,TT,TTi);
    }
    inline void comb(Eigen::PlainObjectBase<DerivedV> &PD1out,
              Eigen::PlainObjectBase<DerivedV> &PD2out)
    {
//      PD1out = PD1;
//      PD2out = PD2;
      PD1out.setZero(F.rows(),3);PD1out<<PD1;
      PD2out.setZero(F.rows(),3);PD2out<<PD2;

      Eigen::VectorXi mark = Eigen::VectorXi::Constant(F.rows(),false);

      std::deque<int> d;

      d.push_back(0);
      mark(0) = true;

      while (!d.empty())
      {
        int f0 = d.at(0);
        d.pop_front();
        for (int k=0; k<3; k++)
        {
          int f1 = TT(f0,k);
          if (f1==-1) continue;
          if (mark(f1)) continue;

          Eigen::Matrix<typename DerivedV::Scalar, 3, 1> dir0    = PD1out.row(f0);
          Eigen::Matrix<typename DerivedV::Scalar, 3, 1> dir1    = PD1out.row(f1);
          Eigen::Matrix<typename DerivedV::Scalar, 3, 1> n0    = N.row(f0);
          Eigen::Matrix<typename DerivedV::Scalar, 3, 1> n1    = N.row(f1);

          Eigen::Matrix<typename DerivedV::Scalar, 3, 1> dir0Rot = igl::rotation_matrix_from_directions(n0, n1)*dir0;
          dir0Rot.normalize();
          Eigen::Matrix<typename DerivedV::Scalar, 3, 1> targD   = K_PI_new(dir1,dir0Rot,n1);

          PD1out.row(f1)  = targD;
          PD2out.row(f1)  = n1.cross(targD).normalized();

          mark(f1) = true;
          d.push_back(f1);

        }
      }

      // everything should be marked
      for (int i=0; i<F.rows(); i++)
      {
        assert(mark(i));
      }
    }

  };
}
template <typename DerivedV, typename DerivedF>
IGL_INLINE void igl::comb_cross_field(const Eigen::PlainObjectBase<DerivedV> &V,
                                      const Eigen::PlainObjectBase<DerivedF> &F,
                                      const Eigen::PlainObjectBase<DerivedV> &PD1,
                                      const Eigen::PlainObjectBase<DerivedV> &PD2,
                                      Eigen::PlainObjectBase<DerivedV> &PD1out,
                                      Eigen::PlainObjectBase<DerivedV> &PD2out)
{
  igl::Comb<DerivedV, DerivedF> cmb(V, F, PD1, PD2);
  cmb.comb(PD1out, PD2out);
}

#ifdef IGL_STATIC_LIBRARY
// Explicit template specialization
template void igl::comb_cross_field<Eigen::Matrix<double, -1, 3, 0, -1, 3>, Eigen::Matrix<int, -1, 3, 0, -1, 3> >(Eigen::PlainObjectBase<Eigen::Matrix<double, -1, 3, 0, -1, 3> > const&, Eigen::PlainObjectBase<Eigen::Matrix<int, -1, 3, 0, -1, 3> > const&, Eigen::PlainObjectBase<Eigen::Matrix<double, -1, 3, 0, -1, 3> > const&, Eigen::PlainObjectBase<Eigen::Matrix<double, -1, 3, 0, -1, 3> > const&, Eigen::PlainObjectBase<Eigen::Matrix<double, -1, 3, 0, -1, 3> >&, Eigen::PlainObjectBase<Eigen::Matrix<double, -1, 3, 0, -1, 3> >&);
template void igl::comb_cross_field<Eigen::Matrix<double, -1, -1, 0, -1, -1>, Eigen::Matrix<int, -1, -1, 0, -1, -1> >(Eigen::PlainObjectBase<Eigen::Matrix<double, -1, -1, 0, -1, -1> > const&, Eigen::PlainObjectBase<Eigen::Matrix<int, -1, -1, 0, -1, -1> > const&, Eigen::PlainObjectBase<Eigen::Matrix<double, -1, -1, 0, -1, -1> > const&, Eigen::PlainObjectBase<Eigen::Matrix<double, -1, -1, 0, -1, -1> > const&, Eigen::PlainObjectBase<Eigen::Matrix<double, -1, -1, 0, -1, -1> >&, Eigen::PlainObjectBase<Eigen::Matrix<double, -1, -1, 0, -1, -1> >&);
#endif

ext: cpp

max_stars_repo_name: FabianRepository/SinusProject

max_issues_repo_name: FabianRepository/SinusProject

max_forks_repo_name: FabianRepository/SinusProject


text:
#define BOOST_TEST_DYN_LINK
#include <canard/net/ofp/v13/utility/meter_band_set.hpp>
#include <boost/test/unit_test.hpp>

namespace ofp = canard::net::ofp;
namespace v13 = ofp::v13;
namespace bands = v13::meter_bands;

namespace {
  template <class T>
  auto calc_key(T const& t) noexcept
    -> std::uint64_t
  {
    return v13::meter_band_set::calc_key(t.rate(), t.burst_size());
  }
}

BOOST_AUTO_TEST_SUITE(utility_test)
BOOST_AUTO_TEST_SUITE(meter_band_set)
  BOOST_AUTO_TEST_SUITE(constructor)
    BOOST_AUTO_TEST_CASE(
        is_constructible_from_multiple_same_band_types_but_rates_are_different)
    {
      auto const drop1 = bands::drop{1};
      auto const drop2 = bands::drop{3};
      auto const dscp_remark = bands::dscp_remark{0, 2};

      v13::meter_band_set const sut{ drop1, drop2, dscp_remark };

      BOOST_TEST(sut.size() == 3);
      BOOST_TEST_REQUIRE((sut.find(calc_key(drop1)) != sut.end()));
      BOOST_TEST((sut.at(calc_key(drop1)) == drop1));
      BOOST_TEST_REQUIRE((sut.find(calc_key(drop2)) != sut.end()));
      BOOST_TEST((sut.at(calc_key(drop2)) == drop2));
      BOOST_TEST_REQUIRE((sut.find(calc_key(dscp_remark)) != sut.end()));
      BOOST_TEST((sut.at(calc_key(dscp_remark)) == dscp_remark));
    }
  BOOST_AUTO_TEST_SUITE_END() // constructor

  BOOST_AUTO_TEST_SUITE(is_valid_set)
    BOOST_AUTO_TEST_CASE(is_true_if_list_contains_different_rate_meter_bands)
    {
      auto const drop1 = bands::drop{1};
      auto const drop2 = bands::drop{3};
      auto const dscp_remark = bands::dscp_remark{0, 2};

      auto const list
        = v13::meter_band_set::list_type{ drop1, drop2, dscp_remark };

      BOOST_TEST(v13::meter_band_set::is_valid_set(list));
    }
    BOOST_AUTO_TEST_CASE(
        is_true_if_list_contains_different_burst_size_meter_bands)
    {
      auto const rate = 1;
      auto const drop1 = bands::drop{rate, 1};
      auto const drop2 = bands::drop{rate, 3};
      auto const dscp_remark = bands::dscp_remark{0, rate, 2};

      auto const list
        = v13::meter_band_set::list_type{ drop1, drop2, dscp_remark };

      BOOST_TEST(v13::meter_band_set::is_valid_set(list));
    }
    BOOST_AUTO_TEST_CASE(
        is_false_if_list_contains_same_rate_and_burst_size_bands)
    {
      auto const rate = 1;
      auto const burst_size = 2;
      auto const drop = bands::drop{rate, burst_size};
      auto const dscp_remark = bands::dscp_remark{1, rate, burst_size};

      auto const list = v13::meter_band_set::list_type{ drop, dscp_remark };

      BOOST_TEST(!v13::meter_band_set::is_valid_set(list));
    }
  BOOST_AUTO_TEST_SUITE_END() // is_valid_set

  BOOST_AUTO_TEST_SUITE(equivalent_as_set)
    BOOST_AUTO_TEST_CASE(
        is_true_if_both_meter_bands_are_equal_but_order_is_not_equal)
    {
      auto const drop = bands::drop{1};
      auto const dscp_remark = bands::dscp_remark{1, 2};
      auto const list1 = v13::meter_band_set::list_type{ drop, dscp_remark };
      auto const list2 = v13::meter_band_set::list_type{ dscp_remark, drop };

      BOOST_TEST(v13::meter_band_set::equivalent_as_set(list1, list2));
    }
  BOOST_AUTO_TEST_SUITE_END() // equivalent_as_set

BOOST_AUTO_TEST_SUITE_END() // meter_band_set
BOOST_AUTO_TEST_SUITE_END() // utility_test


text: #include <boost/proto/functional/fusion/pop_front.hpp>

ext: hpp

max_stars_repo_name: miathedev/BoostForArduino

max_issues_repo_name: miathedev/BoostForArduino

max_forks_repo_name: miathedev/BoostForArduino


text:
//--------------------------------------------------------------------------------------------------------------------//
//                                                                                //
//                                      Tuplex: Blazing Fast Python Data Science                                      //
//                                                                                //
//                                                                                //
//  (c) 2017 - 2021, Tuplex team                                                                                //
//  Created by Leonhard Spiegelberg first on 1/1/2021                                                                 //
//  License: Apache 2.0                                                                                //
//--------------------------------------------------------------------------------------------------------------------//

#include <iostream>
#include <Pipe.h>
#include <boost/process.hpp>
#include <boost/algorithm/string.hpp>
#include <Logger.h>
#include <fstream>
#include <cstdlib>

int Pipe::pipe(const std::string& file_input) {

    try {

        using namespace boost::process;

        ipstream pipe_stdout;
        ipstream pipe_stderr;

        assert(_command.length() > 0);

        // get the program name
        auto idx = _command.find(' ');
        if(std::string::npos == idx)
            idx = _command.length();
        std::string name = _command.substr(0, idx);
        std::string tail = _command.substr(idx);

        std::string cmd = boost::process::search_path(name).generic_string() + tail;

        // check if file input is active, if so create a temp file
        if(file_input.length() > 0) {
            // @TODO: global temp dir should be used...
            // needs to be a configurable option...

            // deprecated
            // @TODO
            std::string tmppath = std::tmpnam(nullptr);
            std::ofstream ofs(tmppath + ".py");
            ofs<<file_input;
            ofs.close();
            cmd += " " + tmppath + ".py";
        }

        child c(cmd, std_err > pipe_stderr, std_out > pipe_stdout);

        std::string line;
        while (pipe_stdout && std::getline(pipe_stdout, line) && !line.empty()) {
            _stdout += line + "\n";
        }
        while (pipe_stderr && std::getline(pipe_stderr, line) && !line.empty()) {
            _stderr += line + "\n";
        }

        c.wait();
        _retval = c.exit_code();

    } catch(std::exception& e) {
        Logger::instance().logger("pipe").error(std::string("error while calling external process: ") + e.what());
        _retval = 1;
    }

    _executed = true;
    return retval();
}

ext: cc


text:
// Author: Diego Vergara
#ifndef C_UTILS_H
#define C_UTILS_H

#include <iostream>
#include <iomanip>
#include <cstdlib>
#include <Eigen/Dense>
#include <Eigen/Core>
#include <opencv2/core.hpp>
#include <opencv2/core/eigen.hpp>
#include <string>
#include <fstream>
#include <vector>
#include <map>
#include <set>
#include <chrono>
#include <random>

using namespace std;
using namespace Eigen;
using namespace cv;

typedef struct{
  double precision;
  double accuracy;
  double recall;
  double f1score;
  double support;
}Metrics;

class C_utils
{
public:
	C_utils();
	double unif(double min, double max);
	VectorXd random_generator(int dimension);
	double random_uniform();
	VectorXd random_binomial(int n, VectorXd prob, int dim);
    void writeToCSVfile(string name, MatrixXd matrix, bool append = false);
    static void calculateAccuracyPercent(VectorXd labels,VectorXd predicted);
    void printProgBar( int value, int max );
    void dataPermutation(MatrixXd& X_train,VectorXd& Y_train);
    void dataNormalization(MatrixXd& data,RowVectorXd& mean, RowVectorXd& std);
    void dataStandardization(MatrixXd& data,RowVectorXd& max, RowVectorXd& min);
    void testNormalization(MatrixXd& data,RowVectorXd mean, RowVectorXd std);
    void testStandardization(MatrixXd& data,RowVectorXd max, RowVectorXd min);
    void dataPartition(MatrixXd& data,VectorXd& labels, MatrixXd& X_train, MatrixXd& X_test, VectorXd& Y_train, VectorXd& Y_test, int partition);
    VectorXi argMin(MatrixXd data, bool row = true);
    VectorXi argMax(MatrixXd data, bool row = true);
    VectorXd matrixDot(MatrixXd &A, VectorXd &x);
    VectorXd sign(VectorXd &x);
    VectorXd vecMax(double value, VectorXd &vec);
    void read_Labels(const string& filename, VectorXi& labels);
    void read_Labels(const string& filename, VectorXd& labels);
	void read_Labels(const string& filename, VectorXi& labels,int rows);
	void read_Labels(const string& filename, VectorXd& labels, int rows);
	void read_Data(const string& filename, MatrixXd& data);
	void read_Data(const string& filename, MatrixXd& data,int rows, int cols);
	void print(VectorXi &test, VectorXi &predicted);
	void classification_Report(VectorXi &test, VectorXd &predicted);
	void classification_Report(VectorXd &test, VectorXi &predicted);
	void classification_Report(VectorXi &test, VectorXi &predicted);
	int get_Rows(const string& filename);
	int get_Cols(const string& filename, char separator);
	vector<int> get_Classes(VectorXi labels);
	vector<int> get_Classes_d(VectorXd labels);

	map<pair<int,int>, int> confusion_matrix(VectorXi &test, VectorXi &predicted, bool print=true);
	map<pair<int,int>, int> confusion_matrix(VectorXi &test, VectorXd &predicted, bool print=true);
	map<pair<int,int>, int> confusion_matrix(VectorXd &test, VectorXd &predicted, bool print=true);

	map<int, double> precision_score(VectorXi &test, VectorXi &predicted, bool print=true);
	map<int, double> precision_score(VectorXi &test, VectorXd &predicted, bool print=true);
	map<int, double> precision_score(VectorXd &test, VectorXd &predicted, bool print=true);
	map<int, double> precision_score(map<pair<int,int>, int> confusion_matrix, bool print=false);

	map<int, double> accuracy_score(VectorXi &test, VectorXi &predicted, bool print=true);
	map<int, double> accuracy_score(VectorXi &test, VectorXd &predicted, bool print=true);
	map<int, double> accuracy_score(VectorXd &test, VectorXd &predicted, bool print=true);
	map<int, double> accuracy_score(map<pair<int,int>, int> confusionMatrix, bool print=false);

	map<int, double> recall_score(VectorXi &test, VectorXi &predicted, bool print=true);
	map<int, double> recall_score(VectorXi &test, VectorXd &predicted, bool print=true);
	map<int, double> recall_score(VectorXd &test, VectorXd &predicted, bool print=true);
	map<int, double> recall_score(map<pair<int,int>, int> confusionMatrix, bool print=false);

	map<int, double> f1_score(VectorXi &test, VectorXi &predicted, bool print=true);
	map<int, double> f1_score(VectorXi &test, VectorXd &predicted, bool print=true);
	map<int, double> f1_score(VectorXd &test, VectorXd &predicted, bool print=true);
	map<int, double> f1_score(map<pair<int, int>, int> confusionMatrix, bool print=false);

	map<int, double> support_score(VectorXi &test);
	map<int, double> support_score(VectorXd &test);
	map<int, double> support_score(map<pair<int, int>, int> confusionMatrix);

	map<int, Metrics> report(VectorXi &test, VectorXi &predicted, bool print=true);
	map<int, Metrics> report(VectorXi &test, VectorXd &predicted, bool print=true);
	map<int, Metrics> report(VectorXd &test, VectorXd &predicted, bool print=true);
	map<int, Metrics> report(map<pair<int, int>, int> confusionMatrix, bool print=true);
private:
	bool initialized;
};

#endif

max_stars_repo_name: fjorquerauribe/multitarget-tracking

max_issues_repo_name: fjorquerauribe/multitarget-tracking

max_forks_repo_name: fjorquerauribe/multitarget-tracking


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

#include <boost/property_tree/xml_parser.hpp>
#include <boost/property_tree/json_parser.hpp>
#include <boost/foreach.hpp>

#include "hazelcast/client/aws/utility/CloudUtility.h"
#include "hazelcast/client/config/ClientAwsConfig.h"
#include "hazelcast/util/ILogger.h"

namespace hazelcast {
    namespace client {
        namespace aws {
            namespace utility {
                std::map<std::string, std::string> CloudUtility::unmarshalTheResponse(std::istream &stream) {
                    std::map<std::string, std::string> privatePublicPairs;

                    pt::ptree tree;
                    try {
                        pt::read_xml(stream, tree);
                    } catch (pt::xml_parser_error &e) {
                        util::ILogger::getLogger().warning(
                                std::string("The parsed xml stream has errors: ") + e.what());
                        return privatePublicPairs;
                    }

                    // Use get_child to find the node containing the reservation set, and iterate over
                    // its children.
                    BOOST_FOREACH(pt::ptree::value_type & item,
                                  tree.get_child("DescribeInstancesResponse.reservationSet")) {
                                    BOOST_FOREACH(pt::ptree::value_type & instanceItem,
                                                  item.second.get_child("instancesSet")) {
                                                    boost::optional<std::string> privateIp = instanceItem.second.get_optional<std::string>(
                                                            "privateIpAddress");
                                                    boost::optional<std::string> publicIp = instanceItem.second.get_optional<std::string>(
                                                            "ipAddress");
                                                    std::string prIp = privateIp.value_or("");
                                                    std::string pubIp = publicIp.value_or("");

                                                    if (privateIp) {
                                                        privatePublicPairs[prIp] = pubIp;
                                                        util::ILogger &logger = util::ILogger::getLogger();
                                                        if (logger.isFinestEnabled()) {
                                                            boost::optional<std::string> instanceName = instanceItem.second.get_optional<std::string>(
                                                                    "tagset.item.value");

                                                            std::string instName = instanceName.value_or("");

                                                            logger.finest(
                                                                    std::string("Accepting EC2 instance [") + instName +
                                                                    "][" + prIp + "]");
                                                        }
                                                    }
                                                }
                                }
                    return privatePublicPairs;
                }

                void CloudUtility::unmarshalJsonResponse(std::istream &stream, config::ClientAwsConfig &awsConfig,
                                                         std::map<std::string, std::string> &attributes) {
                    pt::ptree json;
                    pt::read_json(stream, json);
                    awsConfig.setAccessKey(json.get_optional<std::string>("AccessKeyId").get_value_or(""));
                    awsConfig.setSecretKey(json.get_optional<std::string>("SecretAccessKey").get_value_or(""));
                    attributes["X-Amz-Security-Token"] = json.get_optional<std::string>("Token").get_value_or("");
                }
            }
        }
    }
}

max_stars_repo_name: pirog-spb/hazelcast-cpp-client

max_issues_repo_name: pirog-spb/hazelcast-cpp-client

max_forks_repo_name: pirog-spb/hazelcast-cpp-client


text:
/**
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you 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 avro_json_JsonIO_hh__
#define avro_json_JsonIO_hh__

#include <stack>
#include <string>
#include <sstream>
#include <boost/utility.hpp>

#include "Config.hh"
#include "Stream.hh"

namespace avro {
namespace json {

inline char toHex(unsigned int n) {
    return (n < 10) ? (n + '0') : (n + 'a' - 10);
}

class AVRO_DECL JsonParser : boost::noncopyable {
public:
    enum Token {
        tkNull,
        tkBool,
        tkLong,
        tkDouble,
        tkString,
        tkArrayStart,
        tkArrayEnd,
        tkObjectStart,
        tkObjectEnd
    };

private:
    enum State {
        stValue,    // Expect a data type
        stArray0,   // Expect a data type or ']'
        stArrayN,   // Expect a ',' or ']'
        stObject0,  // Expect a string or a '}'
        stObjectN,  // Expect a ',' or '}'
        stKey       // Expect a ':'
    };
    std::stack<State> stateStack;
    State curState;
    bool hasNext;
    char nextChar;
    bool peeked;

    StreamReader in_;
    Token curToken;
    bool bv;
    int64_t lv;
    double dv;
    std::string sv;

    Token doAdvance();
    Token tryLiteral(const char exp[], size_t n, Token tk);
    Token tryNumber(char ch);
    Token tryString();
    Exception unexpected(unsigned char ch);
    char next();

public:
    JsonParser() : curState(stValue), hasNext(false), peeked(false) { }

    void init(InputStream& is) {
        in_.reset(is);
    }

    Token advance() {
        if (! peeked) {
            curToken = doAdvance();
        } else {
            peeked = false;
        }
        return curToken;
    }

    Token peek() {
        if (! peeked) {
            curToken = doAdvance();
            peeked = true;
        }
        return curToken;
    }

    void expectToken(Token tk);

    bool boolValue() {
        return bv;
    }

    Token cur() {
        return curToken;
    }

    double doubleValue() {
        return dv;
    }

    int64_t longValue() {
        return lv;
    }

    std::string stringValue() {
        return sv;
    }

    static const char* const tokenNames[];

    static const char* toString(Token tk) {
        return tokenNames[tk];
    }
};

class AVRO_DECL JsonGenerator {
    StreamWriter out_;
    enum State {
        stStart,
        stArray0,
        stArrayN,
        stMap0,
        stMapN,
        stKey,
    };

    std::stack<State> stateStack;
    State top;

    void write(const char *b, const char* p) {
        if (b != p) {
            out_.writeBytes(reinterpret_cast<const uint8_t*>(b), p - b);
        }
    }

    void escape(char c, const char* b, const char *p) {
        write(b, p);
        out_.write('\\');
        out_.write(c);
    }

    void escapeCtl(char c) {
        out_.write('\\');
        out_.write('U');
        out_.write('0');
        out_.write('0');
        out_.write(toHex((static_cast<unsigned char>(c)) / 16));
        out_.write(toHex((static_cast<unsigned char>(c)) % 16));
    }

    void doEncodeString(const std::string& s) {
        const char* b = &s[0];
        const char* e = b + s.size();
        out_.write('"');
        for (const char* p = b; p != e; p++) {
            switch (*p) {
            case '\\':
            case '"':
            case '/':
                escape(*p, b, p);
                break;
            case '\b':
                escape('b', b, p);
                break;
            case '\f':
                escape('f', b, p);
                break;
            case '\n':
                escape('n', b, p);
                break;
            case '\r':
                escape('r', b, p);
                break;
            case '\t':
                escape('t', b, p);
                break;
            default:
                if (! iscntrl(*p)) {
                    continue;
                }
                write(b, p);
                escapeCtl(*p);
                break;
            }
            b = p + 1;
        }
        write(b, e);
        out_.write('"');
    }

    void sep() {
        if (top == stArrayN) {
            out_.write(',');
        } else if (top == stArray0) {
            top = stArrayN;
        }
    }

    void sep2() {
        if (top == stKey) {
            top = stMapN;
        }
    }

public:
    JsonGenerator() : top(stStart) { }

    void init(OutputStream& os) {
        out_.reset(os);
    }

    void flush() {
        out_.flush();
    }

    void encodeNull() {
        sep();
        out_.writeBytes(reinterpret_cast<const uint8_t*>("null"), 4);
        sep2();
    }

    void encodeBool(bool b) {
        sep();
        if (b) {
            out_.writeBytes(reinterpret_cast<const uint8_t*>("true"), 4);
        } else {
            out_.writeBytes(reinterpret_cast<const uint8_t*>("false"), 5);
        }
        sep2();
    }

    template <typename T>
    void encodeNumber(T t) {
        sep();
        std::ostringstream oss;
        oss << t;
        const std::string& s = oss.str();
        out_.writeBytes(reinterpret_cast<const uint8_t*>(&s[0]), s.size());
        sep2();
    }

    void encodeNumber(double t);

    void encodeString(const std::string& s) {
        if (top == stMap0) {
            top = stKey;
        } else if (top == stMapN) {
            out_.write(',');
            top = stKey;
        } else if (top == stKey) {
            top = stMapN;
        } else {
            sep();
        }
        doEncodeString(s);
        if (top == stKey) {
            out_.write(':');
        }
    }

    void encodeBinary(const uint8_t* bytes, size_t len) {
        sep();
        out_.write('"');
        const uint8_t* e = bytes + len;
        while (bytes != e) {
            escapeCtl(*bytes++);
        }
        out_.write('"');
        sep2();
    }

    void arrayStart() {
        sep();
        stateStack.push(top);
        top = stArray0;
        out_.write('[');
    }

    void arrayEnd() {
        top = stateStack.top();
        stateStack.pop();
        out_.write(']');
        sep2();
    }

    void objectStart() {
        sep();
        stateStack.push(top);
        top = stMap0;
        out_.write('{');
    }

    void objectEnd() {
        top = stateStack.top();
        stateStack.pop();
        out_.write('}');
        sep2();
    }

};

}
}

#endif

ext: hh

max_stars_repo_name: SpotifyUsedOpenSourceCode/avro

max_issues_repo_name: SpotifyUsedOpenSourceCode/avro

max_forks_repo_name: SpotifyUsedOpenSourceCode/avro


text:
/*****************************************************************************
 *
 * This file is part of Mapnik (c++ mapping toolkit)
 *
 * Copyright (C) 2016 Artem Pavlenko
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 *
 *****************************************************************************/

#include <mapnik/json/geometry_parser.hpp>
#include <mapnik/json/geometry_grammar.hpp>

// boost
#include <boost/spirit/include/qi.hpp>
#include <boost/spirit/include/phoenix_core.hpp>

namespace mapnik { namespace json {

bool from_geojson(std::string const& json, mapnik::geometry::geometry<double> & geom)
{
    using namespace boost::spirit;
    static const geometry_grammar<char const*> g;
    standard::space_type space;
    char const* start = json.c_str();
    char const* end = start + json.length();
    try
    {
        if (!qi::phrase_parse(start, end, g, space, geom))
        {
            throw std::runtime_error("Can't parser GeoJSON Geometry");
        }
    }
    catch (...) { return false; }
    return true;
}

}}


text:
/*
 * Copyright 2019 Applied Research Center for Computer Networks
 *
 * 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.
 */

#pragma once

#include "api/SerializablePacket.hpp"
#include "openflow/common.hh"
#include <runos/core/safe_ptr.hpp>

#include <boost/endian/arithmetic.hpp>

#include <array>
#include <map>
#include <initializer_list>
#include <ostream>
#include <cstddef>
#include <cstdint>

namespace fluid_msg {
namespace of13 {
class PacketIn;
}
}

namespace runos {

class dhcp_opt {
public:
    uint8_t code;
    uint8_t number;
    uint8_t *value;

    dhcp_opt(uint8_t c = 0, uint8_t n = 0, uint8_t* v = nullptr): code(c), number(n), value(v) {}
};

class PacketParser final : public SerializablePacket {
    // buffer
    uint8_t* data;
    size_t data_len;
    boost::endian::big_uint32_t in_port;
    bool vlan_tagged;

    // bindings
    typedef std::array<void*, 45> bindings_arr;
    bindings_arr bindings;

    // replace with
    safe_ptr<struct ethernet_hdr> eth;
    safe_ptr<struct dot1q_hdr> dot1q;
    safe_ptr<struct ipv4_hdr> ipv4;
    safe_ptr<struct tcp_hdr> tcp;
    safe_ptr<struct udp_hdr> udp;
    safe_ptr<struct arp_hdr> arp;
    safe_ptr<struct dhcp_hdr> dhcp;
    std::map<uint8_t, dhcp_opt> dhcp_options;

    void parse_l2(uint8_t* data, size_t data_len);
    void parse_l3(uint16_t eth_type, uint8_t* data, size_t data_len);
    void parse_l4(uint8_t protocol, uint8_t* data, size_t data_len);
    void parse_dhcp(uint8_t* data, size_t data_len);

    using binding_list =
        std::initializer_list<std::pair<of::oxm::basic_match_fields, void*>>;

    void bind(binding_list bindings);
    void rebind(binding_list bindings);
    uint8_t* access(oxm::type t) const;

public:
    PacketParser(fluid_msg::of13::PacketIn& pi);

    oxm::field<> load(oxm::mask<> mask) const override;
    void modify(oxm::field<> patch) override;
    bool vlanTagged() override;

    size_t total_bytes() const override;
    size_t serialize_to(size_t buffer_size, void* buffer) const override;

    dhcp_opt get_dhcp_option(uint8_t code);
};

} // namespace runos

max_stars_repo_name: estepanov-lvk/runos

max_issues_repo_name: estepanov-lvk/runos

max_forks_repo_name: estepanov-lvk/runos


text:
/**
 * Copyright Soramitsu Co., Ltd. All Rights Reserved.
 * SPDX-License-Identifier: Apache-2.0
 */

#ifndef IROHA_PG_CONNECTION_INIT_HPP
#define IROHA_PG_CONNECTION_INIT_HPP

#include <soci/soci.h>

#include <soci/callbacks.h>
#include <soci/postgresql/soci-postgresql.h>
#include <boost/algorithm/string.hpp>
#include <boost/range/algorithm/replace_if.hpp>

#include "ametsuchi/impl/failover_callback_holder.hpp"
#include "ametsuchi/impl/postgres_command_executor.hpp"
#include "ametsuchi/impl/postgres_options.hpp"
#include "ametsuchi/reconnection_strategy.hpp"
#include "common/result.hpp"
#include "interfaces/permissions.hpp"
#include "logger/logger_fwd.hpp"
#include "logger/logger_manager_fwd.hpp"
#include "main/startup_params.hpp"

namespace iroha {
  namespace ametsuchi {

    struct PoolWrapper;

    class PgConnectionInit {
     public:
      static expected::Result<void, std::string> prepareWorkingDatabase(
          StartupWsvDataPolicy startup_wsv_data_policy,
          const PostgresOptions &options);

      static expected::Result<std::shared_ptr<PoolWrapper>, std::string>
      prepareConnectionPool(
          const ReconnectionStrategyFactory &reconnection_strategy_factory,
          const PostgresOptions &options,
          const int pool_size,
          logger::LoggerManagerTreePtr log_manager);

      /**
       * Verify whether postgres supports prepared transactions
       */
      static bool preparedTransactionsAvailable(soci::session &sql);

      static iroha::expected::Result<void, std::string> rollbackPrepared(
          soci::session &sql, const std::string &prepared_block_name);

      /*
       * Drop working database.
       * @return Error message if dropping has failed.
       */
      static expected::Result<void, std::string> dropWorkingDatabase(
          const PostgresOptions &options);

      /**
       * Removes all peers from WSV
       * @return error message if reset has failed
       */
      static expected::Result<void, std::string> resetPeers(soci::session &sql);

      /// Create tables in the given session. Left public for tests.
      static void prepareTables(soci::session &session);

      /**
       * Creates schema. Working database must not exist when calling this.
       * @return void value in case of success or an error message otherwise.
       */
      static expected::Result<void, std::string> createSchema(
          const PostgresOptions &postgres_options);

     private:
      /**
       * Function initializes existing connection pool
       * @param connection_pool - pool with connections
       * @param pool_size - number of connections in pool
       * @param try_rollback - function which performs blocks rollback before
       * initialization
       * @param callback_factory - factory for reconnect callbacks
       * @param reconnection_strategy_factory - factory which creates strategies
       * for each connection
       * @param pg_reconnection_options - parameter of connection startup on
       * reconnect
       * @param log_manager - log manager of storage
       * @tparam RollbackFunction - type of rollback function
       * @return void value on success or string error
       */
      template <typename RollbackFunction>
      static expected::Result<void, std::string> initializeConnectionPool(
          soci::connection_pool &connection_pool,
          size_t pool_size,
          RollbackFunction try_rollback,
          FailoverCallbackHolder &callback_factory,
          const ReconnectionStrategyFactory &reconnection_strategy_factory,
          const std::string &pg_reconnection_options,
          logger::LoggerManagerTreePtr log_manager);
    };
  }  // namespace ametsuchi
}  // namespace iroha

#endif  // IROHA_PG_CONNECTION_INIT_HPP


text:
<<<<<<< HEAD
/*    Copyright (c) 2010-2018, Delft University of Technology
=======
/*    Copyright (c) 2010-2019, Delft University of Technology
>>>>>>> origin/master
 *    All rigths reserved
 *
 *    This file is part of the Tudat. Redistribution and use in source and
 *    binary forms, with or without modification, are permitted exclusively
 *    under the terms of the Modified BSD license. You should have received
 *    a copy of the license with this file. If not, please or visit:
 *    http://tudat.tudelft.nl/LICENSE.
 *
 *    Notes
 *      Reference data generated by datcom script written by F. Engelen. Output has been checked
 *      manually.
 *
 */

#define BOOST_TEST_MAIN

#include <limits>
#include <string>

#include <boost/test/floating_point_comparison.hpp>
#include <boost/test/unit_test.hpp>
#include "Tudat/Basics/testMacros.h"
#include "Tudat/InputOutput/matrixTextFileReader.h"

#include "Tudat/InputOutput/basicInputOutput.h"
#include "Tudat/InputOutput/missileDatcomData.h"

namespace tudat
{
namespace unit_tests
{

BOOST_AUTO_TEST_SUITE( test_missile_datcom_data )

BOOST_AUTO_TEST_CASE( testMissileDatcomData )
{
    using namespace input_output;

    // Read and process data file.
    std::string fileLocation = getTudatRootPath( )
            + "InputOutput/UnitTests/inputForBenchMarkMissileDatcomData.dat";
    MissileDatcomData myMissileDatcomData( fileLocation );

    // Set name of file and path to write to and from.
    std::string outputFileName = getTudatRootPath( ) + "InputOutput/UnitTests/bodyTailConfiguration";

    // Write files for coefficients at each angle of attack.
    myMissileDatcomData.writeCoefficientsToFile( outputFileName, 9, 2 );

    // Read benchmark files and check if all entries are equal to those written by DatcomData
    std::string totalPath;
    Eigen::MatrixXd benchmarkFile, tudatFile;

    for ( int i = 0; i < 5; i++ )
    {
        // Read file just written
        totalPath = outputFileName + "_" + std::to_string( i );
        tudatFile = readMatrixFromFile( totalPath );

        // Read benchmark file
        totalPath = getTudatRootPath( ) + "InputOutput/UnitTests/benchmark_"
                + std::to_string( i );
        benchmarkFile = readMatrixFromFile( totalPath );

        // Iterate over all entries and check values.
        for ( int j = 0; j < tudatFile.rows( ); j++ )
        {
            for ( int k = 1; k < tudatFile.cols( ); k++ )
            {
                if ( std::fabs( benchmarkFile( j, k ) ) >
                        std::numeric_limits< double >::epsilon( ) )
                {
                    BOOST_CHECK_CLOSE_FRACTION( tudatFile( j, k ),
                                                benchmarkFile( j, k ),
                                                std::numeric_limits< double >::epsilon( ) );
                }

                else
                {
                    BOOST_CHECK_SMALL( tudatFile( j, k ) - benchmarkFile( j, k ),
                                       std::numeric_limits< double >::epsilon( )  );
                }
            }
        }
    }
}

} // namespace unit_tests
} // namespace tudat

BOOST_AUTO_TEST_SUITE_END( )

max_stars_repo_name: ViktorJordanov/tudat

max_issues_repo_name: ViktorJordanov/tudat

max_forks_repo_name: ViktorJordanov/tudat


text:
// Copyright (C) 2015 The Regents of the University of California (Regents).
// 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 Regents or University of California 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 HOLDERS 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.
//
// Please contact the author of this library if you have any questions.
// Author: Benjamin Nuernberger (bnuernberger@cs.ucsb.edu)

#include "theia/sfm/estimators/estimate_dominant_plane_from_points.h"

#include <Eigen/Core>
#include <Eigen/Geometry>
#include <limits>
#include <memory>
#include <vector>

#include "theia/sfm/create_and_initialize_ransac_variant.h"
#include "theia/sfm/pose/util.h"
#include "theia/solvers/estimator.h"
#include "theia/solvers/sample_consensus_estimator.h"
#include "theia/util/util.h"

namespace theia {
namespace {

using Eigen::Vector3d;

// An estimator for computing a dominant plane from a set of 3D points.
class DominantPlaneEstimator : public Estimator<Vector3d, Plane> {
 public:
  DominantPlaneEstimator() {}

  // 3 non-collinear points are needed to determine a plane.
  double SampleSize() const { return 3; }

  // Estimates candidate dominant planes from three 3D points.
  bool EstimateModel(const std::vector<Vector3d>& points,
                     std::vector<Plane>* planes) const {
    // If the points are collinear, there are no possible solutions.
    static const double kTolerance = 1e-6;
    const Vector3d a = points[1] - points[0];
    const Vector3d b = points[2] - points[0];
    const Vector3d cross = a.cross(b);
    if (cross.squaredNorm() < kTolerance) {
      VLOG(3) << "The 3 world points are collinear! No solution for a plane "
                 "exists.";
      return false;
    }
    Plane plane;
    plane.point = points[0];
    plane.unit_normal = cross.normalized();

    planes->emplace_back(plane);
    return true;
  }

  // The error for a point given a plane model is the point-to-plane distance.
  double Error(const Vector3d& point, const Plane& plane) const {
    return std::abs(plane.unit_normal.dot(point - plane.point));
  }

 private:
  DISALLOW_COPY_AND_ASSIGN(DominantPlaneEstimator);
};

}  // namespace

bool EstimateDominantPlaneFromPoints(const RansacParameters& ransac_params,
                                     const RansacType& ransac_type,
                                     const std::vector<Vector3d>& points,
                                     Plane* plane,
                                     RansacSummary* ransac_summary) {
  DominantPlaneEstimator dominant_plane_estimator;
  std::unique_ptr<SampleConsensusEstimator<DominantPlaneEstimator> > ransac =
      CreateAndInitializeRansacVariant(
          ransac_type, ransac_params, dominant_plane_estimator);
  // Estimate the dominant plane.
  return ransac->Estimate(points, plane, ransac_summary);
}

}  // namespace theia

max_stars_repo_name: urbste/TheiaSfM

max_issues_repo_name: urbste/TheiaSfM

max_forks_repo_name: urbste/TheiaSfM


text:
/*
    Copyright 2021-2022 The Silkworm Authors

    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.
*/

#pragma once
#ifndef SILKWORM_COMMON_SETTINGS_HPP_
#define SILKWORM_COMMON_SETTINGS_HPP_

#include <memory>

#ifdef __APPLE__
// otherwise <boost/asio/detail/socket_types.hpp> dependency doesn't compile
#define _DARWIN_C_SOURCE
#endif
#include <boost/asio/io_context.hpp>

#include <silkworm/chain/config.hpp>
#include <silkworm/common/base.hpp>
#include <silkworm/common/directories.hpp>
#include <silkworm/db/mdbx.hpp>
#include <silkworm/db/prune_mode.hpp>

namespace silkworm {

struct NodeSettings {
    boost::asio::io_context asio_context;            // Async context (e.g. for timers)
    std::unique_ptr<DataDirectory> data_directory;   // Pointer to data folder
    db::EnvConfig chaindata_env_config{};            // Chaindata db config
    uint64_t network_id{kMainnetConfig.chain_id};    // Network/Chain id
    std::optional<ChainConfig> chain_config;         // Chain config
    size_t batch_size{512_Mebi};                     // Batch size to use in stages
    size_t etl_buffer_size{256_Mebi};                // Buffer size for ETL operations
    std::string private_api_addr{"127.0.0.1:9090"};  // Default API listener
    std::string sentry_api_addr{};                   // Default address(es) of sentry
    bool fake_pow{false};                            // Whether to verify Proof-of-Work
    std::unique_ptr<db::PruneMode> prune_mode;       // Prune mode
    uint32_t sync_loop_throttle_seconds{0};          // Minimum interval amongst sync cycle
    uint32_t sync_loop_log_interval_seconds{10};     // Interval for sync loop to emit logs
};

}  // namespace silkworm

#endif  // SILKWORM_COMMON_SETTINGS_HPP_