text:
// The contents of this file are in the public domain. See LICENSE_FOR_EXAMPLE_PROGRAMS.txt
/*
    This example shows how to run a CNN based vehicle detector using dlib.  The
    example loads a pretrained model and uses it to find the rear ends of cars in
    an image.  We will also visualize some of the detector's processing steps by
    plotting various intermediate images on the screen.  Viewing these can help
    you understand how the detector works.

    The model used by this example was trained by the dnn_mmod_train_find_cars_ex.cpp
    example.  Also, since this is a CNN, you really should use a GPU to get the
    best execution speed.  For instance, when run on a NVIDIA 1080ti, this detector
    runs at 98fps when run on the provided test image.  That's more than an order
    of magnitude faster than when run on the CPU.

    Users who are just learning about dlib's deep learning API should read
    the dnn_introduction_ex.cpp and dnn_introduction2_ex.cpp examples to learn
    how the API works.  For an introduction to the object detection method you
    should read dnn_mmod_ex.cpp.

    You can also see some videos of this vehicle detector running on YouTube:
        https://www.youtube.com/watch?v=4B3bzmxMAZU
        https://www.youtube.com/watch?v=bP2SUo5vSlc
*/

#include <iostream>
#include <dlib/dnn.h>
#include <dlib/image_io.h>
#include <dlib/gui_widgets.h>
#include <dlib/image_processing.h>

using namespace std;
using namespace dlib;

// The rear view vehicle detector network
template <long num_filters, typename SUBNET> using con5d = con<num_filters,5,5,2,2,SUBNET>;
template <long num_filters, typename SUBNET> using con5  = con<num_filters,5,5,1,1,SUBNET>;
template <typename SUBNET> using downsampler  = relu<affine<con5d<32, relu<affine<con5d<32, relu<affine<con5d<16,SUBNET>>>>>>>>>;
template <typename SUBNET> using rcon5  = relu<affine<con5<55,SUBNET>>>;
using net_type = loss_mmod<con<1,9,9,1,1,rcon5<rcon5<rcon5<downsampler<input_rgb_image_pyramid<pyramid_down<6>>>>>>>>;

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

int main() try
{
    net_type net;
    shape_predictor sp;
    // You can get this file from http://dlib.net/files/mmod_rear_end_vehicle_detector.dat.bz2
    // This network was produced by the dnn_mmod_train_find_cars_ex.cpp example program.
    // As you can see, the file also includes a separately trained shape_predictor.  To see
    // a generic example of how to train those refer to train_shape_predictor_ex.cpp.
    deserialize("mmod_rear_end_vehicle_detector.dat") >> net >> sp;

    matrix<rgb_pixel> img;
    load_image(img, "../mmod_cars_test_image.jpg");

    image_window win;
    win.set_image(img);

    // Run the detector on the image and show us the output.
    for (auto&& d : net(img))
    {
        // We use a shape_predictor to refine the exact shape and location of the detection
        // box.  This shape_predictor is trained to simply output the 4 corner points of
        // the box.  So all we do is make a rectangle that tightly contains those 4 points
        // and that rectangle is our refined detection position.
        auto fd = sp(img,d);
        rectangle rect;
        for (unsigned long j = 0; j < fd.num_parts(); ++j)
            rect += fd.part(j);
        win.add_overlay(rect, rgb_pixel(255,0,0));
    }

    cout << "Hit enter to view the intermediate processing steps" << endl;
    cin.get();

    // Now let's look at how the detector works.  The high level processing steps look like:
    //   1. Create an image pyramid and pack the pyramid into one big image.  We call this
    //      image the "tiled pyramid".
    //   2. Run the tiled pyramid image through the CNN.  The CNN outputs a new image where
    //      bright pixels in the output image indicate the presence of cars.
    //   3. Find pixels in the CNN's output image with a value > 0.  Those locations are your
    //      preliminary car detections.
    //   4. Perform non-maximum suppression on the preliminary detections to produce the
    //      final output.
    //
    // We will be plotting the images from steps 1 and 2 so you can visualize what's
    // happening.  For the CNN's output image, we will use the jet colormap so that "bright"
    // outputs, i.e. pixels with big values, appear in red and "dim" outputs appear as a
    // cold blue color.  To do this we pick a range of CNN output values for the color
    // mapping.  The specific values don't matter.  They are just selected to give a nice
    // looking output image.
    const float lower = -2.5;
    const float upper = 0.0;
    cout << "jet color mapping range:  lower="<< lower << "  upper="<< upper << endl;

    // Create a tiled pyramid image and display it on the screen.
    std::vector<rectangle> rects;
    matrix<rgb_pixel> tiled_img;
    // Get the type of pyramid the CNN used
    using pyramid_type = std::remove_reference<decltype(input_layer(net))>::type::pyramid_type;
    // And tell create_tiled_pyramid to create the pyramid using that pyramid type.
    create_tiled_pyramid<pyramid_type>(img, tiled_img, rects,
                                       input_layer(net).get_pyramid_padding(),
                                       input_layer(net).get_pyramid_outer_padding());
    image_window winpyr(tiled_img, "Tiled pyramid");

    // This CNN detector represents a sliding window detector with 3 sliding windows.  Each
    // of the 3 windows has a different aspect ratio, allowing it to find vehicles which
    // are either tall and skinny, squarish, or short and wide.  The aspect ratio of a
    // detection is determined by which channel in the output image triggers the detection.
    // Here we are just going to max pool the channels together to get one final image for
    // our display.  In this image, a pixel will be bright if any of the sliding window
    // detectors thinks there is a car at that location.
    cout << "Number of channels in final tensor image: " << net.subnet().get_output().k() << endl;
    matrix<float> network_output = image_plane(net.subnet().get_output(),0,0);
    for (long k = 1; k < net.subnet().get_output().k(); ++k)
        network_output = max_pointwise(network_output, image_plane(net.subnet().get_output(),0,k));
    // We will also upsample the CNN's output image.  The CNN we defined has an 8x
    // downsampling layer at the beginning. In the code below we are going to overlay this
    // CNN output image on top of the raw input image.  To make that look nice it helps to
    // upsample the CNN output image back to the same resolution as the input image, which
    // we do here.
    const double network_output_scale = img.nc()/(double)network_output.nc();
    resize_image(network_output_scale, network_output);

    // Display the network's output as a color image.
    image_window win_output(jet(network_output, upper, lower), "Output tensor from the network");

    // Also, overlay network_output on top of the tiled image pyramid and display it.
    for (long r = 0; r < tiled_img.nr(); ++r)
    {
        for (long c = 0; c < tiled_img.nc(); ++c)
        {
            dpoint tmp(c,r);
            tmp = input_tensor_to_output_tensor(net, tmp);
            tmp = point(network_output_scale*tmp);
            if (get_rect(network_output).contains(tmp))
            {
                float val = network_output(tmp.y(),tmp.x());
                // alpha blend the network output pixel with the RGB image to make our
                // overlay.
                rgb_alpha_pixel p;
                assign_pixel(p , colormap_jet(val,lower,upper));
                p.alpha = 120;
                assign_pixel(tiled_img(r,c), p);
            }
        }
    }
    // If you look at this image you can see that the vehicles have bright red blobs on
    // them.  That's the CNN saying "there is a car here!".  You will also notice there is
    // a certain scale at which it finds cars.  They have to be not too big or too small,
    // which is why we have an image pyramid.  The pyramid allows us to find cars of all
    // scales.
    image_window win_pyr_overlay(tiled_img, "Detection scores on image pyramid");

    // Finally, we can collapse the pyramid back into the original image.  The CNN doesn't
    // actually do this step, since it's enough to threshold the tiled pyramid image to get
    // the detections.  However, it makes a nice visualization and clearly indicates that
    // the detector is firing for all the cars.
    matrix<float> collapsed(img.nr(), img.nc());
    resizable_tensor input_tensor;
    input_layer(net).to_tensor(&img, &img+1, input_tensor);
    for (long r = 0; r < collapsed.nr(); ++r)
    {
        for (long c = 0; c < collapsed.nc(); ++c)
        {
            // Loop over a bunch of scale values and look up what part of network_output
            // corresponds to the point(c,r) in the original image, then take the max
            // detection score over all the scales and save it at pixel point(c,r).
            float max_score = -1e30;
            for (double scale = 1; scale > 0.2; scale *= 5.0/6.0)
            {
                // Map from input image coordinates to tiled pyramid coordinates.
                dpoint tmp = center(input_layer(net).image_space_to_tensor_space(input_tensor,scale, drectangle(dpoint(c,r))));
                // Now map from pyramid coordinates to network_output coordinates.
                tmp = point(network_output_scale*input_tensor_to_output_tensor(net, tmp));

                if (get_rect(network_output).contains(tmp))
                {
                    float val = network_output(tmp.y(),tmp.x());
                    if (val > max_score)
                        max_score = val;
                }
            }

            collapsed(r,c) = max_score;

            // Also blend the scores into the original input image so we can view it as
            // an overlay on the cars.
            rgb_alpha_pixel p;
            assign_pixel(p , colormap_jet(max_score,lower,upper));
            p.alpha = 120;
            assign_pixel(img(r,c), p);
        }
    }

    image_window win_collapsed(jet(collapsed, upper, lower), "Collapsed output tensor from the network");
    image_window win_img_and_sal(img, "Collapsed detection scores on raw image");

    cout << "Hit enter to end program" << endl;
    cin.get();
}
catch(image_load_error& e)
{
    cout << e.what() << endl;
    cout << "The test image is located in the examples folder.  So you should run this program from a sub folder so that the relative path is correct." << endl;
}
catch(serialization_error& e)
{
    cout << e.what() << endl;
    cout << "The correct model file can be obtained from: http://dlib.net/files/mmod_rear_end_vehicle_detector.dat.bz2" << endl;
}
catch(std::exception& e)
{
    cout << e.what() << endl;
}

max_stars_repo_name: andriy-gerasika/dlib


