text:
#include <stdint.h>
#include <widget/KittiReader.h>
#include <QtCore/QDir>
#include <boost/lexical_cast.hpp>
#include <boost/tokenizer.hpp>
#include <fstream>
#include <iostream>
#include <sstream>
#include "rv/string_utils.h"

#include <boost/lexical_cast.hpp>

// Rakshith: Initialize the point labeller tool
void KittiReader::initialize(const QString& directory) {
  std::cout << ">>> KittiReader Init." << std::endl;
  velodyne_filenames_.clear();
  label_filenames_.clear();
  image_filenames_.clear();
  poses_.clear();

  pointsCache_.clear();
  labelCache_.clear();
  tiles_.clear();

  base_dir_ = QDir(directory);
  QDir velodyne_dir;
  QDir velodyne_dir_1(base_dir_.filePath("velodyne"));
  QDir velodyne_dir_2(base_dir_.filePath("velodyne_pcd"));
  if(b_bin_cloud) velodyne_dir = velodyne_dir_1;
  else velodyne_dir = velodyne_dir_2;
  QStringList entries = velodyne_dir.entryList(QDir::Files, QDir::Name);
  for (int32_t i = 0; i < entries.size(); ++i) {
    velodyne_filenames_.push_back(velodyne_dir.filePath(entries.at(i)).toStdString());
  }

  if (!base_dir_.exists("calib.txt"))
    throw std::runtime_error("Missing calibration file: " + base_dir_.filePath("calib.txt").toStdString());

  calib_.initialize(base_dir_.filePath("calib.txt").toStdString());

  readPoses(base_dir_.filePath("poses.txt").toStdString(), poses_);

  std::cout << ">>> Create label files for each lidar scan and set 0 as class id." << std::endl;
  // create label dir, etc.
  QDir labels_dir;
  QDir labels_dir_1(base_dir_.filePath("labels"));
  QDir labels_dir_2(base_dir_.filePath("labels_ascii"));
  if(b_bin_label) labels_dir = labels_dir_1;
  else labels_dir = labels_dir_2;
  // find corresponding label files.
  if (!labels_dir.exists()) {
    if(b_bin_label) base_dir_.mkdir("labels");
    else base_dir_.mkdir("labels_ascii");
  }

  for (uint32_t i = 0; i < velodyne_filenames_.size(); ++i) {
    QString filename;
    if(b_bin_label) filename = QFileInfo(QString::fromStdString(velodyne_filenames_[i])).baseName() + ".label";
    else filename = QFileInfo(QString::fromStdString(velodyne_filenames_[i])).baseName() + ".label_ascii";

    // std::cout << "filename_velo: " << velodyne_filenames_[i].c_str() << std::endl;
    std::cout << "filename_label: " << labels_dir.filePath(filename).toStdString().c_str() << std::endl;

    if (!labels_dir.exists(filename)) {

      if(b_bin_label) {
        std::ifstream in(velodyne_filenames_[i].c_str());
        in.seekg(0, std::ios::end);
        uint32_t num_points = in.tellg() / (4 * sizeof(float));
        in.close();

        std::ofstream out(labels_dir.filePath(filename).toStdString().c_str());

        // Rakshith: Initialize the labels file for each scan that is loaded
        // Each labels file has the same name as the scan name but ends with .labels
        // The labels file has scan.size() number of integers in the file,
        // each representing the class that a particular point from that scan belongs to
        // HOW ARE MULTIPLE LABLES ENCODED?? --- disabled by default since "overwrite labels" is checked in the toolbar on top. Anyway, not needed for my application
        std::vector<uint32_t> labels(num_points, 0);
        out.write(reinterpret_cast<const char*>(labels.data()), num_points * sizeof(uint32_t));

        out.close();
      }
      else {
        std::string path = velodyne_filenames_[i].c_str();
        pcl::PointCloud<PT_TYPE>::Ptr tmpCloud (new pcl::PointCloud<PT_TYPE>);
        if (pcl::io::loadPCDFile<PT_TYPE> (path, *tmpCloud) == -1) {
            PCL_ERROR ("Couldn't read PCD file. \n");
        }
        int num_points = tmpCloud->size();

        std::ofstream out(labels_dir.filePath(filename).toStdString().c_str());
        std::string str;
        str += "FORMAT: POINT_IDX_IN_CLOUD, CLAstr_LABEL\n";
        for(int i = 0; i < num_points; ++i) {
          str += std::to_string(i) + " " + std::to_string((int)0);
        }
        out << str;
        out.close();
      }
    }

    label_filenames_.push_back(labels_dir.filePath(filename).toStdString().c_str());
  }

  std::string missing_img = QDir::currentPath().toStdString() + "/../assets/missing.png";
  QDir image_dir(base_dir_.filePath("image_2"));
  for (uint32_t i = 0; i < velodyne_filenames_.size(); ++i) {
    QString filename = QFileInfo(QString::fromStdString(velodyne_filenames_[i])).baseName() + ".png";
    if (image_dir.exists(filename)) {
      image_filenames_.push_back(image_dir.filePath(filename).toStdString());
    } else {
      image_filenames_.push_back(missing_img);
    }
  }

  // assumes that (0,0,0) is always the start.
  Eigen::Vector2f min = Eigen::Vector2f::Zero();
  Eigen::Vector2f max = Eigen::Vector2f::Zero();

  for (uint32_t i = 0; i < poses_.size(); ++i) {
    Eigen::Vector4f t = poses_[i].col(3);

    min.x() = std::min(t.x() - maxDistance_, min.x());
    min.y() = std::min(t.y() - maxDistance_, min.y());
    max.x() = std::max(t.x() + maxDistance_, max.x());
    max.y() = std::max(t.y() + maxDistance_, max.y());
  }

  //  std::cout << "tileSize = " << tileSize_ << std::endl;
  //  std::cout << "min = " << min << ", max = " << max << std::endl;

  offset_.x() = std::ceil((std::abs(min.x()) - 0.5 * tileSize_) / tileSize_) * tileSize_ + 0.5 * tileSize_;
  offset_.y() = std::ceil((std::abs(min.y()) - 0.5 * tileSize_) / tileSize_) * tileSize_ + 0.5 * tileSize_;

  //  std::cout << "offset = " << offset_ << std::endl;

  numTiles_.x() = std::ceil((std::abs(min.x()) - 0.5 * tileSize_) / tileSize_) +
                  std::ceil((max.x() - 0.5 * tileSize_) / tileSize_) + 1;
  numTiles_.y() = std::ceil((std::abs(min.y()) - 0.5 * tileSize_) / tileSize_) +
                  std::ceil((max.y() - 0.5 * tileSize_) / tileSize_) + 1;

  //  std::cout << "numTiles = " << numTiles_ << std::endl;

  tiles_.clear();
  tiles_.resize(numTiles_.x() * numTiles_.y());

  Eigen::Vector2f idxRadius(maxDistance_ / tileSize_, maxDistance_ / tileSize_);

  for (uint32_t i = 0; i < uint32_t(numTiles_.x()); ++i) {
    for (uint32_t j = 0; j < uint32_t(numTiles_.y()); ++j) {
      auto& tile = tiles_[tileIdxToOffset(i, j)];

      tile.i = i;
      tile.j = j;
      tile.x = i * tileSize_ - offset_.x() + 0.5 * tileSize_;
      tile.y = j * tileSize_ - offset_.y() + 0.5 * tileSize_;
      tile.size = tileSize_;
    }
  }

  trajectory_.clear();

  Eigen::Vector2f e(0.5 * tileSize_, 0.5 * tileSize_);
  for (uint32_t i = 0; i < poses_.size(); ++i) {
    Eigen::Vector2f t = poses_[i].col(3).head(2);
    Eigen::Vector2f idx((t.x() + offset_.x()) / tileSize_, (t.y() + offset_.y()) / tileSize_);

    trajectory_.push_back(Eigen::Vector2f((t.x() + offset_.x()) / tileSize_, (t.y() + offset_.y()) / tileSize_));

    //    tiles_[tileIdxToOffset(uint32_t(idx.x()), uint32_t(idx.y()))].indexes.push_back(i);
    //    uint32_t u_min = std::max(int32_t(idx.x() - idxRadius.x()), 0);
    //    uint32_t u_max = std::min(int32_t(std::ceil(idx.x() + idxRadius.x())), numTiles_.x());
    //    uint32_t v_min = std::max(int32_t(idx.y() - idxRadius.y()), 0);
    //    uint32_t v_max = std::min(int32_t(std::ceil(idx.y() + idxRadius.y())), numTiles_.y());

    // FIXME: workaround check all tiles.
    for (uint32_t u = 0; u < uint32_t(numTiles_.x()); ++u) {
      for (uint32_t v = 0; v < uint32_t(numTiles_.y()); ++v) {
        auto& tile = tiles_[tileIdxToOffset(u, v)];
        Eigen::Vector2f q = t - Eigen::Vector2f(tile.x, tile.y);
        q[0] = std::abs(q[0]);
        q[1] = std::abs(q[1]);

        // check for exact overlap (see Behley et al., ICRA, 2015)
        if (std::max(q[0], q[1]) > e[0] + maxDistance_) continue;  // definitely outside.
        if (std::min(q[0], q[1]) < e[0] || (q - e).norm() < maxDistance_) {
          tile.indexes.push_back(i);
        }
      }
    }
  }

  // sanity check:

  for (auto& t : tiles_) {
    std::sort(t.indexes.begin(), t.indexes.end());
    //    std::cout << "Tile has " << t.indexes.size() << " tiles associated." << std::endl;
    for (uint32_t i = 1; i < t.indexes.size(); ++i) {
      if (t.indexes[i - 1] == t.indexes[i]) {
        std::cout << "found duplicate!" << std::endl;
      }
    }
  }

  uint32_t tileCount = 0;
  for (uint32_t i = 0; i < uint32_t(numTiles_.x()); ++i) {
    for (uint32_t j = 0; j < uint32_t(numTiles_.y()); ++j) {
      auto& tile = tiles_[tileIdxToOffset(i, j)];

      std::sort(tile.indexes.begin(), tile.indexes.end());
      if (tile.indexes.size() > 0) tileCount += 1;
    }
  }

  std::cout << "#tiles  = " << tileCount << std::endl;

  // meta information for faster loading.
  if (base_dir_.exists("instances.txt")) {
    std::cout << "Reading instances.txt..." << std::flush;

    std::ifstream in(base_dir_.filePath("instances.txt").toStdString());

    while (in.good()) {
      std::string line;
      std::getline(in, line);
      if (line.size() == 0) break;

      std::vector<std::string> tokens = rv::split(line, ":");
      if (tokens.size() != 2) {
        throw std::runtime_error("Invalid instance meta information found!");
      }

      uint32_t label = boost::lexical_cast<uint32_t>(tokens[0]);
      uint32_t maxInstanceId = boost::lexical_cast<uint32_t>(tokens[1]);
      maxInstanceIds_[label] = maxInstanceId;

      in.peek();
    }

    in.close();
    std::cout << "finished." << std::endl;
    std::cout << "-----------" << std::endl;
  } else {

    if (b_no_instances_support)
    {
      std::cout << ">>> Please place default instances.txt file with '0:0' in it." << std::endl;
      exit(0);
    }
    std::cout << "Generating intances.txt" << std::flush;
    // get the counts from the label files.
    for (const std::string& filename : label_filenames_) {
      std::vector<uint32_t> labels;
      readLabels(filename, labels);

      for (uint32_t instance_label : labels) {
        uint32_t instanceId = (instance_label >> 16) & uint32_t(0xFFFF);
        uint32_t label = instance_label & uint32_t(0xFFFF);
        if (maxInstanceIds_.find(label) == maxInstanceIds_.end())
          maxInstanceIds_[label] = instanceId;
        else
          maxInstanceIds_[label] = std::max(instanceId, maxInstanceIds_[label]);
      }
    }

    // directly update meta information:
    updateMetaInformation(maxInstanceIds_);
  }
}

void KittiReader::updateMetaInformation(const std::map<uint32_t, uint32_t>& maxInstanceIds) {
  std::ofstream out(base_dir_.filePath("instances.txt").toStdString().c_str());
  for (auto it = maxInstanceIds.begin(); it != maxInstanceIds.end(); ++it) {
    out << it->first << ":" << it->second << std::endl;
  }
  out.close();
}

void KittiReader::retrieve(const Eigen::Vector3f& position, std::vector<uint32_t>& indexes,
                           std::vector<PointcloudPtr>& points, std::vector<LabelsPtr>& labels,
                           std::vector<std::string>& images) {
  Eigen::Vector2f idx((position.x() + offset_.x()) / tileSize_, (position.y() + offset_.y()) / tileSize_);

  retrieve(idx.x(), idx.y(), indexes, points, labels, images);
}

