text:
/*
 * Copyright (C) 2019-2021 HERE Europe B.V.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 * SPDX-License-Identifier: Apache-2.0
 * License-Filename: LICENSE
 */

#include "IndexLayerClientImpl.h"

#include <boost/format.hpp>
#include <boost/uuid/uuid.hpp>
#include <boost/uuid/uuid_generators.hpp>
#include <boost/uuid/uuid_io.hpp>

#include <olp/core/client/CancellationContext.h>

#include "ApiClientLookup.h"
#include "Common.h"
#include "generated/BlobApi.h"
#include "generated/ConfigApi.h"
#include "generated/IndexApi.h"

#include <atomic>

namespace {
std::string GenerateUuid() {
  static boost::uuids::random_generator gen;
  return boost::uuids::to_string(gen());
}
}  // namespace

namespace olp {
namespace dataservice {
namespace write {

IndexLayerClientImpl::IndexLayerClientImpl(client::HRN catalog,
                                           client::OlpClientSettings settings)
    : catalog_(std::move(catalog)),
      catalog_settings_(catalog_, settings),
      settings_(std::move(settings)),
      apiclient_config_(nullptr),
      apiclient_blob_(nullptr),
      apiclient_index_(nullptr),
      pending_requests_(std::make_shared<client::PendingRequests>()),
      init_in_progress_(false) {}

IndexLayerClientImpl::~IndexLayerClientImpl() {
  tokenList_.CancelAll();
  pending_requests_->CancelAllAndWait();
}

olp::client::CancellationToken IndexLayerClientImpl::InitApiClients(
    std::shared_ptr<client::CancellationContext> cancel_context,
    InitApiClientsCallback callback) {
  auto self = shared_from_this();
  std::unique_lock<std::mutex> ul{mutex_, std::try_to_lock};
  if (init_in_progress_) {
    ul.unlock();
    cond_var_.wait(ul, [self]() { return !self->init_in_progress_; });
    ul.lock();
  }
  if (apiclient_index_ && !apiclient_index_->GetBaseUrl().empty()) {
    callback(boost::none);
    return {};
  }

  init_in_progress_ = true;

  auto cancel_function = [callback]() {
    callback(client::ApiError(client::ErrorCode::Cancelled,
                              "Operation cancelled.", true));
  };

  apiclient_blob_ = client::OlpClientFactory::Create(settings_);
  apiclient_config_ = client::OlpClientFactory::Create(settings_);
  apiclient_index_ = client::OlpClientFactory::Create(settings_);

  auto indexApi_callback = [=](ApiClientLookup::ApisResponse apis) {
    std::lock_guard<std::mutex> lg{self->mutex_};
    self->init_in_progress_ = false;
    if (!apis.IsSuccessful()) {
      callback(std::move(apis.GetError()));
      self->cond_var_.notify_one();
    } else {
      self->apiclient_index_->SetBaseUrl(apis.GetResult().at(0).GetBaseUrl());
      callback(boost::none);
      self->cond_var_.notify_all();
    }
  };

  auto indexApi_function = [=]() -> olp::client::CancellationToken {
    return ApiClientLookup::LookupApi(self->apiclient_index_, "index", "v1",
                                      self->catalog_, indexApi_callback);
  };

  auto blobApi_callback = [=](ApiClientLookup::ApisResponse apis) {
    if (!apis.IsSuccessful()) {
      callback(std::move(apis.GetError()));
      std::lock_guard<std::mutex> lg{self->mutex_};
      self->init_in_progress_ = false;
      self->cond_var_.notify_one();
      return;
    }

    self->apiclient_blob_->SetBaseUrl(apis.GetResult().at(0).GetBaseUrl());

    cancel_context->ExecuteOrCancelled(indexApi_function, cancel_function);
  };

  ul.unlock();

  return ApiClientLookup::LookupApi(self->apiclient_blob_, "blob", "v1",
                                    self->catalog_, blobApi_callback);
}

void IndexLayerClientImpl::CancelPendingRequests() {
  pending_requests_->CancelAll();
  tokenList_.CancelAll();
}

client::CancellableFuture<PublishIndexResponse>
IndexLayerClientImpl::PublishIndex(const model::PublishIndexRequest& request) {
  auto promise = std::make_shared<std::promise<PublishIndexResponse> >();
  auto cancel_token =
      PublishIndex(request, [promise](PublishIndexResponse response) {
        promise->set_value(std::move(response));
      });
  return client::CancellableFuture<PublishIndexResponse>(cancel_token, promise);
}

client::CancellationToken IndexLayerClientImpl::PublishIndex(
    model::PublishIndexRequest request, const PublishIndexCallback& callback) {
  auto publish_task =
      [=](client::CancellationContext context) -> PublishIndexResponse {
    if (!request.GetData()) {
      return client::ApiError(client::ErrorCode::InvalidArgument,
                              "Request data empty.");
    }

    if (request.GetLayerId().empty()) {
      return client::ApiError(client::ErrorCode::InvalidArgument,
                              "Request layer Id empty.");
    }

    const auto data_handle = GenerateUuid();

    auto blob_api_response = ApiClientLookup::LookupApiClient(
        catalog_, context, "blob", "v1", settings_);
    if (!blob_api_response.IsSuccessful()) {
      return blob_api_response.GetError();
    }

    auto index_api_response = ApiClientLookup::LookupApiClient(
        catalog_, context, "index", "v1", settings_);
    if (!index_api_response.IsSuccessful()) {
      return index_api_response.GetError();
    }

    auto layer_settings_response = catalog_settings_.GetLayerSettings(
        context, request.GetBillingTag(), request.GetLayerId());
    if (!layer_settings_response.IsSuccessful()) {
      return layer_settings_response.GetError();
    }
    auto layer_settings = layer_settings_response.GetResult();
    if (layer_settings.content_type.empty()) {
      auto errmsg = boost::format(
                        "Unable to find the Layer ID (%1%) "
                        "provided in the PublishIndexRequest in the "
                        "Catalog specified when creating "
                        "this IndexLayerClient instance.") %
                    request.GetLayerId();
      return client::ApiError(client::ErrorCode::InvalidArgument, errmsg.str());
    }

    auto blob_response = BlobApi::PutBlob(
        blob_api_response.GetResult(), request.GetLayerId(),
        layer_settings.content_type, layer_settings.content_encoding,
        data_handle, request.GetData(), request.GetBillingTag(), context);

    if (!blob_response.IsSuccessful()) {
      return blob_response.GetError();
    }

    auto index = request.GetIndex();
    index.SetId(data_handle);
    auto insert_indexes_response = IndexApi::InsertIndexes(
        index_api_response.GetResult(), index, request.GetLayerId(),
        request.GetBillingTag(), context);

    if (!insert_indexes_response.IsSuccessful()) {
      return insert_indexes_response.GetError();
    }
    model::ResponseOkSingle res;
    res.SetTraceID(data_handle);
    return PublishIndexResponse(std::move(res));
  };

  return AddTask(settings_.task_scheduler, pending_requests_,
                 std::move(publish_task), std::move(callback));
}

client::CancellableFuture<DeleteIndexDataResponse>
IndexLayerClientImpl::DeleteIndexData(
    const model::DeleteIndexDataRequest& request) {
  auto promise = std::make_shared<std::promise<DeleteIndexDataResponse> >();
  auto cancel_token =
      DeleteIndexData(request, [promise](DeleteIndexDataResponse response) {
        promise->set_value(std::move(response));
      });
  return client::CancellableFuture<DeleteIndexDataResponse>(cancel_token,
                                                            promise);
}

client::CancellationToken IndexLayerClientImpl::DeleteIndexData(
    const model::DeleteIndexDataRequest& request,
    const DeleteIndexDataCallback& callback) {
  if (request.GetLayerId().empty() || request.GetIndexId().empty()) {
    callback(DeleteIndexDataResponse(
        client::ApiError(client::ErrorCode::InvalidArgument,
                         "Request layer ID or Index Id is not defined.")));
    return client::CancellationToken();
  }

  auto layer_id = request.GetLayerId();
  auto index_id = request.GetIndexId();

  auto op_id = tokenList_.GetNextId();
  auto cancel_context = std::make_shared<client::CancellationContext>();
  auto self = shared_from_this();

  auto cancel_function = [=]() {
    self->tokenList_.RemoveTask(op_id);
    callback(DeleteIndexDataResponse(client::ApiError(
        client::ErrorCode::Cancelled, "Operation cancelled.", true)));
  };

  auto delete_index_data_function = [=]() -> client::CancellationToken {
    return BlobApi::deleteBlob(
        *self->apiclient_blob_, layer_id, index_id, boost::none,
        [=](DeleteBlobRespone response) {
          self->tokenList_.RemoveTask(op_id);
          if (!response.IsSuccessful()) {
            callback(DeleteBlobRespone(response.GetError()));
            return;
          }
          callback(DeleteBlobRespone(client::ApiNoResult()));
        });
  };

  auto init_api_client_callback =
      [=](boost::optional<client::ApiError> init_api_error) {
        if (init_api_error) {
          self->tokenList_.RemoveTask(op_id);
          callback(DeleteBlobRespone(init_api_error.get()));
          return;
        }

        cancel_context->ExecuteOrCancelled(delete_index_data_function,
                                           cancel_function);
      };

  auto init_api_client_function = [=]() -> client::CancellationToken {
    return self->InitApiClients(cancel_context, init_api_client_callback);
  };

  cancel_context->ExecuteOrCancelled(init_api_client_function, cancel_function);

  auto ret = client::CancellationToken(
      [cancel_context]() { cancel_context->CancelOperation(); });
  tokenList_.AddTask(op_id, ret);
  return ret;
}

client::CancellableFuture<UpdateIndexResponse>
IndexLayerClientImpl::UpdateIndex(const model::UpdateIndexRequest& request) {
  auto promise = std::make_shared<std::promise<UpdateIndexResponse> >();
  auto cancel_token =
      UpdateIndex(request, [promise](UpdateIndexResponse response) {
        promise->set_value(std::move(response));
      });
  return client::CancellableFuture<UpdateIndexResponse>(cancel_token, promise);
}

client::CancellationToken IndexLayerClientImpl::UpdateIndex(
    const model::UpdateIndexRequest& request,
    const UpdateIndexCallback& callback) {
  auto cancel_context = std::make_shared<client::CancellationContext>();
  auto self = shared_from_this();

  auto op_id = tokenList_.GetNextId();
  auto cancel_function = [=]() {
    self->tokenList_.RemoveTask(op_id);
    callback(UpdateIndexResponse(client::ApiError(
        client::ErrorCode::Cancelled, "Operation cancelled.", true)));
  };

  auto updateIndex_callback = [=](UpdateIndexResponse update_index_response) {
    self->tokenList_.RemoveTask(op_id);
    if (!update_index_response.IsSuccessful()) {
      callback(UpdateIndexResponse(update_index_response.GetError()));
      return;
    }
    callback(UpdateIndexResponse(client::ApiNoResult()));
  };

  auto UpdateIndex_function = [=]() -> client::CancellationToken {
    return IndexApi::performUpdate(*self->apiclient_index_, request,
                                   boost::none, updateIndex_callback);
  };

  cancel_context->ExecuteOrCancelled(
      [=]() -> client::CancellationToken {
        return self->InitApiClients(
            cancel_context, [=](boost::optional<client::ApiError> api_error) {
              if (api_error) {
                self->tokenList_.RemoveTask(op_id);
                callback(UpdateIndexResponse(api_error.get()));
                return;
              }
              cancel_context->ExecuteOrCancelled(UpdateIndex_function,
                                                 cancel_function);
            });
      },
      cancel_function);

  auto token = client::CancellationToken(
      [cancel_context]() { cancel_context->CancelOperation(); });
  tokenList_.AddTask(op_id, token);
  return token;
}

}  // namespace write
}  // namespace dataservice
}  // namespace olp

