text:
#include <dRoundRobin.h>
#include <boost/python.hpp>

using namespace boost::python;

void export_dRoundRobin()
{
  class_<DRoundRobin, bases<Element>, boost::shared_ptr<DRoundRobin>, boost::noncopyable>
        ("DRoundRobin", init<std::string, int>())
    .def("class_name",    &DRoundRobin::class_name)
    .def("processing",    &DRoundRobin::processing)
    .def("flow_code",     &DRoundRobin::flow_code)

    .def("add_input",     &DRoundRobin::add_input)
    .def("remove_input",  &DRoundRobin::remove_input)
  ;
}

ext: cpp


text: #include <boost/log/utility/type_dispatch/date_time_types.hpp>

ext: hpp

max_stars_repo_name: miathedev/BoostForArduino

max_issues_repo_name: miathedev/BoostForArduino

max_forks_repo_name: miathedev/BoostForArduino


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

#ifndef BOOST_JSON_DETAIL_IMPL_EXCEPT_IPP
#define BOOST_JSON_DETAIL_IMPL_EXCEPT_IPP

#include <boost/json/detail/except.hpp>
#ifndef BOOST_JSON_STANDALONE
# include <boost/version.hpp>
# include <boost/throw_exception.hpp>
#elif defined(BOOST_JSON_STANDALONE) && defined(BOOST_NO_EXCEPTIONS)
# include <exception>
#endif
#include <stdexcept>

#if defined(BOOST_JSON_STANDALONE)
namespace boost {

#if defined(BOOST_NO_EXCEPTIONS)
// When exceptions are disabled
// in standalone, you must provide
// this function.
BOOST_NORETURN
void
throw_exception(std::exception const&);

#else
template<class E>
void
BOOST_NORETURN
throw_exception(E e)
{
    throw e;
}

#endif

} // boost
#endif

BOOST_JSON_NS_BEGIN

namespace detail {

void
throw_bad_alloc(
    source_location const& loc)
{
    (void)loc;
    throw_exception(
        std::bad_alloc()
#if BOOST_VERSION >= 107300
        , loc
#endif
        );
}

void
throw_length_error(
    char const* what,
    source_location const& loc)
{
    (void)loc;
    throw_exception(
        std::length_error(what)
#if BOOST_VERSION >= 107300
        , loc
#endif
        );
}

void
throw_invalid_argument(
    char const* what,
    source_location const& loc)
{
    (void)loc;
    throw_exception(
        std::invalid_argument(what)
#if BOOST_VERSION >= 107300
        , loc
#endif
        );
}

void
throw_out_of_range(
    source_location const& loc)
{
    (void)loc;
    throw_exception(
        std::out_of_range(
            "out of range")
#if BOOST_VERSION >= 107300
        , loc
#endif
        );
}

void
throw_system_error(
    error_code const& ec,
    source_location const& loc)
{
    (void)loc;
    throw_exception(
        system_error(ec)
#if BOOST_VERSION >= 107300
        , loc
#endif
        );
}

} // detail
BOOST_JSON_NS_END

#endif

ext: ipp

max_stars_repo_name: Julien-Blanc-tgcm/json

max_issues_repo_name: Julien-Blanc-tgcm/json

max_forks_repo_name: Julien-Blanc-tgcm/json


text:
#include <string>
#include <exception>
#include <iostream>
#include <fstream>
#include <boost/program_options/options_description.hpp>
#include <boost/program_options/parsers.hpp>
#include <boost/program_options/variables_map.hpp>
#include "../lib/coefs.hpp"

namespace po = boost::program_options;

po::variables_map process_program_options(
	const int argc,
	const char *const argv[]
){
	po::options_description desc(
		"\nMIP coefficients extractor.\n\n"
		"Usage: mip-coefs [options] input-file [output-file]\n"
		"Allowed arguments");

	desc.add_options()
		("help,h", "Produce this help message.")
		("input-file,i", po::value<std::string>()->required(),
		 "Specifies input file.")
		("sparse,s", "Write coefficients in sparse format.")
		("output-file,o", po::value<std::string>(),
		 "Specifies output file for the coefficients.")
		("remove-empty", "Remove empty constraints.");

	po::positional_options_description p;
	p.add("input-file", 1);
	p.add("output-file", 1);

	po::variables_map vm;
	try {
		po::store(
			po::command_line_parser(argc, argv).options(desc).positional(p).run(),
			vm);
		// Display help text when requested
		if(vm.count("help")){
			std::cout << desc << std::endl;
			exit(EXIT_SUCCESS);
		}
		po::notify(vm);
	} catch (std::exception &e) {
		std::cout << std::endl << e.what() << std::endl;
		std::cout << desc << std::endl;
		exit(EXIT_SUCCESS);
	}

	return vm;
}

int main (int argc, char **argv){
	po::variables_map options = process_program_options(argc, argv);

	bool sparse = options.count("sparse");
	bool keep_empty = !options.count("remove-empty");
	string infile = options["input-file"].as<string>();

	if(options.count("output-file")){
		string outfile = options["output-file"].as<string>();
		ofstream out(outfile);
		process(infile, out, sparse, keep_empty);
		out.close();
	} else
		process(infile, cout, sparse, keep_empty);

	return 0;
}

max_stars_repo_name: AntoinePrv/MipUtils

max_issues_repo_name: AntoinePrv/MipUtils

max_forks_repo_name: AntoinePrv/MipUtils


text:
//--------------------------------------------------------------------------
// Code generated by the SmartSoft MDSD Toolchain
// The SmartSoft Toolchain has been developed by:
//
// Service Robotics Research Center
// University of Applied Sciences Ulm
// Prittwitzstr. 10
// 89075 Ulm (Germany)
//
// Information about the SmartSoft MDSD Toolchain is available at:
// www.servicerobotik-ulm.de
//
// Please do not modify this file. It will be re-generated
// running the code generator.
//--------------------------------------------------------------------------
#include "CommNavigationObjects/CommCorridorNavigationNodeAnswerCore.hh"

// serialization/deserialization operators
//#include "CommNavigationObjects/CommCorridorNavigationNodeAnswerACE.hh"

// include the hash.idl containing the hash constant
#include "hash.hh"
#include <assert.h>
#include <cstring>
#include <iostream>

// SmartUtils used in from_xml method
#include "smartKnuthMorrisPratt.hh"

#ifdef ENABLE_HASH
	#include <boost/functional/hash.hpp>
#endif

namespace CommNavigationObjects
{
	const char* CommCorridorNavigationNodeAnswerCore::getCompiledHash()
	{
		return CommNavigationObjectsIDL::REPO_HASH;
	}

	void CommCorridorNavigationNodeAnswerCore::getAllHashValues(std::list<std::string> &hashes)
	{
		// get own hash value
		hashes.push_back(getCompiledHash());
		// get hash value(s) for CommNavigationObjects::CommCorridorNode(idl_CommCorridorNavigationNodeAnswer.nodesList)
		CommNavigationObjects::CommCorridorNode::getAllHashValues(hashes);
	}

	void CommCorridorNavigationNodeAnswerCore::checkAllHashValues(std::list<std::string> &hashes)
	{
		// check own hash value
		if (strcmp(getCompiledHash(), hashes.front().c_str()) != 0)
		{
			std::cerr << "###################################################" << std::endl;
			std::cerr << "WARNING: HASHES OF COMMUNICATION OBJECTS MISSMATCH!" << std::endl;
			std::cerr << "CommCorridorNavigationNodeAnswerCore hash" << std::endl;
			std::cerr << "Expected: " << getCompiledHash() << std::endl;
			std::cerr << "Received: " << hashes.front() << std::endl;
			std::cerr << "###################################################" << std::endl;
		}
		assert(strcmp(getCompiledHash(), hashes.front().c_str()) == 0);
		hashes.pop_front();

		// check hash value(s) for CommNavigationObjects::CommCorridorNode(idl_CommCorridorNavigationNodeAnswer.nodesList)
		CommNavigationObjects::CommCorridorNode::checkAllHashValues(hashes);
	}

	#ifdef ENABLE_HASH
	size_t CommCorridorNavigationNodeAnswerCore::generateDataHash(const DATATYPE &data)
	{
		size_t seed = 0;

		std::vector<CommNavigationObjectsIDL::CommCorridorNode>::const_iterator data_nodesListIt;
		for(data_nodesListIt=data.nodesList.begin(); data_nodesListIt!=data.nodesList.end(); data_nodesListIt++) {
			seed += CommNavigationObjects::CommCorridorNode::generateDataHash(*data_nodesListIt);
		}
		boost::hash_combine(seed, data.success);

		return seed;
	}
	#endif

	// default constructor
	CommCorridorNavigationNodeAnswerCore::CommCorridorNavigationNodeAnswerCore()
	:	idl_CommCorridorNavigationNodeAnswer()
	{
		setNodesList(std::vector<CommNavigationObjects::CommCorridorNode>());
		setSuccess(false);
	}

	CommCorridorNavigationNodeAnswerCore::CommCorridorNavigationNodeAnswerCore(const DATATYPE &data)
	:	idl_CommCorridorNavigationNodeAnswer(data)
	{  }

