text:
// see also <http://web.mit.edu/fwtools_v3.1.0/www/H5.intro.html>

#include <string>
#include <memory>
#include <Eigen/Dense>
#include <H5Cpp.h>

#include <iostream>

// Auxiliary class to write a 2d table to HDF5 database
class HDF5TableWriter
{
public:
    HDF5TableWriter(const H5::Group& datagroup, const H5::DataType& dtype,
                    const std::size_t n_rows, const std::size_t n_cols,
                    const std::string& dataset_name):
        _dtype{dtype}
        {
            // create the table as a DataSet of shape (n_rows, n_cols)
            const hsize_t dims[_rank] = {n_rows, n_cols};
            _fspace = H5::DataSpace(_rank, dims);
            _dataset = datagroup.createDataSet(dataset_name, _dtype, _fspace);
            // hyperslab from data in file (a single row), shape = (1, n_cols)
            _stride[0] = _block[0] = 1;
            _stride[1] = _block[1] = n_cols;
            // DataSpace for the data in memory (a single row)
            const hsize_t mdims[] = {n_cols};
            _mspace = H5::DataSpace(1, mdims);
            std::cout << "HDF5TableWriter: DataSet '" << _dataset.getObjName() << "'"
                      << "(" << n_rows << "," << n_cols << ")" << std::endl;
        }

    ~HDF5TableWriter()
        {
            _fspace.selectNone();
            std::cout << "HDF5TableWriter: Done." << std::endl;
        }

    // write a given row to the table
    void writeRow(const std::size_t row_idx, const void* const row_dataptr)
        {
            // move the start position of the slab to the beginning of the row
            _start[0] = static_cast<hsize_t>(row_idx);
            _fspace.selectHyperslab(H5S_SELECT_SET, _count, _start, _stride, _block);
            _dataset.write(row_dataptr, _dtype, _mspace, _fspace);
            // std::cout << "HDF5TableWriter: Wrote row " << row_idx << std::endl;
        }

private:
    H5::DataSet _dataset;
    const H5::DataType _dtype;
    // DataSpace for the data in file; shape = (n_rows, n_cols)
    H5::DataSpace _fspace;
    // DataSpace for the data in memory (a single row)
    H5::DataSpace _mspace;
    static constexpr hsize_t _rank = 2;
    // hyperslab configuration
    hsize_t _start[2] = {0, 0};
    hsize_t _stride[2];
    hsize_t _block[2];
    const hsize_t _count[2] = {1, 1};
};

// Auxiliary class to read a 2d table from a HDF5 database
class HDF5TableReader
{
public:

    // initialization for reading
    HDF5TableReader(const H5::DataSet& dataset):
        _dataset{&dataset},
        _dtype{dataset.getDataType()},
        _fspace{dataset.getSpace()}
        {
            // obtain DataSet properties
            // expects that rank = 2; ie. `_fspace.getSimpleExtentNdims() == 2`
            hsize_t fdims[2];
            _fspace.getSimpleExtentDims(fdims);
            const hsize_t n_rows = fdims[0], n_cols = fdims[1];
            // hyperslab from data in file (a single row), shape = (1, n_cols)
            _stride[0] = _block[0] = 1;
            _stride[1] = _block[1] = n_cols;
            // DataSpace for the data in memory (a single row)
            const hsize_t mdims[] = {n_cols};
            _mspace = H5::DataSpace(1, mdims);
            std::cout << "HDF5TableReader: DataSet '" << dataset.getObjName() << "'"
                      << "(" << n_rows << "," << n_cols << ")" << std::endl;
        }

    ~HDF5TableReader()
        {
            _fspace.selectNone();
            std::cout << "HDF5TableReader: Done." << std::endl;
        }

    // read a given row from the table
    void readRow(const std::size_t row_idx, void* const row_dataptr)
        {
            // move the start position of the slab to the beginning of the row
            _start[0] = static_cast<hsize_t>(row_idx);
            _fspace.selectHyperslab(H5S_SELECT_SET, _count, _start, _stride, _block);
            _dataset->read(row_dataptr, _dtype, _mspace, _fspace);
            // std::cout << "HDF5TableReader: Wrote row " << row_idx << std::endl;
        }

private:
    const H5::DataSet* const _dataset;
    const H5::DataType _dtype;
    // DataSpace for the data in file; shape = (n_rows, n_cols)
    H5::DataSpace _fspace;
    // DataSpace for the data in memory (a single row)
    H5::DataSpace _mspace;
    // hyperslab configuration
    static constexpr hsize_t _rank = 2;
    hsize_t _start[2] = {0, 0};
    hsize_t _stride[2];
    hsize_t _block[2];
    const hsize_t _count[2] = {1, 1};
};

using namespace H5;
const H5std_string FILE_NAME("states.h5");
const H5std_string DATASET_NAME("States");
PredType dType {PredType::NATIVE_DOUBLE};
typedef double data_t;

const int FSPACE_RANK = 2; // Dataset rank as it is stored in the file
const int FSPACE_DIM1 = 5; // Dimension sizes of the dataset as it is
const int FSPACE_DIM2 = 3; // stored in the file
const int N_STATES = FSPACE_DIM1; // Dimension sizes of the dataset as it is

const int MSPACE_RANK = 1; // Rank of dataset in memory
const int MSPACE_DIM = FSPACE_DIM1 * FSPACE_DIM2; // Dataset size in memory

void readfile();
void writefile();
void testEigen();

using std::cout;
using std::endl;

int main()
{
    cout << "> Test Eigen..." << endl;
    testEigen();

    cout << "> Write data to " << FILE_NAME << "..." << endl;
    writefile();

    cout << "> Read data from " << FILE_NAME << "..." << endl;
    readfile();

    return 0;
}

void testEigen()
{
    Eigen::MatrixXd m(2,2);
    m(0,0) = 3;
    m(1,0) = 2.5;
    m(0,1) = -1;
    m(1,1) = m(1,0) + m(0,1);
    cout << "MatrixXd m:\n" << m << endl;

    Eigen::Matrix2d m2;
    m2(0,0) = 3;
    m2(1,0) = 2.5;
    m2(0,1) = -1;
    m2(1,1) = m2(1,0) + m2(0,1);
    cout << "Matrix2d m2:\n" << m2 << endl;

    Eigen::VectorXd v(2);
    v(0) = 4;
    v(1) = v(0) - 1;
    cout << "VectorXd v:\n" << v << endl;

    double* data = new double[4];
    data[0] = 9;
    data[1] = 10;
    data[2] = 11;
    data[3] = 12;

    Eigen::RowVector2d vr2(data);
    Eigen::Matrix2d m2b(data);

    cout << "vr2.data at " << vr2.data()
         << ", m2b.data at " << m2b.data()
         << ", data at " << data << endl;
    delete [] data;

    vr2(1) = 42;
    cout << "RowVectorXd vr2:\n" << vr2 << endl;
    cout << "Matrix2d m2b:\n" << m2b << endl;

    // NOTE: internally the coefficients of Eigen::Quaterniond are stored in the order [x, y, z, w]
    double qdata[] = {2, 0, 1, -3};
    Eigen::Quaterniond qt(qdata);
    double* qptr = qt.coeffs().data();
    qptr[0] = 4;

    cout << "Quaterniond qt: "
         << "w = " << qt.w() << ", "
         << "x = " << qt.x() << ", "
         << "y = " << qt.y() << ", "
         << "z = " << qt.z()
         << endl;

    cout << "Quaterniond qt.coeffs = " << qt.coeffs().data() << endl;

    //cout << "at " << qt.data() << endl;
}

void writefile0()
{
    H5File file(FILE_NAME, H5F_ACC_TRUNC);
    // Create dataspace for the dataset in the file
    hsize_t fdim[] = {FSPACE_DIM1, FSPACE_DIM2};
    DataSpace fspace(FSPACE_RANK, fdim);
    // Create dataset and write it into the file
    DataSet dataset(file.createDataSet(DATASET_NAME, dType, fspace));
    // Select hyperslab for the dataset in the file
    hsize_t start[2] = {0, 0}; // Start of hyperslab
    hsize_t stride[2] = {1, FSPACE_DIM2}; // Stride of hyperslab
    hsize_t block[2] = {1, FSPACE_DIM2};  // Block sizes
    hsize_t count[2] = {1, 1};  // Block count

    hsize_t mdim[] = {FSPACE_DIM2};  // Dimension size of the first dataset
    DataSpace mspace(MSPACE_RANK, mdim);
    // data
    const data_t vec[3] = {1, 2, 3}; // vector buffer for dset
    data_t v[3];
    for (int s = 0; s < FSPACE_DIM1; ++s) {
        for (int i = 0; i < FSPACE_DIM2; ++i)
            v[i] = vec[i] + s * 3;

        cout << "w/data[" << s << "]: "
             << v[0] << ", " << v[1] << ", " << v[2]
             << endl;

        start[0] = s; // move the beginning of the slab
        fspace.selectHyperslab(H5S_SELECT_SET, count, start, stride, block);
        dataset.write(v, dType, mspace, fspace);
    }
    // Reset the selection for the file dataspace
    fspace.selectNone();
}

void writefile()
{
    H5File file(FILE_NAME, H5F_ACC_TRUNC);
    const std::string groupName {"DataGroup"};
    H5::Group datagroup {file.createGroup(groupName)};
    // Create dataspace for the dataset in the file
    HDF5TableWriter tablewriter(datagroup, dType, FSPACE_DIM1, FSPACE_DIM2, DATASET_NAME);
    // data
    const data_t vec[3] = {1, 2, 3}; // vector buffer for dset
    data_t v[3];
    for (int s = 0; s < FSPACE_DIM1; ++s) {
        for (int i = 0; i < FSPACE_DIM2; ++i)
            v[i] = vec[i] + s * 3;

        cout << "w/data[" << s << "]: "
             << v[0] << ", " << v[1] << ", " << v[2]
             << endl;

        tablewriter.writeRow(s, v);
    }
}

void readfile0()
{
    // Open the file
    H5File file(FILE_NAME, H5F_ACC_RDONLY);
    // Open the dataset.
    DataSet dataset(file.openDataSet(DATASET_NAME));
    // Get dataspace of the dataset
    DataSpace fspace {dataset.getSpace()};
    int rank = fspace.getSimpleExtentNdims();
    hsize_t* fdims = new hsize_t[rank];
    fspace.getSimpleExtentDims(fdims);

    cout << "r/rank = " << rank << endl;
    cout << "r/dims = ";
    int d = 0;
    for (; d < rank-1; ++d)
        cout << fdims[d] << ", ";

    cout << fdims[d] << endl;
    delete [] fdims;

    // Read data into a vector
    hsize_t dsize = FSPACE_DIM1 * FSPACE_DIM2;
    hsize_t mdim[] = {dsize};
    DataSpace mspace(MSPACE_RANK, mdim);
    // data_t* data = new data_t[dsize];
    Eigen::MatrixXd mat(FSPACE_DIM2, FSPACE_DIM1);
    data_t* data = mat.data();

    dataset.read(mat.data(), dType, mspace, fspace);
    for (int s = 0; s < FSPACE_DIM1; ++s) {
        int i = s * FSPACE_DIM2;
        cout << "r/data[" << s << "]: "
             << data[i] << ", " << data[i+1] << ", " << data[i+2]
             << endl;
    }

    Eigen::Vector3d v3(data);
    cout << "Vector3d v3:\n" << v3 << endl;

    cout << "MatrixXd transpose(mat):\n" << mat.transpose() << endl;

    // delete [] data;
}