// Rakshith: Read scans on opening a folder.
void KittiReader::retrieve(uint32_t i, uint32_t j, std::vector<uint32_t>& indexes, std::vector<PointcloudPtr>& points,
                           std::vector<LabelsPtr>& labels, std::vector<std::string>& images) {

  std::cout << ">>> Reading cloud and label files." << std::endl;

  indexes.clear();
  points.clear();
  labels.clear();
  images.clear();

  std::vector<int32_t> indexesBefore;
  for (auto it = pointsCache_.begin(); it != pointsCache_.end(); ++it) indexesBefore.push_back(it->first);
  std::vector<int32_t> indexesAfter;

  uint32_t scansRead = 0;

  indexes = tiles_[tileIdxToOffset(i, j)].indexes;
  std::sort(indexes.begin(), indexes.end());
  // loop through all scan
  for (uint32_t t : indexes) {
    indexesAfter.push_back(t);
    if (pointsCache_.find(t) == pointsCache_.end()) {
      scansRead += 1;

      points.push_back(std::shared_ptr<Laserscan>(new Laserscan));
      // Rakshith: Function that reads lidar scans from binary file
      std::cout << ">>> Reading cloud file: " << velodyne_filenames_[t] << std::endl;
      readPoints(velodyne_filenames_[t], *points.back());
      pointsCache_[t] = points.back();
      points.back()->pose = poses_[t];

      labels.push_back(std::shared_ptr<std::vector<uint32_t>>(new std::vector<uint32_t>()));
      // Rakshith: Function that reads lidar scans from binary file
      std::cout << ">>> Reading label file: " << label_filenames_[t] << std::endl;
      uint32_t num_points = points.back()->size(); // To prevent resizing of labels vector should pass cloud size
      readLabels(label_filenames_[t], *labels.back(), num_points);
      labelCache_[t] = labels.back();

      if (points.back()->size() != labels.back()->size()) {
        std::cout << "Filename: " << velodyne_filenames_[t] << std::endl;
        std::cout << "Filename: " << label_filenames_[t] << std::endl;
        std::cout << "num. points = " << points.back()->size() << " vs. num. labels = " << labels.back()->size()
                  << std::endl;
        throw std::runtime_error("Inconsistent number of labels.");
      }

    } else {
      points.push_back(pointsCache_[t]);
      labels.push_back(labelCache_[t]);
    }

    images.push_back(image_filenames_[t]);
  }

  std::cout << ">>> " << scansRead << " point clouds read." << std::endl;

  // FIXME: keep more scans in cache. not only remove unloaded scans.

  std::sort(indexesBefore.begin(), indexesBefore.end());
  std::sort(indexesAfter.begin(), indexesAfter.end());

  std::vector<int32_t> needsDelete(indexesBefore.size());
  std::vector<int32_t>::iterator end = std::set_difference(
      indexesBefore.begin(), indexesBefore.end(), indexesAfter.begin(), indexesAfter.end(), needsDelete.begin());

  for (auto it = needsDelete.begin(); it != end; ++it) {
    pointsCache_.erase(*it);
    labelCache_.erase(*it);
  }
}

const KittiReader::Tile& KittiReader::getTile(const Eigen::Vector3f& position) const {
  Eigen::Vector2f idx((position.x() + offset_.x()) / tileSize_, (position.y() + offset_.y()) / tileSize_);
  return tiles_[tileIdxToOffset(idx.x(), idx.y())];
}
const KittiReader::Tile& KittiReader::getTile(uint32_t i, uint32_t j) const { return tiles_[tileIdxToOffset(i, j)]; }

void KittiReader::setTileSize(float size) { tileSize_ = size; }

// Rakshith: Update label file based on current labels marked in tool.
// Update is done across all scans in memory (not just those visible/toggled in the viewer)
void KittiReader::update(const std::vector<uint32_t>& indexes, std::vector<LabelsPtr>& labels) {
  std::cout << ">>> Updating labels as per changes made in viewer." << std::endl;
  for (uint32_t i = 0; i < indexes.size(); ++i) {
    if (labels[i]->size() == 0) {
      std::cout << "Warning: 0 labels?" << std::endl;
      continue;
    }

    if (pointsCache_.find(indexes[i]) == pointsCache_.end()) {
      std::cout << "Warning: labels of non cached points?" << std::endl;
      continue;
    }

    if (labels[i]->size() != pointsCache_[indexes[i]]->size()) {
      std::cout << "Warning: inconsistent numbers of labels for given point cloud!" << std::endl;

      continue;
    }

    if (label_filenames_.size() < indexes[i]) {
      std::cout << "Warning: wrong index?" << std::endl;

      continue;
    }

    if(b_bin_label) {
      // Rakshith: Update label file. By default triggered on pressing save button.
      std::ofstream out(label_filenames_[indexes[i]].c_str());
      // labels = vector<LabelsPtr>;
      // From commons.h: typedef std::shared_ptr<std::vector<uint32_t>> LabelsPtr;
      // So, labels[i] => LabelsPtr => std::vector<uint32_t>
      // (const char*)&(*labels[i])[0] ==> labels[i] = ptr to label data-struct, * dereferences it,
      // Of that, reference/memo-addr of 0th idx is typecasted to (const char*)
      // And a chunk of labels[i]->size() * sizeof(unint32_t) is written to disk as binary.
      out.write((const char*)&(*labels[i])[0], labels[i]->size() * sizeof(uint32_t));
      out.close();
    }
    else {
      std::cout << ">>> Updating label file: " << label_filenames_[indexes[i]].c_str() << std::endl;
      std::ofstream out(label_filenames_[indexes[i]].c_str());

      std::string str;
      str += "FORMAT: POINT_IDX_IN_CLOUD, CLAstr_LABEL\n";

      LabelsPtr labels_for_this_scan = labels[i]; // labels for this scan
      int num_points = labels_for_this_scan->size(); // Assuming one label per points, number of labels = number of points in this scan
      for(int i = 0; i < num_points; ++i) {

        int class_label_for_point = (*labels_for_this_scan)[i];
        str += std::to_string(i) + " " + std::to_string( class_label_for_point ) + "\n";
      }
      out << str;

      out.close();
    }
  }
}

void KittiReader::readPoints(const std::string& filename, Laserscan& scan) {

  if(b_bin_cloud) {
    std::ifstream in(filename.c_str(), std::ios::binary);
    if (!in.is_open()) return;

    scan.clear();

    in.seekg(0, std::ios::end);
    uint32_t num_points = in.tellg() / (4 * sizeof(float));
    in.seekg(0, std::ios::beg);

    std::vector<float> values(4 * num_points);
    in.read((char*)&values[0], 4 * num_points * sizeof(float));

    //@Rakshith
    // std::cout << "num_points: " << num_points << std::endl;
    // std::cout << "sizeof(float): " << sizeof(float) << std::endl;
    // std::cout << "4*sizeof(float): " << 4*sizeof(float) << std::endl;
    // std::cout << "4*num_points*sizeof(float): " << 4*num_points*sizeof(float) << std::endl;

    in.close();

    // Operations are on REFERENCE of "scan.points" and "scan.remissions".
    // So effectively changing "points" and "remissions" variables is changing the "scan" variable!!
    // By convention "scan" should have been accepted as a reference in the funciton call itself rather than here.
    std::vector<Point3f>& points = scan.points;
    std::vector<float>& remissions = scan.remissions;

    points.resize(num_points);
    remissions.resize(num_points);

    for (uint32_t i = 0; i < num_points; ++i) {
      points[i].x = values[4 * i];
      points[i].y = values[4 * i + 1];
      points[i].z = values[4 * i + 2];
      remissions[i] = values[4 * i + 3];
    }
  }
  else
  {
    scan.clear();

    // Operations are on REFERENCE of "scan.points" and "scan.remissions".
    // So effectively changing "points" and "remissions" variables is changing the "scan" variable!!
    // By convention "scan" should have been accepted as a reference in the funciton call itself rather than here.
    std::vector<Point3f>& points = scan.points;
    std::vector<float>& remissions = scan.remissions;

    pcl::PointCloud<PT_TYPE>::Ptr tmpCloud (new pcl::PointCloud<PT_TYPE>);
    if (pcl::io::loadPCDFile<PT_TYPE> (filename, *tmpCloud) == -1) {
        PCL_ERROR ("Couldn't read PCD file. \n");
    }
    int num_points = tmpCloud->size();
    std::cout << "size: " << num_points << std::endl;

    points.resize(num_points);
    remissions.resize(num_points);

    PT_TYPE pt;
    for (int i = 0; i < num_points; ++i) {
      pt = tmpCloud->points[i];
      points[i].x = pt.x;
      points[i].y = pt.y;
      points[i].z = pt.z;
      remissions[i] = pt.intensity;
    }
  }
}

// void KittiReader::readLabels(const std::string& filename, std::vector<uint32_t>& labels) {
void KittiReader::readLabels(const std::string& filename, std::vector<uint32_t>& labels, uint32_t cloud_num_points) {

  if(b_bin_label) {
    std::ifstream in(filename.c_str(), std::ios::binary);
    if (!in.is_open()) {
      std::cerr << "Unable to open label file. " << std::endl;
      return;
    }

    labels.clear();

    in.seekg(0, std::ios::end);
    uint32_t num_points = in.tellg() / (sizeof(uint32_t));
    in.seekg(0, std::ios::beg);

    labels.resize(num_points);
    in.read((char*)&labels[0], num_points * sizeof(uint32_t));

    in.close();
  }
  else
  {
    labels.clear();
    labels.resize(cloud_num_points); // need to re-read PCD file to figure size of cloud so just passing as parameter (OR) can just let C++ resize automatically.

    std::ifstream in(filename.c_str(), std::ios_base::in);

    // Get rid of header lines
    std::string line;
    std::getline(in, line);
    // std::cout << "HEADER LINE 1: " << line << std::endl;

    // process other lines
    int ctr = 0;
    std::string point_index_str, class_label_str;
    uint32_t point_index, class_label;
    while (std::getline(in, line))
    {
        // Read labels
        std::stringstream ss(line);
        ss >> point_index_str >> class_label_str;

        point_index = std::stoi(point_index_str);
        class_label = std::stoi(class_label_str);

        // For now, we are sure that point_indices are continuous and
        // no missing/skipped numbers exist so can use point_index stored in files
        labels[point_index] = class_label;
        // labels[ctr] = class_label; // otherwise just use a counter variable.

        ctr += 1;
    }
    std::cout << "size: " << ctr << std::endl;
  }

}

void KittiReader::readPoses(const std::string& filename, std::vector<Eigen::Matrix4f>& poses) {

  std::cout << ">>> Reading pose file." << std::endl;

  poses = KITTI::Odometry::loadPoses(filename);

  // convert from camera to velodyne coordinate system.
  Eigen::Matrix4f Tr = calib_["Tr"];
  Eigen::Matrix4f Tr_inv = Tr.inverse();
  for (uint32_t i = 0; i < poses.size(); ++i) {
    poses[i] = Tr_inv * poses[i] * Tr;
  }

}

// TODO Rakshith Tree Mapping:
/*

* Note process: load multiple view and label single, multiple in range, or all based on what is visible in an overlapping manner
save all that are in memory (not only visible ones) to file

* Label output in Ascii.
* Label loading from Ascii.

* Depending on the labelling method and how points are being stored, may or may not need to read from pcd.
* MIGHT MAKE THIS TASK EASY IF LABELS ARE ADDED POINTWISE.
* OR even if reading from PCD, just do it such that it is read from pcd and then changed to binary as required by rest of the tool.
* Reading pcd as pcd files than binary -- for easy no pcd to binary conversion, XYZIR info retained rather than just XYZI, individual manipulation, ability to read as ascii when opened and later rviz visualization, etc.

* change extension to .pcd and .asciilabel once changes have been made.

Useful features:

single scan
scan range

follow pose

brush vs polygon

overlap labels

automatically save

selecting tiles to control total RAM used

view: perspective vs orthographic

*/


text:
#include <pybind11/eigen.h>
#include <pybind11/stl_bind.h>
#include <pybind11/pybind11.h>
#include "gtsam/nonlinear/utilities.h"  // for RedirectCout.

#include "gtsam/geometry/Point2.h"
#include "gtsam/geometry/Point3.h"
#include "folder/path/to/Test.h"

#include "wrap/serialization.h"
#include <boost/serialization/export.hpp>

BOOST_CLASS_EXPORT(gtsam::Point2)
BOOST_CLASS_EXPORT(gtsam::Point3)

using namespace std;

namespace py = pybind11;

