<commit_before>// Day21.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"

struct Item {
	size_t Price;
	size_t Damage;
	size_t Armor;

	Item(size_t Price, size_t Damage, size_t Armor)
		:Price(Price), Damage(Damage), Armor(Armor)
	{}
};

typedef std::shared_ptr<Item> PItem;
typedef std::vector<PItem> ItemVector;

struct Character;
typedef std::shared_ptr<Character> PCharacter;

struct Character {
	size_t Hitpoints;
	size_t Damage;
	size_t Armor;
	size_t SpendGold;

	Character(PCharacter Other)
		:Hitpoints(Other->Hitpoints), Damage(Other->Damage), Armor(Other->Armor), SpendGold(Other->SpendGold)
	{}

	Character(PCharacter Other, PItem Item)
		:Hitpoints(Other->Hitpoints), Damage(Other->Damage + Item->Damage), Armor(Other->Armor + Item->Armor), SpendGold(Other->SpendGold + Item->Price)
	{}

	Character(size_t Hitpoints)
		:Hitpoints(Hitpoints), Damage(0), Armor(0), SpendGold(0)
	{}

	Character(size_t Hitpoints, size_t Damage, size_t Armor)
		:Hitpoints(Hitpoints), Damage(Damage), Armor(Armor), SpendGold(0)
	{}

	size_t GetDamagePerRound(size_t OthersArmor)
	{
		if (OthersArmor >= Damage)
		{
			return 1;
		}
		else
		{
			return (Damage - OthersArmor);
		}
	}
};

typedef std::function <size_t(PCharacter, bool, bool)> SimpleItemFunction;
typedef std::function <size_t(PCharacter, bool, bool, PItem)> ItemFunction;

static PCharacter LoadBoss(const std::string & FileName);
static bool WouldPlayerWin(PCharacter Player);
static size_t GetLeastAmountToSpendToWin();
static size_t GetMostAmountToSpendToStillLoose();

static size_t ChooseWeapon(PCharacter Player, bool PlayerShallWin, bool MinimizeGold);
static size_t ChooseArmor(PCharacter Player, bool PlayerShallWin, bool MinimizeGold);
static size_t ChooseFirstRing(PCharacter Player, bool PlayerShallWin, bool MinimizeGold);
static size_t ChooseSecondRing(PCharacter Player, bool PlayerShallWin, bool MinimizeGold, const PItem & FirstRing);
static size_t CheckIfPlayerWouldWin(PCharacter Player, bool PlayerShallWin, bool MinimizeGold, const PItem & Item = PItem());

static size_t IterateOverItems(PCharacter Player, bool PlayerShallWin, bool MinimizeGold, const ItemVector & Items, ItemFunction NextFunction, const PItem & InvalidItem = PItem());

static ItemFunction GetSimpleNextFunctionCall(SimpleItemFunction Funtion);

static const ItemVector Weapons({
	std::make_shared<Item>(8,4,0),
	std::make_shared<Item>(10,5,0),
	std::make_shared<Item>(25,6,0),
	std::make_shared<Item>(40,7,0),
	std::make_shared<Item>(74,8,0)
});

static const ItemVector Armor({
	std::make_shared<Item>(13,0,1),
	std::make_shared<Item>(31,0,2),
	std::make_shared<Item>(53,0,3),
	std::make_shared<Item>(75,0,4),
	std::make_shared<Item>(102,0,5),
});

static const ItemVector Rings({
	std::make_shared<Item>(25,1,0),
	std::make_shared<Item>(20,0,1),
	std::make_shared<Item>(40,0,2),
	std::make_shared<Item>(50,2,0),
	std::make_shared<Item>(80,0,3),
	std::make_shared<Item>(100,3,0),
});

static const PCharacter Boss = LoadBoss("Input.txt");

int main()
{
	size_t MinSpendGold = GetLeastAmountToSpendToWin();
	size_t MaxSpendGold = GetMostAmountToSpendToStillLoose();

	std::cout << "Spend Gold (Part One): " << MinSpendGold << std::endl;
	std::cout << "Spend Gold (Part Two): " << MaxSpendGold << std::endl;

	system("pause");

	return 0;
}

static PCharacter LoadBoss(const std::string & FileName)
{
	StringVectorVector Input = GetFileLineParts(FileName);

	return std::make_shared<Character>(std::atoi(Input[0][1].c_str()), std::atoi(Input[1][1].c_str()), std::atoi(Input[2][1].c_str()));
}

static bool WouldPlayerWin(PCharacter Player)
{
	return (Player->GetDamagePerRound(Boss->Armor) >= Boss->GetDamagePerRound(Player->Armor));
}

static size_t GetLeastAmountToSpendToWin()
{
	return ChooseWeapon(std::make_shared<Character>(100), true, true);
}

static size_t GetMostAmountToSpendToStillLoose()
{
	return ChooseWeapon(std::make_shared<Character>(100), false, false);
}

static size_t ChooseWeapon(PCharacter Player, bool PlayerShallWin, bool MinimizeGold)
{
	return IterateOverItems(Player, PlayerShallWin, MinimizeGold, Weapons, GetSimpleNextFunctionCall(ChooseArmor));
}

static size_t ChooseArmor(PCharacter Player, bool PlayerShallWin, bool MinimizeGold)
{
	size_t ResultWithoutArmor = ChooseFirstRing(Player, PlayerShallWin, MinimizeGold);
	size_t ResultWitArmor = IterateOverItems(Player, PlayerShallWin, MinimizeGold, Armor, GetSimpleNextFunctionCall(ChooseFirstRing));

	return (MinimizeGold) ? std::min(ResultWitArmor, ResultWithoutArmor) : std::max(ResultWitArmor, ResultWithoutArmor);
}

static size_t ChooseFirstRing(PCharacter Player, bool PlayerShallWin, bool MinimizeGold)
{
	size_t ResultWithoutAnyRings = CheckIfPlayerWouldWin(Player, PlayerShallWin, MinimizeGold);
	size_t ResultWithRings = IterateOverItems(Player, PlayerShallWin, MinimizeGold, Rings, ChooseSecondRing);

	return (MinimizeGold) ? std::min(ResultWithoutAnyRings, ResultWithRings) : std::max(ResultWithoutAnyRings, ResultWithRings);
}

static size_t ChooseSecondRing(PCharacter Player, bool PlayerShallWin, bool MinimizeGold, const PItem & FirstRing)
{
	size_t ResultWithoutAnyRings = CheckIfPlayerWouldWin(Player, PlayerShallWin, MinimizeGold);
	size_t ResultWithRings = IterateOverItems(Player, PlayerShallWin, MinimizeGold, Rings, CheckIfPlayerWouldWin, FirstRing);

	return (MinimizeGold) ? std::min(ResultWithoutAnyRings, ResultWithRings) : std::max(ResultWithoutAnyRings, ResultWithRings);
}

static size_t CheckIfPlayerWouldWin(PCharacter Player, bool PlayerShallWin, bool MinimizeGold, const PItem & Item)
{
	return (WouldPlayerWin(Player) == PlayerShallWin) ? Player->SpendGold : (MinimizeGold) ? SIZE_MAX : 0;
}

static size_t IterateOverItems(PCharacter Player, bool PlayerShallWin, bool MinimizeGold, const ItemVector & Items, ItemFunction NextFunction, const PItem & InvalidItem)
{
	size_t BestGoldSpend = (MinimizeGold) ? SIZE_MAX : 0;

	for (const PItem & Item : Items)
	{
		if (Item == InvalidItem)
		{
			continue;
		}

		size_t GoldSpend = NextFunction(std::make_shared<Character>(Player, Item), PlayerShallWin, MinimizeGold, Item);

		if ((MinimizeGold && (GoldSpend < BestGoldSpend)) || (!MinimizeGold && (GoldSpend > BestGoldSpend)))
		{
			BestGoldSpend = GoldSpend;
		}
	}

	return BestGoldSpend;
}

static ItemFunction GetSimpleNextFunctionCall(SimpleItemFunction Funtion)
{
	return [Funtion](PCharacter Player, bool PlayerShallWin, bool MinimizeGold, PItem Item)->size_t { return Funtion(Player, PlayerShallWin, MinimizeGold); };
}<commit_msg>Fix Boss Health and Winning Calculation to take different Boss Health into account<commit_after>// Day21.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"

struct Item {
	size_t Price;
	size_t Damage;
	size_t Armor;

	Item(size_t Price, size_t Damage, size_t Armor)
		:Price(Price), Damage(Damage), Armor(Armor)
	{}
};

typedef std::shared_ptr<Item> PItem;
typedef std::vector<PItem> ItemVector;

struct Character;
typedef std::shared_ptr<Character> PCharacter;

struct Character {
	size_t Hitpoints;
	size_t Damage;
	size_t Armor;
	size_t SpendGold;

	Character(PCharacter Other)
		:Hitpoints(Other->Hitpoints), Damage(Other->Damage), Armor(Other->Armor), SpendGold(Other->SpendGold)
	{}

	Character(PCharacter Other, PItem Item)
		:Hitpoints(Other->Hitpoints), Damage(Other->Damage + Item->Damage), Armor(Other->Armor + Item->Armor), SpendGold(Other->SpendGold + Item->Price)
	{}

	Character(size_t Hitpoints)
		:Hitpoints(Hitpoints), Damage(0), Armor(0), SpendGold(0)
	{}

	Character(size_t Hitpoints, size_t Damage, size_t Armor)
		:Hitpoints(Hitpoints), Damage(Damage), Armor(Armor), SpendGold(0)
	{}

	size_t GetDamagePerRound(size_t OthersArmor)
	{
		if (OthersArmor >= Damage)
		{
			return 1;
		}
		else
		{
			return (Damage - OthersArmor);
		}
	}
};

typedef std::function <size_t(PCharacter, bool, bool)> SimpleItemFunction;
typedef std::function <size_t(PCharacter, bool, bool, PItem)> ItemFunction;

static PCharacter LoadBoss(const std::string & FileName);
static bool WouldPlayerWin(PCharacter Player);
static size_t GetLeastAmountToSpendToWin();
static size_t GetMostAmountToSpendToStillLoose();

static size_t ChooseWeapon(PCharacter Player, bool PlayerShallWin, bool MinimizeGold);
static size_t ChooseArmor(PCharacter Player, bool PlayerShallWin, bool MinimizeGold);
static size_t ChooseFirstRing(PCharacter Player, bool PlayerShallWin, bool MinimizeGold);
static size_t ChooseSecondRing(PCharacter Player, bool PlayerShallWin, bool MinimizeGold, const PItem & FirstRing);
static size_t CheckIfPlayerWouldWin(PCharacter Player, bool PlayerShallWin, bool MinimizeGold, const PItem & Item = PItem());

static size_t IterateOverItems(PCharacter Player, bool PlayerShallWin, bool MinimizeGold, const ItemVector & Items, ItemFunction NextFunction, const PItem & InvalidItem = PItem());

static ItemFunction GetSimpleNextFunctionCall(SimpleItemFunction Funtion);

static const ItemVector Weapons({
	std::make_shared<Item>(8,4,0),
	std::make_shared<Item>(10,5,0),
	std::make_shared<Item>(25,6,0),
	std::make_shared<Item>(40,7,0),
	std::make_shared<Item>(74,8,0)
});

static const ItemVector Armor({
	std::make_shared<Item>(13,0,1),
	std::make_shared<Item>(31,0,2),
	std::make_shared<Item>(53,0,3),
	std::make_shared<Item>(75,0,4),
	std::make_shared<Item>(102,0,5),
});

static const ItemVector Rings({
	std::make_shared<Item>(25,1,0),
	std::make_shared<Item>(20,0,1),
	std::make_shared<Item>(40,0,2),
	std::make_shared<Item>(50,2,0),
	std::make_shared<Item>(80,0,3),
	std::make_shared<Item>(100,3,0),
});

static const PCharacter Boss = LoadBoss("Input.txt");

int main()
{
	size_t MinSpendGold = GetLeastAmountToSpendToWin();
	size_t MaxSpendGold = GetMostAmountToSpendToStillLoose();

	std::cout << "Spend Gold (Part One): " << MinSpendGold << std::endl;
	std::cout << "Spend Gold (Part Two): " << MaxSpendGold << std::endl;

	system("pause");

	return 0;
}

static PCharacter LoadBoss(const std::string & FileName)
{
	StringVectorVector Input = GetFileLineParts(FileName);

	return std::make_shared<Character>(std::atoi(Input[0][2].c_str()), std::atoi(Input[1][1].c_str()), std::atoi(Input[2][1].c_str()));
}

static bool WouldPlayerWin(PCharacter Player)
{
	size_t PlayerRoundsToKillBoss = ((Boss->Hitpoints - 1) / Player->GetDamagePerRound(Boss->Armor)) + 1;
	size_t BossRoundsToKillPlayer = ((Player->Hitpoints - 1) / Boss->GetDamagePerRound(Player->Armor)) + 1;

	return (PlayerRoundsToKillBoss <= BossRoundsToKillPlayer);
}

static size_t GetLeastAmountToSpendToWin()
{
	return ChooseWeapon(std::make_shared<Character>(100), true, true);
}

static size_t GetMostAmountToSpendToStillLoose()
{
	return ChooseWeapon(std::make_shared<Character>(100), false, false);
}

static size_t ChooseWeapon(PCharacter Player, bool PlayerShallWin, bool MinimizeGold)
{
	return IterateOverItems(Player, PlayerShallWin, MinimizeGold, Weapons, GetSimpleNextFunctionCall(ChooseArmor));
}

static size_t ChooseArmor(PCharacter Player, bool PlayerShallWin, bool MinimizeGold)
{
	size_t ResultWithoutArmor = ChooseFirstRing(Player, PlayerShallWin, MinimizeGold);
	size_t ResultWitArmor = IterateOverItems(Player, PlayerShallWin, MinimizeGold, Armor, GetSimpleNextFunctionCall(ChooseFirstRing));

	return (MinimizeGold) ? std::min(ResultWitArmor, ResultWithoutArmor) : std::max(ResultWitArmor, ResultWithoutArmor);
}

static size_t ChooseFirstRing(PCharacter Player, bool PlayerShallWin, bool MinimizeGold)
{
	size_t ResultWithoutAnyRings = CheckIfPlayerWouldWin(Player, PlayerShallWin, MinimizeGold);
	size_t ResultWithRings = IterateOverItems(Player, PlayerShallWin, MinimizeGold, Rings, ChooseSecondRing);

	return (MinimizeGold) ? std::min(ResultWithoutAnyRings, ResultWithRings) : std::max(ResultWithoutAnyRings, ResultWithRings);
}

