text:
/*********************************************************************/
/* Copyright (c) 2017-2018, EPFL/Blue Brain Project                  */
/*                          Raphael Dumusc <raphael.dumusc@epfl.ch>  */
/* All rights reserved.                                              */
/*                                                                   */
/* Redistribution and use in source and binary forms, with or        */
/* without modification, are permitted provided that the following   */
/* conditions are met:                                               */
/*                                                                   */
/*   1. Redistributions of source code must retain the above         */
/*      copyright notice, this list of conditions and the following  */
/*      disclaimer.                                                  */
/*                                                                   */
/*   2. Redistributions in binary form must reproduce the above      */
/*      copyright notice, this list of conditions and the following  */
/*      disclaimer in the documentation and/or other materials       */
/*      provided with the distribution.                              */
/*                                                                   */
/*    THIS  SOFTWARE  IS  PROVIDED  BY  THE  ECOLE  POLYTECHNIQUE    */
/*    FEDERALE DE LAUSANNE  ''AS IS''  AND ANY EXPRESS OR IMPLIED    */
/*    WARRANTIES, INCLUDING, BUT  NOT  LIMITED  TO,  THE  IMPLIED    */
/*    WARRANTIES OF MERCHANTABILITY AND FITNESS FOR  A PARTICULAR    */
/*    PURPOSE  ARE  DISCLAIMED.  IN  NO  EVENT  SHALL  THE  ECOLE    */
/*    POLYTECHNIQUE  FEDERALE  DE  LAUSANNE  OR  CONTRIBUTORS  BE    */
/*    LIABLE  FOR  ANY  DIRECT,  INDIRECT,  INCIDENTAL,  SPECIAL,    */
/*    EXEMPLARY,  OR  CONSEQUENTIAL  DAMAGES  (INCLUDING, BUT NOT    */
/*    LIMITED TO,  PROCUREMENT  OF  SUBSTITUTE GOODS OR SERVICES;    */
/*    LOSS OF USE, DATA, OR  PROFITS;  OR  BUSINESS INTERRUPTION)    */
/*    HOWEVER CAUSED AND  ON ANY THEORY OF LIABILITY,  WHETHER IN    */
/*    CONTRACT, STRICT LIABILITY,  OR TORT  (INCLUDING NEGLIGENCE    */
/*    OR OTHERWISE) ARISING  IN ANY WAY  OUT OF  THE USE OF  THIS    */
/*    SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.   */
/*                                                                   */
/* The views and conclusions contained in the software and           */
/* documentation are those of the authors and should not be          */
/* interpreted as representing official policies, either expressed   */
/* or implied, of Ecole polytechnique federale de Lausanne.          */
/*********************************************************************/

#define BOOST_TEST_MODULE DisplayGroupControllerTests
#include <boost/test/unit_test.hpp>

#include "control/DisplayGroupController.h"
#include "scene/DisplayGroup.h"
#include "scene/Window.h"

#include "DummyContent.h"

namespace
{
const QSizeF WALL_SIZE(2000, 1000);
const QSize CONTENT_SIZE(800, 600);
const qreal CONTENT_AR = qreal(CONTENT_SIZE.width()) / CONTENT_SIZE.height();

ContentPtr makeDummyContent()
{
    return std::make_unique<DummyContent>(CONTENT_SIZE);
}
}

struct Fixture
{
    Fixture() { displayGroup->add(window); }
    WindowPtr window{std::make_shared<Window>(makeDummyContent())};
    Content& content{window->getContent()};
    DisplayGroupPtr displayGroup{DisplayGroup::create(WALL_SIZE)};
    DisplayGroupController controller{*displayGroup};
};

BOOST_FIXTURE_TEST_CASE(testShowWindowFullscreenAndExit, Fixture)
{
    BOOST_REQUIRE_EQUAL(content.getZoomRect(), UNIT_RECTF);
    BOOST_REQUIRE(!window->isFullscreen());
    BOOST_REQUIRE_EQUAL(window->size(), CONTENT_SIZE);

    window->setX(100);
    window->setY(150);
    window->setWidth(CONTENT_SIZE.width() / 2);
    window->setHeight(CONTENT_SIZE.height() / 4);
    content.setZoomRect(QRectF(0.2, 0.2, 0.7, 0.7));

    controller.showFullscreen(window->getID());

    BOOST_CHECK(window->isFullscreen());
    BOOST_CHECK_EQUAL(displayGroup->getFullscreenWindow(), window.get());
    const auto& coord = window->getDisplayCoordinates();
    BOOST_CHECK_EQUAL(coord.x(), (WALL_SIZE.width() - coord.width()) / 2);
    BOOST_CHECK_EQUAL(coord.y(), 0);
    BOOST_CHECK_EQUAL(coord.height(), WALL_SIZE.height());
    BOOST_CHECK_EQUAL(coord.width(), coord.height() * CONTENT_AR);
    BOOST_CHECK_EQUAL(content.getZoomRect(), UNIT_RECTF);

    controller.exitFullscreen();

    BOOST_CHECK(!window->isFullscreen());
    BOOST_CHECK_EQUAL(content.getZoomRect(), QRectF(0.2, 0.2, 0.7, 0.7));
    BOOST_CHECK_EQUAL(window->x(), 100);
    BOOST_CHECK_EQUAL(window->y(), 150);
    BOOST_CHECK_EQUAL(window->width(), CONTENT_SIZE.width() / 2);
    BOOST_CHECK_EQUAL(window->height(), CONTENT_SIZE.height() / 4);
}

BOOST_FIXTURE_TEST_CASE(testAdjustSizeOneToOne, Fixture)
{
    window->setWidth(CONTENT_SIZE.width() / 2);
    window->setHeight(CONTENT_SIZE.height() / 4);
    content.setZoomRect(QRectF(0.2, 0.2, 0.7, 0.7));

    const auto center = window->getDisplayCoordinates().center();

    controller.adjustSizeOneToOne(window->getID());

    BOOST_CHECK(!window->isFullscreen());
    const auto& coord = window->getDisplayCoordinates();
    BOOST_CHECK_EQUAL(coord.center().x(), center.x());
    BOOST_CHECK_EQUAL(coord.center().y(), center.y());
    BOOST_CHECK_EQUAL(coord.width(), CONTENT_SIZE.width());
    BOOST_CHECK_EQUAL(coord.height(), CONTENT_SIZE.height());
    BOOST_CHECK_EQUAL(content.getZoomRect(), UNIT_RECTF);
}

BOOST_FIXTURE_TEST_CASE(testAdjustSizeOneToOneHugeContent, Fixture)
{
    const auto hugeSize = WALL_SIZE * 2;
    content.setDimensions(hugeSize.toSize());

    BOOST_REQUIRE_EQUAL(content.getZoomRect(), UNIT_RECTF);
    BOOST_REQUIRE(!window->isFullscreen());
    BOOST_REQUIRE_EQUAL(window->size(), CONTENT_SIZE);

    window->setX(100);
    window->setY(150);
    window->setWidth(320);
    window->setHeight(460);
    content.setZoomRect(QRectF(0.2, 0.2, 0.7, 0.7));

    controller.adjustSizeOneToOne(window->getID());

    BOOST_CHECK(window->isFullscreen());
    BOOST_CHECK_EQUAL(displayGroup->getFullscreenWindow(), window.get());
    const auto& coord = window->getDisplayCoordinates();
    BOOST_CHECK_EQUAL(coord.center().x(), WALL_SIZE.width() / 2);
    BOOST_CHECK_EQUAL(coord.center().y(), WALL_SIZE.height() / 2);
    BOOST_CHECK_EQUAL(coord.width(), hugeSize.width());
    BOOST_CHECK_EQUAL(coord.height(), hugeSize.height());
    BOOST_CHECK_EQUAL(content.getZoomRect(), UNIT_RECTF);

    controller.exitFullscreen();

    BOOST_CHECK(!window->isFullscreen());
    BOOST_CHECK_EQUAL(content.getZoomRect(), QRectF(0.2, 0.2, 0.7, 0.7));
    BOOST_CHECK_EQUAL(window->x(), 100);
    BOOST_CHECK_EQUAL(window->y(), 150);
    BOOST_CHECK_EQUAL(window->width(), 320);
    BOOST_CHECK_EQUAL(window->height(), 460);
}

max_stars_repo_name: BlueBrain/Tide

max_issues_repo_name: BlueBrain/Tide

max_forks_repo_name: BlueBrain/Tide


text:
#include <Eigen/Dense>
#include <Eigen/Sparse>
#include <iostream>
#include <mimkl/definitions.hpp>
#include <mimkl/kernels.hpp>
#include <mimkl/linear_algebra.hpp>
#include <stdexcept>

int main(int argc, char **argv)
{
    try
    {

        auto console = spdlog::stdout_color_mt("console");

        Eigen::Matrix<double, 2, 3> X;
        Eigen::SparseMatrix<double> L(3, 3);
        double a = 0.01;
        double b = 0.01;
        Eigen::Matrix<double, 2, 2> K_reference;

        X << 1., 2., 3., 4., 5., 6.;
        mimkl::linear_algebra::fill_sparse_diagonal(L, 1.0);

        K_reference << std::tanh(0.15), std::tanh(0.33), std::tanh(0.33),
        std::tanh(.78);
        Eigen::Matrix<double, 2, 2> K =
        mimkl::induction::induce_sigmoidal_kernel<MATRIX(double)>(X, X, L, a, b);

        assert(((K - K_reference).norm() < 0.0000000001) && "Identity Inducer");

        Eigen::SparseMatrix<double> L1(3, 3);
        typedef Eigen::Triplet<double> TripletDouble; // (row,col,coef)
        std::vector<TripletDouble> triplet_list;
        triplet_list.reserve(4);
        triplet_list.push_back(TripletDouble(0, 1, 1.));
        triplet_list.push_back(TripletDouble(1, 2, 1.));
        triplet_list.push_back(TripletDouble(1, 0, 1.));
        triplet_list.push_back(TripletDouble(2, 1, 1.));
        L1.setFromTriplets(triplet_list.begin(), triplet_list.end());

        K_reference << std::tanh(0.17), std::tanh(0.41), std::tanh(0.41),
        std::tanh(1.01);
        ;

        K = mimkl::induction::induce_sigmoidal_kernel<MATRIX(double)>(X, X, L1,
                                                                      a, b);

        std::cout << K << std::endl;
        std::cout << K_reference << std::endl;
        std::cout << (K - K_reference).norm() << std::endl;
        assert(((K - K_reference).norm() < 0.0000000001) &&
               "unweighted Graph Inducer");

        MATRIX(double) random_mat1 = MATRIX(double)::Random(2, 3);
        MATRIX(double) random_mat2 = MATRIX(double)::Random(4, 3);
        MATRIX(double) random_kernel;

        random_kernel =
        mimkl::induction::induce_sigmoidal_kernel<MATRIX(double)>(random_mat1,
                                                                  random_mat2,
                                                                  L1, a, b);
        console->info(" a random sigmoidal kernel\n{}", random_kernel);

        return EXIT_SUCCESS;
    }
    catch (const std::exception &e)
    {
        std::cerr << e.what();
        return EXIT_FAILURE;
    }
}

ext: cpp

max_stars_repo_name: vishalbelsare/mimkl

max_issues_repo_name: vishalbelsare/mimkl

max_forks_repo_name: vishalbelsare/mimkl


text:
#include "channel_encryption.hpp"
#include "http_connection.h"
#include "lokid_key.h"
#include "rate_limiter.h"
#include "service_node.h"
#include "swarm.h"
#include "version.h"

#include <boost/log/core.hpp>
#include <boost/log/expressions.hpp>
#include <boost/log/trivial.hpp>
#include <boost/log/utility/setup/file.hpp>
#include <boost/program_options.hpp>

#include <cstdlib>
#include <iomanip>
#include <iostream>
#include <sstream>
#include <thread>
#include <utility> // for std::pair
#include <vector>

using namespace service_node;
namespace po = boost::program_options;
namespace logging = boost::log;

using LogLevelPair = std::pair<std::string, logging::trivial::severity_level>;
using LogLevelMap = std::vector<LogLevelPair>;
static const LogLevelMap logLevelMap{
    {"trace", logging::trivial::severity_level::trace},
    {"debug", logging::trivial::severity_level::debug},
    {"info", logging::trivial::severity_level::info},
    {"warning", logging::trivial::severity_level::warning},
    {"error", logging::trivial::severity_level::error},
    {"fatal", logging::trivial::severity_level::fatal},
};