PYBIND11_MODULE(geometry_py, m_) {
    m_.doc() = "pybind11 wrapper of geometry_py";

    pybind11::module m_gtsam = m_.def_submodule("gtsam", "gtsam submodule");

    py::class_<gtsam::Point2, std::shared_ptr<gtsam::Point2>>(m_gtsam, "Point2")
        .def(py::init<>())
        .def(py::init< double,  double>(), py::arg("x"), py::arg("y"))
        .def("x",[](gtsam::Point2* self){return self->x();})
        .def("y",[](gtsam::Point2* self){return self->y();})
        .def("dim",[](gtsam::Point2* self){return self->dim();})
        .def("returnChar",[](gtsam::Point2* self){return self->returnChar();})
        .def("argChar",[](gtsam::Point2* self, char a){ self->argChar(a);}, py::arg("a"))
        .def("argUChar",[](gtsam::Point2* self, unsigned char a){ self->argUChar(a);}, py::arg("a"))
        .def("eigenArguments",[](gtsam::Point2* self,const gtsam::Vector& v,const gtsam::Matrix& m){ self->eigenArguments(v, m);}, py::arg("v"), py::arg("m"))
        .def("vectorConfusion",[](gtsam::Point2* self){return self->vectorConfusion();})
.def("serialize",
    [](gtsam::Point2* self){
        return gtsam::serialize(*self);
    }
)
.def("deserialize",
    [](gtsam::Point2* self, string serialized){
        gtsam::deserialize(serialized, *self);
    }, py::arg("serialized"))
;

    py::class_<gtsam::Point3, std::shared_ptr<gtsam::Point3>>(m_gtsam, "Point3")
        .def(py::init< double,  double,  double>(), py::arg("x"), py::arg("y"), py::arg("z"))
        .def("norm",[](gtsam::Point3* self){return self->norm();})
.def("serialize",
    [](gtsam::Point3* self){
        return gtsam::serialize(*self);
    }
)
.def("deserialize",
    [](gtsam::Point3* self, string serialized){
        gtsam::deserialize(serialized, *self);
    }, py::arg("serialized"))

        .def_static("staticFunction",[](){return gtsam::Point3::staticFunction();})
        .def_static("StaticFunctionRet",[]( double z){return gtsam::Point3::StaticFunctionRet(z);}, py::arg("z"));

    py::class_<Test, std::shared_ptr<Test>>(m_, "Test")
        .def(py::init<>())
        .def(py::init< double, const gtsam::Matrix&>(), py::arg("a"), py::arg("b"))
        .def("return_pair",[](Test* self,const gtsam::Vector& v,const gtsam::Matrix& A){return self->return_pair(v, A);}, py::arg("v"), py::arg("A"))
        .def("return_pair",[](Test* self,const gtsam::Vector& v){return self->return_pair(v);}, py::arg("v"))
        .def("return_bool",[](Test* self, bool value){return self->return_bool(value);}, py::arg("value"))
        .def("return_size_t",[](Test* self, size_t value){return self->return_size_t(value);}, py::arg("value"))
        .def("return_int",[](Test* self, int value){return self->return_int(value);}, py::arg("value"))
        .def("return_double",[](Test* self, double value){return self->return_double(value);}, py::arg("value"))
        .def("return_string",[](Test* self, string value){return self->return_string(value);}, py::arg("value"))
        .def("return_vector1",[](Test* self,const gtsam::Vector& value){return self->return_vector1(value);}, py::arg("value"))
        .def("return_matrix1",[](Test* self,const gtsam::Matrix& value){return self->return_matrix1(value);}, py::arg("value"))
        .def("return_vector2",[](Test* self,const gtsam::Vector& value){return self->return_vector2(value);}, py::arg("value"))
        .def("return_matrix2",[](Test* self,const gtsam::Matrix& value){return self->return_matrix2(value);}, py::arg("value"))
        .def("arg_EigenConstRef",[](Test* self,const gtsam::Matrix& value){ self->arg_EigenConstRef(value);}, py::arg("value"))
        .def("return_field",[](Test* self,const Test& t){return self->return_field(t);}, py::arg("t"))
        .def("return_TestPtr",[](Test* self,const std::shared_ptr<Test>& value){return self->return_TestPtr(value);}, py::arg("value"))
        .def("return_Test",[](Test* self,const std::shared_ptr<Test>& value){return self->return_Test(value);}, py::arg("value"))
        .def("return_Point2Ptr",[](Test* self, bool value){return self->return_Point2Ptr(value);}, py::arg("value"))
        .def("create_ptrs",[](Test* self){return self->create_ptrs();})
        .def("create_MixedPtrs",[](Test* self){return self->create_MixedPtrs();})
        .def("return_ptrs",[](Test* self,const std::shared_ptr<Test>& p1,const std::shared_ptr<Test>& p2){return self->return_ptrs(p1, p2);}, py::arg("p1"), py::arg("p2"))
        .def("print_",[](Test* self){ self->print();})
        .def("__repr__",
                    [](const Test &a) {
                        gtsam::RedirectCout redirect;
                        a.print();
                        return redirect.str();
                    });

    py::class_<MyBase, std::shared_ptr<MyBase>>(m_, "MyBase");

    py::class_<MyTemplate<gtsam::Point2>, MyBase, std::shared_ptr<MyTemplate<gtsam::Point2>>>(m_, "MyTemplatePoint2")
        .def(py::init<>())
        .def("templatedMethodPoint2",[](MyTemplate<gtsam::Point2>* self,const gtsam::Point2& t){return self->templatedMethod<gtsam::Point2>(t);}, py::arg("t"))
        .def("templatedMethodPoint3",[](MyTemplate<gtsam::Point2>* self,const gtsam::Point3& t){return self->templatedMethod<gtsam::Point3>(t);}, py::arg("t"))
        .def("templatedMethodVector",[](MyTemplate<gtsam::Point2>* self,const gtsam::Vector& t){return self->templatedMethod<gtsam::Vector>(t);}, py::arg("t"))
        .def("templatedMethodMatrix",[](MyTemplate<gtsam::Point2>* self,const gtsam::Matrix& t){return self->templatedMethod<gtsam::Matrix>(t);}, py::arg("t"))
        .def("accept_T",[](MyTemplate<gtsam::Point2>* self,const gtsam::Point2& value){ self->accept_T(value);}, py::arg("value"))
        .def("accept_Tptr",[](MyTemplate<gtsam::Point2>* self,const std::shared_ptr<gtsam::Point2>& value){ self->accept_Tptr(value);}, py::arg("value"))
        .def("return_Tptr",[](MyTemplate<gtsam::Point2>* self,const std::shared_ptr<gtsam::Point2>& value){return self->return_Tptr(value);}, py::arg("value"))
        .def("return_T",[](MyTemplate<gtsam::Point2>* self,const std::shared_ptr<gtsam::Point2>& value){return self->return_T(value);}, py::arg("value"))
        .def("create_ptrs",[](MyTemplate<gtsam::Point2>* self){return self->create_ptrs();})
        .def("create_MixedPtrs",[](MyTemplate<gtsam::Point2>* self){return self->create_MixedPtrs();})
        .def("return_ptrs",[](MyTemplate<gtsam::Point2>* self,const std::shared_ptr<gtsam::Point2>& p1,const std::shared_ptr<gtsam::Point2>& p2){return self->return_ptrs(p1, p2);}, py::arg("p1"), py::arg("p2"))
        .def_static("Level",[](const gtsam::Point2& K){return MyTemplate<gtsam::Point2>::Level(K);}, py::arg("K"));

    py::class_<MyTemplate<gtsam::Matrix>, MyBase, std::shared_ptr<MyTemplate<gtsam::Matrix>>>(m_, "MyTemplateMatrix")
        .def(py::init<>())
        .def("templatedMethodPoint2",[](MyTemplate<gtsam::Matrix>* self,const gtsam::Point2& t){return self->templatedMethod<gtsam::Point2>(t);}, py::arg("t"))
        .def("templatedMethodPoint3",[](MyTemplate<gtsam::Matrix>* self,const gtsam::Point3& t){return self->templatedMethod<gtsam::Point3>(t);}, py::arg("t"))
        .def("templatedMethodVector",[](MyTemplate<gtsam::Matrix>* self,const gtsam::Vector& t){return self->templatedMethod<gtsam::Vector>(t);}, py::arg("t"))
        .def("templatedMethodMatrix",[](MyTemplate<gtsam::Matrix>* self,const gtsam::Matrix& t){return self->templatedMethod<gtsam::Matrix>(t);}, py::arg("t"))
        .def("accept_T",[](MyTemplate<gtsam::Matrix>* self,const gtsam::Matrix& value){ self->accept_T(value);}, py::arg("value"))
        .def("accept_Tptr",[](MyTemplate<gtsam::Matrix>* self,const std::shared_ptr<gtsam::Matrix>& value){ self->accept_Tptr(value);}, py::arg("value"))
        .def("return_Tptr",[](MyTemplate<gtsam::Matrix>* self,const std::shared_ptr<gtsam::Matrix>& value){return self->return_Tptr(value);}, py::arg("value"))
        .def("return_T",[](MyTemplate<gtsam::Matrix>* self,const std::shared_ptr<gtsam::Matrix>& value){return self->return_T(value);}, py::arg("value"))
        .def("create_ptrs",[](MyTemplate<gtsam::Matrix>* self){return self->create_ptrs();})
        .def("create_MixedPtrs",[](MyTemplate<gtsam::Matrix>* self){return self->create_MixedPtrs();})
        .def("return_ptrs",[](MyTemplate<gtsam::Matrix>* self,const std::shared_ptr<gtsam::Matrix>& p1,const std::shared_ptr<gtsam::Matrix>& p2){return self->return_ptrs(p1, p2);}, py::arg("p1"), py::arg("p2"))
        .def_static("Level",[](const gtsam::Matrix& K){return MyTemplate<gtsam::Matrix>::Level(K);}, py::arg("K"));

    py::class_<PrimitiveRef<double>, std::shared_ptr<PrimitiveRef<double>>>(m_, "PrimitiveRefdouble")
        .def(py::init<>())
        .def_static("Brutal",[](const double& t){return PrimitiveRef<double>::Brutal(t);}, py::arg("t"));

    py::class_<MyVector<3>, std::shared_ptr<MyVector<3>>>(m_, "MyVector3")
        .def(py::init<>());

    py::class_<MyVector<12>, std::shared_ptr<MyVector<12>>>(m_, "MyVector12")
        .def(py::init<>());

    py::class_<MyFactor<gtsam::Pose2, gtsam::Matrix>, std::shared_ptr<MyFactor<gtsam::Pose2, gtsam::Matrix>>>(m_, "MyFactorPosePoint2")
        .def(py::init< size_t,  size_t,  double, const std::shared_ptr<gtsam::noiseModel::Base>&>(), py::arg("key1"), py::arg("key2"), py::arg("measured"), py::arg("noiseModel"));

    m_.def("load2D",[]( string filename,const std::shared_ptr<Test>& model, int maxID, bool addNoise, bool smart){return ::load2D(filename, model, maxID, addNoise, smart);}, py::arg("filename"), py::arg("model"), py::arg("maxID"), py::arg("addNoise"), py::arg("smart"));
    m_.def("load2D",[]( string filename,const std::shared_ptr<gtsam::noiseModel::Diagonal>& model, int maxID, bool addNoise, bool smart){return ::load2D(filename, model, maxID, addNoise, smart);}, py::arg("filename"), py::arg("model"), py::arg("maxID"), py::arg("addNoise"), py::arg("smart"));
    m_.def("load2D",[]( string filename,const std::shared_ptr<gtsam::noiseModel::Diagonal>& model){return ::load2D(filename, model);}, py::arg("filename"), py::arg("model"));
    m_.def("aGlobalFunction",[](){return ::aGlobalFunction();});
    m_.def("overloadedGlobalFunction",[]( int a){return ::overloadedGlobalFunction(a);}, py::arg("a"));
    m_.def("overloadedGlobalFunction",[]( int a, double b){return ::overloadedGlobalFunction(a, b);}, py::arg("a"), py::arg("b"));

#include "python/specializations.h"

}

ext: cpp

max_stars_repo_name: coestreich/gtsam

max_issues_repo_name: coestreich/gtsam

max_forks_repo_name: coestreich/gtsam


text:
// Boost.Signals library

// Copyright Douglas Gregor 2001-2004. Use, modification and
// distribution is subject to the Boost Software License, Version
// 1.0. (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)

// For more information, see http://www.boost.org

#ifndef BOOST_SIGNALS_CONNECTION_HPP
#define BOOST_SIGNALS_CONNECTION_HPP

#include <boost/signals/detail/signals_common.hpp>
#include <boost/smart_ptr.hpp>
#include <boost/operators.hpp>
#include <boost/any.hpp>
#include <list>
#include <cassert>
#include <utility>

#ifdef BOOST_HAS_ABI_HEADERS
#  include BOOST_ABI_PREFIX
#endif

namespace boost {
  namespace BOOST_SIGNALS_NAMESPACE {
    class trackable;

    namespace detail {
      // Represents an object that has been bound as part of a slot, and how
      // to notify that object of a disconnect
      struct bound_object {
        void* obj;
        void* data;
        void (*disconnect)(void*, void*);

        bool operator==(const bound_object& other) const
          { return obj == other.obj && data == other.data; }
        bool operator<(const bound_object& other) const
          { return obj < other.obj; }

        // To support intel 80 compiler, 2004/03/18 (Mark Rodgers)
        bool operator!=(const bound_object& other) const
        { return !(*this==other); }
        bool operator>(const bound_object& other) const
        { return !(*this < other); }
      };

      // Describes the connection between a signal and the objects that are
      // bound for a specific slot. Enables notification of the signal and the
      // slots when a disconnect is requested.
      struct basic_connection {
        void* signal;
        void* signal_data;
        void (*signal_disconnect)(void*, void*);

        std::list<bound_object> bound_objects;
      };
    } // end namespace detail

    // The user may freely pass around the "connection" object and terminate
    // the connection at any time using disconnect().
    class BOOST_SIGNALS_DECL connection :
      private less_than_comparable1<connection>,
      private equality_comparable1<connection>
    {
    public:
      connection() : con(), controlling_connection(false) {}
      connection(const connection&);
      ~connection();

      // Disconnect the signal and slot, if they are connected
      void disconnect() const;

      // Returns true if the signal and slot are connected
      bool connected() const { return con.get() && con->signal_disconnect; }

      // Comparison of connections
      bool operator==(const connection& other) const;
      bool operator<(const connection& other) const;

      // Connection assignment
      connection& operator=(const connection& other) ;

      // Swap connections
      void swap(connection& other);

    public: // TBD: CHANGE THIS
      // Set whether this connection object is controlling or not
      void set_controlling(bool control = true)
      { controlling_connection = control; }

      shared_ptr<BOOST_SIGNALS_NAMESPACE::detail::basic_connection>
      get_connection() const
      { return con; }

    private:
      friend class detail::signal_base_impl;
      friend class detail::slot_base;
      friend class trackable;

      // Reset this connection to refer to a different actual connection
      void reset(BOOST_SIGNALS_NAMESPACE::detail::basic_connection*);

      // Add a bound object to this connection (not for users)
      void add_bound_object(const BOOST_SIGNALS_NAMESPACE::detail::bound_object& b);

      friend class BOOST_SIGNALS_NAMESPACE::detail::bound_objects_visitor;

      // Pointer to the actual contents of the connection
      shared_ptr<BOOST_SIGNALS_NAMESPACE::detail::basic_connection> con;

      // True if the destruction of this connection object should disconnect
      bool controlling_connection;
    };

    // Similar to connection, but will disconnect the connection when it is
    // destroyed unless release() has been called.
    class BOOST_SIGNALS_DECL scoped_connection : public connection {
    public:
      scoped_connection() : connection(), released(false) {}
      scoped_connection(const connection&);
      scoped_connection(const scoped_connection&);
      ~scoped_connection();