static size_t ChooseSecondRing(PCharacter Player, bool PlayerShallWin, bool MinimizeGold, const PItem & FirstRing)
{
	size_t ResultWithoutAnyRings = CheckIfPlayerWouldWin(Player, PlayerShallWin, MinimizeGold);
	size_t ResultWithRings = IterateOverItems(Player, PlayerShallWin, MinimizeGold, Rings, CheckIfPlayerWouldWin, FirstRing);

	return (MinimizeGold) ? std::min(ResultWithoutAnyRings, ResultWithRings) : std::max(ResultWithoutAnyRings, ResultWithRings);
}

static size_t CheckIfPlayerWouldWin(PCharacter Player, bool PlayerShallWin, bool MinimizeGold, const PItem & Item)
{
	return (WouldPlayerWin(Player) == PlayerShallWin) ? Player->SpendGold : (MinimizeGold) ? SIZE_MAX : 0;
}

static size_t IterateOverItems(PCharacter Player, bool PlayerShallWin, bool MinimizeGold, const ItemVector & Items, ItemFunction NextFunction, const PItem & InvalidItem)
{
	size_t BestGoldSpend = (MinimizeGold) ? SIZE_MAX : 0;

	for (const PItem & Item : Items)
	{
		if (Item == InvalidItem)
		{
			continue;
		}

		size_t GoldSpend = NextFunction(std::make_shared<Character>(Player, Item), PlayerShallWin, MinimizeGold, Item);

		if ((MinimizeGold && (GoldSpend < BestGoldSpend)) || (!MinimizeGold && (GoldSpend > BestGoldSpend)))
		{
			BestGoldSpend = GoldSpend;
		}
	}

	return BestGoldSpend;
}

static ItemFunction GetSimpleNextFunctionCall(SimpleItemFunction Funtion)
{
	return [Funtion](PCharacter Player, bool PlayerShallWin, bool MinimizeGold, PItem Item)->size_t { return Funtion(Player, PlayerShallWin, MinimizeGold); };
}<|endoftext|>


<commit_before>#include "cute.h"
#include "test_Box.h"

#include <vector>
#include <algorithm>
#include "Kugel.h"
#include "MatVec.h"

template<unsigned DIM>
class Box {
	typedef boost::units::quantity< boost::units::si::length , double > lengthT;
	typedef boost::units::quantity< boost::units::si::velocity , double > velocityT;
	typedef boost::units::quantity< boost::units::si::mass , double > massT;
	typedef boost::units::quantity< boost::units::si::energy , double > energyT;
	typedef boost::units::quantity< boost::units::si::time , double > timeT;

	timeT m_time;
	std::vector<Kugel<DIM>> vec_kugel;
	MatVec<lengthT, DIM> vec_abmessung;

	void wrap_one(Kugel<DIM>& kugel) {
		auto pos = kugel.position();
		lengthT null{};
		quantity<dimensionless,int> factor{0};

		for (unsigned i=0; i<DIM; ++i) {
			factor = static_cast<quantity<dimensionless,int> > (pos[i] / vec_abmessung[i]);
			pos[i] -= vec_abmessung[i] * factor;
			if ( pos[i] < null )
				pos[i] += vec_abmessung[i];
		}
		kugel.position(pos);
	}

public:
	timeT time() const { return m_time; }

	void fast_forward(const timeT& dt) {
		m_time += dt;
		for (auto& kugel : vec_kugel) {
			kugel.fast_forward(dt);
			wrap_one(kugel);
		}
	}

	void wrap() {
		for (auto& kugel : vec_kugel) wrap_one(kugel);
	}

	Box(const MatVec<lengthT, DIM>& dim, unsigned size, const Kugel<DIM>& kugel)
		: m_time{},vec_kugel(size, kugel), vec_abmessung{dim} {}
	Box(const MatVec<lengthT, DIM>& dim, unsigned size)
		: m_time{}, vec_kugel(size), vec_abmessung{dim} {}
	Box(const MatVec<lengthT, DIM>& dim)
			: Box{dim,0} {}

	const Kugel<DIM>& operator [](unsigned i) const {
		return vec_kugel[i];
	}

	Kugel<DIM>& operator [](unsigned i) {
		return vec_kugel[i];
	}

	auto size() const -> decltype( vec_kugel.size() ){
		return vec_kugel.size();
	}

	auto abmessung() const -> decltype( vec_abmessung ) {
		return vec_abmessung;
	}

	void add(const Box<DIM>& other) {
		if ( vec_abmessung != other.vec_abmessung )
			return;
		vec_kugel.insert(vec_kugel.end(),
				other.vec_kugel.begin(), other.vec_kugel.end() );
	}

};

const length m = meter;
const force N = newton;
const velocity mps = meters_per_second;
typedef quantity<length> lengthT;
typedef quantity<force> forceT;
typedef quantity<velocity> velocityT;

const MatVec<lengthT, 3> box_dimension{1*m,2*m,3*m};

void emptyBox() {
	Box<3> box { box_dimension };
	ASSERTM("", box.size() == 0 );
}

void boxSize10() {
	Box<3> box { box_dimension, 10 };
	ASSERTM("", box.size() == 10 );
}

void boxAbmessung() {
	Box<3> box { box_dimension };
	ASSERTM("", box.abmessung() == box_dimension);
}

void addBoxSize() {
	unsigned s1 { 10 }, s2 { 15 };
	Box<3> box1{box_dimension, s1}, box2{box_dimension, s2};
	box1.add(box2);
	ASSERTM("", box1.size() == s1 + s2);
}

void randomAccess_read(){
	Kugel<3> k{1 * kilogram, 1 * m};
	Box<3> box{box_dimension,10,k};

	ASSERTM("", box[3] == k);
}

void randomAccess_constRead(){
	Kugel<3> k{1 * kilogram, 1 * m};
	const Box<3> box{box_dimension,10,k};

	ASSERTM("", box[3] == k);
}

void randomAccess_write(){
	Kugel<3> k1{1 * kilogram, 1 * m}, k2{2 * kilogram, 2*m};
	Box<3> box{box_dimension,10, k1};

	box[3]=k2;
	ASSERTM("", ( box[3] == k2 && box[0] == k1) );
}

// Geht wahrscheinlich wegen Rundung nicht
void wrapPosition() {
	Box<3> box{box_dimension,1};
	MatVec<lengthT,3> pos{-.5*m, -2.3*m, 6.7*m}, res_pos{.5*m, 1.7*m, .7*m};

	box[0].position(pos);
	box.wrap();
	std::cout << box[0].position() << '\n' << res_pos << '\n';
	ASSERTM("", !( box[0].position() == res_pos ) );
}

void box_fastForward_pos() {
	Kugel<3> k{};
	MatVec<velocityT,3> vel{.2*mps,3*mps,1*mps};
	MatVec<lengthT,3> res_pos{.6*m,1*m,0*m}; //res_pos{3*m,6*m,9*m};

	k.velocity(vel);
	Box<3> box{box_dimension,1,k};

	box.fast_forward(3*second);
	std::cout << box[0].position() << '\n' << res_pos << '\n';
	ASSERTM("", !( box[0].position() == res_pos ) );
}

void box_fastForward_time() {
	Kugel<3> k{};
	MatVec<velocityT,3> vel{.2*mps,3*mps,1*mps};
	MatVec<lengthT,3> res_pos{.6*m,1*m,0*m}; //res_pos{3*m,6*m,9*m};

	k.velocity(vel);
	Box<3> box{box_dimension,1,k};

	auto dt = 3. * second;
	box.fast_forward(dt);
	ASSERTM("", box.time() == dt );
}

cute::suite make_suite_Box(){
	cute::suite s;
	s.push_back(CUTE(emptyBox));
	s.push_back(CUTE(boxSize10));
	s.push_back(CUTE(boxAbmessung));
	s.push_back(CUTE(addBoxSize));
	s.push_back(CUTE(randomAccess_read));
	s.push_back(CUTE(randomAccess_constRead));
	s.push_back(CUTE(randomAccess_write));
	s.push_back(CUTE(wrapPosition));
	s.push_back(CUTE(box_fastForward_pos));
	s.push_back(CUTE(box_fastForward_time));
	return s;
}
<commit_msg>wrap bei Initiierung<commit_after>#include "cute.h"
#include "test_Box.h"

#include <vector>
#include <algorithm>
#include "Kugel.h"
#include "MatVec.h"

template<unsigned DIM>
class Box {
	typedef boost::units::quantity< boost::units::si::length , double > lengthT;
	typedef boost::units::quantity< boost::units::si::velocity , double > velocityT;
	typedef boost::units::quantity< boost::units::si::mass , double > massT;
	typedef boost::units::quantity< boost::units::si::energy , double > energyT;
	typedef boost::units::quantity< boost::units::si::time , double > timeT;

	timeT m_time;
	std::vector<Kugel<DIM>> vec_kugel;
	MatVec<lengthT, DIM> vec_abmessung;

	void wrap_one(Kugel<DIM>& kugel) {
		auto pos = kugel.position();
		lengthT null{};
		quantity<dimensionless,int> factor{0};

		for (unsigned i=0; i<DIM; ++i) {
			factor = static_cast<quantity<dimensionless,int> > (pos[i] / vec_abmessung[i]);
			pos[i] -= vec_abmessung[i] * factor;
			if ( pos[i] < null )
				pos[i] += vec_abmessung[i];
		}
		kugel.position(pos);
	}

public:
	timeT time() const { return m_time; }

	void fast_forward(const timeT& dt) {
		m_time += dt;
		for (auto& kugel : vec_kugel) {
			kugel.fast_forward(dt);
			wrap_one(kugel);
		}
	}

	void wrap() {
		for (auto& kugel : vec_kugel) wrap_one(kugel);
	}

	Box(const MatVec<lengthT, DIM>& dim, unsigned size, const Kugel<DIM>& kugel)
		: m_time{},vec_kugel(size, kugel), vec_abmessung{dim} { wrap(); }
	Box(const MatVec<lengthT, DIM>& dim, unsigned size)
		: m_time{}, vec_kugel(size), vec_abmessung{dim} {}
	Box(const MatVec<lengthT, DIM>& dim)
			: Box{dim,0} {}

	const Kugel<DIM>& operator [](unsigned i) const {
		return vec_kugel[i];
	}

	Kugel<DIM>& operator [](unsigned i) {
		return vec_kugel[i];
	}

	auto size() const -> decltype( vec_kugel.size() ){
		return vec_kugel.size();
	}

	auto abmessung() const -> decltype( vec_abmessung ) {
		return vec_abmessung;
	}

	void add(const Box<DIM>& other) {
		if ( vec_abmessung != other.vec_abmessung )
			return;
		vec_kugel.insert(vec_kugel.end(),
				other.vec_kugel.begin(), other.vec_kugel.end() );
	}

};

const length m = meter;
const force N = newton;
const velocity mps = meters_per_second;
typedef quantity<length> lengthT;
typedef quantity<force> forceT;
typedef quantity<velocity> velocityT;

const MatVec<lengthT, 3> box_dimension{1*m,2*m,3*m};

void emptyBox() {
	Box<3> box { box_dimension };
	ASSERTM("", box.size() == 0 );
}

void boxSize10() {
	Box<3> box { box_dimension, 10 };
	ASSERTM("", box.size() == 10 );
}

void boxAbmessung() {
	Box<3> box { box_dimension };
	ASSERTM("", box.abmessung() == box_dimension);
}

void addBoxSize() {
	unsigned s1 { 10 }, s2 { 15 };
	Box<3> box1{box_dimension, s1}, box2{box_dimension, s2};
	box1.add(box2);
	ASSERTM("", box1.size() == s1 + s2);
}

void randomAccess_read(){
	Kugel<3> k{1 * kilogram, 1 * m};
	Box<3> box{box_dimension,10,k};

	ASSERTM("", box[3] == k);
}

void randomAccess_constRead(){
	Kugel<3> k{1 * kilogram, 1 * m};
	const Box<3> box{box_dimension,10,k};

	ASSERTM("", box[3] == k);
}

void randomAccess_write(){
	Kugel<3> k1{1 * kilogram, 1 * m}, k2{2 * kilogram, 2*m};
	Box<3> box{box_dimension,10, k1};

	box[3]=k2;
	ASSERTM("", ( box[3] == k2 && box[0] == k1) );
}

// Geht wahrscheinlich wegen Rundung nicht
void wrapPosition() {
	Box<3> box{box_dimension,1};
	MatVec<lengthT,3> pos{-.5*m, -2.3*m, 6.7*m}, res_pos{.5*m, 1.7*m, .7*m};

	box[0].position(pos);
	box.wrap();
	std::cout << box[0].position() << '\n' << res_pos << '\n';
	ASSERTM("", !( box[0].position() == res_pos ) );
}

void box_fastForward_pos() {
	Kugel<3> k{};
	MatVec<velocityT,3> vel{.2*mps,3*mps,1*mps};
	MatVec<lengthT,3> res_pos{.6*m,1*m,0*m}; //res_pos{3*m,6*m,9*m};

	k.velocity(vel);
	Box<3> box{box_dimension,1,k};

	box.fast_forward(3*second);
	std::cout << box[0].position() << '\n' << res_pos << '\n';
	ASSERTM("", !( box[0].position() == res_pos ) );
}

void box_fastForward_time() {
	Kugel<3> k{};
	MatVec<velocityT,3> vel{.2*mps,3*mps,1*mps};
	MatVec<lengthT,3> res_pos{.6*m,1*m,0*m}; //res_pos{3*m,6*m,9*m};

	k.velocity(vel);
	Box<3> box{box_dimension,1,k};

	auto dt = 3. * second;
	box.fast_forward(dt);
	ASSERTM("", box.time() == dt );
}

cute::suite make_suite_Box(){
	cute::suite s;
	s.push_back(CUTE(emptyBox));
	s.push_back(CUTE(boxSize10));
	s.push_back(CUTE(boxAbmessung));
	s.push_back(CUTE(addBoxSize));
	s.push_back(CUTE(randomAccess_read));
	s.push_back(CUTE(randomAccess_constRead));
	s.push_back(CUTE(randomAccess_write));
	s.push_back(CUTE(wrapPosition));
	s.push_back(CUTE(box_fastForward_pos));
	s.push_back(CUTE(box_fastForward_time));
	return s;
}
<|endoftext|>


