<commit_before>#pragma once

#include <Utils/DependenciesInjector.hpp>
#include <memory>
#include <Components/ComponentRegistrationManager.hpp>
#include <Core/EntityIdRegistrationManager.hh>
#include <list>
#include <array>
#include <glm/fwd.hpp>
#include <cereal/cereal.hpp>
#include <cereal/archives/binary.hpp>
#include <cereal/archives/json.hpp>
#include <cereal/archives/portable_binary.hpp>
#include <cereal/archives/xml.hpp>
#include <cereal/types/map.hpp>
#include <Utils/Containers/Queue.hpp>
#include <Entities/EntitySerializationInfos.hpp>
#include <Utils/ObjectPool.hpp>
#include <unordered_set>
#include <Components/ComponentManager.hpp>
#include <Utils/Debug.hpp>
#include <fstream>

namespace AGE
{
	class Engine;
	class RenderScene;
	class EntityFilter;
	class System;
	class SceneManager;

	class AScene : public DependenciesInjector, public EntityIdRegistrationManager, public ComponentManager
	{
	private:
		std::multimap<std::size_t, std::shared_ptr<System> >                    _systems;
		std::array<std::list<EntityFilter*>, MAX_CPT_NUMBER + MAX_TAG_NUMBER>   _filters;
		std::list<EntityFilter*>                                                 _allFilters;
		AGE::ObjectPool<EntityData>                                             _entityPool;
		AGE::Queue<std::uint16_t>                                               _freeEntityId;
		std::unordered_set<Entity>                                              _entities;
		ENTITY_ID                                                               _entityNumber;
		AGE::RenderScene                                                        *_renderScene;
		bool                                                                    _active;
		friend EntityFilter;
		friend class AGE::RenderScene;
		friend class AGE::SceneManager;
	protected:
		AGE::Engine *                                              _engine;
		inline void setActive(bool tof) { _active = tof; }
	public:
		AScene(AGE::Engine *engine);
		virtual ~AScene();
		inline std::size_t      getNumberOfEntities() const { return _entities.size(); }
		virtual bool 			userStart() = 0;
		virtual bool 			userUpdateBegin(float time) = 0;
		virtual bool            userUpdateEnd(float time) = 0;
		void 					update(float time);
		bool                    start();
		inline AGE::Engine *getEngine() { return _engine; }
		inline void setRenderScene(AGE::RenderScene *renderScene) { _renderScene = renderScene; }
		inline bool isActive() const { return _active; }

		void                    registerFilter(EntityFilter *filter);
		void                    filterSubscribe(ComponentType id, EntityFilter* filter);
		void                    filterUnsubscribe(ComponentType id, EntityFilter* filter);

		void                    informFiltersTagAddition(TAG_ID id, const EntityData &entity);
		void                    informFiltersTagDeletion(TAG_ID id, const EntityData &entity);
		void                    informFiltersComponentAddition(ComponentType id, const EntityData &entity);
		void                    informFiltersComponentDeletion(ComponentType id, const EntityData &entity);
		void                    informFiltersEntityCreation(const EntityData &entity);
		void                    informFiltersEntityDeletion(const EntityData &entity);

		Entity &createEntity();
		void destroy(const Entity &e);
		void clearAllEntities();

		template <typename T>
		std::shared_ptr<T> addSystem(std::size_t priority)
		{
			auto tmp = std::make_shared<T>((AScene*)(this));
			if (!tmp->init())
				return nullptr;
			_systems.insert(std::make_pair(priority, tmp));
			return tmp;
		}

		template <typename T>
		std::shared_ptr<T> getSystem()
		{
			for (auto &e : _systems)
			{
				if (typeid(*e.second.get()).name() == typeid(T).name())
					return std::static_pointer_cast<T>(e.second);
			}
			return nullptr;
		}

		template <typename T>
		void deleteSystem()
		{
			for (auto &e : _systems)
			{
				if (typeid(*e.second.get()).name() == typeid(T).name())
				{
					delete e.second;
					_systems.erase(e);
					return;
				}
			}
		}

		template <typename T>
		bool activateSystem()
		{
			for (auto &e : _systems)
			{
				if (typeid(*e.second.get()).name() == typeid(T).name())
					return e.second->setActivation(true);
			}
			return false;
		}

		template <typename T>
		bool deactivateSystem()
		{
			for (auto &e : _systems)
			{
				if (typeid(*e.second.get()).name() == typeid(T).name())
					return e.second->setActivation(false);
			}
			return false;
		}

		void saveToJson(const std::string &fileName);
		void loadFromJson(const std::string &fileName);
		void saveToBinary(const std::string &fileName);
		void loadFromBinary(const std::string &fileName);

		template <typename Container>
		void saveSelectionToJson(const std::string &fileName, Container &selection)
		{
			std::ofstream file(fileName.c_str(), std::ios::binary);
			AGE_ASSERT(file.is_open());
			{
				auto ar = cereal::JSONOutputArchive(file);

				std::size_t entityNbr = selection.size();

				ar(cereal::make_nvp("Number_of_serialized_entities", entityNbr));

				auto &typesMap = ComponentRegistrationManager::getInstance().getAgeIdToSystemIdMap();
				ar(cereal::make_nvp("Component type map", typesMap));

				for (auto &e : selection)
				{
					EntitySerializationInfos es(e.ptr);
					for (auto &c : e.ptr->components)
					{
						if (c)
						{
#ifdef EDITOR_ENABLED
							if (WESerialization::SerializeForEditor() == false && !c->serializeInExport())
							{
								continue;
							}
#endif
							es.componentTypes.push_back(c->getType());
							es.components.push_back(c);
						}
					}
					ar(cereal::make_nvp("Entity_" + std::to_string(e.ptr->getEntity().getId()), es));
				}
			}
			file.close();
		}

		template <typename Archive>
		void load(std::ifstream &s)
		{
			// @ECS TODO

			//Archive ar(s);

			//std::uint16_t size = 0;
			//ar(size);
			//for (unsigned int i = 0; i < size; ++i)
			//{
			//	auto &e = createEntity();
			//	auto &ed = *e.ptr;

			//	EntitySerializationInfos infos(ed);
			//	ar(infos);
			//	e.flags = infos.flags;
			//	ed.link.setPosition(infos.link.getPosition());
			//	ed.link.setOrientation(infos.link.getOrientation());
			//	ed.link.setScale(infos.link.getScale());

			//	for (auto &hash : infos.componentsHash)
			//	{
			//		std::size_t componentTypeId;
			//		auto ptr = ComponentRegistrar::getInstance().createComponentFromType(hash, ar, componentTypeId, this);
			//		ed.barcode.setComponent(componentTypeId);
			//		assert(_componentsManagers[componentTypeId] != nullptr);
			//		_componentsManagers[componentTypeId]->addComponentPtr(e, ptr);
			//		informFiltersComponentAddition(componentTypeId, ed);
			//	}
			//	//	ar(*e.get());
			//}
			////updateEntityHandles();
		}

		////////////////////////
		///////
		// Component Manager Get / Set

		template <typename T>
		void clearComponentsType()
		{
			//TODO
			auto id = Component<T>::getTypeId();
			if (_componentsManagers[id] == nullptr)
				return;
			auto &manager = *static_cast<ComponentManager<T>*>(_componentsManagers[id]);
			auto &col = manager.getComponents();
			for (std::size_t i = 0; i < manager.getSize(); ++i)
			{
				_entityPool[col[i].entityId].barcode.unsetComponent(ComponentType(id));
			}
			manager.clearComponents();
			for (auto filter : _filters[id])
			{
				filter->clearCollection();
			}
		}

		void addTag(Entity &e, TAG_ID tag);
		void removeTag(Entity &e, TAG_ID tag);
		bool isTagged(Entity &e, TAG_ID tag);
	};
}
<commit_msg>Missing include<commit_after>#pragma once

#include <Utils/DependenciesInjector.hpp>
#include <memory>
#include <Components/ComponentRegistrationManager.hpp>
#include <Core/EntityIdRegistrationManager.hh>
#include <list>
#include <array>
#include <glm/fwd.hpp>
#include <cereal/cereal.hpp>
#include <cereal/archives/binary.hpp>
#include <cereal/archives/json.hpp>
#include <cereal/archives/portable_binary.hpp>
#include <cereal/archives/xml.hpp>
#include <cereal/types/map.hpp>
#include <Utils/Containers/Queue.hpp>
#include <Entities/EntitySerializationInfos.hpp>
#include <Utils/ObjectPool.hpp>
#include <unordered_set>
#include <Components/ComponentManager.hpp>
#include <Utils/Debug.hpp>
#include <fstream>
#ifdef EDITOR_ENABLED
#include <WorldEditorGlobal.hpp>
#endif

namespace AGE
{
	class Engine;
	class RenderScene;
	class EntityFilter;
	class System;
	class SceneManager;

	class AScene : public DependenciesInjector, public EntityIdRegistrationManager, public ComponentManager
	{
	private:
		std::multimap<std::size_t, std::shared_ptr<System> >                    _systems;
		std::array<std::list<EntityFilter*>, MAX_CPT_NUMBER + MAX_TAG_NUMBER>   _filters;
		std::list<EntityFilter*>                                                 _allFilters;
		AGE::ObjectPool<EntityData>                                             _entityPool;
		AGE::Queue<std::uint16_t>                                               _freeEntityId;
		std::unordered_set<Entity>                                              _entities;
		ENTITY_ID                                                               _entityNumber;
		AGE::RenderScene                                                        *_renderScene;
		bool                                                                    _active;
		friend EntityFilter;
		friend class AGE::RenderScene;
		friend class AGE::SceneManager;
	protected:
		AGE::Engine *                                              _engine;
		inline void setActive(bool tof) { _active = tof; }
	public:
		AScene(AGE::Engine *engine);
		virtual ~AScene();
		inline std::size_t      getNumberOfEntities() const { return _entities.size(); }
		virtual bool 			userStart() = 0;
		virtual bool 			userUpdateBegin(float time) = 0;
		virtual bool            userUpdateEnd(float time) = 0;
		void 					update(float time);
		bool                    start();
		inline AGE::Engine *getEngine() { return _engine; }
		inline void setRenderScene(AGE::RenderScene *renderScene) { _renderScene = renderScene; }
		inline bool isActive() const { return _active; }

		void                    registerFilter(EntityFilter *filter);
		void                    filterSubscribe(ComponentType id, EntityFilter* filter);
		void                    filterUnsubscribe(ComponentType id, EntityFilter* filter);

		void                    informFiltersTagAddition(TAG_ID id, const EntityData &entity);
		void                    informFiltersTagDeletion(TAG_ID id, const EntityData &entity);
		void                    informFiltersComponentAddition(ComponentType id, const EntityData &entity);
		void                    informFiltersComponentDeletion(ComponentType id, const EntityData &entity);
		void                    informFiltersEntityCreation(const EntityData &entity);
		void                    informFiltersEntityDeletion(const EntityData &entity);

		Entity &createEntity();
		void destroy(const Entity &e);
		void clearAllEntities();

		template <typename T>
		std::shared_ptr<T> addSystem(std::size_t priority)
		{
			auto tmp = std::make_shared<T>((AScene*)(this));
			if (!tmp->init())
				return nullptr;
			_systems.insert(std::make_pair(priority, tmp));
			return tmp;
		}

		template <typename T>
		std::shared_ptr<T> getSystem()
		{
			for (auto &e : _systems)
			{
				if (typeid(*e.second.get()).name() == typeid(T).name())
					return std::static_pointer_cast<T>(e.second);
			}
			return nullptr;
		}

		template <typename T>
		void deleteSystem()
		{
			for (auto &e : _systems)
			{
				if (typeid(*e.second.get()).name() == typeid(T).name())
				{
					delete e.second;
					_systems.erase(e);
					return;
				}
			}
		}

		template <typename T>
		bool activateSystem()
		{
			for (auto &e : _systems)
			{
				if (typeid(*e.second.get()).name() == typeid(T).name())
					return e.second->setActivation(true);
			}
			return false;
		}

		template <typename T>
		bool deactivateSystem()
		{
			for (auto &e : _systems)
			{
				if (typeid(*e.second.get()).name() == typeid(T).name())
					return e.second->setActivation(false);
			}
			return false;
		}

		void saveToJson(const std::string &fileName);
		void loadFromJson(const std::string &fileName);
		void saveToBinary(const std::string &fileName);
		void loadFromBinary(const std::string &fileName);

		template <typename Container>
		void saveSelectionToJson(const std::string &fileName, Container &selection)
		{
			std::ofstream file(fileName.c_str(), std::ios::binary);
			AGE_ASSERT(file.is_open());
			{
				auto ar = cereal::JSONOutputArchive(file);

				std::size_t entityNbr = selection.size();

				ar(cereal::make_nvp("Number_of_serialized_entities", entityNbr));

				auto &typesMap = ComponentRegistrationManager::getInstance().getAgeIdToSystemIdMap();
				ar(cereal::make_nvp("Component type map", typesMap));

				for (auto &e : selection)
				{
					EntitySerializationInfos es(e.ptr);
					for (auto &c : e.ptr->components)
					{
						if (c)
						{
#ifdef EDITOR_ENABLED
							if (WESerialization::SerializeForEditor() == false && !c->serializeInExport())
							{
								continue;
							}
#endif
							es.componentTypes.push_back(c->getType());
							es.components.push_back(c);
						}
					}
					ar(cereal::make_nvp("Entity_" + std::to_string(e.ptr->getEntity().getId()), es));
				}
			}
			file.close();
		}