void readfile()
{
    // Open the file
    H5File file(FILE_NAME, H5F_ACC_RDONLY);
    // Open the dataset.
    H5::Group datagroup {file.openGroup("DataGroup")};
    DataSet dataset {datagroup.openDataSet(DATASET_NAME)};
    // Get dataspace of the dataset
    DataSpace fspace {dataset.getSpace()};
    int rank = fspace.getSimpleExtentNdims();
    hsize_t* fdims = new hsize_t[rank];
    fspace.getSimpleExtentDims(fdims);
    cout << "r/rank = " << rank << endl;
    cout << "r/dims = ";
    int d = 0;
    for (; d < rank-1; ++d)
        cout << fdims[d] << ", ";

    cout << fdims[d] << endl;
    delete [] fdims;

    // Create dataspace for the dataset in the file
    HDF5TableReader tablereader(dataset);

    // data_t* data = new data_t[dsize];
    Eigen::Vector3d vec;
    data_t* data = mat.data();
    for (int s = 0; s < FSPACE_DIM1; ++s) {
        tablereader.readRow(s, data);
        cout << "r/data[" << s << "]: "
             << data[0] << ", " << data[1] << ", " << data[2]
             << endl;
    }

    cout << "r/Vector3d:\n" << vec << endl;

}

max_stars_repo_name: AlQuemiste/Sourcery

max_issues_repo_name: AlQuemiste/Sourcery

max_forks_repo_name: AlQuemiste/Sourcery


text:
/*
*  Copyright 2012 Matthias Fuchs
*
*  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 "ThreadUtilities.h"

#include <stromx/runtime/ExceptionObserver.h>
#include <stromx/runtime/Thread.h>

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

using namespace boost::python;
using namespace stromx::python;
using namespace stromx::runtime;

namespace stromx
{
    namespace runtime
    {
        extern boost::thread_specific_ptr<Thread> gThread;
    }
}

namespace
{
    class OperatorExceptionInfo
    {
    public:
        OperatorExceptionInfo(const std::string & message, const std::string & name,
                              const std::string & type, const std::string & package)
          : m_message(message),
            m_name(name),
            m_type(type),
            m_package(package)
        { }

        const std::string & message() const { return m_message; }
        const std::string & name() const { return m_name; }
        const std::string & type() const { return m_type; }
        const std::string & package() const { return m_package; }

    private:
        const std::string m_message;
        const std::string m_name;
        const std::string m_type;
        const std::string m_package;
    };

    template<typename T>
    void do_release(T*)
    {
    }

    struct ExceptionObserverWrap : ExceptionObserver, wrapper<ExceptionObserver>
    {
        void observe(const Phase phase, const OperatorError & ex, const Thread* const thread) const
        {
            OperatorExceptionInfo info(ex.message(), ex.name(), ex.type(), ex.package());
            observeWrap(phase, info, boost::shared_ptr<Thread>(const_cast<Thread*>(thread), &do_release<Thread>));
        }

        void observeWrap(const Phase phase, const OperatorExceptionInfo & info,
                         boost::shared_ptr<Thread> thread) const
        {
            PyGILState_STATE state = PyGILState_Ensure();

            try
            {
                this->get_override("observe")(phase, info, thread);
            }
            catch(...)
            {
                // catch everything to make sure the GIL is released
            }

            PyGILState_Release(state);

            Thread* threadPtr = gThread.get();
            if (threadPtr && ThreadUtilities::interruptedFlag(threadPtr))
                throw Interrupt();
        }
    };
}

void exportExceptionObserver()
{
    class_<OperatorExceptionInfo>("OperatorExceptionInfo", no_init)
        .def("message", &OperatorExceptionInfo::message, return_value_policy<copy_const_reference>())
        .def("name", &OperatorExceptionInfo::name, return_value_policy<copy_const_reference>())
        .def("type", &OperatorExceptionInfo::type, return_value_policy<copy_const_reference>())
        .def("package", &OperatorExceptionInfo::package, return_value_policy<copy_const_reference>())
    ;

    scope in_ExceptionObserver =
    class_<ExceptionObserverWrap, boost::noncopyable>("ExceptionObserver")
        .def("observe", pure_virtual(&ExceptionObserverWrap::observeWrap))
    ;

    enum_<ExceptionObserver::Phase>("Phase")
        .value("EXECUTION", ExceptionObserver::EXECUTION)
        .value("ACTIVATION", ExceptionObserver::ACTIVATION)
        .value("DEACTIVATION", ExceptionObserver::DEACTIVATION)
        .value("INTERRUPT", ExceptionObserver::INTERRUPT)
        .value("INITIALIZATION", ExceptionObserver::INITIALIZATION)
        .value("DEINITIALIZATION", ExceptionObserver::DEINITIALIZATION)
        .value("PARAMETER_ACCESS", ExceptionObserver::PARAMETER_ACCESS)
        ;
}

ext: cpp

max_stars_repo_name: roteroktober/stromx

max_issues_repo_name: roteroktober/stromx

max_forks_repo_name: roteroktober/stromx


text:
#ifndef BOOST_TYPE_TRAITS_COPY_CV_HPP_INCLUDED
#define BOOST_TYPE_TRAITS_COPY_CV_HPP_INCLUDED

//
//  Copyright 2015 Peter Dimov
//
//  Distributed under the Boost Software License, Version 1.0.
//  See accompanying file LICENSE_1_0.txt or copy at
//  http://www.boost.org/LICENSE_1_0.txt
//

#include <boost/type_traits/is_const.hpp>
#include <boost/type_traits/is_volatile.hpp>
#include <boost/type_traits/add_const.hpp>
#include <boost/type_traits/add_volatile.hpp>
#include <boost/type_traits/conditional.hpp>

namespace lslboost
{

template<class T, class U> struct copy_cv
{
private:

    typedef typename lslboost::conditional<lslboost::is_const<U>::value, typename lslboost::add_const<T>::type, T>::type CT;

public:

    typedef typename lslboost::conditional<lslboost::is_volatile<U>::value, typename lslboost::add_volatile<CT>::type, CT>::type type;
};

#if !defined(BOOST_NO_CXX11_TEMPLATE_ALIASES)

   template <class T, class U> using copy_cv_t = typename copy_cv<T, U>::type;

#endif

} // namespace lslboost

#endif // #ifndef BOOST_TYPE_TRAITS_COPY_CV_HPP_INCLUDED

ext: hpp

max_stars_repo_name: samuelpowell/liblsl

max_issues_repo_name: samuelpowell/liblsl

max_forks_repo_name: samuelpowell/liblsl


text:
#include <gtest/gtest.h>
#include <boost/geometry/algorithms/perimeter.hpp>
#include <random>
#include "lanelet2_core/geometry/Polygon.h"
#include "lanelet2_core/primitives/CompoundPolygon.h"
#include "lanelet2_core/primitives/Polygon.h"

using namespace lanelet;
template <typename T>
T toPolygon(const Polygon3d& p) {
  return T(p);
}
template <>
Polygon2d toPolygon<Polygon2d>(const Polygon3d& p) {
  return utils::to2D(p);
}
template <>
ConstPolygon2d toPolygon<ConstPolygon2d>(const Polygon3d& p) {
  return utils::to2D(p);
}
template <>
BasicPolygon2d toPolygon<BasicPolygon2d>(const Polygon3d& p) {
  return utils::to2D(p).basicPolygon();
}
template <>
BasicPolygon3d toPolygon<BasicPolygon3d>(const Polygon3d& p) {
  return p.basicPolygon();
}

class PolygonPoints : public ::testing::Test {
 public:
  PolygonPoints() {
    Id id{1};
    p11 = Point3d(++id, 0., 0., 0.);
    p12 = Point3d(++id, 1., 2., 1.);
    p13 = Point3d(++id, 1., 0., 0.);
    p21 = Point3d(++id, 2., 0., 0.);
    p22 = Point3d(++id, 3., 1., 0.);
    p23 = Point3d(++id, 3., 0., 0.);
    p31 = Point3d(++id, 1., 0., 2.);
    p32 = Point3d(++id, 1., 1., 2.);
    p33 = Point3d(++id, 2., 1., 2.);
    p34 = Point3d(++id, 2., 0., 2.);
    /*
     *      p42    X
     *           /   \
     *         /   X   \
     *       / -/ p44 \- \
     * p41 X/            \X p43
     */
    p41 = Point3d(++id, 1.5, 1.5, 2.);
    p42 = Point3d(++id, 1.5, 0.5, 2.);
  }

  Point3d p11, p12, p13;
  Point3d p21, p22, p23;
  Point3d p31, p32, p33, p34;
  Point3d p41, p42;
};

template <typename T>
class PolygonTypeTest : public PolygonPoints {
 public:
  using PolygonT = T;
  PolygonTypeTest() {
    Id id{20};
    AttributeMap poly1Attrs{{AttributeNamesString::Type, AttributeValueString::Curbstone}};
    poly1 = toPolygon<T>(Polygon3d{++id, {p11, p12, p13}, poly1Attrs});
    poly2 = toPolygon<T>(Polygon3d{++id, {p21, p22, p23}});
    poly3 = toPolygon<T>(Polygon3d{++id, {p31, p32, p33, p34}});
    Polygon3d temp{++id, {p31, p41, p34, p42}};
    simpleStar = toPolygon<T>(temp);
    subdivide(temp, 2, ++id);
    fancyStar = toPolygon<T>(temp);
  }

  PolygonT poly1, poly2, poly3, fancyStar, simpleStar;  // NOLINT

 private:
  void randomSubdivide(Polygon3d& poly, const size_t after, const int nNew, Id id) const {
    BasicPoint3d delta =
        (utils::toBasicPoint(poly[(after + 1) % poly.size()]) - utils::toBasicPoint(poly[after])) / (2 * nNew + 1);
    std::vector<Point3d> points;
    points.reserve(size_t(nNew));
    for (int i = 0; i < nNew; ++i) {
      points.emplace_back(Point3d(++id, utils::toBasicPoint(poly[after]) + (2 * double(i) + randomNum_() + 1) * delta));
    }
    Polygon3d newLs(++id, points);
    poly.insert(poly.begin() + long((after + 1) % poly.size()), newLs.begin(), newLs.end());
  }
  void subdivide(Polygon3d& poly, const int n, Id id) {
    auto initSize = poly.size();
    for (size_t i = 0; i < initSize; ++i) {
      randomSubdivide(poly, (n + 1) * i, n, id);
    }
  }
  std::function<double(void)> randomNum_ = [distr = std::uniform_real_distribution<double>(-0.5, 0.5),
                                            gen = std::mt19937(133769420)]() mutable { return distr(gen); };
};

template <typename PolygonT>
PolygonT composePolygon(std::initializer_list<ConstLineString3d> list) {
  return PolygonT(list);
}

template <typename T>
class CompoundPolygonTypeTest : public PolygonPoints {
 protected:
  using PolygonT = T;
  CompoundPolygonTypeTest() {
    Id id{10};
    ConstLineString3d tempLs11{++id, {p11, p12, p13}};
    ConstLineString3d tempLs21{++id, {p21, p22}};
    ConstLineString3d tempLs22{++id, {p22, p23}};
    ConstLineString3d tempLs31{++id, {p31, p32}};
    ConstLineString3d tempLs32{++id, {p33, p34}};
    ConstLineString3d tempStar1{++id, {p31, p41, p34}};
    ConstLineString3d tempStar2{++id, {p34, p42}};

    poly1 = PolygonT({tempLs11});
    poly2 = PolygonT({tempLs21, tempLs22});
    poly3 = PolygonT({tempLs31, tempLs32});
    simpleStar = PolygonT({tempStar1, tempStar2});
    fancyStar = simpleStar;
  }

 public:
  PolygonT poly1, poly2, poly3, fancyStar, simpleStar;
};

template <typename T>
auto getZ(const T& p) -> std::enable_if_t<!traits::is2D<T>(), double> {
  return p.z();
}
template <typename T>
auto getZ(const T & /*p*/) -> std::enable_if_t<traits::is2D<T>(), double> {
  return 0.;
}

template <>
class PolygonTypeTest<CompoundPolygon2d> : public CompoundPolygonTypeTest<CompoundPolygon2d> {};

template <>
class PolygonTypeTest<CompoundPolygon3d> : public CompoundPolygonTypeTest<CompoundPolygon3d> {};

template <>
class PolygonTypeTest<CompoundHybridPolygon2d> : public CompoundPolygonTypeTest<CompoundHybridPolygon2d> {};

