<commit_before>#include "img.h"
#include "config.h"
#include "global.h"
#include <iostream>
#include <sstream>
#include <string>

class tree_node
{
	tree_node *parent = nullptr;
	tree_node *left_child = nullptr;
	tree_node *right_child = nullptr;
	double up_time = 0.0;
	ssize_t index = -1; //?

  public:
	static tree_node leaf(ssize_t idx)
	{
		auto ret = tree_node();
		ret.index = idx;
		return ret;
	}
	tree_node() = default;
	~tree_node() = default;

	void set_left(tree_node *new_left)
	{
		left_child = new_left;
		left_child->parent = this;
	}

	void set_right(tree_node *new_right)
	{
		right_child = new_right;
		right_child->parent = this;
	}

	bool is_branch() const
	{
		return left_child != nullptr;
	}

	bool is_leaf() const
	{
		return left_child == nullptr;
	}

	ssize_t get_index() const
	{
		return index;
	}

	template <typename Func> void traverse(const Func &process)
	{
		if (left_child) {
			left_child->traverse(process);
		}
		process(*this);
		if (right_child) {
			right_child->traverse(process);
		}
	}

	template <typename Func1, typename Func2, typename Func3>
	void traverse(const Func1 &pre, const Func2 &process, const Func3 &post)
	{
		pre(*this);
		if (left_child) {
			left_child->traverse(pre, process, post);
		}
		process(*this);
		if (right_child) {
			right_child->traverse(pre, process, post);
		}
		post(*this);
	}

	std::string to_newick()
	{
		auto ret = std::string();

		auto pre = [&ret](const tree_node &self) {
			if (self.is_branch()) {
				ret += "(";
			}
		};
		auto process = [&ret](const tree_node &self) {
			if (self.is_leaf()) {
				ret += std::to_string(self.get_index());
			} else {
				ret += ",";
			}
		};
		auto post = [&ret](const tree_node &self) {
			if (self.is_branch()) {
				ret += ")";
			}
		};

		traverse(pre, process, post);

		return ret;
	}
};

void img_model::parse_param(std::string key, std::string value)
{
	if (key == "img_theta") {
		this->img_theta = std::stoul(value);
		return;
	}
	if (key == "img_rho") {
		this->img_rho = std::stoul(value);
		return;
	}
	evo_model::parse_param(key, value);
}

std::string img_model::parameters() const
{
	auto str = std::stringstream();

	str << "pangenomesim " << VERSION << "\n\n";
	str << "full options:\n";
	str << "--param gene_length=" << loci_length << "\n";
	str << "--param num_loci=" << num_loci << "\n";
	str << "--param num_genomes=" << num_genomes << "\n";
	str << "--param img_theta=" << img_theta << "\n";
	str << "--param img_rho=" << img_rho << "\n";
	str << "--param seed=" << seed << "\n";

	return str.str();
}

void img_model::simulate()
{
	// generate coalescent
	auto n = num_genomes;
	auto pool = std::vector<tree_node>(2 * n - 1);

	for (size_t i = 0; i < n; i++) {
		pool[i] = tree_node::leaf(i);
	}

	auto indirect = std::vector<tree_node *>();
	indirect.reserve(2 * n - 1);
	for (auto &tn : pool) {
		indirect.push_back(&tn);
	}

	auto rand_int = [](size_t lower, size_t upper) {
		auto rng_help = std::uniform_int_distribution<size_t>(lower, upper - 1);
		return rng_help(RNG);
	};

	std::cerr << "n: " << n << std::endl;
	for (size_t i = 0; i < n - 1; i++) {
		auto p = n + i;
		std::cerr << "i: " << i << " p: " << p << std::endl;
		auto c = rand_int(0, n - i);
		std::cerr << "c: " << c << std::endl;
		indirect.at(p)->set_left(indirect[c]); // also sets [c].parent
		indirect[c] = indirect[n - i - 1];

		auto d = rand_int(0, n - i - 1);
		std::cerr << "d: " << d << std::endl;
		indirect[p]->set_right(indirect[d]);
		indirect[d] = indirect[p];
	}

	std::cerr << indirect[0]->to_newick() << std::endl;

	// create core sequences
	// generate pan genome and create sequences
}

// STUB
std::vector<locus> img_model::get_reference()
{
	return std::vector<locus>();
}

// STUB
std::vector<locus> img_model::get_core()
{
	return std::vector<locus>();
}

// STUB
std::vector<locus> img_model::get_accessory()
{
	return std::vector<locus>();
}

// STUB
std::vector<locus> img_model::get_genome(size_t)
{
	return std::vector<locus>();
}

// STUB
std::vector<locus> img_model::get_locus(size_t)
{
	return std::vector<locus>();
}
<commit_msg>add times to coalescent<commit_after>#include "img.h"
#include "config.h"
#include "global.h"
#include <cassert>
#include <iostream>
#include <sstream>
#include <string>

class tree_node
{
	tree_node *parent = nullptr;
	tree_node *left_child = nullptr;
	tree_node *right_child = nullptr;
	double up_time = 0.0;
	double abs_time = 0.0;
	ssize_t index = -1; //?

  public:
	static tree_node leaf(ssize_t idx)
	{
		auto ret = tree_node();
		ret.index = idx;
		return ret;
	}
	tree_node() = default;
	~tree_node() = default;

	void set_left(tree_node *new_left)
	{
		left_child = new_left;
		left_child->parent = this;
	}

	void set_right(tree_node *new_right)
	{
		right_child = new_right;
		right_child->parent = this;
	}

	void set_time(double t)
	{
		assert(t > 0);
		up_time = t;
	}

	void set_abs_time(double t)
	{
		assert(t > 0);
		abs_time = t;
	}

	double get_time() const noexcept
	{
		return up_time;
	}

	double get_abs_time() const noexcept
	{
		return abs_time;
	}

	bool has_parent() const noexcept
	{
		return parent != nullptr;
	}

	tree_node &get_parent() noexcept
	{
		return *parent;
	}

	bool is_branch() const noexcept
	{
		return left_child != nullptr;
	}

	bool is_leaf() const noexcept
	{
		return left_child == nullptr;
	}

	ssize_t get_index() const noexcept
	{
		return index;
	}

	template <typename Func> void traverse(const Func &process)
	{
		if (left_child) {
			left_child->traverse(process);
		}
		process(*this);
		if (right_child) {
			right_child->traverse(process);
		}
	}

	template <typename Func1, typename Func2, typename Func3>
	void traverse(const Func1 &pre, const Func2 &process, const Func3 &post)
	{
		pre(*this);
		if (left_child) {
			left_child->traverse(pre, process, post);
		}
		process(*this);
		if (right_child) {
			right_child->traverse(pre, process, post);
		}
		post(*this);
	}

	std::string to_newick()
	{
		auto ret = std::string();

		auto pre = [&ret](const tree_node &self) {
			if (self.is_branch()) {
				ret += "(";
			}
		};
		auto process = [&ret](const tree_node &self) {
			if (self.is_leaf()) {
				ret += std::to_string(self.get_index());
			} else {
				ret += ",";
			}
		};
		auto post = [&ret](const tree_node &self) {
			if (self.is_branch()) {
				ret += ")";
			}
			if (self.up_time != 0.0) {
				ret += ":";
				ret += std::to_string(self.up_time);
			}
		};

		traverse(pre, process, post);

		ret += ";";
		return ret;
	}
};

void img_model::parse_param(std::string key, std::string value)
{
	if (key == "img_theta") {
		this->img_theta = std::stoul(value);
		return;
	}
	if (key == "img_rho") {
		this->img_rho = std::stoul(value);
		return;
	}
	evo_model::parse_param(key, value);
}

std::string img_model::parameters() const
{
	auto str = std::stringstream();

	str << "pangenomesim " << VERSION << "\n\n";
	str << "full options:\n";
	str << "--param gene_length=" << loci_length << "\n";
	str << "--param num_loci=" << num_loci << "\n";
	str << "--param num_genomes=" << num_genomes << "\n";
	str << "--param img_theta=" << img_theta << "\n";
	str << "--param img_rho=" << img_rho << "\n";
	str << "--param seed=" << seed << "\n";

	return str.str();
}

void img_model::simulate()
{
	// generate coalescent
	auto n = num_genomes;

	// Use a pool for allocating the tree nodes. Nodes 0 to n are leafes, the
	// rest are internal nodes, with the last being the root.
	auto pool = std::vector<tree_node>(2 * n - 1);
	auto &root = *(pool.end() - 1);

	for (size_t i = 0; i < n; i++) {
		pool[i] = tree_node::leaf(i);
	}

	auto indirect = std::vector<tree_node *>();
	indirect.reserve(2 * n - 1);
	for (auto &tn : pool) {
		indirect.push_back(&tn);
	}

	auto rand_int = [](size_t lower, size_t upper) {
		auto rng_help = std::uniform_int_distribution<size_t>(lower, upper - 1);
		return rng_help(RNG);
	};

	// simulate topology
	for (size_t i = 0; i < n - 1; i++) {
		auto p = n + i;
		auto c = rand_int(0, n - i);
		indirect.at(p)->set_left(indirect[c]); // also sets [c].parent
		indirect[c] = indirect[n - i - 1];

		auto d = rand_int(0, n - i - 1);
		indirect[p]->set_right(indirect[d]);
		indirect[d] = indirect[p];
	}

	// add times
	auto t = 0.0;
	auto rand_exp = [](double arg) {
		auto rng_dist = std::exponential_distribution<double>(arg);
		return rng_dist(RNG);
	};

	// simulate absolute times
	auto sample_size = n;
	for (size_t i = 0; i < n - 1; i++, sample_size--) {
		auto ss1 = sample_size * (sample_size - 1) / 2; // N_e ??
		t += rand_exp(ss1);
		pool[n + i].set_abs_time(t);
	}

	// compute relative times
	root.traverse([](tree_node &self) {
		if (self.has_parent()) {
			auto branch_length =
				self.get_parent().get_abs_time() - self.get_abs_time();
			self.set_time(branch_length);
		}
	});

	std::cout << indirect[0]->to_newick() << std::endl;

	// create core sequences
	// generate pan genome and create sequences
}

// STUB
std::vector<locus> img_model::get_reference()
{
	return std::vector<locus>();
}

// STUB
std::vector<locus> img_model::get_core()
{
	return std::vector<locus>();
}

// STUB
std::vector<locus> img_model::get_accessory()
{
	return std::vector<locus>();
}

// STUB
std::vector<locus> img_model::get_genome(size_t)
{
	return std::vector<locus>();
}

// STUB
std::vector<locus> img_model::get_locus(size_t)
{
	return std::vector<locus>();
}
<|endoftext|>


<commit_before>#include "alvision.h"

#include "opencv/Matrix.h"
#include "ffmpeg/ffmpeg.h"
#include "ffmpeg/packet.h"
#include "ffmpeg/stream.h"

#include "opencv/base.h"

#include "opencv/UMatrix.h"

#include "opencv/HighGUI.h"
#include "opencv/Constants.h"
#include "opencv/Cuda.h"
#include "opencv/flann.h"
#include "opencv/cvtest.h"

#include "opencv/Vec.h"

#include "opencv/ml.h"
#include "opencv/superres.h"

#include "opencv/Affine3.h"

#include "opencv/calib3d.h"

#include "opencv/MatExpr.h"

#include "opencv/core.h"

#include "opencv/Matx.h"

#include "opencv/Mat_.h"

#include "opencv/persistence.h"

#include "opencv/MatND.h"
#include "opencv/SparseMat.h"

#include "opencv/imgcodecs.h"
#include "opencv/imgproc.h"

#include "opencv/stitching.h"

#include "opencv/shape.h"
#include "opencv/video.h"

#include "opencv/videoio.h"

#include "opencv/IOArray.h"

#include "opencv/TrackedPtr.h"
#include "opencv/TrackedElement.h"

#include "opencv/core/Algorithm.h"
#include "opencv/features2d/Feature2D.h"
#include "opencv/features2d/SimpleBlobDetector.h"

#include "opencv/types.h"