	CommCorridorNavigationNodeAnswerCore::~CommCorridorNavigationNodeAnswerCore()
	{  }

	void CommCorridorNavigationNodeAnswerCore::to_ostream(std::ostream &os) const
	{
	  os << "CommCorridorNavigationNodeAnswer(";
	  std::vector<CommNavigationObjects::CommCorridorNode>::const_iterator nodesListIt;
	  std::vector<CommNavigationObjects::CommCorridorNode> nodesListList = getNodesListCopy();
	  for(nodesListIt=nodesListList.begin(); nodesListIt!=nodesListList.end(); nodesListIt++) {
	  	nodesListIt->to_ostream(os);
	  }
	  os << getSuccess() << " ";
	  os << ") ";
	}

	// convert to xml stream
	void CommCorridorNavigationNodeAnswerCore::to_xml(std::ostream &os, const std::string &indent) const {
		size_t counter = 0;

		std::vector<CommNavigationObjects::CommCorridorNode>::const_iterator nodesListIt;
		std::vector<CommNavigationObjects::CommCorridorNode> nodesListList = getNodesListCopy();
		counter = 0;
		os << indent << "<nodesListList n=\"" << nodesListList.size() << "\">";
		for(nodesListIt=nodesListList.begin(); nodesListIt!=nodesListList.end(); nodesListIt++) {
			os << indent << "<nodesList i=\"" << counter++ << "\">";
			nodesListIt->to_xml(os, indent);
			os << indent << "</nodesList>";
		}
		os << indent << "</nodesListList>";
		os << indent << "<success>" << getSuccess() << "</success>";
	}

	// restore from xml stream
	void CommCorridorNavigationNodeAnswerCore::from_xml(std::istream &is) {
		size_t counter = 0;

		static const Smart::KnuthMorrisPratt kmp_nodesListList("<nodesListList n=\"");
		static const Smart::KnuthMorrisPratt kmp_nodesList("\">");
		static const Smart::KnuthMorrisPratt kmp_success("<success>");

		if(kmp_nodesListList.search(is)) {
			size_t numberElements;
			is >> numberElements;
			CommNavigationObjects::CommCorridorNode nodesListItem;
			std::vector<CommNavigationObjects::CommCorridorNode> nodesListList;
			kmp_nodesList.search(is);
			for(counter=0; counter<numberElements; counter++) {
				if(kmp_nodesList.search(is)) {
					nodesListItem.from_xml(is);
					nodesListList.push_back(nodesListItem);
				}
			}
			setNodesList(nodesListList);
		}
		if(kmp_success.search(is)) {
			bool successItem;
			is >> successItem;
			setSuccess(successItem);
		}
	}

	/*
	void CommCorridorNavigationNodeAnswerCore::get(ACE_Message_Block *&msg) const
	{
		// start with a default internal buffer size(will automatically grow if needed)
		ACE_OutputCDR cdr(ACE_DEFAULT_CDR_BUFSIZE);

		CommNavigationObjectsIDL::HashList hashes;
		getAllHashValues(hashes);
		cdr << static_cast<ACE_CDR::Long>(hashes.size());
		for(CommNavigationObjectsIDL::HashList::const_iterator it=hashes.begin(); it!=hashes.end(); it++)
		{
			cdr << ACE_CString(it->c_str());
		}

		// Here the actual serialization takes place using the OutputCDR serialization operator<<
		// (see CommCorridorNavigationNodeAnswerACE.hh)
		cdr << idl_CommCorridorNavigationNodeAnswer;

	#ifdef ENABLE_HASH
		ACE_CDR::ULong data_hash = generateDataHash(idl_CommCorridorNavigationNodeAnswer);
		cdr << data_hash;
		// std::cout << "CommCorridorNavigationNodeAnswerCore: current data hash: " << data_hash << std::endl;
	#endif

		// return a shallow copy of the serialized message
		// (no data is actually copied, only the internal reference counter is incremented)
		// in order to prevent memory leaks the caller of this get(msg) method must
		// manually free the memory by calling the release() method of the message block msg
		msg = cdr.begin()->duplicate();
	}

	void CommCorridorNavigationNodeAnswerCore::set(const ACE_Message_Block *msg)
	{
		ACE_InputCDR cdr(msg);

		CommNavigationObjectsIDL::HashList hashes;
		ACE_CDR::Long hashes_size;
		cdr >> hashes_size;
		for(int i=0; i<hashes_size; ++i)
		{
			ACE_CString hash;
			cdr >> hash;
			hashes.push_back(hash.c_str());
		}
		checkAllHashValues(hashes);

		// Here the actual de-serialization takes place using the InputCDR serialization operator>>
		// (see CommCorridorNavigationNodeAnswerACE.hh)
		cdr >> idl_CommCorridorNavigationNodeAnswer;

	#ifdef ENABLE_HASH
		ACE_CDR::Long data_hash;
		cdr >> data_hash;
		ACE_CDR::Long own_hash = generateDataHash(idl_CommCorridorNavigationNodeAnswer);
		assert(data_hash == own_hash);
		// std::cout << "CommCorridorNavigationNodeAnswerCore: own data hash: " << own_hash << "; received data hash: " << data_hash << std::endl;
	#endif
	}
	*/
} /* namespace CommNavigationObjects */

ext: cc


text:
#pragma once

#include <string>
#include <vector>
#include <cmath>
#include <functional>
#include <algorithm>
#include <stdexcept>

#include <boost/filesystem.hpp>
#include <gdal_priv.h>

#include "Transformation.h"
#include "Metadata.h"
#include "Helper.h"

namespace fs = boost::filesystem;

namespace CloudTools
{
namespace DEM
{
/// <summary>
/// Represents a sweepline transformation on DEM datasets.
/// </summary>
template <typename TargetType, typename SourceType = TargetType>
class DatasetTransformation : public Transformation
{
public:
	typedef std::function<void(int, int)> ComputationType;
	ComputationType computation;

	/// <summary>
	/// The indices of bands to use respectively for each data source.
	/// </summary>
	std::vector<int> bands;

protected:
	std::vector<SourceType*> _sourceData;
	TargetType* _targetData;

private:
	std::vector<SourceType> _sourceNodataValue;

public:
	/// <summary>
	/// Initializes a new instance of the class and loads source metadata.
	/// </summary>
	/// <param name="sourcePaths">The source files of the transformation.</param>
	/// <param name="targetPath">The target file of the transformation.</param>
	/// <param name="computation">The callback function for computation.</param>
	/// <param name="progress">The callback method to report progress.</param>
	DatasetTransformation(const std::vector<std::string>& sourcePaths,
	                      const std::string& targetPath,
	                      ComputationType computation,
	                      ProgressType progress = nullptr)
		: Transformation(sourcePaths, targetPath, progress),
		computation(computation)
	{ }

	/// <summary>
	/// Initializes a new instance of the class and loads source metadata.
	/// </summary>
	/// <remarks>
	/// Target is in memory raster by default and can be retrieved by <see cref="target()"/>.
	/// </remarks>
	/// <param name="sourceDatasets">The source datasets of the transformation.</param>
	/// <param name="targetPath">The target file of the transformation.</param>
	/// <param name="computation">The callback function for computation.</param>
	/// <param name="progress">The callback method to report progress.</param>
	DatasetTransformation(const std::vector<GDALDataset*>& sourceDatasets,
	                      const std::string& targetPath,
	                      ComputationType computation,
	                      ProgressType progress = nullptr)
		: Transformation(sourceDatasets, targetPath, progress),
		computation(computation)
	{ }

	/// <summary>
	/// Initializes a new instance of the class and loads source metadata.
	/// </summary>
	/// <remarks>
	/// Target is in memory raster by default and can be retrieved by <see cref="target()"/>.
	/// </remarks>
	/// <param name="sourceDatasets">The source datasets of the transformation.</param>
	/// <param name="computation">The callback function for computation.</param>
	/// <param name="progress">The callback method to report progress.</param>
	DatasetTransformation(const std::vector<GDALDataset*>& sourceDatasets,
	                      ComputationType computation,
	                      ProgressType progress = nullptr)
		: DatasetTransformation(sourceDatasets, std::string(), computation, progress)
	{
		targetFormat = "MEM";
	}

	DatasetTransformation(const DatasetTransformation&) = delete;
	DatasetTransformation& operator=(const DatasetTransformation&) = delete;

	~DatasetTransformation();

protected:
	/// <summary>
	/// Produces the target file.
	/// </summary>
	void onExecute() override;

	SourceType sourceData(int index, int i, int j) const
	{
		if (!isValid(index, i, j))
			return _sourceNodataValue[index];
		return _sourceData[index][j * _sourceMetadata[index].rasterSizeX() + i];
	}

	SourceType sourceData(int i, int j) const
	{
		return sourceData(0, i, j);
	}

	TargetType targetData(int i, int j) const
	{
		if (!isValid(i, j))
			return nodataValue;
		return _targetData[j * _targetMetadata.rasterSizeX() + i];
	}

	void setTargetData(int i, int j, TargetType value)
	{
		if (isValid(i, j))
			_targetData[j * _targetMetadata.rasterSizeX() + i] = value;
	}