		template <typename Archive>
		void load(std::ifstream &s)
		{
			// @ECS TODO

			//Archive ar(s);

			//std::uint16_t size = 0;
			//ar(size);
			//for (unsigned int i = 0; i < size; ++i)
			//{
			//	auto &e = createEntity();
			//	auto &ed = *e.ptr;

			//	EntitySerializationInfos infos(ed);
			//	ar(infos);
			//	e.flags = infos.flags;
			//	ed.link.setPosition(infos.link.getPosition());
			//	ed.link.setOrientation(infos.link.getOrientation());
			//	ed.link.setScale(infos.link.getScale());

			//	for (auto &hash : infos.componentsHash)
			//	{
			//		std::size_t componentTypeId;
			//		auto ptr = ComponentRegistrar::getInstance().createComponentFromType(hash, ar, componentTypeId, this);
			//		ed.barcode.setComponent(componentTypeId);
			//		assert(_componentsManagers[componentTypeId] != nullptr);
			//		_componentsManagers[componentTypeId]->addComponentPtr(e, ptr);
			//		informFiltersComponentAddition(componentTypeId, ed);
			//	}
			//	//	ar(*e.get());
			//}
			////updateEntityHandles();
		}

		////////////////////////
		///////
		// Component Manager Get / Set

		template <typename T>
		void clearComponentsType()
		{
			//TODO
			auto id = Component<T>::getTypeId();
			if (_componentsManagers[id] == nullptr)
				return;
			auto &manager = *static_cast<ComponentManager<T>*>(_componentsManagers[id]);
			auto &col = manager.getComponents();
			for (std::size_t i = 0; i < manager.getSize(); ++i)
			{
				_entityPool[col[i].entityId].barcode.unsetComponent(ComponentType(id));
			}
			manager.clearComponents();
			for (auto filter : _filters[id])
			{
				filter->clearCollection();
			}
		}

		void addTag(Entity &e, TAG_ID tag);
		void removeTag(Entity &e, TAG_ID tag);
		bool isTagged(Entity &e, TAG_ID tag);
	};
}
<|endoftext|>


<commit_before><commit_msg>Fixed multiple duplicate lights in mesh lightsources vector<commit_after><|endoftext|>


<commit_before>#include "ComponentBone.h"
#include "Application.h"

#include "imgui/imgui.h"
#include "mmgr\mmgr.h"

ComponentBone::ComponentBone() : Component(componentType_Bone)
{
	typeName = "Skeleton";
	name = "Bone";
}

ComponentBone::ComponentBone(GameObject * argparent) : Component(componentType_Bone, argparent)
{
	typeName = "Skeleton";
	name = "Bone";
}

ComponentBone::ComponentBone(componentType argtype, GameObject * argparent) : Component(componentType_Bone, argparent)
{
	typeName = "Skeleton";
	name = "Bone";
}

ComponentBone::~ComponentBone()
{
	typeName = "Skeleton";
}

void ComponentBone::Start()
{
}

void ComponentBone::Update(float dt)
{
	//for (uint i = 0; i < skeleton.size(); ++i)
	//{
	//	float3 position, scale;
	//	float4x4 rot;
	//	skeleton[i]->offsetMat.Decompose(position, rot, scale);
	//	App->renderer3D->debugger->DrawAABB(position, scale);
	//}
}

void ComponentBone::CleanUp()
{
	for (int i = 0; i < skeleton.size(); i++) {
		if (skeleton[i] != nullptr) {
			skeleton[i]->CleanUp();
			mdelete skeleton[i];
		}
	}
}

void ComponentBone::Enable()
{
	isActive = true;
}

void ComponentBone::Disable()
{
	isActive = false;
}

void ComponentBone::OnEditor()
{
	int num_bones = skeleton.size();
	ImGui::TextColored(COLOR_YELLOW, "Num Bones:");
	ImGui::InputInt("const", &num_bones);
	ImGui::TextColored(COLOR_YELLOW, "Bones:");
	if (ImGui::CollapsingHeader("Bones:")) {
		for (int i = 0; i < skeleton.size(); i++) {
			ImGui::TextColored(COLOR_YELLOW, "%i: ", i);
			ImGui::SameLine();
			ImGui::Text(skeleton[i]->name.c_str());
		}
	}
}

ComponentMesh * ComponentBone::GetMesh() const
{
	return mesh;
}

void ComponentBone::SetMesh(ComponentMesh * m)
{
	mesh = m;
}
void ComponentBone::CollectGOs(GameObject * go)
{
	PairedGOToBones tmp;
	tmp.object = go;
	tmp.name = go->GetName();
	pairedgotobones.push_back(tmp);

	for (uint i = 0; i < go->children.size(); ++i)
		CollectGOs(go->children[i]);
}
bool ComponentBone::insert_BoneToIterate(ResourceBone * bone)
{
	if (bone == nullptr || gos_filled == false)
		return false;

	for (uint i = 0; i < pairedgotobones.size(); ++i) {
		if (pairedgotobones[i].name == bone->name)
		{
			pairedgotobones[i].bones.push_back(bone);
			bone->object = pairedgotobones[i].object;
			return true;
		}
	}
	return false;
}

ResourceBone * ComponentBone::GetRootBone()
{
	return skeleton.empty() ? nullptr : skeleton[0];
}

GameObject * ComponentBone::GetRootBoneGO()
{

	if (rootBoneGO != nullptr)
		return rootBoneGO;

	for (int i = 0; i < GetParent()->children.size(); i++) {
		GameObject* child = GetParent()->children[i];
		if (child->GetName() == GetRootBone()->name) {
			rootBoneGO = child;
			return rootBoneGO;
		}
	}

	return nullptr;
}

void ComponentBone::GetGOFromBones()
{
	if (gos_filled == false)
	{
		CollectGOs(App->scene->GetRoot());
		gos_filled = true;
	}

	if (pairs_filled == false)
	{
		for (uint i = 0; i < skeleton.size(); ++i)
		{
			insert_BoneToIterate(skeleton[i]);
		}

		/*for (vector<PairedGOToBones>::iterator it = pairedgotobones.begin(); it != pairedgotobones.end();)
		{
			if ((*it).bones.empty() == true)
				it = pairedgotobones.erase(it);

			++it;
		}*/
		pairs_filled = true;
	}
}

<commit_msg>added security :police_car:<commit_after>#include "ComponentBone.h"
#include "Application.h"

#include "imgui/imgui.h"
#include "mmgr\mmgr.h"

ComponentBone::ComponentBone() : Component(componentType_Bone)
{
	typeName = "Skeleton";
	name = "Bone";
}

ComponentBone::ComponentBone(GameObject * argparent) : Component(componentType_Bone, argparent)
{
	typeName = "Skeleton";
	name = "Bone";
}

ComponentBone::ComponentBone(componentType argtype, GameObject * argparent) : Component(componentType_Bone, argparent)
{
	typeName = "Skeleton";
	name = "Bone";
}

ComponentBone::~ComponentBone()
{
	typeName = "Skeleton";
}

void ComponentBone::Start()
{
}

void ComponentBone::Update(float dt)
{
	//for (uint i = 0; i < skeleton.size(); ++i)
	//{
	//	float3 position, scale;
	//	float4x4 rot;
	//	skeleton[i]->offsetMat.Decompose(position, rot, scale);
	//	App->renderer3D->debugger->DrawAABB(position, scale);
	//}
}

void ComponentBone::CleanUp()
{
	for (int i = 0; i < skeleton.size(); i++) {
		if (skeleton[i] != nullptr) {
			skeleton[i]->CleanUp();
			mdelete skeleton[i];
		}
	}
}

void ComponentBone::Enable()
{
	isActive = true;
}

void ComponentBone::Disable()
{
	isActive = false;
}

void ComponentBone::OnEditor()
{
	int num_bones = skeleton.size();
	ImGui::TextColored(COLOR_YELLOW, "Num Bones:");
	ImGui::InputInt("const", &num_bones);
	ImGui::TextColored(COLOR_YELLOW, "Bones:");
	if (ImGui::CollapsingHeader("Bones:")) {
		for (int i = 0; i < skeleton.size(); i++) {
			ImGui::TextColored(COLOR_YELLOW, "%i: ", i);
			ImGui::SameLine();
			ImGui::Text(skeleton[i]->name.c_str());
		}
	}
}

ComponentMesh * ComponentBone::GetMesh() const
{
	return mesh;
}

void ComponentBone::SetMesh(ComponentMesh * m)
{
	mesh = m;
}
void ComponentBone::CollectGOs(GameObject * go)
{
	PairedGOToBones tmp;
	tmp.object = go;
	tmp.name = go->GetName();
	pairedgotobones.push_back(tmp);

	for (uint i = 0; i < go->children.size(); ++i)
		CollectGOs(go->children[i]);
}
bool ComponentBone::insert_BoneToIterate(ResourceBone * bone)
{
	if (bone == nullptr || gos_filled == false)
		return false;

	for (uint i = 0; i < pairedgotobones.size(); ++i) {
		if (pairedgotobones[i].name == bone->name)
		{
			pairedgotobones[i].bones.push_back(bone);
			bone->object = pairedgotobones[i].object;
			return true;
		}
	}
	return false;
}

ResourceBone * ComponentBone::GetRootBone()
{
	return skeleton.empty() ? nullptr : skeleton[0];
}

GameObject * ComponentBone::GetRootBoneGO()
{

	if (rootBoneGO != nullptr)
		return rootBoneGO;
	if (GetRootBone() == nullptr)
		return nullptr;

	for (int i = 0; i < GetParent()->children.size(); i++) {
		GameObject* child = GetParent()->children[i];
		if (child->GetName() == GetRootBone()->name) {
			rootBoneGO = child;
			return rootBoneGO;
		}
	}

	return nullptr;
}

void ComponentBone::GetGOFromBones()
{
	if (gos_filled == false)
	{
		CollectGOs(App->scene->GetRoot());
		gos_filled = true;
	}

	if (pairs_filled == false)
	{
		for (uint i = 0; i < skeleton.size(); ++i)
		{
			insert_BoneToIterate(skeleton[i]);
		}

		/*for (vector<PairedGOToBones>::iterator it = pairedgotobones.begin(); it != pairedgotobones.end();)
		{
			if ((*it).bones.empty() == true)
				it = pairedgotobones.erase(it);

			++it;
		}*/
		pairs_filled = true;
	}
}

<|endoftext|>


<commit_before>#include "Expression.hpp"

#include <cmath>
#include <sstream>

#include <iostream>

namespace lm
{
Expression::Expression(const std::string& inputInit) : input{inputInit}
{
    std::cout << "contructor" << std::endl;
}

double Expression::getResult()
{        std::cout << "get result" << std::endl;
    std::istringstream istr(input);
    std::cout << "after istr" << std::endl;

            std::cout << "val init" << std::endl;
    double val1 = 0.0;
    double val2 = 0.0;
    char op = '\0';
    std::cout << "before >> " << istr.str() << std::endl;
    istr >> val1;
    std::cout << "after val1 >> " << val1 << std::endl;
    istr >> op;
    std::cout << "after op >> " << op << std::endl;
    istr >> val2;
    std::cout << "after val2 >> " << val2 << std::endl;
    switch (op)
    {
    case '+': std::cout << "1" << std::endl; return val1 + val2;
    case '-': std::cout << "2" << std::endl; return val1 - val2;
    case '*': std::cout << "3" << std::endl; return val1 * val2;
    case '/':

        std::cout << "4" << std::endl;
        if (std::fabs(val2) < epsilon)
        {
            std::cout << "5" << std::endl;
            throw std::runtime_error("division by zero");
        }

        std::cout << "6" << std::endl;
        return val1 / val2;
    default:
        std::cout << "7" << std::endl;
        throw std::runtime_error("unknown operation");
    }
}
}
<commit_msg>travis test<commit_after>#include "Expression.hpp"

#include <cmath>
#include <sstream>

#include <iostream>

namespace lm
{
Expression::Expression(const std::string& inputInit) : input{inputInit}
{
    std::cout << "contructor" << std::endl;
}

double Expression::getResult()
{        std::cout << "get result " << input << std::endl;
    std::istringstream istr(input);
    std::cout << "after istr" << std::endl;

            std::cout << "val init" << std::endl;
    double val1 = 0.0;
    double val2 = 0.0;
    char op = '\0';
    std::cout << "before >> " << istr.str() << std::endl;
    istr >> val1;
    std::cout << "after val1 >> " << val1 << std::endl;
    istr >> op;
    std::cout << "after op >> " << op << std::endl;
    istr >> val2;
    std::cout << "after val2 >> " << val2 << std::endl;
    switch (op)
    {
    case '+': std::cout << "1" << std::endl; return val1 + val2;
    case '-': std::cout << "2" << std::endl; return val1 - val2;
    case '*': std::cout << "3" << std::endl; return val1 * val2;
    case '/':

        std::cout << "4" << std::endl;
        if (std::fabs(val2) < epsilon)
        {
            std::cout << "5" << std::endl;
            throw std::runtime_error("division by zero");
        }

        std::cout << "6" << std::endl;
        return val1 / val2;
    default:
        std::cout << "7" << std::endl;
        throw std::runtime_error("unknown operation");
    }
}
}
<|endoftext|>


<commit_before>///
/// @file  S2_easy.cpp
/// @brief Calculate the contribution of the clustered easy leaves
///        and the sparse easy leaves in parallel using OpenMP
///        (Deleglise-Rivat algorithm).
///
/// Copyright (C) 2017 Kim Walisch, <kim.walisch@gmail.com>
///
/// This file is distributed under the BSD License. See the COPYING
/// file in the top level directory.
///