<commit_before>/*
  Copyright (C) 2005-2019 Steven L. Scott

  This library is free software; you can redistribute it and/or modify it under
  the terms of the GNU Lesser General Public License as published by the Free
  Software Foundation; either version 2.1 of the License, or (at your option)
  any later version.

  This library is distributed in the hope that it will be useful, but WITHOUT
  ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
  FOR A PARTICULAR PURPOSE.  See the GNU Lesser General Public License for more
  details.

  You should have received a copy of the GNU Lesser General Public License along
  with this library; if not, write to the Free Software Foundation, Inc., 51
  Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
*/

#include "Models/ExponentialIncrementModel.hpp"
#include "distributions.hpp"

namespace BOOM {

  namespace {
    using EIM = ExponentialIncrementModel;
  }

  EIM::ExponentialIncrementModel(const Vector &increment_rates)
  {
    for (int i = 0; i < increment_rates.size(); ++i) {
      add_increment_model(new ExponentialModel(increment_rates[i]));
    }
  }

  EIM::ExponentialIncrementModel(
      const std::vector<Ptr<ExponentialModel>> &increment_models)
  {
    for (const auto &m : increment_models) {
      add_increment_model(m);
    }
  }

  EIM::ExponentialIncrementModel(const EIM &rhs)
      : Model(rhs),
        VectorModel(rhs),
        CompositeParamPolicy(rhs),
        DataPolicy(rhs),
        PriorPolicy(rhs)
  {
    for (int i = 0; i < rhs.models_.size(); ++i) {
      add_increment_model(rhs.models_[i]->clone());
    }
  }

  EIM & EIM::operator=(const EIM &rhs) {
    if (&rhs != this) {
      Model::operator=(rhs);
      ParamPolicy::operator=(rhs);
      DataPolicy::operator=(rhs);
      PriorPolicy::operator=(rhs);
      ParamPolicy::clear();
      models_.clear();
      for (const auto &m : rhs.models_) {
        add_increment_model(m->clone());
      }
    }
    return *this;
  }

  EIM & EIM::operator=(EIM &&rhs) {
    if (&rhs != this) {
      Model::operator=(rhs);
      VectorModel::operator=(rhs);
      ParamPolicy::operator=(rhs);
      DataPolicy::operator=(rhs);
      PriorPolicy::operator=(rhs);
      models_ = std::move(rhs.models_);
    }
    return *this;
  }

  EIM * EIM::clone() const {return new EIM(*this);}

  void EIM::add_increment_model(const Ptr<ExponentialModel> &m) {
    models_.push_back(m);
    ParamPolicy::add_model(m);
  }

  double EIM::logp(const Vector &x) const {
    if (x.size() != 1 + models_.size()) {
      return negative_infinity();
    }
    double ans = 0;
    for (int i = 0; i < models_.size(); ++i) {
      ans += models_[i]->logp(x[i + 1] - x[i]);
    }
    return ans;
  }

  Vector EIM::sim(RNG &rng) const {
    Vector ans;
    ans.reserve(models_.size() + 1);
    ans.push_back(0);
    for (int i = 0; i < models_.size(); ++i) {
      ans.push_back(ans.back() + models_[i]->sim(rng));
    }
    return ans;
  }

}
<commit_msg>Model now assumes initial difference is relative to 0.<commit_after>/*
  Copyright (C) 2005-2019 Steven L. Scott

  This library is free software; you can redistribute it and/or modify it under
  the terms of the GNU Lesser General Public License as published by the Free
  Software Foundation; either version 2.1 of the License, or (at your option)
  any later version.

  This library is distributed in the hope that it will be useful, but WITHOUT
  ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
  FOR A PARTICULAR PURPOSE.  See the GNU Lesser General Public License for more
  details.

  You should have received a copy of the GNU Lesser General Public License along
  with this library; if not, write to the Free Software Foundation, Inc., 51
  Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
*/

#include "Models/ExponentialIncrementModel.hpp"
#include "distributions.hpp"

namespace BOOM {

  namespace {
    using EIM = ExponentialIncrementModel;
  }

  EIM::ExponentialIncrementModel(const Vector &increment_rates)
  {
    for (int i = 0; i < increment_rates.size(); ++i) {
      add_increment_model(new ExponentialModel(increment_rates[i]));
    }
  }

  EIM::ExponentialIncrementModel(
      const std::vector<Ptr<ExponentialModel>> &increment_models)
  {
    for (const auto &m : increment_models) {
      add_increment_model(m);
    }
  }

  EIM::ExponentialIncrementModel(const EIM &rhs)
      : Model(rhs),
        VectorModel(rhs),
        CompositeParamPolicy(rhs),
        DataPolicy(rhs),
        PriorPolicy(rhs)
  {
    for (int i = 0; i < rhs.models_.size(); ++i) {
      add_increment_model(rhs.models_[i]->clone());
    }
  }

  EIM & EIM::operator=(const EIM &rhs) {
    if (&rhs != this) {
      Model::operator=(rhs);
      ParamPolicy::operator=(rhs);
      DataPolicy::operator=(rhs);
      PriorPolicy::operator=(rhs);
      ParamPolicy::clear();
      models_.clear();
      for (const auto &m : rhs.models_) {
        add_increment_model(m->clone());
      }
    }
    return *this;
  }

  EIM & EIM::operator=(EIM &&rhs) {
    if (&rhs != this) {
      Model::operator=(rhs);
      VectorModel::operator=(rhs);
      ParamPolicy::operator=(rhs);
      DataPolicy::operator=(rhs);
      PriorPolicy::operator=(rhs);
      models_ = std::move(rhs.models_);
    }
    return *this;
  }

  EIM * EIM::clone() const {return new EIM(*this);}

  void EIM::add_increment_model(const Ptr<ExponentialModel> &m) {
    models_.push_back(m);
    ParamPolicy::add_model(m);
  }

  double EIM::logp(const Vector &x) const {
    if (x.size() != models_.size()) {
      return negative_infinity();
    }
    double ans = 0;
    for (int i = 0; i < models_.size(); ++i) {
      double dx = (i == 0) ? x[0] : x[i] - x[i - 1];
      ans += models_[i]->logp(dx);
    }
    return ans;
  }

  Vector EIM::sim(RNG &rng) const {
    Vector ans;
    ans.reserve(models_.size() + 1);
    ans.push_back(0);
    for (int i = 0; i < models_.size(); ++i) {
      ans.push_back(ans.back() + models_[i]->sim(rng));
    }
    return ans;
  }

}
<|endoftext|>


<commit_before>/*===================================================================

The Medical Imaging Interaction Toolkit (MITK)

Copyright (c) German Cancer Research Center,
Division of Medical and Biological Informatics.
All rights reserved.

This software is distributed WITHOUT ANY WARRANTY; without
even the implied warranty of MERCHANTABILITY or FITNESS FOR
A PARTICULAR PURPOSE.

See LICENSE.txt or http://www.mitk.org for details.

===================================================================*/

#include "mitkRTDoseReader.h"

#include <mitkIOUtil.h>
#include <mitkDataNodeFactory.h>
#include <mitkImagePixelWriteAccessor.h>
#include <mitkImageAccessByItk.h>
#include <itkImageIterator.h>
#include <itkImageRegionIterator.h>

#include <DataStructures/mitkRTConstants.h>

namespace mitk
{

  RTDoseReader::RTDoseReader(){}

  RTDoseReader::~RTDoseReader(){}

  mitk::DataNode::Pointer RTDoseReader::
      LoadRTDose(const char* filename)
  {
    DcmFileFormat fileformat;
    OFCondition outp = fileformat.loadFile(filename, EXS_Unknown);
    if(outp.bad())
    {
      MITK_ERROR << "Cant read the file" << endl;
    }
    DcmDataset *dataset = fileformat.getDataset();

    std::string name = filename;
    itk::FilenamesContainer file;
    file.push_back(name);

    mitk::DicomSeriesReader* reader = new mitk::DicomSeriesReader;

    mitk::DataNode::Pointer originalNode = reader->LoadDicomSeries(file,false);

    if(originalNode.IsNull())
    {
      MITK_ERROR << "Error reading the dcm file" << endl;
      return 0;
    }

    mitk::Image::Pointer originalImage
        = dynamic_cast<mitk::Image*>(originalNode->GetData());

    DRTDoseIOD doseObject;
    OFCondition result = doseObject.read(*dataset);

    if(result.bad())
    {
      MITK_ERROR << "Error reading the Dataset" << endl;
      return 0;
    }

    OFString gridScaling;
    Float32 gridscale;

    doseObject.getDoseGridScaling(gridScaling);
    gridscale = OFStandard::atof(gridScaling.c_str());

    AccessByItk_1(originalImage, MultiplayGridScaling, gridscale);

    double prescripeDose = this->GetMaxDoseValue(dataset);

    originalNode->SetName("RT Dose");
    originalNode->SetFloatProperty(mitk::Constants::PRESCRIBED_DOSE_PROPERTY_NAME.c_str(),prescripeDose);
    originalNode->SetFloatProperty(mitk::Constants::REFERENCE_DOSE_PROPERTY_NAME.c_str(), 40);
    originalNode->SetBoolProperty(mitk::Constants::DOSE_PROPERTY_NAME.c_str(),true);
    return originalNode;
  }

  template<typename TPixel, unsigned int VImageDimension>
  void RTDoseReader::MultiplayGridScaling(itk::Image<TPixel,
                                           VImageDimension>* image,
                                           Float32 gridscale)
  {
    typedef itk::Image<TPixel, VImageDimension> InputImageType;
    itk::ImageRegionIterator<InputImageType> it(image,
                                                image->GetRequestedRegion());
    for(it=it.Begin(); !it.IsAtEnd(); ++it)
    {
      it.Set(it.Get()*gridscale);
    }
  }

  double RTDoseReader::GetMaxDoseValue(DcmDataset* dataSet)
  {
    DRTDoseIOD doseObject;
    OFCondition result = doseObject.read(*dataSet);
    if(result.bad())
    {
      MITK_ERROR << "Error reading the RT Dose dataset" << endl;
      return 0;
    }

    Uint16 rows, columns, frames;
    OFString nrframes, gridScaling;
    const Uint16 *pixelData = NULL;
    Float32 gridscale;

    Uint16 &rows_ref = rows;
    Uint16 &columns_ref = columns;

    doseObject.getRows(rows_ref);
    doseObject.getColumns(columns_ref);
    doseObject.getNumberOfFrames(nrframes);
    doseObject.getDoseGridScaling(gridScaling);

    frames = atoi(nrframes.c_str());
    gridscale = OFStandard::atof(gridScaling.c_str());
    dataSet->findAndGetUint16Array(DCM_PixelData, pixelData, 0);

    int size = columns*rows*frames;
    double highest = 0;

    for(int i=0; i<size; ++i)
    {
      if((pixelData[i]*gridscale)>highest)
      {
        highest = pixelData[i] * gridscale;
      }
    }

    return highest;
  }

}
<commit_msg>COMP = added the std namespace before endl<commit_after>/*===================================================================

The Medical Imaging Interaction Toolkit (MITK)

Copyright (c) German Cancer Research Center,
Division of Medical and Biological Informatics.
All rights reserved.

This software is distributed WITHOUT ANY WARRANTY; without
even the implied warranty of MERCHANTABILITY or FITNESS FOR
A PARTICULAR PURPOSE.

See LICENSE.txt or http://www.mitk.org for details.

===================================================================*/

#include "mitkRTDoseReader.h"

#include <mitkIOUtil.h>
#include <mitkDataNodeFactory.h>
#include <mitkImagePixelWriteAccessor.h>
#include <mitkImageAccessByItk.h>
#include <itkImageIterator.h>
#include <itkImageRegionIterator.h>

#include <DataStructures/mitkRTConstants.h>

namespace mitk
{

  RTDoseReader::RTDoseReader(){}

  RTDoseReader::~RTDoseReader(){}

  mitk::DataNode::Pointer RTDoseReader::
      LoadRTDose(const char* filename)
  {
    DcmFileFormat fileformat;
    OFCondition outp = fileformat.loadFile(filename, EXS_Unknown);
    if(outp.bad())
    {
      MITK_ERROR << "Cant read the file" << std::endl;
    }
    DcmDataset *dataset = fileformat.getDataset();

    std::string name = filename;
    itk::FilenamesContainer file;
    file.push_back(name);

    mitk::DicomSeriesReader* reader = new mitk::DicomSeriesReader;

    mitk::DataNode::Pointer originalNode = reader->LoadDicomSeries(file,false);

    if(originalNode.IsNull())
    {
      MITK_ERROR << "Error reading the dcm file" << std::endl;
      return 0;
    }

    mitk::Image::Pointer originalImage
        = dynamic_cast<mitk::Image*>(originalNode->GetData());

    DRTDoseIOD doseObject;
    OFCondition result = doseObject.read(*dataset);

    if(result.bad())
    {
      MITK_ERROR << "Error reading the Dataset" << std::endl;
      return 0;
    }

    OFString gridScaling;
    Float32 gridscale;

    doseObject.getDoseGridScaling(gridScaling);
    gridscale = OFStandard::atof(gridScaling.c_str());

    AccessByItk_1(originalImage, MultiplayGridScaling, gridscale);

    double prescripeDose = this->GetMaxDoseValue(dataset);

    originalNode->SetName("RT Dose");
    originalNode->SetFloatProperty(mitk::Constants::PRESCRIBED_DOSE_PROPERTY_NAME.c_str(),prescripeDose);
    originalNode->SetFloatProperty(mitk::Constants::REFERENCE_DOSE_PROPERTY_NAME.c_str(), 40);
    originalNode->SetBoolProperty(mitk::Constants::DOSE_PROPERTY_NAME.c_str(),true);
    return originalNode;
  }

  template<typename TPixel, unsigned int VImageDimension>
  void RTDoseReader::MultiplayGridScaling(itk::Image<TPixel,
                                           VImageDimension>* image,
                                           Float32 gridscale)
  {
    typedef itk::Image<TPixel, VImageDimension> InputImageType;
    itk::ImageRegionIterator<InputImageType> it(image,
                                                image->GetRequestedRegion());
    for(it=it.Begin(); !it.IsAtEnd(); ++it)
    {
      it.Set(it.Get()*gridscale);
    }
  }

  double RTDoseReader::GetMaxDoseValue(DcmDataset* dataSet)
  {
    DRTDoseIOD doseObject;
    OFCondition result = doseObject.read(*dataSet);
    if(result.bad())
    {
      MITK_ERROR << "Error reading the RT Dose dataset" << std::endl;
      return 0;
    }

    Uint16 rows, columns, frames;
    OFString nrframes, gridScaling;
    const Uint16 *pixelData = NULL;
    Float32 gridscale;

    Uint16 &rows_ref = rows;
    Uint16 &columns_ref = columns;

    doseObject.getRows(rows_ref);
    doseObject.getColumns(columns_ref);
    doseObject.getNumberOfFrames(nrframes);
    doseObject.getDoseGridScaling(gridScaling);

    frames = atoi(nrframes.c_str());
    gridscale = OFStandard::atof(gridScaling.c_str());
    dataSet->findAndGetUint16Array(DCM_PixelData, pixelData, 0);

    int size = columns*rows*frames;
    double highest = 0;

    for(int i=0; i<size; ++i)
    {
      if((pixelData[i]*gridscale)>highest)
      {
        highest = pixelData[i] * gridscale;
      }
    }

    return highest;
  }

}
<|endoftext|>