	bool hasSourceData(int index, int i, int j) const
	{
		if (!isValid(index, i, j))
			return false;
		return sourceData(index, i, j) != _sourceNodataValue[index];
	}

	bool hasSourceData(int i, int j) const
	{
		return hasSourceData(0, i, j);
	}

	bool hasTargetData(int i, int j) const
	{
		if (!isValid(i, j))
			return false;
		return targetData(i, j) != nodataValue;
	}

private:
	bool isValid(int i, int j) const
	{
		return i >= 0 && i < _targetMetadata.rasterSizeX() &&
			   j >= 0 && j < _targetMetadata.rasterSizeY();
	}

	bool isValid(int index, int i, int j) const
	{
		return index >= 0 && index < sourceCount() &&
			   i >= 0 && i < _sourceMetadata[index].rasterSizeX() &&
			   j >= 0 && j < _sourceMetadata[index].rasterSizeY();
	}
};

template <typename TargetType, typename SourceType>
void DatasetTransformation<TargetType, SourceType>::onExecute()
{
	if (!computation)
		throw std::logic_error("No computation method defined.");

	// Create and open the target file
	GDALDriver* driver = GetGDALDriverManager()->GetDriverByName(targetFormat.c_str());
	if (driver == nullptr)
		throw std::invalid_argument("Target output format unrecognized.");

	if (fs::exists(_targetPath) &&
		driver->Delete(_targetPath.c_str()) == CE_Failure &&
		!fs::remove(_targetPath))
		throw std::runtime_error("Cannot overwrite previously created target file.");

	GDALDataType sourceType = gdalType<SourceType>();
	GDALDataType targetType = gdalType<TargetType>();

	char **targetParams = nullptr;
	for (auto& co : createOptions)
		targetParams = CSLSetNameValue(targetParams, co.first.c_str(), co.second.c_str());

	_targetDataset = driver->Create(_targetPath.c_str(),
		_targetMetadata.rasterSizeX(), _targetMetadata.rasterSizeY(), 1,
		targetType, targetParams);
	CSLDestroy(targetParams);
	if (_targetDataset == nullptr)
		throw std::runtime_error("Target file creation failed.");

	_targetDataset->SetGeoTransform(&_targetMetadata.geoTransform()[0]);
	if (_targetMetadata.reference().Validate() == OGRERR_NONE)
	{
		char *wkt;
		_targetMetadata.reference().exportToWkt(&wkt);
		_targetDataset->SetProjection(wkt);
		CPLFree(wkt);
	}

	// Determine computation progress steps
	int computationSteps = sourceCount() + 2;

	// Open and check bands
	std::vector<GDALRasterBand*> sourceBands(sourceCount());
	_sourceNodataValue.resize(sourceCount());
	for (unsigned int i = 0; i < sourceCount(); ++i)
	{
		long long bandIndex;
		if (bands.size() > i)
		{
			// Use manually defined band index
			bandIndex = bands[i];
		}
		else
		{
			// Default band index: multiplicity of same source
			bandIndex = _sourceOwnership
				? std::count(_sourcePaths.begin(), _sourcePaths.begin() + i, _sourcePaths[i]) + 1
				: std::count(_sourceDatasets.begin(), _sourceDatasets.begin() + i, _sourceDatasets[i]) + 1;
		}
		sourceBands[i] = _sourceDatasets[i]->GetRasterBand(static_cast<int>(bandIndex));
		_sourceNodataValue[i] = static_cast<SourceType>(sourceBands[i]->GetNoDataValue());
	}
	GDALRasterBand* targetBand = _targetDataset->GetRasterBand(1);
	targetBand->SetNoDataValue(nodataValue);

	if (strictTypes && std::any_of(sourceBands.begin(), sourceBands.end(),
		[sourceType](GDALRasterBand* band)
	{
		return band->GetRasterDataType() != sourceType;
	}))
		throw std::domain_error("The data type of a source band does not match with the given data type.");

	// Read sources
	_sourceData.resize(sourceCount());
	for (unsigned int i = 0; i < sourceCount(); ++i)
		_sourceData[i] = new SourceType[_sourceMetadata[i].rasterSizeX() * _sourceMetadata[i].rasterSizeY()];

	CPLErr ioResult = CE_None;
	for (unsigned int i = 0; i < sourceCount(); ++i)
	{
		ioResult = static_cast<CPLErr>(ioResult |
			sourceBands[i]->RasterIO(GF_Read,
				0, 0,
				_sourceMetadata[i].rasterSizeX(), _sourceMetadata[i].rasterSizeY(),
				_sourceData[i],
				_sourceMetadata[i].rasterSizeX(), _sourceMetadata[i].rasterSizeY(),
				sourceType,
				0, 0));

		if (progress)
			progress((i + 1) * 1.f / computationSteps, "Done reading source #" + std::to_string(i + 1));
	}
	if (ioResult != CE_None)
		throw std::runtime_error("Source read error occured.");

	// Compute target
	_targetData = new TargetType[_targetMetadata.rasterSizeX() * _targetMetadata.rasterSizeY()];
	std::fill_n(_targetData, _targetMetadata.rasterSizeX() * _targetMetadata.rasterSizeY(), nodataValue);

	ProgressType origProgress = progress;
	if (progress)
	{
		progress = [&origProgress, computationSteps](float complete, std::string message)
		{
			return origProgress((computationSteps - 2 + complete) * 1.f / computationSteps, message);
		};
	}

	computation(_targetMetadata.rasterSizeX(), _targetMetadata.rasterSizeY());

	progress = origProgress;
	if (progress)
		progress((computationSteps - 1) * 1.f / computationSteps, "Computation performed");

	// Write target
	ioResult = targetBand->RasterIO(GF_Write,
		0, 0,
		_targetMetadata.rasterSizeX(), _targetMetadata.rasterSizeY(),
		_targetData,
		_targetMetadata.rasterSizeX(), _targetMetadata.rasterSizeY(),
		targetType,
		0, 0);
	if (ioResult != CE_None)
		throw std::runtime_error("Target write error occured.");

	if (progress)
		progress(1.f, "Target written");
}

template <typename TargetType, typename SourceType>
DatasetTransformation<TargetType, SourceType>::~DatasetTransformation()
{
	if (isExecuted())
	{
		for (int i = 0; i < sourceCount(); ++i)
			delete[] _sourceData[i];
		delete[] _targetData;
	}
}
} // DEM
} // CloudTools

max_stars_repo_name: mcserep/PointCloudTools

max_issues_repo_name: mcserep/PointCloudTools

max_forks_repo_name: mcserep/PointCloudTools


text:
#define BOOST_TEST_MODULE TestQR
#include <boost/test/unit_test.hpp>

#include <vector>
#include <random>
#include <boost/multi_array.hpp>

#include <amgcl/detail/qr.hpp>
#include <amgcl/value_type/interface.hpp>
#include <amgcl/value_type/complex.hpp>
#include <amgcl/value_type/static_matrix.hpp>

template <class T>
struct make_random {
    static T get() {
        static std::mt19937 gen;
        static std::uniform_real_distribution<T> rnd;

        return rnd(gen);
    }
};

template <class T>
T random() {
    return make_random<T>::get();
}

template <class T>
struct make_random< std::complex<T> > {
    static std::complex<T> get() {
        return std::complex<T>( random<T>(), random<T>() );
    }
};

template <class T, int N, int M>
struct make_random< amgcl::static_matrix<T,N,M> > {
    typedef amgcl::static_matrix<T,N,M> matrix;
    static matrix get() {
        matrix A = amgcl::math::zero<matrix>();
        for(int i = 0; i < N; ++i)
            for(int j = 0; j < M; ++j)
                A(i,j) = make_random<T>::get();
        return A;
    }
};

template <class value_type, amgcl::detail::storage_order order>
void qr_factorize(int n, int m) {
    std::cout << "factorize " << n << " " << m << std::endl;
    typedef typename std::conditional<order == amgcl::detail::row_major,
            boost::c_storage_order,
            boost::fortran_storage_order
            >::type ma_storage_order;

    boost::multi_array<value_type, 2> A0(boost::extents[n][m], ma_storage_order());

    for(int i = 0; i < n; ++i)
        for(int j = 0; j < m; ++j)
            A0[i][j] = random<value_type>();

    boost::multi_array<value_type, 2> A = A0;

    amgcl::detail::QR<value_type> qr;

    qr.factorize(n, m, A.data(), order);

    // Check that A = QR
    int p = std::min(n, m);
    for(int i = 0; i < n; ++i) {
        for(int j = 0; j < m; ++j) {
            value_type sum = amgcl::math::zero<value_type>();

            for(int k = 0; k < p; ++k)
                sum += qr.Q(i,k) * qr.R(k,j);

            sum -= A0[i][j];

            BOOST_CHECK_SMALL(amgcl::math::norm(sum), 1e-8);
        }
    }
}