void usage(char* argv[]) {
    std::cerr << "Usage: " << argv[0]
              << " <address> <port> --lokid-key path [--db-location "
                 "path] [--log-level level] [--output-log path] [--version]\n";
    std::cerr << "  For IPv4, try:\n";
    std::cerr << "    receiver 0.0.0.0 80\n";
    std::cerr << "  For IPv6, try:\n";
    std::cerr << "    receiver 0::0 80\n";
    std::cerr << "  Log levels:\n";
    for (const auto& logLevel : logLevelMap) {
        std::cerr << "    " << logLevel.first << "\n";
    }
}

bool parseLogLevel(const std::string& input,
                   logging::trivial::severity_level& logLevel) {

    const auto it = std::find_if(
        logLevelMap.begin(), logLevelMap.end(),
        [&](const LogLevelPair& pair) { return pair.first == input; });
    if (it != logLevelMap.end()) {
        logLevel = it->second;
        return true;
    }
    return false;
}

int main(int argc, char* argv[]) {
    try {
        // Check command line arguments.
        if (argc < 2) {
            usage(argv);
            return EXIT_FAILURE;
        }

        std::string lokid_key_path;
        std::string db_location(".");
        std::string log_location;
        std::string log_level_string("info");
        bool print_version = false;
        uint16_t lokid_rpc_port = 22023;

        po::options_description desc;
        desc.add_options()("lokid-key", po::value(&lokid_key_path),
                           "")("db-location", po::value(&db_location),
                               "")("output-log", po::value(&log_location), "")(
            "log-level", po::value(&log_level_string),
            "")("version,v", po::bool_switch(&print_version),
                "")("lokid-rpc-port", po::value(&lokid_rpc_port));

        po::variables_map vm;
        po::store(po::parse_command_line(argc, argv, desc), vm);
        po::notify(vm);

        std::cout << "Loki Storage Server v" << STORAGE_SERVER_VERSION_STRING
                  << std::endl
                  << " git commit hash: " << STORAGE_SERVER_GIT_HASH_STRING
                  << std::endl
                  << " build time: " << STORAGE_SERVER_BUILD_TIME << std::endl;

        if (print_version) {
            return EXIT_SUCCESS;
        }

        if (argc < 3) {
            usage(argv);
            return EXIT_FAILURE;
        }

        const auto port = static_cast<uint16_t>(std::atoi(argv[2]));
        std::string ip = argv[1];

        if (vm.count("output-log")) {

            // TODO: remove this line once confirmed that no one
            // is relying on this
            log_location += ".out";

            // Hacky, but I couldn't find a way to recover from
            // boost throwing on invalid file and apparently poisoning
            // the logging mechanism...
            std::ofstream input(log_location);

            if (input.is_open()) {
                input.close();
                auto sink = logging::add_file_log(log_location);
                sink->locked_backend()->auto_flush(true);
                BOOST_LOG_TRIVIAL(info)
                    << "Outputting logs to " << log_location;
            } else {
                BOOST_LOG_TRIVIAL(error) << "Could not open " << log_location;
            }
        }

        logging::trivial::severity_level logLevel;
        if (!parseLogLevel(log_level_string, logLevel)) {
            BOOST_LOG_TRIVIAL(error)
                << "Incorrect log level" << log_level_string;
            usage(argv);
            return EXIT_FAILURE;
        }

        // TODO: consider adding auto-flushing for logging
        logging::core::get()->set_filter(logging::trivial::severity >=
                                         logLevel);
        BOOST_LOG_TRIVIAL(info) << "Setting log level to " << log_level_string;

        if (vm.count("lokid-key")) {
            BOOST_LOG_TRIVIAL(info)
                << "Setting Lokid key path to " << lokid_key_path;
        }

        if (vm.count("db-location")) {
            BOOST_LOG_TRIVIAL(info)
                << "Setting database location to " << db_location;
        }

        if (vm.count("lokid-rpc-port")) {
            BOOST_LOG_TRIVIAL(info)
                << "Setting lokid RPC port to " << lokid_rpc_port;
        }

        BOOST_LOG_TRIVIAL(info)
            << "Listening at address " << ip << " port " << port << std::endl;

        boost::asio::io_context ioc{1};

        // ed25519 key
        const auto private_key = loki::parseLokidKey(lokid_key_path);
        const auto public_key = loki::calcPublicKey(private_key);

        // TODO: avoid conversion to vector
        const std::vector<uint8_t> priv(private_key.begin(), private_key.end());
        ChannelEncryption<std::string> channel_encryption(priv);

        loki::lokid_key_pair_t lokid_key_pair{private_key, public_key};
        loki::ServiceNode service_node(ioc, port, lokid_key_pair, db_location,
                                       lokid_rpc_port);
        RateLimiter rate_limiter;

        /// Should run http server
        loki::http_server::run(ioc, ip, port, service_node, channel_encryption,
                               rate_limiter);

    } catch (const std::exception& e) {
        // It seems possible for logging to throw its own exception,
        // in which case it will be propagated to libc...
        BOOST_LOG_TRIVIAL(fatal) << "Exception caught in main: " << e.what();
        return EXIT_FAILURE;
    } catch (...) {
        BOOST_LOG_TRIVIAL(fatal) << "Unknown exception caught in main.";
        return EXIT_FAILURE;
    }
}

max_stars_repo_name: sachaaaaa/loki-storage-server-old

max_issues_repo_name: sachaaaaa/loki-storage-server-old

max_forks_repo_name: sachaaaaa/loki-storage-server-old


text: #include <boost/spirit/home/support/utree/operators.hpp>

ext: hpp

max_stars_repo_name: miathedev/BoostForArduino

max_issues_repo_name: miathedev/BoostForArduino

max_forks_repo_name: miathedev/BoostForArduino


text:
//
// Copyright (c) 2019 Vinnie Falco (vinnie.falco@gmail.com)
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//
// Official repository: https://github.com/boostorg/json
//

#ifndef BOOST_JSON_IMPL_OBJECT_HPP
#define BOOST_JSON_IMPL_OBJECT_HPP

#include <boost/json/value.hpp>
#include <iterator>
#include <cmath>
#include <type_traits>
#include <utility>

BOOST_JSON_NS_BEGIN

namespace detail {

// Objects with size less than or equal
// to this number will use a linear search
// instead of the more expensive hash function.
static
constexpr
std::size_t
small_object_size_ = 18;

BOOST_STATIC_ASSERT(
    small_object_size_ <
    BOOST_JSON_MAX_STRUCTURED_SIZE);

} // detail

//----------------------------------------------------------

struct alignas(key_value_pair)
    object::table
{
    std::uint32_t size = 0;
    std::uint32_t capacity = 0;
    std::uintptr_t salt = 0;

#if defined(_MSC_VER) && BOOST_JSON_ARCH == 32
    // VFALCO If we make key_value_pair smaller,
    //        then we might want to revisit this
    //        padding.
    BOOST_STATIC_ASSERT(
        sizeof(key_value_pair) == 32);
    char pad[4] = {}; // silence warnings
#endif

    constexpr table();

    // returns true if we use a linear
    // search instead of the hash table.
    bool is_small() const noexcept
    {
        return capacity <=
            detail::small_object_size_;
    }

    key_value_pair&
    operator[](
        std::size_t pos) noexcept
    {
        return reinterpret_cast<
            key_value_pair*>(
                this + 1)[pos];
    }

    // VFALCO This is exported for tests
    BOOST_JSON_DECL
    std::size_t
    digest(string_view key) const noexcept;

    inline
    index_t&
    bucket(std::size_t hash) noexcept;

    inline
    index_t&
    bucket(string_view key) noexcept;

    inline
    void
    clear() noexcept;

    static
    inline
    table*
    allocate(
        std::size_t capacity,
        std::uintptr_t salt,
        storage_ptr const& sp);

    static
    void
    deallocate(
        table* p,
        storage_ptr const& sp) noexcept
    {
        if(p->capacity == 0)
            return;
        if(! p->is_small())
            sp->deallocate(p,
                sizeof(table) + p->capacity * (
                    sizeof(key_value_pair) +
                    sizeof(index_t)));
        else
            sp->deallocate(p,
                sizeof(table) + p->capacity *
                    sizeof(key_value_pair));
    }
};

//----------------------------------------------------------

class object::revert_construct
{
    object* obj_;

    BOOST_JSON_DECL
    void
    destroy() noexcept;

public:
    explicit
    revert_construct(
        object& obj) noexcept
        : obj_(&obj)
    {
    }

    ~revert_construct()
    {
        if(! obj_)
            return;
        destroy();
    }

    void
    commit() noexcept
    {
        obj_ = nullptr;
    }
};

//----------------------------------------------------------

class object::revert_insert
{
    object* obj_;
    std::size_t size_;

    BOOST_JSON_DECL
    void
    destroy() noexcept;

public:
    explicit
    revert_insert(
        object& obj) noexcept
        : obj_(&obj)
        , size_(obj_->size())
    {
    }

    ~revert_insert()
    {
        if(! obj_)
            return;
        destroy();
        obj_->t_->size = static_cast<
            index_t>(size_);
    }

    void
    commit() noexcept
    {
        obj_ = nullptr;
    }
};

//----------------------------------------------------------
//
// Iterators
//
//----------------------------------------------------------

auto
object::
begin() noexcept ->
    iterator
{
    return &(*t_)[0];
}

auto
object::
begin() const noexcept ->
    const_iterator
{
    return &(*t_)[0];
}

auto
object::
cbegin() const noexcept ->
    const_iterator
{
    return &(*t_)[0];
}

auto
object::
end() noexcept ->
    iterator
{
    return &(*t_)[t_->size];
}

auto
object::
end() const noexcept ->
    const_iterator
{
    return &(*t_)[t_->size];
}

auto
object::
cend() const noexcept ->
    const_iterator
{
    return &(*t_)[t_->size];
}

auto
object::
rbegin() noexcept ->
    reverse_iterator
{
    return reverse_iterator(end());
}

auto
object::
rbegin() const noexcept ->
    const_reverse_iterator
{
    return const_reverse_iterator(end());
}

auto
object::
crbegin() const noexcept ->
    const_reverse_iterator
{
    return const_reverse_iterator(end());
}

auto
object::
rend() noexcept ->
    reverse_iterator
{
    return reverse_iterator(begin());
}

auto
object::
rend() const noexcept ->
    const_reverse_iterator
{
    return const_reverse_iterator(begin());
}

auto
object::
crend() const noexcept ->
    const_reverse_iterator
{
    return const_reverse_iterator(begin());
}

//----------------------------------------------------------
//
// Capacity
//
//----------------------------------------------------------

bool
object::
empty() const noexcept
{
    return t_->size == 0;
}

auto
object::
size() const noexcept ->
    std::size_t
{
    return t_->size;
}

constexpr
std::size_t
object::
max_size() noexcept
{
    // max_size depends on the address model
    using min = std::integral_constant<std::size_t,
        (std::size_t(-1) - sizeof(table)) /
            (sizeof(key_value_pair) + sizeof(index_t))>;
    return min::value < BOOST_JSON_MAX_STRUCTURED_SIZE ?
        min::value : BOOST_JSON_MAX_STRUCTURED_SIZE;
}

auto
object::
capacity() const noexcept ->
    std::size_t
{
    return t_->capacity;
}

//----------------------------------------------------------
//
// Lookup
//
//----------------------------------------------------------

auto
object::
at(string_view key) ->
    value&
{
    auto it = find(key);
    if(it == end())
        detail::throw_out_of_range(
            BOOST_JSON_SOURCE_POS);
    return it->value();
}

auto
object::
at(string_view key) const ->
    value const&
{
    auto it = find(key);
    if(it == end())
        detail::throw_out_of_range(
            BOOST_JSON_SOURCE_POS);
    return it->value();
}

//----------------------------------------------------------

template<class P, class>
auto
object::
insert(P&& p) ->
    std::pair<iterator, bool>
{
    key_value_pair v(
        std::forward<P>(p), sp_);
    return insert_impl(pilfer(v));
}