template <>
class PolygonTypeTest<CompoundHybridPolygon3d> : public CompoundPolygonTypeTest<CompoundHybridPolygon3d> {};

template <typename T>
class AllPolygonsTest : public PolygonTypeTest<T> {};

template <typename T>
class NormalPolygonsTest : public PolygonTypeTest<T> {};

template <typename T>
class MutablePolygonsTest : public PolygonTypeTest<T> {};

template <typename T>
class PrimitivePolygonsTest : public PolygonTypeTest<T> {};

template <typename T>
class NonHybridPolygonsTest : public PolygonTypeTest<T> {};

template <typename T>
class HybridPolygonsTest : public PolygonTypeTest<T> {};

template <typename T>
class HybridPolygonsTwoDTest : public PolygonTypeTest<T> {};

template <typename T>
class ThreeDPolygonsTest : public PolygonTypeTest<T> {};

template <typename T>
class TwoDPolygonsTest : public PolygonTypeTest<T> {};

template <typename T>
class ThreeDAndBasicPolygonsTest : public PolygonTypeTest<T> {};

template <typename T>
class TwoDAndBasicPolygonsTest : public PolygonTypeTest<T> {};

using AllPolygons =
    testing::Types<Polygon2d, Polygon3d, ConstPolygon2d, ConstPolygon3d, ConstHybridPolygon2d, ConstHybridPolygon3d,
                   CompoundPolygon2d, CompoundPolygon3d, CompoundHybridPolygon2d, CompoundHybridPolygon3d>;
using NormalPolygons = testing::Types<Polygon2d, Polygon3d, ConstPolygon2d, ConstPolygon3d>;
using ThreeDPolygons =
    testing::Types<Polygon3d, ConstPolygon3d, ConstHybridPolygon3d, CompoundPolygon3d, CompoundHybridPolygon3d>;
using TwoDPolygons =
    testing::Types<Polygon2d, ConstPolygon2d, ConstHybridPolygon2d, CompoundPolygon2d, CompoundHybridPolygon2d>;
using ThreeDAndBasicPolygons = testing::Types<BasicPolygon3d, Polygon3d, ConstPolygon3d, ConstHybridPolygon3d,
                                              CompoundPolygon3d, CompoundHybridPolygon3d>;
using TwoDAndBasicPolygons = testing::Types<BasicPolygon2d, Polygon2d, ConstPolygon2d, ConstHybridPolygon2d,
                                            CompoundPolygon2d, CompoundHybridPolygon2d>;
using MutablePolygons = testing::Types<Polygon2d, Polygon3d>;
using PrimitivePolygons =
    testing::Types<Polygon2d, Polygon3d, ConstPolygon2d, ConstPolygon3d, ConstHybridPolygon2d, ConstHybridPolygon3d>;
using NonHybridPolygons =
    testing::Types<Polygon2d, Polygon3d, ConstPolygon2d, ConstPolygon3d, CompoundPolygon2d, CompoundPolygon3d>;
using HybridPolygons =
    testing::Types<ConstHybridPolygon2d, ConstHybridPolygon3d, CompoundHybridPolygon2d, CompoundHybridPolygon3d>;
using HybridPolygonsTwoD = testing::Types<ConstHybridPolygon2d, CompoundHybridPolygon2d>;

TYPED_TEST_CASE(AllPolygonsTest, AllPolygons);
TYPED_TEST_CASE(TwoDPolygonsTest, TwoDPolygons);
TYPED_TEST_CASE(ThreeDPolygonsTest, ThreeDPolygons);
TYPED_TEST_CASE(TwoDAndBasicPolygonsTest, TwoDAndBasicPolygons);
TYPED_TEST_CASE(ThreeDAndBasicPolygonsTest, ThreeDAndBasicPolygons);
TYPED_TEST_CASE(NormalPolygonsTest, NormalPolygons);
TYPED_TEST_CASE(MutablePolygonsTest, MutablePolygons);
TYPED_TEST_CASE(PrimitivePolygonsTest, PrimitivePolygons);
TYPED_TEST_CASE(NonHybridPolygonsTest, NonHybridPolygons);
TYPED_TEST_CASE(HybridPolygonsTest, HybridPolygons);
TYPED_TEST_CASE(HybridPolygonsTwoDTest, HybridPolygonsTwoD);

TYPED_TEST(MutablePolygonsTest, id) {  // NOLINT
  this->poly1.setId(100);
  EXPECT_EQ(100, this->poly1.id());
}

TYPED_TEST(MutablePolygonsTest, readAttributes) {  // NOLINT
  EXPECT_TRUE(this->poly1.hasAttribute(AttributeName::Type));
  EXPECT_TRUE(this->poly1.hasAttribute(AttributeNamesString::Type));
  EXPECT_EQ(this->poly1.attribute(AttributeName::Type), AttributeValueString::Curbstone);
  EXPECT_EQ(this->poly1.attribute(AttributeNamesString::Type), AttributeValueString::Curbstone);
}

TYPED_TEST(TwoDAndBasicPolygonsTest, bounds2d) {  // NOLINT
  BoundingBox2d bbox = geometry::boundingBox2d(this->poly2);
  EXPECT_EQ(bbox.min().x(), 2);
  EXPECT_EQ(bbox.min().y(), 0);
  EXPECT_EQ(bbox.max().x(), 3);
  EXPECT_EQ(bbox.max().y(), 1);
}

TYPED_TEST(ThreeDAndBasicPolygonsTest, bounds3d) {  // NOLINT
  BoundingBox3d bbox = geometry::boundingBox3d(this->poly1);
  EXPECT_EQ(bbox.min().x(), 0);
  EXPECT_EQ(bbox.min().y(), 0);
  EXPECT_EQ(bbox.min().z(), 0);
  EXPECT_EQ(bbox.max().x(), 1);
  EXPECT_EQ(bbox.max().y(), 2);
  EXPECT_EQ(bbox.max().z(), 1);
}

TYPED_TEST(HybridPolygonsTwoDTest, distance2d) {  // NOLINT
  EXPECT_DOUBLE_EQ(geometry::distance(this->poly1, this->poly3), 0.);
  EXPECT_DOUBLE_EQ(geometry::distance(this->poly1, this->poly2), 1.);
}

TYPED_TEST(HybridPolygonsTwoDTest, distancePoint2d) {  // NOLINT
  EXPECT_DOUBLE_EQ(geometry::distance(this->poly1, BasicPoint2d(2, 1)), 1.);
}

TYPED_TEST(HybridPolygonsTwoDTest, area) {  // NOLINT
  auto a = geometry::area(this->poly1);
  EXPECT_DOUBLE_EQ(a, 1.);
}

TYPED_TEST(HybridPolygonsTwoDTest, centroid) {  // NOLINT
  BasicPoint2d p{0, 0};
  boost::geometry::centroid(this->poly3, p);
  EXPECT_DOUBLE_EQ(p.x(), 1.5);
  EXPECT_DOUBLE_EQ(p.y(), 0.5);
}

TYPED_TEST(AllPolygonsTest, perimeter) {  // NOLINT
  auto p = boost::geometry::perimeter(this->poly3);
  EXPECT_DOUBLE_EQ(p, 4);
}

TYPED_TEST(TwoDPolygonsTest, toBasicPolygon) {  // NOLINT
  auto pBasic = this->poly3.basicPolygon();
  EXPECT_EQ(4, boost::geometry::perimeter(pBasic));
  EXPECT_EQ(4ul, pBasic.size());
}

inline auto crossProd(const Eigen::Matrix<double, 2, 1>& p1, const Eigen::Matrix<double, 2, 1>& p2) {
  return BasicPoint3d(p1.x(), p1.y(), 0.).cross(BasicPoint3d(p2.x(), p2.y(), 0.)).eval();
}

bool isConnectionConvex(const BasicPoint2d& seg1, const BasicPoint2d& seg2,
                        const double eps = 4 * std::numeric_limits<double>::epsilon()) {
  return crossProd(seg1.normalized(), seg2.normalized()).z() <= eps;
}

bool isConvex(const BasicPolygon2d& poly) {
  for (size_t i = 2; i < poly.size(); ++i) {
    if (!isConnectionConvex(poly.at(i - 1) - poly.at(i - 2), poly.at(i) - poly.at(i - 1))) {
      return false;
    }
  }
  return (isConnectionConvex(poly.back() - poly.at(poly.size() - 2), poly.front() - poly.back()) &&
          isConnectionConvex(poly.front() - poly.back(), poly.at(1) - poly.front()));
}

void checkPartitionConsistency(const BasicPolygon2d& poly, const BasicPolygons2d& parts) {
  double areaSum{0.};
  for (auto i = 0ul; i < parts.size(); ++i) {
    areaSum += boost::geometry::area(parts.at(i));
    for (auto j = i + 1; j < parts.size(); ++j) {
      BasicPolygon2d intersection;
      boost::geometry::intersection(parts.at(i), parts.at(j), intersection);
      EXPECT_DOUBLE_EQ(boost::geometry::area(intersection), 0.);
    }
    for (const auto& p : parts.at(i)) {
      Eigen::Matrix<double, 2, 1> pCopy(p.x(), p.y());
      EXPECT_DOUBLE_EQ(boost::geometry::distance(pCopy, poly), 0.);
    }
  }
  EXPECT_DOUBLE_EQ(areaSum, boost::geometry::area(poly));
}

TYPED_TEST(TwoDPolygonsTest, convexPartition) {
  auto t1 = lanelet::geometry::convexPartition(this->poly3);
  EXPECT_EQ(t1.size(), 1ul);
  EXPECT_TRUE(isConvex(t1.front()));
  checkPartitionConsistency(BasicPolygon2d(this->poly3.basicBegin(), this->poly3.basicEnd()), t1);
  auto t2 = lanelet::geometry::convexPartition(this->simpleStar);
  EXPECT_EQ(t2.size(), 2ul);
  for (const auto& poly : t2) {
    EXPECT_TRUE(isConvex(poly));
  }
  checkPartitionConsistency(BasicPolygon2d(this->simpleStar.basicBegin(), this->simpleStar.basicEnd()), t2);
  auto t3 = lanelet::geometry::convexPartition(this->fancyStar);
  EXPECT_EQ(t3.size(), 2ul);
  for (const auto& poly : t3) {
    EXPECT_TRUE(isConvex(poly));
  }
  checkPartitionConsistency(BasicPolygon2d(this->fancyStar.basicBegin(), this->fancyStar.basicEnd()), t3);
}

TYPED_TEST(TwoDAndBasicPolygonsTest, triangulate) {
  auto isIn = [](const geometry::IndexedTriangle& p, const size_t idx) {
    return std::find(p.begin(), p.end(), idx) != p.end();
  };
  auto res = lanelet::geometry::triangulate(this->poly3);
  ASSERT_EQ(res.size(), 2ul);
  EXPECT_EQ(res.front().size(), 3ul);
  EXPECT_EQ(res.back().size(), 3ul);
  const auto& t1 = res.front();
  const auto& t2 = res.back();
  EXPECT_TRUE((isIn(t1, 1) && isIn(t1, 3) && isIn(t2, 1) && isIn(t2, 3)) ||
              (isIn(t1, 0) && isIn(t1, 2) && isIn(t2, 0) && isIn(t2, 2)));
}


text: #include <boost/mpl/aux_/preprocessed/bcc/full_lambda.hpp>

max_stars_repo_name: miathedev/BoostForArduino

max_issues_repo_name: miathedev/BoostForArduino

max_forks_repo_name: miathedev/BoostForArduino


text:
// The Reactive C++ Toolbox.
// Copyright (C) 2013-2019 Swirly Cloud Limited
// Copyright (C) 2021 Reactive Markets Limited
//
// 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 "IntTypes.hpp"

#include <boost/test/unit_test.hpp>

#include <boost/lexical_cast.hpp>

using namespace boost;
using namespace std;
using namespace toolbox;