template <class value_type, amgcl::detail::storage_order order>
void qr_solve(int n, int m) {
    std::cout << "solve " << n << " " << m << std::endl;
    typedef typename std::conditional<order == amgcl::detail::row_major,
            boost::c_storage_order,
            boost::fortran_storage_order
            >::type ma_storage_order;

    typedef typename amgcl::math::rhs_of<value_type>::type rhs_type;

    boost::multi_array<value_type, 2> A0(boost::extents[n][m], ma_storage_order());

    for(int i = 0; i < n; ++i)
        for(int j = 0; j < m; ++j)
            A0[i][j] = random<value_type>();

    boost::multi_array<value_type, 2> A = A0;

    amgcl::detail::QR<value_type> qr;

    std::vector<rhs_type> f0(n, amgcl::math::constant<rhs_type>(1));
    std::vector<rhs_type> f = f0;

    std::vector<rhs_type> x(m);

    qr.solve(n, m, A.data(), f.data(), x.data(), order);

    std::vector<rhs_type> Ax(n);
    for(int i = 0; i < n; ++i) {
        rhs_type sum = amgcl::math::zero<rhs_type>();
        for(int j = 0; j < m; ++j)
            sum += A0[i][j] * x[j];

        Ax[i] = sum;

        if (n < m) {
            BOOST_CHECK_SMALL(amgcl::math::norm(sum - f0[i]), 1e-8);
        }
    }

    if (n >= m) {
        for(int i = 0; i < m; ++i) {
            rhs_type sumx = amgcl::math::zero<rhs_type>();
            rhs_type sumf = amgcl::math::zero<rhs_type>();

            for(int j = 0; j < n; ++j) {
                sumx += amgcl::math::adjoint(A0[j][i]) * Ax[j];
                sumf += amgcl::math::adjoint(A0[j][i]) * f0[j];
            }

            rhs_type delta = sumx - sumf;

            BOOST_CHECK_SMALL(amgcl::math::norm(delta), 1e-8);
        }
    }
}

BOOST_AUTO_TEST_SUITE( test_qr )

BOOST_AUTO_TEST_CASE( test_qr_factorize ) {
    const int shape[][2] = {
        {3, 3},
        {3, 5},
        {5, 3},
        {5, 5}
    };

    const int n = sizeof(shape) / sizeof(shape[0]);

    for(int i = 0; i < n; ++i) {
        qr_factorize<double,                             amgcl::detail::row_major>(shape[i][0], shape[i][1]);
        qr_factorize<double,                             amgcl::detail::col_major>(shape[i][0], shape[i][1]);
        qr_factorize<std::complex<double>,               amgcl::detail::row_major>(shape[i][0], shape[i][1]);
        qr_factorize<std::complex<double>,               amgcl::detail::col_major>(shape[i][0], shape[i][1]);
        qr_factorize<amgcl::static_matrix<double, 2, 2>, amgcl::detail::row_major>(shape[i][0], shape[i][1]);
        qr_factorize<amgcl::static_matrix<double, 2, 2>, amgcl::detail::col_major>(shape[i][0], shape[i][1]);
    }
}

BOOST_AUTO_TEST_CASE( test_qr_solve ) {
    const int shape[][2] = {
        {3, 3},
        {3, 5},
        {5, 3},
        {5, 5}
    };

    const int n = sizeof(shape) / sizeof(shape[0]);

    for(int i = 0; i < n; ++i) {
        qr_solve<double,                             amgcl::detail::row_major>(shape[i][0], shape[i][1]);
        qr_solve<double,                             amgcl::detail::col_major>(shape[i][0], shape[i][1]);
        qr_solve<std::complex<double>,               amgcl::detail::row_major>(shape[i][0], shape[i][1]);
        qr_solve<std::complex<double>,               amgcl::detail::col_major>(shape[i][0], shape[i][1]);
        qr_solve<amgcl::static_matrix<double, 2, 2>, amgcl::detail::row_major>(shape[i][0], shape[i][1]);
        qr_solve<amgcl::static_matrix<double, 2, 2>, amgcl::detail::col_major>(shape[i][0], shape[i][1]);
    }
}

BOOST_AUTO_TEST_CASE( qr_issue_39 ) {
    boost::multi_array<double, 2> A0(boost::extents[2][2]);
    A0[0][0] = 1e+0;
    A0[0][1] = 1e+0;
    A0[1][0] = 1e-8;
    A0[1][1] = 1e+0;

    boost::multi_array<double, 2> A = A0;

    amgcl::detail::QR<double> qr;

    qr.factorize(2, 2, A.data());

    // Check that A = QR
    for(int i = 0; i < 2; ++i) {
        for(int j = 0; j < 2; ++j) {
            double sum = 0;
            for(int k = 0; k < 2; ++k)
                sum += qr.Q(i,k) * qr.R(k,j);

            sum -= A0[i][j];

            BOOST_CHECK_SMALL(sum, 1e-8);
        }
    }
}

BOOST_AUTO_TEST_SUITE_END()

max_stars_repo_name: tenglongcong/amgcl

max_issues_repo_name: tenglongcong/amgcl

max_forks_repo_name: tenglongcong/amgcl


text: #include <boost/graph/distributed/adjlist/handlers.hpp>


text:
// Author(s): Gijs Kant
// Copyright: see the accompanying file COPYING or copy at
// https://svn.win.tue.nl/trac/MCRL2/browser/trunk/COPYING
//
// 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)
//
/// \file ppg_rewriter_test.cpp
/// \brief Test for the ppg rewriter.

#include <iostream>
#include <boost/test/minimal.hpp>
#include "mcrl2/pbes/normalize.h"
#include "mcrl2/pbes/txt2pbes.h"
#include "mcrl2/pbes/rewriter.h"
#include "mcrl2/pbes/detail/ppg_visitor.h"
#include "mcrl2/pbes/detail/bqnf2ppg_rewriter.h"
#include "mcrl2/pbes/detail/bqnf_traverser.h"
#include "mcrl2/pbes/detail/ppg_traverser.h"
#include "mcrl2/pbes/detail/ppg_rewriter.h"

using namespace mcrl2;
using namespace mcrl2::pbes_system;

void rewrite_ppg(const std::string& bqnf_text, const std::string& ppg_text)
{
  std::clog << "rewrite_ppg" << std::endl;
  std::clog << "Parsing text..." << std::endl;
  //std::clog << bqnf_text << std::endl;
  pbes p = txt2pbes(bqnf_text);
  std::clog << "done." << std::endl;

  bool is_bqnf = pbes_system::detail::is_bqnf(p);
  std::clog << "bqnf_traverser says: p is " << (is_bqnf ? "" : "NOT ") << "in BQNF." << std::endl;
  bool is_ppg = pbes_system::detail::is_ppg(p);
  std::clog << "ppg_traverser says: p is " << (is_ppg ? "" : "NOT ") << "a PPG." << std::endl;
  std::clog << "Try the new rewriter:" << std::endl;
  pbes q = pbes_system::detail::to_ppg(p);
  std::clog << "The new rewriter is done." << std::endl;
  //std::clog << "result:" << std::endl << pbes_system::pp(q) << std::endl << std::endl;
  is_ppg = pbes_system::detail::is_ppg(q);
  std::clog << "ppg_traverser says: result is " << (is_ppg ? "" : "NOT ") << "a PPG." << std::endl;
  p = q;
  normalize(p);
  std::clog << "Parsing text..." << std::endl;
  pbes ppg = txt2pbes(ppg_text);
  normalize(ppg);
  std::clog << "Checking for equality..." << std::endl;
  if (!(p==ppg))
  {
    std::clog << "target:" << std::endl << ppg_text << std::endl << std::endl;
    std::clog << "result:" << std::endl << pbes_system::pp(p) << std::endl;
  }
  BOOST_CHECK(p==ppg);
  std::clog << "done." << std::endl;
}

void test_ppg_rewriter()
{
  // buffer.always_send_and_receive
  std::string bqnf_text =
      "sort D = struct d1 | d2;\n"
      "map  N: Pos;\n"
      "eqn  N  =  2;\n"
      "pbes nu X(q_Buffer: List(D)) =\n"
      "  (exists d: D. (val(#q_Buffer < 2) && X(q_Buffer <| d))) && (exists d: D. val(head(q_Buffer) == d) && val(!(q_Buffer == [])) && X(tail(q_Buffer)));\n"
      "init X([]);"
  ;
  std::string ppg_text =
      "sort D = struct d1 | d2;\n"
      "map  N: Pos;\n"
      "eqn  N  =  2;\n"
      "pbes nu X_1(q_Buffer: List(D)) =\n"
      "  exists d: D. val(#q_Buffer < 2) && X(q_Buffer <| d);\n"
      "nu X_2(q_Buffer: List(D)) =\n"
      "  exists d: D. val(head(q_Buffer) == d) && val(!(q_Buffer == [])) && X(tail(q_Buffer));\n"
      "nu X(q_Buffer: List(D)) =\n"
      "  X_1(q_Buffer) && X_2(q_Buffer);\n"
      "init X([]);"
  ;
  rewrite_ppg(bqnf_text, ppg_text);
}

int test_main(int argc, char* argv[])
{
  test_ppg_rewriter();

  return 0;
}


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

  Defines the as_simd metafunction for SSE2 like extensions

  @copyright 2012 - 2015 NumScale SAS

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

