text:
/* ---------------------------------------------------------------------------
 *
 * Autonomous Navigation and Perception Lab (ANPL),
 * Technion, Israel Institute of Technology,
 * Faculty of Aerospace Engineering,
 * Haifa, Israel, 32000
 * All Rights Reserved
 *
 * See LICENSE for the license information
 *
 * -------------------------------------------------------------------------- */

/**
 * @file: robot_map_octomap_laser.cpp
 * @brief:
 * @author: Asaf Feniger
 */

#include "mapper/robot_map_octomap_laser.h"

#include <mrbsp_utils/conversion.h>
#include <mrbsp_utils/mrbsp_utils.h>

#include <octomap_ros/conversions.h>
#include <laser_geometry/laser_geometry.h>
#include <octomap_msgs/Octomap.h>
#include <octomap_msgs/conversions.h>
#include <rosbag/bag.h>
#include <nav_msgs/OccupancyGrid.h>

#include <gtsam/inference/Symbol.h>

#include "gtsam/base/serialization.h"
#include <boost/archive/archive_exception.hpp>

#define MAP_RESOLUTION 0.1
#define MAP_FILENAME "octomap.ot"

using namespace MRBSP;

RobotMapOctomapLaser::RobotMapOctomapLaser():
        m_resolution(MAP_RESOLUTION),
        m_p_octree_map(new octomap::OcTree(m_resolution)),
        m_map_file_name(MAP_FILENAME),
        m_save_incremental_map(false)
{

}

RobotMapOctomapLaser::RobotMapOctomapLaser(const ros::NodeHandle& nh, const ros::NodeHandle& nh_private):
        // read from param server...
        m_resolution(MAP_RESOLUTION),
        m_map_node(nh),
        m_p_octree_map(new octomap::OcTree(m_resolution)),
        m_save_incremental_map(false)
{
    if(!m_map_node.hasParam("/logger/loggerPath")) {
        ROS_WARN("Unable to find log folder...");
        ros::Duration(1.0).sleep();
        if(m_map_node.hasParam("/logger/loggerPath")) {
            nh_private.getParam("/logger/loggerPath", m_path_to_log_folder);
        }
        else {
            m_path_to_log_folder = "~/.ros";
            MRBSP::Utils::createFolder(m_path_to_log_folder);
        }
    }
    else {
        nh_private.getParam("/logger/loggerPath", m_path_to_log_folder);
    }

    MRBSP::Utils::initLogger(nh_private);
    //std::string sensor_type;
    //nh_private.param("/config_setup/is_3D_vis", m_is_3D_vis, false);
    //if(m_is_3D_vis) {
        // set keyframe type (with pointclouds)
        m_map_data_3D_sub = m_map_node.subscribe("/DA/map_data/3D", 100, &RobotMapOctomapLaser::mapData3DCallback, this);
    //    sensor_type = "pointcloud";
    //    ROS_INFO("Map: publish 3D map");
    //}
    //else {
        m_map_data_2D_sub = m_map_node.subscribe("/DA/map_data/2D", 100, &RobotMapOctomapLaser::mapDataCallback, this);
    //    sensor_type = "laser";
    //    ROS_INFO("Map: publish 2D map");
    //}

    nh_private.param("map_resolution", m_resolution, double(0.1));
    std::string filename;
    nh_private.param("save_incremental_map", m_save_incremental_map, false);
    nh_private.param("map_filename", filename, std::string("octomap.ot"));

    if(m_map_node.hasParam("/logger/loggerPath")) {
        std::string path_to_log_folder;
        nh_private.getParam("/logger/loggerPath", path_to_log_folder);
        m_map_file_name = std::string(path_to_log_folder + "/" + filename);
    }
    else {
        ROS_WARN("Cant find path to log folder...");
        std::string scenario_folder;
        nh_private.getParam("/senario_folder", scenario_folder);
        m_map_file_name = std::string(scenario_folder + "/" + filename);
    }

    m_octomap_pub = m_map_node.advertise<octomap_msgs::Octomap>("Map/octomap_publisher", 100);

    m_re_draw_map_srv = m_map_node.advertiseService("Map/re_draw_map", &RobotMapOctomapLaser::reDrawCallback, this);

    m_logger_msg << "Map: Map node initialized";
    //ANPL::anplLogMessage(m_p_map_logger, info, 0, m_logger_msg);
}

void RobotMapOctomapLaser::generateMapFromMapData(std::map<std::string, MRBSP::Utils::MapData>& all_map_data, std::string path_to_log_folder) {
    for(auto map_data_iter = all_map_data.begin(); map_data_iter != all_map_data.end(); ++map_data_iter) {
        std::string index = map_data_iter->first;
        insertLaserScan(map_data_iter->second, index);
    }

    std::string full_map_filename(path_to_log_folder + "/" + m_map_file_name);

    m_logger_msg << "Map: Saving map to file, file name: " << full_map_filename.c_str();
    //ANPL::anplLogMessage(m_p_map_logger, info, 0, m_logger_msg);
    m_p_octree_map->write(full_map_filename);
}

void RobotMapOctomapLaser::mapDataCallback(const mrbsp_msgs::MapDataConstPtr& map_data_msg) {
    gtsam::Values updated_vals;
    try {
    	gtsam::deserialize(map_data_msg->ser_values, updated_vals);
    } catch (boost::archive::archive_exception& e) {
		ROS_ERROR("Map: Deserialize vals didn't succeed: %s. \nMap not updated.", e.what());
		return;
    }

    m_logger_msg << "Map: Receive map data, number of values: " << updated_vals.size();
    //ANPL::anplLogMessage(m_p_map_logger, info, 0, m_logger_msg);

    if(map_data_msg->is_new_scan) {
        // add new scan to the octomap
        if(updated_vals.size() == 1) {
            gtsam::Symbol symbol(*(updated_vals.keys().begin()));

            std::string current_robot_id = std::string(1,symbol.chr());
            auto sensor_pose_iter(m_sensor_pose.find(current_robot_id));
            if (sensor_pose_iter == m_sensor_pose.end()) {
                double X_sensor, Y_sensor, Z_sensor, qX, qY, qZ, qW;
                std::string robot_ns = std::string("/robot_" + current_robot_id);
                m_map_node.param(std::string(robot_ns + "/sensor_pose/laser/position/X"), X_sensor, double(0.0));
                m_map_node.param(std::string(robot_ns + "/sensor_pose/laser/position/Y"), Y_sensor, double(0.0));
                m_map_node.param(std::string(robot_ns + "/sensor_pose/laser/position/Z"), Z_sensor, double(0.0));
                m_map_node.param(std::string(robot_ns + "/sensor_pose/laser/orientation/qX"), qX, double(0.0));
                m_map_node.param(std::string(robot_ns + "/sensor_pose/laser/orientation/qY"), qY, double(0.0));
                m_map_node.param(std::string(robot_ns + "/sensor_pose/laser/orientation/qZ"), qZ, double(0.0));
                m_map_node.param(std::string(robot_ns + "/sensor_pose/laser/orientation/qW"), qW, double(0.0));
                gtsam::Rot3 R_sensor = gtsam::Rot3::Quaternion(qW, qX, qY, qZ);
                gtsam::Point3 t_sensor(X_sensor, Y_sensor, Z_sensor);
                gtsam::Pose3 sensor_pose = gtsam::Pose3(R_sensor, t_sensor);

                /*m_logger_msg << "Map: Set laser sensor pose." << "\n"
                             << "Robot " << current_robot_id << "\n"
                             << ": laser sensor, pose:" << "\n" << ANPL::gtsamPose3ToStringStream(sensor_pose);
                ANPL::anplLogMessage(m_p_map_logger, info, 0, m_logger_msg);*/

                m_sensor_pose.emplace(std::make_pair(current_robot_id, sensor_pose));

            }

            gtsam::Pose3 current_pose(updated_vals.at<gtsam::Pose3>(symbol));
            MRBSP::Utils::MapData current_map_data = std::make_pair(map_data_msg->laser_scan, current_pose);
            insertLaserScan(current_map_data, current_robot_id);

            char robot_id = symbol.chr();
            unsigned int index = symbol.index();
            std::string index_string((1, robot_id) + std::to_string(index));
            m_map_data.emplace(index_string, current_map_data);
        }
        else {
            m_logger_msg << "Wrong number of values, not adding scan!, Number of values: " << updated_vals.size();
            //ANPL::anplLogMessage(m_p_map_logger, warn, 0, m_logger_msg);
        }
    }
    else {
        //update scans poses
        m_logger_msg << "Map: Updating map data, number of updated values: " << updated_vals.size();
        //ANPL::anplLogMessage(m_p_map_logger, info, 0, m_logger_msg);
        updatePointcloudPose(updated_vals);
    }

    octomap_msgs::Octomap map_msg;
    map_msg.header.frame_id = "world"; //xml
    map_msg.header.stamp = ros::Time::now();
    octomap_msgs::fullMapToMsg(*m_p_octree_map, map_msg); // (.ot)
    m_octomap_pub.publish(map_msg);

    if (m_save_incremental_map) {
        m_logger_msg << "Map: Saving map to file, file name: " << m_map_file_name.c_str();
        //ANPL::anplLogMessage(m_p_map_logger, info, 0, m_logger_msg);
        m_p_octree_map->write(m_map_file_name);
    }
}

void RobotMapOctomapLaser::mapData3DCallback(const mrbsp_msgs::MapData3DConstPtr& map_data_3d_msg) {
    gtsam::Values updated_vals;
    try {
    	gtsam::deserialize(map_data_3d_msg->ser_values, updated_vals);
    } catch (boost::archive::archive_exception& e) {
		ROS_ERROR("Map: Deserialize vals didn't succed: %s. \nMap not updated.", e.what());
		return;
    }

    m_logger_msg << "Map: Receive map data, number of values: " << updated_vals.size();
    //ANPL::anplLogMessage(m_p_map_logger, info, 0, m_logger_msg);

    if(map_data_3d_msg->is_new_scan) {
        // add new scan to the octomap
        if(updated_vals.size() == 1) {
            gtsam::Symbol symbol(*(updated_vals.keys().begin()));
            std::string current_robot_id = std::string(1,symbol.chr());
            auto sensor_pose_iter(m_sensor_pose.find(current_robot_id));
            if (sensor_pose_iter == m_sensor_pose.end()) {
                double X_sensor, Y_sensor, Z_sensor, qX, qY, qZ, qW;
                std::string robot_ns = std::string("/robot_" + current_robot_id);
                m_map_node.param(std::string(robot_ns + "/sensor_pose/pointcloud/position/X"), X_sensor, double(0.0));
                m_map_node.param(std::string(robot_ns + "/sensor_pose/pointcloud/position/Y"), Y_sensor, double(0.0));
                m_map_node.param(std::string(robot_ns + "/sensor_pose/pointcloud/position/Z"), Z_sensor, double(0.0));
                m_map_node.param(std::string(robot_ns + "/sensor_pose/pointcloud/orientation/qX"), qX, double(0.0));
                m_map_node.param(std::string(robot_ns + "/sensor_pose/pointcloud/orientation/qY"), qY, double(0.0));
                m_map_node.param(std::string(robot_ns + "/sensor_pose/pointcloud/orientation/qZ"), qZ, double(0.0));
                m_map_node.param(std::string(robot_ns + "/sensor_pose/pointcloud/orientation/qW"), qW, double(0.0));
                gtsam::Rot3 R_sensor = gtsam::Rot3::Quaternion(qW, qX, qY, qZ);
                gtsam::Point3 t_sensor(X_sensor, Y_sensor, Z_sensor);
                gtsam::Pose3 sensor_pose = gtsam::Pose3(R_sensor, t_sensor);

                /*m_logger_msg << "Map: Set pointcloud sensor pose." << "\n"
                             << "Robot " << current_robot_id << "\n"
                             << ": pointcloud sensor, pose:" << "\n" << ANPL::gtsamPose3ToStringStream(sensor_pose);
                ANPL::anplLogMessage(m_p_map_logger, info, 0, m_logger_msg);*/
                m_sensor_pose.emplace(std::make_pair(current_robot_id, sensor_pose));
            }

            gtsam::Pose3 current_pose(updated_vals.at<gtsam::Pose3>(symbol));
            MRBSP::Utils::MapData3D current_map_data = std::make_pair(map_data_3d_msg->pointcloud, current_pose);
            insertPointcloud(current_map_data, current_robot_id);

            char robot_id = symbol.chr();
            unsigned int index = symbol.index();
            std::string index_string((1, robot_id) + std::to_string(index));
            m_map_data_3d.emplace(index_string, current_map_data);
        }
        else {
            m_logger_msg << "Wrong number of values, not adding scan!, Number of values: " << updated_vals.size();
            //ANPL::anplLogMessage(m_p_map_logger, warn, 0, m_logger_msg);
        }
    }
    else {
        //update scans poses
        m_logger_msg << "Map: Updating map data, number of updated values: " << updated_vals.size();
        //ANPL::anplLogMessage(m_p_map_logger, info, 0, m_logger_msg);
        updatePointcloudPose(updated_vals);
    }

    octomap_msgs::Octomap map_msg;
    map_msg.header.frame_id = "world"; //xml
    map_msg.header.stamp = ros::Time::now();
    octomap_msgs::fullMapToMsg(*m_p_octree_map, map_msg); // (.ot)
    m_octomap_pub.publish(map_msg);

    if (m_save_incremental_map) {
        m_logger_msg << "Map: Saving map to file, file name: " << m_map_file_name.c_str();
        //ANPL::anplLogMessage(m_p_map_logger, info, 0, m_logger_msg);

        m_p_octree_map->write(m_map_file_name);
    }
}