      connection release();

      inline void swap(scoped_connection&);

      scoped_connection& operator=(const connection&);
      scoped_connection& operator=(const scoped_connection&);

    private:
      bool released;
    };

    namespace detail {
      struct connection_slot_pair {
        connection first;
        any second;

        connection_slot_pair() {}

        connection_slot_pair(const connection& c, const any& a)
          : first(c), second(a)
        {
        }

        // Dummys to allow explicit instantiation to work
        bool operator==(const connection_slot_pair&) const { return false; }
        bool operator<(const connection_slot_pair&) const { return false;}
      };

      // Determines if the underlying connection is disconnected
      struct is_disconnected {
        typedef connection_slot_pair argument_type;
        typedef bool result_type;

        inline bool operator()(const argument_type& c) const
        {
          return !c.first.connected();
        }
      };

      // Autodisconnects the bound object when it is destroyed unless the
      // release method is invoked.
      class auto_disconnect_bound_object {
      public:
        auto_disconnect_bound_object(const bound_object& b) :
          binding(b), auto_disconnect(true)
        {
        }

        ~auto_disconnect_bound_object()
        {
          if (auto_disconnect)
            binding.disconnect(binding.obj, binding.data);
        }

        void release() { auto_disconnect = false; }

      private:
        bound_object binding;
        bool auto_disconnect;
      };
    } // end namespace detail
  } // end namespace BOOST_SIGNALS_NAMESPACE
} // end namespace boost

#ifdef BOOST_HAS_ABI_HEADERS
#  include BOOST_ABI_SUFFIX
#endif

#endif // BOOST_SIGNALS_CONNECTION_HPP

ext: hpp

max_stars_repo_name: Imperator-Knoedel/Sunset

max_issues_repo_name: Imperator-Knoedel/Sunset

max_forks_repo_name: Imperator-Knoedel/Sunset


text:
/**
 * @file
 *
 * 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
 */

#define TENUM_USE_SHORTCUTS 1
#include "tenum.hpp"

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

lte_bit_field(bit_field,
    lte_ev(bit1,0b0001)
    lte_ev(bit2,0b0010)
    lte_ev(bit3,0b0100)
    lte_evn(bit4,0b1000,"last_bit"),
    ::boost::uint16_t
)

/**
 * @defgroup bit_field_tests Bit fields test cases
 */
BOOST_AUTO_TEST_SUITE(bit_field_tests)

/**
 * @class test_bit_field_from_or_serialization
 * @brief Tests bit field construction from '|' operator and serialization.
 * @ingroup bit_field_tests
 */
BOOST_AUTO_TEST_CASE(test_bit_field_from_or_serialization) {
  bit_field_t enum_value = static_cast< bit_field_t > (bit_field::bit1 | bit_field::bit2);
  ::std::string string_value;
  ::std::stringstream stream;
  stream << enum_value;
  stream >> string_value;
  BOOST_CHECK_EQUAL(string_value,"bit1+bit2");
}

/**
 * @class test_bit_field_serialization_explicit
 * @brief Tests bit field serialization with an explicit string equivalent.
 * @ingroup bit_field_tests
 */
BOOST_AUTO_TEST_CASE(test_bit_field_serialization_explicit) {
  bit_field_t enum_value = static_cast< bit_field_t > (bit_field::bit2 | bit_field::bit4);
  ::std::string string_value;
  ::std::stringstream stream;
  stream << enum_value;
  stream >> string_value;
  BOOST_CHECK_EQUAL(string_value,"bit2+last_bit");
}

/**
 * @class test_bit_field_from_int_serialization
 * @brief Tests bit field construction from integer and serialization.
 * @ingroup bit_field_tests
 */
BOOST_AUTO_TEST_CASE(test_bit_field_from_int_serialization) {
  bit_field_t enum_value = static_cast< bit_field_t > (0b110);
  ::std::string string_value;
  ::std::stringstream stream;
  stream << enum_value;
  stream >> string_value;
  BOOST_CHECK_EQUAL(string_value,"bit2+bit3");
}

/**
 * @class test_bit_field_deserialization
 * @brief Tests bit field deserialization and comparison.
 * @ingroup bit_field_tests
 */
BOOST_AUTO_TEST_CASE(test_bit_field_deserialization) {
  bit_field_t enum_value;
  ::std::string string_value = "bit1+bit3";
  ::std::stringstream stream;
  stream << string_value;
  stream >> enum_value;
  BOOST_CHECK_EQUAL(enum_value,static_cast< bit_field_t > (bit_field::bit1 | bit_field::bit3));
  BOOST_CHECK_EQUAL(enum_value,static_cast< bit_field_t > (0b101));
}

/**
 * @class test_bit_field_or_variable
 * @brief Tests bit field '|' operator between Bit field variable and constants and serialization.
 * @ingroup bit_field_tests
 */
BOOST_AUTO_TEST_CASE(test_bit_field_or_variable) {
  bit_field_t enum_value = static_cast< bit_field_t > (bit_field::bit1 | bit_field::bit2);
  enum_value = static_cast< bit_field_t > (enum_value | bit_field::bit3);
  ::std::string string_value;
  ::std::stringstream stream;
  stream << enum_value;
  stream >> string_value;
  BOOST_CHECK_EQUAL(string_value,"bit1+bit2+bit3");
}

/**
 * @class test_bit_field_xor_variable
 * @brief Tests bit field '^' operator between Bit field variable and constants and serialization.
 * @ingroup bit_field_tests
 */
BOOST_AUTO_TEST_CASE(test_bit_field_xor_variable) {
  bit_field_t enum_value = static_cast< bit_field_t > (bit_field::bit1 | bit_field::bit2);
  enum_value = static_cast< bit_field_t > (enum_value ^ bit_field::bit2);
  ::std::string string_value;
  ::std::stringstream stream;
  stream << enum_value;
  stream >> string_value;
  BOOST_CHECK_EQUAL(string_value,"bit1");
}

/**
 * @class test_bit_field_empty_serialization
 * @brief Tests empty Bit field serialization.
 * @ingroup bit_field_tests
 */
BOOST_AUTO_TEST_CASE(test_bit_field_empty_serialization) {
  bit_field_t enum_value = static_cast< bit_field_t > (0);
  ::std::string string_value;
  ::std::stringstream stream;
  stream << enum_value;
  stream >> string_value;
  BOOST_CHECK_EQUAL(string_value,"");
}

/**
 * @class test_bit_field_empty_deserialization
 * @brief Tests empty Bit field deserialization.
 * @ingroup bit_field_tests
 */
BOOST_AUTO_TEST_CASE(test_bit_field_empty_deserialization) {
  bit_field_t enum_value;
  ::std::string string_value = "";
  ::std::stringstream stream;
  stream << string_value;
  stream >> enum_value;
  BOOST_CHECK_EQUAL(enum_value,static_cast< bit_field_t > (0));
}

/**
 * @class test_bit_field_integers_eq
 * @brief Tests bit field integer equality operator.
 * @ingroup bit_field_tests
 */
BOOST_AUTO_TEST_CASE(test_bit_field_integers_eq) {
  bit_field_t enum_value = bit_field::bit2;
  ::boost::uint64_t integer_value = 2;
  BOOST_CHECK(integer_value == enum_value);
  BOOST_CHECK(enum_value == integer_value);
}

/**
 * @class test_bit_field_integers_neq
 * @brief Tests bit field integer inequality operator.
 * @ingroup bit_field_tests
 */
BOOST_AUTO_TEST_CASE(test_bit_field_integers_neq) {
  bit_field_t enum_value = bit_field::bit2;
  ::boost::uint64_t integer_value = 0;
  BOOST_CHECK(integer_value != enum_value);
  BOOST_CHECK(enum_value != integer_value);
}

/**
 * @class test_bit_field_integers_bitwise_and
 * @brief Tests integer bitwise and operator with bit field.
 * @ingroup bit_field_tests
 */
BOOST_AUTO_TEST_CASE(test_bit_field_integers_bitwise_and) {
  bit_field_t enum_value = bit_field::bit2;
  ::boost::uint64_t integer_value1 = 0b011 & enum_value;
  BOOST_CHECK(integer_value1 == 0b010);
  ::boost::uint64_t integer_value2 = enum_value & 0b011;
  BOOST_CHECK(integer_value2 == 0b010);
}

/**
 * @class test_bit_field_integers_bitwise_or
 * @brief Tests integer bitwise or operator with bit field.
 * @ingroup bit_field_tests
 */
BOOST_AUTO_TEST_CASE(test_bit_field_integers_bitwise_or) {
  bit_field_t enum_value = bit_field::bit2;
  ::boost::uint64_t integer_value1 = 0b001 | enum_value;
  BOOST_CHECK(integer_value1 == 0b011);
  ::boost::uint64_t integer_value2 = enum_value | 0b001;
  BOOST_CHECK(integer_value2 == 0b011);
}

/**
 * @class test_bit_field_integers_bitwise_xor
 * @brief Tests integer bitwise xor operator with bit field.
 * @ingroup bit_field_tests
 */
BOOST_AUTO_TEST_CASE(test_bit_field_integers_bitwise_xor) {
  bit_field_t enum_value = bit_field::bit2;
  ::boost::uint64_t integer_value1 = 0b011 ^ enum_value;
  BOOST_CHECK(integer_value1 == 0b001);
  ::boost::uint64_t integer_value2 = enum_value ^ 0b011;
  BOOST_CHECK(integer_value2 == 0b001);
}

/**
 * @class test_bit_field_integers_bitwise_and_assign
 * @brief Tests integer bitwise and assination operator with bit field.
 * @ingroup bit_field_tests
 */
BOOST_AUTO_TEST_CASE(test_bit_field_integers_bitwise_and_assign) {
  bit_field_t enum_value = bit_field::bit2;
  ::boost::uint64_t integer_value = 0b011;
  integer_value &= enum_value;
  BOOST_CHECK(integer_value == 0b010);
}

/**
 * @class test_bit_field_integers_bitwise_or_assign
 * @brief Tests integer bitwise or assination operator with bit field.
 * @ingroup bit_field_tests
 */
BOOST_AUTO_TEST_CASE(test_bit_field_integers_bitwise_or_assign) {
  bit_field_t enum_value = bit_field::bit2;
  ::boost::uint64_t integer_value = 0b001;
  integer_value |= enum_value;
  BOOST_CHECK(integer_value == 0b011);
}

/**
 * @class test_bit_field_integers_bitwise_xor_assign
 * @brief Tests integer bitwise xor assination operator with bit field.
 * @ingroup bit_field_tests
 */
BOOST_AUTO_TEST_CASE(test_bit_field_integers_bitwise_xor_assign) {
  bit_field_t enum_value = bit_field::bit2;
  ::boost::uint64_t integer_value = 0b011;
  integer_value ^= enum_value;
  BOOST_CHECK(integer_value == 0b001);
}

BOOST_AUTO_TEST_SUITE_END()

max_stars_repo_name: berenm/libtenum

max_issues_repo_name: berenm/libtenum

max_forks_repo_name: berenm/libtenum


text:
// test/string/atom.cpp

#include <boost/test/unit_test.hpp>

#include <wordring/string/atom.hpp>

#include <algorithm>
#include <iterator>
#include <iomanip>
#include <memory>
#include <string>

BOOST_AUTO_TEST_SUITE(atom__test)

// ----------------------------------------------------------------------------
// basic_atom
// ----------------------------------------------------------------------------

/*
空のアトムを構築する

basic_atom()
*/
BOOST_AUTO_TEST_CASE(basic_atom__construct__1)
{
	using namespace wordring::detail;

	basic_atom<std::string> a;
}

/*
アトムをIDに変換する

operator std::uint32_t() const
*/
BOOST_AUTO_TEST_CASE(basic_atom__id__1)
{
	using namespace wordring;
	using namespace wordring::detail;

	std::vector<std::u32string> v{ U"あ", U"あう", U"い", U"うあい", U"うえ" };
	auto as = basic_atom_set<std::u32string>(v.begin(), v.end());

	auto a = as.at(U"い");
	std::uint32_t i = a;

	BOOST_CHECK(i != 0);
}

BOOST_AUTO_TEST_CASE(basic_atom__id__2)
{
	using namespace wordring;
	using namespace wordring::detail;

	std::vector<std::u32string> v{ U"あ", U"あう", U"い", U"うあい", U"うえ" };
	auto as = basic_atom_set<std::u32string>(v.begin(), v.end());

	auto a = as.at(U"");
	std::uint32_t i = a;

	BOOST_CHECK(i == 0);
}

/*
アトムを文字列に変換する

operator string_type() const
*/
BOOST_AUTO_TEST_CASE(basic_atom__string__1)
{
	using namespace wordring;
	using namespace wordring::detail;

	std::vector<std::u32string> v{ U"あ", U"あう", U"い", U"うあい", U"うえ" };
	auto as = basic_atom_set<std::u32string>(v.begin(), v.end());

	auto a = as.at(U"い");
	std::u32string s = a;

	BOOST_CHECK(s == U"い");
}

BOOST_AUTO_TEST_CASE(basic_atom__string__2)
{
	using namespace wordring;
	using namespace wordring::detail;

	std::vector<std::u32string> v{ U"あ", U"あう", U"い", U"うあい", U"うえ" };
	auto as = basic_atom_set<std::u32string>(v.begin(), v.end());

	auto a = as.at(U"");
	std::u32string s = a;

	BOOST_CHECK(s == U"");
}

/*
アトムを文字列に変換する

string_type& string(string_type& result) const
*/
BOOST_AUTO_TEST_CASE(basic_atom__string__3)
{
	using namespace wordring;
	using namespace wordring::detail;

	std::vector<std::u32string> v{ U"あ", U"あう", U"い", U"うあい", U"うえ" };
	auto as = basic_atom_set<std::u32string>(v.begin(), v.end());

	auto a = as.at(U"い");
	std::u32string s;
	a.string(s);

	BOOST_CHECK(s == U"い");
}