**/
//==================================================================================================
#ifndef BOOST_SIMD_ARCH_X86_SSE2_AS_SIMD_HPP_INCLUDED
#define BOOST_SIMD_ARCH_X86_SSE2_AS_SIMD_HPP_INCLUDED

#include <boost/simd/arch/x86/sse1/as_simd.hpp>
#include <boost/dispatch/meta/is_natural.hpp>

namespace boost { namespace simd
{
  template<typename T> struct logical;

  namespace ext
  {
    template<> struct as_simd<double, boost::simd::sse_>
    {
      using type = __m128d;
    };

    template<typename T>
    struct as_simd< T, boost::simd::sse_
                  , typename std::enable_if<boost::dispatch::is_natural<T>::value>::type
                  >
    {
      using type = __m128i;
    };
  }
} }

#endif


text:
#include <antgame/Ant.h>
#include <antgame/Food.h>
#include <antgame/World.h>

#include <easyloggingpp/easylogging++.h>

#include <boost/math/constants/constants.hpp>
#include <boost/geometry.hpp>

#include <math.h>
#include <stdlib.h>

namespace {
	float RandFloat(float lo, float hi) {
		return lo + static_cast <float> (rand()) /( static_cast <float> (RAND_MAX/(hi - lo)));
	}

	inline float DegreesToRadians(float degrees) {
		return degrees * boost::math::constants::pi<double>() / 180;
	}

	static constexpr auto kStartingEnergy = 100;
}

Ant::Ant(const Point& initialPosition, const std::string& name)
: Agent(initialPosition, name)
, m_direction(RandFloat(-180, 180))
, m_energy(kStartingEnergy)
{ }

void Ant::Turn(float Angle) { //updates direction of Ant
	m_direction += Angle;

	// if (m_direction < -180){
	// 	m_direction += 360;
	// }
	// else if (m_direction > 180) {
	// 	m_direction -= 360;
	// }
}

void Ant::Move(float turningAngle, float distanceForward) {
	Ant::Turn(turningAngle);
	this->SetPosX(this->GetPosX() + (distanceForward * cos(DegreesToRadians(m_direction)))); //move forward in new direction
	this->SetPosY(this->GetPosY() + (distanceForward * sin(DegreesToRadians(m_direction))));
}

void Ant::Eat(Food& food) {
	AddEnergy(food.GetNutritionalValue());
	food.BecomeEaten();
}

void Ant::Update(const WorldTree& world) {
	static constexpr auto kDriftDelta = 0.05;
	static constexpr auto kEatingDistance = 0.2;
	static constexpr auto kDivideEnergy = 200;
	static constexpr auto kEnergyDrain = 0.1;
	static constexpr auto kMaxTurnAngle = 10;
	static constexpr auto kSpeed = 0.01; //ant speed
	static constexpr auto kVisionDistance = 200 * kSpeed; //ant speed

	AddEnergy(-kEnergyDrain);

	if (m_energy < 0) {
		LOG(INFO) << "died from lack of food";
		RemoveSelfFromWorld();
		return;
	}

	if (m_energy > kDivideEnergy) {
        auto child1 = std::make_shared<Ant>(m_position, GetName() + "_1");
        m_world->QueueAddAgent(std::move(child1));
        auto child2 = std::make_shared<Ant>(m_position, GetName() + "_2");
        m_world->QueueAddAgent(std::move(child2));

		RemoveSelfFromWorld();
		return;
	}

    auto nearestObject =  world.GetNearestNeighbours(m_position, 2).front();

	// This is just demo activity.
	// TODO: ant brain
	if (typeid(Food) == typeid(*nearestObject.get())) {

		auto direction = this->GetPosition(); //gets ants current position
		boost::geometry::subtract_point(direction, nearestObject->GetPosition()); //p1 - p2 = p21 a vector from the food to the ant
		auto distance = boost::geometry::strategy::distance::pythagoras().apply(m_position, nearestObject->GetPosition()); // distance to food

		if(distance < kVisionDistance) { //if you see food but it's too far away you don't see it sike
			boost::geometry::divide_value(direction, -distance); //normalises and  flips the vector to point from ant to food

			float angleToTurn;
			if (direction.get<0>() >= 0) {
				angleToTurn = DegreesToRadians(atan(direction.get<1>()/direction.get<0>())) - m_direction;
			}
			else if (direction.get<1>() >= 0){
				angleToTurn = 180 - DegreesToRadians(atan(direction.get<1>()/direction.get<0>())) - m_direction;
			}
			else {
				angleToTurn = -180 + DegreesToRadians(atan(direction.get<1>()/direction.get<0>())) - m_direction;
			}

			if (angleToTurn > kMaxTurnAngle) {
				angleToTurn = kMaxTurnAngle;
			}
			else if (angleToTurn < -kMaxTurnAngle) {
				angleToTurn = -kMaxTurnAngle;
			}

			if (distance < kEatingDistance) {
				Eat(*dynamic_cast<Food*>(nearestObject.get()));
			}
			else {
				Ant::Move(angleToTurn, kSpeed);
			}
		}
		else {
			Ant::Move(RandFloat(-kMaxTurnAngle, kMaxTurnAngle), kSpeed);
		}
	}
	else {
		Ant::Move(RandFloat(-kMaxTurnAngle, kMaxTurnAngle), RandFloat(kSpeed, kSpeed*2));
	}
}

max_stars_repo_name: maxnoka/AntGame

max_issues_repo_name: maxnoka/AntGame

max_forks_repo_name: maxnoka/AntGame


text:
/////////1/////////2/////////3/////////4/////////5/////////6/////////7/////////8
// Name        : Openssl
// Author      : Avi
// Revision    : $Revision: #10 $
//
// Copyright 2009- ECMWF.
// This software is licensed under the terms of the Apache Licence version 2.0
// which can be obtained at http://www.apache.org/licenses/LICENSE-2.0.
// In applying this licence, ECMWF does not waive the privileges and immunities
// granted to it by virtue of its status as an intergovernmental organisation
// nor does it submit to any jurisdiction.
//
// Description :
/////////1/////////2/////////3/////////4/////////5/////////6/////////7/////////8
#include <stdexcept>
#include <cstdlib>  // getenv
#include <cassert>

//#include <iostream>

#include "boost/filesystem/operations.hpp"
#include <boost/bind.hpp>

#include "Openssl.hpp"
#include "File.hpp"
#include "Host.hpp"
#include "Str.hpp"

using namespace std;
namespace fs = boost::filesystem;