template<class M>
auto
object::
insert_or_assign(
    string_view key, M&& m) ->
        std::pair<iterator, bool>
{
    reserve(size() + 1);
    auto const result = find_impl(key);
    if(result.first)
    {
        value(std::forward<M>(m),
            sp_).swap(result.first->value());
        return { result.first, false };
    }
    key_value_pair kv(key,
        std::forward<M>(m), sp_);
    return { insert_impl(pilfer(kv),
        result.second), true };
}

template<class Arg>
auto
object::
emplace(
    string_view key,
    Arg&& arg) ->
        std::pair<iterator, bool>
{
    reserve(size() + 1);
    auto const result = find_impl(key);
    if(result.first)
        return { result.first, false };
    key_value_pair kv(key,
        std::forward<Arg>(arg), sp_);
    return { insert_impl(pilfer(kv),
        result.second), true };
}

//----------------------------------------------------------
//
// (private)
//
//----------------------------------------------------------

template<class InputIt>
void
object::
construct(
    InputIt first,
    InputIt last,
    std::size_t min_capacity,
    std::input_iterator_tag)
{
    reserve(min_capacity);
    revert_construct r(*this);
    while(first != last)
    {
        insert(*first);
        ++first;
    }
    r.commit();
}

template<class InputIt>
void
object::
construct(
    InputIt first,
    InputIt last,
    std::size_t min_capacity,
    std::forward_iterator_tag)
{
    auto n = static_cast<
        std::size_t>(std::distance(
            first, last));
    if( n < min_capacity)
        n = min_capacity;
    reserve(n);
    revert_construct r(*this);
    while(first != last)
    {
        insert(*first);
        ++first;
    }
    r.commit();
}

template<class InputIt>
void
object::
insert(
    InputIt first,
    InputIt last,
    std::input_iterator_tag)
{
    // Since input iterators cannot be rewound,
    // we keep inserted elements on an exception.
    //
    while(first != last)
    {
        insert(*first);
        ++first;
    }
}

template<class InputIt>
void
object::
insert(
    InputIt first,
    InputIt last,
    std::forward_iterator_tag)
{
    auto const n =
        static_cast<std::size_t>(
            std::distance(first, last));
    auto const n0 = size();
    if(n > max_size() - n0)
        detail::throw_length_error(
            "object too large",
            BOOST_JSON_SOURCE_POS);
    reserve(n0 + n);
    revert_insert r(*this);
    while(first != last)
    {
        insert(*first);
        ++first;
    }
    r.commit();
}

//----------------------------------------------------------

namespace detail {

unchecked_object::
~unchecked_object()
{
    if(! data_)
        return;
    if(sp_.is_not_shared_and_deallocate_is_trivial())
        return;
    value* p = data_;
    while(size_--)
    {
        p[0].~value();
        p[1].~value();
        p += 2;
    }
}

} // detail

BOOST_JSON_NS_END

#endif

max_stars_repo_name: bazelboost/json

max_issues_repo_name: RangoW/json

max_forks_repo_name: RangoW/json


text:
//
//  Copyright (c) 2015 Terry Seyler
//
//  Distributed under the MIT License
//  See accompanying file LICENSE.md
//

#include <iostream>
#include <sstream>
#include <boost/lexical_cast.hpp>
#include <core/protocol/http/http_constants.hpp>
#include <core/protocol/http/http_message.hpp>

namespace proto_net
{
    namespace protocol
    {
        namespace http
        {
            http_message::http_message() : http_version_("HTTP/1.1"),
                                           headers_(),
                                           message_body_()
            { }

            void
            http_message::clone(const http_message &copy)
            {
                http_version_ = copy.http_version();
                headers_ = copy.headers(); // using http_headers assignment operator
                message_body_ = copy.body();
            }

            std::string
            http_message::http_version(void) const
            {
                return http_version_;
            }

            void
            http_message::http_version(const std::string& version)
            {
                http_version_ = version;
            }

            http_headers
            http_message::headers(void) const
            {
                return headers_;
            }

            http_headers &
            http_message::get_headers(void)
            {
                return headers_;
            }

            std::string
            http_message::header_to_string(void) const
            {
                std::stringstream ss;

                ss << headers_.to_string();
                ss << crlf; // end of header

                return ss.str();
            }

            std::string
            http_message::to_string(void) const
            {
                std::stringstream ss;
                ss << header_to_string() << message_body_.to_string();

                return ss.str();
            }

            proto_net_string_data
            http_message::body(void) const
            {
                return message_body_;
            }

            void
            http_message::body(const proto_net_string_data& data)
            {
                message_body_ = data;
            }

            proto_net_string_data
            http_message::to_net_data(void) const
            {
                std::string header = header_to_string();
                proto_net_string_data header_data(header);

                return header_data + message_body_;
            }

            size_t
            http_message::content_length(void)
            {
                size_t ct(0);

                http_header_fields entity_fields = headers_[http_headers::entity_category];
                std::string content_length;
                if (entity_fields.get_header_field("Content-Length", content_length))
                    ct = boost::lexical_cast<size_t>(content_length);

                return ct;
            }
        }
    }
}

max_stars_repo_name: tseyler/proto-server

max_issues_repo_name: tseyler/proto-server

max_forks_repo_name: tseyler/proto-server


text:
//
// Copyright 2018 Pixar
//
// Licensed under the Apache License, Version 2.0 (the "Apache License")
// with the following modification; you may not use this file except in
// compliance with the Apache License and the following modification to it:
// Section 6. Trademarks. is deleted and replaced with:
//
// 6. Trademarks. This License does not grant permission to use the trade
//    names, trademarks, service marks, or product names of the Licensor
//    and its affiliates, except as required to comply with Section 4(c) of
//    the License and to reproduce the content of the NOTICE file.
//
// You may obtain a copy of the Apache License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the Apache License with the above modification is
// distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the Apache License for the specific
// language governing permissions and limitations under the Apache License.
//

#include "pxr/pxr.h"
#include "usdMaya/diagnosticDelegate.h"

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

using namespace boost::python;

PXR_NAMESPACE_USING_DIRECTIVE;

namespace {

// This exposes UsdMayaDiagnosticBatchContext as a Python "context manager"
// object that can be used with the "with"-statement.
class _PyDiagnosticBatchContext {
public:
    void __enter__() {
        _context.reset(new UsdMayaDiagnosticBatchContext());
    }
    void __exit__(object, object, object) {
        _context.reset();
    }

private:
    std::unique_ptr<UsdMayaDiagnosticBatchContext> _context;
};

} // anonymous namespace

void wrapDiagnosticDelegate()
{
    typedef UsdMayaDiagnosticDelegate This;
    class_<This, boost::noncopyable>("DiagnosticDelegate", no_init)
        .def("GetBatchCount", &This::GetBatchCount)
        .staticmethod("GetBatchCount")
        ;

    typedef _PyDiagnosticBatchContext Context;
    class_<Context, boost::noncopyable>("DiagnosticBatchContext")
        .def("__enter__", &Context::__enter__, return_self<>())
        .def("__exit__", &Context::__exit__)
        ;
}

max_stars_repo_name: YuqiaoZhang/USD

max_issues_repo_name: YuqiaoZhang/USD

max_forks_repo_name: YuqiaoZhang/USD


text:
//
// Copyright (c) 2013-2016 Vinnie Falco (vinnie dot falco at gmail dot com)
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//

#ifndef BEAST_HTTP_PARSE_ERROR_HPP
#define BEAST_HTTP_PARSE_ERROR_HPP

#include <beast/http/error.hpp>
#include <boost/system/error_code.hpp>

namespace beast {
namespace http {

enum class parse_error
{
    connection_closed,

    bad_method,
    bad_uri,
    bad_version,
    bad_crlf,
    bad_request,

    bad_status_code,
    bad_status,

    bad_field,
    bad_value,
    bad_content_length,
    illegal_content_length,
    bad_on_headers_rv,

    invalid_chunk_size,

    short_read
};

class parse_error_category : public boost::system::error_category
{
public:
    const char*
    name() const noexcept override
    {
        return "http";
    }

    std::string
    message(int ev) const override
    {
        switch(static_cast<parse_error>(ev))
        {
        case parse_error::connection_closed:
            return "data after Connection close";

        case parse_error::bad_method:
            return "bad method";

        case parse_error::bad_uri:
            return "bad Request-URI";

        case parse_error::bad_version:
            return "bad HTTP-Version";

        case parse_error::bad_crlf:
            return "missing CRLF";

        case parse_error::bad_request:
            return "bad Request-Line";

        case parse_error::bad_status_code:
            return "bad Status-Code";

        case parse_error::bad_status:
            return "bad Status-Line";

        case parse_error::bad_field:
            return "bad field token";

        case parse_error::bad_value:
            return "bad field-value";

        case parse_error::bad_content_length:
            return "bad Content-Length";

        case parse_error::illegal_content_length:
            return "illegal Content-Length with chunked Transfer-Encoding";

        case parse_error::bad_on_headers_rv:
            return "on_headers returned an unknown value";

        case parse_error::invalid_chunk_size:
            return "invalid chunk size";

        case parse_error::short_read:
            return "unexpected end of data";

        default:
            return "beast::http::parser error";
        }
    }

    boost::system::error_condition
    default_error_condition(int ev) const noexcept override
    {
        return boost::system::error_condition(ev, *this);
    }

    bool
    equivalent(int ev,
        boost::system::error_condition const& condition
            ) const noexcept override
    {
        return condition.value() == ev &&
            &condition.category() == this;
    }

    bool
    equivalent(error_code const& error, int ev) const noexcept override
    {
        return error.value() == ev &&
            &error.category() == this;
    }
};

inline
boost::system::error_category const&
get_parse_error_category()
{
    static parse_error_category const cat{};
    return cat;
}

inline
boost::system::error_code
make_error_code(parse_error ev)
{
    return error_code(static_cast<int>(ev),
        get_parse_error_category());
}

} // http
} // beast

namespace boost {
namespace system {
template<>
struct is_error_code_enum<beast::http::parse_error>
{
    static bool const value = true;
};
} // system
} // boost

#endif


text:
/*************************************************************************
	> File Name: pex65.cpp
	> Author: ziqiang
	> Mail: ziqiang_free@163.com
	> Created Time: Mon 24 Apr 2017 03:46:34 PM CST
 ************************************************************************/

#include <iostream>
#include <boost/regex.hpp>
#include <string>
#include <fstream>
using namespace std;

int main()
{
	string s;
	boost::smatch m;
	boost::regex e("a+");

	ifstream ifs ("test.txt", ifstream::in);

	char c = ifs.get();
	while(ifs.good()){
		do{
			if(c == '\n'){
				c = ifs.get();
				continue;
			}
			s.append(1, c);
			c = ifs.get();
		}while(ifs.good() && c!='\n');

		cout << s << endl;

//		while(regex_search(s,m,e)){
//			for(auto x : m) cout << x << " ";
//			s = m.suffix().str();
//		}

		s.erase();
	}

	ifs.close();
}

max_stars_repo_name: sczzq/symmetrical-spoon

max_issues_repo_name: sczzq/symmetrical-spoon

max_forks_repo_name: sczzq/symmetrical-spoon


text:
//
// Created by attila on 21.08.18.
//

#include "ParallelOptimizerGenerator.h"
#include <boost/property_tree/json_parser.hpp>
#include <algorithm>
#include <utility>

namespace poma {

    ParallelOptimizerGenerator::ParallelOptimizerGenerator(std::string& p_source_mid, std::map<std::string,Module>& p_modules, std::vector<Link>& p_links)
            : m_source_mid{p_source_mid}, m_modules{p_modules}, m_links{p_links} {
    }