text:
/*
Copyright (c) 2019 - 2021 Advanced Micro Devices, Inc. All rights reserved.

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

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

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

#include <cassert>
#include <algorithm>
#include <commons.h>
#include "sequence_file_source_reader.h"
#include <boost/filesystem.hpp>

namespace filesys = boost::filesystem;

SequenceFileSourceReader::SequenceFileSourceReader() : _shuffle_time("shuffle_time", DBG_TIMING)
{
    _src_dir = nullptr;
    _sub_dir = nullptr;
    _entity = nullptr;
    _curr_file_idx = 0;
    _current_file_size = 0;
    _current_fPtr = nullptr;
    _loop = false;
    _sequence_id = 0;
    _shuffle = false;
    _sequence_count_all_shards = 0;
}

unsigned SequenceFileSourceReader::count_items()
{
    if (_loop)
        return _frame_names.size();
    int ret = ((int)_frame_names.size() - _read_counter);
    return ((ret < 0) ? 0 : ret);
}

Reader::Status SequenceFileSourceReader::initialize(ReaderConfig desc)
{
    auto ret = Reader::Status::OK;
    _sequence_id = 0;
    _folder_path = desc.path();
    _shard_id = desc.get_shard_id();
    _shard_count = desc.get_shard_count();
    _user_batch_count = desc.get_batch_size();
    _shuffle = desc.shuffle();
    _loop = desc.loop();
    _sequence_length = desc.get_sequence_length();
    _step = desc.get_frame_step();
    _stride = desc.get_frame_stride();
    _batch_count = _user_batch_count / _sequence_length;
    ret = subfolder_reading();
    if (ret != Reader::Status::OK)
        return ret;
    ret = get_sequences();

    // the following code is required to make every shard the same size:: required for multi-gpu training
    if (_shard_count > 1 && _batch_count > 1)
    {
        int _num_batches = _sequence_frame_names.size() / _batch_count;
        int max_batches_per_shard = (_sequence_count_all_shards + _shard_count - 1) / _shard_count;
        max_batches_per_shard = (max_batches_per_shard + _batch_count - 1) / _batch_count;
        if (_num_batches < max_batches_per_shard)
        {
            replicate_last_batch_to_pad_partial_shard();
        }
    }

    //shuffle dataset if set
    _shuffle_time.start();
    if (ret == Reader::Status::OK && _shuffle)
        std::random_shuffle(_sequence_frame_names.begin(), _sequence_frame_names.end());
    _shuffle_time.end();
    for(auto && seq : _sequence_frame_names)
    {
        _frame_names.insert(_frame_names.end(), seq.begin(), seq.end());
    }
    return ret;
}

void SequenceFileSourceReader::incremenet_read_ptr()
{
    _read_counter++;
    _curr_file_idx = (_curr_file_idx + 1) % _frame_names.size();
}

size_t SequenceFileSourceReader::open()
{
    auto file_path = _frame_names[_curr_file_idx]; // Get next file name
    incremenet_read_ptr();
    _last_id = file_path;
    auto last_slash_idx = _last_id.find_last_of("\\/");
    if (std::string::npos != last_slash_idx)
    {
        _last_id.erase(0, last_slash_idx + 1);
    }
    _current_fPtr = fopen(file_path.c_str(), "rb"); // Open the file,
    if (!_current_fPtr)                             // Check if it is ready for reading
        return 0;
    fseek(_current_fPtr, 0, SEEK_END);         // Take the file read pointer to the end
    _current_file_size = ftell(_current_fPtr); // Check how many bytes are there between and the current read pointer position (end of the file)
    if (_current_file_size == 0)
    {
        // If file is empty continue
        fclose(_current_fPtr);
        _current_fPtr = nullptr;
        return 0;
    }
    fseek(_current_fPtr, 0, SEEK_SET); // Take the file pointer back to the start
    return _current_file_size;
}

size_t SequenceFileSourceReader::read_data(unsigned char *buf, size_t read_size)
{
    if (!_current_fPtr)
        return 0;

    // Requested read size bigger than the file size? just read as many bytes as the file size
    read_size = (read_size > _current_file_size) ? _current_file_size : read_size;
    size_t actual_read_size = fread(buf, sizeof(unsigned char), read_size, _current_fPtr);
    return actual_read_size;
}

int SequenceFileSourceReader::close()
{
    return release();
}

SequenceFileSourceReader::~SequenceFileSourceReader()
{
    release();
}

int SequenceFileSourceReader::release()
{
    if (!_current_fPtr)
        return 0;
    fclose(_current_fPtr);
    _current_fPtr = nullptr;
    return 0;
}

void SequenceFileSourceReader::reset()
{
    _shuffle_time.start();
    if (_shuffle)
        std::random_shuffle(_sequence_frame_names.begin(), _sequence_frame_names.end());
    _shuffle_time.end();
    _read_counter = 0;
    _curr_file_idx = 0;
}

Reader::Status SequenceFileSourceReader::get_sequences()
{
    for (unsigned folder_idx = 0; folder_idx < _folder_file_names.size(); folder_idx++)
    {
        if (_folder_file_names[folder_idx].size() == 0)
        {
            WRN("\nFolder #" + TOSTR(folder_idx) + "does not have any files")
            continue;
        }
        if (_sequence_length > _folder_file_names[folder_idx].size())
        {
            THROW("Sequence length is not valid");
        }
        for (unsigned file_idx = 0; (file_idx + (_stride * (_sequence_length - 1))) < _folder_file_names[folder_idx].size(); file_idx += _step)
        {
            if (get_sequence_shard_id() != _shard_id)
            {
                _sequence_count_all_shards++;
                incremenet_sequence_id();
                continue;
            }
            _in_batch_read_count++;
            _in_batch_read_count = (_in_batch_read_count % _batch_count == 0) ? 0 : _in_batch_read_count;
            std::vector<std::string> temp_sequence;
            for (unsigned frame_count = 0, frame_idx = file_idx; (frame_count < _sequence_length); frame_count++, frame_idx += _stride)
            {
                temp_sequence.push_back(_folder_file_names[folder_idx][frame_idx]);
            }
            _last_sequence = temp_sequence;
            _sequence_frame_names.push_back(temp_sequence);
            _sequence_count_all_shards++;
            incremenet_sequence_id();
        }
    }
    if (_sequence_frame_names.empty())
        WRN("SequenceReader ShardID [" + TOSTR(_shard_id) + "] Did not load any file from " + _folder_path)
    if (_in_batch_read_count > 0 && _in_batch_read_count < _batch_count)
    {
        replicate_last_sequence_to_fill_last_shard();
        LOG("SequenceReader ShardID [" + TOSTR(_shard_id) + "] Replicated last sequence " + TOSTR((_batch_count - _in_batch_read_count)) + " times to fill the last batch")
    }
    return Reader::Status::OK;
}

Reader::Status SequenceFileSourceReader::subfolder_reading()
{
    if ((_sub_dir = opendir(_folder_path.c_str())) == nullptr)
        THROW("SequenceReader ShardID [" + TOSTR(_shard_id) + "] ERROR: Failed opening the directory at " + _folder_path);
    std::vector<std::string> entry_name_list;
    std::string _full_path = _folder_path;
    while ((_entity = readdir(_sub_dir)) != nullptr)
    {
        std::string entry_name(_entity->d_name);
        if (strcmp(_entity->d_name, ".") == 0 || strcmp(_entity->d_name, "..") == 0)
            continue;
        entry_name_list.push_back(entry_name);
    }
    closedir(_sub_dir);
    std::sort(entry_name_list.begin(), entry_name_list.end());
    auto ret = Reader::Status::OK;
    for (unsigned dir_count = 0; dir_count < entry_name_list.size(); ++dir_count)
    {
        std::string subfolder_path = _full_path + "/" + entry_name_list[dir_count];
        filesys::path pathObj(subfolder_path);
        if (filesys::exists(pathObj) && filesys::is_regular_file(pathObj))
        {
            // ignore files with extensions .tar, .zip, .7z, .mp4
            auto file_extension_idx = subfolder_path.find_last_of(".");
            if (file_extension_idx  != std::string::npos) {
                std::string file_extension = subfolder_path.substr(file_extension_idx+1);
                if ((file_extension == "tar") || (file_extension == "zip") || (file_extension == "7z") || (file_extension == "rar") || (file_extension == "mp4"))
                    continue;
            }
            _file_names.push_back(subfolder_path);
        }
        else if (filesys::exists(pathObj) && filesys::is_directory(pathObj))
        {
            _folder_path = subfolder_path;
            if (open_folder() != Reader::Status::OK)
                WRN("SequenceReader ShardID [" + TOSTR(_shard_id) + "] File reader cannot access the storage at " + _folder_path);
            _folder_file_names.push_back(_file_names);
            _file_names.clear();
        }
    }
    if (!_file_names.empty())
    {
        _folder_file_names.push_back(_file_names);
        _file_names.clear();
    }
    return ret;
}

void SequenceFileSourceReader::replicate_last_sequence_to_fill_last_shard()
{
    for (size_t i = _in_batch_read_count; i < _batch_count; i++)
        _sequence_frame_names.push_back(_last_sequence);
}

void SequenceFileSourceReader::replicate_last_batch_to_pad_partial_shard()
{
    if (_sequence_frame_names.size() >= _batch_count)
    {
        for (size_t i = 0; i < _batch_count; i++)
            _sequence_frame_names.push_back(_sequence_frame_names[i - _batch_count]);
    }
}

Reader::Status SequenceFileSourceReader::open_folder()
{
    if ((_src_dir = opendir(_folder_path.c_str())) == nullptr)
        THROW("SequenceReader ShardID [" + TOSTR(_shard_id) + "] ERROR: Failed opening the directory at " + _folder_path);
    while ((_entity = readdir(_src_dir)) != nullptr)
    {
        if (_entity->d_type != DT_REG)
            continue;

        std::string file_path = _folder_path;
        file_path.append("/");
        file_path.append(_entity->d_name);
        _file_names.push_back(file_path);
    }
    std::sort(_file_names.begin(), _file_names.end());
    closedir(_src_dir);
    return Reader::Status::OK;
}

size_t SequenceFileSourceReader::get_sequence_shard_id()
{
    if (_batch_count == 0 || _shard_count == 0)
        THROW("Shard (Batch) size cannot be set to 0")
    //return (_sequence_id / (_batch_count)) % _shard_count;
    return _sequence_id % _shard_count;
}

ext: cpp

max_stars_repo_name: hansely/MIVisionX

max_issues_repo_name: hansely/MIVisionX

max_forks_repo_name: hansely/MIVisionX


text:
#pragma once

#include <memory>

#include <boost/algorithm/string/classification.hpp>
#include <boost/range/algorithm_ext/erase.hpp>

#include "base_test.hpp"

#include "storage/chunk_encoder.hpp"
#include "storage/encoding_type.hpp"
#include "storage/table.hpp"
#include "utils/load_table.hpp"

namespace opossum {

// Base Class for tests that should be run with various encodings
class EncodingTest : public BaseTestWithParam<SegmentEncodingSpec> {
 public:
  std::shared_ptr<Table> load_table_with_encoding(const std::string& path,
                                                  ChunkOffset target_chunk_size = Chunk::DEFAULT_SIZE) {
    const auto table = load_table(path, target_chunk_size);

    auto chunk_encoding_spec = ChunkEncodingSpec{table->column_count(), EncodingType::Unencoded};

    for (auto column_id = ColumnID{0}; column_id < table->column_count(); ++column_id) {
      if (encoding_supports_data_type(GetParam().encoding_type, table->column_data_type(column_id))) {
        chunk_encoding_spec[column_id] = GetParam();
      }
    }

    ChunkEncoder::encode_all_chunks(table, chunk_encoding_spec);
    return table;
  }
};

void assert_chunk_encoding(const std::shared_ptr<Chunk>& chunk, const ChunkEncodingSpec& spec);

inline std::string all_segment_encoding_specs_formatter(
    const testing::TestParamInfo<EncodingTest::ParamType>& param_info) {
  std::stringstream stringstream;
  stringstream << param_info.param;
  auto string = stringstream.str();
  boost::remove_erase_if(string, boost::is_any_of("() -"));
  return string;
}

}  // namespace opossum

ext: hpp

max_stars_repo_name: youri-k/hyrise

max_issues_repo_name: youri-k/hyrise

max_forks_repo_name: youri-k/hyrise


text:
/*
 * NetworkDiscovery.cpp
 *
 *  Created on: Apr 21, 2016
 *      Author: James Hong
 */

#include "controller/NetworkDiscoveryClient.h"

#define BOOST_NETWORK_ENABLE_HTTPS

#include <boost/network/protocol/http/client.hpp>
#include <boost/network/protocol/http/request.hpp>
#include <exception>
#include <iostream>
#include <json/json.hpp>
#include <sstream>

#include "Beetle.h"
#include "Debug.h"
#include "controller/ControllerClient.h"

using json = nlohmann::json;

NetworkDiscoveryClient::NetworkDiscoveryClient(Beetle &beetle, std::shared_ptr<ControllerClient> client_) :
		beetle(beetle) {
	client = client_;
}

NetworkDiscoveryClient::~NetworkDiscoveryClient() {

}

bool NetworkDiscoveryClient::discoverDevices(std::list<discovery_result_t> &ret) {
	std::stringstream resource;
	resource << "network/discover/devices";
	return queryHelper(resource.str(), ret);
}

bool NetworkDiscoveryClient::discoverByUuid(UUID uuid, std::list<discovery_result_t> &ret, bool isService, device_t d) {
	std::stringstream resource;
	resource << "network/discover/" << ((isService) ? "service" : "char") << "/" << uuid.str();
	if (d != -1) {
		resource << "?gateway=" << beetle.name << "&" << "remote_id" << std::fixed << d;
	}
	return queryHelper(resource.str(), ret);
}

bool NetworkDiscoveryClient::findGatewayByName(std::string name, std::string &ip, int &port) {
	std::string url = client->getApiUrl("network/find/gateway/" + name);

	using namespace boost::network;
	http::client::request request(url);
	request << header("User-Agent", "linux");

	try {
		auto response = client->getClient()->get(request);
		if (response.status() == 200) {
			std::stringstream ss;
			ss << body(response);
			json j;
			j << ss;
			ip = j["ip"];
			port = j["port"];
			return true;
		} else {
			if (debug_controller) {
				std::stringstream ss;
				ss << "error : " << body(response);
				pwarn(ss.str());
			}
			return false;
		}
	} catch (std::exception &e) {
		pexcept(e);
		return false;
	}
}

bool NetworkDiscoveryClient::queryHelper(std::string resource, std::list<discovery_result_t> &ret) {
	std::string url = client->getApiUrl(resource);

	using namespace boost::network;
	http::client::request request(url);
	request << header("User-Agent", "linux");

	try {
		auto response = client->getClient()->get(request);
		if (response.status() == 200) {
			std::stringstream ss;
			ss << body(response);
			json j;
			j << ss;
			for (auto &it : j) {
				discovery_result_t result;
				result.name = it["device"]["name"];
				result.id = it["device"]["id"];
				result.gateway = it["gateway"]["name"];
				result.ip = it["gateway"]["ip"];
				result.port = it["gateway"]["port"];
				ret.push_back(result);
			}
			return true;
		} else {
			if (debug_controller) {
				std::stringstream ss;
				ss << "network discovery failed : " << body(response);
				pwarn(ss.str());
			}
			return false;
		}
	} catch (std::exception &e) {
		pexcept(e);
		return false;
	}
}