namespace {

struct TestTag : Int32Policy {
};
using Test = IntWrapper<TestTag>;

constexpr Test operator""_test(unsigned long long val) noexcept
{
    return Test{val};
}

} // namespace

BOOST_AUTO_TEST_SUITE(IntTypesSuite)

BOOST_AUTO_TEST_CASE(IntAddAssignCase)
{
    auto x = 5_test;
    BOOST_TEST((x += 3_test) == 8_test);
    BOOST_TEST(x == 8_test);
}

BOOST_AUTO_TEST_CASE(IntSubAssignCase)
{
    auto x = 5_test;
    BOOST_TEST((x -= 3_test) == 2_test);
    BOOST_TEST(x == 2_test);
}

BOOST_AUTO_TEST_CASE(IntMulAssignCase)
{
    auto x = 5_test;
    BOOST_TEST((x *= 3_test) == 15_test);
    BOOST_TEST(x == 15_test);
}

BOOST_AUTO_TEST_CASE(IntDivAssignCase)
{
    auto x = 15_test;
    BOOST_TEST((x /= 3_test) == 5_test);
    BOOST_TEST(x == 5_test);
}

BOOST_AUTO_TEST_CASE(IntModAssignCase)
{
    auto x = 5_test;
    BOOST_TEST((x %= 3_test) == 2_test);
    BOOST_TEST(x == 2_test);
}

BOOST_AUTO_TEST_CASE(IntBitwiseAndAssignCase)
{
    // 11100
    // 00111
    // 00100
    auto x = 28_test;
    BOOST_TEST((x &= 7_test) == 4_test);
    BOOST_TEST(x == 4_test);
}

BOOST_AUTO_TEST_CASE(IntBitwiseOrAssignCase)
{
    // 11100
    // 00111
    // 11111
    auto x = 28_test;
    BOOST_TEST((x |= 7_test) == 31_test);
    BOOST_TEST(x == 31_test);
}

BOOST_AUTO_TEST_CASE(IntBitwiseXorAssignCase)
{
    // 11100
    // 00111
    // 11011
    auto x = 28_test;
    BOOST_TEST((x ^= 7_test) == 27_test);
    BOOST_TEST(x == 27_test);
}

BOOST_AUTO_TEST_CASE(IntLeftShiftAssignCase)
{
    // 00111
    // 11100
    auto x = 7_test;
    BOOST_TEST((x <<= 2_test) == 28_test);
    BOOST_TEST(x == 28_test);
}

BOOST_AUTO_TEST_CASE(IntRightShiftAssignCase)
{
    // 11100
    // 00111
    auto x = 28_test;
    BOOST_TEST((x >>= 2_test) == 7_test);
    BOOST_TEST(x == 7_test);
}

BOOST_AUTO_TEST_CASE(IntPreIncCase)
{
    auto x = 5_test;
    BOOST_TEST(++x == 6_test);
    BOOST_TEST(x == 6_test);
}

BOOST_AUTO_TEST_CASE(IntPreDecCase)
{
    auto x = 5_test;
    BOOST_TEST(--x == 4_test);
    BOOST_TEST(x == 4_test);
}

BOOST_AUTO_TEST_CASE(IntPostIncCase)
{
    auto x = 5_test;
    BOOST_TEST(x++ == 5_test);
    BOOST_TEST(x == 6_test);
}

BOOST_AUTO_TEST_CASE(IntPostDecCase)
{
    auto x = 5_test;
    BOOST_TEST(x-- == 5_test);
    BOOST_TEST(x == 4_test);
}

BOOST_AUTO_TEST_CASE(IntUnaryPlusCase)
{
    constexpr auto x = 5_test;
    BOOST_TEST(+x == 5_test);
}

BOOST_AUTO_TEST_CASE(IntUnaryMinusCase)
{
    constexpr auto x = 5_test;
    BOOST_TEST(-x == -5_test);
}

BOOST_AUTO_TEST_CASE(IntAddCase)
{
    constexpr auto x = 5_test;
    BOOST_TEST((x + 3_test) == 8_test);
}

BOOST_AUTO_TEST_CASE(IntSubCase)
{
    constexpr auto x = 5_test;
    BOOST_TEST((x - 3_test) == 2_test);
}

BOOST_AUTO_TEST_CASE(IntMulCase)
{
    constexpr auto x = 5_test;
    BOOST_TEST((x * 3_test) == 15_test);
}

BOOST_AUTO_TEST_CASE(IntDivCase)
{
    constexpr auto x = 15_test;
    BOOST_TEST(x / 3_test == 5_test);
}

BOOST_AUTO_TEST_CASE(IntModCase)
{
    constexpr auto x = 5_test;
    BOOST_TEST((x % 3_test) == 2_test);
}

BOOST_AUTO_TEST_CASE(IntBitwiseNotCase)
{
    constexpr auto x = Test{~1};
    BOOST_TEST(~x == 1_test);
}

BOOST_AUTO_TEST_CASE(IntBitwiseAndCase)
{
    // 11100
    // 00111
    // 00100
    constexpr auto x = 28_test;
    BOOST_TEST((x & 7_test) == 4_test);
}

BOOST_AUTO_TEST_CASE(IntBitwiseOrCase)
{
    // 11100
    // 00111
    // 11111
    constexpr auto x = 28_test;
    BOOST_TEST((x | 7_test) == 31_test);
}

BOOST_AUTO_TEST_CASE(IntBitwiseXorCase)
{
    // 11100
    // 00111
    // 11011
    constexpr auto x = 28_test;
    BOOST_TEST((x ^ 7_test) == 27_test);
}

BOOST_AUTO_TEST_CASE(IntLeftShiftCase)
{
    // 00111
    // 11100
    constexpr auto x = 7_test;
    BOOST_TEST((x << 2_test) == 28_test);
}

BOOST_AUTO_TEST_CASE(IntRightShiftCase)
{
    // 11100
    // 00111
    constexpr auto x = 28_test;
    BOOST_TEST((x >> 2_test) == 7_test);
}

BOOST_AUTO_TEST_CASE(IntEqualToCase)
{
    BOOST_TEST(5_test == 5_test);
}

BOOST_AUTO_TEST_CASE(IntNotEqualToCase)
{
    BOOST_TEST(5_test != 7_test);
}

BOOST_AUTO_TEST_CASE(IntLessThanCase)
{
    BOOST_TEST(5_test < 7_test);
}

BOOST_AUTO_TEST_CASE(IntGreaterThanCase)
{
    BOOST_TEST(5_test > 3_test);
}

BOOST_AUTO_TEST_CASE(IntLessThanOrEqualToCase)
{
    BOOST_TEST(5_test <= 5_test);
    BOOST_TEST(5_test <= 7_test);
}

BOOST_AUTO_TEST_CASE(IntGreaterThanOrEqualToCase)
{
    BOOST_TEST(5_test >= 5_test);
    BOOST_TEST(5_test >= 3_test);
}

BOOST_AUTO_TEST_CASE(IntInsertionCase)
{
    BOOST_TEST(lexical_cast<string>(5_test) == "5");
}

BOOST_AUTO_TEST_SUITE_END()

max_stars_repo_name: Shivix/toolbox-cpp

max_issues_repo_name: Shivix/toolbox-cpp

max_forks_repo_name: Shivix/toolbox-cpp


text:
//
// Copyright yutopp 2013 - .
//
// 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)
//

#pragma once

#include <cassert>
#include <memory>
#include <unordered_map>
#include <bitset>
#include <vector>
#include <utility>
#include <boost/range/adaptor/transformed.hpp>

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

//#include <boost/detail/bitmask.hpp>
//#include <boost/optional.hpp>

#include "../config/macros.hpp"

#include "environment_base.hpp"
#include "global_environment.hpp"
#include "attributes_mixin.hpp"
#include "../behavior/intrinsic_action_holder_fwd.hpp"

namespace rill
{
    //
    // environments for normal function
    // per a function
    //
    class function_symbol_environment RILL_CXX11_FINAL
        : public environment_base, public attributes_mixin
    {
    public:
        static kind::type_value const KindValue;

    public:
        // pre construct
        function_symbol_environment(
            environment_parameter_t&& pp,
            weak_multiple_set_environment_ptr const& multiset_env_ptr,
            native_string_type const& base_name
            )
            : environment_base( std::move( pp ) )
            , multiset_env_ptr_( multiset_env_ptr )
            , base_name_( base_name )
            , return_type_id_( type_id_undefined )
            , is_initializer_function_( false )
        {}

    public:
        auto get_symbol_kind() const
            -> kind::type_value RILL_CXX11_OVERRIDE
        {
            return KindValue;
        }

        auto get_parameter_decl_ids() const
            -> environment_id_list_t const&
        {
            return parameter_decl_ids_;
        }

        auto get_parameter_type_ids() const
            -> type_id_list_t const&
        {
            return parameter_type_ids_;
        }

        auto decide_return_type( type_id_t const& return_type_id )
            -> void
        {
            return_type_id_ = return_type_id;
        }

        auto is_return_type_decided() const
            -> bool
        {
            return return_type_id_ != type_id_undefined;
        }

        auto complete(
            native_string_type const& mangled_name,
            attribute::decl::type const& decl_attr = attribute::decl::k_default
            )
            -> void
        {
            assert( is_return_type_decided() );
            mangled_name_ = mangled_name;
            set_attribute( decl_attr );

            change_progress_to_completed();
        }

        auto get_return_type_id() const
            -> type_id_t
        {
            return return_type_id_;
        }

        auto dump( std::ostream& os, std::string const& indent ) const
            -> std::ostream& RILL_CXX11_OVERRIDE
        {
            os  << indent << "function_symbol_environment[ "
                << base_name_ << " : " << mangled_name_ << " ]" << std::endl;
            return dump_include_env( os, indent );
        }

        auto append_parameter_variable(
            variable_symbol_environment_ptr const& v_env
            )
            -> void;

        auto get_base_name() const
            -> native_string_type const&
        {
            return base_name_;
        }

        auto get_mangled_name() const
            -> native_string_type const&
        {
            return mangled_name_;
        }

        auto unique_key_for_overload() const
            ->  native_string_type
        {
            return mangled_name_;
        }

        bool is_return_type_completed() const
        {
            return return_type_id_ != type_id_undefined;
        }

        void mark_as_initialize_function()
        {
            is_initializer_function_ = true;
        }

        bool is_initializer() const
        {
            return is_initializer_function_;
        }

        void mark_as_virtual( std::size_t const& index )
        {
            virtual_index_ = index;
        }

        auto is_virtual() const
            -> bool
        {
            return virtual_index_ != boost::none;
        }

        auto get_virtual_index() const
            -> std::size_t const&
        {
            assert( is_virtual() );
            return *virtual_index_;
        }

        void mark_as_intrinsic_function( intrinsic_action_id_t const& id )
        {
            intrinsic_action_id_ = id;
        }

        auto get_action_id() const
            -> intrinsic_action_id_t const&
        {
            assert( intrinsic_action_id_ != boost::none );
            return *intrinsic_action_id_;
        }

        auto get_multiset_env()
        {
            return multiset_env_ptr_.lock();
        }

    private:
        weak_multiple_set_environment_ptr multiset_env_ptr_;

        native_string_type base_name_, mangled_name_;

        // parameter variable environments
        environment_id_list_t parameter_decl_ids_;

        // types
        type_id_list_t parameter_type_ids_;
        type_id_t return_type_id_;

        type_id_list_t return_type_candidates_;

        bool is_initializer_function_;
        boost::optional<std::size_t> virtual_index_;

        boost::optional<intrinsic_action_id_t> intrinsic_action_id_;
    };

} // namespace rill

max_stars_repo_name: rhysd/rill

max_issues_repo_name: rhysd/rill

max_forks_repo_name: rhysd/rill


text:
/*************** <auto-copyright.rb BEGIN do not edit this line> **************
 *
 * Copyright 2012-2013 by Ames Laboratory
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Library General Public
 * License version 2.1 as published by the Free Software Foundation.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Library General Public License for more details.
 *
 * You should have received a copy of the GNU Library General Public
 * License along with this library; if not, write to the
 * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
 * Boston, MA 02111-1307, USA.
 *
 *************** <auto-copyright.rb END do not edit this line> ***************/