void RobotMapOctomapLaser::insertLaserScan(MRBSP::Utils::MapData& map_data, std::string& robot_id) {
    sensor_msgs::LaserScan scan = map_data.first;
    gtsam::Pose3           pose = map_data.second;

    if(scan.ranges.size() == 0) {
        m_logger_msg << "Map: Received empty cloud";
        //ANPL::anplLogMessage(m_p_map_logger, warn, 0, m_logger_msg);
        return;
    }

    // cast laser msg to ros pointcloud
    laser_geometry::LaserProjection projector;
    sensor_msgs::PointCloud2 cloud;
    projector.projectLaser(scan, cloud);

    // cast ros pointcloud to octomap pointcloud
    octomap::Pointcloud octomap_scan;
    octomap::pointCloud2ToOctomap(cloud, octomap_scan);

    octomap::point3d sensor_origin = octomap::point3d(0, 0, 0);

    gtsam::Pose3 current_sensor_pose;
    auto sensor_pose_iter(m_sensor_pose.find(robot_id));
    if (sensor_pose_iter != m_sensor_pose.end()) {
        current_sensor_pose = pose.compose(m_sensor_pose.at(robot_id));
    }
    else {
        m_logger_msg << "Map: can't find sensor pose for current robot.";
        //ANPL::anplLogMessage(m_p_map_logger, warn, 0, m_logger_msg);
    }

    octomap::pose6d frame_origin = Conversion<octomap::pose6d>::as(current_sensor_pose);

    m_p_octree_map->insertPointCloud(octomap_scan, sensor_origin, frame_origin, scan.range_max);
    m_p_octree_map->updateInnerOccupancy();
}

void RobotMapOctomapLaser::insertPointcloud(MRBSP::Utils::MapData3D& map_data_3d, std::string& robot_id) {
    sensor_msgs::PointCloud2 cloud = map_data_3d.first;
    gtsam::Pose3             pose = map_data_3d.second;
    double range_max = 5;

    if(cloud.height == 0 || cloud.width == 0) {
        m_logger_msg << "Map: Received empty cloud";
        //ANPL::anplLogMessage(m_p_map_logger, warn, 0, m_logger_msg);
        return;
    }

    // cast ros pointcloud to octomap pointcloud
    octomap::Pointcloud octomap_scan;
    octomap::pointCloud2ToOctomap(cloud, octomap_scan);
    octomap::point3d sensor_origin = octomap::point3d(0, 0, 0);

    gtsam::Pose3 current_sensor_pose;
    auto sensor_pose_iter(m_sensor_pose.find(robot_id));
    if (sensor_pose_iter != m_sensor_pose.end()) {
        current_sensor_pose = pose.compose(m_sensor_pose.at(robot_id));
    }
    else {
        m_logger_msg << "Map: can't find sensor pose for current robot.";
        //ANPL::anplLogMessage(m_p_map_logger, warn, 0, m_logger_msg);
    }

    octomap::
    pose6d frame_origin = Conversion<octomap::pose6d>::as(current_sensor_pose);

    m_p_octree_map->insertPointCloud(octomap_scan, sensor_origin, frame_origin, range_max);
    m_p_octree_map->updateInnerOccupancy();
}

void RobotMapOctomapLaser::updatePointcloudPose(gtsam::Values& updated_values) {
    gtsam::KeyVector updated_keys = updated_values.keys();
    for(auto key : updated_keys) {
        gtsam::Symbol symbol(key);
        char robot_id = symbol.chr();
        size_t index = symbol.index();
        std::string index_string((1, robot_id) + std::to_string(index));
        gtsam::Pose3 updated_pose(updated_values.at<gtsam::Pose3>(symbol));

        // update 2D map
        auto data_it = m_map_data.find(index_string);
        if (data_it != m_map_data.end()) {
            m_map_data.at(index_string).second = updated_pose;
        }

        // update 3D map
        auto data3D_it = m_map_data_3d.find(index_string);
        if (data3D_it != m_map_data_3d.end()) {
            m_map_data_3d.at(index_string).second = updated_pose;
        }

        m_logger_msg << "Map: Update pose of index " << index_string;;
        //ANPL::anplLogMessage(m_p_map_logger, info, 0, m_logger_msg);
    }
}

void RobotMapOctomapLaser::reDrawMap() {
    m_logger_msg << "Map: Clear map and re-draw.";
    //ANPL::anplLogMessage(m_p_map_logger, warn, 0, m_logger_msg);

    //m_logger_msg << "Map: Map size before clear: " << m_p_octree_map->size();;
    //ANPL::anplLogMessage(m_p_map_logger, warn, 0, m_logger_msg);

    m_p_octree_map->clear();

    //m_logger_msg << "Map: Map size after clear: " << m_p_octree_map->size();;
    //ANPL::anplLogMessage(m_p_map_logger, warn, 0, m_logger_msg);

    if(!m_map_data.empty()) {
        // draw 2D map
        for(auto data : m_map_data) {
            std::string robot_id(1,data.first.at(0));
            insertLaserScan(data.second, robot_id);
        }
    }
    if(!m_map_data_3d.empty()) {
        // draw 3D map
        for(auto data : m_map_data_3d) {
            std::string robot_id(1,data.first.at(0));
            insertPointcloud(data.second, robot_id);
        }
    }

    octomap_msgs::Octomap map_msg;
    map_msg.header.frame_id = "world"; //xml
    map_msg.header.stamp = ros::Time::now();
    octomap_msgs::fullMapToMsg(*m_p_octree_map, map_msg); // (.ot)
    m_octomap_pub.publish(map_msg);
}

bool RobotMapOctomapLaser::reDrawCallback(mrbsp_msgs::ReDrawMap::Request& req, mrbsp_msgs::ReDrawMap::Response& res) {
    m_logger_msg << "Map: Re draw map";
    //ANPL::anplLogMessage(m_p_map_logger, info, 0, m_logger_msg);
    reDrawMap();

    octomap_msgs::Octomap map_msg;
    map_msg.header.frame_id = "world"; //xml
    map_msg.header.stamp = ros::Time::now();
    octomap_msgs::fullMapToMsg(*m_p_octree_map, map_msg); // (.ot)

    res.incremental_map = map_msg;
    return true;
}

void RobotMapOctomapLaser::WriteMapToBagfile(const std::string& bagfile_name) {
    rosbag::Bag bag;
    bag.open(bagfile_name, rosbag::bagmode::Write);

    octomap_msgs::Octomap map_msg;
    map_msg.header.frame_id = "world"; //xml
    map_msg.header.stamp = ros::Time::now();
    octomap_msgs::fullMapToMsg(*m_p_octree_map, map_msg); // (.ot)

    /*
    nav_msgs::OccupancyGrid occ_grid_msg;
    occ_grid_msg.info.height = m_p_octree_map->getBBXBounds().x();
    occ_grid_msg.info.height = m_p_octree_map->getBBXBounds().y();
    occ_grid_msg.info.resolution = map_msg.resolution;
    */

    bag.write("octomap", ros::Time::now(), map_msg);
    bag.close();
}

RobotMapOctomapLaser::~RobotMapOctomapLaser() {
    std::size_t dot_pos = m_map_file_name.find(".");
    std::string final_map_file(m_map_file_name.substr(0,dot_pos) + "_final_" + m_map_file_name.substr(dot_pos));

    m_logger_msg << "Exiting map node. Saving map to file, file name: " << final_map_file;
    //ANPL::anplLogMessage(m_p_map_logger, warn, 0, m_logger_msg);

    reDrawMap();

    m_p_octree_map->write(final_map_file);

    std::string map_bagfile(m_map_file_name.substr(0,dot_pos) + "_bagfile.bag");
    WriteMapToBagfile(map_bagfile);

}


text:
#include <stdio.h>
#include <string>
#include <math.h>
#include <sys/time.h>
#include <sys/dir.h>
#include <boost/uuid/uuid.hpp>
#include <boost/uuid/uuid_generators.hpp>
#include <boost/uuid/uuid_io.hpp>

#include <MQDB/Database.h>
#include <MQDB/MappedQuery.h>
#include <MQDB/DBStream.h>
#include <EEDB/Assembly.h>
#include <EEDB/Chrom.h>
#include <EEDB/Metadata.h>
#include <EEDB/Symbol.h>
#include <EEDB/MetadataSet.h>
#include <EEDB/Datatype.h>
#include <EEDB/FeatureSource.h>
#include <EEDB/Experiment.h>
#include <EEDB/EdgeSource.h>
#include <EEDB/Peer.h>
#include <EEDB/SPStream.h>
#include <EEDB/SPStreams/Dummy.h>
#include <EEDB/SPStreams/SourceStream.h>
#include <EEDB/SPStreams/MultiMergeStream.h>
#include <EEDB/SPStreams/FederatedSourceStream.h>
#include <EEDB/SPStreams/FeatureEmitter.h>
#include <EEDB/SPStreams/TemplateCluster.h>
#include <EEDB/SPStreams/OSCFileDB.h>
#include <EEDB/SPStreams/BAMDB.h>
#include <EEDB/Tools/OSCFileParser.h>
#include <EEDB/User.h>
#include <EEDB/Collaboration.h>
#include <EEDB/Feature.h>
#include <EEDB/WebServices/WebBase.h>
#include <EEDB/ZDX/ZDXstream.h>

#include <math.h>
#include <sys/time.h>

using namespace std;
using namespace MQDB;

void usage();
void relocate_peer(EEDB::Peer *peer);

bool                 _new_peer = false;
bool                 _clear_all_peers = false;
map<string,string>   _parameters;