extern "C"{
void
init(Handle<Object> target) {
	assert(false);
	auto overload = std::make_shared<overload_resolution>();

	overload->add_type_alias("InputArray", "IOArray");
	overload->add_type_alias("InputArrayOfArrays", "Array<InputArray>");
	overload->add_type_alias("OutputArray", "IOArray");
	overload->add_type_alias("OutputArrayOfArrays", "Array<InputArray>");
	overload->add_type_alias("InputOutputArray", "IOArray");
	overload->add_type_alias("InputOutputArrayOfArrays", "Array<InputArray>");
	overload->add_type_alias("int", "Number");
	overload->add_type_alias("double", "Number");
	overload->add_type_alias("float", "Number");
	overload->add_type_alias("uint64_t", "Number");
	overload->add_type_alias("uint", "Number");
	overload->add_type_alias("unsigned", "Number");
	overload->add_type_alias("bool", "Boolean");
	overload->add_type_alias("size_t", "int");
	overload->add_type_alias("MatrixType", "int");

	base::Init(target, overload);

	IOArray::Init(target, overload);
	types::Init(target, overload);

	Matrix::Init(target,overload);
	UMatrix::Init(target, overload);
	TrackedPtr<Matrix>::Init(target, "TrackedPtr_Mat", overload);
	//TrackedElement<Matrix>::Init(target, overload);

	alvision::ffmpeg::Init(target,overload);
	alvision::packet::Init(target,overload);
	alvision::stream::Init(target,overload);
	Constants::Init(target,overload);

	Cuda::Init(target,overload);

	flann::Init(target,overload);

	ml::Init(target, overload);
	superres::Init(target, overload);

	MatExpr::Init(target, overload);

	MatxInit::Init(target, overload);
	VecInit::Init(target, overload);

	//cv::Vec3d::mat_type

	Mat_Init::Init(target, overload);

	core::Init(target, overload);

	persistence::Init(target, overload);

	MatND::Init(target, overload);
	SparseMat::Init(target, overload);

	Feature2D::Init(target, overload);
	SimpleBlobDetector::Init(target, overload);

	imgcodecs::Init(target, overload);
	imgproc::Init(target, overload);

	stitching::Init(target, overload);

	shape::Init(target,overload);
	video::Init(target,overload);

	videoio::Init(target, overload);

	AffineInit::Init(target, overload);

	calib3d::Init(target, overload);
	cv_test::Init(target, overload);
	highgui::Init(target, overload);

	target->Set(Nan::New("version").ToLocalChecked(), Nan::New("1.0.0").ToLocalChecked());

	//validate type/overload registrations
	assert(overload->validate_type_registrations());
};
}

NODE_MODULE(alvision, init)
<commit_msg>fix object initialization order<commit_after>#include "alvision.h"

#include "opencv/Matrix.h"
#include "ffmpeg/ffmpeg.h"
#include "ffmpeg/packet.h"
#include "ffmpeg/stream.h"

#include "opencv/base.h"

#include "opencv/UMatrix.h"

#include "opencv/HighGUI.h"
#include "opencv/Constants.h"
#include "opencv/Cuda.h"
#include "opencv/flann.h"
#include "opencv/cvtest.h"

#include "opencv/Vec.h"

#include "opencv/ml.h"
#include "opencv/superres.h"

#include "opencv/Affine3.h"

#include "opencv/calib3d.h"

#include "opencv/MatExpr.h"

#include "opencv/core.h"

#include "opencv/Matx.h"

#include "opencv/Mat_.h"

#include "opencv/persistence.h"

#include "opencv/MatND.h"
#include "opencv/SparseMat.h"

#include "opencv/imgcodecs.h"
#include "opencv/imgproc.h"

#include "opencv/stitching.h"

#include "opencv/shape.h"
#include "opencv/video.h"

#include "opencv/videoio.h"

#include "opencv/IOArray.h"

#include "opencv/TrackedPtr.h"
#include "opencv/TrackedElement.h"

#include "opencv/core/Algorithm.h"
#include "opencv/features2d/Feature2D.h"
#include "opencv/features2d/SimpleBlobDetector.h"

#include "opencv/types.h"

extern "C"{
void
init(Handle<Object> target) {
	assert(false);
	auto overload = std::make_shared<overload_resolution>();

	overload->add_type_alias("InputArray", "IOArray");
	overload->add_type_alias("InputArrayOfArrays", "Array<InputArray>");
	overload->add_type_alias("OutputArray", "IOArray");
	overload->add_type_alias("OutputArrayOfArrays", "Array<InputArray>");
	overload->add_type_alias("InputOutputArray", "IOArray");
	overload->add_type_alias("InputOutputArrayOfArrays", "Array<InputArray>");
	overload->add_type_alias("int", "Number");
	overload->add_type_alias("double", "Number");
	overload->add_type_alias("float", "Number");
	overload->add_type_alias("uint64_t", "Number");
	overload->add_type_alias("uint", "Number");
	overload->add_type_alias("unsigned", "Number");
	overload->add_type_alias("bool", "Boolean");
	overload->add_type_alias("size_t", "int");
	overload->add_type_alias("MatrixType", "int");

	base::Init(target, overload);

	IOArray::Init(target, overload);

	Matrix::Init(target,overload);
	UMatrix::Init(target, overload);
	TrackedPtr<Matrix>::Init(target, "TrackedPtr_Mat", overload);
	//TrackedElement<Matrix>::Init(target, overload);

	alvision::ffmpeg::Init(target,overload);
	alvision::packet::Init(target,overload);
	alvision::stream::Init(target,overload);
	Constants::Init(target,overload);

	Cuda::Init(target,overload);

	flann::Init(target,overload);

	ml::Init(target, overload);
	superres::Init(target, overload);

	MatExpr::Init(target, overload);

	MatxInit::Init(target, overload);
	VecInit::Init(target, overload);
	types::Init(target, overload);
	//cv::Vec3d::mat_type

	Mat_Init::Init(target, overload);

	core::Init(target, overload);

	persistence::Init(target, overload);

	MatND::Init(target, overload);
	SparseMat::Init(target, overload);

	Feature2D::Init(target, overload);
	SimpleBlobDetector::Init(target, overload);

	imgcodecs::Init(target, overload);
	imgproc::Init(target, overload);

	stitching::Init(target, overload);

	shape::Init(target,overload);
	video::Init(target,overload);

	videoio::Init(target, overload);

	AffineInit::Init(target, overload);

	calib3d::Init(target, overload);
	cv_test::Init(target, overload);
	highgui::Init(target, overload);

	target->Set(Nan::New("version").ToLocalChecked(), Nan::New("1.0.0").ToLocalChecked());

	//validate type/overload registrations
	assert(overload->validate_type_registrations());
};
}

NODE_MODULE(alvision, init)
<|endoftext|>


<commit_before>#include "testsettings.hpp"
#ifdef TEST_COLUMN_BASIC

#include <realm/column_basic.hpp>

#include "test.hpp"

using namespace realm;

// Test independence and thread-safety
// -----------------------------------
//
// All tests must be thread safe and independent of each other. This
// is required because it allows for both shuffling of the execution
// order and for parallelized testing.
//
// In particular, avoid using std::rand() since it is not guaranteed
// to be thread safe. Instead use the API offered in
// `test/util/random.hpp`.
//
// All files created in tests must use the TEST_PATH macro (or one of
// its friends) to obtain a suitable file system path. See
// `test/util/test_path.hpp`.
//
//
// Debugging and the ONLY() macro
// ------------------------------
//
// A simple way of disabling all tests except one called `Foo`, is to
// replace TEST(Foo) with ONLY(Foo) and then recompile and rerun the
// test suite. Note that you can also use filtering by setting the
// environment varible `UNITTEST_FILTER`. See `README.md` for more on
// this.
//
// Another way to debug a particular test, is to copy that test into
// `experiments/testcase.cpp` and then run `sh build.sh
// check-testcase` (or one of its friends) from the command line.

TEST(ColumnBasic_LowerUpperBound)
{
    // Create column with sorted members
    ref_type ref = BasicColumn<int>::create(Allocator::get_default());
    BasicColumn<int> col(Allocator::get_default(), ref);

    col.add(5);
    for (int i = 5; i < 100; i += 5)
        col.add(i);

    // before first entry
    CHECK_EQUAL(0, col.lower_bound(0));
    CHECK_EQUAL(0, col.upper_bound(0));

    // first entry (duplicate)
    CHECK_EQUAL(0, col.lower_bound(5));
    CHECK_EQUAL(2, col.upper_bound(5));

    // middle entry
    CHECK_EQUAL(10, col.lower_bound(50));
    CHECK_EQUAL(11, col.upper_bound(50));

    // non-existent middle entry
    CHECK_EQUAL(11, col.lower_bound(52));
    CHECK_EQUAL(11, col.upper_bound(52));

    // last entry
    CHECK_EQUAL(19, col.lower_bound(95));
    CHECK_EQUAL(20, col.upper_bound(95));

    // beyond last entry
    CHECK_EQUAL(20, col.lower_bound(96));
    CHECK_EQUAL(20, col.upper_bound(96));

    // Clean up
    col.destroy();
}

TEST(ColumnBasic_NullOperations)
{
    ref_type ref = BasicColumn<int>::create(Allocator::get_default());
    BasicColumn<int> c(Allocator::get_default(), ref);

    CHECK(!c.is_nullable());
    CHECK(!c.is_null(0));
    CHECK_LOGIC_ERROR(c.set_null(0), LogicError::column_not_nullable);

    c.destroy();
}

#endif // TEST_COLUMN_BASIC
<commit_msg>Moved column error handling test to separate testcase<commit_after>#include "testsettings.hpp"
#ifdef TEST_COLUMN_BASIC

#include <realm/column_basic.hpp>

#include "test.hpp"

using namespace realm;

// Test independence and thread-safety
// -----------------------------------
//
// All tests must be thread safe and independent of each other. This
// is required because it allows for both shuffling of the execution
// order and for parallelized testing.
//
// In particular, avoid using std::rand() since it is not guaranteed
// to be thread safe. Instead use the API offered in
// `test/util/random.hpp`.
//
// All files created in tests must use the TEST_PATH macro (or one of
// its friends) to obtain a suitable file system path. See
// `test/util/test_path.hpp`.
//
//
// Debugging and the ONLY() macro
// ------------------------------
//
// A simple way of disabling all tests except one called `Foo`, is to
// replace TEST(Foo) with ONLY(Foo) and then recompile and rerun the
// test suite. Note that you can also use filtering by setting the
// environment varible `UNITTEST_FILTER`. See `README.md` for more on
// this.
//
// Another way to debug a particular test, is to copy that test into
// `experiments/testcase.cpp` and then run `sh build.sh
// check-testcase` (or one of its friends) from the command line.

TEST(ColumnBasic_LowerUpperBound)
{
    // Create column with sorted members
    ref_type ref = BasicColumn<int>::create(Allocator::get_default());
    BasicColumn<int> col(Allocator::get_default(), ref);

    col.add(5);
    for (int i = 5; i < 100; i += 5)
        col.add(i);

    // before first entry
    CHECK_EQUAL(0, col.lower_bound(0));
    CHECK_EQUAL(0, col.upper_bound(0));

    // first entry (duplicate)
    CHECK_EQUAL(0, col.lower_bound(5));
    CHECK_EQUAL(2, col.upper_bound(5));

    // middle entry
    CHECK_EQUAL(10, col.lower_bound(50));
    CHECK_EQUAL(11, col.upper_bound(50));

    // non-existent middle entry
    CHECK_EQUAL(11, col.lower_bound(52));
    CHECK_EQUAL(11, col.upper_bound(52));

    // last entry
    CHECK_EQUAL(19, col.lower_bound(95));
    CHECK_EQUAL(20, col.upper_bound(95));

    // beyond last entry
    CHECK_EQUAL(20, col.lower_bound(96));
    CHECK_EQUAL(20, col.upper_bound(96));

    // Clean up
    col.destroy();
}

TEST(ColumnBasic_NullOperations)
{
    ref_type ref = BasicColumn<int>::create(Allocator::get_default());
    BasicColumn<int> c(Allocator::get_default(), ref);

    CHECK(!c.is_nullable());
    CHECK(!c.is_null(0));

    c.destroy();
}