void NetworkDiscoveryClient::registerInterestInUuid(device_t id, UUID uuid, bool isService, std::function<void()> cb) {
	std::stringstream resource;
	resource << "network/registerInterest/" << ((isService) ? "service" : "char") << "/" << std::fixed << id
			<< "/" << uuid.str();

	std::string url = client->getApiUrl(resource.str());

	using namespace boost::network;
	http::client::request request(url);
	request << header("User-Agent", "linux");
	request << header(ControllerClient::SESSION_HEADER, client->getSessionToken());

	try {
		auto response = client->getClient()->post(request);
		if (response.status() != 200) {
			if (debug_controller) {
				std::stringstream ss;
				ss << "error registering interest: " << body(response);
				pdebug(ss.str());
			}
		}
	} catch (std::exception &e) {
		pexcept(e);
	}

	/*
	 * TODO: might want to wait
	 */
	cb();
}

max_stars_repo_name: helena-project/beetle

max_issues_repo_name: helena-project/beetle

max_forks_repo_name: helena-project/beetle


text:
/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */

#include "BLogger.h"
#include <boost/log/utility/setup/common_attributes.hpp>
#include <boost/filesystem.hpp>
#include <boost/filesystem/fstream.hpp>
#include <boost/regex.hpp>
#include <boost/smart_ptr/shared_ptr.hpp>
#include <boost/log/sinks/text_file_backend.hpp>
#include <boost/log/core/core.hpp>
#include <boost/log/attributes.hpp>
#include <boost/log/attributes/scoped_attribute.hpp>
#include <boost/lexical_cast.hpp>
#include <boost/thread.hpp>
#include <boost/log/sinks/text_file_backend.hpp>
#include <boost/log/utility/setup/file.hpp>
#include <boost/log/sources/severity_logger.hpp>
#include <boost/log/sources/record_ostream.hpp>
#include <boost/date_time/posix_time/posix_time.hpp>
#include <boost/log/support/date_time.hpp>

#include <ctime>

namespace org
{
	namespace apache
	{
		namespace plc4x
		{
			namespace cpp
			{
				namespace utils
				{
					namespace fs = boost::filesystem;
					namespace logging = boost::log;
					namespace attrs = boost::log::attributes;

					const char* BLogger::_pDefaultFileTitle = "plc4x";
					const char* BLogger::_pDefaultFileExtension = ".log";

					BLogger* BLogger::m_pInstance = NULL;

					BLogger* BLogger::Instance()
					{
						if (!m_pInstance)
						{
							m_pInstance = new BLogger;
						}

					return m_pInstance;
					}

					void BLogger::Release()
					{
						if (m_pInstance != NULL)
						{
							delete m_pInstance;
							m_pInstance = NULL;
						}

					return;
					}

					BLogger::BLogger() :
						_iMaxFileSize(10 * 1024 * 1024),			/* default max. filesize = 10 MB */
						_uiMaxNumberOfFiles(5),
						_strFileTitle(_pDefaultFileTitle),
						_strFileExtension(_pDefaultFileExtension),
						_logFilter (BoostLogger::trivial::severity >= BoostLogger::trivial::trace),
						_severityLevel(BoostLogger::trivial::trace),
						_uiFlushCounter(0)
					{
						_iSeverityLevelNumber=getNumberfromSeverityLevel(_severityLevel);

						_uiMaxFlushEntrys[0] = 20 ; // trace
						_uiMaxFlushEntrys[1] = 10 ; // debug
						_uiMaxFlushEntrys[2] = 20 ; // info // 0 -> write once
						_uiMaxFlushEntrys[3] = 0 ; // warning // 0 -> write once
						_uiMaxFlushEntrys[4] = 0 ; // error // 0 -> write once
						_uiMaxFlushEntrys[5] = 0 ; // fatal // 0 -> write once

                        Initialize();

                        return;
					}

					BLogger::~BLogger()
					{
						_uiFlushCounter = _uiMaxFlushEntrys[_iSeverityLevelNumber];
						FlushLog();

                        return;
					}

					void BLogger::setFileTitle(string strFileTitle)
					{
						if (strFileTitle != _strFileTitle)
						{
							_strFileTitle = strFileTitle;
                        }

                        return;
					}

					void BLogger::setFileExtension(string strFileExtension)
					{
						if (strFileExtension != _strFileExtension)
						{
							_strFileExtension = strFileExtension;
						}

                        return;
					}

					void BLogger::setMaxFileSize(int iMaxFileSize)
					{
						if (iMaxFileSize != _iMaxFileSize)
						{
							_iMaxFileSize = iMaxFileSize; /* MB */
						}

                        return;
					}

					void BLogger::setMaxNumberOfFiles(unsigned int uiMaxNumberOfFiles)
					{
						if (uiMaxNumberOfFiles != _uiMaxNumberOfFiles)
						{
							_uiMaxNumberOfFiles = uiMaxNumberOfFiles;
						}

                        return;
					}

					void BLogger::setSeverityLogLevel(severity_level severityLevel)
					{
						_severityLevel = severityLevel;

						_iSeverityLevelNumber = getNumberfromSeverityLevel(_severityLevel);

						_logFilter = BoostLogger::trivial::severity >= severityLevel;

						BoostLogger::core::get()->set_filter(_logFilter);

                        return;
					}

					void BLogger::clearLogDir()
					{
						const boost::regex logFilter( "(.*\\" + _strFileExtension + ")" );

						fs::path phPathFile(_strFileTitle);
						fs::path phDir = phPathFile.parent_path();
						if (fs::exists(phDir))
						{
							fs::directory_iterator it{phDir};
							while (it != boost::filesystem::directory_iterator{})
							{
								if (fs::is_regular_file(*it))
								{
									std::string logFilename = it->path().filename().string();

									if( boost::regex_match( logFilename, logFilter ) )
									{
										boost::filesystem::remove(it->path());
									}
								}
								it++;
							}
						}

                        return;
					}

					void BLogger::Initialize()
					{

						if (_strFileTitle.length() == 0) _strFileTitle = _pDefaultFileTitle;
						if (_strFileExtension.length() == 0) _strFileExtension = _pDefaultFileExtension;
						string strLogFileName = _strFileTitle + "_%m%d%Y_%H%M%S_%N" + _strFileExtension;

						boost::shared_ptr< logging::core > core = logging::core::get();
						core->flush();
						core->remove_all_sinks();
						core->add_global_attribute("TimeStamp", attrs::local_clock());

						boost::shared_ptr< sinks::text_file_backend > backend =
								boost::make_shared< sinks::text_file_backend >
						(
								keywords::file_name = strLogFileName.c_str(),
								keywords::rotation_size = _iMaxFileSize * 1024 * 1024,
								keywords::time_based_rotation = sinks::file::rotation_at_time_point(0, 0, 0)
						);

						fs::path phDirPath(strLogFileName);

						backend->set_file_collector(sinks::file::make_collector
								(
									keywords::target = phDirPath.parent_path().c_str(),
									keywords::max_size = (_uiMaxNumberOfFiles - 1)  * _iMaxFileSize * 1024 * 1024,
									keywords::min_free_space = 50 * 1024 * 1024
								));

						typedef sinks::synchronous_sink< sinks::text_file_backend > sink_t;
						boost::shared_ptr< sink_t > sink(new sink_t(backend));

						sink->set_formatter
							(
									expr::stream
									<< expr::format_date_time< boost::posix_time::ptime >("TimeStamp", "[%d.%m. %H:%M:%S.%f] ")
									<< " <" << BoostLogger::trivial::severity
									<< "> : " << expr::message
							);

						core->add_sink(sink);

                        return;
					}

					void  BLogger::Log(const char* pMessage, severity_level logLevel /*= info*/)
					{
						try
						{
							if (isLog(logLevel))
							{
								_mtxLock.lock();

								BOOST_LOG_SEV(_lg, severity_level::info) << "ThreadID 0x" << boost::this_thread::get_id() << " " << pMessage;

								if(logLevel == severity_level::fatal)
									ForceFlushLog();
								else
									FlushLog();

								_mtxLock.unlock();
							}
						}
						catch(...)
						{
							_mtxLock.unlock();
						}

                        return;
					}

					void  BLogger::Log(string strMessage, severity_level logLevel /* = info */)
					{
						try
						{
							if (isLog(logLevel))
							{
								_mtxLock.lock();

								BOOST_LOG_SEV(_lg, logLevel) << "ThreadID 0x" << boost::this_thread::get_id() << " " << strMessage;

								if(logLevel == severity_level::fatal)
									ForceFlushLog();
								else
									FlushLog();

								_mtxLock.unlock();
							}
						}
						catch(...)
						{
							_mtxLock.unlock();
						}

                        return;
					}

					void  BLogger::LogBool(bool b, severity_level logLevel /*= info*/)
					{

						try
						{
							if (isLog(logLevel))
							{
								_mtxLock.lock();

								string strBoolMessage = b ? _strTrueMessage : _strFalseMessage;
								BOOST_LOG_SEV(_lg, logLevel) << "ThreadID 0x" << boost::this_thread::get_id() << " " << strBoolMessage;

								if(logLevel == severity_level::fatal)
									ForceFlushLog();
								else
									FlushLog();

								_mtxLock.unlock();
							}
						}
						catch(...)
						{
							_mtxLock.unlock();
						}

                        return;
					}

					void  BLogger::LogBool(string strMessage, bool b, severity_level logLevel /*= info*/)
					{
						try
						{
							if (isLog(logLevel))
							{
								_mtxLock.lock();

								string strBoolMessage = b ? _strTrueMessage : _strFalseMessage;
								BOOST_LOG_SEV(_lg, logLevel) << "ThreadID 0x" << boost::this_thread::get_id() << " " << strMessage << ' ' << strBoolMessage;

								if(logLevel == severity_level::fatal)
									ForceFlushLog();
								else
									FlushLog();

								_mtxLock.unlock();
							}
						}
						catch(...)
						{
							_mtxLock.unlock();
						}

                        return;
					}

					void BLogger::LogHexDump(unsigned char* pBinaryData, unsigned int uiNumBytes, const char* pDumpPrefix /*= NULL*/, severity_level logLevel /*= info*/)
					{
						try
						{
							if (isLog(logLevel))
							{
								_mtxLock.lock();

								DatDmp dump;
								dump.setLeadingNewLine(true);
								dump.setPrefix(pDumpPrefix);
								string strDumpMessage = dump.Show(pBinaryData, uiNumBytes);
								BOOST_LOG_SEV(_lg, logLevel) << "ThreadID 0x" << boost::this_thread::get_id() << " " << strDumpMessage;

                                if (logLevel == severity_level::fatal)
                                {
                                    ForceFlushLog();
                                }
                                else
                                {
                                    FlushLog();
                                }

								_mtxLock.unlock();
							}
						}
						catch(...)
						{
							_mtxLock.unlock();
						}

                        return;
					}

					void BLogger::FlushLog(void)
					{
						if(_uiFlushCounter >= _uiMaxFlushEntrys[_iSeverityLevelNumber])
						{
							BOOST_LOG_SEV(_lg, boost::log::trivial::severity_level::info) << "ThreadID 0x" << boost::this_thread::get_id() << " Flush LogEntries";
							logging::core::get()->flush();
							_uiFlushCounter = 0;
						}
						else
						{
							_uiFlushCounter++;
						}

                        return;
					}

					void BLogger::ForceFlushLog(void)
					{
						unsigned int ui = _uiMaxFlushEntrys[_iSeverityLevelNumber];
						_uiMaxFlushEntrys[_iSeverityLevelNumber] = 0;
						FlushLog();
						_uiMaxFlushEntrys[_iSeverityLevelNumber] = ui;

                        return;
					}

					void BLogger::setSeverityLogLevelNumber(int iSeverityLevelNumber)
					{

						_iSeverityLevelNumber = iSeverityLevelNumber;

						_severityLevel = getSeverityLevelfromNumber(_iSeverityLevelNumber);

						setSeverityLogLevel(_severityLevel);

                        return;
					}

					bool BLogger::isLog(severity_level logLevel)
					{
						bool bResult = false;

						try
						{
							int ilogLevel = getNumberfromSeverityLevel(logLevel);

							if (_iSeverityLevelNumber <= ilogLevel)
							{
								bResult = true;
							}
						}
						catch(...)
						{
						}

						return bResult;
					}

					severity_level BLogger::getSeverityLevelfromNumber(int iSeverityLevelNumber)
					{
						severity_level logLevel = boost::log::trivial::severity_level::trace;

						switch (iSeverityLevelNumber)
						{
							case 0: logLevel = boost::log::trivial::severity_level::trace; break;
							case 1: logLevel = boost::log::trivial::severity_level::debug; break;
							case 2: logLevel = boost::log::trivial::severity_level::info; break;
							case 3: logLevel = boost::log::trivial::severity_level::warning; break;
							case 4: logLevel = boost::log::trivial::severity_level::error; break;
							case 5: logLevel = boost::log::trivial::severity_level::fatal; break;
							default: logLevel = boost::log::trivial::severity_level::trace; break;
						}

						return logLevel;
					}

