text:
/* Copyright (c) 2016 - 2020, the adamantine authors.
 *
 * This file is subject to the Modified BSD License and may not be distributed
 * without copyright and license information. Please refer to the file LICENSE
 * for the text and further information on this license.
 */

#define BOOST_TEST_MODULE Geometry

#include <Geometry.hh>
#include <types.hh>

#include <deal.II/grid/filtered_iterator.h>

#include <boost/property_tree/ptree.hpp>

#include "main.cc"

template <int dim>
void check_material_id(
    dealii::parallel::distributed::Triangulation<dim> const &tria)
{
  dealii::types::boundary_id const top_boundary = 3;
  for (auto cell :
       dealii::filter_iterators(tria.active_cell_iterators(),
                                dealii::IteratorFilters::LocallyOwnedCell()))
  {
    if (cell->at_boundary())
    {
      bool powder = false;
      for (unsigned int i = 0; i < dealii::GeometryInfo<dim>::faces_per_cell;
           ++i)
      {
        if ((cell->face(i)->at_boundary()) &&
            (cell->face(i)->boundary_id() == top_boundary))
        {
          BOOST_CHECK(cell->user_index() ==
                      static_cast<int>(adamantine::MaterialState::powder));
          powder = true;
          break;
        }
      }
      if (powder == false)
        BOOST_CHECK(cell->user_index() ==
                    static_cast<int>(adamantine::MaterialState::solid));
    }
    else
      BOOST_CHECK(cell->user_index() ==
                  static_cast<int>(adamantine::MaterialState::solid));
  }
}

BOOST_AUTO_TEST_CASE(geometry_2D)
{
  MPI_Comm communicator = MPI_COMM_WORLD;
  boost::property_tree::ptree database;
  database.put("length", 12);
  database.put("length_divisions", 4);
  database.put("height", 6);
  database.put("height_divisions", 5);

  adamantine::Geometry<2> geometry(communicator, database);
  dealii::parallel::distributed::Triangulation<2> const &tria =
      geometry.get_triangulation();

  BOOST_CHECK(tria.n_active_cells() == 20);
  check_material_id(tria);
}

BOOST_AUTO_TEST_CASE(geometry_3D)
{
  MPI_Comm communicator = MPI_COMM_WORLD;
  boost::property_tree::ptree database;
  database.put("length", 12);
  database.put("length_divisions", 4);
  database.put("height", 4);
  database.put("height_divisions", 2);
  database.put("width", 6);
  database.put("width_divisions", 5);

  adamantine::Geometry<3> geometry(communicator, database);
  dealii::parallel::distributed::Triangulation<3> const &tria =
      geometry.get_triangulation();

  BOOST_CHECK(tria.n_active_cells() == 40);
  check_material_id(tria);
}

ext: cc

max_stars_repo_name: stvdwtt/adamantine

max_issues_repo_name: stvdwtt/adamantine

max_forks_repo_name: stvdwtt/adamantine


text:
#include <iostream>
#include <boost/algorithm/clamp.hpp>
#include <boost/algorithm/minmax.hpp>

#include <ros/ros.h>

#include <dronefly/compute_pid.h>

using namespace computepid;

PID::PID(double p, double i, double d, double imax, double imin)
{
	// PID values
	p_gain = p;
	i_gain = i;
	d_gain = d;

	// Min/max bounds for the integral windup
	i_max = imax;
	i_min = imin;

	//ROS_INFO("PID: %f, %f, %f", p_gain_, i_gain_, d_gain_);
}

PID::~PID()
{}

void PID::initPID(double p, double i, double d, double imax, double imin)
{
	// PID values
	p_gain = p;
	i_gain = i;
	d_gain = d;

	// Min/max bounds for the integral windup
	i_max = imax;
	i_min = imin;

	//ROS_INFO("PID: %f, %f, %f", p_gain_, i_gain_, d_gain_);
}

double PID::computeCommand(double error, ros::Duration dt)
{
	if (dt == ros::Duration(0.0) || std::isnan(error) || std::isinf(error))
		return 0.0;

	double error_dot = d_error;

	// Calculate the derivative error
	if (dt.toSec() > 0.0)
	{
		if (valid_p_error_last)
			error_dot = (error - p_error_last)/dt.toSec();
		p_error_last = error;
		valid_p_error_last = true;
	}

	return computeCommand(error, error_dot, dt);
}

double PID::computeCommand(double error, double error_dot, ros::Duration dt)
{
	double p_term, d_term, i_term;
	p_error = error;                 // this is error = target - state
	d_error = error_dot;

	if (dt == ros::Duration(0.0) || std::isnan(error) || std::isinf(error) || std::isnan(error_dot) || std::isinf(error_dot))
		return 0.0;

	// Calculate proportional contribution to command
	p_term = p_gain * p_error;

	// Calculate the integral of the position error
	i_error += dt.toSec() * p_error;

	if(i_gain!=0)
	{
		// Prevent i_error_ from climbing higher than permitted by i_max_/i_min_
		boost::tuple<double, double> bounds = boost::minmax<double>(i_min / i_gain, i_max / i_gain);
		i_error = boost::algorithm::clamp(i_error, bounds.get<0>(), bounds.get<1>());
	}

	// Calculate integral contribution to command
	i_term = i_gain * i_error;

	// Limit i_term so that the limit is meaningful in the output
	i_term = boost::algorithm::clamp(i_term, i_min, i_max);

	// Calculate derivative contribution to command
	d_term = d_gain * d_error;

	// Compute the command
	cmd = p_term + i_term + d_term;

	return cmd;
}

double PID::bound(double v, double b)
{
	if(v < -b)
		return -b;
	if(v > b)
		return b;
	return v;
}

ext: cpp

max_stars_repo_name: Dieptranivsr/DroneIVSR

max_issues_repo_name: Dieptranivsr/DroneIVSR

max_forks_repo_name: Dieptranivsr/DroneIVSR


text:
#include "clew.h"
#include <vector>
#include <string>
#include <iostream>
#include <fstream>
#include <sstream>
#include <stdio.h>
#include <stdlib.h>
#include "tyrant.h"
#include "9_tuo.h"
#include <boost/filesystem.hpp>

cl_program load_cl_programs(cl_context context) {
    std::vector<std::string> filenames;
    for (boost::filesystem::directory_entry& entry : boost::filesystem::directory_iterator("cl/"))  {
        filenames.push_back(entry.path().string());
    }
    std::sort(filenames.begin(),filenames.end());

	int n =  filenames.size();
	std::vector<std::string> files(n);
    const char** programBuffer = (const char**) malloc(n);
    size_t* programSize = ( size_t*) malloc(n);
	for(int i=0; i < n; ++i) {
        std::ifstream inFile;
		inFile.open(filenames[i]); //open the input file
    	std::stringstream strStream;
    	strStream << inFile.rdbuf(); //read the file
    	std::string str = strStream.str(); //str holds the content of the file
		files.push_back(str);
        programBuffer[i] = files.back().c_str();
        programSize[i] = files.back().length();
	}
    return clCreateProgramWithSource(context, n,
            programBuffer, programSize, NULL);
}
int main() {
    int clpresent = 0 == clewInit();
    if( !clpresent ) {
        printf("opencl library not found.\n");
        return 0;
    }
    const unsigned int size_card=10+4*3*9+Skill::num_skills*2+2;
    const unsigned int size_all_cards = 2*size_card;
    const unsigned int size_deck=10;
    const unsigned int sims = 1024;
    const unsigned int N = sims;
    const unsigned long seed = 5;
    int err;

    cl_platform_id platform;
    cl_device_id device_id;
    cl_command_queue commands;
    cl_context context;
    cl_program program;

    size_t kernelSourceSize;
    size_t global,local;
    char  *kernelSource;

    printf("clGetPlatformIDs\n");
    // get first available platform and gpu and create context
    err = clGetPlatformIDs(1, &platform, NULL);
    if (err != CL_SUCCESS) {
        printf("something went wrong, errorcode %i\n", err);
    		return 0;
  	}

    printf("clGetDeviceIDs\n");
    clGetDeviceIDs(platform, CL_DEVICE_TYPE_GPU, 1, &device_id, NULL);
    context = clCreateContext(NULL, 1, &device_id, NULL, NULL, NULL);

    // create program from buffer
    program = load_cl_programs(context);
    err = clBuildProgram(program,0,NULL,"-D _OpenCL -I clh/",NULL,NULL);
    size_t len = 0;
    cl_int ret = CL_SUCCESS;
    ret = clGetProgramBuildInfo(program, device_id, CL_PROGRAM_BUILD_LOG, 0, NULL, &len);
    char *buffer = (char*) calloc(len, sizeof(char));
    ret = clGetProgramBuildInfo(program, device_id, CL_PROGRAM_BUILD_LOG, len, buffer, NULL);

    printf("%s",buffer);

    if(err) printf("BUILD Kernel error%d",err);

    // read kernel source back in from program to check
    clGetProgramInfo(program, CL_PROGRAM_SOURCE, 0, NULL, &kernelSourceSize);
    kernelSource = (char*) malloc(kernelSourceSize);
    clGetProgramInfo(program, CL_PROGRAM_SOURCE, kernelSourceSize, kernelSource, NULL);
    //printf("\nKernel source:\n\n%s\n", kernelSource);
    free(kernelSource);

    commands = clCreateCommandQueue(context, device_id, 0, &err);

    cl_kernel kernel = clCreateKernel(program, "simulate",&err);
    if(err) printf("KERNEL Kernel error%d",err);
    cl_mem input0 = clCreateBuffer(context,  CL_MEM_READ_ONLY,  sizeof(int) * size_all_cards, NULL, NULL);
    cl_mem input1 = clCreateBuffer(context,  CL_MEM_READ_ONLY,  sizeof(int) * size_deck, NULL, NULL);
    cl_mem input2 = clCreateBuffer(context, CL_MEM_READ_ONLY, sizeof(int) * size_deck, NULL, NULL);
    cl_mem output = clCreateBuffer(context, CL_MEM_WRITE_ONLY, sizeof(int) * N, NULL, NULL);

    int mydeck[size_deck];
    int enemydeck[size_deck];
    int allcards[size_all_cards];
    for( int i =0; i < size_all_cards;++i) {
        allcards[i] = 0;
    }
    allcards[0] = 2;
    allcards[1] = 2;
    allcards[2] = 2;
    allcards[4] = 2;
    allcards[5] = 2;

    allcards[size_card +0] = 1;
    allcards[size_card +1] = 1;
    allcards[size_card +2] = 1;
    allcards[size_card +4] = 1;
    allcards[size_card +5] = 1;

    int results[N];

    for(int i =0; i  < size_deck ;++i) {
	    mydeck[i] = 1;
	    enemydeck[i] = 2;
    }
    for(int i =0; i  < N; ++i) {
	    results[i] = 2;
    }

    clEnqueueWriteBuffer(commands, input0, CL_TRUE, 0, sizeof(int) * size_all_cards, allcards, 0, NULL, NULL);
    clEnqueueWriteBuffer(commands, input1, CL_TRUE, 0, sizeof(int) * size_deck, mydeck, 0, NULL, NULL);
    clEnqueueWriteBuffer(commands, input2, CL_TRUE, 0, sizeof(int) * size_deck, enemydeck, 0, NULL, NULL);

    int index = 0;
    clSetKernelArg(kernel, index++, sizeof(cl_mem), &input0);
    clSetKernelArg(kernel, index++, sizeof(unsigned int), &size_all_cards);
    clSetKernelArg(kernel, index++, sizeof(cl_mem), &input1);
    clSetKernelArg(kernel, index++, sizeof(cl_mem), &input2);
    clSetKernelArg(kernel, index++, sizeof(cl_mem), &output);
    clSetKernelArg(kernel, index++, sizeof(unsigned int), &N);
    clSetKernelArg(kernel, index++, sizeof(unsigned int), &seed);

    clGetKernelWorkGroupInfo(kernel, device_id, CL_KERNEL_WORK_GROUP_SIZE, sizeof(local), &local, NULL);
    global = N;
    printf("global: %ld local %ld\n",global, local);
    err = clEnqueueNDRangeKernel(commands, kernel, 1, NULL, &global, &local, 0, NULL, NULL);
    if(err) printf("NDRANGE Kernel error%d",err);

    clFinish(commands);
    clEnqueueReadBuffer( commands, output, CL_TRUE, 0, sizeof(int) * N, results, 0, NULL, NULL );

    for (int i = 0; i  < N ; ++i) {
	    printf("%d",results[i]);
    }

    //simulate(allcards,size_all_cards,mydeck,enemydeck,results,N,seed);
	printf("\nsingle run %d\n",results[0]);

    clReleaseMemObject(input0);
    clReleaseMemObject(input1);
    clReleaseMemObject(input2);
    clReleaseMemObject(output);
    clReleaseProgram(program);
    clReleaseKernel(kernel);
    clReleaseCommandQueue(commands);
    clReleaseContext(context);
    return 0;

}