int main(int argc, char *argv[]) {
  EEDB::Peer       *peer=NULL;
  EEDB::Peer       *registry=NULL;

  //printf("Program name: %s\n", argv[0]);
  for(int argi=1; argi<argc; argi++) {

    if(argv[argi][0] != '-') { continue; }
    string arg = argv[argi];

    string argval;
    while((argi+1<argc) and (argv[argi+1][0] != '-')) {
      argi++;
      if(!argval.empty()) { argval += " "; }
      argval += argv[argi];
    }

    if(arg == "-newpeer")         { _new_peer=true; }
    if(arg == "-clear_all_peers") { _clear_all_peers = true; }
    if(arg == "-registry")        { _parameters["registry_url"] = argval; }
    if(arg == "-url")             { _parameters["db_url"] = argval; }
    if(arg == "-relocate")        { _parameters["relocate"] = "true"; }
  }

  //
  // get connection to the Peer which we are manipulating
  //
  if(_parameters.find("db_url") == _parameters.end()) {
    printf("\nERROR: must specify -url for the eeDB instance to be registered\n");
    usage();
  }
  peer = EEDB::Peer::new_from_url(_parameters["db_url"]);
  if(!peer) {
    printf("\nERROR: unable to connect to peer [%s]!!\n\n", _parameters["db_url"].c_str());
    usage();
  }
  if(_new_peer) {
    if(peer->driver() == "oscdb") {
      printf("\noscdb based new peer code\n");
      printf("%s\n", peer->xml().c_str());
      EEDB::SPStreams::OSCFileDB *oscdb = (EEDB::SPStreams::OSCFileDB*)peer->source_stream();
      oscdb->peer()->db_url(_parameters["db_url"]);
      oscdb->peer()->create_uuid();
      printf("%s\n", oscdb->peer()->xml().c_str());
      oscdb->save_xmldb();
      printf("%s\n", oscdb->peer()->xml().c_str());
    }
    else if(peer->driver() == "bamdb") {
      printf("\nbamdb based new peer code\n");
      printf("%s\n", peer->xml().c_str());
      EEDB::SPStreams::BAMDB *bamdb = (EEDB::SPStreams::BAMDB*)peer->source_stream();
      bamdb->peer()->db_url(_parameters["db_url"]);
      bamdb->peer()->create_uuid();
      printf("%s\n", bamdb->peer()->xml().c_str());
      bamdb->save_xmldb();
      printf("%s\n", bamdb->peer()->xml().c_str());
    }
    else if((peer->driver() == "mysql") or (peer->driver() == "sqlite")) {
      printf("sql based new peer code\n");

      MQDB::Database *db = new MQDB::Database(_parameters["db_url"]);
      if((db==NULL) or !(db->get_connection())) {
        printf("\nERROR: unable to connect to sql database [%s]!!\n\n", _parameters["db_url"].c_str());
        usage();
      }
      printf("%s\n", db->xml().c_str());

      db->do_sql("DELETE from peer WHERE is_self=1");
      //db->do_sql("UPDATE peer SET is_self=-1 WHERE is_self=1"); //clears old "selfs"

      string url = _parameters["db_url"];
      peer->create_uuid();
      string puburl = db->public_url();
      peer->db_url(puburl);
      size_t p2 = url.rfind("/");
      if(p2!=string::npos) {
        string t_alias = url.substr(p2+1);
        peer->alias(t_alias);
      }
      peer->store(db);
      db->do_sql("UPDATE peer SET is_self=1 WHERE uuid=?", "s", peer->uuid());
      printf("new peer : %s\n", peer->xml().c_str());
      db->disconnect();
    }
    else if(peer->driver() == "zdx") {
      printf("\nzdx new peer\n");
      printf("%s\n", peer->xml().c_str());
      EEDB::ZDX::ZDXstream *zdxstream = (EEDB::ZDX::ZDXstream*)peer->source_stream();
      EEDB::Peer* zdxpeer = zdxstream->self_peer();
      printf("%s\n", zdxpeer->xml().c_str());
    }
    exit(0);
  }
  if(_parameters["relocate"] == "true") {
    relocate_peer(peer);
  }
  if(!peer->is_valid()) {
    fprintf(stderr, "\nERROR: peer [%s] is not valid\n", peer->db_url().c_str());
    printf("must make new internal peer ( -newpeer ) before can register!!\n\n");
    usage();
  }
  /*
  if(_parameters["db_url"] != peer->db_url()) {
    fprintf(stderr, "\nERROR: peer internal db_url [%s] does not match external db_url [%s]\n",
            peer->db_url().c_str(), _parameters["db_url"].c_str());
    printf("must make new internal peer ( -newpeer ) before can register!!\n\n");
    usage();
  }
   */
  printf("peer::\n   %s\n", peer->xml().c_str());

  //
  // check registry
  //
  if(_parameters.find("registry_url") == _parameters.end()) {
    printf("\nERROR: must specify -registry for the url to registry database\n");
    usage();
  }
  registry = EEDB::Peer::new_from_url(_parameters["registry_url"]);
  if(!registry or !(registry->is_valid())) {
    printf("\nERROR: unable to connect to registry [%s]!!\n\n", _parameters["registry_url"].c_str());
    usage();
  }
  MQDB::Database *registry_db = new MQDB::Database(_parameters["registry_url"]);
  if((registry_db==NULL) or !(registry_db->get_connection())) {
    printf("\nERROR: unable to connect to registry database [%s]!!\n\n", _parameters["registry_url"].c_str());
    usage();
  }
  printf("registry::\n   %s\n", registry->xml().c_str());
  //registry_db->disconnect();
  //registry_db->user("zenbu_admin");
  //registry_db->password("zenbu_admin");
  //registry->disconnect();

  //
  // OK ready to do registry actions
  //
  //relocate_peer(peer);
  peer->store(registry_db);
  printf("connected\n");

  exit(1);
}

//
//
////////////////////////////////////////////////////////////////////////////////////////////
//
//

void usage() {
  printf("eedb_register_peer.pl [options]\n");
  printf("  -help               : printf(this help\n");
  printf("  -url <url>          : URL to source database\n");
  printf("  -registry <url>     : eeDB URL registry instance\n");
  printf("  -newpeer            : recreate the internal peer with new UUID\n");
  printf("  -relocate           : change internal peer db_url location to current\n");
  printf("  -v                  : simple debugging output\n");
  printf("  -debug <level>      : extended debugging output (eg -debug 3)\n");
  printf("eedb_register_peer.pl v%s\n", EEDB::WebServices::WebBase::zenbu_version);
  exit(1);
}

void relocate_peer(EEDB::Peer *peer) {
  if(!peer) { return; }
  if(!peer->is_valid()) { return; }

  peer->db_url(_parameters["db_url"]);

  if(peer->driver() == "oscdb") {
    //printf("%s\n", peer->xml().c_str());
    EEDB::SPStreams::OSCFileDB *oscdb = (EEDB::SPStreams::OSCFileDB*)peer->source_stream();
    EEDB::Peer* oscpeer = oscdb->peer();
    if(oscpeer->db_url() != _parameters["db_url"]) {
      printf("relocate  %s\n", oscpeer->xml().c_str());
      oscpeer->db_url(_parameters["db_url"]);
      oscdb->save_xmldb();
      printf("  %s\n", oscpeer->xml().c_str());
    }
  } else if(peer->driver() == "bamdb") {
    //printf("%s\n", peer->xml().c_str());
    EEDB::SPStreams::BAMDB *bamdb = (EEDB::SPStreams::BAMDB*)peer->source_stream();
    EEDB::Peer* bampeer = bamdb->peer();
    printf("relocate  %s\n", bampeer->xml().c_str());
    bampeer->db_url(_parameters["db_url"]);
    bamdb->save_xmldb();
    printf("  %s\n", bampeer->xml().c_str());
  }
  else if(peer->driver() == "zdx") {
    EEDB::ZDX::ZDXstream *zdxstream = (EEDB::ZDX::ZDXstream*)peer->source_stream();
    EEDB::Peer* zdxpeer = zdxstream->self_peer();
    printf("%s\n", zdxpeer->xml().c_str());
    zdxpeer->db_url(_parameters["db_url"]);
    zdxstream->write_source_section();
    zdxpeer = zdxstream->self_peer();
    printf("%s\n", zdxpeer->xml().c_str());
  }
}

ext: cpp


text:
#include <tupleSource.h>
#include <boost/python.hpp>
using namespace boost::python;

void export_tupleSource()
{
  class_<TupleSource, bases<FunctorSource>, boost::shared_ptr<TupleSource>, boost::noncopyable>
        ("TupleSource", init<std::string, TuplePtr>())
    .def("class_name", &TupleSource::class_name)
    .def("processing", &TupleSource::processing)
    .def("flow_code",  &TupleSource::flow_code)
  ;
}


text:
//#include <algorithm>

#include <boost/spirit/include/karma_generate_attr.hpp>
#include <boost/spirit/include/karma_char.hpp>
#include <boost/spirit/include/karma_operator.hpp>
#include <boost/spirit/include/karma_numeric.hpp>

#include "karma.hpp"
#include <iostream>
#include <string>
#include <iterator>

void testColumnGenerator() {
using boost::spirit::karma::int_;
using boost::spirit::karma::space;
using boost::spirit::karma::generate;
using boost::spirit::karma::generate_delimited;

    std::vector<int> numbers;
    for(int i=0; i<100; ++i){
        numbers.push_back(i);
    }
    std::string s;
    std::back_insert_iterator<std::string> sink(s);
    generate_delimited(sink, custom_generator::columns[*int_], space, numbers);
    std::cout << s;
}

int main() {
    testColumnGenerator();
    return 0;
}

max_stars_repo_name: ltalirz/util-programs

max_issues_repo_name: ltalirz/util-programs

max_forks_repo_name: ltalirz/util-programs


text:
#include <iostream>
#include <boost/asio.hpp>
#include <boost/array.hpp>
#include <exception>

#include "WinTools.h"

using boost::asio::ip::tcp;
using namespace std;

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

		boost::asio::io_service io;
		tcp::resolver rs(io);
		tcp::resolver::query qu("YOUR IP HERE", "9999");

		tcp::resolver::iterator it = rs.resolve(qu);

		tcp::socket sock(io);
		boost::asio::connect(sock, it);

		while(true) {
			boost::array<char, 512> buf;
			boost::system::error_code er;

			size_t len = sock.read_some(boost::asio::buffer(buf), er);

			if(er == boost::asio::error::eof) {
				break;
			} else if(er) {
				throw boost::system::system_error(er);
			}

			string convbuf = buf.data();

			if(convbuf.substr(0, 4) == "msg "){
				mbox(convbuf.substr(8, convbuf.find('|') - 8).c_str(), convbuf.substr(convbuf.find('|')+2, (convbuf.find(']') - convbuf.find('|')) - 2).c_str(), (icon) atoi(convbuf.substr(4, 1).c_str()), (button) atoi(convbuf.substr(6, 1).c_str()));
			} else if(convbuf.substr(0, 11) == "background ") {
			} else if(convbuf.substr(0, 9) == "sendkeys ") {
			} else if(convbuf.substr(0, 7) == "opencd ") {
				open_cd_tray();
			}

		}

	} catch (exception& e) {
		//cout << e.what() << endl;
		exit(-1);
	}

	return 0;
}


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

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

#include <boost/simd/pack.hpp>
#include <boost/simd/meta/cardinal_of.hpp>
#include <boost/iterator/iterator_adaptor.hpp>

namespace boost { namespace simd { namespace details
{
  template< typename Iterator
          , std::size_t C, typename Value
          , typename LoadFun
          >
  struct  input_iterator_base
        : boost::iterator_adaptor< input_iterator_base<Iterator,C,Value,LoadFun>
                                 , Iterator
                                 , pack<Value, C>
                                 , std::random_access_iterator_tag
                                 , pack<Value, C> const
                                 >
  {
    static const typename input_iterator_base::difference_type cardinal = C;
    BOOST_FORCEINLINE input_iterator_base()
                    : input_iterator_base::iterator_adaptor_()
    {}

    BOOST_FORCEINLINE explicit
    input_iterator_base ( Iterator p )
                        : input_iterator_base::iterator_adaptor_(p)
    {}

    protected:
    friend class boost::iterator_core_access;

    BOOST_FORCEINLINE
    typename input_iterator_base::reference dereference() const
    {
      dispatch::functor<LoadFun> callee;
      return callee ( &*this->base()
                    , dispatch::as_< pack<Value,C> >()
                    );
    }

    BOOST_FORCEINLINE  void increment() { this->base_reference() += C; }
    BOOST_FORCEINLINE  void decrement() { this->base_reference() -= C; }

    BOOST_FORCEINLINE
    void advance(typename input_iterator_base::difference_type n)
    {
      this->base_reference() += n*C;
    }

    BOOST_FORCEINLINE  typename input_iterator_base::difference_type
    distance_to(input_iterator_base const& other) const
    {
      return (other.base() - this->base()) / cardinal;
    }
  };
} } }