					int BLogger::getNumberfromSeverityLevel(severity_level severityLevel)
					{
						int iSeverityLevelNumber = 0;

						switch (severityLevel)
						{
							case boost::log::trivial::severity_level::trace: iSeverityLevelNumber = 0; break;
							case boost::log::trivial::severity_level::debug: iSeverityLevelNumber = 1; break;
							case boost::log::trivial::severity_level::info: iSeverityLevelNumber = 2; break;
							case boost::log::trivial::severity_level::warning: iSeverityLevelNumber = 3; break;
							case boost::log::trivial::severity_level::error: iSeverityLevelNumber = 4; break;
							case boost::log::trivial::severity_level::fatal: iSeverityLevelNumber = 5; break;
						}

						return iSeverityLevelNumber;
					}
				}
			}
		}
	}
}


text:
/**
* This file is part of ORB-SLAM3
*
* Copyright (C) 2017-2021 Carlos Campos, Richard Elvira, Juan J. Gómez Rodríguez, José M.M. Montiel and Juan D. Tardós, University of Zaragoza.
* Copyright (C) 2014-2016 Raúl Mur-Artal, José M.M. Montiel and Juan D. Tardós, University of Zaragoza.
*
* ORB-SLAM3 is free software: you can redistribute it and/or modify it under the terms of the GNU General Public
* License as published by the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* ORB-SLAM3 is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even
* the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along with ORB-SLAM3.
* If not, see <http://www.gnu.org/licenses/>.
*/

#include "Pinhole.h"

#include <boost/serialization/export.hpp>

//BOOST_CLASS_EXPORT_IMPLEMENT(ORB_SLAM3::Pinhole)

namespace ORB_SLAM3 {
//BOOST_CLASS_EXPORT_GUID(Pinhole, "Pinhole")

    long unsigned int GeometricCamera::nNextId=0;

    cv::Point2f Pinhole::project(const cv::Point3f &p3D) {
        return cv::Point2f(mvParameters[0] * p3D.x / p3D.z + mvParameters[2],
                           mvParameters[1] * p3D.y / p3D.z + mvParameters[3]);
    }

    Eigen::Vector2d Pinhole::project(const Eigen::Vector3d &v3D) {
        Eigen::Vector2d res;
        res[0] = mvParameters[0] * v3D[0] / v3D[2] + mvParameters[2];
        res[1] = mvParameters[1] * v3D[1] / v3D[2] + mvParameters[3];

        return res;
    }

    Eigen::Vector2f Pinhole::project(const Eigen::Vector3f &v3D) {
        Eigen::Vector2f res;
        res[0] = mvParameters[0] * v3D[0] / v3D[2] + mvParameters[2];
        res[1] = mvParameters[1] * v3D[1] / v3D[2] + mvParameters[3];

        return res;
    }

    Eigen::Vector2f Pinhole::projectMat(const cv::Point3f &p3D) {
        cv::Point2f point = this->project(p3D);
        return Eigen::Vector2f(point.x, point.y);
    }

    float Pinhole::uncertainty2(const Eigen::Matrix<double,2,1> &p2D)
    {
        return 1.0;
    }

    Eigen::Vector3f Pinhole::unprojectEig(const cv::Point2f &p2D) {
        return Eigen::Vector3f((p2D.x - mvParameters[2]) / mvParameters[0], (p2D.y - mvParameters[3]) / mvParameters[1],
                           1.f);
    }

    cv::Point3f Pinhole::unproject(const cv::Point2f &p2D) {
        return cv::Point3f((p2D.x - mvParameters[2]) / mvParameters[0], (p2D.y - mvParameters[3]) / mvParameters[1],
                           1.f);
    }

    Eigen::Matrix<double, 2, 3> Pinhole::projectJac(const Eigen::Vector3d &v3D) {
        Eigen::Matrix<double, 2, 3> Jac;
        Jac(0, 0) = mvParameters[0] / v3D[2];
        Jac(0, 1) = 0.f;
        Jac(0, 2) = -mvParameters[0] * v3D[0] / (v3D[2] * v3D[2]);
        Jac(1, 0) = 0.f;
        Jac(1, 1) = mvParameters[1] / v3D[2];
        Jac(1, 2) = -mvParameters[1] * v3D[1] / (v3D[2] * v3D[2]);

        return Jac;
    }

    bool Pinhole::ReconstructWithTwoViews(const std::vector<cv::KeyPoint>& vKeys1, const std::vector<cv::KeyPoint>& vKeys2, const std::vector<int> &vMatches12,
                                 Sophus::SE3f &T21, std::vector<cv::Point3f> &vP3D, std::vector<bool> &vbTriangulated){
        if(!tvr){
            Eigen::Matrix3f K = this->toK_();
            tvr = new TwoViewReconstruction(K);
        }

        return tvr->Reconstruct(vKeys1,vKeys2,vMatches12,T21,vP3D,vbTriangulated);
    }

    cv::Mat Pinhole::toK() {
        cv::Mat K = (cv::Mat_<float>(3, 3)
                << mvParameters[0], 0.f, mvParameters[2], 0.f, mvParameters[1], mvParameters[3], 0.f, 0.f, 1.f);
        return K;
    }

    Eigen::Matrix3f Pinhole::toK_() {
        Eigen::Matrix3f K;
        K << mvParameters[0], 0.f, mvParameters[2], 0.f, mvParameters[1], mvParameters[3], 0.f, 0.f, 1.f;
        return K;
    }

    bool Pinhole::epipolarConstrain(GeometricCamera* pCamera2,  const cv::KeyPoint &kp1, const cv::KeyPoint &kp2, const Eigen::Matrix3f& R12, const Eigen::Vector3f& t12, const float sigmaLevel, const float unc) {
        //Compute Fundamental Matrix
        Eigen::Matrix3f t12x = Sophus::SO3f::hat(t12);
        Eigen::Matrix3f K1 = this->toK_();
        Eigen::Matrix3f K2 = pCamera2->toK_();
        Eigen::Matrix3f F12 = K1.transpose().inverse() * t12x * R12 * K2.inverse();

        // Epipolar line in second image l = x1'F12 = [a b c]
        const float a = kp1.pt.x*F12(0,0)+kp1.pt.y*F12(1,0)+F12(2,0);
        const float b = kp1.pt.x*F12(0,1)+kp1.pt.y*F12(1,1)+F12(2,1);
        const float c = kp1.pt.x*F12(0,2)+kp1.pt.y*F12(1,2)+F12(2,2);

        const float num = a*kp2.pt.x+b*kp2.pt.y+c;

        const float den = a*a+b*b;

        if(den==0)
            return false;

        const float dsqr = num*num/den;

        return dsqr<3.84*unc;
    }

    std::ostream & operator<<(std::ostream &os, const Pinhole &ph) {
        os << ph.mvParameters[0] << " " << ph.mvParameters[1] << " " << ph.mvParameters[2] << " " << ph.mvParameters[3];
        return os;
    }

    std::istream & operator>>(std::istream &is, Pinhole &ph) {
        float nextParam;
        for(size_t i = 0; i < 4; i++){
            assert(is.good());  //Make sure the input stream is good
            is >> nextParam;
            ph.mvParameters[i] = nextParam;

        }
        return is;
    }

    bool Pinhole::IsEqual(GeometricCamera* pCam)
    {
        if(pCam->GetType() != GeometricCamera::CAM_PINHOLE)
            return false;

        Pinhole* pPinholeCam = (Pinhole*) pCam;

        if(size() != pPinholeCam->size())
            return false;

        bool is_same_camera = true;
        for(size_t i=0; i<size(); ++i)
        {
            if(abs(mvParameters[i] - pPinholeCam->getParameter(i)) > 1e-6)
            {
                is_same_camera = false;
                break;
            }
        }
        return is_same_camera;
    }
}

max_stars_repo_name: robin-shaun/xtdrone

max_issues_repo_name: robin-shaun/xtdrone

max_forks_repo_name: robin-shaun/xtdrone


text:
#include <math.h>
#include <limits.h>
#include "defines.h"
#include <flann/mpi/matrix.h>
#include <algorithm>
#include <vector>
#include <map>
#include <matio.h>
#include "ros/ros.h"
#include <nav_msgs/GridCells.h>
#include <boost/geometry.hpp>
#include <boost/geometry/geometries/point_xy.hpp>
#include <boost/geometry/geometries/polygon.hpp>

#define INF 1000000.0

using namespace std;
using namespace __gnu_cxx;
using namespace flann;

typedef boost::geometry::model::d2::point_xy<double> point_type;
typedef boost::geometry::model::polygon<point_type> polygon_type;

int xf, yf, fif;

extern const float mapResolution;
extern const int node_dist;

void publishVisitedNodes(nav_msgs::GridCells gCells);

class Vector : public vector<int>
{
public:
    //operator size_t() const { return (*this).size(); };
    operator size_t() const { return (*this)[0]*1600 + (*this)[1]*16 + (*this)[2]; };
};

// zamjena mjesta elemenata na indexima i,j u vektoru
void swap(int i, int j, vector<pair<Vector, double> > *v, map<Vector, int> *h)
{
    pair<Vector, double> tmp;
    tmp = (*v)[i];
    (*v)[i] = (*v)[j];
    (*v)[j] = tmp;

    (*h)[(*v)[i].first] = i;
    (*h)[(*v)[j].first] = j;
}

// podizanje elementa na odgovarajući nivo u binarnom stablu
void bubble_up(int index, vector<pair<Vector, double> > *v, map<Vector, int> *h)
{
    int new_ind;

    while (index > 0)
    {
        new_ind = (index - 1)/2;

        if ((*v)[index].second < (*v)[new_ind].second)
        {
            swap(index, new_ind, v, h);
            index = new_ind;
        }
        else
        {
            break;
        }
    }
}

// spuštanje elementa na odgovarajući nivo u binarnom stablu
void bubble_down(int index, vector<pair<Vector, double> > *v, map<Vector, int> *h)
{
    int size = v->size();
    int new_ind;

    while (true)
    {
        if (2 * index + 2 >= size)
        {
            if (2 * index + 1 >= size)
            {
                break;
            }
            else
            {
                new_ind = 2 * index + 1;
            }
        }
        else
        {
            if ((*v)[2 * index + 1].second < (*v)[2 * index + 2].second)
            {
                new_ind = 2 * index + 1;
            }
            else
            {
                new_ind = 2 * index + 2;
            }
        }

        if ((*v)[index].second > (*v)[new_ind].second)
        {
            swap(index, new_ind, v, h);
            index = new_ind;
        }
        else
        {
            break;
        }
    }
}

// provjera izvedivosti i određivanje cijene segmenta
// ako je segment izvediv vraća se njegova cijena, u suprotnom se vraća vrijednost INF
double cost(int x, int y, int ei, int ej, vector<vector<pair<int, int> > > *cm, const vector<vector<short> >& map, vector<pair<vector<int>, double> > *g)
{
    double rez = 0.0;
    int m, n, mapWidth, mapHeight;
    double h = 0;

    mapWidth = map.size();

    if(mapWidth > 0)
        mapHeight = map[0].size();
    else return INF;

    // ***********************************************************************
    // ************* PROVJERA KOLIZIJE IZMEĐU VOZILA I PREPREKA  *************
    // ***********************************************************************

    for (unsigned int i = 0; i < cm[ei][ej].size(); i++)
    {
      m = node_dist * x + cm[ei][ej][i].first;
      n = node_dist * y + cm[ei][ej][i].second;

      // ako se bilo koja od čelija koju vozilo okupira tijekom izvođenja segmenta putanje nalazi
      // izvan granica karte, vraća se vrijednost 100000
      if (m < 0 || n < 0 || m > (mapWidth - 1) || n > (mapHeight - 1))
      {
        return INF;
      }
      else
      {
        if (map[m][n] < 0)  // ako čelija zahvaća prepreku vraća se vrijednost 100000
          return INF;
        else
          rez += map[m][n];
      }
    }
    // **********************************************************************

    int vx = x + g[ei][ej].first[0];
    int vy = y + g[ei][ej].first[1];

    int dx = xf - vx;
    int dy = yf - vy;

    h = sqrt(dx * dx + dy * dy);    // heuristična komponenta cijene
    //fprintf(stderr, "xf: %d yf: %d vx: %d vy: %d h: %f g: %f\n", xf, yf, vx, vy, h, g[ei][ej].second);

    return (g[ei][ej].second + h);  // ako sve čelije segmenta putanje leže u slobodnom prostoru karte, vraća se cijena segmenta
}