BOOST_AUTO_TEST_CASE(basic_atom__string__4)
{
	using namespace wordring;
	using namespace wordring::detail;

	std::vector<std::u32string> v{ U"あ", U"あう", U"い", U"うあい", U"うえ" };
	auto as = basic_atom_set<std::u32string>(v.begin(), v.end());

	auto a = as.at(U"");
	std::u32string s;
	a.string(s);

	BOOST_CHECK(s == U"");
}

/*
二つのアトムが等しいか調べる

inline bool operator==(basic_atom<String1, Allocator1> const& lhs, basic_atom<String1, Allocator1> const& rhs)
*/
BOOST_AUTO_TEST_CASE(basic_atom__equal__1)
{
	using namespace wordring;
	using namespace wordring::detail;

	std::vector<std::u32string> v{ U"あ", U"あう", U"い", U"うあい", U"うえ" };
	auto as = basic_atom_set<std::u32string>(v.begin(), v.end());

	auto a1 = as.at(U"あ");
	auto a2 = as.at(U"あ");

	BOOST_CHECK(a1 == a2);
}

/*
二つのアトムが等しくないか調べる

inline bool operator!=(basic_atom<String1, Allocator1> const& lhs, basic_atom<String1, Allocator1> const& rhs)
*/
BOOST_AUTO_TEST_CASE(basic_atom__not_equal__1)
{
	using namespace wordring;
	using namespace wordring::detail;

	std::vector<std::u32string> v{ U"あ", U"あう", U"い", U"うあい", U"うえ" };
	auto as = basic_atom_set<std::u32string>(v.begin(), v.end());

	auto a1 = as.at(U"あ");
	auto a2 = as.at(U"あう");

	BOOST_CHECK(a1 != a2);
}

// ----------------------------------------------------------------------------
// basic_atom_set
// ----------------------------------------------------------------------------

/*
空のコンテナを構築する

basic_atom_set()
*/
BOOST_AUTO_TEST_CASE(basic_atom_set__construct__1)
{
	using namespace wordring;

	basic_atom_set<std::string> as;
}

/*
アロケータを指定して空のコンテナを構築する

explicit basic_atom_set(allocator_type const& alloc)
*/
BOOST_AUTO_TEST_CASE(basic_atom_set__construct__2)
{
	using namespace wordring;

	basic_atom_set<std::string> as(std::allocator<detail::trie_node>{});
}

/*
直列化データからの構築

basic_atom_set(InputIterator first, InputIterator last, allocator_type const& alloc = allocator_type())
*/
BOOST_AUTO_TEST_CASE(basic_atom_set__construct__3)
{
	using namespace wordring;

	std::vector<std::u32string> v{ U"あ", U"あう", U"い", U"うあい", U"うえ" };
	basic_atom_set<std::u32string> as1(v.begin(), v.end());

	basic_atom_set<std::u32string> as2(as1.ibegin(), as1.iend());

	BOOST_CHECK(as2.contains(std::u32string(U"あ")));
	BOOST_CHECK(as2.contains(std::u32string(U"あう")));
	BOOST_CHECK(as2.contains(std::u32string(U"い")));
	BOOST_CHECK(as2.contains(std::u32string(U"うあい")));
	BOOST_CHECK(as2.contains(std::u32string(U"うえ")));
}

/*
文字列リストからの構築

basic_atom_set(InputIterator first, InputIterator last, allocator_type const& alloc = allocator_type())
*/
BOOST_AUTO_TEST_CASE(basic_atom_set__construct__4)
{
	using namespace wordring;

	std::vector<std::u32string> v{ U"あ", U"あう", U"い", U"うあい", U"うえ" };
	basic_atom_set<std::u32string> as(v.begin(), v.end());

	BOOST_CHECK(as.contains(std::u32string(U"あ")));
	BOOST_CHECK(as.contains(std::u32string(U"あう")));
	BOOST_CHECK(as.contains(std::u32string(U"い")));
	BOOST_CHECK(as.contains(std::u32string(U"うあい")));
	BOOST_CHECK(as.contains(std::u32string(U"うえ")));
}

/*
初期化子リストから構築する

basic_atom_set(std::initializer_list<detail::trie_node> il, allocator_type const& alloc = allocator_type())
*/
BOOST_AUTO_TEST_CASE(basic_atom_set__construct__5)
{
	using namespace wordring;

	/*
	std::vector<std::u32string> v{ U"あ", U"あう", U"い", U"うあい", U"うえ" };
	basic_atom_set<std::u32string> as1(v.begin(), v.end());

	auto it1 = as1.ibegin();
	auto it2 = as1.iend();
	for (std::uint32_t i= 0; it1 != it2; ++i)
	{
		std::int32_t j = *it1++;
		if (i % 2 == 0) std::cout << "{ " << j << ", ";
		else std::cout << j << " }, ";
		if (1 < i && (i - 1) % 16 == 0) std::cout << std::endl;
	}
	*/
	basic_atom_set<std::u32string> as2 = {
		{ 5, -10 }, { 2, 0 }, { 3, 1 }, { 1, 2 }, { 5, 68 }, { 2, 4 }, { 7, 72 }, { 3, 6 }, { 9, 67 },
		{ 4, 8 }, { 0, -11 }, { 0, -12 }, { 0, -13 }, { 0, -14 }, { 0, -15 }, { 0, -16 }, { 0, -17 },
		{ 0, -18 }, { 0, -19 }, { 0, -20 }, { 0, -21 }, { 0, -22 }, { 0, -23 }, { 0, -24 }, { 0, -25 },
		{ 0, -26 }, { 0, -27 }, { 0, -28 }, { 0, -29 }, { 0, -30 }, { 0, -31 }, { 0, -32 }, { 0, -33 },
		{ 0, -34 }, { 0, -35 }, { 0, -36 }, { 0, -37 }, { 0, -38 }, { 0, -39 }, { 0, -40 }, { 0, -41 },
		{ 0, -42 }, { 0, -43 }, { 0, -44 }, { 0, -45 }, { 0, -46 }, { 0, -47 }, { 0, -48 }, { 0, -53 },
		{ 2, 3 }, { 1, 5 }, { 1, 7 }, { 1, 9 }, { 0, -54 }, { 0, -55 }, { 0, -56 }, { 0, -57 },
		{ 0, -58 }, { 0, -59 }, { 0, -60 }, { 0, -61 }, { 0, -62 }, { 0, -63 }, { 0, -64 }, { 0, -65 },
		{ 0, -66 }, { 0, -74 }, { 8, 51 }, { 4, 49 }, { 3, 52 }, { 2, 49 }, { 1, 50 }, { 6, 49 },
		{ 5, 51 }, { 0, -75 }, { 0, -76 }, { 0, -77 }, { 0, -78 }, { 0, -79 }, { 0, -80 }, { 0, -81 },
		{ 0, -82 }, { 0, -83 }, { 0, -84 }, { 0, -85 }, { 0, -86 }, { 0, -87 }, { 0, -88 }, { 0, -89 },
		{ 0, -90 }, { 0, -91 }, { 0, -92 }, { 0, -93 }, { 0, -94 }, { 0, -95 }, { 0, -96 }, { 0, -97 },
		{ 0, -98 }, { 0, -99 }, { 0, -100 }, { 0, -101 }, { 0, -102 }, { 0, -103 }, { 0, -104 }, { 0, -105 },
		{ 0, -106 }, { 0, -107 }, { 0, -108 }, { 0, -109 }, { 0, -110 }, { 0, -111 }, { 0, -112 }, { 0, -113 },
		{ 0, -114 }, { 0, -115 }, { 0, -116 }, { 0, -117 }, { 0, -118 }, { 0, -119 }, { 0, -120 }, { 0, -121 },
		{ 0, -122 }, { 0, -123 }, { 0, -124 }, { 0, -125 }, { 0, -126 }, { 0, -127 }, { 0, -128 }, { 0, -129 },
		{ 0, -130 }, { 0, -131 }, { 0, -132 }, { 0, -133 }, { 0, -134 }, { 0, -135 }, { 0, -136 }, { 0, -137 },
		{ 0, -138 }, { 0, -139 }, { 0, -140 }, { 0, -141 }, { 0, -142 }, { 0, -143 }, { 0, -144 }, { 0, -145 },
		{ 0, -146 }, { 0, -147 }, { 0, -148 }, { 0, -149 }, { 0, -150 }, { 0, -151 }, { 0, -152 }, { 0, -153 },
		{ 0, -154 }, { 0, -155 }, { 0, -156 }, { 0, -157 }, { 0, -158 }, { 0, -159 }, { 0, -160 }, { 0, -161 },
		{ 0, -162 }, { 0, -163 }, { 0, -164 }, { 0, -165 }, { 0, -166 }, { 0, -167 }, { 0, -168 }, { 0, -169 },
		{ 0, -170 }, { 0, -171 }, { 0, -172 }, { 0, -173 }, { 0, -174 }, { 0, -175 }, { 0, -176 }, { 0, -177 },
		{ 0, -178 }, { 0, -179 }, { 0, -180 }, { 0, -181 }, { 0, -182 }, { 0, -183 }, { 0, -184 }, { 0, -185 },
		{ 0, -186 }, { 0, -187 }, { 0, -188 }, { 0, -189 }, { 0, -190 }, { 0, -191 }, { 0, -192 }, { 0, -193 },
		{ 0, -194 }, { 0, -195 }, { 0, -196 }, { 0, -197 }, { 0, -198 }, { 0, -199 }, { 0, -200 }, { 0, -201 },
		{ 0, -202 }, { 0, -203 }, { 0, -204 }, { 0, -205 }, { 0, -206 }, { 0, -207 }, { 0, -208 }, { 0, -209 },
		{ 0, -210 }, { 0, -211 }, { 0, -212 }, { 0, -213 }, { 0, -214 }, { 0, -215 }, { 0, -216 }, { 0, -217 },
		{ 0, -218 }, { 0, -219 }, { 0, -220 }, { 0, -221 }, { 0, -222 }, { 0, -223 }, { 0, -224 }, { 0, -225 },
		{ 0, -226 }, { 0, -227 }, { 0, -228 }, { 0, -229 }, { 0, -230 }, { 0, -231 }, { 0, -232 }, { 0, -233 },
		{ 0, -234 }, { 0, -235 }, { 0, -236 }, { 0, -237 }, { 0, -238 }, { 0, -239 }, { 0, -240 }, { 0, -241 },
		{ 0, -242 }, { 0, -243 }, { 0, -244 }, { 0, -245 }, { 0, -246 }, { 0, -247 }, { 0, -248 }, { 0, -249 },
		{ 0, -250 }, { 0, -251 }, { 0, -252 }, { 0, -253 }, { 0, -254 }, { 0, -255 }, { 0, -256 }, { 0, 0 },
		{ -257, 71 }, { -258, 70 }, { -259, 69 }, { -257, 68 }, { -261, 73 }
	};

	BOOST_CHECK(as2.contains(std::u32string(U"あ")));
	BOOST_CHECK(as2.contains(std::u32string(U"あう")));
	BOOST_CHECK(as2.contains(std::u32string(U"い")));
	BOOST_CHECK(as2.contains(std::u32string(U"うあい")));
	BOOST_CHECK(as2.contains(std::u32string(U"うえ")));
}

/*
直列化データからの割り当て

void assign(InputIterator first, InputIterator last)
*/
BOOST_AUTO_TEST_CASE(basic_atom_set__assign__1)
{
	using namespace wordring;

	std::vector<std::u32string> v1{ U"あ", U"あう", U"い", U"うあい", U"うえ" };
	auto as1 = basic_atom_set<std::u32string>(v1.begin(), v1.end());
	auto v2 = std::vector<std::int32_t>(as1.ibegin(), as1.iend());

	auto as2 = basic_atom_set<std::u32string>(v2.begin(), v2.end());

	BOOST_CHECK(as2.contains(std::u32string(U"あ")));
	BOOST_CHECK(as2.contains(std::u32string(U"あう")));
	BOOST_CHECK(as2.contains(std::u32string(U"い")));
	BOOST_CHECK(as2.contains(std::u32string(U"うあい")));
	BOOST_CHECK(as2.contains(std::u32string(U"うえ")));

	BOOST_CHECK(as2.contains(std::u32string(U"え")) == false);
}

/*
文字列リストからの割り当て

void assign(InputIterator first, InputIterator last)
*/
BOOST_AUTO_TEST_CASE(basic_atom_set__assign__2)
{
	using namespace wordring;

	std::vector<std::u32string> v{ U"あ", U"あう", U"い", U"うあい", U"うえ" };
	basic_atom_set<std::u32string> as;

	as.assign(v.begin(), v.end());

	BOOST_CHECK(as.contains(std::u32string(U"あ")));
	BOOST_CHECK(as.contains(std::u32string(U"あう")));
	BOOST_CHECK(as.contains(std::u32string(U"い")));
	BOOST_CHECK(as.contains(std::u32string(U"うあい")));
	BOOST_CHECK(as.contains(std::u32string(U"うえ")));

	BOOST_CHECK(as.contains(std::u32string(U"え")) == false);
}

// 要素アクセス ----------------------------------------------------------------

/*
IDからアトムを返す

value_type at(std::uint32_t id) const
*/
BOOST_AUTO_TEST_CASE(basic_atom_set__at__1)
{
	using namespace wordring;

	std::vector<std::u32string> v1{ U"あ", U"あう", U"い", U"うあい", U"うえ" };
	auto as = basic_atom_set<std::u32string>(v1.begin(), v1.end());

	auto a = as.at(U"あう");
	std::uint32_t i = a;

	BOOST_CHECK(a);
	BOOST_CHECK(static_cast<std::u32string>(as.at(i)) == std::u32string(U"あう"));
}