max_stars_repo_name: APN-Pucky/opencl-testing

max_issues_repo_name: APN-Pucky/opencl-testing

max_forks_repo_name: APN-Pucky/opencl-testing


text:
#include <opencv2/core/core.hpp>

#include <stdint.h>

#include <string>
#include <vector>

#include "caffe/common.hpp"
#include "caffe/layers/tsv_data_layer.hpp"
#include "caffe/util/benchmark.hpp"
#include "caffe/util/io.hpp"
#include "caffe/util/rng.hpp"
#include "caffe/util/random_helper.h"

#ifdef USE_MPI
#include "caffe/clusters.hpp"
#endif

#include <boost/thread.hpp>

#ifdef _MSC_VER
#include <ppl.h>
using namespace concurrency;
#endif

namespace caffe {

cv::Mat ReadImageStreamToCVMat(vector<unsigned char>& imbuf, const int height, const int width, const bool is_color)
{
	cv::Mat cv_img;
	int cv_read_flag = (is_color ? CV_LOAD_IMAGE_COLOR :
		CV_LOAD_IMAGE_GRAYSCALE);
	cv::Mat cv_img_origin = cv::imdecode(cv::Mat(imbuf), cv_read_flag);
	if (!cv_img_origin.data) {
		LOG(ERROR) << "Could not open memeory image";
		return cv_img_origin;
	}
	if (height > 0 && width > 0) {
		cv::resize(cv_img_origin, cv_img, cv::Size(width, height));
	}
	else {
		cv_img = cv_img_origin;
	}
	return cv_img;
}

cv::Mat CreateCVMat(const unsigned char* image, int width, int height, int channels, int stride)
{
    CHECK(image != NULL && width > 0 && height > 0 && (channels == 1 || channels == 3 || channels == 4)
        && stride >= width * channels) << "Invalid args";

    cv::Mat cv_img;
    if (channels == 1) // 8 bit gray scale palette (special case)
    {
        cv_img = cv::Mat(height, width, CV_8UC1);

        unsigned char* u8_Src = (unsigned char*)image;
        unsigned char* u8_Dst = cv_img.data;

        for (int R = 0; R < height; R++)
        {
            memcpy(u8_Dst, u8_Src, width);
            u8_Src += stride;
            u8_Dst += cv_img.step;
        }
    }
    else // 24 Bit / 32 Bit
    {
        int s32_CvType = channels == 3 ? CV_8UC3 : CV_8UC4;
        // Create a Mat pointing to external memory
        cv::Mat mat(height, width, s32_CvType, (void *)image, stride);

        // Create a Mat with own memory
        mat.copyTo(cv_img);
    }

    return cv_img;
}

#define PI 3.1415926

void CropImageAndResize(const cv::Mat &cv_img,
    std::string &dst, int dstWidth, int dstHeight,
    float centerX, float centerY, float rotationRadius,
    float baseWidth,
    float cropUp, float cropDown, float cropLeft, float cropRight)
{
    // 1. rotate CV::Mat at center(x,y)
    cv::Mat rotatedImage;
    if (abs(rotationRadius) < 1E-4)
    {
        // skip rotation if the rotationRadius is 0.
        rotatedImage = cv_img;
    }
    else
    {
        cv::Point2f rotation_center_pt(centerX, centerY);
        cv::Mat rotation_mat = cv::getRotationMatrix2D(rotation_center_pt, -rotationRadius * 180 / PI, 1.0);
        cv::warpAffine(cv_img, rotatedImage, rotation_mat, cv::Size(cv_img.cols, cv_img.rows));
    }

    // 2. crop CV::Mat from (x-cropLeft, y-cropUp, x+cropRight, y+cropDown)
    int x1 = (int)(centerX - cropLeft * baseWidth);
    int y1 = (int)(centerY - cropUp * baseWidth);
    int x2 = (int)(centerX + cropRight * baseWidth);
    int y2 = (int)(centerY + cropDown * baseWidth);
    x1 = std::max(x1, 0);
    x2 = std::min(x2, cv_img.cols);
    y1 = std::max(y1, 0);
    y2 = std::min(y2, cv_img.rows);
    cv::Rect crop_rect(x1, y1, x2 - x1, y2 - y1);
    // Crop the full image to that image contained by the rectangle crop_rect
    // Note that this doesn't copy the data
    cv::Mat croppedImage = rotatedImage(crop_rect);

    // 3. resize to (dstWidth, dstHeight)
    cv::Mat resizedImage;
    cv::resize(croppedImage, resizedImage, cv::Size(dstWidth, dstHeight), 0, 0, 2); // 2 for bicubic interpolation

    //cv::imshow("rotated", rotatedImage);
    //cv::imshow("cropped", croppedImage);
    //cv::imshow("resized", resizedImage);
    //cv::waitKey(0);

    // 4. CV::Mat => dst
    Datum datum;
    caffe::CVMatToDatum(resizedImage, &datum);
    dst = datum.data();
}

// crop image by rotating the image at the specified center (x,y) and crop the region at
// (x1, y1, x2, y2), which is (centerX-cropLeft*baseWidth, centerY-cropUp*baseWidth,
//  centerX+cropRight*baseWidth, centerY+cropDown*baseWidth)
// The separate of baseWidth is for convenient so that the crop params can be relatively fixed for the same scenario.
#ifdef _MSC_VER
 __declspec(dllexport)
#endif
void CropImageAndResize(const unsigned char* image, int width, int height, int channels, int stride,
    std::string &dst, int dstWidth, int dstHeight,
    float centerX, float centerY, float ratationRadius,
    float baseWidth, float cropUp, float cropDown, float cropLeft, float cropRight)
{
    // src => CV::Mat
    cv::Mat cv_img = CreateCVMat(image, width, height, channels, stride);

    // crop and resize
    CropImageAndResize(cv_img, dst, dstWidth, dstHeight,
        centerX, centerY, ratationRadius,
        baseWidth, cropUp, cropDown, cropLeft, cropRight);
}

template <typename Dtype>
TsvDataLayer<Dtype>::~TsvDataLayer() {
  this->StopInternalThread();
}

template <typename Dtype>
void TsvDataLayer<Dtype>::DataLayerSetUp(const vector<Blob<Dtype>*>& bottom,
      const vector<Blob<Dtype>*>& top) {
  const TsvDataParameter &tsv_param = this->layer_param().tsv_data_param();

  CHECK_EQ(tsv_param.has_world_size(), tsv_param.has_world_rank())
      << "world_size and world_rank must be specified together";
  world_size_ = tsv_param.world_size();
  world_rank_ = tsv_param.world_rank();
#ifdef USE_MPI
  if (!tsv_param.has_world_size()) {
    world_size_ = Clusters::proc_count();
    world_rank_ = Clusters::proc_rank();
  }
#endif
  CHECK_LT(world_rank_, world_size_);
  CHECK_GT(world_size_, 0);
  // open TSV file
  bool has_shuffle_file = tsv_param.has_source_shuffle();
  string tsv_shuffle;
  if (has_shuffle_file)
      tsv_shuffle = tsv_param.source_shuffle();
  int col_data = tsv_param.col_data();
  int col_label = tsv_param.col_label();
  //int col_crop = tsv_param.col_crop();
  bool has_separate_label_file = tsv_param.source_label_size() > 0;

  vector<string> sources(tsv_param.source_size());
  for (int i = 0; i < tsv_param.source_size(); i++) {
      sources[i] = tsv_param.source(i);
  }
  tsv_.reset(ITsvDataFile::make_tsv(sources, tsv_param.cache_all(), col_data, has_separate_label_file? -1: col_label));

  if (has_shuffle_file)
    tsv_->ShuffleData(tsv_shuffle);
  if (has_separate_label_file)
  {
      vector<string> source_labels(tsv_param.source_label_size());
      for (int i = 0; i < tsv_param.source_label_size(); i++) {
          source_labels[i] = tsv_param.source_label(i);
      }
      tsv_label_.reset(ITsvDataFile::make_tsv(source_labels, true, -1, col_label));
	  if (has_shuffle_file)
        tsv_label_->ShuffleData(tsv_shuffle);
	  CHECK_EQ(tsv_->TotalLines(), tsv_label_->TotalLines())
		  << "Data and label files must have the same line number: "
		  << tsv_->TotalLines() << " vs. " << tsv_label_->TotalLines();
  }
  int batch_size = tsv_param.batch_size();
  LOG(INFO) << "Total data: " << tsv_->TotalLines() << ", Batch size: " << batch_size << ", Epoch iterations: " << (float)tsv_->TotalLines() / batch_size;

  // initialize the prefetch and top blobs.
  // For detection data, new_width, new_height, channels, crop_size can all be ignored.
  // In case they are ignored, here we just initialize batch and top blob as placeholder.
  // And they will be reshaped again in on_load_batch(...).
  int new_width = tsv_param.new_width();
  int new_height = tsv_param.new_height();
  int channels = tsv_param.channels();
  int crop_size = this->layer_param().transform_param().crop_size();
  vector<int> top_shape(4);
  top_shape[0] = 1;
  top_shape[1] = channels;
  top_shape[2] = crop_size > 0 ? crop_size : new_height;
  top_shape[3] = crop_size > 0 ? crop_size : new_width;

  top_shape[0] = batch_size;
  top[0]->Reshape(top_shape);
  for (int i = 0; i < this->prefetch_.size(); ++i) {
	  this->prefetch_[i]->data_.Reshape(top_shape);
  }

  LOG(INFO) << "output data size: " << top[0]->num() << ","
      << top[0]->channels() << "," << top[0]->height() << ","
      << top[0]->width();
  // label
  if (this->output_labels_) {
	int label_dim = tsv_param.label_dim();
    vector<int> label_shape(2);
    label_shape[0] = batch_size;
    label_shape[1] = label_dim;
	top[1]->Reshape(label_shape);
	for (int i = 0; i < this->prefetch_.size(); ++i) {
	  this->prefetch_[i]->label_.Reshape(label_shape);
	}
  }

  if (this->layer_param().transform_param().mean_value_size() > 0) {
      CHECK(this->layer_param().transform_param().has_mean_file() == false) <<
          "Cannot specify mean_file and mean_value at the same time";
      for (int c = 0; c < this->layer_param().transform_param().mean_value_size(); ++c) {
          mean_values_.push_back(this->layer_param().transform_param().mean_value(c));
      }
  }

  if (tsv_param.has_color_kl_file()) {
      load_kl(tsv_param.color_kl_file());
  }
}

template <typename Dtype>
void TsvDataLayer<Dtype>::load_kl(const string &kl_filename)
{
    std::ifstream kl_file;
    kl_file.open(kl_filename.c_str());
    CHECK(!kl_file.fail()) << "kl data cannot be loaded: " << kl_filename;

    eig_val_.clear();
    eig_vec_.clear();

    std::string line;
    // read eigen values
    std::getline(kl_file, line);
    std::stringstream lineStream(line);
    string cell;
    while (std::getline(lineStream, cell, ','))
        eig_val_.push_back(sqrt(atof(cell.c_str())));

    // read eigen vectors, values in BGR order
    std::getline(kl_file, line);
    lineStream.clear();
    lineStream.str(line);
    while (std::getline(lineStream, cell, ','))
        eig_vec_.push_back(atof(cell.c_str()));

    CHECK_EQ(eig_val_.size(), 3) << "The number of eigen values should be 3, but it is " << eig_val_.size();
    CHECK_EQ(eig_vec_.size(), 9) << "The number of values for eigen vectors should be 9, but it is " << eig_vec_.size();
}

template <typename Dtype>
void TsvDataLayer<Dtype>::get_random_kl_shift(std::vector<float> &shift, float kl_coef)
{
    memset(&shift[0], 0, shift.size() * sizeof(float));

    float a[3];
    a[0] = (float)(random_helper::normal_real() * kl_coef);
    a[1] = (float)(random_helper::normal_real() * kl_coef);
    a[2] = (float)(random_helper::normal_real() * kl_coef);

    for (int k = 0; k < 3; k++)
        for (int j = 0; j < 3; j++)
            shift[k] += eig_vec_[j * 3 + k] * eig_val_[j] * a[j];
}

template <typename Dtype>
cv::Rect TsvDataLayer<Dtype>::get_crop_rect(const cv::Mat &img, const TsvDataParameter &tsv_param)
{
    int width = img.cols;
    int height = img.rows;
    int x_off, y_off, crop_w, crop_h;

    if (this->phase_ == TEST)
    {
        float scale_target = 0.875; // 0.875 = 224 / 256
        int crop_size = (int)(std::min(height, width) * scale_target);
        x_off = (width - crop_size) / 2;
        y_off = (height - crop_size) / 2;
        crop_w = crop_h = crop_size;
    }
    else
    {
        if (tsv_param.crop_type() == TsvDataParameter_CropType_ResnetStyle)
        {
            float scale_lower = 0.467; // 256 * 0.467 = 119.552
            float scale_upper = 0.875; // 256 * 0.875 = 224
            float scale_target = scale_lower + (scale_upper - scale_lower) * random_helper::uniform_real();

            int crop_size = (int)(std::min(height, width) * scale_target);
            y_off = random_helper::uniform_int(0, height - crop_size + 1 - 1);
            x_off = random_helper::uniform_int(0, width - crop_size + 1 - 1);
            crop_w = crop_h = crop_size;
        }
        else if (tsv_param.crop_type() == TsvDataParameter_CropType_InceptionStyle)
        {
            int area = width * height;
            // try up to 10 times
            int attempt = 0;
            for (attempt = 0; attempt < 10; attempt++)
            {
                float target_area_ratio = (float)random_helper::uniform_real(0.08, 1.0);
                float target_area = target_area_ratio * area;
                float target_aspect_ratio = (float)random_helper::uniform_real(3.0/4.0, 4.0/3.0);
                crop_w = sqrt(target_area * target_aspect_ratio) + 0.5;
                crop_h = sqrt(target_area / target_aspect_ratio) + 0.5;
                if (random_helper::uniform_int(0, 1))
                    std::swap(crop_w, crop_h);

                if (crop_h <= height && crop_w <= width)
                {
                    x_off = crop_w < width ? random_helper::uniform_int(0, width - crop_w + 1 - 1) : 0;
                    y_off = crop_h < height ? random_helper::uniform_int(0, height - crop_h + 1 - 1) : 0;
                    break;
                }
            }

            if (attempt >= 10)
            {
                x_off = y_off = 0;
                crop_w = width;
                crop_h = height;
            }
        }
    }

    return cv::Rect(x_off, y_off, crop_w, crop_h);
}

template <typename Dtype>
void TsvDataLayer<Dtype>::CVMatToBlobBuffer(const cv::Mat &cv_img_float, Dtype *buffer)
{
    int channels = cv_img_float.channels();
    int height = cv_img_float.rows;
    int width = cv_img_float.cols;
    for (int h = 0; h < height; ++h) {
        const float* ptr = cv_img_float.ptr<float>(h);
        int img_index = 0;
        for (int w = 0; w < width; ++w) {
            for (int c = 0; c < channels; ++c) {
                int index = (c * height + h) * width + w;
                buffer[index] = static_cast<Dtype>(ptr[img_index++]);
            }
        }
    }
}

template <typename Dtype>
void TsvDataLayer<Dtype>::process_one_image_and_label(const string &input_b64coded_data, const string &input_label_data, const TsvDataParameter &tsv_param, Dtype *output_image_data, Dtype *output_label_data)
{
    process_one_image(input_b64coded_data, tsv_param, output_image_data);
    process_one_label(input_label_data, tsv_param, output_label_data);
}

template <typename Dtype>
void TsvDataLayer<Dtype>::process_one_image(const cv::Mat &img_origin, const TsvDataParameter &tsv_param, Dtype *output_image_data)
{
    if (tsv_param.crop_type() == TsvDataParameter_CropType_AlexStyle) {
        Datum datum;
        CVMatToDatum(img_origin, &datum);
        this->data_transformer_->TransformData(datum, output_image_data);
    } else {
        // crop
        cv::Rect crop_rect = get_crop_rect(img_origin, tsv_param);
        cv::Mat img_crop = img_origin(crop_rect).clone();

        // flip
        if (this->phase_ == TRAIN && random_helper::uniform_int(0, 1))
            cv::flip(img_crop, img_crop, 1);

        // convert to float
        cv::Mat img_float;
        img_crop.convertTo(img_float, CV_32F);

        if (tsv_param.channels() > 1) {
            std::vector<float> shift(3);
            // color jittering
            if (this->phase_ == TRAIN && tsv_param.has_color_kl_file())
                get_random_kl_shift(shift, 0.1);

            // mean subtraction
            shift[0] -= mean_values_[0];
            shift[1] -= mean_values_[1];
            shift[2] -= mean_values_[2];

            int nChannel = img_float.channels();
            for (int y = 0; y < img_float.rows; y++) {
                float *pImg = (float*)img_float.ptr(y);
                for (int x = 0; x < img_float.cols; x++) {
                    pImg[nChannel*x] += shift[0];
                    pImg[nChannel*x + 1] += shift[1];
                    pImg[nChannel*x + 2] += shift[2];
                }
            }
        } else {
            float shift = 0;
            // mean subtraction
            shift -= mean_values_[0];
            for (int y = 0; y < img_float.rows; y++) {
                float *pImgStart = (float*)img_float.ptr(y);
                for (float* pImg = pImgStart; pImg<pImgStart + img_float.cols; pImg++) {
                    *pImg += shift;
                }
            }
        }
        // resize
        cv::Mat cvImg;
        int crop_size = this->layer_param().transform_param().crop_size();
        cv::resize(img_float, cvImg, cv::Size(crop_size, crop_size));

        // copy to output buffer
        CVMatToBlobBuffer(cvImg, output_image_data);
    }
    // Default pixel_value_scale is 255 in caffe.proto. The following function will not change the pixel values by default.
    // But if pixel_value_scale is set to 1 and the mean_values to (0,0,0), we will be able to set the pixel value range to [0,1].
    int crop_size = this->layer_param().transform_param().crop_size();
    caffe_cpu_scale(crop_size * crop_size * tsv_param.channels(), Dtype(255) / tsv_param.pixel_value_scale(), output_image_data, output_image_data);
}

template <typename Dtype>
void TsvDataLayer<Dtype>::process_one_image(const string &input_b64coded_data, const TsvDataParameter &tsv_param, Dtype *output_image_data)
{
    if (tsv_param.data_format() == TsvDataParameter_DataFormat_ImagePath)
    {
        cv::Mat img_origin;
        if (tsv_param.crop_type() == TsvDataParameter_CropType_AlexStyle) {
            img_origin = ReadImageToCVMat(input_b64coded_data, tsv_param.new_height(), tsv_param.new_width(), tsv_param.channels() > 1);
        } else {
            img_origin = ReadImageToCVMat(input_b64coded_data, tsv_param.channels() > 1);
        }
        process_one_image(img_origin, tsv_param, output_image_data);
    }
    else if (tsv_param.data_format() == TsvDataParameter_DataFormat_Image)
    {
        vector<BYTE> data = base64_decode(input_b64coded_data);
        cv::Mat img_origin;
        if (tsv_param.crop_type() == TsvDataParameter_CropType_AlexStyle) {
            img_origin = ReadImageStreamToCVMat(data, tsv_param.new_height(), tsv_param.new_width(), tsv_param.channels() > 1);
        } else {
            img_origin = ReadImageStreamToCVMat(data, -1, -1, tsv_param.channels() > 1);
        }
        process_one_image(img_origin, tsv_param, output_image_data);
    }
    else if (tsv_param.data_format() == TsvDataParameter_DataFormat_RawData)
    {
        vector<BYTE> data = base64_decode(input_b64coded_data);
        caffe_copy(tsv_param.new_height() * tsv_param.new_width() * tsv_param.channels(), (Dtype*)&data[0], output_image_data);
    }
}

template <typename Dtype>
void TsvDataLayer<Dtype>::process_one_label(const string &input_label_data, const TsvDataParameter &tsv_param, Dtype *output_label_data)
{
    if (this->output_labels_) {
        int label_dim = tsv_param.label_dim();
        if (label_dim == 1)   // single label case
        {
            output_label_data[0] = atoi(input_label_data.c_str());
        }
        else
        {
            std::stringstream lineStream(input_label_data);
            string cell;
            vector<Dtype> labels;
            if (tsv_param.unroll_label())  // for multi-hot labels
            {
                labels.resize(label_dim);
                memset(&labels[0], 0, label_dim * sizeof(int));
                while (std::getline(lineStream, cell, ';'))
                {
                    int lbl = atoi(cell.c_str());
                    CHECK_LT(lbl, label_dim) << "Label value is too large! Dim = " << label_dim << ", but label is: " << lbl;
                    if (lbl >= 0)       // ignore negative padding values
                        labels[lbl] = 1;
                }
            }
            else  // for compact format labels
            {
                while (std::getline(lineStream, cell, ';'))
                {
                    labels.push_back(atoi(cell.c_str()));
                    if (labels.size() == label_dim)
                    {
                        LOG(FATAL) << "Too many labels! label_dim = " << label_dim << ", but labels are: " << input_label_data;
                        break;
                    }
                }
                for (int i = labels.size(); i < label_dim; i++)
                    labels.push_back(-1);
            }
            caffe_copy(label_dim, &labels[0], output_label_data);
        }
    }

}

template <typename Dtype>
bool TsvDataLayer<Dtype>::Skip() {
    // In test mode, only rank 0 (of each node) runs, so avoid skipping within a node
    if (this->layer_param_.phase() == TEST)
        return offset_ % world_size_ != 0;  // for world_size == 1, this is always false
    int size = Caffe::solver_count() * world_size_;
    int rank = Caffe::solver_count() * world_rank_ + Caffe::solver_rank();
    bool keep = (offset_ % size) == rank;
    return !keep;
}

template<typename Dtype>
void TsvDataLayer<Dtype>::Next() {
    bool has_separate_label_file = tsv_label_ != nullptr;
    if (tsv_->IsEOF()) {
        LOG_IF(INFO, Caffe::root_solver())
            << "Restarting data prefetching from start.";
        tsv_->MoveToFirst();
    }
    tsv_->MoveToNext();
    if (has_separate_label_file)
    {
        if (tsv_label_->IsEOF()) {
            LOG_IF(INFO, Caffe::root_solver())
                << "Restarting label prefetching from start.";
            tsv_label_->MoveToFirst();
        }
        tsv_label_->MoveToNext();
    }
}

template <typename Dtype>
void TsvDataLayer<Dtype>::on_load_batch_start(Batch<Dtype>* batch)
{
    const TsvDataParameter &tsv_param = this->layer_param().tsv_data_param();
    int crop_size = this->layer_param().transform_param().crop_size();

    vector<int> shape = batch->data_.shape();
    shape[2] = crop_size > 0 ? crop_size : tsv_param.new_height();
    shape[3] = crop_size > 0 ? crop_size : tsv_param.new_width();
    batch->data_.Reshape(shape);
}

template <typename Dtype>
void TsvDataLayer<Dtype>::on_load_batch_end(Batch<Dtype>* batch)
{
}

// This function is called on prefetch thread
template <typename Dtype>
void TsvDataLayer<Dtype>::load_batch(Batch<Dtype>* batch) {
	CPUTimer batch_timer;
	batch_timer.Start();
	double read_time = 0;
	double trans_time = 0;
	CPUTimer timer;
	CHECK(batch->data_.count());

    on_load_batch_start(batch);

	if (this->output_labels_) {
        memset(batch->label_.mutable_cpu_data(), 0, batch->label_.count() * sizeof(Dtype));
	}

    const TsvDataParameter &tsv_param = this->layer_param().tsv_data_param();
    int batch_size = tsv_param.batch_size();

    vector<string> base64coded_data;
    vector<string> label;
    bool has_separate_label_file = tsv_label_ != nullptr;
    timer.Start();
	for (int item_id = 0; item_id < batch_size; ++item_id)
	{
        while (Skip()) {
            Next();
            offset_++;
        }
        if (tsv_->IsEOF())
        {
            LOG_IF(INFO, Caffe::root_solver()) << "Restarting data prefetching from start.";
            tsv_->MoveToFirst();
        }
        int result = tsv_->ReadNextLine(base64coded_data, label);
        CHECK(result == 0) << "Data: empty line or unexpected EOF.";
		if (has_separate_label_file)
		{
			if (tsv_label_->IsEOF())
			{
                LOG_IF(INFO, Caffe::root_solver()) << "Restarting label prefetching from start.";
				tsv_label_->MoveToFirst();
            }
            int result_label = tsv_label_->ReadNextLine(base64coded_data, label);
            CHECK(result_label == 0) << "Label: empty line or unexpected EOF.";
        }
        // TsvRawDataFile allows sequential read. After calling ReadNextLine, the so-called cursor is
        // already pointing to the next line. So we don't need to call Next()
        offset_++;
	}
	read_time += timer.MicroSeconds();

	timer.Start();
    Dtype *batch_data = batch->data_.mutable_cpu_data();
    Dtype *label_data = batch->label_.mutable_cpu_data();
    CHECK_EQ(base64coded_data.size(), label.size());
#ifdef _MSC_VER
    parallel_for((size_t)0, base64coded_data.size(), [&](size_t i) {
#else
    #pragma omp parallel for schedule(static)
    for (long long i = 0; i < base64coded_data.size(); i++) {
#endif // _MSC_VER
        process_one_image_and_label(base64coded_data[i], label[i], tsv_param, batch_data + batch->data_.offset(i), label_data + batch->label_.offset(i));
    }
#ifdef _MSC_VER
    );
#endif
    on_load_batch_end(batch);
    trans_time += timer.MicroSeconds();

    timer.Stop();
	batch_timer.Stop();
    DLOG_IF(INFO, Caffe::root_solver()) << "Prefetch batch: " << batch_timer.MilliSeconds() << " ms.";
    DLOG_IF(INFO, Caffe::root_solver()) << "     Read time: " << read_time / 1000 << " ms.";
    DLOG_IF(INFO, Caffe::root_solver()) << "Transform time: " << trans_time / 1000 << " ms.";
}

INSTANTIATE_CLASS(TsvDataLayer);
REGISTER_LAYER_CLASS(TsvData);

}  // namespace caffe

max_stars_repo_name: MSRCCS/Caffe

max_issues_repo_name: MSRCCS/Caffe

max_forks_repo_name: MSRCCS/Caffe


text:
#include <igl/readDMAT.h>
#include <Eigen/Core>

void read_transformation(const std::string filename, std::vector<Eigen::Matrix4d> & Transformations){
    Eigen::MatrixXd bigT;
    igl::readDMAT(filename,bigT);
    for (int i = 0; i<(bigT.rows()/4); i++) {
        Transformations.push_back(bigT.block(4*i,0,4,4));
    }
}

max_stars_repo_name: sgsellan/swept-volumes

max_issues_repo_name: sgsellan/swept-volumes

max_forks_repo_name: sgsellan/swept-volumes


text: #include <boost/graph/parallel/properties.hpp>

ext: hpp

max_stars_repo_name: miathedev/BoostForArduino

max_issues_repo_name: miathedev/BoostForArduino

max_forks_repo_name: miathedev/BoostForArduino


text:
//
// $Id$
//
// -------------------------------------------------------------------------
// This file is part of ZeroBugs, Copyright (c) 2010 Cristian L. Vlasceanu
//
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
// -------------------------------------------------------------------------
//
#include "gui.h"
#include "app_slots.h"
#include "zdk/debug_symbol_list.h"
#include "zdk/check_ptr.h"
#include "zdk/data_filter.h"
#include "zdk/data_type.h"
#include "zdk/zero.h"
#include "zdk/zobject_scope.h"

#include "auto_condition.h"
#include "generic/lock.h"
#include "gtkmm/flags.h"
#include "gtkmm/widget.h"
#include "dharma/environ.h"
#include "dharma/symbol_util.h"
#include "engine/query_symbols.h"
#include "engine/query_type.h"
#include "message_box.h"
#include "popup_list.h" // for auto_complete
#include "text_entry.h" // for auto_complete
#include "slot_macros.h"

#include <string>
#include <boost/utility.hpp>

using namespace std;
using namespace boost;

namespace
{
    /**
     * Saves stack traces to output stream.
     */
    class ZDK_LOCAL StackTraceSaver
        : public EnumCallback<Process*>
        , public EnumCallback<Thread*>
    {
        ostream& out_;

    public:
        explicit StackTraceSaver(ostream& out) : out_(out) { }

        void notify(Process* proc)
        {
            if (proc)
            {
                out_ << "===== Process " << proc->pid() << " =====\n";
                proc->enum_threads(this);
            }
        }

        void notify(Thread* thread)
        {
            if (thread)
            {
                out_ << "----- Thread lwpid=" << thread->lwpid();
                out_ << " id=" << thread->thread_id() << " -----\n";

                StackTrace* trace = thread->stack_trace();
                for (size_t i = 0; i != trace->size(); ++i)
                {
                    out_ << "#" << i << " ";
                    RefPtr<Symbol> sym = trace->frame(i)->function();
                    if (sym)
                    {
                        out_ << sym;
                    }
                    out_ << endl;
                }
            }
        }
    };
} // namespace

static LookupScope right_click_scope()
{
    static LookupScope lookupScope = LOOKUP_LOCAL;

    if (lookupScope == LOOKUP_LOCAL)
    {
        string scope = env::get_string("ZERO_RIGHT_CLICK_SCOPE", "unit");

        if (scope == "all")
        {
            lookupScope = LOOKUP_ALL;
        }
        else if (scope == "module")
        {
            lookupScope = LOOKUP_MODULE;
        }
        else
        {
            lookupScope = LOOKUP_UNIT;
        }
    }
    return lookupScope;
}

AppSlots::AppSlots(Debugger& dbg) : ThreadMarshaller(dbg)
{
}

void
AppSlots::read_symbol(RefPtr<DebugSymbol> sym, DebugSymbolEvents* events)
{
    if (is_ui_thread())
    {
        call_on_main_thread(&AppSlots::read_symbol, sym, events);
    }
    else
    {
        MainThreadScope scope(mainThreadMutex_, mainThreadReady_);

        if (sym)
        {
            sym->read(events);
        }
    }
}

void AppSlots::save_stack(ostream* outp)
{
    if (is_ui_thread())
    {
        call_on_main_thread(&AppSlots::save_stack, outp);
    }
    else
    {
        MainThreadScope scope(mainThreadMutex_, mainThreadReady_);

        StackTraceSaver saver(*outp);
        debugger().enum_processes(&saver);
    }
}

BEGIN_SLOT_(bool, AppSlots::on_evaluate,
(
    RefPtr<Thread>  thread,
    string          expr,
    addr_t          addr,
    ExprEvents*     events,
    int             base
))
{
    static bool evalComplete = true;

    if (is_ui_thread())
    {
        call_on_main_thread(&AppSlots::on_evaluate,
                            thread,
                            expr,
                            addr,
                            events,
                            base);
        if (!evalComplete)
        {
            post_response(new ResumeCommand);
            dbgout(0) << __func__ << ": resume command posted" << endl;
        }
    }
    else
    {
        MainThreadScope scope(mainThreadMutex_, mainThreadReady_);

        if (thread)
        {
            try
            {
                evalComplete = debugger().evaluate( expr.c_str(),
                                                    thread.get(),
                                                    addr,
                                                    events,
                                                    base);
            }
            catch (const std::exception& e)
            {
                cerr << __func__ << ": " << e.what() << endl;
            }
        }
    }
    return evalComplete;
}
END_SLOT_(true)

BEGIN_SLOT(AppSlots::on_query_symbols,
(
    RefPtr<Thread>      thread,
    string              name,
    addr_t              addr,
    DebugSymbolList*    syms,
    bool                readValues
))
{
    assert(syms);

    if (is_ui_thread())
    {
        call_on_main_thread(&AppSlots::on_query_symbols,
                            thread, name, addr, syms, readValues);
    }
    else
    {
        MainThreadScope scope(mainThreadMutex_, mainThreadReady_);

        if (thread)
        {
            RefPtr<Symbol> fun;

            if (addr)
            {
                fun = CHKPTR(thread->symbols())->lookup_symbol(addr);
            }
            const LookupScope scope = right_click_scope();
            query_debug_symbols(thread, name.c_str(), fun, *syms, scope);
            if (readValues)
            {
                for (DebugSymbolList::iterator i = syms->begin();
                     i != syms->end();
                     ++i)
                {
                    (*i)->read(NULL);
                }
            }
        }
    }
}
END_SLOT()

BEGIN_SLOT_(RefPtr<DataType>, AppSlots::on_query_type,
(
    RefPtr<Thread> thread,
    string name,
    addr_t addr
))
{
    assert(thread.get()); // pre-condition

    static RefPtr<DataType> type;

    if (is_ui_thread())
    {
        call_on_main_thread(&AppSlots::on_query_type, thread, name, addr);
    }
    else
    {
        MainThreadScope scope(mainThreadMutex_, mainThreadReady_);

        if (thread)
        {
            TypeLookupHelper helper(*thread, name, addr);
            debugger().enum_plugins(&helper);

            type = helper.type();
        }
    }
    return type;
}
END_SLOT_(0)

BEGIN_SLOT(AppSlots::step_over_func, (RefPtr<Symbol> sym))
{
    if (sym)
    {
        if (is_ui_thread())
        {
            CALL_MAIN_THREAD_(command(&AppSlots::step_over_func, this, sym));
        }
        else
        {
            //
            // get the beginning of current function
            //
            RefPtr<Symbol> func = sym;
            if (sym->offset())
            {
                addr_t addr = sym->addr() - sym->offset();
                //ZObjectScope scope;
                // func = sym->table(&scope)->lookup_symbol(addr);
                if (RefPtr<Thread> thread = current_thread())
                {
                    func = CHKPTR(thread->symbols())->lookup_symbol(addr);
                }
            }
            if (func)
            {
                dbgout(0) << __func__ << ": " << *func << endl;
                debugger().add_step_over(func->file(), func->line());
            }
        }
    }
}
END_SLOT()

BEGIN_SLOT(AppSlots::step_over_file,(RefPtr<Symbol> sym))
{
    if (sym)
    {
        if (is_ui_thread())
        {
            CALL_MAIN_THREAD_(command(&AppSlots::step_over_file, this, sym));
        }
        else
        {
            dbgout(0) << __func__ << ": " << *sym << endl;
            debugger().add_step_over(sym->file(), 0);
        }
    }
#if DEBUG
    else
    {
        throw runtime_error(__func__ + string(": null symbol"));
    }
#endif
}
END_SLOT()

BEGIN_SLOT(AppSlots::step_over_dir,(RefPtr<Symbol> sym))
{
    if (sym)
    {
        if (is_ui_thread())
        {
            CALL_MAIN_THREAD_(command(&AppSlots::step_over_dir, this, sym));
        }
        else
        {
            dbgout(0) << __func__ << ": " << *sym << endl;
            debugger().add_step_over(sym->file(), -1);
        }
    }
#if DEBUG
    else
    {
        throw runtime_error(__func__ + string(": null symbol"));
    }
#endif
}
END_SLOT()

BEGIN_SLOT(AppSlots::step_over_reset,(RefPtr<Symbol> sym))
{
    if (is_ui_thread())
    {
        CALL_MAIN_THREAD_(command(&AppSlots::step_over_reset, this, sym));
    }
    else
    {
        dbgout(0) << __func__ << endl;
        debugger().remove_step_over(0, 0);
    }
}
END_SLOT()

BEGIN_SLOT(AppSlots::step_over_delete,(RefPtr<SharedString> path, long line))
{
    assert(path);

    if (is_ui_thread())
    {
        CALL_MAIN_THREAD_(command(&AppSlots::step_over_delete, this, path, line));
    }
    else
    {
        dbgout(0) << __func__ << ": " << path->c_str() << ":" << line << endl;
        debugger().remove_step_over(path.get(), line);
    }
}
END_SLOT()

BEGIN_SLOT_(bool,
AppSlots::on_auto_complete,(TextEntry* textEntry,
                            string prev,
                            bool useUnmappedLibs))
{
    if (RefPtr<Thread> thread = current_thread())
    {
        string text = textEntry->get_text(false);

        if (text.empty())
        {
            if (popupList_)
            {
                popupList_->hide();
            }
        }
        else
        {
            FunctionEnum syms; // collects enumeration results

            SymbolTable::LookupMode mode =
                SymbolTable::LKUP_RANGE | SymbolTable::LKUP_DYNAMIC;

            if (useUnmappedLibs)
            {
                mode = (mode | SymbolTable::LKUP_UNMAPPED);
            }

            thread->symbols()->enum_symbols(text.c_str(), &syms, mode);

            set<string> names;

            for (SymbolEnum::const_iterator i = syms.begin();
                    i != syms.end();
                    ++i)
            {
                RefPtr<SharedString> s = (*i)->demangled_name(false);
                if (s && s->length())
                {
                    names.insert(s->c_str());
                }
            }
            if (!popupList_)
            {
                popupList_.reset(new PopupList);
            }
            if (names.empty())
            {
                popupList_->hide();
            }
            else
            {
                popupList_->set_text_entry(textEntry);
                popupList_->show_all();

                if (names.size() > 1)
                {
                    popupList_->set_items(names);
                }
                else if (text.size() > prev.size())
                {
                    text = *names.begin();
                    popupList_->set_text_and_hide(text);
                }
            }
        }
    }
}
END_SLOT_(true)

////////////////////////////////////////////////////////////////
bool
AppSlots::on_apply_filter(RefPtr<DebugSymbol>* symbol,
                          RefPtr<DebugSymbol>  parent,
                          DebugSymbolEvents*   events)
{
    if (!symbol)
    {
        return false;
    }
    if (is_ui_thread())
    {
        call_on_main_thread(&AppSlots::on_apply_filter, symbol, parent, events);

        if (symbol->is_null())
        {
            return false;
        }
    }
    else
    {
        MainThreadScope scope(mainThreadMutex_, mainThreadReady_);

        if (DataFilter* filter = interface_cast<DataFilter*>(&debugger()))
        {
            if (filter->hide(symbol->get()))
            {
                symbol->reset();
                return false;
            }
            RefPtr<DebugSymbol> sym =
                filter->transform(symbol->get(), parent.get(), events);

            if (sym && (sym != *symbol))
            {
                if (events)
                {
                    if (events->is_expanding(symbol->get()))
                    {
                        //sym->read(events);
                        events->symbol_change(sym.get(), symbol->get());
                    }
                }
                *symbol = sym;
            }
        }
    }
    return true;
}

////////////////////////////////////////////////////////////////
BEGIN_SLOT(AppSlots::update_stack_on_main_thread,())
{
    if (is_ui_thread())
    {
        call_on_main_thread(&AppSlots::update_stack_on_main_thread);
    }
    else
    {
        MainThreadScope scope(mainThreadMutex_, mainThreadReady_);
        update_stack_view();
    }
}
END_SLOT()

////////////////////////////////////////////////////////////////
BEGIN_SLOT(AppSlots::on_menu_delete_breakpoint,
(
    addr_t addr,
    size_t line
))
{
    if (is_ui_thread())
    {
        call_on_main_thread(&AppSlots::on_menu_delete_breakpoint, addr, line);

        // When the remove_user_breakpoint call succeeds,
        // an on_remove_breakpoint() notification will be sent.
        // should not need to update, but does it hurt?
        update_breakpoint_view(addr, line);
    }
    else
    {
        MainThreadScope scope(mainThreadMutex_, mainThreadReady_);

        // clear breakpoint globally: this needs to change when
        // per-thread breakpoints are better supported in the UI
        debugger().remove_user_breakpoint(0, 0, addr);
    }
}
END_SLOT()
// vim: tabstop=4:softtabstop=4:expandtab:shiftwidth=4

max_stars_repo_name: cristivlas/zerobugs

max_issues_repo_name: cristivlas/zerobugs

max_forks_repo_name: cristivlas/zerobugs


text:
/**
 *  @copyright Copyright 2018 The J-PET Framework Authors. All rights reserved.
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may find a copy of the License in the LICENCE file.
 *
 *  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.
 *
 *  @file JPetUnzipAndUnpackTaskTest.cpp
 */

#define BOOST_TEST_DYN_LINK
#define BOOST_TEST_MODULE JPetUnzipAndUnpackTaskTest

#include "JPetUnzipAndUnpackTask/JPetUnzipAndUnpackTask.h"

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

BOOST_AUTO_TEST_SUITE(JPetUnzipAndUnpackTaskTestSuite)

BOOST_AUTO_TEST_CASE(sucessGz)
{
  boost::filesystem::remove("unitTestData/JPetTaskChainExecutorUtilsTest/goodGZ");
  BOOST_REQUIRE(JPetUnzipAndUnpackTask::unzipFile("unitTestData/JPetTaskChainExecutorUtilsTest/goodGZ.gz"));
}

BOOST_AUTO_TEST_CASE(tryToUnzipSomethingNotExistingFileWithGz)
{
  std::string initialPath = boost::filesystem::path(boost::filesystem::current_path()).string();
  initialPath = initialPath.substr(0, initialPath.find("build"));
  std::string wrongZipPath = initialPath + "wrongGZ.gz";
  BOOST_REQUIRE(!JPetUnzipAndUnpackTask::unzipFile(wrongZipPath.c_str()));
  BOOST_REQUIRE(!JPetUnzipAndUnpackTask::unzipFile("unitTestData/JPetTaskChainExecutorUtilsTest/wrongGZ.gz"));
}

BOOST_AUTO_TEST_CASE(sucessXz)
{
  boost::filesystem::remove("unitTestData/JPetTaskChainExecutorUtilsTest/goodXZ");
  BOOST_REQUIRE(JPetUnzipAndUnpackTask::unzipFile("unitTestData/JPetTaskChainExecutorUtilsTest/goodXZ.xz"));
}

BOOST_AUTO_TEST_CASE(tryToUnzipSomethingNotExistingFileWithXz)
{
  std::string initialPath = boost::filesystem::path(boost::filesystem::current_path()).string();
  initialPath = initialPath.substr(0, initialPath.find("build"));
  std::string wrongZipPath = initialPath + "unitTestData/JPetTaskChainExecutorUtilsTest/wrongXZ.Xz";
  BOOST_REQUIRE(!JPetUnzipAndUnpackTask::unzipFile(wrongZipPath.c_str()));
  BOOST_REQUIRE(!JPetUnzipAndUnpackTask::unzipFile("unitTestData/JPetTaskChainExecutorUtilsTest/wrongXZ.xz"));
}

BOOST_AUTO_TEST_CASE(sucessBz2)
{
  boost::filesystem::remove("unitTestData/JPetTaskChainExecutorUtilsTest/goodBZ2");
  BOOST_REQUIRE(JPetUnzipAndUnpackTask::unzipFile("unitTestData/JPetTaskChainExecutorUtilsTest/goodBZ2.bz2"));
}

BOOST_AUTO_TEST_CASE(tryToUnzipSomethingNotExistingFileWithBz2)
{
  std::string initialPath = boost::filesystem::path(boost::filesystem::current_path()).string();
  initialPath = initialPath.substr(0, initialPath.find("build"));
  std::string wrongZipPath = initialPath + "unitTestData/JPetTaskChainExecutorUtilsTest/wrongBZ2.bz2";
  BOOST_REQUIRE(!JPetUnzipAndUnpackTask::unzipFile(wrongZipPath.c_str()));
  BOOST_REQUIRE(!JPetUnzipAndUnpackTask::unzipFile("unitTestData/JPetTaskChainExecutorUtilsTest/wrongBZ2.bz2"));
}

BOOST_AUTO_TEST_CASE(sucessZip)
{
  boost::filesystem::remove("unitTestData/JPetTaskChainExecutorUtilsTest/goodZIP");
  BOOST_REQUIRE(JPetUnzipAndUnpackTask::unzipFile("unitTestData/JPetTaskChainExecutorUtilsTest/goodZIP.zip"));
}

BOOST_AUTO_TEST_CASE(tryToUnzipSomethingNotExistingFileWithZip)
{
  std::string initialPath = boost::filesystem::path(boost::filesystem::current_path()).string();
  initialPath = initialPath.substr(0, initialPath.find("build"));
  std::string wrongZipPath = initialPath + "unitTestData/JPetTaskChainExecutorUtilsTest/wrongZIP.zip";
  BOOST_REQUIRE(!JPetUnzipAndUnpackTask::unzipFile(wrongZipPath.c_str()));
  BOOST_REQUIRE(!JPetUnzipAndUnpackTask::unzipFile("unitTestData/JPetTaskChainExecutorUtilsTest/wrongZIP.zip"));
}

BOOST_AUTO_TEST_SUITE_END()

max_stars_repo_name: kdulski/j-pet-framework

max_issues_repo_name: kdulski/j-pet-framework

max_forks_repo_name: kdulski/j-pet-framework


text:
#include <memory>
#include <openssl/rsa.h>
#include <openssl/x509.h>
#include <boost/intrusive_ptr.hpp>
#include "certificate.hpp"

void intrusive_ptr_add_ref(EVP_PKEY* pkey)
{
  ::EVP_PKEY_up_ref(pkey);
}
void intrusive_ptr_release(EVP_PKEY* pkey)
{
  ::EVP_PKEY_free(pkey);
}

namespace nexus::test {

using evp_pkey_ptr = boost::intrusive_ptr<evp_pkey_st>;

struct x509_deleter { void operator()(x509_st* p) { ::X509_free(p); } };
using x509_ptr = std::unique_ptr<x509_st, x509_deleter>;

struct evp_pkey_ctx_deleter {
  void operator()(EVP_PKEY_CTX* p) { ::EVP_PKEY_CTX_free(p); };
};
using evp_pkey_ctx_ptr = std::unique_ptr<EVP_PKEY_CTX, evp_pkey_ctx_deleter>;

evp_pkey_ptr generate_rsa_key(int bits, error_code& ec)
{
  auto ctx = evp_pkey_ctx_ptr{::EVP_PKEY_CTX_new_id(EVP_PKEY_RSA, nullptr)};
  if (!ctx) {
    ec.assign(ERR_get_error(), boost::asio::error::get_ssl_category());
    return nullptr;
  }
  if (::EVP_PKEY_keygen_init(ctx.get()) != 1) {
    ec.assign(ERR_get_error(), boost::asio::error::get_ssl_category());
    return nullptr;
  }
  if (::EVP_PKEY_CTX_set_rsa_keygen_bits(ctx.get(), bits) != 1) {
    ec.assign(ERR_get_error(), boost::asio::error::get_ssl_category());
    return nullptr;
  }
  EVP_PKEY *pkey = nullptr;
  if (::EVP_PKEY_keygen(ctx.get(), &pkey) != 1) {
    ec.assign(ERR_get_error(), boost::asio::error::get_ssl_category());
    return nullptr;
  }
  constexpr bool add_ref = false; // EVP_PKEY_generate() starts with 1 ref
  return {pkey, add_ref};
}

int add_name_entry(X509_NAME* name, const char* field, std::string_view value)
{
  auto bytes = reinterpret_cast<const unsigned char*>(value.data());
  return ::X509_NAME_add_entry_by_txt(name, field, MBSTRING_ASC,
                                      bytes, value.size(), -1, 0);
}

x509_ptr self_sign_certificate(evp_pkey_ptr key,
                               std::string_view country,
                               std::string_view organization,
                               std::string_view common_name,
                               std::chrono::seconds duration,
                               error_code& ec)
{
  auto cert = x509_ptr{::X509_new()};
  if (!cert) {
    ec.assign(ERR_get_error(), boost::asio::error::get_ssl_category());
    return nullptr;
  }
  if (::X509_set_version(cert.get(), 2) != 1) {
    ec.assign(ERR_get_error(), boost::asio::error::get_ssl_category());
    return nullptr;
  }
  if (::ASN1_INTEGER_set(::X509_get_serialNumber(cert.get()), 1) != 1) {
    ec.assign(ERR_get_error(), boost::asio::error::get_ssl_category());
    return nullptr;
  }
  if (::X509_set_pubkey(cert.get(), key.get()) != 1) {
    ec.assign(ERR_get_error(), boost::asio::error::get_ssl_category());
    return nullptr;
  }
  if (!::X509_gmtime_adj(::X509_get_notBefore(cert.get()), 0)) {
    ec.assign(ERR_get_error(), boost::asio::error::get_ssl_category());
    return nullptr;
  }
  if (!::X509_gmtime_adj(::X509_get_notAfter(cert.get()), duration.count())) {
    ec.assign(ERR_get_error(), boost::asio::error::get_ssl_category());
    return nullptr;
  }
  auto name = ::X509_get_subject_name(cert.get());
  if (add_name_entry(name, "C", country) != 1) {
    ec.assign(ERR_get_error(), boost::asio::error::get_ssl_category());
    return nullptr;
  }
  if (add_name_entry(name, "O", organization) != 1) {
    ec.assign(ERR_get_error(), boost::asio::error::get_ssl_category());
    return nullptr;
  }
  if (add_name_entry(name, "CN", common_name) != 1) {
    ec.assign(ERR_get_error(), boost::asio::error::get_ssl_category());
    return nullptr;
  }
  if (::X509_set_issuer_name(cert.get(), name) != 1) {
    ec.assign(ERR_get_error(), boost::asio::error::get_ssl_category());
    return nullptr;
  }
  if (::X509_sign(cert.get(), key.get(), ::EVP_sha256()) == 0) {
    ec.assign(ERR_get_error(), boost::asio::error::get_ssl_category());
    return nullptr;
  }
  return cert;
}

void self_sign_certificate(ssl::context& ctx,
                           std::string_view country,
                           std::string_view organization,
                           std::string_view common_name,
                           std::chrono::seconds duration,
                           error_code& ec)
{
  auto key = test::generate_rsa_key(2048, ec);
  if (ec) {
    return;
  }
  auto cert = test::self_sign_certificate(key, country, organization,
                                          common_name, duration, ec);
  if (ec) {
    return;
  }
  if (::SSL_CTX_use_certificate(ctx.native_handle(), cert.get()) != 1) {
    ec.assign(ERR_get_error(), boost::asio::error::get_ssl_category());
    return;
  }
  if (::SSL_CTX_use_PrivateKey(ctx.native_handle(), key.get()) != 1) {
    ec.assign(ERR_get_error(), boost::asio::error::get_ssl_category());
    return;
  }
}

void self_sign_certificate(ssl::context& ctx,
                           std::string_view country,
                           std::string_view organization,
                           std::string_view common_name,
                           std::chrono::seconds duration)
{
  error_code ec;
  self_sign_certificate(ctx, country, organization, common_name, duration, ec);
  if (ec) {
    throw system_error(ec);
  }
}

int alpn_select_cb(SSL* ssl, const unsigned char** out, unsigned char* outlen,
                   const unsigned char* in, unsigned int inlen, void* arg)
{
  auto alpn = static_cast<const char*>(arg);
  int r = ::SSL_select_next_proto(const_cast<unsigned char**>(out), outlen,
                                  const_cast<unsigned char*>(in), inlen,
                                  reinterpret_cast<const unsigned char*>(alpn),
                                  strlen(alpn));
  if (r == OPENSSL_NPN_NEGOTIATED) {
    return SSL_TLSEXT_ERR_OK;
  } else {
    return SSL_TLSEXT_ERR_ALERT_FATAL;
  }
}

ssl::context init_client_context(const char* alpn)
{
  auto ctx = ssl::context{ssl::context::tlsv13};
  ::SSL_CTX_set_min_proto_version(ctx.native_handle(), TLS1_3_VERSION);
  ::SSL_CTX_set_max_proto_version(ctx.native_handle(), TLS1_3_VERSION);
  ::SSL_CTX_set_alpn_protos(ctx.native_handle(),
                            reinterpret_cast<const unsigned char*>(alpn),
                            strlen(alpn));
  return ctx;
}

ssl::context init_server_context(const char* alpn)
{
  auto ctx = ssl::context{ssl::context::tlsv13};
  ::SSL_CTX_set_min_proto_version(ctx.native_handle(), TLS1_3_VERSION);
  ::SSL_CTX_set_max_proto_version(ctx.native_handle(), TLS1_3_VERSION);
  ::SSL_CTX_set_alpn_select_cb(ctx.native_handle(), alpn_select_cb,
                               const_cast<char*>(alpn));
  self_sign_certificate(ctx, "US", "Nexus", "host", std::chrono::hours(24));
  return ctx;
}

} // namespace nexus::test

max_stars_repo_name: cbodley/nexus

max_issues_repo_name: cbodley/nexus

max_forks_repo_name: cbodley/nexus


text:
/*
 * Copyright (c) 2014, Stanislav Vorobiov
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * 1. Redistributions of source code must retain the above copyright notice, this
 *    list of conditions and the following disclaimer.
 * 2. 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.
 *
 * 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 "WeaponPistolComponent.h"
#include "SceneObject.h"
#include "Scene.h"
#include "SceneObjectFactory.h"
#include "AssetManager.h"
#include "Utils.h"
#include "Const.h"
#include "af/Utils.h"
#include <boost/make_shared.hpp>

namespace af
{
    WeaponPistolComponent::WeaponPistolComponent(SceneObjectType objectType)
    : WeaponComponent(objectType, WeaponTypePistol),
      damage_(0),
      velocity_(0),
      interval_(0),
      t_(0),
      snd_(audio.createSound("pistol_fire.ogg"))
    {
    }

    WeaponPistolComponent::~WeaponPistolComponent()
    {
    }

    void WeaponPistolComponent::accept(ComponentVisitor& visitor)
    {
        visitor.visitPhasedComponent(shared_from_this());
    }

    void WeaponPistolComponent::update(float dt)
    {
        t_ -= dt;

        if (t_ < (interval_ - 0.05f)) {
            flash_->setVisible(false);
            flashAc_->startAnimation(AnimationNone);
            light_->setVisible(false);
        }

        if ((t_ > 0.0f) || !triggerHeld()) {
            return;
        }

        if (!changeAmmo(1)) {
            return;
        }

        b2Transform xf = b2Mul(parent()->getTransform(),
            b2Transform(pos(), b2Rot(angle())));

        scene()->stats()->incShotsFired(this);

        SceneObjectPtr shot = sceneObjectFactory.createBullet(objectType(), 0.3f, damage_);

        float a = getRandom(-deg2rad(10.0f) / 2.0f, deg2rad(10.0f) / 2.0f);

        b2Transform realXf = xf;

        realXf.q = b2Mul(realXf.q, b2Rot(a));

        shot->setTransform(realXf);
        shot->setLinearVelocity(shot->getDirection(velocity_));

        scene()->addObject(shot);

        flash_->setPos(pos() + angle2vec(angle(), 0.32f * flash_->width() + flashDistance()));
        flash_->setAngle(angle());
        flash_->setVisible(true);
        flashAc_->startAnimation(AnimationDefault);

        light_->setPos(flash_->pos());
        light_->setVisible(true);

        if (haveSound()) {
            snd_->play();
        }

        t_ = interval_;
    }

    void WeaponPistolComponent::reload()
    {
        t_ = interval_;
    }

    void WeaponPistolComponent::onRegister()
    {
        DrawablePtr drawable = assetManager.getDrawable("factory4/flash1.png");

        float height = 2.5f;
        float width = height * drawable->image().aspect();

        flash_ =
            boost::make_shared<RenderQuadComponent>(
                pos() + angle2vec(angle(), 0.32f * width + flashDistance()),
                angle(), width, height,
                drawable, zOrderEffects);
        flash_->setColor(Color(1.0f, 1.0f, 1.0f, 1.0f));
        flash_->setVisible(false);

        parent()->addComponent(flash_);

        flashAc_ = boost::make_shared<AnimationComponent>(drawable);
        flashAc_->addAnimation(AnimationDefault, "flash");

        parent()->addComponent(flashAc_);

        light_ = boost::make_shared<PointLight>();
        light_->setVisible(false);
        light_->setColor(Color(0.4f, 0.4f, 0.0f, 1.0f));
        light_->setDiffuse(false);
        light_->setXray(true);
        light_->setDistance(6.0f);
        light_->setPos(flash_->pos());

        lightC_ = boost::make_shared<LightComponent>();

        lightC_->attachLight(light_);

        parent()->addComponent(lightC_);
    }

    void WeaponPistolComponent::onUnregister()
    {
        flash_->removeFromParent();
        flashAc_->removeFromParent();
        lightC_->removeFromParent();
    }
}

max_stars_repo_name: Sheph/TriggerTime

max_issues_repo_name: Sheph/TriggerTime

max_forks_repo_name: Sheph/TriggerTime


text:
//  (C) Copyright John Maddock 2006.
//  Use, modification and distribution are 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)

#include <boost/math/bindings/rr.hpp>
#include <boost/test/included/prg_exec_monitor.hpp>
#include <boost/math/special_functions/gamma.hpp>
#include <boost/math/special_functions/beta.hpp>
#include <boost/math/constants/constants.hpp>
#include <boost/math/tools/test.hpp>
#include <boost/lexical_cast.hpp>
#include <fstream>
#include <map>

#include <boost/math/tools/test_data.hpp>

using namespace boost::math::tools;
using namespace boost::math;
using namespace std;

template <class T>
struct ibeta_fraction1_t
{
   typedef std::pair<T, T> result_type;

   ibeta_fraction1_t(T a_, T b_, T x_) : a(a_), b(b_), x(x_), k(1) {}

   result_type operator()()
   {
      T aN;
      if(k & 1)
      {
         int m = (k - 1) / 2;
         aN = -(a + m) * (a + b + m) * x;
         aN /= a + 2*m;
         aN /= a + 2*m + 1;
      }
      else
      {
         int m = k / 2;
         aN = m * (b - m) *x;
         aN /= a + 2*m - 1;
         aN /= a + 2*m;
      }
      ++k;
      return std::make_pair(aN, T(1));
   }

private:
   T a, b, x;
   int k;
};

//
// This function caches previous calls to beta
// just so we can speed things up a bit:
//
template <class T>
T get_beta(T a, T b)
{
   static std::map<std::pair<T, T>, T> m;

   if(a < b)
      std::swap(a, b);

   std::pair<T, T> p(a, b);
   typename std::map<std::pair<T, T>, T>::const_iterator i = m.find(p);
   if(i != m.end())
      return i->second;

   T r = beta(a, b);
   p.first = a;
   p.second = b;
   m[p] = r;

   return r;
}

//
// compute the continued fraction:
//
template <class T>
T get_ibeta_fraction1(T a, T b, T x)
{
   ibeta_fraction1_t<T> f(a, b, x);
   T fract = boost::math::tools::continued_fraction_a(f, boost::math::policies::digits<T, boost::math::policies::policy<> >());
   T denom = (a * (fract + 1));
   T num = pow(x, a) * pow(1 - x, b);
   if(num == 0)
      return 0;
   else if(denom == 0)
      return -1;
   return num / denom;
}
//
// calculate the incomplete beta from the fraction:
//
template <class T>
std::pair<T,T> ibeta_fraction1(T a, T b, T x)
{
   T bet = get_beta(a, b);
   if(x > ((a+1)/(a+b+2)))
   {
      T fract = get_ibeta_fraction1(b, a, 1-x);
      if(fract/bet > 0.75)
      {
         fract = get_ibeta_fraction1(a, b, x);
         return std::make_pair(fract, bet - fract);
      }
      return std::make_pair(bet - fract, fract);
   }
   T fract = get_ibeta_fraction1(a, b, x);
   if(fract/bet > 0.75)
   {
      fract = get_ibeta_fraction1(b, a, 1-x);
      return std::make_pair(bet - fract, fract);
   }
   return std::make_pair(fract, bet - fract);

}
//
// calculate the regularised incomplete beta from the fraction:
//
template <class T>
std::pair<T,T> ibeta_fraction1_regular(T a, T b, T x)
{
   T bet = get_beta(a, b);
   if(x > ((a+1)/(a+b+2)))
   {
      T fract = get_ibeta_fraction1(b, a, 1-x);
      if(fract == 0)
         bet = 1;  // normalise so we don't get 0/0
      else if(bet == 0)
         return std::make_pair(T(-1), T(-1)); // Yikes!!
      if(fract / bet > 0.75)
      {
         fract = get_ibeta_fraction1(a, b, x);
         return std::make_pair(fract / bet, 1 - (fract / bet));
      }
      return std::make_pair(1 - (fract / bet), fract / bet);
   }
   T fract = get_ibeta_fraction1(a, b, x);
   if(fract / bet > 0.75)
   {
      fract = get_ibeta_fraction1(b, a, 1-x);
      return std::make_pair(1 - (fract / bet), fract / bet);
   }
   return std::make_pair(fract / bet, 1 - (fract / bet));
}

//
// we absolutely must trunctate the input values to float
// precision: we have to be certain that the input values
// can be represented exactly in whatever width floating
// point type we are testing, otherwise the output will
// necessarily be off.
//
float external_f;
float force_truncate(const float* f)
{
   external_f = *f;
   return external_f;
}

float truncate_to_float(boost::math::ntl::RR r)
{
   float f = boost::math::tools::real_cast<float>(r);
   return force_truncate(&f);
}

std::tr1::mt19937 rnd;
std::tr1::uniform_real<float> ur_a(1.0F, 5.0F);
std::tr1::variate_generator<std::tr1::mt19937, std::tr1::uniform_real<float> > gen(rnd, ur_a);
std::tr1::uniform_real<float> ur_a2(0.0F, 100.0F);
std::tr1::variate_generator<std::tr1::mt19937, std::tr1::uniform_real<float> > gen2(rnd, ur_a2);

struct beta_data_generator
{
   boost::math::tuple<boost::math::ntl::RR, boost::math::ntl::RR, boost::math::ntl::RR, boost::math::ntl::RR, boost::math::ntl::RR, boost::math::ntl::RR, boost::math::ntl::RR> operator()(boost::math::ntl::RR ap, boost::math::ntl::RR bp, boost::math::ntl::RR x_)
   {
      float a = truncate_to_float(real_cast<float>(gen() * pow(boost::math::ntl::RR(10), ap)));
      float b = truncate_to_float(real_cast<float>(gen() * pow(boost::math::ntl::RR(10), bp)));
      float x = truncate_to_float(real_cast<float>(x_));
      std::cout << a << " " << b << " " << x << std::endl;
      std::pair<boost::math::ntl::RR, boost::math::ntl::RR> ib_full = ibeta_fraction1(boost::math::ntl::RR(a), boost::math::ntl::RR(b), boost::math::ntl::RR(x));
      std::pair<boost::math::ntl::RR, boost::math::ntl::RR> ib_reg = ibeta_fraction1_regular(boost::math::ntl::RR(a), boost::math::ntl::RR(b), boost::math::ntl::RR(x));
      return boost::math::make_tuple(a, b, x, ib_full.first, ib_full.second, ib_reg.first, ib_reg.second);
   }
};

// medium sized values:
struct beta_data_generator_medium
{
   boost::math::tuple<boost::math::ntl::RR, boost::math::ntl::RR, boost::math::ntl::RR, boost::math::ntl::RR, boost::math::ntl::RR, boost::math::ntl::RR, boost::math::ntl::RR> operator()(boost::math::ntl::RR x_)
   {
      boost::math::ntl::RR a = gen2();
      boost::math::ntl::RR b = gen2();
      boost::math::ntl::RR x = x_;
      a = ConvPrec(a.value(), 22);
      b = ConvPrec(b.value(), 22);
      x = ConvPrec(x.value(), 22);
      std::cout << a << " " << b << " " << x << std::endl;
      //boost::math::ntl::RR exp_beta = boost::math::beta(a, b, x);
      std::pair<boost::math::ntl::RR, boost::math::ntl::RR> ib_full = ibeta_fraction1(boost::math::ntl::RR(a), boost::math::ntl::RR(b), boost::math::ntl::RR(x));
      /*exp_beta = boost::math::tools::relative_error(ib_full.first, exp_beta);
      if(exp_beta > 1e-40)
      {
         std::cout << exp_beta << std::endl;
      }*/
      std::pair<boost::math::ntl::RR, boost::math::ntl::RR> ib_reg = ibeta_fraction1_regular(boost::math::ntl::RR(a), boost::math::ntl::RR(b), boost::math::ntl::RR(x));
      return boost::math::make_tuple(a, b, x, ib_full.first, ib_full.second, ib_reg.first, ib_reg.second);
   }
};