#include <PiTable.hpp>
#include <primecount-internal.hpp>
#include <calculator.hpp>
#include <fast_div.hpp>
#include <generate.hpp>
#include <int128_t.hpp>
#include <min.hpp>
#include <imath.hpp>
#include <S2Status.hpp>
#include <S2.hpp>
#include <json.hpp>

#include <stdint.h>
#include <vector>
#include <string>

#ifdef _OPENMP
  #include <omp.h>
#endif

using namespace std;
using namespace primecount;

namespace {

/// backup to file every 60 seconds
bool is_backup(double time)
{
  double seconds = get_wtime() - time;
  return seconds > 60;
}

template <typename T>
void print_resume(double percent, T x)
{
  print_log("Resume from " + backup_file());
  print_status(percent, x);
}

/// backup to file
template <typename T, typename J>
void backup(J& json,
            T x,
            int64_t y,
            int64_t z,
            int threads,
            double percent,
            double time)
{
  json["S2_easy"]["x"] = to_string(x);
  json["S2_easy"]["y"] = y;
  json["S2_easy"]["z"] = z;
  json["S2_easy"]["threads"] = threads;
  json["S2_easy"]["percent"] = percent;
  json["S2_easy"]["seconds"] = get_wtime() - time;

  store_backup(json);
}

/// backup thread
template <typename T, typename J>
void backup(J& json,
            int64_t start,
            int64_t b,
            int64_t thread_id,
            T s2_easy)
{
  string tid = "thread" + to_string(thread_id);

  json["S2_easy"]["start"] = start;
  json["S2_easy"][tid]["b"] = b;
  json["S2_easy"][tid]["s2_easy"] = to_string(s2_easy);
}

/// backup result
template <typename T, typename J>
void backup(J& json,
            T x,
            int64_t y,
            int64_t z,
            T s2_easy,
            double time)
{
  json.erase("S2_easy");

  json["S2_easy"]["x"] = to_string(x);
  json["S2_easy"]["y"] = y;
  json["S2_easy"]["z"] = z;
  json["S2_easy"]["s2_easy"] = to_string(s2_easy);
  json["S2_easy"]["percent"] = 100;
  json["S2_easy"]["seconds"] = get_wtime() - time;

  store_backup(json);
}

template <typename T, typename J>
int64_t get_start(J& json,
                  T x,
                  int64_t y,
                  int64_t z,
                  int64_t start)
{
  if (is_resume(json, "S2_easy", x, y, z) &&
      json["S2_easy"].count("start"))
  {
    start = json["S2_easy"]["start"];
  }

  return start;
}

template <typename T, typename J>
int get_threads(J& json,
                T x,
                int64_t y,
                int64_t z,
                int threads)
{
  if (is_resume(json, "S2_easy", x, y, z) &&
      json["S2_easy"].count("threads"))
  {
    double percent = json["S2_easy"]["percent"];
    int backup_threads = json["S2_easy"]["threads"];
    threads = max(threads, backup_threads);
    print_resume(percent, x);
  }

  return threads;
}

template <typename T, typename J>
double get_time(J& json,
                T x,
                int64_t y,
                int64_t z,
                double time)
{
  if (is_resume(json, "S2_easy", x, y, z))
  {
    double seconds = json["S2_easy"]["seconds"];
    time = get_wtime() - seconds;
  }

  return time;
}

/// resume result
template <typename T, typename J>
bool resume(J& json,
            T x,
            int64_t y,
            int64_t z,
            T& s2_easy,
            double& time)
{
  if (is_resume(json, "S2_easy", x, y, z) &&
      json["S2_easy"].count("s2_easy"))
  {
    double percent = json["S2_easy"]["percent"];
    double seconds = json["S2_easy"]["seconds"];

    s2_easy = calculator::eval<T>(json["S2_easy"]["s2_easy"]);
    time = get_wtime() - seconds;
    print_resume(percent, x);
    return true;
  }

  return false;
}

/// resume thread
template <typename T, typename J>
bool resume(J& json,
            T x,
            int64_t y,
            int64_t z,
            int64_t& b,
            int thread_id,
            T& s2_easy)
{
  bool resumed = false;

  #pragma omp critical (s2_easy_resume)
  if (is_resume(json, "S2_easy", thread_id, x, y, z))
  {
    resumed = true;
    string tid = "thread" + to_string(thread_id);
    b = json["S2_easy"][tid]["b"];
    s2_easy = calculator::eval<T>(json["S2_easy"][tid]["s2_easy"]);
  }

  return resumed;
}

template <typename T, typename Primes>
T S2_easy(T x,
          int64_t y,
          int64_t z,
          int64_t b,
          Primes& primes,
          PiTable& pi)
{
  int64_t prime = primes[b];
  T x2 = x / prime;
  int64_t min_trivial = min(x2 / prime, y);
  int64_t min_clustered = (int64_t) isqrt(x2);
  int64_t min_sparse = z / prime;

  min_clustered = in_between(prime, min_clustered, y);
  min_sparse = in_between(prime, min_sparse, y);

  int64_t l = pi[min_trivial];
  int64_t pi_min_clustered = pi[min_clustered];
  int64_t pi_min_sparse = pi[min_sparse];
  T s2_easy = 0;

  // Find all clustered easy leaves:
  // n = primes[b] * primes[l]
  // x / n <= y && phi(x / n, b - 1) == phi(x / m, b - 1)
  // where phi(x / n, b - 1) = pi(x / n) - b + 2
  while (l > pi_min_clustered)
  {
    int64_t xn = (int64_t) fast_div(x2, primes[l]);
    int64_t phi_xn = pi[xn] - b + 2;
    int64_t xm = (int64_t) fast_div(x2, primes[b + phi_xn - 1]);
    int64_t l2 = pi[xm];
    s2_easy += phi_xn * (l - l2);
    l = l2;
  }

  // Find all sparse easy leaves:
  // n = primes[b] * primes[l]
  // x / n <= y && phi(x / n, b - 1) = pi(x / n) - b + 2
  for (; l > pi_min_sparse; l--)
  {
    int64_t xn = (int64_t) fast_div(x2, primes[l]);
    s2_easy += pi[xn] - b + 2;
  }

  return s2_easy;
}

/// Calculate the contribution of the clustered easy leaves
/// and the sparse easy leaves.
/// @param T  either int64_t or uint128_t.
///
template <typename T, typename Primes>
T S2_easy_OpenMP(T x,
                 int64_t y,
                 int64_t z,
                 int64_t c,
                 Primes& primes,
                 int threads,
                 double& time)
{
  T s2 = 0;
  auto json = load_backup();
  auto copy = json;

  if (resume(json, x, y, z, s2, time))
    return s2;

  if (!is_resume(json, "S2_easy", x, y, z))
    json.erase("S2_easy");

  PiTable pi(y);
  S2Status status(x);
  double backup_time = get_wtime();
  time = get_time(json, x, y, z, time);

  int64_t x13 = iroot<3>(x);
  int64_t pi_x13 = pi[x13];
  int64_t pi_sqrty = pi[isqrt(y)];
  int64_t start = max(c, pi_sqrty) + 1;
  start = get_start(json, x, y, z, start);

  int64_t thread_threshold = 1000;
  threads = ideal_num_threads(threads, x13, thread_threshold);
  threads = get_threads(json, x, y, z, threads);

  #pragma omp parallel for \
      num_threads(threads) reduction(+: s2)
  for (int i = 0; i < threads; i++)
  {
    T s2_easy = 0;
    int64_t b = 0;

    if (resume(copy, x, y, z, b, i, s2_easy))
      s2_easy += S2_easy(x, y, z, b, primes, pi);

    while (true)
    {
      if (is_print())
        status.print(b, pi_x13);

      #pragma omp critical (s2_easy_backup)
      {
        b = start++;

        backup(json, start, b, i, s2_easy);

        if (is_backup(backup_time))
        {
          double percent = status.getPercent(start, pi_x13, start, pi_x13);
          backup(json, x, y, z, threads, percent, time);
          backup_time = get_wtime();
        }
      }

      if (b > pi_x13)
        break;

      s2_easy += S2_easy(x, y, z, b, primes, pi);
    }

    s2 += s2_easy;
  }

  backup(json, x, y, z, s2, time);

  return s2;
}

} // namespace

namespace primecount {

int64_t S2_easy(int64_t x,
                int64_t y,
                int64_t z,
                int64_t c,
                int threads)
{
#ifdef HAVE_MPI
  if (mpi_num_procs() > 1)
    return S2_easy_mpi(x, y, z, c, threads);
#endif

  print_log("");
  print_log("=== S2_easy(x, y) ===");
  print_log("Computation of the easy special leaves");
  print_log(x, y, c, threads);

  double time = get_wtime();
  auto primes = generate_primes<int32_t>(y);
  int64_t s2_easy = S2_easy_OpenMP((intfast64_t) x, y, z, c, primes, threads, time);

  print_log("S2_easy", s2_easy, time);
  return s2_easy;
}

#ifdef HAVE_INT128_T

int128_t S2_easy(int128_t x,
                 int64_t y,
                 int64_t z,
                 int64_t c,
                 int threads)
{
#ifdef HAVE_MPI
  if (mpi_num_procs() > 1)
    return S2_easy_mpi(x, y, z, c, threads);
#endif

  print_log("");
  print_log("=== S2_easy(x, y) ===");
  print_log("Computation of the easy special leaves");
  print_log(x, y, c, threads);

  int128_t s2_easy;
  double time = get_wtime();

  // uses less memory
  if (y <= numeric_limits<uint32_t>::max())
  {
    auto primes = generate_primes<uint32_t>(y);
    s2_easy = S2_easy_OpenMP((intfast128_t) x, y, z, c, primes, threads, time);
  }
  else
  {
    auto primes = generate_primes<int64_t>(y);
    s2_easy = S2_easy_OpenMP((intfast128_t) x, y, z, c, primes, threads, time);
  }

  print_log("S2_easy", s2_easy, time);
  return s2_easy;
}

#endif

} // namespace
<commit_msg>Remove critical section<commit_after>///
/// @file  S2_easy.cpp
/// @brief Calculate the contribution of the clustered easy leaves
///        and the sparse easy leaves in parallel using OpenMP
///        (Deleglise-Rivat algorithm).
///
/// Copyright (C) 2017 Kim Walisch, <kim.walisch@gmail.com>
///
/// This file is distributed under the BSD License. See the COPYING
/// file in the top level directory.
///

#include <PiTable.hpp>
#include <primecount-internal.hpp>
#include <calculator.hpp>
#include <fast_div.hpp>
#include <generate.hpp>
#include <int128_t.hpp>
#include <min.hpp>
#include <imath.hpp>
#include <S2Status.hpp>
#include <S2.hpp>
#include <json.hpp>

#include <stdint.h>
#include <vector>
#include <string>

#ifdef _OPENMP
  #include <omp.h>
#endif

using namespace std;
using namespace primecount;

