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

#include "privilege_manager.h"
#include <boost/algorithm/string.hpp>
#ifdef BAIDU_INTERNAL
#include <baidu/rpc/channel.h>
#else
#include <brpc/channel.h>
#endif
#include "meta_state_machine.h"
#include "schema_manager.h"
#include "meta_server.h"
#include "meta_util.h"
#include "meta_rocksdb.h"

namespace baikaldb {
//合法性检查，真正的处理在state_machine中
void PrivilegeManager::process_user_privilege(google::protobuf::RpcController* controller,
                                                const pb::MetaManagerRequest* request,
                                                pb::MetaManagerResponse* response,
                                                google::protobuf::Closure* done) {
    brpc::ClosureGuard done_guard(done);
    brpc::Controller* cntl =
            static_cast<brpc::Controller*>(controller);
    uint64_t log_id = 0;
    if (cntl->has_log_id()) {
        log_id = cntl->log_id();
    }
    if (!request->has_user_privilege()) {
        ERROR_SET_RESPONSE(response,
                           pb::INPUT_PARAM_ERROR,
                           "no user_privilege",
                           request->op_type(),
                           log_id);
        return;
    }
    switch (request->op_type()) {
    case pb::OP_CREATE_USER: {
        if (!request->user_privilege().has_password()) {
            ERROR_SET_RESPONSE(response,
                                pb::INPUT_PARAM_ERROR,
                                "no password",
                                request->op_type(),
                                log_id);
            return;
        }
        _meta_state_machine->process(controller, request, response,  done_guard.release());
        return;
    }
    case pb::OP_DROP_USER:
    case pb::OP_ADD_PRIVILEGE:
    case pb::OP_DROP_PRIVILEGE: {
        _meta_state_machine->process(controller, request, response,  done_guard.release());
        return;
    }
    default: {
        ERROR_SET_RESPONSE(response,
                           pb::INPUT_PARAM_ERROR,
                           "invalid op_type",
                           request->op_type(),
                           log_id);
        return;
    }
    }
}

void PrivilegeManager::create_user(const pb::MetaManagerRequest& request, braft::Closure* done) {
    auto& user_privilege = const_cast<pb::UserPrivilege&>(request.user_privilege());
    std::string username = user_privilege.username();
    if (_user_privilege.find(username) != _user_privilege.end()) {
        DB_WARNING("request username has been created, username:%s",
                user_privilege.username().c_str());
        IF_DONE_SET_RESPONSE(done, pb::INPUT_PARAM_ERROR, "username has been repeated");
        return;
    }
    int ret = SchemaManager::get_instance()->check_and_get_for_privilege(user_privilege);
    if (ret < 0) {
        DB_WARNING("request not illegal, request:%s", request.ShortDebugString().c_str());
        IF_DONE_SET_RESPONSE(done, pb::INPUT_PARAM_ERROR, "request invalid");
        return;
    }
    user_privilege.set_version(1);
    // 构造key 和 value
    std::string value;
    if (!user_privilege.SerializeToString(&value)) {
        DB_WARNING("request serializeToArray fail, request:%s",request.ShortDebugString().c_str());
        IF_DONE_SET_RESPONSE(done, pb::PARSE_TO_PB_FAIL, "serializeToArray fail");
        return;
    }
    // write date to rocksdb
    ret = MetaRocksdb::get_instance()->put_meta_info(construct_privilege_key(username), value);
    if (ret < 0) {
        DB_WARNING("add username:%s privilege to rocksdb fail", username.c_str());
        IF_DONE_SET_RESPONSE(done, pb::INTERNAL_ERROR, "write db fail");
        return;
    }
    //更新内存
    BAIDU_SCOPED_LOCK(_user_mutex);
    _user_privilege[username] = user_privilege;
    IF_DONE_SET_RESPONSE(done, pb::SUCCESS, "success");
    DB_NOTICE("create user success, request:%s", request.ShortDebugString().c_str());
}

void PrivilegeManager::drop_user(const pb::MetaManagerRequest& request, braft::Closure* done) {
    std::string username =  request.user_privilege().username();
    if (_user_privilege.find(username) == _user_privilege.end()) {
        DB_WARNING("request username not exist, username:%s", username.c_str());
        IF_DONE_SET_RESPONSE(done, pb::INPUT_PARAM_ERROR, "username not exist");
        return;
    }
    auto ret = MetaRocksdb::get_instance()->delete_meta_info(
                std::vector<std::string>{construct_privilege_key(username)});
    if (ret < 0) {
        DB_WARNING("drop username:%s privilege to rocksdb fail", username.c_str());
        IF_DONE_SET_RESPONSE(done, pb::INTERNAL_ERROR, "delete from db fail");
        return;
    }
    BAIDU_SCOPED_LOCK(_user_mutex);
    _user_privilege.erase(username);
    IF_DONE_SET_RESPONSE(done, pb::SUCCESS, "success");
    DB_NOTICE("drop user success, request:%s", request.ShortDebugString().c_str());
}

void PrivilegeManager::add_privilege(const pb::MetaManagerRequest& request, braft::Closure* done) {
    auto& user_privilege = const_cast<pb::UserPrivilege&>(request.user_privilege());
    std::string username = user_privilege.username();
    if (_user_privilege.find(username) == _user_privilege.end()) {
        DB_WARNING("request username not exist, username:%s", username.c_str());
        IF_DONE_SET_RESPONSE(done, pb::INPUT_PARAM_ERROR, "username not exist");
        return;
    }
    int ret = SchemaManager::get_instance()->check_and_get_for_privilege(user_privilege);
    if (ret < 0) {
        DB_WARNING("request not illegal, request:%s",request.ShortDebugString().c_str());
        IF_DONE_SET_RESPONSE(done, pb::INPUT_PARAM_ERROR, "request invalid");
        return;
    }
    pb::UserPrivilege tmp_mem_privilege = _user_privilege[username];
    for (auto& privilege_database : user_privilege.privilege_database()) {
        insert_database_privilege(privilege_database, tmp_mem_privilege);
    }
    for (auto& privilege_table :  user_privilege.privilege_table()) {
        insert_table_privilege(privilege_table, tmp_mem_privilege);
    }
    for (auto& bns : user_privilege.bns()) {
        insert_bns(bns, tmp_mem_privilege);
    }
    for (auto& ip : user_privilege.ip()) {
        insert_ip(ip, tmp_mem_privilege);
    }
    if (user_privilege.has_need_auth_addr()) {
        tmp_mem_privilege.set_need_auth_addr(user_privilege.need_auth_addr());
    }
    tmp_mem_privilege.set_version(tmp_mem_privilege.version() + 1);
    // 构造key 和 value
    std::string value;
    if (!tmp_mem_privilege.SerializeToString(&value)) {
        DB_WARNING("request serializeToArray fail, request:%s",request.ShortDebugString().c_str());
        IF_DONE_SET_RESPONSE(done, pb::PARSE_TO_PB_FAIL, "serializeToArray fail");
        return;
    }
    // write date to rocksdb
    ret = MetaRocksdb::get_instance()->put_meta_info(construct_privilege_key(username), value);
    if (ret != 0) {
        DB_WARNING("add username:%s privilege to rocksdb fail", username.c_str());
        IF_DONE_SET_RESPONSE(done, pb::INTERNAL_ERROR, "write db fail");
        return;
    }
    BAIDU_SCOPED_LOCK(_user_mutex);
    _user_privilege[username] = tmp_mem_privilege;
    IF_DONE_SET_RESPONSE(done, pb::SUCCESS, "success");
    DB_NOTICE("add privilege success, request:%s", request.ShortDebugString().c_str());
}

void PrivilegeManager::drop_privilege(const pb::MetaManagerRequest& request, braft::Closure* done) {
    auto& user_privilege = const_cast<pb::UserPrivilege&>(request.user_privilege());
    std::string username = user_privilege.username();
    if (_user_privilege.find(username) == _user_privilege.end()) {
        DB_WARNING("request username not exist, username:%s", username.c_str());
        IF_DONE_SET_RESPONSE(done, pb::INPUT_PARAM_ERROR, "username not exist");
        return;
    }
    int ret = SchemaManager::get_instance()->check_and_get_for_privilege(user_privilege);
    if (ret < 0) {
        DB_WARNING("request not illegal, request:%s",request.ShortDebugString().c_str());
        IF_DONE_SET_RESPONSE(done, pb::INPUT_PARAM_ERROR, "request invalid");
        return;
    }
    pb::UserPrivilege tmp_mem_privilege = _user_privilege[username];
    for (auto& privilege_database : user_privilege.privilege_database()) {
        delete_database_privilege(privilege_database, tmp_mem_privilege);
    }
    for (auto& privilege_table : user_privilege.privilege_table()) {
        delete_table_privilege(privilege_table, tmp_mem_privilege);
    }
    for (auto& bns : user_privilege.bns()) {
        delete_bns(bns, tmp_mem_privilege);
    }
    for (auto& ip : user_privilege.ip()) {
        delete_ip(ip, tmp_mem_privilege);
    }
    if (user_privilege.has_need_auth_addr()) {
        tmp_mem_privilege.set_need_auth_addr(user_privilege.need_auth_addr());
    }
    tmp_mem_privilege.set_version(tmp_mem_privilege.version() + 1);
    // 构造key 和 value
    std::string value;
    if (!tmp_mem_privilege.SerializeToString(&value)) {
        DB_WARNING("request serializeToArray fail, request:%s",request.ShortDebugString().c_str());
        IF_DONE_SET_RESPONSE(done, pb::PARSE_TO_PB_FAIL, "serializeToArray fail");
        return;
    }
    // write date to rocksdb
    ret = MetaRocksdb::get_instance()->put_meta_info(construct_privilege_key(username), value);
    if (ret < 0) {
        DB_WARNING("add username:%s privilege to rocksdb fail", username.c_str());
        IF_DONE_SET_RESPONSE(done, pb::INTERNAL_ERROR, "write db fail");
        return;
    }
    BAIDU_SCOPED_LOCK(_user_mutex);
    _user_privilege[username] = tmp_mem_privilege;
    IF_DONE_SET_RESPONSE(done, pb::SUCCESS, "success");
    DB_NOTICE("drop privilege success, request:%s", request.ShortDebugString().c_str());
}

void PrivilegeManager::process_baikal_heartbeat(const pb::BaikalHeartBeatRequest* request,
                                               pb::BaikalHeartBeatResponse* response) {
    BAIDU_SCOPED_LOCK(_user_mutex);
    for (auto& user_info : _user_privilege) {
        auto privilege = response->add_privilege_change_info();
        *privilege = user_info.second;
    }
}

int PrivilegeManager::load_snapshot() {
    _user_privilege.clear();
    std::string privilege_prefix = MetaServer::PRIVILEGE_IDENTIFY;
    rocksdb::ReadOptions read_options;
    read_options.prefix_same_as_start = true;
    read_options.total_order_seek = false;
    RocksWrapper* db = RocksWrapper::get_instance();
    std::unique_ptr<rocksdb::Iterator> iter(
            db->new_iterator(read_options, db->get_meta_info_handle()));
    iter->Seek(privilege_prefix);
    for (; iter->Valid(); iter->Next()) {
        std::string username(iter->key().ToString(), privilege_prefix.size());
        pb::UserPrivilege user_privilege;
        if (!user_privilege.ParseFromString(iter->value().ToString())) {
            DB_FATAL("parse from pb fail when load privilege snapshot, key:%s",
                     iter->key().data());
            return -1;
        }
        DB_WARNING("user_privilege:%s", user_privilege.ShortDebugString().c_str());
        BAIDU_SCOPED_LOCK(_user_mutex);
        _user_privilege[username] = user_privilege;
    }
    return 0;
}

void PrivilegeManager::insert_database_privilege(const pb::PrivilegeDatabase& privilege_database,
                                                  pb::UserPrivilege& mem_privilege) {
    bool whether_exist = false;
    for (auto& mem_database : *mem_privilege.mutable_privilege_database()) {
        if (mem_database.database_id() == privilege_database.database_id()) {
            whether_exist = true;
            if (privilege_database.database_rw() > mem_database.database_rw()) {
                mem_database.set_database_rw(privilege_database.database_rw());
            }
            break;
        }
    }
    if (!whether_exist) {
        pb::PrivilegeDatabase* ptr_database = mem_privilege.add_privilege_database();
        *ptr_database = privilege_database;
    }
}

void PrivilegeManager::insert_table_privilege(const pb::PrivilegeTable& privilege_table,
                                               pb::UserPrivilege& mem_privilege) {
    bool whether_exist = false;
    int64_t database_id = privilege_table.database_id();
    int64_t table_id = privilege_table.table_id();
    for (auto& mem_privilege_table : *mem_privilege.mutable_privilege_table()) {
        if (mem_privilege_table.database_id() == database_id
                && mem_privilege_table.table_id() == table_id) {
            whether_exist = true;
            if (privilege_table.table_rw() > mem_privilege_table.table_rw()) {
                mem_privilege_table.set_table_rw(privilege_table.table_rw());
            }
            break;
        }
    }
    if (!whether_exist) {
         pb::PrivilegeTable* ptr_table = mem_privilege.add_privilege_table();
         *ptr_table = privilege_table;
    }
}

void PrivilegeManager::insert_bns(const std::string& bns,
                                   pb::UserPrivilege& mem_privilege) {
    bool whether_exist = false;
    for (auto& mem_bns :  mem_privilege.bns()) {
        if (mem_bns == bns) {
            whether_exist = true;
        }
    }
    if (!whether_exist) {
        mem_privilege.add_bns(bns);
    }
}

void PrivilegeManager::insert_ip(const std::string& ip,
                                 pb::UserPrivilege& mem_privilege) {
    bool whether_exist = false;
    for (auto& mem_ip : mem_privilege.ip()) {
        if (mem_ip == ip) {
            whether_exist = true;
        }
    }
    if (!whether_exist) {
        mem_privilege.add_ip(ip);
    }
}

void PrivilegeManager::delete_database_privilege(const pb::PrivilegeDatabase& privilege_database,
                                                  pb::UserPrivilege& mem_privilege) {
    pb::UserPrivilege copy_mem_privilege = mem_privilege;
    mem_privilege.clear_privilege_database();
    for (auto& copy_database : copy_mem_privilege.privilege_database()) {
        if (copy_database.database_id() == privilege_database.database_id()) {
            //收回写权限
            if (privilege_database.has_database_rw() &&
                    privilege_database.database_rw() < copy_database.database_rw()) {
                auto add_database = mem_privilege.add_privilege_database();
                *add_database = privilege_database;
            }
        } else {
            auto add_database = mem_privilege.add_privilege_database();
            *add_database = copy_database;

        }
    }
}

void PrivilegeManager::delete_table_privilege(const pb::PrivilegeTable& privilege_table,
                                               pb::UserPrivilege& mem_privilege) {
    int64_t database_id = privilege_table.database_id();
    int64_t table_id = privilege_table.table_id();
    pb::UserPrivilege copy_mem_privilege = mem_privilege;
    mem_privilege.clear_privilege_table();
    for (auto& copy_table : copy_mem_privilege.privilege_table()) {
        if (database_id == copy_table.database_id() && table_id == copy_table.table_id()) {
            //写权限收回
            if (privilege_table.has_table_rw() &&
                    privilege_table.table_rw() < copy_table.table_rw()) {
                 auto add_table = mem_privilege.add_privilege_table();
                 *add_table = privilege_table;
            }
        } else {
            auto add_table = mem_privilege.add_privilege_table();
            *add_table = copy_table;
        }
    }
}

void PrivilegeManager::delete_bns(const std::string& bns,
                                  pb::UserPrivilege& mem_privilege) {
    pb::UserPrivilege copy_mem_privilege = mem_privilege;
    mem_privilege.clear_bns();
    for (auto copy_bns : copy_mem_privilege.bns()) {
        if (copy_bns != bns) {
            mem_privilege.add_bns(copy_bns);
        }
    }
}

void PrivilegeManager::delete_ip(const std::string& ip,
                                  pb::UserPrivilege& mem_privilege) {
    pb::UserPrivilege copy_mem_privilege = mem_privilege;
    mem_privilege.clear_ip();
    for (auto copy_ip : copy_mem_privilege.ip()) {
        if (copy_ip != ip) {
            mem_privilege.add_ip(copy_ip);
        }
    }
}

}// namespace