<commit_before>#include <thread>
#include "NFCHttpServer.h"

bool NFCHttpServer::Execute()
{
    if (mxBase)
    {
        event_base_loop(mxBase, EVLOOP_ONCE | EVLOOP_NONBLOCK);
    }

    return true;
}

int NFCHttpServer::InitServer(const unsigned short port)
{
	/*
    event_init();
    struct evhttp *httpserv = evhttp_start(addr,port);
	evhttp_set_gencb(httpserv, reqHandler,NULL);
	event_dispatch();
	*/

    //struct event_base *base;
    struct evhttp* http;
    struct evhttp_bound_socket* handle;

#if NF_PLATFORM == NF_PLATFORM_WIN
    WSADATA WSAData;
    WSAStartup(0x101, &WSAData);
#else
    if (signal(SIGPIPE, SIG_IGN) == SIG_ERR)
        return (1);
#endif

    mxBase = event_base_new();
    if (!mxBase)
    {
        std::cout << "create event_base fail" << std::endl;;
        return 1;
    }

    http = evhttp_new(mxBase);
    if (!http)
    {
        std::cout << "create evhttp fail" << std::endl;;
        return 1;
    }

    handle = evhttp_bind_socket_with_handle(http, "0.0.0.0", port);
    if (!handle)
    {
        std::cout << "bind port :" << port << " fail" << std::endl;;
        return 1;
    }

    evhttp_set_gencb(http, listener_cb, (void*) this);

    return 0;
}

void NFCHttpServer::listener_cb(struct evhttp_request* req, void* arg)
{
	NFCHttpServer* pNet = (NFCHttpServer*)arg;
	NFHttpRequest* pRequest = pNet->AllowHttpRequest();

	pRequest->req = req;

	//headers
	struct evkeyvalq * header = evhttp_request_get_input_headers(req);
	struct evkeyval* kv = header->tqh_first;
	while (kv)
	{
		pRequest->headers.insert(std::map<std::string, std::string>::value_type(kv->key, kv->value));

		kv = kv->next.tqe_next;
	}

	//uri
	const char* uri = evhttp_request_get_uri(req);
	pRequest->url = uri;
	pRequest->remoteHost = evhttp_request_get_host(req);
	pRequest->type = (NFHttpType)evhttp_request_get_command(req);

	//get decodeUri
	struct evhttp_uri* decoded = evhttp_uri_parse(uri);
	if (!decoded)
	{
		std::cout << "It's not a good URI. Sending BADREQUEST" << std::endl;
		evhttp_send_error(req, HTTP_BADREQUEST, 0);

		pNet->mxHttpRequestPool.push_back(pRequest);

		return;
	}

	//path
	pRequest->path = evhttp_uri_get_path(decoded);
	evhttp_uri_free(decoded);

	//std::cout << "Got a GET request:" << uri << std::endl;
	if (evhttp_request_get_command(req) == evhttp_cmd_type::EVHTTP_REQ_GET)
	{
		//OnGetProcess(request, );
		std::cout << "EVHTTP_REQ_GET" << std::endl;

		struct evkeyvalq params;
		evhttp_parse_query(uri, &params);
		struct evkeyval* kv = params.tqh_first;
		while (kv)
		{
			pRequest->params.insert(std::map<std::string, std::string>::value_type(kv->key, kv->value));

			kv = kv->next.tqe_next;
		}
	}

	struct evbuffer *in_evb = evhttp_request_get_input_buffer(req);
	size_t len = evbuffer_get_length(in_evb);
	if (len > 0)
	{
		unsigned char *pData = evbuffer_pullup(in_evb, len);
		pRequest->body.clear();
		pRequest->body.append((const char *)pData, len);
	}

	if (pNet->mFilter)
	{
		//return 401
		NFWebStatus xWebStatus = pNet->mFilter(*pRequest);
		if (xWebStatus != NFWebStatus::WEB_OK)
		{

			pNet->mxHttpRequestPool.push_back(pRequest);

			//401
			pNet->ResponseMsg(*pRequest, "Filter error", xWebStatus);
			return;
		}
	}

	// call cb
	if (pNet->mReceiveCB)
	{
		pNet->mReceiveCB(*pRequest);
	}
	else
	{
		pNet->ResponseMsg(*pRequest, "NO PROCESSER", NFWebStatus::WEB_ERROR);
	}
}

NFHttpRequest* NFCHttpServer::AllowHttpRequest()
{
	if (mxHttpRequestPool.size() <= 0)
	{
		for (int i = 0; i < 100; ++i)
		{
			mxHttpRequestPool.push_back(NF_NEW NFHttpRequest());
		}
	}

	NFHttpRequest* pRequest = mxHttpRequestPool.front();
	mxHttpRequestPool.pop_front();
	pRequest->Reset();

	pRequest->id = ++mnIndex;

	return pRequest;
}

bool NFCHttpServer::ResponseMsg(const NFHttpRequest& req, const std::string& strMsg, NFWebStatus code,
                                const std::string& strReason)
{
	auto it = mxHttpRequestMap.find(req.id);
	if (it != mxHttpRequestMap.end())
	{
		mxHttpRequestPool.push_back(it->second);
		mxHttpRequestMap.erase(it);
	}

	evhttp_request* pHttpReq = (evhttp_request*)req.req;
    //create buffer
    struct evbuffer* eventBuffer = evbuffer_new();

    //send data
    evbuffer_add_printf(eventBuffer, strMsg.c_str());

    evhttp_add_header(evhttp_request_get_output_headers(pHttpReq), "Content-Type", "application/json");

	evhttp_send_reply(pHttpReq, code, strReason.c_str(), eventBuffer);

    //free
    evbuffer_free(eventBuffer);

    return true;
}<commit_msg>Update NFCHttpServer.cpp<commit_after>#include <thread>
#include "NFCHttpServer.h"

bool NFCHttpServer::Execute()
{
    if (mxBase)
    {
        event_base_loop(mxBase, EVLOOP_ONCE | EVLOOP_NONBLOCK);
    }

    return true;
}

int NFCHttpServer::InitServer(const unsigned short port)
{
	/*
    event_init();
    struct evhttp *httpserv = evhttp_start(addr,port);
	evhttp_set_gencb(httpserv, reqHandler,NULL);
	event_dispatch();
	*/

    //struct event_base *base;
    struct evhttp* http;
    struct evhttp_bound_socket* handle;

#if NF_PLATFORM == NF_PLATFORM_WIN
    WSADATA WSAData;
    WSAStartup(0x101, &WSAData);
#else
    if (signal(SIGPIPE, SIG_IGN) == SIG_ERR)
        return (1);
#endif

    mxBase = event_base_new();
    if (!mxBase)
    {
        std::cout << "create event_base fail" << std::endl;;
        return 1;
    }

    http = evhttp_new(mxBase);
    if (!http)
    {
        std::cout << "create evhttp fail" << std::endl;;
        return 1;
    }
    /* 创建SSL上下文环境 ，可以理解为 SSL句柄 */
    /*
    SSL_CTX *ctx = SSL_CTX_new (SSLv23_server_method ());
    SSL_CTX_set_options (ctx,
            SSL_OP_SINGLE_DH_USE |
            SSL_OP_SINGLE_ECDH_USE |
            SSL_OP_NO_SSLv2);
*/
    /* Cheesily pick an elliptic curve to use with elliptic curve ciphersuites.
     * We just hardcode a single curve which is reasonably decent.
     * See http://www.mail-archive.com/openssl-dev@openssl.org/msg30957.html */
	/*
    EC_KEY *ecdh = EC_KEY_new_by_curve_name (NID_X9_62_prime256v1);
    if (! ecdh)
        die_most_horribly_from_openssl_error ("EC_KEY_new_by_curve_name");
    if (1 != SSL_CTX_set_tmp_ecdh (ctx, ecdh))
        die_most_horribly_from_openssl_error ("SSL_CTX_set_tmp_ecdh");
*/
    /* 选择服务器证书 和 服务器私钥. */
	/*
    const char *certificate_chain = "server-certificate-chain.pem";
    const char *private_key = "server-private-key.pem";
    */
    /* 设置服务器证书 和 服务器私钥 到
     OPENSSL ctx上下文句柄中 */
    //server_setup_certs (ctx, certificate_chain, private_key);

    /*
        使我们创建好的evhttp句柄 支持 SSL加密
        实际上，加密的动作和解密的动作都已经帮
        我们自动完成，我们拿到的数据就已经解密之后的
    */
    handle = evhttp_bind_socket_with_handle(http, "0.0.0.0", port);
    if (!handle)
    {
        std::cout << "bind port :" << port << " fail" << std::endl;;
        return 1;
    }

    evhttp_set_gencb(http, listener_cb, (void*) this);

    return 0;
}

void NFCHttpServer::listener_cb(struct evhttp_request* req, void* arg)
{
	NFCHttpServer* pNet = (NFCHttpServer*)arg;
	NFHttpRequest* pRequest = pNet->AllowHttpRequest();

	pRequest->req = req;

	//headers
	struct evkeyvalq * header = evhttp_request_get_input_headers(req);
	struct evkeyval* kv = header->tqh_first;
	while (kv)
	{
		pRequest->headers.insert(std::map<std::string, std::string>::value_type(kv->key, kv->value));

		kv = kv->next.tqe_next;
	}

	//uri
	const char* uri = evhttp_request_get_uri(req);
	pRequest->url = uri;
	pRequest->remoteHost = evhttp_request_get_host(req);
	pRequest->type = (NFHttpType)evhttp_request_get_command(req);

	//get decodeUri
	struct evhttp_uri* decoded = evhttp_uri_parse(uri);
	if (!decoded)
	{
		std::cout << "It's not a good URI. Sending BADREQUEST" << std::endl;
		evhttp_send_error(req, HTTP_BADREQUEST, 0);

		pNet->mxHttpRequestPool.push_back(pRequest);

		return;
	}

	//path
	pRequest->path = evhttp_uri_get_path(decoded);
	evhttp_uri_free(decoded);

	//std::cout << "Got a GET request:" << uri << std::endl;
	if (evhttp_request_get_command(req) == evhttp_cmd_type::EVHTTP_REQ_GET)
	{
		//OnGetProcess(request, );
		std::cout << "EVHTTP_REQ_GET" << std::endl;

		struct evkeyvalq params;
		evhttp_parse_query(uri, &params);
		struct evkeyval* kv = params.tqh_first;
		while (kv)
		{
			pRequest->params.insert(std::map<std::string, std::string>::value_type(kv->key, kv->value));

			kv = kv->next.tqe_next;
		}
	}

	struct evbuffer *in_evb = evhttp_request_get_input_buffer(req);
	size_t len = evbuffer_get_length(in_evb);
	if (len > 0)
	{
		unsigned char *pData = evbuffer_pullup(in_evb, len);
		pRequest->body.clear();
		pRequest->body.append((const char *)pData, len);
	}

	if (pNet->mFilter)
	{
		//return 401
		NFWebStatus xWebStatus = pNet->mFilter(*pRequest);
		if (xWebStatus != NFWebStatus::WEB_OK)
		{

			pNet->mxHttpRequestPool.push_back(pRequest);

			//401
			pNet->ResponseMsg(*pRequest, "Filter error", xWebStatus);
			return;
		}
	}

	// call cb
	if (pNet->mReceiveCB)
	{
		pNet->mReceiveCB(*pRequest);
	}
	else
	{
		pNet->ResponseMsg(*pRequest, "NO PROCESSER", NFWebStatus::WEB_ERROR);
	}
}

NFHttpRequest* NFCHttpServer::AllowHttpRequest()
{
	if (mxHttpRequestPool.size() <= 0)
	{
		for (int i = 0; i < 100; ++i)
		{
			mxHttpRequestPool.push_back(NF_NEW NFHttpRequest());
		}
	}

	NFHttpRequest* pRequest = mxHttpRequestPool.front();
	mxHttpRequestPool.pop_front();
	pRequest->Reset();

	pRequest->id = ++mnIndex;

	return pRequest;
}

bool NFCHttpServer::ResponseMsg(const NFHttpRequest& req, const std::string& strMsg, NFWebStatus code,
                                const std::string& strReason)
{
	auto it = mxHttpRequestMap.find(req.id);
	if (it != mxHttpRequestMap.end())
	{
		mxHttpRequestPool.push_back(it->second);
		mxHttpRequestMap.erase(it);
	}

	evhttp_request* pHttpReq = (evhttp_request*)req.req;
    //create buffer
    struct evbuffer* eventBuffer = evbuffer_new();

    //send data
    evbuffer_add_printf(eventBuffer, strMsg.c_str());

    evhttp_add_header(evhttp_request_get_output_headers(pHttpReq), "Content-Type", "application/json");

	evhttp_send_reply(pHttpReq, code, strReason.c_str(), eventBuffer);

    //free
    evbuffer_free(eventBuffer);

    return true;
}
<|endoftext|>


<commit_before><commit_msg>DBCK-917 [nickel] BT sync: Can't transfer books to nickel after the 3rd sync<commit_after><|endoftext|>


<commit_before><commit_msg>Display optional board name in system info<commit_after><|endoftext|>


<commit_before>/*===================================================================

The Medical Imaging Interaction Toolkit (MITK)

Copyright (c) German Cancer Research Center,
Division of Medical and Biological Informatics.
All rights reserved.

This software is distributed WITHOUT ANY WARRANTY; without
even the implied warranty of MERCHANTABILITY or FITNESS FOR
A PARTICULAR PURPOSE.

See LICENSE.txt or http://www.mitk.org for details.

===================================================================*/

#include "mitkItkImageFileReader.h"
#include "mitkConfig.h"
#include "mitkException.h"

#include <itkImageFileReader.h>
#include <itksys/SystemTools.hxx>
#include <itksys/Directory.hxx>
#include <itkImage.h>
//#include <itkImageSeriesReader.h>
#include <itkImageFileReader.h>
#include <itkImageIOFactory.h>
#include <itkImageIORegion.h>
//#include <itkImageSeriesReader.h>
//#include <itkDICOMImageIO2.h>
//#include <itkDICOMSeriesFileNames.h>
//#include <itkGDCMImageIO.h>
//#include <itkGDCMSeriesFileNames.h>
//#include <itkNumericSeriesFileNames.h>