max_stars_repo_name: heremaps/here-olp-edge-sdk-cpp

max_issues_repo_name: heremaps/here-olp-sdk-cpp

max_forks_repo_name: heremaps/here-olp-edge-sdk-cpp


text:
#define BOOST_TEST_MODULE SolutionTest

#include "solution.hpp"

//#define BOOST_TEST_DYN_LINK
#include <boost/test/unit_test.hpp>

BOOST_AUTO_TEST_SUITE(SolutionSuite)

BOOST_AUTO_TEST_CASE(PlainTest1)
{
    vector<int> nums{1,3,4,2,2};
    int results = Solution().findDuplicate(nums);

    int expected = 2;

    BOOST_CHECK_EQUAL(results, expected);
}

BOOST_AUTO_TEST_CASE(PlainTest2)
{
    vector<int> nums{3,1,3,4,2};
    int results = Solution().findDuplicate(nums);

    int expected = 3;

    BOOST_CHECK_EQUAL(results, expected);
}

BOOST_AUTO_TEST_SUITE_END()

ext: cpp

max_stars_repo_name: johnhany/leetcode

max_issues_repo_name: johnhany/leetcode

max_forks_repo_name: johnhany/leetcode


text:
// Boost.Range library
//
//  Copyright Neil Groves 2014. Use, modification and
//  distribution is subject to the Boost Software License, Version
//  1.0. (See accompanying file LICENSE_1_0.txt or copy at
//  http://www.boost.org/LICENSE_1_0.txt)
//
//
// For more information, see http://www.boost.org/libs/range/
//
#include <boost/range/adaptor/indirected.hpp>
#include <boost/optional.hpp>
#include <boost/optional/optional_io.hpp>

#include <boost/test/test_tools.hpp>
#include <boost/test/unit_test.hpp>

#include <vector>

namespace boost
{
    namespace
    {
        void test_ticket_5811_indirected_optional()
        {
            std::vector<boost::optional<int> > v;
            std::vector<int> r;
            for (int i = 0; i < 10; ++i)
            {
                v.push_back(i);
                r.push_back(i);
            }
            BOOST_CHECK_EQUAL_COLLECTIONS(r.begin(), r.end(),
                                          v.begin(), v.end());
        }
    }
}

boost::unit_test::test_suite*
init_unit_test_suite(int argc, char* argv[])
{
    boost::unit_test::test_suite* test
        = BOOST_TEST_SUITE("RangeTestSuite.ticket_5811_indirected_optional");

    test->add(BOOST_TEST_CASE(&boost::test_ticket_5811_indirected_optional));

    return test;
}


text: #include <boost/spirit/include/phoenix_object.hpp>

ext: hpp

max_stars_repo_name: miathedev/BoostForArduino

max_issues_repo_name: miathedev/BoostForArduino

max_forks_repo_name: miathedev/BoostForArduino


text:
#include <sensor_msgs/Image.h>
#include <sensor_msgs/CompressedImage.h>
#include <sensor_msgs/image_encodings.h>
#include <cv_bridge/cv_bridge.h>
#include <opencv2/imgproc/imgproc.hpp>
#include <opencv2/opencv.hpp>
#include <boost/foreach.hpp>
#include <compressed_depth_image_transport/codec.h>
#include <compressed_depth_image_transport/compression_common.h>
#include "ros/ros.h"
#include <limits>
#include <string>
#include <vector>
#include <fstream>

using namespace std;
namespace enc = sensor_msgs::image_encodings;
using namespace cv;

double max_range = 10.0;

void decodeAndEmit(const sensor_msgs::CompressedImage& message);
void compressedImageCb(const sensor_msgs::CompressedImageConstPtr &c_im);

ros::Publisher image_pub;

int main(int argc, char **argv)
{
  std::string camera("/up");

  ros::init(argc, argv, "test_plane_marker");

  cout << "Usage: " << argv[0] << " [<camera_name> = \"up\"] [<max_range> = 10] \n";

  if (argc > 1) {
    camera = string(argv[1]);
  }
  cout << "Using camera: " << camera << endl;

  if (argc > 2) {
    max_range = atoi(argv[2]);
  } else
    max_range = 10.0;

  cout << "Maximum range: " << max_range << endl;

  ros::NodeHandle nh;
  std::string compressed_topic = camera + "/depth_registered/image_raw/compressedDepth";
  std::string uncompressed_topic = camera + "/depth_registered/image_raw";
  ros::Subscriber compressed_image_sub = nh.subscribe(compressed_topic, 1, &compressedImageCb);

  image_pub = nh.advertise<sensor_msgs::Image>(uncompressed_topic, 1);

  ros::spin();

  return 0;
}

void decodeAndEmit(const sensor_msgs::CompressedImage& message)
{

  cv_bridge::CvImagePtr cv_ptr(new cv_bridge::CvImage);

  // Copy message header
  cv_ptr->header = message.header;

  // Assign image encoding
  std::string image_encoding = message.format.substr(0, message.format.find(';'));
  cv_ptr->encoding = image_encoding;

  // Decode message data
  if (message.data.size() > sizeof(compressed_depth_image_transport::ConfigHeader))
  {

    // Read compression type from stream
    compressed_depth_image_transport::ConfigHeader compressionConfig;
    memcpy(&compressionConfig, &message.data[0], sizeof(compressionConfig));

    // Get compressed image data
    const std::vector<uint8_t> imageData(message.data.begin() + sizeof(compressionConfig), message.data.end());

    // Depth map decoding
    float depthQuantA, depthQuantB;

    // Read quantization parameters
    depthQuantA = compressionConfig.depthParam[0];
    depthQuantB = compressionConfig.depthParam[1];

    if (enc::bitDepth(image_encoding) == 32)
    {
      cv::Mat decompressed;
      try
      {
        // Decode image data
        decompressed = cv::imdecode(imageData, cv::IMREAD_UNCHANGED);
      }
      catch (cv::Exception& e)
      {
        ROS_ERROR("%s", e.what());
      }

      size_t rows = decompressed.rows;
      size_t cols = decompressed.cols;

      if ((rows > 0) && (cols > 0))
      {
        // cv_ptr->image = Mat(rows, cols, CV_32FC1);

        cv_bridge::CvImage img_bridge;
        img_bridge.image = decompressed;
        img_bridge.encoding = cv_ptr->encoding;
        img_bridge.header = message.header;

        image_pub.publish(img_bridge.toImageMsg());
      }
    }
  }
}

void compressedImageCb(const sensor_msgs::CompressedImageConstPtr &c_im) {
    decodeAndEmit(*c_im);
}


text:
#include <iostream>
#include <boost/program_options.hpp>
#include <csignal>
#include "UDP_server.hpp"
#include "TorrentDataBase.hpp"

namespace po = boost::program_options;

static void sig_handler(int sig) {
    (void)sig;
    UDP_server::Server::in_process = false;
}

int main(int argc, char *argv[]) {
    po::options_description description("Allowed options");
    description.add_options()
            ("help,h", "show help message")
            ("port,p", po::value<uint16_t>()->default_value(8000), "set servers port")
            ("interval,i", po::value<int32_t>()->default_value(10), "set request interval for client (in seconds)")
            ("silent,s", "disable info messages about requests");

    po::variables_map options;
    po::store(po::parse_command_line(argc, argv, description), options);
    po::notify(options);

    if (options.count("help")) {
        std::cout << description << "\n";
        return 0;
    }

    DataBase::TorrentDataBase db;
    UDP_server::Server server(db,
                              options["port"].as<uint16_t>(),
                              options["interval"].as<int32_t>(),
                              !options["silent"].empty());

    struct sigaction act{};
    act.sa_handler = sig_handler;
    sigaction(SIGINT, &act, nullptr);

    server.start();

    return 0;
}


text:
#define CATCH_CONFIG_MAIN

#include "CALPHADFreeEnergyFunctionsTernary.h"
#include "InterpolationType.h"

#include "catch.hpp"

#include <boost/optional/optional.hpp>
#include <boost/property_tree/json_parser.hpp>
#include <boost/property_tree/ptree.hpp>

#include <string>

#include <omp.h>

namespace pt = boost::property_tree;

TEST_CASE("CALPHAD ternary kks in a loop", "[ternary kks loop]")
{
#ifdef _OPENMP
    std::cout << "Run test with " << omp_get_max_threads() << " threads"
              << std::endl;
#endif

    Thermo4PFM::EnergyInterpolationType energy_interp_func_type
        = Thermo4PFM::EnergyInterpolationType::PBG;
    Thermo4PFM::ConcInterpolationType conc_interp_func_type
        = Thermo4PFM::ConcInterpolationType::PBG;

    const double Tmin     = 2990;
    const double Tmax     = 3020.;
    const int nTintervals = 10;
    const double deltaT   = (Tmax - Tmin) / (double)nTintervals;

    std::cout << "Read CALPHAD database..." << std::endl;
    pt::ptree calphad_db;
    try
    {
        pt::read_json("../thermodynamic_data/calphadMoNbTa.json", calphad_db);
    }
    catch (std::exception& e)
    {
        std::cerr << "exception caught: " << e.what() << std::endl;
    }

    boost::optional<pt::ptree&> newton_db;

    // initial guesses
    const double init_guess[4] = { 0.33, 0.38, 0.32, 0.33 };
    double nominalc[2]         = { 0.33, 0.33 };

    std::vector<double> cl(2 * (nTintervals + 1));
    std::vector<double> cs(2 * (nTintervals + 1));

    Thermo4PFM::CALPHADFreeEnergyFunctionsTernary* cafe
        = new Thermo4PFM::CALPHADFreeEnergyFunctionsTernary(calphad_db,
            newton_db, energy_interp_func_type, conc_interp_func_type);

    {
        // serial loop
        for (int i = 0; i < nTintervals + 1; i++)
        {
            const double temperature = Tmin + i * deltaT;

            double phi = 0.5;

            double conc[4] = { init_guess[0], init_guess[1], // liquid
                init_guess[2], init_guess[3] }; // solid

            // compute equilibrium concentrations in each phase
            cafe->computePhaseConcentrations(temperature, nominalc, &phi, conc);

            std::cout << "Temperature = " << temperature << std::endl;
            std::cout << "Concentrations: cl = (" << conc[0] << "." << conc[1]
                      << ")"
                      << " and cs = (" << conc[2] << "," << conc[3] << ")"
                      << std::endl;

            cl[2 * i]     = conc[0];
            cl[2 * i + 1] = conc[1];
            cs[2 * i]     = conc[2];
            cs[2 * i + 1] = conc[3];
        }
    }

// parallel loop
#pragma omp parallel for
    for (int i = 0; i < nTintervals + 1; i++)
    {
        const double temperature = Tmin + i * deltaT;
        double phi               = 0.5;

        double conc[4] = { init_guess[0], init_guess[1], // liquid
            init_guess[2], init_guess[3] }; // solid

        // compute equilibrium concentrations in each phase
        cafe->computePhaseConcentrations(temperature, nominalc, &phi, &conc[0]);

        CHECK(conc[0] == Approx(cl[2 * i]).margin(1.e-6));
        CHECK(conc[1] == Approx(cl[2 * i + 1]).margin(1.e-6));
        CHECK(conc[2] == Approx(cs[2 * i]).margin(1.e-6));
        CHECK(conc[3] == Approx(cs[2 * i + 1]).margin(1.e-6));
    }

#ifdef HAVE_OPENMP_OFFLOAD
    double* xdev = new double[4 * (nTintervals + 1)];
// clang-format off
#pragma omp target map(to : cafe [0:1],     \
                            init_guess[:4]) \
                   map(from : xdev[:4 * (nTintervals + 1)])
