text:
#pragma once
#include "zrpc.h"
#include <boost/algorithm/hex.hpp>

#if ZRPC_CXX_STD_11
#include <log.hpp>
#else
#if !defined(LOG) && !defined(LOG_IF)
#define LOG(...)
#define LOG_IF(...)
#endif
#endif

#if ZRPC_HAS_CXX_11
#  include <functional>
#  include <memory>
#  include <vector>
#else
#  include <boost/make_shared.hpp>
#endif

#include <msgpack.hpp>

namespace zrpc
{
    namespace detail
    {
        typedef unsigned __int32 uint32_t;
        typedef unsigned __int16 uint16_t;

        using msgpack::type::tuple;

        struct Header
        {
            char sign[4];
            uint32_t length;
            uint16_t major;
            uint16_t minor;
        };

        template<typename T>
        inline void hex(const Header& header, T result)
        {
            boost::algorithm::hex(
                (const char*)(&header),
                (const char*)(&header) + sizeof(header),
                result);
        }

        inline std::string hex(const std::string& buffer)
        {
            std::string result;
            boost::algorithm::hex(
                buffer.begin(),
                buffer.end(),
                std::back_inserter(result));
            return result;
        }

        inline void initialize(Header& header)
        {
            memset(header.sign, '@', sizeof(header.sign));
            header.length = 0;
            header.major = 0;
            header.minor = 0;
        }

        struct Call
        {
            std::string func;
            std::string args;
            ~Call()
            {
                LOG(info, "");
            }
            MSGPACK_DEFINE(func, args);
        };

#if ZRPC_HAS_CXX_11
        using std::vector;
#else
        template<typename T>
        class vector
        {
        public:
            vector()
                : data_(NULL)
            {
            }

            vector(std::size_t size, T val)
                : data_(new T[size])
                , size_(size)
            {
                std::fill(data_, data_ + size, val);
            }

            ~vector()
            {
                if (data_ != NULL)
                {
                    delete[] data_;
                    data_ = NULL;
                }
            }

            T* data()
            {
                return data_;
            }

            std::size_t size()
            {
                return size_;
            }

        private:
            T* data_;
            std::size_t size_;
        };
#endif

        struct ICallable
        {
            ICallable()
            {
            }

            virtual ~ICallable()
            {
            }

            virtual std::string call(std::string param) = 0;
        };

#if ZRPC_HAS_CXX_11
        template<typename R, typename... Args>
        struct Callable : public ICallable
        {
            Callable(std::function<R(Args...)> func_)
                : func(func_)
            {
            }

            ~Callable()
            {
            }

            std::string call(std::string param) override
            {
                tuple<Args...> args;
                bool r = tryUnpack(param.c_str(), param.size(), args);
                if (!r)
                {
                    return "";
                }
                R result = lite::apply(func, args);
                return pack(result);
            }

            std::function<R(Args...)> func;
        };

        template<typename R, typename... Args>
        std::shared_ptr<ICallable> makeCallable(std::function<R(Args...)> func_)
        {
            return std::make_shared<Callable<R, Args...>>(func_);
        }

        template<typename R, typename... Args>
        std::shared_ptr<ICallable> makeCallable(R(*func_)(Args...))
        {
            return std::make_shared<Callable<R, Args...>>(func_);
        }
#else
        template<typename R, typename T0>
        struct Callable1 : public ICallable
        {
            Callable1(ZRPC_FUNCTION<R(T0)> func_)
                : func(func_)
            {
            }
            ~Callable1()
            {
            }
            std::string call(std::string param)
            {
                tuple<T0> args;
                bool u = tryUnpack(param.c_str(), param.size(), args);
                if (!u)
                {
                    return "";
                }
                R result = lite::apply(func, args);
                return pack(result);
            }
            ZRPC_FUNCTION<R(T0)> func;
        };

#ifndef ZRPC_CALLABLE
#  define ZRPC_CALLABLE(z, n, _) \
        template<typename R, BOOST_PP_REPEAT_Z(z, n, BOOST_PP_TYPENAME, T)> \
        struct BOOST_PP_CAT(Callable, n) : public ICallable \
        { \
            BOOST_PP_CAT(Callable, n)(ZRPC_FUNCTION<R(BOOST_PP_REPEAT_Z(z, n, BOOST_PP_TYPE, T))> func_) \
                : func(func_) \
            { \
            } \
            ~BOOST_PP_CAT(Callable, n)() \
            { \
            } \
            std::string call(std::string param) \
            { \
                tuple<BOOST_PP_REPEAT_Z(z, n, BOOST_PP_TYPE, T)> args; \
                bool u = tryUnpack(param.c_str(), param.size(), args); \
                if (!u) \
                { \
                    return ""; \
                } \
                R result = lite::apply(func, args); \
                return pack(result); \
            } \
            ZRPC_FUNCTION<R(BOOST_PP_REPEAT_Z(z, n, BOOST_PP_TYPE, T))> func; \
        };
        BOOST_PP_REPEAT_FROM_TO(2, 10, ZRPC_CALLABLE, _)
#endif

        template<typename R, typename T0>
        inline typename shared_ptr<ICallable>::type makeCallable(ZRPC_FUNCTION < R(T0) > func_)
        {
            return ZRPC_MAKE_SHARED< Callable1<R, T0> >(func_);
        }

        template<typename R, typename T0>
        inline typename shared_ptr<ICallable>::type makeCallable(R(*func_)(T0))
        {
            return ZRPC_MAKE_SHARED< Callable1<R, T0> >(func_);
        }

#ifndef ZRPC_MAKE_CALLABLE
#  define ZRPC_MAKE_CALLABLE(z, n, _) \
        template<typename R, BOOST_PP_REPEAT_Z(z, n, BOOST_PP_TYPENAME, T)> \
        inline typename shared_ptr<ICallable>::type makeCallable(ZRPC_FUNCTION < R(BOOST_PP_REPEAT_Z(z, n, BOOST_PP_TYPE, T)) > func_) \
        { \
            return ZRPC_MAKE_SHARED< BOOST_PP_CAT(Callable, n)<R, BOOST_PP_REPEAT_Z(z, n, BOOST_PP_TYPE, T)> >(func_); \
        } \
        template<typename R, BOOST_PP_REPEAT_Z(z, n, BOOST_PP_TYPENAME, T)> \
        inline typename shared_ptr<ICallable>::type makeCallable(R(*func_)(BOOST_PP_REPEAT_Z(z, n, BOOST_PP_TYPE, T))) \
        { \
            return ZRPC_MAKE_SHARED< BOOST_PP_CAT(Callable, n)<R, BOOST_PP_REPEAT_Z(z, n, BOOST_PP_TYPE, T)> >(func_); \
        }
        BOOST_PP_REPEAT_FROM_TO(2, 10, ZRPC_MAKE_CALLABLE, _)
#endif
#endif
    }
}

max_stars_repo_name: gwankyun/zrpc

max_issues_repo_name: gwankyun/zrpc

max_forks_repo_name: gwankyun/zrpc


text: #include <boost/spirit/home/lex/domain.hpp>

ext: hpp

max_stars_repo_name: miathedev/BoostForArduino

max_issues_repo_name: miathedev/BoostForArduino

max_forks_repo_name: miathedev/BoostForArduino


text:
#ifndef BOOST_SERIALIZATION_LIBRARY_VERSION_TYPE_HPP
#define BOOST_SERIALIZATION_LIBRARY_VERSION_TYPE_HPP

// MS compatible compilers support #pragma once
#if defined(_MSC_VER)
# pragma once
#endif

/////////1/////////2/////////3/////////4/////////5/////////6/////////7/////////8
// library_version_type.hpp:

// (C) Copyright 2002-2020 Robert Ramey - http://www.rrsd.com .
// Use, modification and distribution is subject to the Boost Software
// License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)

//  See http://www.boost.org for updates, documentation, and revision history.
#include <cstring> // count
#include <boost/cstdint.hpp> // uint_least16_t
#include <boost/assert.hpp>
#include <boost/config.hpp>
#include <boost/integer_traits.hpp>

namespace lslboost {
namespace serialization {

#if defined(_MSC_VER)
#pragma warning( push )
#pragma warning( disable : 4244 4267 )
#endif

/* NOTE : Warning  : Warning : Warning : Warning : Warning
 * Don't ever changes this.  If you do, they previously created
 * binary archives won't be readable !!!
 */
class library_version_type {
private:
    typedef uint_least16_t base_type;
    base_type t;
public:
    library_version_type(): t(0) {}
    explicit library_version_type(const unsigned int & t_) : t(t_){
        BOOST_ASSERT(t_ <= lslboost::integer_traits<base_type>::const_max);
    }
    library_version_type(const library_version_type & t_) :
        t(t_.t)
    {}
    library_version_type & operator=(const library_version_type & rhs){
        t = rhs.t;
        return *this;
    }
    // used for text output
    operator base_type () const {
        return t;
    }
    // used for text input
    operator base_type & (){
        return t;
    }
    bool operator==(const library_version_type & rhs) const {
        return t == rhs.t;
    }
    bool operator<(const library_version_type & rhs) const {
        return t < rhs.t;
    }
};

#if defined(_MSC_VER)
#pragma warning( pop )
#endif

} // serialization
} // boost

#endif // BOOST_SERIALIZATION_LIBRARY_VERSION_TYPE_HPP

max_stars_repo_name: mvidaldp/liblsl-android-builder

max_issues_repo_name: mvidaldp/liblsl-android-builder

max_forks_repo_name: mvidaldp/liblsl-android-builder


text:
#pragma once

#include <iostream>
#include <string>
#include <fstream>
#include <memory>
#include <boost/asio/ts/internet.hpp>
#include <boost/lexical_cast.hpp>
#include <boost/algorithm/string/erase.hpp>

#include <boost/beast.hpp>

#include <cereal/external/base64.hpp>

#include "context.hpp"
#include <system_error>

namespace http = boost::beast::http;

class HTTPClient
{
  public:
    /** @brief Only need the default HTTPClient */
    HTTPClient() = delete;
    ~HTTPClient() = default;
    HTTPClient(const HTTPClient&) = delete;
    HTTPClient& operator=(const HTTPClient&) = delete;
    HTTPClient(HTTPClient&&) = delete;
    HTTPClient& operator=(HTTPClient&&) = delete;

    HTTPClient(const std::string& host, const std::string& port):
        m_ep(boost::asio::ip::address::from_string(host), boost::lexical_cast<int>(port)),
        m_sock(m_ios)
    {
        m_sock.open(m_ep.protocol());
    }
    void connect()
    {
      m_sock.connect(m_ep);
    }
    void close()
    {
      m_sock.shutdown(boost::asio::ip::tcp::socket::shutdown_both);
      m_sock.close();
    }
  /** Send POST request to tus-server */
  bool requestNewResourse(Context& ctx, std::string& resourse, const std::string& path, const std::string& metadata,
                          const std::size_t length, const std::string name)
  {
    if (path.empty() || !resourse.empty() || ctx.ec)
    {
      return false;
    }
    //std::size_t length = 10;
    std::size_t offset = 0;
    // Set up extra header fields for request message
    std::map<std::string, std::string> fields;
    fields["Tus-Resumable"] = tus_version;
    fields["Upload-length"] = std::to_string(length);
    fields["Upload-Metadata"] = "data " + base64encode(metadata) + ",filename " + base64encode(name);
    http::response<http::dynamic_body> msg;
    const char* body = nullptr;
    // Send the HTTP request to the remote host
    HTTPRequest(http::verb::post, path, fields, msg, body, 0);
    if (msg.base().result_int() == 500)
    {
      std::cout << "requestNewResourse. Response returned with status code "
        << msg.base().result_int() << "\n";
      ctx.ec = std::make_error_code(std::errc::bad_message);
      return false;
    }
    // Check that response is OK.
    if (msg.base().result_int() != 201)
    {
      std::cout << "requestNewResourse. Response returned with status code "
        << msg.base().result_int() << "\n";
      ctx.ec = std::make_error_code(std::errc::resource_unavailable_try_again);
      return false;
    }
    // Try to get field <Location>
    resourse = findField(msg, "Location");
    if (!resourse.empty())
    {
      std::cout << "Location: " << resourse << std::endl;  // TODO: test
      m_length = length;
      m_offset = offset;
    }
    return !resourse.empty();
  }