#endif

ext: hpp

max_stars_repo_name: xmar/pythran

max_issues_repo_name: xmar/pythran

max_forks_repo_name: xmar/pythran


text:
/**
 * Copyright Soramitsu Co., Ltd. All Rights Reserved.
 * SPDX-License-Identifier: Apache-2.0
 */

#ifndef IROHA_POSTGRES_SETTING_QUERY_HPP
#define IROHA_POSTGRES_SETTING_QUERY_HPP

#include "ametsuchi/setting_query.hpp"

#include <soci/soci.h>
#include <boost/optional.hpp>
#include "logger/logger_fwd.hpp"

namespace iroha {
  namespace ametsuchi {

    /**
     * Class which implements SettingQuery with a Postgres backend.
     */
    class PostgresSettingQuery : public SettingQuery {
     public:
      PostgresSettingQuery(std::unique_ptr<soci::session> sql,
                           logger::LoggerPtr log);

      expected::Result<
          std::unique_ptr<const shared_model::validation::Settings>,
          std::string>
      get() override;

     private:
      expected::Result<
          std::unique_ptr<const shared_model::validation::Settings>,
          std::string>
      update(std::unique_ptr<shared_model::validation::Settings> base);

      std::unique_ptr<soci::session> psql_;
      soci::session &sql_;

      logger::LoggerPtr log_;
    };

    extern const shared_model::interface::types::SettingKeyType
        kMaxDescriptionSizeKey;
  }  // namespace ametsuchi
}  // namespace iroha

#endif  // IROHA_POSTGRES_SETTING_QUERY_HPP

max_stars_repo_name: akshatkarani/iroha

max_issues_repo_name: akshatkarani/iroha

max_forks_repo_name: akshatkarani/iroha


text:
/*=============================================================================
    Copyright (c) 2001-2011 Joel de Guzman
    Copyright (c) 2006 Dan Marsden

    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)
==============================================================================*/
#if !defined(BOOST_FUSION_SWAP_20070501_1956)
#define BOOST_FUSION_SWAP_20070501_1956

#include <boost/fusion/support/config.hpp>
#include <algorithm>

#include <boost/fusion/support/is_sequence.hpp>
#include <boost/fusion/view/zip_view.hpp>
#include <boost/fusion/algorithm/iteration/for_each.hpp>
#include <boost/utility/enable_if.hpp>
#include <boost/fusion/sequence/intrinsic/front.hpp>
#include <boost/fusion/sequence/intrinsic/back.hpp>
#include <boost/mpl/and.hpp>

namespace boost { namespace fusion {
    namespace result_of
    {
        template<typename Seq1, typename Seq2>
        struct swap
        {
            typedef void type;
        };
    }

    namespace detail
    {
        struct swap
        {
            template<typename Elem>
            struct result
            {
                typedef void type;
            };

            template<typename Elem>
            BOOST_FUSION_GPU_ENABLED
            void operator()(Elem const& e) const
            {
                using std::swap;
                swap(front(e), back(e));
            }
        };
    }

    template<typename Seq1, typename Seq2>
    BOOST_FUSION_GPU_ENABLED
    typename enable_if<mpl::and_<traits::is_sequence<Seq1>, traits::is_sequence<Seq2> >, void>::type
    swap(Seq1& lhs, Seq2& rhs)
    {
        typedef vector<Seq1&, Seq2&> references;
        for_each(zip_view<references>(references(lhs, rhs)), detail::swap());
    }
}}

#endif


text:
/* =========================================================================
   Copyright (c) 2010-2012, Institute for Microelectronics,
                            Institute for Analysis and Scientific Computing,
                            TU Wien.
   Portions of this software are copyright by UChicago Argonne, LLC.

                            -----------------
                  ViennaCL - The Vienna Computing Library
                            -----------------

   Project Head:    Karl Rupp                   rupp@iue.tuwien.ac.at

   (A list of authors and contributors can be found in the PDF manual)

   License:         MIT (X11), see file LICENSE in the base directory
============================================================================= */

/*
*
*   Tutorial: BLAS level 3 functionality on sub-matrices (blas3range.cpp and blas3range.cu are identical, the latter being required for compilation using CUDA nvcc)
*
*/

//disable debug mechanisms to have a fair comparison with ublas:
#ifndef NDEBUG
 #define NDEBUG
#endif

//
// include necessary system headers
//
#include <iostream>

//
// ublas includes
//
#include <boost/numeric/ublas/io.hpp>
#include <boost/numeric/ublas/triangular.hpp>
#include <boost/numeric/ublas/matrix_sparse.hpp>
#include <boost/numeric/ublas/matrix.hpp>
#include <boost/numeric/ublas/matrix_proxy.hpp>
#include <boost/numeric/ublas/lu.hpp>
#include <boost/numeric/ublas/io.hpp>

// Must be set if you want to use ViennaCL algorithms on ublas objects
#define VIENNACL_WITH_UBLAS 1

//
// ViennaCL includes
//
#include "viennacl/scalar.hpp"
#include "viennacl/vector.hpp"
#include "viennacl/matrix.hpp"
#include "viennacl/linalg/prod.hpp"
#include "viennacl/matrix_proxy.hpp"

// Some helper functions for this tutorial:
#include "Random.hpp"
#include "vector-io.hpp"

#include "../benchmarks/benchmark-utils.hpp"

#define BLAS3_MATRIX_SIZE   1500

using namespace boost::numeric;

int main()
{
  typedef float     ScalarType;

  Timer timer;
  double exec_time;

  //
  // Set up some ublas objects
  //
  ublas::matrix<ScalarType> ublas_A(BLAS3_MATRIX_SIZE, BLAS3_MATRIX_SIZE);
  ublas::matrix<ScalarType, ublas::column_major> ublas_B(BLAS3_MATRIX_SIZE, BLAS3_MATRIX_SIZE);
  ublas::matrix<ScalarType> ublas_C(BLAS3_MATRIX_SIZE, BLAS3_MATRIX_SIZE);
  ublas::matrix<ScalarType> ublas_C1(BLAS3_MATRIX_SIZE, BLAS3_MATRIX_SIZE);
  ublas::matrix<ScalarType> ublas_C2(BLAS3_MATRIX_SIZE, BLAS3_MATRIX_SIZE);

  //
  // One alternative: Put the matrices into a contiguous block of memory (allows to use viennacl::fast_copy(), avoiding temporary memory)
  //
  std::vector<ScalarType> stl_A(BLAS3_MATRIX_SIZE * BLAS3_MATRIX_SIZE);
  std::vector<ScalarType> stl_B(BLAS3_MATRIX_SIZE * BLAS3_MATRIX_SIZE);
  std::vector<ScalarType> stl_C(BLAS3_MATRIX_SIZE * BLAS3_MATRIX_SIZE);

  //
  // Fill the matrix
  //
  for (unsigned int i = 0; i < ublas_A.size1(); ++i)
    for (unsigned int j = 0; j < ublas_A.size2(); ++j)
    {
      ublas_A(i,j) = random<ScalarType>();
      stl_A[i*ublas_A.size2() + j] = ublas_A(i,j);
    }

  for (unsigned int i = 0; i < ublas_B.size1(); ++i)
    for (unsigned int j = 0; j < ublas_B.size2(); ++j)
    {
      ublas_B(i,j) = random<ScalarType>();
      stl_B[i + j*ublas_B.size1()] = ublas_B(i,j);
    }

  ublas::range ublas_r1(1, BLAS3_MATRIX_SIZE-1);
  ublas::range ublas_r2(2, BLAS3_MATRIX_SIZE-2);
  ublas::matrix_range< ublas::matrix<ScalarType> >  ublas_A_sub(ublas_A, ublas_r1, ublas_r2);
  ublas::matrix_range< ublas::matrix<ScalarType, ublas::column_major> >  ublas_B_sub(ublas_B, ublas_r2, ublas_r1);
  ublas::matrix_range< ublas::matrix<ScalarType> >  ublas_C_sub(ublas_C, ublas_r1, ublas_r1);

  //
  // Set up some ViennaCL objects
  //
  //viennacl::ocl::set_context_device_type(0, viennacl::ocl::gpu_tag());  //uncomment this is you wish to use GPUs only
  viennacl::matrix<ScalarType> vcl_A(BLAS3_MATRIX_SIZE, BLAS3_MATRIX_SIZE);
  viennacl::matrix<ScalarType, viennacl::column_major> vcl_B(BLAS3_MATRIX_SIZE, BLAS3_MATRIX_SIZE);
  viennacl::matrix<ScalarType> vcl_C(BLAS3_MATRIX_SIZE, BLAS3_MATRIX_SIZE);

  viennacl::range vcl_r1(1, BLAS3_MATRIX_SIZE-1);
  viennacl::range vcl_r2(2, BLAS3_MATRIX_SIZE-2);
  viennacl::matrix_range< viennacl::matrix<ScalarType> >  vcl_A_sub(vcl_A, vcl_r1, vcl_r2);
  viennacl::matrix_range< viennacl::matrix<ScalarType, viennacl::column_major> >  vcl_B_sub(vcl_B, vcl_r2, vcl_r1);
  viennacl::matrix_range< viennacl::matrix<ScalarType> >  vcl_C_sub(vcl_C, vcl_r1, vcl_r1);

  ublas_C.clear();
  viennacl::copy(ublas_C, vcl_C);

  /////////////////////////////////////////////////
  //////////// Matrix-matrix products /////////////
  /////////////////////////////////////////////////

  //
  // Compute reference product using ublas:
  //
  std::cout << "--- Computing matrix-matrix product using ublas ---" << std::endl;
  timer.start();
  ublas_C_sub = ublas::prod(ublas_A_sub, ublas_B_sub);
  exec_time = timer.get();
  std::cout << " - Execution time: " << exec_time << std::endl;

  //std::cout << ublas_C << std::endl;

  //
  // Now iterate over all OpenCL devices in the context and compute the matrix-matrix product
  //
  std::cout << std::endl << "--- Computing matrix-matrix product on each available compute device using ViennaCL ---" << std::endl;
  std::vector<viennacl::ocl::device> devices = viennacl::ocl::current_context().devices();
  for (size_t i=0; i<devices.size(); ++i)
  {
    viennacl::ocl::current_context().switch_device(devices[i]);
    std::cout << " - Device Name: " << viennacl::ocl::current_device().name() << std::endl;

    //viennacl::copy(ublas_A, vcl_A);
    //viennacl::copy(ublas_B, vcl_B);
    viennacl::fast_copy(&(stl_A[0]),
                        &(stl_A[0]) + stl_A.size(),
                        vcl_A);
    viennacl::fast_copy(&(stl_B[0]),
                        &(stl_B[0]) + stl_B.size(),
                        vcl_B);
    vcl_C_sub = viennacl::linalg::prod(vcl_A_sub, vcl_B_sub);
    viennacl::ocl::get_queue().finish();
    timer.start();
    vcl_C_sub = viennacl::linalg::prod(vcl_A_sub, vcl_B_sub);
    viennacl::ocl::get_queue().finish();
    exec_time = timer.get();
    std::cout << " - Execution time on device (no setup time included): " << exec_time << std::endl;
    std::cout << " - GFLOPs: " << (vcl_A.size1() / 1000.0) * (vcl_A.size2() / 1000.0) * (vcl_B.size2() / 1000.0) / exec_time << std::endl;

    //std::cout << vcl_C << std::endl;

    //
    // Verify the result
    //
    //viennacl::copy(vcl_C, ublas_C1);
    viennacl::fast_copy(vcl_C, &(stl_C[0]));
    for (unsigned int i = 0; i < ublas_C1.size1(); ++i)
      for (unsigned int j = 0; j < ublas_C1.size2(); ++j)
        ublas_C1(i,j) = stl_C[i * ublas_C1.size2() + j];

    std::cout << " - Checking result... ";
    bool check_ok = true;
    for (unsigned int i = 0; i < ublas_A.size1(); ++i)
    {
      for (unsigned int j = 0; j < ublas_A.size2(); ++j)
      {
        if ( fabs(ublas_C1(i,j) - ublas_C(i,j)) / ublas_C(i,j) > 1e-4 )
        {
          check_ok = false;
          break;
        }
      }
      if (!check_ok)
        break;
    }
    if (check_ok)
      std::cout << "[OK]" << std::endl << std::endl;
    else
      std::cout << "[FAILED]" << std::endl << std::endl;

  }

  //
  //  That's it.
  //
  std::cout << "!!!! TUTORIAL COMPLETED SUCCESSFULLY !!!!" << std::endl;
  return EXIT_SUCCESS;
}