    void ParallelOptimizerGenerator::process() {
        // Find autogenerated Fork
        auto autogenerated_fork_test{[&] (const std::pair<std::string,Module>& m) {return m.second.mtype == "ParExecutor" && m.second.mparams.count("#autogenerated") > 0;}};
        bool invalidated_vector{true};
        while(invalidated_vector) {
            invalidated_vector = false;
            for (auto it{std::find_if(m_modules.begin(), m_modules.end(), autogenerated_fork_test)};
                 it != m_modules.end();
                 it = std::find_if(++it, m_modules.end(), autogenerated_fork_test))
            {
                // Find all outgoing links from this module
                long count{std::count_if(m_links.begin(), m_links.end(), [&] (const Link& l) { return l.fid == it->second.mid;})};
                // If there is only one outgoing link
                if (count == 1) {
                    // Check if it goes to another ParExecutor autogenerated module
                    auto lnk{std::find_if(m_links.begin(), m_links.end(), [&] (const Link& l) { return l.fid == it->second.mid;})};
                    if (lnk == m_links.end()) {
                        continue;
                    }
                    auto mod{std::find_if(m_modules.begin(), m_modules.end(), [&] (const std::pair<const std::string,Module>& m) { return m.second.mid == lnk->tid; })};
                    if (mod == m_modules.end()) {
                        continue;
                    }
                    // Merge only ParExecutors with the same number of threads
                    if (autogenerated_fork_test(*mod) && it->second.mparams["threads"] == mod->second.mparams["threads"]) {
                        // If so, merge the two modules
                        if (merge_parallel_modules(it->second, mod->second)) {
                            invalidated_vector = true;
                            break;
                        } else {
                            die("Inconsistent pipeline");
                        }
                    }
                }
            }
        }
    }

    bool ParallelOptimizerGenerator::merge_parallel_modules(Module a, Module b) {
        // Determine Ma (tid of link with fid == a.mid and channel == "template")
        auto ita = std::find_if(m_links.begin(), m_links.end(), [&] (const Link& l) { return l.fid == a.mid && l.channel == "template"; });
        if (ita == m_links.end()) {
            return false;
        }
        std::string ma = ita->tid;
        // Determine Mb (tid of link with fid == b.mid and channel == "template")
        auto itb = std::find_if(m_links.begin(), m_links.end(), [&] (const Link& l) { return l.fid == b.mid && l.channel == "template"; });
        if (itb == m_links.end()) {
            return false;
        }
        std::string mb = itb->tid;
        // Determine Ja (tid of link with fid == ma)
        auto itja = std::find_if(m_links.begin(), m_links.end(), [&] (const Link& l) { return l.fid == ma; });
        if (itja == m_links.end()) {
            return false;
        }
        std::string ja = itja->tid;
        // Determine Jb (tid of link with fid == mb)
        auto itjb = std::find_if(m_links.begin(), m_links.end(), [&] (const Link& l) { return l.fid == mb; });
        if (itjb == m_links.end()) {
            return false;
        }
        std::string jb = itjb->tid;
        // Remove link from a to b
        m_links.erase(std::remove_if(m_links.begin(), m_links.end(), [&] (const Link& l) { return l.fid == a.mid && l.tid == b.mid; }));
        // Remove link from b to Mb
        m_links.erase(std::remove_if(m_links.begin(), m_links.end(), [&] (const Link& l) { return l.fid == b.mid && l.tid == mb; }));
        // Remove link between Joiner module (Jb) and B
        m_links.erase(std::remove_if(m_links.begin(), m_links.end(), [&] (const Link& l) { return l.fid == jb && l.tid == b.mid; }));
        // Remove link between Mb and Joiner module Jb
        m_links.erase(std::remove_if(m_links.begin(), m_links.end(), [&] (const Link& l) { return l.fid == mb && l.tid == jb; }));
        // Remove link between Ma and Joiner module Ja
        m_links.erase(std::remove_if(m_links.begin(), m_links.end(), [&] (const Link& l) { return l.fid == ma && l.tid == ja; }));
        // Create link between Ma and Mb
        Link link;
        link.fid = ma;
        link.tid = mb;
        link.channel = "default";
        m_links.push_back(link);
        // Create link between Mb and Ja
        Link jlink;
        jlink.fid = mb;
        jlink.tid = ja;
        jlink.channel = "default";
        m_links.push_back(jlink);
        // Change all links from B to originate from A
        for (auto& l : m_links) {
            if (l.fid == b.mid) {
                l.fid = a.mid;
            }
        }
        // Remove Joiner module (Jb)
        for(auto it = m_modules.begin(); it != m_modules.end();) {
            if(it->second.mid == jb)
                it = m_modules.erase(it);
            else
                ++it;
        }
        // Remove module B
        for(auto it = m_modules.begin(); it != m_modules.end();) {
            if(it->second.mid == b.mid)
                it = m_modules.erase(it);
            else
                ++it;
        }
        return true;
    }

}

max_stars_repo_name: slashdotted/PomaPure

max_issues_repo_name: slashdotted/PomaPure

max_forks_repo_name: slashdotted/PomaPure


text:
#pragma once
//=====================================================================//
/*!	@file
	@brief	標準イメージを扱うテンプレートクラス
    @author 平松邦仁 (hira@rvf-rc45.net)
	@copyright	Copyright (C) 2017 Kunihito Hiramatsu @n
				Released under the MIT license @n
				https://github.com/hirakuni45/glfw3_app/blob/master/LICENSE
*/
//=====================================================================//
#include <iostream>
#include <vector>
#include <algorithm>
#include <boost/unordered_set.hpp>
#include <boost/foreach.hpp>
#include <boost/variant.hpp>
#include "utils/vtx.hpp"
#include "img_io/img.hpp"

namespace img {

	//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
	/*!
		@brief	任意形式の画像を扱うクラス
	*/
	//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
	template <class BPX, uint32_t clutsize = 0>
	struct img_base {
		typedef BPX	value_type;
		typedef std::vector<BPX>	img_type;
		typedef std::vector<rgba8>	clut_type;

	private:
		vtx::spos	size_;
		bool		alpha_;
		img_type	img_;

		uint32_t	clut_limit_;
		clut_type	clut_;

	public:
		//-----------------------------------------------------------------//
		/*!
			@brief	コンストラクター
		*/
		//-----------------------------------------------------------------//
		img_base() : size_(0), alpha_(false), img_(),
			clut_limit_(0) {
			clut_.resize(clutsize);
std::cout << "Const: " << static_cast<int>(get_type()) << std::endl;
		}

		//-----------------------------------------------------------------//
		/*!
			@brief	デストラクター
		*/
		//-----------------------------------------------------------------//
		~img_base() {
std::cout << "Destr: " << static_cast<int>(get_type()) << std::endl;
		}

		//-----------------------------------------------------------------//
		/*!
			@brief	イメージのタイプを得る。
			@return	イメージタイプ
		*/
		//-----------------------------------------------------------------//
		IMG::type get_type() const { return BPX::type_; }

		//-----------------------------------------------------------------//
		/*!
			@brief	イメージを確保する
			@param[in]	size	サイズ
			@param[in]	alpha	アルファチャネルを有効にする場合に「true」
		*/
		//-----------------------------------------------------------------//
		void create(const vtx::spos& size, bool alpha = false) {
			img_.clear();
			size_ = size;
			img_.resize(size_.x * size_.y);
			alpha_ = alpha;
		}

		//-----------------------------------------------------------------//
		/*!
			@brief	カラー・ルック・アップ・テーブルを設定
			@param[in]	idx	テーブルの位置
			@param[in]	c	設定するカラー
			@return 正常なら「true」
		*/
		//-----------------------------------------------------------------//
		bool put_clut(uint32_t idx, const rgba8& c) {
			if(idx < clut_.size()) {
				clut_[idx] = c;
				return true;
			}
			return false;
		}

		//-----------------------------------------------------------------//
		/*!
			@brief	カラー・ルック・アップ・テーブルを得る
			@param[in]	idx	テーブルの位置
			@param[in]	c	受け取るカラー参照ポイント
			@return 正常なら「true」
		*/
		//-----------------------------------------------------------------//
		bool get_clut(uint32_t idx, rgba8& c) const {
			if(idx < clut_.size()) {
				c = clut_[idx];
				return true;
			}
			return false;
		}

		//-----------------------------------------------------------------//
		/*!
			@brief	イメージに点を描画
			@param[in]	pos	描画位置
			@param[in]	c	描画するカラー
			@return 領域なら「true」
		*/
		//-----------------------------------------------------------------//
		template <class PIX>
		bool put_pixel(const vtx::spos& pos, const PIX& c) {
			if(BPX::type_ != PIX::type_) return false;
			if(img_.empty()) return false;
			if(pos.x >= 0 && pos.x < size_.x && pos.y >= 0 && pos.y < size_.y) {
				img_[size_.x * pos.y + pos.x] = c;
				return true;
			} else {
				return false;
			}
		}

		//-----------------------------------------------------------------//
		/*!
			@brief	イメージの点を得る
			@param[in]	pos	描画位置
			@param[in]	c	描画されたカラーを受け取るリファレンス
			@return 領域なら「true」
		*/
		//-----------------------------------------------------------------//
		template <class PIX>
		bool get_pixel(const vtx::spos& pos, PIX& c) const {
			if(BPX::type_ != PIX::type_) return false;
			if(img_.empty()) return false;
			if(pos.x >= 0 && pos.x < size_.x && pos.y >= 0 && pos.y < size_.y) {
				c  = img_[size_.x * pos.y + pos.x];
				return true;
			} else {
				return false;
			}
		}

		//-----------------------------------------------------------------//
		/*!
			@brief	アルファ合成描画
			@param[in]	pos	描画位置
			@param[in]	c	描画カラー
			@return 領域なら「true」
		*/
		//-----------------------------------------------------------------//
		bool alpha_pixel(const vtx::spos& pos, rgba8& c) {
			if(img_.empty()) return false;
			if(pos.x >= 0 && pos.x < size_.x && pos.y >= 0 && pos.y < size_.y) {
				rgba8 s = img_[size_.x * pos.y + pos.x];
				unsigned short i = 256 - c.a;
				unsigned short a = c.a + 1;
				img_[size_.x * pos.y + pos.x].set(((s.r * i) + (c.r * a)) >> 8,
										   ((s.g * i) + (c.g * a)) >> 8,
										   ((s.b * i) + (c.b * a)) >> 8);
				return true;
			} else {
				return false;
			}
		}

		//-----------------------------------------------------------------//
		/*!
			@brief	イメージのサイズを得る
			@return	イメージのサイズ
		*/
		//-----------------------------------------------------------------//
		const vtx::spos& get_size() const { return size_; }

		//-----------------------------------------------------------------//
		/*!
			@brief	イメージの参照
			@return	イメージ
		*/
		//-----------------------------------------------------------------//
		const img_type& get_image() const { return img_; }

		//-----------------------------------------------------------------//
		/*!
			@brief	イメージの参照
			@return	イメージ
		*/
		//-----------------------------------------------------------------//
		img_type& at_image() { return img_; }

		//-----------------------------------------------------------------//
		/*!
			@brief	カラー・ルック・アップ・テーブルの最大数を返す
			@return	最大数
		*/
		//-----------------------------------------------------------------//
		int get_clut_limit() const { return clut_limit_; }

		//-----------------------------------------------------------------//
		/*!
			@brief	カラーテーブルの参照
			@return	カラーテーブル
		*/
		//-----------------------------------------------------------------//
		const clut_type& get_clut() const { return clut_; }

		//-----------------------------------------------------------------//
		/*!
			@brief	カラーテーブルの参照
			@return	カラーテーブル
		*/
		//-----------------------------------------------------------------//
		clut_type& at_clut() { return clut_; }

		//-----------------------------------------------------------------//
		/*!
			@brief	アルファ・チャネルが有効か調べる
			@return	アルファ・チャネルが有効なら「true」
		*/
		//-----------------------------------------------------------------//
		bool test_alpha() const { return alpha_; }

		//-----------------------------------------------------------------//
		/*!
			@brief	画像が「空」か検査する
			@return	「空」なら「true」
		*/
		//-----------------------------------------------------------------//
		bool empty() const { return img_.empty(); }

		//-----------------------------------------------------------------//
		/*!
			@brief	利用している色数の総数をカウントする
			@return	利用している色数
		*/
		//-----------------------------------------------------------------//
		uint32_t count_color() const {
			boost::unordered_set<BPX> n;
			BOOST_FOREACH(const BPX& c, img_) {
				n.insert(c);
			}
			return static_cast<uint32_t>(n.size());
		}

		//-----------------------------------------------------------------//
		/*!
			@brief	イメージの部分コピー
			@param[in]	dst		コピー先
			@param[in]	isrc	ソースイメージ
			@param[in]	rsrc	ソースの領域
			@return コピーに失敗すると「false」を返す
		*/
		//-----------------------------------------------------------------//
		template <class SPX = rgba8, uint32_t csz = 0>
		bool copy(const vtx::spos& dst, const img_base<SPX, csz>& isrc, const vtx::srect& rsrc) {
			// FULL から INDEXED
			if(SPX::type_ == IMG::FULL8 && BPX::type_ == IMG::INDEXED8) return false;
			vtx::spos p;
			for(p.y = 0; p.y < rsrc.size.y; ++p.y) {
				for(p.x = 0; p.x < rsrc.size.x; ++p.x) {
					SPX c;
					if(isrc.get_pixel(p + rsrc.org, c)) {
						put_pixel(p + dst, c);
					}
				}
			}
			return true;
		}