/* vim: set expandtab ts=4 sw=4 sts=4 tw=100: */

max_stars_repo_name: lvxinup/BaikalDB

max_issues_repo_name: lvxinup/BaikalDB

max_forks_repo_name: lvxinup/BaikalDB


text: #include <boost/mpl/key_type.hpp>

ext: hpp

max_stars_repo_name: miathedev/BoostForArduino

max_issues_repo_name: miathedev/BoostForArduino

max_forks_repo_name: miathedev/BoostForArduino


text:
/*! \file checkpoint.cpp
    \brief 時間計測のためのクラスの実装

    Copyright ©  2014 @dc1394 All Rights Reserved.
    This software is released under the BSD 2-Clause License.
*/

#include "checkpoint.h"
#include <iostream>             // for std::cout
#include <optional>				// for std::optional
#include <system_error>         // for std::system_category
#include <boost/assert.hpp>     // for boost::assert
#include <boost/cast.hpp>       // for boost::numeric_cast
#include <boost/format.hpp>     // for boost::format

#ifdef _WIN32
    #include <Windows.h>        // for GetCurrentProcess
    #include <Psapi.h>          // for GetProcessMemoryInfo

    #pragma comment(lib, "Psapi.Lib")
#else
    #include <errno.h>          // for errno
    #include <sys/time.h>       // for struct timeval
    #include <sys/resource.h>   // for getrusage
#endif

namespace checkpoint {
    CheckPoint::CheckPoint()
        : cfp(
            reinterpret_cast<CheckPoint::CheckPointFastImpl *>(
                FastArenaObject<sizeof(CheckPoint::CheckPointFastImpl)>::operator new(0)))
    {
    }

    CheckPoint::~CheckPoint()
    {
    }

    void CheckPoint::checkpoint(char const * action, std::int32_t line)
    {
        BOOST_ASSERT(cfp->cur < static_cast<std::int32_t>(CheckPoint::CheckPointFastImpl::N));

        auto const p = cfp->points.begin() + cfp->cur;

        p->action = action;
        p->line = line;
        p->realtime = std::chrono::high_resolution_clock::now();

        cfp->cur++;
    }

    void CheckPoint::checkpoint_print() const
    {
        using namespace std::chrono;

        std::optional<high_resolution_clock::time_point> prevreal(std::nullopt);

        auto itr = cfp->points.begin();
        for (auto i = 0; i < cfp->cur; ++i, ++itr) {
            if (prevreal) {
                auto const realtime(duration_cast<duration<double, std::milli>>(itr->realtime - *prevreal));
                std::cout << itr->action
                          << boost::format(" elapsed time = %.4f (msec)\n") % realtime.count();
            }

            prevreal = std::optional<high_resolution_clock::time_point>(itr->realtime);
        }
    }

    void CheckPoint::totalpassageoftime() const
    {
        using namespace std::chrono;

        auto const realtime = duration_cast<duration<double, std::milli>>(
            cfp->points[cfp->cur - 1].realtime - cfp->points[0].realtime);

        std::cout << boost::format("Total elapsed time = %.4f (msec)") % realtime.count() << std::endl;
    }

    // #region 非メンバ関数

#ifdef _WIN32
    void usedmem()
    {
        PROCESS_MEMORY_COUNTERS memInfo = { 0 };

        if (!::GetProcessMemoryInfo(::GetCurrentProcess(), &memInfo, sizeof(memInfo))) {
            throw std::system_error(std::error_code(::GetLastError(), std::system_category()));
        }

        std::cout << "Used Memory Size: "
                  << boost::numeric_cast<std::uint32_t>(memInfo.PeakWorkingSetSize >> 10)
                  << "(kB)"
                  << std::endl;
    }
#else
    void usedmem()
    {
        struct rusage r;

        if (getrusage(RUSAGE_SELF, &r)) {
            throw std::system_error(errno, std::system_category());
        }

        std::cout << "Used Memory Size: "
                  << boost::numeric_cast<std::uint32_t>(r.ru_maxrss)
                  << "(kB)"
                  << std::endl;
    }
#endif

    // #endregion 非メンバ関数
}

ext: cpp


text:
//
// Copyright (c) Thomas Klimpel 2008
//
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
//

#ifndef BOOST_NUMERIC_BINDINGS_LAPACK_SYEVX_HPP
#define BOOST_NUMERIC_BINDINGS_LAPACK_SYEVX_HPP

#include <boost/numeric/bindings/lapack/heevx.hpp>

namespace boost { namespace numeric { namespace bindings {
  namespace lapack {

    template <typename A, typename T, typename W, typename Z, typename IFail, typename Work>
    inline
    int syevx (
      char jobz, char range, A& a, T vl, T vu, integer_t il, integer_t iu, T abstol, integer_t& m,
      W& w, Z& z, IFail& ifail, Work work = optimal_workspace() ) {

#ifndef BOOST_NUMERIC_BINDINGS_NO_STRUCTURE_CHECK
      typedef typename A::value_type                               value_type ;
      typedef typename traits::type_traits< value_type >::real_type real_type ;
      BOOST_STATIC_ASSERT((boost::is_same<value_type, real_type>::value));
#endif

      return heevx (jobz, range, a, vl, vu, il, iu, abstol, m, w, z, ifail, work);
    }
  }
}}}

#endif

max_stars_repo_name: diku-dk/PROX

max_issues_repo_name: diku-dk/PROX

max_forks_repo_name: diku-dk/PROX


text:
// Copyright (C) 2009-2012 Lorenzo Caminiti
// Distributed under the Boost Software License, Version 1.0
// (see accompanying file LICENSE_1_0.txt or a copy at
// http://www.boost.org/LICENSE_1_0.txt)
// Home at http://www.boost.org/libs/utility/identity_type

#include <boost/utility/identity_type.hpp>
#include <map>
#include <iostream>

//[template_f_decl
#define ARG(type, n) type arg ## n

template<typename T>
void f( // Prefix macro with `typename` in templates.
    ARG(typename BOOST_IDENTITY_TYPE((std::map<int, T>)), 1)
) {
    std::cout << arg1[0] << std::endl;
}
//]

//[template_g_decl
template<typename T>
void g(
    std::map<int, T> arg1
) {
    std::cout << arg1[0] << std::endl;
}
//]

int main() {
    //[template_f_call
    std::map<int, char> a;
    a[0] = 'a';

    f<char>(a); // OK...
    // f(a);    // ... but error.
    //]

    //[template_g_call
    g<char>(a); // OK...
    g(a);       // ... and also OK.
    //]

    return 0;
}


text:
#ifndef AYLA_GL_TEXTURE_CUBE_MAP_HPP
#define AYLA_GL_TEXTURE_CUBE_MAP_HPP

#include "ayla_gl/config.hpp"

#include <boost/noncopyable.hpp>

namespace ayla {
	class Image;
	class ImageCubeMap;
}

namespace ayla_gl {

/**
 * @see ayla::Image
 *
 * @author O Programador
 */
class AYLA_GL_API TextureCubeMap final : boost::noncopyable {
public:
	TextureCubeMap(const ayla::ImageCubeMap& image);

	TextureCubeMap(
		const ayla::Image& positiveX,
		const ayla::Image& negativeX,
		const ayla::Image& positiveY,
		const ayla::Image& negativeY,
		const ayla::Image& positiveZ,
		const ayla::Image& negativeZ
	);

	~TextureCubeMap();

	void bind() const;

private:
	struct Private;
	std::unique_ptr<Private> _pimpl;
};

}

#endif // AYLA_GL_TEXTURE_CUBE_MAP_HPP

max_stars_repo_name: oprogramadorreal/vize

max_issues_repo_name: oprogramadorreal/vize

max_forks_repo_name: oprogramadorreal/vize


text: #include <boost/graph/adjacency_matrix.hpp>


text:
#include "M6Lib.h"

#include <iostream>
#include <numeric>
#include <boost/test/unit_test.hpp>

#include "M6BitStream.h"

using namespace std;

BOOST_AUTO_TEST_CASE(test_bit_stream_1)
{
    cout << "testing bitstream" << endl;

    M6OBitStream bits;

    for (uint32 i = 1; i < 100; ++i)
        WriteGamma(bits, i);
    bits.Sync();

    M6IBitStream ibits(bits);

    for (uint32 i = 1; i < 100; ++i)
    {
        uint32 v;
        ReadGamma(ibits, v);
        BOOST_CHECK_EQUAL(i, v);
    }
}

BOOST_AUTO_TEST_CASE(test_bit_stream_2)
{
    cout << "testing bitstream" << endl;

    vector<uint32> a(1000);
    iota(a.begin(), a.end(), 1);
    for_each(a.begin(), a.end(), [](uint32& i) { i *= 20; });

    M6OBitStream bits;

    CompressSimpleArraySelector(bits, a);

    cout << "bitsize: " << bits.Size() << endl;

    M6IBitStream ibits(bits);
    M6CompressedArray arr(ibits, 1000);

    auto ai = a.begin();
    auto bi = arr.begin();

    for (int i = 0; i < 1000; ++i)
    {
        BOOST_CHECK_EQUAL(*ai, *bi);
        ++ai;
        ++bi;
    }

    BOOST_CHECK(ai == a.end());
    BOOST_CHECK(bi == arr.end());

    M6OBitStream b2;
    CopyBits(b2, bits);

    M6IBitStream ibits2(b2);
    M6CompressedArray arr2(ibits2, 1000);

    auto a2i = a.begin();
    auto b2i = arr2.begin();

    for (int i = 0; i < 1000; ++i)
    {
        BOOST_CHECK_EQUAL(*a2i, *b2i);
        ++a2i;
        ++b2i;
    }

    BOOST_CHECK(a2i == a.end());
    BOOST_CHECK(b2i == arr2.end());
}