void mitk::ItkImageFileReader::GenerateData()
{
  const std::string& locale = "C";
  const std::string& currLocale = setlocale( LC_ALL, NULL );

  if ( locale.compare(currLocale)!=0 )
  {
    try
    {
      setlocale(LC_ALL, locale.c_str());
    }
    catch(...)
    {
      MITK_INFO << "Could not set locale " << locale;
    }
  }

  mitk::Image::Pointer image = this->GetOutput();

  const unsigned int MINDIM = 2;
  const unsigned int MAXDIM = 4;

  MITK_INFO << "loading " << m_FileName << " via itk::ImageIOFactory... " << std::endl;

  // Check to see if we can read the file given the name or prefix
  if ( m_FileName == "" )
  {
    mitkThrow() << "Empty filename in mitk::ItkImageFileReader ";
    return ;
  }

  itk::ImageIOBase::Pointer imageIO = itk::ImageIOFactory::CreateImageIO( m_FileName.c_str(), itk::ImageIOFactory::ReadMode );
  if ( imageIO.IsNull() )
  {
    //itkWarningMacro( << "File Type not supported!" );
    mitkThrow() << "Could not create itk::ImageIOBase object for filename " << m_FileName;
    return ;
  }

  // Got to allocate space for the image. Determine the characteristics of
  // the image.
  imageIO->SetFileName( m_FileName.c_str() );
  imageIO->ReadImageInformation();

  unsigned int ndim = imageIO->GetNumberOfDimensions();
  if ( ndim < MINDIM || ndim > MAXDIM )
  {
    itkWarningMacro( << "Sorry, only dimensions 2, 3 and 4 are supported. The given file has " << ndim << " dimensions! Reading as 4D." );
    ndim = MAXDIM;
  }

  itk::ImageIORegion ioRegion( ndim );
  itk::ImageIORegion::SizeType ioSize = ioRegion.GetSize();
  itk::ImageIORegion::IndexType ioStart = ioRegion.GetIndex();

  unsigned int dimensions[ MAXDIM ];
  dimensions[ 0 ] = 0;
  dimensions[ 1 ] = 0;
  dimensions[ 2 ] = 0;
  dimensions[ 3 ] = 0;

  float spacing[ MAXDIM ];
  spacing[ 0 ] = 1.0f;
  spacing[ 1 ] = 1.0f;
  spacing[ 2 ] = 1.0f;
  spacing[ 3 ] = 1.0f;

  Point3D origin;
  origin.Fill(0);

  unsigned int i;
  for ( i = 0; i < ndim ; ++i )
  {
    ioStart[ i ] = 0;
    ioSize[ i ] = imageIO->GetDimensions( i );
    if(i<MAXDIM)
    {
      dimensions[ i ] = imageIO->GetDimensions( i );
      spacing[ i ] = imageIO->GetSpacing( i );
      if(spacing[ i ] <= 0)
        spacing[ i ] = 1.0f;
    }
    if(i<3)
    {
      origin[ i ] = imageIO->GetOrigin( i );
    }
  }

  ioRegion.SetSize( ioSize );
  ioRegion.SetIndex( ioStart );

  MITK_INFO << "ioRegion: " << ioRegion << std::endl;
  imageIO->SetIORegion( ioRegion );
  void* buffer = new unsigned char[imageIO->GetImageSizeInBytes()];
  imageIO->Read( buffer );
  //mitk::Image::Pointer image = mitk::Image::New();
  if((ndim==4) && (dimensions[3]<=1))
    ndim = 3;
  if((ndim==3) && (dimensions[2]<=1))
    ndim = 2;

  mitk::PixelType pixelType = mitk::PixelType(imageIO->GetComponentTypeInfo(), mitk::GetPixelTypeFromITKImageIO(imageIO),
                                              imageIO->GetComponentSize(), imageIO->GetNumberOfComponents(),
                                              imageIO->GetComponentTypeAsString( imageIO->GetComponentType() ).c_str(),
                                              imageIO->GetPixelTypeAsString( imageIO->GetPixelType() ).c_str() );
  image->Initialize( pixelType, ndim, dimensions );
  image->SetImportChannel( buffer, 0, Image::ManageMemory );

  // access direction of itk::Image and include spacing
  mitk::Matrix3D matrix;
  matrix.SetIdentity();
  unsigned int j, itkDimMax3 = (ndim >= 3? 3 : ndim);
  for ( i=0; i < itkDimMax3; ++i)
    for( j=0; j < itkDimMax3; ++j )
      matrix[i][j] = imageIO->GetDirection(j)[i];

  // re-initialize PlaneGeometry with origin and direction
  PlaneGeometry* planeGeometry = static_cast<PlaneGeometry*>(image->GetSlicedGeometry(0)->GetGeometry2D(0));
  planeGeometry->SetOrigin(origin);
  planeGeometry->GetIndexToWorldTransform()->SetMatrix(matrix);

  // re-initialize SlicedGeometry3D
  SlicedGeometry3D* slicedGeometry = image->GetSlicedGeometry(0);
  slicedGeometry->InitializeEvenlySpaced(planeGeometry, image->GetDimension(2));
  slicedGeometry->SetSpacing(spacing);

  // re-initialize TimeSlicedGeometry
  image->GetTimeSlicedGeometry()->InitializeEvenlyTimed(slicedGeometry, image->GetDimension(3));

  buffer = NULL;
  MITK_INFO << "number of image components: "<< image->GetPixelType().GetNumberOfComponents() << std::endl;
//  mitk::DataNode::Pointer node = this->GetOutput();
//  node->SetData( image );

  // add level-window property
  //if ( image->GetPixelType().GetNumberOfComponents() == 1 )
  //{
  //  SetDefaultImageProperties( node );
  //}
  MITK_INFO << "...finished!" << std::endl;

  try
  {
    setlocale(LC_ALL, currLocale.c_str());
  }
  catch(...)
  {
    MITK_INFO << "Could not reset locale " << currLocale;
  }
}

bool mitk::ItkImageFileReader::CanReadFile(const std::string filename, const std::string filePrefix, const std::string filePattern)
{
  // First check the extension
  if(  filename == "" )
    return false;

  // check if image is serie
  if( filePattern != "" && filePrefix != "" )
    return false;

  itk::ImageIOBase::Pointer imageIO = itk::ImageIOFactory::CreateImageIO( filename.c_str(), itk::ImageIOFactory::ReadMode );
  if ( imageIO.IsNull() )
    return false;

  return true;
}

mitk::ItkImageFileReader::ItkImageFileReader()
    : m_FileName(""), m_FilePrefix(""), m_FilePattern("")
{
}

mitk::ItkImageFileReader::~ItkImageFileReader()
{
}
<commit_msg>Fixed PixelType constructor call in Reader<commit_after>/*===================================================================

The Medical Imaging Interaction Toolkit (MITK)

Copyright (c) German Cancer Research Center,
Division of Medical and Biological Informatics.
All rights reserved.

This software is distributed WITHOUT ANY WARRANTY; without
even the implied warranty of MERCHANTABILITY or FITNESS FOR
A PARTICULAR PURPOSE.

See LICENSE.txt or http://www.mitk.org for details.

===================================================================*/

#include "mitkItkImageFileReader.h"
#include "mitkConfig.h"
#include "mitkException.h"

#include <itkImageFileReader.h>
#include <itksys/SystemTools.hxx>
#include <itksys/Directory.hxx>
#include <itkImage.h>
//#include <itkImageSeriesReader.h>
#include <itkImageFileReader.h>
#include <itkImageIOFactory.h>
#include <itkImageIORegion.h>
//#include <itkImageSeriesReader.h>
//#include <itkDICOMImageIO2.h>
//#include <itkDICOMSeriesFileNames.h>
//#include <itkGDCMImageIO.h>
//#include <itkGDCMSeriesFileNames.h>
//#include <itkNumericSeriesFileNames.h>

void mitk::ItkImageFileReader::GenerateData()
{
  const std::string& locale = "C";
  const std::string& currLocale = setlocale( LC_ALL, NULL );

  if ( locale.compare(currLocale)!=0 )
  {
    try
    {
      setlocale(LC_ALL, locale.c_str());
    }
    catch(...)
    {
      MITK_INFO << "Could not set locale " << locale;
    }
  }

  mitk::Image::Pointer image = this->GetOutput();

  const unsigned int MINDIM = 2;
  const unsigned int MAXDIM = 4;

  MITK_INFO << "loading " << m_FileName << " via itk::ImageIOFactory... " << std::endl;

  // Check to see if we can read the file given the name or prefix
  if ( m_FileName == "" )
  {
    mitkThrow() << "Empty filename in mitk::ItkImageFileReader ";
    return ;
  }

  itk::ImageIOBase::Pointer imageIO = itk::ImageIOFactory::CreateImageIO( m_FileName.c_str(), itk::ImageIOFactory::ReadMode );
  if ( imageIO.IsNull() )
  {
    //itkWarningMacro( << "File Type not supported!" );
    mitkThrow() << "Could not create itk::ImageIOBase object for filename " << m_FileName;
    return ;
  }

  // Got to allocate space for the image. Determine the characteristics of
  // the image.
  imageIO->SetFileName( m_FileName.c_str() );
  imageIO->ReadImageInformation();

  unsigned int ndim = imageIO->GetNumberOfDimensions();
  if ( ndim < MINDIM || ndim > MAXDIM )
  {
    itkWarningMacro( << "Sorry, only dimensions 2, 3 and 4 are supported. The given file has " << ndim << " dimensions! Reading as 4D." );
    ndim = MAXDIM;
  }

  itk::ImageIORegion ioRegion( ndim );
  itk::ImageIORegion::SizeType ioSize = ioRegion.GetSize();
  itk::ImageIORegion::IndexType ioStart = ioRegion.GetIndex();

  unsigned int dimensions[ MAXDIM ];
  dimensions[ 0 ] = 0;
  dimensions[ 1 ] = 0;
  dimensions[ 2 ] = 0;
  dimensions[ 3 ] = 0;

  float spacing[ MAXDIM ];
  spacing[ 0 ] = 1.0f;
  spacing[ 1 ] = 1.0f;
  spacing[ 2 ] = 1.0f;
  spacing[ 3 ] = 1.0f;

  Point3D origin;
  origin.Fill(0);

  unsigned int i;
  for ( i = 0; i < ndim ; ++i )
  {
    ioStart[ i ] = 0;
    ioSize[ i ] = imageIO->GetDimensions( i );
    if(i<MAXDIM)
    {
      dimensions[ i ] = imageIO->GetDimensions( i );
      spacing[ i ] = imageIO->GetSpacing( i );
      if(spacing[ i ] <= 0)
        spacing[ i ] = 1.0f;
    }
    if(i<3)
    {
      origin[ i ] = imageIO->GetOrigin( i );
    }
  }

  ioRegion.SetSize( ioSize );
  ioRegion.SetIndex( ioStart );

  MITK_INFO << "ioRegion: " << ioRegion << std::endl;
  imageIO->SetIORegion( ioRegion );
  void* buffer = new unsigned char[imageIO->GetImageSizeInBytes()];
  imageIO->Read( buffer );
  //mitk::Image::Pointer image = mitk::Image::New();
  if((ndim==4) && (dimensions[3]<=1))
    ndim = 3;
  if((ndim==3) && (dimensions[2]<=1))
    ndim = 2;

  mitk::PixelType pixelType = mitk::PixelType(imageIO->GetComponentTypeInfo(), imageIO->GetPixelType(),
                                              imageIO->GetComponentSize(), imageIO->GetNumberOfComponents(),
                                              imageIO->GetComponentTypeAsString( imageIO->GetComponentType() ).c_str(),
                                              imageIO->GetPixelTypeAsString( imageIO->GetPixelType() ).c_str() );
  image->Initialize( pixelType, ndim, dimensions );
  image->SetImportChannel( buffer, 0, Image::ManageMemory );

  // access direction of itk::Image and include spacing
  mitk::Matrix3D matrix;
  matrix.SetIdentity();
  unsigned int j, itkDimMax3 = (ndim >= 3? 3 : ndim);
  for ( i=0; i < itkDimMax3; ++i)
    for( j=0; j < itkDimMax3; ++j )
      matrix[i][j] = imageIO->GetDirection(j)[i];

  // re-initialize PlaneGeometry with origin and direction
  PlaneGeometry* planeGeometry = static_cast<PlaneGeometry*>(image->GetSlicedGeometry(0)->GetGeometry2D(0));
  planeGeometry->SetOrigin(origin);
  planeGeometry->GetIndexToWorldTransform()->SetMatrix(matrix);

  // re-initialize SlicedGeometry3D
  SlicedGeometry3D* slicedGeometry = image->GetSlicedGeometry(0);
  slicedGeometry->InitializeEvenlySpaced(planeGeometry, image->GetDimension(2));
  slicedGeometry->SetSpacing(spacing);

  // re-initialize TimeSlicedGeometry
  image->GetTimeSlicedGeometry()->InitializeEvenlyTimed(slicedGeometry, image->GetDimension(3));

  buffer = NULL;
  MITK_INFO << "number of image components: "<< image->GetPixelType().GetNumberOfComponents() << std::endl;
//  mitk::DataNode::Pointer node = this->GetOutput();
//  node->SetData( image );

  // add level-window property
  //if ( image->GetPixelType().GetNumberOfComponents() == 1 )
  //{
  //  SetDefaultImageProperties( node );
  //}
  MITK_INFO << "...finished!" << std::endl;

  try
  {
    setlocale(LC_ALL, currLocale.c_str());
  }
  catch(...)
  {
    MITK_INFO << "Could not reset locale " << currLocale;
  }
}

bool mitk::ItkImageFileReader::CanReadFile(const std::string filename, const std::string filePrefix, const std::string filePattern)
{
  // First check the extension
  if(  filename == "" )
    return false;

  // check if image is serie
  if( filePattern != "" && filePrefix != "" )
    return false;

  itk::ImageIOBase::Pointer imageIO = itk::ImageIOFactory::CreateImageIO( filename.c_str(), itk::ImageIOFactory::ReadMode );
  if ( imageIO.IsNull() )
    return false;

  return true;
}

mitk::ItkImageFileReader::ItkImageFileReader()
    : m_FileName(""), m_FilePrefix(""), m_FilePattern("")
{
}

mitk::ItkImageFileReader::~ItkImageFileReader()
{
}
<|endoftext|>