// clang-format on
#pragma omp parallel for
    for (int i = 0; i < nTintervals + 1; i++)
    {
        const double temperature = Tmin + i * deltaT;

        double phi = 0.5;

        xdev[4 * i + 0] = init_guess[0];
        xdev[4 * i + 1] = init_guess[1]; // liquid
        xdev[4 * i + 2] = init_guess[2];
        xdev[4 * i + 3] = init_guess[3]; // solid
        // compute equilibrium concentrations in each phase
        cafe->computePhaseConcentrations(
            temperature, nominalc, &phi, &xdev[4 * i]);
    }

    for (int i = 0; i < nTintervals + 1; i++)
    {
        std::cout << "Device: x=" << xdev[4 * i] << "," << xdev[4 * i + 1]
                  << "," << xdev[4 * i + 2] << "," << xdev[4 * i + 3]
                  << std::endl;
        CHECK(xdev[4 * i + 0] == Approx(cl[2 * i]).margin(1.e-6));
        CHECK(xdev[4 * i + 1] == Approx(cl[2 * i + 1]).margin(1.e-6));
        CHECK(xdev[4 * i + 2] == Approx(cs[2 * i]).margin(1.e-6));
        CHECK(xdev[4 * i + 3] == Approx(cs[2 * i + 1]).margin(1.e-6));
    }

    delete[] xdev;
#endif

    delete cafe;
}

ext: cc


text: #include <boost/format/parsing.hpp>


text:
#include "hg_intersect.h"

#include <vector>
#ifndef HAVE_OLD_CPP
# include <unordered_map>
#else
# include <tr1/unordered_map>
namespace std { using std::tr1::unordered_map; }
#endif
#include "fast_lexical_cast.hpp"
#include <boost/functional/hash.hpp>

#include "verbose.h"
#include "tdict.h"
#include "hg.h"
#include "trule.h"
#include "wordid.h"
#include "bottom_up_parser.h"

using boost::lexical_cast;
using namespace std;

struct RuleFilter {
  unordered_map<vector<WordID>, bool, boost::hash<vector<WordID> > > exists_;
  bool true_lattice;
  RuleFilter(const Lattice& target, unsigned max_phrase_size) {
    true_lattice = false;
    for (unsigned i = 0; i < target.size(); ++i) {
      vector<WordID> phrase;
      const unsigned lim = min(static_cast<unsigned>(target.size()), i + max_phrase_size);
      for (unsigned j = i; j < lim; ++j) {
        if (target[j].size() > 1) { true_lattice = true; break; }
        phrase.push_back(target[j][0].label);
        exists_[phrase] = true;
      }
    }
    vector<WordID> sos(1, TD::Convert("<s>"));
    exists_[sos] = true;
  }
  bool operator()(const TRule& r) const {
    // TODO do some smarter filtering for lattices
    if (true_lattice) return false;  // don't filter "true lattice" input
    const vector<WordID>& e = r.e();
    for (unsigned i = 0; i < e.size(); ++i) {
      if (e[i] <= 0) continue;
      vector<WordID> phrase;
      for (unsigned j = i; j < e.size(); ++j) {
        if (e[j] <= 0) break;
        phrase.push_back(e[j]);
        if (exists_.count(phrase) == 0) return true;
      }
    }
    return false;
  }
};

static bool FastLinearIntersect(const Lattice& target, Hypergraph* hg) {
  if (!SILENT) cerr << "  Fast linear-chain intersection...\n";
  vector<bool> prune(hg->edges_.size(), false);
  set<int> cov;
  map<const TRule*, TRulePtr> inverted_rules;
  for (unsigned i = 0; i < prune.size(); ++i) {
    Hypergraph::Edge& edge = hg->edges_[i];
    if (edge.Arity() == 0) {
      const int trg_index = edge.prev_i_;
      const WordID trg = target[trg_index][0].label;
      assert(edge.rule_->EWords() == 1);
      TRulePtr& inv_rule = inverted_rules[edge.rule_.get()];
      if (!inv_rule) {
        inv_rule.reset(new TRule(*edge.rule_));
        inv_rule->e_.swap(inv_rule->f_);
      }
      prune[i] = (edge.rule_->e_[0] != trg);
      if (!prune[i]) {
        cov.insert(trg_index);
        swap(edge.prev_i_, edge.i_);
        swap(edge.prev_j_, edge.j_);
        edge.rule_.swap(inv_rule);
      }
    }
  }
  hg->PruneEdges(prune, true);
  return (cov.size() == target.size());
}

namespace HG {

bool Intersect(const Lattice& target, Hypergraph* hg) {
  // there are a number of faster algorithms available for restricted
  // classes of hypergraph and/or target.
  if (hg->IsLinearChain() && target.IsSentence())
    return FastLinearIntersect(target, hg);

  vector<bool> rem(hg->edges_.size(), false);
  const RuleFilter filter(target, 9999);   // TODO make configurable
  for (unsigned i = 0; i < rem.size(); ++i)
    rem[i] = filter(*hg->edges_[i].rule_);
  hg->PruneEdges(rem, true);

  const unsigned nedges = hg->edges_.size();
  const unsigned nnodes = hg->nodes_.size();

  TextGrammar* g = new TextGrammar;
  GrammarPtr gp(g);
  vector<int> cats(nnodes);
  // each node in the translation forest becomes a "non-terminal" in the new
  // grammar, create the labels here
  const string kSEP = "_";
  for (unsigned i = 0; i < nnodes; ++i) {
    string pstr = "CAT";
    if (hg->nodes_[i].cat_ < 0)
      pstr = TD::Convert(-hg->nodes_[i].cat_);
    cats[i] = TD::Convert(pstr + kSEP + lexical_cast<string>(i)) * -1;
  }

  // construct the grammar
  for (unsigned i = 0; i < nedges; ++i) {
    const Hypergraph::Edge& edge = hg->edges_[i];
    const vector<WordID>& tgt = edge.rule_->e();
    const vector<WordID>& src = edge.rule_->f();
    TRulePtr rule(new TRule);
    rule->prev_i = edge.i_;
    rule->prev_j = edge.j_;
    rule->lhs_ = cats[edge.head_node_];
    vector<WordID>& f = rule->f_;
    vector<WordID>& e = rule->e_;
    f.resize(tgt.size());   // swap source and target, since the parser
    e.resize(src.size());   // parses using the source side!
    Hypergraph::TailNodeVector tn(edge.tail_nodes_.size());
    int ntc = 0;
    for (unsigned j = 0; j < tgt.size(); ++j) {
      const WordID& cur = tgt[j];
      if (cur > 0) {
        f[j] = cur;
      } else {
        tn[-cur] = -ntc;
        ++ntc;
        f[j] = cats[edge.tail_nodes_[-cur]];
      }
    }
    ntc = 0;
    for (unsigned j = 0; j < src.size(); ++j) {
      const WordID& cur = src[j];
      if (cur > 0) {
        e[j] = cur;
      } else {
        e[j] = tn[ntc++];
      }
    }
    rule->scores_ = edge.feature_values_;
    rule->parent_rule_ = edge.rule_;
    rule->ComputeArity();
    //cerr << "ADD: " << rule->AsString() << endl;

    g->AddRule(rule);
  }
  g->SetMaxSpan(target.size() + 1);
  const string& new_goal = TD::Convert(cats.back() * -1);
  vector<GrammarPtr> grammars(1, gp);
  Hypergraph tforest;
  ExhaustiveBottomUpParser parser(new_goal, grammars);
  if (!parser.Parse(target, &tforest))
    return false;
  else
    hg->swap(tforest);
  return true;
}

}

max_stars_repo_name: kho/cdec

max_issues_repo_name: kho/cdec

max_forks_repo_name: kho/cdec


text:
//rqt plugin for tuning parameters
//Author: Sebastian Schüller

#include <pluginlib/class_list_macros.h>
#include <boost/iterator/iterator_concepts.hpp>

#include <config_server/Save.h>
#include <config_server/Load.h>

#include "parametertuner.h"
#include "parameteritem.h"
#include <config_server/parameterclient.h>