  bool requestInfo(Context& ctx, const std::string& path)
  {
    if (path.empty() || ctx.ec)
    {
      return false;
    }
    // Set up extra header fields for request message
    std::map<std::string, std::string> fields;
    fields["Tus-Resumable"] = tus_version;
    http::response<http::dynamic_body> msg;
    const char* body = nullptr;
    // Send the HTTP request to the remote host
    HTTPRequest(http::verb::head, path, fields, msg, body, 0);
    //std::cout << "Msg response:\n" << msg << std::endl;  // TODO: test response of GET
    // std::cout << "Msg status: " << msg.base().result_int() << std::endl; // TODO: test status response of GET
    // Check that response is OK.
    if (msg.base().result_int() == 200)
    {
      // Find field <Upload-Length> and <Upload-Offset>
      //std::cout << "Response returned with status code " << msg.base().result_int() << "\n";
      auto length = boost::lexical_cast<std::size_t>(findField(msg, "Upload-Length"));
      auto offset = boost::lexical_cast<std::size_t>(findField(msg, "Upload-Offset"));
      auto meta = findField(msg, "Upload-Metadata");
      //std::cout << "Upload-Length: " << length << std::endl;
      if (length != 0 && length > offset && checkMetadata(meta))
      {
        m_length = length;
        m_offset = offset;
        return true;
      }
      if (length != 0 && length == offset && checkMetadata(meta))  // If file upload is finished, then start new upload.
      {
        ctx.finished = true;
        return true;
      }
      ctx.ec = std::make_error_code(std::errc::invalid_argument);
      return true;
    }
    if (msg.base().result_int() == 500)
    {
    std::cout << "Response returned with status code " << msg.base().result_int() << "\n";
    ctx.ec = std::make_error_code(std::errc::operation_canceled);
    return true;
    }
    std::cout << "Response returned with status code " << msg.base().result_int() << "\n";
    ctx.ec = std::make_error_code(std::errc::not_connected);
    return true;
  }

  bool sendFile(Context& ctx, const std::string& path, const std::string& nameOfFile, std::size_t lengthOfBlock)
  {
    if (path.empty() || nameOfFile.empty() || ctx.ec || ctx.finished)
    {
      return false;
    }
    http::response<http::dynamic_body> msg;
    {
      std::map<std::string, std::string> fields;
      fields["Tus-Resumable"] = tus_version;
      fields["Upload-Offset"] = std::to_string(m_offset);
      fields["Content-Type"]  = "application/offset+octet-stream";
      // create buffer for data
      std::unique_ptr<char[]> bodybuf(new char[lengthOfBlock]);
      // read block of data:
      auto sizeOfBody = readLog(nameOfFile, bodybuf.get(), lengthOfBlock);
      // Send the HTTP request to the remote host
      HTTPRequest(http::verb::patch, path, fields, msg, bodybuf.get(), sizeOfBody);
    }
    // Check that response is OK.
    //std::cout << "Msg response:\n" << msg << std::endl;  // TODO: test response of GET
    if (msg.base().result_int() != 204)
    {
      std::cout << "sendFile. Response returned with status code "
        << msg.base().result_int() << "\n";
      ctx.ec = std::make_error_code(std::errc::resource_unavailable_try_again);
      return false;
    }
    const auto value = findField(msg, "Upload-Offset");
    if (value.empty())
    {
      ctx.ec = std::make_error_code(std::errc::bad_message);
      return false;
    }
    auto offset = boost::lexical_cast<std::size_t>(value);
    if (offset < m_length)
    {
      m_offset = offset;
      return true;
    }
    if (offset == m_length)
    {
      ctx.finished = true;
      return false;
    }
    //std::cout << "sendFile. status code: " << msg.base().result_int() << std::endl;
    ctx.ec = std::make_error_code(std::errc::resource_unavailable_try_again);
    return false;
  }

  private:
  boost::asio::io_context m_ios;
  boost::asio::ip::tcp::endpoint m_ep;
  boost::asio::ip::tcp::socket m_sock;

  const int version = 11;
  const std::string tus_version = "1.0.0";

  std::size_t m_length{0};
  std::size_t m_offset{0};

  template<bool isRequest, class Body, class Allocator>
  std::string findField(http::message<
    isRequest,
    Body,
    http::basic_fields<Allocator>>& msg,
    const std::string& field)
  {
    auto it = msg.find(field);
    if(it == msg.end())
    {
      return std::string{};
    }
    return it->value().to_string();
  }

  template<bool isRequest, class Body, class Allocator>
  int HTTPRequest(
    http::verb method,
    const std::string& path,
    const std::map<std::string, std::string>& fields,
    http::message<isRequest, Body, http::basic_fields<Allocator>>& msg,
    const char* body,
    std::size_t sizeOfBody
    )
  {
    //_s.expires_after(std::chrono::seconds(30));
    connect();
    // Set up an HTTP request message
    http::request<http::dynamic_body> req{method, path, version};
    req.set(http::field::host, m_ep.address().to_string());
    req.set(http::field::user_agent, BOOST_BEAST_VERSION_STRING);
    req.set(http::field::accept, "*/*");
    req.set(http::field::connection, "close");
    for (const auto& [key, value] : fields)
    {
      req.set(key, value);
    }
    if (sizeOfBody > 0)
    {
      boost::beast::ostream(req.body()).write(body, sizeOfBody);
      req.set(http::field::content_length, req.body().size());
    }
    // Send the HTTP request to the remote host
    http::write(m_sock, req);
    // Receive the HTTP response
    boost::beast::flat_buffer buffer;
    http::read(m_sock, buffer, msg);
    close();
    return 0;
  }

  bool checkMetadata(std::string metadata)
  {
    return true;
  }

  std::string base64encode(std::string data)
  {
    //boost::erase_all(data, " ");  // TODO: need to remain whitespace in "LogCollectionTimestamp"
    boost::erase_all(data, "\n");
    return cereal::base64::encode(reinterpret_cast<const unsigned char *>(data.c_str()), data.size());
  }

  std::size_t readLog(const std::string& nameOfFile, char* bodybuf, std::size_t lengthOfBlock)
  {
    std::ifstream is(nameOfFile, std::ifstream::binary);
    if (!is)
    {
      throw std::errc::bad_file_descriptor;
    }
    is.seekg(m_offset);
    // read data as a block:
    return is.readsome(bodybuf, lengthOfBlock);
  }
};


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 _MSC_VER
#   define BOOST_TEST_DYN_LINK
#endif

#include <boost/test/unit_test.hpp>

#include <ignite/odbc/parser.h>

using namespace ignite::odbc;

struct TestMessage
{
    TestMessage() : a(0), b()
    {
        // No-op.
    }

    TestMessage(int32_t a, const std::string& b) : a(a), b(b)
    {
        // No-op.
    }

    ~TestMessage()
    {
        // No-op.
    }

    void Write(ignite::impl::binary::BinaryWriterImpl& writer) const
    {
        writer.WriteInt32(a);
        writer.WriteString(b.data(), static_cast<int32_t>(b.size()));
    }

    void Read(ignite::impl::binary::BinaryReaderImpl& reader, const ProtocolVersion&)
    {
        a = reader.ReadInt32();

        b.resize(reader.ReadString(0, 0));
        reader.ReadString(&b[0], static_cast<int32_t>(b.size()));
    }

    int32_t a;
    std::string b;
};

bool operator==(const TestMessage& lhs, const TestMessage& rhs)
{
    return lhs.a == rhs.a &&
           lhs.b == rhs.b;
}

BOOST_AUTO_TEST_SUITE(ParserTestSuite)

BOOST_AUTO_TEST_CASE(TestParserEncodeDecode)
{
    Parser parser;

    std::vector<int8_t> buffer;

    TestMessage outMsg(42, "Test message");
    TestMessage inMsg;

    parser.Encode(outMsg, buffer);

    parser.Decode(inMsg, buffer);

    BOOST_REQUIRE(outMsg == inMsg);
}

BOOST_AUTO_TEST_SUITE_END()

ext: cpp

max_stars_repo_name: ntikhonov/ignite

max_issues_repo_name: ntikhonov/ignite

max_forks_repo_name: ntikhonov/ignite


text:
#include "StdAfx.h"
#include "PullReplicationService.h"

#include "AppLog.h"
#include "Settings.h"

//compiler complains about std::copy inside of boost
#pragma warning(disable:4996)
#include <boost/algorithm/string.hpp>
#pragma warning(default:4996)

#include <boost/foreach.hpp>

PullReplicationService::PullReplicationService(const boost::asio::ip::tcp::endpoint& replicationMasterEndpoint,
	int pullFrequency, iwvfs::ExistenceIndex::ptr existenceIndex, IAsyncStorageBackend::ptr storageBackend)
	: _replicationMasterEndpoint(replicationMasterEndpoint), _pullFrequency(pullFrequency), _existenceIndex(existenceIndex),
		_storageBackend(storageBackend), _stop(false), _serviceThread(), _ioService(), _connected(false),
		_reconnectTimer(_ioService), _currentStep(RS_NONE), _replRestartTimer(_ioService)
{
	_batchSize = whip::Settings::instance().get("pull_replication_batch_size").as<unsigned int>();
}

PullReplicationService::~PullReplicationService()
{
}

void PullReplicationService::start()
{
	SAFELOG(AppLog::instance().out() << "[REPL] Starting pull replication service for master " << _replicationMasterEndpoint << std::endl);

	_work.reset(new boost::asio::io_service::work(_ioService));
	_stop = false;
	_serviceThread = boost::thread(boost::bind(&PullReplicationService::run, this));
}

void PullReplicationService::run()
{
	this->runStep();
	_ioService.run();
	SAFELOG(AppLog::instance().out() << "[REPL] Pull replication thread finished " << _replicationMasterEndpoint << std::endl);
}

void PullReplicationService::runStep()
{
	if (_stop) return;

	//first thing's first. we need a connection
	if (! this->verifyConnection()) return;
	//if we have a connection we can resume or start replication
	this->replicateStep();
}

bool PullReplicationService::verifyConnection()
{
	if (_stop) return false;

	if (_currentStep == RS_NONE || _currentStep == RS_WAIT || _currentStep == RS_NOMASTER) {
		std::string master = whip::Settings::instance().replicationMaster();

		if (master != "") {
			boost::asio::ip::tcp::endpoint ep(whip::Settings::ParseHostPortPairToTcpEndpoint(master));

			if (ep != _replicationMasterEndpoint) {
				SAFELOG(AppLog::instance().out() << "[REPL] Replication master has changed, reconnecting to new master " << ep << std::endl);
				_currentStep = RS_NONE;
				_replicationMasterEndpoint = ep;

				if (_assetSvc && _connected) {
					_assetSvc->close();
					return false;
				}
			}

		} else {
			if (_currentStep != RS_NOMASTER) {
				SAFELOG(AppLog::instance().out() << "[REPL] This server is no longer a replication pull slave" << std::endl);
				_currentStep = RS_NOMASTER;
				_assetSvc->close();
			}

			return true;
		}
	}

	if (! _assetSvc) {
		//create a new asset service
		_assetSvc.reset(new RemoteAssetService(_replicationMasterEndpoint, _ioService));
		_assetSvc->setSafekillCallback(boost::bind(&PullReplicationService::onServerConnectionFailed, this, _1));
	}

	if (! _connected) {
		SAFELOG(AppLog::instance().out() << "[REPL] Attempting connection to replication master " << _replicationMasterEndpoint << std::endl);
		_assetSvc->connect(boost::bind(&PullReplicationService::onServiceConnectionStatus, this, _1, _2));
		return false;
	}

	return true;
}

void PullReplicationService::onServiceConnectionStatus(RemoteAssetService::ptr service, bool success)
{
	if (! success) {
		//we failed. retry connection in 10 seconds
		_reconnectTimer.expires_from_now(boost::posix_time::seconds(10));
		_reconnectTimer.async_wait(boost::bind(&PullReplicationService::verifyConnection, this));
		return;
	}

	//Otherwise we're connected to the master server. So we should start/continue the replication process
	_connected = true;
	this->runStep();
}