<commit_before>#include "MovableCollider.h"
#include <Physics/BulletConv.h>
#include <Physics/PhysicsLevel.h>
#include <Physics/CollisionShape.h>
#include <BulletDynamics/Dynamics/btDiscreteDynamicsWorld.h>
#include <BulletDynamics/Dynamics/btRigidBody.h>
#include <BulletCollision/CollisionShapes/btCollisionShape.h>

namespace Physics
{

// Physics object doesn't know the source of its transform, it only stores an incoming copy
class CKinematicMotionState: public btMotionState
{
protected:

	btTransform _Tfm;

public:

	BT_DECLARE_ALIGNED_ALLOCATOR();

	CKinematicMotionState(const matrix44& InitialTfm, const vector3& Offset) { SetTransform(InitialTfm, Offset); }

	void SetTransform(const matrix44& NewTfm, const vector3& Offset)
	{
		_Tfm = TfmToBtTfm(NewTfm);
		_Tfm.getOrigin() = _Tfm * VectorToBtVector(Offset);
	}

	virtual void getWorldTransform(btTransform& worldTrans) const override { worldTrans = _Tfm; }
	virtual void setWorldTransform(const btTransform& worldTrans) override { /* must not be called on static and kinematic objects */ }
};

CMovableCollider::CMovableCollider(CCollisionShape& Shape, CStrID CollisionGroupID, CStrID CollisionMaskID, const matrix44& InitialTfm, const CPhysicsMaterial& Material)
	: CPhysicsObject(CollisionGroupID, CollisionMaskID)
{
	// Instead of storing strong ref, we manually control refcount and use
	// a pointer from the bullet collision shape
	Shape.AddRef();

	btRigidBody::btRigidBodyConstructionInfo CI(
		0.f,
		new CKinematicMotionState(InitialTfm, Shape.GetOffset()),
		Shape.GetBulletShape());

	SetupInternalObject(new btRigidBody(CI), Shape, Material);
	_pBtObject->setCollisionFlags(_pBtObject->getCollisionFlags() | btRigidBody::CF_KINEMATIC_OBJECT);
}
//---------------------------------------------------------------------

CMovableCollider::~CMovableCollider()
{
	if (_Level) _Level->GetBtWorld()->removeRigidBody(static_cast<btRigidBody*>(_pBtObject));

	auto pShape = static_cast<CCollisionShape*>(_pBtObject->getCollisionShape()->getUserPointer());
	delete static_cast<btRigidBody*>(_pBtObject)->getMotionState();
	delete _pBtObject;
	pShape->Release(); // See constructor
}
//---------------------------------------------------------------------

void CMovableCollider::AttachToLevelInternal()
{
	const U16 Group = _Level->CollisionGroups.GetMask(_CollisionGroupID ? _CollisionGroupID.CStr() : "Default");
	const U16 Mask = _Level->CollisionGroups.GetMask(_CollisionMaskID ? _CollisionMaskID.CStr() : "All");
	_Level->GetBtWorld()->addRigidBody(static_cast<btRigidBody*>(_pBtObject), Group, Mask);
}
//---------------------------------------------------------------------

void CMovableCollider::RemoveFromLevelInternal()
{
	_Level->GetBtWorld()->removeRigidBody(static_cast<btRigidBody*>(_pBtObject));
}
//---------------------------------------------------------------------

void CMovableCollider::SetActive(bool Active, bool Always)
{
	// Kinematic object must never be auto-deactivated
	if (Active)
		_pBtObject->forceActivationState(DISABLE_DEACTIVATION);
	else
		_pBtObject->forceActivationState(Always ? DISABLE_SIMULATION : WANTS_DEACTIVATION);
}
//---------------------------------------------------------------------

void CMovableCollider::SetTransform(const matrix44& Tfm)
{
	_pBtObject->forceActivationState(DISABLE_DEACTIVATION);
	auto pShape = static_cast<CCollisionShape*>(_pBtObject->getCollisionShape()->getUserPointer());
	static_cast<CKinematicMotionState*>(static_cast<btRigidBody*>(_pBtObject)->getMotionState())->SetTransform(Tfm, pShape->GetOffset());
}
//---------------------------------------------------------------------

void CMovableCollider::GetTransform(matrix44& OutTfm) const
{
	btTransform Tfm;
	static_cast<btRigidBody*>(_pBtObject)->getMotionState()->getWorldTransform(Tfm);

	auto pShape = static_cast<CCollisionShape*>(_pBtObject->getCollisionShape()->getUserPointer());

	OutTfm = BtTfmToTfm(Tfm);
	OutTfm.Translation() = OutTfm * (-pShape->GetOffset());
}
//---------------------------------------------------------------------

// Interpolated AABB from motion state, matches the graphics representation
void CMovableCollider::GetGlobalAABB(CAABB& OutBox) const
{
	btTransform Tfm;
	static_cast<btRigidBody*>(_pBtObject)->getMotionState()->getWorldTransform(Tfm);

	btVector3 Min, Max;
	_pBtObject->getCollisionShape()->getAabb(Tfm, Min, Max);
	OutBox.Min = BtVectorToVector(Min);
	OutBox.Max = BtVectorToVector(Max);
}
//---------------------------------------------------------------------

}
<commit_msg>Collision shape scaling issue solved by hack (to be rewritten in the nearest future, just for history)<commit_after>#include "MovableCollider.h"
#include <Physics/BulletConv.h>
#include <Physics/PhysicsLevel.h>
#include <Physics/CollisionShape.h>
#include <BulletDynamics/Dynamics/btDiscreteDynamicsWorld.h>
#include <BulletDynamics/Dynamics/btRigidBody.h>
#include <BulletCollision/CollisionShapes/btCollisionShape.h>

//!!!DBG TMP!
#include <Math/TransformSRT.h>

namespace Physics
{

// Physics object doesn't know the source of its transform, it only stores an incoming copy
class CKinematicMotionState: public btMotionState
{
protected:

	btTransform _Tfm;

public:

	BT_DECLARE_ALIGNED_ALLOCATOR();

	CKinematicMotionState(const matrix44& InitialTfm, const vector3& Offset) { SetTransform(InitialTfm, Offset); }

	void SetTransform(const matrix44& NewTfm, const vector3& Offset)
	{
		_Tfm = TfmToBtTfm(NewTfm);
		_Tfm.getOrigin() = _Tfm * VectorToBtVector(Offset);
	}

	virtual void getWorldTransform(btTransform& worldTrans) const override { worldTrans = _Tfm; }
	virtual void setWorldTransform(const btTransform& worldTrans) override { /* must not be called on static and kinematic objects */ }
};

CMovableCollider::CMovableCollider(CCollisionShape& Shape, CStrID CollisionGroupID, CStrID CollisionMaskID, const matrix44& InitialTfm, const CPhysicsMaterial& Material)
	: CPhysicsObject(CollisionGroupID, CollisionMaskID)
{
	// Instead of storing strong ref, we manually control refcount and use
	// a pointer from the bullet collision shape
	Shape.AddRef();

	btRigidBody::btRigidBodyConstructionInfo CI(
		0.f,
		new CKinematicMotionState(InitialTfm, Shape.GetOffset()),
		Shape.GetBulletShape());

	SetupInternalObject(new btRigidBody(CI), Shape, Material);
	_pBtObject->setCollisionFlags(_pBtObject->getCollisionFlags() | btRigidBody::CF_KINEMATIC_OBJECT);
}
//---------------------------------------------------------------------

CMovableCollider::~CMovableCollider()
{
	if (_Level) _Level->GetBtWorld()->removeRigidBody(static_cast<btRigidBody*>(_pBtObject));

	auto pShape = static_cast<CCollisionShape*>(_pBtObject->getCollisionShape()->getUserPointer());
	delete static_cast<btRigidBody*>(_pBtObject)->getMotionState();
	delete _pBtObject;
	pShape->Release(); // See constructor
}
//---------------------------------------------------------------------

void CMovableCollider::AttachToLevelInternal()
{
	const U16 Group = _Level->CollisionGroups.GetMask(_CollisionGroupID ? _CollisionGroupID.CStr() : "Default");
	const U16 Mask = _Level->CollisionGroups.GetMask(_CollisionMaskID ? _CollisionMaskID.CStr() : "All");
	_Level->GetBtWorld()->addRigidBody(static_cast<btRigidBody*>(_pBtObject), Group, Mask);
}
//---------------------------------------------------------------------

void CMovableCollider::RemoveFromLevelInternal()
{
	_Level->GetBtWorld()->removeRigidBody(static_cast<btRigidBody*>(_pBtObject));
}
//---------------------------------------------------------------------

void CMovableCollider::SetActive(bool Active, bool Always)
{
	// Kinematic object must never be auto-deactivated
	if (Active)
		_pBtObject->forceActivationState(DISABLE_DEACTIVATION);
	else
		_pBtObject->forceActivationState(Always ? DISABLE_SIMULATION : WANTS_DEACTIVATION);
}
//---------------------------------------------------------------------

void CMovableCollider::SetTransform(const matrix44& Tfm)
{
	_pBtObject->forceActivationState(DISABLE_DEACTIVATION);
	auto pShape = static_cast<CCollisionShape*>(_pBtObject->getCollisionShape()->getUserPointer());

	//!!!DBG TMP!
	::Math::CTransformSRT SRT(Tfm);
	_pBtObject->getCollisionShape()->setLocalScaling(VectorToBtVector(SRT.Scale));
	const vector3 Offset = { pShape->GetOffset().x * SRT.Scale.x, pShape->GetOffset().y * SRT.Scale.y, pShape->GetOffset().z * SRT.Scale.z };

	static_cast<CKinematicMotionState*>(static_cast<btRigidBody*>(_pBtObject)->getMotionState())->SetTransform(Tfm, Offset);
}
//---------------------------------------------------------------------

void CMovableCollider::GetTransform(matrix44& OutTfm) const
{
	btTransform Tfm;
	static_cast<btRigidBody*>(_pBtObject)->getMotionState()->getWorldTransform(Tfm);

	auto pShape = static_cast<CCollisionShape*>(_pBtObject->getCollisionShape()->getUserPointer());

	OutTfm = BtTfmToTfm(Tfm);
	OutTfm.Translation() = OutTfm * (-pShape->GetOffset());
}
//---------------------------------------------------------------------

// Interpolated AABB from motion state, matches the graphics representation
void CMovableCollider::GetGlobalAABB(CAABB& OutBox) const
{
	btTransform Tfm;
	static_cast<btRigidBody*>(_pBtObject)->getMotionState()->getWorldTransform(Tfm);

	btVector3 Min, Max;
	_pBtObject->getCollisionShape()->getAabb(Tfm, Min, Max);
	OutBox.Min = BtVectorToVector(Min);
	OutBox.Max = BtVectorToVector(Max);
}
//---------------------------------------------------------------------

}
<|endoftext|>


<commit_before>#include "border.h"
#include "window.h"
#include "keys.h"

extern  ax_application *FocusedApplication;

void UpdateBorder(std::string BorderType)
{
    Assert(BorderType == "focused" || BorderType == "marked");

    kwm_border *Border = &FocusedBorder;
    int WindowID = FocusedApplication && FocusedApplication->Focus ? FocusedApplication->Focus->ID : -1;

    if(!KWMHotkeys.ActiveMode->Color.Format.empty())
        Border->Color = KWMHotkeys.ActiveMode->Color;

    if(BorderType == "marked")
    {
        WindowID = KWMScreen.MarkedWindow.WID;
        Border = &MarkedBorder;
    }

    OpenBorder(Border);
    if(!Border->Enabled)
        CloseBorder(Border);

    if(WindowID == -1)
        ClearBorder(Border);
    else if(Border->Enabled)
        RefreshBorder(Border, FocusedApplication->Focus);
}
<commit_msg>windowids are unsigned int<commit_after>#include "border.h"
#include "window.h"
#include "keys.h"

extern  ax_application *FocusedApplication;

void UpdateBorder(std::string BorderType)
{
    Assert(BorderType == "focused" || BorderType == "marked");

    kwm_border *Border = &FocusedBorder;
    unsigned int WindowID = FocusedApplication && FocusedApplication->Focus ? FocusedApplication->Focus->ID : 0;

    if(!KWMHotkeys.ActiveMode->Color.Format.empty())
        Border->Color = KWMHotkeys.ActiveMode->Color;

    if(BorderType == "marked")
    {
        WindowID = KWMScreen.MarkedWindow.WID;
        Border = &MarkedBorder;
    }

    OpenBorder(Border);
    if(!Border->Enabled)
        CloseBorder(Border);

    if(WindowID == 0)
        ClearBorder(Border);
    else if(Border->Enabled)
        RefreshBorder(Border, FocusedApplication->Focus);
}
<|endoftext|>


<commit_before>// This file is part of Eigen, a lightweight C++ template library
// for linear algebra.
//
// Copyright (C) 2014 Gael Guennebaud <gael.guennebaud@inria.fr>
//
// This Source Code Form is subject to the terms of the Mozilla
// Public License v. 2.0. If a copy of the MPL was not distributed
// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.

#include "lapack_common.h"
#include <Eigen/SVD>
#include <unsupported/Eigen/BDCSVD>

// computes the singular values/vectors a general M-by-N matrix A using divide-and-conquer
EIGEN_LAPACK_FUNC(gesdd,(char *jobz, int *m, int* n, Scalar* a, int *lda, RealScalar *s, Scalar *u, int *ldu, Scalar *vt, int *ldvt, Scalar* /*work*/, int* lwork,
                         EIGEN_LAPACK_ARG_IF_COMPLEX(RealScalar */*rwork*/) int * /*iwork*/, int *info))
{
  // TODO exploit the work buffer
  bool query_size = *lwork==-1;
  int diag_size = (std::min)(*m,*n);

  *info = 0;
        if(*jobz!='A' && *jobz!='S' && *jobz!='O' && *jobz!='N')  *info = -1;
  else  if(*m<0)                                                  *info = -2;
  else  if(*n<0)                                                  *info = -3;
  else  if(*lda<std::max(1,*m))                                   *info = -5;
  else  if(*lda<std::max(1,*m))                                   *info = -8;
  else  if(*ldu <1 || (*jobz=='A' && *ldu <*m)
                   || (*jobz=='O' && *m<*n && *ldu<*m))           *info = -8;
  else  if(*ldvt<1 || (*jobz=='A' && *ldvt<*n)
                   || (*jobz=='S' && *ldvt<diag_size)
                   || (*jobz=='O' && *m>=*n && *ldvt<*n))         *info = -10;

  if(*info!=0)
  {
    int e = -*info;
    return xerbla_(SCALAR_SUFFIX_UP"GESDD ", &e, 6);
  }

  if(query_size)
  {
    *lwork = 0;
    return 0;
  }

  if(*n==0 || *m==0)
    return 0;

  PlainMatrixType mat(*m,*n);
  mat = matrix(a,*m,*n,*lda);

  int option = *jobz=='A' ? ComputeFullU|ComputeFullV
             : *jobz=='S' ? ComputeThinU|ComputeThinV
             : *jobz=='O' ? ComputeThinU|ComputeThinV
             : 0;

  BDCSVD<PlainMatrixType> svd(mat,option);

  make_vector(s,diag_size) = svd.singularValues().head(diag_size);

  if(*jobz=='A')
  {
    matrix(u,*m,*m,*ldu)   = svd.matrixU();
    matrix(vt,*n,*n,*ldvt) = svd.matrixV().adjoint();
  }
  else if(*jobz=='S')
  {
    matrix(u,*m,diag_size,*ldu)   = svd.matrixU();
    matrix(vt,diag_size,*n,*ldvt) = svd.matrixV().adjoint();
  }
  else if(*jobz=='O' && *m>=*n)
  {
    matrix(a,*m,*n,*lda)   = svd.matrixU();
    matrix(vt,*n,*n,*ldvt) = svd.matrixV().adjoint();
  }
  else if(*jobz=='O')
  {
    matrix(u,*m,*m,*ldu)        = svd.matrixU();
    matrix(a,diag_size,*n,*lda) = svd.matrixV().adjoint();
  }

  return 0;
}