BOOST_AUTO_TEST_CASE(test_bit_stream_3)
{
    cout << "testing bitstream" << endl;

    M6OBitStream bits;

    uint32 v = 0x01234567;

    WriteBinary(bits, 32, v);
    M6IBitStream ibits(bits);

    uint32 t;
    ReadBinary(ibits, 32, t);
    BOOST_CHECK_EQUAL(t, v);
}

BOOST_AUTO_TEST_CASE(test_bit_stream_4)
{
    cout << "testing bitstream 4" << endl;

    M6OBitStream bits;

    uint32 a[] = { 3 };
    uint32 b[] = { 1, 2, 5, 8, 9 };
    uint32 c[] = { 1, 2, 4, 5, 8, 9 };

    vector<uint32> va(a, a + sizeof(a) / sizeof(uint32));
    vector<uint32> vb(b, b + sizeof(b) / sizeof(uint32));
    vector<uint32> vc(c, c + sizeof(c) / sizeof(uint32));

    WriteArray(bits, va);
    WriteArray(bits, vb);
    WriteArray(bits, vc);
    bits.Sync();

    M6OBitStream b2;
    CopyBits(b2, bits);
    b2.Sync();

    M6IBitStream b3(b2);
    vector<uint32> t;

    ReadArray(b3, t);    BOOST_CHECK(t == va);
    ReadArray(b3, t);    BOOST_CHECK(t == vb);
    ReadArray(b3, t);    BOOST_CHECK(t == vc);
}

BOOST_AUTO_TEST_CASE(test_bit_stream_5)
{
    cout << "testing bitstream 5" << endl;

    M6OBitStream bits;

    uint32 a[] = { 3 };
    uint32 b[] = { 1, 2, 5, 8, 9 };
    uint32 c[] = { 1, 2, 4, 5, 8, 9 };

    vector<uint32> va(a, a + sizeof(a) / sizeof(uint32));
    vector<uint32> vb(b, b + sizeof(b) / sizeof(uint32));
    vector<uint32> vc(c, c + sizeof(c) / sizeof(uint32));

    M6OBitStream ob1;    WriteArray(ob1, va);    CopyBits(bits, ob1);
    BOOST_CHECK_EQUAL(ob1.BitSize(), bits.BitSize());
    M6OBitStream ob2;    WriteArray(ob2, vb);    CopyBits(bits, ob2);
    BOOST_CHECK_EQUAL(ob1.BitSize() + ob2.BitSize(), bits.BitSize());
    M6OBitStream ob3;    WriteArray(ob3, vc);    CopyBits(bits, ob3);
    BOOST_CHECK_EQUAL(ob1.BitSize() + ob2.BitSize() + ob3.BitSize(), bits.BitSize());
    bits.Sync();

    M6IBitStream b3(bits);
    vector<uint32> t;

    ReadArray(b3, t);    BOOST_CHECK(t == va);
    ReadArray(b3, t);    BOOST_CHECK(t == vb);
    ReadArray(b3, t);    BOOST_CHECK(t == vc);
}

BOOST_AUTO_TEST_CASE(test_bit_stream_6)
{
    cout << "testing bitstream 6" << endl;

    M6OBitStream bits;

    for (int i = 0; i < 10; ++i)
    {
        vector<uint32> v(100 + i * 13);
        iota(v.begin(), v.end(), 100 + i * 13);

        M6OBitStream ob;
        WriteArray(ob, v);
        CopyBits(bits, ob);
    }

    bits.Sync();

    M6IBitStream ib(bits);

    for (int i = 0; i < 10; ++i)
    {
        vector<uint32> v(100 + i * 13);
        iota(v.begin(), v.end(), 100 + i * 13);

        vector<uint32> t;
        ReadArray(ib, t);
        BOOST_CHECK(t == v);
    }
}

BOOST_AUTO_TEST_CASE(test_bit_stream_7)
{
    cout << "testing bitstream 7" << endl;

    M6OBitStream bits;

    uint32 a[] = {
        3458, 3483, 3600, 5200, 5217, 5272, 5280, 5297,
        5343, 5386, 5475, 5490, 5536, 5572, 5596, 5661,
        5679, 5721, 5742, 6519, 6520, 6521, 6522
    };

    vector<uint32> v(a, a + sizeof(a) / sizeof(uint32));

    WriteArray(bits, v);

    M6OBitStream b2;
    WriteBits(b2, bits);

    {
        M6IBitStream ib(bits);
        vector<uint32> t;
        ReadArray(ib, t);

        BOOST_CHECK(t == v);
    }

    {
        M6IBitStream ib(b2);
        M6OBitStream ob;

        ReadBits(ib, ob);

        M6IBitStream ib2(ob);

        vector<uint32> t;
        ReadArray(ib2, t);

        BOOST_CHECK(t == v);
    }
}

BOOST_AUTO_TEST_CASE(test_bit_stream_8)
{
    cout << "testing bitstream 8" << endl;

    for (uint32 i = 1; i < 1000; ++i)
    {
        cerr << i << endl;

        M6OBitStream bits;

        for (uint32 j = 0; j < i; ++j)
            bits << 1;

        M6OBitStream b2;
        //CopyBits(b2, bits);
        swap(b2, bits);

        M6IBitStream ib1(b2);
        for (uint32 j = 0; j < i; ++j)
            BOOST_CHECK_EQUAL(ib1(), 1);
        BOOST_CHECK_EQUAL(ib1(), 0);

        M6OBitStream b3;
        WriteBits(b3, b2);

        M6IBitStream ib2(b3);
        M6OBitStream b4;
        ReadBits(ib2, b4);

        M6IBitStream ib3(b4);
        for (uint32 j = 0; j < i; ++j)
            BOOST_CHECK_EQUAL(ib3(), 1);
        BOOST_CHECK_EQUAL(ib3(), 0);
    }

}

BOOST_AUTO_TEST_CASE(test_bit_stream_9)
{
    cout << "testing bitstream 9" << endl;

    uint32 d[] = { 294, 771 };

    vector<uint32> docs(d, d + 2);

    M6OBitStream bits;
    WriteArray(bits, docs);

    M6IBitStream b2(bits);

    vector<uint32> d2;
    ReadArray(b2, d2);

    BOOST_CHECK(docs == d2);
}

max_stars_repo_name: mhekkel/mrs

max_issues_repo_name: mhekkel/mrs

max_forks_repo_name: mhekkel/mrs


text:
// Copyright (C) 2005 Arkadiy Vertleyb, Peder Holt.
// Use, modification and distribution is subject to the Boost Software
// License, Version 1.0. (http://www.boost.org/LICENSE_1_0.txt)

#ifndef BOOST_TYPEOF_STD_list_hpp_INCLUDED
#define BOOST_TYPEOF_STD_list_hpp_INCLUDED

#include <list>
#include <boost/typeof/typeof.hpp>
#include <boost/typeof/std/memory.hpp>

#include BOOST_TYPEOF_INCREMENT_REGISTRATION_GROUP()

BOOST_TYPEOF_REGISTER_TEMPLATE(std::list, 1)
BOOST_TYPEOF_REGISTER_TEMPLATE(std::list, 2)

#endif//BOOST_TYPEOF_STD_list_hpp_INCLUDED

max_stars_repo_name: randolphwong/mcsema

max_issues_repo_name: randolphwong/mcsema

max_forks_repo_name: randolphwong/mcsema


text:
#pragma once
#include "ros/ros.h"
#include <ros/console.h>
#include <boost/array.hpp>
#include <geometry_msgs/PointStamped.h>
#include <gnss_msgs/BaselinePosition.h>
#include <gnss_msgs/BaselineVelocity.h>
#include <gnss_msgs/RtkAvailable.h>
#include <geometry_msgs/PointStamped.h>
#include <piksi_rtk_msgs/BaselineNed.h>
#include <piksi_rtk_msgs/VelNedCov.h>
#include <libsbp_ros_msgs/MsgBaselineNed.h>
#include <libsbp_ros_msgs/MsgVelNedCov.h>
#include <libsbp_ros_msgs/MsgPosLlh.h>
#include <libsbp_ros_msgs/MsgGpsTime.h>
#include <eigen3/Eigen/Dense>
#include <math.h>
#include <std_msgs/Bool.h>

#include <diagnostic_msgs/DiagnosticArray.h>
#include <diagnostic_updater/diagnostic_updater.h>
#include <diagnostic_updater/publisher.h>

#include "libsbp_ros_msgs/ros_conversion.h"

class SwiftNavRover{
public:
    SwiftNavRover(ros::NodeHandle* node_handle, double la, double lo, double al);

    // WGS 84 derived geometric constants
    const double kSemimajorAxis = 6378137.0;
    const double kSemiminorAxis = 6356752.3142;
    const double kFirstEccentricitySquared = 6.69437999014 * 0.001;
    const double kSecondEccentricitySquared = 6.73949674228 * 0.001;
    const double kFlattening = 1/298.257223563;

    typedef Eigen::Matrix<double,3,3> Matrix3x3d;
    Matrix3x3d ecef_to_ned_matrix;

    ros::NodeHandle nh;

    /**
     * Initialize the publishers and subscribers for the ROS node
     * @param
     * @return
     */
    void init();

    // Publisher functions
    /**
     * Publish the baseline position (NED), with mesage type gnss_msgs/BaselinePosition
     * @param fields of the gnss_msgs/BaselinePosition message type
     * @return void
     */
    void publishBaselinePosition(ros::Time& t, double n, double e, double d, int tow, boost::array<double, 9>& covariance, int n_sats, int fixed_mode);

    /**
     * Publish the baseline velocity, with mesage type gnss_msgs/BaselineVelocity
     * @param fields of the gnss_msgs/BaselineVelocity message type
     * @return
     */
    void publishBaselineVelocity(ros::Time& t, int tow,double n,double e,double d,boost::array<double, 9>& covariance,int n_sats,int vel_mode,int ins_mode);

    /**
     * Publish the availability of RTK positioning, as a boolean
     * @param ROS timestamp
     * @return
     */
    void publishRTKAvailable(ros::Time& t);

    /**
     * Publish the diagnostic information of the GNSS driver
     * @param ROS timer
     * @return
     */
    void publishStatus(const ros::TimerEvent& event);

    // Callback functions
    /**
     * Callback function when message of type libsbp_ros_msgs/MsgVelNedCov is published
     * @param pointer to the message
     * @return
     */
    void baselineVelocityCallback(const libsbp_ros_msgs::MsgVelNedCov::ConstPtr & msg);

    /**
     * Callback function when message of type libsbp_ros_msgs/MsgPosLlh is published
     * @param pointer to the message
     * @return
     */
    void posLLHCallback(const libsbp_ros_msgs::MsgPosLlh::ConstPtr & msg);

    /**
     * Callback function when message of type libsbp_ros_msgs/MsgBaselineNed is published
     * @param pointer to the message
     * @return
     */
    void baselinePositionCallback(const libsbp_ros_msgs::MsgBaselineNed::ConstPtr & msg);

    /**
     * Callback function when message of type libsbp_ros_msgs/MsgGpsTime is published
     * @param pointer to the message
     * @return
     */
    void gpsTimeCallback(const libsbp_ros_msgs::MsgGpsTime::ConstPtr & msg);

    // Co-ordinate conversions
    /**
     * Convert geodetic frame position (LLH) to NED coordinates
     * @param LLH position, and pointer to the NED position variables
     * @return
     */
    void geodetic2ned(double latitude, double longitude, double altitude, double* north, double* east, double* down);

    /**
     * Convert geodetic frame position (LLH) to ECEF coordinates
     * @param LLH position, and pointer to the ECEF position variables
     * @return
     */
    void geodetic2ecef(double latitude, double longitude, double altitude, double *x, double *y, double *z);

    /**
     * Convert ECEF coordinates to NED coordinates
     * @param ECEF position, and pointer to the NED position variables
     * @return
     */
    void ecef2ned(double x_t, double y_t, double z_t, double* north, double* east, double* down);

    // Setters
    void setHomeECEF(double* x, double* y, double* z)
    {
        home_ecef_x_ = *x;
        home_ecef_y_ = *y;
        home_ecef_z_ = *z;
    }

    // Utility functions
    inline double deg2rad(double degrees)
    {
        return (degrees / 180.0) * M_PI;
    }

    inline Matrix3x3d nRe(const double lat_radians, const double lon_radians)
    {
        const double sLat = sin(lat_radians);
        const double sLon = sin(lon_radians);
        const double cLat = cos(lat_radians);
        const double cLon = cos(lon_radians);
        Matrix3x3d ret;
        ret(0, 0) = -sLat * cLon;
        ret(0, 1) = -sLat * sLon;
        ret(0, 2) = cLat;
        ret(1, 0) = -sLon;
        ret(1, 1) = cLon;
        ret(1, 2) = 0.0;
        ret(2, 0) = cLat * cLon;
        ret(2, 1) = cLat * sLon;
        ret(2, 2) = sLat;
        return ret;
    }