namespace {

/// backup to file every 60 seconds
bool is_backup(double time)
{
  double seconds = get_wtime() - time;
  return seconds > 60;
}

template <typename T>
void print_resume(double percent, T x)
{
  print_log("Resume from " + backup_file());
  print_status(percent, x);
}

/// backup to file
template <typename T, typename J>
void backup(J& json,
            T x,
            int64_t y,
            int64_t z,
            int threads,
            double percent,
            double time)
{
  json["S2_easy"]["x"] = to_string(x);
  json["S2_easy"]["y"] = y;
  json["S2_easy"]["z"] = z;
  json["S2_easy"]["threads"] = threads;
  json["S2_easy"]["percent"] = percent;
  json["S2_easy"]["seconds"] = get_wtime() - time;

  store_backup(json);
}

/// backup thread
template <typename T, typename J>
void backup(J& json,
            int64_t start,
            int64_t b,
            int64_t thread_id,
            T s2_easy)
{
  string tid = "thread" + to_string(thread_id);

  json["S2_easy"]["start"] = start;
  json["S2_easy"][tid]["b"] = b;
  json["S2_easy"][tid]["s2_easy"] = to_string(s2_easy);
}

/// backup result
template <typename T, typename J>
void backup(J& json,
            T x,
            int64_t y,
            int64_t z,
            T s2_easy,
            double time)
{
  json.erase("S2_easy");

  json["S2_easy"]["x"] = to_string(x);
  json["S2_easy"]["y"] = y;
  json["S2_easy"]["z"] = z;
  json["S2_easy"]["s2_easy"] = to_string(s2_easy);
  json["S2_easy"]["percent"] = 100;
  json["S2_easy"]["seconds"] = get_wtime() - time;

  store_backup(json);
}

template <typename T, typename J>
int64_t get_start(J& json,
                  T x,
                  int64_t y,
                  int64_t z,
                  int64_t start)
{
  if (is_resume(json, "S2_easy", x, y, z) &&
      json["S2_easy"].count("start"))
  {
    start = json["S2_easy"]["start"];
  }

  return start;
}

template <typename T, typename J>
int get_threads(J& json,
                T x,
                int64_t y,
                int64_t z,
                int threads)
{
  if (is_resume(json, "S2_easy", x, y, z) &&
      json["S2_easy"].count("threads"))
  {
    double percent = json["S2_easy"]["percent"];
    int backup_threads = json["S2_easy"]["threads"];
    threads = max(threads, backup_threads);
    print_resume(percent, x);
  }

  return threads;
}

template <typename T, typename J>
double get_time(J& json,
                T x,
                int64_t y,
                int64_t z,
                double time)
{
  if (is_resume(json, "S2_easy", x, y, z))
  {
    double seconds = json["S2_easy"]["seconds"];
    time = get_wtime() - seconds;
  }

  return time;
}

/// resume result
template <typename T, typename J>
bool resume(J& json,
            T x,
            int64_t y,
            int64_t z,
            T& s2_easy,
            double& time)
{
  if (is_resume(json, "S2_easy", x, y, z) &&
      json["S2_easy"].count("s2_easy"))
  {
    double percent = json["S2_easy"]["percent"];
    double seconds = json["S2_easy"]["seconds"];

    s2_easy = calculator::eval<T>(json["S2_easy"]["s2_easy"]);
    time = get_wtime() - seconds;
    print_resume(percent, x);
    return true;
  }

  return false;
}

/// resume thread
template <typename T, typename J>
bool resume(J& json,
            T x,
            int64_t y,
            int64_t z,
            int64_t& b,
            int thread_id,
            T& s2_easy)
{
  bool resumed = false;

  if (is_resume(json, "S2_easy", thread_id, x, y, z))
  {
    resumed = true;
    string tid = "thread" + to_string(thread_id);
    b = json["S2_easy"][tid]["b"];
    s2_easy = calculator::eval<T>(json["S2_easy"][tid]["s2_easy"]);
  }

  return resumed;
}

template <typename T, typename Primes>
T S2_easy(T x,
          int64_t y,
          int64_t z,
          int64_t b,
          Primes& primes,
          PiTable& pi)
{
  int64_t prime = primes[b];
  T x2 = x / prime;
  int64_t min_trivial = min(x2 / prime, y);
  int64_t min_clustered = (int64_t) isqrt(x2);
  int64_t min_sparse = z / prime;

  min_clustered = in_between(prime, min_clustered, y);
  min_sparse = in_between(prime, min_sparse, y);

  int64_t l = pi[min_trivial];
  int64_t pi_min_clustered = pi[min_clustered];
  int64_t pi_min_sparse = pi[min_sparse];
  T s2_easy = 0;

  // Find all clustered easy leaves:
  // n = primes[b] * primes[l]
  // x / n <= y && phi(x / n, b - 1) == phi(x / m, b - 1)
  // where phi(x / n, b - 1) = pi(x / n) - b + 2
  while (l > pi_min_clustered)
  {
    int64_t xn = (int64_t) fast_div(x2, primes[l]);
    int64_t phi_xn = pi[xn] - b + 2;
    int64_t xm = (int64_t) fast_div(x2, primes[b + phi_xn - 1]);
    int64_t l2 = pi[xm];
    s2_easy += phi_xn * (l - l2);
    l = l2;
  }

  // Find all sparse easy leaves:
  // n = primes[b] * primes[l]
  // x / n <= y && phi(x / n, b - 1) = pi(x / n) - b + 2
  for (; l > pi_min_sparse; l--)
  {
    int64_t xn = (int64_t) fast_div(x2, primes[l]);
    s2_easy += pi[xn] - b + 2;
  }

  return s2_easy;
}

/// Calculate the contribution of the clustered easy leaves
/// and the sparse easy leaves.
/// @param T  either int64_t or uint128_t.
///
template <typename T, typename Primes>
T S2_easy_OpenMP(T x,
                 int64_t y,
                 int64_t z,
                 int64_t c,
                 Primes& primes,
                 int threads,
                 double& time)
{
  T s2 = 0;
  auto json = load_backup();
  auto copy = json;

  if (resume(json, x, y, z, s2, time))
    return s2;

  if (!is_resume(json, "S2_easy", x, y, z))
    json.erase("S2_easy");

  PiTable pi(y);
  S2Status status(x);
  double backup_time = get_wtime();
  time = get_time(json, x, y, z, time);

  int64_t x13 = iroot<3>(x);
  int64_t pi_x13 = pi[x13];
  int64_t pi_sqrty = pi[isqrt(y)];
  int64_t start = max(c, pi_sqrty) + 1;
  start = get_start(json, x, y, z, start);

  int64_t thread_threshold = 1000;
  threads = ideal_num_threads(threads, x13, thread_threshold);
  threads = get_threads(json, x, y, z, threads);

  #pragma omp parallel for \
      num_threads(threads) reduction(+: s2)
  for (int i = 0; i < threads; i++)
  {
    T s2_easy = 0;
    int64_t b = 0;

    if (resume(copy, x, y, z, b, i, s2_easy))
      s2_easy += S2_easy(x, y, z, b, primes, pi);

    while (true)
    {
      if (is_print())
        status.print(b, pi_x13);

      #pragma omp critical (s2_easy)
      {
        b = start++;

        backup(json, start, b, i, s2_easy);

        if (is_backup(backup_time))
        {
          double percent = status.getPercent(start, pi_x13, start, pi_x13);
          backup(json, x, y, z, threads, percent, time);
          backup_time = get_wtime();
        }
      }

      if (b > pi_x13)
        break;

      s2_easy += S2_easy(x, y, z, b, primes, pi);
    }

    s2 += s2_easy;
  }

  backup(json, x, y, z, s2, time);

  return s2;
}

} // namespace

namespace primecount {

int64_t S2_easy(int64_t x,
                int64_t y,
                int64_t z,
                int64_t c,
                int threads)
{
#ifdef HAVE_MPI
  if (mpi_num_procs() > 1)
    return S2_easy_mpi(x, y, z, c, threads);
#endif

  print_log("");
  print_log("=== S2_easy(x, y) ===");
  print_log("Computation of the easy special leaves");
  print_log(x, y, c, threads);

  double time = get_wtime();
  auto primes = generate_primes<int32_t>(y);
  int64_t s2_easy = S2_easy_OpenMP((intfast64_t) x, y, z, c, primes, threads, time);

  print_log("S2_easy", s2_easy, time);
  return s2_easy;
}

#ifdef HAVE_INT128_T

int128_t S2_easy(int128_t x,
                 int64_t y,
                 int64_t z,
                 int64_t c,
                 int threads)
{
#ifdef HAVE_MPI
  if (mpi_num_procs() > 1)
    return S2_easy_mpi(x, y, z, c, threads);
#endif

  print_log("");
  print_log("=== S2_easy(x, y) ===");
  print_log("Computation of the easy special leaves");
  print_log(x, y, c, threads);

  int128_t s2_easy;
  double time = get_wtime();

  // uses less memory
  if (y <= numeric_limits<uint32_t>::max())
  {
    auto primes = generate_primes<uint32_t>(y);
    s2_easy = S2_easy_OpenMP((intfast128_t) x, y, z, c, primes, threads, time);
  }
  else
  {
    auto primes = generate_primes<int64_t>(y);
    s2_easy = S2_easy_OpenMP((intfast128_t) x, y, z, c, primes, threads, time);
  }

  print_log("S2_easy", s2_easy, time);
  return s2_easy;
}

#endif

} // namespace
<|endoftext|>


<commit_before>/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2008 by Sun Microsystems, Inc.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * $RCSfile: worksheetbuffer.cxx,v $
 * $Revision: 1.4 $
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org 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 version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/

#include "oox/xls/worksheetbuffer.hxx"
#include <rtl/ustrbuf.hxx>
#include <com/sun/star/container/XIndexAccess.hpp>
#include <com/sun/star/container/XNamed.hpp>
#include <com/sun/star/lang/XMultiServiceFactory.hpp>
#include <com/sun/star/i18n/XCharacterClassification.hpp>
#include <com/sun/star/i18n/KParseTokens.hpp>
#include <com/sun/star/i18n/KParseType.hpp>
#include <com/sun/star/sheet/XSpreadsheetDocument.hpp>
#include <com/sun/star/sheet/XExternalSheetName.hpp>
#include <com/sun/star/sheet/XSheetLinkable.hpp>
#include <comphelper/processfactory.hxx>
#include "oox/helper/attributelist.hxx"
#include "oox/helper/containerhelper.hxx"
#include "oox/helper/propertyset.hxx"
#include "oox/helper/recordinputstream.hxx"
#include "oox/core/filterbase.hxx"
#include "oox/xls/biffinputstream.hxx"
#include "oox/xls/excelhandlers.hxx"

using ::rtl::OUString;
using ::rtl::OUStringBuffer;
using ::com::sun::star::uno::Reference;
using ::com::sun::star::uno::Exception;
using ::com::sun::star::uno::UNO_QUERY;
using ::com::sun::star::uno::UNO_QUERY_THROW;
using ::com::sun::star::container::XIndexAccess;
using ::com::sun::star::container::XNameAccess;
using ::com::sun::star::container::XNamed;
using ::com::sun::star::lang::Locale;
using ::com::sun::star::lang::XMultiServiceFactory;
using ::com::sun::star::i18n::ParseResult;
using ::com::sun::star::sheet::XSpreadsheetDocument;
using ::com::sun::star::sheet::XSpreadsheets;
using ::com::sun::star::sheet::XSpreadsheet;
using ::com::sun::star::sheet::XExternalSheetName;
using ::com::sun::star::sheet::XSheetLinkable;