// computes the singular values/vectors a general M-by-N matrix A using two sided jacobi algorithm
EIGEN_LAPACK_FUNC(gesvd,(char *jobu, char *jobv, int *m, int* n, Scalar* a, int *lda, RealScalar *s, Scalar *u, int *ldu, Scalar *vt, int *ldvt, Scalar* /*work*/, int* lwork,
                         EIGEN_LAPACK_ARG_IF_COMPLEX(RealScalar */*rwork*/) int *info))
{
  // TODO exploit the work buffer
  bool query_size = *lwork==-1;
  int diag_size = (std::min)(*m,*n);

  *info = 0;
        if( *jobu!='A' && *jobu!='S' && *jobu!='O' && *jobu!='N') *info = -1;
  else  if((*jobv!='A' && *jobv!='S' && *jobv!='O' && *jobv!='N')
           || (*jobu=='O' && *jobv=='O'))                         *info = -2;
  else  if(*m<0)                                                  *info = -3;
  else  if(*n<0)                                                  *info = -4;
  else  if(*lda<std::max(1,*m))                                   *info = -6;
  else  if(*ldu <1 || ((*jobu=='A' || *jobu=='S') && *ldu<*m))    *info = -9;
  else  if(*ldvt<1 || (*jobv=='A' && *ldvt<*n)
                   || (*jobv=='S' && *ldvt<diag_size))            *info = -11;

  if(*info!=0)
  {
    int e = -*info;
    return xerbla_(SCALAR_SUFFIX_UP"GESVD ", &e, 6);
  }

  if(query_size)
  {
    *lwork = 0;
    return 0;
  }

  if(*n==0 || *m==0)
    return 0;

  PlainMatrixType mat(*m,*n);
  mat = matrix(a,*m,*n,*lda);

  int option = (*jobu=='A' ? ComputeFullU : *jobu=='S' || *jobu=='O' ? ComputeThinU : 0)
             | (*jobv=='A' ? ComputeFullV : *jobv=='S' || *jobv=='O' ? ComputeThinV : 0);

  JacobiSVD<PlainMatrixType> svd(mat,option);

  make_vector(s,diag_size) = svd.singularValues().head(diag_size);

        if(*jobu=='A') matrix(u,*m,*m,*ldu)           = svd.matrixU();
  else  if(*jobu=='S') matrix(u,*m,diag_size,*ldu)    = svd.matrixU();
  else  if(*jobu=='O') matrix(a,*m,diag_size,*lda)           = svd.matrixU();

        if(*jobv=='A') matrix(vt,*n,*n,*ldvt)         = svd.matrixV().adjoint();
  else  if(*jobv=='S') matrix(vt,diag_size,*n,*ldvt)  = svd.matrixV().adjoint();
  else  if(*jobv=='O') matrix(a,diag_size,*n,*lda)    = svd.matrixV().adjoint();

  return 0;
}
<commit_msg>Removed deprecated header (unsupported/Eigen/BDCSVD is included in Eigen/SVD now)<commit_after>// This file is part of Eigen, a lightweight C++ template library
// for linear algebra.
//
// Copyright (C) 2014 Gael Guennebaud <gael.guennebaud@inria.fr>
//
// This Source Code Form is subject to the terms of the Mozilla
// Public License v. 2.0. If a copy of the MPL was not distributed
// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.

#include "lapack_common.h"
#include <Eigen/SVD>

// computes the singular values/vectors a general M-by-N matrix A using divide-and-conquer
EIGEN_LAPACK_FUNC(gesdd,(char *jobz, int *m, int* n, Scalar* a, int *lda, RealScalar *s, Scalar *u, int *ldu, Scalar *vt, int *ldvt, Scalar* /*work*/, int* lwork,
                         EIGEN_LAPACK_ARG_IF_COMPLEX(RealScalar */*rwork*/) int * /*iwork*/, int *info))
{
  // TODO exploit the work buffer
  bool query_size = *lwork==-1;
  int diag_size = (std::min)(*m,*n);

  *info = 0;
        if(*jobz!='A' && *jobz!='S' && *jobz!='O' && *jobz!='N')  *info = -1;
  else  if(*m<0)                                                  *info = -2;
  else  if(*n<0)                                                  *info = -3;
  else  if(*lda<std::max(1,*m))                                   *info = -5;
  else  if(*lda<std::max(1,*m))                                   *info = -8;
  else  if(*ldu <1 || (*jobz=='A' && *ldu <*m)
                   || (*jobz=='O' && *m<*n && *ldu<*m))           *info = -8;
  else  if(*ldvt<1 || (*jobz=='A' && *ldvt<*n)
                   || (*jobz=='S' && *ldvt<diag_size)
                   || (*jobz=='O' && *m>=*n && *ldvt<*n))         *info = -10;

  if(*info!=0)
  {
    int e = -*info;
    return xerbla_(SCALAR_SUFFIX_UP"GESDD ", &e, 6);
  }

  if(query_size)
  {
    *lwork = 0;
    return 0;
  }

  if(*n==0 || *m==0)
    return 0;

  PlainMatrixType mat(*m,*n);
  mat = matrix(a,*m,*n,*lda);

  int option = *jobz=='A' ? ComputeFullU|ComputeFullV
             : *jobz=='S' ? ComputeThinU|ComputeThinV
             : *jobz=='O' ? ComputeThinU|ComputeThinV
             : 0;

  BDCSVD<PlainMatrixType> svd(mat,option);

  make_vector(s,diag_size) = svd.singularValues().head(diag_size);

  if(*jobz=='A')
  {
    matrix(u,*m,*m,*ldu)   = svd.matrixU();
    matrix(vt,*n,*n,*ldvt) = svd.matrixV().adjoint();
  }
  else if(*jobz=='S')
  {
    matrix(u,*m,diag_size,*ldu)   = svd.matrixU();
    matrix(vt,diag_size,*n,*ldvt) = svd.matrixV().adjoint();
  }
  else if(*jobz=='O' && *m>=*n)
  {
    matrix(a,*m,*n,*lda)   = svd.matrixU();
    matrix(vt,*n,*n,*ldvt) = svd.matrixV().adjoint();
  }
  else if(*jobz=='O')
  {
    matrix(u,*m,*m,*ldu)        = svd.matrixU();
    matrix(a,diag_size,*n,*lda) = svd.matrixV().adjoint();
  }

  return 0;
}

// computes the singular values/vectors a general M-by-N matrix A using two sided jacobi algorithm
EIGEN_LAPACK_FUNC(gesvd,(char *jobu, char *jobv, int *m, int* n, Scalar* a, int *lda, RealScalar *s, Scalar *u, int *ldu, Scalar *vt, int *ldvt, Scalar* /*work*/, int* lwork,
                         EIGEN_LAPACK_ARG_IF_COMPLEX(RealScalar */*rwork*/) int *info))
{
  // TODO exploit the work buffer
  bool query_size = *lwork==-1;
  int diag_size = (std::min)(*m,*n);

  *info = 0;
        if( *jobu!='A' && *jobu!='S' && *jobu!='O' && *jobu!='N') *info = -1;
  else  if((*jobv!='A' && *jobv!='S' && *jobv!='O' && *jobv!='N')
           || (*jobu=='O' && *jobv=='O'))                         *info = -2;
  else  if(*m<0)                                                  *info = -3;
  else  if(*n<0)                                                  *info = -4;
  else  if(*lda<std::max(1,*m))                                   *info = -6;
  else  if(*ldu <1 || ((*jobu=='A' || *jobu=='S') && *ldu<*m))    *info = -9;
  else  if(*ldvt<1 || (*jobv=='A' && *ldvt<*n)
                   || (*jobv=='S' && *ldvt<diag_size))            *info = -11;

  if(*info!=0)
  {
    int e = -*info;
    return xerbla_(SCALAR_SUFFIX_UP"GESVD ", &e, 6);
  }

  if(query_size)
  {
    *lwork = 0;
    return 0;
  }

  if(*n==0 || *m==0)
    return 0;

  PlainMatrixType mat(*m,*n);
  mat = matrix(a,*m,*n,*lda);

  int option = (*jobu=='A' ? ComputeFullU : *jobu=='S' || *jobu=='O' ? ComputeThinU : 0)
             | (*jobv=='A' ? ComputeFullV : *jobv=='S' || *jobv=='O' ? ComputeThinV : 0);

  JacobiSVD<PlainMatrixType> svd(mat,option);

  make_vector(s,diag_size) = svd.singularValues().head(diag_size);

        if(*jobu=='A') matrix(u,*m,*m,*ldu)           = svd.matrixU();
  else  if(*jobu=='S') matrix(u,*m,diag_size,*ldu)    = svd.matrixU();
  else  if(*jobu=='O') matrix(a,*m,diag_size,*lda)           = svd.matrixU();

        if(*jobv=='A') matrix(vt,*n,*n,*ldvt)         = svd.matrixV().adjoint();
  else  if(*jobv=='S') matrix(vt,diag_size,*n,*ldvt)  = svd.matrixV().adjoint();
  else  if(*jobv=='O') matrix(a,diag_size,*n,*lda)    = svd.matrixV().adjoint();

  return 0;
}
<|endoftext|>


<commit_before>
#include <string.h> /* for memcmp, memmove */
#include <time.h>
#include <sys/time.h>
#include <stdio.h>
#include <stdlib.h> /* for malloc, free */
#include <ctype.h>  /* for isupper, islower, tolower */
#include <pthread.h>

#include "../../utils/timer.h"
#include "../../utils/memoryman.h"
#include "porter.h"

static char *s; /* buffer for words to be stemmed */

#define INC 50          /* size units in which s is increased */
static int i_max = INC; /* maximum offset in s */

// change ARRAYSIZE for larger input set
#define ARRAYSIZE 1000000
#define A_INC 10000
static int a_max = ARRAYSIZE;
int iterations;
int NTHREADS;

static struct stemmer **stem_list;

#define LETTER(ch) (isupper(ch) || islower(ch))

void *stem_thread(void *tid) {
  int i, start, *mytid, end;

  mytid = (int *)tid;
  start = (*mytid * iterations);
  end = start + iterations;
  // printf ("Thread %d doing iterations %d to %d\n", *mytid, start, end-1);

  for (i = start; i < end; i++) {
    stem_list[i]->b[stem2(stem_list[i]) + 1] = 0;
  }

  pthread_exit(NULL);
}

int load_data(struct stemmer **stem_list, FILE *f) {
  int a_size = 0;
  while (a_size < ARRAYSIZE) {
    int ch = getc(f);
    if (ch == EOF) return a_size;
    char *s = (char *)sirius_malloc(i_max + 1);
    if (LETTER(ch)) {
      int i = 0;
      while (TRUE) {
        if (i == i_max) {
          i_max += INC;
          s = (char *)realloc(s, i_max + 1);
        }
        ch = tolower(ch); /* forces lower case */

        s[i] = ch;
        i++;
        ch = getc(f);
        if (!LETTER(ch)) {
          ungetc(ch, f);
          break;
        }
      }
      struct stemmer *z = create_stemmer();
      z->b = s;
      z->k = i - 1;
      stem_list[a_size] = z;
      if (a_size == a_max) {
        a_max += A_INC;
        stem_list = (struct stemmer **)realloc(stem_list, a_max);
      }
      a_size += 1;
    }
  }
  return a_size;
}

int main(int argc, char *argv[]) {
  if (argc < 3) {
    fprintf(stderr, "[ERROR] Invalid arguments provided.\n\n");
    fprintf(stderr, "Usage: %s [NUMBER OF THREADS] [INPUT FILE]\n\n", argv[0]);
    exit(0);
  }

  /* Timing */
  STATS_INIT("kernel", "pthread_porter_stemming");
  PRINT_STAT_STRING("abrv", "pthread_stemmer");

  NTHREADS = atoi(argv[1]);
  PRINT_STAT_INT("threads", NTHREADS);
  FILE *f = fopen(argv[2], "r");
  if (f == 0) {
    fprintf(stderr, "File %s not found\n", argv[1]);
    exit(1);
  }

  stem_list =
      (struct stemmer **)sirius_malloc(ARRAYSIZE * sizeof(struct stemmer *));
  int words = load_data(stem_list, f);
  fclose(f);
  PRINT_STAT_INT("words", words);

  tic();
  int start, tids[NTHREADS];
  pthread_t threads[NTHREADS];
  pthread_attr_t attr;
  iterations = words / NTHREADS;

  pthread_attr_init(&attr);
  pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
  for (int i = 0; i < NTHREADS; i++) {
    tids[i] = i;
    pthread_create(&threads[i], &attr, stem_thread, (void *)&tids[i]);
  }

  for (int i = 0; i < NTHREADS; i++) {
    pthread_join(threads[i], NULL);
  }
  PRINT_STAT_DOUBLE("pthread_stemmer", toc());

  STATS_END();

#ifdef TESTING
  f = fopen("../input/stem_porter.pthread", "w");

  for (int i = 0; i < words; ++i) fprintf(f, "%s\n", stem_list[i]->b);

  fclose(f);
#endif

  sirius_free(s);

  // free up allocated data
  for (int i = 0; i < words; i++) {
    sirius_free(stem_list[i]->b);
    sirius_free(stem_list[i]);
  }

  return 0;
}
<commit_msg>sirius-suite/stemmer/pthread/main.cpp: fix realloc memory leak<commit_after>
#include <string.h> /* for memcmp, memmove */
#include <time.h>
#include <sys/time.h>
#include <stdio.h>
#include <stdlib.h> /* for malloc, free */
#include <ctype.h>  /* for isupper, islower, tolower */
#include <pthread.h>
#include <errno.h>