    private:
    // Timer to publish status messages at 1Hz
    ros::Timer status_timer_;

    double home_lat_, home_lon_, home_alt_;
    double home_ecef_x_, home_ecef_y_, home_ecef_z_;
    double home_lat_rad_, home_lon_rad_;

    // Declare subscribers
    ros::Subscriber vel_sub_;
    ros::Subscriber pos_sub_;
    ros::Subscriber pos_llh_sub_;
    ros::Subscriber gps_time_sub_;

    // Declare publishers
    ros::Publisher ned_point_fix_;
    ros::Publisher ned_baseline_position_fix_;
    ros::Publisher ned_vel_cov_fix_;
    ros::Publisher rtk_mode_available_;
    ros::Publisher diagnostic_publisher_;

    // Flag to check if satellites are visible - if this drops to 0,
    // RTK blackout has occured. If false, it means that RTK blackout
    // has occured
    bool satellite_check_ = false;

    // Variable to store the operation mode of the rover - float RTK,
    // fix-RTK, SBAS, etc
    int positioning_mode_;

    // /gps_time converted to UNIX time stamp
    ros::Time convertedTime_;

    int week_;
    int residual_;
    int leap_seconds_ = 18;
};


text:
/*    Copyright (c) 2010-2019, Delft University of Technology
 *    All rigths reserved
 *
 *    This file is part of the Tudat. Redistribution and use in source and
 *    binary forms, with or without modification, are permitted exclusively
 *    under the terms of the Modified BSD license. You should have received
 *    a copy of the license with this file. If not, please or visit:
 *    http://tudat.tudelft.nl/LICENSE.
 *
 */

#include <boost/date_time/gregorian/gregorian.hpp>

#include "Tudat/Astrodynamics/BasicAstrodynamics/physicalConstants.h"
#include "Tudat/Astrodynamics/BasicAstrodynamics/timeConversions.h"
#include "Tudat/Basics/timeType.h"

namespace tudat
{
namespace basic_astrodynamics
{

//! Function to get the Julian day on J2000, in double precision.
template< >
double getJulianDayOnJ2000< double >( )
{
    return JULIAN_DAY_ON_J2000;
}

//! Function to get the Julian day on J2000, in long double precision.
template< >
long double getJulianDayOnJ2000< long double >( )
{
    return JULIAN_DAY_ON_J2000_LONG;
}

//! Function to get the Julian day on zero modified Julian day, in double precision.
template< >
double getJulianDayOnMjd0< double >( )
{
    return JULIAN_DAY_AT_0_MJD;
}

//! Function to get the Julian day on zero modified Julian day, in long double precision.
template< >
long double getJulianDayOnMjd0< long double >( )
{
    return JULIAN_DAY_AT_0_MJD_LONG;
}

//! Function to get the synchronization Julian day of TT, TCG, and TCB, in double precision.
template< >
double getTimeOfTaiSynchronizationJulianDay< double >( )
{
    return TAI_JULIAN_DAY_AT_TIME_SYNCHRONIZATION;
}

//! Function to get the synchronization Julian day of TT, TCG, and TCB, in long double precision.
template< >
long double getTimeOfTaiSynchronizationJulianDay< long double >( )
{
    return TAI_JULIAN_DAY_AT_TIME_SYNCHRONIZATION_LONG;
}

//! Function to get the difference between TDB and (TT, TCB and TCB) at TAI_JULIAN_DAY_AT_TIME_SYNCHRONIZATION,
//! in double precision.
template< >
double getTdbSecondsOffsetAtSynchronization< double >( )
{
    return TDB_SECONDS_OFFSET_AT_SYNCHRONIZATION;
}

//! Function to get the difference between TDB and (TT, TCB and TCB) at TAI_JULIAN_DAY_AT_TIME_SYNCHRONIZATION,
//! in long double precision.
template< >
long double getTdbSecondsOffsetAtSynchronization< long double >( )
{
    return TDB_SECONDS_OFFSET_AT_SYNCHRONIZATION_LONG;
}

//! Function to get the offset of TT from TAI (constant by definition), in double precision.
template< >
double getTTMinusTai< double >( )
{
    return TT_MINUS_TAI;
}

//! Function to get the offset of TT from TAI (constant by definition), in long double precision.
template< >
long double getTTMinusTai< long double >( )
{
    return TT_MINUS_TAI_LONG;
}

//! Function to get the offset of TT from TAI (constant by definition), in Time format.
template< >
Time getTTMinusTai< Time>( )
{
    return Time( TT_MINUS_TAI_LONG );
}

//! Function to convert julian day to gregorian calendar date.
boost::gregorian::date convertJulianDayToCalendarDate( const double julianDay )
{
    // Declare temporary variables.
    int L, M, N, P, Q;

    // Declare date variables.
    int day, month, year;

    // Execute algorithm.
    double shiftedJulianDay = julianDay + 0.5;
    if( shiftedJulianDay > 2299160 )    // after Oct 4, 1582
    {
        L = shiftedJulianDay + 68569;
        M = (4 * L) / 146097;
        L = L - ((146097 * M + 3) / 4);
        N = (4000 * (L + 1)) / 1461001;
        L = L - ((1461 * N) / 4) + 31;
        P = (80 * L) / 2447;
        day = int(L - (2447 * P) / 80);
        L = P / 11;
        month = int(P + 2 - 12 * L);
        year = int(100 * (M - 49) + N + L);
    }
    else
    {
        P = shiftedJulianDay + 1402;
        Q = (P - 1) / 1461;
        L = P - 1461 * Q;
        M = (L - 1) / 365 - L / 1461;
        N = L - 365 * M + 30;
        P = (80 * N) / 2447;
        day = int(N - (2447 * P) / 80);
        N = P / 11;
        month = int( P + 2 - 12 * N );
        year = int( 4 * Q + M + N - 4716 );
        if(year <= 0)
        {
            --year;
        }
    }
    // catch century/non-400 non-leap years
    if( year > 1599 && !( year % 100 )
            && ( year % 400 ) && month == 2 && day == 29 )
    {
        month = 3;
        day = 1;
    }

    // Create and return date object

    return boost::gregorian::date( year, month, static_cast< double >( day ) );
}

//! Function to determine whether the given year is a leap year (i.e. has 366 days)
bool isLeapYear( const int year )
{
    bool isLeapYear = 0;
    if( ( year % 4 == 0 ) && !( ( year % 100 == 0 ) && !( year % 400 == 0 ) ) )
    {
        isLeapYear = 1;
    }
    return isLeapYear;
}

//! Function that returns number of days in given month number
int getDaysInMonth( const int month,
                    const int year )
{
    // Declare number of days per month
    static const int daysPerMonth[ 12 ] =
    { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
    int numberOfDays = 0;

    // Check input consistency
    if( month < 1 || month > 12 )
    {
        throw std::runtime_error( "Error, month number " + std::to_string( month ) +
                                  " does not exist, value must be gretaer than 0 and smaller than 13" );
    }
    else
    {
        numberOfDays = daysPerMonth[ month - 1 ];

        // Check for leap year.
        if( month == 2 && isLeapYear( year ) )
        {
            numberOfDays++;
        }
    }
    return numberOfDays;
}

//! Determine number of full days that have passed in current year
int convertDayMonthYearToDayOfYear( const int day,
                                    const int month,
                                    const int year )
{
    return convertDayMonthYearToDayOfYear( boost::gregorian::date( year, month, day ) );
}

//! Determine number of full days that have passed in current year
int convertDayMonthYearToDayOfYear( const boost::gregorian::date calendarDate )
{
    // Calculate and return result (taking into account that this function should return 0 for first day, not 1)
    return ( calendarDate.day_of_year( ) - 1 );
}

//! Determine number of seconds into current day of given time
double calculateSecondsInCurrentJulianDay( const double julianDay )
{
    // Calculate and return result, taking into accoun the fact that julian day 0.0 is at 12:00 and result starts counting at 00:00
    return ( julianDay + 0.5 - std::floor( julianDay + 0.5 ) ) * physical_constants::JULIAN_DAY;
}

//! Function to create the calendar date from the year and the number of days in the year
boost::gregorian::date convertYearAndDaysInYearToDate( const int year, const int daysInYear )
{
    // Go to day 1 at 01-01 convention
    int daysLeft = daysInYear + 1;

    // Loop over all months (starting at January until month in which daysinYear is situated is found)
    int currentMonth = 1;
    int daysInCurrentMonth;
    bool isConverged = 0;
    while( !isConverged )
    {
        // Determine days in current month
        daysInCurrentMonth = getDaysInMonth( currentMonth, year );
        if( daysInCurrentMonth < daysLeft )
        {
            // Subtract days in current month from days left.
            daysLeft -= daysInCurrentMonth;

            // Update month and check consistency
            currentMonth++;
            if( currentMonth > 12 )
            {
                throw std::runtime_error(
                            "Error when converting year and days in year to date, month number has exceeded 12" );
            }
        }
        else
        {
            isConverged = 1;
        }
    }

    // Create date and return
    boost::gregorian::date date( year, currentMonth, daysLeft );

    if( date.day_of_year( ) != daysInYear + 1 )
    {
        throw std::runtime_error(
                    "Error when converting year and days in year to date, inconsistent output" );
    }

    return date;
}

//! Perform apprixmate conversion of TT to TDB
double approximateConvertTTtoTDB( const double ttSecondsSinceJ2000 )
{
    double ttCenturiesSinceJ2000 = ttSecondsSinceJ2000 / ( 100.0 * physical_constants::JULIAN_YEAR );
    return ttSecondsSinceJ2000 + 0.001657  * std::sin( 628.3076 * ttCenturiesSinceJ2000 + 6.2401 );
}

} // namespace basic_astrodynamics
} // namespace tudat

max_stars_repo_name: sebranchett/tudat

max_issues_repo_name: sebranchett/tudat

max_forks_repo_name: sebranchett/tudat


text:
#include <boost/python.hpp>
#include <boost/cstdint.hpp>

#include <Magick++/Drawable.h>
#include <Magick++.h>

using namespace boost::python;

namespace  {

struct Magick_DrawableText_Wrapper: Magick::DrawableText
{
    Magick_DrawableText_Wrapper(PyObject* py_self_, const double p0, const double p1, const std::string& p2):
        Magick::DrawableText(p0, p1, p2), py_self(py_self_) {}

    Magick_DrawableText_Wrapper(PyObject* py_self_, const double p0, const double p1, const std::string& p2, const std::string& p3):
        Magick::DrawableText(p0, p1, p2, p3), py_self(py_self_) {}

    Magick_DrawableText_Wrapper(PyObject* py_self_, const Magick::DrawableText& p0):
        Magick::DrawableText(p0), py_self(py_self_) {}

    PyObject* py_self;
};

}

void __DrawableText()
{
    class_< Magick::DrawableText, bases<Magick::DrawableBase>, Magick_DrawableText_Wrapper >("DrawableText", init< const Magick::DrawableText& >())
        .def(init< const double, const double, const std::string& >())
        .def(init< const double, const double, const std::string&, const std::string& >())
        .def("encoding", &Magick::DrawableText::encoding)
        .def("x", (void (Magick::DrawableText::*)(double) )&Magick::DrawableText::x)
        .def("x", (double (Magick::DrawableText::*)() const)&Magick::DrawableText::x)
        .def("y", (void (Magick::DrawableText::*)(double) )&Magick::DrawableText::y)
        .def("y", (double (Magick::DrawableText::*)() const)&Magick::DrawableText::y)
        .def("text", (void (Magick::DrawableText::*)(const std::string&) )&Magick::DrawableText::text)
        .def("text", (std::string (Magick::DrawableText::*)() const)&Magick::DrawableText::text)
    ;
}

max_stars_repo_name: veryhappythings/pgmagick

max_issues_repo_name: veryhappythings/pgmagick

max_forks_repo_name: veryhappythings/pgmagick


text:
/**
 * Copyright (c) 2016, Adrien Devresse <adrien.devresse@epfl.ch>
 *
 * Boost Software License - Version 1.0
 *
 * Permission is hereby granted, free of charge, to any person or organization
 * obtaining a copy of the software and accompanying documentation covered by
 * this license (the "Software") to use, reproduce, display, distribute,
 * execute, and transmit the Software, and to prepare derivative works of the
 * Software, and to permit third-parties to whom the Software is furnished to
 * do so, all subject to the following:
 *
 * The copyright notices in the Software and this entire statement, including
 * the above license grant, this restriction and the following disclaimer,
 * must be included in all copies of the Software, in whole or in part, and
 * all derivative works of the Software, unless such copies or derivative
 * works are solely in the form of machine-executable object code generated by
 * a source language processor.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT
 * SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
 * FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
 * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
 * DEALINGS IN THE SOFTWARE.
 *
 */
#ifndef _HADOKEN_RANDOM_ENGINE_MAPPER_HPP_
#define _HADOKEN_RANDOM_ENGINE_MAPPER_HPP_

#include <algorithm>
#include <cassert>
#include <memory>
#include <vector>

#include <boost/integer.hpp>
#include <boost/random.hpp>

namespace hadoken {

// internals
namespace impl {
template <typename Uint>
class abstract_engine;
}

///
/// runtime abstraction layer for the C++11 / boost.Random
/// random engine system
///
/// Allow to abstract different random generators behind a single
/// interface at runtime
///
///
template <typename Uint>
class random_engine_mapper {
  public:
    typedef Uint result_type;