void PullReplicationService::replicateStep()
{
	switch (_currentStep) {
	case RS_NONE:
		_currentAssetPrefix = whip::Settings::instance().get("pull_replication_start_at").as<int>();
		//fallthrough

	case RS_IDLIST:
		this->retrieveIdListForPrefix();
		break;

	case RS_RETRIEVE:
		this->retrieveNextMissingAssetBatch();
		break;

	case RS_WAIT:
		this->checkResumeNextReplRound();
		break;

	case RS_NOMASTER:
		this->setReplicationRestartTimer();
		break;
	}
}

void PullReplicationService::checkResumeNextReplRound()
{
	if (boost::posix_time::second_clock::universal_time() >= _nextReplStart) {
		_currentStep = RS_NONE;
		this->runStep();
	} else {
		this->setReplicationRestartTimer();
	}
}

void PullReplicationService::retrieveIdListForPrefix()
{
	_assetSvc->getStoredAssetIDsWithPrefix(this->getStringPrefixForIndex(), boost::bind(&PullReplicationService::onGetStoredAssetIds, this, _1, _2, _3));
}

std::string PullReplicationService::getStringPrefixForIndex()
{
	std::stringstream hexNum;
	hexNum << std::setfill('0') << std::setw(whip::Settings::UUID_PATH_CHARS) << std::hex << _currentAssetPrefix;

	return hexNum.str();
}

void PullReplicationService::onGetStoredAssetIds(Asset::ptr asset, RASError error, std::string ids)
{
	if (! _connected) {
		return;
	}

	if (! error) {
		//parse the stored ids to retain a list
		if (ids == "") {
			//no ids here, move on
			this->retrieveNextIdList();
			return;
		}

		//_pendingAssets.swap(std::queue<std::string>());
		std::queue<std::string> empty;
		std::swap(_pendingAssets, empty);

		std::vector<std::string> idList;
		boost::split(idList, ids, boost::is_any_of(","));

		BOOST_FOREACH(const std::string& id, idList)
		{
			if (id != "" && !_existenceIndex->assetExists(id)) {
				_pendingAssets.push(id);
			}
		}

		if (_pendingAssets.empty()) {
			this->retrieveNextIdList();
		} else {
			SAFELOG( AppLog::instance().out() << "[REPL] Requesting " << _pendingAssets.size()
				<< " assets for pull [" << this->getStringPrefixForIndex() << "]" << std::endl );
			_currentStep = RS_RETRIEVE;
			this->runStep();
		}
	} else {
		SAFELOG( AppLog::instance().error() << "[REPL] Error requesting asset list from master: " << ids << std::endl );
		if (! error.isFatal()) this->runStep();
	}

}

void PullReplicationService::retrieveNextIdList()
{
	_currentStep = RS_IDLIST;
	_currentAssetPrefix++;

	if (_currentAssetPrefix <= 0xfff) {
		this->runStep();
	} else {
		//replication is finished
		_currentAssetPrefix = 0;
		_currentStep = RS_WAIT;

		_nextReplStart = boost::posix_time::second_clock::universal_time() + boost::posix_time::minutes(_pullFrequency);
		SAFELOG( AppLog::instance().out() << "[REPL] Pull replication run completed from " << _replicationMasterEndpoint
			<< ". Next replication run will begin at " << _nextReplStart << std::endl );
		this->setReplicationRestartTimer();
	}
}

void PullReplicationService::setReplicationRestartTimer()
{
	_replRestartTimer.expires_from_now(boost::posix_time::seconds(5));
	_replRestartTimer.async_wait(boost::bind(&PullReplicationService::runStep, this));
}

void PullReplicationService::retrieveNextMissingAssetBatch()
{
	if (_pendingAssets.empty()) {
		this->retrieveNextIdList();

	} else {
		unsigned int requestsSent = 0;

		while (! _pendingAssets.empty()) {
			const std::string& nextAsset = _pendingAssets.front();

			if (_existenceIndex->assetExists(nextAsset)) {
				_pendingAssets.pop();
				continue;
			} else {
				_inProgressAssets.insert(nextAsset);
				requestsSent++;
				_assetSvc->getAsset(nextAsset, false, boost::bind(&PullReplicationService::onAssetRetrieved, this, _1, _2, _3, nextAsset));
				_pendingAssets.pop();

				if (requestsSent == _batchSize)
				{
					break;
				}
			}
		}

		if (requestsSent == 0)
		{
			//there was nothing to retrieve, we need to step again
			this->retrieveNextIdList();
		}
	}
}

void PullReplicationService::onAssetRetrieved(Asset::ptr asset, RASError error, std::string errorMesg, std::string assetId)
{
	if (! _connected) {
		return;
	}

	if (error) {
		//an asset error isn't fatal. the only way we disconnect is a protocol or connection error,
		//so we continue replication until we get a safekill message
		SAFELOG(AppLog::instance().error() << "[REPL] Unable to retrieve asset " << assetId
			<< " from replication server " << _replicationMasterEndpoint << ": " << errorMesg << std::endl);

		_inProgressAssets.erase(assetId);
		if (! error.isFatal() && _inProgressAssets.size() == 0)
		{
			this->runStep();
		}
	} else {
		//we have the asset, write it locally
		_storageBackend->storeAsset(asset, boost::bind(&PullReplicationService::onAfterAssetStoredStub, this, _1, _2, assetId));
	}
}

void PullReplicationService::onAfterAssetStoredStub(bool success, AssetStorageError::ptr error, std::string assetId)
{
	_ioService.post(boost::bind(&PullReplicationService::onAfterAssetStored, this, success, error, assetId));
}

void PullReplicationService::onAfterAssetStored(bool success, AssetStorageError::ptr error, std::string assetId)
{
	if (! success) {
		SAFELOG(AppLog::instance().error() << "[REPL] Unable to save asset " << assetId
			<< " from replication server " << _replicationMasterEndpoint << ": " << error->what() << std::endl);
	}

	_inProgressAssets.erase(assetId);

	if (_inProgressAssets.size() == 0)
	{
		this->runStep();
	}
}

void PullReplicationService::doStop()
{
	_stop = true;
	_assetSvc->close();
	_work.reset();
}

void PullReplicationService::stop()
{
	_ioService.post(boost::bind(&PullReplicationService::doStop, this));
	_serviceThread.join();
}

void PullReplicationService::onServerConnectionFailed(RemoteAssetService::ptr remoteServer)
{
	if (_connected) {
		_connected = false;
		_assetSvc.reset();

		SAFELOG(AppLog::instance().error() << "[REPL] Master server connection to " <<
			_replicationMasterEndpoint << " failed " << std::endl);

		//a return from asset storage will call runstep, so we need to make sure we only call it once
		if (_inProgressAssets.size() == 0 && _currentStep != RS_NOMASTER && _currentStep != RS_WAIT) {
			this->runStep();
		} else if (_currentStep == RS_NOMASTER) {
			this->setReplicationRestartTimer();
		}
	}
}


text: #include <boost/mpi/allocator.hpp>


text:
#define BOOST_TEST_MODULE SimpListTests
#include <boost/test/included/unit_test.hpp>
#include <boost/archive/text_oarchive.hpp>
#include <boost/archive/text_iarchive.hpp>
#include <boost/filesystem.hpp>
#include "TodoController.hpp"
#include <fstream>
#include <iostream>
#include <string>

//Where to save listItems
const std::string LISTITEM_STORE = "listitems.list";
static std::string listStringLocation = std::string(getenv("HOME")) + std::string("/.simplist");

//Utility function because std::algorithm shit the bed earlier.
bool contains(std::vector<std::string>* collection, std::string searchTerm)
{
    bool contains = false;
    for(unsigned int iter = 0; iter < collection->size(); ++iter)
    {
        if(collection->at(iter) == searchTerm)
            contains = !contains;
    }
    return contains;
}

BOOST_AUTO_TEST_CASE(test_list_create)
{
    std::cout << "-----------------------STARTING TEST------------------\n";
    ListItem g("Hello World");
    g.setTodoBody("good morning");

    ListItemLoadWrapper wrap = ListItemLoadWrapper();
    wrap.addItem(&g);
    std::string listName = "readWriteExample";
    std::string fileName = listName + ".list";
    wrap.writeToFile(listStringLocation + "/" + fileName);

    TodoController controller = TodoController();
    std::vector<std::string> controlLists = controller.getLists();

    BOOST_TEST(contains(&controlLists,listName));
    std::cout << "-----------------------TEST END------------------\n";
}

BOOST_AUTO_TEST_CASE(test_load_from_file)
{
    std::cout << "-----------------------STARTING TEST------------------\n";
    TodoController controller = TodoController();
    BOOST_TEST(controller.showLists() != "");
    std::cout << "-----------------------TEST END------------------\n";
}

BOOST_AUTO_TEST_CASE(test_add_list)
{
    std::cout << "-----------------------STARTING TEST------------------\n";
    TodoController controller = TodoController();
    controller.addList("Example");

    std::vector<std::string> controlLists = controller.getLists();

    BOOST_TEST(contains(&controlLists,"Example"));
    std::cout << "-----------------------TEST END------------------\n";
}

BOOST_AUTO_TEST_CASE(test_delete_list)
{
    std::cout << "-----------------------STARTING TEST------------------\n";
    TodoController controller = TodoController();
    std::string listName = "readWriteExample";
    controller.deleteList(listName);

    std::vector<std::string> controlLists = controller.getLists();

    BOOST_TEST(!contains(&controlLists,"readWriteExample"));
    std::cout << "-----------------------TEST END------------------\n";
}

//Empty list tests.
BOOST_AUTO_TEST_CASE(test_show_empty_list)
{
    std::cout << "-----------------------STARTING TEST------------------\n";
    TodoController controller = TodoController();
    controller.addList("Empty");
    std::string listShow = controller.showList("Empty");

    //std::cout << listShow << std::endl;
    BOOST_TEST(listShow.find(std::string("Empty")) != std::string::npos);

    std::cout << "-----------------------TEST END------------------\n";
}

BOOST_AUTO_TEST_CASE(test_delete_empty_list)
{
    std::cout << "-----------------------STARTING TEST------------------\n";
    TodoController controller = TodoController();
    std::string listName = "Empty";
    controller.deleteList(listName);

    std::vector<std::string> controlLists = controller.getLists();
    BOOST_TEST(!contains(&controlLists,"Empty"));
    std::cout << "-----------------------TEST END------------------\n";
}

// Make sure .list file is deleted from disk after list is deleted.
BOOST_AUTO_TEST_CASE(test_list_deleted_from_disk)
{
    std::cout << "-----------------------STARTING TEST------------------\n";
    std::string listName = "Empty";

    boost::filesystem::path p(".");
    boost::filesystem::directory_iterator end_itr;

    //Look through directory to see if listName exists.
    for(boost::filesystem::directory_iterator itr(p); itr != end_itr; ++itr)
    {
        std::string current_file = itr->path().string();
        //Check for file. Make sure is not directory or non-.list
        if(boost::filesystem::is_regular_file(itr->path())
            && current_file.find(listName) != std::string::npos)
        {
            //Failed to delete listName.
            BOOST_TEST(false);
        }
    }
    std::cout << "-----------------------TEST END-----------------------\n";
}

BOOST_AUTO_TEST_CASE(test_add_to_empty_list)
{
    std::cout << "-----------------------STARTING TEST------------------\n";
    TodoController controller = TodoController();
    controller.addList("emptyTest");
    boost::gregorian::date dead(2002,1,10);
    controller.addToList("emptyTest","NewInEmpty",dead,"3:00PM","AllArgsUsed");

    //std::cout << "Failure\n";
    //controller.showLists();
    BOOST_TEST(controller.showList("emptyTest").find("NewInEmpty") != std::string::npos);
    std::cout << "-----------------------TEST END------------------\n";
}

BOOST_AUTO_TEST_CASE(test_edit_list_item)
{
    std::cout << "-----------------------STARTING TEST------------------\n";
    TodoController controller = TodoController();

    boost::gregorian::date dead(2002,2,10);
    controller.editList("emptyTest","NewInEmpty",dead,"4:00AM","AllArgs");

    //Make sure time is now differant in output.
    BOOST_TEST(controller.showList("emptyTest").find("3:00PM") == std::string::npos);
    std::cout << "-----------------------TEST END------------------\n";
}