#include "../../utils/timer.h"
#include "../../utils/memoryman.h"
#include "porter.h"

static char *s; /* buffer for words to be stemmed */

#define INC 50          /* size units in which s is increased */
static int i_max = INC; /* maximum offset in s */

// change ARRAYSIZE for larger input set
#define ARRAYSIZE 1000000
#define A_INC 10000
static int a_max = ARRAYSIZE;
int iterations;
int NTHREADS;

static struct stemmer **stem_list;

#define LETTER(ch) (isupper(ch) || islower(ch))

void *stem_thread(void *tid) {
  int i, start, *mytid, end;

  mytid = (int *)tid;
  start = (*mytid * iterations);
  end = start + iterations;
  // printf ("Thread %d doing iterations %d to %d\n", *mytid, start, end-1);

  for (i = start; i < end; i++) {
    stem_list[i]->b[stem2(stem_list[i]) + 1] = 0;
  }

  pthread_exit(NULL);
}

int load_data(struct stemmer **stem_list, FILE *f) {
  int a_size = 0;
  while (a_size < ARRAYSIZE) {
    int ch = getc(f);
    if (ch == EOF) return a_size;
    char *s = (char *)sirius_malloc(i_max + 1);
    if (LETTER(ch)) {
      int i = 0;
      while (TRUE) {
        if (i == i_max) {
          i_max += INC;
          void *_realloc = NULL;
          if ((_realloc = realloc(s, i_max + 1)) == NULL) {
            fprintf(stderr, "realloc() failed!\n");
            return -ENOMEM;
          }
          s = (char*)_realloc;
        }
        ch = tolower(ch); /* forces lower case */

        s[i] = ch;
        i++;
        ch = getc(f);
        if (!LETTER(ch)) {
          ungetc(ch, f);
          break;
        }
      }
      struct stemmer *z = create_stemmer();
      z->b = s;
      z->k = i - 1;
      stem_list[a_size] = z;
      if (a_size == a_max) {
        a_max += A_INC;
        void *_realloc = NULL;
        if ((_realloc = realloc(stem_list, a_max)) == NULL) {
            fprintf(stderr, "realloc() failed!\n");
            return -ENOMEM;
        }
        stem_list = (struct stemmer **)_realloc;
      }
      a_size += 1;
    }
  }
  return a_size;
}

int main(int argc, char *argv[]) {
  if (argc < 3) {
    fprintf(stderr, "[ERROR] Invalid arguments provided.\n\n");
    fprintf(stderr, "Usage: %s [NUMBER OF THREADS] [INPUT FILE]\n\n", argv[0]);
    exit(0);
  }

  /* Timing */
  STATS_INIT("kernel", "pthread_porter_stemming");
  PRINT_STAT_STRING("abrv", "pthread_stemmer");

  NTHREADS = atoi(argv[1]);
  PRINT_STAT_INT("threads", NTHREADS);
  FILE *f = fopen(argv[2], "r");
  if (f == 0) {
    fprintf(stderr, "File %s not found\n", argv[1]);
    exit(1);
  }

  stem_list =
      (struct stemmer **)sirius_malloc(ARRAYSIZE * sizeof(struct stemmer *));
  int words = load_data(stem_list, f);
  fclose(f);

 if (words < 0)
    goto out;

  PRINT_STAT_INT("words", words);

  tic();
  int start, tids[NTHREADS];
  pthread_t threads[NTHREADS];
  pthread_attr_t attr;
  iterations = words / NTHREADS;

  pthread_attr_init(&attr);
  pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
  for (int i = 0; i < NTHREADS; i++) {
    tids[i] = i;
    pthread_create(&threads[i], &attr, stem_thread, (void *)&tids[i]);
  }

  for (int i = 0; i < NTHREADS; i++) {
    pthread_join(threads[i], NULL);
  }
  PRINT_STAT_DOUBLE("pthread_stemmer", toc());

  STATS_END();

#ifdef TESTING
  f = fopen("../input/stem_porter.pthread", "w");

  for (int i = 0; i < words; ++i) fprintf(f, "%s\n", stem_list[i]->b);

  fclose(f);
#endif

out:
  sirius_free(s);

  // free up allocated data
  for (int i = 0; i < words; i++) {
    sirius_free(stem_list[i]->b);
    sirius_free(stem_list[i]);
  }

  return 0;
}
<|endoftext|>


<commit_before>#pragma once

#include <map>
#include <memory>

#include "pugixml.hpp"

#include "pin_mesh.hpp"
#include "pin.hpp"
#include "material_lib.hpp"
#include "lattice.hpp"
#include "assembly.hpp"
#include "core.hpp"
#include "plane.hpp"

namespace mocc {

    // The core mesh stores everything needed to represent the physical state
    // of the system. Pin meshes, material library, actual pin types, lattices
    // etc. The CoreMesh is then used to perform complex operations like ray
    // tracing, generation of coarse mesh, etc. A lot of the heavy lifting for
    // input processing happens in the constructor, and the CoreMesh assumes
    // ownership of a lot of the structures used to represent the system.
    class CoreMesh {
    public:
        CoreMesh() {
            // do nothing
            return;
        }

        // Construct a CoreMesh from XML input. This routine is responsible for
        // parsing many of the tags in the XML document: <mesh>, <pin>,
        // <material_lib>, <lattice>, <core>
        CoreMesh( pugi::xml_node &input );

        ~CoreMesh();

        float_t hx() const {
            return hx_;
        }

        float_t hy() const {
            return hy_;
        }

        unsigned int nx() const {
            return nx_;
        }

        unsigned int ny() const {
            return ny_;
        }

        unsigned int nz() const {
            return nz_;
        }

        int n_unique_planes() const {
            return first_unique_.size();
        }

        unsigned int n_reg() const {
            return n_reg_;
        }

        // Given a vector containing two points (Which should be on the boundary
        // of the core mesh), insert points corresponding to intersections of
        // the line formed by those points. The points are added to the vector
        // itself.
        void trace( std::vector<Point2> &p ) const;

        // return a reference to the PinMesh that occupies the space at a point,
        // within a given plane.
        const PinMesh* get_pinmesh( Point2 &p, unsigned int iz,
                int &first_reg) const;

        const Plane& plane( unsigned int iz ) const {
            assert( (0 <= iz) & (iz < planes_.size()) );
            return planes_[iz];
        }

        std::vector<const Pin*>::const_iterator begin_pin() const {
            return core_pins_.cbegin();
        }

        std::vector<const Pin*>::const_iterator end_pin() const {
            return core_pins_.cend();
        }

        // Return a reference to the material library
        const MaterialLib& mat_lib() const {
            return mat_lib_;
        }

        // Return the first FSR index for a given plane
        unsigned int first_reg_plane( unsigned int iz ) const {
            assert( (0 <= iz ) & ( iz<nz_ ) );
            return first_reg_plane_[iz];
        }

        // Return the core boundary conditions
        std::vector<Boundary> boundary() const {
            return core_.boundary();
        }

    private:
        // Map for storing pin mesh objects indexed by user-specified IDs
        std::map<int, UP_PinMesh_t> pin_meshes_;

        // The material library
        MaterialLib mat_lib_;

        // Map of actual pin objects, indexed by user-specified IDs
        std::map<int, UP_Pin_t> pins_;

        // Map of lattice objects
        std::map<int, Lattice> lattices_;

        // Map of assembly objects
        std::map<int, UP_Assembly_t> assemblies_;

        // Vector of Plane instances. There should be one for each unique planar
        // geometry
        std::vector<Plane> planes_;

        // Vector of references to all pins in the core. This facilitates
        // iteration through the entire problem geometry in a linear fashion.
        // The pins are ordered in the same order that flat source regions are
        // indexed.
        std::vector<const Pin*> core_pins_;

        // Core object (essentially a 2D array of Assemblies)
        Core core_;

        // Total core size in the x dimension
        float_t hx_;

        // Total core size in the y dimension
        float_t hy_;

        // Total core size in the z dimension
        float_t hz_;

        // List of pin boundaries in the x dimension
        VecF x_vec_;

        // List of pin boundaries in the y dimension
        VecF y_vec_;

        // Numbers of pins/planes in each dimension
        unsigned int nx_;
        unsigned int ny_;
        unsigned int nz_;

        // Number of assemblies
        unsigned int nasy_;

        // Total number of FSRs in the entire geometry
        unsigned int n_reg_;
        // Total number of XS regions in the entire geometry
        unsigned int n_xsreg_;

        // List of geometrically-unique planes. Each entry in the list
        // corresponds to the unique plane index that is geometrically valid for
        // the actual plane.
        VecI unique_plane_;

        // Plane index of the first occurance of each geometrically-unique plane
        VecI first_unique_;

        // Index of the first flat source region on each plane
        VecI first_reg_plane_;

        // Vector of Line objects, representing pin boundaries. This greatly
        // simplifies the ray trace.
        std::vector<Line> lines_;

        // Vector containing the flat source region index of the first region in
        // each plane.

    };

    typedef std::shared_ptr<CoreMesh> SP_CoreMesh_t;
    typedef std::unique_ptr<CoreMesh> UP_CoreMesh_t;
}
<commit_msg>Add begin() and end() to CoreMesh<commit_after>#pragma once

#include <map>
#include <memory>

#include "pugixml.hpp"

#include "pin_mesh.hpp"
#include "pin.hpp"
#include "material_lib.hpp"
#include "lattice.hpp"
#include "assembly.hpp"
#include "core.hpp"
#include "plane.hpp"

namespace mocc {

    // The core mesh stores everything needed to represent the physical state
    // of the system. Pin meshes, material library, actual pin types, lattices
    // etc. The CoreMesh is then used to perform complex operations like ray
    // tracing, generation of coarse mesh, etc. A lot of the heavy lifting for
    // input processing happens in the constructor, and the CoreMesh assumes
    // ownership of a lot of the structures used to represent the system.
    class CoreMesh {
    public:
        CoreMesh() {
            // do nothing
            return;
        }

        // Construct a CoreMesh from XML input. This routine is responsible for
        // parsing many of the tags in the XML document: <mesh>, <pin>,
        // <material_lib>, <lattice>, <core>
        CoreMesh( pugi::xml_node &input );

        ~CoreMesh();

        float_t hx() const {
            return hx_;
        }

        float_t hy() const {
            return hy_;
        }

        unsigned int nx() const {
            return nx_;
        }

        unsigned int ny() const {
            return ny_;
        }

        unsigned int nz() const {
            return nz_;
        }

        int n_unique_planes() const {
            return first_unique_.size();
        }

        unsigned int n_reg() const {
            return n_reg_;
        }

        // Given a vector containing two points (Which should be on the boundary
        // of the core mesh), insert points corresponding to intersections of
        // the line formed by those points. The points are added to the vector
        // itself.
        void trace( std::vector<Point2> &p ) const;

        // return a reference to the PinMesh that occupies the space at a point,
        // within a given plane.
        const PinMesh* get_pinmesh( Point2 &p, unsigned int iz,
                int &first_reg) const;

        const Plane& plane( unsigned int iz ) const {
            assert( (0 <= iz) & (iz < planes_.size()) );
            return planes_[iz];
        }

        std::vector<const Pin*>::const_iterator begin_pin() const {
            return core_pins_.cbegin();
        }

        std::vector<const Pin*>::const_iterator end_pin() const {
            return core_pins_.cend();
        }

        // Return a reference to the material library
        const MaterialLib& mat_lib() const {
            return mat_lib_;
        }

        // Return the first FSR index for a given plane
        unsigned int first_reg_plane( unsigned int iz ) const {
            assert( (0 <= iz ) & ( iz<nz_ ) );
            return first_reg_plane_[iz];
        }

        // Return the core boundary conditions
        std::vector<Boundary> boundary() const {
            return core_.boundary();
        }

        std::vector<const Pin*>::const_iterator begin() const {
            return core_pins_.cbegin();
        }

        std::vector<const Pin*>::const_iterator end() const {
            return core_pins_.cend();
        }

    private:
        // Map for storing pin mesh objects indexed by user-specified IDs
        std::map<int, UP_PinMesh_t> pin_meshes_;

        // The material library
        MaterialLib mat_lib_;

        // Map of actual pin objects, indexed by user-specified IDs
        std::map<int, UP_Pin_t> pins_;

        // Map of lattice objects
        std::map<int, Lattice> lattices_;

        // Map of assembly objects
        std::map<int, UP_Assembly_t> assemblies_;

        // Vector of Plane instances. There should be one for each unique planar
        // geometry
        std::vector<Plane> planes_;

        // Vector of references to all pins in the core. This facilitates
        // iteration through the entire problem geometry in a linear fashion.
        // The pins are ordered in the same order that flat source regions are
        // indexed.
        std::vector<const Pin*> core_pins_;

        // Core object (essentially a 2D array of Assemblies)
        Core core_;

        // Total core size in the x dimension
        float_t hx_;

        // Total core size in the y dimension
        float_t hy_;

        // Total core size in the z dimension
        float_t hz_;

        // List of pin boundaries in the x dimension
        VecF x_vec_;

        // List of pin boundaries in the y dimension
        VecF y_vec_;

        // Numbers of pins/planes in each dimension
        unsigned int nx_;
        unsigned int ny_;
        unsigned int nz_;

        // Number of assemblies
        unsigned int nasy_;

        // Total number of FSRs in the entire geometry
        unsigned int n_reg_;
        // Total number of XS regions in the entire geometry
        unsigned int n_xsreg_;

        // List of geometrically-unique planes. Each entry in the list
        // corresponds to the unique plane index that is geometrically valid for
        // the actual plane.
        VecI unique_plane_;

        // Plane index of the first occurance of each geometrically-unique plane
        VecI first_unique_;

        // Index of the first flat source region on each plane
        VecI first_reg_plane_;

        // Vector of Line objects, representing pin boundaries. This greatly
        // simplifies the ray trace.
        std::vector<Line> lines_;

        // Vector containing the flat source region index of the first region in
        // each plane.

    };

    typedef std::shared_ptr<CoreMesh> SP_CoreMesh_t;
    typedef std::unique_ptr<CoreMesh> UP_CoreMesh_t;
}
<|endoftext|>