namespace parametertuner
{

Parametertuner::Parametertuner()
 : m_useJoystick(false)
{}

Parametertuner::~Parametertuner()
{
}

void Parametertuner::initPlugin(qt_gui_cpp::PluginContext& context)
{
	QWidget* w = new QWidget();
	m_ui.setupUi(w);

	connect(m_ui.joystick_button, SIGNAL(toggled(bool)), this, SLOT(handleJoystickButton()));
	connect(m_ui.save_button, SIGNAL(clicked(bool)), this, SLOT(save()));
	connect(m_ui.reset_button, SIGNAL(clicked(bool)), this, SLOT(reset()));

	m_sub_paramList = getNodeHandle().subscribe("/config_server/parameter_list", 1, &Parametertuner::handleList, this);
	m_sub_joystick = getNodeHandle().subscribe("/joy", 1, &Parametertuner::handleJoystickInput, this);
	connect(this, SIGNAL(updateRequested()), this, SLOT(update()), Qt::QueuedConnection);
	connect(this, SIGNAL(moveSelectionRequested(int)), this, SLOT(moveSelection(int)), Qt::QueuedConnection);
	connect(this, SIGNAL(ValueChangeRequested(int)), this, SLOT(ChangeValue(int)), Qt::QueuedConnection);

	m_ui.parameter_root_widget->setColumnCount(2);
	m_ui.parameter_root_widget->setColumnWidth(0, 200);

	context.addWidget(w);
}

void Parametertuner::handleList(const config_server::ParameterListConstPtr& list)
{
	QMutexLocker locker(&m_mutex);
	m_list = list;
	updateRequested();
}

void Parametertuner::deleteWidget(QTreeWidgetItem* item)
{
	QWidget* w = m_ui.parameter_root_widget->itemWidget(item, 1);
	m_ui.parameter_root_widget->removeItemWidget(item, 1);

	if(w)
		delete w;

	for(int i = 0; i < item->childCount(); ++i)
		deleteWidget(item->child(i));
}

void Parametertuner::update()
{
	deleteWidget(m_ui.parameter_root_widget->invisibleRootItem());
	m_ui.parameter_root_widget->clear();

	qApp->processEvents();

	config_server::ParameterClient* client = config_server::ParameterClient::instance();
	client->cork();

	QMutexLocker locker (&m_mutex);
	for(size_t i = 0; i < m_list->parameters.size(); i++)
	{
		QString param = QString::fromStdString(m_list->parameters[i].name);
		insertParameter(param, 0, m_list->parameters[i]);
	}

	client->uncork();
}

void Parametertuner::insertParameter(QString param, QTreeWidgetItem* ancestor, const config_server::ParameterDescription& description)
{
	if (param.isEmpty())
		return;

	QString levelParam, strippedParam;
	bool isLeaf;
	levelParam = param.section("/", 1, 1);
	strippedParam = param.section("/", 2);
	isLeaf = strippedParam.isEmpty();
	if (!isLeaf)
		strippedParam = "/" + strippedParam;

	QTreeWidgetItem* nextItem = 0;
	if (!ancestor)
	{
		QList<QTreeWidgetItem *> topLevelItems;
		topLevelItems = m_ui.parameter_root_widget->findItems(levelParam, 0);
		if (topLevelItems.isEmpty())
		{
			QTreeWidgetItem* newItem = 0;
			newItem = new QTreeWidgetItem();
			newItem->setText(0, levelParam);
			m_ui.parameter_root_widget->addTopLevelItem(newItem);
			nextItem  = newItem;
		}
		else
		{
			nextItem = topLevelItems.at(0);
		}
		insertParameter(strippedParam, nextItem, description);
		return;
	}

	int childCount = ancestor->childCount();
	int i;
	for (i = 0; i < childCount; i++)
	{
		if (levelParam == ancestor->child(i)->text(0))
		{
			insertParameter(strippedParam, ancestor->child(i), description);
			return;
		}
	}

	if (isLeaf)
		nextItem = insertParameterNode(description, ancestor);
	else
		nextItem = new QTreeWidgetItem(ancestor);

	nextItem->setText(0, levelParam);
	insertParameter(strippedParam, nextItem, description);
	return;

}

QTreeWidgetItem* Parametertuner::insertParameterNode(const config_server::ParameterDescription& description, QTreeWidgetItem* ancestor)
{
	QTreeWidgetItem* newItem = new QTreeWidgetItem(ancestor);

	QWidget* newWidget = 0;
	QString type = QString::fromStdString(description.type);
	if (type == "int")
		newWidget = new IntParameterWidget(getNodeHandle(), description);
	else if (type == "string")
		newWidget = new StringParameterWidget(getNodeHandle(), description);
	else if (type == "float")
		newWidget = new FloatParameterWidget(getNodeHandle(), description);
	else if (type == "bool")
		newWidget = new BoolParameterWidget(getNodeHandle(), description);

	if (newWidget != 0)
		m_ui.parameter_root_widget->setItemWidget(newItem, 1, newWidget);

	return newItem;
}

void Parametertuner::save()
{
	config_server::Save srv;

	if (!ros::service::call("/config_server/save",srv))
	{
		m_ui.save_button->setText("saving failed");
		ROS_WARN("Could not call config_server service 'save'!");
		return;
	}
	m_ui.save_button->setText("save");
}

void Parametertuner::reset()
{
	config_server::Load srv;

	srv.request.filename = "";

	if (!ros::service::call("/config_server/load", srv))
	{
		m_ui.reset_button->setText("failed");
		ROS_WARN("Could not call config_server service 'load'!");
	}
	m_ui.reset_button->setText("reset");
}

void Parametertuner::handleJoystickButton()
{
	m_useJoystick = m_ui.joystick_button->isChecked();
}

void Parametertuner::handleJoystickInput(const sensor_msgs::JoyConstPtr& joy)
{
	if (!m_useJoystick)
		return;

	int buttonUp = 4;
	int buttonDown = 6;
	int buttonLeft = 5;
	int buttonRight = 7;

	if (m_buttonUp && !joy->buttons[buttonUp])
		moveSelectionRequested(UP);
	m_buttonUp = joy->buttons[buttonUp];

	if (m_buttonDown && !joy->buttons[buttonDown])
		moveSelectionRequested(DOWN);
	m_buttonDown = joy->buttons[buttonDown];

	if (m_buttonDec && !joy->buttons[buttonLeft])
		ValueChangeRequested(LEFT);
	m_buttonDec = joy->buttons[buttonLeft];

	if (m_buttonInc && !joy->buttons[buttonRight])
		ValueChangeRequested(RIGHT);
	m_buttonInc = joy->buttons[buttonRight];

}

void Parametertuner::moveSelection(int dir)
{
	QTreeWidgetItem* thisItem = getSelectedItem();
	if (!thisItem)
	{
		m_ui.parameter_root_widget->topLevelItem(0)->setSelected(true);
		return;
	}
	QTreeWidgetItem* parent = thisItem->parent();
	QTreeWidgetItem* nextItem;

	if (!parent)
	{
		parent = m_ui.parameter_root_widget->invisibleRootItem();
	}
	int thisItemIndex = parent->indexOfChild(thisItem);
	if (thisItem->isExpanded() && dir == DOWN)
	{
		nextItem = thisItem->child(0);
		updateSelection(thisItem, nextItem);
		return;
	}
	else if (!parent->child(thisItemIndex + dir))
	{
		updateSelection(thisItem, parent);
		return;
	}
	else
	{
		nextItem = parent->child(thisItemIndex + dir);
		updateSelection(thisItem, nextItem);
		return;
	}

}

QTreeWidgetItem* Parametertuner::getSelectedItem()
{
	QList<QTreeWidgetItem *> selectList = m_ui.parameter_root_widget->selectedItems();
	if (selectList.size() == 0)
	{
		return 0;
	}
	else
		return selectList.at(0);
}

void Parametertuner::updateSelection(QTreeWidgetItem* old, QTreeWidgetItem* next)
{
	old->setSelected(false);
	next->setSelected(true);
	m_ui.parameter_root_widget->scrollToItem(next);
}

void Parametertuner::ChangeValue(int dir)
{
	QTreeWidgetItem* thisItem;
	if (!(thisItem = getSelectedItem()))
		return;

	if (thisItem->childCount() != 0)
	{
		if (dir == RIGHT && (!thisItem->isExpanded()))
			thisItem->setExpanded(true);
		else if (dir == LEFT && thisItem->isExpanded())
			thisItem->setExpanded(false);
		return;
	}
	ParameterWidgetBase* param;
	param = (ParameterWidgetBase *)m_ui.parameter_root_widget->itemWidget(thisItem, 1);
	if (!param)
		return;

	if (dir == LEFT)
		param->DecValue();
	else
		param->IncValue();
}

}

PLUGINLIB_EXPORT_CLASS(parametertuner::Parametertuner, rqt_gui_cpp::Plugin)

max_stars_repo_name: cxdcxd/NAVbot

max_issues_repo_name: cxdcxd/NAVbot

max_forks_repo_name: cxdcxd/NAVbot


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

#include <iostream>
#include <boost/python.hpp>
#include <cv_bridge/cv_bridge.h>
#include <Python.h>

#include <numpy/ndarrayobject.h>

#include <opencv2/core/core.hpp>

#include <opencv2/imgproc/types_c.h>

PyObject *mod_opencv;

using namespace cv;
namespace bp = boost::python;

// These are sucky, sketchy versions of the real things in OpenCV Python,
// inferior in every way.

static int failmsg(const char *fmt, ...)
{
  char str[1000];

  va_list ap;
  va_start(ap, fmt);
  vsnprintf(str, sizeof(str), fmt, ap);
  va_end(ap);

  PyErr_SetString(PyExc_TypeError, str);
  return 0;
}

// Taken from http://stackoverflow.com/questions/19136944/call-c-opencv-functions-from-python-send-a-cv-mat-to-c-dll-which-is-usi

static size_t REFCOUNT_OFFSET = ( size_t )&((( PyObject* )0)->ob_refcnt ) +
( 0x12345678 != *( const size_t* )"\x78\x56\x34\x12\0\0\0\0\0" )*sizeof( int );

static inline PyObject* pyObjectFromRefcount( const int* refcount )
{
return ( PyObject* )(( size_t )refcount - REFCOUNT_OFFSET );
}

static inline int* refcountFromPyObject( const PyObject* obj )
{
return ( int* )(( size_t )obj + REFCOUNT_OFFSET );
}

class NumpyAllocator : public cv::MatAllocator
{
public:
NumpyAllocator( ) { }
~NumpyAllocator( ) { }

void allocate( int dims, const int* sizes, int type, int*& refcount,
uchar*& datastart, uchar*& data, size_t* step );

void deallocate( int* refcount, uchar* datastart, uchar* data );
};

#if PYTHON3
int doImport( )
{
    import_array( );
}
#else
void doImport( )
{
    import_array( );
}
#endif

void NumpyAllocator::allocate( int dims, const int* sizes, int type, int*& refcount, uchar*& datastart, uchar*& data, size_t* step )
{
    int depth = CV_MAT_DEPTH( type );
    int cn = CV_MAT_CN( type );
    const int f = ( int )( sizeof( size_t )/8 );
    int typenum = depth == CV_8U ? NPY_UBYTE : depth == CV_8S ? NPY_BYTE :
                  depth == CV_16U ? NPY_USHORT : depth == CV_16S ? NPY_SHORT :
                  depth == CV_32S ? NPY_INT : depth == CV_32F ? NPY_FLOAT :
                  depth == CV_64F ? NPY_DOUBLE : f*NPY_ULONGLONG + (f^1)*NPY_UINT;
    int i;
    npy_intp _sizes[CV_MAX_DIM+1];
    for( i = 0; i < dims; i++ )
        _sizes[i] = sizes[i];
    if( cn > 1 )
    {
    /*if( _sizes[dims-1] == 1 )
         _sizes[dims-1] = cn;
    else*/
        _sizes[dims++] = cn;
    }
    PyObject* o = PyArray_SimpleNew( dims, _sizes, typenum );
    if( !o )
    CV_Error_(CV_StsError, ("The numpy array of typenum=%d, ndims=%d can not be created", typenum, dims));
    refcount = refcountFromPyObject(o);
    npy_intp* _strides = PyArray_STRIDES(o);
    for( i = 0; i < dims - (cn > 1); i++ )
        step[i] = (size_t)_strides[i];
    datastart = data = (uchar*)PyArray_DATA(o);

}

void NumpyAllocator::deallocate( int* refcount, uchar* datastart, uchar* data )
{
    if( !refcount )
       return;
    PyObject* o = pyObjectFromRefcount(refcount);
    Py_INCREF(o);
    Py_DECREF(o);
}

// Declare the object
NumpyAllocator *g_numpyAllocator;