struct beta_data_generator_small
{
   boost::math::tuple<boost::math::ntl::RR, boost::math::ntl::RR, boost::math::ntl::RR, boost::math::ntl::RR, boost::math::ntl::RR, boost::math::ntl::RR, boost::math::ntl::RR> operator()(boost::math::ntl::RR x_)
   {
      float a = truncate_to_float(gen2()/10);
      float b = truncate_to_float(gen2()/10);
      float x = truncate_to_float(real_cast<float>(x_));
      std::cout << a << " " << b << " " << x << std::endl;
      std::pair<boost::math::ntl::RR, boost::math::ntl::RR> ib_full = ibeta_fraction1(boost::math::ntl::RR(a), boost::math::ntl::RR(b), boost::math::ntl::RR(x));
      std::pair<boost::math::ntl::RR, boost::math::ntl::RR> ib_reg = ibeta_fraction1_regular(boost::math::ntl::RR(a), boost::math::ntl::RR(b), boost::math::ntl::RR(x));
      return boost::math::make_tuple(a, b, x, ib_full.first, ib_full.second, ib_reg.first, ib_reg.second);
   }
};

struct beta_data_generator_int
{
   boost::math::tuple<boost::math::ntl::RR, boost::math::ntl::RR, boost::math::ntl::RR, boost::math::ntl::RR, boost::math::ntl::RR, boost::math::ntl::RR, boost::math::ntl::RR> operator()(boost::math::ntl::RR a, boost::math::ntl::RR b, boost::math::ntl::RR x_)
   {
      float x = truncate_to_float(real_cast<float>(x_));
      std::cout << a << " " << b << " " << x << std::endl;
      std::pair<boost::math::ntl::RR, boost::math::ntl::RR> ib_full = ibeta_fraction1(a, b, boost::math::ntl::RR(x));
      std::pair<boost::math::ntl::RR, boost::math::ntl::RR> ib_reg = ibeta_fraction1_regular(a, b, boost::math::ntl::RR(x));
      return boost::math::make_tuple(a, b, x, ib_full.first, ib_full.second, ib_reg.first, ib_reg.second);
   }
};