namespace oox {
namespace xls {

// ============================================================================

namespace {

/** Returns the base file name without path and extension. */
OUString lclGetBaseFileName( const OUString& rUrl )
{
    sal_Int32 nFileNamePos = ::std::max< sal_Int32 >( rUrl.lastIndexOf( '/' ) + 1, 0 );
    sal_Int32 nExtPos = rUrl.lastIndexOf( '.' );
    if( nExtPos <= nFileNamePos ) nExtPos = rUrl.getLength();
    return rUrl.copy( nFileNamePos, nExtPos - nFileNamePos );
}

} // namespace

// ============================================================================

OoxSheetInfo::OoxSheetInfo() :
    mnSheetId( -1 ),
    mnState( XML_visible )
{
}

// ============================================================================

WorksheetBuffer::WorksheetBuffer( const WorkbookHelper& rHelper ) :
    WorkbookHelper( rHelper ),
    maIsVisibleProp( CREATE_OUSTRING( "IsVisible" ) )
{
    // character classification service for conversion to valid sheet names
    Reference< XMultiServiceFactory > xFactory = ::comphelper::getProcessServiceFactory();
    mxCharClass.set( xFactory->createInstance( CREATE_OUSTRING( "com.sun.star.i18n.CharacterClassification" ) ), UNO_QUERY );
    OSL_ENSURE( mxCharClass.is(), "WorksheetBuffer::WorksheetBuffer - no character classification service" );
}

void WorksheetBuffer::initializeSingleSheet()
{
    OSL_ENSURE( maSheetInfos.empty(), "WorksheetBuffer::initializeSingleSheet - invalid call" );
    OoxSheetInfo aSheetInfo;
    aSheetInfo.maName = lclGetBaseFileName( getBaseFilter().getFileUrl() );
    insertSheet( aSheetInfo );
}

void WorksheetBuffer::importSheet( const AttributeList& rAttribs )
{
    OoxSheetInfo aSheetInfo;
    aSheetInfo.maId = rAttribs.getString( R_TOKEN( id ) );
    aSheetInfo.maName = rAttribs.getString( XML_name );
    aSheetInfo.mnSheetId = rAttribs.getInteger( XML_sheetId, -1 );
    aSheetInfo.mnState = rAttribs.getToken( XML_state, XML_visible );
    insertSheet( aSheetInfo );
}

void WorksheetBuffer::importSheet( RecordInputStream& rStrm )
{
    sal_Int32 nState;
    OoxSheetInfo aSheetInfo;
    rStrm >> nState >> aSheetInfo.mnSheetId >> aSheetInfo.maId >> aSheetInfo.maName;
    static const sal_Int32 spnStates[] = { XML_visible, XML_hidden, XML_veryHidden };
    aSheetInfo.mnState = STATIC_ARRAY_SELECT( spnStates, nState, XML_visible );
    insertSheet( aSheetInfo );
}

void WorksheetBuffer::importSheet( BiffInputStream& rStrm )
{
    sal_uInt16 nState = 0;
    if( getBiff() >= BIFF5 )
    {
        rStrm.skip( 4 );
        rStrm >> nState;
    }

    OoxSheetInfo aSheetInfo;
    aSheetInfo.maName = (getBiff() == BIFF8) ?
        rStrm.readUniString( rStrm.readuInt8() ) :
        rStrm.readByteString( false, getTextEncoding() );
    static const sal_Int32 spnStates[] = { XML_visible, XML_hidden, XML_veryHidden };
    aSheetInfo.mnState = STATIC_ARRAY_SELECT( spnStates, nState, XML_visible );
    insertSheet( aSheetInfo );
}

sal_Int32 WorksheetBuffer::insertExternalSheet( const OUString& rTargetUrl, const OUString& rSheetName )
{
    // try to find existing external sheet (needed for BIFF4W and BIFF5)
    ExternalSheetName aExtSheet( rTargetUrl, rSheetName );
    ExternalSheetMap::iterator aIt = maExternalSheets.find( aExtSheet );
    if( aIt != maExternalSheets.end() )
        return aIt->second;

    // create a new external sheet
    sal_Int16& rnSheet = maExternalSheets[ aExtSheet ];
    rnSheet = getTotalSheetCount();
    insertSheet( OUString(), rnSheet, false );

    try
    {
        Reference< XSpreadsheet > xSheet = getSheet( rnSheet );
        // use base file name as sheet name, if sheet name is missing (e.g. links to BIFF2-BIFF4 files)
        OUString aSheetName = rSheetName;
        if( aSheetName.getLength() == 0 )
            aSheetName = lclGetBaseFileName( rTargetUrl );
        // link the sheet
        Reference< XSheetLinkable > xLinkable( xSheet, UNO_QUERY_THROW );
        xLinkable->link( rTargetUrl, aSheetName, OUString(), OUString(), ::com::sun::star::sheet::SheetLinkMode_VALUE );
        // set the special external sheet name
        Reference< XExternalSheetName > xSheetName( xSheet, UNO_QUERY_THROW );
        xSheetName->setExternalName( xLinkable->getLinkUrl(), xLinkable->getLinkSheetName() );
    }
    catch( Exception& )
    {
    }

    // return sheet index
    return rnSheet;
}

sal_Int32 WorksheetBuffer::getInternalSheetCount() const
{
    return static_cast< sal_Int32 >( maSheetInfos.size() );
}

OUString WorksheetBuffer::getSheetRelId( sal_Int32 nSheet ) const
{
    OUString aRelId;
    if( const OoxSheetInfo* pInfo = getSheetInfo( nSheet ) )
        aRelId = pInfo->maId;
    return aRelId;
}

OUString WorksheetBuffer::getFinalSheetName( sal_Int32 nSheet ) const
{
    OUString aName;
    if( const OoxSheetInfo* pInfo = getSheetInfo( nSheet ) )
        aName = pInfo->maFinalName;
    return aName;
}

OUString WorksheetBuffer::getFinalSheetName( const OUString& rName ) const
{
    for( SheetInfoVec::const_iterator aIt = maSheetInfos.begin(), aEnd = maSheetInfos.end(); aIt != aEnd; ++aIt )
        // TODO: handle encoded characters
        if( aIt->maName.equalsIgnoreAsciiCase( rName ) )
            return aIt->maFinalName;
    return OUString();
}

sal_Int32 WorksheetBuffer::getFinalSheetIndex( const OUString& rName ) const
{
    for( SheetInfoVec::const_iterator aIt = maSheetInfos.begin(), aEnd = maSheetInfos.end(); aIt != aEnd; ++aIt )
        // TODO: handle encoded characters
        if( aIt->maName.equalsIgnoreAsciiCase( rName ) )
            return static_cast< sal_Int32 >( aIt - maSheetInfos.begin() );
    return -1;
}

// private --------------------------------------------------------------------

sal_Int16 WorksheetBuffer::getTotalSheetCount() const
{
    try
    {
        Reference< XIndexAccess > xSheetsIA( getDocument()->getSheets(), UNO_QUERY_THROW );
        return static_cast< sal_Int16 >( xSheetsIA->getCount() );
    }
    catch( Exception& )
    {
        OSL_ENSURE( false, "WorksheetBuffer::getTotalSheetCount - cannot get sheet count" );
    }
    return 1;
}

const OoxSheetInfo* WorksheetBuffer::getSheetInfo( sal_Int32 nSheet ) const
{
    return ((0 <= nSheet) && (static_cast< size_t >( nSheet ) < maSheetInfos.size())) ?
        &maSheetInfos[ static_cast< size_t >( nSheet ) ] : 0;
}

OUString WorksheetBuffer::convertToValidSheetName( const OUString& rName, sal_Unicode cReplaceChar ) const
{
    if( !mxCharClass.is() ) return rName;

    using namespace ::com::sun::star::i18n::KParseTokens;
    using namespace ::com::sun::star::i18n::KParseType;

    OUStringBuffer aFinalName( rName );
    Locale aLocale( CREATE_OUSTRING( "en" ), CREATE_OUSTRING( "US" ), OUString() );
    sal_Int32 nStartFlags = ANY_LETTER_OR_NUMBER | ASC_UNDERSCORE;
    sal_Int32 nContFlags = nStartFlags;
    OUString aStartChars;
    OUString aContChars( sal_Unicode( ' ' ) );
    sal_Int32 nStartPos = 0;
    while( nStartPos < aFinalName.getLength() )
    {
        ParseResult aRes = mxCharClass->parsePredefinedToken(
            IDENTNAME, rName, nStartPos, aLocale, nStartFlags, aStartChars, nContFlags, aContChars );
        if( aRes.EndPos < aFinalName.getLength() )
        {
            aFinalName.setCharAt( aRes.EndPos, cReplaceChar );
            nStartFlags = nContFlags;
            aStartChars = aContChars;
        }
        nStartPos = aRes.EndPos + 1;
    }
    return aFinalName.makeStringAndClear();
}

OUString WorksheetBuffer::insertSheet( const OUString& rName, sal_Int16 nSheet, bool bVisible )
{
    OUString aFinalName = (rName.getLength() == 0) ? CREATE_OUSTRING( "Sheet" ) : convertToValidSheetName( rName, '_' );
    try
    {
        Reference< XSpreadsheets > xSheets( getDocument()->getSheets(), UNO_QUERY_THROW );
        Reference< XIndexAccess > xSheetsIA( xSheets, UNO_QUERY_THROW );
        Reference< XNameAccess > xSheetsNA( xSheets, UNO_QUERY_THROW );
        PropertySet aPropSet;
        if( nSheet < xSheetsIA->getCount() )
        {
            // existing sheet - try to rename
            Reference< XNamed > xSheetName( xSheetsIA->getByIndex( nSheet ), UNO_QUERY_THROW );
            if( xSheetName->getName() != aFinalName )
            {
                aFinalName = ContainerHelper::getUnusedName( xSheetsNA, aFinalName, ' ' );
                xSheetName->setName( aFinalName );
            }
            aPropSet.set( xSheetName );
        }
        else
        {
            // new sheet - insert with unused name
            aFinalName = ContainerHelper::getUnusedName( xSheetsNA, aFinalName, ' ' );
            xSheets->insertNewByName( aFinalName, nSheet );
            aPropSet.set( xSheetsIA->getByIndex( nSheet ) );
        }

        // sheet properties
        aPropSet.setProperty( maIsVisibleProp, bVisible );
    }
    catch( Exception& )
    {
        OSL_ENSURE( false, "WorksheetBuffer::insertSheet - cannot insert or rename worksheet" );
    }
    return aFinalName;
}

void WorksheetBuffer::insertSheet( const OoxSheetInfo& rSheetInfo )
{
    OSL_ENSURE( maExternalSheets.empty(), "WorksheetBuffer::insertSheet - external sheets exist already" );
    sal_Int16 nSheet = static_cast< sal_Int16 >( maSheetInfos.size() );
    maSheetInfos.push_back( rSheetInfo );
    maSheetInfos.back().maFinalName = insertSheet( rSheetInfo.maName, nSheet, rSheetInfo.mnState == XML_visible );
}

// ============================================================================

} // namespace xls
} // namespace oox

<commit_msg>INTEGRATION: CWS xmlfilter05 (1.3.4); FILE MERGED 2008/05/02 11:19:28 hbrinkm 1.3.4.4: RESYNC: (1.3-1.4); FILE MERGED 2008/04/16 13:10:12 dr 1.3.4.3: new optional token handling, fix default rotation in 3d charts 2008/04/02 12:42:04 hbrinkm 1.3.4.2: merged changes from xmlfilter04 to xmlfilter05 2008/04/01 15:38:48 hbrinkm 1.3.4.1: 'Merged xmlfilter04'<commit_after>/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2008 by Sun Microsystems, Inc.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * $RCSfile: worksheetbuffer.cxx,v $
 * $Revision: 1.5 $
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org 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 version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/

#include "oox/xls/worksheetbuffer.hxx"
#include <rtl/ustrbuf.hxx>
#include <com/sun/star/container/XIndexAccess.hpp>
#include <com/sun/star/container/XNamed.hpp>
#include <com/sun/star/lang/XMultiServiceFactory.hpp>
#include <com/sun/star/i18n/XCharacterClassification.hpp>
#include <com/sun/star/i18n/KParseTokens.hpp>
#include <com/sun/star/i18n/KParseType.hpp>
#include <com/sun/star/sheet/XSpreadsheetDocument.hpp>
#include <com/sun/star/sheet/XExternalSheetName.hpp>
#include <com/sun/star/sheet/XSheetLinkable.hpp>
#include <comphelper/processfactory.hxx>
#include "oox/helper/attributelist.hxx"
#include "oox/helper/containerhelper.hxx"
#include "oox/helper/propertyset.hxx"
#include "oox/helper/recordinputstream.hxx"
#include "oox/core/filterbase.hxx"
#include "oox/xls/biffinputstream.hxx"
#include "oox/xls/excelhandlers.hxx"

using ::rtl::OUString;
using ::rtl::OUStringBuffer;
using ::com::sun::star::uno::Reference;
using ::com::sun::star::uno::Exception;
using ::com::sun::star::uno::UNO_QUERY;
using ::com::sun::star::uno::UNO_QUERY_THROW;
using ::com::sun::star::container::XIndexAccess;
using ::com::sun::star::container::XNameAccess;
using ::com::sun::star::container::XNamed;
using ::com::sun::star::lang::Locale;
using ::com::sun::star::lang::XMultiServiceFactory;
using ::com::sun::star::i18n::ParseResult;
using ::com::sun::star::sheet::XSpreadsheetDocument;
using ::com::sun::star::sheet::XSpreadsheets;
using ::com::sun::star::sheet::XSpreadsheet;
using ::com::sun::star::sheet::XExternalSheetName;
using ::com::sun::star::sheet::XSheetLinkable;