    /// default constructor
    /// generate empty mapper
    explicit random_engine_mapper();
    ///
    /// map a specialized random generator in the C++11 / boost format
    ///  to a generic random_engine_mapper that can be used in any distribution
    ///
    template <typename Engine>
    explicit random_engine_mapper(Engine&& intern);

    random_engine_mapper(random_engine_mapper&& other);

    random_engine_mapper& operator=(random_engine_mapper&&);

    /// reset to defautl seed, mapping
    inline void seed();

    /// reset to seed X, mapping
    void seed(result_type seed);

    /// generator operation
    result_type operator()();

    /// derivate create a random engine
    ///  derivated from the current random engine
    ///  seed and the key.
    ///
    ///  The derivation respect the following rules
    ///  - The operation is always deterministic for a given key and seed
    ///  - The new random engine do not have statistical correlation with the old one
    ///  - Two different keys, even close in range guarantee two independent random streams
    ///
    ///
    random_engine_mapper derivate(result_type key) const;

    /// minimum value returned by engine
    /// map to minimum value of the type
    static result_type min() { return std::numeric_limits<result_type>::min(); }

    /// minimum value returned by engine
    /// map to maximum value of the type
    static result_type max() { return std::numeric_limits<result_type>::max(); }

  private:
    std::unique_ptr<impl::abstract_engine<result_type>> _engine;

    random_engine_mapper(const random_engine_mapper& other) = delete;

    random_engine_mapper& operator=(const random_engine_mapper& other) = delete;
};

typedef random_engine_mapper<boost::uint32_t> random_engine_mapper_32;
typedef random_engine_mapper<boost::uint64_t> random_engine_mapper_64;

// specialize random_engine_derivate
// for random mapper

template <typename Uint>
inline random_engine_mapper<Uint> random_engine_derivate(const random_engine_mapper<Uint>& engine,
                                                         const typename random_engine_mapper<Uint>::result_type& key) {
    return engine.derivate(key);
}

} // namespace hadoken

#include "impl/random_engine_mapper_misc.hpp"

#endif // _HADOKEN_RANDOM_ENGINE_MAPPER_HPP_

max_stars_repo_name: adevress/hadoken

max_issues_repo_name: mrexodia/hadoken

max_forks_repo_name: mrexodia/hadoken


text:
//==================================================================================================
/**
  Copyright 2016 NumScale SAS

  Distributed under the Boost Software License, Version 1.0.
  (See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)
**/
//==================================================================================================
#ifndef BOOST_SIMD_RANGE_HPP_INCLUDED
#define BOOST_SIMD_RANGE_HPP_INCLUDED

#include <boost/simd/range/input_range.hpp>
#include <boost/simd/range/output_range.hpp>
#include <boost/simd/range/aligned_input_range.hpp>
#include <boost/simd/range/aligned_output_range.hpp>
#include <boost/simd/range/segmented_input_range.hpp>
#include <boost/simd/range/segmented_output_range.hpp>

#endif

max_stars_repo_name: xmar/pythran

max_issues_repo_name: xmar/pythran

max_forks_repo_name: xmar/pythran


text:
#include <iostream>
#include <boost/program_options.hpp>

#include "core.hpp"
#include "network_graph.hpp"

namespace po = boost::program_options;

int Core::_handle_po(int argc, char *argv[])
{
	/* Command line options handling */
	std::string app_name(argv[0]);
	std::string usage("Usage: " + app_name + " [options] <graph file>");
	std::string in_graph_file;
	bool enable_gui = true;
	unsigned int sqr_weight = 10;
	po::options_description cmdline_opts;
	po::options_description normal_opts("Allowed options");
	po::options_description hidden_opts;
	po::positional_options_description pos_opts;
	po::variables_map var_map;

	try {
		normal_opts.add_options()
			("help,h", "this help message")
			("no-gui", "disable gui")
			("sqr-weight,s", po::value<unsigned int>()->default_value(10),
			 "number of squares of vertices")
			;
		hidden_opts.add_options()
			("input-file", "graph file")
			;
		pos_opts.add("input-file", -1);
		cmdline_opts.add(normal_opts).add(hidden_opts);
		store(po::command_line_parser(argc, argv).options(cmdline_opts).positional(pos_opts).run(),
			var_map);
		notify(var_map);

		if (var_map.count("help")) {
			std::cout << usage << std::endl;
			std::cout << normal_opts << std::endl;
			return 1;
		}
		if (var_map.count("no-gui"))
			enable_gui = false;
		if (var_map.count("input-file"))
			in_graph_file = var_map["input-file"].as<std::string>();
		if (var_map.count("sqr-weight"))
			sqr_weight = var_map["sqr-weight"].as<unsigned int>();
	} catch (std::exception& e) {
		std::cout << "error: " << e.what() << std::endl;
		return -1;
	}

	if (enable_gui)
		return 0;

	if (in_graph_file.empty())
		_ngraph.sqr_weight(sqr_weight);
	else
		_ngraph.graph_file(in_graph_file);

	return 1;
}

NetworkGraph * Core::network_graph()
{
	return &_ngraph;
}

int Core::run_cli()
{
	unsigned int src, dst;
	route_t route;

	if (_ngraph.graph_file().empty())
		_ngraph.add_routes_random();

	_ngraph.add_routes_from_file();
	_ngraph.graph_edges();
	_ngraph.calc_routing_graph();

	std::cout << "Choose the source node: ";
	std::cin >> src;
	std::cout << "Choose the destination node: ";
	std::cin >> dst;

	route = _ngraph.find_shortest_path(src, dst);

	std::cout << "distance from " << src << " to " << dst << ": " <<
		route.first.cost << std::endl;
	std::cout << "route: ";
	for (auto vertex: route.second)
		std::cout << vertex->id << " ";
	std::cout << std::endl;

	return 0;
}

int Core::init(int argc, char *argv[])
{
	return _handle_po(argc, argv);
}

max_stars_repo_name: bmeneguele/wnet-sim

max_issues_repo_name: bmeneguele/wnet-sim

max_forks_repo_name: bmeneguele/wnet-sim


text:
#include <facter/util/string.hpp>
#include <boost/regex.hpp>
#include <sstream>
#include <iomanip>
#include <algorithm>
#include <iterator>
#include <cmath>
#include <limits>

using namespace std;

namespace facter { namespace util {

    string to_hex(uint8_t const* bytes, size_t length, bool uppercase)
    {
        ostringstream ss;
        if (bytes) {
            ss << hex << (uppercase ? std::uppercase : std::nouppercase) << setfill('0');
            for (size_t i = 0; i < length; ++i) {
                ss << setw(2) << static_cast<int>(bytes[i]);
            }
        }
        return ss.str();
    }

    void each_line(string const& s, function<bool(string&)> callback)
    {
        string line;
        istringstream in(s);
        while (getline(in, line)) {
            // Handle Windows CR in the string.
            if (line.size() && line.back() == '\r') {
                line.pop_back();
            }
            if (!callback(line)) {
                break;
            }
        }
    }

    string si_string(uint64_t size)
    {
        static char prefixes[] = { 'K', 'M', 'G', 'T', 'P', 'E' };

        if (size < 1024) {
            return to_string(size) + " bytes";
        }
        unsigned int exp = floor(log2(size) / 10.0);
        double converted = round(100.0 * (size / pow(1024.0, exp))) / 100.0;

        // Check to see if rounding up gets us to 1024; if so, move to the next unit
        if (fabs(converted - 1024.0) < numeric_limits<double>::epsilon()) {
            converted = 1.00;
            ++exp;
        }

        // If we exceed the SI prefix (we shouldn't, but just in case), just return the bytes
        if (exp - 1 >= sizeof(prefixes)) {
            return to_string(size) + " bytes";
        }

        ostringstream ss;
        ss  << fixed << setprecision(2) << converted << " " << prefixes[exp - 1] << "iB";
        return ss.str();
    }

    string percentage(uint64_t used, uint64_t total)
    {
        if (total == 0 || used >= total) {
            return "100%";
        }
        if (used == 0) {
            return "0%";
        }
        double converted = round(10000.0 * (used / static_cast<double>(total))) / 100.0;
        // Check to see if we would round up to 100%; if so, keep it at 99.99%
        if (fabs(converted - 100.0) < numeric_limits<double>::epsilon()) {
            converted = 99.99;
        }
        ostringstream ss;
        ss << fixed << setprecision(2) << converted << "%";
        return ss.str();
    }

    string frequency(int64_t freq)
    {
        static char prefixes[] = { 'k', 'M', 'G', 'T'  };

        if (freq < 1000) {
            return to_string(freq) + " Hz";
        }
        unsigned int exp = floor(log10(freq) / 3.0);
        double converted = round(100.0 * (freq / pow(1000.0, exp))) / 100.0;

        // Check to see if rounding up gets us to 1000; if so, move to the next unit
        if (fabs(converted - 1000.0) < numeric_limits<double>::epsilon()) {
            converted = 1.00;
            ++exp;
        }

        // If we exceed the SI prefix (we shouldn't, but just in case), just return the speed in Hz
        if (exp - 1 >= sizeof(prefixes)) {
            return to_string(freq) + " Hz";
        }

        ostringstream ss;
        ss  << fixed << setprecision(2) << converted << " " << prefixes[exp - 1] << "Hz";
        return ss.str();
    }