// --- LEAF Includes --- //
#include <leaf/wrapper/java/lang/Thread.h>

#include <leaf/wrapper/java/util/Map.h>

// --- Boost Includes --- //
#include <boost/algorithm/string/predicate.hpp>

namespace leaf
{
namespace wrapper
{
namespace java
{
namespace lang
{

////////////////////////////////////////////////////////////////////////////////
Thread::Thread(
    jobject const& o )
    :
    Object( o )
{
    ;
}
////////////////////////////////////////////////////////////////////////////////
Thread::~Thread()
{
    ;
}
////////////////////////////////////////////////////////////////////////////////
ThreadPtr Thread::CurrentThread()
{
    return Create< Thread >(
        java::CallStaticMethod< jobject >(
            GetJclass(), GetJmid( "currentThread" ) ) );
}
////////////////////////////////////////////////////////////////////////////////
util::Map< Thread, util::Array< StackTraceElement > >::SPtr
Thread::GetAllStackTraces()
{
    return Create< util::Map< Thread, util::Array< StackTraceElement > > >(
        java::CallStaticMethod< jobject >(
            GetJclass(), GetJmid( "getAllStackTraces" ) ) );
}
////////////////////////////////////////////////////////////////////////////////
ClassLoaderPtr Thread::GetContextClassLoader() const
{
    return Create< ClassLoader >(
        java::CallMethod< jobject >(
            m_jobject, GetJmid( "getContextClassLoader" ) ) );
}
////////////////////////////////////////////////////////////////////////////////
long Thread::GetId() const
{
    //This conversion may be incorrect
    return static_cast< long >(
        java::CallMethod< jlong >( m_jobject, GetJmid( "getId" ) ) );
}
////////////////////////////////////////////////////////////////////////////////
StringPtr Thread::GetName() const
{
    return Create< String >(
        java::CallMethod< jobject >( m_jobject, GetJmid( "getName" ) ) );
}
////////////////////////////////////////////////////////////////////////////////
EnumPtr Thread::GetState() const
{
    return Create< Enum >(
        java::CallMethod< jobject >( m_jobject, GetJmid( "getState" ) ) );
}
////////////////////////////////////////////////////////////////////////////////
void Thread::Join() const
{
    java::CallMethod< void >( m_jobject, GetJmid( "join" ) );
}
////////////////////////////////////////////////////////////////////////////////
StringPtr Thread::ToString() const
{
    return Create< String >(
        java::CallMethod< jobject >( m_jobject, GetJmid( "toString" ) ) );
}
////////////////////////////////////////////////////////////////////////////////
void Thread::SetContextClassLoader(
    ClassLoader const& cl )
{
    java::CallMethod< void >(
        m_jobject, GetJmid( "setContextClassLoader" ), cl.Jobj() );
}
////////////////////////////////////////////////////////////////////////////////
void Thread::WaitForEDT()
{
    util::Set< Thread >::SPtr threadSet = GetAllStackTraces()->KeySet();

    typedef util::Iterator< Thread > ItrType;
    ItrType::SPtr itr = threadSet->GetIterator();
    while( itr->HasNext() )
    {
        ItrType::TypeSPtr thread = itr->Next();
        std::string name = thread->GetName()->StdString();
        if( boost::starts_with( name, "AWT-EventQueue" ) ) thread->Join();
    }
}
////////////////////////////////////////////////////////////////////////////////
jclass const& Thread::GetJclass()
{
    static jclass const clazz = java::FindClass( "java/lang/Thread" );
    return clazz;
}
////////////////////////////////////////////////////////////////////////////////
jmethodID const& Thread::GetJmid(
    std::string const& name )
{
    static java::JMIDMAP const jmidMap = boost::assign::map_list_of
        ( "currentThread",
          java::GetStaticMethodID(
              GetJclass(), "currentThread",
              "()Ljava/lang/Thread;" ) )
        ( "getAllStackTraces",
          java::GetStaticMethodID(
              GetJclass(), "getAllStackTraces",
              "()Ljava/util/Map;" ) )
        ( "getContextClassLoader",
          java::GetMethodID(
              GetJclass(), "getContextClassLoader",
              "()Ljava/lang/ClassLoader;" ) )
        ( "getId",
          java::GetMethodID(
              GetJclass(), "getId",
              "()J" ) )
        ( "getName",
          java::GetMethodID(
              GetJclass(), "getName",
              "()Ljava/lang/String;" ) )
        ( "getState",
          java::GetMethodID(
              GetJclass(), "getState",
              "()Ljava/lang/Thread$State;" ) )
        ( "join",
          java::GetMethodID(
              GetJclass(), "join",
              "()V" ) )
        ( "setContextClassLoader",
          java::GetMethodID(
              GetJclass(), "setContextClassLoader",
              "(Ljava/lang/ClassLoader;)V" ) )
        ( "toString",
          java::GetMethodID(
              GetJclass(), "toString",
              "()Ljava/lang/String;" ) );

    java::JMIDMAP::const_iterator itr = jmidMap.find( name );
    return itr->second;
}
////////////////////////////////////////////////////////////////////////////////

} //end lang
} //end java
} //end wrapper
} //end leaf

ext: cxx

max_stars_repo_name: IdahoLabCuttingBoard/LEAF

max_issues_repo_name: IdahoLabCuttingBoard/LEAF

max_forks_repo_name: IdahoLabCuttingBoard/LEAF


text:
#include "uniform_bspline_ceres.hpp"

#include <random>

#include <Eigen/Dense>
#include <ceres/ceres.h>
#include <gtest/gtest.h>

#include "test_helper.hpp"
#include "uniform_bspline_ceres.hpp"

namespace {
template <typename Spline_>
class FitCostFunctor {
public:
    static_assert(Spline_::OutputDims == 1, "Invalid number of output dims specified.");

    explicit FitCostFunctor(const ubs::UniformBSplineCeresEvaluator<Spline_>& splineEvaluator, double val)
            : splineEvaluator_(splineEvaluator), val_(val) {
    }

    template <typename T>
    bool operator()(T const* const* paramPointers, T* residual) const {
        splineEvaluator_.evaluate(paramPointers, residual);
        *residual -= T(val_);
        return true;
    }

private:
    ubs::UniformBSplineCeresEvaluator<Spline_> splineEvaluator_;
    double val_;
};

} // namespace

TEST(UniformBSplineCeres, PlaneFitPrior) { // NOLINT(readability-function-size)
    using Spline = ubs::UniformBSpline<double, 3, Eigen::Vector2d, double, Eigen::MatrixXd>;

    Eigen::MatrixXd controlPoints = Eigen::MatrixXd::Random(20, 20);
    Spline spline(controlPoints);

    // Generate measurements.
    ubs::UniformBSplineCeres<Spline> splineCeres(spline);

    std::vector<double*> parameterPointers(splineCeres.ControlPointsSupport);
    ceres::Problem problem;
    const int numMeasurements = 10;

    const Eigen::Vector3d supportPoint(1.0, 2.0, 3.0);
    const Eigen::Vector3d dir1 = Eigen::Vector3d(2.0, 0.12, 0.32).normalized();
    const Eigen::Vector3d dir2 = Eigen::Vector3d(0.1, 1.5, 1.74).normalized();

    Eigen::Matrix2d a = Eigen::Matrix2d::Zero();
    a << dir1.head<2>(), dir2.head<2>();

    const Eigen::Matrix2d aInv = a.inverse();

    // Create ceres problem.
    for (int i = 0; i < numMeasurements; ++i) {
        for (int j = 0; j < numMeasurements; ++j) {
            Eigen::Vector2d planePos{};
            planePos << i, j;
            planePos = planePos / (numMeasurements - 1) * 0.2 - supportPoint.head<2>();

            const Eigen::Vector2d rs = aInv * planePos;
            const Eigen::Vector3d pos = supportPoint + dir1 * rs[0] + dir2 * rs[1];

            const auto data = splineCeres.getPointData(pos.head<2>());
            splineCeres.fillParameterPointers(data, parameterPointers.begin(), parameterPointers.end());
            ubs::UniformBSplineCeresEvaluator<Spline> evaluator = splineCeres.getEvaluator(data);

            auto* costFunctor = new ceres::DynamicAutoDiffCostFunction<FitCostFunctor<Spline>>(
                new FitCostFunctor<Spline>(evaluator, pos[2]));
            for (int k = 0; k < splineCeres.ControlPointsSupport; ++k) {
                costFunctor->AddParameterBlock(1);
            }
            costFunctor->SetNumResiduals(1);

            problem.AddResidualBlock(costFunctor, nullptr, parameterPointers);
        }
    }

    splineCeres.addSmoothnessResiduals<2>(problem);

    // Solve problem.
    ceres::Solver::Options options;
    options.minimizer_progress_to_stdout = false;
    options.initial_trust_region_radius = 1e16;
    ceres::Solver::Summary summary;
    ceres::Solve(options, &problem, &summary);

    // Check result.
    test_util::linspace(std::array<int, 2>{200, 200}, [&](const Eigen::Vector2d& pos) {
        const Eigen::Vector3d splinePos(pos[0], pos[1], spline.evaluate(pos));

        Eigen::Vector2d planePos = pos - supportPoint.head<2>();
        Eigen::Vector2d rs = aInv * planePos;
        const Eigen::Vector3d gtPos = supportPoint + dir1 * rs[0] + dir2 * rs[1];

        for (int i = 0; i < 3; ++i) {
            EXPECT_NEAR(gtPos[i], splinePos[i], 1e-8) << pos;
        }
    });
}


text:
#include "stdafx.h"
#include <boost/test/auto_unit_test.hpp>
#include <boost/bind.hpp>
#include "litwindow/ui/list_mediator.hpp"

#define new DEBUG_NEW

using namespace litwindow;
using namespace std;
using namespace boost;
using namespace litwindow::ui;

struct TestData
{
	int integer;
	wstring name;
	bool calc() const { return 5.9*integer>integer; }
	void calc(const double &d) { integer=(int)ceil(d); }
	int calc2() const { return 2*integer;}
	TestData()
		:integer(7),name(L"name"){}
};

wstring TestDataAccess(const TestData &a, int col)
{
	return a.name+wstring(L"-TestDataAccess(int col)");
}
wstring TestDataAccess(const TestData &a)
{
	return a.name+wstring(L"-TestDataAccess");
}

template <typename RowValue, typename Accessor, typename Enabled = void>
struct column_access
{
	typedef boost::function<void(const RowValue&, wstring&)> text_renderer_t;
};

template <typename RowValue, typename ColValue>
struct column_access<RowValue, ColValue (RowValue::*)() const>
{
	typedef boost::function<void(const RowValue&, wstring&)> text_renderer_t;
	typedef ColValue (RowValue::*accessor_type)() const;
	void text(text_renderer_t &renderer, accessor_type a)
	{
		renderer=boost::bind(a, _1);
	}
};
template <typename RowValue, typename Accessor>
void testtemplate(Accessor a)
{
	typedef column_access<RowValue, Accessor>::text_renderer_t text_renderer_t;
	text_renderer_t t;
	column_access<RowValue>().text(t, a);
}
template <typename RowValue, typename ColValue>
void testtemplate(ColValue (RowValue::*a)() const)
{

}

void TestDataAccess_renderer(const TestData &a, wstring &r)
{
	r=a.name;
}

void StringDataFormatter(const wstring &in, wstring &out)
{
	out=in+L"--";
}

void DataFormatter(int i, wstring &r)
{
	r=lexical_cast<wstring>(i*3);
}