const static unsigned int LIST_LOAD_SIZE = 50;
const static std::string LIST_FILE_LOAD = "exampleLoadTest.list";
//Wrapper tests.
BOOST_AUTO_TEST_CASE(test_heavy_wrapper_load)
{
    std::cout << "-----------------------STARTING TEST------------------\n";

    std::vector<ListItem> verifyCopies;

    {
        ListItemLoadWrapper wrapper = ListItemLoadWrapper();

        for(unsigned int iter = 0; iter < LIST_LOAD_SIZE; ++iter)
        {
            //Create Object.
            ListItem toAdd = ListItem("Example item " + (char)('0' + iter));
            toAdd.setTodoBody("Standard body");

            //Push object to be stored into two differant vectors.
            wrapper.addItem(&toAdd);
            verifyCopies.push_back(toAdd);
        }

        //Pickle the archive
        wrapper.writeToFile(LIST_FILE_LOAD);
    }

    ListItemLoadWrapper loader = ListItemLoadWrapper();
    loader.loadFromFile(LIST_FILE_LOAD);

    //Load and compare loaded vector to pre loaded vector.
    for(unsigned int iter = 0; iter < loader.wrapArray.size(); ++iter)
    {
        std::string loadName = loader.wrapArray.at(iter).getTodoName();
        BOOST_TEST(loadName == verifyCopies.at(iter).getTodoName());
    }

    std::cout << "-----------------------TEST END------------------\n";
}

//Test scheduling method.
BOOST_AUTO_TEST_CASE(test_check_dead_lines)
{
    std::cout << "-----------------------STARTING TEST------------------\n";
    TodoController controller = TodoController();
    //Example items that SHOULD get output.
    boost::posix_time::ptime local = boost::posix_time::second_clock::local_time();

    int hours = local.time_of_day().hours();
    int minutes = (local.time_of_day().minutes() + 2);

    //std::string hourString = local.time_of_day().hours() + ":" + (local.time_of_day().minutes() + 2);
    /*
    std::cout << "HOURS:" << hours;
    std::cout << ":";
    std::cout << "MINUTES:" << minutes << std::endl;
    */
    std::string hourString = std::to_string(hours) + ":" + std::to_string(minutes);

    //Create list to pump full of deadlines
    controller.addList("deadLines");
    //Example items that SHOULD NOT get output
    controller.addToList("deadLines","NotDue",boost::gregorian::from_string("2024/1/1"),"3:00PM","This is not due");

    controller.addToList("deadLines","NotDueToo",boost::gregorian::from_string("2020/1/1"),"3:00PM","This is not due");

    BOOST_TEST(controller.checkDeadLines().find("NotDue") == std::string::npos);

    controller.addToList("deadLines","NotDueToo",local.date(),hourString,"This is not due");

    BOOST_TEST(controller.checkDeadLines().find("NotDue") != std::string::npos);

    //Add some far away dates that should not illicit a response.
    std::cout << "-----------------------TEST END------------------\n";
}

max_stars_repo_name: IsaacMilarky/simpList

max_issues_repo_name: IsaacMilarky/simpList

max_forks_repo_name: IsaacMilarky/simpList


text:
/*
 * Bullet OSG Framework.
 *
 * Copyright (c) 2015 Jérémie Decock <jd.jdhp@gmail.com>
 *
 * www.jdhp.org
 */

#include "bullet_environment.h"
#include "osg_environment.h"

#include "actuator.h"
#include "actuators/motor.h"

#include "controller.h"
#include "controllers/constant_signal.h"
#include "controllers/sinusoidal_signal.h"

#include "joint.h"
#include "joint_slots/hinge_slot.h"

#include "object.h"

#include "part.h"
#include "parts/sphere.h"
#include "parts/ground.h"

#include "sensor.h"
#include "sensors/clock.h"

#include "tools/common_options_parser.h"
#include "tools/logger_ticks_parts_dat.h"
#include "tools/logger_ticks_parts_json.h"
#include "tools/logger_time_steps_parts_dat.h"
#include "tools/logger_time_steps_parts_json.h"
#include "tools/logger_time_steps_bullet_environment_dat.h"
#include "tools/logger_time_steps_bullet_environment_json.h"
#include "tools/tools.h"

#include <boost/program_options.hpp>
namespace po = boost::program_options;

#include <iostream>
#include <set>
#include <string>

#include <Eigen/Dense>

/*
 * LOCAL OPTIONS
 */

static double radius = 1.;
static double mass = 1.;
static double friction = 0.5;
static double rolling_friction = 0.;
static double restitution = 0.;

static Eigen::Vector3d initial_position;
static Eigen::Vector4d initial_angle;
static Eigen::Vector3d initial_velocity;
static Eigen::Vector3d initial_angular_velocity;
static Eigen::Vector3d initial_inertia;

static std::string initial_position_str_opt         = "0.,0.,4.";
static std::string initial_angle_str_opt            = "0.,0.,0.,1.";
static std::string initial_velocity_str_opt         = "0.,0.,0.";
static std::string initial_angular_velocity_str_opt = "0.,0.,0.";
static std::string initial_inertia_str_opt          = "0.,0.,0.";

/*
 * MAIN FUNCTION
 */

int main(int argc, char * argv[]) {

    // Parse program params ///////////////////////////////////////////////////

    // Declare the group of local options that are allowed on command line and config file

    /*
     * Validates bool value
     * (see $(BOOST_ROOT)/libs/program_options/src/value_semantic.cpp):
     *
     * Any of "1", "true", "yes", "on" will be converted to "1".
     * Any of "0", "false", "no", "off" will be converted to "0".
     * Case is ignored. The 'xs' vector can either be empty, in which
     * case the value is 'true', or can contain explicit value.
     */

    po::options_description local_options_desc;
    local_options_desc.add_options()
        ("mass",             po::value<double>(&mass)->default_value(mass), "set the sphere mass (in kilograms). Expects a decimal number.")
        ("friction",         po::value<double>(&friction)->default_value(friction), "set the sphere and the ground friction value. Expects a decimal number (ideally between 0. and 1.). Best simulation results when friction is non-zero.")
        ("rolling_friction", po::value<double>(&rolling_friction)->default_value(rolling_friction), "set the sphere rolling friction value. Expects a decimal number (ideally between 0. and 1.).")
        ("restitution",      po::value<double>(&restitution)->default_value(restitution), "set the sphere and the ground restitution value. Expects a decimal number (ideally between 0. and 1.). Best simulation results using zero restitution.")
        ("radius",           po::value<double>(&radius)->default_value(radius), "set the sphere radius (in meters). Expects a decimal number.")
        ("position",         po::value<std::string>(&initial_position_str_opt)->default_value(initial_position_str_opt), "set the initial position vector of the sphere (in meters). Expects a vector of 3 decimal numbers separated with a comma and without space character (e.g. \"1.0,2.0,3.0\").")
        ("angle",            po::value<std::string>(&initial_angle_str_opt)->default_value(initial_angle_str_opt), "set the initial angle of the sphere using a quaternion representation. Expects a vector of 4 decimal numbers separated with a comma and without space character (e.g. \"1.0,2.0,3.0,4.0\").")
        ("velocity",         po::value<std::string>(&initial_velocity_str_opt)->default_value(initial_velocity_str_opt), "set the initial velocity vector of the sphere. Expects a vector of 3 decimal numbers separated with a comma and without space character (e.g. \"1.0,2.0,3.0\").")
        ("angular_velocity", po::value<std::string>(&initial_angular_velocity_str_opt)->default_value(initial_angular_velocity_str_opt), "set the initial angular velocity vector of the sphere. Expects a vector of 3 decimal numbers separated with a comma and without space character (e.g. \"1.0,2.0,3.0\").")
        ("inertia",          po::value<std::string>(&initial_inertia_str_opt)->default_value(initial_inertia_str_opt), "set the initial inertia vector of the sphere. Expects a vector of 3 decimal numbers separated with a comma and without space character (e.g. \"1.0,2.0,3.0\").")
    ;

    // Parse programm options (local and common)

    botsim::CommonOptionsParser options(argc, argv, local_options_desc);

    if(options.exit) {
        return options.exitValue;
    }

    // Assign some options value (vectors)

    initial_position = botsim::string_to_eigen_vector3(initial_position_str_opt);
    initial_angle = botsim::string_to_eigen_vector4(initial_angle_str_opt);
    initial_velocity = botsim::string_to_eigen_vector3(initial_velocity_str_opt);
    initial_angular_velocity = botsim::string_to_eigen_vector3(initial_angular_velocity_str_opt);
    initial_inertia = botsim::string_to_eigen_vector3(initial_inertia_str_opt);

    // Print options value

    if(options.verbose) {
        std::cout << "MASS: " << mass << "kg" << std::endl;
        std::cout << "FRICTION: " << friction << std::endl;
        std::cout << "ROLLING FRICTION: " << rolling_friction << std::endl;
        std::cout << "RESTITUTION: " << restitution << std::endl;
        std::cout << "RADIUS: " << radius << "m" << std::endl;
        std::cout << "INITIAL POSITION: " << botsim::eigen_vector_to_string(initial_position) << std::endl;
        std::cout << "INITIAL ANGLE: " << botsim::eigen_vector_to_string(initial_angle) << std::endl;
        std::cout << "INITIAL VELOCITY: " << botsim::eigen_vector_to_string(initial_velocity) << std::endl;
        std::cout << "INITIAL ANGULAR VELOCITY: " << botsim::eigen_vector_to_string(initial_angular_velocity) << std::endl;
        std::cout << "INITIAL INERTIA: " << botsim::eigen_vector_to_string(initial_inertia) << std::endl;
    }

    // Init Bullet ////////////////////////////////////////////////////////////

    // Pendulum object ////////////////

    // Pendulum parts
    botsim::Sphere * p_sphere = new botsim::Sphere(radius, initial_position, initial_angle, initial_velocity, initial_angular_velocity, initial_inertia, mass, friction, rolling_friction, restitution, "pendulum_sphere");

    std::set<botsim::Part *> pendulum_part_set;
    pendulum_part_set.insert(p_sphere);

    // Pendulum joints
    std::set<botsim::Joint *> pendulum_joint_set;

    // Pendulum actuators
    Eigen::Vector3d pendulum_hinge_pivot(0., 0., 2.);
    Eigen::Vector3d pendulum_hinge_axis(0., 1., 0.);
    botsim::HingeSlot * p_pendulum_hinge_slot = new botsim::HingeSlot(pendulum_hinge_pivot, pendulum_hinge_axis);
    botsim::Motor * p_pendulum_motor = new botsim::Motor(p_sphere, p_pendulum_hinge_slot, "pendulum_motor");

    std::set<botsim::Actuator *> pendulum_actuator_set;
    pendulum_actuator_set.insert(p_pendulum_motor);

    // Pendulum object
    botsim::Object * p_pendulum = new botsim::Object(pendulum_part_set, pendulum_joint_set, pendulum_actuator_set, "pendulum");

    // Other parts ////////////////////

    // Ground
    botsim::Ground * p_ground = new botsim::Ground(friction, rolling_friction, restitution);

    // Controllers ////////////////////

    botsim::Clock * p_clock_sensor = new botsim::Clock(NULL, "clock");  // TODO: UGLY WORKAROUND !
    std::set<botsim::Sensor *> sensor_set;
    sensor_set.insert(p_clock_sensor);

    //botsim::ConstantSignal * p_pendulum_controller = new botsim::SinusoidalSignal(pendulum_actuator_set, sensor_set, 2.0, "pendulum_controller");
    botsim::SinusoidalSignal * p_pendulum_controller = new botsim::SinusoidalSignal(pendulum_actuator_set, sensor_set, 4., 0.25, 3.14/2., "pendulum_controller");

    // Bullet environment /////////////

    // Bullet object set
    std::set<botsim::Object *> bullet_object_set;
    bullet_object_set.insert(p_pendulum);

    // Bullet part set
    std::set<botsim::Part *> bullet_part_set;
    bullet_part_set.insert(p_ground);

    // Controller set
    std::set<botsim::Controller *> controller_set;
    controller_set.insert(p_pendulum_controller);

    // Bullet environment
    botsim::BulletEnvironment * p_bullet_environment = new botsim::BulletEnvironment(bullet_object_set, bullet_part_set, controller_set, options.timeStepDurationSec, options.tickDurationSec, options.maxTicksPerTimeStep, options.simulationDurationSec);

    p_clock_sensor->bulletEnvironment = p_bullet_environment;  // TODO: UGLY WORKAROUND !

    // Init log ///////////////////////////////////////////////////////////////

    // Bullet time steps dat log
    botsim::LoggerTimeStepsBulletEnvironmentDat * p_logger_time_steps_bullet_environment_dat = new botsim::LoggerTimeStepsBulletEnvironmentDat();
    p_bullet_environment->attachTimeStepObserver(p_logger_time_steps_bullet_environment_dat);

    // Bullet time steps json log
    botsim::LoggerTimeStepsBulletEnvironmentJson * p_logger_time_steps_bullet_environment_json = new botsim::LoggerTimeStepsBulletEnvironmentJson();
    p_bullet_environment->attachTimeStepObserver(p_logger_time_steps_bullet_environment_json);

    // Parts time steps dat log
    botsim::LoggerTimeStepsPartsDat * p_logger_time_steps_parts_dat = new botsim::LoggerTimeStepsPartsDat(pendulum_part_set);
    p_bullet_environment->attachTimeStepObserver(p_logger_time_steps_parts_dat);

    // Parts time steps json log
    botsim::LoggerTimeStepsPartsJson * p_logger_time_steps_parts_json = new botsim::LoggerTimeStepsPartsJson(pendulum_part_set);
    p_bullet_environment->attachTimeStepObserver(p_logger_time_steps_parts_json);

    // Parts ticks dat log
    botsim::LoggerTicksPartsDat * p_logger_ticks_parts_dat = new botsim::LoggerTicksPartsDat(pendulum_part_set);
    p_bullet_environment->attachTickObserver(p_logger_ticks_parts_dat);

    // Parts ticks json log
    botsim::LoggerTicksPartsJson * p_logger_ticks_parts_json = new botsim::LoggerTicksPartsJson(pendulum_part_set);
    p_bullet_environment->attachTickObserver(p_logger_ticks_parts_json);

    // Run the simulation /////////////////////////////////////////////////////

    botsim::OSGEnvironment * p_osg_environment = NULL;

    if(options.useHeadLessMode) {
        // Run Bullet
        p_bullet_environment->run();
    } else {
        // Init OSG
        p_osg_environment = new botsim::OSGEnvironment(p_bullet_environment, options.useFullScreenMode);

        // Run OSG
        p_osg_environment->run();
    }

    // Clean Bullet ///////////////////////////////////////////////////////////

    delete p_logger_time_steps_bullet_environment_dat;
    delete p_logger_time_steps_bullet_environment_json;
    delete p_logger_time_steps_parts_dat;
    delete p_logger_time_steps_parts_json;
    delete p_logger_ticks_parts_dat;
    delete p_logger_ticks_parts_json;

    std::cout << "Delete Bullet environment." << std::endl;
    delete p_bullet_environment;

    //delete p_sphere;
    delete p_pendulum_hinge_slot;
    delete p_pendulum_motor;
    delete p_pendulum;
    //delete p_ground;
    delete p_clock_sensor;
    delete p_pendulum_controller;

    if(!options.useHeadLessMode) {
        std::cout << "Delete OSG environment." << std::endl;
        delete p_osg_environment;
    }

    std::cout << "Bye." << std::endl;

    return 0;
}