		//-----------------------------------------------------------------//
		/*!
			@brief	コピー
			@param[in]	src	ソースイメージ
			@return コピーに失敗すると「false」を返す
		*/
		//-----------------------------------------------------------------//
		template <class SPX = rgba8, uint32_t csz = 0>
		bool copy(const img_base<SPX, csz>& src) {
			return copy(vtx::spos(0), src, vtx::srect(vtx::spos(0), src.get_size()));
		}

		//-----------------------------------------------------------------//
		/*!
			@brief	交換
			@param[in]	src	ソース・コンテキスト
		*/
		//-----------------------------------------------------------------//
		void swap(img_base& src) {
//			size_.swap(src.size_);
			img_.swap(src.at_image());
//			std::swap(alpha_, src.alpha_);
//			std::swap(clut_limit_, src.clut_limit_);
			clut_.swap(src.at_clut());
		}

		//-----------------------------------------------------------------//
		/*!
			@brief	単色で塗りつぶす
			@param[in]	c	塗る色
			@param[in]	r	領域（省略すると全体）
		*/
		//-----------------------------------------------------------------//
		void fill(const BPX& c, const vtx::srect& r = vtx::srect(vtx::spos(0), get_size())) {
			vtx::spos pos = r.org;
			for(pos.y = 0; pos.y < r.end_y(); ++pos.y) {
				for(pos.x = 0; pos.x < r.end_x(); ++pos.x) {
					put_pixel(pos, c);
				}
			}
		}

		//-----------------------------------------------------------------//
		/*!
			@brief	イメージを廃棄する
		*/
		//-----------------------------------------------------------------//
		void destroy() {
			size_.set(0);
			alpha_ = false;
			img_type().swap(img_);
			clut_limit_ = 0;
			clut_type().swap(clut_);
		}
	};

	typedef img_base<idx8>    img_idx8;
	typedef img_base<idx16>   img_idx16;
	typedef img_base<gray8>   img_gray8;
//	typedef img_base<gray16>  img_gray16;
	typedef img_base<rgba8>   img_rgba8;
	typedef img_base<rgba16>  img_rgba16;

	typedef boost::variant<img_idx8, img_gray8, img_rgba8>  image8;
}


text:
#ifndef BOOST_TEST_DYN_LINK
#define BOOST_TEST_DYN_LINK
#endif
#include <memory>
#include <boost/test/unit_test.hpp>
#include "generic_test_definitions.hpp"
#include "../zero_on_destruction.hpp"
using namespace boost::unit_test;

// ===== Emplacing =====

BOOST_FIXTURE_TEST_CASE( emplace_get, GicWithOneElementFixture ) {
    gic_type::element_access_type maybe_val = container.get(key);

    // Boost.Test tries to print maybe_val without the extra pair of parenthesis
    BOOST_TEST((maybe_val != container.failed_get()));
    BOOST_TEST(*maybe_val == NON_ZERO_VAL);
}

BOOST_FIXTURE_TEST_CASE( emplace_brackets_get, GicWithOneElementFixture ) {
    auto maybe_val = container[key];

    BOOST_TEST((maybe_val != container.failed_get()));
    BOOST_TEST(*maybe_val == NON_ZERO_VAL);
}

BOOST_FIXTURE_TEST_CASE( emplace_and_get, GicFixture ) {
    auto [key, elem] = container.emplace_and_get(NON_ZERO_VAL);
    auto maybe_val = container[key];

    BOOST_TEST((maybe_val != container.failed_get()));
    BOOST_TEST(elem == NON_ZERO_VAL);
    BOOST_TEST(std::addressof(elem) == std::addressof(*maybe_val));
}

struct has_its_own_key {
    using key_type = genex::key<has_its_own_key>;

    key_type const key;
    int val;

    has_its_own_key(key_type const& k, int v) : key(k), val(v) {}
    has_its_own_key(int v, key_type&& k) : key(k), val(v) {}
};

BOOST_AUTO_TEST_CASE( emplace_with_key_by_cref ) {
    gic_derived<has_its_own_key> container;
    auto [key, elem] = container.emplace_and_get(genex::key_placeholder,
                                                 NON_ZERO_VAL);

    BOOST_TEST(elem.val == NON_ZERO_VAL);
    BOOST_TEST((elem.key == key));
}

BOOST_AUTO_TEST_CASE( emplace_with_key_by_rv_ref ) {
    gic_derived<has_its_own_key> container;
    auto [key, elem] = container.emplace_and_get(NON_ZERO_VAL,
                                                 genex::key_placeholder);

    BOOST_TEST(elem.val == NON_ZERO_VAL);
    BOOST_TEST((elem.key == key));
}

BOOST_FIXTURE_TEST_CASE( get_const, GicWithOneElementFixture ) {
    gic_type const& container_const_ref = container;

    gic_type::element_const_access_type maybe_val =
            container_const_ref.get(key);

    BOOST_TEST((maybe_val != container_const_ref.failed_get()));
    BOOST_TEST(*maybe_val == NON_ZERO_VAL);
}

BOOST_FIXTURE_TEST_CASE( remove_get, GicWithOneElementFixture ) {
    container.remove(key);
    auto maybe_val = container[key];

    BOOST_TEST((maybe_val == container.failed_get()));
}

BOOST_FIXTURE_TEST_CASE( remove_old_key, GicFixture ) {
    auto old_key = container.emplace(NON_ZERO_VAL_1);
    container.remove(old_key);
    auto new_key = container.emplace(NON_ZERO_VAL_2);
    container.remove(old_key); // should have no effect
    auto maybe_val = container[new_key];

    BOOST_TEST((maybe_val != container.failed_get()));
    BOOST_TEST(*maybe_val == NON_ZERO_VAL_2);
}

BOOST_FIXTURE_TEST_CASE( get_old_key, GicFixture ) {
    auto old_key = container.emplace(NON_ZERO_VAL_1);
    container.remove(old_key);
    auto new_key = container.emplace(NON_ZERO_VAL_2);
    (void)new_key;
    auto maybe_val = container[old_key];

    BOOST_TEST((maybe_val == container.failed_get()));
}

BOOST_AUTO_TEST_CASE( destruction_on_raii ) {
    int val = NON_ZERO_VAL;

    {
        gic_derived<zero_on_destruction<int>> container;
        auto key = container.emplace(val);
        (void)key;
    }

    BOOST_TEST(val == 0);
}

BOOST_AUTO_TEST_CASE( destruction_on_removal ) {
    int val = NON_ZERO_VAL;

    gic_derived<zero_on_destruction<int>> container;
    auto key = container.emplace(val);
    container.remove(key);

    BOOST_TEST(val == 0);
}

BOOST_AUTO_TEST_CASE( destruction_on_emplacement ) {
    int val = NON_ZERO_VAL;

    gic_derived<zero_on_destruction<int>> container;
    auto key = container.emplace(val);
    container.remove(key);

    BOOST_TEST(val == 0);
}

max_stars_repo_name: ll-h/genex

max_issues_repo_name: ll-h/genex

max_forks_repo_name: ll-h/genex


text:
/**
 * @file IbeoLUX.hpp
 *
 * Enthält Klasse IbeoLUX, die Verbindung zu einem ibeoLUX-Laserscanner aufnehmen kann und die individuellen Daten abruft und verarbeitet.
 *
 * @author Christian Blumberg
 * @date 2012-06-05
 */

#include "IbeoLaserAbstract.hpp"
#include "IbeoLUX.hpp"
#include "IbeoLUXData.hpp"

#include <iostream>
#include <list>
#include <cstring>

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

#include "../Additional/Buffers/RingbufferException.hpp"
#include "../Additional/Timestamp/Timestamp.hpp"
#include "../Additional/Convert/Convert.hpp"
#include "../Additional/XMath/MovingMatrix.hpp"
#include "../Additional/XMath/Convert.hpp"

#include "../Capture/ProcessAndCaptureAbstract.hpp"

namespace ibeo
{

	namespace ibeoLUX
	{
		IbeoLUX *IbeoLUX::singletonInstance = 0;

		IbeoLUX *IbeoLUX::getInstance()
		{
			return(singletonInstance);
		}

		void IbeoLUX::initInstance(const std::string& IP_address, unsigned short port, unsigned int history)
		{
			if(singletonInstance) singletonInstance->releaseInstance();

			singletonInstance = new IbeoLUX(IP_address, port, history);
		}

		void IbeoLUX::releaseInstance()
		{
			if(singletonInstance)
			{
				singletonInstance->stopMeasuring();
				singletonInstance->disconnect();
				delete singletonInstance;
				singletonInstance = 0;
			}
		}

		/**
		 * Der Konstruktor der Klasse.
		 *
		 * @param[in] IP_address Die IP-Adresse, zu der die Verbindung mit dem Laserscanner aufgebaut werden soll.
		 * @param[in] port       Der Port über den die Verbindung laufen soll.
		 * @param[in] history    Die Größe der Historie. Von dort können die neuesten und auch ältere Daten abgerufen werden.
		 */
		IbeoLUX::IbeoLUX(const std::string& IP_address,
						 unsigned short port,
						 unsigned int history
						)

						:

						IbeoLaserAbstract(IP_address, port, 0xAFFEC0C2, 24, history)
		{
			float angle = -1.2;
			for(unsigned int i = 0; i < 4; i++, angle += 0.8)
			{
				zValueLayerAdjustmentMatrix[i].rotateY(MathConvert::Convert::deg2rad(angle));
			}

			fillWithEmptyIbeoLaserData();
		}

		/**
		 * Der Destruktor der Klasse.
		 */
		IbeoLUX::~IbeoLUX()
		{

		}

		/**
		 * füllt die deques mit NULL-Daten (Leerdaten), so dass später einige IF-Konstrukte gespart werden können beim Abruf von DataObjekten.
		 */
		void IbeoLUX::fillWithEmptyIbeoLaserData()
		{
			for(unsigned int i = 0; i < history; i++)
			{
				ibeoLaserDataAbstractSmartPtr dat(new IbeoLUXData());
				data.push_front(dat);
			}
		}