int cpp_main(int, char* [])
{
   boost::math::ntl::RR::SetPrecision(1000);
   boost::math::ntl::RR::SetOutputPrecision(40);

   parameter_info<boost::math::ntl::RR> arg1, arg2, arg3, arg4, arg5;
   test_data<boost::math::ntl::RR> data;

   std::cout << "Welcome.\n"
      "This program will generate spot tests for the incomplete beta functions:\n"
      "  beta(a, b, x) and ibeta(a, b, x)\n\n"
      "This is not an interactive program be prepared for a long wait!!!\n\n";

   arg1 = make_periodic_param(boost::math::ntl::RR(-5), boost::math::ntl::RR(6), 11);
   arg2 = make_periodic_param(boost::math::ntl::RR(-5), boost::math::ntl::RR(6), 11);
   arg3 = make_random_param(boost::math::ntl::RR(0.0001), boost::math::ntl::RR(1), 10);
   arg4 = make_random_param(boost::math::ntl::RR(0.0001), boost::math::ntl::RR(1), 100 /*500*/);
   arg5 = make_periodic_param(boost::math::ntl::RR(1), boost::math::ntl::RR(41), 10);

   arg1.type |= dummy_param;
   arg2.type |= dummy_param;
   arg3.type |= dummy_param;
   arg4.type |= dummy_param;
   arg5.type |= dummy_param;

   // comment out all but one of the following when running
   // or this program will take forever to complete!
   //data.insert(beta_data_generator(), arg1, arg2, arg3);
   //data.insert(beta_data_generator_medium(), arg4);
   //data.insert(beta_data_generator_small(), arg4);
   data.insert(beta_data_generator_int(), arg5, arg5, arg3);

   test_data<boost::math::ntl::RR>::const_iterator i, j;
   i = data.begin();
   j = data.end();
   while(i != j)
   {
      boost::math::ntl::RR v1 = beta((*i)[0], (*i)[1], (*i)[2]);
      boost::math::ntl::RR v2 = relative_error(v1, (*i)[3]);
      std::string s = boost::lexical_cast<std::string>((*i)[3]);
      boost::math::ntl::RR v3 = boost::lexical_cast<boost::math::ntl::RR>(s);
      boost::math::ntl::RR v4 = relative_error(v3, (*i)[3]);
      if(v2 > 1e-40)
      {
         std::cout << v2 << std::endl;
      }
      if(v4 > 1e-60)
      {
         std::cout << v4 << std::endl;
      }
      ++ i;
   }

   std::cout << "Enter name of test data file [default=ibeta_data.ipp]";
   std::string line;
   std::getline(std::cin, line);
   boost::algorithm::trim(line);
   if(line == "")
      line = "ibeta_data.ipp";
   std::ofstream ofs(line.c_str());
   write_code(ofs, data, "ibeta_data");

   return 0;
}