int convert_to_CvMat2(const PyObject* o, cv::Mat& m)
{
    // to avoid PyArray_Check() to crash even with valid array
    doImport( );

    if(!o || o == Py_None)
    {
        if( !m.data )
            m.allocator = g_numpyAllocator;
        return true;
    }

    if( !PyArray_Check(o) )
    {
        failmsg("Not a numpy array");
        return false;
    }

    // NPY_LONG (64 bit) is converted to CV_32S (32 bit)
    int typenum = PyArray_TYPE(o);
    int type = typenum == NPY_UBYTE ? CV_8U : typenum == NPY_BYTE ? CV_8S :
        typenum == NPY_USHORT ? CV_16U : typenum == NPY_SHORT ? CV_16S :
        typenum == NPY_INT || typenum == NPY_LONG ? CV_32S :
        typenum == NPY_FLOAT ? CV_32F :
        typenum == NPY_DOUBLE ? CV_64F : -1;

    if( type < 0 )
    {
        failmsg("data type = %d is not supported", typenum);
        return false;
    }

    int ndims = PyArray_NDIM(o);
    if(ndims >= CV_MAX_DIM)
    {
        failmsg("dimensionality (=%d) is too high", ndims);
        return false;
    }

    int size[CV_MAX_DIM+1];
    size_t step[CV_MAX_DIM+1], elemsize = CV_ELEM_SIZE1(type);
    const npy_intp* _sizes = PyArray_DIMS(o);
    const npy_intp* _strides = PyArray_STRIDES(o);
    bool transposed = false;

    for(int i = 0; i < ndims; i++)
    {
        size[i] = (int)_sizes[i];
        step[i] = (size_t)_strides[i];
    }

    if( ndims == 0 || step[ndims-1] > elemsize ) {
        size[ndims] = 1;
        step[ndims] = elemsize;
        ndims++;
    }

    if( ndims >= 2 && step[0] < step[1] )
    {
        std::swap(size[0], size[1]);
        std::swap(step[0], step[1]);
        transposed = true;
    }

    if( ndims == 3 && size[2] <= CV_CN_MAX && step[1] == elemsize*size[2] )
    {
        ndims--;
        type |= CV_MAKETYPE(0, size[2]);
    }

    if( ndims > 2 )
    {
        failmsg("more than 2 dimensions");
        return false;
    }

    m = cv::Mat(ndims, size, type, PyArray_DATA(o), step);

    if( m.data )
    {
        //m.refcount = refcountFromPyObject(o);
        m.addref(); // protect the original numpy array from deallocation
        // (since Mat destructor will decrement the reference counter)
    };
    m.allocator = g_numpyAllocator;

    if( transposed )
    {
        cv::Mat tmp;
        tmp.allocator = g_numpyAllocator;
        transpose(m, tmp);
        m = tmp;
    }
    return true;
}

bp::object
cvtColor2Wrap(bp::object obj_in, const std::string & encoding_in, const std::string & encoding_out) {
  // Convert the Python input to an image
  cv::Mat mat_in;
  convert_to_CvMat2(obj_in.ptr(), mat_in);

  // Call cv_bridge for color conversion
  cv_bridge::CvImagePtr cv_image(new cv_bridge::CvImage(std_msgs::Header(), encoding_in, mat_in));

  cv::Mat mat = cv_bridge::cvtColor(cv_image, encoding_out)->image;

  npy_intp dims[] = {mat.rows, mat.cols, mat.channels()};

  PyObject *res = 0 ;
  if (mat.depth() == CV_8U)
      res = PyArray_SimpleNew(3, dims, NPY_UBYTE);
  else if (mat.depth() == CV_8S)
      res = PyArray_SimpleNew(3, dims, NPY_BYTE);
  else if (mat.depth() == CV_16S)
      res = PyArray_SimpleNew(3, dims, NPY_SHORT);
  else if (mat.depth() == CV_16U)
      res = PyArray_SimpleNew(3, dims, NPY_USHORT);
  else if (mat.depth() == CV_32S)
      res = PyArray_SimpleNew(3, dims, NPY_INT);
  else if (mat.depth() == CV_32F)
      res = PyArray_SimpleNew(3, dims, NPY_CFLOAT);
  else if (mat.depth() == CV_64F)
      res = PyArray_SimpleNew(3, dims, NPY_CDOUBLE);

  std::memcpy(PyArray_DATA((PyArrayObject*)res), mat.data, mat.step*mat.rows);

  return bp::object(boost::python::handle<>(res));
}

BOOST_PYTHON_MODULE(cv_bridge_boost)
{
  mod_opencv = PyImport_ImportModule("cv");

  // Wrap the function to get encodings as OpenCV types
  boost::python::def("getCvType", cv_bridge::getCvType);
  boost::python::def("cvtColor2", cvtColor2Wrap);
}

max_stars_repo_name: Engietoday/ralph

max_issues_repo_name: Engietoday/ralph

max_forks_repo_name: Engietoday/ralph


text:
// Copyright David Abrahams, Daniel Wallin 2003.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)

#ifndef BOOST_PARAMETER_AUX_PACK_PREDICATE_HPP
#define BOOST_PARAMETER_AUX_PACK_PREDICATE_HPP

namespace boost { namespace parameter { namespace aux {

    // helper for get_predicate<...>, below
    template <typename T>
    struct get_predicate_or_default
    {
        typedef T type;
    };

    // helper for predicate<...>, below
    template <typename T>
    struct get_predicate
      : ::boost::parameter::aux
        ::get_predicate_or_default<typename T::predicate>
    {
    };
}}} // namespace boost::parameter::aux

#include <boost/parameter/aux_/use_default.hpp>
#include <boost/parameter/aux_/always_true_predicate.hpp>

namespace boost { namespace parameter { namespace aux {

    template <>
    struct get_predicate_or_default< ::boost::parameter::aux::use_default>
    {
        typedef ::boost::parameter::aux::always_true_predicate type;
    };
}}} // namespace boost::parameter::aux

#include <boost/parameter/required.hpp>
#include <boost/parameter/optional.hpp>
#include <boost/parameter/config.hpp>

#if defined(BOOST_PARAMETER_CAN_USE_MP11)
#include <boost/mp11/integral.hpp>
#include <boost/mp11/utility.hpp>
#else
#include <boost/mpl/bool.hpp>
#include <boost/mpl/if.hpp>
#include <boost/mpl/eval_if.hpp>
#include <boost/mpl/identity.hpp>
#endif

namespace boost { namespace parameter { namespace aux {

    template <typename T>
#if defined(BOOST_PARAMETER_CAN_USE_MP11)
    using predicate = ::boost::mp11::mp_if<
        ::boost::mp11::mp_if<
            ::boost::parameter::aux::is_optional<T>
          , ::boost::mp11::mp_true
          , ::boost::parameter::aux::is_required<T>
        >
      , ::boost::parameter::aux::get_predicate<T>
      , ::boost::mp11::mp_identity<
            ::boost::parameter::aux::always_true_predicate
        >
    >;
#else
    struct predicate
      : ::boost::mpl::eval_if<
            typename ::boost::mpl::if_<
                ::boost::parameter::aux::is_optional<T>
              , ::boost::mpl::true_
              , ::boost::parameter::aux::is_required<T>
            >::type
          , ::boost::parameter::aux::get_predicate<T>
          , ::boost::mpl::identity<
                ::boost::parameter::aux::always_true_predicate
            >
        >
    {
    };
#endif  // BOOST_PARAMETER_CAN_USE_MP11
}}} // namespace boost::parameter::aux

#endif  // include guard


text:
#include <gmock/gmock.h>
#include <gtest/gtest.h>

// tr064
#include <tr064/RootDevice.hh>
#include <tr064/Device.hh>
#include <tr064/Service.hh>
#include <tr064/ServiceAction.hh>

#include <boost/property_tree/ptree.hpp>
#include <boost/property_tree/json_parser.hpp>

#include <vector>
#include <string>
#include <sstream>
#include <iostream>

using namespace tr064;

//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
//  DEVICE tests
//------------------------------------------------------------------------------

TEST(SerializeJsonTest, SerializeDeviceOkWithoutChildren)
{
  std::vector<std::string> dev_props { "the name", "the model name", "the model desc", "the friendly name"};
  Device dev(dev_props[0], dev_props[1], dev_props[2], dev_props[3]);

  boost::property_tree::ptree parent;

  dev.serialize_json(parent);

  std::stringstream ss;
  boost::property_tree::json_parser::write_json(ss, parent);

  auto to_serialize = ss.str();

  EXPECT_NE(std::string::npos, to_serialize.find("name"));
  EXPECT_EQ(std::string::npos, to_serialize.find("services"));
  EXPECT_EQ(std::string::npos, to_serialize.find("devices"));

  for (auto& p : dev_props )
  {
    EXPECT_NE(std::string::npos, to_serialize.find(p));
  }
}

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

TEST(SerializeJsonTest, SerializeDeviceOkWithChildren)
{
  std::vector<std::string> dev_props { "the name", "the model name", "the model desc", "the friendly name"};
  Device dev(dev_props[0], dev_props[1], dev_props[2], dev_props[3]);

  std::vector<std::string> s1_props {
        "s1 type",
        "s1 name",
        "s1 id",
        "s1 control url",
        "s1 evne url",
        "s1 scpd url"};
  Service::Ptr service1(
      new Service(s1_props[0], s1_props[1], s1_props[2], s1_props[3], s1_props[4], s1_props[5]));
  dev.add_service(service1);

  std::vector<std::string> s2_props {
        "s2 type",
        "s2 name",
        "s2 id",
        "s2 control url",
        "s2 evne url",
        "s2 scpd url"};
  Service::Ptr service2(
      new Service(s2_props[0], s2_props[1], s2_props[2], s2_props[3], s2_props[4], s2_props[5]));
  dev.add_service(service2);

  std::vector<std::string> sub_dev_props { "subdev the name", "subdev the model_name", "subdev the model desc", "subdev the friendly name"};
  Device::Ptr sub_dev(new Device(sub_dev_props[0], sub_dev_props[1], sub_dev_props[2], sub_dev_props[3]));
  dev.add_device(sub_dev);

  boost::property_tree::ptree parent;

  dev.serialize_json(parent);

  std::stringstream ss;
  boost::property_tree::json_parser::write_json(ss, parent);

  auto to_serialize = ss.str();

  EXPECT_NE(std::string::npos, to_serialize.find("name"));
  EXPECT_NE(std::string::npos, to_serialize.find("services"));
  EXPECT_NE(std::string::npos, to_serialize.find("devices"));

  for (auto& p : dev_props )
  {
    EXPECT_NE(std::string::npos, to_serialize.find(p));
  }
  for (auto& p : s1_props )
  {
    EXPECT_NE(std::string::npos, to_serialize.find(p));
  }
  for (auto& p : s2_props )
  {
    EXPECT_NE(std::string::npos, to_serialize.find(p));
  }
  for (auto& p : sub_dev_props )
  {
    EXPECT_NE(std::string::npos, to_serialize.find(p));
  }
}

//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
//  SERVICE tests
//------------------------------------------------------------------------------