namespace ecf {

std::string Openssl::info() const
{
   if (ssl_ == "1")  return "1 : enabled : uses shared ssl certificates";
   return ssl_ + " : enabled : uses server/port specific ssl certificates";
}

bool Openssl::enable_no_throw(std::string host,const std::string& port, const std::string& ecf_ssl_env)
{
   if (host == Str::LOCALHOST())  host = Host().name();

   //   if (Ecf::server()) cout << "Openssl::enable(SERVER) ---> input host:" << host << " port:" << port << " ECF_SSL = " << ecf_ssl_env << "\n";
   //   else               cout << "Openssl::enable(CLIENT) ---> input host:" << host << " port:" << port << " ECF_SSL = " << ecf_ssl_env << "\n";

   if (ecf_ssl_env.empty() || ecf_ssl_env == "1") {
      // LOOK for      $HOME/.ecflowrc/ssl/server.crt
      // THEN LOOK for $HOME/.ecflowrc/ssl/<host>.<port>.crt
      // Look for the certificate that HAVE to exist on both client and server. i.e Self signed certificate (CRT)
      // Needed for testing, avoid <host>.<port>.crt when ports numbers are auto generated
      ssl_ = "1";
      if (!fs::exists(crt())) { // crt() uses ssl_

         // More specific per server. But we take an extra hit on file access.
         ssl_ = host;
         ssl_ += ".";
         ssl_ += port;
         if (!fs::exists(crt())) {  // crt() uses ssl_
            ssl_.clear();
            return false;
         }
      }
   }
   else {
      ssl_ = host;
      ssl_ += ".";
      ssl_ += port;
      if (!fs::exists(crt())) {  // crt() uses ssl_
         ssl_.clear();
         return false;
      }
   }
   //cout << "Openssl::enable input ssl_:'" << ssl_ << "'\n";
   return true;
}

void Openssl::enable(std::string host,const std::string& port)
{
   if (host == Str::LOCALHOST())  host = Host().name();

   if (!enable_no_throw(host,port)) {
      std::stringstream ss;
      ss << "Openssl::enable: Error: Expected to find the self signed certificate file(CRT) server.crt or " << host << "." << port << ".crt in $HOME/.ecflowrc/ssl";
      throw std::runtime_error(ss.str());
   }
}

void Openssl::enable_if_defined(std::string host,const std::string& port)
{
   char* ecf_ssl = getenv("ECF_SSL");
   if ( ecf_ssl ) {
      std::string ecf_ssl_env = ecf_ssl;

      if (host == Str::LOCALHOST()) host = Host().name();

      if (!enable_no_throw(host,port,ecf_ssl_env)) {
         std::stringstream ss;
         if (ecf_ssl_env == "1") {
            ss << "Openssl::enable: Error: Expected to find the self signed certificate file(CRT) server.crt *OR* " << host << "." << port << ".crt in $HOME/.ecflowrc/ssl when ECF_SSL=1";
         }
         else {
            ss << "Openssl::enable: Error: Expected to find the self signed certificate file(CRT) " << host << "." << port << ".crt in $HOME/.ecflowrc/ssl when ECF_SSL="<< host << "." << port;
         }
         throw std::runtime_error(ss.str());
      }
   }
}

boost::asio::ssl::context& Openssl::context()
{
	assert(ssl_context_);
	return *ssl_context_;
}

void Openssl::init_for_server()
{
//   std::cout << " Openssl::init_for_server  host :" << host_ << "@" << port_ << "\n";
//   std::cout << " Openssl::init_for_server ssl_:'" << ssl_ << "'\n";
	if (enabled()) {
		check_server_certificates();

		ssl_context_ = std::make_unique<boost::asio::ssl::context>(boost::asio::ssl::context::sslv23);
		ssl_context_->set_options(
				boost::asio::ssl::context::default_workarounds
				| boost::asio::ssl::context::no_sslv2
				| boost::asio::ssl::context::single_dh_use);
		// this must be done before loading any keys. as below
		ssl_context_->set_password_callback(boost::bind(&Openssl::get_password, this));
		ssl_context_->use_certificate_chain_file( crt() );
		ssl_context_->use_private_key_file( key(), boost::asio::ssl::context::pem);
		ssl_context_->use_tmp_dh_file( pem() );
	}
}

void Openssl::init_for_client()
{
//   std::cout << " Openssl::init_for_client host :" << host_ << "@" << port_ << "\n";
   if (!init_for_client_ && enabled()) {
      init_for_client_ = true;

      ssl_context_ = std::make_unique<boost::asio::ssl::context>(boost::asio::ssl::context::sslv23);
      ssl_context_->load_verify_file(crt());
   }
}

std::string Openssl::get_password() const
{
   // std::cout << "Openssl::get_password()\n";
   std::string passwd_file = passwd();
   if (fs::exists(passwd_file)) {
      std::string contents;
      if (ecf::File::open(passwd_file,contents)) {
         // remove /n added by editor.
         if (!contents.empty() && contents[contents.size()-1] == '\n') contents.erase(contents.begin() + contents.size()-1);
         //std::cout << "Server::get_password() passwd('" << contents << "')\n";
         return contents;
      }
      else {
         std::stringstream ss;
         ss << "Server::get_password file " << passwd_file << " exists, but can't be opened (" << strerror(errno) << ")";
         throw std::runtime_error(ss.str());
      }
   }
   //std::cout << "Server::get_password() passwd('test')\n";
   return "test";
}

std::string Openssl::certificates_dir() const
{
   std::string home_path = getenv("HOME");
   home_path += "/.ecflowrc/ssl/";
   return home_path;
}

std::string Openssl::pem() const
{
   std::string str = certificates_dir();
   if (ssl_ == "1") {
      // assume 2048-bit dh key, but accept 1024-bit for
      // backwards-compatibility (note: openssl might
      // not accept it, depending on the version used)
      str += "dh2048.pem";

      if (!fs::exists(str)) {
         return certificates_dir() + "dh1024.pem";
      }
      return str;
   }

   str += ssl_;
   str += ".pem";
   return str;
}

std::string Openssl::crt() const
{
   std::string str = certificates_dir();
   if (ssl_ == "1") { str += "server.crt"; return str;}
   str += ssl_;
   str += ".crt";
   return str;
}

std::string Openssl::key() const
{
   std::string str = certificates_dir();
   if (ssl_ == "1") { str += "server.key"; return str; }
   str += ssl_;
   str += ".key";
   return str;
}

std::string Openssl::passwd() const
{
   std::string str = certificates_dir();
   if (ssl_ == "1") { str += "server.passwd"; return str;}
   str += ssl_;
   str += ".passwd";
   return str;
}

const char* Openssl::ssl_info() {
   return
            "ecFlow client and server are SSL enabled. To use SSL choose between:\n"
            "  1. export ECF_SSL=1              # search for server.crt otherwise <host>.<port>.crt\n"
            "  2. export ECF_SSL=<host>.<port>  # Use server specific certificates <host>.<port>.***\n"
            "  3. use --ssl           # argument on ecflow_client/ecflow_server, same as option 1.\n"
            "                         # Typically ssl server can be started with ecflow_start.sh -s\n"
            "  4. Client.enable_ssl() # for python client\n\n"
            "ecFlow expects the certificates to be in directory $HOME/.ecflowrc/ssl\n"
            "The certificates can be shared if you have multiple servers running on\n"
            "the same machine. In this case use ECF_SSL=1, then\n"
            "ecflow_server expects the following files in $HOME/.ecflowrc/ssl\n\n"
            "   - dh2048.pem\n"
            "   - server.crt\n"
            "   - server.key\n"
            "   - server.passwd (optional) if this exists it must contain the pass phrase used to create server.key\n\n"
            "ecflow_client expects the following files in : $HOME/.ecflowrc/ssl\n\n"
            "   - server.crt (this must be the same as server)\n\n"
            "Alternatively you can have different setting for each server ECF_SSL=<host>.<port>\n"
            "Then server expect files of the type:\n\n"
            "   - <host>.<port>.pem\n"
            "   - <host>.<port>.crt\n"
            "   - <host>.<port>.key\n"
            "   - <host>.<port>.passwd (optional)\n\n"
            "and client expect files of the type:\n\n"
            "   - <host>.<port>.crt  # as before this must be same as the server\n\n"
            "The server/client will automatically check existence of both variants,\n"
            "but will give preference to NON <host>.<port>.*** variants first, when ECF_SSL=1\n"
            "The following steps, show you how to create the certificate files.\n"
            "This may need to be adapted if you want to use <host>.<port>.***\n\n"
            "- Generate a password protected private key. This will request a pass phrase.\n"
            "  This key is a 1024 bit RSA key which is encrypted using Triple-DES and stored\n"
            "  in a PEM format so that it is readable as ASCII text\n\n"
            "     > openssl genrsa -des3 -out server.key 1024   # Password protected private key\n"
            "- Additional security.\n"
            "  If you want additional security, create a file called 'server.passwd' and add the pass phrase to the file.\n"
            "  Then set the file permission so that file is only readable by the server process.\n"
            "  Or you can choose to remove password requirement. In that case we don't need server.passwd file.\n\n"
            "     > cp server.key server.key.secure\n"
            "     > openssl rsa -in server.key.secure -out server.key  # remove password requirement\n"
            "- Sign certificate with private key (self signed certificate).Generate Certificate Signing Request(CSR).\n"
            "  This will prompt with a number of questions.\n"
            "  However please ensure 'common name' matches the host where your server is going to run.\n\n"
            "     > openssl req -new -key server.key -out server.csr # Generate Certificate Signing Request(CSR)\n"
            "- Generate a self signed certificate CRT, by using the CSR and private key.\n\n"
            "     > openssl x509 -req -days 3650 -in server.csr -signkey server.key -out server.crt\n\n"
            "- Generate dhparam file. ecFlow expects 2048 key.\n"
            "     > openssl dhparam -out dh2048.pem 2048"
            ;
}

void Openssl::check_server_certificates() const
{
//   cout << "Openssl::check_server_certificates: ssl'" << ssl_ << "'\n";

   {
      string server_key = key();
      if (!fs::exists(server_key)) throw std::runtime_error("Error: The password protected private server key file '" + server_key  + "' does not exist\n\n" + ssl_info() );
   }
   {
      string server_pem = pem();
      if (!fs::exists(server_pem)) throw std::runtime_error("Error: The dhparam file(pem) '" +  server_pem  + "' does not exist\n\n" + ssl_info());
   }
}

std::ostream& operator<<(std::ostream& os, const ecf::Openssl& ssl)
{
   ssl.print(os);
   return os;
}

}

max_stars_repo_name: mpartio/ecflow

max_issues_repo_name: mpartio/ecflow

max_forks_repo_name: mpartio/ecflow


text:
#include <emp-tool/emp-tool.h>
#include <boost/program_options.hpp>
#include <boost/lexical_cast/try_lexical_convert.hpp>
#include <boost/program_options/value_semantic.hpp>
#include <cstdlib>

using namespace std;
namespace po = boost::program_options;

std::vector<po::option> ignore_numbers(std::vector<std::string>& args)
{
	std::vector<po::option> result;
	int pos = 0;
	while(!args.empty()) {
		const auto& arg = args[0];
		int64_t num;
		if(boost::conversion::try_lexical_convert(arg, num)) {
			result.push_back(po::option());
			po::option& opt = result.back();

			opt.position_key = pos++;
			opt.value.push_back(arg);
			opt.original_tokens.push_back(arg);

			args.erase(args.begin());
		} else {
			break;
		}
	}

	return result;
}