max_stars_repo_name: ballisticwhisper/boost

max_issues_repo_name: ballisticwhisper/boost

max_forks_repo_name: ballisticwhisper/boost


text:
/**
 * @file test_updatePolicy.cpp
 * @brief This file defines the test cases for the update policy.
 *
 * @copyright Copyright (c) 2022
 *
 */

#include <boost/test/tools/floating_point_comparison.hpp>
#include <boost/test/unit_test.hpp>
#include <boost/test/unit_test_suite.hpp>
#include <vector>

#include "proseco_planning/action/actionClass.h"
#include "proseco_planning/policies/updatePolicy.h"

using namespace proseco_planning;

BOOST_AUTO_TEST_CASE(discountedReward) {
  auto discounted_reward = UpdatePolicy::discountedReward(0.99, 5, 10);
  BOOST_CHECK_CLOSE(discounted_reward, 9.509900499, 0.0001);
}

BOOST_AUTO_TEST_CASE(cumulativeDiscountedReward) {
  std::vector<float> rewards0{0.5f, 0.5f, 0.5f};
  std::vector<float> rewards1{2.f, 2.f, 2.f};
  std::vector<float> rewards2{5.f, 5.f, 5.f};
  std::vector<float> rewards3{-10.f, -10.f, -10.f};
  std::vector<std::vector<float>> agents_rewards{rewards0, rewards1, rewards2, rewards3};

  auto cumulative_discounted_reward0 =
      UpdatePolicy::cumulativeDiscountedReward(0.99, 1, 1, agents_rewards, 1);
  BOOST_CHECK_CLOSE(cumulative_discounted_reward0, 0.5, 0.0001);

  auto cumulative_discounted_reward1 =
      UpdatePolicy::cumulativeDiscountedReward(0.99, 1, 2, agents_rewards, 1);
  BOOST_CHECK_CLOSE(cumulative_discounted_reward1, 2.48, 0.0001);

  auto cumulative_discounted_reward2 =
      UpdatePolicy::cumulativeDiscountedReward(0.99, 2, 4, agents_rewards, 0);
  BOOST_CHECK_CLOSE(cumulative_discounted_reward2, -2.851, 0.0001);

  auto cumulative_discounted_reward3 =
      UpdatePolicy::cumulativeDiscountedReward(0.99, 1, 4, agents_rewards, 2);
  BOOST_CHECK_CLOSE(cumulative_discounted_reward3, -2.32249, 0.0001);
}