TEST(SerializeJsonTest, SerializeServiceOkWithChildren)
{
  const std::string s_type = "s1 type";
  const std::string s_name = "s1 name";
  const std::string s_id = "s1 id";
  const std::string s_ctrl_url = "s1 control url";
  const std::string s_event_url = "s1 event url";
  const std::string s_scpd_url = "s1 scpd url";
  const std::string a1_name = "action 1";
  const std::string a2_name = "action 2";

  Service s(
        s_type,
        s_name,
        s_id,
        s_ctrl_url,
        s_event_url,
        s_scpd_url);
  ServiceAction::Ptr action1(new ServiceAction(a1_name));
  s.add_action(action1);
  ServiceAction::Ptr action2(new ServiceAction(a2_name));
  s.add_action(action2);

  boost::property_tree::ptree parent;

  s.serialize_json(parent);

  std::stringstream ss;
  boost::property_tree::json_parser::write_json(ss, parent);

  auto to_serialize = ss.str();

  EXPECT_NE(std::string::npos, to_serialize.find("name"));
  EXPECT_NE(std::string::npos, to_serialize.find(s_type));
  EXPECT_NE(std::string::npos, to_serialize.find(s_name));
  EXPECT_NE(std::string::npos, to_serialize.find(s_id));
  EXPECT_NE(std::string::npos, to_serialize.find(s_ctrl_url));
  EXPECT_NE(std::string::npos, to_serialize.find(s_event_url));
  EXPECT_NE(std::string::npos, to_serialize.find(s_scpd_url));
  EXPECT_NE(std::string::npos, to_serialize.find("actions"));
  EXPECT_NE(std::string::npos, to_serialize.find(a1_name));
  EXPECT_NE(std::string::npos, to_serialize.find(a2_name));
}

//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
//  ACTION tests
//------------------------------------------------------------------------------

TEST(SerializeJsonTest, SerializeActionOkWithChildren)
{
  const std::string a_name = "action 1";
  const std::string arg1_name = "arg 1 name";
  const std::string arg2_name = "argj2 name";

  ServiceAction a(a_name);
  ServiceActionArg::Ptr arg1(new ServiceActionArg(arg1_name, ServiceActionArg::IN));
  a.add_arg(arg1);
  ServiceActionArg::Ptr arg2(new ServiceActionArg(arg2_name, ServiceActionArg::OUT));
  a.add_arg(arg2);

  boost::property_tree::ptree parent;

  a.serialize_json(parent);

  std::stringstream ss;
  boost::property_tree::json_parser::write_json(ss, parent);

  auto to_serialize = ss.str();

  EXPECT_NE(std::string::npos, to_serialize.find("name"));
  EXPECT_NE(std::string::npos, to_serialize.find(a_name));
  EXPECT_NE(std::string::npos, to_serialize.find("arguments"));
  EXPECT_NE(std::string::npos, to_serialize.find(arg1_name));
  EXPECT_NE(std::string::npos, to_serialize.find(arg2_name));
}

//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
//  RootDevice tests
//------------------------------------------------------------------------------

TEST(SerializeJsonTest, SerializeRootDeviceOk)
{
  const std::string location = "the loc";
  const std::string server = "the server";
  const std::string cache_ctrl = "the cache ctrl";
  const std::string s_type = "the s type";
  const std::string usn = "the usn";
  const std::string device_desc_doc = "the dev desc doc";
  const std::string host = "the host";
  const std::string port = "the port";
  const std::string cpe_dev_name = "the cpe device";
  const std::string cpe_dev_model = "the cpe device model";

  auto dev = new Device(cpe_dev_name, cpe_dev_model);
  RootDevice rd(location, server, cache_ctrl, s_type, usn, device_desc_doc, host, port, dev);

  boost::property_tree::ptree parent;

  rd.serialize_json(parent);

  std::stringstream ss;
  boost::property_tree::json_parser::write_json(ss, parent);

  auto to_serialize = ss.str();

  EXPECT_NE(std::string::npos, to_serialize.find(location));
  EXPECT_NE(std::string::npos, to_serialize.find(server));
  EXPECT_NE(std::string::npos, to_serialize.find(cache_ctrl));
  EXPECT_NE(std::string::npos, to_serialize.find(s_type));
  EXPECT_NE(std::string::npos, to_serialize.find(usn));
  EXPECT_NE(std::string::npos, to_serialize.find(device_desc_doc));
  EXPECT_NE(std::string::npos, to_serialize.find(host));
  EXPECT_NE(std::string::npos, to_serialize.find(port));
  EXPECT_NE(std::string::npos, to_serialize.find(cpe_dev_name));
  EXPECT_NE(std::string::npos, to_serialize.find(cpe_dev_model));
}


text:
/**
 * Reactive
 *
 * (c) 2015-2016 Axel Etcheverry
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

#include <boost/test/unit_test.hpp>
#include <reactive/identifier/uuid.hpp>

BOOST_AUTO_TEST_SUITE(reactive_identifier_uuid)

BOOST_AUTO_TEST_CASE(test_v4)
{
    std::string uuid = reactive::identifier::uuid::v4();

    BOOST_CHECK_EQUAL(uuid.length(), 36u);

    BOOST_CHECK_EQUAL(uuid[14], '4');

    bool is_valid = false;

    if (uuid[19] == '8' || uuid[19] == '9' || uuid[19] == 'a' || uuid[19] == 'b') {
        is_valid = true;
    }

    BOOST_CHECK_EQUAL(is_valid, true);
}

BOOST_AUTO_TEST_SUITE_END()

max_stars_repo_name: ReactiveFramework/ReactiveFramework

max_issues_repo_name: ReactiveFramework/ReactiveFramework

max_forks_repo_name: ReactiveFramework/ReactiveFramework


text:
/*###############################################################################
#
# This software is distributed under the following ISC license:
#
# Copyright © 2017 BRAZILIAN SYNCHROTRON LIGHT SOURCE <sol@lnls.br>
#   Dawood Alnajjar <dawood.alnajjar@lnls.br>
#
# Permission to use, copy, modify, and/or distribute this software for any
# purpose with or without fee is hereby granted, provided that the above
# copyright notice and this permission notice appear in all copies.
#
# THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
# MERCHANTABILITY AND FITNESS.  IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION
# OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
# CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
#
# Description:
# Binary input functions
#
###############################################################################*/

#include "Common.h"
#include "utils.h"

#include <ctype.h>
#include <errno.h>
#include <stdexcept>
#include <time.h>
#include <boost/bimap.hpp>
#include "rt_var_handler.h"
#include "CrioLinux.h"
#include <sys/types.h>
#include <sys/syscall.h>
#include "cfg_parser.h"

#define CACHE_TIMEOUT_US 1000

/* boost namespace */
using boost::bimap;

/* typedefs */
typedef bimap< unsigned, std::string > bim_type;
typedef bimap< std::string, unsigned > bm_address_type;

/* prototypes */
static __inline__ bool getBIVectorItem(struct crio_context *ctx, uint32_t index, uint64_t address);
static __inline__ int getBIVector(struct crio_context *ctx, uint64_t *output, uint64_t address);

/* --------------- HELPERS --------------- */

static __inline__ int getBIVector(struct crio_context *ctx, uint64_t *output, uint64_t address) {

    pthread_mutex_lock(&ctx->bi_mutex);

    /* Check if 1ms passed, if not, use cached value */
    struct timespec  current, delta;
    clock_gettime(CLOCK_REALTIME, &current);
    timespec_diff(&ctx->bi_sample_time, &current, &delta);
    double delta_us = delta.tv_sec * 1000000.0 + delta.tv_nsec / 1000.0;
    if ((delta_us < ctx->bi_cache_timeout) && ctx->bi_cache_valid == true)
    {
        *output = ctx->bi_cache;
    }
    else
    {
        auto Res = NiFpga_ReadU64(NiFpga_Session(ctx->session), address, output);
        if (NiFpga_IsError(Res)) throw (CrioLibException(E_VAR_ACCESS, "Cannot access address"));
        ctx->bi_cache = *output;
        memcpy(&ctx->bi_sample_time, &current, sizeof (struct timespec));
        ctx->bi_cache_valid = true;
    }
    pthread_mutex_unlock(&ctx->bi_mutex);
    return 0;
}

static __inline__ bool getBIVectorItem(struct crio_context *ctx, uint32_t index, uint64_t address){
    uint64_t output;
    try{
        getBIVector(ctx, &output, address);
    } catch(CrioLibException &e) {
        throw (e);
    }

    return (bool) (output & (0x1UL << index));
}

static __inline__ bool getBIScalarItem(struct crio_context *ctx, uint64_t address){
    bool ret;
    auto Res = NiFpga_ReadBool(NiFpga_Session(ctx->session), address, (NiFpga_Bool*)&ret);
    if (NiFpga_IsError(Res))
        throwCRIOError(Res);
    return ret;
}

/* ---------------- API FUNCTIONS ---------------- */

void setBICacheTimeout(struct crio_context *ctx, double timeout)
{
    ctx->bi_cache_timeout = timeout;
}

int crioGetBIArraySize(struct crio_context *ctx, unsigned *size) {
    if (!ctx->session_open)
        throw (CrioLibException(E_SESSION_CLOSED , "[%s] Operation performed on closed session.", LIB_CRIO_LINUX ));
    *size = ctx->bi_count;
    return 0;
}

int crioGetBIArrayItemByName(struct crio_context *ctx, bool *item, const char *name) {
    double value;
    unsigned address ;
    if (!ctx->session_open)
        throw (CrioLibException(E_SESSION_CLOSED , "[%s] Operation performed on closed session.", LIB_CRIO_LINUX ));

    uint64_t index;
    try {
        /* See if RT variable is an RT variable */
        if (is_rt_var(name) == true)
        {
            uint32_t address =  ctx->rt_variable_offsets[((bm_address_type *)ctx->rt_addresses)->left.at(name)];
            get_rt_val(ctx->shared_memory, address, value, name);
            *item = static_cast<bool>(value);
            if (ctx->debugCRIO)
            {
                printf ("RT BI name=%s, Value=%d, Offset=0x%05x\n" , name, *item, address);
                fprintf (ctx->log, "RT BI name=%s, Value=%d, Offset=0x%05x\n" , name, *item, address);
            }
        }
        /* FPGA variable */
        else
        {

            try{
                /* Search for item in the BI vector map */
                index = ((bim_type *)ctx->bi_map)->right.at(name);
                address = ((bm_address_type *)ctx->bi_addresses)->left.at(BI_VECTOR);
                *item = getBIVectorItem(ctx, index, address);

            } catch (out_of_range) {
                try{
                    /* Item was not found in the BI vector, now searching the the BI scalar map */
                    address = ((bm_address_type *)ctx->bi_addresses)->left.at(name);
                    *item = getBIScalarItem(ctx, address);
                } catch (out_of_range) {
                    /* Item not found in either of the 2 maps */
                    throw (CrioLibException(E_OUT_OF_RANGE , "[%s] Property [%s]: Query returned null.", LIB_CRIO_LINUX , name ));
                } catch(CrioLibException &e) {
                    throw (CrioLibException(e.errorcode, "[%s] Property [%s]: %s.", LIB_CRIO_LINUX , name, e.what()));
                }
            }
             /* debug enable check */
            if (ctx->debugCRIO)
            {
                printf ("FPGA BI name=%s, Value=%d, Address=0x%05x, Index=%lu\n" , name, *item, address, index);
                fprintf (ctx->log, "FPGA BI name=%s, Value=%d, Address=0x%05x, Index=%lu\n" , name, *item, address, index);
            }
        }
    } catch (out_of_range) {
        throw (CrioLibException(E_OUT_OF_RANGE , "[%s] Property [%s]: Query returned null.", LIB_CRIO_LINUX , name ));
    } catch(CrioLibException &e) {
        throw (CrioLibException(e.errorcode, "[%s] Property [%s]: %s.", LIB_CRIO_LINUX , name, e.what()));
    }
    return 0;
}