int main(int argc, char** argv) {
	uint64_t bit_len = 1;
	vector<uint64_t> bit_len_vector;
	vector<int64_t> input;
	string input_str;
	string output_str;
	vector<int64_t> output;
	bool is_signed = false;

	po::variables_map vm;

	po::options_description desc{"Format the input string or parse the output string. \nAllowed options"};
	desc.add_options()  //
	("help,h", "produce help message")  //
	("input,i", po::value<vector<int64_t>>(&input)->multitoken(), "input decimal numbers") //
	("output,o", po::value<string>(&output_str), "output hex string") //
	("bits,b", po::value<vector<uint64_t>>(&bit_len_vector)->multitoken(), "number of bits in each decimal number") //
	("signed,s",  "outputs are parsed as signed numbers (default is unsigned)");

	po::store(po::command_line_parser(argc, argv)
	.extra_style_parser(&ignore_numbers)
	.options(desc)
	.run(), vm);

	try {
		po::parsed_options parsed = po::command_line_parser(argc, argv).options(desc).allow_unregistered().run();
		po::store(parsed, vm);
		if (vm.count("help")) {
			cout << desc << endl;
			return 0;
		}
		po::notify(vm);
	}catch (po::error& e) {
		cout << "ERROR: " << e.what() << endl << endl;
		cout << desc << endl;
		return -1;
	}

	if (!vm.count("bits"))  error("Error: specify the bit-length of each number.\n");
	if (bit_len_vector.size() == 1) bit_len = bit_len_vector[0];

	if (vm.count("signed")) is_signed = true;

	if (vm.count("input")){
		if (bit_len_vector.size() == 1) input_str = formatGCInputString(input, bit_len);
		else{
			if (input.size() != bit_len_vector.size()) error("Error: number of inputs should match the number of bit-lengths.\n");
			input_str = formatGCInputString(input, bit_len_vector);
		}
		cout << input_str << endl;
	}

	if (vm.count("output")){
		if (bit_len_vector.size() == 1) parseGCOutputString(output, output_str, bit_len, 0, is_signed);
		else parseGCOutputString(output, output_str, bit_len_vector, 0, is_signed);
		for (uint64_t i = 0; i < output.size(); ++i)
			cout << output[i] << " ";
		cout << endl;
	}

	return 0;
}

max_stars_repo_name: sygc-pets/sygc

max_issues_repo_name: sygc-pets/sygc

max_forks_repo_name: sygc-pets/sygc


text:
// Copyright (c) 2017 Daniel Cooke
// Use of this source code is governed by the MIT license that can be found in the LICENSE file.

#include <boost/test/unit_test.hpp>

#include <vector>
#include <iterator>
#include <algorithm>

#include "basics/contig_region.hpp"
#include "containers/mappable_flat_set.hpp"

namespace octopus { namespace test {

using octopus::MappableFlatSet;

BOOST_AUTO_TEST_SUITE(containers)
BOOST_AUTO_TEST_SUITE(mappable_flat_set)

BOOST_AUTO_TEST_CASE(emplace_works)
{
    MappableFlatSet<ContigRegion> set {};

    set.emplace(0, 0);
    BOOST_REQUIRE_EQUAL(set.size(), 1);
    set.emplace(0, 0);
    BOOST_CHECK_EQUAL(set.size(), 1);
    set.emplace(0, 1);
    BOOST_REQUIRE_EQUAL(set.size(), 2);
    set.emplace(0, 1);
    BOOST_CHECK_EQUAL(set.size(), 2);

    set.emplace(0, 3);
    set.emplace(1, 1);
    set.emplace(2, 4);
    set.emplace(4, 5);

    BOOST_CHECK_EQUAL(set.size(), 6);
    BOOST_CHECK(std::is_sorted(std::cbegin(set), std::cend(set)));
}

BOOST_AUTO_TEST_CASE(range_insert_acceptes_empty_ranges)
{
    MappableFlatSet<ContigRegion> set {};

    std::vector<ContigRegion> empty {};

    BOOST_CHECK_NO_THROW(set.insert(std::cbegin(empty), std::cend(empty)));
    BOOST_CHECK(set.empty());

    set.emplace(0, 1);

    BOOST_CHECK_NO_THROW(set.insert(std::cbegin(empty), std::cend(empty)));
    BOOST_CHECK_EQUAL(set.size(), 1);
}

BOOST_AUTO_TEST_CASE(range_insert_accepts_unsorted_ranges)
{
    const ContigRegion r1 {0, 1}, r2 {0, 2}, r3 {1, 1}, r4 {0, 0}, r5 {0, 4}, r6 {2, 2}, r7 {0, 3}, r8 {1, 2};

    std::vector<ContigRegion> unsorted {r1, r2, r3, r4, r5, r6, r7, r8};

    MappableFlatSet<ContigRegion> set {};

    set.insert(std::cbegin(unsorted), std::cend(unsorted));

    BOOST_CHECK_EQUAL(set.size(), unsorted.size());
    BOOST_CHECK(std::is_sorted(std::cbegin(set), std::cend(set)));
}

BOOST_AUTO_TEST_CASE(insert_hint_works)
{
    const ContigRegion r1 {0, 1}, r2 {0, 2}, r3 {1, 1}, r4 {0, 0}, r5 {0, 4},
                        r6 {2, 2}, r7 {1, 1}, r8 {0, 2}, r9 {0, 3}, r10 {1, 2};

    std::vector<ContigRegion> regions {r1, r2, r3, r4, r5, r6, r7, r8, r9, r10};

    MappableFlatSet<ContigRegion> set {};

    // std::inserter calls the hinted insert version
    std::copy(std::begin(regions), std::end(regions), std::inserter(set, std::begin(set)));

    auto unique_regions = regions;

    std::sort(std::begin(unique_regions), std::end(unique_regions));

    unique_regions.erase(std::unique(std::begin(unique_regions), std::end(unique_regions)),
                         std::end(unique_regions));

    BOOST_REQUIRE_EQUAL(set.size(), unique_regions.size());

    BOOST_CHECK(std::equal(std::cbegin(set), std::cend(set), std::cbegin(unique_regions)));

    set.clear();

    BOOST_REQUIRE(set.empty());

    std::copy(std::make_move_iterator(std::begin(regions)),
              std::make_move_iterator(std::end(regions)),
              std::inserter(set, std::begin(set)));

    BOOST_REQUIRE_EQUAL(set.size(), unique_regions.size());

    BOOST_CHECK(std::equal(std::cbegin(set), std::cend(set), std::cbegin(unique_regions)));

    auto it = set.insert(std::cbegin(set), r2);

    BOOST_CHECK_EQUAL(*it, r2);

    it = set.insert(std::cend(set), r2);

    BOOST_CHECK_EQUAL(*it, r2);

    it = set.insert(std::cbegin(set), r3);

    BOOST_CHECK_EQUAL(*it, r3);

    it = set.insert(std::cend(set), r3);

    BOOST_CHECK_EQUAL(*it, r3);

    const ContigRegion r11 {0, 5};

    it = set.insert(std::next(std::cbegin(set), 3), r11);

    BOOST_CHECK_EQUAL(set.size(), unique_regions.size() + 1);
    BOOST_CHECK_EQUAL(*it, r11);
    BOOST_CHECK(std::is_sorted(std::cbegin(set), std::cend(set)));
}

BOOST_AUTO_TEST_CASE(erase_maybe_removes_a_single_element)
{
    MappableFlatSet<ContigRegion> set {};

    ContigRegion r1 {}, r2 {0, 0}, r3 {0, 1}, r4 {0, 2}, r5 {1, 1}, r6 {1, 5};

    BOOST_CHECK_NO_THROW(set.erase(r1));

    set.emplace(0, 0);

    set.erase(r1);

    BOOST_CHECK(set.empty());

    set.insert(r2);
    set.erase(r2);

    BOOST_CHECK(set.empty());

    set.insert(r3);
    set.erase(r3);

    BOOST_CHECK(set.empty());

    set.insert(r2);
    set.insert(r3);
    set.insert(r4);
    set.insert(r5);

    set.erase(r4);

    BOOST_CHECK_EQUAL(set.size(), 3);

    set.insert(r4);
    set.insert(r6);

    set.erase(r5);
    BOOST_CHECK_EQUAL(set.size(), 4);
    BOOST_CHECK(std::is_sorted(std::cbegin(set), std::cend(set)));
    set.erase(r3);
    BOOST_CHECK_EQUAL(set.size(), 3);
    BOOST_CHECK(std::is_sorted(std::cbegin(set), std::cend(set)));
    set.erase(r6);
    BOOST_CHECK_EQUAL(set.size(), 2);
    BOOST_CHECK(std::is_sorted(std::cbegin(set), std::cend(set)));
    set.erase(r4);
    BOOST_CHECK_EQUAL(set.size(), 1);
    BOOST_CHECK(std::is_sorted(std::cbegin(set), std::cend(set)));
    set.erase(r2);
    BOOST_CHECK(set.empty());
}

BOOST_AUTO_TEST_CASE(erase_all_works_for_empty_range)
{
    MappableFlatSet<ContigRegion> set {};

    set.emplace(0, 0);
    set.emplace(0, 1);
    set.emplace(1, 1);

    std::vector<ContigRegion> empty {};

    BOOST_REQUIRE_NO_THROW(set.erase_all(std::cbegin(empty), std::cend(empty)));

    BOOST_CHECK_EQUAL(set.size(), 3);
}

BOOST_AUTO_TEST_CASE(erase_all_is_unchanged_if_there_are_no_matches)
{
    const ContigRegion r1 {0, 1}, r2 {0, 2}, r3 {1, 1}, r4 {0, 0}, r5 {0, 4},
    r6 {2, 2}, r7 {1, 1}, r8 {0, 2}, r9 {0, 3}, r10 {1, 2};

    std::vector<ContigRegion> regions {r1, r2, r3, r4, r5, r6, r7, r8, r9, r10};

    std::sort(std::begin(regions), std::end(regions));

    MappableFlatSet<ContigRegion> set {};

    auto n = set.erase_all(std::cbegin(regions), std::cend(regions));

    BOOST_CHECK_EQUAL(n, 0);
    BOOST_CHECK(set.empty());

    set.insert(std::cbegin(regions), std::cend(regions));

    std::vector<ContigRegion> others {ContigRegion {1, 3}, ContigRegion {3, 3}, ContigRegion {3, 4}};

    const auto s = set.size();

    n = set.erase_all(std::cbegin(others), std::cend(others));

    BOOST_CHECK_EQUAL(n, 0);
    BOOST_CHECK_EQUAL(set.size(), s);
}

BOOST_AUTO_TEST_CASE(erase_all_only_erases_given_elements_and_maintains_order)
{
    std::vector<ContigRegion> tmp {};

    MappableFlatSet<ContigRegion> set {};

    set.emplace(0, 0);

    tmp.emplace_back(0, 0);

    set.erase_all(std::cbegin(tmp), std::cend(tmp));

    BOOST_CHECK(set.empty());

    set.emplace(0, 0);
    set.emplace(0, 1);
    set.emplace(1, 1);
    set.emplace(0, 3);

    set.erase_all(std::cbegin(tmp), std::cend(tmp));

    BOOST_CHECK_EQUAL(set.size(), 3);

    tmp.emplace_back(0, 3);
    tmp.emplace_back(1, 1);
    tmp.emplace_back(1, 2);

    set.erase_all(std::cbegin(tmp), std::cend(tmp));

    BOOST_CHECK_EQUAL(set.size(), 1);

    // Now a tricky one

    set.clear();
    tmp.clear();

    BOOST_REQUIRE(set.empty());

    set.emplace(81, 82);
    set.emplace(136, 137);
    set.emplace(138, 138);
    set.emplace(163, 171);
    set.emplace(164, 164);
    set.emplace(164, 165);
    set.emplace(165, 166);
    set.emplace(166, 167);
    set.emplace(167, 168);
    set.emplace(168, 169);
    set.emplace(169, 170);
    set.emplace(170, 171);
    set.emplace(170, 179);
    set.emplace(171, 172);
    set.emplace(173, 174);

    tmp.emplace_back(163, 171);
    tmp.emplace_back(164, 164);
    tmp.emplace_back(164, 165);
    tmp.emplace_back(170, 171);
    tmp.emplace_back(170, 179);

    auto s = set.size();

    set.erase_all(std::cbegin(tmp), std::cend(tmp));

    BOOST_CHECK_EQUAL(set.size(), s - tmp.size());
    BOOST_CHECK(std::is_sorted(std::cbegin(set), std::cend(set)));
}

BOOST_AUTO_TEST_SUITE_END()
BOOST_AUTO_TEST_SUITE_END()

} // namespace test
} // namespace octopus