    bool needs_quotation(string const& str)
    {
        // Empty strings should be quoted
        if (str.empty()) {
            return true;
        }

        // Taken from http://yaml.org/type/bool.html.
        // The string would be interpreted as a boolean, so quote it.
        static boost::regex yaml_bool("y|Y|yes|Yes|YES|n|N|no|No|NO|true|True|TRUE|false|False|FALSE|on|On|ON|off|Off|OFF");
        if (boost::regex_match(str, yaml_bool)) {
            return true;
        }

        // A string starting with the ':' special character interferes with parsing.
        // Other string patterns containing ':' can be unexpectedly parsed as sexagesimal.
        // To be safe quote all strings that contain ':' characters.
        if (str.find(':') != string::npos) {
            return true;
        }

        // Poor man's check for a numerical string or list of numbers
        // May start with - or +
        // May contain one . and one or more ,
        // All other characters should be digits
        // Note: Ruby YAML interprets 1,2,3 as a number, but not 1.2.3.
        // It doesn't appear to honor locales when parsing YAML.
        bool has_dot = false;
        for (size_t i = 0; i < str.size(); ++i) {
            char c = str[i];
            if (i == 0 && (c == '+' || c == '-')) {
                continue;
            }
            if (c == ',') {
                continue;
            }
            if (c == '.') {
                if (has_dot) {
                    return false;
                }
                has_dot = true;
                continue;
            }
            if (!isdigit(c)) {
                return false;
            }
        }

        // Numerical strings should be quoted
        return true;
    }

}}  // namespace facter::util

ext: cc

max_stars_repo_name: hkenney/facter

max_issues_repo_name: hkenney/facter

max_forks_repo_name: hkenney/facter


text:
// copyright (c) 2012-2014 the moorecoin core developers
// distributed under the mit software license, see the accompanying
// file copying or http://www.opensource.org/licenses/mit-license.php.

#include "wallet/wallet.h"
#include "wallet/walletdb.h"

#include "test/test_moorecoin.h"

#include <stdint.h>

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

extern cwallet* pwalletmain;

boost_fixture_test_suite(accounting_tests, testingsetup)

static void
getresults(cwalletdb& walletdb, std::map<camount, caccountingentry>& results)
{
    std::list<caccountingentry> aes;

    results.clear();
    boost_check(walletdb.reordertransactions(pwalletmain) == db_load_ok);
    walletdb.listaccountcreditdebit("", aes);
    boost_foreach(caccountingentry& ae, aes)
    {
        results[ae.norderpos] = ae;
    }
}

boost_auto_test_case(acc_orderupgrade)
{
    cwalletdb walletdb(pwalletmain->strwalletfile);
    std::vector<cwallettx*> vpwtx;
    cwallettx wtx;
    caccountingentry ae;
    std::map<camount, caccountingentry> results;

    lock(pwalletmain->cs_wallet);

    ae.straccount = "";
    ae.ncreditdebit = 1;
    ae.ntime = 1333333333;
    ae.strotheraccount = "b";
    ae.strcomment = "";
    walletdb.writeaccountingentry(ae);

    wtx.mapvalue["comment"] = "z";
    pwalletmain->addtowallet(wtx, false, &walletdb);
    vpwtx.push_back(&pwalletmain->mapwallet[wtx.gethash()]);
    vpwtx[0]->ntimereceived = (unsigned int)1333333335;
    vpwtx[0]->norderpos = -1;

    ae.ntime = 1333333336;
    ae.strotheraccount = "c";
    walletdb.writeaccountingentry(ae);

    getresults(walletdb, results);

    boost_check(pwalletmain->norderposnext == 3);
    boost_check(2 == results.size());
    boost_check(results[0].ntime == 1333333333);
    boost_check(results[0].strcomment.empty());
    boost_check(1 == vpwtx[0]->norderpos);
    boost_check(results[2].ntime == 1333333336);
    boost_check(results[2].strotheraccount == "c");

    ae.ntime = 1333333330;
    ae.strotheraccount = "d";
    ae.norderpos = pwalletmain->incorderposnext();
    walletdb.writeaccountingentry(ae);

    getresults(walletdb, results);

    boost_check(results.size() == 3);
    boost_check(pwalletmain->norderposnext == 4);
    boost_check(results[0].ntime == 1333333333);
    boost_check(1 == vpwtx[0]->norderpos);
    boost_check(results[2].ntime == 1333333336);
    boost_check(results[3].ntime == 1333333330);
    boost_check(results[3].strcomment.empty());

    wtx.mapvalue["comment"] = "y";
    {
        cmutabletransaction tx(wtx);
        --tx.nlocktime;  // just to change the hash :)
        *static_cast<ctransaction*>(&wtx) = ctransaction(tx);
    }
    pwalletmain->addtowallet(wtx, false, &walletdb);
    vpwtx.push_back(&pwalletmain->mapwallet[wtx.gethash()]);
    vpwtx[1]->ntimereceived = (unsigned int)1333333336;

    wtx.mapvalue["comment"] = "x";
    {
        cmutabletransaction tx(wtx);
        --tx.nlocktime;  // just to change the hash :)
        *static_cast<ctransaction*>(&wtx) = ctransaction(tx);
    }
    pwalletmain->addtowallet(wtx, false, &walletdb);
    vpwtx.push_back(&pwalletmain->mapwallet[wtx.gethash()]);
    vpwtx[2]->ntimereceived = (unsigned int)1333333329;
    vpwtx[2]->norderpos = -1;

    getresults(walletdb, results);

    boost_check(results.size() == 3);
    boost_check(pwalletmain->norderposnext == 6);
    boost_check(0 == vpwtx[2]->norderpos);
    boost_check(results[1].ntime == 1333333333);
    boost_check(2 == vpwtx[0]->norderpos);
    boost_check(results[3].ntime == 1333333336);
    boost_check(results[4].ntime == 1333333330);
    boost_check(results[4].strcomment.empty());
    boost_check(5 == vpwtx[1]->norderpos);

    ae.ntime = 1333333334;
    ae.strotheraccount = "e";
    ae.norderpos = -1;
    walletdb.writeaccountingentry(ae);

    getresults(walletdb, results);

    boost_check(results.size() == 4);
    boost_check(pwalletmain->norderposnext == 7);
    boost_check(0 == vpwtx[2]->norderpos);
    boost_check(results[1].ntime == 1333333333);
    boost_check(2 == vpwtx[0]->norderpos);
    boost_check(results[3].ntime == 1333333336);
    boost_check(results[3].strcomment.empty());
    boost_check(results[4].ntime == 1333333330);
    boost_check(results[4].strcomment.empty());
    boost_check(results[5].ntime == 1333333334);
    boost_check(6 == vpwtx[1]->norderpos);
}

boost_auto_test_suite_end()

max_stars_repo_name: moorecoin/MooreCoinMiningAlgorithm

max_issues_repo_name: moorecoin/MooreCoinMiningAlgorithm

max_forks_repo_name: moorecoin/MooreCoinMiningAlgorithm


text:
//
// Copyright 2005-2007 Adobe Systems Incorporated
//
// Distributed under the Boost Software License, Version 1.0
// See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt
//
#ifndef BOOST_GIL_EXTENSION_DYNAMIC_IMAGE_VARIANT_HPP
#define BOOST_GIL_EXTENSION_DYNAMIC_IMAGE_VARIANT_HPP

// TODO: Replace with C++17 std::variant?

#include <boost/gil/utilities.hpp>

#include <boost/bind.hpp>
#include <boost/mpl/at.hpp>
#include <boost/mpl/bool.hpp>
#include <boost/mpl/fold.hpp>
#include <boost/mpl/max.hpp>
#include <boost/mpl/size.hpp>
#include <boost/mpl/sizeof.hpp>
#include <boost/mpl/transform.hpp>
#include <boost/utility/enable_if.hpp>

#include <algorithm>
#include <cassert>
#include <cstddef>
#include <typeinfo>

namespace boost { namespace gil {

// Support for run-time instantiated types

namespace detail {
    template <typename Types, typename T> struct type_to_index;
    template <typename Op, typename T> struct reduce;
    struct destructor_op {
        typedef void result_type;
        template <typename T> result_type operator()(const T& t) const { t.~T(); }
    };
    template <typename T, typename Bits> void copy_construct_in_place(const T& t, Bits& bits);
    template <typename Bits> struct copy_construct_in_place_fn;
    template <typename Types> struct type_to_index_fn;
}
/**
\brief Represents a concrete instance of a run-time specified type from a set of types
\class variant
\ingroup Variant

A concept is typically modeled by a collection of different types. They may be instantiations
of a templated type with different template parameters or even completely unrelated types.

We call the type with which the concept is instantiated in a given place in the code "the concrete type".
The concrete type must be chosen at compile time, which sometimes is a severe limitation.
Consider, for example, having an image concept modeled by an image class templated over the color space.
It would be difficult to write a function that reads an image from file preserving its native color space, since the
type of the return value is only available at run time. It would be difficult to store images of different color
spaces in the same container or apply operations on them uniformly.

The variant class addresses this deficiency. It allows for run-time instantiation of a class from a given set of allowed classes
specified at compile time. For example, the set of allowed classes may include 8-bit and 16-bit RGB and CMYK images. Such a variant
can be constructed with rgb8_image_t and then assigned a cmyk16_image_t.

The variant has a templated constructor, which allows us to construct it with any concrete type instantiation. It can also perform a generic
operation on the concrete type via a call to apply_operation. The operation must be provided as a function object whose application
operator has a single parameter which can be instantiated with any of the allowed types of the variant.

variant breaks down the instantiated type into a non-templated underlying base type and a unique instantiation
type identifier. In the most common implementation the concrete instantiation in stored 'in-place' - in 'bits_t'.
bits_t contains sufficient space to fit the largest of the instantiated objects.

GIL's variant is similar to boost::variant in spirit (hence we borrow the name from there) but it differs in several ways from the current boost
implementation. Most notably, it does not take a variable number of template parameters but a single parameter defining the type enumeration. As
such it can be used more effectively in generic code.

The Types parameter specifies the set of allowable types. It models MPL Random Access Container
*/

template <typename Types>    // models MPL Random Access Container
class variant {
    // size in bytes of the largest type in Types
    static const std::size_t MAX_SIZE  = mpl::fold<Types, mpl::size_t<0>, mpl::max<mpl::_1, mpl::sizeof_<mpl::_2> > >::type::value;
    static const std::size_t NUM_TYPES = mpl::size<Types>::value;
public:
    typedef Types                            types_t;

    typedef struct { char data[MAX_SIZE]; } base_t;    // empty space equal to the size of the largest type in Types

    // Default constructor - default construct the first type
    variant() : _index(0)    { new(&_bits) typename mpl::at_c<Types,0>::type(); }
    virtual ~variant()        { apply_operation(*this, detail::destructor_op()); }

    // Throws std::bad_cast if T is not in Types
    template <typename T> explicit variant(const T& obj){ _index=type_id<T>(); if (_index==NUM_TYPES) throw std::bad_cast(); detail::copy_construct_in_place(obj, _bits); }

    template <typename Types2> explicit variant(const variant<Types2>& obj) : _index(apply_operation(obj,detail::type_to_index_fn<Types>())) {
        if (_index==NUM_TYPES) throw std::bad_cast();
        apply_operation(obj, detail::copy_construct_in_place_fn<base_t>(_bits));
    }

    // When doSwap is true, swaps obj with the contents of the variant. obj will contain default-constructed instance after the call
    template <typename T> explicit variant(T& obj, bool do_swap);

    template <typename T> variant& operator=(const T& obj) { variant tmp(obj); swap(*this,tmp); return *this; }
    variant& operator=(const variant& v)                   { variant tmp(v  ); swap(*this,tmp); return *this; }

    variant(const variant& v) : _index(v._index)           { apply_operation(v, detail::copy_construct_in_place_fn<base_t>(_bits)); }
    template <typename T> void move_in(T& obj)             { variant tmp(obj, true); swap(*this,tmp); }

    template <typename TS> friend bool operator==(const variant<TS>& x, const variant<TS>& y);
    template <typename TS> friend bool operator!=(const variant<TS>& x, const variant<TS>& y);

    template <typename T> static bool has_type()           { return type_id<T>()!=NUM_TYPES; }

    template <typename T> const T& _dynamic_cast()   const { if (!current_type_is<T>()) throw std::bad_cast(); return *gil_reinterpret_cast_c<const T*>(&_bits); }
    template <typename T>       T& _dynamic_cast()         { if (!current_type_is<T>()) throw std::bad_cast(); return *gil_reinterpret_cast  <      T*>(&_bits); }

    template <typename T> bool current_type_is()     const { return type_id<T>()==_index; }

    base_t      bits()  const { return _bits;  }
    std::size_t index() const { return _index; }

private:
    template <typename T> static std::size_t type_id()     { return detail::type_to_index<Types,T>::value; }

    template <typename Cs> friend void swap(variant<Cs>& x, variant<Cs>& y);
    template <typename Types2, typename UnaryOp> friend typename UnaryOp::result_type apply_operation(variant<Types2>& var, UnaryOp op);
    template <typename Types2, typename UnaryOp> friend typename UnaryOp::result_type apply_operation(const variant<Types2>& var, UnaryOp op);
    template <typename Types1, typename Types2, typename BinaryOp> friend typename BinaryOp::result_type apply_operation(const variant<Types1>& arg1, const variant<Types2>& arg2, BinaryOp op);

    base_t      _bits;
    std::size_t    _index;
};

namespace detail {

    template <typename T, typename Bits>
    void copy_construct_in_place(const T& t, Bits& bits) {
        T& b=*gil_reinterpret_cast<T*>(&bits);
        new(&b)T(t);     // default-construct
    }

    template <typename Bits>
    struct copy_construct_in_place_fn {
        typedef void result_type;
        Bits& _dst;
        copy_construct_in_place_fn(Bits& dst) : _dst(dst) {}

        template <typename T> void operator()(const T& src) const { copy_construct_in_place(src,_dst); }
    };

    template <typename Bits>
    struct equal_to_fn {
        const Bits& _dst;
        equal_to_fn(const Bits& dst) : _dst(dst) {}

        typedef bool result_type;
        template <typename T> result_type operator()(const T& x) const {
            return x==*gil_reinterpret_cast_c<const T*>(&_dst);
        }
    };

    template <typename Types>
    struct type_to_index_fn {
        typedef std::size_t result_type;