max_stars_repo_name: lnls-sol/nheengatu-linuxlibs

max_issues_repo_name: lnls-sol/nheengatu-linuxlibs

max_forks_repo_name: lnls-sol/nheengatu-linuxlibs


text:
#include "../Core/Utils/Macros.h"
#include "MainController.h"
#include "Tools/KlgLogReader.h"
#include "Tools/OpenNI2LiveReader.h"
#ifdef WITH_FREENECT2
#include "Tools/FreenectLiveReader.h"
#endif
#include "Tools/ImageLogReader.h"

#include <GUI/Tools/PangolinReader.h>
#include <boost/algorithm/string.hpp>
#include <boost/filesystem.hpp>
#include <opencv2/core/ocl.hpp>
#include <toml.hpp>

#ifdef WAYNE_DEBUG
int WRITE_MASK_INDEX = 0;
const std::string WRITE_MASK_DIR = "/data/wayne/SLAM/train_log/";
#endif

// #include "../Core/Segmentation/MaskRCNN/MaskRCNN.h"

// class MaskRCNN;

int main(int argc, char* argv[]) {
    // mainControler staff
    bool good;
    MaskFusion* maskFusion;
    GUI* gui;
    bool showcaseMode;
    GroundTruthOdometry* groundTruthOdometry;
    std::unique_ptr<LogReader> logReader;

    bool iclnuim;
    std::string logFile;
    std::string poseFile;
    std::string exportDir;
    bool exportSegmentation;
    bool exportViewport;
    bool exportLabels;
    bool exportNormals;
    bool exportPoses;
    bool exportModels;

    float confGlobalInit, confObjectInit, icpErrThresh, covThresh, photoThresh,
        fernThresh;

    int timeDelta, icpCountThresh, start, end, preallocatedModelsCount,
        frameQueueSize;

    bool fillIn, openLoop, reloc, frameskip, quit, fastOdom, so3, rewind,
        frameToFrameRGB, usePrecomputedMasksOnly;

    int framesToSkip;
    bool streaming;
    bool resetButton;
    Segmentation::Method segmentationMethod;

    GPUResize* resizeStream;

    std::set<int> trackableClassIds;

    std::string tmpString;
    float tmpFloat;

    iclnuim = Parse::get().arg(argc, argv, "-icl", tmpString) > -1;

    std::string baseDir;
    Parse::get().arg(argc, argv, "-basedir", baseDir);
    if (baseDir.length()) baseDir += '/';

    std::string calibrationFile;
    Parse::get().arg(argc, argv, "-cal", calibrationFile);
    if (calibrationFile.size()) calibrationFile = baseDir + calibrationFile;

    // Asus is default camera (might change later)
    if (Parse::get().arg(argc, argv, "-v2", tmpString) > -1) {
        Resolution::setResolution(512, 424);
        Intrinsics::setIntrinics(528, 528, 256, 212);
    } else if (Parse::get().arg(argc, argv, "-tum3", tmpString) > -1) {
        Resolution::setResolution(640, 480);
        Intrinsics::setIntrinics(535.4, 539.2, 320.1, 247.6);
    } else {
        Resolution::setResolution(640, 480);
        Intrinsics::setIntrinics(528, 528, 320, 240);
    }

    // if (calibrationFile.length()) loadCalibration(calibrationFile);
    // std::cout << "Calibration set to resolution: " <<
    //              Resolution::getInstance().width() << "x" <<
    //              Resolution::getInstance().height() <<
    //              ", [fx: " << Intrinsics::getInstance().fx() <<
    //              " fy: " << Intrinsics::getInstance().fy() <<
    //              ", cx: " << Intrinsics::getInstance().cx() <<
    //              " cy: " << Intrinsics::getInstance().cy() << "]" <<
    //              std::endl;

    bool logReaderReady = false;

    Parse::get().arg(argc, argv, "-l", logFile);
    if (logFile.length()) {
        if (boost::filesystem::exists(logFile) &&
            boost::algorithm::ends_with(logFile, ".klg")) {
            logReader = std::make_unique<KlgLogReader>(
                logFile, Parse::get().arg(argc, argv, "-f", tmpString) > -1);
        } else {
            logReader = std::make_unique<PangolinReader>(
                logFile, Parse::get().arg(argc, argv, "-f", tmpString) > -1);
        }
        logReaderReady = true;
    }

    if (!logReaderReady) {
        Parse::get().arg(argc, argv, "-dir", logFile);
        if (logFile.length()) {
            logFile += '/';  // "colorDir"
            std::string depthDir, maskDir, depthPrefix, colorPrefix, maskPrefix;
            Parse::get().arg(argc, argv, "-depthdir", depthDir);
            Parse::get().arg(argc, argv, "-maskdir", maskDir);
            Parse::get().arg(argc, argv, "-colorprefix", colorPrefix);
            Parse::get().arg(argc, argv, "-depthprefix", depthPrefix);
            Parse::get().arg(argc, argv, "-maskprefix", maskPrefix);
            if (depthDir.length()) depthDir += '/';
            // else depthDir = logFile;
            if (maskDir.length()) maskDir += '/';
            // else maskDir = logFile;
            int indexW = -1;
            ImageLogReader* imageLogReader = new ImageLogReader(
                baseDir + logFile, baseDir + depthDir, baseDir + maskDir,
                Parse::get().arg(argc, argv, "-indexW", indexW) > -1 ? indexW
                                                                     : 4,
                colorPrefix, depthPrefix, maskPrefix,
                Parse::get().arg(argc, argv, "-f", tmpString) > -1);

            // How many masks?
            int maxMasks = -1;
            if (Parse::get().arg(argc, argv, "-nm", maxMasks) > -1) {
                if (maxMasks >= 0)
                    imageLogReader->setMaxMasks(maxMasks);
                else {
                    imageLogReader->ignoreMask();
#ifdef WAYNE_DEBUG
                    std::cout
                        << "\n Log : Image LogReader Ready in Ignore Mask.\n";
#endif
                }
            }

            logReader = std::unique_ptr<LogReader>(imageLogReader);
            usePrecomputedMasksOnly = imageLogReader->hasPrecomputedMasksOnly();
            logReaderReady = true;

#ifdef WAYNE_DEBUG
            std::cout << "\n Log : Use precomputed mask ? : "
                      << usePrecomputedMasksOnly << std::endl;
            ;
#endif
        }
    }

#ifdef WAYNE_DEBUG
    std::cout << "\n Log : Image-loger initialize success.\n";
#endif

    // Start process frame

    // note initialize MaskRCNN module
    // std::unique_ptr<MaskRCNN> maskRCNN;
    // bool sequentialMaskRCNN;
    // std::queue<FrameDataPointer> queue; //  should be nullptr ???
    // bool sequentialMaskRCNN = true;
    // std::unique_ptr<MaskRCNN> maskRCNN;

    // // if(embedMaskRCNN){ // usePreComputedMask
    // if(true){
    //     maskRCNN = std::make_unique<MaskRCNN>(nullptr); // queue in
    //     sourceCode
    //     // sequentialMaskRCNN = (queue == nullptr);
    // }

    // if (maskFusion->processFrame(logReader->getFrameData(), currentPose,
    // weightMultiplier) && !showcaseMode) {
    //                 gui->pause->Ref().Set(true);
    //             }
    // logReader->getFrameData == frame.

    // SegmentationResult segmentationResult = performSegmentation(frame);

    // SegmentationResult MaskFusion::performSegmentation(FrameDataPointer
    // frame) {
    //     return labelGenerator.performSegmentation(models, frame,
    //     getNextModelID(), spawnOffset >= modelSpawnOffset);
    // }

    /*** Imagelogger test ***/
    for (int i = 0; i < 10; i++) {
        if (logReader->hasMore()) {
            // processFrame(FrameDataPointer frame, logReader->getframe
            FrameDataPointer frame = logReader->getFrameData();
            // std::cout<<"\n Log : frames in log : "<<logReader->frames.size()<<"\n";
            // std::cout<<"\n Log : Checking the frame data.....\n";
            // std::cout<<"\n Log : "<<frame->rgb.empty()<<frame->depth.empty()<<std::endl;
            // std::cout<<"\n Log : Timestamp index "<<frame->timestamp<<" "<<frame->index<<std::endl;

        }
    }

// #ifdef WAYNE_DEBUG
//     std::cout << "\n Log : Attempt to load the mask num" << frame->mask.total()
//               << std::endl;
// #endif

    // if(frame->mask.total() == 0) {

    // #ifdef WAYNE_DEBUG
    //     std::cout<<"\nPre execute Sequential\n";
    // #endif

    // if(!maskRCNN) throw std::runtime_error("MaskRCNN is not embedded and no
    // masks were pre-computed."); else if(sequentialMaskRCNN)
    // maskRCNN->executeSequential(frame);
    // }

#ifdef WAYNE_DEBUG
    std::cout << "\nProgram passed MaskRCNN.\n";
#endif

    // #ifdef WAYNE_DEBUG
    //     cv::imwrite(WRITE_MASK_DIR + "mrcnn" + std::to_string(frame->index) +
    //     ".png", frame->mask);
    // #endif

#ifdef WAYNE_DEBUG
    std::cout << "\nProgram passed Image save.\n";
#endif

    return 0;

    // FrameDataPointer result = std::make_shared<FrameData>();

    // ImageLogReader* imageLogReader = new ImageLogReader(baseDir + logFile,
    // baseDir + depthDir, baseDir + maskDir,
    //                                                 Parse::get().arg(argc,
    //                                                 argv, "-indexW", indexW)
    //                                                 > -1 ? indexW : 4,
    //                                                 colorPrefix, depthPrefix,
    //                                                 maskPrefix,
    //                                                 Parse::get().arg(argc,
    //                                                 argv, "-f", tmpString) >
    //                                                 -1);
}

// FrameDataPointer ImageLogReader::loadFrameFromDrive(const size_t& index) {
//   FrameDataPointer result = std::make_shared<FrameData>();

//   // Get path to image files
//   std::stringstream ss;
//   ss << std::setw(indexW) << std::setfill('0') << index + startIndex;
//   std::string indexStr = ss.str();

//   std::string depthImagePath = depthImagesDir + depthPre + indexStr +
//   depthExt; if (!boost::filesystem::exists(depthImagePath)) throw
//   std::invalid_argument("Could not find depth-image file: " +
//   depthImagePath);