		/**
		 * verarbeitet den Header einer Messdatenreihe
		 */
		bool IbeoLUX::processMessageHeader(bool allowSynchronisation)
		{
			while(ringBuffer->getReadBytesLeft() < headerSize)
				this->receiveData(TMPBUFSIZE);

			unsigned char *readPtrOne, *readPtrTwo;
			unsigned int readBytesOne, readBytesTwo;

			unsigned int offset = 0;

			try
			{
				ringBuffer->readBytes(&readPtrOne, &readPtrTwo, &readBytesOne, &readBytesTwo, headerSize, true);
			}
			catch(buffer::RingbufferReadOverflowException&)
			{
				std::cerr << "Es wurde versucht mehr Daten zu lesen, als im Ringpuffer enthalten sind." << "[HEADERSIZE=" << headerSize << "]"<< std::endl;
			}
			if(readBytesOne) memcpy(tmpBuffer, readPtrOne, readBytesOne);
			if(readBytesTwo) memcpy(tmpBuffer + readBytesOne, readPtrTwo, readBytesTwo);

			// Daten liegen in Netzwork-Byteorder vor; müssen also vor der Verarbeitung für x86-CPU umgewandelt werden

			namespace boost_socket_ops = boost::asio::detail::socket_ops; // der namespace macht Network-Byte-Order-Operationen plattformunabhängig verfügbar

			// Magicword einlesen: Offset 0/0x00, Länge 4
			memcpy(&(magicWord), tmpBuffer, 4);
			magicWord = boost_socket_ops::network_to_host_long(magicWord);
			if(magicWord != MAGICWORD)
			{
				if(allowSynchronisation) synchronizeToStream();
				return(false);
			}
			//else std::cout << std::hex << magicWord << std::endl;

			// BodySize einlesen: Offset 8/0x08, Länge 4
			offset += 8;
			memcpy(&(bodySize), tmpBuffer + offset, 4);
			bodySize = boost_socket_ops::network_to_host_long(bodySize);

			// DataType einlesen: Offset 14/0x0E, Länge 2
			offset += 6;
			memcpy(&(dataType), tmpBuffer + offset, 2);
			dataType = static_cast<ibeo::DATATYPE>(boost_socket_ops::network_to_host_short(dataType));

			// da es verschiedene Arten von Paketen gibt, müssen die relevaten SCANDATA-Pakete herausgefiltert werden
			// die Daten die einem NICHT-SCANDATA-Paket anhängen, müssen zwar abgerufen werden aus dem Ringbuffer, aber sie werden nicht verarbeitet.
			if(dataType != IbeoLUX_SCANDATA)
			{
				while(ringBuffer->getReadBytesLeft() < bodySize)
					this->receiveData(TMPBUFSIZE);

				try
				{
					ringBuffer->readBytes(&readPtrOne, &readPtrTwo, &readBytesOne, &readBytesTwo, bodySize, true);
				}
				catch(buffer::RingbufferReadOverflowException&)
				{
					std::cerr << "Es wurde versucht mehr Daten zu lesen, als im Ringpuffer enthalten sind." << "[bodySize=" << bodySize << ", buffer= " << ringBuffer->getReadBytesLeft() << ", SCANDATA=NO]"<< std::endl;
				}
				return(false);
			}

			/* ********************************************************************************************************************************************
			 *  Timestamp des Lasers nur dann einlesen, wenn es erforderlich wird. Jetzt wird Timestamp global und statisch über Timestamp-klasse abgerufen
			 * ********************************************************************************************************************************************
			// TimeStamp einlesen: Offset 18/0x12, Länge 4
			offset += 2;
			memcpy(&(timeStampSeconds), tmpBuffer + offset, 4);
			timeStampSeconds = boost_socket_ops::network_to_host_long(timeStampSeconds);

			// TimeStamp einlesen: Offset 22/0x16, Länge 4
			offset += 4;
			memcpy(&(timeStampMilliseconds), tmpBuffer + offset, 4);
			timeStampMilliseconds = boost_socket_ops::network_to_host_long(timeStampMilliseconds);
			*/
			return(true);
		}

		/**
		 * verarbeitet die nachgelagerten Daten nach dem Header, jedoch nicht die Messdaten selbst, und legt ein passendes DataObjekt an.
		 */
		void IbeoLUX::processScanDataHeader()
		{
			while(ringBuffer->getReadBytesLeft() < bodySize)
			{
				this->receiveData(TMPBUFSIZE);
			}

			unsigned char *readPtrOne, *readPtrTwo;
			unsigned int readBytesOne, readBytesTwo;

			try
			{
				ringBuffer->readBytes(&readPtrOne, &readPtrTwo, &readBytesOne, &readBytesTwo, bodySize, true);
			}
			catch(buffer::RingbufferReadOverflowException&)
			{
				std::cerr << "Es wurde versucht mehr Daten zu lesen, als im Ringpuffer enthalten sind. [bodySize=" << bodySize << ", SCANDATA=YES]" << std::endl;
			}
			if(readBytesOne) memcpy(tmpBuffer, readPtrOne, readBytesOne);
			if(readBytesTwo) memcpy(tmpBuffer + readBytesOne, readPtrTwo, readBytesTwo);

			unsigned char* dataPointer = tmpBuffer;

			// ScanNummer einlesen: Offset 0/0x00, Länge 2
			memcpy(&(scanNumber), dataPointer, 2);

			// Angleticks per Rotation einlesen: Offset 22/0x16, Länge 2
			memcpy(&(angleTicksPerRotation), (dataPointer + 22), 2);

			// Anzahl an Scanpunkten einlesen: Offset 28/0x1C, Länge 2
			memcpy(&(numberOfScanPoints), (dataPointer + 28), 2);

			// Pointer versetzen; vorher: Scandaten inkl. Headerinformationen, nachher: Scanpunktliste: Offset 44/0x2C, Länge <numberOfScanPoints>
			dataPointer = (dataPointer + 44);

			ibeoLaserDataAbstractSmartPtr dat(new IbeoLUXData(bodySize, scanNumber, numberOfScanPoints, angleTicksPerRotation, dataPointer));
			if(disclosureMethod) disclosureMethod(dat);
			appendData(dat);
			//std::cout << "SNR:" << scanNumber << std::endl;
			static int i = 0;

			if (i == 0) {
				//imuData();
				ibeoLaserDataAvailable(dat);
				i = 0;
			} else
				i++;

		}

	} // namespace ibeoLUX
} /* namespace ibeo */

max_stars_repo_name: MechLabEngineering/SICKRPi-Scanner

max_issues_repo_name: MechLabEngineering/SICKRPi-Scanner

max_forks_repo_name: MechLabEngineering/SICKRPi-Scanner


text:
/*
 * Copyright 2021 Assured Information Security, Inc.
 *
 * 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 <introvirt/introvirt.hh>

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

#include <csignal>
#include <functional>
#include <iostream>
#include <mutex>
#include <string>

using namespace introvirt;
using namespace introvirt::windows;

namespace po = boost::program_options;

using std::placeholders::_1;

void parse_program_options(int argc, char** argv, po::options_description& desc,
                           po::variables_map& vm);

bool interrupted = false;
std::unique_ptr<Domain> domain;

void sig_handler(int signum) {
    interrupted = true;
    domain->interrupt();
}

class EventHandler : public EventCallback {
  public:
    void process_event(Event& event) override {
        std::cout << "Received event " << event.type() << std::endl;
    }
};

void mem_callback(Event& event) {
    const Vcpu& vcpu = event.vcpu();
    const auto& regs = vcpu.registers();

    std::cout << "Vcpu " << vcpu.id() << ": [" << event.task().pid() << ":" << event.task().tid()
              << "] " << event.task().process_name() << '\n';
    std::cout << '\t' << "RIP 0x" << std::hex << regs.rip() << std::dec << '\n';

    std::cout << '\t';
    if (event.mem_access().read_violation())
        std::cout << "R";
    if (event.mem_access().write_violation())
        std::cout << "w";
    if (event.mem_access().execute_violation())
        std::cout << "X";
    std::cout << '\n';

    std::cout.flush();
}

int main(int argc, char** argv) {
    po::options_description desc("Options");

    std::string domain_name;
    std::string process_name;
    std::string address_str; // String so we can handle hex. Is there a better way?
    uint32_t length = 0;
    uint64_t pid = 0;

    // clang-format off
    desc.add_options()
      ("domain,D", po::value<std::string>(&domain_name)->required(), "The domain name or ID attach to")
      ("physical,P", "Use a physical address instead of a virtual address")
      ("procname", po::value<std::string>(&process_name), "A process name to watch")
      ("pid", po::value<uint64_t>(&pid), "A process identifier to watch")
      ("address,a", po::value<std::string>(&address_str)->required(), "An address of a buffer to watch. Requires procname or pid if not physical.")
      ("length,l", po::value<uint32_t>(&length)->default_value(1), "The length of the buffer to watch")
      ("read,r",  "Watch read accesses")
      ("write,w",  "Watch writes accesses")
      ("execute,x", "Watch instruction fetch accesses")
      ("help", "Display program help");
    // clang-format on

    // We're not mixing with printf, improve cout performance.
    std::cout.sync_with_stdio(false);

    po::variables_map vm;
    parse_program_options(argc, argv, desc, vm);

    const bool read = vm.count("read");
    const bool write = vm.count("write");
    const bool exec = vm.count("execute");
    const bool physical = vm.count("physical");

    //
    // Argument Validation
    //
    char* endptr = nullptr;
    uint64_t address = strtoull(address_str.c_str(), &endptr, 0);
    if (*endptr != '\0') {
        std::cerr << "Invalid input address: " << address_str << '\n';
        return 1;
    }

    if (!physical) {
        // Make sure a process name or PID was provided
        if (process_name.empty() && vm.count("pid") == 0) {
            std::cerr << "Virtual addresses require a process name or PID\n";
            return 1;
        }
    }

    if (!length) {
        std::cerr << "A minimum length of 1 is required\n";
        return 1;
    }

    if (!read && !write && !exec) {
        std::cerr << "At least one of read, write, or execute must be specified\n";
        return 1;
    }

    if (vm.count("pid") && !process_name.empty()) {
        std::cerr << "Specifiy either pid or procname, not both.\n";
        return 1;
    }

    // Make sure the process name (if any) is lowercase
    boost::to_lower(process_name);

    // Get a hypervisor instance
    // This will automatically select the correct type of hypervisor.
    auto hypervisor = Hypervisor::instance();

    // Attach to the domain
    signal(SIGINT, &sig_handler);
    domain = hypervisor->attach_domain(domain_name);

    // Create our watchpoint
    std::unique_ptr<Watchpoint> watchpoint;

    // Detect the guest OS
    if (!domain->detect_guest()) {
        std::cerr << "Failed to detect guest OS\n";
        return 1;
    }

    if (!physical) {
        domain->pause();

        switch (domain->guest()->os()) {
        case OS::Windows: {
            // Find a matching process
            const auto* guest = static_cast<const WindowsGuest*>(domain->guest());
            const auto& kernel = guest->kernel();
            auto cidtable = kernel.CidTable();
            std::shared_ptr<nt::PROCESS> process;

            for (const auto& entry : cidtable->open_handles()) {
                auto object_header = entry->ObjectHeader();
                if (object_header->type() == nt::ObjectType::Process) {
                    auto test_process = kernel.process(object_header->Body());
                    if (vm.count("pid") == 0) {
                        // String match
                        auto name = boost::to_lower_copy(test_process->ImageFileName());
                        if (boost::starts_with(name, process_name)) {
                            process = std::move(test_process);
                            break;
                        }
                    } else {
                        // Pid match
                        if (pid == test_process->UniqueProcessId()) {
                            process = std::move(test_process);
                            break;
                        }
                    }
                }
            }

            if (!process) {
                std::cerr << "Failed to find a matching process\n";
                return 1;
            }

            // Make the GuestVirtualAddress in the right address space
            GuestVirtualAddress gva(*domain, address, process->DirectoryTableBase());

            // Create the watchpoint
            watchpoint = domain->create_watchpoint(gva, length, read, write, exec,
                                                   std::bind(&mem_callback, _1));

            break;
        }
        default:
            std::cerr << "Unsupported OS\n";
            return 1;
        }

        domain->resume();
    } else {
        // Just get the physical address
        GuestPhysicalAddress physical_address(*domain, address);
        watchpoint = domain->create_watchpoint(physical_address, length, read, write, exec,
                                               std::bind(&mem_callback, _1));
    }

    std::cout << "Running!" << std::endl;

    // Start the poll
    EventHandler handler;
    domain->poll(handler);

    return 0;
}

/**
 * Parse command line options here
 */
void parse_program_options(int argc, char** argv, po::options_description& desc,
                           po::variables_map& vm) {
    try {
        po::store(po::parse_command_line(argc, argv, desc), vm);
        /*
         * --help option
         */
        if (vm.count("help")) {
            std::cout << "ivmemwatch - Watch guest memory accesses" << '\n';
            std::cout << desc << '\n';
            exit(0);
        }

        po::notify(vm); // throws on error, so do after help in case
                        // there are any problems
    } catch (po::error& e) {
        std::cerr << "ERROR: " << e.what() << std::endl << std::endl;
        std::cerr << desc << std::endl;
        exit(1);
    }
}

ext: cc

max_stars_repo_name: srpape/IntroVirt

max_issues_repo_name: srpape/IntroVirt

max_forks_repo_name: srpape/IntroVirt


text:
#ifndef SHIFT_CORE_EXCEPTION_HPP
#define SHIFT_CORE_EXCEPTION_HPP

#include <string>
#include <shift/core/boost_disable_warnings.hpp>
#include <boost/exception/diagnostic_information.hpp>
#include <boost/exception/error_info.hpp>
#include <boost/exception/exception.hpp>
#include <boost/exception/get_error_info.hpp>
#include <boost/exception/info.hpp>
#include <boost/exception/info_tuple.hpp>
#include <boost/stacktrace/stacktrace_fwd.hpp>
#include <shift/core/boost_restore_warnings.hpp>