ext: cc

max_stars_repo_name: jeremiedecock/botsim

max_issues_repo_name: jeremiedecock/botsim

max_forks_repo_name: jeremiedecock/botsim


text:
#include <geometry.h>
#include <tiny.h>

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

typedef tiny::MathTypes<float> MT;
typedef MT::quaternion_type    Q;
typedef MT::vector3_type       V;
typedef MT::real_type          T;
typedef MT::value_traits       VT;

BOOST_AUTO_TEST_SUITE(geometry);

BOOST_AUTO_TEST_CASE(inside_obb_test)
{

  {
    V const center   = V::make(0.0, 0.0, 0.0);
    V const half_ext = V::make(1.0, 1.0, 1.0);
    Q const q        = Q::identity();

    geometry::OBB<MT> A = geometry::make_obb<MT>(center, q, half_ext);

    V const p0 = V::make( 0.0,  0.0,  0.0);
    V const p1 = V::make( 1.0,  1.0,  1.0);
    V const p2 = V::make( 2.0,  2.0,  2.0);

    BOOST_CHECK( geometry::inside_obb(p0, A) == true );
    BOOST_CHECK( geometry::inside_obb(p1, A) == true );
    BOOST_CHECK( geometry::inside_obb(p2, A) == false );
  }

  {
    V const center   = V::make(0.0, 0.0, 0.0);
    V const half_ext = V::make(1.0, 1.0, 1.0);
    Q const q        = Q::Rx( VT::pi_half() );

    geometry::OBB<MT> A = geometry::make_obb<MT>(center, q, half_ext);

    V const p0 = geometry::transform_from_obb( V::make( 0.0,  0.0,  0.0), A);
    V const p1 = geometry::transform_from_obb(V::make( 1.0,  1.0,  1.0), A);
    V const p2 = geometry::transform_from_obb(V::make( 2.0,  2.0,  2.0), A);

    BOOST_CHECK( geometry::inside_obb(p0, A) == true );
    BOOST_CHECK( geometry::inside_obb(p1, A) == true );
    BOOST_CHECK( geometry::inside_obb(p2, A) == false );
  }

}

BOOST_AUTO_TEST_SUITE_END();

max_stars_repo_name: diku-dk/PROX

max_issues_repo_name: erleben/matchstick

max_forks_repo_name: erleben/matchstick


text:
/*
 * TopologyTest.cpp
 *
 *  Created on: Jun 13, 2017
 *      Author: quang
 */
#define BOOST_TEST_DYN_LINK
#include <boost/test/unit_test.hpp>

#include "../../../AnyGraph.h"

using namespace anygraph;

BOOST_AUTO_TEST_CASE(TopologyTest) {
	Topology topology;

	AnyNode node1, node2, node3;
	node1.set_ID("n1");
	node2.set_ID("n2");
	node3.set_ID("n3");

	AnyEdge edge1, edge2;
	edge1.set_from("n1");
	edge1.set_to("n2");
	edge2.set_from("n1");
	edge2.set_to("n3");

	Attributes attr1, attr2;
	attr1.set_id("a1");
	attr2.set_id("a2");

	topology.add_node(node1);
	topology.add_node(node2);
	topology.add_node(node3);
	topology.add_edge(edge1);
	topology.add_edge(edge2);
	topology.add_attribute(attr1);
	topology.add_attribute(attr2);

	BOOST_CHECK(topology.get_attributes().size() == 2);
	BOOST_CHECK(topology.get_edge_size() == 2);
	BOOST_CHECK(topology.get_node_size() == 3);
	BOOST_CHECK(topology.get_node()[0].get_ID() == std::string("n1"));
	BOOST_CHECK(topology.get_node()[1].get_ID() == std::string("n2"));
	BOOST_CHECK(topology.get_node()[2].get_ID() == std::string("n3"));
	BOOST_CHECK(topology.get_edge()[0].get_From() == std::string("n1"));
	BOOST_CHECK(topology.get_edge()[0].get_To() == std::string("n2"));
	BOOST_CHECK(topology.get_edge()[1].get_From() == std::string("n1"));
	BOOST_CHECK(topology.get_edge()[1].get_To() == std::string("n3"));
	BOOST_CHECK(topology.get_attributes()[0].get_attribute_id() == std::string("a1"));
	BOOST_CHECK(topology.get_attributes()[1].get_attribute_id() == std::string("a2"));
}


text:
#include <iostream>
#include <boost/filesystem/fstream.hpp>
#include <boost/filesystem/operations.hpp>
#include <GraphMol/FileParsers/MolSupplier.h>
#include <GraphMol/DistGeomHelpers/Embedder.h>
#include <GraphMol/FileParsers/MolWriters.h>
#include <GraphMol/SmilesParse/SmilesParse.h>
#include <GraphMol/Descriptors/MolDescriptors.h>
#include <GraphMol/Substruct/SubstructMatch.h>

using namespace std;
using namespace RDGeom;
using namespace RDKit;
using namespace RDKit::MolOps;
using namespace RDKit::DGeomHelpers;
using namespace RDKit::Descriptors;
using namespace boost::filesystem;
using boost_ofstream = boost::filesystem::ofstream;
using boost_ifstream = boost::filesystem::ifstream;

int main(int argc, char* argv[])
{
	const string sdf_path = argv[1];
	// const path output_confs = "/home/kassa-baghdouche/Documents/USR-VS/USR_FILES/final/ligands_fixed.sdf";
	// boost_ofstream ofs(output_confs, ios::app);
	// SDWriter writer(&cout);
	long counter = 0;
	int16_t c = 0;
	SDMolSupplier sup(sdf_path, true, false, true);
	while (!sup.atEnd())
	{
		// if (c != 4)
		// {
			const unique_ptr<ROMol> qry_ptr(sup.next());
			auto& mol = *qry_ptr;
			string compound = mol.getProp<string>("_Name");
			// if (compound == "PV-001924561275_1_T1")
			// {
				// writer.write(mol);
				// c++;
				counter++;
				// cout << counter << endl;
				// continue;
			// }
			// writer.write(mol);
			// counter++;
			cout << counter << " " << compound << endl;
	}
	// boost_ifstream ifs(sdf_path, ios::ate);
	// ifs.seekg(0);
	// long counter = 0;
	// for (string line; getline(ifs, line);)
	// {
	// 	if (line == "$$$$")
	// 		counter++;
	// 	cout << counter << endl;
	// }
	cout << "Number of writtern compounds are " << counter << endl;
}


text:
// Copyright 2018 Peter Dimov
//
// 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

#include <boost/shared_ptr.hpp>
#include <boost/make_shared.hpp>
#include <boost/config.hpp>
#include <memory>

#if defined(DLL_TEST_DYN_LINK)
# define EXPORT BOOST_SYMBOL_EXPORT
#else
# define EXPORT
#endif

EXPORT boost::shared_ptr<int> dll_test_41()
{
    return boost::shared_ptr<int>( new int( 41 ) );
}

EXPORT boost::shared_ptr<int> dll_test_42()
{
    return boost::make_shared<int>( 42 );
}

EXPORT boost::shared_ptr<int> dll_test_43()
{
    return boost::allocate_shared<int>( std::allocator<int>(), 43 );
}

EXPORT boost::shared_ptr<int[]> dll_test_44()
{
    return boost::make_shared<int[1]>( 44 );
}

EXPORT boost::shared_ptr<int[]> dll_test_45()
{
    return boost::allocate_shared<int[1]>( std::allocator<int>(), 45 );
}

max_stars_repo_name: Jackarain/tinyrpc

max_issues_repo_name: avplayer/cxxrpc

max_forks_repo_name: avplayer/cxxrpc


text:
// Copyright PA Knowledge Ltd 2021
// MIT License. For licence terms see LICENCE.md file.

#ifndef UDPSERVERINTERFACE_HPP
#define UDPSERVERINTERFACE_HPP

#include "BytesBuffer.hpp"

#include <functional>
#include <boost/asio/buffer.hpp>

class UdpServerInterface
{
public:
  explicit UdpServerInterface() = default;

  virtual ~UdpServerInterface() = default;

  using Callback_t = std::function<bool(BytesBuffer&&, BytesBuffer&&)>;

  void setCallback(Callback_t requestedCallback)
  {
    callback = requestedCallback;
  }

protected:
  Callback_t callback;
};

#endif //UDPSERVERINTERFACE_HPP

max_stars_repo_name: oakdoor/enterprisediodefiletransfer

max_issues_repo_name: oakdoor/enterprisediodefiletransfer

max_forks_repo_name: oakdoor/enterprisediodefiletransfer


text:
#define BOOST_TEST_MODULE mcl
#include <boost/test/included/unit_test.hpp>

max_stars_repo_name: nicuveo/MCL

max_issues_repo_name: nicuveo/MCL

max_forks_repo_name: nicuveo/MCL