//   std::string rgbImagePath = file + colorPre + indexStr + colorExt;
//   if (!boost::filesystem::exists(rgbImagePath)) throw
//   std::invalid_argument("Could not find rgb-image file: " + rgbImagePath);

//   // Load mask ids
//   //std::string maskImagePath = maskImagesDir + maskPre +
//   std::to_string(index); std::string maskImagePath = maskImagesDir + maskPre
//   + indexStr; std::string maskDescrPath = maskImagePath + ".txt";
//   maskImagePath += maskExt;
//   if (hasMasksGT) {
//     if (!boost::filesystem::exists(maskImagePath)) throw
//     std::invalid_argument("Could not find mask-image file: " +
//     maskImagePath); if (boost::filesystem::exists(maskDescrPath))
//     loadMaskIDs(maskDescrPath, &result->classIDs, &result->rois);
//   }

//   // Load RGB
//   result->rgb = cv::imread(rgbImagePath);
//   if (result->rgb.total() == 0) throw std::invalid_argument("Could not read
//   rgb-image file."); result->flipColors();

//   // Load Depth
//   result->depth = cv::imread(depthImagePath, cv::IMREAD_UNCHANGED);
//   if (result->depth.total() == 0) throw std::invalid_argument("Could not read
//   depth-image file. (Empty)"); if (result->depth.type() != CV_32FC1) {
//     cv::Mat newDepth(result->depth.rows, result->depth.cols, CV_32FC1);
//     if (result->depth.type() == CV_32FC3) {
//       unsigned depthIdx = 0;
//       for (int i = 0; i < result->depth.rows; ++i) {
//         cv::Vec3f* pixel = result->depth.ptr<cv::Vec3f>(i);
//         for (int j = 0; j < result->depth.cols; ++j)
//         ((float*)newDepth.data)[depthIdx++] = pixel[j][0];
//       }

//     } else if (result->depth.type() == CV_16UC1) {
//       //std::cout << "Warning -- your depth scale is likely to mismatch.
//       Check ImageLogReader.cpp!" << std::endl; unsigned depthIdx = 0; for
//       (int i = 0; i < result->depth.rows; ++i) {
//         unsigned short* pixel = result->depth.ptr<unsigned short>(i);
//         for (int j = 0; j < result->depth.cols; ++j)
//         ((float*)newDepth.data)[depthIdx++] = 0.001f * pixel[j];
//         //for (int j = 0; j < result->depth.cols; ++j)
//         ((float*)newDepth.data)[depthIdx++] = 0.0002f * pixel[j]; // FIXME
//       }
//     } else {
//       throw std::invalid_argument("Unsupported depth-files: " +
//       cvTypeToString(result->depth.type()));
//     }
//     result->depth = newDepth;
//   }

//   // Load Mask
//   if (hasMasksGT && (index < maxMasks)) {
//     result->mask = cv::imread(maskImagePath, cv::IMREAD_GRAYSCALE);
//     if (result->mask.total() != result->rgb.total()) throw
//     std::invalid_argument("Could not read mask-image file."); if
//     (!result->mask.isContinuous() || result->mask.type() != CV_8UC1) throw
//     std::invalid_argument("Incompatible mask image.");
//   }

//   result->timestamp = index * 1000.0f / rateHz;
//   result->index = index;

//   return result;
// }

// void ImageLogReader::bufferFramesImpl() {
//   if (int(nextBufferIndex) - minBuffered + 1 > int(currentFrame)) return;
//   for (unsigned i = 0; i < 15 && nextBufferIndex < frames.size(); ++i,
//   ++nextBufferIndex) {
//     frames[nextBufferIndex] = loadFrameFromDrive(nextBufferIndex);
//   }
// }

//   // Data
//   std::vector<FrameDataPointer> frames;

//   FrameDataPointer ImageLogReader::getFrameData() {
//   // assert(frames[currentFrame] != 0);
//   if (currentFrame < 0) return NULL;

//   bool bufferFail = false;
//   while (!frames[currentFrame] || frames[currentFrame]->depth.total() == 0) {
//     usleep(1);
//     bufferFail = true;
//   }
//   if (bufferFail) std::cout << "Buffering failure." << std::endl;
//   return frames[currentFrame];
//  }

//    FrameDataPointer getFrameData();

//    imageLogReader* imageLogReader = new ImageLogReader(baseDir + logFile,
//    baseDir + depthDir, baseDir + maskDir,
//                                                                 Parse::get().arg(argc,
//                                                                 argv,
//                                                                 "-indexW",
//                                                                 indexW) > -1
//                                                                 ? indexW : 4,
//                                                                 colorPrefix,
//                                                                 depthPrefix,
//                                                                 maskPrefix,
//                                                                 Parse::get().arg(argc,
//                                                                 argv, "-f",
//                                                                 tmpString) >
//                                                                 -1);

//     // How many masks?
//     int maxMasks = -1;
//     if (Parse::get().arg(argc, argv, "-nm", maxMasks) > -1) {
//         if (maxMasks >= 0)
//             imageLogReader->setMaxMasks(maxMasks);
//         else
//             imageLogReader->ignoreMask();
//     }

//     logReader = std::unique_ptr<LogReader>(imageLogReader);

//    // note get frame data
//     if (maskFusion->processFrame(logReader->getFrameData(), currentPose,
//     weightMultiplier) && !showcaseMode) {
//         gui->pause->Ref().Set(true);
//     }

//     bool MaskFusion::processFrame(FrameDataPointer frame, const
//     Eigen::Matrix4f* inPose, const float weightMultiplier, const bool
//     bootstrap) {

//     assert(frame->depth.type() == CV_32FC1);
//     assert(frame->rgb.type() == CV_8UC3);
//     assert(frame->timestamp >= 0);
//     TICK("Run");

//     frameQueue.push(frame);
//     if(frameQueue.size() < queueLength) return 0;
//     frame = frameQueue.front();
//     frameQueue.pop();

//     // Upload RGB to graphics card
//     textureRGB->texture->Upload(frame->rgb.data, GL_RGB, GL_UNSIGNED_BYTE);

//     // note maskfusion class preprocess
//     TICK("Preprocess");

//     textureDepthMetric->texture->Upload((float*)frame->depth.data,
//     GL_LUMINANCE, GL_FLOAT); filterDepth();

//     // if(frame.mask) {
//     //    // Use ground-truth segmentation if provided (TODO: Overwritten at
//     the moment)
//     //    textureMask->texture->Upload(frame.mask, GL_LUMINANCE_INTEGER_EXT,
//     GL_UNSIGNED_BYTE);
//     //} else
//     if (!enableMultipleModels) {
//         // If the support for multiple objects is deactivated, segment
//         everything as background (static scene). const long size =
//         Resolution::getInstance().width() *
//         Resolution::getInstance().height(); unsigned char* data = new
//         unsigned char[size]; memset(data, 0, size);
//         textureMask->texture->Upload(data, GL_LUMINANCE_INTEGER_EXT,
//         GL_UNSIGNED_BYTE); delete[] data;
//     }

//     TOCK("Preprocess");

//    // note maskfusion call perform segmentation function
//     SegmentationResult segmentationResult = performSegmentation(frame);

//    // create MaskFusion class
//    if(embedMaskRCNN){
//         maskRCNN = std::make_unique<MaskRCNN>(queue);
//         sequentialMaskRCNN = (queue == nullptr);
//     }

//     // TODO does MaskRCNN finished here ?? YES. result in frame-mask
//     if(frame->mask.total() == 0) {
//         if(!maskRCNN) throw std::runtime_error("MaskRCNN is not embedded and
//         no masks were pre-computed."); else if(sequentialMaskRCNN)
//         maskRCNN->executeSequential(frame);
//     }

max_stars_repo_name: Wayne-Mai/DynSLAM

max_issues_repo_name: Wayne-Mai/DynSLAM

max_forks_repo_name: Wayne-Mai/DynSLAM


text:
/*

Copyright (c) 2009, Yoav Aviram
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:

* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in
the documentation and/or other materials provided with the distribution.
* Neither the name of the author nor the names of its
contributors may be used to endorse or promote products derived
from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.

*/

#include "StdAfx.hpp"
#include "Entry.hpp"
#include "Utils.hpp"

#include <algorithm>
#include <boost/date_time/special_defs.hpp>
#include <boost/date_time/posix_time/posix_time_types.hpp>
#include <xercesc/util/XMLString.hpp>
#include <xercesc/dom/DOM.hpp>
#include "Feed.hpp"

namespace FeedReader
{
	Entry::Entry(const xercesc_2_8::DOMNode* const entryNode) :
		UniqueId(),
		Published(boost::date_time::min_date_time),
		IsLive(true)
	{
		ParseNodeData(entryNode);
	}

	Entry::Entry(const Entry& other)
	{
		UniqueId = other.UniqueId;
		Published = other.Published;
		IsLive = other.IsLive;
		m_entryElements = other.m_entryElements;
	}

	Entry& Entry::operator= (const Entry& other)
	{
		if (this != &other)
		{
			UniqueId = other.UniqueId;
			Published = other.Published;
			IsLive = other.IsLive;
			m_entryElements = other.m_entryElements;
		}
		return *this;
	}

	void Entry::ParseNodeData(const xercesc_2_8::DOMNode* const entryNode)
	{
		const xercesc_2_8::DOMNodeList* const children = entryNode->getChildNodes();
		for (XMLSize_t i = 0, listLength = children->getLength(); i < listLength; ++i)
		{
			const xercesc_2_8::DOMNode* const node = children->item(i);
			const std::string nodeName = XmlCharsToStdString(node->getNodeName());
			const std::string textContent = XmlCharsToStdString(node->getTextContent());

			if (nodeName == XERCESC_EMPTY_NODE_NAME)
			{
				continue;
			}
			if (xercesc_2_8::XMLString::equals(nodeName.c_str(), "entryUniqueId"))
			{
				UniqueId = textContent;
				m_entryElements["entryUniqueId"] = textContent;
			}
			else if (xercesc_2_8::XMLString::equals(nodeName.c_str(), "publishDateTime"))
			{
				Published = boost::posix_time::microsec_clock::universal_time();
				m_entryElements["publishDateTime"] = textContent;
			}
			else
			{
				m_entryElements[nodeName] = textContent;
			}
		}

		if (UniqueId.empty())
		{
			UniqueId = m_entryElements["url"];
		}
	}

	const std::string& Entry::operator[](const std::string& node) const
	{
		EntryElements::const_iterator itr = m_entryElements.find(node);
		if (itr == m_entryElements.end())
		{
			static const std::string empty = "";
			return empty;
		}

		return itr->second;
	}

	void Entry::Print(std::ostream& os) const
	{
		for (EntryElements::const_iterator itr = m_entryElements.begin();
			 itr != m_entryElements.end();
			 itr++)
		{
			os << itr->first << ": '" << itr->second << "'" << std::endl;
		}
	}
}

max_stars_repo_name: thawkins/feed-reader-lib

max_issues_repo_name: thawkins/feed-reader-lib

max_forks_repo_name: thawkins/feed-reader-lib