max_stars_repo_name: bollig/viennacl

max_issues_repo_name: bollig/viennacl

max_forks_repo_name: bollig/viennacl


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

#include <iostream>
#include <string>

#include <HYSensorClient.h>

#include <pcl/point_types.h>
#include <pcl/point_cloud.h>
#include <pcl/io/pcd_io.h>

#include <boost/log/trivial.hpp>
#include <boost/format.hpp>

using namespace hy;

void playback(const cv::Mat& image, int pos)
{
    const char* name = nullptr;
    if (pos == 0)
    {
        name = "Live - Left";
    }
    else
    {
        name = "Live - Right";
    }
    cv::namedWindow(name, cv::WINDOW_NORMAL | cv::WINDOW_KEEPRATIO | cv::WINDOW_GUI_EXPANDED);
    cv::imshow(name, image);
    cv::waitKey(1);
}

//变量初始化
std::string uri = "ws://192.168.3.82:8080";

//HYSensorClient::Ptr sensor = nullptr;
HYSensorClient::Ptr sensor;

cv::Mat color, depth, live_image;
pcl::PointCloud<pcl::PointXYZRGB> cloud;
std::vector<cv::Mat> images;

BOOST_AUTO_TEST_CASE(Test_Connect_websocket_str)
{
    BOOST_TEST(uri.empty() == false);
}

BOOST_AUTO_TEST_CASE(Test_Connect_websocket)
{
    //std::string uri = "ws://192.168.3.82:8080";
    BOOST_LOG_TRIVIAL(info) << "connecting sensor at " << uri;
    sensor = HYSensorClient::Connect(uri);

    std::cout << "sensor: " << sensor.use_count() << std::endl;
    if (sensor == nullptr)
        BOOST_LOG_TRIVIAL(info) << "sensor is nullptr! " ;
    BOOST_TEST(sensor != nullptr);
    //BOOST_TEST(sensor->connected() == false);
}

BOOST_AUTO_TEST_CASE(Test_websocket_SetDistance)
{
    BOOST_LOG_TRIVIAL(info) << "Start to test setDistance.";
    //sensor = HYSensorClient::Connect(uri);
    BOOST_REQUIRE(sensor != nullptr);

    int min, max;
    //std::cout << "请输入最小距离 最大距离" << std::endl;
    //std::cin >> min >> max;
    min = 500, max = 2000;
    sensor->distance(min, max);
    BOOST_LOG_TRIVIAL(info) << boost::format("sensor distance set to %1% - %2%") % sensor->info().Min % sensor->info().Max;
    BOOST_TEST(sensor->info().Min);
    BOOST_TEST(sensor->info().Max);
}

BOOST_AUTO_TEST_CASE(Test_websocket_SetFov)
{
    BOOST_LOG_TRIVIAL(info) << "Start to test setFov.";
    BOOST_REQUIRE(sensor != nullptr);
    int x, y, w, h;
    x = 100, y = 100;
    w = 1440, h = 1080;
    sensor->fov(x, y, w, h);
    BOOST_LOG_TRIVIAL(info) << boost::format("sensor fov set to (%1% , %2%) , (%3% , %4%).") % sensor->info().X % sensor->info().Y
                % sensor->info().Width % sensor->info().Height;
    BOOST_TEST(sensor->info().X);
    BOOST_TEST(sensor->info().Y);
    BOOST_TEST(sensor->info().Width);
    BOOST_TEST(sensor->info().Height);
}

BOOST_AUTO_TEST_CASE(Test_websocket_SetCurrent)
{
    BOOST_LOG_TRIVIAL(info) << "Start to test setCurrent.";
    BOOST_REQUIRE(sensor != nullptr);

    int r, g, b;
    r = 110, g = 110, b = 110;
    sensor->current(r, g, b);
    BOOST_LOG_TRIVIAL(info) << boost::format("sensor current set to %1%, %2%, %3%") % (int)sensor->info().Red % (int)sensor->info().Green
                % (int)sensor->info().Blue;

    BOOST_TEST(sensor->info().Red);
    BOOST_TEST(sensor->info().Green);
    BOOST_TEST(sensor->info().Blue);
}

BOOST_AUTO_TEST_CASE(Test_websocket_SetLive)
{
    BOOST_LOG_TRIVIAL(info) << "Start to test setLive.";
    BOOST_REQUIRE(sensor != nullptr);

    int live = 20000;
    sensor->live(live);

    BOOST_LOG_TRIVIAL(info) << boost::format("sensor LiveExposure set to %1%") % sensor->info().LiveExposure;
    BOOST_TEST(sensor->info().LiveExposure);
}

BOOST_AUTO_TEST_CASE(Test_websocket_SetExposure)
{
    BOOST_LOG_TRIVIAL(info) << "Start to test setExposure.";
    BOOST_REQUIRE(sensor != nullptr);

    // 根据实际需要配置触发曝光时间和周期，单位为us
    int e, p;
    //std::cout << "请输入触发曝光，周期" << std::endl;
    //std::cin >> e >> p;
    e = 3000, p = 30000;
    sensor->exposure(e, p);
    BOOST_LOG_TRIVIAL(info) << boost::format("sensor exposure set to %1%, period %2%") % sensor->info().Exposure % sensor->info().Period;

    BOOST_TEST(sensor->info().Exposure);
    BOOST_TEST(sensor->info().Period);
}

BOOST_AUTO_TEST_CASE(Test_websocket_SetStyle)
{
    BOOST_LOG_TRIVIAL(info) << "Start to test setStyle.";
    BOOST_REQUIRE(sensor != nullptr);

    // 根据实际需要设置编码风格
    int plain , led , bit ;
    //std::cout << "bit: Pattern的位数（范围：1~8）" << std::endl;
    //std::cin >> plain >> led >> bit;
    /*
    std::cout << "请根据实际需要设置编码风格" << std::endl; //STYLE_GRAY = 3;	const int STYLE_BGR = 4;
    std::cout << "plain: 3--灰度图" << std::endl;
    std::cout << "       4--彩色图" << std::endl;
    std::cout << "led: 0--无颜色" << std::endl;
    std::cout << "     1--红色" << std::endl;
    std::cout << "     2--绿色" << std::endl;
    std::cout << "     3--黄色" << std::endl;
    std::cout << "     4--蓝色" << std::endl;
    std::cout << "     5--紫红色" << std::endl;
    std::cout << "     6--蓝绿色" << std::endl;
    std::cout << "     7--白色" << std::endl;
    */
    plain = 3, led = 4, bit = 8;
    sensor->style(plain, led, bit);
    BOOST_LOG_TRIVIAL(info) << boost::format("sensor style plain: %1%; led: %2%; bit:%3%")
        % sensor->info().PlainType % sensor->info().DisplayColor % sensor->info().DisplayBit;

    BOOST_TEST(sensor->info().PlainType);
    BOOST_TEST(sensor->info().DisplayColor);
    BOOST_TEST(sensor->info().DisplayBit);
}

BOOST_AUTO_TEST_CASE(Test_websocket_SetDecode)
{
    BOOST_LOG_TRIVIAL(info) << "Start to test setDecode.";
    //BOOST_REQUIRE(sensor != nullptr);

    /*
    DECODE_MF_HETERODYNE = 5;	// 多频外差
	const int DECODE_GRAYCODE = 6;		// 格雷码
	const int DECODE_GRAYCODE_PHASE = 7;	// 格雷码+相移
	const int DECODE_SPECKLE = 8;			// 散斑
    */
    int type;
    type = 5;
    //21-07-08: decoder(type = 6)有问题
    //sensor->decoder(type);
    //BOOST_LOG_TRIVIAL(info) << boost::format("sensor style decoder is %1%;") % sensor->info().DecodeType;

    //BOOST_TEST(sensor->info().DecodeType);
}

BOOST_AUTO_TEST_CASE(Test_websocket_SetCallback)
{
    BOOST_LOG_TRIVIAL(info) << "Start to test setCallback.";
    BOOST_REQUIRE(sensor != nullptr);

    //获取相机的实时图像
    // set sensor playback, grpc protcol is not support this feature
    sensor->onPlayback(&playback);
}

BOOST_AUTO_TEST_CASE(Test_websocket_SetCapture)
{
    BOOST_LOG_TRIVIAL(info) << "Start to test setCapture.";
    //BOOST_REQUIRE(sensor != nullptr);

    // 控制相机取图，如果需要做手眼标定，可以使用int capture(std::vector<cv::Mat>& images)接口获取相机图片
    if(0 != sensor->capture(images))
    {
        BOOST_LOG_TRIVIAL(error) << "sensor capture fail";
        //return -1;
    }
    BOOST_LOG_TRIVIAL(info) << "sensor capture sucess";

    BOOST_TEST(images.empty() == false);

}

BOOST_AUTO_TEST_CASE(Test_websocket_SetCompute)
{
    BOOST_LOG_TRIVIAL(info) << "Start to test setCompute.";
    BOOST_REQUIRE(sensor != nullptr);
    BOOST_REQUIRE(images.empty() == false);

    // 生成并获取彩色图和深度图
    BOOST_TEST(0 == sensor->compute(color, depth));

    BOOST_LOG_TRIVIAL(info) << boost::format("color image type: %1%, size %2%") % color.type() % color.size();
    BOOST_LOG_TRIVIAL(info) << boost::format("depth image type: %1%, size %2%") % depth.type() % depth.size();

    cv::imwrite("color.bmp", color);
    cv::imwrite("depth.tiff", depth);
    cv::imwrite("depth.png", depth);

    // 深度图可直接生成点云，以pcl为例：

    for (int i = 0; i < depth.rows; ++i)
    {
        for (int j = 0; j < depth.cols; ++j)
        {
            pcl::PointXYZRGB point;
            point.x = depth.at<cv::Vec3f>(i, j)[0];
            point.y = depth.at<cv::Vec3f>(i, j)[1];
            point.z = depth.at<cv::Vec3f>(i, j)[2];
            if (point.z <= 0)
                continue;

            if (color.type() == CV_8UC3)
            {
                point.b = color.at<cv::Vec3b>(i, j)[0];
                point.g = color.at<cv::Vec3b>(i, j)[1];
                point.r = color.at<cv::Vec3b>(i, j)[2];
            }
            else
            {
                point.b = point.g = point.r = color.at<uint8_t>(i, j);
            }

            cloud.emplace_back(point);
        }
    }

    if (cloud.size() > 0)
    {
        BOOST_LOG_TRIVIAL(info) << boost::format("get point cloud sucess, total %1% points") % cloud.size();
        pcl::PCDWriter writer;
        writer.writeBinaryCompressed("cloud.pcd", cloud);
    }
    else
        BOOST_LOG_TRIVIAL(error) << "point cloud is empty";
}