// graph search algoritm (Dijkstra + A*)
void graphSearch(matvar_t * varVars, matvar_t * varCost, const vector<vector<short> >& vMap, int start[], int finish[], vector<int> wrX, vector<int> wrY, double** M, int sizeM[], int** veh_orientations)
{
    // varVars -> sadrži informacije o latici; za svaku početnu orijentaciju sadrži koord. susjednih čvorova, konačne orijentacije i cijene pripadajućih segmenta
    // varCost -> koordinate svih čelija kroz koje vozilo prolazi prilikom gibanja pojedinim segmentom u latici

    vector<int> wrongx;
    vector<int> wrongy;

    // početne koordinate i orijentacija vozila
    int xs =  start[0];
    int ys =  start[1];
    int fis = start[2];

    xf = finish[0];
    yf = finish[1];
    fif = finish[2];

    //publishanje posjećenih čvorova (za prikaz u RViz-u)
    geometry_msgs::Point a;
    nav_msgs::GridCells gCells;
    gCells.header.frame_id = "/Alfa/map";
    gCells.cell_width = mapResolution;
    gCells.cell_height = mapResolution;
    gCells.cells.clear();

    map<Vector, int> hm;
    map<Vector, pair<int, int> > hm_sol;

    int m, n, mc, nc;
    double *data_in, *data_out, *cell_in, *map_in;

    vector<pair<vector<int>, double> > graph[16];
    vector<vector<pair<int, int> > > cost_map[16];

    vector<int> tmp;
    vector<pair<int, int> > vptmp;
    double sf;

    m = varVars->dims[0];
    n = varVars->dims[1];

    data_in = (double*)varVars->data;

    // petlja po svim segmentima u latici, počevši od segmenata s početnom orijentacijom 0
    for (int i = 0; i < m; i++)
    {
        tmp.clear();
        tmp.push_back((int)data_in[m + i]);     // x - koordinata susjednog čvora
        tmp.push_back((int)data_in[2*m + i]);   // y - koordinata susjednog čvora
        tmp.push_back((int)data_in[3*m + i]);   // konačna orijentacija u susjednom čvoru
        sf = data_in[4*m + i];                  // cijena (duljina pripadajućeg segmenta)

        // indexi elemenata vektora "graph" predstavljaju početne orijentacije (0-15)
        // svaki element vektora "graph" sadrži informacije o svim
        // susjednim čvorovima u koje se može doći s dotičnom početnom orijentacijom
        // informacije o susjednim čvorovima sadržane su u parovima oblika:
        // (x-y koordinate susjednog čvora + konačna orijentacija, cijena pripadajućeg segmenta)
        graph[(int)data_in[i]].push_back(make_pair(tmp, sf));

        matvar_t* matvar = Mat_VarGetCell(varCost, i);
        mc = matvar->dims[0];
        nc = matvar->dims[1];
        cell_in = (double*)matvar->data;

        vptmp.clear();
        for (int j = 0; j < nc; j++)
        {
            vptmp.push_back(make_pair((int)cell_in[2*j], (int)cell_in[2*j+1]));
        }

        // indexi elemenata vektora "cost_map" predstavljaju početne orijentacije (0-15)
        // svaki element vektora "cost_map" sadrži vektore parova s
        // x-y koordinatama svih čelija kroz koje vozilo prolazi prilikom
        // izvođenja pojedinog segmenta s dotičnom početnom orijentacijom
        cost_map[(int)data_in[i]].push_back(vptmp);
    }

    // definicija vektora za pohranu posjećenih čvorova prilikom pretraživanja grafa
    // koristi se kao sortirano binarno stablo (min-heap)
    // korijen stabla (prvi element vektora) je čvor s najmanjom cijenom
    vector<pair<Vector, double> > heap;

    double c;
    double new_c;
    //double pen = 0.0; // penalizacija promjena kuta
    bool path_exist = true;

    Vector v;
    Vector new_v;

    // spremanje početnih koordinata i orijentacije vozila u vektor "v"
    v.push_back(xs);
    v.push_back(ys);
    v.push_back(fis);

    heap.push_back(make_pair(v, 0.0));

    bool found;

    while(true)
    {
        if (heap.size() == 0)
        {
            path_exist = false;
            break;
        }
        swap(0, heap.size() - 1, &heap, &hm);   // zamjena mjesta prvog i posljednjeg čvora u stablu -> čvor s najmanjom cijenom dolazi na dno stabla

        // pomicanje u sljedeći čvor s najmanjom cijenom iz kojega će se dalje provjeravati ukupne cijene dolaska u njegove susjedne čvorove
        v = heap.back().first;  // koordinate trenutnog čvora (x,y,fi)
        c = heap.back().second; // ukupna minimalna cijena dolaska u trenutni čvor iz početnog čvora
        hm[v] = -1;

        heap.pop_back();    // uklanjanje čvora s najmanjom cijenom iz binarnog stabla (to je trenutno zadnji čvor u heap-u)
        bubble_down(0, &heap, &hm); // spuštanje elementa koji se privremeno našao na root mjestu binarnog stabla (nakon prethodne swap operacije)

        // publishanje posjećenih čvorova (za prikaz u RViz-u)
        /*a.x = v[0] * node_dist * mapResolution;
        a.y = v[1] * node_dist * mapResolution;
        a.z = 0.0;
        gCells.cells.push_back(a);
        gCells.header.stamp = ros::Time::now();
        publishVisitedNodes(gCells);*/

        // određivanje ciljnih koordinata kod removinga
        if (v[0] == xf  &&  v[1] == yf  &&  v[2] == fif) // ako su koord. tenutnog čvora jednake koordinatama ciljnog čvora..
        {
            //fprintf(stderr, "Pronađen ciljni čvor!!\n");
            break;  // prekida se proces planiranja putanje..
        }

        // određivanje najkraćih putanja do svih susjednih čvorova pod pretpostavkom da se vozilo kreće unaprijed
        for (unsigned int i = 0; i < graph[v[2]].size(); i++)   // graph[v[2]] sadrži podatke o svim susjednim čvorovima u koje se može doći iz trenutnog čvora "v" uz početnu orijentaciju v[2]
        {
            // u "new_v" se upisuju x-y koordinate i konačne orijentacije i-tog susjednog čvora koji je povezan s čvorom "v",
            // a u koji se iz čvora "v" može doći uz početnu orijentaciju v[2]
            new_v.clear();
            new_v.push_back(v[0] + graph[v[2]][i].first[0]);    // x - koordinata i-tog susjednog čvora
            new_v.push_back(v[1] + graph[v[2]][i].first[1]);    // y - koordinata i-tog susjednog čvora
            new_v.push_back(graph[v[2]][i].first[2]);           // konačna orijentacija u i-tom susjednom čvoru

            if (hm.find(new_v) == hm.end()) // ako "new_v" još nije dodan u mapu "hm"..
            {
                //heap.push_back(make_pair(new_v, c + graph[v[2]][i].second + pen * abs(new_v[2] - v[2])));
                new_c = cost(v[0], v[1], v[2], i, cost_map, vMap, graph);   // provjera izvedivosti i određivanje cijene segmenta

                if (new_c < INF)    // ako je segment izvediv
                {
                    heap.push_back(make_pair(new_v, c + new_c));    // čvor se dodaje na kraj stabla zajedno s pripadajućom ukupnom cijenom
                    hm[new_v] = heap.size() - 1;        // pamti se index čvora u stablu
                    hm_sol[new_v] = make_pair(v[2], i); // pamti se orijentacija u prethodnom čvoru i index segmenta do čvora "new_v"
                    bubble_up(heap.size() - 1, &heap, &hm); // čvor se podiže na odgovarajuće mjesto u stablu tako da stablo bude sortirano
                }
            }
            else
            {
                if (hm[new_v] != -1)
                {
                    // ako je cijena dolaska u susjedni čvor "new_v" manja od prehodne cijene za taj čvor..
                    if (c + cost(v[0], v[1], v[2], i, cost_map, vMap, graph) < heap[hm[new_v]].second)
                    {
                        if(heap[hm[new_v]].first[0] != new_v[0] || heap[hm[new_v]].first[1] != new_v[1] || heap[hm[new_v]].first[2] != new_v[2])
                            fprintf(stderr, "Error in graph search!\n");

                        //heap[hm[new_v]].second = c + graph[v[2]][i].second + pen * (abs(new_v[2] - v[2]));
                        heap[hm[new_v]].second = c + cost(v[0], v[1], v[2], i, cost_map, vMap, graph); // upisuje se nova cijena do čvora "new_v"
                        hm_sol[new_v] = make_pair(v[2], i); // pamti se orijentacija u prethodnom čvoru i index segmenta do čvora "new_v"
                        bubble_up(hm[new_v], &heap, &hm);   // modificira se mjesto "new_v" čvora u stablu tako da stablo ponovno bude sortirano
                    }
                }
            }
        }

        // određivanje najkraćih putanja do svih čvorova pod pretpostavkom da se vozilo kreće unatrag
        for (unsigned int i = 0; i < graph[(v[2] + 8) % 16].size(); i++)    // graph[(v[2] + 8) % 16] sadrži podatke o svim susjednim čvorovima u koje se može doći iz trenutnog čvora "v" kretanjem unatrag
        {
            // u "new_v" se upisuju x-y koordinate i konačne orijentacije i-tog susjednog čvora koji je povezan s čvorom "v",
            // a u koji se iz čvora "v" može doći uz početnu orijentaciju (v[2] + 8) % 16 (vožnjom unatrag)
            new_v.clear();
            new_v.push_back(v[0] + graph[(v[2] + 8) % 16][i].first[0]);     // x - koordinata i-tog susjednog čvora
            new_v.push_back(v[1] + graph[(v[2] + 8) % 16][i].first[1]);     // y - koordinata i-tog susjednog čvora
            new_v.push_back((graph[(v[2] + 8) % 16][i].first[2] + 8) % 16); // konačna orijentacija u i-tom susjednom čvoru

            if (hm.find(new_v) == hm.end()) // ako "new_v" još nije dodan u mapu "hm"..
            {
                //heap.push_back(make_pair(new_v, c + graph[v[2]][i].second + pen * abs(new_v[2] - v[2])));
                new_c = 2 * cost(v[0], v[1], (v[2] + 8) % 16, i, cost_map, vMap, graph);    // provjera izvedivosti i određivanje cijene segmenta
                if (new_c < INF)    // ako je segment izvediv
                {
                    heap.push_back(make_pair(new_v, c + new_c));    // čvor se dodaje na kraj stabla zajedno s pripadajućom ukupnom cijenom
                    hm[new_v] = heap.size() - 1;    // pamti se index čvora u stablu
                    hm_sol[new_v] = make_pair((v[2] + 8) % 16 + 16, i); // pamti se orijentacija u prethodnom čvoru i index segmenta do čvora "new_v"
                    bubble_up(heap.size() - 1, &heap, &hm); // čvor se podiže na odgovarajuće mjesto u stablu tako da stablo bude sortirano
                }
            }
            else
            {
                if (hm[new_v] != -1)
                {
                    // ako je cijena dolaska u susjedni čvor "new_v" manja od prehodne cijene za taj čvor..
                    if (c + 2*cost(v[0], v[1], (v[2] + 8) % 16, i, cost_map, vMap, graph) < heap[hm[new_v]].second)
                    {
                        if(heap[hm[new_v]].first[0] != new_v[0] ||  heap[hm[new_v]].first[1] != new_v[1] || heap[hm[new_v]].first[2] != new_v[2])
                            fprintf(stderr, "Error in graph search!\n");

                        //heap[hm[new_v]].second = c + graph[v[2]][i].second + pen * (abs(new_v[2] - v[2]));
                        heap[hm[new_v]].second = c + 2*cost(v[0], v[1], (v[2] + 8)%16, i, cost_map, vMap, graph); // upisuje se nova cijena do čvora "new_v"
                        hm_sol[new_v] = make_pair((v[2] + 8) % 16 + 16, i); // pamti se orijentacija u prethodnom čvoru i index segmenta do čvora "new_v"
                        bubble_up(hm[new_v], &heap, &hm);   // modificira se mjesto "new_v" čvora u stablu tako da stablo ponovno bude sortirano
                    }
                }
            }
        }
    }

    if (path_exist) // ako je pronađena izvediva putanja
    {
        vector<pair<int, int> > sol;
        pair<int, int> p;
        vector<int> orient;

        v[0] = xf; v[1] = yf; v[2] = fif;

        // kretanje unatrag od ciljnog čvora do početnog čvora
        while (true)
        {
            // kada se dođe do početnog čvora prekida se while petlja
            if (v[0] == xs  &&  v[1] == ys  &&  v[2] == fis)
            {
                break;
            }

            p = hm_sol[v];
            sol.push_back(p);   // pohrana početne orijentacije u prethodnom čvoru i indexa segmenta putanje koji povezuje prethodni čvor s trenutnim čvorom "v"

            // pomicanje u prethodni čvor (tj. u jedan čvor bliže početnom čvoru)
            v[0] = v[0] - graph[p.first % 16][p.second].first[0];
            v[1] = v[1] - graph[p.first % 16][p.second].first[1];

            if (p.first > 15)
            {
                v[2] = (p.first + 8) % 16;
            }
            else
                v[2] = p.first % 16;

            orient.push_back(v[2]);
        }

        // vektor "veh_orientations" sadrži stvarne orijentacije vozila na početku svakog segmenta, počevši od zadnjeg prema prvom
        *veh_orientations = new int[orient.size() * sizeof(int)];
        for (int i = orient.size() - 1; i >= 0; i--)
        {
            (*veh_orientations)[i] = orient[i];
        }

        *M = new double [2 * sol.size() * sizeof(double)];
        //*M = new double [2 * 336 * sizeof(double)];
        data_out = *M;
        sizeM[0] = 2;
        sizeM[1] = sol.size();  // ukupan broj segmenata od kojih se sastoji izračunata putanja
        //sizeM[1] = 336;   // ukupan broj segmenata od kojih se sastoji izračunata putanja

        int k = 0;
        for (int i = sol.size() - 1; i >= 0; i--)
        {
            data_out[k] = sol[i].first % 16;    // početna orijentacija u i-tom čvoru
            data_out[k+1] = sol[i].second;      // index segmenta koji uz danu početnu orijentaciju vodi do sljedećeg čvora na putanji
            k += 2;
        }

        // ZA ISCRTAVANJE CIJELE LATICE:
        /*for(int j = 0; j < 16; j++)
        {
            for (unsigned int i = 0; i < graph[j].size(); i++)
            {
                data_out[k] = j;        // početna orijentacija u i-tom čvoru
                data_out[k+1] = i;      // index segmenta koji uz danu početnu orijentaciju vodi do sljedećeg čvora na putanji
                k += 2;
            }
        }*/
    }
    else
    {
        *M = NULL;
        data_out = *M;
        sizeM[0] = 0;
        sizeM[1] = 0;
    }
}