text:
/* Copyright 2017-2018 PaGMO development team

This file is part of the PaGMO library.

The PaGMO library is free software; you can redistribute it and/or modify
it under the terms of either:

  * the GNU Lesser General Public License as published by the Free
    Software Foundation; either version 3 of the License, or (at your
    option) any later version.

or

  * the GNU General Public License as published by the Free Software
    Foundation; either version 3 of the License, or (at your option) any
    later version.

or both in parallel, as here.

The PaGMO 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 General Public License
for more details.

You should have received copies of the GNU General Public License and the
GNU Lesser General Public License along with the PaGMO library.  If not,
see https://www.gnu.org/licenses/. */

#ifndef PAGMO_ALGORITHMS_SGA_HPP
#define PAGMO_ALGORITHMS_SGA_HPP

#include <algorithm> // std::sort, std::all_of, std::copy
#include <boost/bimap.hpp>
#include <boost/lexical_cast.hpp>
#include <boost/test/floating_point_comparison.hpp>
#include <iomanip>
#include <iostream>
#include <numeric> // std::iota
#include <random>
#include <stdexcept>
#include <string>
#include <tuple>
#include <vector>

#include <pagmo/algorithm.hpp>
#include <pagmo/detail/custom_comparisons.hpp>
#include <pagmo/exceptions.hpp>
#include <pagmo/io.hpp>
#include <pagmo/population.hpp>
#include <pagmo/rng.hpp>
#include <pagmo/utils/generic.hpp> // detail::force_bounds_stick

namespace pagmo
{
namespace detail
{
// Usual template trick to have static members in header only libraries
// see: http://stackoverflow.com/questions/18860895/how-to-initialize-static-members-in-the-header
// All this scaffolding is to establish a one to one correspondance between enums and genetic operator types
// represented as strings.
template <typename = void>
struct sga_statics {
    enum class selection { TOURNAMENT, TRUNCATED };
    enum class crossover { EXPONENTIAL, BINOMIAL, SINGLE, SBX };
    enum class mutation { GAUSSIAN, UNIFORM, POLYNOMIAL };
    using selection_map_t = boost::bimap<std::string, selection>;
    using crossover_map_t = boost::bimap<std::string, crossover>;
    using mutation_map_t = boost::bimap<std::string, mutation>;
    const static selection_map_t m_selection_map;
    const static crossover_map_t m_crossover_map;
    const static mutation_map_t m_mutation_map;
};
// Helper init functions
inline typename sga_statics<>::selection_map_t init_selection_map()
{
    typename sga_statics<>::selection_map_t retval;
    using value_type = typename sga_statics<>::selection_map_t::value_type;
    retval.insert(value_type("tournament", sga_statics<>::selection::TOURNAMENT));
    retval.insert(value_type("truncated", sga_statics<>::selection::TRUNCATED));
    return retval;
}
inline typename sga_statics<>::crossover_map_t init_crossover_map()
{
    typename sga_statics<>::crossover_map_t retval;
    using value_type = typename sga_statics<>::crossover_map_t::value_type;
    retval.insert(value_type("exponential", sga_statics<>::crossover::EXPONENTIAL));
    retval.insert(value_type("binomial", sga_statics<>::crossover::BINOMIAL));
    retval.insert(value_type("sbx", sga_statics<>::crossover::SBX));
    retval.insert(value_type("single", sga_statics<>::crossover::SINGLE));
    return retval;
}
inline typename sga_statics<>::mutation_map_t init_mutation_map()
{
    typename sga_statics<>::mutation_map_t retval;
    using value_type = typename sga_statics<>::mutation_map_t::value_type;
    retval.insert(value_type("gaussian", sga_statics<>::mutation::GAUSSIAN));
    retval.insert(value_type("uniform", sga_statics<>::mutation::UNIFORM));
    retval.insert(value_type("polynomial", sga_statics<>::mutation::POLYNOMIAL));
    return retval;
}
// We now init the various members
template <typename T>
const typename sga_statics<T>::selection_map_t sga_statics<T>::m_selection_map = init_selection_map();
template <typename T>
const typename sga_statics<T>::crossover_map_t sga_statics<T>::m_crossover_map = init_crossover_map();
template <typename T>
const typename sga_statics<T>::mutation_map_t sga_statics<T>::m_mutation_map = init_mutation_map();
} // end namespace detail

/// A Simple Genetic Algorithm
/**
 * \image html sga.jpg "The DNA Helix" width=3cm
 *
 * \verbatim embed:rst:leading-asterisk
 * .. versionadded:: 2.2
 * \endverbatim
 *
 * Approximately during the same decades as Evolutionary Strategies (see pagmo::sea) were studied, a different group
 * led by John Holland, and later by his student David Goldberg, introduced and studied an algorithmic framework called
 * "genetic algorithms" that were, essentially, leveraging on the same idea but introducing also crossover as a genetic
 * operator. This led to a few decades of confusion and discussions on what was an evolutionary startegy and what a
 * genetic algorithm and on whether the crossover was a useful operator or mutation only algorithms were to be
 * preferred.
 *
 * In pagmo we provide a rather classical implementation of a genetic algorithm, letting the user choose between
 * some selected crossover types, selection schemes and mutation types.
 *
 * The pseudo code of our version is:
 * @code{.unparsed}
 * > Start from a pagmo::population (pop) of dimension N
 * > while i < gen
 * > > Selection: create a new population (pop2) with N individuals selected from pop (with repetition allowed)
 * > > Crossover: create a new population (pop3) with N individuals obtained applying crossover to pop2
 * > > Mutation:  create a new population (pop4) with N individuals obtained applying mutation to pop3
 * > > Evaluate all new chromosomes in pop4
 * > > Reinsertion: set pop to contain the best N individuals taken from pop and pop4
 * @endcode
 *
 * The various blocks of pagmo genetic algorithm are listed below:
 *
 * *Selection*: two selection methods are provided: "tournament" and "truncated". Tournament selection works by
 * selecting each offspring as the one having the minimal fitness in a random group of size \p param_s. The truncated
 * selection, instead, works selecting the best \p param_s chromosomes in the entire population over and over.
 * We have deliberately not implemented the popular roulette wheel selection as we are of the opinion that such
 * a system does not generalize much being highly sensitive to the fitness scaling.
 *
 * *Crossover*: four different crossover schemes are provided: "single", "exponential", "binomial", "sbx". The
 * single point crossover, called "single", works selecting a random point in the parent chromosome and inserting the
 * partner chromosome thereafter. The exponential crossover is taken from the algorithm differential evolution,
 * implemented, in pagmo, as pagmo::de. It essentially selects a random point in the parent chromosome and inserts,
 * in each successive gene, the partner values with probability \p cr up to when it stops. The binomial crossover
 * inserts each gene from the partner with probability \p cr. The simulated binary crossover (called "sbx"), is taken
 * from the NSGA-II algorithm, implemented in pagmo as pagmo::nsga2, and makes use of an additional parameter called
 * distribution index \p eta_c.
 *
 * *Mutation*: three different mutations schemes are provided: "uniform", "gaussian" and "polynomial". Uniform mutation
 * simply randomly samples from the bounds. Gaussian muattion samples around each gene using a normal distribution
 * with standard deviation proportional to the \p m_param_m and the bounds width. The last scheme is the polynomial
 * mutation.
 *
 * *Reinsertion*: the only reinsertion strategy provided is what we call pure elitism. After each generation
 * all parents and children are put in the same pool and only the best are passed to the next generation.
 *
 * \verbatim embed:rst:leading-asterisk
 *
 * .. warning::
 *
 *    The algorithm is not suitable for multi-objective problems, nor for
 *    constrained optimization.
 *
 * .. note::
 *
 *    Most genetic operators use the lower and upper bound information. Hence, unbounded problems will produce undefined
 *    behaviours.
 *
 * .. seealso::
 *
 *    Oliveto, Pietro S., Jun He, and Xin Yao. "Time complexity of evolutionary algorithms for
 *    combinatorial optimization: A decade of results." International Journal of Automation and Computing
 *    4.3 (2007): 281-293.
 *
 * .. seealso::
 *
 *    http://www.scholarpedia.org/article/Evolution_strategies
 *
 * \endverbatim
 */
class sga : private detail::sga_statics<>
{
public:
    /// Single entry of the log (gen, fevals, best, improvement)
    typedef std::tuple<unsigned int, unsigned long long, double, double> log_line_type;
    /// The log
    typedef std::vector<log_line_type> log_type;

    /// Constructor
    /**
     * Constructs a simple genetic algorithm.
     *
     * @param gen number of generations.
     * @param cr crossover probability.
     * @param eta_c distribution index for "sbx" crossover. This is an inactive parameter if other types of crossovers
     * are selected.
     * @param m mutation probability.
     * @param param_m distribution index ("polynomial" mutation), gaussian width ("gaussian" mutation) or inactive
     * ("uniform" mutation)
     * @param param_s when "truncated" selection is used this indicates the number of best individuals to use. When
     * "tournament" selection is used this indicates the size of the tournament.
     * @param mutation the mutation strategy. One of "gaussian", "polynomial" or "uniform".
     * @param selection the selection strategy. One of "tournament", "truncated".
     * @param crossover the crossover strategy. One of "exponential", "binomial", "single" or "sbx"
     * @param seed seed used by the internal random number generator
     *
     * @throws std::invalid_argument if \p cr not in [0,1], \p eta_c not in [1, 100], \p m not in [0,1],
     * \p mutation not one of "gaussian", "uniform" or "polynomial", \p selection not one of "roulette" or "truncated"
     * \p crossover not one of "exponential", "binomial", "sbx" or "single", if \p param_m is not in [0,1] and
     * \p mutation is not "polynomial" or \p mutation is not in [1,100] and \p mutation is polynomial.
     */
    sga(unsigned gen = 1u, double cr = .90, double eta_c = 1., double m = 0.02, double param_m = 1.,
        unsigned param_s = 2u, std::string crossover = "exponential", std::string mutation = "polynomial",
        std::string selection = "tournament", unsigned seed = pagmo::random_device::next())
        : m_gen(gen), m_cr(cr), m_eta_c(eta_c), m_m(m), m_param_m(param_m), m_param_s(param_s), m_e(seed), m_seed(seed),
          m_verbosity(0u), m_log()
    {
        if (cr > 1. || cr < 0.) {
            pagmo_throw(std::invalid_argument, "The crossover probability must be in the [0,1] range, while a value of "
                                                   + std::to_string(cr) + " was detected");
        }
        if (eta_c < 1. || eta_c > 100.) {
            pagmo_throw(std::invalid_argument,
                        "The distribution index for SBX crossover must be in [1, 100], while a value of "
                            + std::to_string(eta_c) + " was detected");
        }
        if (m < 0. || m > 1.) {
            pagmo_throw(std::invalid_argument, "The mutation probability must be in the [0,1] range, while a value of "
                                                   + std::to_string(cr) + " was detected");
        }
        if (param_s == 0u) {
            pagmo_throw(std::invalid_argument, "The selection parameter must be at least 1, while a value of "
                                                   + std::to_string(param_s) + " was detected");
        }
        if (mutation != "gaussian" && mutation != "uniform" && mutation != "polynomial") {
            pagmo_throw(
                std::invalid_argument,
                R"(The mutation type must either be "gaussian" or "uniform" or "polynomial": unknown type requested: )"
                    + mutation);
        }
        if (selection != "truncated" && selection != "tournament") {
            pagmo_throw(
                std::invalid_argument,
                R"(The selection type must either be "roulette" or "truncated" or "tournament": unknown type requested: )"
                    + selection);
        }
        if (crossover != "exponential" && crossover != "binomial" && crossover != "sbx" && crossover != "single") {
            pagmo_throw(
                std::invalid_argument,
                R"(The crossover type must either be "exponential" or "binomial" or "sbx" or "single": unknown type requested: )"
                    + crossover);
        }
        // param_m represents the distribution index if polynomial mutation is selected
        if (mutation == "polynomial" && (param_m < 1. || param_m > 100.)) {
            pagmo_throw(std::invalid_argument, "Polynomial mutation was selected, the mutation parameter (distribution "
                                               "index) must be in [1, 100], while a value of "
                                                   + std::to_string(param_m) + " was detected");
        }

        // otherwise param_m represents the width of the mutation relative to the box bounds
        if (mutation != "polynomial" && (param_m < 0 || param_m > 1.)) {
            pagmo_throw(std::invalid_argument, "The mutation parameter must be in [0,1], while a value of "
                                                   + std::to_string(param_m) + " was detected");
        }
        // We can now init the data members representing the various choices made using std::string
        m_crossover = m_crossover_map.left.at(crossover);
        m_mutation = m_mutation_map.left.at(mutation);
        m_selection = m_selection_map.left.at(selection);
    }