namespace shift::core
{
/// Boost exceptions in a nutshell:
/// - Compared to std::exceptions they provide an extendible way to attach
///   arbitrary data to the exception.
/// - Define own custom base exception type:
///   struct my_generic_error : virtual boost::exception,
///                             virtual std::exception {};
///   (don't forget to use virtual inheritance!)
/// - Define own custom specific/derived exception type:
///   struct my_specific_error : virtual my_generic_error {};
/// - Define a new information field which can be attached to any Boost
///   exception:
///   using my_info = boost::error_info<struct my_info_tag, any_type>;
///   - Replace any_type with some common type like std::string, int, float,
///     bool, ... (any type T that has an operator
///     std::ostream&<<(std::ostream&, const T&);)
///   - my_info_tag must be globally unique and does not have to be defined.
/// - Throw exceptions:
///     BOOST_THROW_EXCEPTION(my_specific_error() << my_info("Error
///     message"));
///     - The macro BOOST_THROW_EXCEPTION adds source filename and line info
///       to the exception (debug build only). Alternatively, one can use the
///       regular throw my_specific_error() << my_info("Error message");
///       syntax.
/// - Catch, add info and rethrow exceptions:
///   try { ... }
///   catch (boost::exception& e)
///   {
///     e << my_info("More info about the error");
///     throw;
///   }
/// - Catch and print exceptions:
///   try { ... }
///   catch (const boost::exception& e)
///   {
///     shift::log::exception() << boost::diagnostic_information(e);
///   }

using traced =
  boost::error_info<struct traced_tag, boost::stacktrace::stacktrace>;

#define SHIFT_THROW_EXCEPTION(x) BOOST_THROW_EXCEPTION(x)

/// Base class for almost all exceptions directly thrown by this library
/// collection.
struct error : virtual boost::exception, virtual std::exception
{
};

using context_info = boost::error_info<struct context_info_tag, std::string>;

template <typename T>
using error_code_info = boost::error_info<struct error_code_info_tag, T>;

/// Base class for exceptions caused by evaluation of run-time computed
/// information.
struct runtime_error : virtual error
{
};

/// Base class for exceptions caused by wrong usage of some type.
struct logic_error : virtual error
{
};

/// An exception type to be used when an out of memory situation occurs.
struct out_of_memory : virtual runtime_error
{
};

/// An exception type to be used when a method call is invalid for the
/// object's current state.
/// @remarks
///   Any invalid_operation should have a context_info attachment.
struct invalid_operation : virtual runtime_error
{
};

/// An exception type to be used when one of the arguments provided to a
/// method is invalid.
/// @remarks
///   Any invalid_argument should have a context_info attachment.
struct invalid_argument : virtual runtime_error
{
};

/// An exception type for any IO error
struct io_error : virtual runtime_error
{
};

using file_name_info =
  boost::error_info<struct file_name_info_tag, std::string>;

/// An exception type for any file related error
/// @remarks
///   Any file_error should have a file_name_info attachment.
struct file_error : virtual io_error
{
};

/// An exception type thrown if some kind of file could not be opened.
struct file_open_error : virtual file_error
{
};

/// An exception type thrown if some kind of file could not be read from.
struct file_read_error : virtual file_error
{
};

/// An exception type thrown if some kind of file could not be written to.
struct file_write_error : virtual file_error
{
};

using path_name_info =
  boost::error_info<struct path_name_info_tag, std::string>;

/// An exception type thrown if some path is invalid or non-existent.
struct path_error : virtual io_error
{
};
}

#endif

max_stars_repo_name: cspanier/shift

max_issues_repo_name: cspanier/shift

max_forks_repo_name: cspanier/shift


text:
/**
 * GeoDa TM, Copyright (C) 2011-2015 by Luc Anselin - all rights reserved
 *
 * This file is part of GeoDa.
 *
 * GeoDa is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * GeoDa is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

#include <string>
#include <vector>
#include <map>
#include <ogrsf_frmts.h>
#include <cpl_port.h>
#include <boost/thread.hpp>
#include <boost/bind.hpp>

#include "OGRDatasourceProxy.h"
#include "OGRLayerProxy.h"
#include "../GdaException.h"
#include "../GenUtils.h"
#include "../GeneralWxUtils.h"

using namespace std;

OGRDatasourceProxy::OGRDatasourceProxy(GDALDataset* _ds, wxString _ds_name)
: ds(_ds), ds_name(_ds_name)
{
}

OGRDatasourceProxy::OGRDatasourceProxy(wxString _ds_name, GdaConst::DataSourceType _ds_type, bool bUpdate)
{
    ds_name = _ds_name;
    ds_type = _ds_type;

    const char* pszDsPath = GET_ENCODED_FILENAME(ds_name);

    CPLErrorReset();

    if (ds_type == GdaConst::ds_csv) {
        if (GdaConst::gda_ogr_csv_header == 0) {
            const char *papszOpenOptions[255] = {"AUTODETECT_TYPE=YES", "EMPTY_STRING_AS_NULL=YES", "HEADERS=NO"};
            ds = (GDALDataset*) GDALOpenEx(pszDsPath, GDAL_OF_VECTOR|GDAL_OF_UPDATE, NULL, papszOpenOptions, NULL);
        } else if (GdaConst::gda_ogr_csv_header == 1) {
            const char *papszOpenOptions[255] = {"AUTODETECT_TYPE=YES", "EMPTY_STRING_AS_NULL=YES", "HEADERS=YES"};
            ds = (GDALDataset*) GDALOpenEx(pszDsPath, GDAL_OF_VECTOR|GDAL_OF_UPDATE, NULL, papszOpenOptions, NULL);
        } else {
            const char *papszOpenOptions[255] = {"AUTODETECT_TYPE=YES", "EMPTY_STRING_AS_NULL=YES"};
            ds = (GDALDataset*) GDALOpenEx(pszDsPath, GDAL_OF_VECTOR|GDAL_OF_UPDATE, NULL, papszOpenOptions, NULL);

        }

    } else {
        ds = (GDALDataset*) GDALOpenEx(pszDsPath, GDAL_OF_VECTOR|GDAL_OF_UPDATE, NULL, NULL, NULL);
    }

    is_writable = true;
	if (!ds) {
        // try without UPDATE
        ds = (GDALDataset*) GDALOpenEx(pszDsPath, GDAL_OF_VECTOR, NULL, NULL, NULL);

        if (ds==0) {
			//wxString drv_name(ds->GetDriverName());
			//if (drv_name == "OpenFileGDB") {
            // raise open fialed
            // we don't use OpenFileGDB since it has some bugs
            string error_detail = CPLGetLastErrorMsg();
            ostringstream msg;
			msg << "Failed to open data source. Please check the data/datasource and check if the data type/format is supported by GeoDa.\n\nTip: you can set up the necessary GeoDa driver by following the instructions at:\n http://geodacenter.github.io/formats.html";

            if ( error_detail.length() == 0 || error_detail == "Unknown") {
            } else {
                msg << "\n\nDetails: " << error_detail;
            }

            throw GdaException(msg.str().c_str());
			//}
        }
        is_writable = false;
	}

	// deprecated by above logic
    //is_writable = ds->TestCapability( ODsCCreateLayer );
	layer_count = ds->GetLayerCount();
}

OGRDatasourceProxy::OGRDatasourceProxy(wxString format, wxString dest_datasource)
: ds_name(dest_datasource)
{
	// create a OGRDatasourceProxy with a geometry layer
	ostringstream error_message;
	const char* pszFormat = format.c_str();
	const char* pszDestDataSource = GET_ENCODED_FILENAME(ds_name);

	GDALDriver *poDriver;
	poDriver = GetGDALDriverManager()->GetDriverByName(pszFormat);

	if( poDriver == NULL ){
		error_message << "The format \"" << format << "\" is not supported (or read-only) by GeoDa";
        if (GeneralWxUtils::isMac()) {
            error_message << " on Mac OSX";
        } else if (GeneralWxUtils::isWindows()) {
            error_message << " on Windows";
        } else if (GeneralWxUtils::isUnix()) {
            error_message << " on Unix";
        }
        error_message <<".\n\nNote: Please check if the related plugin has been installed.";
		throw GdaException(error_message.str().c_str());
	}

    ds_type = GetGdaDataSourceType(poDriver);

	// create the output data source.
	const char *papszLCO[50] = {"OVERWRITE=yes"};
	//ds = poDriver->CreateDataSource( pszDestDataSource, papszLCO);
	ds = poDriver->Create( pszDestDataSource, 0,0,0,GDT_Unknown, NULL);

	if(ds == NULL ) {
		// driver failed to load
		error_message << "Unfortunately, GeoDa is not able to execute this request. \n\nDetails: "<< CPLGetLastErrorMsg();
		throw GdaException(error_message.str().c_str());
	}
    if(!ds->TestCapability(ODsCCreateLayer)) {
		// driver failed to load
		error_message << "GeoDa can't write layer to this datasource. \n\nDetails: "<< CPLGetLastErrorMsg();
		throw GdaException(error_message.str().c_str());
    }

	layer_count = ds->GetLayerCount();
}

OGRDatasourceProxy::~OGRDatasourceProxy()
{
	// clean map of layer_pool
	map<wxString, OGRLayerProxy*>::iterator it;
	for (it=layer_pool.begin(); it!=layer_pool.end(); it++) {
		if (it->second)
            delete it->second;
	}
	layer_pool.clear();

	// clean ogr data sources
	//OGRDataSource::DestroyDataSource(ds);

	GDALClose(ds);
}

GdaConst::DataSourceType
OGRDatasourceProxy::GetGdaDataSourceType(GDALDriver *poDriver)
{
    if (poDriver == NULL) return GdaConst::ds_unknown;

    const char* drv_name = GDALGetDriverShortName(poDriver);
    string ogr_ds_type(drv_name);

    if (ogr_ds_type.find("CartoDB") != std::string::npos) {
       return GdaConst::datasrc_str_to_type["CartoDB"];

    } else if (GdaConst::datasrc_str_to_type.find(ogr_ds_type) == GdaConst::datasrc_str_to_type.end()) {
		return GdaConst::ds_unknown;

	} else {
		return GdaConst::datasrc_str_to_type[ogr_ds_type];
	}
}

vector<wxString> OGRDatasourceProxy::GetLayerNames()
{
	// GetLayerNames can happen before actually read data from layer
	// , so this provide us a chance to store all OGRLayer instance
	// in this datasource proxy for future use.

	if (layer_count == layer_pool.size() && layer_count > 0) {
		// return layer names from pool directly
		//map<string, OGRLayerProxy*>::iterator it;
		//for (it = layer_pool.begin(); it!= layer_pool.end(); it++) {
		//	layer_names.push_back(it->first);
		//}

    } else if (layer_count == 0){
       // try to read (by default) first layer
       // Note: http://ogi.state.ok.us/geoserver/wfs?VERSION=1.1.0&REQUEST=GetFeature&typename=okcounties
       // this WFS return 0 layer count, which is unusual
		OGRLayerProxy* layer_proxy = NULL;
        OGRLayer* layer = ds->GetLayer(0);
        if (layer) {
            wxString layer_name(layer->GetName());
            this->layer_names.push_back(layer_name);
            layer_pool[layer_name] = new OGRLayerProxy(std::string(GET_ENCODED_FILENAME(layer_name)),layer,ds_type);
        }

	} else {
		// read and store layer one by one, get the layer name
		int system_layers = 0;
		OGRLayer* layer = NULL;
		for (int i=0; i<layer_count; i++)
		{
			layer = ds->GetLayer(i);
			wxString layer_name(layer->GetName());
            // don't \show some system tables in postgres
            if ( layer_name == "raster_columns" ||
                 layer_name == "raster_overviews" ||
                 layer_name == "topology.topology"  ||
                 layer_name == "topology.layer" )
            {
                system_layers++;
                continue;
            }
			this->layer_names.push_back(layer_name);
            layer_pool[layer_name] = new OGRLayerProxy(std::string(GET_ENCODED_FILENAME(layer_name)),layer,ds_type);
		}
        layer_count = layer_count - system_layers;

	}
	return this->layer_names;
}

OGRLayerProxy* OGRDatasourceProxy::ExecuteSQL(string sql)
{
	OGRLayer* tmp_layer = ds->ExecuteSQL(sql.c_str(),  0, 0);
	//tmp_layer->SyncToDisk();
	ds->ReleaseResultSet(tmp_layer);
	return NULL;
}

OGRLayerProxy* OGRDatasourceProxy::GetLayerProxyBySQL(string sql)
{
    // Note: layer is not managed here. Memory leak is possible.
	OGRLayer* layer = ds->ExecuteSQL(sql.c_str(), 0, 0);
	if (layer == NULL) return NULL;
	OGRLayerProxy* layer_proxy = new OGRLayerProxy(sql, layer, ds_type);
	return layer_proxy;
}

bool OGRDatasourceProxy::DeleteLayer(string layer_name)
{
    int tmp_layer_count = layer_count;
    for (int i=0; i < tmp_layer_count; i++)
	{
        OGRLayer* layer = ds->GetLayer(i);
		string tmp_layer_name(layer->GetName());
        if ( tmp_layer_name.compare(layer_name) == 0) {
            if ( ds->DeleteLayer(i) == OGRERR_NONE ) {
                map<wxString, OGRLayerProxy*>::iterator it =
                    layer_pool.find(layer_name);
                if ( it != layer_pool.end()) {
                    layer_pool.erase(it);
                }
                for (int j=0; j<layer_names.size(); j++) {
                    if (layer_name.compare(layer_names[i]) == 0) {
                        layer_names.erase(layer_names.begin() + j);
                        break;
                    }
                }
                layer_count--;
                return true;
            }
            else return false;
        }
    }
    return false;
}

OGRLayerProxy* OGRDatasourceProxy::GetLayerProxy(string layer_name)
{
	OGRLayerProxy* layer_proxy;

	if (layer_pool.count(layer_name) > 0) {
		// find it from pool and return it
		layer_proxy = layer_pool[layer_name];

	} else {
		// otherwise, create one and store it in pool
		OGRLayer* layer = ds->GetLayerByName(layer_name.c_str());
		if (layer == NULL) {
			// for some files, there's no layer name. Just get the first one
			layer = ds->GetLayer(0);
            if (layer == NULL) {
                ostringstream error_message;
                error_message << "No layer was found in this datasource.";
                throw GdaException(error_message.str().c_str());
            }
		}

		//bool is_thread_safe = layer->TestCapability(OLCRandomRead);
		layer_proxy = new OGRLayerProxy(layer_name, layer, ds_type);

		//todo: if there is one already existed, clean/delete the old first
		layer_pool[layer_name] = layer_proxy;
	}

	return layer_proxy;
}

void OGRDatasourceProxy::CreateDataSource(string format,
										  wxString dest_datasource)
{
	ostringstream error_message;
	const char* pszFormat = format.c_str();
	const char* pszDestDataSource = dest_datasource.c_str();
	GDALDriver *poDriver;
	poDriver = GetGDALDriverManager()->GetDriverByName(pszFormat);

	if( poDriver == NULL ){
		error_message << "Current OGR dirver " + format + " is not supported by GeoDa.\n" << CPLGetLastErrorMsg();
		throw GdaException(error_message.str().c_str());
	}

	// Create the output data source.
	GDALDataset *poODS = poDriver->Create( pszDestDataSource, 0,0,0,GDT_Unknown, NULL);
	if( poODS == NULL ) {
		// driver failed to load
		error_message << "Can't create output OGR driver. \n\nDetails:"<< CPLGetLastErrorMsg();
		throw GdaException(error_message.str().c_str());
	}
	//OGRDataSource::DestroyDataSource( poODS );
	GDALClose(poODS);
}

// Create a geom only layer, the table will added ID column automatically
OGRLayerProxy*
OGRDatasourceProxy::CreateLayer(wxString layer_name,
                                OGRwkbGeometryType eGType,
                                vector<OGRGeometry*>& geometries,
                                TableInterface* table,
                                vector<int>& selected_rows,
                                OGRSpatialReference* spatial_ref)
{
    ostringstream  error_message;
    if(!ds->TestCapability(ODsCCreateLayer)) {
		// driver failed to load
		error_message << "GeoDa can't create a layer."
		<<"\n\nDetails: "<< CPLGetLastErrorMsg();
		throw GdaException(error_message.str().c_str());
    }

    OGRSpatialReference *poOutputSRS = spatial_ref;

    // PRECISION is for database e.g. MSSQL
    // LAUNDER is for database: rename desired field name
    char* papszLCO[50] = {"OVERWRITE=yes", "PRECISION=no", "LAUNDER=yes"};

    OGRLayer *poDstLayer = ds->CreateLayer(layer_name.mb_str(),
                                           poOutputSRS, eGType, papszLCO);

    if( poDstLayer == NULL ) {
        error_message << "Can't write/create layer \"" << layer_name.mb_str() << "\". \n\nDetails: Attemp to write a readonly database, or "
                      << CPLGetLastErrorMsg();
		throw GdaException(error_message.str().c_str());
    }

    map<wxString, pair<int, int> >::iterator field_it;

    // create fields using TableInterface:table
    if ( table != NULL ) {

        std::vector<int> col_id_map;
        table->FillColIdMap(col_id_map);

        for (int id=0; id < table->GetNumberCols(); id++) {

            bool is_time_var = table->IsColTimeVariant(id);
            int time_steps = is_time_var ? table->GetTimeSteps() : 1;

            for ( int t=0; t < time_steps; t++ ) {

                wxString fname = table->GetColName(col_id_map[id], t);
                if (fname.empty()) {
                    error_message << "Can't create layer \"" << layer_name.mb_str()
                    << "\" with empty field name.";
                    throw GdaException(error_message.str().c_str());
                }

                OGRFieldType ogr_type;
                int ogr_fwidth = table->GetColLength(col_id_map[id], t);
                int ogr_fprecision = table->GetColDecimals(col_id_map[id], t);
                GdaConst::FieldType ftype = table->GetColType(col_id_map[id], t);
                if (ftype == GdaConst::string_type){
                    ogr_type = OFTString;
                } else if (ftype == GdaConst::long64_type){
                    ogr_type = OFTInteger64;
                } else if (ftype == GdaConst::double_type){
                    ogr_type = OFTReal;
                } else if (ftype == GdaConst::date_type){
                    ogr_type = OFTDate;
                } else if (ftype == GdaConst::time_type){
                    ogr_type = OFTTime;
                } else if (ftype == GdaConst::datetime_type) {
                    ogr_type = OFTDateTime;
                } else {
                    ogr_type = OFTString;
                }
                OGRFieldDefn oField(fname, ogr_type);
                oField.SetWidth(ogr_fwidth);
                if ( ogr_fprecision>0 ) {
                    oField.SetPrecision(ogr_fprecision);
                }
                if( poDstLayer->CreateField( &oField ) != OGRERR_NONE ) {
                    error_message << "Creating a field failed.\n\nDetails:" << CPLGetLastErrorMsg();
                    throw GdaException(error_message.str().c_str());
                }
            }
        }
    }
    OGRLayerProxy* layer =  new OGRLayerProxy(poDstLayer, ds_type, eGType);

    layer_pool[layer_name] = layer;
    return layer;
}

max_stars_repo_name: chenyoujie/GeoDa

max_issues_repo_name: chenyoujie/GeoDa

max_forks_repo_name: chenyoujie/GeoDa


text:
/******************************************************************************
 * Author:   Laurent Kneip                                                    *
 * Contact:  kneip.laurent@gmail.com                                          *
 * License:  Copyright (c) 2013 Laurent Kneip, ANU. All rights reserved.      *
 *                                                                            *
 * Redistribution and use in source and binary forms, with or without         *
 * modification, are permitted provided that the following conditions         *
 * are met:                                                                   *
 * * Redistributions of source code must retain the above copyright           *
 *   notice, this list of conditions and the following disclaimer.            *
 * * Redistributions in binary form must reproduce the above copyright        *
 *   notice, this list of conditions and the following disclaimer in the      *
 *   documentation and/or other materials provided with the distribution.     *
 * * Neither the name of ANU nor the names of its contributors may be         *
 *   used to endorse or promote products derived from this software without   *
 *   specific prior written permission.                                       *
 *                                                                            *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"*
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE  *
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE *
 * ARE DISCLAIMED. IN NO EVENT SHALL ANU OR THE CONTRIBUTORS BE LIABLE        *
 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL *
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR *
 * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER *
 * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT         *
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY  *
 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF     *
 * SUCH DAMAGE.                                                               *
 ******************************************************************************/