text:
#include <common/logger.hpp>
#include "graphsync_acceptance_common.hpp"
#include <boost/program_options.hpp>
#include <libp2p/multi/multibase_codec/multibase_codec_impl.hpp>
#include <libp2p/log/configurator.hpp>
#include <libp2p/log/logger.hpp>

#include <iostream>

// logger used by these tests
static std::shared_ptr<spdlog::logger> logger;

// max test case run time, always limited by various params
static size_t run_time_msec = 0;

// Test node aggregate
class Node {
public:
    // total requests sent by all nodes in a test case
    static size_t requests_sent;

    // total responses received by all nodes in a test case
    static size_t responses_received;

    // n_responses_expected: count of responses received by the node after which
    // io->stop() is called
    Node(std::shared_ptr<boost::asio::io_context> io,
        std::shared_ptr<sgns::ipfs_lite::ipfs::graphsync::MerkleDagBridge> data_service,
        sgns::ipfs_lite::ipfs::graphsync::Graphsync::BlockCallback cb,
        size_t n_responses_expected,
        std::optional<libp2p::crypto::KeyPair> keyPair)
        : io_(std::move(io)),
        data_service_(std::move(data_service)),
        block_cb_(std::move(cb)),
        n_responses_expected_(n_responses_expected)
    {
        if (keyPair)
            std::tie(graphsync_, host_) = createNodeObjects(io_, keyPair.value());
        else
            std::tie(graphsync_, host_) = createNodeObjects(io_);
    }