BOOST_AUTO_TEST_CASE(basic_atom_set__at__2)
{
	using namespace wordring;

	std::vector<std::u32string> v1{ U"あ", U"あう", U"い", U"うあい", U"うえ" };
	auto as = basic_atom_set<std::u32string>(v1.begin(), v1.end());

	auto a = as.at(U"え");
	std::uint32_t i = a;

	BOOST_CHECK(!a);
	BOOST_CHECK(i == 0);
}

BOOST_AUTO_TEST_CASE(basic_atom_set__at__3)
{
	using namespace wordring;

	std::vector<std::u32string> v1{ U"あ", U"あう", U"い", U"うあい", U"うえ" };
	auto as = basic_atom_set<std::u32string>(v1.begin(), v1.end());

	auto a = as.at(U"");
	std::uint32_t i = a;

	BOOST_CHECK(!a);
	BOOST_CHECK(i == 0);
}

BOOST_AUTO_TEST_CASE(basic_atom_set__at__4)
{
	using namespace wordring;

	basic_atom_set<std::u32string> as;

	auto a = as.at(U"え");
	std::uint32_t i = a;

	BOOST_CHECK(!a);
	BOOST_CHECK(i == 0);
}

BOOST_AUTO_TEST_CASE(basic_atom_set__at__5)
{
	using namespace wordring;

	basic_atom_set<std::u32string> as;

	auto a = as.at(U"");
	std::uint32_t i = a;

	BOOST_CHECK(!a);
	BOOST_CHECK(i == 0);
}

/*
文字列からアトムを返す

value_type at(InputIterator first, InputIterator last) const
*/
BOOST_AUTO_TEST_CASE(basic_atom_set__at__6)
{
	using namespace wordring;

	std::vector<std::u32string> v1{ U"あ", U"あう", U"い", U"うあい", U"うえ" };
	auto as = basic_atom_set<std::u32string>(v1.begin(), v1.end());

	auto s = std::u32string(U"あう");
	auto a = as.at(s.begin(), s.end());

	BOOST_CHECK(a);
	BOOST_CHECK(static_cast<std::u32string>(s) == U"あう");
}

BOOST_AUTO_TEST_CASE(basic_atom_set__at__7)
{
	using namespace wordring;

	std::vector<std::u32string> v1{ U"あ", U"あう", U"い", U"うあい", U"うえ" };
	auto as = basic_atom_set<std::u32string>(v1.begin(), v1.end());

	auto s = std::u32string(U"え");
	auto a = as.at(s.begin(), s.end());

	BOOST_CHECK(!a);
}

BOOST_AUTO_TEST_CASE(basic_atom_set__at__8)
{
	using namespace wordring;

	std::vector<std::u32string> v1{ U"あ", U"あう", U"い", U"うあい", U"うえ" };
	auto as = basic_atom_set<std::u32string>(v1.begin(), v1.end());

	auto s = std::u32string(U"");
	auto a = as.at(s.begin(), s.end());

	BOOST_CHECK(!a);
}

BOOST_AUTO_TEST_CASE(basic_atom_set__at__9)
{
	using namespace wordring;

	basic_atom_set<std::u32string> as;

	auto s = std::u32string(U"え");
	auto a = as.at(s.begin(), s.end());

	BOOST_CHECK(!a);
}

BOOST_AUTO_TEST_CASE(basic_atom_set__at__10)
{
	using namespace wordring;

	basic_atom_set<std::u32string> as;

	auto s = std::u32string(U"");
	auto a = as.at(s.begin(), s.end());

	BOOST_CHECK(!a);
}

/*
文字列からアトムを返す

value_type at(std::basic_string_view<label_type> sv) const
*/
BOOST_AUTO_TEST_CASE(basic_atom_set__at__11)
{
	using namespace wordring;

	std::vector<std::u32string> v1{ U"あ", U"あう", U"い", U"うあい", U"うえ" };
	auto as = basic_atom_set<std::u32string>(v1.begin(), v1.end());

	auto a = as.at(U"あう");

	BOOST_CHECK(static_cast<std::u32string>(a) == U"あう");
}

BOOST_AUTO_TEST_CASE(basic_atom_set__at__12)
{
	using namespace wordring;

	std::vector<std::u32string> v1{ U"あ", U"あう", U"い", U"うあい", U"うえ" };
	auto as = basic_atom_set<std::u32string>(v1.begin(), v1.end());

	auto a = as.at(U"え");

	BOOST_CHECK(!a);
}

BOOST_AUTO_TEST_CASE(basic_atom_set__at__13)
{
	using namespace wordring;

	std::vector<std::u32string> v1{ U"あ", U"あう", U"い", U"うあい", U"うえ" };
	auto as = basic_atom_set<std::u32string>(v1.begin(), v1.end());

	auto a = as.at(U"");

	BOOST_CHECK(!a);
}

BOOST_AUTO_TEST_CASE(basic_atom_set__at__14)
{
	using namespace wordring;

	basic_atom_set<std::u32string> as;

	auto a = as.at(U"え");

	BOOST_CHECK(!a);
}

BOOST_AUTO_TEST_CASE(basic_atom_set__at__15)
{
	using namespace wordring;

	basic_atom_set<std::u32string> as;

	auto a = as.at(U"");

	BOOST_CHECK(!a);
}

/*
文字列からアトムを返す

value_type operator[](std::basic_string_view<label_type> sv)
*/
BOOST_AUTO_TEST_CASE(basic_atom_set__at__16)
{
	using namespace wordring;

	std::vector<std::u32string> v1{ U"あ", U"あう", U"い", U"うあい", U"うえ" };
	auto as = basic_atom_set<std::u32string>(v1.begin(), v1.end());

	std::u32string s{ U'え', U'\0', U'い' };
	BOOST_CHECK(s.size() == 3);
	auto a = as[s];

	BOOST_CHECK(a);
	BOOST_CHECK(static_cast<std::u32string>(a) == s);
}

BOOST_AUTO_TEST_CASE(basic_atom_set__at__17)
{
	using namespace wordring;

	std::vector<std::u32string> v1{ U"あ", U"あう", U"い", U"うあい", U"うえ" };
	auto as = basic_atom_set<std::u32string>(v1.begin(), v1.end());

	auto a = as[U""];

	BOOST_CHECK(!a);
}

BOOST_AUTO_TEST_CASE(basic_atom_set__at__18)
{
	using namespace wordring;

	basic_atom_set<std::u32string> as;

	auto a = as[U""];

	BOOST_CHECK(!a);
}

// 変更 -----------------------------------------------------------------------

/*
文字列を挿入する

value_type insert(InputIterator first, InputIterator last)
*/
BOOST_AUTO_TEST_CASE(basic_atom_set__insert__1)
{
	using namespace wordring;

	basic_atom_set<std::u32string> as;

	std::u32string s(U"あ");
	auto a = as.insert(s.begin(), s.end());

	BOOST_CHECK(static_cast<std::u32string>(a) == U"あ");
	BOOST_CHECK(as.size() == 1);
}

BOOST_AUTO_TEST_CASE(basic_atom_set__insert__2)
{
	using namespace wordring;

	basic_atom_set<std::u32string> as;

	std::u32string s(U"");
	auto a = as.insert(s.begin(), s.end());

	BOOST_CHECK(!a);
	BOOST_CHECK(as.empty());
}

/*
文字列を挿入する

value_type insert(std::basic_string_view<label_type> sv)
*/
BOOST_AUTO_TEST_CASE(basic_atom_set__insert__3)
{
	using namespace wordring;

	basic_atom_set<std::u32string> as;

	auto a = as.insert(U"あ");

	BOOST_CHECK(static_cast<std::u32string>(a) == U"あ");
	BOOST_CHECK(as.size() == 1);
}

BOOST_AUTO_TEST_CASE(basic_atom_set__insert__4)
{
	using namespace wordring;

	basic_atom_set<std::u32string> as;

	auto a = as.insert(U"");

	BOOST_CHECK(!a);
	BOOST_CHECK(as.empty());
}

/*
アトムを削除する

void erase(std::uint32_t id)
*/
BOOST_AUTO_TEST_CASE(basic_atom_set__erase__1)
{
	using namespace wordring;

	std::vector<std::u32string> v1{ U"あ", U"あう", U"い", U"うあい", U"うえ" };
	auto as = basic_atom_set<std::u32string>(v1.begin(), v1.end());
	auto a = as.insert(U"え");

	as.erase(static_cast<std::uint32_t>(a));

	BOOST_CHECK(as.contains(U"え") == false);
	BOOST_CHECK(as.size() == 5);
}

BOOST_AUTO_TEST_CASE(basic_atom_set__erase__2)
{
	using namespace wordring;

	basic_atom_set<std::u32string> as;
	auto a = as.insert(U"");

	as.erase(static_cast<std::uint32_t>(a));

	BOOST_CHECK(as.contains(U"") == false);
	BOOST_CHECK(as.size() == 0);
}

/*
アトムを削除する

void erase(InputIterator first, InputIterator last)
*/
BOOST_AUTO_TEST_CASE(basic_atom_set__erase__3)
{
	using namespace wordring;

	std::vector<std::u32string> v1{ U"あ", U"あう", U"い", U"うあい", U"うえ" };
	auto as = basic_atom_set<std::u32string>(v1.begin(), v1.end());

	auto s = std::u32string(U"うあい");
	as.erase(s.begin(), s.end());

	BOOST_CHECK(as.contains(U"うあい") == false);
	BOOST_CHECK(as.size() == 4);
}

BOOST_AUTO_TEST_CASE(basic_atom_set__erase__4)
{
	using namespace wordring;

	basic_atom_set<std::u32string> as;

	auto s = std::u32string(U"");
	as.erase(s.begin(), s.end());

	BOOST_CHECK(as.empty());
}

/*
アトムを削除する

void erase(std::basic_string_view<label_type> sv)
*/
BOOST_AUTO_TEST_CASE(basic_atom_set__erase__5)
{
	using namespace wordring;

	std::vector<std::u32string> v1{ U"あ", U"あう", U"い", U"うあい", U"うえ" };
	auto as = basic_atom_set<std::u32string>(v1.begin(), v1.end());

	as.erase(U"うあい");

	BOOST_CHECK(as.contains(U"うあい") == false);
	BOOST_CHECK(as.size() == 4);
}

BOOST_AUTO_TEST_CASE(basic_atom_set__erase__6)
{
	using namespace wordring;

	basic_atom_set<std::u32string> as;

	as.erase(U"");

	BOOST_CHECK(as.empty());
}

BOOST_AUTO_TEST_CASE(basic_atom_set__erase__7)
{
	using namespace wordring;

	std::vector<std::u32string> v1{ U"あ", U"あう", U"い", U"うあい", U"うえ" };
	auto as = basic_atom_set<std::u32string>(v1.begin(), v1.end());

	as.erase(U"え");

	BOOST_CHECK(as.size() == 5);
}

// 検索 -----------------------------------------------------------------------

/*
文字列が格納されているか調べる

bool contains(InputIterator first, InputIterator last) const
bool contains(std::basic_string_view<label_type> sv) const
*/
BOOST_AUTO_TEST_CASE(basic_atom_set__contains__1)
{
	using namespace wordring;

	std::vector<std::u32string> v1{ U"あ", U"あう", U"い", U"うあい", U"うえ" };
	auto as = basic_atom_set<std::u32string>(v1.begin(), v1.end());

	BOOST_CHECK(as.contains(U"あ"));
	BOOST_CHECK(as.contains(U"あう"));
	BOOST_CHECK(as.contains(U"い"));
	BOOST_CHECK(as.contains(U"うあい"));
	BOOST_CHECK(as.contains(U"うえ"));

	BOOST_CHECK(as.contains(U"え") == false);
}

BOOST_AUTO_TEST_CASE(basic_atom_set__contains__2)
{
	using namespace wordring;

	std::vector<std::u32string> v1{ U"あ", U"あう", U"い", U"うあい", U"うえ" };
	auto as = basic_atom_set<std::u32string>(v1.begin(), v1.end());

	BOOST_CHECK(as.contains(U"") == false);
}

BOOST_AUTO_TEST_CASE(basic_atom_set__contains__3)
{
	using namespace wordring;

	basic_atom_set<std::u32string> as;

	BOOST_CHECK(as.contains(U"") == false);
}

// 直列化 ---------------------------------------------------------------------

BOOST_AUTO_TEST_CASE(basic_atom_set__serialize__1)
{
	using namespace wordring;

	std::vector<std::u32string> v1{ U"あ", U"あう", U"い", U"うあい", U"うえ" };
	auto as1 = basic_atom_set<std::u32string>(v1.begin(), v1.end());

	auto v2 = std::vector<std::uint32_t>(as1.ibegin(), as1.iend());

	auto as2 = basic_atom_set<std::u32string>(v2.begin(), v2.end());

	BOOST_CHECK(as2.size() == 5);
}

BOOST_AUTO_TEST_SUITE_END()

max_stars_repo_name: wordring/wordring

max_issues_repo_name: wordring/libwordring

max_forks_repo_name: wordring/libwordring


text:
#include <chrono>
#include <fstream>
#include <iostream>
#include <random>
#include <utility>
#include <vector>

#include <Eigen/Geometry>
#include <common_robotics_utilities/math.hpp>
#include <common_robotics_utilities/simple_hierarchical_clustering.hpp>
#include <common_robotics_utilities/simple_kmeans_clustering.hpp>

using PointVector = common_robotics_utilities::math::VectorVector4d;
using IndexClusteringResult
    = common_robotics_utilities::simple_hierarchical_clustering
        ::IndexClusteringResult;