max_stars_repo_name: gunjanbaid/octopus

max_issues_repo_name: gunjanbaid/octopus

max_forks_repo_name: gunjanbaid/octopus


text:
#include "ModeListStoragePools.h"

#include <app/App.h>
#include <common/net/message/nodes/storagepools/GetStoragePoolsMsg.h>
#include <common/net/message/nodes/storagepools/GetStoragePoolsRespMsg.h>
#include <common/toolkit/MessagingTk.h>
#include <common/toolkit/ZipIterator.h>
#include <program/Program.h>

#include <boost/format.hpp>

int ModeListStoragePools::execute()
{
   // check arguments
   StringMap* cfg = Program::getApp()->getConfig()->getUnknownConfigArgs();

   if(ModeHelper::checkInvalidArgs(cfg) )
      return APPCODE_INVALID_CONFIG;

   NodeStoreServers* mgmtNodes = Program::getApp()->getMgmtNodes();
   NodeHandle mgmtNode = mgmtNodes->referenceFirstNode();

   if (!mgmtNode)
   {
      std::cerr << "Management node not defined." << std::endl;
      return APPCODE_INVALID_CONFIG;
   }

   GetStoragePoolsRespMsg* respMsgCast;

   GetStoragePoolsMsg msg;

   const auto respMsg = MessagingTk::requestResponse(*mgmtNode, msg,
         NETMSGTYPE_GetStoragePoolsResp);

   if (!respMsg)
   {
      std::cerr << "Communication with server failed: " << mgmtNode->getNodeIDWithTypeStr()
         << std::endl;

      return APPCODE_RUNTIME_ERROR;
   }

   respMsgCast = static_cast<GetStoragePoolsRespMsg*>(respMsg.get());

   printPools(respMsgCast->getStoragePools());

   return APPCODE_NO_ERROR;
}

void ModeListStoragePools::printHelp()
{
   std::cout << "MODE ARGUMENTS:" << std::endl;
   std::cout << std::endl;
   std::cout << "USAGE:" << std::endl;
   std::cout << " This mode lists all storage target pools." << std::endl;
   std::cout << std::endl;
   std::cout << " Example: List all pools." << std::endl;
   std::cout << "  $ beegfs-ctl --liststoragepools" << std::endl;
}

void ModeListStoragePools::printPools(const StoragePoolPtrVec& pools) const
{
   std::cout << boost::format("%7s %18s %28s %28s\n") % "Pool ID"
                                                      % "Pool Description"
                                                      % "Targets"
                                                      % "Buddy Groups";
   std::cout << boost::format("%7s %18s %28s %28s\n")
      % "======="
      % "=================="
      % "============================"
      % "============================";

   for (StoragePoolPtrVecCIter poolIter = pools.begin(); poolIter != pools.end(); poolIter++)
   {
      const UInt16Set targets = (*poolIter)->getTargets();
      StringVector targetsStrVec = StringTk::implodeMultiLine (targets, ',', 28);

      const UInt16Set buddyGroups = (*poolIter)->getBuddyGroups();
      StringVector buddyGroupsStrVec = StringTk::implodeMultiLine (buddyGroups, ',', 28);

      std::cout << boost::format ("%7i %18s %|-28s| %|-28s|\n") % (*poolIter)->getId()
                % (*poolIter)->getDescription()
                % targetsStrVec[0]
                % buddyGroupsStrVec[0];

      size_t targetsStrVecSize = targetsStrVec.size();
      size_t buddyGroupsStrVecSize = buddyGroupsStrVec.size();

      if (targetsStrVecSize > 1 || buddyGroupsStrVecSize > 1)
      {
         if (targetsStrVecSize > buddyGroupsStrVecSize)
         {
            buddyGroupsStrVec.resize (targetsStrVecSize);
         }
         else if (buddyGroupsStrVecSize > targetsStrVecSize)
         {
            targetsStrVec.resize (buddyGroupsStrVecSize);
         }

         for (size_t i = 1; i < targetsStrVecSize; i++)
         {
            std::cout << boost::format ("%7i %18s %|-28s| %|-28s|\n")
                      % ""
                      % ""
                      % targetsStrVec[i]
                      % buddyGroupsStrVec[i];
         }
      }
   }
}

max_stars_repo_name: TomatoYoung/beegfs

max_issues_repo_name: TomatoYoung/beegfs

max_forks_repo_name: TomatoYoung/beegfs


text:
#define BOOST_TEST_MODULE SolutionTest

#include "solution.hpp"

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

BOOST_AUTO_TEST_SUITE(SolutionSuite)

BOOST_AUTO_TEST_CASE(PlainTest1)
{
    string num1 = "2";
    string num2 = "3";
    string result = Solution().multiply(num1, num2);

    string expected = "6";
    BOOST_CHECK_EQUAL(result, expected);
}

BOOST_AUTO_TEST_CASE(PlainTest2)
{
    string num1 = "123";
    string num2 = "456";
    string result = Solution().multiply(num1, num2);

    string expected = "56088";
    BOOST_CHECK_EQUAL(result, expected);
}

BOOST_AUTO_TEST_CASE(PlainTest3)
{
    string num1 = "0";
    string num2 = "0";
    string result = Solution().multiply(num1, num2);

    string expected = "0";
    BOOST_CHECK_EQUAL(result, expected);
}

BOOST_AUTO_TEST_CASE(PlainTest5)
{
    string num1 = "999";
    string num2 = "999";
    string result = Solution().multiply(num1, num2);

    string expected = "998001";
    BOOST_CHECK_EQUAL(result, expected);
}

BOOST_AUTO_TEST_SUITE_END()

max_stars_repo_name: johnhany/leetcode

max_issues_repo_name: johnhany/leetcode

max_forks_repo_name: johnhany/leetcode