namespace oox {
namespace xls {

// ============================================================================

namespace {

/** Returns the base file name without path and extension. */
OUString lclGetBaseFileName( const OUString& rUrl )
{
    sal_Int32 nFileNamePos = ::std::max< sal_Int32 >( rUrl.lastIndexOf( '/' ) + 1, 0 );
    sal_Int32 nExtPos = rUrl.lastIndexOf( '.' );
    if( nExtPos <= nFileNamePos ) nExtPos = rUrl.getLength();
    return rUrl.copy( nFileNamePos, nExtPos - nFileNamePos );
}

} // namespace

// ============================================================================

OoxSheetInfo::OoxSheetInfo() :
    mnSheetId( -1 ),
    mnState( XML_visible )
{
}

// ============================================================================

WorksheetBuffer::WorksheetBuffer( const WorkbookHelper& rHelper ) :
    WorkbookHelper( rHelper ),
    maIsVisibleProp( CREATE_OUSTRING( "IsVisible" ) )
{
    // character classification service for conversion to valid sheet names
    Reference< XMultiServiceFactory > xFactory = ::comphelper::getProcessServiceFactory();
    mxCharClass.set( xFactory->createInstance( CREATE_OUSTRING( "com.sun.star.i18n.CharacterClassification" ) ), UNO_QUERY );
    OSL_ENSURE( mxCharClass.is(), "WorksheetBuffer::WorksheetBuffer - no character classification service" );
}

void WorksheetBuffer::initializeSingleSheet()
{
    OSL_ENSURE( maSheetInfos.empty(), "WorksheetBuffer::initializeSingleSheet - invalid call" );
    OoxSheetInfo aSheetInfo;
    aSheetInfo.maName = lclGetBaseFileName( getBaseFilter().getFileUrl() );
    insertSheet( aSheetInfo );
}

void WorksheetBuffer::importSheet( const AttributeList& rAttribs )
{
    OoxSheetInfo aSheetInfo;
    aSheetInfo.maId = rAttribs.getString( R_TOKEN( id ), OUString() );
    aSheetInfo.maName = rAttribs.getString( XML_name, OUString() );
    aSheetInfo.mnSheetId = rAttribs.getInteger( XML_sheetId, -1 );
    aSheetInfo.mnState = rAttribs.getToken( XML_state, XML_visible );
    insertSheet( aSheetInfo );
}

void WorksheetBuffer::importSheet( RecordInputStream& rStrm )
{
    sal_Int32 nState;
    OoxSheetInfo aSheetInfo;
    rStrm >> nState >> aSheetInfo.mnSheetId >> aSheetInfo.maId >> aSheetInfo.maName;
    static const sal_Int32 spnStates[] = { XML_visible, XML_hidden, XML_veryHidden };
    aSheetInfo.mnState = STATIC_ARRAY_SELECT( spnStates, nState, XML_visible );
    insertSheet( aSheetInfo );
}

void WorksheetBuffer::importSheet( BiffInputStream& rStrm )
{
    sal_uInt16 nState = 0;
    if( getBiff() >= BIFF5 )
    {
        rStrm.skip( 4 );
        rStrm >> nState;
    }

    OoxSheetInfo aSheetInfo;
    aSheetInfo.maName = (getBiff() == BIFF8) ?
        rStrm.readUniString( rStrm.readuInt8() ) :
        rStrm.readByteString( false, getTextEncoding() );
    static const sal_Int32 spnStates[] = { XML_visible, XML_hidden, XML_veryHidden };
    aSheetInfo.mnState = STATIC_ARRAY_SELECT( spnStates, nState, XML_visible );
    insertSheet( aSheetInfo );
}

sal_Int32 WorksheetBuffer::insertExternalSheet( const OUString& rTargetUrl, const OUString& rSheetName )
{
    // try to find existing external sheet (needed for BIFF4W and BIFF5)
    ExternalSheetName aExtSheet( rTargetUrl, rSheetName );
    ExternalSheetMap::iterator aIt = maExternalSheets.find( aExtSheet );
    if( aIt != maExternalSheets.end() )
        return aIt->second;

    // create a new external sheet
    sal_Int16& rnSheet = maExternalSheets[ aExtSheet ];
    rnSheet = getTotalSheetCount();
    insertSheet( OUString(), rnSheet, false );

    try
    {
        Reference< XSpreadsheet > xSheet = getSheet( rnSheet );
        // use base file name as sheet name, if sheet name is missing (e.g. links to BIFF2-BIFF4 files)
        OUString aSheetName = rSheetName;
        if( aSheetName.getLength() == 0 )
            aSheetName = lclGetBaseFileName( rTargetUrl );
        // link the sheet
        Reference< XSheetLinkable > xLinkable( xSheet, UNO_QUERY_THROW );
        xLinkable->link( rTargetUrl, aSheetName, OUString(), OUString(), ::com::sun::star::sheet::SheetLinkMode_VALUE );
        // set the special external sheet name
        Reference< XExternalSheetName > xSheetName( xSheet, UNO_QUERY_THROW );
        xSheetName->setExternalName( xLinkable->getLinkUrl(), xLinkable->getLinkSheetName() );
    }
    catch( Exception& )
    {
    }

    // return sheet index
    return rnSheet;
}

sal_Int32 WorksheetBuffer::getInternalSheetCount() const
{
    return static_cast< sal_Int32 >( maSheetInfos.size() );
}

OUString WorksheetBuffer::getSheetRelId( sal_Int32 nSheet ) const
{
    OUString aRelId;
    if( const OoxSheetInfo* pInfo = getSheetInfo( nSheet ) )
        aRelId = pInfo->maId;
    return aRelId;
}

OUString WorksheetBuffer::getFinalSheetName( sal_Int32 nSheet ) const
{
    OUString aName;
    if( const OoxSheetInfo* pInfo = getSheetInfo( nSheet ) )
        aName = pInfo->maFinalName;
    return aName;
}

OUString WorksheetBuffer::getFinalSheetName( const OUString& rName ) const
{
    for( SheetInfoVec::const_iterator aIt = maSheetInfos.begin(), aEnd = maSheetInfos.end(); aIt != aEnd; ++aIt )
        // TODO: handle encoded characters
        if( aIt->maName.equalsIgnoreAsciiCase( rName ) )
            return aIt->maFinalName;
    return OUString();
}

sal_Int32 WorksheetBuffer::getFinalSheetIndex( const OUString& rName ) const
{
    for( SheetInfoVec::const_iterator aIt = maSheetInfos.begin(), aEnd = maSheetInfos.end(); aIt != aEnd; ++aIt )
        // TODO: handle encoded characters
        if( aIt->maName.equalsIgnoreAsciiCase( rName ) )
            return static_cast< sal_Int32 >( aIt - maSheetInfos.begin() );
    return -1;
}

// private --------------------------------------------------------------------

sal_Int16 WorksheetBuffer::getTotalSheetCount() const
{
    try
    {
        Reference< XIndexAccess > xSheetsIA( getDocument()->getSheets(), UNO_QUERY_THROW );
        return static_cast< sal_Int16 >( xSheetsIA->getCount() );
    }
    catch( Exception& )
    {
        OSL_ENSURE( false, "WorksheetBuffer::getTotalSheetCount - cannot get sheet count" );
    }
    return 1;
}

const OoxSheetInfo* WorksheetBuffer::getSheetInfo( sal_Int32 nSheet ) const
{
    return ((0 <= nSheet) && (static_cast< size_t >( nSheet ) < maSheetInfos.size())) ?
        &maSheetInfos[ static_cast< size_t >( nSheet ) ] : 0;
}

OUString WorksheetBuffer::convertToValidSheetName( const OUString& rName, sal_Unicode cReplaceChar ) const
{
    if( !mxCharClass.is() ) return rName;

    using namespace ::com::sun::star::i18n::KParseTokens;
    using namespace ::com::sun::star::i18n::KParseType;

    OUStringBuffer aFinalName( rName );
    Locale aLocale( CREATE_OUSTRING( "en" ), CREATE_OUSTRING( "US" ), OUString() );
    sal_Int32 nStartFlags = ANY_LETTER_OR_NUMBER | ASC_UNDERSCORE;
    sal_Int32 nContFlags = nStartFlags;
    OUString aStartChars;
    OUString aContChars( sal_Unicode( ' ' ) );
    sal_Int32 nStartPos = 0;
    while( nStartPos < aFinalName.getLength() )
    {
        ParseResult aRes = mxCharClass->parsePredefinedToken(
            IDENTNAME, rName, nStartPos, aLocale, nStartFlags, aStartChars, nContFlags, aContChars );
        if( aRes.EndPos < aFinalName.getLength() )
        {
            aFinalName.setCharAt( aRes.EndPos, cReplaceChar );
            nStartFlags = nContFlags;
            aStartChars = aContChars;
        }
        nStartPos = aRes.EndPos + 1;
    }
    return aFinalName.makeStringAndClear();
}

OUString WorksheetBuffer::insertSheet( const OUString& rName, sal_Int16 nSheet, bool bVisible )
{
    OUString aFinalName = (rName.getLength() == 0) ? CREATE_OUSTRING( "Sheet" ) : convertToValidSheetName( rName, '_' );
    try
    {
        Reference< XSpreadsheets > xSheets( getDocument()->getSheets(), UNO_QUERY_THROW );
        Reference< XIndexAccess > xSheetsIA( xSheets, UNO_QUERY_THROW );
        Reference< XNameAccess > xSheetsNA( xSheets, UNO_QUERY_THROW );
        PropertySet aPropSet;
        if( nSheet < xSheetsIA->getCount() )
        {
            // existing sheet - try to rename
            Reference< XNamed > xSheetName( xSheetsIA->getByIndex( nSheet ), UNO_QUERY_THROW );
            if( xSheetName->getName() != aFinalName )
            {
                aFinalName = ContainerHelper::getUnusedName( xSheetsNA, aFinalName, ' ' );
                xSheetName->setName( aFinalName );
            }
            aPropSet.set( xSheetName );
        }
        else
        {
            // new sheet - insert with unused name
            aFinalName = ContainerHelper::getUnusedName( xSheetsNA, aFinalName, ' ' );
            xSheets->insertNewByName( aFinalName, nSheet );
            aPropSet.set( xSheetsIA->getByIndex( nSheet ) );
        }

        // sheet properties
        aPropSet.setProperty( maIsVisibleProp, bVisible );
    }
    catch( Exception& )
    {
        OSL_ENSURE( false, "WorksheetBuffer::insertSheet - cannot insert or rename worksheet" );
    }
    return aFinalName;
}

void WorksheetBuffer::insertSheet( const OoxSheetInfo& rSheetInfo )
{
    OSL_ENSURE( maExternalSheets.empty(), "WorksheetBuffer::insertSheet - external sheets exist already" );
    sal_Int16 nSheet = static_cast< sal_Int16 >( maSheetInfos.size() );
    maSheetInfos.push_back( rSheetInfo );
    maSheetInfos.back().maFinalName = insertSheet( rSheetInfo.maName, nSheet, rSheetInfo.mnState == XML_visible );
}

// ============================================================================

} // namespace xls
} // namespace oox

<|endoftext|>


<commit_before>/**
 * @file WebotsController.cpp
 *
 * @author Schlotter, Benjamin
 * @brief Interface for the Webots simulator
 *
 */

#include "WebotsController.h"

#include <iostream>
#include <fstream>

#include "PlatformInterface/Platform.h"
#include "Tools/Communication/MessageQueue/MessageQueue4Threads.h"

#include <Tools/ImageProcessing/ColorModelConversions.h>
#include <Tools/StringTools.h>
#include <Tools/ThreadUtil.h>
#include <Tools/NaoTime.h>
#include <Tools/NaoInfo.h>
#include <Tools/Math/Common.h>
#include <Tools/Communication/ASCIIEncoder.h>

using namespace std;

  WebotsController::WebotsController(const std::string& name)
  :
  thePlatformName(name),
  theSyncMode(false),
  theSenseTime(0),
  theStepTime(0),
  exiting(false)
{
  // register input
  registerInput<AccelerometerData>(*this);
  registerInput<FrameInfo>(*this);
  registerInput<SensorJointData>(*this);
  registerInput<Image>(*this);
  registerInput<FSRData>(*this);
  registerInput<GyrometerData>(*this);
  registerInput<InertialSensorData>(*this);
  registerInput<BatteryData>(*this);
  registerInput<VirtualVision>(*this);
  registerInput<VirtualVisionTop>(*this);
  registerInput<TeamMessageDataIn>(*this);
  registerInput<GameData>(*this);
  registerInput<GPSData>(*this);
  registerInput<BatteryData>(*this);

  // register output
  registerOutput<const MotorJointData>(*this);
  registerOutput<const TeamMessageDataOut>(*this);

  // debug
  registerInput<DebugMessageInCognition>(*this);
  registerInput<DebugMessageInMotion>(*this);
  registerOutput<DebugMessageOut>(*this);

  GError *err = NULL;
  socket = g_socket_new(G_SOCKET_FAMILY_IPV4, G_SOCKET_TYPE_STREAM, G_SOCKET_PROTOCOL_TCP, &err);
  if (err)
  {
    socket = NULL;
    std::cout << "[WARN] Could not create a socket. This is a fatal error and communication is available. Error message:"
              << std::endl << err->message << std::endl;
    g_error_free (err);
  }
}

WebotsController::~WebotsController()
{
  if (socket != NULL) {
    g_socket_close(socket, NULL);
  }
}

bool WebotsController::connect(const std::string& host, int port)
{
  if(socket == NULL) {
    return false;
  }

  cout << "[WebotsController] connecting to " << host << ":" << port << endl;

  gboolean conn = false;
  GCancellable* cancellable = NULL;
  GSocketAddress* sockaddr = NULL;
  GError* conn_error = NULL;
  GError* error = NULL;

  GSocketConnectable* addr = g_network_address_new(host.c_str(),static_cast<guint16> (port));
  GSocketAddressEnumerator* enumerator = g_socket_connectable_enumerate(addr);
  g_object_unref(addr);

  /**
  * Try each sockaddr until we succeed. Record the first
  * connection error, but not any further ones (since they'll probably
  * be basically the same as the first).
  */
  while (!conn && (sockaddr = g_socket_address_enumerator_next(enumerator, cancellable, &error)))
  {
    conn = g_socket_connect(socket, sockaddr, NULL, conn_error ? NULL : &conn_error);
    g_object_unref(sockaddr);
  }
  g_object_unref(enumerator);
  if (conn)
  {
    /**
    * We couldn't connect to the first address, but we succeeded
    * in connecting to a later address.
    */
    if (conn_error) {
      g_error_free (conn_error);
    }
    return true;
  }

  if(error) {
    std::cout  << "[WARN] Could not connect:" << std::endl << error->message << std::endl;
    g_error_free(error);
  }

  if (conn_error) {
    std::cout << "[WARN] Could not connect:" << std::endl << conn_error->message << std::endl;
    g_error_free(conn_error);
  }

  return false;
}//end connect

bool WebotsController::init(
  const std::string& modelPath,
  const std::string& parameterTeamName,
  unsigned int parameterTeamNumber,
  unsigned int parameterPlayerNumber,
  const std::string& server,
  unsigned int port,
  bool sync)
{
  Platform::getInstance().init(this);

  Configuration& config = Platform::getInstance().theConfiguration;

  // set the team number first
  unsigned int teamNumber;
  if (parameterTeamNumber != 0) {
    teamNumber = parameterTeamNumber;
  } else if (config.hasKey("player", "TeamNumber")) {
    teamNumber = config.getInt("player", "TeamNumber");
  } else {
    teamNumber = 4;
  }

  // use the player number if one is given, otherwise use the number from the simulation
  unsigned int playerNumber;
  if(parameterPlayerNumber != 0) {
    playerNumber = parameterPlayerNumber;
  } else if(config.hasKey("player", "PlayerNumber") && config.getInt("player", "PlayerNumber") != 0) {
    playerNumber = config.getInt("player", "PlayerNumber");
  } else {
    playerNumber = 0;
  }

  // use the team name if one is given, otherwise generate a name
  string teamName;
  if (!parameterTeamName.empty()) {
    teamName = parameterTeamName;
  } else if (config.hasKey("player", "TeamName")) {
    teamName = config.getString("player", "TeamName");
  } else {
    teamName = "NaoTH-" + std::to_string(teamNumber);
  }

  theSyncMode = sync;

  // connect to the simulator
  if(!connect(server, port)) {
    std::cerr << "WebotsController could not connect" << std::endl;
    return false;
  }
  theSocket.init(socket);

  // TODO: send create command to simulator
  //"rsg/agent/naov4/nao.rsg";
  theSocket << "(scene " << modelPath << ")" << send;

  // wait the response
  getSensorData(theSensorData);

  std::cout << "Sensordata: " << theSensorData << std::endl;

  // initialize the teamname and number
  //theSocket << "(init (teamname " << theGameInfo.teamName << ")(unum " << theGameInfo.playerNumber << "))" << theSync << send;

  cout << "NaoTH Simpark initialization successful: " << teamName << " " << playerNumber << endl;

  //DEBUG_REQUEST_REGISTER("SimSparkController:beam", "beam to start pose", false);
  //REGISTER_DEBUG_COMMAND("beam", "beam to given pose", this);

  // hack?
  config.setInt("player", "TeamNumber", teamNumber);
  config.setInt("player", "PlayerNumber", playerNumber);
  config.setString("player", "TeamName", teamName);

#ifdef DEBUG
  // calculate debug communicaiton port
  unsigned short debugPort = static_cast<short unsigned int> (5000 + (teamNumber*100) + playerNumber);
  theDebugServer.start(debugPort);
#endif

  theLastSenseTime = NaoTime::getNaoTimeInMilliSeconds();
  theLastActTime = theLastSenseTime;
  calculateNextActTime();

  return true;
}

void WebotsController::main()
{
  if ( theSyncMode ) {
    singleThreadMain();
  } else {
    multiThreadsMain();
  }
}

void WebotsController::singleThreadMain()
{
  cout << "SimSpark Controller runs in single thread" << endl;
  while ( getSensorData(theSensorData) )
  {
    /*
    updateSensors(theSensorData);
    if ( isNewImage || isNewVirtualVision )
    {
      callCognition();
    }
    */
    PlatformInterface::runMotion();
    act();
  }//end while
}//end main