    /// Algorithm evolve method (juice implementation of the algorithm)
    /**
     * Evolves the population for a maximum number of generations
     *
     * @param pop population to be evolved
     * @return evolved population
     * @throws std::invalid_argument if the problem is multi-objective or constrained, if the population size is smaller
     * than 2, if \p param_s is larger than the population size, if the size of \p pop is odd and a "sbx" crossover has
     * been selected upon construction.
     */
    population evolve(population pop) const
    {
        const auto &prob = pop.get_problem();
        auto dim_i = prob.get_nix();
        const auto bounds = prob.get_bounds();
        auto NP = pop.size();
        auto fevals0 = prob.get_fevals(); // fevals already made
        auto count = 1u;                  // regulates the screen output
        // PREAMBLE-------------------------------------------------------------------------------------------------
        // Check whether the problem/population are suitable for bee_colony
        if (prob.get_nc() != 0u) {
            pagmo_throw(std::invalid_argument, "Constraints detected in " + prob.get_name() + " instance. " + get_name()
                                                   + " cannot deal with them");
        }
        if (prob.get_nf() != 1u) {
            pagmo_throw(std::invalid_argument, "Multiple objectives detected in " + prob.get_name() + " instance. "
                                                   + get_name() + " cannot deal with them");
        }
        if (NP < 2u) {
            pagmo_throw(std::invalid_argument, prob.get_name() + " needs at least 2 individuals in the population, "
                                                   + std::to_string(NP) + " detected");
        }
        if (m_param_s > pop.size()) {
            pagmo_throw(std::invalid_argument,
                        "The parameter for selection must be smaller than the population size, while a value of: "
                            + std::to_string(m_param_s)
                            + " was detected in a population of size: " + std::to_string(pop.size()));
        }
        if (m_crossover == crossover::SBX && (pop.size() % 2 != 0u)) {
            pagmo_throw(std::invalid_argument,
                        "Population size must be even if sbx crossover is selected. Detected pop size is: "
                            + std::to_string(pop.size()));
        }
        // Get out if there is nothing to do.
        if (m_gen == 0u) {
            return pop;
        }
        // ---------------------------------------------------------------------------------------------------------

        // No throws, all valid: we clear the logs
        m_log.clear();

        double improvement; // stores the difference in fitness between parents and offsprings
        std::uniform_int_distribution<unsigned int> urng;
        for (decltype(m_gen) i = 1u; i <= m_gen; ++i) {
            // 1 - if the problem is stochastic we change seed and re-evaluate the entire population
            if (prob.is_stochastic()) {
                pop.get_problem().set_seed(urng(m_e));
                // re-evaluate the whole population w.r.t. the new seed
                for (decltype(pop.size()) j = 0u; j < pop.size(); ++j) {
                    pop.set_xf(j, pop.get_x()[j], prob.fitness(pop.get_x()[j]));
                }
            }
            auto XNEW = pop.get_x();
            auto FNEW = pop.get_f();
            // 2 - Selection.
            auto selected_idx = perform_selection(FNEW);
            for (decltype(NP) j = 0u; j < NP; ++j) {
                XNEW[j] = pop.get_x()[selected_idx[j]];
            }
            // 3 - Crossover
            perform_crossover(XNEW, prob.get_bounds(), dim_i);
            // 4 - Mutation
            perform_mutation(XNEW, prob.get_bounds(), dim_i);
            // 5 - Evaluate the new population
            for (decltype(NP) j = 0u; j < NP; ++j) {
                FNEW[j] = prob.fitness(XNEW[j]);
            }
            // 6 - Logs and prints
            if (m_verbosity > 0u) {
                double bestf = std::numeric_limits<double>::max();
                for (decltype(NP) j = 0u; j < NP; ++j) {
                    if (FNEW[j][0] < bestf) bestf = FNEW[j][0];
                }
                improvement = pop.get_f()[pop.best_idx()][0] - bestf;
                // (verbosity modes = 1: a line is added at each improvement
                // (verbosity modes > 1: a line is added every m_verbosity generations)
                if (((i % m_verbosity == 1u) && (m_verbosity > 1u)) || ((improvement > 0) && (m_verbosity == 1u))) {

                    // Every 50 lines print the column names
                    if (count % 50u == 1u) {
                        print("\n", std::setw(7), "Gen:", std::setw(15), "Fevals:", std::setw(15),
                              "Best:", std::setw(15), "Improvement:", '\n');
                    }
                    print(std::setw(7), i, std::setw(15), prob.get_fevals() - fevals0, std::setw(15),
                          pop.get_f()[pop.best_idx()][0], std::setw(15), improvement, '\n');
                    ++count;
                    // Logs
                    m_log.emplace_back(i, prob.get_fevals() - fevals0, pop.get_f()[pop.best_idx()][0], improvement);
                }
            }
            // 7 - And insert the best into pop
            // We add all the parents to the new population
            for (decltype(NP) j = 0u; j < NP; ++j) {
                XNEW.push_back(pop.get_x()[j]);
                FNEW.push_back(pop.get_f()[j]);
            }
            // sort the entire pool
            std::vector<vector_double::size_type> best_idxs(FNEW.size());
            std::iota(best_idxs.begin(), best_idxs.end(), vector_double::size_type(0u));
            std::sort(best_idxs.begin(), best_idxs.end(),
                      [&FNEW](vector_double::size_type a, vector_double::size_type b) {
                          return detail::less_than_f(FNEW[a][0], FNEW[b][0]);
                      });
            for (decltype(NP) j = 0u; j < NP; ++j) {
                pop.set_xf(j, XNEW[best_idxs[j]], FNEW[best_idxs[j]]);
            }
        }
        return pop;
    }

    /// Sets the seed
    /**
     * @param seed the seed controlling the algorithm stochastic behaviour
     */
    void set_seed(unsigned seed)
    {
        m_e.seed(seed);
        m_seed = seed;
    }
    /// Gets the seed
    /**
     * @return the seed controlling the algorithm stochastic behaviour
     */
    unsigned get_seed() const
    {
        return m_seed;
    }
    /// Sets the algorithm verbosity
    /**
     * Sets the verbosity level of the screen output and of the
     * log returned by get_log(). \p level can be:
     * - 0: no verbosity
     * - 1: will only print and log when the population is improved
     * - >1: will print and log one line each \p level generations.
     *
     * Example (verbosity 1):
     * @code{.unparsed}
     * Gen:        Fevals:          Best:   Improvement:
     *    1             20        6605.75         415.95
     *    3             60        6189.79        500.359
     *    4             80        5689.44        477.663
     *    5            100        5211.77        218.231
     *    6            120        4993.54        421.684
     *    8            160        4571.86        246.532
     *   10            200        4325.33        166.685
     *   11            220        4158.64        340.382
     *   14            280        3818.26        294.232
     *   15            300        3524.03        55.0358
     *   16            320        3468.99        452.544
     *   17            340        3016.45        16.7273
     *   19            380        2999.72         150.68
     *   21            420        2849.04        301.156
     *   22            440        2547.88        1.25038
     *   23            460        2546.63        192.561
     *   25            500        2354.07        22.6248
     * @endcode
     * Gen is the generation number, Fevals the number of fitness evaluations , Best is the best fitness found,
     * Improvement is the improvement of the new population of offspring with respect to the parents.
     *
     * @param level verbosity level
     */
    void set_verbosity(unsigned level)
    {
        m_verbosity = level;
    }
    /// Gets the verbosity level
    /**
     * @return the verbosity level
     */
    unsigned get_verbosity() const
    {
        return m_verbosity;
    }
    /// Algorithm name
    /**
     * @return a string containing the algorithm name
     */
    std::string get_name() const
    {
        return "SGA: Genetic Algorithm";
    }
    /// Extra informations
    /**
     * @return a string containing extra informations on the algorithm
     */
    std::string get_extra_info() const
    {
        std::ostringstream ss;
        stream(ss, "\tNumber of generations: ", m_gen);
        stream(ss, "\n\tCrossover:");
        stream(ss, "\n\t\tType: " + m_crossover_map.right.at(m_crossover));
        stream(ss, "\n\t\tProbability: ", m_cr);
        if (m_crossover == crossover::SBX) stream(ss, "\n\t\tDistribution index: ", m_eta_c);
        stream(ss, "\n\tMutation:");
        stream(ss, "\n\t\tType: ", m_mutation_map.right.at(m_mutation));
        stream(ss, "\n\t\tProbability: ", m_m);
        if (m_mutation != mutation::POLYNOMIAL) {
            stream(ss, "\n\t\tWidth: ", m_param_m);
        } else {
            stream(ss, "\n\t\tDistribution index: ", m_param_m);
        }
        stream(ss, "\n\tSelection:");
        stream(ss, "\n\t\tType: ", m_selection_map.right.at(m_selection));
        if (m_selection == selection::TRUNCATED) stream(ss, "\n\t\tTruncation size: ", m_param_s);
        if (m_selection == selection::TOURNAMENT) stream(ss, "\n\t\tTournament size: ", m_param_s);
        stream(ss, "\n\tSeed: ", m_seed);
        stream(ss, "\n\tVerbosity: ", m_verbosity);
        return ss.str();
    }