BOOST_AUTO_TEST_CASE(columns_descriptor_test)
{
	//te(bind(&TestDataAccess_renderer, _1, _2));
	//te(&TestDataAccess);
	typedef basic_columns_adapter<basic_column_descriptor<TestData> > bca_t;
	bca_t d;
	d.add
		(L"integer",	10,		&TestData::integer)	// ptr to member
		(L"calc",		20,		&TestData::calc)	// ptr to member_function with overload
		(L"calc2",		100,	&TestData::calc2)	// ptr to member without overload
		(L"TestDataAccess",	200,	&TestDataAccess)	// ptr to free function
		;
	d.add
		(L"bind",		100,	boost::bind(&TestDataAccess, _1, 9)) // bind
		(L"name",		100,	&TestData::name)	// ptr to member
		;
	bca_t::text_renderer_type renderer;
	renderer=boost::bind(&TestDataAccess_renderer, _1, _2);
	d.add
		(L"function-renderer", 10,	renderer)
		(L"free-renderer", 10,	&TestDataAccess_renderer)
		(L"bind-renderer", 10, boost::bind(&TestDataAccess_renderer, _1, _2))
		;

	TestData t;
	wstring r;
	d.render_element_at(0, r, t);
	BOOST_CHECK(r == L"7");
	d.render_element_at(1, r, t);
	BOOST_CHECK(r == L"1");
	d.render_element_at(2, r, t);
	BOOST_CHECK(r == L"14");
	d.render_element_at(3, r, t);
	BOOST_CHECK(r == L"name-TestDataAccess");

	d.render_element_at(L"calc2", r, t);
	BOOST_CHECK(r == L"14");

	d.render_element_at(4, r, t);
	BOOST_CHECK(r == L"name-TestDataAccess(int col)");
	d.render_element_at(5, r, t);
	BOOST_CHECK(r == L"name");

	r.clear();
	d.render_element_at(L"name", r, t);	// should be column 6
	BOOST_CHECK(r == L"name");
	r.clear();
	d.render_element_at(L"function-renderer", r, t);
	BOOST_CHECK(r == L"name");
	r.clear();
	d.render_element_at(L"free-renderer", r, t);
	BOOST_CHECK(r == L"name");
	r.clear();
	d.render_element_at(L"bind-renderer", r, t);
	BOOST_CHECK(r == L"name");

	d.add
		(L"formatter-renderer", 10, &TestData::integer, &DataFormatter)
		(L"formatter-renderer-2", 10, &TestData::calc2, &DataFormatter)
		(L"bind-formatter-renderer", 10, boost::bind(&TestDataAccess, _1, 9), &StringDataFormatter)
		(L"free-function-formatter", 10, &TestDataAccess, &StringDataFormatter)
		;
	r.clear();
	d.render_element_at(L"formatter-renderer", r, t);
	BOOST_CHECK(r == L"21");
	r.clear();
	d.render_element_at(L"formatter-renderer-2", r, t);
	BOOST_CHECK(r == L"42");
	r.clear();
	d.render_element_at(L"bind-formatter-renderer", r, t);
	BOOST_CHECK(r == L"name-TestDataAccess(int col)--");
	r.clear();
	d.render_element_at(L"free-function-formatter", r, t);
	BOOST_CHECK(r == L"name-TestDataAccess--");
}

BOOST_AUTO_TEST_CASE(column_values_test)
{
	TestData t;
	BOOST_CHECK_EQUAL(t.integer, 7);
	boost::function<int(const TestData&)> f0=boost::bind(&TestData::integer, _1);
	boost::function<bool(const TestData&)> f1=boost::bind(&TestData::calc, _1);
	testtemplate<TestData>(&TestData::calc);
	boost::function<wstring(const TestData&)> f2=boost::bind(&TestDataAccess, _1);
	boost::function<wstring(const TestData&)> f3=boost::bind(f2, _1);
	BOOST_CHECK_EQUAL(f0(t), 7);
	BOOST_CHECK_EQUAL(f1(t), true);
	BOOST_CHECK(f2(t)==wstring(L"name-TestDataAccess"));
	BOOST_CHECK(f3(t)==wstring(L"name-TestDataAccess"));

	boost::function<int(const TestData&)> f4=boost::bind(&TestData::calc2, _1);
	boost::function<bool(const TestData&, const TestData&)> c0=boost::bind(f0, t) < boost::bind(f4, t);
	BOOST_CHECK(c0(t, t));
	wstring rc;
	to_string(f0(t), rc);
	BOOST_CHECK(rc==L"7");
	boost::function<void(const TestData&, wstring&)> strg=boost::bind<void>(&to_string<int>, boost::bind(f0, _1), _2);
}

max_stars_repo_name: hajokirchhoff/litwindow

max_issues_repo_name: hajokirchhoff/litwindow

max_forks_repo_name: hajokirchhoff/litwindow


text:
// Copyright (c) 2009-2012 The Darkcoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.

#include "protocol.h"
#include "activefloatingcity.h"
#include "floatingcityman.h"
#include <boost/lexical_cast.hpp>
#include "clientversion.h"

//
// Bootup the floatingcity, look for a 10,000 ZLM input and register on the network
//
void CActiveFloatingcity::ManageStatus()
{
    std::string errorMessage;

    if (fDebug) LogPrintf("CActiveFloatingcity::ManageStatus() - Begin\n");

    if(!fFloatingCity) return;

    //need correct adjusted time to send ping
    bool fIsInitialDownload = IsInitialBlockDownload();
    if(fIsInitialDownload) {
        status = FLOATINGCITY_SYNC_IN_PROCESS;
        LogPrintf("CActiveFloatingcity::ManageStatus() - Sync in progress. Must wait until sync is complete to start floatingcity.\n");
        return;
    }

    if(status == FLOATINGCITY_INPUT_TOO_NEW || status == FLOATINGCITY_NOT_CAPABLE || status == FLOATINGCITY_SYNC_IN_PROCESS){
        status = FLOATINGCITY_NOT_PROCESSED;
    }

    if(status == FLOATINGCITY_NOT_PROCESSED) {
        if(strFloatingCityAddr.empty()) {
            if(!GetLocal(service)) {
                notCapableReason = "Can't detect external address. Please use the floatingcityaddr configuration option.";
                status = FLOATINGCITY_NOT_CAPABLE;
                LogPrintf("CActiveFloatingcity::ManageStatus() - not capable: %s\n", notCapableReason.c_str());
                return;
            }
        } else {
        	service = CService(strFloatingCityAddr, true);
        }

        LogPrintf("CActiveFloatingcity::ManageStatus() - Checking inbound connection to '%s'\n", service.ToString().c_str());

            if(!ConnectNode((CAddress)service, service.ToString().c_str())){
                notCapableReason = "Could not connect to " + service.ToString();
                status = FLOATINGCITY_NOT_CAPABLE;
                LogPrintf("CActiveFloatingcity::ManageStatus() - not capable: %s\n", notCapableReason.c_str());
                return;
            }

        if(pwalletMain->IsLocked()){
            notCapableReason = "Wallet is locked.";
            status = FLOATINGCITY_NOT_CAPABLE;
            LogPrintf("CActiveFloatingcity::ManageStatus() - not capable: %s\n", notCapableReason.c_str());
            return;
        }

        // Set defaults
        status = FLOATINGCITY_NOT_CAPABLE;
        notCapableReason = "Unknown. Check debug.log for more information.\n";

        // Choose coins to use
        CPubKey pubKeyCollateralAddress;
        CKey keyCollateralAddress;

        if(GetFloatingCityVin(vin, pubKeyCollateralAddress, keyCollateralAddress)) {

            if(GetInputAge(vin) < FLOATINGCITY_MIN_CONFIRMATIONS){
                notCapableReason = "Input must have least " + boost::lexical_cast<string>(FLOATINGCITY_MIN_CONFIRMATIONS) +
                        " confirmations - " + boost::lexical_cast<string>(GetInputAge(vin)) + " confirmations";
                LogPrintf("CActiveFloatingcity::ManageStatus() - %s\n", notCapableReason.c_str());
                status = FLOATINGCITY_INPUT_TOO_NEW;
                return;
            }

            LogPrintf("CActiveFloatingcity::ManageStatus() - Is capable floating city!\n");

            status = FLOATINGCITY_IS_CAPABLE;
            notCapableReason = "";

            pwalletMain->LockCoin(vin.prevout);

            // send to all nodes
            CPubKey pubKeyFloatingcity;
            CKey keyFloatingcity;

            if(!mnEngineSigner.SetKey(strFloatingCityPrivKey, errorMessage, keyFloatingcity, pubKeyFloatingcity))
            {
            	LogPrintf("ActiveFloatingcity::Dseep() - Error upon calling SetKey: %s\n", errorMessage.c_str());
            	return;
            }

            /* donations are not supported in Zalem-Coin.conf */
            CScript donationAddress = CScript();
            int donationPercentage = 0;

            if(!Register(vin, service, keyCollateralAddress, pubKeyCollateralAddress, keyFloatingcity, pubKeyFloatingcity, donationAddress, donationPercentage, errorMessage)) {
                LogPrintf("CActiveFloatingcity::ManageStatus() - Error on Register: %s\n", errorMessage.c_str());
            }

            return;
        } else {
            notCapableReason = "Could not find suitable coins!";
        	LogPrintf("CActiveFloatingcity::ManageStatus() - Could not find suitable coins!\n");
        }
    }

    //send to all peers
    if(!Dseep(errorMessage)) {
    	LogPrintf("CActiveFloatingcity::ManageStatus() - Error on Ping: %s\n", errorMessage.c_str());
    }
}

// Send stop dseep to network for remote floatingcity
bool CActiveFloatingcity::StopFloatingCity(std::string strService, std::string strKeyFloatingcity, std::string& errorMessage) {
	CTxIn vin;
    CKey keyFloatingcity;
    CPubKey pubKeyFloatingcity;

    if(!mnEngineSigner.SetKey(strKeyFloatingcity, errorMessage, keyFloatingcity, pubKeyFloatingcity)) {
    	LogPrintf("CActiveFloatingcity::StopFloatingCity() - Error: %s\n", errorMessage.c_str());
		return false;
	}

    if (GetFloatingCityVin(vin, pubKeyFloatingcity, keyFloatingcity)){
        LogPrintf("FloatingcityStop::VinFound: %s\n", vin.ToString());
    }

	return StopFloatingCity(vin, CService(strService, true), keyFloatingcity, pubKeyFloatingcity, errorMessage);
}

// Send stop dseep to network for main floatingcity
bool CActiveFloatingcity::StopFloatingCity(std::string& errorMessage) {
	if(status != FLOATINGCITY_IS_CAPABLE && status != FLOATINGCITY_REMOTELY_ENABLED) {
		errorMessage = "floatingcity is not in a running status";
    	LogPrintf("CActiveFloatingcity::StopFloatingCity() - Error: %s\n", errorMessage.c_str());
		return false;
	}

	status = FLOATINGCITY_STOPPED;

    CPubKey pubKeyFloatingcity;
    CKey keyFloatingcity;

    if(!mnEngineSigner.SetKey(strFloatingCityPrivKey, errorMessage, keyFloatingcity, pubKeyFloatingcity))
    {
    	LogPrintf("Register::ManageStatus() - Error upon calling SetKey: %s\n", errorMessage.c_str());
    	return false;
    }

	return StopFloatingCity(vin, service, keyFloatingcity, pubKeyFloatingcity, errorMessage);
}

// Send stop dseep to network for any floatingcity
bool CActiveFloatingcity::StopFloatingCity(CTxIn vin, CService service, CKey keyFloatingcity, CPubKey pubKeyFloatingcity, std::string& errorMessage) {
   	pwalletMain->UnlockCoin(vin.prevout);
	return Dseep(vin, service, keyFloatingcity, pubKeyFloatingcity, errorMessage, true);
}

bool CActiveFloatingcity::Dseep(std::string& errorMessage) {
	if(status != FLOATINGCITY_IS_CAPABLE && status != FLOATINGCITY_REMOTELY_ENABLED) {
		errorMessage = "floatingcity is not in a running status";
    	LogPrintf("CActiveFloatingcity::Dseep() - Error: %s\n", errorMessage.c_str());
		return false;
	}

    CPubKey pubKeyFloatingcity;
    CKey keyFloatingcity;

    if(!mnEngineSigner.SetKey(strFloatingCityPrivKey, errorMessage, keyFloatingcity, pubKeyFloatingcity))
    {
    	LogPrintf("CActiveFloatingcity::Dseep() - Error upon calling SetKey: %s\n", errorMessage.c_str());
    	return false;
    }

	return Dseep(vin, service, keyFloatingcity, pubKeyFloatingcity, errorMessage, false);
}