    // stops graphsync and host, otherwise they can interact with further tests!
    void stop() {
        graphsync_->stop();
        host_->stop();
    }

    // returns peer ID, so they can connect to each other
    auto getId() const {
        return host_->getId();
    }

    // listens to network and starts nodes if not yet started
    void listen(const libp2p::multi::Multiaddress& listen_to) {
        auto listen_res = host_->listen(listen_to);
        if (!listen_res) {
            logger->trace("Cannot listen to multiaddress {}, {}",
                listen_to.getStringAddress(),
                listen_res.error().message());
            return;
        }
        start();
    }

    // calls Graphsync's makeRequest
    void makeRequest(const libp2p::peer::PeerId& peer,
        boost::optional<libp2p::multi::Multiaddress> address,
        const sgns::CID& root_cid) {
        start();

        std::vector<sgns::ipfs_lite::ipfs::graphsync::Extension> extensions;
        sgns::ipfs_lite::ipfs::graphsync::ResponseMetadata response_metadata{};
        sgns::ipfs_lite::ipfs::graphsync::Extension response_metadata_extension =
            sgns::ipfs_lite::ipfs::graphsync::encodeResponseMetadata(response_metadata);
        extensions.push_back(response_metadata_extension);
        std::vector<sgns::CID> cids;
        sgns::ipfs_lite::ipfs::graphsync::Extension do_not_send_cids_extension =
            sgns::ipfs_lite::ipfs::graphsync::encodeDontSendCids(cids);
        extensions.push_back(do_not_send_cids_extension);
        // unused code , request_ is deleted because Subscription have deleted copy-constructor and operator
              // requests_.push_back(graphsync_->makeRequest(peer,
              //                                             std::move(address),
              //                                             root_cid,
              //                                             {},
              //                                             extensions,
              //                                             requestProgressCallback()));
              // Subscription subscription = graphsync_->makeRequest(peer,
              //                                             std::move(address),
              //                                             root_cid,
              //                                             {},
              //                                             extensions,
              //                                             requestProgressCallback());
        requests_.push_back(std::shared_ptr<sgns::ipfs_lite::ipfs::graphsync::Subscription>(
            new sgns::ipfs_lite::ipfs::graphsync::Subscription(std::move(graphsync_->makeRequest(peer,
            std::move(address),
            root_cid,
            {},
            extensions,
            requestProgressCallback())))));

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

        ++requests_sent;
    }

private:
    void start() {
        if (!started_) {
            graphsync_->start(data_service_, block_cb_);
            host_->start();
            started_ = true;
        }
    }