BOOST_AUTO_TEST_CASE(Test_websocket_Disconnected)
{
    BOOST_LOG_TRIVIAL(info) << "Start to test setStyle.";
    BOOST_REQUIRE(sensor != nullptr);

    //sensor->disconnect();

    //BOOST_TEST(sensor->disconnect());
}

max_stars_repo_name: MagicalBrain/My-note.

max_issues_repo_name: MagicalBrain/My-note.

max_forks_repo_name: MagicalBrain/My-note.


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

#include "topologybuilder.h"

#include <boost/make_shared.hpp>

#include <chemkit/atom.h>
#include <chemkit/bond.h>
#include <chemkit/foreach.h>
#include <chemkit/molecule.h>
#include <chemkit/atomtyper.h>
#include <chemkit/partialchargemodel.h>

#include "topology.h"

namespace chemkit {

namespace {

bool atomsWithinTwoBonds(const Atom *a, const Atom *b)
{
    foreach(const Atom *neighbor, a->neighbors()){
        if(neighbor == b){
            return true;
        }
        else if(neighbor->isBondedTo(b)){
            return true;
        }
    }

    return false;
}

} // end anonymous namespace

// === TopologyBuilderPrivate ============================================== //
class TopologyBuilderPrivate
{
public:
    std::string atomTyper;
    std::string partialChargeModel;
    boost::shared_ptr<Topology> topology;
};

// === TopologyBuilder ===================================================== //
/// \class TopologyBuilder topologybuilder.h chemkit/topologybuilder.h
/// \ingroup chemkit-md
/// \brief The TopologyBuilder class builds molecular dynamics
///        topologies.
///
/// For example, to create a topology suitable for use with the UFF
/// force field:
/// \code
/// // load molecule from file, formula, etc.
/// const Molecule *molecule = ...
///
/// // create topology builder object
/// TopologyBuilder builder;
///
/// // set options
/// builder.setAtomTyper("uff");
///
/// // add molecule
/// builder.addMolecule(molecule);
///
/// // get topology
/// boost::shared_ptr<Topology> = builder.topology();
/// \endcode

// --- Construction and Destruction ---------------------------------------- //
/// Creates a new topology builder.
TopologyBuilder::TopologyBuilder()
    : d(new TopologyBuilderPrivate)
{
    d->topology = boost::make_shared<Topology>();
}

/// Destroys the topology builder object.
TopologyBuilder::~TopologyBuilder()
{
    delete d;
}

// --- Properties ---------------------------------------------------------- //
/// Returns the current size of the topology.
size_t TopologyBuilder::size() const
{
    return d->topology->size();
}

/// Returns \c true if the current topology is empty.
bool TopologyBuilder::isEmpty() const
{
    return d->topology->isEmpty();
}

/// Sets the atom typer to \p atomTyper.
bool TopologyBuilder::setAtomTyper(const std::string &atomTyper)
{
    d->atomTyper = atomTyper;

    return true;
}

/// Sets the partial charge model to \p model.
bool TopologyBuilder::setPartialChargeModel(const std::string &model)
{
    d->partialChargeModel = model;

    return true;
}

// --- Topology ------------------------------------------------------------ //
/// Adds \p molecule to the topology.
void TopologyBuilder::addMolecule(const Molecule *molecule)
{
    // reference to the current topology
    boost::shared_ptr<Topology> &topology = d->topology;

    // create atom typer
    boost::scoped_ptr<AtomTyper> atomTyper(0);
    if(!d->atomTyper.empty()){
        atomTyper.reset(AtomTyper::create(d->atomTyper));
    }

    // create partial charge model
    boost::scoped_ptr<PartialChargeModel> chargeModel(0);
    if(!d->partialChargeModel.empty()){
        chargeModel.reset(PartialChargeModel::create(d->partialChargeModel));
    }

    // increase topology size to store the new molecule
    size_t initialSize = topology->size();
    topology->resize(initialSize + molecule->size());

    // set atom types
    if(atomTyper){
        atomTyper->setMolecule(molecule);

        foreach(const Atom *atom, molecule->atoms()){
            topology->setType(initialSize + atom->index(), atomTyper->type(atom));
        }
    }

    // set atom masses
    foreach(const Atom *atom, molecule->atoms()){
        topology->setMass(initialSize + atom->index(), atom->mass());
    }

    // set atom charges
    if(chargeModel){
        chargeModel->setMolecule(molecule);

        foreach(const Atom *atom, molecule->atoms()){
            topology->setCharge(initialSize + atom->index(), chargeModel->partialCharge(atom));
        }
    }
    else{
        foreach(const Atom *atom, molecule->atoms()){
            topology->setCharge(initialSize + atom->index(), atom->partialCharge());
        }
    }

    // add bonded interactions
    foreach(const Bond *bond, molecule->bonds()){
        topology->addBondedInteraction(initialSize + bond->atom1()->index(),
                                       initialSize + bond->atom2()->index());

        if(atomTyper){
            int type = atomTyper->bondedInteractionType(bond->atom1(), bond->atom2());
            if(type != 0){
                topology->setBondedInteractionType(bond->atom1()->index(),
                                                   bond->atom2()->index(),
                                                   type);
            }
        }
    }

    // add angle interactions
    foreach(const Atom *atom, molecule->atoms()){
        if(!atom->isTerminal()){
            std::vector<const Atom *> neighbors(atom->neighbors().begin(),
                                                atom->neighbors().end());

            for(size_t i = 0; i < neighbors.size(); i++){
                for(size_t j = i + 1; j < neighbors.size(); j++){
                    topology->addAngleInteraction(initialSize + neighbors[i]->index(),
                                                  initialSize + atom->index(),
                                                  initialSize + neighbors[j]->index());

                    if(atomTyper){
                        int type = atomTyper->angleInteractionType(neighbors[i], atom, neighbors[j]);
                        if(type != 0){
                            topology->setAngleInteractionType(initialSize + neighbors[i]->index(),
                                                              initialSize + atom->index(),
                                                              initialSize + neighbors[j]->index(),
                                                              type);
                        }
                    }
                }
            }
        }
    }

    // add torsion interactions
    std::vector<std::pair<const Atom *, const Atom *> > torsionPairs;
    foreach(const Bond *bond, molecule->bonds()){
        if(!bond->atom1()->isTerminal() && !bond->atom2()->isTerminal()){
            torsionPairs.push_back(std::make_pair(bond->atom1(), bond->atom2()));
        }
    }

    std::pair<const Atom *, const Atom *> torsionPair;
    foreach(torsionPair, torsionPairs){
        const Atom *b = torsionPair.first;
        const Atom *c = torsionPair.second;

        foreach(const Atom *a, b->neighbors()){
            if(a == c){
                continue;
            }

            foreach(const Atom *d, c->neighbors()){
                if(d == b || d == a){
                    continue;
                }

                topology->addTorsionInteraction(initialSize + a->index(),
                                                initialSize + b->index(),
                                                initialSize + c->index(),
                                                initialSize + d->index());

                if(atomTyper){
                    int type = atomTyper->torsionInteractionType(a, b, c, d);
                    if(type != 0){
                        topology->setTorsionInteractionType(initialSize + a->index(),
                                                            initialSize + b->index(),
                                                            initialSize + c->index(),
                                                            initialSize + d->index(),
                                                            type);
                    }
                }
            }
        }
    }

    // add improper torsion interactions
    foreach(const Atom *atom, molecule->atoms()){
        if(atom->neighborCount() == 3){
            topology->addImproperTorsionInteraction(initialSize + atom->neighbor(0)->index(),
                                                    initialSize + atom->index(),
                                                    initialSize + atom->neighbor(1)->index(),
                                                    initialSize + atom->neighbor(2)->index());
        }
    }

    // add nonbonded interactions
    std::vector<const Atom *> atoms(molecule->atoms().begin(), molecule->atoms().end());
    for(size_t i = 0; i < atoms.size(); i++){
        for(size_t j = i + 1; j < atoms.size(); j++){
            if(!atomsWithinTwoBonds(atoms[i], atoms[j])){
                topology->addNonbondedInteraction(initialSize + atoms[i]->index(),
                                                  initialSize + atoms[j]->index());
            }
        }
    }
}

/// Returns the constructed topology.
boost::shared_ptr<Topology> TopologyBuilder::topology() const
{
    return d->topology;
}

} // end chemkit namespace

max_stars_repo_name: quizzmaster/chemkit

max_issues_repo_name: soplwang/chemkit

max_forks_repo_name: soplwang/chemkit


text: #include <boost/function/function10.hpp>

max_stars_repo_name: miathedev/BoostForArduino

max_issues_repo_name: miathedev/BoostForArduino

max_forks_repo_name: miathedev/BoostForArduino


text:
/*
Copyright 2019 Glen Joseph Fernandes
(glenjofe@gmail.com)

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

#include <boost/type_traits/copy_cv.hpp>
#include <boost/type_traits/copy_reference.hpp>
#include <boost/type_traits/remove_reference.hpp>

namespace boost {

template<class T, class U>
struct copy_cv_ref {
    typedef typename copy_reference<typename copy_cv<T,
        typename remove_reference<U>::type >::type, U>::type type;
};

#if !defined(BOOST_NO_CXX11_TEMPLATE_ALIASES)
template<class T, class U>
using copy_cv_ref_t = typename copy_cv_ref<T, U>::type;
#endif

} /* boost */

#endif

max_stars_repo_name: kindlychung/mediasoup-sfu-cpp

max_issues_repo_name: kindlychung/mediasoup-sfu-cpp

max_forks_repo_name: kindlychung/mediasoup-sfu-cpp


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

#ifndef BOOST_URL_IMPL_FRAGMENT_BNF_IPP
#define BOOST_URL_IMPL_FRAGMENT_BNF_IPP

#include <boost/url/rfc/fragment_bnf.hpp>
#include <boost/url/bnf/parse.hpp>
#include <boost/url/rfc/char_sets.hpp>
#include <boost/url/rfc/pct_encoded_bnf.hpp>

namespace boost {
namespace urls {

bool
parse(
    char const*& it,
    char const* const end,
    error_code& ec,
    fragment_bnf const& t)
{
    using bnf::parse;
    return parse(it, end, ec,
        pct_encoded_bnf<
            masked_char_set<
                pchar_mask |
                slash_char_mask |
                question_char_mask>>{
        t.v});
}

} // urls
} // boost

#endif

ext: ipp

max_stars_repo_name: TankerHQ/url

max_issues_repo_name: TankerHQ/url

max_forks_repo_name: TankerHQ/url


text:
#define BOOST_TEST_DYN_LINK
#define BOOST_TEST_MODULE Test_SignalProcessing
#include <boost/test/unit_test.hpp>
#include "../SignalProcessing.hpp"

BOOST_AUTO_TEST_CASE(SanityCheck_DirectConvolution1) {
    std::vector<int> v1{1, 2, 3};
    std::vector<int> v2{1};
    std::vector<int> v = direct_conv(v1, v2);
    BOOST_REQUIRE(v.size() == v1.size() + v2.size() - 1);
    for (size_t i = 0; i < v.size(); i++) {
        BOOST_REQUIRE(v[i] == v1[i]);
    }
}

BOOST_AUTO_TEST_CASE(SanityCheck_DirectConvolution2) {
    //>>> np.convolve([1,-1,0,10, 3], [3, 9, -2]  ==> array([  3,   6, -11,  32,  99,   7,  -6])
    std::vector<int> v1{1, -1, 0, 10, 3};
    std::vector<int> v2{3, 9, -2};
    std::vector<int> desired_res{3, 6, -11, 32, 99, 7, -6};

    std::vector<int> v = direct_conv(v1, v2);
    BOOST_REQUIRE(desired_res.size() == v.size());
    for (size_t i = 0; i < v.size(); i++) {
        BOOST_REQUIRE(desired_res[i] == v[i]);
    }
}