TEST(ColumnBasic_NullErrorHandling)
{
    ref_type ref = BasicColumn<int>::create(Allocator::get_default());
    BasicColumn<int> c(Allocator::get_default(), ref);

    CHECK_LOGIC_ERROR(c.set_null(0), LogicError::column_not_nullable);

    c.destroy();
}

#endif // TEST_COLUMN_BASIC
<|endoftext|>


<commit_before>#include "commodity_producer.h"

#include "cyc_limits.h"
#include "error.h"

namespace cyclus {
namespace supply_demand {

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
CommodityInformation::CommodityInformation()
  : capacity(0),
    cost(cyclus::kModifierLimit) { }

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
CommodityInformation::CommodityInformation(double a_capacity,
                                           double a_cost)
  : capacity(a_capacity),
    cost(a_cost) { }

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
CommodityProducer::CommodityProducer()
  : default_capacity_(0.0),
    default_cost_(cyclus::kModifierLimit) { }

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
CommodityProducer::~CommodityProducer() {}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
std::set<Commodity, CommodityCompare> CommodityProducer::ProducedCommodities() {
  std::set<Commodity, CommodityCompare> commodities;
  std::map<Commodity, CommodityInformation, CommodityCompare>::iterator it;
  for (it = produced_commodities_.begin();
       it != produced_commodities_.end();
       it++) {
    commodities.insert(it->first);
  }
  return commodities;
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
bool CommodityProducer::ProducesCommodity(const Commodity& commodity) {
  return (produced_commodities_.find(commodity) !=
          produced_commodities_.end());
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
double CommodityProducer::ProductionCapacity(const Commodity& commodity) {
  ThrowErrorIfCommodityNotProduced(commodity);
  return produced_commodities_[commodity].capacity;
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
double CommodityProducer::ProductionCost(const Commodity& commodity) {
  ThrowErrorIfCommodityNotProduced(commodity);
  return produced_commodities_[commodity].cost;
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void CommodityProducer::AddCommodity(const Commodity& commodity) {
  CommodityInformation info(default_capacity_, default_cost_);
  AddCommodityWithInformation(commodity, info);
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void CommodityProducer::SetCapacity(const Commodity& commodity,
                                    double capacity) {
  ThrowErrorIfCommodityNotProduced(commodity);
  produced_commodities_[commodity].capacity = capacity;
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void CommodityProducer::SetCost(const Commodity& commodity,
                                double cost) {
  ThrowErrorIfCommodityNotProduced(commodity);
  produced_commodities_[commodity].cost = cost;
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void CommodityProducer::AddCommodityWithInformation(const Commodity& commodity,
                                                    const CommodityInformation& info) {
  if (!ProducesCommodity(commodity)) {
    produced_commodities_.insert(std::make_pair(commodity, info));
  }
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void CommodityProducer::CopyProducedCommoditiesFrom(CommodityProducer* source) {
  std::set<Commodity, CommodityCompare> commodities =
    source->ProducedCommodities();
  std::set<Commodity, CommodityCompare>::iterator it;
  for (it = commodities.begin(); it != commodities.end(); it++) {
    AddCommodity(*it);
    SetCapacity(*it, source->ProductionCapacity(*it));
    SetCost(*it, source->ProductionCost(*it));
  }
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void CommodityProducer::ThrowErrorIfCommodityNotProduced(
  const Commodity& commodity) {
  if (!ProducesCommodity(commodity)) {
    throw KeyError("Producer does not produce "
                   + commodity.name());
  }
}
} // namespace supply_demand
} // namespace cyclus
<commit_msg>removed extraneous cyclus namespace from commodity_producer impl<commit_after>#include "commodity_producer.h"

#include "cyc_limits.h"
#include "error.h"

namespace cyclus {
namespace supply_demand {

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
CommodityInformation::CommodityInformation()
  : capacity(0),
    cost(kModifierLimit) { }

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
CommodityInformation::CommodityInformation(double a_capacity,
                                           double a_cost)
  : capacity(a_capacity),
    cost(a_cost) { }

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
CommodityProducer::CommodityProducer()
  : default_capacity_(0.0),
    default_cost_(kModifierLimit) { }

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
CommodityProducer::~CommodityProducer() {}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
std::set<Commodity, CommodityCompare> CommodityProducer::ProducedCommodities() {
  std::set<Commodity, CommodityCompare> commodities;
  std::map<Commodity, CommodityInformation, CommodityCompare>::iterator it;
  for (it = produced_commodities_.begin();
       it != produced_commodities_.end();
       it++) {
    commodities.insert(it->first);
  }
  return commodities;
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
bool CommodityProducer::ProducesCommodity(const Commodity& commodity) {
  return (produced_commodities_.find(commodity) !=
          produced_commodities_.end());
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
double CommodityProducer::ProductionCapacity(const Commodity& commodity) {
  ThrowErrorIfCommodityNotProduced(commodity);
  return produced_commodities_[commodity].capacity;
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
double CommodityProducer::ProductionCost(const Commodity& commodity) {
  ThrowErrorIfCommodityNotProduced(commodity);
  return produced_commodities_[commodity].cost;
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void CommodityProducer::AddCommodity(const Commodity& commodity) {
  CommodityInformation info(default_capacity_, default_cost_);
  AddCommodityWithInformation(commodity, info);
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void CommodityProducer::SetCapacity(const Commodity& commodity,
                                    double capacity) {
  ThrowErrorIfCommodityNotProduced(commodity);
  produced_commodities_[commodity].capacity = capacity;
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void CommodityProducer::SetCost(const Commodity& commodity,
                                double cost) {
  ThrowErrorIfCommodityNotProduced(commodity);
  produced_commodities_[commodity].cost = cost;
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void CommodityProducer::AddCommodityWithInformation(const Commodity& commodity,
                                                    const CommodityInformation& info) {
  if (!ProducesCommodity(commodity)) {
    produced_commodities_.insert(std::make_pair(commodity, info));
  }
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void CommodityProducer::CopyProducedCommoditiesFrom(CommodityProducer* source) {
  std::set<Commodity, CommodityCompare> commodities =
    source->ProducedCommodities();
  std::set<Commodity, CommodityCompare>::iterator it;
  for (it = commodities.begin(); it != commodities.end(); it++) {
    AddCommodity(*it);
    SetCapacity(*it, source->ProductionCapacity(*it));
    SetCost(*it, source->ProductionCost(*it));
  }
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void CommodityProducer::ThrowErrorIfCommodityNotProduced(
  const Commodity& commodity) {
  if (!ProducesCommodity(commodity)) {
    throw KeyError("Producer does not produce "
                   + commodity.name());
  }
}
} // namespace supply_demand
} // namespace cyclus
<|endoftext|>


<commit_before>/* bzflag
 * Copyright (c) 1993 - 2005 Tim Riker
 *
 * This package is free software;  you can redistribute it and/or
 * modify it under the terms of the license found in the file
 * named COPYING that should have accompanied this file.
 *
 * THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
 * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
 * WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE.
 */

/* interface header */
#include "TimeKeeper.h"

/* system implementation headers */
#include <time.h>
#include <string>
#ifdef HAVE_UNISTD_H
#  include <unistd.h>
#endif
#ifdef __BEOS__
#  include <OS.h>
#endif
#if !defined(_WIN32)
#  include <sys/time.h>
#  include <sys/types.h>
static struct timeval	lastTime = { 0, 0 };
#else /* !defined(_WIN32) */
#  include <mmsystem.h>
static unsigned int	lastTime = 0;
static LARGE_INTEGER	qpcLastTime;
static double		qpcFrequency = 0.0;
#endif /* !defined(_WIN32) */

/* common implementation headers */
#include "TextUtils.h"

TimeKeeper TimeKeeper::currentTime;
TimeKeeper TimeKeeper::tickTime;
TimeKeeper TimeKeeper::sunExplodeTime;
TimeKeeper TimeKeeper::sunGenesisTime;
TimeKeeper TimeKeeper::nullTime;
TimeKeeper TimeKeeper::startTime = TimeKeeper::getCurrent();

const TimeKeeper&	TimeKeeper::getCurrent(void)
{
  // if not first call then update current time, else use default initial time
#if !defined(_WIN32)
  if (lastTime.tv_sec != 0) {
    struct timeval now;
    gettimeofday(&now, NULL);
    currentTime += float(now.tv_sec - lastTime.tv_sec) +
		1.0e-6f * float(now.tv_usec - lastTime.tv_usec);
    lastTime = now;
  }
  else {
    gettimeofday(&lastTime, NULL);
  }
#else /* !defined(_WIN32) */
  if (qpcFrequency != 0.0) {
    LARGE_INTEGER now;
    QueryPerformanceCounter(&now);
    currentTime += (float)(qpcFrequency *
			(double)(now.QuadPart - qpcLastTime.QuadPart));
    qpcLastTime = now;
  }
  else if (lastTime != 0) {
    unsigned int now = (unsigned int)timeGetTime();
    unsigned int diff;
    if (now <= lastTime) {
      diff = 0;
    } else {
      diff = now - lastTime;
    }
    currentTime += 1.0e-3f * (float)diff;
    lastTime = now;
  }
  else {
    LARGE_INTEGER freq;
    if (QueryPerformanceFrequency(&freq)) {
      qpcFrequency = 1.0 / (double)freq.QuadPart;
      QueryPerformanceCounter(&qpcLastTime);
    }
    else {
      DEBUG1("QueryPerformanceFrequency failed with error %s\n", IntToString(GetLastError).c_str());
      lastTime = (unsigned int)timeGetTime();
    }
  }
#endif /* !defined(_WIN32) */
  return currentTime;
}

const TimeKeeper&	TimeKeeper::getStartTime(void) // const
{
  return startTime;
}

const TimeKeeper&	TimeKeeper::getTick(void) // const
{
  return tickTime;
}

void			TimeKeeper::setTick(void)
{
  tickTime = getCurrent();
}

const TimeKeeper& TimeKeeper::getSunExplodeTime(void)
{
  sunExplodeTime.seconds = 10000.0 * 365 * 24 * 60 * 60;
  return sunExplodeTime;
}

const TimeKeeper& TimeKeeper::getSunGenesisTime(void)
{
  sunGenesisTime.seconds = -10000.0 * 365 * 24 * 60 * 60;
  return sunGenesisTime;
}

const TimeKeeper& TimeKeeper::getNullTime(void)
{
  nullTime.seconds = 0;
  return nullTime;
}

const char *TimeKeeper::timestamp(void) // const
{
  static char buffer[256]; // static, so that it doesn't vanish
  time_t tnow = time(0);
  struct tm *now = localtime(&tnow);
  now->tm_year += 1900;
  ++now->tm_mon;

  strncpy (buffer, TextUtils::format("%04d-%02d-%02d %02d:%02d:%02d",
		     now->tm_year, now->tm_mon, now->tm_mday,
		     now->tm_hour, now->tm_min, now->tm_sec).c_str(), 256);
  buffer[255] = '\0'; // safety

  return buffer;
}

// function for converting a float time (e.g. difference of two TimeKeepers)
// into an array of ints
const void TimeKeeper::convertTime(float raw, int convertedTimes[])
{
  int day, hour, min, sec, remainder;
  static const int secondsInDay = 86400;

  sec = (int)raw;
  day = sec / secondsInDay;
  remainder = sec - (day * secondsInDay);
  hour = remainder / 3600;
  remainder = sec - ((hour * 3600) + (day * secondsInDay));
  min = remainder / 60;
  remainder = sec - ((hour * 3600) + (day * secondsInDay) + (min * 60));
  sec = remainder;

  convertedTimes[0] = day;
  convertedTimes[1] = hour;
  convertedTimes[2] = min;
  convertedTimes[3] = sec;

  return;
}

// function for printing an array of ints representing a time
// as a human-readable string
const std::string TimeKeeper::printTime(int timeValue[])
{
  std::string valueNames;
  char temp[20];

  if (timeValue[0] > 0) {
    snprintf(temp, 20, "%i day%s", timeValue[0], timeValue[0] == 1 ? "" : "s");
    valueNames.append(temp);
  }
  if (timeValue[1] > 0) {
    if (timeValue[0] > 0) {
      valueNames.append(", ");
    }
    snprintf(temp, 20, "%i hour%s", timeValue[1], timeValue[1] == 1 ? "" : "s");
    valueNames.append(temp);
  }
  if (timeValue[2] > 0) {
    if ((timeValue[1] > 0) || (timeValue[0] > 0)) {
      valueNames.append(", ");
    }
    snprintf(temp, 20, "%i min%s", timeValue[2], timeValue[2] == 1 ? "" : "s");
    valueNames.append(temp);
  }
  if (timeValue[3] > 0) {
    if ((timeValue[2] > 0) || (timeValue[1] > 0) || (timeValue[0] > 0)) {
      valueNames.append(", ");
    }
    snprintf(temp, 20, "%i sec%s", timeValue[3], timeValue[3] == 1 ? "" : "s");
    valueNames.append(temp);
  }

  return valueNames;
}

// function for printing a float time difference as a human-readable string
const std::string TimeKeeper::printTime(float diff)
{
  int temp[4];
  convertTime(diff, temp);
  return printTime(temp);
}

void TimeKeeper::sleep(float seconds)
{
  if (seconds <= 0.0f) {
    return;
  }

#ifdef HAVE_USLEEP
  usleep((unsigned int)(1.0e6 * seconds));
  return;
#endif
#if defined(HAVE_SLEEP) && !defined(__APPLE__)
  // equivalent to _sleep() on win32 (not sleep(3))
  Sleep((DWORD)(seconds * 1000));
  return;
#endif
#ifdef HAVE_SNOOZE
  snooze((bigtime_t)(1.0e6 * seconds));
  return;
#endif
#ifdef HAVE_SELECT
  struct timeval tv;
  tv.tv_sec = (long)seconds;
  tv.tv_usec = (long)(1.0e6 * (seconds - tv.tv_sec));
  select(0, NULL, NULL, NULL, &tv);
  return;
#endif
#ifdef HAVE_WAITFORSINGLEOBJECT
  HANDLE dummyEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
  WaitForSingleObject(dummyEvent, (DWORD)(1000.0f * seconds));
  CloseHandle(dummyEvent);
  return;
#endif

  // fall-back case is fugly manual timekeeping
  TimeKeeper now = TimeKeeper::getCurrent();
  while ((TimeKeeper::getCurrent() - now) < seconds) {
    continue;
  }
  return;
}

// Local Variables: ***
// mode: C++ ***
// tab-width: 8 ***
// c-basic-offset: 2 ***
// indent-tabs-mode: t ***
// End: ***
// ex: shiftwidth=2 tabstop=8
<commit_msg>add a sanity check and make sure we're using the best possible timer resolution for timeGetTime()<commit_after>/* bzflag
 * Copyright (c) 1993 - 2005 Tim Riker
 *
 * This package is free software;  you can redistribute it and/or
 * modify it under the terms of the license found in the file
 * named COPYING that should have accompanied this file.
 *
 * THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
 * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
 * WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE.
 */

/* interface header */
#include "TimeKeeper.h"

/* system implementation headers */
#include <time.h>
#include <string>
#ifdef HAVE_UNISTD_H
#  include <unistd.h>
#endif
#ifdef __BEOS__
#  include <OS.h>
#endif
#if !defined(_WIN32)
#  include <sys/time.h>
#  include <sys/types.h>
static struct timeval	lastTime = { 0, 0 };
#else /* !defined(_WIN32) */
#  include <mmsystem.h>
static unsigned int	lastTime = 0;
static LARGE_INTEGER	qpcLastTime;
static double		qpcFrequency = 0.0;
#endif /* !defined(_WIN32) */

/* common implementation headers */
#include "TextUtils.h"

TimeKeeper TimeKeeper::currentTime;
TimeKeeper TimeKeeper::tickTime;
TimeKeeper TimeKeeper::sunExplodeTime;
TimeKeeper TimeKeeper::sunGenesisTime;
TimeKeeper TimeKeeper::nullTime;
TimeKeeper TimeKeeper::startTime = TimeKeeper::getCurrent();

const TimeKeeper&	TimeKeeper::getCurrent(void)
{
  // if not first call then update current time, else use default initial time
#if !defined(_WIN32)
  if (lastTime.tv_sec != 0) {
    struct timeval now;
    gettimeofday(&now, NULL);
    currentTime += float(now.tv_sec - lastTime.tv_sec) +
		1.0e-6f * float(now.tv_usec - lastTime.tv_usec);
    lastTime = now;
  }
  else {
    gettimeofday(&lastTime, NULL);
  }
#else /* !defined(_WIN32) */
  if (qpcFrequency != 0.0) {
    LARGE_INTEGER now;
    QueryPerformanceCounter(&now);
    currentTime += (float)(qpcFrequency *
			(double)(now.QuadPart - qpcLastTime.QuadPart));
    qpcLastTime = now;
  }
  else if (lastTime != 0) {
    unsigned int now = (unsigned int)timeGetTime();
    unsigned int diff;
    if (now <= lastTime) {
      // eh, how'd we go back in time?
      diff = 0;
    } else {
      diff = now - lastTime;
    }
    currentTime += 1.0e-3f * (float)diff;
    lastTime = now;
  }
  else {
    static bool sane = true;

    // should only get into here once on app start
    if (!sane) {
      DEBUG1("Sanity check failure in TimeKeeper::getCurrent()\n");
    }
    sane = false;

    LARGE_INTEGER freq;
    if (QueryPerformanceFrequency(&freq)) {
      qpcFrequency = 1.0 / (double)freq.QuadPart;
      QueryPerformanceCounter(&qpcLastTime);
    }
    else {
      DEBUG1("QueryPerformanceFrequency failed with error %s\n", IntToString(GetLastError).c_str());

      // make sure we're at our best timer resolution possible
      timeBeginPeriod(1);

      lastTime = (unsigned int)timeGetTime();
    }
  }
#endif /* !defined(_WIN32) */
  return currentTime;
}

const TimeKeeper&	TimeKeeper::getStartTime(void) // const
{
  return startTime;
}

const TimeKeeper&	TimeKeeper::getTick(void) // const
{
  return tickTime;
}

void			TimeKeeper::setTick(void)
{
  tickTime = getCurrent();
}

const TimeKeeper& TimeKeeper::getSunExplodeTime(void)
{
  sunExplodeTime.seconds = 10000.0 * 365 * 24 * 60 * 60;
  return sunExplodeTime;
}

const TimeKeeper& TimeKeeper::getSunGenesisTime(void)
{
  sunGenesisTime.seconds = -10000.0 * 365 * 24 * 60 * 60;
  return sunGenesisTime;
}

const TimeKeeper& TimeKeeper::getNullTime(void)
{
  nullTime.seconds = 0;
  return nullTime;
}

const char *TimeKeeper::timestamp(void) // const
{
  static char buffer[256]; // static, so that it doesn't vanish
  time_t tnow = time(0);
  struct tm *now = localtime(&tnow);
  now->tm_year += 1900;
  ++now->tm_mon;

  strncpy (buffer, TextUtils::format("%04d-%02d-%02d %02d:%02d:%02d",
		     now->tm_year, now->tm_mon, now->tm_mday,
		     now->tm_hour, now->tm_min, now->tm_sec).c_str(), 256);
  buffer[255] = '\0'; // safety

  return buffer;
}

// function for converting a float time (e.g. difference of two TimeKeepers)
// into an array of ints
const void TimeKeeper::convertTime(float raw, int convertedTimes[])
{
  int day, hour, min, sec, remainder;
  static const int secondsInDay = 86400;

  sec = (int)raw;
  day = sec / secondsInDay;
  remainder = sec - (day * secondsInDay);
  hour = remainder / 3600;
  remainder = sec - ((hour * 3600) + (day * secondsInDay));
  min = remainder / 60;
  remainder = sec - ((hour * 3600) + (day * secondsInDay) + (min * 60));
  sec = remainder;

  convertedTimes[0] = day;
  convertedTimes[1] = hour;
  convertedTimes[2] = min;
  convertedTimes[3] = sec;

  return;
}

// function for printing an array of ints representing a time
// as a human-readable string
const std::string TimeKeeper::printTime(int timeValue[])
{
  std::string valueNames;
  char temp[20];

  if (timeValue[0] > 0) {
    snprintf(temp, 20, "%i day%s", timeValue[0], timeValue[0] == 1 ? "" : "s");
    valueNames.append(temp);
  }
  if (timeValue[1] > 0) {
    if (timeValue[0] > 0) {
      valueNames.append(", ");
    }
    snprintf(temp, 20, "%i hour%s", timeValue[1], timeValue[1] == 1 ? "" : "s");
    valueNames.append(temp);
  }
  if (timeValue[2] > 0) {
    if ((timeValue[1] > 0) || (timeValue[0] > 0)) {
      valueNames.append(", ");
    }
    snprintf(temp, 20, "%i min%s", timeValue[2], timeValue[2] == 1 ? "" : "s");
    valueNames.append(temp);
  }
  if (timeValue[3] > 0) {
    if ((timeValue[2] > 0) || (timeValue[1] > 0) || (timeValue[0] > 0)) {
      valueNames.append(", ");
    }
    snprintf(temp, 20, "%i sec%s", timeValue[3], timeValue[3] == 1 ? "" : "s");
    valueNames.append(temp);
  }

  return valueNames;
}

// function for printing a float time difference as a human-readable string
const std::string TimeKeeper::printTime(float diff)
{
  int temp[4];
  convertTime(diff, temp);
  return printTime(temp);
}

void TimeKeeper::sleep(float seconds)
{
  if (seconds <= 0.0f) {
    return;
  }

#ifdef HAVE_USLEEP
  usleep((unsigned int)(1.0e6 * seconds));
  return;
#endif
#if defined(HAVE_SLEEP) && !defined(__APPLE__)
  // equivalent to _sleep() on win32 (not sleep(3))
  Sleep((DWORD)(seconds * 1000));
  return;
#endif
#ifdef HAVE_SNOOZE
  snooze((bigtime_t)(1.0e6 * seconds));
  return;
#endif
#ifdef HAVE_SELECT
  struct timeval tv;
  tv.tv_sec = (long)seconds;
  tv.tv_usec = (long)(1.0e6 * (seconds - tv.tv_sec));
  select(0, NULL, NULL, NULL, &tv);
  return;
#endif
#ifdef HAVE_WAITFORSINGLEOBJECT
  HANDLE dummyEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
  WaitForSingleObject(dummyEvent, (DWORD)(1000.0f * seconds));
  CloseHandle(dummyEvent);
  return;
#endif

  // fall-back case is fugly manual timekeeping
  TimeKeeper now = TimeKeeper::getCurrent();
  while ((TimeKeeper::getCurrent() - now) < seconds) {
    continue;
  }
  return;
}

// Local Variables: ***
// mode: C++ ***
// tab-width: 8 ***
// c-basic-offset: 2 ***
// indent-tabs-mode: t ***
// End: ***
// ex: shiftwidth=2 tabstop=8
<|endoftext|>


<commit_before>#include "open_loop.h"

OpenLoop::OpenLoop()
{
    joySub = n.subscribe("joystick", 1, &OpenLoop::joyCallback, this);
    tauPub = n.advertise<geometry_msgs::Wrench>("control_forces", 1);
}

void OpenLoop::joyCallback(const joystick::Joystick &joy_msg)
{
    geometry_msgs::Wrench tau;
    tau.force.x  = joy_msg.strafe_X * NORMALIZATION * SCALING_LIN;
    tau.force.y  = joy_msg.strafe_Y * NORMALIZATION * SCALING_LIN;
    tau.force.z  = joy_msg.ascend   * NORMALIZATION * SCALING_LIN;
    tau.torque.x = 0;
    tau.torque.y = joy_msg.turn_X   * NORMALIZATION * SCALING_ANG;
    tau.torque.z = joy_msg.turn_Y   * NORMALIZATION * SCALING_ANG;

    tauPub.publish(tau);
}

int main(int argc, char **argv)
{
    ros::init(argc, argv, "openloop");
    ROS_INFO("Launching node open_loop.");
    OpenLoop openLoop;
    ros::spin();
    return 0;
}
<commit_msg>Remove heave force, not used for test rov<commit_after>#include "open_loop.h"

OpenLoop::OpenLoop()
{
    joySub = n.subscribe("joystick", 1, &OpenLoop::joyCallback, this);
    tauPub = n.advertise<geometry_msgs::Wrench>("control_forces", 1);
}

void OpenLoop::joyCallback(const joystick::Joystick &joy_msg)
{
    geometry_msgs::Wrench tau;
    tau.force.x  = joy_msg.strafe_X * NORMALIZATION * SCALING_LIN;
    tau.force.y  = joy_msg.strafe_Y * NORMALIZATION * SCALING_LIN;
    tau.force.z  = 0;
    tau.torque.x = 0;
    tau.torque.y = joy_msg.turn_X   * NORMALIZATION * SCALING_ANG;
    tau.torque.z = joy_msg.turn_Y   * NORMALIZATION * SCALING_ANG;

    tauPub.publish(tau);
}

int main(int argc, char **argv)
{
    ros::init(argc, argv, "openloop");
    ROS_INFO("Launching node open_loop.");
    OpenLoop openLoop;
    ros::spin();
    return 0;
}
<|endoftext|>


<commit_before>/*

Copyright (c) 2013, Arvid Norberg
All rights reserved.

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

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

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

*/

#include "test.hpp"
#include "setup_transfer.hpp"

#include "libtorrent/file_storage.hpp"

using namespace libtorrent;

void setup_test_storage(file_storage& st)
{
	st.add_file("test/a", 10000);
	st.add_file("test/b", 20000);
	st.add_file("test/c/a", 30000);
	st.add_file("test/c/b", 40000);

	st.set_piece_length(0x4000);
	st.set_num_pieces((st.total_size() + st.piece_length() - 1) / 0x4000);

	TEST_EQUAL(st.file_name(0), "a");
	TEST_EQUAL(st.file_name(1), "b");
	TEST_EQUAL(st.file_name(2), "a");
	TEST_EQUAL(st.file_name(3), "b");
	TEST_EQUAL(st.name(), "test");

	TEST_EQUAL(st.file_path(0), "test/a");
	TEST_EQUAL(st.file_path(1), "test/b");
	TEST_EQUAL(st.file_path(2), "test/c/a");
	TEST_EQUAL(st.file_path(3), "test/c/b");

	TEST_EQUAL(st.file_size(0), 10000);
	TEST_EQUAL(st.file_size(1), 20000);
	TEST_EQUAL(st.file_size(2), 30000);
	TEST_EQUAL(st.file_size(3), 40000);

	TEST_EQUAL(st.file_offset(0), 0);
	TEST_EQUAL(st.file_offset(1), 10000);
	TEST_EQUAL(st.file_offset(2), 30000);
	TEST_EQUAL(st.file_offset(3), 60000);

	TEST_EQUAL(st.total_size(), 100000);
	TEST_EQUAL(st.piece_length(), 0x4000);
	printf("%d\n", st.num_pieces());
	TEST_EQUAL(st.num_pieces(), (100000 + 0x3fff) / 0x4000);
}

int test_main()
{
	{
		file_storage st;
		setup_test_storage(st);

		st.rename_file(0, "test/c/d");
		TEST_EQUAL(st.file_path(0, "./"), "./test/c/d");

#ifdef TORRENT_WINDOWS
		st.rename_file(0, "c:\\tmp\\a");
		TEST_EQUAL(st.file_path(0, "."), "c:\\tmp\\a");
#else
		st.rename_file(0, "/tmp/a");
		TEST_EQUAL(st.file_path(0, "."), "/tmp/a");
#endif
	}

	{
		file_storage st;
		st.add_file("a", 10000);

		st.rename_file(0, "test/c/d");
		TEST_EQUAL(st.file_path(0, "./"), "./test/c/d");

#ifdef TORRENT_WINDOWS
		st.rename_file(0, "c:\\tmp\\a");
		TEST_EQUAL(st.file_path(0, "."), "c:\\tmp\\a");
#else
		st.rename_file(0, "/tmp/a");
		TEST_EQUAL(st.file_path(0, "."), "/tmp/a");
#endif
	}

	{
		file_storage fs;
		fs.set_piece_length(512);
		fs.add_file(combine_path("temp_storage", "test1.tmp"), 17);
		fs.add_file(combine_path("temp_storage", "test2.tmp"), 612);
		fs.add_file(combine_path("temp_storage", "test3.tmp"), 0);
		fs.add_file(combine_path("temp_storage", "test4.tmp"), 0);
		fs.add_file(combine_path("temp_storage", "test5.tmp"), 3253);
		// size: 3882
		fs.add_file(combine_path("temp_storage", "test6.tmp"), 841);
		// size: 4723

		peer_request rq = fs.map_file(0, 0, 10);
		TEST_EQUAL(rq.piece, 0);
		TEST_EQUAL(rq.start, 0);
		TEST_EQUAL(rq.length, 10);
		rq = fs.map_file(5, 0, 10);
		TEST_EQUAL(rq.piece, 7);
		TEST_EQUAL(rq.start, 298);
		TEST_EQUAL(rq.length, 10);
		rq = fs.map_file(5, 0, 1000);
		TEST_EQUAL(rq.piece, 7);
		TEST_EQUAL(rq.start, 298);
		TEST_EQUAL(rq.length, 841);
	}

	return 0;
}

<commit_msg>fix windows build of test_file_storage<commit_after>/*

Copyright (c) 2013, Arvid Norberg
All rights reserved.

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

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

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

*/

#include "test.hpp"
#include "setup_transfer.hpp"

#include "libtorrent/file_storage.hpp"

using namespace libtorrent;

void setup_test_storage(file_storage& st)
{
	st.add_file("test/a", 10000);
	st.add_file("test/b", 20000);
	st.add_file("test/c/a", 30000);
	st.add_file("test/c/b", 40000);

	st.set_piece_length(0x4000);
	st.set_num_pieces((st.total_size() + st.piece_length() - 1) / 0x4000);

	TEST_EQUAL(st.file_name(0), "a");
	TEST_EQUAL(st.file_name(1), "b");
	TEST_EQUAL(st.file_name(2), "a");
	TEST_EQUAL(st.file_name(3), "b");
	TEST_EQUAL(st.name(), "test");

	TEST_EQUAL(st.file_path(0), combine_path("test", "a"));
	TEST_EQUAL(st.file_path(1), combine_path("test", "b"));
	TEST_EQUAL(st.file_path(2), combine_path("test", combine_path("c", "a")));
	TEST_EQUAL(st.file_path(3), combine_path("test", combine_path("c", "b")));

	TEST_EQUAL(st.file_size(0), 10000);
	TEST_EQUAL(st.file_size(1), 20000);
	TEST_EQUAL(st.file_size(2), 30000);
	TEST_EQUAL(st.file_size(3), 40000);

	TEST_EQUAL(st.file_offset(0), 0);
	TEST_EQUAL(st.file_offset(1), 10000);
	TEST_EQUAL(st.file_offset(2), 30000);
	TEST_EQUAL(st.file_offset(3), 60000);

	TEST_EQUAL(st.total_size(), 100000);
	TEST_EQUAL(st.piece_length(), 0x4000);
	printf("%d\n", st.num_pieces());
	TEST_EQUAL(st.num_pieces(), (100000 + 0x3fff) / 0x4000);
}

int test_main()
{
	{
		file_storage st;
		setup_test_storage(st);

		st.rename_file(0, combine_path("test", combine_path("c", "d")));
		TEST_EQUAL(st.file_path(0, "."), combine_path(".", combine_path("test", combine_path("c", "d"))));

#ifdef TORRENT_WINDOWS
		st.rename_file(0, "c:\\tmp\\a");
		TEST_EQUAL(st.file_path(0, "."), "c:\\tmp\\a");
#else
		st.rename_file(0, "/tmp/a");
		TEST_EQUAL(st.file_path(0, "."), "/tmp/a");
#endif
	}

	{
		file_storage st;
		st.add_file("a", 10000);

		st.rename_file(0, combine_path("test", combine_path("c", "d")));
		TEST_EQUAL(st.file_path(0, "."), combine_path(".", combine_path("test", combine_path("c", "d"))));

#ifdef TORRENT_WINDOWS
		st.rename_file(0, "c:\\tmp\\a");
		TEST_EQUAL(st.file_path(0, "."), "c:\\tmp\\a");
#else
		st.rename_file(0, "/tmp/a");
		TEST_EQUAL(st.file_path(0, "."), "/tmp/a");
#endif
	}

	{
		file_storage fs;
		fs.set_piece_length(512);
		fs.add_file(combine_path("temp_storage", "test1.tmp"), 17);
		fs.add_file(combine_path("temp_storage", "test2.tmp"), 612);
		fs.add_file(combine_path("temp_storage", "test3.tmp"), 0);
		fs.add_file(combine_path("temp_storage", "test4.tmp"), 0);
		fs.add_file(combine_path("temp_storage", "test5.tmp"), 3253);
		// size: 3882
		fs.add_file(combine_path("temp_storage", "test6.tmp"), 841);
		// size: 4723

		peer_request rq = fs.map_file(0, 0, 10);
		TEST_EQUAL(rq.piece, 0);
		TEST_EQUAL(rq.start, 0);
		TEST_EQUAL(rq.length, 10);
		rq = fs.map_file(5, 0, 10);
		TEST_EQUAL(rq.piece, 7);
		TEST_EQUAL(rq.start, 298);
		TEST_EQUAL(rq.length, 10);
		rq = fs.map_file(5, 0, 1000);
		TEST_EQUAL(rq.piece, 7);
		TEST_EQUAL(rq.start, 298);
		TEST_EQUAL(rq.length, 841);
	}

	return 0;
}

<|endoftext|>


<commit_before>#include "catch.hpp"
#include "crib_hand_helper/hand_counter.h"

TEST_CASE("Nobs")
{
  SECTION("Without nobs")
  {
    Hand hand = {Card("2c"), Card("4d"), Card("6h"), Card("Js")};
    Card cut("8c");

    REQUIRE(count_hand(hand, cut) == 0);
  }

  SECTION("With nobs")
  {
    Hand hand = {Card("2c"), Card("4d"), Card("6h"), Card("Js")};
    Card cut("8s");

    REQUIRE(count_hand(hand, cut) == 1);
  }
}

TEST_CASE("Flush")
{
  SECTION("Without flush")
  {
    Hand hand = {Card("2c"), Card("4d"), Card("6h"), Card("Js")};
    Card cut("8c");

    REQUIRE(count_hand(hand, cut) == 0);
  }

  SECTION("Without hand-only flush")
  {
    Hand hand = {Card("2d"), Card("4d"), Card("6d"), Card("Jd")};
    Card cut("8c");

    REQUIRE(count_hand(hand, cut) == 4);
  }

  SECTION("Without full flush")
  {
    Hand hand = {Card("2d"), Card("4d"), Card("6d"), Card("Qd")};
    Card cut("8d");

    REQUIRE(count_hand(hand, cut) == 5);
  }
}

TEST_CASE("Pairs")
{
  SECTION("No pairs")
  {
    Hand hand = {Card("2c"), Card("4d"), Card("6h"), Card("Js")};
    Card cut("8c");

    REQUIRE(count_hand(hand, cut) == 0);
  }

  SECTION("Single pair")
  {
    Hand hand = {Card("2d"), Card("2c"), Card("6d"), Card("Jd")};
    Card cut("8c");

    REQUIRE(count_hand(hand, cut) == 2);
  }

  SECTION("Two pairs")
  {
    Hand hand = {Card("2d"), Card("2c"), Card("6d"), Card("8d")};
    Card cut("8d");

    REQUIRE(count_hand(hand, cut) == 4);
  }

  SECTION("Three pairs")
  {
    Hand hand = {Card("2d"), Card("2c"), Card("6d"), Card("8d")};
    Card cut("2s");

    REQUIRE(count_hand(hand, cut) == 6);
  }

  SECTION("Six pairs")
  {
    Hand hand = {Card("2d"), Card("2c"), Card("2h"), Card("8d")};
    Card cut("2s");

    REQUIRE(count_hand(hand, cut) == 12);
  }
}

TEST_CASE("Runs")
{
  SECTION("No runs")
  {
    Hand hand = {Card("2c"), Card("4d"), Card("6h"), Card("Js")};
    Card cut("8c");

    REQUIRE(count_hand(hand, cut) == 0);
  }

  SECTION("Run of five")
  {
    Hand hand = {Card("9c"), Card("Td"), Card("Jh"), Card("Qs")};
    Card cut("Kc");

    REQUIRE(count_hand(hand, cut) == 5);
  }

  SECTION("Run of four")
  {
    Hand hand = {Card("Qc"), Card("Td"), Card("Kh"), Card("7s")};
    Card cut("Jc");

    REQUIRE(count_hand(hand, cut) == 4);
  }

  SECTION("Run of three")
  {
    Hand hand = {Card("Qc"), Card("Td"), Card("4h"), Card("7s")};
    Card cut("Jc");

    REQUIRE(count_hand(hand, cut) == 3);
  }
}

TEST_CASE("Fifteens")
{
}

TEST_CASE("Miscellaneous hands")
{
  SECTION("Like this one will ever happen")
  {
    Hand hand = {Card("5c"), Card("5d"), Card("5h"), Card("Js")};
    Card cut("5s");

    REQUIRE(count_hand(hand, cut) == 29);
  }
}
<commit_msg>Added more hand counter tests.<commit_after>#include "catch.hpp"
#include "crib_hand_helper/hand_counter.h"

TEST_CASE("Nobs")
{
  SECTION("Without nobs")
  {
    Hand hand = {Card("2c"), Card("4d"), Card("6h"), Card("Js")};
    Card cut("8c");

    REQUIRE(count_hand(hand, cut) == 0);
  }

  SECTION("With nobs")
  {
    Hand hand = {Card("2c"), Card("4d"), Card("6h"), Card("Js")};
    Card cut("8s");

    REQUIRE(count_hand(hand, cut) == 1);
  }
}

TEST_CASE("Flush")
{
  SECTION("Without flush")
  {
    Hand hand = {Card("2c"), Card("4d"), Card("6h"), Card("Js")};
    Card cut("8c");

    REQUIRE(count_hand(hand, cut) == 0);
  }

  SECTION("Without hand-only flush")
  {
    Hand hand = {Card("2d"), Card("4d"), Card("6d"), Card("Jd")};
    Card cut("8c");

    REQUIRE(count_hand(hand, cut) == 4);
  }

  SECTION("Without full flush")
  {
    Hand hand = {Card("2d"), Card("4d"), Card("6d"), Card("Qd")};
    Card cut("8d");

    REQUIRE(count_hand(hand, cut) == 5);
  }
}

TEST_CASE("Pairs")
{
  SECTION("No pairs")
  {
    Hand hand = {Card("2c"), Card("4d"), Card("6h"), Card("Js")};
    Card cut("8c");

    REQUIRE(count_hand(hand, cut) == 0);
  }

  SECTION("Single pair")
  {
    Hand hand = {Card("2d"), Card("2c"), Card("6d"), Card("Jd")};
    Card cut("8c");

    REQUIRE(count_hand(hand, cut) == 2);
  }

  SECTION("Two pairs")
  {
    Hand hand = {Card("2d"), Card("2c"), Card("6d"), Card("8d")};
    Card cut("8d");

    REQUIRE(count_hand(hand, cut) == 4);
  }

  SECTION("Three pairs")
  {
    Hand hand = {Card("2d"), Card("2c"), Card("6d"), Card("8d")};
    Card cut("2s");

    REQUIRE(count_hand(hand, cut) == 6);
  }

  SECTION("Six pairs")
  {
    Hand hand = {Card("2d"), Card("2c"), Card("2h"), Card("8d")};
    Card cut("2s");

    REQUIRE(count_hand(hand, cut) == 12);
  }
}

TEST_CASE("Runs")
{
  SECTION("No runs")
  {
    Hand hand = {Card("2c"), Card("4d"), Card("6h"), Card("Js")};
    Card cut("8c");

    REQUIRE(count_hand(hand, cut) == 0);
  }

  SECTION("Run of five")
  {
    Hand hand = {Card("9c"), Card("Td"), Card("Jh"), Card("Qs")};
    Card cut("Kc");

    REQUIRE(count_hand(hand, cut) == 5);
  }

  SECTION("Run of four")
  {
    Hand hand = {Card("Qc"), Card("Td"), Card("Kh"), Card("7s")};
    Card cut("Jc");

    REQUIRE(count_hand(hand, cut) == 4);
  }

  SECTION("Run of three")
  {
    Hand hand = {Card("Qc"), Card("Td"), Card("4h"), Card("7s")};
    Card cut("Jc");

    REQUIRE(count_hand(hand, cut) == 3);
  }
}

TEST_CASE("Fifteens")
{
  SECTION("Two card fifteens")
  {
    REQUIRE(count_hand({Card("2c"), Card("4d"), Card("7h"), Card("Js")}, Card("8c")) == 2);
    REQUIRE(count_hand({Card("2c"), Card("Ad"), Card("6h"), Card("Js")}, Card("9c")) == 2);
    REQUIRE(count_hand({Card("2c"), Card("4d"), Card("5h"), Card("Js")}, Card("7c")) == 2);
  }

  SECTION("Three card fifteens")
  {
    REQUIRE(count_hand({Card("2c"), Card("4d"), Card("9h"), Card("Js")}, Card("8c")) == 2);
    REQUIRE(count_hand({Card("4c"), Card("Ad"), Card("7h"), Card("Js")}, Card("9c")) == 2);
    REQUIRE(count_hand({Card("3c"), Card("4d"), Card("8h"), Card("Js")}, Card("6c")) == 2);
  }

  SECTION("Four card fifteen")
  {
    REQUIRE(count_hand({Card("Ac"), Card("2d"), Card("4h"), Card("8s")}, Card("6c")) == 4);
  }

  SECTION("Five card fifteen")
  {
    REQUIRE(count_hand({Card("Ac"), Card("2d"), Card("3h"), Card("4s")}, Card("5c")) == 7);
  }
}

TEST_CASE("Miscellaneous hands")
{
  SECTION("Like this one will ever happen")
  {
    Hand hand = {Card("5c"), Card("5d"), Card("5h"), Card("Js")};
    Card cut("5s");

    REQUIRE(count_hand(hand, cut) == 29);
  }
}
<|endoftext|>


<commit_before>// Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2015 The Bitcoin Core developers
// Copyright (c) 2014-2017 The Energi Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.

#include "chainparams.h"
#include "clientversion.h"
#include "rpc/server.h"
#include "init.h"
#include "noui.h"
#include "scheduler.h"
#include "util.h"
#include "masternodeconfig.h"
#include "httpserver.h"
#include "httprpc.h"
#include "main.h"

#include <boost/algorithm/string/predicate.hpp>
#include <boost/filesystem.hpp>
#include <boost/thread.hpp>

#include <stdio.h>

/* Introduction text for doxygen: */

/*! \mainpage Developer documentation
 *
 * \section intro_sec Introduction
 *
 * This is the developer documentation of the reference client for an experimental new digital currency called Energi (https://www.energi.org/),
 * which enables instant payments to anyone, anywhere in the world. Energi uses peer-to-peer technology to operate
 * with no central authority: managing transactions and issuing money are carried out collectively by the network.
 *
 * The software is a community-driven open source project, released under the MIT license.
 *
 * \section Navigation
 * Use the buttons Namespaces, Classes or Files at the top of the page to start navigating the code.
 */

static bool fDaemon;

void WaitForShutdown(boost::thread_group* threadGroup)
{
    bool fShutdown = ShutdownRequested();
    // Tell the main threads to shutdown.
    while (!fShutdown)
    {
        MilliSleep(200);
        fShutdown = ShutdownRequested();
    }
    if (threadGroup)
    {
        Interrupt(*threadGroup);
        threadGroup->join_all();
    }
}

//////////////////////////////////////////////////////////////////////////////
//
// Start
//
bool AppInit(int argc, char* argv[])
{
    boost::thread_group threadGroup;
    CScheduler scheduler;

    bool fRet = false;

    //
    // Parameters
    //
    // If Qt is used, parameters/energi.conf are parsed in qt/energi.cpp's main()
    ParseParameters(argc, argv);

    // Process help and version before taking care about datadir
    if (mapArgs.count("-?") || mapArgs.count("-h") ||  mapArgs.count("-help") || mapArgs.count("-version")) {
        std::string strUsage = _("Energi Core Daemon") + " " + _("version") + " " + FormatFullVersion() + "\n";

        if (mapArgs.count("-version")) {
            strUsage += LicenseInfo();
        } else {
            strUsage += "\n" + _("Usage:") + "\n" +
                  "  energid [options]                     " + _("Start Energi Core Daemon") + "\n";

            strUsage += "\n" + HelpMessage(HMM_BITCOIND);
        }
        fprintf(stdout, "%s", strUsage.c_str());
        return true;
    }

    try
    {
        bool datadirFromCmdLine = mapArgs.count("-datadir") != 0;
        if (datadirFromCmdLine && !boost::filesystem::is_directory(GetDataDir(false)))
        {
            fprintf(stderr, "Error: Specified data directory \"%s\" does not exist.\n", mapArgs["-datadir"].c_str());
            return false;
        }
        try
        {
            ReadConfigFile(mapArgs, mapMultiArgs);
        } catch (const std::exception& e) {
            fprintf(stderr,"Error reading configuration file: %s\n", e.what());
            return false;
        }
        if (!datadirFromCmdLine && !boost::filesystem::is_directory(GetDataDir(false)))
        {
            fprintf(stderr, "Error: Specified data directory \"%s\" from config file does not exist.\n", mapArgs["-datadir"].c_str());
            return EXIT_FAILURE;
        }
        // Check for -testnet or -regtest parameter (Params() calls are only valid after this clause)
        try {
            SelectParams(ChainNameFromCommandLine());
        } catch (const std::exception& e) {
            fprintf(stderr, "Error: %s\n", e.what());
            return false;
        }

        // parse masternode.conf
        std::string strErr;
        if(!masternodeConfig.read(strErr)) {
            fprintf(stderr,"Error reading masternode configuration file: %s\n", strErr.c_str());
            return false;
        }

        // Command-line RPC
        bool fCommandLine = false;
        for (int i = 1; i < argc; i++)
            if (!IsSwitchChar(argv[i][0]) && !boost::algorithm::istarts_with(argv[i], "energi:"))
                fCommandLine = true;

        if (fCommandLine)
        {
            fprintf(stderr, "Error: There is no RPC client functionality in energid anymore. Use the energi-cli utility instead.\n");
            exit(EXIT_FAILURE);
        }
#ifndef WIN32
        fDaemon = GetBoolArg("-daemon", false);
        if (fDaemon)
        {
            fprintf(stdout, "Energi Core server starting\n");

            // Daemonize
            pid_t pid = fork();
            if (pid < 0)
            {
                fprintf(stderr, "Error: fork() returned %d errno %d\n", pid, errno);
                return false;
            }
            if (pid > 0) // Parent process, pid is child process id
            {
                return true;
            }
            // Child process falls through to rest of initialization

            pid_t sid = setsid();
            if (sid < 0)
                fprintf(stderr, "Error: setsid() returned %d errno %d\n", sid, errno);
        }
#endif
        SoftSetBoolArg("-server", true);

        // Set this early so that parameter interactions go to console
        InitLogging();
        InitParameterInteraction();
        fRet = AppInit2(threadGroup, scheduler);
    }
    catch (const std::exception& e) {
        PrintExceptionContinue(&e, "AppInit()");
    } catch (...) {
        PrintExceptionContinue(NULL, "AppInit()");
    }

    if (!fRet)
    {
        Interrupt(threadGroup);
        // threadGroup.join_all(); was left out intentionally here, because we didn't re-test all of
        // the startup-failure cases to make sure they don't result in a hang due to some
        // thread-blocking-waiting-for-another-thread-during-startup case
    } else {
        WaitForShutdown(&threadGroup);
    }
    Shutdown();

    return fRet;
}

int main(int argc, char* argv[])
{
    SetupEnvironment();

    // Connect energid signal handlers
    noui_connect();

    return (AppInit(argc, argv) ? EXIT_SUCCESS : EXIT_FAILURE);
}
<commit_msg>fixing copyright and comment<commit_after>// Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2015 The Bitcoin Core developers
// Copyright (c) 2014-2017 The Dash Core developers
// Copyright (c) 2017 The Energi Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.

#include "chainparams.h"
#include "clientversion.h"
#include "rpc/server.h"
#include "init.h"
#include "noui.h"
#include "scheduler.h"
#include "util.h"
#include "masternodeconfig.h"
#include "httpserver.h"
#include "httprpc.h"

#include <boost/algorithm/string/predicate.hpp>
#include <boost/filesystem.hpp>
#include <boost/thread.hpp>

#include <stdio.h>

/* Introduction text for doxygen: */

/*! \mainpage Developer documentation
 *
 * \section intro_sec Introduction
 *
 * This is the developer documentation of the reference client for an experimental new digital currency called Energi (http://energi.world/),
 * which enables instant payments to anyone, anywhere in the world. Energi uses peer-to-peer technology to operate
 * with no central authority: managing transactions and issuing money are carried out collectively by the network.
 *
 * The software is a community-driven open source project, released under the MIT license.
 *
 * \section Navigation
 * Use the buttons Namespaces, Classes or Files at the top of the page to start navigating the code.
 */

static bool fDaemon;

void WaitForShutdown(boost::thread_group* threadGroup)
{
    bool fShutdown = ShutdownRequested();
    // Tell the main threads to shutdown.
    while (!fShutdown)
    {
        MilliSleep(200);
        fShutdown = ShutdownRequested();
    }
    if (threadGroup)
    {
        Interrupt(*threadGroup);
        threadGroup->join_all();
    }
}

//////////////////////////////////////////////////////////////////////////////
//
// Start
//
bool AppInit(int argc, char* argv[])
{
    boost::thread_group threadGroup;
    CScheduler scheduler;

    bool fRet = false;

    //
    // Parameters
    //
    // If Qt is used, parameters/energi.conf are parsed in qt/energi.cpp's main()
    ParseParameters(argc, argv);

    // Process help and version before taking care about datadir
    if (mapArgs.count("-?") || mapArgs.count("-h") ||  mapArgs.count("-help") || mapArgs.count("-version")) {
        std::string strUsage = _("Energi Core Daemon") + " " + _("version") + " " + FormatFullVersion() + "\n";

        if (mapArgs.count("-version")) {
            strUsage += LicenseInfo();
        } else {
            strUsage += "\n" + _("Usage:") + "\n" +
                  "  energid [options]                     " + _("Start Energi Core Daemon") + "\n";

            strUsage += "\n" + HelpMessage(HMM_BITCOIND);
        }
        fprintf(stdout, "%s", strUsage.c_str());
        return true;
    }

    try
    {
        bool datadirFromCmdLine = mapArgs.count("-datadir") != 0;
        if (datadirFromCmdLine && !boost::filesystem::is_directory(GetDataDir(false)))
        {
            fprintf(stderr, "Error: Specified data directory \"%s\" does not exist.\n", mapArgs["-datadir"].c_str());
            return false;
        }
        try
        {
            ReadConfigFile(mapArgs, mapMultiArgs);
        } catch (const std::exception& e) {
            fprintf(stderr,"Error reading configuration file: %s\n", e.what());
            return false;
        }
        if (!datadirFromCmdLine && !boost::filesystem::is_directory(GetDataDir(false)))
        {
            fprintf(stderr, "Error: Specified data directory \"%s\" from config file does not exist.\n", mapArgs["-datadir"].c_str());
            return EXIT_FAILURE;
        }
        // Check for -testnet or -regtest parameter (Params() calls are only valid after this clause)
        try {
            SelectParams(ChainNameFromCommandLine());
        } catch (const std::exception& e) {
            fprintf(stderr, "Error: %s\n", e.what());
            return false;
        }

        // parse masternode.conf
        std::string strErr;
        if(!masternodeConfig.read(strErr)) {
            fprintf(stderr,"Error reading masternode configuration file: %s\n", strErr.c_str());
            return false;
        }

        // Command-line RPC
        bool fCommandLine = false;
        for (int i = 1; i < argc; i++)
            if (!IsSwitchChar(argv[i][0]) && !boost::algorithm::istarts_with(argv[i], "energi:"))
                fCommandLine = true;

        if (fCommandLine)
        {
            fprintf(stderr, "Error: There is no RPC client functionality in energid anymore. Use the energi-cli utility instead.\n");
            exit(EXIT_FAILURE);
        }
#ifndef WIN32
        fDaemon = GetBoolArg("-daemon", false);
        if (fDaemon)
        {
            fprintf(stdout, "Energi Core server starting\n");

            // Daemonize
            pid_t pid = fork();
            if (pid < 0)
            {
                fprintf(stderr, "Error: fork() returned %d errno %d\n", pid, errno);
                return false;
            }
            if (pid > 0) // Parent process, pid is child process id
            {
                return true;
            }
            // Child process falls through to rest of initialization

            pid_t sid = setsid();
            if (sid < 0)
                fprintf(stderr, "Error: setsid() returned %d errno %d\n", sid, errno);
        }
#endif
        SoftSetBoolArg("-server", true);

        // Set this early so that parameter interactions go to console
        InitLogging();
        InitParameterInteraction();
        fRet = AppInit2(threadGroup, scheduler);
    }
    catch (const std::exception& e) {
        PrintExceptionContinue(&e, "AppInit()");
    } catch (...) {
        PrintExceptionContinue(NULL, "AppInit()");
    }

    if (!fRet)
    {
        Interrupt(threadGroup);
        // threadGroup.join_all(); was left out intentionally here, because we didn't re-test all of
        // the startup-failure cases to make sure they don't result in a hang due to some
        // thread-blocking-waiting-for-another-thread-during-startup case
    } else {
        WaitForShutdown(&threadGroup);
    }
    Shutdown();

    return fRet;
}

int main(int argc, char* argv[])
{
    SetupEnvironment();

    // Connect energid signal handlers
    noui_connect();

    return (AppInit(argc, argv) ? EXIT_SUCCESS : EXIT_FAILURE);
}
<|endoftext|>


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

#include <gtest/gtest.h>
#include <pcl/kdtree/kdtree_flann.h>
#include <pcl/point_types.h>
#include <pcl/point_cloud.h>
#include <pcl/io/pcd_io.h>
#include <pcl/search/search.h>
#include <pcl/features/normal_3d.h>

#include <pcl/segmentation/extract_polygonal_prism_data.h>
#include <pcl/segmentation/segment_differences.h>
//#include <pcl/segmentation/region_growing.h>

using namespace pcl;
using namespace pcl::io;

PointCloud<PointXYZ>::Ptr cloud_;
PointCloud<PointXYZ>::Ptr cloud_t_;
KdTree<PointXYZ>::Ptr tree_;

pcl::PointCloud<pcl::PointXYZ>::Ptr another_cloud_;
pcl::PointCloud<pcl::Normal>::Ptr normals_;
pcl::PointCloud<pcl::Normal>::Ptr another_normals_;

////////////////////////////////////////////////////////////////////////////////////////////////
//TEST (//gionGrowingTest, Segment)
//{
//  pcl::RegionGrowing<pcl::PointXYZ> rg;
//  rg.setCloud(cloud_);
//  rg.setNormals(normals_);
//
//  int num_of_segments = rg.segmentPoints();
//  EXPECT_NE(0, num_of_segments);
//
//  std::vector<std::list<int>> segments;
//  segments = rg.getSegments();
//  EXPECT_NE(0, segments.size());
//}
//
////////////////////////////////////////////////////////////////////////////////////////////////
//TEST (RegionGrowingTest, SegmentWithoutCloud)
//{
//  pcl::RegionGrowing<pcl::PointXYZ> rg;
//  rg.setNormals(normals_);
//
//  int num_of_segments = rg.segmentPoints();
//  EXPECT_EQ(0, num_of_segments);
//
//  std::vector<std::list<int>> segments;
//  segments = rg.getSegments();
//  EXPECT_EQ(0, segments.size());
//}
//
////////////////////////////////////////////////////////////////////////////////////////////////
//TEST (RegionGrowingTest, SegmentWithoutNormals)
//{
//  pcl::RegionGrowing<pcl::PointXYZ> rg;
//  rg.setCloud(cloud_);
//
//  int num_of_segments = rg.segmentPoints();
//  EXPECT_EQ(0, num_of_segments);
//
//  std::vector<std::list<int>> segments;
//  segments = rg.getSegments();
//  EXPECT_EQ(0, segments.size());
//}
//
////////////////////////////////////////////////////////////////////////////////////////////////
//TEST (RegionGrowingTest, SegmentEmptyCloud)
//{
//  pcl::PointCloud<pcl::PointXYZ>::Ptr empty_cloud(new pcl::PointCloud<pcl::PointXYZ>);
//  pcl::PointCloud<pcl::Normal>::Ptr empty_normals(new pcl::PointCloud<pcl::Normal>);
//
//  pcl::RegionGrowing<pcl::PointXYZ> rg;
//  rg.setCloud(empty_cloud);
//  rg.setNormals(empty_normals);
//
//  int num_of_segments = rg.segmentPoints();
//  EXPECT_EQ(0, num_of_segments);
//
//  std::vector<std::list<int>> segments;
//  segments = rg.getSegments();
//  EXPECT_EQ(0, segments.size());
//}
//
////////////////////////////////////////////////////////////////////////////////////////////////
//TEST (RegionGrowingTest, SegmentWithDifferentNormalAndCloudSize)
//{
//  pcl::RegionGrowing<pcl::PointXYZ> rg;
//  rg.setCloud(another_cloud_);
//  rg.setNormals(normals_);
//
//  int first_cloud_size = cloud_->points.size();
//  int second_cloud_size = another_cloud_->points.size();
//  ASSERT_NE(first_cloud_size, second_cloud_size);
//
//  int num_of_segments = rg.segmentPoints();
//  EXPECT_EQ(0, num_of_segments);
//
//  std::vector<std::list<int>> segments;
//  segments = rg.getSegments();
//  EXPECT_EQ(0, segments.size());
//
//  rg.setCloud(cloud_);
//  rg.setNormals(another_normals_);
//
//  num_of_segments = rg.segmentPoints();
//  EXPECT_EQ(0, num_of_segments);
//
//  segments = rg.getSegments();
//  EXPECT_EQ(0, segments.size());
//}
//
////////////////////////////////////////////////////////////////////////////////////////////////
//TEST (RegionGrowingTest, SegmentWithWrongThresholdParameters)
//{
//  pcl::RegionGrowing<pcl::PointXYZ> rg;
//  rg.setCloud(cloud_);
//  rg.setNormals(normals_);
//
//  rg.setNumberOfNeighbours(0);
//
//  int num_of_segments = rg.segmentPoints();
//  EXPECT_EQ(0, num_of_segments);
//
//  std::vector<std::list<int>> segments;
//  segments = rg.getSegments();
//  EXPECT_EQ(0, segments.size());
//
//  rg.setNumberOfNeighbours(30);
//  rg.setResidualThreshold(-10.0);
//
//  num_of_segments = rg.segmentPoints();
//  EXPECT_EQ(0, num_of_segments);
//
//  segments = rg.getSegments();
//  EXPECT_EQ(0, segments.size());
//}
//
////////////////////////////////////////////////////////////////////////////////////////////////
//TEST (RegionGrowingTest, SegmentFromPoint)
//{
//  pcl::RegionGrowing<pcl::PointXYZ> rg;
//
//  std::list<int> segment = rg.getSegmentFromPoint(0);
//  EXPECT_EQ(0, segment.size());
//
//  rg.setCloud(cloud_);
//  rg.setNormals(normals_);
//  segment = rg.getSegmentFromPoint(0);
//  EXPECT_NE(0, segment.size());
//}

//////////////////////////////////////////////////////////////////////////////////////////////
TEST (SegmentDifferences, Segmentation)
{
  SegmentDifferences<PointXYZ> sd;
  sd.setInputCloud (cloud_);
  sd.setDistanceThreshold (0.00005);

  // Set the target as itself
  sd.setTargetCloud (cloud_);

  PointCloud<PointXYZ> output;
  sd.segment (output);

  EXPECT_EQ ((int)output.points.size (), 0);

  // Set a different target
  sd.setTargetCloud (cloud_t_);
  sd.segment (output);
  EXPECT_EQ ((int)output.points.size (), 126);
  //savePCDFile ("./test/0-t.pcd", output);

  // Reverse
  sd.setInputCloud (cloud_t_);
  sd.setTargetCloud (cloud_);
  sd.segment (output);
  EXPECT_EQ ((int)output.points.size (), 127);
  //savePCDFile ("./test/t-0.pcd", output);
}

//////////////////////////////////////////////////////////////////////////////////////////////
TEST (ExtractPolygonalPrism, Segmentation)
{
  PointCloud<PointXYZ>::Ptr hull (new PointCloud<PointXYZ>);
  hull->points.resize (5);

  for (size_t i = 0; i < hull->points.size (); ++i)
  {
    hull->points[i].x = hull->points[i].y = i;
    hull->points[i].z = 0;
  }

  ExtractPolygonalPrismData<PointXYZ> ex;
  ex.setInputCloud (cloud_);
  ex.setInputPlanarHull (hull);

  PointIndices output;
  ex.segment (output);

  EXPECT_EQ ((int)output.indices.size (), 0);
}

/* ---[ */
int
  main (int argc, char** argv)
{
  if (argc < 3)
  {
    std::cerr << "No test file given. Please download `bun0.pcd` and pass its path to the test." << std::endl;
    std::cerr << "The test needs two files. Please, pass two paths of different pcd files." << std::endl;
    return (-1);
  }

  // Load a standard PCD file from disk
  PointCloud<PointXYZ> cloud, cloud_t, another_cloud;
  if (loadPCDFile (argv[1], cloud) < 0)
  {
    std::cerr << "Failed to read test file. Please download `bun0.pcd` and pass its path to the test." << std::endl;
    return (-1);
  }
  if (pcl::io::loadPCDFile (argv[2], another_cloud) < 0)
  {
    std::cerr << "Failed to read test file. Please download `bun0.pcd` and pass its path to the test." << std::endl;
    return (-1);
  }

  // Tranpose the cloud
  cloud_t = cloud;
  for (size_t i = 0; i < cloud.points.size (); ++i)
    cloud_t.points[i].x += 0.01;

  cloud_   = cloud.makeShared ();
  cloud_t_ = cloud_t.makeShared ();

  another_cloud_ = another_cloud.makeShared();
  normals_ = (new pcl::PointCloud<pcl::Normal>)->makeShared();
  pcl::NormalEstimation<pcl::PointXYZ, pcl::Normal> normal_estimator;
  normal_estimator.setInputCloud(cloud_);
  normal_estimator.setKSearch(30);
  normal_estimator.compute(*normals_);

  another_normals_ = (new pcl::PointCloud<pcl::Normal>)->makeShared();
  normal_estimator.setInputCloud(another_cloud_);
  normal_estimator.setKSearch(30);
  normal_estimator.compute(*another_normals_);

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

#include <gtest/gtest.h>
#include <pcl/kdtree/kdtree_flann.h>
#include <pcl/point_types.h>
#include <pcl/point_cloud.h>
#include <pcl/io/pcd_io.h>
#include <pcl/search/search.h>
#include <pcl/features/normal_3d.h>

#include <pcl/segmentation/extract_polygonal_prism_data.h>
#include <pcl/segmentation/segment_differences.h>
#include <pcl/segmentation/region_growing.h>

using namespace pcl;
using namespace pcl::io;

PointCloud<PointXYZ>::Ptr cloud_;
PointCloud<PointXYZ>::Ptr cloud_t_;
KdTree<PointXYZ>::Ptr tree_;

pcl::PointCloud<pcl::PointXYZ>::Ptr another_cloud_;
pcl::PointCloud<pcl::Normal>::Ptr normals_;
pcl::PointCloud<pcl::Normal>::Ptr another_normals_;

////////////////////////////////////////////////////////////////////////////////////////////////
TEST (//gionGrowingTest, Segment)
{
  pcl::RegionGrowing<pcl::PointXYZ> rg;
  rg.setCloud(cloud_);
  rg.setNormals(normals_);

  int num_of_segments = rg.segmentPoints();
  EXPECT_NE(0, num_of_segments);

  std::vector<std::list<int>> segments;
  segments = rg.getSegments();
  EXPECT_NE(0, segments.size());
}

////////////////////////////////////////////////////////////////////////////////////////////////
TEST (RegionGrowingTest, SegmentWithoutCloud)
{
  pcl::RegionGrowing<pcl::PointXYZ> rg;
  rg.setNormals(normals_);

  int num_of_segments = rg.segmentPoints();
  EXPECT_EQ(0, num_of_segments);

  std::vector<std::list<int>> segments;
  segments = rg.getSegments();
  EXPECT_EQ(0, segments.size());
}

////////////////////////////////////////////////////////////////////////////////////////////////
TEST (RegionGrowingTest, SegmentWithoutNormals)
{
  pcl::RegionGrowing<pcl::PointXYZ> rg;
  rg.setCloud(cloud_);

  int num_of_segments = rg.segmentPoints();
  EXPECT_EQ(0, num_of_segments);

  std::vector<std::list<int>> segments;
  segments = rg.getSegments();
  EXPECT_EQ(0, segments.size());
}

////////////////////////////////////////////////////////////////////////////////////////////////
TEST (RegionGrowingTest, SegmentEmptyCloud)
{
  pcl::PointCloud<pcl::PointXYZ>::Ptr empty_cloud(new pcl::PointCloud<pcl::PointXYZ>);
  pcl::PointCloud<pcl::Normal>::Ptr empty_normals(new pcl::PointCloud<pcl::Normal>);

  pcl::RegionGrowing<pcl::PointXYZ> rg;
  rg.setCloud(empty_cloud);
  rg.setNormals(empty_normals);

  int num_of_segments = rg.segmentPoints();
  EXPECT_EQ(0, num_of_segments);

  std::vector<std::list<int>> segments;
  segments = rg.getSegments();
  EXPECT_EQ(0, segments.size());
}

////////////////////////////////////////////////////////////////////////////////////////////////
TEST (RegionGrowingTest, SegmentWithDifferentNormalAndCloudSize)
{
  pcl::RegionGrowing<pcl::PointXYZ> rg;
  rg.setCloud(another_cloud_);
  rg.setNormals(normals_);

  int first_cloud_size = cloud_->points.size();
  int second_cloud_size = another_cloud_->points.size();
  ASSERT_NE(first_cloud_size, second_cloud_size);

  int num_of_segments = rg.segmentPoints();
  EXPECT_EQ(0, num_of_segments);

  std::vector<std::list<int>> segments;
  segments = rg.getSegments();
  EXPECT_EQ(0, segments.size());

  rg.setCloud(cloud_);
  rg.setNormals(another_normals_);

  num_of_segments = rg.segmentPoints();
  EXPECT_EQ(0, num_of_segments);

  segments = rg.getSegments();
  EXPECT_EQ(0, segments.size());
}

////////////////////////////////////////////////////////////////////////////////////////////////
TEST (RegionGrowingTest, SegmentWithWrongThresholdParameters)
{
  pcl::RegionGrowing<pcl::PointXYZ> rg;
  rg.setCloud(cloud_);
  rg.setNormals(normals_);

  rg.setNumberOfNeighbours(0);

  int num_of_segments = rg.segmentPoints();
  EXPECT_EQ(0, num_of_segments);

  std::vector<std::list<int>> segments;
  segments = rg.getSegments();
  EXPECT_EQ(0, segments.size());

  rg.setNumberOfNeighbours(30);
  rg.setResidualThreshold(-10.0);

  num_of_segments = rg.segmentPoints();
  EXPECT_EQ(0, num_of_segments);

  segments = rg.getSegments();
  EXPECT_EQ(0, segments.size());
}

////////////////////////////////////////////////////////////////////////////////////////////////
//TEST (RegionGrowingTest, SegmentFromPoint)
{
  pcl::RegionGrowing<pcl::PointXYZ> rg;

  std::list<int> segment = rg.getSegmentFromPoint(0);
  EXPECT_EQ(0, segment.size());

  rg.setCloud(cloud_);
  rg.setNormals(normals_);
  segment = rg.getSegmentFromPoint(0);
  EXPECT_NE(0, segment.size());
}

//////////////////////////////////////////////////////////////////////////////////////////////
TEST (SegmentDifferences, Segmentation)
{
  SegmentDifferences<PointXYZ> sd;
  sd.setInputCloud (cloud_);
  sd.setDistanceThreshold (0.00005);

  // Set the target as itself
  sd.setTargetCloud (cloud_);

  PointCloud<PointXYZ> output;
  sd.segment (output);

  EXPECT_EQ ((int)output.points.size (), 0);

  // Set a different target
  sd.setTargetCloud (cloud_t_);
  sd.segment (output);
  EXPECT_EQ ((int)output.points.size (), 126);
  //savePCDFile ("./test/0-t.pcd", output);

  // Reverse
  sd.setInputCloud (cloud_t_);
  sd.setTargetCloud (cloud_);
  sd.segment (output);
  EXPECT_EQ ((int)output.points.size (), 127);
  //savePCDFile ("./test/t-0.pcd", output);
}

//////////////////////////////////////////////////////////////////////////////////////////////
TEST (ExtractPolygonalPrism, Segmentation)
{
  PointCloud<PointXYZ>::Ptr hull (new PointCloud<PointXYZ>);
  hull->points.resize (5);

  for (size_t i = 0; i < hull->points.size (); ++i)
  {
    hull->points[i].x = hull->points[i].y = i;
    hull->points[i].z = 0;
  }

  ExtractPolygonalPrismData<PointXYZ> ex;
  ex.setInputCloud (cloud_);
  ex.setInputPlanarHull (hull);

  PointIndices output;
  ex.segment (output);

  EXPECT_EQ ((int)output.indices.size (), 0);
}

/* ---[ */
int
  main (int argc, char** argv)
{
  if (argc < 3)
  {
    std::cerr << "No test file given. Please download `bun0.pcd` and pass its path to the test." << std::endl;
    std::cerr << "The test needs two files. Please, pass two paths of different pcd files." << std::endl;
    return (-1);
  }

  // Load a standard PCD file from disk
  PointCloud<PointXYZ> cloud, cloud_t, another_cloud;
  if (loadPCDFile (argv[1], cloud) < 0)
  {
    std::cerr << "Failed to read test file. Please download `bun0.pcd` and pass its path to the test." << std::endl;
    return (-1);
  }
  if (pcl::io::loadPCDFile (argv[2], another_cloud) < 0)
  {
    std::cerr << "Failed to read test file. Please download `bun0.pcd` and pass its path to the test." << std::endl;
    return (-1);
  }

  // Tranpose the cloud
  cloud_t = cloud;
  for (size_t i = 0; i < cloud.points.size (); ++i)
    cloud_t.points[i].x += 0.01;

  cloud_   = cloud.makeShared ();
  cloud_t_ = cloud_t.makeShared ();

  another_cloud_ = another_cloud.makeShared();
  normals_ = (new pcl::PointCloud<pcl::Normal>)->makeShared();
  pcl::NormalEstimation<pcl::PointXYZ, pcl::Normal> normal_estimator;
  normal_estimator.setInputCloud(cloud_);
  normal_estimator.setKSearch(30);
  normal_estimator.compute(*normals_);

  another_normals_ = (new pcl::PointCloud<pcl::Normal>)->makeShared();
  normal_estimator.setInputCloud(another_cloud_);
  normal_estimator.setKSearch(30);
  normal_estimator.compute(*another_normals_);

  testing::InitGoogleTest (&argc, argv);
  return (RUN_ALL_TESTS ());
}
/* ]--- */
<|endoftext|>