#include <opengv/triangulation/methods.hpp>
#include <Eigen/Eigenvalues>

opengv::point_t
opengv::triangulation::triangulate(
    const relative_pose::RelativeAdapterBase & adapter,
    size_t index )
{
  translation_t t12 = adapter.gett12();
  rotation_t R12 = adapter.getR12();
  Eigen::Matrix<double,3,4> P1 = Eigen::Matrix<double,3,4>::Zero();
  P1.block<3,3>(0,0) = Eigen::Matrix3d::Identity();
  Eigen::Matrix<double,3,4> P2 = Eigen::Matrix<double,3,4>::Zero();
  P2.block<3,3>(0,0) = R12.transpose();
  P2.block<3,1>(0,3) = -R12.transpose()*t12;
  bearingVector_t f1 = adapter.getBearingVector1(index);
  bearingVector_t f2 = adapter.getBearingVector2(index);

  Eigen::MatrixXd A(4,4);
  A.row(0) = f1[0] * P1.row(2) - f1[2] * P1.row(0);
  A.row(1) = f1[1] * P1.row(2) - f1[2] * P1.row(1);
  A.row(2) = f2[0] * P2.row(2) - f2[2] * P2.row(0);
  A.row(3) = f2[1] * P2.row(2) - f2[2] * P2.row(1);

  Eigen::JacobiSVD< Eigen::MatrixXd > mySVD(A, Eigen::ComputeFullV );
  point_t worldPoint;
  worldPoint[0] = mySVD.matrixV()(0,3);
  worldPoint[1] = mySVD.matrixV()(1,3);
  worldPoint[2] = mySVD.matrixV()(2,3);
  worldPoint = worldPoint / mySVD.matrixV()(3,3);

  return worldPoint;
};

opengv::point_t
opengv::triangulation::triangulate(bearingVector_t const & f1, bearingVector_t const &  f2,
    translation_t const &  t12, rotation_t const &  R12)
{
  Eigen::Matrix<double,3,4> P1 = Eigen::Matrix<double,3,4>::Zero();
  P1.block<3,3>(0,0) = Eigen::Matrix3d::Identity();
  Eigen::Matrix<double,3,4> P2 = Eigen::Matrix<double,3,4>::Zero();
  P2.block<3,3>(0,0) = R12.transpose();
  P2.block<3,1>(0,3) = -R12.transpose()*t12;

  Eigen::MatrixXd A(4,4);
  A.row(0) = f1[0] * P1.row(2) - f1[2] * P1.row(0);
  A.row(1) = f1[1] * P1.row(2) - f1[2] * P1.row(1);
  A.row(2) = f2[0] * P2.row(2) - f2[2] * P2.row(0);
  A.row(3) = f2[1] * P2.row(2) - f2[2] * P2.row(1);

  Eigen::JacobiSVD< Eigen::MatrixXd > mySVD(A, Eigen::ComputeFullV );
  point_t worldPoint;
  worldPoint[0] = mySVD.matrixV()(0,3);
  worldPoint[1] = mySVD.matrixV()(1,3);
  worldPoint[2] = mySVD.matrixV()(2,3);
  worldPoint = worldPoint / mySVD.matrixV()(3,3);

  return worldPoint;
};

opengv::point_t
opengv::triangulation::triangulate2(
    const relative_pose::RelativeAdapterBase & adapter,
    size_t index )
{
  translation_t t12 = adapter.gett12();
  rotation_t R12 = adapter.getR12();
  bearingVector_t f1 = adapter.getBearingVector1(index);
  bearingVector_t f2 = adapter.getBearingVector2(index);

  bearingVector_t f2_unrotated = R12 * f2;
  Eigen::Vector2d b;
  b[0] = t12.dot(f1);
  b[1] = t12.dot(f2_unrotated);
  Eigen::Matrix2d A;
  A(0,0) = f1.dot(f1);
  A(1,0) = f1.dot(f2_unrotated);
  A(0,1) = -A(1,0);
  A(1,1) = -f2_unrotated.dot(f2_unrotated);
  Eigen::Vector2d lambda = A.inverse() * b;
  Eigen::Vector3d xm = lambda[0] * f1;
  Eigen::Vector3d xn = t12 + lambda[1] * f2_unrotated;
  point_t point = ( xm + xn )/2;
  return point;
};