// **************************************************************************************


text:
/**
 * dpmeans.hpp
 * @author koide
 * 16/06/07
 **/
#ifndef KKL_DPMEANS_HPP
#define KKL_DPMEANS_HPP

#include <vector>
#include <Eigen/Dense>
#include <Eigen/StdVector>

namespace kkl {
  namespace alg {

/**
 * @brief DP-means
 * @ref http://people.eecs.berkeley.edu/~jordan/papers/kulis-jordan-icml12.pdf
 */
template<typename T, int dim>
class DPmeans {
  typedef Eigen::Matrix<T, dim, 1> VectorTd;

public:
  // constructor, destructor
  DPmeans() {}
  ~DPmeans() {}

  /**
   * @brief train
   * @param x           input data
   * @param lambda      cluster penalty prameter
   * @param criteria    convergence criteria
   * @param loop_limit  maximum number of iterations
   * @return
   */
  bool train(const std::vector<VectorTd>& x, T lambda, T criteria = 0.01, int loop_limit = 128) {
    labels.assign(x.size(), 0);
    centroids.clear();
    centroids.push_back(VectorTd::Zero());

    for (int i = 0; i < loop_limit; i++) {
      updateCentroids(x, criteria);
      if (updateLabels(x, lambda) ) {
        return true;
      }
    }

    return false;
  }

private:
  // update centroids acoording to labels
  bool updateCentroids(const std::vector<VectorTd>& x, T criteria) {
    int k = centroids.size();
    std::vector<int> accums(k, 0);
    std::vector<VectorTd> new_centroids(k);
    std::for_each(new_centroids.begin(), new_centroids.end(), [=](VectorTd& centroid) { centroid.setZero(); });

    // update centrods
    for (int i = 0; i < x.size(); i++) {
      accums[labels[i]]++;
      new_centroids[labels[i]] += x[i];
    }
    for (int i = 0; i < k; i++) {
      new_centroids[i] /= std::max( 1, accums[i] );
    }

    centroids.swap(new_centroids);

    // check if converged
    for (int i = 0; i < centroids.size(); i++) {
      if ((centroids[i] - new_centroids[i]).squaredNorm() > criteria * criteria) {
        return false;
      }
    }
    return true;
  }

  // update labels acoording to estimated centroids
  // if the distance between a point and the closest centroid is lager than lambda, the point is added as a new centroid
  bool updateLabels(const std::vector<VectorTd>& x, T lambda) {
    bool is_converged = true;
    bool k_incremented = false;
    // for each point
    for (int i = 0; i < x.size(); i++) {
      T min_d = (centroids[0] - x[i]).squaredNorm();
      int min_label = 0;

      // find the closest centroid
      for (int j = 1; j < centroids.size(); j++) {
        T d = (centroids[j] - x[i]).squaredNorm();
        if (d < min_d) {
          min_d = d;
          min_label = j;
        }
      }

      // check if the distance between the point and the closest centroid is larger than lambda
      if ( !k_incremented && min_d > lambda * lambda) {
        k_incremented = true;
        min_label = centroids.size();
        centroids.push_back(x[i]);

//				i = 0;	// re-calculate all labels since a new centroid is added
      }

      // if a label is changed, estimation is not converged
      if (labels[i] != min_label) {
        is_converged = false;
      }
      labels[i] = min_label;
    }

    return is_converged;
  }

public:
  std::vector<int> labels;			    // labels assigned to input data
  std::vector<VectorTd> centroids;	// estimated centroids
};

  }
}

#endif


text:
/*
 * 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)
 *
 * Copyright (c) 2009 Helge Bahmann
 * Copyright (c) 2012 Tim Blechmann
 * Copyright (c) 2013 - 2014 Andrey Semashev
 */
/*!
 * \file   atomic/detail/caps_gcc_x86.hpp
 *
 * This header defines feature capabilities macros
 */

#ifndef BOOST_ATOMIC_DETAIL_CAPS_GCC_X86_HPP_INCLUDED_
#define BOOST_ATOMIC_DETAIL_CAPS_GCC_X86_HPP_INCLUDED_

#include <boost/atomic/detail/config.hpp>

#ifdef BOOST_HAS_PRAGMA_ONCE
#pragma once
#endif

#if defined(__i386__) &&\
    (\
        defined(__GCC_HAVE_SYNC_COMPARE_AND_SWAP_8) ||\
        defined(__i586__) || defined(__i686__) || defined(__pentium4__) || defined(__nocona__) || defined(__core2__) || defined(__corei7__) ||\
        defined(__k6__) || defined(__athlon__) || defined(__k8__) || defined(__amdfam10__) || defined(__bdver1__) || defined(__bdver2__) || defined(__bdver3__) || defined(__btver1__) || defined(__btver2__)\
    )
#define BOOST_ATOMIC_DETAIL_X86_HAS_CMPXCHG8B 1
#endif

#if defined(__x86_64__) && defined(__GCC_HAVE_SYNC_COMPARE_AND_SWAP_16)
#define BOOST_ATOMIC_DETAIL_X86_HAS_CMPXCHG16B 1
#endif

#define BOOST_ATOMIC_INT8_LOCK_FREE 2
#define BOOST_ATOMIC_INT16_LOCK_FREE 2
#define BOOST_ATOMIC_INT32_LOCK_FREE 2
#if defined(__x86_64__) || defined(BOOST_ATOMIC_DETAIL_X86_HAS_CMPXCHG8B)
#define BOOST_ATOMIC_INT64_LOCK_FREE 2
#endif
#if defined(BOOST_ATOMIC_DETAIL_X86_HAS_CMPXCHG16B) && (defined(BOOST_HAS_INT128) || !defined(BOOST_NO_ALIGNMENT))
#define BOOST_ATOMIC_INT128_LOCK_FREE 2
#endif
#define BOOST_ATOMIC_POINTER_LOCK_FREE 2

#define BOOST_ATOMIC_THREAD_FENCE 2
#define BOOST_ATOMIC_SIGNAL_FENCE 2

#endif // BOOST_ATOMIC_DETAIL_CAPS_GCC_X86_HPP_INCLUDED_

max_stars_repo_name: multi-os-engine/cinder-natj-binding

max_issues_repo_name: wujf/mongo

max_forks_repo_name: wujf/mongo


text:
#pragma once

#include <boost/range/combine.hpp>

#include "fermion_operator.hpp"
#include "observable.hpp"
#include "pauli_operator.hpp"
#include "state.hpp"
#include "type.hpp"

namespace transforms {
Observable bravyi_kitaev(FermionOperator const& fop, UINT n_qubits);
UINT count_qubits(FermionOperator const& fop);
Observable inline_sum(std::vector<Observable> summands, Observable seed);
Observable inline_product(std::vector<Observable> factors, Observable seed);
std::set<UINT> _update_set(UINT index, UINT n_qubits);
std::set<UINT> _occupation_set(UINT index);
std::set<UINT> _parity_set(UINT index);
Observable _transform_ladder_operator(
    UINT target_index, UINT action_id, UINT n_qubits);
Observable _transform_operator_term(
    SingleFermionOperator& sfop, CPPCTYPE coef, UINT n_qubits);
}  // namespace transforms


text:
// Copyright (2013) JDSU.  All rights reserved.

#include <pcap/pcap.h>
#include <string.h>
#include <errno.h>
#include <iostream>     // NOLINT(readability/streams)
#include <iomanip>
#include <boost/format.hpp>

// Forward declarations.
void output(size_t packet_number, const unsigned char* packet, size_t len);

// This program reads a pcap file and output C++ code for each packet in the pcap file.
// Recommend you only run this program on some pcap files.
int main(int argc, char* argv[]) {
    if (argc != 2) {
        std::cerr << "usage: " << argv[0] << " pcap-file" << std::endl;
        return 1;
    }

    char* filename = argv[1];

    char pcap_errbuf[PCAP_ERRBUF_SIZE];
    pcap_t* pcap_handle = pcap_open_offline(filename, pcap_errbuf);
    if (pcap_handle == 0) {
        std::cerr << "can't open " << filename << " : " << strerror(errno)
                  << " pcap-error='" << pcap_errbuf << "'" << std::endl;
        return 2;
    }

    size_t packet_number = 0;
    while (true) {
        pcap_pkthdr pcap_header;
        const unsigned char* packet = pcap_next(pcap_handle, &pcap_header);
        if (packet == 0) {
            break;
        }
        output(++packet_number, packet, pcap_header.caplen);
    }
    pcap_close(pcap_handle);
    return 0;
}

void output(size_t packet_number, const unsigned char* packet, size_t len) {
    std::cout << "unsigned char packet_" << packet_number << "[] = {";
    for (size_t i = 0; i < len; ++i) {
        if ((i % 8) == 0) {
            if (i) {
                std::cout << ",";
            }
            std::cout << std::endl << "    ";
        } else {
            std::cout << ", ";
        }
#if 1
        std::cout << boost::format("0x%1$02x") % (unsigned int)packet[i];
#else
        std::cout << std::hex << std::setw(2) << std::fill('0') << (unsigned int)packet[i];
#endif
    }
    std::cout << std::endl << "};" << std::endl << std::endl;
}

ext: cc


text:
// Taken from http://wiki.ros.org/image_geometry/Tutorials/ProjectTfFrameToImage

#include <ros/ros.h>
#include <image_transport/image_transport.h>
#include <opencv/cv.h>
#include <cv_bridge/cv_bridge.h>
#include <image_geometry/pinhole_camera_model.h>
#include <tf/transform_listener.h>
#include <boost/foreach.hpp>
#include <sensor_msgs/image_encodings.h>
#include <fstream>

class FrameDrawer
{
  ros::NodeHandle nh_;
  image_transport::ImageTransport it_;
  image_transport::CameraSubscriber sub_;
  image_transport::Publisher pub_;
  tf::TransformListener tf_listener_;
  image_geometry::PinholeCameraModel cam_model_;
  std::vector<std::string> frame_ids_;
  CvFont font_;

public:
  FrameDrawer(const std::vector<std::string>& frame_ids) : it_(nh_), frame_ids_(frame_ids)
  {
    std::string image_topic = nh_.resolveName("image");

    std::string param_name = "/SQ01s/panther/mode";

    if (!nh_.getParam("/SQ01s/panther/mode", mode_))
    {
      ROS_ERROR("Failed to find parameter: %s", nh_.resolveName(param_name, true).c_str());
      exit(1);
    }

    name_file_pos_ = "/home/jtorde/Desktop/ws/src/panther/" + mode_ + "_projection_positions.txt";
    name_file_vel_ = "/home/jtorde/Desktop/ws/src/panther/" + mode_ + "_projection_velocities.txt";

    // ros::NodeHandle nh;
    // image_transport::ImageTransport it(nh);
    // image_transport::Subscriber sub = it.subscribe("in_image_base_topic", 1 & FrameDrawer::imageCb, this);
    // image_transport::Publisher pub = it.advertise("out_image_base_topic", 1);

    sub_ = it_.subscribeCamera(image_topic, 1, &FrameDrawer::imageCb, this);
    pub_ = it_.advertise("image_out", 1);
    cvInitFont(&font_, CV_FONT_HERSHEY_SIMPLEX, 0.5, 0.5);

    // Delete content of the files
    // https://stackoverflow.com/questions/17032970/clear-data-inside-text-file-in-c
    std::ofstream ofs;
    ofs.open(name_file_pos_, std::ofstream::out | std::ofstream::trunc);
    ofs.close();

    ofs.open(name_file_vel_, std::ofstream::out | std::ofstream::trunc);
    ofs.close();
  }