max_stars_repo_name: sigurdstorve/OpenBCSim

max_issues_repo_name: rojsc/OpenBCSim

max_forks_repo_name: rojsc/OpenBCSim


text:
//==================================================================================================
/*!
  @file

  @copyright 2015 NumScale SAS
  @copyright 2015 J.T. Lapreste

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

#include <boost/simd/constant/mindenormal.hpp>
#include <boost/simd/constant/nan.hpp>
#include <boost/simd/constant/one.hpp>
#include <boost/simd/function/scalar/abs.hpp>
#include <boost/simd/function/scalar/bitwise_cast.hpp>
#include <boost/simd/function/scalar/is_eqz.hpp>
#include <boost/simd/function/scalar/is_invalid.hpp>
#include <boost/simd/function/scalar/min.hpp>
#include <boost/simd/function/scalar/prev.hpp>
#include <boost/dispatch/function/overload.hpp>
#include <boost/dispatch/meta/as_integer.hpp>
#include <boost/config.hpp>

namespace boost { namespace simd { namespace ext
{
  namespace bd = boost::dispatch;
 BOOST_DISPATCH_OVERLOAD ( ulp_
                         , (typename A0)
                         , bd::cpu_
                         , bd::scalar_< bd::arithmetic_<A0> >
                         )
 {
   BOOST_FORCEINLINE A0 operator() ( A0 const &) const BOOST_NOEXCEPT
   {
     return One<A0>();
   }
 };

  BOOST_DISPATCH_OVERLOAD ( ulp_
                          , (typename A0)
                          , bd::cpu_
                          , bd::scalar_< bd::floating_<A0> >
                          )
  {
    BOOST_FORCEINLINE A0 operator() ( A0 a0) const BOOST_NOEXCEPT
    {
      using i_t = bd::as_integer_t<A0,unsigned>;
      if (is_eqz(a0)) return Mindenormal<A0>();
      if (is_invalid(a0)) return Nan<A0>();
      const A0 x = boost::simd::abs(a0);
      i_t aa = bitwise_cast<i_t>(x);
      i_t bb = aa;
      --bb;
      ++aa;
      return boost::simd::min(x-bitwise_cast<A0>(bb), bitwise_cast<A0>(aa)-x);
    }
  };
} } }

#endif


text:
#include "easing/easing.hpp"
#include "interpolation/interpolation.hpp"
#include <boost/process.hpp>
#include <iostream>
#include <string>
#define FMT_HEADER_ONLY
#include <fmt/format.h>

static void plot(const std::string &plot_name,
                 const std::string &points_data_path,
                 const std::string &output_png_path, bool is_dynamic) {
  boost::process::opstream write;
  boost::filesystem::path command("/usr/local/bin/gnuplot");
  boost::process::child plot(command, boost::process::std_in = write);

  write << "set terminal png\n";
  write << fmt::format("unset key\n");
  write << fmt::format("set output \"{}\"\n", output_png_path);
  write << fmt::format("set xlabel \"{}\"\n", "axis-x");
  write << fmt::format("set ylabel \"{}\"\n", "axis-y");
  write << fmt::format("set xrange {}\n", "[0:1]");
  write << fmt::format("set yrange {}\n", is_dynamic ? "[-0.5:1.5]" : "[0:1]");
  write << fmt::format("plot \"{}\" with points pt 7 lc 1,", points_data_path);

  write.flush();
  write.pipe().close();
  plot.wait();
  std::cout << plot_name << " was done, exit code: " << plot.exit_code()
            << std::endl;
}

template <typename F>
static void
plot(const std::string &plot_name, const std::string &points_data_path,
     const std::string &output_png_path, F easing, bool is_dynamic = false) {
  std::vector<float> xs(101), ys(101);
  for (int i = 0; i <= 100; i++) {
    xs[i] = i * 0.01f;
    ys[i] = interpolation::lerp(0.0f, 1.0f, easing(xs[i]));
  }
  std::ofstream points_file(points_data_path);
  for (int i = 0; i <= 100; i++) {
    points_file << xs[i] << " " << ys[i] << "\n";
  }
  points_file.close();

  plot(plot_name, points_data_path, output_png_path, is_dynamic);
}

template <typename T>
static void plot(const std::string &type_name, bool is_dynamic = false) {
  plot(fmt::format("{} in plot", type_name),
       fmt::format("data/{}_in.dat", type_name),
       fmt::format("data/{}_in.png", type_name), T::in, is_dynamic);
  plot(fmt::format("{} out plot", type_name),
       fmt::format("data/{}_out.dat", type_name),
       fmt::format("data/{}_out.png", type_name), T::out, is_dynamic);
  plot(fmt::format("{} in-out plot", type_name),
       fmt::format("data/{}_inout.dat", type_name),
       fmt::format("data/{}_inout.png", type_name), T::inout, is_dynamic);
}

int main() {
  plot("linear plot", "data/linear.dat", "data/linear.png",
       easing::linear<float>);
  plot("ease in plot", "data/ease_in.dat", "data/ease_in.png",
       easing::ease_in<float>);
  plot("ease out plot", "data/ease_out.dat", "data/ease_out.png",
       easing::ease_out<float>);
  plot("ease inout plot", "data/ease_inout.dat", "data/ease_inout.png",
       easing::ease_inout<float>);

  plot<easing::ease<easing::sine<float>, float>>("sine");
  plot<easing::ease<easing::quad<float>, float>>("quad");
  plot<easing::ease<easing::cubic<float>, float>>("cubic");
  plot<easing::ease<easing::quart<float>, float>>("quart");
  plot<easing::ease<easing::quint<float>, float>>("quint");
  plot<easing::ease<easing::expo<float>, float>>("expo");
  plot<easing::ease<easing::circ<float>, float>>("circ");
  plot<easing::ease<easing::back<float>, float>>("back", true);
  plot<easing::ease<easing::elastic<float>, float>>("elastic", true);
  plot<easing::ease<easing::bounce<float>, float>>("bounce");
  return 0;
}

max_stars_repo_name: mnrn/game-memo

max_issues_repo_name: mnrn/game-memo

max_forks_repo_name: mnrn/game-memo


text:
/* ----------------------------------------------------------------------------

 * GTSAM Copyright 2010, Georgia Tech Research Corporation,
 * Atlanta, Georgia 30332-0415
 * All Rights Reserved
 * Authors: Frank Dellaert, et al. (see THANKS for the full author list)

 * See LICENSE for the license information

 * -------------------------------------------------------------------------- */

/**
 *  @file DiscreteConditional.cpp
 *  @date Feb 14, 2011
 *  @author Duy-Nguyen Ta
 *  @author Frank Dellaert
 */

#include <gtsam/discrete/DiscreteConditional.h>
#include <gtsam/discrete/Signature.h>
#include <gtsam/inference/Conditional-inst.h>
#include <gtsam/base/Testable.h>
#include <gtsam/base/debug.h>

#include <boost/make_shared.hpp>

#include <algorithm>
#include <random>
#include <stdexcept>
#include <string>
#include <vector>

using namespace std;