bool CActiveFloatingcity::Dseep(CTxIn vin, CService service, CKey keyFloatingcity, CPubKey pubKeyFloatingcity, std::string &retErrorMessage, bool stop) {
    std::string errorMessage;
    std::vector<unsigned char> vchFloatingCitySignature;
    std::string strFloatingCitySignMessage;
    int64_t masterNodeSignatureTime = GetAdjustedTime();

    std::string strMessage = service.ToString() + boost::lexical_cast<std::string>(masterNodeSignatureTime) + boost::lexical_cast<std::string>(stop);

    if(!mnEngineSigner.SignMessage(strMessage, errorMessage, vchFloatingCitySignature, keyFloatingcity)) {
    	retErrorMessage = "sign message failed: " + errorMessage;
    	LogPrintf("CActiveFloatingcity::Dseep() - Error: %s\n", retErrorMessage.c_str());
        return false;
    }

    if(!mnEngineSigner.VerifyMessage(pubKeyFloatingcity, vchFloatingCitySignature, strMessage, errorMessage)) {
    	retErrorMessage = "Verify message failed: " + errorMessage;
    	LogPrintf("CActiveFloatingcity::Dseep() - Error: %s\n", retErrorMessage.c_str());
        return false;
    }

    // Update Last Seen timestamp in floatingcity list
    CFloatingcity* pmn = mnodeman.Find(vin);
    if(pmn != NULL)
    {
        if(stop)
            mnodeman.Remove(pmn->vin);
        else
            pmn->UpdateLastSeen();
    } else {
    	// Seems like we are trying to send a ping while the floatingcity is not registered in the network
        retErrorMessage = "MNengine Floatingcity List doesn't include our floatingcity, Shutting down floatingcity pinging service! " + vin.ToString();
    	LogPrintf("CActiveFloatingcity::Dseep() - Error: %s\n", retErrorMessage.c_str());
        status = FLOATINGCITY_NOT_CAPABLE;
        notCapableReason = retErrorMessage;
        return false;
    }

    //send to all peers
    LogPrintf("CActiveFloatingcity::Dseep() - RelayFloatingcityEntryPing vin = %s\n", vin.ToString().c_str());
    mnodeman.RelayFloatingcityEntryPing(vin, vchFloatingCitySignature, masterNodeSignatureTime, stop);

    return true;
}

bool CActiveFloatingcity::Register(std::string strService, std::string strKeyFloatingcity, std::string txHash, std::string strOutputIndex, std::string strDonationAddress, std::string strDonationPercentage, std::string& errorMessage) {
    CTxIn vin;
    CPubKey pubKeyCollateralAddress;
    CKey keyCollateralAddress;
    CPubKey pubKeyFloatingcity;
    CKey keyFloatingcity;
    CScript donationAddress = CScript();
    int donationPercentage = 0;

    if(!mnEngineSigner.SetKey(strKeyFloatingcity, errorMessage, keyFloatingcity, pubKeyFloatingcity))
    {
        LogPrintf("CActiveFloatingcity::Register() - Error upon calling SetKey: %s\n", errorMessage.c_str());
        return false;
    }

    if(!GetFloatingCityVin(vin, pubKeyCollateralAddress, keyCollateralAddress, txHash, strOutputIndex)) {
        errorMessage = "could not allocate vin";
        LogPrintf("CActiveFloatingcity::Register() - Error: %s\n", errorMessage.c_str());
        return false;
    }
    CZalemCoinAddress address;
    if (strDonationAddress != "")
    {
        if(!address.SetString(strDonationAddress))
        {
            LogPrintf("ActiveFloatingcity::Register - Invalid Donation Address\n");
            return false;
        }
        donationAddress.SetDestination(address.Get());

        try {
            donationPercentage = boost::lexical_cast<int>( strDonationPercentage );
        } catch( boost::bad_lexical_cast const& ) {
            LogPrintf("ActiveFloatingcity::Register - Invalid Donation Percentage (Couldn't cast)\n");
            return false;
        }

        if(donationPercentage < 0 || donationPercentage > 100)
        {
            LogPrintf("ActiveFloatingcity::Register - Donation Percentage Out Of Range\n");
            return false;
        }
    }

	return Register(vin, CService(strService, true), keyCollateralAddress, pubKeyCollateralAddress, keyFloatingcity, pubKeyFloatingcity, donationAddress, donationPercentage, errorMessage);
}

bool CActiveFloatingcity::Register(CTxIn vin, CService service, CKey keyCollateralAddress, CPubKey pubKeyCollateralAddress, CKey keyFloatingcity, CPubKey pubKeyFloatingcity, CScript donationAddress, int donationPercentage, std::string &retErrorMessage) {
    std::string errorMessage;
    std::vector<unsigned char> vchFloatingCitySignature;
    std::string strFloatingCitySignMessage;
    int64_t masterNodeSignatureTime = GetAdjustedTime();

    std::string vchPubKey(pubKeyCollateralAddress.begin(), pubKeyCollateralAddress.end());
    std::string vchPubKey2(pubKeyFloatingcity.begin(), pubKeyFloatingcity.end());

    std::string strMessage = service.ToString() + boost::lexical_cast<std::string>(masterNodeSignatureTime) + vchPubKey + vchPubKey2 + boost::lexical_cast<std::string>(PROTOCOL_VERSION) + donationAddress.ToString() + boost::lexical_cast<std::string>(donationPercentage);

    if(!mnEngineSigner.SignMessage(strMessage, errorMessage, vchFloatingCitySignature, keyCollateralAddress)) {
		retErrorMessage = "sign message failed: " + errorMessage;
		LogPrintf("CActiveFloatingcity::Register() - Error: %s\n", retErrorMessage.c_str());
		return false;
    }

    if(!mnEngineSigner.VerifyMessage(pubKeyCollateralAddress, vchFloatingCitySignature, strMessage, errorMessage)) {
		retErrorMessage = "Verify message failed: " + errorMessage;
		LogPrintf("CActiveFloatingcity::Register() - Error: %s\n", retErrorMessage.c_str());
		return false;
	}

    CFloatingcity* pmn = mnodeman.Find(vin);
    if(pmn == NULL)
    {
        LogPrintf("CActiveFloatingcity::Register() - Adding to floatingcity list service: %s - vin: %s\n", service.ToString().c_str(), vin.ToString().c_str());
        CFloatingcity mn(service, vin, pubKeyCollateralAddress, vchFloatingCitySignature, masterNodeSignatureTime, pubKeyFloatingcity, PROTOCOL_VERSION, donationAddress, donationPercentage);
        mn.ChangeNodeStatus(false);
        mn.UpdateLastSeen(masterNodeSignatureTime);
        mnodeman.Add(mn);
    }

    //send to all peers
    LogPrintf("CActiveFloatingcity::Register() - RelayElectionEntry vin = %s\n", vin.ToString().c_str());
    mnodeman.RelayFloatingcityEntry(vin, service, vchFloatingCitySignature, masterNodeSignatureTime, pubKeyCollateralAddress, pubKeyFloatingcity, -1, -1, masterNodeSignatureTime, PROTOCOL_VERSION, donationAddress, donationPercentage);

    return true;
}

bool CActiveFloatingcity::GetFloatingCityVin(CTxIn& vin, CPubKey& pubkey, CKey& secretKey) {
	return GetFloatingCityVin(vin, pubkey, secretKey, "", "");
}

bool CActiveFloatingcity::GetFloatingCityVin(CTxIn& vin, CPubKey& pubkey, CKey& secretKey, std::string strTxHash, std::string strOutputIndex) {
    CScript pubScript;

    // Find possible candidates
    vector<COutput> possibleCoins = SelectCoinsFloatingcity();
    COutput *selectedOutput;

    // Find the vin
	if(!strTxHash.empty()) {
		// Let's find it
		uint256 txHash(strTxHash);
        int outputIndex = boost::lexical_cast<int>(strOutputIndex);
		bool found = false;
		BOOST_FOREACH(COutput& out, possibleCoins) {
			if(out.tx->GetHash() == txHash && out.i == outputIndex)
			{
				selectedOutput = &out;
				found = true;
				break;
			}
		}
		if(!found) {
			LogPrintf("CActiveFloatingcity::GetFloatingCityVin - Could not locate valid vin\n");
			return false;
		}
	} else {
		// No output specified,  Select the first one
		if(possibleCoins.size() > 0) {
			selectedOutput = &possibleCoins[0];
		} else {
			LogPrintf("CActiveFloatingcity::GetFloatingCityVin - Could not locate specified vin from possible list\n");
			return false;
		}
    }

	// At this point we have a selected output, retrieve the associated info
	return GetVinFromOutput(*selectedOutput, vin, pubkey, secretKey);
}

bool CActiveFloatingcity::GetFloatingCityVinForPubKey(std::string collateralAddress, CTxIn& vin, CPubKey& pubkey, CKey& secretKey) {
	return GetFloatingCityVinForPubKey(collateralAddress, vin, pubkey, secretKey, "", "");
}

bool CActiveFloatingcity::GetFloatingCityVinForPubKey(std::string collateralAddress, CTxIn& vin, CPubKey& pubkey, CKey& secretKey, std::string strTxHash, std::string strOutputIndex) {
    CScript pubScript;

    // Find possible candidates
    vector<COutput> possibleCoins = SelectCoinsFloatingcityForPubKey(collateralAddress);
    COutput *selectedOutput;

    // Find the vin
	if(!strTxHash.empty()) {
		// Let's find it
		uint256 txHash(strTxHash);
        int outputIndex = boost::lexical_cast<int>(strOutputIndex);
		bool found = false;
		BOOST_FOREACH(COutput& out, possibleCoins) {
			if(out.tx->GetHash() == txHash && out.i == outputIndex)
			{
				selectedOutput = &out;
				found = true;
				break;
			}
		}
		if(!found) {
			LogPrintf("CActiveFloatingcity::GetFloatingCityVinForPubKey - Could not locate valid vin\n");
			return false;
		}
	} else {
		// No output specified,  Select the first one
		if(possibleCoins.size() > 0) {
			selectedOutput = &possibleCoins[0];
		} else {
			LogPrintf("CActiveFloatingcity::GetFloatingCityVinForPubKey - Could not locate specified vin from possible list\n");
			return false;
		}
    }

	// At this point we have a selected output, retrieve the associated info
	return GetVinFromOutput(*selectedOutput, vin, pubkey, secretKey);
}

// Extract floatingcity vin information from output
bool CActiveFloatingcity::GetVinFromOutput(COutput out, CTxIn& vin, CPubKey& pubkey, CKey& secretKey) {

    CScript pubScript;

	vin = CTxIn(out.tx->GetHash(),out.i);
    pubScript = out.tx->vout[out.i].scriptPubKey; // the inputs PubKey

	CTxDestination address1;
    ExtractDestination(pubScript, address1);
    CZalemCoinAddress address2(address1);

    CKeyID keyID;
    if (!address2.GetKeyID(keyID)) {
        LogPrintf("CActiveFloatingcity::GetFloatingCityVin - Address does not refer to a key\n");
        return false;
    }

    if (!pwalletMain->GetKey(keyID, secretKey)) {
        LogPrintf ("CActiveFloatingcity::GetFloatingCityVin - Private key for address is not known\n");
        return false;
    }

    pubkey = secretKey.GetPubKey();
    return true;
}

// get all possible outputs for running floatingcity
vector<COutput> CActiveFloatingcity::SelectCoinsFloatingcity()
{
    vector<COutput> vCoins;
    vector<COutput> filteredCoins;

    // Retrieve all possible outputs
    pwalletMain->AvailableCoinsMN(vCoins);

    // Filter
    BOOST_FOREACH(const COutput& out, vCoins)
    {
        if(out.tx->vout[out.i].nValue == FloatingcityCollateral(pindexBest->nHeight)*COIN) { //exactly
        	filteredCoins.push_back(out);
        }
    }
    return filteredCoins;
}