  std::string mode_;
  double last_time_ = 0.0;
  bool last_initialized_ = false;
  cv::Point2d last_uv_;

  std::string name_file_pos_;
  std::string name_file_vel_;

  void imageCb(const sensor_msgs::ImageConstPtr& image_msg, const sensor_msgs::CameraInfoConstPtr& info_msg)
  {
    cv::Mat image;
    cv_bridge::CvImagePtr input_bridge;
    try
    {
      input_bridge = cv_bridge::toCvCopy(image_msg, sensor_msgs::image_encodings::BGR8);
      image = input_bridge->image;
    }
    catch (cv_bridge::Exception& ex)
    {
      ROS_ERROR("[draw_frames] Failed to convert image");
      return;
    }

    cam_model_.fromCameraInfo(info_msg);

    std::string frame_id = frame_ids_.front();  // Taking only the first one for now. TODO

    // BOOST_FOREACH (const std::string& frame_id, frame_ids_)
    // {
    tf::StampedTransform transform;
    try
    {
      ros::Time acquisition_time = info_msg->header.stamp;
      ros::Duration timeout(1.0 / 30);
      tf_listener_.waitForTransform(cam_model_.tfFrame(), frame_id, acquisition_time, timeout);
      tf_listener_.lookupTransform(cam_model_.tfFrame(), frame_id, acquisition_time, transform);
    }
    catch (tf::TransformException& ex)
    {
      ROS_WARN("[draw_frames] TF exception:\n%s", ex.what());
      return;
    }

    tf::Point pt = transform.getOrigin();

    cv::Point3d pt_cv(pt.x(), pt.y(), pt.z());
    cv::Point2d uv = cam_model_.project3dToPixel(pt_cv);

    // Create and open a text file

    // NOte that the (x,y) coordinates are as follows:

    //  ------> x
    //  |
    //  |   IMAGE
    //  |
    //  V y

    // (i.e. origin is on the top left corner of the image).
    // For a point to be in the image, we need to have x \in [0, image.cols] and y \in [0, image.rows]

    bool point_in_front_of_camera = (pt.z() > 0);
    bool point_behind_camera = (!point_in_front_of_camera);
    std::fstream myfile;

    // if (point_behind_camera == false)
    // {

    myfile.open(name_file_pos_, std::ios_base::app);
    myfile << uv.x << " " << uv.y << " " << image.cols << " " << image.rows << " " << int(point_in_front_of_camera)
           << "\n";
    myfile.close();
    // }
    // else
    // {
    //   std::cout << "Point is behind the camera!!!" << std::endl;
    // }

    std::cout << "Image of width= " << image.cols << ", height= " << image.rows << std::endl;
    if (uv.x > image.cols || uv.x < 0 || uv.y > image.rows || uv.y < 0 || point_behind_camera)
    {
      std::cout << "Not in FOV!" << std::endl;
      last_initialized_ = false;
    }
    else
    {
      all_projections_.push_back(uv);
      plotAllProjections(image);
      // cv::circle(image, uv, RADIUS, CV_RGB(255, 0, 0), -1);

      // CvSize text_size;
      // int baseline;
      // cvGetTextSize(frame_id.c_str(), &font_, &text_size, &baseline);
      //   CvPoint origin = cvPoint(uv.x - text_size.width / 2, uv.y - RADIUS - baseline - 3);
      // cv:
      //   putText(image, frame_id.c_str(), origin, cv::FONT_HERSHEY_SIMPLEX, 12, CV_RGB(255, 0, 0));

      if (last_initialized_ == true)
      {
        double distance = sqrt(pow(uv.x - last_uv_.x, 2) + pow(uv.y - last_uv_.y, 2));
        double delta_t = ((info_msg->header.stamp).toSec() - last_time_);
        double vel = distance / delta_t;

        std::cout << "Last point was " << last_uv_.x << ", " << last_uv_.y << std::endl;
        std::cout << "Now is " << uv.x << ", " << uv.y << std::endl;
        std::cout << "delta_t= " << std::setprecision(4) << delta_t << " ss" << std::endl;
        std::cout << "Vel= " << vel << " px/s" << std::endl;

        myfile.open(name_file_vel_, std::ios_base::app);
        myfile << vel << "\n";
        myfile.close();
      }
      last_time_ = (info_msg->header.stamp).toSec();
      last_uv_ = uv;
      last_initialized_ = true;
    }

    //}

    pub_.publish(input_bridge->toImageMsg());
  }

  void plotAllProjections(cv::Mat& image)
  {
    static const int RADIUS = 3;

    for (int i = 0; i < all_projections_.size(); i++)
    {
      if (i == (all_projections_.size() - 1))
      {
        cv::circle(image, all_projections_[i], 2 * RADIUS, CV_RGB(0, 255, 0), -1);
      }
      else
      {
        cv::circle(image, all_projections_[i], RADIUS, CV_RGB(255, 0, 0), -1);
      }
    }
  }

private:
  std::vector<cv::Point2d> all_projections_;
};

int main(int argc, char** argv)
{
  ros::init(argc, argv, "draw_frames");
  std::vector<std::string> frame_ids(argv + 1, argv + argc);
  FrameDrawer drawer(frame_ids);
  ros::spin();
}

max_stars_repo_name: t-thanh/panther

max_issues_repo_name: t-thanh/panther

max_forks_repo_name: t-thanh/panther


text:
// Copyright (c) 2020 Egor Tensin <Egor.Tensin@gmail.com>
// This file is part of the "winapi-common" project.
// For details, see https://github.com/egor-tensin/winapi-common.
// Distributed under the MIT License.

#pragma once

#include "shared/command.hpp"

#include <winapi/cmd_line.hpp>
#include <winapi/file.hpp>
#include <winapi/path.hpp>

#include <boost/test/unit_test.hpp>

#include <exception>
#include <stdexcept>
#include <string>

class RemoveFileGuard {
public:
    explicit RemoveFileGuard(const winapi::CanonicalPath& path) : m_path(path) {}

    ~RemoveFileGuard() {
        try {
            winapi::File::remove(m_path);
        } catch (const std::exception& e) {
            BOOST_TEST_MESSAGE("Couldn't remove file " << m_path.get() << ": " << e.what());
        }
    }

private:
    winapi::CanonicalPath m_path;

    RemoveFileGuard(const RemoveFileGuard&) = delete;
    RemoveFileGuard& operator=(const RemoveFileGuard&) = delete;
};

class WithParam {
public:
    WithParam(const std::string& param_prefix) : m_value(find_param_value(param_prefix)) {}

    const std::string& get_value() { return m_value; }

private:
    static std::string find_param_value(const std::string& param_prefix) {
        const auto cmd_line = winapi::CommandLine::query();
        const auto& args = cmd_line.get_args();
        for (const auto& arg : args) {
            if (arg.rfind(param_prefix, 0) == 0) {
                return arg.substr(param_prefix.length());
            }
        }
        throw std::runtime_error{"couldn't find parameter " + param_prefix};
    }

    std::string m_value;
};

class WithEchoExe : public WithParam {
public:
    WithEchoExe() : WithParam("--echo_exe=") {}

    const std::string& get_echo_exe() { return get_value(); }
};

class WithWorkerExe : public WithParam {
public:
    WithWorkerExe() : WithParam("--worker_exe="), m_cmd(worker::Command::create()) {}

    const std::string& get_worker_exe() { return get_value(); }

    worker::Command::Shared m_cmd;
};

max_stars_repo_name: egor-tensin/winapi-common

max_issues_repo_name: egor-tensin/winapi-common

max_forks_repo_name: egor-tensin/winapi-common


text:
/*
 * scope_guard.hpp
 *
 *  Created on: Sep 3, 2009
 *      Author: stewie
 */

#ifndef SCOPE_GUARD_HPP_
#define SCOPE_GUARD_HPP_

#include <boost/preprocessor/cat.hpp>

namespace bn {

namespace util {

namespace detail {

class scope_guard_base {
public:
	void release() const {
		released = true;
	}

	void __touch__() const {
	}

protected:
	scope_guard_base() :
		released(false) {
	}

	scope_guard_base(const scope_guard_base& other) :
		released(other.released) {
		other.release();
	}

	template<class T> static void execute(T& guard) {
		if (!guard.released)
			guard();
	}

	mutable bool released;

private:
	scope_guard_base& operator=(const scope_guard_base&);

	void* operator new(size_t);
};

}

template<class T> class scope_guard_facade : public detail::scope_guard_base {
protected:
	scope_guard_facade() {
	}

	~scope_guard_facade() {
		detail::scope_guard_base::execute(static_cast<T&> (*this));
	}
};

typedef const detail::scope_guard_base& scope_guard;

#define SCOPE_GUARD_HELPER(name, guard) \
	::bn::util::scope_guard name = guard; \
	name.__touch__()
#define SCOPE_GUARD(guard) \
	SCOPE_GUARD_HELPER(BOOST_PP_CAT(__scope_guard_at_line_, __LINE__), guard)

}

}

#endif /* SCOPE_GUARD_HPP_ */

max_stars_repo_name: Markfrancisrogers/BooleanNetwork

max_issues_repo_name: Markfrancisrogers/BooleanNetwork

max_forks_repo_name: Markfrancisrogers/BooleanNetwork


text: #include <boost/thread/pthread/once_atomic.hpp>

max_stars_repo_name: miathedev/BoostForArduino

max_issues_repo_name: miathedev/BoostForArduino

max_forks_repo_name: miathedev/BoostForArduino