    /// Get log
    /**
     * A log containing relevant quantities monitoring the last call to evolve. Each element of the returned
     * <tt>std::vector</tt> is a sga::log_line_type containing: Gen, Fevals, Current best, Best as
     * described in sga::set_verbosity().
     *
     * @return an <tt> std::vector</tt> of sga::log_line_type containing the logged values Gen, Fevals, Best
     * improvement
     */
    const log_type &get_log() const
    {
        return m_log;
    }
    /// Object serialization
    /**
     * This method will save/load \p this into the archive \p ar.
     *
     * @param ar target archive.
     *
     * @throws unspecified any exception thrown by the serialization of the UDP and of primitive types.
     */
    template <typename Archive>
    void serialize(Archive &ar)
    {
        ar(m_gen, m_cr, m_eta_c, m_m, m_param_m, m_param_s, m_mutation, m_selection, m_crossover, m_e, m_seed,
           m_verbosity, m_log);
    }

private:
    std::vector<vector_double::size_type> perform_selection(const std::vector<vector_double> &F) const
    {
        assert(m_param_s <= F.size());
        std::vector<vector_double::size_type> retval(F.size());
        std::vector<vector_double::size_type> best_idxs(F.size());
        std::iota(best_idxs.begin(), best_idxs.end(), vector_double::size_type(0u));
        switch (m_selection) {
            case (selection::TRUNCATED): {
                std::sort(best_idxs.begin(), best_idxs.end(),
                          [&F](vector_double::size_type a, vector_double::size_type b) {
                              return detail::less_than_f(F[a][0], F[b][0]);
                          });
                for (decltype(retval.size()) i = 0u; i < retval.size(); ++i) {
                    retval[i] = best_idxs[i % m_param_s];
                }
                break;
            }
            case (selection::TOURNAMENT): {
                std::uniform_int_distribution<std::vector<vector_double::size_type>::size_type> dist;
                // We make one tournament for each of the offspring to be generated
                for (decltype(retval.size()) j = 0u; j < retval.size(); ++j) {
                    // Fisher Yates algo http://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle
                    // to select m_param_s individial at random
                    for (decltype(m_param_s) i = 0u; i < m_param_s; ++i) {
                        dist.param(
                            std::uniform_int_distribution<std::vector<vector_double::size_type>::size_type>::param_type(
                                i, best_idxs.size() - 1u));
                        auto index = dist(m_e);
                        std::swap(best_idxs[index], best_idxs[i]);
                    }
                    // Find the index of the individual with minimum fitness among the randomly selected ones
                    auto winner = best_idxs[0];
                    for (decltype(m_param_s) i = 1u; i < m_param_s; ++i) {
                        if (F[best_idxs[i]] < F[winner]) {
                            winner = best_idxs[i];
                        }
                    }
                    retval[j] = winner;
                }
                break;
            }
        }
        return retval;
    }
    void perform_crossover(std::vector<vector_double> &X, const std::pair<vector_double, vector_double> &bounds,
                           vector_double::size_type dim_i) const
    {
        auto dim = X[0].size();
        assert(X.size() > 1u);
        assert(std::all_of(X.begin(), X.end(), [dim](const vector_double &item) { return item.size() == dim; }));
        std::vector<vector_double::size_type> all_idx(X.size()); // stores indexes to then select one at random
        std::iota(all_idx.begin(), all_idx.end(), vector_double::size_type(0u));
        std::uniform_real_distribution<> drng(0., 1.);
        // We need different loops if the crossover type is "sbx"" as this method creates two offsprings per
        // selected couple.
        if (m_crossover == crossover::SBX) {
            assert(X.size() % 2u == 0u);
            std::shuffle(X.begin(), X.end(), m_e);
            for (decltype(X.size()) i = 0u; i < X.size(); i += 2) {
                auto children = sbx_crossover_impl(X[i], X[i + 1], bounds, dim_i);
                X[i] = children.first;
                X[i + 1] = children.second;
            }
        } else {
            auto XCOPY = X;
            std::uniform_int_distribution<std::vector<vector_double::size_type>::size_type> rnd_gene_idx(0, dim - 1u);
            std::uniform_int_distribution<std::vector<vector_double::size_type>::size_type> rnd_skip_first_idx(
                1, all_idx.size() - 1);
            // Start of main loop through the X
            for (decltype(X.size()) i = 0u; i < X.size(); ++i) {
                // 1 - we select a mating partner
                std::swap(all_idx[0], all_idx[i]);
                auto partner_idx = rnd_skip_first_idx(m_e);
                // 2 - We rename these chromosomes for code clarity
                auto &child = X[i];
                const auto &parent2 = XCOPY[all_idx[partner_idx]];
                // 3 - We perform crossover according to the selected method
                switch (m_crossover) {
                    case (crossover::EXPONENTIAL): {
                        auto n = rnd_gene_idx(m_e);
                        decltype(dim) L = 0u;
                        do {
                            child[n] = parent2[n];
                            n = (n + 1u) % dim;
                            L++;
                        } while ((drng(m_e) < m_cr) && (L < dim));
                        break;
                    }
                    case (crossover::BINOMIAL): {
                        auto n = rnd_gene_idx(m_e);
                        for (decltype(dim) L = 0u; L < dim; ++L) {    /* performs D binomial trials */
                            if ((drng(m_e) < m_cr) || L + 1 == dim) { /* changes at least one parameter */
                                child[n] = parent2[n];
                            }
                            n = (n + 1) % dim;
                        }
                        break;
                    }
                    case (crossover::SINGLE): {
                        if (drng(m_e) < m_cr) {
                            auto n = rnd_gene_idx(m_e);
                            for (decltype(dim) j = n; j < dim; ++j) {
                                child[j] = parent2[j];
                            }
                        }
                        break;
                    }
                    // LCOV_EXCL_START
                    default: {
                        assert(false); // the code should never reach this point
                        break;
                    }
                        // LCOV_EXCL_STOP
                }
            }
        }
    }
    void perform_mutation(std::vector<vector_double> &X, const std::pair<vector_double, vector_double> &bounds,
                          vector_double::size_type dimi) const
    {
        // Asserting the correct behaviour of input parameters
        assert(X.size() > 1u);
        auto dim = X[0].size();
        assert(std::all_of(X.begin(), X.end(), [dim](const vector_double &item) { return item.size() == dim; }));
        assert(bounds.first.size() == bounds.second.size());
        assert(bounds.first.size() == X[0].size());

        // Renaming some dimensions
        auto dimc = dim - dimi;
        // Problem bounds
        const auto &lb = bounds.first;
        const auto &ub = bounds.second;
        // Random distributions
        std::uniform_real_distribution<> drng(0., 1.);  // to generate a number in [0, 1)
        std::uniform_real_distribution<> drngs(-1, 1.); // to generate a number in [-1, 1)
        std::normal_distribution<> normal(0., 1.);
        std::uniform_int_distribution<int> rnd_lb_ub; // to generate a random int between int bounds
        // This will contain the indexes of the genes to be mutated
        std::vector<vector_double::size_type> to_be_mutated(dim);
        std::iota(to_be_mutated.begin(), to_be_mutated.end(), vector_double::size_type(0u));
        // Then we start tha main loop through the population
        for (decltype(X.size()) i = 0u; i < X.size(); ++i) {
            // We select the indexes to be mutated (the first N of to_be_mutated)
            std::shuffle(to_be_mutated.begin(), to_be_mutated.end(), m_e);
            auto N = std::binomial_distribution<vector_double::size_type>(dim, m_m)(m_e);
            // We ensure at least one is mutated if m_m > 0
            // if (m_m > 0. and N == 0u) N = 1;
            // We apply the mutation scheme
            switch (m_mutation) {
                case (mutation::UNIFORM): {
                    // Start of main loop through the chromosome
                    for (decltype(N) j = 0u; j < N; ++j) {
                        auto gene_idx = to_be_mutated[j];
                        if (gene_idx < dimc) {
                            X[i][gene_idx] = uniform_real_from_range(lb[gene_idx], ub[gene_idx], m_e);
                        } else {
                            rnd_lb_ub.param(std::uniform_int_distribution<int>::param_type(
                                static_cast<int>(lb[gene_idx]), static_cast<int>(ub[gene_idx])));
                            X[i][gene_idx] = static_cast<double>(rnd_lb_ub(m_e));
                        }
                    }
                    break;
                }
                case (mutation::GAUSSIAN): {
                    // Start of main loop through the chromosome
                    for (decltype(N) j = 0u; j < N; ++j) {
                        auto gene_idx = to_be_mutated[j];
                        auto std = (ub[gene_idx] - lb[gene_idx]) * m_param_m;
                        if (gene_idx < dimc) {
                            X[i][gene_idx] += normal(m_e) * std;
                        } else {
                            X[i][gene_idx] += std::round(normal(m_e) * std);
                        }
                    }
                    break;
                }
                case (mutation::POLYNOMIAL): { // https://www.iitk.ac.in/kangal/papers/k2012016.pdf
                    // Start of main loop through the chromosome
                    for (decltype(N) j = 0u; j < N; ++j) {
                        auto gene_idx = to_be_mutated[j];
                        if (gene_idx < dimc) {
                            double u = drng(m_e);
                            if (u <= 0.5) {
                                auto delta_l = std::pow(2. * u, 1. / (1. + m_param_m)) - 1.;
                                X[i][gene_idx] += delta_l * (X[i][gene_idx] - lb[gene_idx]);
                            } else {
                                auto delta_r = 1 - std::pow(2. * (1. - u), 1. / (1. + m_param_m));
                                X[i][gene_idx] += delta_r * (ub[gene_idx] - X[i][gene_idx]);
                            }
                        } else {
                            rnd_lb_ub.param(std::uniform_int_distribution<int>::param_type(
                                static_cast<int>(lb[gene_idx]), static_cast<int>(ub[gene_idx])));
                            X[i][gene_idx] = static_cast<double>(rnd_lb_ub(m_e));
                        }
                    }
                    break;
                }
            }
            // We fix chromosomes possibly created outside the bounds to stick to the bounds
            detail::force_bounds_stick(X[i], lb, ub);
        }
    }
    std::pair<vector_double, vector_double> sbx_crossover_impl(const vector_double &parent1,
                                                               const vector_double &parent2,
                                                               const std::pair<vector_double, vector_double> &bounds,
                                                               vector_double::size_type Di) const
    {
        // Decision vector dimensions
        auto D = parent1.size();
        auto Dc = D - Di;
        // Problem bounds
        const auto &lb = bounds.first;
        const auto &ub = bounds.second;
        // declarations
        double y1, y2, yl, yu, rand01, beta, alpha, betaq, c1, c2;
        vector_double::size_type site1, site2;
        // Initialize the child decision vectors
        auto child1 = parent1;
        auto child2 = parent2;
        // Random distributions
        std::uniform_real_distribution<> drng(0., 1.); // to generate a number in [0, 1)

        // This implements a Simulated Binary Crossover SBX and applies it to the non integer part of the decision
        // vector
        if (drng(m_e) <= m_cr) {
            for (decltype(Dc) i = 0u; i < Dc; i++) {
                if ((drng(m_e) <= 0.5) && (std::abs(parent1[i] - parent2[i])) > 1e-14 && lb[i] != ub[i]) {
                    if (parent1[i] < parent2[i]) {
                        y1 = parent1[i];
                        y2 = parent2[i];
                    } else {
                        y1 = parent2[i];
                        y2 = parent1[i];
                    }
                    yl = lb[i];
                    yu = ub[i];
                    rand01 = drng(m_e);
                    beta = 1. + (2. * (y1 - yl) / (y2 - y1));
                    alpha = 2. - std::pow(beta, -(m_eta_c + 1.));
                    if (rand01 <= (1. / alpha)) {
                        betaq = std::pow((rand01 * alpha), (1. / (m_eta_c + 1.)));
                    } else {
                        betaq = std::pow((1. / (2. - rand01 * alpha)), (1. / (m_eta_c + 1.)));
                    }
                    c1 = 0.5 * ((y1 + y2) - betaq * (y2 - y1));
                    beta = 1. + (2. * (yu - y2) / (y2 - y1));
                    alpha = 2. - std::pow(beta, -(m_eta_c + 1.));
                    if (rand01 <= (1. / alpha)) {
                        betaq = std::pow((rand01 * alpha), (1. / (m_eta_c + 1.)));
                    } else {
                        betaq = std::pow((1. / (2. - rand01 * alpha)), (1. / (m_eta_c + 1.)));
                    }
                    c2 = 0.5 * ((y1 + y2) + betaq * (y2 - y1));
                    if (c1 < lb[i]) c1 = lb[i];
                    if (c2 < lb[i]) c2 = lb[i];
                    if (c1 > ub[i]) c1 = ub[i];
                    if (c2 > ub[i]) c2 = ub[i];
                    if (drng(m_e) <= .5) {
                        child1[i] = c1;
                        child2[i] = c2;
                    } else {
                        child1[i] = c2;
                        child2[i] = c1;
                    }
                }
            }
        }
        // This implements two-point binary crossover and applies it to the integer part of the chromosome
        for (decltype(Dc) i = Dc; i < D; ++i) {
            // in this loop we are sure Di is at least 1
            std::uniform_int_distribution<vector_double::size_type> ra_num(0, Di - 1u);
            if (drng(m_e) <= m_cr) {
                site1 = ra_num(m_e);
                site2 = ra_num(m_e);
                if (site1 > site2) {
                    std::swap(site1, site2);
                }
                for (decltype(site1) j = 0u; j < site1; ++j) {
                    child1[j] = parent1[j];
                    child2[j] = parent2[j];
                }
                for (decltype(site2) j = site1; j < site2; ++j) {
                    child1[j] = parent2[j];
                    child2[j] = parent1[j];
                }
                for (decltype(Di) j = site2; j < Di; ++j) {
                    child1[j] = parent1[j];
                    child2[j] = parent2[j];
                }
            } else {
                child1[i] = parent1[i];
                child2[i] = parent2[i];
            }
        }
        return std::make_pair(std::move(child1), std::move(child2));
    }
    unsigned m_gen;
    double m_cr;
    double m_eta_c;
    double m_m;
    double m_param_m;
    unsigned m_param_s;
    mutation m_mutation;
    selection m_selection;
    crossover m_crossover;
    mutable detail::random_engine_type m_e;
    unsigned int m_seed;
    unsigned int m_verbosity;
    mutable log_type m_log;
};

} // namespace pagmo

PAGMO_REGISTER_ALGORITHM(pagmo::sga)

#endif

max_stars_repo_name: haisenzhao/CarpentryCompiler

max_issues_repo_name: haisenzhao/CarpentryCompiler

max_forks_repo_name: haisenzhao/CarpentryCompiler