using PointClusteringResult
    = common_robotics_utilities::simple_hierarchical_clustering
        ::ClusteringResult<Eigen::Vector4d, PointVector>;

void SaveClustering(
    const PointClusteringResult& clusters,
    const std::string& filename)
{
  // Use the cluster index to set z-coordinates for easy visualization
  std::ofstream clustering_output_file(filename, std::ios_base::out);
  if (!clustering_output_file.is_open())
  {
    throw std::invalid_argument(
        "Log file " + filename + " must be write-openable");
  }
  std::cout << "Saving clustering to " << filename << std::endl;
  for (size_t idx = 0; idx < clusters.Clusters().size(); idx++)
  {
    const PointVector& cluster = clusters.Clusters().at(idx);
    const double cluster_num = 1.0 + static_cast<double>(idx);
    for (const Eigen::Vector4d& point : cluster)
    {
      clustering_output_file << point(0) << "," << point(1) << ","
                             << cluster_num << std::endl;
    }
  }
  clustering_output_file.close();
}

void SaveIndexClustering(
    const PointVector& raw_points,
    const IndexClusteringResult& index_clusters,
    const std::string& filename)
{
  SaveClustering(
      common_robotics_utilities::simple_hierarchical_clustering
          ::MakeElementClusteringFromIndexClustering<
              Eigen::Vector4d, PointVector>(raw_points, index_clusters),
      filename);
}

int main(int argc, char** argv)
{
  const size_t num_points
      = (argc >= 2) ? static_cast<size_t>(atoi(argv[1])) : 1000;
  const double cluster_threshold
      = (argc >= 3) ? atof(argv[2]) : 0.1;
  if (cluster_threshold < 0.0)
  {
    throw std::invalid_argument("cluster_threshold < 0.0");
  }
  std::cout << "Generating " << num_points << " points..." << std::endl;
  const int64_t seed = 42;
  std::mt19937_64 prng(seed);
  std::uniform_real_distribution<double> dist(0.0, 10.0);
  PointVector random_points(num_points);
  for (size_t idx = 0; idx < num_points; idx++)
  {
    const double x = dist(prng);
    const double y = dist(prng);
    random_points.at(idx) = Eigen::Vector4d(x, y, 0.0, 0.0);
  }
  std::function<double(const Eigen::Vector4d&, const Eigen::Vector4d&)>
      distance_fn = [] (const Eigen::Vector4d& v1, const Eigen::Vector4d& v2)
  {
    return (v1 - v2).norm();
  };
  const std::vector<bool> use_parallel_options = {false, true};
  for (const bool use_parallel : use_parallel_options)
  {
    // Cluster using index-cluster methods
    // Single-link clustering
    std::cout << "Single-link hierarchical index clustering " << num_points
              << " points..." << std::endl;
    const auto slhic_start = std::chrono::steady_clock::now();
    const auto single_link_index_clusters
        = common_robotics_utilities::simple_hierarchical_clustering
            ::IndexCluster(
                random_points, distance_fn, 1.0,
                common_robotics_utilities::simple_hierarchical_clustering
                    ::ClusterStrategy::SINGLE_LINK, use_parallel);
    const auto slhic_end = std::chrono::steady_clock::now();
    const double slhic_elapsed =
        std::chrono::duration<double>(slhic_end - slhic_start).count();
    std::cout << "...took " << slhic_elapsed << " seconds" << std::endl;
    // Save
    SaveIndexClustering(
        random_points, single_link_index_clusters, (use_parallel)
            ? "/tmp/test_parallel_single_link_index_clustering.csv"
            : "/tmp/test_serial_single_link_index_clustering.csv");
    // Complete-link clustering
    std::cout << "Complete-link hierarchical index clustering " << num_points
              << " points..." << std::endl;
    const auto clhic_start = std::chrono::steady_clock::now();
    const auto complete_link_index_clusters
        = common_robotics_utilities::simple_hierarchical_clustering
            ::IndexCluster(
                random_points, distance_fn, 1.0,
                common_robotics_utilities::simple_hierarchical_clustering
                    ::ClusterStrategy::COMPLETE_LINK, use_parallel);
    const auto clhic_end = std::chrono::steady_clock::now();
    const double clhic_elapsed =
        std::chrono::duration<double>(clhic_end - clhic_start).count();
    std::cout << "...took " << clhic_elapsed << " seconds" << std::endl;
    // Save
    SaveIndexClustering(
        random_points, complete_link_index_clusters, (use_parallel)
            ? "/tmp/test_parallel_complete_link_index_clustering.csv"
            : "/tmp/test_serial_complete_link_index_clustering.csv");
    // Cluster using value-cluster methods
    // Single-link clustering
    std::cout << "Single-link hierarchical clustering " << num_points
              << " points..." << std::endl;
    const auto slhc_start = std::chrono::steady_clock::now();
    const auto single_link_clusters
        = common_robotics_utilities::simple_hierarchical_clustering::Cluster(
            random_points, distance_fn, 1.0,
            common_robotics_utilities::simple_hierarchical_clustering
                ::ClusterStrategy::SINGLE_LINK, use_parallel);
    const auto slhc_end = std::chrono::steady_clock::now();
    const double slhc_elapsed =
        std::chrono::duration<double>(slhc_end - slhc_start).count();
    std::cout << "...took " << slhc_elapsed << " seconds" << std::endl;
    // Save
    SaveClustering(single_link_clusters, (use_parallel)
        ? "/tmp/test_parallel_single_link_clustering.csv"
        : "/tmp/test_serial_single_link_clustering.csv");
    // Complete-link clustering
    std::cout << "Complete-link hierarchical clustering " << num_points
              << " points..." << std::endl;
    const auto clhc_start = std::chrono::steady_clock::now();
    const auto complete_link_clusters
        = common_robotics_utilities::simple_hierarchical_clustering::Cluster(
            random_points, distance_fn, 1.0,
            common_robotics_utilities::simple_hierarchical_clustering
                ::ClusterStrategy::COMPLETE_LINK, use_parallel);
    const auto clhc_end = std::chrono::steady_clock::now();
    const double clhc_elapsed =
        std::chrono::duration<double>(clhc_end - clhc_start).count();
    std::cout << "...took " << clhc_elapsed << " seconds" << std::endl;
    // Save
    SaveClustering(complete_link_clusters, (use_parallel)
        ? "/tmp/test_parallel_complete_link_clustering.csv"
        : "/tmp/test_serial_complete_link_clustering.csv");
    // Cluster using K-means
    const int32_t num_clusters = 50;
    std::cout << "K-means clustering " << num_points << " points into "
              << num_clusters << " clusters..." << std::endl;
    std::function<Eigen::Vector4d(const PointVector&)>
        average_fn = [] (const PointVector& cluster)
    {
      return common_robotics_utilities::math::AverageEigenVector4d(cluster);
    };
    const auto kmeans_start = std::chrono::steady_clock::now();
    const std::vector<int32_t> kmeans_labels
        = common_robotics_utilities::simple_kmeans_clustering::Cluster(
            random_points, distance_fn, average_fn, num_clusters, 42, true,
            use_parallel);
    const auto kmeans_end = std::chrono::steady_clock::now();
    const double kmeans_elapsed =
        std::chrono::duration<double>(kmeans_end - kmeans_start).count();
    std::cout << "...took " << kmeans_elapsed << " seconds" << std::endl;
    // Get value clusters from the K-means labels
    std::vector<PointVector> kmeans_clusters(num_clusters);
    for (size_t idx = 0; idx < kmeans_labels.size(); idx++)
    {
      const size_t cluster_num = static_cast<size_t>(kmeans_labels.at(idx));
      kmeans_clusters.at(cluster_num).push_back(random_points.at(idx));
    }
    // Save
    SaveClustering(complete_link_clusters, (use_parallel)
        ? "/tmp/test_parallel_kmeans_clustering.csv"
        : "/tmp/test_serial_kmeans_clustering.csv");
  }
  std::cout << "Done saving, you can plot as a 3d scatterplot to see clustering"
            << std::endl;
  return 0;
}


text:
#include <vsim/env/camera.hpp>

#include <iostream>
#include <fstream>

#include <Eigen/Geometry>

using namespace std ;
using namespace Eigen ;

namespace vsim {

Eigen::Matrix4f PerspectiveCamera::projectionMatrix() const {
    assert(abs(aspect_ - std::numeric_limits<float>::epsilon()) > static_cast<float>(0));

    float xfov = aspect_ * yfov_ ;
    float const d = 1/tan(xfov / static_cast<float>(2));

    Matrix4f result ;
    result.setZero() ;

    result(0, 0) = d / aspect_ ;
    result(1, 1) = d ;
    result(2, 2) =  (zfar_ + znear_) / (znear_ - zfar_);
    result(2, 3) =  2 * zfar_ * znear_ /(znear_ - zfar_) ;
    result(3, 2) = -1 ;

    return result;
}

void Camera::lookAt(const Vector3f &eye, const Vector3f &center, const Vector3f &up) {
    Vector3f f = (center - eye).normalized();
    Vector3f s = f.cross(up).normalized();
    Vector3f u = s.cross(f) ;

    mat_ << s.x(), s.y(), s.z(), -s.dot(eye),
            u.x(), u.y(), u.z(), -u.dot(eye),
            -f.x(), -f.y(), -f.z(), f.dot(eye),
            0, 0, 0, 1 ;
}

void Camera::lookAt(const Vector3f &eye, const Vector3f &center, float roll) {
    lookAt(eye, center, Vector3f(0, 1, 0)) ;

    Affine3f rot ;
    rot.setIdentity();
    rot.rotate(AngleAxisf(roll, Eigen::Vector3f::UnitZ())) ;
    mat_ = mat_ * rot.matrix() ;
}

}

max_stars_repo_name: malasiot/vsim

max_issues_repo_name: malasiot/vsim

max_forks_repo_name: malasiot/vsim


text:
/*
  [auto_generated]
  boost/numeric/odeint/iterator/detail/const_step_iterator_impl.hpp

  [begin_description]
  tba.
  [end_description]

  Copyright 2013 Karsten Ahnert
  Copyright 2013 Mario Mulansky

  Distributed under the Boost Software License, Version 1.0.
  (See accompanying file LICENSE_1_0.txt or
  copy at http://www.boost.org/LICENSE_1_0.txt)
*/

#ifndef BOOST_NUMERIC_ODEINT_ITERATOR_DETAIL_CONST_STEP_ITERATOR_IMPL_HPP_DEFINED
#define BOOST_NUMERIC_ODEINT_ITERATOR_DETAIL_CONST_STEP_ITERATOR_IMPL_HPP_DEFINED

#include <boost/numeric/odeint/iterator/detail/ode_iterator_base.hpp>
#include <boost/numeric/odeint/util/unit_helper.hpp>

namespace boost {
namespace numeric {
namespace odeint {

    template< class Iterator , class Stepper , class System , class State , typename Tag , class StepperTag >
    class const_step_iterator_impl;

    /*
     * Specilization for steppers and error steppers
     */
    template< class Iterator , class Stepper , class System , class State , typename Tag >
    class const_step_iterator_impl< Iterator , Stepper , System , State , Tag , stepper_tag >
        : public detail::ode_iterator_base< Iterator , Stepper , System , State , Tag >
    {
    private:

        typedef Stepper stepper_type;
        typedef System system_type;
        typedef typename boost::numeric::odeint::unwrap_reference< stepper_type >::type unwrapped_stepper_type;
        typedef State state_type;
        typedef typename traits::time_type< stepper_type >::type time_type;
        typedef typename traits::value_type< stepper_type >::type ode_value_type;
        #ifndef DOXYGEN_SKIP
        typedef detail::ode_iterator_base< Iterator , Stepper , System , State , Tag > base_type;
        #endif

    public:

        /**
         * \brief Constructs a const_step_iterator. This constructor should be used to construct the begin iterator.
         *
         * \param stepper The stepper to use during the iteration.
         * \param sys The system function (ODE) to solve.
         * \param s The initial state. const_step_iterator stores a reference of s and changes its value during the iteration.
         * \param t The initial time.
         * \param t_end The end time, at which the iteration should stop.
         * \param dt The initial time step.
         */
        const_step_iterator_impl( stepper_type stepper , system_type sys , state_type &s , time_type t , time_type t_end , time_type dt )
            : base_type( stepper , sys , t , dt ) , m_t_start( t ) , m_t_end( t_end ) , m_state( &s ) , m_step( 0 )
        {
            if( detail::less_with_sign( this->m_t_end , this->m_t , this->m_dt ) )
                this->m_at_end = true;
        }

        /**
         * \brief Constructs a const_step_iterator. This constructor should be used to construct the end iterator.
         *
         * \param stepper The stepper to use during the iteration.
         * \param sys The system function (ODE) to solve.
         * \param s The initial state. const_step_iterator stores a reference of s and changes its value during the iteration.
         */
        const_step_iterator_impl( stepper_type stepper , system_type sys , state_type &s )
            : base_type( stepper , sys ) { }

    protected:

        friend class boost::iterator_core_access;

        void increment()
        {
            if( detail::less_eq_with_sign( static_cast<time_type>(this->m_t+this->m_dt) ,
                                           this->m_t_end , this->m_dt ) )
            {
                unwrapped_stepper_type &stepper = this->m_stepper;
                stepper.do_step( this->m_system , *this->m_state , this->m_t , this->m_dt );
                // use integer to compute current time to reduce roundoff errors
                this->m_step++;
                this->m_t = this->m_t_start + static_cast< typename unit_value_type<time_type>::type >(this->m_step)*this->m_dt;
            } else {
                this->m_at_end = true;
            }
        }

    public:
        const state_type& get_state() const
        {
            return *m_state;
        }

    private:
        time_type m_t_start;
        time_type m_t_end;
        state_type* m_state;
        size_t m_step;

    };