void WebotsController::motionLoop()
{
  while ( !exiting )
  {
    std::string data;
    {
      std::unique_lock<std::mutex> lock(theSensorDataMutex);
      theSensorDataCond.wait(lock);
      data = theSensorData;
      theSensorData = "";
    }
    PlatformInterface::runMotion();
  }
}//end motionLoop

void WebotsController::cognitionLoop()
{
  while (!exiting)
  {
    callCognition();
  }
}//end cognitionLoop

void WebotsController::callCognition()
{
  if(cognitionRegistered())
  {
    getCognitionInput();
    if ( !exiting )
    {
      PlatformInterface::callCognition();
      setCognitionOutput();
    }
  }
}//end callCognition

void WebotsController::senseLoop()
{
  while( true )
  {
    string data;
    if ( !getSensorData(data) )
    {
      break;
    }

    {
      std::unique_lock<std::mutex> lock(theSensorDataMutex);
      if ( !theSensorData.empty() )
      {
        cerr<<"[Warning] the sensor data @ " << theLastSenseTime << " is dropped!"<<endl;
      }
      theSensorData = data;
    }
    theTimeCond.notify_one();
    theSensorDataCond.notify_one();
  }

  exiting = true;
  theSensorDataCond.notify_one(); // tell motion to exit
  theTimeCond.notify_one(); // tell act loop to exit
  theCognitionInputCond.notify_one(); // tell cognition to exit
}

void WebotsController::actLoop()
{
  while( !exiting )
  {
    { // NOTE: lock object lives only in this code block
      std::unique_lock<std::mutex> lock(theTimeMutex);
      theTimeCond.wait(lock);
      calculateNextActTime();
    }

    unsigned int now = NaoTime::getNaoTimeInMilliSeconds();
    if ( theNextActTime > now )
    {
      ThreadUtil::sleep(theNextActTime - now);
    }

    act();
  }
}

void WebotsController::act()
{
  // send command
  std::unique_lock<std::mutex> lock(theActDataMutex);
  try {
    //theSocket << theActData.str() << theSync << send;
  }
  catch(std::runtime_error& exp)
  {
    cerr<<"can not send data to server, because of "<<exp.what()<<endl;
  }
}

void WebotsController::multiThreadsMain()
{
  cout << "Webots Controller runs in multi-threads" << endl;

  std::thread senseThread = std::thread([this]{this->senseLoop();});
  std::thread actThread = std::thread([this]{this->actLoop();});
  std::thread motionThread = std::thread([this]{this->motionLoop();});

  cognitionLoop();

  if(motionThread.joinable()) {
    motionThread.join();
  }
  if(actThread.joinable()) {
    actThread.join();
  }
  if(senseThread.joinable()) {
    senseThread.join();
  }
}//end multiThreadsMain

void WebotsController::getMotionInput()
{
  PlatformInterface::getMotionInput();

  /*
  for (int i = 0; i < JointData::numOfJoint; i++) {
    theSensorJointData.stiffness[i] = theLastSensorJointData.stiffness[i];
  }
  theLastSensorJointData = theSensorJointData;
  */
}

void WebotsController::setMotionOutput()
{
  PlatformInterface::setMotionOutput();

  /*
  {
    std::unique_lock<std::mutex> lock(theActDataMutex);
    say();
    autoBeam();
    jointControl();
    theActData << theSync;
  }
  */
}

void WebotsController::getCognitionInput()
{
  /*
  std::unique_lock<std::mutex> lock(theCognitionInputMutex);
  while (!isNewImage && !isNewVirtualVision && !exiting )
  {
    theCognitionInputCond.wait(lock);
  }

  PlatformInterface::getCognitionInput();
  isNewVirtualVision = false;
  isNewImage = false;
  */
}

void WebotsController::setCognitionOutput()
{
  std::unique_lock<std::mutex> lock(theCognitionOutputMutex);
  PlatformInterface::setCognitionOutput();
}

bool WebotsController::getSensorData(std::string& data)
{
  try {
    theSocket >> data;

    // Test the message pack parsing
    msgpack::object_handle oh = msgpack::unpack(data.data(), data.size());

    // deserialized object is valid during the msgpack::object_handle instance is alive.
    msgpack::object deserialized = oh.get();

    // msgpack::object supports ostream.
    std::cout << deserialized << std::endl;

    theLastSenseTime = NaoTime::getNaoTimeInMilliSeconds();
  }
  catch (std::runtime_error& exp)
  {
    cerr<<"can not get data from server, because of "<<exp.what()<<endl;
    return false;
  }
  return true;
}

void WebotsController::get(FrameInfo& data)
{
  //data.setTime(theFrameInfo.getTime());
  data.setFrameNumber(data.getFrameNumber() + 1);
}

void WebotsController::get(SensorJointData& data)
{

}

void WebotsController::get(AccelerometerData& data)
{

}

void WebotsController::get(BatteryData& data)
{

}

void WebotsController::get(GPSData& data)
{

}

void WebotsController::get(Image& data)
{
}//end get

void WebotsController::get(GyrometerData& data)
{

}

void WebotsController::get(FSRData& data)
{

}

void WebotsController::get(InertialSensorData& data)
{

}

void WebotsController::get(VirtualVision& data)
{

}

void WebotsController::get(VirtualVisionTop& data)
{

}

void WebotsController::get(GameData& data)
{

}

void WebotsController::set(const MotorJointData& data)
{

}

void WebotsController::get(TeamMessageDataIn& data)
{

}

void WebotsController::set(const TeamMessageDataOut& data)
{

}

MessageQueue* WebotsController::createMessageQueue(const std::string& /*name*/)
{
  if ( theSyncMode ) {
    return new MessageQueue();
  } else {
    return new MessageQueue4Threads();
  }
}

void WebotsController::calculateNextActTime()
{
   theNextActTime = theLastSenseTime + 10;
   while(theLastActTime > theNextActTime)
   {
     theNextActTime += getBasicTimeStep();
   }
}
<commit_msg>comment<commit_after>/**
 * @file WebotsController.cpp
 *
 * @author Schlotter, Benjamin
 * @brief Interface for the Webots simulator
 *
 */

#include "WebotsController.h"

#include <iostream>
#include <fstream>

#include "PlatformInterface/Platform.h"
#include "Tools/Communication/MessageQueue/MessageQueue4Threads.h"

#include <Tools/ImageProcessing/ColorModelConversions.h>
#include <Tools/StringTools.h>
#include <Tools/ThreadUtil.h>
#include <Tools/NaoTime.h>
#include <Tools/NaoInfo.h>
#include <Tools/Math/Common.h>
#include <Tools/Communication/ASCIIEncoder.h>

using namespace std;

  WebotsController::WebotsController(const std::string& name)
  :
  thePlatformName(name),
  theSyncMode(false),
  theSenseTime(0),
  theStepTime(0),
  exiting(false)
{
  // register input
  registerInput<AccelerometerData>(*this);
  registerInput<FrameInfo>(*this);
  registerInput<SensorJointData>(*this);
  registerInput<Image>(*this);
  registerInput<FSRData>(*this);
  registerInput<GyrometerData>(*this);
  registerInput<InertialSensorData>(*this);
  registerInput<BatteryData>(*this);
  registerInput<VirtualVision>(*this);
  registerInput<VirtualVisionTop>(*this);
  registerInput<TeamMessageDataIn>(*this);
  registerInput<GameData>(*this);
  registerInput<GPSData>(*this);
  registerInput<BatteryData>(*this);

  // register output
  registerOutput<const MotorJointData>(*this);
  registerOutput<const TeamMessageDataOut>(*this);

  // debug
  registerInput<DebugMessageInCognition>(*this);
  registerInput<DebugMessageInMotion>(*this);
  registerOutput<DebugMessageOut>(*this);

  GError *err = NULL;
  socket = g_socket_new(G_SOCKET_FAMILY_IPV4, G_SOCKET_TYPE_STREAM, G_SOCKET_PROTOCOL_TCP, &err);
  if (err)
  {
    socket = NULL;
    std::cout << "[WARN] Could not create a socket. This is a fatal error and communication is available. Error message:"
              << std::endl << err->message << std::endl;
    g_error_free (err);
  }
}

WebotsController::~WebotsController()
{
  if (socket != NULL) {
    g_socket_close(socket, NULL);
  }
}

bool WebotsController::connect(const std::string& host, int port)
{
  if(socket == NULL) {
    return false;
  }

  cout << "[WebotsController] connecting to " << host << ":" << port << endl;

  gboolean conn = false;
  GCancellable* cancellable = NULL;
  GSocketAddress* sockaddr = NULL;
  GError* conn_error = NULL;
  GError* error = NULL;

  GSocketConnectable* addr = g_network_address_new(host.c_str(),static_cast<guint16> (port));
  GSocketAddressEnumerator* enumerator = g_socket_connectable_enumerate(addr);
  g_object_unref(addr);

  /**
  * Try each sockaddr until we succeed. Record the first
  * connection error, but not any further ones (since they'll probably
  * be basically the same as the first).
  */
  while (!conn && (sockaddr = g_socket_address_enumerator_next(enumerator, cancellable, &error)))
  {
    conn = g_socket_connect(socket, sockaddr, NULL, conn_error ? NULL : &conn_error);
    g_object_unref(sockaddr);
  }
  g_object_unref(enumerator);
  if (conn)
  {
    /**
    * We couldn't connect to the first address, but we succeeded
    * in connecting to a later address.
    */
    if (conn_error) {
      g_error_free (conn_error);
    }
    return true;
  }

  if(error) {
    std::cout  << "[WARN] Could not connect:" << std::endl << error->message << std::endl;
    g_error_free(error);
  }

  if (conn_error) {
    std::cout << "[WARN] Could not connect:" << std::endl << conn_error->message << std::endl;
    g_error_free(conn_error);
  }

  return false;
}//end connect

bool WebotsController::init(
  const std::string& modelPath,
  const std::string& parameterTeamName,
  unsigned int parameterTeamNumber,
  unsigned int parameterPlayerNumber,
  const std::string& server,
  unsigned int port,
  bool sync)
{
  // IMPORTANT: initialize the platform
  Platform::getInstance().init(this);

  Configuration& config = Platform::getInstance().theConfiguration;

  // set the team number first
  unsigned int teamNumber;
  if (parameterTeamNumber != 0) {
    teamNumber = parameterTeamNumber;
  } else if (config.hasKey("player", "TeamNumber")) {
    teamNumber = config.getInt("player", "TeamNumber");
  } else {
    teamNumber = 4;
  }

  // use the player number if one is given, otherwise use the number from the simulation
  unsigned int playerNumber;
  if(parameterPlayerNumber != 0) {
    playerNumber = parameterPlayerNumber;
  } else if(config.hasKey("player", "PlayerNumber") && config.getInt("player", "PlayerNumber") != 0) {
    playerNumber = config.getInt("player", "PlayerNumber");
  } else {
    playerNumber = 0;
  }

  // use the team name if one is given, otherwise generate a name
  string teamName;
  if (!parameterTeamName.empty()) {
    teamName = parameterTeamName;
  } else if (config.hasKey("player", "TeamName")) {
    teamName = config.getString("player", "TeamName");
  } else {
    teamName = "NaoTH-" + std::to_string(teamNumber);
  }

  theSyncMode = sync;

  // connect to the simulator
  if(!connect(server, port)) {
    std::cerr << "WebotsController could not connect" << std::endl;
    return false;
  }
  theSocket.init(socket);

  // TODO: send create command to simulator
  //"rsg/agent/naov4/nao.rsg";
  theSocket << "(scene " << modelPath << ")" << send;

  // wait the response
  getSensorData(theSensorData);

  std::cout << "Sensordata: " << theSensorData << std::endl;

  // initialize the teamname and number
  //theSocket << "(init (teamname " << theGameInfo.teamName << ")(unum " << theGameInfo.playerNumber << "))" << theSync << send;

  cout << "NaoTH Simpark initialization successful: " << teamName << " " << playerNumber << endl;

  //DEBUG_REQUEST_REGISTER("SimSparkController:beam", "beam to start pose", false);
  //REGISTER_DEBUG_COMMAND("beam", "beam to given pose", this);

  // hack?
  config.setInt("player", "TeamNumber", teamNumber);
  config.setInt("player", "PlayerNumber", playerNumber);
  config.setString("player", "TeamName", teamName);

#ifdef DEBUG
  // calculate debug communicaiton port
  unsigned short debugPort = static_cast<short unsigned int> (5000 + (teamNumber*100) + playerNumber);
  theDebugServer.start(debugPort);
#endif

  theLastSenseTime = NaoTime::getNaoTimeInMilliSeconds();
  theLastActTime = theLastSenseTime;
  calculateNextActTime();

  return true;
}

void WebotsController::main()
{
  if ( theSyncMode ) {
    singleThreadMain();
  } else {
    multiThreadsMain();
  }
}

void WebotsController::singleThreadMain()
{
  cout << "SimSpark Controller runs in single thread" << endl;
  while ( getSensorData(theSensorData) )
  {
    /*
    updateSensors(theSensorData);
    if ( isNewImage || isNewVirtualVision )
    {
      callCognition();
    }
    */
    PlatformInterface::runMotion();
    act();
  }//end while
}//end main

void WebotsController::motionLoop()
{
  while ( !exiting )
  {
    std::string data;
    {
      std::unique_lock<std::mutex> lock(theSensorDataMutex);
      theSensorDataCond.wait(lock);
      data = theSensorData;
      theSensorData = "";
    }
    PlatformInterface::runMotion();
  }
}//end motionLoop

void WebotsController::cognitionLoop()
{
  while (!exiting)
  {
    callCognition();
  }
}//end cognitionLoop