// get all possible outputs for running floatingcity for a specific pubkey
vector<COutput> CActiveFloatingcity::SelectCoinsFloatingcityForPubKey(std::string collateralAddress)
{
    CZalemCoinAddress address(collateralAddress);
    CScript scriptPubKey;
    scriptPubKey.SetDestination(address.Get());
    vector<COutput> vCoins;
    vector<COutput> filteredCoins;

    // Retrieve all possible outputs
    pwalletMain->AvailableCoins(vCoins);

    // Filter
    BOOST_FOREACH(const COutput& out, vCoins)
    {
        if(out.tx->vout[out.i].scriptPubKey == scriptPubKey && out.tx->vout[out.i].nValue == FloatingcityCollateral(pindexBest->nHeight)*COIN) { //exactly
        	filteredCoins.push_back(out);
        }
    }
    return filteredCoins;
}

// when starting a floatingcity, this can enable to run as a hot wallet with no funds
bool CActiveFloatingcity::EnableHotColdFloatingCity(CTxIn& newVin, CService& newService)
{
    if(!fFloatingCity) return false;

    status = FLOATINGCITY_REMOTELY_ENABLED;
    notCapableReason = "";

    //The values below are needed for signing dseep messages going forward
    this->vin = newVin;
    this->service = newService;

    LogPrintf("CActiveFloatingcity::EnableHotColdFloatingCity() - Enabled! You may shut down the cold daemon.\n");

    return true;
}

max_stars_repo_name: ZalemCoin/ZalemCoin

max_issues_repo_name: ZalemCoin/ZalemCoin

max_forks_repo_name: ZalemCoin/ZalemCoin


text:
#include <iostream>
#include <limits>
#include <random>
#include <system_error>
#include <thread>

#include <benchmark/benchmark.h>
#include <boost/outcome/outcome.hpp>

#include "katana/Random.h"
#include "katana/Result.h"

namespace {

void
MakeArguments(benchmark::internal::Benchmark* b) {
  for (long num_threads : {1, 4}) {
    for (long size : {1024, 64 * 1024}) {
      for (long handle_ratio : {1, 3}) {
        for (long depth : {16, 32}) {
          for (long fail_delta : {-8, -1, 8}) {
            long fail_depth = depth + fail_delta;
            b->Args({num_threads, size, handle_ratio, depth, fail_depth});
          }
        }
      }
    }
  }
}

struct Random {
  Random() {
    std::uniform_int_distribution<int64_t> dist(
        {}, std::numeric_limits<int64_t>::max());
    int64_t max = dist(katana::GetGenerator());
    seed = max;
  }

  int64_t RandomInt(int64_t n) {
    if (n == 1) {
      return 0;
    }

    // This is not a good random number generator but to avoid being
    // bottlenecked on calls to std::uniform_int_distribution, we write
    // something wrong but inlinable here. The constant is from
    // std::minstd_rand.
    seed *= 48271;
    return seed % n;
  }

  bool ShouldStop(int depth, int max_depth) {
    if (depth >= max_depth) {
      return true;
    }

    int shift = max_depth - depth - 1;
    int64_t len = 1;
    len <<= shift;
    return RandomInt(len) == 0;
  }

  bool ShouldFail(int depth, int fail_depth) {
    return ShouldStop(depth, fail_depth);
  }

  uint64_t seed;
};

template <typename Scaffold>
void
Launch(int num_threads, int size, Scaffold& s) {
  if (num_threads == 1) {
    Random r;
    for (int i = 0; i < size; ++i) {
      s.Start(r);
    }
    return;
  }

  std::vector<std::thread> threads;
  threads.reserve(num_threads);

  for (int i = 0; i < num_threads; ++i) {
    threads.emplace_back([&]() {
      Random r;
      for (int i = 0; i < size; ++i) {
        s.Start(r);
      }
    });
  }

  for (std::thread& t : threads) {
    t.join();
  }
}

class ExceptionScaffold {
public:
  ExceptionScaffold(int handle_ratio, int max_depth, int fail_depth)
      : handle_ratio_(handle_ratio),
        max_depth_(max_depth),
        fail_depth_(fail_depth) {}

  int Go(Random& r, int depth) {
    int rv = r.RandomInt(handle_ratio_);

    if (r.ShouldStop(depth, max_depth_)) {
      return rv;
    }

    if (r.ShouldFail(depth, fail_depth_)) {
      throw depth;
    }

    if (rv) {
      return Go(r, depth + 1);
    }

    return GoWithHandler(r, depth + 1);
  }

  int GoWithHandler(Random& r, int depth) {
    int rv = r.RandomInt(handle_ratio_);

    if (r.ShouldStop(depth, max_depth_)) {
      return rv;
    }

    try {
      if (r.ShouldFail(depth, fail_depth_)) {
        throw depth;
      }

      if (rv) {
        return Go(r, depth + 1);
      }
      return GoWithHandler(r, depth + 1);
    } catch (const int& e) {
      return e;
    }

    // unreachable
    std::abort();
  }

  int Start(Random& r) { return GoWithHandler(r, 0); }

  int handle_ratio_;
  int max_depth_;
  int fail_depth_;
};

template <typename R, typename ErrorMaker>
class ResultScaffold {
public:
  ResultScaffold(int handle_ratio, int max_depth, int fail_depth)
      : handle_ratio_(handle_ratio),
        max_depth_(max_depth),
        fail_depth_(fail_depth) {}

  R Go(Random& r, int depth) {
    int rv = r.RandomInt(handle_ratio_);

    if (r.ShouldStop(depth, max_depth_)) {
      return rv;
    }

    if (r.ShouldFail(depth, fail_depth_)) {
      return error_maker();
    }

    if (rv) {
      return Go(r, depth + 1);
    }

    return GoWithHandler(r, depth + 1);
  }

  R GoWithHandler(Random& r, int depth) {
    int rv = r.RandomInt(handle_ratio_);

    if (r.ShouldStop(depth, max_depth_)) {
      return rv;
    }

    if (r.ShouldFail(depth, fail_depth_)) {
      if (depth == 0) {
        return rv;
      } else {
        return error_maker();
      }
    }

    if (rv) {
      if (auto res = Go(r, depth + 1); !res) {
        return rv;
      } else {
        return res.value();
      }
    }
    if (auto res = GoWithHandler(r, depth + 1); !res) {
      return rv;
    } else {
      return res.value();
    }
  }

  int Start(Random& r) { return GoWithHandler(r, 0).value(); }

  ErrorMaker error_maker;

  int handle_ratio_;
  int max_depth_;
  int fail_depth_;
};

class StringErrorInfo : public std::error_code {
public:
  StringErrorInfo() = default;

  template <
      typename ErrorEnum, typename U = std::enable_if_t<
                              std::is_error_code_enum_v<ErrorEnum> ||
                              std::is_error_condition_enum_v<ErrorEnum>>>
  StringErrorInfo(ErrorEnum&& e)
      : std::error_code(make_error_code(std::forward<ErrorEnum>(e))) {}

  StringErrorInfo WithContext(std::string message) {
    message_ = message;
    return *this;
  }

private:
  std::string message_;
};

void
ReturnException(benchmark::State& state) {
  ExceptionScaffold s(state.range(2), state.range(3), state.range(4));

  for (auto _ : state) {
    Launch(state.range(0), state.range(1), s);
  }
}

template <typename Result>
struct ErrorCodeMaker {
  Result operator()() const { return std::errc::invalid_argument; }
};

template <typename Result>
struct ErrorStringMaker {
  Result operator()() const {
    Result r = std::errc::invalid_argument;
    auto err = r.error();
    return err.WithContext(
        "a string longer than std::string's small string optimization");
  }
};

void
ReturnErrorCodeResult(benchmark::State& state) {
  using Result = BOOST_OUTCOME_V2_NAMESPACE::std_result<int>;

  ResultScaffold<Result, ErrorCodeMaker<Result>> s(
      state.range(2), state.range(3), state.range(4));

  for (auto _ : state) {
    Launch(state.range(0), state.range(1), s);
  }
}

void
ReturnStringResult(benchmark::State& state) {
  using Result = BOOST_OUTCOME_V2_NAMESPACE::std_result<int, StringErrorInfo>;

  ResultScaffold<Result, ErrorCodeMaker<Result>> s(
      state.range(2), state.range(3), state.range(4));

  for (auto _ : state) {
    Launch(state.range(0), state.range(1), s);
  }
}

void
ReturnStringResultWithContext(benchmark::State& state) {
  using Result = BOOST_OUTCOME_V2_NAMESPACE::std_result<int, StringErrorInfo>;

  ResultScaffold<Result, ErrorStringMaker<Result>> s(
      state.range(2), state.range(3), state.range(4));

  for (auto _ : state) {
    Launch(state.range(0), state.range(1), s);
  }
}

void
ReturnKatanaResult(benchmark::State& state) {
  using Result = katana::Result<int>;

  ResultScaffold<Result, ErrorCodeMaker<Result>> s(
      state.range(2), state.range(3), state.range(4));

  for (auto _ : state) {
    Launch(state.range(0), state.range(1), s);
  }
}

void
ReturnKatanaResultWithContext(benchmark::State& state) {
  using Result = katana::Result<int>;

  ResultScaffold<Result, ErrorStringMaker<Result>> s(
      state.range(2), state.range(3), state.range(4));

  for (auto _ : state) {
    Launch(state.range(0), state.range(1), s);
  }
}

BENCHMARK(ReturnException)->Apply(MakeArguments)->UseRealTime();
BENCHMARK(ReturnErrorCodeResult)->Apply(MakeArguments)->UseRealTime();
BENCHMARK(ReturnStringResult)->Apply(MakeArguments)->UseRealTime();
BENCHMARK(ReturnKatanaResult)->Apply(MakeArguments)->UseRealTime();
BENCHMARK(ReturnStringResultWithContext)->Apply(MakeArguments)->UseRealTime();
BENCHMARK(ReturnKatanaResultWithContext)->Apply(MakeArguments)->UseRealTime();

}  // namespace

BENCHMARK_MAIN();

max_stars_repo_name: chakpongchung/katana

max_issues_repo_name: chakpongchung/katana

max_forks_repo_name: chakpongchung/katana


text:
/*
Copyright (c) 2020 Daniel Stahlke

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/

#include <vector>
#include <cmath>
#include <cstdlib>

#include <boost/tuple/tuple.hpp>

// This must be defined before the first time that "gnuplot-iostream.h" is included.
#define GNUPLOT_ENABLE_PTY
#include "gnuplot-iostream.h"

int main() {
    Gnuplot gp;

    // Create field of arrows at random locations.
    std::vector<std::tuple<double,double,double,double>> arrows;
    for(size_t i=0; i<100; i++) {
        double x = rand() / static_cast<double>(RAND_MAX);
        double y = rand() / static_cast<double>(RAND_MAX);
        arrows.emplace_back(x, y, 0, 0);
    }

    double mx=0.5, my=0.5;
    int mb=1;
    while(mb != 3 && mb >= 0) {
        // Make the arrows point towards the mouse click.
        for(auto &[x, y, dx, dy] : arrows) {
            dx = (mx-x) * 0.1;
            dy = (my-y) * 0.1;
        }

        gp << "plot '-' with vectors notitle\n";
        gp.send1d(arrows);

        gp.getMouse(mx, my, mb, "Left click to aim arrows, right click to exit.");
        printf("You pressed mouse button %d at x=%f y=%f\n", mb, mx, my);
        if(mb < 0) printf("The gnuplot window was closed.\n");
    }
}

ext: cc

max_stars_repo_name: zenfey/gnuplot-iostream

max_issues_repo_name: zenfey/gnuplot-iostream

max_forks_repo_name: zenfey/gnuplot-iostream