namespace gtsam {

// Instantiate base class
template class GTSAM_EXPORT Conditional<DecisionTreeFactor, DiscreteConditional> ;

/* ******************************************************************************** */
DiscreteConditional::DiscreteConditional(const size_t nrFrontals,
    const DecisionTreeFactor& f) :
    BaseFactor(f / (*f.sum(nrFrontals))), BaseConditional(nrFrontals) {
}

/* ******************************************************************************** */
DiscreteConditional::DiscreteConditional(const DecisionTreeFactor& joint,
    const DecisionTreeFactor& marginal) :
    BaseFactor(
        ISDEBUG("DiscreteConditional::COUNT") ? joint : joint / marginal), BaseConditional(
            joint.size()-marginal.size()) {
  if (ISDEBUG("DiscreteConditional::DiscreteConditional"))
    cout << (firstFrontalKey()) << endl; //TODO Print all keys
}

/* ******************************************************************************** */
DiscreteConditional::DiscreteConditional(const DecisionTreeFactor& joint,
    const DecisionTreeFactor& marginal, const Ordering& orderedKeys) :
    DiscreteConditional(joint, marginal) {
  keys_.clear();
  keys_.insert(keys_.end(), orderedKeys.begin(), orderedKeys.end());
}

/* ******************************************************************************** */
DiscreteConditional::DiscreteConditional(const Signature& signature)
    : BaseFactor(signature.discreteKeys(), signature.cpt()),
      BaseConditional(1) {}

/* ******************************************************************************** */
void DiscreteConditional::print(const string& s,
                                const KeyFormatter& formatter) const {
  cout << s << " P( ";
  for (const_iterator it = beginFrontals(); it != endFrontals(); ++it) {
    cout << formatter(*it) << " ";
  }
  if (nrParents()) {
    cout << "| ";
    for (const_iterator it = beginParents(); it != endParents(); ++it) {
      cout << formatter(*it) << " ";
    }
  }
  cout << ")";
  Potentials::print("");
  cout << endl;
}

/* ******************************************************************************** */
bool DiscreteConditional::equals(const DiscreteFactor& other,
    double tol) const {
  if (!dynamic_cast<const DecisionTreeFactor*>(&other))
    return false;
  else {
    const DecisionTreeFactor& f(
        static_cast<const DecisionTreeFactor&>(other));
    return DecisionTreeFactor::equals(f, tol);
  }
}

/* ******************************************************************************** */
static DiscreteConditional::ADT Choose(const DiscreteConditional& conditional,
                                       const DiscreteValues& parentsValues) {
  // Get the big decision tree with all the levels, and then go down the
  // branches based on the value of the parent variables.
  DiscreteConditional::ADT adt(conditional);
  size_t value;
  for (Key j : conditional.parents()) {
    try {
      value = parentsValues.at(j);
      adt = adt.choose(j, value);  // ADT keeps getting smaller.
    } catch (std::out_of_range&) {
      parentsValues.print("parentsValues: ");
      throw runtime_error("DiscreteConditional::choose: parent value missing");
    };
  }
  return adt;
}

/* ******************************************************************************** */
DecisionTreeFactor::shared_ptr DiscreteConditional::choose(
    const DiscreteValues& parentsValues) const {
  // Get the big decision tree with all the levels, and then go down the
  // branches based on the value of the parent variables.
  ADT adt(*this);
  size_t value;
  for (Key j : parents()) {
    try {
      value = parentsValues.at(j);
      adt = adt.choose(j, value);  // ADT keeps getting smaller.
    } catch (exception&) {
      parentsValues.print("parentsValues: ");
      throw runtime_error("DiscreteConditional::choose: parent value missing");
    };
  }

  // Convert ADT to factor.
  DiscreteKeys discreteKeys;
  for (Key j : frontals()) {
    discreteKeys.emplace_back(j, this->cardinality(j));
  }
  return boost::make_shared<DecisionTreeFactor>(discreteKeys, adt);
}

/* ******************************************************************************** */
DecisionTreeFactor::shared_ptr DiscreteConditional::likelihood(
    const DiscreteValues& frontalValues) const {
  // Get the big decision tree with all the levels, and then go down the
  // branches based on the value of the frontal variables.
  ADT adt(*this);
  size_t value;
  for (Key j : frontals()) {
    try {
      value = frontalValues.at(j);
      adt = adt.choose(j, value);  // ADT keeps getting smaller.
    } catch (exception&) {
      frontalValues.print("frontalValues: ");
      throw runtime_error("DiscreteConditional::choose: frontal value missing");
    };
  }

  // Convert ADT to factor.
  DiscreteKeys discreteKeys;
  for (Key j : parents()) {
    discreteKeys.emplace_back(j, this->cardinality(j));
  }
  return boost::make_shared<DecisionTreeFactor>(discreteKeys, adt);
}

/* ******************************************************************************** */
DecisionTreeFactor::shared_ptr DiscreteConditional::likelihood(
    size_t parent_value) const {
  if (nrFrontals() != 1)
    throw std::invalid_argument(
        "Single value likelihood can only be invoked on single-variable "
        "conditional");
  DiscreteValues values;
  values.emplace(keys_[0], parent_value);
  return likelihood(values);
}

/* ******************************************************************************** */
void DiscreteConditional::solveInPlace(DiscreteValues* values) const {
  // TODO: Abhijit asks: is this really the fastest way? He thinks it is.
  ADT pFS = Choose(*this, *values); // P(F|S=parentsValues)

  // Initialize
  DiscreteValues mpe;
  double maxP = 0;

  DiscreteKeys keys;
  for(Key idx: frontals()) {
    DiscreteKey dk(idx, cardinality(idx));
    keys & dk;
  }
  // Get all Possible Configurations
  const auto allPosbValues = cartesianProduct(keys);

  // Find the MPE
  for(const auto& frontalVals: allPosbValues) {
    double pValueS = pFS(frontalVals); // P(F=value|S=parentsValues)
    // Update MPE solution if better
    if (pValueS > maxP) {
      maxP = pValueS;
      mpe = frontalVals;
    }
  }

  //set values (inPlace) to mpe
  for(Key j: frontals()) {
    (*values)[j] = mpe[j];
  }
}

/* ******************************************************************************** */
void DiscreteConditional::sampleInPlace(DiscreteValues* values) const {
  assert(nrFrontals() == 1);
  Key j = (firstFrontalKey());
  size_t sampled = sample(*values); // Sample variable given parents
  (*values)[j] = sampled; // store result in partial solution
}

/* ******************************************************************************** */
size_t DiscreteConditional::solve(const DiscreteValues& parentsValues) const {

  // TODO: is this really the fastest way? I think it is.
  ADT pFS = Choose(*this, parentsValues); // P(F|S=parentsValues)

  // Then, find the max over all remaining
  // TODO, only works for one key now, seems horribly slow this way
  size_t mpe = 0;
  DiscreteValues frontals;
  double maxP = 0;
  assert(nrFrontals() == 1);
  Key j = (firstFrontalKey());
  for (size_t value = 0; value < cardinality(j); value++) {
    frontals[j] = value;
    double pValueS = pFS(frontals); // P(F=value|S=parentsValues)
    // Update MPE solution if better
    if (pValueS > maxP) {
      maxP = pValueS;
      mpe = value;
    }
  }
  return mpe;
}

/* ******************************************************************************** */
size_t DiscreteConditional::sample(const DiscreteValues& parentsValues) const {
  static mt19937 rng(2);  // random number generator

  // Get the correct conditional density
  ADT pFS = Choose(*this, parentsValues);  // P(F|S=parentsValues)

  // TODO(Duy): only works for one key now, seems horribly slow this way
  if (nrFrontals() != 1) {
    throw std::invalid_argument(
        "DiscreteConditional::sample can only be called on single variable "
        "conditionals");
  }
  Key key = firstFrontalKey();
  size_t nj = cardinality(key);
  vector<double> p(nj);
  DiscreteValues frontals;
  for (size_t value = 0; value < nj; value++) {
    frontals[key] = value;
    p[value] = pFS(frontals);  // P(F=value|S=parentsValues)
    if (p[value] == 1.0) {
      return value;  // shortcut exit
    }
  }
  std::discrete_distribution<size_t> distribution(p.begin(), p.end());
  return distribution(rng);
}

/* ******************************************************************************** */
size_t DiscreteConditional::sample(size_t parent_value) const {
  if (nrParents() != 1)
    throw std::invalid_argument(
        "Single value sample() can only be invoked on single-parent "
        "conditional");
  DiscreteValues values;
  values.emplace(keys_.back(), parent_value);
  return sample(values);
}

/* ************************************************************************* */
std::string DiscreteConditional::markdown(
    const KeyFormatter& keyFormatter) const {
  std::stringstream ss;

  // Print out signature.
  ss << " *P(";
  bool first = true;
  for (Key key : frontals()) {
    if (!first) ss << ",";
    ss << keyFormatter(key);
    first = false;
  }
  if (nrParents() == 0) {
   // We have no parents, call factor method.
    ss << ")*:\n" << std::endl;
    ss << DecisionTreeFactor::markdown(keyFormatter);
    return ss.str();
  }

  // We have parents, continue signature and do custom print.
  ss << "|";
  first = true;
  for (Key parent : parents()) {
    if (!first) ss << ",";
    ss << keyFormatter(parent);
    first = false;
  }
  ss << ")*:\n" << std::endl;

  // Print out header and construct argument for `cartesianProduct`.
  std::vector<std::pair<Key, size_t>> pairs;
  ss << "|";
  const_iterator it;
  for(Key parent: parents()) {
    ss << keyFormatter(parent) << "|";
    pairs.emplace_back(parent, cardinalities_.at(parent));
  }

  size_t n = 1;
  for(Key key: frontals()) {
    size_t k = cardinalities_.at(key);
    pairs.emplace_back(key, k);
    n *= k;
  }
  std::vector<std::pair<Key, size_t>> slatnorf(pairs.rbegin(),
                                               pairs.rend() - nrParents());
  const auto frontal_assignments = cartesianProduct(slatnorf);
  for (const auto& a : frontal_assignments) {
    for (it = beginFrontals(); it != endFrontals(); ++it) ss << a.at(*it);
    ss << "|";
  }
  ss << "\n";

  // Print out separator with alignment hints.
  ss << "|";
  for (size_t j = 0; j < nrParents() + n; j++) ss << ":-:|";
  ss << "\n";

  // Print out all rows.
  std::vector<std::pair<Key, size_t>> rpairs(pairs.rbegin(), pairs.rend());
  const auto assignments = cartesianProduct(rpairs);
  size_t count = 0;
  for (const auto& a : assignments) {
    if (count == 0) {
      ss << "|";
      for (it = beginParents(); it != endParents(); ++it)
        ss << a.at(*it) << "|";
    }
    ss << operator()(a) << "|";
    count = (count + 1) % n;
    if (count == 0) ss << "\n";
  }
  return ss.str();
}
/* ************************************************************************* */

}  // namespace gtsam


text:
//==================================================================================================
/*!
  @file

  @copyright 2016 NumScale SAS

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

#include <boost/simd/meta/hierarchy/simd.hpp>
#include <boost/dispatch/function/overload.hpp>
#include <boost/dispatch/adapted/common/pointer.hpp>
#include <boost/config.hpp>

namespace boost { namespace simd { namespace ext
{
  namespace bd = ::boost::dispatch;
  namespace bs = ::boost::simd;

  //------------------------------------------------------------------------------------------------
  // load from a pointer of integers
  BOOST_DISPATCH_OVERLOAD ( load_
                          , (typename Target, typename Pointer)
                          , bs::avx2_
                          , bd::pointer_<bd::scalar_<bd::integer_<Pointer>>,1u>
                          , bd::target_<bs::pack_<bd::integer_<Target>,bs::avx_>>
                          )
  {
    using target = typename Target::type;
    BOOST_FORCEINLINE target operator()(Pointer p, Target const&) const
    {
      return _mm256_loadu_si256((__m256i*)(p));
    }
  };
} } }

#endif


text:
#include <atomic>
#include <chrono>
#include <iostream>
#include <sstream>
#include <stdexcept>
#include <string>
#include <thread>

#include <boost/thread.hpp>
#include <clipper/config.hpp>
#include <clipper/constants.hpp>
#include <clipper/persistent_state.hpp>
#include <clipper/redis.hpp>
#include <clipper/logging.hpp>

namespace clipper {

std::string generate_redis_key(const StateKey& key) {
  std::stringstream key_stream;
  key_stream << std::get<0>(key);
  key_stream << ":";
  key_stream << std::get<1>(key);
  key_stream << ":";
  key_stream << std::get<2>(key);
  return key_stream.str();
}

StateDB::StateDB() {
  Config& conf = get_config();
  while (!redis_connection_.connect(conf.get_redis_address(),
                                    conf.get_redis_port())) {
    log_error(LOGGING_TAG_STATE_DB, "StateDB failed to connect to redis", "Retrying in 1 second...");
    std::this_thread::sleep_for(std::chrono::seconds(1));
  }
  if (!redis::send_cmd_no_reply<std::string>(
          redis_connection_, {"SELECT", std::to_string(REDIS_STATE_DB_NUM)})) {
    throw std::runtime_error("Could not select StateDB table from Redis");
  }
  log_info(LOGGING_TAG_STATE_DB, "Persistent state DB created");
}

StateDB::~StateDB() { redis_connection_.disconnect(); }

boost::optional<std::string> StateDB::get(const StateKey& key) {
  std::string redis_key = generate_redis_key(key);
  const std::vector<std::string> cmd_vec{"GET", redis_key};
  return redis::send_cmd_with_reply<std::string>(redis_connection_, cmd_vec);
}

bool StateDB::put(StateKey key, std::string value) {
  std::string redis_key = generate_redis_key(key);
  const std::vector<std::string> cmd_vec{"SET", redis_key, value};
  return redis::send_cmd_no_reply<std::string>(redis_connection_, cmd_vec);
}

bool StateDB::remove(StateKey key) {
  std::string redis_key = generate_redis_key(key);
  const std::vector<std::string> cmd_vec{"DEL", redis_key};
  return redis::send_cmd_no_reply<int>(redis_connection_, cmd_vec);
}

int StateDB::num_entries() {
  const std::vector<std::string> cmd_vec{"DBSIZE"};
  boost::optional<int> result =
      redis::send_cmd_with_reply<int>(redis_connection_, cmd_vec);
  if (result) {
    return *result;
  } else {
    return 0;
  }
}

}  // namespace clipper

max_stars_repo_name: jegonzal/clipper

max_issues_repo_name: jegonzal/clipper

max_forks_repo_name: jegonzal/clipper


text: #include <boost/math/special_functions/relative_difference.hpp>


text:
/**
 * Copyright (C) 2016 Turi
 * All rights reserved.
 *
 * This software may be modified and distributed under the terms
 * of the BSD license. See the LICENSE file for details.
 */

/**
 * Copyright (c) 2009 Carnegie Mellon University.
 *     All rights reserved.
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing,
 *  software distributed under the License is distributed on an "AS
 *  IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
 *  express or implied.  See the License for the specific language
 *  governing permissions and limitations under the License.
 *
 * For more about this software visit:
 *
 *      http://www.graphlab.ml.cmu.edu
 *
 */

#ifndef GRAPHLAB_SERIALIZABLE
#define GRAPHLAB_SERIALIZABLE
#include <boost/concept/assert.hpp>
#include <boost/concept/requires.hpp>
#include <boost/concept_check.hpp>
#include <sstream>
#include <serialization/serialize.hpp>
namespace graphlab {

  /**
   * \brief Concept checks if a type T is serializable.
   *
   * This is a concept checking class for boost::concept and can be
   * used to enforce that a type T is \ref sec_serializable, assignable and
   * default constructible.
   *
   * \tparam T The type to test for serializability.
   */
  template <typename T>
  class Serializable : boost::Assignable<T>, boost::DefaultConstructible<T> {
   public:
    BOOST_CONCEPT_USAGE(Serializable) {
      std::stringstream strm;
      oarchive oarc(strm);
      iarchive iarc(strm);
      const T const_t = T();
      T t = T();
      // A compiler error on these lines implies that your type is not
      // serializable.  See the documentaiton on how to make
      // serializable type.
      oarc << const_t;
      iarc >> t;
    }
  };

} // namespace graphlab
#endif

max_stars_repo_name: venkattgg/venkey

max_issues_repo_name: venkattgg/venkey

max_forks_repo_name: venkattgg/venkey