        template <typename T> result_type operator()(const T&) const { return detail::type_to_index<Types,T>::value; }
    };
}

// When doSwap is true, swaps obj with the contents of the variant. obj will contain default-constructed instance after the call
template <typename Types>
template <typename T> variant<Types>::variant(T& obj, bool do_swap) {
    _index=type_id<T>();
    if (_index==NUM_TYPES) throw std::bad_cast();

    if (do_swap) {
        new(&_bits) T();    // default construct
        swap(obj, *gil_reinterpret_cast<T*>(&_bits));
    } else
        detail::copy_construct_in_place(const_cast<const T&>(obj), _bits);
}

template <typename Types>
void swap(variant<Types>& x, variant<Types>& y) {
    std::swap(x._bits,y._bits);
    std::swap(x._index, y._index);
}

template <typename Types>
inline bool operator==(const variant<Types>& x, const variant<Types>& y) {
    return x._index==y._index && apply_operation(x,detail::equal_to_fn<typename variant<Types>::base_t>(y._bits));
}

template <typename C>
inline bool operator!=(const variant<C>& x, const variant<C>& y) {
    return !(x==y);
}

} }  // namespace boost::gil

#endif


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

#include <folly/Conv.h>
#include <folly/Logging.h>
#include <folly/io/Cursor.h>
#include <google/protobuf/io/coded_stream.h>
#include <google/protobuf/io/zero_copy_stream_impl_lite.h>
#include <google/protobuf/message.h>
#include <boost/algorithm/string.hpp>

#include <utility>

#include "rpc/RPC.pb.h"
#include "hbase/serde/rpc-serde.h"
#include "utils/version.h"

using folly::IOBuf;
using folly::io::RWPrivateCursor;
using google::protobuf::Message;
using google::protobuf::io::ArrayInputStream;
using google::protobuf::io::ArrayOutputStream;
using google::protobuf::io::CodedInputStream;
using google::protobuf::io::CodedOutputStream;
using google::protobuf::io::ZeroCopyOutputStream;

using namespace hbase::pb;

namespace hbase {

static const std::string PREAMBLE = "HBas";
static const std::string INTERFACE = "ClientService";
static const uint8_t RPC_VERSION = 0;
static const uint8_t DEFAULT_AUTH_TYPE = 80;
static const uint8_t KERBEROS_AUTH_TYPE = 81;

int RpcSerde::ParseDelimited(const IOBuf *buf, Message *msg) {
  if (buf == nullptr || msg == nullptr) {
    return -2;
  }

  DCHECK(!buf->isChained());

  ArrayInputStream ais{buf->data(), static_cast<int>(buf->length())};
  CodedInputStream coded_stream{&ais};

  uint32_t msg_size;

  // Try and read the varint.
  if (coded_stream.ReadVarint32(&msg_size) == false) {
    FB_LOG_EVERY_MS(ERROR, 1000) << "Unable to read a var uint32_t";
    return -3;
  }

  coded_stream.PushLimit(msg_size);
  // Parse the message.
  if (msg->MergeFromCodedStream(&coded_stream) == false) {
    FB_LOG_EVERY_MS(ERROR, 1000) << "Unable to read a protobuf message from data.";
    return -4;
  }

  // Make sure all the data was consumed.
  if (coded_stream.ConsumedEntireMessage() == false) {
    FB_LOG_EVERY_MS(ERROR, 1000) << "Orphaned data left after reading protobuf message";
    return -5;
  }

  return coded_stream.CurrentPosition();
}

RpcSerde::RpcSerde() {}

RpcSerde::RpcSerde(std::shared_ptr<Codec> codec) : codec_(codec) {}

std::unique_ptr<IOBuf> RpcSerde::Preamble(bool secure) {
  auto magic = IOBuf::copyBuffer(PREAMBLE, 0, 2);
  magic->append(2);
  RWPrivateCursor c(magic.get());
  c.skip(4);
  // Version
  c.write(RPC_VERSION);
  if (secure) {
    // for now support only KERBEROS (DIGEST is not supported)
    c.write(KERBEROS_AUTH_TYPE);
  } else {
    c.write(DEFAULT_AUTH_TYPE);
  }
  return magic;
}

std::unique_ptr<IOBuf> RpcSerde::Header(const std::string &user) {
  pb::ConnectionHeader h;

  // TODO(eclark): Make this not a total lie.
  h.mutable_user_info()->set_effective_user(user);
  // The service name that we want to talk to.
  //
  // Right now we're completely ignoring the service interface.
  // That may or may not be the correct thing to do.
  // It worked for a while with the java client; until it
  // didn't.
  // TODO: send the service name and user from the RpcClient
  h.set_service_name(INTERFACE);

  std::unique_ptr<pb::VersionInfo> version_info = CreateVersionInfo();

  h.set_allocated_version_info(version_info.release());

  if (codec_ != nullptr) {
    h.set_cell_block_codec_class(codec_->java_class_name());
  }
  return PrependLength(SerializeMessage(h));
}

std::unique_ptr<pb::VersionInfo> RpcSerde::CreateVersionInfo() {
  std::unique_ptr<pb::VersionInfo> version_info = std::make_unique<pb::VersionInfo>();
  version_info->set_user(Version::user);
  version_info->set_revision(Version::revision);
  version_info->set_url(Version::url);
  version_info->set_date(Version::date);
  version_info->set_src_checksum(Version::src_checksum);
  version_info->set_version(Version::version);

  std::string version{Version::version};
  std::vector<std::string> version_parts;
  boost::split(version_parts, version, boost::is_any_of("."), boost::token_compress_on);
  uint32_t major_version = 0, minor_version = 0;
  if (version_parts.size() >= 2) {
    version_info->set_version_major(folly::to<uint32_t>(version_parts[0]));
    version_info->set_version_minor(folly::to<uint32_t>(version_parts[1]));
  }

  VLOG(1) << "Client VersionInfo:" << version_info->ShortDebugString();
  return version_info;
}

std::unique_ptr<IOBuf> RpcSerde::Request(const uint32_t call_id, const std::string &method,
                                         const Message *msg) {
  pb::RequestHeader rq;
  rq.set_method_name(method);
  rq.set_call_id(call_id);
  rq.set_request_param(msg != nullptr);
  auto ser_header = SerializeDelimited(rq);
  if (msg != nullptr) {
    auto ser_req = SerializeDelimited(*msg);
    ser_header->appendChain(std::move(ser_req));
  }

  return PrependLength(std::move(ser_header));
}

std::unique_ptr<folly::IOBuf> RpcSerde::Response(const uint32_t call_id,
                                                 const google::protobuf::Message *msg) {
  pb::ResponseHeader rh;
  rh.set_call_id(call_id);
  auto ser_header = SerializeDelimited(rh);
  auto ser_resp = SerializeDelimited(*msg);
  ser_header->appendChain(std::move(ser_resp));

  return PrependLength(std::move(ser_header));
}

std::unique_ptr<folly::IOBuf> RpcSerde::Response(const uint32_t call_id,
                                                 const google::protobuf::Message *msg,
                                                 const folly::exception_wrapper &exception) {
  /* create ResponseHeader */
  pb::ResponseHeader rh;
  rh.set_call_id(call_id);

  /* create ExceptionResponse */
  if (bool(exception)) {
    VLOG(1) << "packing ExceptionResponse";
    auto exception_response = new pb::ExceptionResponse();
    exception_response->set_exception_class_name(exception.class_name().c_str());
    exception_response->set_stack_trace(exception.what().c_str());
    rh.set_allocated_exception(exception_response);
  }

  /* serialize Response header and body */
  auto ser_header = SerializeDelimited(rh);
  auto ser_resp = SerializeDelimited(*msg);
  ser_header->appendChain(std::move(ser_resp));

  VLOG(3) << "Converted hbase::Response to folly::IOBuf";
  return PrependLength(std::move(ser_header));
}

std::unique_ptr<CellScanner> RpcSerde::CreateCellScanner(std::unique_ptr<folly::IOBuf> buf,
                                                         uint32_t offset, uint32_t length) {
  if (codec_ == nullptr) {
    return nullptr;
  }
  return codec_->CreateDecoder(std::move(buf), offset, length);
}

std::unique_ptr<IOBuf> RpcSerde::PrependLength(std::unique_ptr<IOBuf> msg) {
  // Java ints are 4 long. So create a buffer that large
  auto len_buf = IOBuf::create(4);
  // Then make those bytes visible.
  len_buf->append(4);

  RWPrivateCursor c(len_buf.get());
  // Get the size of the data to be pushed out the network.
  auto size = msg->computeChainDataLength();

  // Write the length to this IOBuf.
  c.writeBE(static_cast<uint32_t>(size));

  // Then attach the origional to the back of len_buf
  len_buf->appendChain(std::move(msg));
  return len_buf;
}

std::unique_ptr<IOBuf> RpcSerde::SerializeDelimited(const Message &msg) {
  // Get the buffer size needed for just the message.
  int msg_size = msg.ByteSize();
  int buf_size = CodedOutputStream::VarintSize32(msg_size) + msg_size;

  // Create a buffer big enough to hold the varint and the object.
  auto buf = IOBuf::create(buf_size);
  buf->append(buf_size);

  // Create the array output stream.
  ArrayOutputStream aos{buf->writableData(), static_cast<int>(buf->length())};
  // Wrap the ArrayOuputStream in the coded output stream to allow writing
  // Varint32
  CodedOutputStream cos{&aos};

  // Write out the size.
  cos.WriteVarint32(msg_size);

  // Now write the rest out.
  // We're using the protobuf output streams here to keep track
  // of where in the output array we are rather than IOBuf.
  msg.SerializeWithCachedSizesToArray(cos.GetDirectBufferForNBytesAndAdvance(msg_size));

  // Return the buffer.
  return buf;
}
// TODO(eclark): Make this 1 copy.
std::unique_ptr<IOBuf> RpcSerde::SerializeMessage(const Message &msg) {
  auto buf = IOBuf::copyBuffer(msg.SerializeAsString());
  return buf;
}
}  // namespace hbase

max_stars_repo_name: julia-emelyanova/hbase-native-client

max_issues_repo_name: julia-emelyanova/hbase-native-client

max_forks_repo_name: julia-emelyanova/hbase-native-client


text:
// C&C NLP tools
// Copyright (c) Universities of Edinburgh, Oxford and Sydney
// Copyright (c) James R. Curran
//
// This software is covered by a non-commercial use licence.
// See LICENCE.txt for the full text of the licence.
//
// If LICENCE.txt is not included in this distribution
// please email candc@it.usyd.edu.au to obtain a copy.

#include <mpi.h>

#include <cassert>
#include <cmath>
#include <string>
#include <vector>
#include <fstream>
#include <iostream>
#include <sstream>
#include <limits>
#include <valarray>

#include <sys/types.h>
#include <unistd.h>

#include <boost/filesystem.hpp>

#include <boost/iostreams/filtering_stream.hpp>
#include <boost/iostreams/filter/gzip.hpp>
#include <boost/iostreams/filter/bzip2.hpp>
#include <boost/iostreams/device/file.hpp>

#include "base.h"

#include "cluster.h"

#include "config/config.h"
#include "io/format.h"
#include "config/format.h"

#include "prob.h"

#include "model/model.h"
#include "model/types.h"

#include "io/reader.h"
#include "io/reader_factory.h"
#include "io/writer.h"

#include "tagger/tagdict.h"
#include "tagger/tagger.h"

#include "maxent/feature.h"
#include "maxent/attribute.h"
#include "maxent/context.h"
#include "maxent/gis.h"
#include "maxent/bfgs.h"
#include "maxent/perceptron.h"

#include "timer.h"

#include "tagger/tagsetdict.h"
#include "tagger/super.h"
#include "extract/super.h"

const char *PROGRAM_NAME = "mpi_train_super";

int rank = 1;
int size = 1;

namespace fs = boost::filesystem;
namespace io = boost::iostreams;

using namespace std;
using namespace NLP;

void
write(ulong cur_node, const string &line, ofstream &out){
  if(cur_node != 0)
    Cluster::send(line, cur_node, 0);
  else
    out << line;
}

int
main(int argc, char* argv[]){
  NLP::Cluster::init(argc, argv, true);

  std::ostringstream PREFACE;
  PREFACE << start_preface(argc, argv);

  Config::Main cfg(PROGRAM_NAME);

  Config::OpPath temp_dir("temp_dir", "where to store temporary files", "/tmp");

  Config::OpPath src(cfg, SPACE, "src", "source file to distribute");
  Config::OpPath dest(cfg, "dest", "destination filename (default relative to temp_dir", "", &temp_dir);

  cfg.reg(temp_dir, SPACE);

  Config::Op<bool> header(cfg, SPACE, "header", "source file has a header", false);

  Config::Op<bool> gzip(cfg, SPACE, "gzip", "source file is compressed with gzip", false);
  Config::Op<bool> bzip2(cfg, "bzip2", "source file is compressed with bzip2", false);

  Config::Op<ulong> dist_block_size(cfg, SPACE,  "dist_block_size", "the number of sentences to distribute in each step", 1);
  Config::Op<ulong> max_lines(cfg, "max_lines", "how many lines from the input file to use", 0);
  Config::Op<bool> ignore_blank(cfg, "ignore_blank", "ignore blank lines in the input file", true);

  cfg.parse(argc, argv);
  cfg.check();

  Timer timer("total");

  try {
    if(dist_block_size() < 1)
      throw NLP::Exception("dist_block_size must be at least 1");
    if(max_lines() < 0)
      throw NLP::Exception("max_lines must be 0 or more (0 means use the whole file)");
    fs::path src_path = src();
    fs::path dest_path;
    if(dest.value != "")
      dest_path = dest();
    else{
      dest_path = temp_dir();
      if(src_path.extension() == ".gz" || src_path.extension() == ".bz2")
        dest_path /= src_path.stem();
      else
        dest_path /= src_path.filename();
    }
    string dest_filename = dest_path.string() + '.' + Cluster::rank_str;

    ofstream out(dest_filename.c_str());
    if(!out)
      throw NLP::IOException("failed to open local out file for writing", dest_filename);

    cout << Cluster::rank_str + " writing " + dest_filename + '\n' << flush;

    string line;
    if(Cluster::rank == 0){
      io::filtering_istream in;

      if(gzip() || src_path.extension() == ".gz")
        in.push(io::gzip_decompressor());
      else if(bzip2() || src_path.extension() == ".bz2")
        in.push(io::bzip2_decompressor());

      in.push(io::file_source(src_path.string()));

      ulong cur_node = 0;
      bool in_header = header();
      ulong block_size = 0;
      ulong nline = 0;
      while(getline(in, line)){
        line += '\n';
        if(in_header){
          if(line[0] == '\n')
            in_header = false;
          for(ulong i = 0; i != Cluster::size; ++i)
            write(i, line, out);
          continue;
        }

        if(ignore_blank() && line[0] == '\n')
          continue;

        write(cur_node, line, out);
        block_size = (block_size + 1) % dist_block_size();
        if(block_size == 0)
          cur_node = (cur_node + 1) % Cluster::size;
        nline++;
        if(nline == max_lines())
          break;
      }
      for(cur_node = 1; cur_node != Cluster::size; ++cur_node)
        Cluster::send("", cur_node, 0);
    }else{
      while(true){
        Cluster::recv(line, 0, 0);
        if(line.size() == 0)
          break;
        out << line;
      }
    }
  }catch(NLP::IOException e){
    if(NLP::Cluster::rank == 0){
      cerr << "maxent.ioexception[" << NLP::Cluster::rank << "]:" << e.msg << endl;
      cerr << "  in location " << e.uri << ':' << e.line << endl;
    }
  }catch(NLP::Exception e){
    if(NLP::Cluster::rank == 0)
      cerr << "maxent.exception[" << NLP::Cluster::rank << "]: " << e.msg << endl;
  }

  NLP::Cluster::finalize();

  return 0;
}


text:
// Copyright Ricardo Calheiros de Miranda Cosme 2018.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE or copy at
//  http://www.boost.org/LICENSE_1_0.txt)

#pragma once

#include "coruja/support/signal/signal_id_t.hpp"

#include <boost/hof/is_invocable.hpp>

namespace coruja {

template<typename Observed,
         typename Derived_,
         template <class> class Signal>
class object_base
{
protected:

    using Derived = Derived_;

    Derived& as_derived() noexcept
    { return static_cast<Derived&>(*this); }

    const Derived& as_derived() const noexcept
    { return static_cast<const Derived&>(*this); }

    using after_change_t = Signal<void(Derived&)>;

    after_change_t _after_change;

public:

    using observed_t = Observed;
    using after_change_connection_t = typename after_change_t::connection_t;
    using signal_id_t = ::coruja::signal_id_t;

    template<typename F>
    enable_if_is_invocable_t<after_change_connection_t, F, Derived&>
    after_change(F&& f)
    { return _after_change.connect(std::forward<F>(f)); }

    template<typename F>
    enable_if_is_invocable_t<after_change_connection_t, F, const observed_t&>
    after_change(F&& f)
    { return _after_change.connect
            (detail::lift_to_observable(std::forward<F>(f))); }

    //Experimental
    template<typename F>
    enable_if_is_invocable_t<after_change_connection_t, F, Derived&>
    for_each(F&& f)
    {
        f(as_derived());
        return after_change(std::forward<F>(f));
    }

    //Experimental
    template<typename F>
    enable_if_is_invocable_t<after_change_connection_t, F, const observed_t&>
    for_each(F&& f)
    {
        detail::lift_to_observable_impl<F&>{f}(as_derived());
        return after_change(std::forward<F>(f));
    }

    //Experimental
    signal_id_t after_change_id() const noexcept
    { return _after_change.id(); }

    //Experimental
    signal_id_t for_each_id() const noexcept
    { return _after_change.id(); }
};

}

max_stars_repo_name: romariorios/coruja

max_issues_repo_name: romariorios/coruja

max_forks_repo_name: romariorios/coruja


text:
#include "fidstr/AprilTagFiducial.h"

#include "fidstr/AprilTagPhysicalLayer.h"
#include "fidstr/PhysicalLayer.h"
#include "fidstr/DataLinkLayer.h"

#include <iostream>

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

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

using namespace fidstr;

void CameraLoop() {

	AprilTagFiducialFamily family( APRILTAG_36H9 );

	AprilTagReceiver receiver( 15, family );
	FiducialPacketReceiver preceiver( family, receiver );

	cv::VideoCapture cap( 1 );
	cv::namedWindow( "capture" );

	unsigned int iter = 0;

	while( true ) {
		cv::Mat image;
		cap >> image;

		Time now = boost::posix_time::microsec_clock::universal_time();

		imshow( "capture", image );

// 		std::stringstream ss;
// 		ss << "capture_" << iter << ".jpg";

// 		imwrite( ss.str(), image );
// 		iter++;

 		receiver.Receive( image, now );
// 		preceiver.ProcessInputs();
//
// 		Payload pl = preceiver.DequeuePayload();
//
// 		if( !pl.empty() ) {
// 			std::cout << "Received payload of length " << pl.size() << std::endl;
// 		}
	}

}

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

	unsigned int messageLength = 128;
	if( argc >= 2 ) {
		messageLength = stoi( argv[1] );
	}

	// TODO Check that frame length, etc. fit in the fiducials!
	AprilTagFiducialFamily family( APRILTAG_36H9 );

	cv::startWindowThread();

// 	boost::thread cameraThread( boost::bind( &CameraLoop ) );

	FiducialTransmitter transmitter( "AprilTagTransmitter", 15 );
	transmitter.SetWindowCoordinates( 0, 0 );
	transmitter.SetFullscreen( true );

	usleep( 0.25*1E6 );

	FiducialPacketTransmitter ptransmitter( family, transmitter, messageLength );

	// Create a dummy packet
	Packet packet;
	for( char i = 0; i < messageLength; i++ ) {
		packet.push_back( i );
	}

	Time startTime = boost::posix_time::microsec_clock::universal_time();
	ptransmitter.TransmitPacket( packet );
	Time endTime = boost::posix_time::microsec_clock::universal_time();

	TimeDuration transmissionTime = endTime - startTime;

	std::cout << "Transmission took " << transmissionTime << " at " <<
		packet.size() / (transmissionTime.total_milliseconds() * 1E-3)
		<< " bytes/sec." << std::endl;

	usleep( 2*1E6 );

	exit(0);

}

max_stars_repo_name: Humhu/FiducialStream

max_issues_repo_name: Humhu/FiducialStream

max_forks_repo_name: Humhu/FiducialStream


text:
// Desctiption:
// This program's a framework of sync mode server to having some children sessions which are written in separated classes.
// At the bottom of thie file, you can see a sample code for using this program.
//
// Author : Masaru Shimizu
// E-Mail : shimizu@sist.chukyo-u.ac.jp
// Date   : 4.2015
//

#ifndef BSTSVRFRMWK_HH
#define BSTSVRFRMWK_HH

/*
 Realized points of this server framework.
 a. Server function
 b. Separated Server Framework and Child Session
 c. Realized the separation with template of C++
*/

#include <set>
#include <iostream>
#include <boost/asio.hpp>
#include <boost/bind.hpp>
#include <boost/thread.hpp>

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

//////////////////////////////////////////////////////////////////
// Server_Framework
template <typename Child_Session> class Server_Framework
{
  //////////////////////////////////////////////////////////////////
  // Server_Framework.Variables
private:
public:
  gazebo::physics::WorldPtr       _world;
  boost::asio::io_service         _ioservice;
  boost::asio::ip::tcp::acceptor  _acceptor;
  std::set<Child_Session*>        _Child_Session_list;
  Child_Session                  *_new_Child_Sessionp;
  boost::thread                   _thread;

  //////////////////////////////////////////////////////////////////
  // Server_Framework.Make_A_Child_Session_and_Accept_Loop
  void Make_A_Child_Session_and_Accept_Loop(void)
  {
    while(1)
    {
      _new_Child_Sessionp = new Child_Session(*this);
      _Child_Session_list.insert(_new_Child_Sessionp);
//std::cout << "Made a child session [" << _new_Child_Sessionp<<"]"<<std::endl;
      boost::system::error_code err;
      _acceptor.accept(_new_Child_Sessionp->_socket, err);
//std::cout << "After accept\n";
      _new_Child_Sessionp->_thread = boost::thread(
                             boost::bind(&Child_Session::Accept_Process
                                         , _new_Child_Sessionp));
//std::cout << "After thread\n";
    }
  }

  //////////////////////////////////////////////////////////////////
  // Server_Framework.Remove_Child_Session
  void Remove_Child_Session(Child_Session *Child_Sessionp)
  {
    delete Child_Sessionp;
    _Child_Session_list.erase(Child_Sessionp);
  }

  //////////////////////////////////////////////////////////////////
  // Server_Framework.Constractor
  Server_Framework(unsigned short port
	                 , gazebo::physics::WorldPtr world) try
    :_acceptor(_ioservice
        , boost::asio::ip::tcp::endpoint(boost::asio::ip::tcp::v4(), port))
    , _new_Child_Sessionp(NULL)
  {
		_world = world;
    _thread = boost::thread(
        boost::bind(&Server_Framework::Make_A_Child_Session_and_Accept_Loop
                          , this));
  }
  catch(std::exception const &err)
  {
    std::cerr << err.what() << std::endl;
  }

  //////////////////////////////////////////////////////////////////
  // Server_Framework.Destractor
  ~Server_Framework()
  {
    _thread.join();
    for(typename std::set<Child_Session*>::iterator
      i = _Child_Session_list.begin(); i != _Child_Session_list.end(); i++)
        delete *i;
  }
};

#ifdef __SAMPLE_MAIN__

/*
# How to compile this sample code.
gcc -o a boost_server.cc -D__SAMPLE_MAIN__ -lboost_system-mt -lboost_thread-mt

# Realized points of this server framework.
 a. Server function
 b. Separated Server Framework and Child Session
 c. Realized the separation with template of C++
*/

//////////////////////////////////////////////////////////////////
// Sample_Child_Session :
//   COPY THIS CLASS and MODIFY to create your own child_session
struct Sample_Child_Session
{
  //////////////////////////////////////////////////////////////////
  // Sample_Child_Session.Variables
  Server_Framework<Sample_Child_Session> &_parent;
  boost::asio::io_service       _ioservice;
  boost::asio::ip::tcp::socket  _socket;
  boost::asio::streambuf        _buffer;
  boost::thread                 _thread;
  // Add your own variables here

  //////////////////////////////////////////////////////////////////
  // Sample_Child_Session.Constructor
  Sample_Child_Session(Server_Framework<Sample_Child_Session>&parent)
                              : _parent(parent), _socket(_ioservice) {}
      // CAUTION:_socket needs local member _ioservice to be initialized,
      //          not by parent._ioservice.
      // _parent is for using _parent.Remove_Child_Session()

  //////////////////////////////////////////////////////////////////
  // Sample_Child_Session.Child_Session_Loop_Core
  void Child_Session_Loop_Core(void)
  {
    boost::system::error_code err;
//std::cout << "Child_Session_Loop a [" << this << "]" << std::endl;
    boost::asio::read_until(_socket, _buffer , "\r\n", err);
//std::cout << "Child_Session_Loop b [" << this << "]" << std::endl;
// SAMPLE CODE : Sendback received data for debug
    std::istream is(&_buffer);
    std::string  line;
		for(;1;)
		{
      std::getline(is, line);
			if(0 < line.length())
			{

// THIS IS WRONG =>         boost::asio::write(_socket, line);
// SAMPLE CODE : Display received data for debug
//       std::cout << line.c_str() << std::endl;
			}
			else
			  break;
		}
//    boost::asio::write(_socket, _buffer);

//
//std::cout << "Child_Session_Loop c [" << this << "]" << std::endl;
//std::cout << "Child_Session_Loop d [" << this << "]" << std::endl;
  }

  //////////////////////////////////////////////////////////////////
  // Sample_Child_Session.Accept_Process
  void Accept_Process(void)
  {
//std::cout << "Accept_Process a [" << this << "]" << std::endl;
/* SAMPLE CODE : Sendback Accepted Acknowledgment for debug
    boost::asio::streambuf  ack_comment;
    std::iostream st(&ack_comment);
    st << "+ -- Accepted ["  << this << "]" << std::endl;;
    boost::asio::write(_socket, ack_comment);
*/
//std::cout << "Accept_Process b [" << this << "]" << std::endl;
    while(1)
      Child_Session_Loop_Core();
//std::cout << "Accept_Process c [" << this << "]" << std::endl;
  }
  // Add your own functions here
};

int main(void)
{
  Server_Framework<Sample_Child_Session> sf(3000);
  while(1)
    sleep(10);
  return 0;
}
#endif

#endif

ext: hh

max_stars_repo_name: nicedone/RoboCupRescuePackage

max_issues_repo_name: nicedone/RoboCupRescuePackage

max_forks_repo_name: nicedone/RoboCupRescuePackage