text:
/**
 * @file contact_managers_plugin_factory.cpp
 * @brief Factory for loading contact managers as plugins
 *
 * @author Levi Armstrong
 * @date October 25, 2021
 * @version TODO
 * @bug No known bugs
 *
 * @copyright Copyright (c) 2021, Southwest Research Institute
 *
 * @par License
 * Software License Agreement (Apache License)
 * @par
 * 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
 * @par
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include <tesseract_common/macros.h>
TESSERACT_COMMON_IGNORE_WARNINGS_PUSH
#include <boost/algorithm/string.hpp>
TESSERACT_COMMON_IGNORE_WARNINGS_POP

#include <tesseract_common/plugin_loader.hpp>
#include <tesseract_common/yaml_utils.h>
#include <tesseract_collision/core/contact_managers_plugin_factory.h>

static const std::string TESSERACT_CONTACT_MANAGERS_PLUGIN_DIRECTORIES_ENV = "TESSERACT_CONTACT_MANAGERS_PLUGIN_"
                                                                             "DIRECTORIES";
static const std::string TESSERACT_CONTACT_MANAGERS_PLUGINS_ENV = "TESSERACT_CONTACT_MANAGERS_PLUGINS";

using tesseract_common::ContactManagersPluginInfo;

namespace tesseract_collision
{
const std::string DiscreteContactManagerFactory::SECTION_NAME = "DiscColl";
const std::string ContinuousContactManagerFactory::SECTION_NAME = "ContColl";

ContactManagersPluginFactory::ContactManagersPluginFactory()
{
  plugin_loader_.search_libraries_env = TESSERACT_CONTACT_MANAGERS_PLUGINS_ENV;
  plugin_loader_.search_paths_env = TESSERACT_CONTACT_MANAGERS_PLUGIN_DIRECTORIES_ENV;
  plugin_loader_.search_paths.insert(TESSERACT_CONTACT_MANAGERS_PLUGIN_PATH);
  boost::split(plugin_loader_.search_libraries,
               TESSERACT_CONTACT_MANAGERS_PLUGINS,
               boost::is_any_of(":"),
               boost::token_compress_on);
}

ContactManagersPluginFactory::ContactManagersPluginFactory(YAML::Node config) : ContactManagersPluginFactory()
{
  if (const YAML::Node& plugin_info = config[ContactManagersPluginInfo::CONFIG_KEY])
  {
    auto cm_plugin_info = plugin_info.as<tesseract_common::ContactManagersPluginInfo>();
    plugin_loader_.search_paths.insert(cm_plugin_info.search_paths.begin(), cm_plugin_info.search_paths.end());
    plugin_loader_.search_libraries.insert(cm_plugin_info.search_libraries.begin(),
                                           cm_plugin_info.search_libraries.end());
    discrete_plugin_info_ = cm_plugin_info.discrete_plugin_infos;
    continuous_plugin_info_ = cm_plugin_info.continuous_plugin_infos;
  }
}

ContactManagersPluginFactory::ContactManagersPluginFactory(const tesseract_common::fs::path& config)
  : ContactManagersPluginFactory(YAML::LoadFile(config.string()))
{
}

ContactManagersPluginFactory::ContactManagersPluginFactory(const std::string& config)
  : ContactManagersPluginFactory(YAML::Load(config))
{
}

// This prevents it from being defined inline.
// If not the forward declare of PluginLoader cause compiler error.
ContactManagersPluginFactory::~ContactManagersPluginFactory() = default;

void ContactManagersPluginFactory::addSearchPath(const std::string& path) { plugin_loader_.search_paths.insert(path); }

std::set<std::string> ContactManagersPluginFactory::getSearchPaths() const { return plugin_loader_.search_paths; }

void ContactManagersPluginFactory::addSearchLibrary(const std::string& library_name)
{
  plugin_loader_.search_libraries.insert(library_name);
}

std::set<std::string> ContactManagersPluginFactory::getSearchLibraries() const
{
  return plugin_loader_.search_libraries;
}

void ContactManagersPluginFactory::addDiscreteContactManagerPlugin(const std::string& name,
                                                                   tesseract_common::PluginInfo plugin_info)
{
  discrete_plugin_info_.plugins[name] = std::move(plugin_info);
}

bool ContactManagersPluginFactory::hasDiscreteContactManagerPlugins() const
{
  return !discrete_plugin_info_.plugins.empty();
}

tesseract_common::PluginInfoMap ContactManagersPluginFactory::getDiscreteContactManagerPlugins() const
{
  return discrete_plugin_info_.plugins;
}

void ContactManagersPluginFactory::removeDiscreteContactManagerPlugin(const std::string& name)
{
  auto cm_it = discrete_plugin_info_.plugins.find(name);
  if (cm_it == discrete_plugin_info_.plugins.end())
    throw std::runtime_error("ContactManagersPluginFactory, tried to remove discrete contact manager '" + name +
                             "' that does not exist!");

  discrete_plugin_info_.plugins.erase(cm_it);

  if (discrete_plugin_info_.default_plugin == name)
    discrete_plugin_info_.default_plugin.clear();
}

void ContactManagersPluginFactory::setDefaultDiscreteContactManagerPlugin(const std::string& name)
{
  auto cm_it = discrete_plugin_info_.plugins.find(name);
  if (cm_it == discrete_plugin_info_.plugins.end())
    throw std::runtime_error("ContactManagersPluginFactory, tried to set default discrete contact manager '" + name +
                             "' that does not exist!");

  discrete_plugin_info_.default_plugin = name;
}

std::string ContactManagersPluginFactory::getDefaultDiscreteContactManagerPlugin() const
{
  if (discrete_plugin_info_.plugins.empty())
    throw std::runtime_error("ContactManagersPluginFactory, tried to get default discrete contact manager but none "
                             "exist!");

  if (discrete_plugin_info_.default_plugin.empty())
    return discrete_plugin_info_.plugins.begin()->first;

  return discrete_plugin_info_.default_plugin;
}

void ContactManagersPluginFactory::addContinuousContactManagerPlugin(const std::string& name,
                                                                     tesseract_common::PluginInfo plugin_info)
{
  continuous_plugin_info_.plugins[name] = std::move(plugin_info);
}

bool ContactManagersPluginFactory::hasContinuousContactManagerPlugins() const
{
  return !continuous_plugin_info_.plugins.empty();
}

tesseract_common::PluginInfoMap ContactManagersPluginFactory::getContinuousContactManagerPlugins() const
{
  return continuous_plugin_info_.plugins;
}

void ContactManagersPluginFactory::removeContinuousContactManagerPlugin(const std::string& name)
{
  auto cm_it = continuous_plugin_info_.plugins.find(name);
  if (cm_it == continuous_plugin_info_.plugins.end())
    throw std::runtime_error("ContactManagersPluginFactory, tried to remove continuous contact manager '" + name +
                             "' that does not exist!");

  continuous_plugin_info_.plugins.erase(cm_it);

  if (continuous_plugin_info_.default_plugin == name)
    continuous_plugin_info_.default_plugin.clear();
}

void ContactManagersPluginFactory::setDefaultContinuousContactManagerPlugin(const std::string& name)
{
  auto cm_it = continuous_plugin_info_.plugins.find(name);
  if (cm_it == continuous_plugin_info_.plugins.end())
    throw std::runtime_error("ContactManagersPluginFactory, tried to set default continuous contact manager '" + name +
                             "' that does not exist!");

  continuous_plugin_info_.default_plugin = name;
}

std::string ContactManagersPluginFactory::getDefaultContinuousContactManagerPlugin() const
{
  if (continuous_plugin_info_.plugins.empty())
    throw std::runtime_error("ContactManagersPluginFactory, tried to get default continuous contact manager but none "
                             "exist!");

  if (continuous_plugin_info_.default_plugin.empty())
    return continuous_plugin_info_.plugins.begin()->first;

  return continuous_plugin_info_.default_plugin;
}

DiscreteContactManager::UPtr ContactManagersPluginFactory::createDiscreteContactManager(const std::string& name) const
{
  auto cm_it = discrete_plugin_info_.plugins.find(name);
  if (cm_it == discrete_plugin_info_.plugins.end())
  {
    CONSOLE_BRIDGE_logWarn("ContactManagersPluginFactory, tried to get discrete contact manager '%s' that does not "
                           "exist!",
                           name.c_str());
    return nullptr;
  }

  return createDiscreteContactManager(name, cm_it->second);
}

DiscreteContactManager::UPtr
ContactManagersPluginFactory::createDiscreteContactManager(const std::string& name,
                                                           const tesseract_common::PluginInfo& plugin_info) const
{
  try
  {
    auto it = discrete_factories_.find(plugin_info.class_name);
    if (it != discrete_factories_.end())
      return it->second->create(name, plugin_info.config);

    auto plugin = plugin_loader_.instantiate<DiscreteContactManagerFactory>(plugin_info.class_name);
    if (plugin == nullptr)
    {
      CONSOLE_BRIDGE_logWarn("Failed to load symbol '%s'", plugin_info.class_name.c_str());
      return nullptr;
    }
    discrete_factories_[plugin_info.class_name] = plugin;
    return plugin->create(name, plugin_info.config);
  }
  catch (const std::exception&)
  {
    CONSOLE_BRIDGE_logWarn("Failed to load symbol '%s'", plugin_info.class_name.c_str());
    return nullptr;
  }
}

ContinuousContactManager::UPtr
ContactManagersPluginFactory::createContinuousContactManager(const std::string& name) const
{
  auto cm_it = continuous_plugin_info_.plugins.find(name);
  if (cm_it == continuous_plugin_info_.plugins.end())
  {
    CONSOLE_BRIDGE_logWarn("ContactManagersPluginFactory, tried to get continuous contact manager '%s' that does not "
                           "exist!",
                           name.c_str());
    return nullptr;
  }

  return createContinuousContactManager(name, cm_it->second);
}

ContinuousContactManager::UPtr
ContactManagersPluginFactory::createContinuousContactManager(const std::string& name,
                                                             const tesseract_common::PluginInfo& plugin_info) const
{
  try
  {
    auto it = continuous_factories_.find(plugin_info.class_name);
    if (it != continuous_factories_.end())
      return it->second->create(name, plugin_info.config);

    auto plugin = plugin_loader_.instantiate<ContinuousContactManagerFactory>(plugin_info.class_name);
    if (plugin == nullptr)
    {
      CONSOLE_BRIDGE_logWarn("Failed to load symbol '%s'", plugin_info.class_name.c_str());
      return nullptr;
    }
    continuous_factories_[plugin_info.class_name] = plugin;
    return plugin->create(name, plugin_info.config);
  }
  catch (const std::exception&)
  {
    CONSOLE_BRIDGE_logWarn("Failed to load symbol '%s'", plugin_info.class_name.c_str());
    return nullptr;
  }
}

void ContactManagersPluginFactory::saveConfig(const tesseract_common::fs::path& file_path) const
{
  YAML::Node config = getConfig();
  std::ofstream fout(file_path.string());
  fout << config;
}

YAML::Node ContactManagersPluginFactory::getConfig() const
{
  tesseract_common::ContactManagersPluginInfo cm_plugins;
  cm_plugins.search_paths = plugin_loader_.search_paths;
  cm_plugins.search_libraries = plugin_loader_.search_libraries;
  cm_plugins.discrete_plugin_infos = discrete_plugin_info_;
  cm_plugins.continuous_plugin_infos = continuous_plugin_info_;

  YAML::Node config;
  config[ContactManagersPluginInfo::CONFIG_KEY] = cm_plugins;

  return config;
}

}  // namespace tesseract_collision

max_stars_repo_name: daoran/tesseract

max_issues_repo_name: daoran/tesseract

max_forks_repo_name: daoran/tesseract


text:
// Copyright (C) 2017 Vicente J. Botet Escriba
//
//  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)

// <experimental/strong_bool.hpp>

#include <experimental/strong_bool.hpp>
#include <sstream>

#include <boost/detail/lightweight_test.hpp>

namespace stdex = std::experimental;

using EngineStarted = stdex::strict_bool<class EngineStartedTag>;
using CrewReady     = stdex::strict_bool<class CrewReadyTag>;
using UEngineStarted = stdex::strict_bool<class EngineStartedTag, unsigned char>;
using UCrewReady     = stdex::strict_bool<class CrewReadyTag, unsigned char>;

void set_status(EngineStarted started, CrewReady ready)
{
  (void)started;
  (void)ready;
}

struct X {
    operator bool() { return true; }
};

struct Y {
    explicit operator bool() { return true; }
};

enum class boolean : bool {};
enum class byte : unsigned char{};

void f(bool) {}

int main()
{
#if defined __clang__ && __cplusplus > 201402L
  {
    //boolean b1 = true;     // error - explicit required
    boolean b2 {true};
    BOOST_TEST(static_cast<bool>(b2) == true);
    //boolean b2 {1}; // fails as expected
  }
  {
    byte b{0xab};
    BOOST_TEST(static_cast<unsigned char>(b) == 0xab);
  }
#endif
  {
      //EngineStarted es1 = true;     // error - explicit required

      //EngineStarted es2 {nullptr};  // error void* deleted

      //EngineStarted es3 {1};        // error int deleted
      //short s;
      //EngineStarted es4 {s};        // error int deleted

      //EngineStarted es5 {1.0};      // error double deleted

      EngineStarted es {true};        // ok
      CrewReady     cr {false};       // ok

      //EngineStarted es6 =cr;       // error
      //EngineStarted es7 {cr};       // fixme: how can we forbid this providing explicit conversion to bool? clang compile this while gcc don't.

      //bool b = cr;                  // error - implicit conversion required

      bool ans = es==EngineStarted{true} && ! (cr==CrewReady{true});           // ok - explicit conversion required by the use of &&
      BOOST_TEST(ans);
      if (cr==CrewReady{true})                         // ok - explicit conversion required by the use cr in an if
          std::cout << "True\n";

      //set_status(true, true);       // error - implicit conversion required
      set_status(EngineStarted{true}, CrewReady{true});        // function call

      //auto r = es == 1;
  }
  {
      //EngineStarted es {Y{}};        // error, explicit conversion
      // we can not prevent all the implicit conversions, or can we?
      EngineStarted es {X{}};        // ok, implicit conversion from UDT
      BOOST_TEST(es==EngineStarted{true});
  }
  {
      EngineStarted es1 {true};
      EngineStarted es2 {false};
      BOOST_TEST(es2<es1);
      BOOST_TEST(es2!=es1);
      //CrewReady     cr {false};
      //BOOST_TEST(cr<es1); // error
  }
  {
      EngineStarted es1 {true};
      EngineStarted es2 {false};
      EngineStarted es = es1 || es2;
      BOOST_TEST(es==EngineStarted{true});
  }
  {
      EngineStarted es1 {true};
      EngineStarted es = es1 || EngineStarted{false};
      BOOST_TEST(es==EngineStarted{true});
  }
  {
      EngineStarted es2 {false};
      EngineStarted es = EngineStarted{true} || es2;
      BOOST_TEST(es==EngineStarted{true});
  }
  {
      EngineStarted es1 {true};
      EngineStarted es2 {false};
      EngineStarted es = es1 && es2;
      BOOST_TEST(es==EngineStarted{false});
  }
  {
      EngineStarted es1 {true};
      EngineStarted es = ! es1 ;
      BOOST_TEST(es==EngineStarted{false});
  }
  {
      EngineStarted es {true};
      if (es.underlying())
        BOOST_TEST(true);
      else
        BOOST_TEST(false);
  }
  {
      EngineStarted es {true};
      f (es.underlying());
  }

  {
      EngineStarted es {true};
      std::stringstream os;
      os << std::boolalpha << es;
      BOOST_TEST_EQ(os.str(), "true");
  }
  {
      EngineStarted es;
      std::stringstream s;
      s << std::boolalpha << true;
      s >> std::boolalpha >> es;

      BOOST_TEST_EQ(es, EngineStarted{true});
  }
  {
//    UEngineStarted es {true};        // ok
//    UCrewReady     cr {false};       // ok

  }
  return ::boost::report_errors();
}

max_stars_repo_name: jwakely/std-make

max_issues_repo_name: jwakely/std-make

max_forks_repo_name: jwakely/std-make