    // helper, returns requesu callback fn
    sgns::ipfs_lite::ipfs::graphsync::Graphsync::RequestProgressCallback requestProgressCallback() {
        static auto formatExtensions =
            [](const std::vector<sgns::ipfs_lite::ipfs::graphsync::Extension>& extensions) -> std::string {
            std::string s;
            for (const auto& item : extensions) {
                s += fmt::format(
                    "({}: 0x{}) ", item.name, sgns::common::Buffer(item.data).toHex());
            }
            return s;
        };
        return [this](sgns::ipfs_lite::ipfs::graphsync::ResponseStatusCode code,
            const std::vector<sgns::ipfs_lite::ipfs::graphsync::Extension>& extensions) {
                ++responses_received;
                logger->trace("request progress: code={}, extensions={}",
                    sgns::ipfs_lite::ipfs::graphsync::statusCodeToString(code),
                    formatExtensions(extensions));
                if (++n_responses == n_responses_expected_) {
                    io_->stop();
                }
        };
    }

    // asion context to be stopped when needed
    std::shared_ptr<boost::asio::io_context> io_;

    std::shared_ptr<sgns::ipfs_lite::ipfs::graphsync::Graphsync> graphsync_;

    std::shared_ptr<libp2p::Host> host_;

    std::shared_ptr<sgns::ipfs_lite::ipfs::graphsync::MerkleDagBridge> data_service_;

    sgns::ipfs_lite::ipfs::graphsync::Graphsync::BlockCallback block_cb_;

    // keeping subscriptions alive, otherwise they cancel themselves
    // class Subscription have non-copyable constructor and operator, so it can not be used in std::vector
    // std::vector<Subscription> requests_;

    std::vector<std::shared_ptr<sgns::ipfs_lite::ipfs::graphsync::Subscription >> requests_;

    size_t n_responses_expected_;
    size_t n_responses = 0;
    bool started_ = false;
};

size_t Node::requests_sent = 0;
size_t Node::responses_received = 0;

namespace
{
    boost::optional<libp2p::peer::PeerInfo> PeerInfoFromString(const std::string& str)
    {
        auto server_ma_res = libp2p::multi::Multiaddress::create(str);
        if (!server_ma_res)
        {
            return boost::none;
        }
        auto server_ma = std::move(server_ma_res.value());

        auto server_peer_id_str = server_ma.getPeerId();
        if (!server_peer_id_str)
        {
            return boost::none;
        }

        auto server_peer_id_res = libp2p::peer::PeerId::fromBase58(*server_peer_id_str);
        if (!server_peer_id_res)
        {
            return boost::none;
        }

        return libp2p::peer::PeerInfo{ server_peer_id_res.value(), {server_ma} };
    }
}

// Two nodes interact, one connection is utilized
void RunIpfsServer()
{
    auto io_server = std::make_shared<boost::asio::io_context>();
    // strings from which we create blocks and CIDs
    std::vector<std::string> strings({ "xxx", "yyy", "zzz" });

    size_t unexpected = 0;
    // creating instances
    auto server_data = std::make_shared<TestDataService>();

    // server block callback expects no blocks
    auto server_cb = [&unexpected](sgns::CID, sgns::common::Buffer) { ++unexpected; };

    for (const auto& s : strings) {
        // client expects what server has

        server_data->addData(s);
    }

    std::string publicKey = "z5b3BTS9wEgJxi9E8NHH6DT8Pj9xTmxBRgTaRUpBVox9a";
    std::string privateKey = "zGRXH26ag4k9jxTGXp2cg8n31CEkR2HN1SbHaKjaHnFTu";

    libp2p::crypto::KeyPair keyPair;
    auto codec = libp2p::multi::MultibaseCodecImpl();
    keyPair.publicKey = { libp2p::crypto::PublicKey::Type::Ed25519, codec.decode(publicKey).value() };
    keyPair.privateKey = { libp2p::crypto::PublicKey::Type::Ed25519, codec.decode(privateKey).value() };

    Node server(io_server, server_data, server_cb, 0, keyPair);

    auto listen_to =
        libp2p::multi::Multiaddress::create("/ip4/127.0.0.1/tcp/40000/ipfs/" + server.getId().toBase58()).value();
    logger->debug(listen_to.getStringAddress());

    // starting all the stuff asynchronously
    server.listen(listen_to);

    std::thread t_server([&]() { io_server->run(); });
    //runEventLoop(io_server, run_time_msec);

    t_server.join();

    server.stop();
}

void RunIpfsClient(std::string remote) {
    Node::requests_sent = 0;
    Node::responses_received = 0;

    auto io_client = std::make_shared<boost::asio::io_context>();

    auto client_data = std::make_shared<TestDataService>();

    size_t unexpected = 0;
    // clienc block callback expect 3 blocks from the string above
    auto client_cb = [&client_data, &unexpected](sgns::CID cid, sgns::common::Buffer data) {
        if (!client_data->onDataBlock(std::move(cid), std::move(data))) {
            ++unexpected;
        }
    };

    // strings from which we create blocks and CIDs
    std::vector<std::string> strings({ "xxx", "yyy", "zzz" });
    for (const auto& s : strings) {
        // client expects what server has
        client_data->addExpected(s);
    }

    Node client(io_client, client_data, client_cb, 3, std::nullopt);

    auto listen_to =
        libp2p::multi::Multiaddress::create("/ip4/127.0.0.1/tcp/40000/ipfs/" + client.getId().toBase58()).value();
    client.listen(listen_to);

    io_client->post([&, remote]() {
        // server listens
        auto pi = PeerInfoFromString(remote);
        auto peer = pi.value().id;
        bool use_address = true;

        // client makes 3 requests

        for (const auto& [cid, _] : client_data->getExpected()) {
            boost::optional<libp2p::multi::Multiaddress> address(pi.value().addresses[0]);

            // don't need to pass the address more than once
            client.makeRequest(peer, use_address ? address : boost::none, cid);
            use_address = false;
        }
        });

    std::thread t_client([&]() { io_client->run(); });
    //runEventLoop(io_client, run_time_msec);

    t_client.join();

    client.stop();

    logger->info("total requests sent {}, responses received {}",
        Node::requests_sent,
        Node::responses_received);
}

// Context for more complex cases
struct NodeParams {
    // listen address
    boost::optional<libp2p::multi::Multiaddress> listen_to;

    // MerkleDAG stub for node
    std::shared_ptr<TestDataService> data_service;

    // Strings to make blocks and CIDs from them
    std::vector<std::string> strings;

    // peer ID
    boost::optional<libp2p::peer::PeerId> peer;
};

// N nodes communicate P2P with each other  and collect many blocks.
// Each node has n_data data blocks
void testManyNodesExchange(size_t N, size_t n_data) {
    Node::requests_sent = 0;
    Node::responses_received = 0;

    size_t unexpected_responses = 0;
    size_t total_responses = 0;
    size_t expected = 0;

    // creating parameters for N nodes

    std::vector<NodeParams> params;
    params.reserve(N);
    for (size_t i = 0; i < N; ++i) {
        auto& p = params.emplace_back();

        // The node #i will listen to 40000+i pore
        p.listen_to = libp2p::multi::Multiaddress::create(
            fmt::format("/ip4/127.0.0.1/tcp/{}", 40000 + i))
            .value();

        p.data_service = std::make_shared<TestDataService>();

        // the i-th node has data represented by strings data_i_j, j in[0, n_data)
        p.strings.reserve(n_data);
        for (size_t j = 0; j < n_data; ++j) {
            auto& s = p.strings.emplace_back(fmt::format("data_{}_{}", i, j));
            p.data_service->addData(s);
        }
    }

    auto io = std::make_shared<boost::asio::io_context>();

    // creating N nodes

    std::vector<Node> nodes;
    nodes.reserve(N);

    for (size_t i = 0; i < N; ++i) {
        auto& p = params[i];

        auto cb = [ds = p.data_service,
            &expected,
            &unexpected_responses,
            &total_responses,
            &io](sgns::CID cid, sgns::common::Buffer data) {
            logger->trace("data block received, {}:{}, {}/{}",
                cid.toString().value(),
                std::string((const char*)data.data(), data.size()),
                total_responses + 1,
                expected);
            if (!ds->onDataBlock(std::move(cid), std::move(data))) {
                ++unexpected_responses;
            }
            else if (++total_responses == expected) {
                io->stop();
            }
        };

        auto& n = nodes.emplace_back(io, p.data_service, cb, 0, std::nullopt);

        // peer IDs are known only at this point
        p.peer = n.getId();

        for (size_t j = 0; j < N; ++j) {
            if (j != i) {
                for (const auto& s : params[j].strings)

                    // each node expects data other hodes have
                    p.data_service->addExpected(s);
            }
        }
    }

    // starting N nodes asynchronously

    io->post([&]() {
        for (size_t i = 0; i < N; ++i) {
            auto& p = params[i];
            auto& n = nodes[i];

            // each node listens
            n.listen(p.listen_to.value());
        }

        // will make connections in the next cycle
        io->post([&]() {
            for (size_t i = 0; i < N; ++i) {
                auto& p = params[i];
                auto& n = nodes[i];

                for (const auto& [cid, d] : p.data_service->getExpected()) {
                    ++expected;
                    for (const auto& p0 : params) {
                        if (&p0 != &p) {
                            logger->trace("request from {} to {} for {}:{}",
                                p.peer->toBase58().substr(46),
                                p0.peer->toBase58().substr(46),
                                cid.toString().value(),
                                std::string((const char*)d.data(), d.size()));

                            // each node request every piece of expected data from
                            // all other nodes. And gets RS_FULL_CONTENT 1 time per each
                            // data block,
                            // and respectively RS_NOT_FOUND will come N-2 times per block

                            n.makeRequest(p0.peer.value(), p0.listen_to, cid);
                        }
                    }
                }
            }
            });
        });

    runEventLoop(io, run_time_msec);

    for (auto& n : nodes) {
        n.stop();
    }

    logger->info("total requests sent {}, responses received {}",
        Node::requests_sent,
        Node::responses_received);

}  // namespace sgns::ipfs_lite::ipfs::graphsync::test

namespace
{
    // cmd line options
    struct Options
    {
        // optional remote peer to connect to
        std::optional<std::string> remote;
        std::string mode;
    };

    boost::optional<Options> parseCommandLine(int argc, char** argv) {
        namespace po = boost::program_options;
        try
        {
            Options o;
            std::string remote;

            po::options_description desc("processing service options");
            desc.add_options()("help,h", "print usage message")
                ("mode,m", po::value(&o.mode), "application mode (client/server)")
                ("remote,r", po::value(&remote), "remote service multiaddress to connect to")
                ;

            po::variables_map vm;
            po::store(parse_command_line(argc, argv, desc), vm);
            po::notify(vm);

            if (vm.count("help") != 0 || argc == 1)
            {
                std::cerr << desc << "\n";
                return boost::none;
            }

            if (!remote.empty())
            {
                o.remote = remote;
            }

            if (o.mode != "client" && o.mode != "server")
            {
                std::cerr << desc << "\n";
                return boost::none;
            }

            return o;
        }
        catch (const std::exception& e)
        {
            std::cerr << e.what() << std::endl;
        }
        return boost::none;
    }
}

int main(int argc, char* argv[]) {
    auto options = parseCommandLine(argc, argv);
    if (!options)
    {
        return 1;
    }

    const std::string logger_config(R"(
    # ----------------
    sinks:
      - name: console
        type: console
        color: true
    groups:
      - name: graphsync_app
        sink: console
        level: info
        children:
          - name: libp2p
          - name: Gossip
    # ----------------
    )");

    // prepare log system
    auto logging_system = std::make_shared<soralog::LoggingSystem>(
        std::make_shared<soralog::ConfiguratorFromYAML>(
            // Original LibP2P logging config
            std::make_shared<libp2p::log::Configurator>(),
            // Additional logging config for application
            logger_config));
    logging_system->configure();

    libp2p::log::setLoggingSystem(logging_system);

    logger = sgns::common::createLogger("graphsync_app");
    logger->set_level(spdlog::level::trace);
    sgns::common::createLogger("graphsync")->set_level(spdlog::level::trace);

    if (options->mode == "client")
    {
        if (!options->remote)
        {
            std::cerr << "--remote parameter must be specified for the 'client' mode";
            return 1;
        }
        RunIpfsClient(options->remote.value());
    }
    else
        RunIpfsServer();
    return 0;
}

max_stars_repo_name: GeniusVentures/SuperGenius

max_issues_repo_name: GeniusVentures/SuperGenius

max_forks_repo_name: GeniusVentures/SuperGenius