    /*
     * Specilization for dense output stepper
     */
    /**
     * \brief ODE Iterator with constant step size. The value type of this iterator is the state type of the stepper.
     *
     * Implements an ODE iterator solving the ODE with constant steps. Uses dense-output steppers.
     * const_step_iterator is a model of single-pass iterator.
     *
     * The value type of this iterator is the state type of the stepper. Hence one can only access the state and not the current time.
     *
     * \tparam Stepper The stepper type which should be used during the iteration.
     * \tparam System The type of the system function (ODE) which should be solved.
     */
    template< class Iterator , class Stepper , class System , class State , typename Tag >
    class const_step_iterator_impl< Iterator , Stepper , System , State , Tag , dense_output_stepper_tag >
        : public detail::ode_iterator_base< Iterator , Stepper , System , State , Tag >
    {
    private:

        typedef Stepper stepper_type;
        typedef System system_type;
        typedef typename boost::numeric::odeint::unwrap_reference< stepper_type >::type unwrapped_stepper_type;
        typedef State state_type;
        typedef typename traits::time_type< stepper_type >::type time_type;
        typedef typename traits::value_type< stepper_type >::type ode_value_type;
        #ifndef DOXYGEN_SKIP
        typedef detail::ode_iterator_base< Iterator , Stepper , System , State , Tag > base_type;
        #endif

    public:

        /**
         * \brief Constructs a const_step_iterator. This constructor should be used to construct the begin iterator.
         *
         * \param stepper The stepper to use during the iteration.
         * \param sys The system function (ODE) to solve.
         * \param s The initial state. const_step_iterator stores a reference of s and changes its value during the iteration.
         * \param t The initial time.
         * \param t_end The end time, at which the iteration should stop.
         * \param dt The initial time step.
         */
        const_step_iterator_impl( stepper_type stepper , system_type sys , state_type &s , time_type t , time_type t_end , time_type dt )
            : base_type( stepper , sys , t , dt ) , m_t_start( t ) , m_t_end( t_end ) , m_state( &s ) , m_step( 0 )
        {
            if( detail::less_eq_with_sign( this->m_t , this->m_t_end , this->m_dt ) )
            {
                unwrapped_stepper_type &st = this->m_stepper;
                st.initialize( * ( this->m_state ) , this->m_t , this->m_dt );
            } else {
                this->m_at_end = true;
            }
        }

        /**
         * \brief Constructs a const_step_iterator. This constructor should be used to construct the end iterator.
         *
         * \param stepper The stepper to use during the iteration.
         * \param sys The system function (ODE) to solve.
         * \param s The initial state. const_step_iterator stores a reference of s and changes its value during the iteration.
         */
        const_step_iterator_impl( stepper_type stepper , system_type sys , state_type &s )
            : base_type( stepper , sys ) , m_state( &s )
        {
        }

    protected:

        friend class boost::iterator_core_access;

        void increment( void )
        {
            if( detail::less_eq_with_sign( static_cast<time_type>(this->m_t+this->m_dt) ,
                                           this->m_t_end , this->m_dt ) )
            {
                unwrapped_stepper_type &stepper = this->m_stepper;
                // use integer to compute current time to reduce roundoff errors
                this->m_step++;
                this->m_t = this->m_t_start + static_cast< typename unit_value_type<time_type>::type >(this->m_step)*this->m_dt;
                while( detail::less_with_sign( stepper.current_time() , this->m_t ,
                       stepper.current_time_step() ) )
                {
                    stepper.do_step( this->m_system );
                }
                stepper.calc_state( this->m_t , *( this->m_state ) );
            } else {
                this->m_at_end = true;
            }
        }

    public:
        const state_type& get_state() const
        {
            return *m_state;
        }

    private:
        time_type m_t_start;
        time_type m_t_end;
        state_type* m_state;
        size_t m_step;
    };

} // namespace odeint
} // namespace numeric
} // namespace boost

#endif // BOOST_NUMERIC_ODEINT_ITERATOR_DETAIL_CONST_STEP_ITERATOR_IMPL_HPP_DEFINED


text:
//=======================================================================
// Copyright 1997, 1998, 1999, 2000 University of Notre Dame.
// Authors: Andrew Lumsdaine, Lie-Quan Lee, Jeremy G. Siek
//
// 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/config.hpp>
#include <iostream>
#include <boost/graph/adjacency_list.hpp>
#include <boost/graph/graph_utility.hpp>

/*
  Sample output:

  original graph:
  0 --> 3 2 3
  1 --> 3
  2 --> 0
  3 --> 2

  removing edges (0,3)
  0 --> 2
  1 --> 3
  2 --> 0
  3 --> 2
  removing edge (0,2) and (3, 2)
  0 -->
  1 --> 3
  2 --> 0
  3 -->

 */

using namespace boost;

typedef adjacency_list< vecS, vecS, directedS > Graph;

int main()
{
    typedef std::pair< std::size_t, std::size_t > Edge;
    Edge edges[6] = { Edge(0, 3), Edge(0, 2), Edge(0, 3), Edge(1, 3),
        Edge(2, 0), Edge(3, 2) };

#if defined(BOOST_MSVC) && BOOST_MSVC <= 1300
    // VC++ can't handle iterator constructor
    Graph g(4);
    for (std::size_t j = 0; j < 6; ++j)
        add_edge(edges[j].first, edges[j].second, g);
#else
    Graph g(edges, edges + 6, 4);
#endif

    std::cout << "original graph:" << std::endl;
    print_graph(g, get(vertex_index, g));
    std::cout << std::endl;

    std::cout << "removing edges (0,3)" << std::endl;
    remove_out_edge_if(vertex(0, g), incident_to(vertex(3, g), g), g);
    print_graph(g, get(vertex_index, g));

    std::cout << "removing edge (0,2) and (3, 2)" << std::endl;
    remove_edge_if(incident_to(vertex(2, g), g), g);
    print_graph(g, get(vertex_index, g));

    return 0;
}

max_issues_repo_name: qingkouwei/mediaones

max_forks_repo_name: qingkouwei/mediaones


text: #include <boost/xpressive/regex_constants.hpp>

max_stars_repo_name: miathedev/BoostForArduino

max_issues_repo_name: miathedev/BoostForArduino

max_forks_repo_name: miathedev/BoostForArduino


text:
#ifndef PYTHONIC_INCLUDE_NUMPY_EXP_HPP
#define PYTHONIC_INCLUDE_NUMPY_EXP_HPP

#include "pythonic/include/utils/functor.hpp"
#include "pythonic/include/types/ndarray.hpp"
#include "pythonic/include/utils/numpy_traits.hpp"
#include <boost/simd/function/exp.hpp>

namespace pythonic
{

  namespace numpy
  {
#define NUMPY_NARY_FUNC_NAME exp
#define NUMPY_NARY_FUNC_SYM boost::simd::exp
#include "pythonic/include/types/numpy_nary_expr.hpp"
  }
}

#endif

max_stars_repo_name: xmar/pythran

max_issues_repo_name: xmar/pythran

max_forks_repo_name: xmar/pythran


text:
#include "do_port_finder.h"

#include <chrono>
#include <ctime>
#include <string>
#include <thread>

#include <boost/filesystem.hpp>

#include "do_exceptions_internal.h"
#include "do_exceptions.h"
#include "do_persistence.h"

using namespace std::chrono_literals; // NOLINT(build/namespaces)

const int32_t g_maxNumPortFileReadAttempts = 3;

namespace microsoft::deliveryoptimization::details
{
static std::string g_DiscoverDOPort()
{
    const std::string runtimeDirectory = GetRuntimeDirectory();
    if (!boost::filesystem::exists(runtimeDirectory))
    {
        return std::string();
    }

    boost::filesystem::path mostRecentFile("");
    std::time_t mostRecentTime = 0;
    for (boost::filesystem::directory_iterator itr(runtimeDirectory); itr != boost::filesystem::directory_iterator(); ++itr)
    {
        const boost::filesystem::path& dirEntry = itr->path();
        if (dirEntry.filename().string().find("restport") != std::string::npos)
        {
            std::time_t currTime = boost::filesystem::last_write_time(dirEntry);
            if (currTime > mostRecentTime)
            {
                mostRecentTime = currTime;
                mostRecentFile = dirEntry;
            }
        }
    }
    std::ifstream file(mostRecentFile.string());
    std::string port;
    std::getline(file, port);

    return port;
}

std::string CPortFinder::GetDOPort(bool launchClientFirst)
{
    std::string port;

    for (int numAttempts = 1; (numAttempts <= g_maxNumPortFileReadAttempts) && port.empty(); numAttempts++)
    {
        // If built as service, then we expect client to already be running.
        // We still wait+discover loop below in case client started just now.
        // TODO(jimson) Do attempt to start the service if launchClientFirst==true

        // Wait up to 1s for client to write the restport file
        for (int i = 1; (i <= 4) && port.empty(); ++i)
        {
            std::this_thread::sleep_for(250ms);
            port = g_DiscoverDOPort();
        }
        launchClientFirst = port.empty(); // force launch on further attempts
    }
    if (port.empty())
    {
        ThrowException(errc::no_service);
    }
    return port;
}

} // namespace microsoft::deliveryoptimization::details

max_stars_repo_name: QPC-database/do-client

max_issues_repo_name: QPC-database/do-client

max_forks_repo_name: QPC-database/do-client


text:
#include "program_options.hpp"

#include <boost/program_options.hpp>

#include <sstream>
#include <iostream>

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

namespace program_options = boost::program_options;

bool process_command_line(int argc, char** argv,
                          std::string& prefix,
                          beltpp::ip_address& connect_to_address,
                          beltpp::ip_address& listen_on_address)
{
    string str_connect_to_address;
    string str_listen_on_address;

    program_options::options_description options_description;
    try
    {
        auto desc_init = options_description.add_options()
            ("help,h", "Print this help message and exit.")
            ("connect_to_address,c", program_options::value<string>(&str_connect_to_address)->required(),
                            "the blockchain daemon rpc address")
            ("listen_on_address,l", program_options::value<string>(&str_listen_on_address)->required(),
                            "commander rpc address")
            ("prefix,p", program_options::value<string>(&prefix)->required(),
                            "blockchain prefix");
        (void)(desc_init);

        program_options::variables_map options;

        program_options::store(
                    program_options::parse_command_line(argc, argv, options_description),
                    options);

        program_options::notify(options);

        if (options.count("help"))
        {
            throw std::runtime_error("");
        }

        connect_to_address.from_string(str_connect_to_address);
        listen_on_address.from_string(str_listen_on_address);

        if (false == connect_to_address.remote.empty())
        {
            connect_to_address.local = connect_to_address.remote;
            connect_to_address.remote = beltpp::ip_destination();
        }
        if (listen_on_address.local.empty())
        {
            listen_on_address.local = listen_on_address.remote;
            listen_on_address.remote = beltpp::ip_destination();
        }
    }
    catch (std::exception const& ex)
    {
        std::stringstream ss;
        ss << options_description;

        string ex_message = ex.what();
        if (false == ex_message.empty())
            cout << ex.what() << endl << endl;
        cout << ss.str();
        return false;
    }
    catch (...)
    {
        cout << "always throw std::exceptions" << endl;
        return false;
    }

    return true;
}


text:
/*
    AtomBall.hpp
    ============
        Class AtomBall implementation.
*/

#ifndef __YSASA_ATOM_BALL_HPP
#define __YSASA_ATOM_BALL_HPP

#include <vector>
#include <Eigen/Dense>
#include <PDBToolsCpp/PDBTools>
#include "AtomBall.h"
#include "Constants.hpp"
#include "MathUtil.hpp"

namespace YSASA
{

////////////////////////////////////////////////////////////////////////////////
// Using
////////////////////////////////////////////////////////////////////////////////

using std::vector;
using Eigen::RowVector3d;
using PDBTools::Atom;

////////////////////////////////////////////////////////////////////////////////
// Constructor
////////////////////////////////////////////////////////////////////////////////

AtomBall::AtomBall(const Atom *atomObj, const vector<RowVector3d> &unitBallCoord,
    double probeR):
    __atomObj(atomObj), __VDWR(VDW_RADII_HASH.at(atomObj->name)), __probeR(probeR),
    __realR(__VDWR + __probeR), __fullS(CalcBallS(__realR)),
    __dS(__fullS / unitBallCoord.size()), __ballCoord(unitBallCoord)
{
    for (auto &dotCoord: __ballCoord)
    {
        dotCoord = dotCoord * __realR + __atomObj->coord;
    }
}

////////////////////////////////////////////////////////////////////////////////
// Calc loss S with another ball
////////////////////////////////////////////////////////////////////////////////

double AtomBall::CalcLossS(AtomBall &rhs)
{
    double lossS = 0.;

    for (auto dotCoordIter = __ballCoord.begin(); dotCoordIter != __ballCoord.end();
        dotCoordIter++)
    {
        if ((*dotCoordIter - (rhs.__atomObj)->coord).norm() < rhs.__realR)
        {
            lossS += __dS;
            __ballCoord.erase(dotCoordIter--);
        }
    }

    for (auto dotCoordIter = rhs.__ballCoord.begin(); dotCoordIter != rhs.__ballCoord.end();
        dotCoordIter++)
    {
        if ((*dotCoordIter - __atomObj->coord).norm() < __realR)
        {
            lossS += rhs.__dS;
            rhs.__ballCoord.erase(dotCoordIter--);
        }
    }

    return lossS;
}

}  // End namespace YSASA

#endif  // __YSASA_ATOM_BALL_HPP

max_stars_repo_name: yingyulou/YSASA

max_issues_repo_name: yingyulou/YSASA

max_forks_repo_name: yingyulou/YSASA


text: #include <boost/mpl/aux_/preprocessed/gcc/quote.hpp>