void WebotsController::callCognition()
{
  if(cognitionRegistered())
  {
    getCognitionInput();
    if ( !exiting )
    {
      PlatformInterface::callCognition();
      setCognitionOutput();
    }
  }
}//end callCognition

void WebotsController::senseLoop()
{
  while( true )
  {
    string data;
    if ( !getSensorData(data) )
    {
      break;
    }

    {
      std::unique_lock<std::mutex> lock(theSensorDataMutex);
      if ( !theSensorData.empty() )
      {
        cerr<<"[Warning] the sensor data @ " << theLastSenseTime << " is dropped!"<<endl;
      }
      theSensorData = data;
    }
    theTimeCond.notify_one();
    theSensorDataCond.notify_one();
  }

  exiting = true;
  theSensorDataCond.notify_one(); // tell motion to exit
  theTimeCond.notify_one(); // tell act loop to exit
  theCognitionInputCond.notify_one(); // tell cognition to exit
}

void WebotsController::actLoop()
{
  while( !exiting )
  {
    { // NOTE: lock object lives only in this code block
      std::unique_lock<std::mutex> lock(theTimeMutex);
      theTimeCond.wait(lock);
      calculateNextActTime();
    }

    unsigned int now = NaoTime::getNaoTimeInMilliSeconds();
    if ( theNextActTime > now )
    {
      ThreadUtil::sleep(theNextActTime - now);
    }

    act();
  }
}

void WebotsController::act()
{
  // send command
  std::unique_lock<std::mutex> lock(theActDataMutex);
  try {
    //theSocket << theActData.str() << theSync << send;
  }
  catch(std::runtime_error& exp)
  {
    cerr<<"can not send data to server, because of "<<exp.what()<<endl;
  }
}

void WebotsController::multiThreadsMain()
{
  cout << "Webots Controller runs in multi-threads" << endl;

  std::thread senseThread = std::thread([this]{this->senseLoop();});
  std::thread actThread = std::thread([this]{this->actLoop();});
  std::thread motionThread = std::thread([this]{this->motionLoop();});

  cognitionLoop();

  if(motionThread.joinable()) {
    motionThread.join();
  }
  if(actThread.joinable()) {
    actThread.join();
  }
  if(senseThread.joinable()) {
    senseThread.join();
  }
}//end multiThreadsMain

void WebotsController::getMotionInput()
{
  PlatformInterface::getMotionInput();

  /*
  for (int i = 0; i < JointData::numOfJoint; i++) {
    theSensorJointData.stiffness[i] = theLastSensorJointData.stiffness[i];
  }
  theLastSensorJointData = theSensorJointData;
  */
}

void WebotsController::setMotionOutput()
{
  PlatformInterface::setMotionOutput();

  /*
  {
    std::unique_lock<std::mutex> lock(theActDataMutex);
    say();
    autoBeam();
    jointControl();
    theActData << theSync;
  }
  */
}

void WebotsController::getCognitionInput()
{
  /*
  std::unique_lock<std::mutex> lock(theCognitionInputMutex);
  while (!isNewImage && !isNewVirtualVision && !exiting )
  {
    theCognitionInputCond.wait(lock);
  }

  PlatformInterface::getCognitionInput();
  isNewVirtualVision = false;
  isNewImage = false;
  */
}

void WebotsController::setCognitionOutput()
{
  std::unique_lock<std::mutex> lock(theCognitionOutputMutex);
  PlatformInterface::setCognitionOutput();
}

bool WebotsController::getSensorData(std::string& data)
{
  try {
    theSocket >> data;

    // Test the message pack parsing
    msgpack::object_handle oh = msgpack::unpack(data.data(), data.size());

    // deserialized object is valid during the msgpack::object_handle instance is alive.
    msgpack::object deserialized = oh.get();

    // msgpack::object supports ostream.
    std::cout << deserialized << std::endl;

    theLastSenseTime = NaoTime::getNaoTimeInMilliSeconds();
  }
  catch (std::runtime_error& exp)
  {
    cerr<<"can not get data from server, because of "<<exp.what()<<endl;
    return false;
  }
  return true;
}

void WebotsController::get(FrameInfo& data)
{
  //data.setTime(theFrameInfo.getTime());
  data.setFrameNumber(data.getFrameNumber() + 1);
}

void WebotsController::get(SensorJointData& data)
{

}

void WebotsController::get(AccelerometerData& data)
{

}

void WebotsController::get(BatteryData& data)
{

}

void WebotsController::get(GPSData& data)
{

}

void WebotsController::get(Image& data)
{
}//end get

void WebotsController::get(GyrometerData& data)
{

}

void WebotsController::get(FSRData& data)
{

}

void WebotsController::get(InertialSensorData& data)
{

}

void WebotsController::get(VirtualVision& data)
{

}

void WebotsController::get(VirtualVisionTop& data)
{

}

void WebotsController::get(GameData& data)
{

}

void WebotsController::set(const MotorJointData& data)
{

}

void WebotsController::get(TeamMessageDataIn& data)
{

}

void WebotsController::set(const TeamMessageDataOut& data)
{

}

MessageQueue* WebotsController::createMessageQueue(const std::string& /*name*/)
{
  if ( theSyncMode ) {
    return new MessageQueue();
  } else {
    return new MessageQueue4Threads();
  }
}

void WebotsController::calculateNextActTime()
{
   theNextActTime = theLastSenseTime + 10;
   while(theLastActTime > theNextActTime)
   {
     theNextActTime += getBasicTimeStep();
   }
}
<|endoftext|>


<commit_before>#include "../include/InputParams.h"

// array of all parameters
namespace {
	const char* parameter_list[] = {
		// General
		"outputfile",
		"deflection_off",
		"read_redshift_planes",
		"redshift_planes_fil",
		"z_lens",
		"z_source",

		// Cosmology
		"Omega_matter",
		"Omega_lambda",
		"Omega_baryon",
		"Omega_neutrino",
		"hubble",
		"sigm_8",

		// Main halos type
		"main_halo_on",
		"main_DM_halo_type",
		"main_galaxy_halo_type",

		// Field halos
		"field_off",
		"field_Nplanes",

		// Field halos type
		"field_internal_profile",
		"field_internal_profile_galaxy",
		"field_prof_internal_slope_pnfw",
		"field_prof_internal_slope_pl",

		// Field halos from a mass function
		"field_mass_func_type",
		"field_fov",
		"field_buffer",
		"field_min_mass",

		// Field halos from an input file
		"field_input_simulation_file",

		// AnaNSIE lens halo model
		"main_sigma",
		"main_core",
		"main_axis_ratio",
		"main_pos_angle",
		"main_NDistortionModes",
		"main_perturb_beta",
		"main_perturb_kappa",
		"main_perturb_gamma",
		"main_perturb_monopole",
		"main_perturb_quadrapole",
		"main_perturb_hexopole",
		"main_perturb_octopole",
		"main_sub_Ndensity",
		"main_sub_beta",
		"main_sub_alpha",
		"main_sub_Rmax",
		"main_sub_mass_max",
		"main_sub_mass_min",
		"main_sub_type",
		"main_stars_N",
		"main_stars_fraction",
		"main_stars_mass",

		// MOKA lens halo model
		"MOKA_input_file",
		"MOKA_input_params",
		"MOKA_analyze",
		"background_field",

		// NFW lens halo model
		"mass_nfw"
		"Rmax_nfw"
		"zlens_nfw"
		"concentration_nfw"

		// Pseudo NFW lens halo model
		"mass_pnfw"
		"Rmax_pnfw"
		"zlens_pnfw"
		"concentration_pnfw"
		"slope_pnfw"

		// Power law lens halo model
		"mass_pl"
		"Rmax_pl"
		"zlens_pl"
		"slope_pl"

		// Simple NSIE lens halo model
		"mass_nsie"

		// Hernquist lens halo model
		"mass_hernquist"
		"Rmax_hernquist"
		"zlens_hernquist"
		"rscale_hernquist"

		// Jaffe lens halo model
		"mass_jaffe"
		"Rmax_jaffe"
		"zlens_jaffe"
		"rscale_jaffe"

		// MultiDark lenses
		"MultiDark_input_file",

		// Type of source SB model
		"SourceSBType",

		// Gaussian source model
		"gauss_r2",

		// BLR source model
		"BHmass",
		"gamma",
		"inclin",
		"opening_ang",
		"r_in",
		"r_out",
		"nuo",
		"source_sigma"
	};
}

// initialize the static set of all known labels
const std::set<std::string> InputParams::known_labels(parameter_list, parameter_list + sizeof(parameter_list)/sizeof(parameter_list[0]));
<commit_msg>Added Uniform halo and stars parameters to input_params_list.cpp<commit_after>#include "../include/InputParams.h"

// array of all parameters
namespace {
	const char* parameter_list[] = {
		// General
		"outputfile",
		"deflection_off",
		"read_redshift_planes",
		"redshift_planes_fil",
		"z_lens",
		"z_source",

		// Cosmology
		"Omega_matter",
		"Omega_lambda",
		"Omega_baryon",
		"Omega_neutrino",
		"hubble",
		"sigm_8",

		// Main halos type
		"main_halo_on",
		"main_DM_halo_type",
		"main_galaxy_halo_type",

		// Field halos
		"field_off",
		"field_Nplanes",

		// Field halos type
		"field_internal_profile",
		"field_internal_profile_galaxy",
		"field_prof_internal_slope_pnfw",
		"field_prof_internal_slope_pl",

		// Field halos from a mass function
		"field_mass_func_type",
		"field_fov",
		"field_buffer",
		"field_min_mass",

		// Field halos from an input file
		"field_input_simulation_file",

		// AnaNSIE lens halo model
		"main_sigma",
		"main_core",
		"main_axis_ratio",
		"main_pos_angle",
		"main_NDistortionModes",
		"main_perturb_beta",
		"main_perturb_kappa",
		"main_perturb_gamma",
		"main_perturb_monopole",
		"main_perturb_quadrapole",
		"main_perturb_hexopole",
		"main_perturb_octopole",
		"main_sub_Ndensity",
		"main_sub_beta",
		"main_sub_alpha",
		"main_sub_Rmax",
		"main_sub_mass_max",
		"main_sub_mass_min",
		"main_sub_type",

		// MOKA lens halo model
		"MOKA_input_file",
		"MOKA_input_params",
		"MOKA_analyze",
		"background_field",

		// NFW lens halo model
		"mass_nfw",
		"Rmax_nfw",
		"zlens_nfw",
		"concentration_nfw",

		// Pseudo NFW lens halo model
		"mass_pnfw",
		"Rmax_pnfw",
		"zlens_pnfw",
		"concentration_pnfw",
		"slope_pnfw",

		// Power law lens halo model
		"mass_pl",
		"Rmax_pl",
		"zlens_pl",
		"slope_pl",

		// Simple NSIE lens halo model
		"mass_nsie",

		// Hernquist lens halo model
		"mass_hernquist",
		"Rmax_hernquist",
		"zlens_hernquist",
		"rscale_hernquist",

		// Jaffe lens halo model
		"mass_jaffe",
		"Rmax_jaffe",
		"zlens_jaffe",
		"rscale_jaffe",

		// Uniform lens halo model
		"zlens_uniform",
		"kappa_uniform",
		"gamma_uniform_1",
		"gamma_uniform_2",
		"zsource_reference",

		// Stars
		"main_stars_N",
		"main_stars_fraction",
		"main_stars_mass",
		"main_stars_mass_function",
		"main_stars_min_mass",
		"main_stars_max_mass",
		"main_stars_bending_point",
		"main_stars_lo_mass_slope",
		"main_stars_hi_mass_slope",

		// MultiDark lenses
		"MultiDark_input_file",

		// Type of source SB model
		"SourceSBType",

		// Gaussian source model
		"gauss_r2",

		// BLR source model
		"BHmass",
		"gamma",
		"inclin",
		"opening_ang",
		"r_in",
		"r_out",
		"nuo",
		"source_sigma"
	};
}

// initialize the static set of all known labels
const std::set<std::string> InputParams::known_labels(parameter_list, parameter_list + sizeof(parameter_list)/sizeof(parameter_list[0]));
<|endoftext|>


<commit_before>#include <iostream>

using namespace std;

int main()
{
	cout << "TODO" << endl;

	return -1;
}
<commit_msg>Implement ranking system based on web, title, and pageindex.<commit_after>#include <iostream>
#include <string>
#include <fstream>
#include <array>
#include <utility>
#include <map>
#include <vector>
#include <algorithm>
#include "IndexHelper.hpp"

using namespace std;

const array<pair<int, string>, 3> INDEXWEIGHTS {{
	{16, "titleindex"},
	{4, "webindex"},
	{1, "pageindex"}
}};

string getQueryString()
{
	ifstream input("query.txt");
	string query;
	getline(input, query);

	return query;
}

map<string, int> getWeightedResults(const string& query)
{
	map<string, int> results;
	IndexHelper helper;

	// Add the base score from the index
	for (const auto index : INDEXWEIGHTS) {
		for (auto link : helper.getLinksFromIndex(query, index.second)) {
			results[link] += index.first;
		}
	}

	// TODO: Add the link score

	return results;
}

vector<string> getResults(string query)
{
	vector<pair<int, string>> orderedResults;
	for (auto entry : getWeightedResults(query)) {
		orderedResults.emplace_back(entry.second, entry.first);
	}

	sort(orderedResults.begin(), orderedResults.end(), greater<pair<int, string>>());

	vector<string> results;
	for (auto result : orderedResults) {
		results.emplace_back(result.second);
	}

	return results;

}

int main()
{
	string query = "liacs";
	for (auto result : getResults(query)) {
		cout << result << endl;
	}
	return 0;
}
<|endoftext|>