<commit_before>// Time:  push:    O(logn)
//        pop:     O(logn)
//        popMax:  O(logn)
//        top:     O(1)
//        peekMax: O(1)
// Space: O(n), n is the number of values in the current stack

class MaxStack {
public:
    /** initialize your data structure here. */
    MaxStack() {

    }

    void push(int x) {
        const auto idx = idx_to_val_.empty() ? 0 : idx_to_val_.begin()->first + 1;
        idx_to_val_[idx] = x;
        val_to_idxs_[x].emplace_back(idx);
    }

    int pop() {
        const auto& it = idx_to_val_.begin();
        const auto val = it->second;
        remove(val);
        return val;
    }

    int top() {
        return idx_to_val_.begin()->second;
    }

    int peekMax() {
        return val_to_idxs_.begin()->first;
    }

    int popMax() {
        const auto& it = val_to_idxs_.begin();
        const auto val = it->first;
        remove(val);
        return val;
    }

private:
    map<int, int, greater<int>> idx_to_val_;
    map<int, vector<int>, greater<int>> val_to_idxs_;

    void remove(const int val) {
        const auto idx = val_to_idxs_[val].back();
        val_to_idxs_[val].pop_back();
        if (val_to_idxs_[val].empty()) {
            val_to_idxs_.erase(val);
        }
        idx_to_val_.erase(idx);
    }
};

/**
 * Your MaxStack object will be instantiated and called as such:
 * MaxStack obj = new MaxStack();
 * obj.push(x);
 * int param_2 = obj.pop();
 * int param_3 = obj.top();
 * int param_4 = obj.peekMax();
 * int param_5 = obj.popMax();
 */
<commit_msg>Update max-stack.cpp<commit_after>// Time:  push:    O(logn)
//        pop:     O(logn)
//        popMax:  O(logn)
//        top:     O(1)
//        peekMax: O(1)
// Space: O(n), n is the number of values in the current stack

class MaxStack {
public:
    /** initialize your data structure here. */
    MaxStack() {

    }

    void push(int x) {
        const auto idx = idx_to_val_.empty() ? 0 : idx_to_val_.begin()->first + 1;
        idx_to_val_[idx] = x;
        val_to_idxs_[x].emplace_back(idx);
    }

    int pop() {
        const auto val = idx_to_val_.begin()->second;
        remove(val);
        return val;
    }

    int top() {
        return idx_to_val_.begin()->second;
    }

    int peekMax() {
        return val_to_idxs_.begin()->first;
    }

    int popMax() {
        const auto val = val_to_idxs_.begin()->first;
        remove(val);
        return val;
    }

private:
    map<int, int, greater<int>> idx_to_val_;
    map<int, vector<int>, greater<int>> val_to_idxs_;

    void remove(const int val) {
        const auto idx = val_to_idxs_[val].back();
        val_to_idxs_[val].pop_back();
        if (val_to_idxs_[val].empty()) {
            val_to_idxs_.erase(val);
        }
        idx_to_val_.erase(idx);
    }
};

/**
 * Your MaxStack object will be instantiated and called as such:
 * MaxStack obj = new MaxStack();
 * obj.push(x);
 * int param_2 = obj.pop();
 * int param_3 = obj.top();
 * int param_4 = obj.peekMax();
 * int param_5 = obj.popMax();
 */
<|endoftext|>


<commit_before>#include "initOgre.h"

#include "OgreConfigFile.h"
#include <OgreMeshSerializer.h>

#ifdef OGRE_PLATFORM_LINUX
#include <sys/stat.h>
#endif

initOgre::initOgre(){
		FrameListener = NULL;
		Root = NULL;
		OverlaySystem = NULL;

	}
initOgre::~initOgre()
{
	//delete Root;
}

int initOgre::start(){

	Ogre::String PluginName;
	Ogre::String mResourcesCfg;
	mResourcesCfg = "resources.cfg";

	Root = new Ogre::Root("", mResourcesCfg, "Generator.LOG");
	OverlaySystem = new Ogre::OverlaySystem();

#if OGRE_PLATFORM == OGRE_PLATFORM_WIN32
	PluginName.append("RenderSystem_Direct3D9");
#else
	/* Use Posix-function stat to check existence of a file.
	 * This is needed because Ogre makes zero effort to find its own plugins. */
	struct stat statBuf;
	Ogre::String PluginFile[4];

	PluginFile[0].append("/usr/lib/OGRE/RenderSystem_GL.so");
	PluginFile[1].append("/usr/lib/local/OGRE/RenderSystem_GL.so");
	// Ubuntu
#ifdef __x86_64__
	PluginFile[2].append("/usr/lib/x86_64-linux-gnu/OGRE-");
	PluginFile[3].append("/usr/lib64/OGRE/RenderSystem_GL.so");
#elif __i386__
	PluginFile[2].append("/usr/lib/i386-linux-gnu/OGRE-");
	PluginFile[3].append("/usr/lib32/OGRE/RenderSystem_GL.so");
#endif
	PluginFile[2] += Ogre::StringConverter::toString(OGRE_VERSION_MAJOR) + ".";
	PluginFile[2] += Ogre::StringConverter::toString(OGRE_VERSION_MINOR) + ".";
	PluginFile[2] += Ogre::StringConverter::toString(OGRE_VERSION_PATCH);
	PluginFile[2] += "/RenderSystem_GL.so";

	int i;
	for(i=0; i < 4; i++)
	{
		if( stat(PluginFile[i].c_str(), &statBuf) == 0 )
		{
			PluginFile[i].resize(PluginFile[i].size()-3);	// strip ".so"
			PluginName.assign( PluginFile[i] );
			break;											// Exit loop if file exists
		}
	}
	if(PluginName == "")
		Ogre::LogManager::getSingleton().logMessage(Ogre::LML_CRITICAL, "Could not find RenderSystem_GL.so!");
#endif

	// RenderSystem_GL_d if using Ogre debug mode
	if(OGRE_DEBUG_MODE)
		PluginName.append("_d");
	// Loads renderer plugin
	Root->loadPlugin(PluginName);

	//Load information from resource.cfg file
	Ogre::ConfigFile cf;
	cf.load(mResourcesCfg);
	Ogre::String name, locType;
	Ogre::ConfigFile::SectionIterator secIt = cf.getSectionIterator();
	while (secIt.hasMoreElements()) {
		Ogre::ConfigFile::SettingsMultiMap* settings = secIt.getNext();
		Ogre::ConfigFile::SettingsMultiMap::iterator it;
		for (it = settings->begin(); it != settings->end(); ++it) {
			locType = it->first;
			name = it->second;
			Ogre::ResourceGroupManager::getSingleton().addResourceLocation(name, locType, Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME);
		}

	}

	//Ogre::ResourceGroupManager::getSingleton().declareResource("ram.mesh", "Mesh", Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME, Ogre::NameValuePairList());
	//Ogre::ResourceGroupManager::getSingleton().declareResource("char_ram_col.jpg", "Font", Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME, Ogre::NameValuePairList());
	////Ogre::ResourceGroupManager::getSingleton().declareResource("char_ram_nor.png", "Font", Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME, Ogre::NameValuePairList());
	//Ogre::ResourceGroupManager::getSingleton().declareResource("ram_skin.material", "Material", Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME, Ogre::NameValuePairList());
	//Ogre::ResourceGroupManager::getSingleton().declareResource("ram_skin_eyelids.material", "Material", Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME, Ogre::NameValuePairList());
	//Ogre::ResourceGroupManager::getSingleton().declareResource("ram_skin_eyes.material", "Material", Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME, Ogre::NameValuePairList());
	//Ogre::ResourceGroupManager::getSingleton().declareResource("ram_skin_horns.material", "Material", Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME, Ogre::NameValuePairList());

	//Ogre::ResourceGroupManager::getSingleton().declareResource("asteroid.mesh", "Mesh", Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME, Ogre::NameValuePairList());
	//Ogre::ResourceGroupManager::getSingleton().declareResource("Material.001.material", "Material", Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME, Ogre::NameValuePairList());
	//Ogre::ResourceGroupManager::getSingleton().declareResource("space rock tex 3.jpg", "Font", Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME, Ogre::NameValuePairList());

	//Ogre::TextureManager::getSingleton().setDefaultNumMipmaps(5);
	Ogre::ResourceGroupManager::getSingleton().initialiseAllResourceGroups();
	//Ogre::ResourceGroupManager::getSingleton().initialiseResourceGroup(Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME);

	// Check renderer availability
	const Ogre::RenderSystemList& RenderSystemList = Root->getAvailableRenderers();
	if( RenderSystemList.size() == 0 )
	{
		Ogre::LogManager::getSingleton().logMessage("Rendersystems not found.");
		return 1;
	}
	Ogre::RenderSystem *RenderSystem = RenderSystemList[0];
	Root->setRenderSystem(RenderSystem);

	// Do not create window automatically
	Root->initialise(false);

	Ogre::NameValuePairList renderParams;

	renderParams["FSAA"] = "0";
	renderParams["vsync"] = "true"; // Waits for vertical sync

	// Actual call to create window, bool value is fullscreen flag
	Window = Root->createRenderWindow("My little planet", 800, 600, false, &renderParams);

	// Start creating scene
	Scene = Root->createSceneManager(Ogre::ST_GENERIC);
	RootSceneNode = Scene->getRootSceneNode();

	if(OverlaySystem)
		Scene->addRenderQueueListener(OverlaySystem);

	return 0;
}

void initOgre::CreateFrameListener(PSphere *pSphere){

#if OGRE_PLATFORM == OGRE_PLATFORM_APPLE_IOS
	FrameListener= new GeneratorFrameListener(Window, Camera, true, true, true);
#else
	FrameListener= new GeneratorFrameListener(Window, Camera,pSphere ,Scene , RootSceneNode ,CollisionDetectionManager);
#endif
	//FrameListener->showDebugOverlay(true);
	Root->addFrameListener(FrameListener);
}

void initOgre::setSceneAndRun(PSphere *planet){

	// Create camera
	Camera = Scene->createCamera("VertCamera");

	// Camera position
	Camera->setPosition(Ogre::Vector3(0,0,planet->getRadius()*2.65f));
	planet->setObserverPosition(Camera->getPosition());
	// Camera looks toward origo
	Camera->lookAt(Ogre::Vector3(0,0,0));

	// Create viewport
	Ogre::Viewport *vp = Window->addViewport(Camera);
	vp->setBackgroundColour(Ogre::ColourValue(0,0,0));

	// Draw distances
	Camera->setNearClipDistance(1.5f);
	Camera->setFarClipDistance(3000.0f);     // note to self: do not set if using stencil shadows

	// Let there be light
	Scene->setAmbientLight(Ogre::ColourValue(0.2f, 0.2f, 0.2f));
	Ogre::Light *light = Scene->createLight( "PointLight" );
	light->setDiffuseColour(1.0, 1.0, 1.0);
	light->setSpecularColour(1.0, 1.0, 1.0);
	light->setType(Ogre::Light::LT_POINT);
	light->setPosition(200, 40, 150);

	// Draw a sphere
	planet->loadToBuffers("CustomMesh", "sphereTex");

	//Export the shape in a mesh file before destroying it
	//Ogre::MeshPtr mesh;
	//mesh = planet->getMesh();
	//Ogre::MeshSerializer ser;
	//ser.exportMesh(mesh.getPointer(), "C:\\Users\\giova\\Documents\\PlanetGenerator\\planet.mesh",  Ogre::MeshSerializer::ENDIAN_NATIVE);

	// Attach entitys to sceneNodes
	Ogre::SceneNode *CameraNode = RootSceneNode->createChildSceneNode("DefaultCameraNode");
	CameraNode->attachObject(Camera);

	Ogre::Entity *entity1 = Scene->createEntity("CustomEntity", "CustomMesh");
	Ogre::SceneNode *sphere1 = Scene->getRootSceneNode()->createChildSceneNode("planetSphere");
	sphere1->attachObject(entity1);

	//planet->loadMeshFile("ram1.mesh", "LocalMesh");

	planet->attachMeshOnGround(sphere1, Scene, "ram.mesh", "Ramiro", 0.0, 270.0);
	planet->attachMesh(sphere1, Scene, "asteroid.mesh", "CK7", 0.0, 180.0);

	// No need for this anymore
	//Ogre::MeshManager::getSingleton().remove("CustomMesh");

	Ogre::MaterialPtr textureMap = Ogre::MaterialManager::getSingleton()
			.create("TextureObject",Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME);
	textureMap->getTechnique(0)->getPass(0)->createTextureUnitState("sphereTex");
	textureMap->getTechnique(0)->getPass(0)->setSceneBlending(Ogre::SBT_TRANSPARENT_ALPHA);

	// Set texture for the sphere
	entity1->setMaterial(textureMap);

	sphere1->setOrientation(1.3003361e-01f, -1.5604560e-01f, -7.5052901e-01f, 6.2884596e-01f);

	//Collision Manager
	CollisionDetectionManager = new CollisionManager(planet->getObjects(),Camera);
	planet->setCollisionManager( CollisionDetectionManager );

	//createFrameListener
	CreateFrameListener(planet);

	//start Rendering
	Root->startRendering();
}

void initOgre::cleanup(){

	// Clean up our mess before exiting
	Ogre::MaterialManager::getSingleton().remove("TextureObject");
	Ogre::TextureManager::getSingleton().remove("sphereTex");
	Scene->destroyEntity("CustomEntity");
	Scene->destroySceneNode("planetSphere");
	Scene->destroySceneNode("DefaultCameraNode");
	Scene->destroyCamera(Camera);
	Scene->destroyLight("PointLight");
	Ogre::Root::getSingleton().getRenderSystem()->destroyRenderWindow("My little planet");
	Scene->clearScene();
	Root->destroySceneManager(Scene);

	Root->shutdown();

	delete FrameListener;
	FrameListener = NULL;
	delete OverlaySystem;
	OverlaySystem = NULL;
	delete Root;
	Root = NULL;

	//Ogre::LogManager::getSingleton().logMessage("Ogre is cleaned up");
}
<commit_msg>Reorientate planet<commit_after>#include "initOgre.h"

#include "OgreConfigFile.h"
#include <OgreMeshSerializer.h>

#ifdef OGRE_PLATFORM_LINUX
#include <sys/stat.h>
#endif

initOgre::initOgre(){
		FrameListener = NULL;
		Root = NULL;
		OverlaySystem = NULL;

	}
initOgre::~initOgre()
{
	//delete Root;
}

int initOgre::start(){

	Ogre::String PluginName;
	Ogre::String mResourcesCfg;
	mResourcesCfg = "resources.cfg";

	Root = new Ogre::Root("", mResourcesCfg, "Generator.LOG");
	OverlaySystem = new Ogre::OverlaySystem();

#if OGRE_PLATFORM == OGRE_PLATFORM_WIN32
	PluginName.append("RenderSystem_Direct3D9");
#else
	/* Use Posix-function stat to check existence of a file.
	 * This is needed because Ogre makes zero effort to find its own plugins. */
	struct stat statBuf;
	Ogre::String PluginFile[4];

	PluginFile[0].append("/usr/lib/OGRE/RenderSystem_GL.so");
	PluginFile[1].append("/usr/lib/local/OGRE/RenderSystem_GL.so");
	// Ubuntu
#ifdef __x86_64__
	PluginFile[2].append("/usr/lib/x86_64-linux-gnu/OGRE-");
	PluginFile[3].append("/usr/lib64/OGRE/RenderSystem_GL.so");
#elif __i386__
	PluginFile[2].append("/usr/lib/i386-linux-gnu/OGRE-");
	PluginFile[3].append("/usr/lib32/OGRE/RenderSystem_GL.so");
#endif
	PluginFile[2] += Ogre::StringConverter::toString(OGRE_VERSION_MAJOR) + ".";
	PluginFile[2] += Ogre::StringConverter::toString(OGRE_VERSION_MINOR) + ".";
	PluginFile[2] += Ogre::StringConverter::toString(OGRE_VERSION_PATCH);
	PluginFile[2] += "/RenderSystem_GL.so";

	int i;
	for(i=0; i < 4; i++)
	{
		if( stat(PluginFile[i].c_str(), &statBuf) == 0 )
		{
			PluginFile[i].resize(PluginFile[i].size()-3);	// strip ".so"
			PluginName.assign( PluginFile[i] );
			break;											// Exit loop if file exists
		}
	}
	if(PluginName == "")
		Ogre::LogManager::getSingleton().logMessage(Ogre::LML_CRITICAL, "Could not find RenderSystem_GL.so!");
#endif

	// RenderSystem_GL_d if using Ogre debug mode
	if(OGRE_DEBUG_MODE)
		PluginName.append("_d");
	// Loads renderer plugin
	Root->loadPlugin(PluginName);

	//Load information from resource.cfg file
	Ogre::ConfigFile cf;
	cf.load(mResourcesCfg);
	Ogre::String name, locType;
	Ogre::ConfigFile::SectionIterator secIt = cf.getSectionIterator();
	while (secIt.hasMoreElements()) {
		Ogre::ConfigFile::SettingsMultiMap* settings = secIt.getNext();
		Ogre::ConfigFile::SettingsMultiMap::iterator it;
		for (it = settings->begin(); it != settings->end(); ++it) {
			locType = it->first;
			name = it->second;
			Ogre::ResourceGroupManager::getSingleton().addResourceLocation(name, locType, Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME);
		}

	}

	//Ogre::ResourceGroupManager::getSingleton().declareResource("ram.mesh", "Mesh", Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME, Ogre::NameValuePairList());
	//Ogre::ResourceGroupManager::getSingleton().declareResource("char_ram_col.jpg", "Font", Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME, Ogre::NameValuePairList());
	////Ogre::ResourceGroupManager::getSingleton().declareResource("char_ram_nor.png", "Font", Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME, Ogre::NameValuePairList());
	//Ogre::ResourceGroupManager::getSingleton().declareResource("ram_skin.material", "Material", Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME, Ogre::NameValuePairList());
	//Ogre::ResourceGroupManager::getSingleton().declareResource("ram_skin_eyelids.material", "Material", Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME, Ogre::NameValuePairList());
	//Ogre::ResourceGroupManager::getSingleton().declareResource("ram_skin_eyes.material", "Material", Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME, Ogre::NameValuePairList());
	//Ogre::ResourceGroupManager::getSingleton().declareResource("ram_skin_horns.material", "Material", Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME, Ogre::NameValuePairList());

	//Ogre::ResourceGroupManager::getSingleton().declareResource("asteroid.mesh", "Mesh", Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME, Ogre::NameValuePairList());
	//Ogre::ResourceGroupManager::getSingleton().declareResource("Material.001.material", "Material", Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME, Ogre::NameValuePairList());
	//Ogre::ResourceGroupManager::getSingleton().declareResource("space rock tex 3.jpg", "Font", Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME, Ogre::NameValuePairList());

	//Ogre::TextureManager::getSingleton().setDefaultNumMipmaps(5);
	Ogre::ResourceGroupManager::getSingleton().initialiseAllResourceGroups();
	//Ogre::ResourceGroupManager::getSingleton().initialiseResourceGroup(Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME);

	// Check renderer availability
	const Ogre::RenderSystemList& RenderSystemList = Root->getAvailableRenderers();
	if( RenderSystemList.size() == 0 )
	{
		Ogre::LogManager::getSingleton().logMessage("Rendersystems not found.");
		return 1;
	}
	Ogre::RenderSystem *RenderSystem = RenderSystemList[0];
	Root->setRenderSystem(RenderSystem);

	// Do not create window automatically
	Root->initialise(false);

	Ogre::NameValuePairList renderParams;

	renderParams["FSAA"] = "0";
	renderParams["vsync"] = "true"; // Waits for vertical sync

	// Actual call to create window, bool value is fullscreen flag
	Window = Root->createRenderWindow("My little planet", 800, 600, false, &renderParams);

	// Start creating scene
	Scene = Root->createSceneManager(Ogre::ST_GENERIC);
	RootSceneNode = Scene->getRootSceneNode();

	if(OverlaySystem)
		Scene->addRenderQueueListener(OverlaySystem);

	return 0;
}

void initOgre::CreateFrameListener(PSphere *pSphere){

#if OGRE_PLATFORM == OGRE_PLATFORM_APPLE_IOS
	FrameListener= new GeneratorFrameListener(Window, Camera, true, true, true);
#else
	FrameListener= new GeneratorFrameListener(Window, Camera,pSphere ,Scene , RootSceneNode ,CollisionDetectionManager);
#endif
	//FrameListener->showDebugOverlay(true);
	Root->addFrameListener(FrameListener);
}

void initOgre::setSceneAndRun(PSphere *planet){

	// Create camera
	Camera = Scene->createCamera("VertCamera");

	// Camera position
	Camera->setPosition(Ogre::Vector3(0,0,planet->getRadius()*2.65f));
	planet->setObserverPosition(Camera->getPosition());
	// Camera looks toward origo
	Camera->lookAt(Ogre::Vector3(0,0,0));

	// Create viewport
	Ogre::Viewport *vp = Window->addViewport(Camera);
	vp->setBackgroundColour(Ogre::ColourValue(0,0,0));

	// Draw distances
	Camera->setNearClipDistance(1.5f);
	Camera->setFarClipDistance(3000.0f);     // note to self: do not set if using stencil shadows

	// Let there be light
	Scene->setAmbientLight(Ogre::ColourValue(0.2f, 0.2f, 0.2f));
	Ogre::Light *light = Scene->createLight( "PointLight" );
	light->setDiffuseColour(1.0, 1.0, 1.0);
	light->setSpecularColour(1.0, 1.0, 1.0);
	light->setType(Ogre::Light::LT_POINT);
	light->setPosition(200, 40, 150);

	// Draw a sphere
	planet->loadToBuffers("CustomMesh", "sphereTex");

	//Export the shape in a mesh file before destroying it
	//Ogre::MeshPtr mesh;
	//mesh = planet->getMesh();
	//Ogre::MeshSerializer ser;
	//ser.exportMesh(mesh.getPointer(), "C:\\Users\\giova\\Documents\\PlanetGenerator\\planet.mesh",  Ogre::MeshSerializer::ENDIAN_NATIVE);

	// Attach entitys to sceneNodes
	Ogre::SceneNode *CameraNode = RootSceneNode->createChildSceneNode("DefaultCameraNode");
	CameraNode->attachObject(Camera);

	Ogre::Entity *entity1 = Scene->createEntity("CustomEntity", "CustomMesh");
	Ogre::SceneNode *sphere1 = Scene->getRootSceneNode()->createChildSceneNode("planetSphere");
	sphere1->attachObject(entity1);

	//planet->loadMeshFile("ram1.mesh", "LocalMesh");

	planet->attachMeshOnGround(sphere1, Scene, "ram.mesh", "Ramiro", 0.0, 270.0);
	planet->attachMesh(sphere1, Scene, "asteroid.mesh", "CK7", 0.0, 180.0);

	// No need for this anymore
	//Ogre::MeshManager::getSingleton().remove("CustomMesh");

	Ogre::MaterialPtr textureMap = Ogre::MaterialManager::getSingleton()
			.create("TextureObject",Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME);
	textureMap->getTechnique(0)->getPass(0)->createTextureUnitState("sphereTex");
	textureMap->getTechnique(0)->getPass(0)->setSceneBlending(Ogre::SBT_TRANSPARENT_ALPHA);

	// Set texture for the sphere
	entity1->setMaterial(textureMap);

	sphere1->setOrientation(0.163149834f, -0.19578641f, -0.314332321f, -0.9144643269f);

	//Collision Manager
	CollisionDetectionManager = new CollisionManager(planet->getObjects(),Camera);
	planet->setCollisionManager( CollisionDetectionManager );

	//createFrameListener
	CreateFrameListener(planet);

	//start Rendering
	Root->startRendering();
}

void initOgre::cleanup(){

	// Clean up our mess before exiting
	Ogre::MaterialManager::getSingleton().remove("TextureObject");
	Ogre::TextureManager::getSingleton().remove("sphereTex");
	Scene->destroyEntity("CustomEntity");
	Scene->destroySceneNode("planetSphere");
	Scene->destroySceneNode("DefaultCameraNode");
	Scene->destroyCamera(Camera);
	Scene->destroyLight("PointLight");
	Ogre::Root::getSingleton().getRenderSystem()->destroyRenderWindow("My little planet");
	Scene->clearScene();
	Root->destroySceneManager(Scene);

	Root->shutdown();

	delete FrameListener;
	FrameListener = NULL;
	delete OverlaySystem;
	OverlaySystem = NULL;
	delete Root;
	Root = NULL;

	//Ogre::LogManager::getSingleton().logMessage("Ogre is cleaned up");
}
<|endoftext|>


<commit_before>#include <mutex>
#include <stdint.h>
#include <iostream>
#include <condition_variable>
#include "protocol.h"
#include "RCSwitch.h"

// The RF device data pin
#define RF_DEVICE_COMM_PIN 2

std::mutex m;
std::condition_variable cv;

void transmissionHandler() {
  // A signal is being received, wake up program
  cv.notify_all();
}

int init(RCSwitch& rfSwitch, int pulseLength) {
  // Init wiring PI
  if(wiringPiSetup() == -1) {
    std::cerr << "wiringPiSetup failed, exiting..." << std::endl;
    return 1;
  }
  // Init RF Switch
  if (pulseLength != 0) rfSwitch.setPulseLength(pulseLength);
  rfSwitch.enableReceive(RF_DEVICE_COMM_PIN);  // Receiver on interrupt 0 => that is pin #2
  std::cout << "listening..." << std::endl;
  rfSwitch.registerCustomInterruptHandler(transmissionHandler);
}

void processPacket(packet_s packet) {
  std::cout << "sensor type: " << (int) packet.stype <<
             ", sensor id: " << (int) packet.sid <<
             ", message: " << (int) packet.message << std::endl;

}

void receiveMessage(RCSwitch& rfSwitch) {
  bool receiving_first = true;
  uint64_t previous_value = 0;
  uint64_t value = 0;
  packet_t raw_packet = 0;
  while(1) {
    std::unique_lock<std::mutex> lk(m);
    cv.wait(lk);

    if (rfSwitch.available()) {
      value = rfSwitch.getReceivedValue();
      rfSwitch.resetAvailable();
      if (value == previous_value)
        continue; // If we receive the same value, this is just a repeat
      previous_value = value;
      raw_packet |= value;
      // If we are receiving the first part of the packet, shift the value by
      // 32 to let room for the second half
      if (receiving_first) {
        raw_packet <<= 32;
        receiving_first = false;
      } else {
        // We received the second part, process it
        packet_s packet;
        int ret = read_packet(raw_packet, &packet);
        if (ret == WRONG_MAGIC_ERROR) {
          std::cout << "DEBUG: Wrong magic number, dismiss message" << std::endl;
          continue;
        } else if (ret == PARITY_ERROR) {
          std::cerr << "ERROR: Parity error in message, tread lightly" << std::endl;
        }
        processPacket(packet);
        receiving_first = true;
        raw_packet = 0;
        value = 0;
      }
    }
  }
}

int main(int argc, char **argv) {
  RCSwitch rfSwitch;

  if (argv[1] != NULL) {
    int retcode = 0;
    if ((retcode = init(rfSwitch, atoi(argv[1]))) != 0);
      return retcode;
  }

  receiveMessage(rfSwitch);

  return 0;
}

<commit_msg>Couple of fix.<commit_after>#include <mutex>
#include <stdint.h>
#include <iostream>
#include <condition_variable>
#include "protocol.h"
#include "RCSwitch.h"

// The RF device data pin
#define RF_DEVICE_COMM_PIN 27

std::mutex m;
std::condition_variable cv;

void transmissionHandler() {
  // A signal is being received, wake up program
  cv.notify_all();
}

int init(RCSwitch& rfSwitch, int pulseLength) {
  // Init wiring PI
  if(wiringPiSetupSys() == -1) {
    std::cerr << "wiringPiSetup failed, exiting..." << std::endl;
    return 1;
  }
  // Init RF Switch
  if (pulseLength != 0) rfSwitch.setPulseLength(pulseLength);
  rfSwitch.enableReceive(RF_DEVICE_COMM_PIN);  // Receiver on interrupt 0 => that is pin #2
  rfSwitch.registerCustomInterruptHandler(transmissionHandler);
  return 0;
}

void processPacket(packet_s packet) {
  std::cout << "sensor type: " << (int) packet.stype <<
             ", sensor id: " << (int) packet.sid <<
             ", message: " << (int) packet.message << std::endl;

}

void receiveMessage(RCSwitch& rfSwitch) {
  bool receiving_first = true;
  uint64_t previous_value = 0;
  uint64_t value = 0;
  packet_t raw_packet = 0;
  std::cout << "listening..." << std::endl;
  while(1) {
    std::unique_lock<std::mutex> lk(m);
    cv.wait(lk);

    if (rfSwitch.available()) {
      value = rfSwitch.getReceivedValue();
      // std::cout << value << std::endl;
      rfSwitch.resetAvailable();
      if (value == previous_value)
        continue; // If we receive the same value, this is just a repeat
      previous_value = value;
      raw_packet |= value;
      // If we are receiving the first part of the packet, shift the value by
      // 32 to let room for the second half
      if (receiving_first) {
        raw_packet <<= 32;
        receiving_first = false;
      } else {
        // We received the second part, process it
        packet_s packet;
        int ret = read_packet(raw_packet, &packet);
        if (ret == WRONG_MAGIC_ERROR) {
          std::cout << "DEBUG: Wrong magic number, dismiss message" << std::endl;
          continue;
        } else if (ret == PARITY_ERROR) {
          std::cerr << "ERROR: Parity error in message, tread lightly" << std::endl;
        }
        processPacket(packet);
        receiving_first = true;
        raw_packet = 0;
        value = 0;
      }
    }
  }
}

int main(int argc, char **argv) {
  RCSwitch rfSwitch;

  int retcode;
  if ((retcode = init(rfSwitch, 0)) != 0) {
    std::cout << "Initialization failed with " << retcode << std::endl;
    return retcode;
  }

  receiveMessage(rfSwitch);

  return 0;
}

<|endoftext|>


<commit_before>#pragma once

#include <agency/detail/config.hpp>
#include <agency/detail/index_cast.hpp>
#include <agency/detail/shape_cast.hpp>
#include <agency/detail/swap.hpp>
#include <agency/detail/memory/allocator_traits.hpp>
#include <utility>
#include <memory>

namespace agency
{
namespace detail
{

template<class T, class Shape = size_t, class Alloc = std::allocator<T>, class Index = Shape>
class array
{
  public:
    using value_type = T;

    using allocator_type = typename std::allocator_traits<Alloc>::template rebind_alloc<value_type>;

    using pointer = typename std::allocator_traits<allocator_type>::pointer;

    using const_pointer = typename std::allocator_traits<allocator_type>::const_pointer;

    using shape_type = Shape;

    using index_type = Index;

    // note that array's constructors have __agency_hd_warning_disable__
    // because Alloc's constructors may not have __AGENCY_ANNOTATION

    __agency_hd_warning_disable__
    __AGENCY_ANNOTATION
    array() : alloc_{}, shape_{}, data_(nullptr) {}

    __agency_hd_warning_disable__
    __AGENCY_ANNOTATION
    explicit array(const shape_type& shape, const allocator_type& alloc = allocator_type())
      : alloc_(allocator_type()),
        shape_(shape),
        data_(allocate_and_construct_elements(alloc_, size()))
    {
    }

    __agency_hd_warning_disable__
    __AGENCY_ANNOTATION
    explicit array(const shape_type& shape, const T& val, const allocator_type& alloc = allocator_type())
      : alloc_(alloc),
        shape_(shape),
        data_(allocate_and_construct_elements(alloc_, size(), val))
    {
    }

    __agency_hd_warning_disable__
    template<class Iterator,
             class = typename std::enable_if<
               !std::is_convertible<Iterator,shape_type>::value
             >::type>
    __AGENCY_ANNOTATION
    array(Iterator first, Iterator last)
      : array(shape_cast<shape_type>(last - first))
    {
      for(auto result = begin(); result != end(); ++result, ++first)
      {
        *result = *first;
      }
    }

    __agency_hd_warning_disable__
    __AGENCY_ANNOTATION
    array(const array& other)
      : array(other.shape())
    {
      auto iter = other.begin();
      auto result = begin();

      for(; iter != other.end(); ++iter, ++result)
      {
        *result = *iter;
      }
    }

    __agency_hd_warning_disable__
    __AGENCY_ANNOTATION
    array(array&& other)
      : alloc_{}, shape_{}, data_{}
    {
      swap(other);
    }

    __AGENCY_ANNOTATION
    ~array()
    {
      clear();
    }

    __AGENCY_ANNOTATION
    array& operator=(const array& other)
    {
      // XXX this is not a very efficient implementation
      array tmp = other;
      swap(tmp);
      return *this;
    }

    __AGENCY_ANNOTATION
    array& operator=(array&& other)
    {
      swap(other);
      return *this;
    }

    __AGENCY_ANNOTATION
    void swap(array& other)
    {
      agency::detail::swap(shape_, other.shape_);
      agency::detail::swap(data_,  other.data_);
    }

    __AGENCY_ANNOTATION
    value_type& operator[](index_type idx)
    {
      std::size_t idx_1d = agency::detail::index_cast<std::size_t>(idx, shape(), size());

      return data_[idx_1d];
    }

    __AGENCY_ANNOTATION
    shape_type shape() const
    {
      return shape_;
    }

    __AGENCY_ANNOTATION
    std::size_t size() const
    {
      return agency::detail::shape_cast<std::size_t>(shape_);
    }

    __AGENCY_ANNOTATION
    pointer data()
    {
      return data_;
    }

    __AGENCY_ANNOTATION
    const_pointer data() const
    {
      return data_;
    }

    __AGENCY_ANNOTATION
    pointer begin()
    {
      return data();
    }

    __AGENCY_ANNOTATION
    pointer end()
    {
      return begin() + size();
    }

    __AGENCY_ANNOTATION
    const_pointer begin() const
    {
      return data();
    }

    __AGENCY_ANNOTATION
    const_pointer cbegin() const
    {
      return begin();
    }

    __AGENCY_ANNOTATION
    const_pointer end() const
    {
      return begin() + size();
    }

    __AGENCY_ANNOTATION
    const_pointer cend() const
    {
      return end();
    }

    __agency_hd_warning_disable__
    __AGENCY_ANNOTATION
    void clear()
    {
      if(size())
      {
        // XXX should really destroy through the allocator
        for(auto& x : *this)
        {
          x.~value_type();
        }

        alloc_.deallocate(data_, size());

        shape_ = shape_type{};
      }
    }

    __agency_hd_warning_disable__
    template<class Range>
    __AGENCY_ANNOTATION
    bool operator==(const Range& rhs) const
    {
      auto i = begin();
      auto j = rhs.begin();

      for(; i != end(); ++i, ++j)
      {
        if(*i != *j)
        {
          return false;
        }
      }

      return true;
    }

  private:
    __agency_hd_warning_disable__
    template<class... Args>
    __AGENCY_ANNOTATION
    static pointer allocate_and_construct_elements(allocator_type& alloc, size_t size, Args&&... args)
    {
      pointer result = alloc.allocate(size);

      allocator_traits<allocator_type>::construct_each(alloc, result, result + size, std::forward<Args>(args)...);

      return result;
    }

    allocator_type alloc_;

    shape_type shape_;

    pointer data_;
};

} // end detail
} // end agency

<commit_msg>Add __agency_hd_warning_disable__ to array's destructor<commit_after>#pragma once

#include <agency/detail/config.hpp>
#include <agency/detail/index_cast.hpp>
#include <agency/detail/shape_cast.hpp>
#include <agency/detail/swap.hpp>
#include <agency/detail/memory/allocator_traits.hpp>
#include <utility>
#include <memory>

namespace agency
{
namespace detail
{

template<class T, class Shape = size_t, class Alloc = std::allocator<T>, class Index = Shape>
class array
{
  public:
    using value_type = T;

    using allocator_type = typename std::allocator_traits<Alloc>::template rebind_alloc<value_type>;

    using pointer = typename std::allocator_traits<allocator_type>::pointer;

    using const_pointer = typename std::allocator_traits<allocator_type>::const_pointer;

    using shape_type = Shape;

    using index_type = Index;

    // note that array's constructors have __agency_hd_warning_disable__
    // because Alloc's constructors may not have __AGENCY_ANNOTATION

    __agency_hd_warning_disable__
    __AGENCY_ANNOTATION
    array() : alloc_{}, shape_{}, data_(nullptr) {}

    __agency_hd_warning_disable__
    __AGENCY_ANNOTATION
    explicit array(const shape_type& shape, const allocator_type& alloc = allocator_type())
      : alloc_(allocator_type()),
        shape_(shape),
        data_(allocate_and_construct_elements(alloc_, size()))
    {
    }

    __agency_hd_warning_disable__
    __AGENCY_ANNOTATION
    explicit array(const shape_type& shape, const T& val, const allocator_type& alloc = allocator_type())
      : alloc_(alloc),
        shape_(shape),
        data_(allocate_and_construct_elements(alloc_, size(), val))
    {
    }

    __agency_hd_warning_disable__
    template<class Iterator,
             class = typename std::enable_if<
               !std::is_convertible<Iterator,shape_type>::value
             >::type>
    __AGENCY_ANNOTATION
    array(Iterator first, Iterator last)
      : array(shape_cast<shape_type>(last - first))
    {
      for(auto result = begin(); result != end(); ++result, ++first)
      {
        *result = *first;
      }
    }

    __agency_hd_warning_disable__
    __AGENCY_ANNOTATION
    array(const array& other)
      : array(other.shape())
    {
      auto iter = other.begin();
      auto result = begin();

      for(; iter != other.end(); ++iter, ++result)
      {
        *result = *iter;
      }
    }

    __agency_hd_warning_disable__
    __AGENCY_ANNOTATION
    array(array&& other)
      : alloc_{}, shape_{}, data_{}
    {
      swap(other);
    }

    __agency_hd_warning_disable__
    __AGENCY_ANNOTATION
    ~array()
    {
      clear();
    }

    __AGENCY_ANNOTATION
    array& operator=(const array& other)
    {
      // XXX this is not a very efficient implementation
      array tmp = other;
      swap(tmp);
      return *this;
    }

    __AGENCY_ANNOTATION
    array& operator=(array&& other)
    {
      swap(other);
      return *this;
    }

    __AGENCY_ANNOTATION
    void swap(array& other)
    {
      agency::detail::swap(shape_, other.shape_);
      agency::detail::swap(data_,  other.data_);
    }

    __AGENCY_ANNOTATION
    value_type& operator[](index_type idx)
    {
      std::size_t idx_1d = agency::detail::index_cast<std::size_t>(idx, shape(), size());

      return data_[idx_1d];
    }

    __AGENCY_ANNOTATION
    shape_type shape() const
    {
      return shape_;
    }

    __AGENCY_ANNOTATION
    std::size_t size() const
    {
      return agency::detail::shape_cast<std::size_t>(shape_);
    }

    __AGENCY_ANNOTATION
    pointer data()
    {
      return data_;
    }

    __AGENCY_ANNOTATION
    const_pointer data() const
    {
      return data_;
    }

    __AGENCY_ANNOTATION
    pointer begin()
    {
      return data();
    }

    __AGENCY_ANNOTATION
    pointer end()
    {
      return begin() + size();
    }

    __AGENCY_ANNOTATION
    const_pointer begin() const
    {
      return data();
    }

    __AGENCY_ANNOTATION
    const_pointer cbegin() const
    {
      return begin();
    }

    __AGENCY_ANNOTATION
    const_pointer end() const
    {
      return begin() + size();
    }

    __AGENCY_ANNOTATION
    const_pointer cend() const
    {
      return end();
    }

    __agency_hd_warning_disable__
    __AGENCY_ANNOTATION
    void clear()
    {
      if(size())
      {
        // XXX should really destroy through the allocator
        for(auto& x : *this)
        {
          x.~value_type();
        }

        alloc_.deallocate(data_, size());

        shape_ = shape_type{};
      }
    }

    __agency_hd_warning_disable__
    template<class Range>
    __AGENCY_ANNOTATION
    bool operator==(const Range& rhs) const
    {
      auto i = begin();
      auto j = rhs.begin();

      for(; i != end(); ++i, ++j)
      {
        if(*i != *j)
        {
          return false;
        }
      }

      return true;
    }

  private:
    __agency_hd_warning_disable__
    template<class... Args>
    __AGENCY_ANNOTATION
    static pointer allocate_and_construct_elements(allocator_type& alloc, size_t size, Args&&... args)
    {
      pointer result = alloc.allocate(size);

      allocator_traits<allocator_type>::construct_each(alloc, result, result + size, std::forward<Args>(args)...);

      return result;
    }

    allocator_type alloc_;

    shape_type shape_;

    pointer data_;
};

} // end detail
} // end agency

<|endoftext|>


<commit_before>/*
 * lanczosSO.hpp
 *
 *  Created on: Mar 3, 2015
 *      Author: hugo
 */

#ifndef ALGORITHM_LANCZOSSO_HPP_
#define ALGORITHM_LANCZOSSO_HPP_

#include <string>

#include "../core/matrix.hpp"
#include "../Eigen/Dense"

using namespace std;

namespace mflash{

	class LancsosSO{
			Matrix<float, EmptyType> *matrix;
			int iterations;
			int k;

		public:
			void run();
	};

	void LancsosSO::run(){
		string path = mflash::get_parent_directory(matrix->get_file());

		const int64 block_size = matrix->get_elements_by_block();

	}

}

#endif /* ALGORITHM_LANCZOSSO_HPP_ */
<commit_msg>Lanczos Implementation using double without rit vectors<commit_after>/*
 * lanczosSO.hpp
 *
 *  Created on: Mar 3, 2015
 *      Author: hugo
 */

#ifndef ALGORITHM_LANCZOSSO_HPP_
#define ALGORITHM_LANCZOSSO_HPP_

#include <string>
#include <cmath>
#include "../core/matrix.hpp"
#include "../core/primitivevector.hpp"

#include "../Eigen/Dense"

#include "../log/easylogging++.h"

using namespace std;

namespace mflash{

	class LanczosSO{
			PrimitiveMatrix<double, EmptyType> *matrix;
			int iterations;
			int k;

			Eigen::Matrix build_tridiagonal_matrix(int m, double alpha [], double beta[]);

		public:
			void run();
	};

	void LanczosSO::run(){
		string path = mflash::get_parent_directory(matrix->get_file()) + FILE_SEPARATOR;
		string v_file = path + "v.bin";
		//string v_tmp = path + FILE_SEPARATOR + "tmp.bin";
		string r_file = path + "r.bin";

		const int64 block_size = matrix->get_elements_by_block();
		const int64 node_count = matrix->size();

		double epsilon = sqrt(1E-18);
		double beta[] = new double[iterations];
		double alpha[] = new double[iterations];

		//orthogonal vectors v
		PrimitiveVector<double> *vectors[] = new PrimitiveVector<double>*[iterations];
		PrimitiveVector<double> v (v_file, node_count, block_size);
		PrimitiveVector<double> r (r_file, node_count, block_size);

		LOG (INFO) << "1: initial values";
		vectors[0] = new PrimitiveVector<double> ( path + "v0", node_count, block_size );
		vectors[0]->fill_random();
		vectors[0]->multiply(((double)1/vectors[0]->pnorm(2)));

		for (int i = 0; i < iterations; i++){
				LOG (INFO) << "3: Find a new basis vector";
				matrix->multiply( *(vectors[i]), v);

				LOG (INFO) << "4:";
				alpha[i] = vectors[i]->transpose().multiply(v);

				LOG (INFO) << "5: v = v - beta[i-1]V[i-1] - alpha[i]V[i]";
				if(i>0){
						v.linear_combination(3, new double[3]{1, -1*beta[i-1], -1*alpha[i]}, new PrimitiveVector<double>*[3]{&v, vectors[i-1], vectors[i]});
				}else{
						v.linear_combination(2, new double[2]{1, -1*alpha[i]}, new PrimitiveVector<double>*[2]{&v, vectors[i]});
				}

				LOG (INFO) << "6: beta[i] = ||v||";
				beta[i] = v.pnorm(2);

				LOG (INFO) << "7: build tri-diagonal matrix from alpha and beta";
				Eigen::Matrix<double, i+1, i+1> ti = build_tridiagonal_matrix(i+1, alpha, beta);

				LOG (INFO) << "8: ";
				Eigen::SelfAdjointEigenSolver<Eigen::Matrix<double,i+1,i+1> > eigensolver(ti);
				Eigen::Matrix<double, i+1, 1> evalues = eigensolver.eigenvalues();
				Eigen::Matrix<double, i+1, i+1> q = eigensolver.eigenvectors();

				LOG (INFO) << "Iteration " << i << ", EigenValues: ";
				LOG (INFO) << evalues;

				Eigen::Matrix<double, i+1, 1> mtmp = alpha;
				LOG (INFO) << "Alphas: ";
				LOG (INFO) << mtmp;
				mtmp = beta;
				LOG (INFO) << "Betas: ";
				LOG (INFO) << mtmp;

				//Max singular value
				double max_sv = abs((double)evalues[0]);
				for (int i = 1; i <= i; i++){
						max_sv = max(max_sv, abs((double)evalues[i]));
				}
				LOG (INFO) << "Max Singular Value = " << max_sv;

				bool so = false;

				LOG (INFO) << "9: Reorthogonalization";
				for (int j = 0; j <= i; j++){
						if (beta[i] * abs((double) q[i][j]) <= epsilon * max_sv){
							 LOG (INFO) << "Reorthogonalization for ritz vector = "<< j;

							 double constants [] = new double[i+1];
							 for ( int k = 0; k < i+1; k++ ){
									 constants[k] = (double)q[k,j];
							 }
							 r.linear_combination(i+1, constants, vectors);
							 //-(r*v)
							 double constant = -1 * r.transpose().multiply(v);
							 //v=v-(r*v)r
							 v.linear_combination(2, new double[2]{1, constant},  new PrimitiveVector<double>*[2]{&v, &r});
							 so = true;
						}
				}
				LOG (INFO) << "15:";
				if ( so ){
						LOG (INFO) << "16: Recompute normalization constant beta["<< i <<"]";
						beta[i] = v.pnorm(2);
				}

				LOG (INFO) << "18:";
				if ( beta[i] == 0){
						iterations = i+1;
						break;
				}

				if ( i < iterations-1 ){
						LOG (INFO) << "21: V[i+1] = v/beta[i]";
						vectors[i+1] = new PrimitiveVector(path + "v" + (i+1), node_count, block_size);
						v.multiply(1/beta[i], *vectors[i+1]);
				}
		}
		LOG (INFO) << "Creating EigenValues";
		Eigen::Matrix<double, iterations, iterations> ti = build_tridiagonal_matrix(iterations, alpha, beta);
		Eigen::SelfAdjointEigenSolver<Eigen::Matrix<double,iterations,iterations> > eigensolver(ti);
		Eigen::Matrix<double, iterations, 1> evalues = eigensolver.eigenvalues();
		Eigen::Matrix<double, iterations, iterations> q = eigensolver.eigenvectors();

		//int64 ids[] = new int64[topK];

	}

	Eigen::Matrix LanczosSO::build_tridiagonal_matrix(int m, double alpha [], double beta[]){

		Eigen::Matrix<double, m, m> matrix;
		matrix.fill(0);

		matrix[0][0] = alpha[0];

		if(m==1) return matrix;

		matrix[0][1] = beta[0];
		matrix[m-1][m-2] = beta[m-2];
		matrix[m-1][m-1] = alpha[m-1];

		for(int i=1; i<m-1; i++){
			matrix[i][i] = 		alpha[i];
			matrix[i][i+1] = 	beta[i];
			matrix[i][i-1] =	beta[i-1];
		}
		return matrix;
	}
}

#endif /* ALGORITHM_LANCZOSSO_HPP_ */
<|endoftext|>


<commit_before>/*
This file is part of Bohrium and copyright (c) 2012 the Bohrium
team <http://www.bh107.org>.

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

Bohrium 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 General Public License for more details.

You should have received a copy of the
GNU Lesser General Public License along with Bohrium.

If not, see <http://www.gnu.org/licenses/>.
*/

#pragma once

#include <cstdint>
#include <bhxx/BhArray.hpp>
#include <bhxx/array_operations.hpp>

namespace bhxx {

/** Return a new empty array
 *
 * @tparam T    The data type of the new array
 * @param shape The shape of the new array
 * @return      The new array
 */
template<typename T>
BhArray <T> empty(Shape shape) {
    return BhArray<T>{std::move(shape)};
}

/** Return a new empty array that has the same shape as `ary`
 *
 * @tparam OutType  The data type of the returned new array
 * @tparam InType   The data type of the input array
 * @param ary       The array to take the shape from
 * @return          The new array
 */
template<typename OutType, typename InType>
BhArray <OutType> empty_like(const bhxx::BhArray<InType> &ary) {
    return BhArray<OutType>{ary.shape()};
}

/** Return a new array filled with zeros
 *
 * @tparam T    The data type of the new array
 * @param shape The shape of the new array
 * @return      The new array
 */
template<typename T>
BhArray <T> zeros(Shape shape) {
    BhArray<T> ret{std::move(shape)};
    ret = T{0};
    return ret;
}

/** Return evenly spaced values within a given interval.
 *
 * @tparam T     Data type of the returned array
 * @param start  Start of interval. The interval includes this value.
 * @param stop   End of interval. The interval does not include this value.
 * @param step   Spacing between values. For any output out, this is the distance between
 *               two adjacent values, out[i+1] - out[i].
 * @return       New 1D array
 */
template<typename T>
BhArray <T> arange(int64_t start, int64_t stop, int64_t step);

/** Return evenly spaced values within a given interval using steps of 1.
 *
 * @tparam T     Data type of the returned array
 * @param start  Start of interval. The interval includes this value.
 * @param stop   End of interval. The interval does not include this value.
 * @return       New 1D array
 */
template<typename T>
BhArray <T> arange(int64_t start, int64_t stop) {
    return arange<T>(start, stop, 1);
}

/** Return evenly spaced values from 0 to `stop` using steps of 1.
 *
 * @tparam T     Data type of the returned array
 * @param stop   End of interval. The interval does not include this value.
 * @return       New 1D array
 */
template<typename T>
BhArray <T> arange(int64_t stop) {
    return arange<T>(0, stop, 1);
}

/** Element-wise `static_cast`.
 *
 * @tparam OutType  The data type of the returned array
 * @tparam InType   The data type of the input array
 * @param ary       Input array to cast
 * @return          New array
 */
template<typename OutType, typename InType>
BhArray <OutType> cast(const bhxx::BhArray<InType> &ary) {
    BhArray<OutType> ret = empty_like<OutType>(ary);
    bhxx::identity(ret, ary);
    return ret;
}

}  // namespace bhxx
<commit_msg>bhxx: implemented ones() and full()<commit_after>/*
This file is part of Bohrium and copyright (c) 2012 the Bohrium
team <http://www.bh107.org>.

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

Bohrium 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 General Public License for more details.

You should have received a copy of the
GNU Lesser General Public License along with Bohrium.

If not, see <http://www.gnu.org/licenses/>.
*/

#pragma once

#include <cstdint>
#include <bhxx/BhArray.hpp>
#include <bhxx/array_operations.hpp>

namespace bhxx {

/** Return a new empty array
 *
 * @tparam T    The data type of the new array
 * @param shape The shape of the new array
 * @return      The new array
 */
template<typename T>
BhArray <T> empty(Shape shape) {
    return BhArray<T>{std::move(shape)};
}

/** Return a new empty array that has the same shape as `ary`
 *
 * @tparam OutType  The data type of the returned new array
 * @tparam InType   The data type of the input array
 * @param ary       The array to take the shape from
 * @return          The new array
 */
template<typename OutType, typename InType>
BhArray <OutType> empty_like(const bhxx::BhArray<InType> &ary) {
    return BhArray<OutType>{ary.shape()};
}

/** Return a new array filled with `value`
 *
 * @tparam T    The data type of the new array
 * @param shape The shape of the new array
 * @param value The value to fill the new array with
 * @return      The new array
 */
template<typename T>
BhArray <T> full(Shape shape, T value) {
    BhArray<T> ret{std::move(shape)};
    ret = value;
    return ret;
}

/** Return a new array filled with zeros
 *
 * @tparam T    The data type of the new array
 * @param shape The shape of the new array
 * @return      The new array
 */
template<typename T>
BhArray <T> zeros(Shape shape) {
    return full(std::move(shape), T{0});
}

/** Return a new array filled with ones
 *
 * @tparam T    The data type of the new array
 * @param shape The shape of the new array
 * @return      The new array
 */
template<typename T>
BhArray <T> ones(Shape shape) {
    return full(std::move(shape), T{1});
}

/** Return evenly spaced values within a given interval.
 *
 * @tparam T     Data type of the returned array
 * @param start  Start of interval. The interval includes this value.
 * @param stop   End of interval. The interval does not include this value.
 * @param step   Spacing between values. For any output out, this is the distance between
 *               two adjacent values, out[i+1] - out[i].
 * @return       New 1D array
 */
template<typename T>
BhArray <T> arange(int64_t start, int64_t stop, int64_t step);

/** Return evenly spaced values within a given interval using steps of 1.
 *
 * @tparam T     Data type of the returned array
 * @param start  Start of interval. The interval includes this value.
 * @param stop   End of interval. The interval does not include this value.
 * @return       New 1D array
 */
template<typename T>
BhArray <T> arange(int64_t start, int64_t stop) {
    return arange<T>(start, stop, 1);
}

/** Return evenly spaced values from 0 to `stop` using steps of 1.
 *
 * @tparam T     Data type of the returned array
 * @param stop   End of interval. The interval does not include this value.
 * @return       New 1D array
 */
template<typename T>
BhArray <T> arange(int64_t stop) {
    return arange<T>(0, stop, 1);
}

/** Element-wise `static_cast`.
 *
 * @tparam OutType  The data type of the returned array
 * @tparam InType   The data type of the input array
 * @param ary       Input array to cast
 * @return          New array
 */
template<typename OutType, typename InType>
BhArray <OutType> cast(const bhxx::BhArray<InType> &ary) {
    BhArray<OutType> ret = empty_like<OutType>(ary);
    bhxx::identity(ret, ary);
    return ret;
}

}  // namespace bhxx
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: urp_writer.cxx,v $
 *
 *  $Revision: 1.12 $
 *
 *  last change: $Author: vg $ $Date: 2003-04-15 16:29:18 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (the "License"); You may not use this file
 *  except in compliance with the License. You may obtain a copy of the
 *  License at http://www.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/
#include <stdio.h>

#ifndef _OSL_TIME_H_
#include <osl/time.h>
#endif

#include <osl/mutex.hxx>
#include <osl/conditn.h>

#include <typelib/typedescription.h>

#include <bridges/remote/connection.h>
#include <bridges/remote/remote.hxx>

#include <com/sun/star/uno/Sequence.hxx>

#include <bridges/remote/counter.hxx>

#include "urp_writer.hxx"
#include "urp_bridgeimpl.hxx"
#include "urp_marshal.hxx"
#include "urp_dispatch.hxx"

#if OSL_DEBUG_LEVEL > 1
static MyCounter thisCounter( "DEBUG : WriterThread" );
#endif

using namespace ::osl;

namespace bridges_urp {

OWriterThread::OWriterThread( remote_Connection *pConnection, urp_BridgeImpl *pBridgeImpl,
                              uno_Environment *pEnvRemote) :
    m_pConnection( pConnection ),
    m_bAbort( sal_False ),
    m_pBridgeImpl( pBridgeImpl ),
    m_pEnvRemote( pEnvRemote ),
    m_bInBlockingWait( sal_False ),
    m_bEnterBlockingWait( sal_False )

{
    m_oslCondition = osl_createCondition();
    osl_resetCondition( m_oslCondition );
    m_pConnection->acquire( m_pConnection );

#if OSL_DEBUG_LEVEL > 1
    thisCounter.acquire();
#endif
}

OWriterThread::~OWriterThread()
{
    osl_destroyCondition( m_oslCondition );
    m_pConnection->release( m_pConnection );
#if OSL_DEBUG_LEVEL > 1
    thisCounter.release();
#endif
}

// touch is called with locked m_marshalingMutex
void OWriterThread::touch( sal_Bool bImmediately )
{
      if( bImmediately || m_pBridgeImpl->m_blockMarshaler.getPos() > m_pBridgeImpl->m_properties.nFlushBlockSize )
      {
        write();
      }
    else
    {
        // wake the writer thread up
        if( m_bInBlockingWait )
        {
            m_bInBlockingWait = sal_False;
            osl_setCondition( m_oslCondition );
        }
        else
        {
            // ensure, that the writing thread does not enter blocking mode
              m_bEnterBlockingWait = sal_False;
        }
    }
}

void OWriterThread::abort()
{
    MutexGuard guard( m_pBridgeImpl->m_marshalingMutex );

    m_bAbort = sal_True;
    m_bEnterBlockingWait = sal_False;
    if( m_bInBlockingWait )
    {
        m_bInBlockingWait = sal_False;
        osl_setCondition( m_oslCondition );
    }
}

// must be called with locked marshaling mutex
void OWriterThread::write()
{
     if( ! m_pBridgeImpl->m_blockMarshaler.empty() && ! m_bAbort )
     {
        m_pBridgeImpl->m_blockMarshaler.finish( m_pBridgeImpl->m_nMarshaledMessages);
        m_pBridgeImpl->m_nMarshaledMessages = 0;

        sal_Int32 nLength = m_pBridgeImpl->m_blockMarshaler.getSize();
        sal_Int8 *pBuf = m_pBridgeImpl->m_blockMarshaler.getBuffer();

        if( nLength != m_pConnection->write( m_pConnection, pBuf, nLength ))
        {
            m_pBridgeImpl->m_blockMarshaler.restart();
            return;
        }
        m_pConnection->flush( m_pConnection );
        m_pBridgeImpl->m_blockMarshaler.restart();
    }
}

void OWriterThread::sendEmptyMessage()
{
    // must be called with locked marshaling mutex
    sal_Int32 a[2] = {0,0};
    if( m_pConnection )
    {
        m_pConnection->write( m_pConnection , (sal_Int8*) a , sizeof( sal_Int32) *2 );
    }
}

void OWriterThread::insertReleaseRemoteCall(
    rtl_uString *pOid,typelib_TypeDescriptionReference *pTypeRef)
{
    {
        ::osl::MutexGuard guard( m_releaseCallMutex );

        struct RemoteReleaseCall call;
        call.sOid = pOid;
        call.typeInterface = pTypeRef;
        m_lstReleaseCalls.push_back( call );
    }
    {
        MutexGuard guard( m_pBridgeImpl->m_marshalingMutex );
        if( m_bInBlockingWait )
        {
            m_bInBlockingWait = sal_False;
            osl_setCondition( m_oslCondition );
        }
        else
        {
            // ensure, that the writing thread does not enter blocking mode
              m_bEnterBlockingWait = sal_False;
        }
    }
}

/* The release calls for doubled interfaces
 *
 *
 ***/
void OWriterThread::executeReleaseRemoteCalls()
{
    sal_Bool bFound = sal_True;
    ::std::list< struct RemoteReleaseCall > lstReleaseCalls;
    {
        ::osl::MutexGuard guard( m_releaseCallMutex );
        lstReleaseCalls.swap( m_lstReleaseCalls );
    }

    for( ::std::list< struct RemoteReleaseCall >::iterator ii = lstReleaseCalls.begin();
         ii != lstReleaseCalls.end();
         ++ ii )
    {
        struct RemoteReleaseCall &call = (*ii) ;

        typelib_TypeDescription *pInterfaceTypeDesc = 0;
        typelib_TypeDescription *pReleaseMethod = 0;

        call.typeInterface.getDescription( &pInterfaceTypeDesc );
        if( ! pInterfaceTypeDesc->bComplete )
        {
            typelib_typedescription_complete( &pInterfaceTypeDesc );
        }

        uno_Any any;
        uno_Any *pAny = &any;

        typelib_typedescriptionreference_getDescription(
            &pReleaseMethod ,
            ((typelib_InterfaceTypeDescription*)pInterfaceTypeDesc)->ppAllMembers[REMOTE_RELEASE_METHOD_INDEX] );

        urp_sendRequest( m_pEnvRemote , pReleaseMethod, call.sOid.pData,
                         (typelib_InterfaceTypeDescription*) pInterfaceTypeDesc,
                         0, 0 , &pAny );

        typelib_typedescription_release( pReleaseMethod );
        typelib_typedescription_release( pInterfaceTypeDesc );
    }
}

void OWriterThread::run()
{
    while( ! m_bAbort )
    {
        sal_Bool bWait;
        {
            MutexGuard guard( m_pBridgeImpl->m_marshalingMutex );
            bWait = m_bEnterBlockingWait;
            if( bWait )
            {
                osl_resetCondition( m_oslCondition );
                m_bInBlockingWait = sal_True;
            }
            m_bEnterBlockingWait = sal_True;
        }

        // wait for some notification
        if( bWait )
            osl_waitCondition( m_oslCondition , 0 );
        // (m_bInBlockingWait = sal_False was set by the activating thread)

          if( m_bAbort )
              break;

        // Wait for the timeout
        TimeValue value = { 0 , 1000 * m_pBridgeImpl->m_properties.nOnewayTimeoutMUSEC };
        osl_resetCondition( m_oslCondition );
        osl_waitCondition( m_oslCondition , &value );

        // check if there are some release calls to be sent ....
        executeReleaseRemoteCalls();

        {
            // write to the socket
            MutexGuard guard( m_pBridgeImpl->m_marshalingMutex );
            if( ! m_pBridgeImpl->m_blockMarshaler.empty() )
            {
                write();
            }
        }
    }
}

}

<commit_msg>INTEGRATION: CWS ooo20040329 (1.12.90); FILE MERGED 2004/03/17 10:21:09 waratah 1.12.90.1: #i1858# alter the order of some definitions to fix some -Wall warnings<commit_after>/*************************************************************************
 *
 *  $RCSfile: urp_writer.cxx,v $
 *
 *  $Revision: 1.13 $
 *
 *  last change: $Author: svesik $ $Date: 2004-04-21 13:46:50 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (the "License"); You may not use this file
 *  except in compliance with the License. You may obtain a copy of the
 *  License at http://www.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/
#include <stdio.h>
#ifndef _OSL_TIME_H_
#include <osl/time.h>
#endif

#include <osl/mutex.hxx>
#include <osl/conditn.h>

#include <typelib/typedescription.h>

#include <bridges/remote/connection.h>
#include <bridges/remote/remote.hxx>

#include <com/sun/star/uno/Sequence.hxx>

#include <bridges/remote/counter.hxx>

#include "urp_writer.hxx"
#include "urp_bridgeimpl.hxx"
#include "urp_marshal.hxx"
#include "urp_dispatch.hxx"

#if OSL_DEBUG_LEVEL > 1
static MyCounter thisCounter( "DEBUG : WriterThread" );
#endif

using namespace ::osl;

namespace bridges_urp {

OWriterThread::OWriterThread( remote_Connection *pConnection, urp_BridgeImpl *pBridgeImpl,
                              uno_Environment *pEnvRemote) :
    m_bAbort( sal_False ),
    m_bInBlockingWait( sal_False ),
    m_bEnterBlockingWait( sal_False ),
    m_pConnection( pConnection ),
    m_pBridgeImpl( pBridgeImpl ),
    m_pEnvRemote( pEnvRemote )

{
    m_oslCondition = osl_createCondition();
    osl_resetCondition( m_oslCondition );
    m_pConnection->acquire( m_pConnection );

#if OSL_DEBUG_LEVEL > 1
    thisCounter.acquire();
#endif
}

OWriterThread::~OWriterThread()
{
    osl_destroyCondition( m_oslCondition );
    m_pConnection->release( m_pConnection );
#if OSL_DEBUG_LEVEL > 1
    thisCounter.release();
#endif
}

// touch is called with locked m_marshalingMutex
void OWriterThread::touch( sal_Bool bImmediately )
{
      if( bImmediately || m_pBridgeImpl->m_blockMarshaler.getPos() > m_pBridgeImpl->m_properties.nFlushBlockSize )
      {
        write();
      }
    else
    {
        // wake the writer thread up
        if( m_bInBlockingWait )
        {
            m_bInBlockingWait = sal_False;
            osl_setCondition( m_oslCondition );
        }
        else
        {
            // ensure, that the writing thread does not enter blocking mode
              m_bEnterBlockingWait = sal_False;
        }
    }
}

void OWriterThread::abort()
{
    MutexGuard guard( m_pBridgeImpl->m_marshalingMutex );

    m_bAbort = sal_True;
    m_bEnterBlockingWait = sal_False;
    if( m_bInBlockingWait )
    {
        m_bInBlockingWait = sal_False;
        osl_setCondition( m_oslCondition );
    }
}

// must be called with locked marshaling mutex
void OWriterThread::write()
{
     if( ! m_pBridgeImpl->m_blockMarshaler.empty() && ! m_bAbort )
     {
        m_pBridgeImpl->m_blockMarshaler.finish( m_pBridgeImpl->m_nMarshaledMessages);
        m_pBridgeImpl->m_nMarshaledMessages = 0;

        sal_Int32 nLength = m_pBridgeImpl->m_blockMarshaler.getSize();
        sal_Int8 *pBuf = m_pBridgeImpl->m_blockMarshaler.getBuffer();

        if( nLength != m_pConnection->write( m_pConnection, pBuf, nLength ))
        {
            m_pBridgeImpl->m_blockMarshaler.restart();
            return;
        }
        m_pConnection->flush( m_pConnection );
        m_pBridgeImpl->m_blockMarshaler.restart();
    }
}

void OWriterThread::sendEmptyMessage()
{
    // must be called with locked marshaling mutex
    sal_Int32 a[2] = {0,0};
    if( m_pConnection )
    {
        m_pConnection->write( m_pConnection , (sal_Int8*) a , sizeof( sal_Int32) *2 );
    }
}

void OWriterThread::insertReleaseRemoteCall(
    rtl_uString *pOid,typelib_TypeDescriptionReference *pTypeRef)
{
    {
        ::osl::MutexGuard guard( m_releaseCallMutex );

        struct RemoteReleaseCall call;
        call.sOid = pOid;
        call.typeInterface = pTypeRef;
        m_lstReleaseCalls.push_back( call );
    }
    {
        MutexGuard guard( m_pBridgeImpl->m_marshalingMutex );
        if( m_bInBlockingWait )
        {
            m_bInBlockingWait = sal_False;
            osl_setCondition( m_oslCondition );
        }
        else
        {
            // ensure, that the writing thread does not enter blocking mode
              m_bEnterBlockingWait = sal_False;
        }
    }
}

/* The release calls for doubled interfaces
 *
 *
 ***/
void OWriterThread::executeReleaseRemoteCalls()
{
    ::std::list< struct RemoteReleaseCall > lstReleaseCalls;
    {
        ::osl::MutexGuard guard( m_releaseCallMutex );
        lstReleaseCalls.swap( m_lstReleaseCalls );
    }

    for( ::std::list< struct RemoteReleaseCall >::iterator ii = lstReleaseCalls.begin();
         ii != lstReleaseCalls.end();
         ++ ii )
    {
        struct RemoteReleaseCall &call = (*ii) ;

        typelib_TypeDescription *pInterfaceTypeDesc = 0;
        typelib_TypeDescription *pReleaseMethod = 0;

        call.typeInterface.getDescription( &pInterfaceTypeDesc );
        if( ! pInterfaceTypeDesc->bComplete )
        {
            typelib_typedescription_complete( &pInterfaceTypeDesc );
        }

        uno_Any any;
        uno_Any *pAny = &any;

        typelib_typedescriptionreference_getDescription(
            &pReleaseMethod ,
            ((typelib_InterfaceTypeDescription*)pInterfaceTypeDesc)->ppAllMembers[REMOTE_RELEASE_METHOD_INDEX] );

        urp_sendRequest( m_pEnvRemote , pReleaseMethod, call.sOid.pData,
                         (typelib_InterfaceTypeDescription*) pInterfaceTypeDesc,
                         0, 0 , &pAny );

        typelib_typedescription_release( pReleaseMethod );
        typelib_typedescription_release( pInterfaceTypeDesc );
    }
}

void OWriterThread::run()
{
    while( ! m_bAbort )
    {
        sal_Bool bWait;
        {
            MutexGuard guard( m_pBridgeImpl->m_marshalingMutex );
            bWait = m_bEnterBlockingWait;
            if( bWait )
            {
                osl_resetCondition( m_oslCondition );
                m_bInBlockingWait = sal_True;
            }
            m_bEnterBlockingWait = sal_True;
        }

        // wait for some notification
        if( bWait )
            osl_waitCondition( m_oslCondition , 0 );
        // (m_bInBlockingWait = sal_False was set by the activating thread)

          if( m_bAbort )
              break;

        // Wait for the timeout
        TimeValue value = { 0 , 1000 * m_pBridgeImpl->m_properties.nOnewayTimeoutMUSEC };
        osl_resetCondition( m_oslCondition );
        osl_waitCondition( m_oslCondition , &value );

        // check if there are some release calls to be sent ....
        executeReleaseRemoteCalls();

        {
            // write to the socket
            MutexGuard guard( m_pBridgeImpl->m_marshalingMutex );
            if( ! m_pBridgeImpl->m_blockMarshaler.empty() )
            {
                write();
            }
        }
    }
}

}

<|endoftext|>


<commit_before>/*!
 * \page batch_airinv_cpp Command-Line Utility to Demonstrate Typical AirInv Usage
 * \code
 */
// STL
#include <cassert>
#include <iostream>
#include <sstream>
#include <fstream>
#include <string>
// Boost (Extended STL)
#include <boost/program_options.hpp>
#include <boost/tokenizer.hpp>
// StdAir
#include <stdair/basic/BasLogParams.hpp>
#include <stdair/basic/BasDBParams.hpp>
#include <stdair/service/Logger.hpp>
// AirInv
#include <airinv/AIRINV_Master_Service.hpp>
#include <airinv/config/airinv-paths.hpp>

// //////// Constants //////
/** Default name and location for the log file. */
const std::string K_AIRINV_DEFAULT_LOG_FILENAME ("airinv.log");

/** Default name and location for the (CSV) input files. */
const std::string K_AIRINV_DEFAULT_INVENTORY_FILENAME (STDAIR_SAMPLE_DIR
                                                       "/invdump01.csv");
/** Default name and location for the (CSV) input files. */
const std::string K_AIRINV_DEFAULT_SCHEDULE_FILENAME (STDAIR_SAMPLE_DIR
                                                      "/schedule01.csv");
/** Default name and location for the (CSV) input files. */
const std::string K_AIRINV_DEFAULT_OND_FILENAME (STDAIR_SAMPLE_DIR "/ond01.csv");

/** Default segment-date key on which the sale should be made. */
const std::string K_AIRINV_DEFAULT_SEGMENT_DATE_KEY ("SV/5/2010-03-11/KBP.JFK");

/** Default class code for which the sale should be made. */
const stdair::ClassCode_T K_AIRINV_DEFAULT_CLASS_CODE ("Y");

/** Default party size for the sale. */
const stdair::PartySize_T K_AIRINV_DEFAULT_PARTY_SIZE (2);

/** Default for the input type. It can be either built-in or provided by an
    input file. That latter must then be given with the -i option. */
const bool K_AIRINV_DEFAULT_BUILT_IN_INPUT = false;

/** Default for the input type. The BOM tree can be built from either an
    inventory dump or from a schedule file (and, potentially, an O&D list). */
const bool K_AIRINV_DEFAULT_FOR_SCHEDULE = false;

/** Early return status (so that it can be differentiated from an
    error). */
const int K_AIRINV_EARLY_RETURN_STATUS = 99;

// ///////// Parsing of Options & Configuration /////////
// A helper function to simplify the main part.
template<class T> std::ostream& operator<< (std::ostream& os,
                                            const std::vector<T>& v) {
  std::copy (v.begin(), v.end(), std::ostream_iterator<T> (std::cout, " "));
  return os;
}

/** Read and parse the command line options. */
int readConfiguration (int argc, char* argv[],
                       bool& ioIsBuiltin, bool& ioIsForSchedule,
                       stdair::Filename_T& ioInventoryFilename,
                       stdair::Filename_T& ioScheduleInputFilename,
                       stdair::Filename_T& ioODInputFilename,
                       std::string& ioSegmentDateKey,
                       stdair::ClassCode_T& ioClassCode,
                       stdair::PartySize_T& ioPartySize,
                       std::string& ioLogFilename) {
  // Default for the built-in input
  ioIsBuiltin = K_AIRINV_DEFAULT_BUILT_IN_INPUT;

  // Default for the inventory or schedule option
  ioIsForSchedule = K_AIRINV_DEFAULT_FOR_SCHEDULE;

  // Declare a group of options that will be allowed only on command line
  boost::program_options::options_description generic ("Generic options");
  generic.add_options()
    ("prefix", "print installation prefix")
    ("version,v", "print version string")
    ("help,h", "produce help message");

  // Declare a group of options that will be allowed both on command
  // line and in config file

  boost::program_options::options_description config ("Configuration");
  config.add_options()
    ("builtin,b",
     "The sample BOM tree can be either built-in or parsed from an input file. That latter must then be given with the -i/--inventory or -s/--schedule option")
    ("for_schedule,f",
     "The BOM tree should be built from a schedule file (instead of from an inventory dump)")
    ("inventory,i",
     boost::program_options::value< std::string >(&ioInventoryFilename)->default_value(K_AIRINV_DEFAULT_INVENTORY_FILENAME),
     "(CVS) input file for the inventory")
    ("schedule,s",
     boost::program_options::value< std::string >(&ioScheduleInputFilename)->default_value(K_AIRINV_DEFAULT_SCHEDULE_FILENAME),
     "(CVS) input file for the schedule")
    ("ond,o",
     boost::program_options::value< std::string >(&ioODInputFilename)->default_value(K_AIRINV_DEFAULT_OND_FILENAME),
     "(CVS) input file for the O&D")
    ("segment_date_key,k",
     boost::program_options::value< std::string >(&ioSegmentDateKey)->default_value(K_AIRINV_DEFAULT_SEGMENT_DATE_KEY),
     "Segment-date key")
    ("class_code,c",
     boost::program_options::value< stdair::ClassCode_T >(&ioClassCode)->default_value(K_AIRINV_DEFAULT_CLASS_CODE),
     "Class code")
    ("party_size,p",
     boost::program_options::value< stdair::PartySize_T >(&ioPartySize)->default_value(K_AIRINV_DEFAULT_PARTY_SIZE),
     "Party size")
    ("log,l",
     boost::program_options::value< std::string >(&ioLogFilename)->default_value(K_AIRINV_DEFAULT_LOG_FILENAME),
     "Filename for the logs")
    ;

  // Hidden options, will be allowed both on command line and
  // in config file, but will not be shown to the user.
  boost::program_options::options_description hidden ("Hidden options");
  hidden.add_options()
    ("copyright",
     boost::program_options::value< std::vector<std::string> >(),
     "Show the copyright (license)");

  boost::program_options::options_description cmdline_options;
  cmdline_options.add(generic).add(config).add(hidden);

  boost::program_options::options_description config_file_options;
  config_file_options.add(config).add(hidden);
  boost::program_options::options_description visible ("Allowed options");
  visible.add(generic).add(config);

  boost::program_options::positional_options_description p;
  p.add ("copyright", -1);

  boost::program_options::variables_map vm;
  boost::program_options::
    store (boost::program_options::command_line_parser (argc, argv).
           options (cmdline_options).positional(p).run(), vm);

  std::ifstream ifs ("airinv.cfg");
  boost::program_options::store (parse_config_file (ifs, config_file_options),
                                 vm);
  boost::program_options::notify (vm);

  if (vm.count ("help")) {
    std::cout << visible << std::endl;
    return K_AIRINV_EARLY_RETURN_STATUS;
  }

  if (vm.count ("version")) {
    std::cout << PACKAGE_NAME << ", version " << PACKAGE_VERSION << std::endl;
    return K_AIRINV_EARLY_RETURN_STATUS;
  }

  if (vm.count ("prefix")) {
    std::cout << "Installation prefix: " << PREFIXDIR << std::endl;
    return K_AIRINV_EARLY_RETURN_STATUS;
  }

  if (vm.count ("builtin")) {
    ioIsBuiltin = true;
  }
  const std::string isBuiltinStr = (ioIsBuiltin == true)?"yes":"no";
  std::cout << "The BOM should be built-in? " << isBuiltinStr << std::endl;

  if (vm.count ("for_schedule")) {
    ioIsForSchedule = true;
  }
  const std::string isForScheduleStr = (ioIsForSchedule == true)?"yes":"no";
  std::cout << "The BOM should be built from schedule? " << isForScheduleStr
            << std::endl;

  if (ioIsBuiltin == false) {

    if (ioIsForSchedule == false) {
      // The BOM tree should be built from parsing an inventory dump
      if (vm.count ("inventory")) {
        ioInventoryFilename = vm["inventory"].as< std::string >();
        std::cout << "Input inventory filename is: " << ioInventoryFilename
                  << std::endl;

      } else {
        // The built-in option is not selected. However, no inventory dump
        // file is specified
        std::cerr << "Either one among the -b/--builtin, -i/--inventory or "
                  << " -f/--for_schedule and -s/--schedule options "
                  << "must be specified" << std::endl;
      }

    } else {
      // The BOM tree should be built from parsing a schedule (and O&D) file
      if (vm.count ("schedule")) {
        ioScheduleInputFilename = vm["schedule"].as< std::string >();
        std::cout << "Input schedule filename is: " << ioScheduleInputFilename
                  << std::endl;

      } else {
        // The built-in option is not selected. However, no schedule file
        // is specified
        std::cerr << "Either one among the -b/--builtin, -i/--inventory or "
                  << " -f/--for_schedule and -s/--schedule options "
                  << "must be specified" << std::endl;
      }

      if (vm.count ("ond")) {
        ioODInputFilename = vm["ond"].as< std::string >();
        std::cout << "Input O&D filename is: " << ioODInputFilename << std::endl;
      }
    }
  }

  if (vm.count ("log")) {
    ioLogFilename = vm["log"].as< std::string >();
    std::cout << "Log filename is: " << ioLogFilename << std::endl;
  }

  return 0;
}

// ///////// M A I N ////////////
int main (int argc, char* argv[]) {

  // State whether the BOM tree should be built-in or parsed from an
  // input file
  bool isBuiltin;
  bool isForSchedule;

  // Input file names
  stdair::Filename_T lInventoryFilename;
  stdair::Filename_T lScheduleInputFilename;
  stdair::Filename_T lODInputFilename;

  // Parameters for the sale
  std::string lSegmentDateKey;
  stdair::ClassCode_T lClassCode;
  stdair::PartySize_T lPartySize;

  // Output log File
  stdair::Filename_T lLogFilename;

  // Call the command-line option parser
  const int lOptionParserStatus =
    readConfiguration (argc, argv, isBuiltin, isForSchedule, lInventoryFilename,
                       lScheduleInputFilename, lODInputFilename,
                       lSegmentDateKey, lClassCode, lPartySize, lLogFilename);

  if (lOptionParserStatus == K_AIRINV_EARLY_RETURN_STATUS) {
    return 0;
  }

  // Set the log parameters
  std::ofstream logOutputFile;
  // Open and clean the log outputfile
  logOutputFile.open (lLogFilename.c_str());
  logOutputFile.clear();

  // Initialise the inventory service
  const stdair::BasLogParams lLogParams (stdair::LOG::DEBUG, logOutputFile);

  // Check wether or not a (CSV) input file should be read
  if (isBuiltin == true) {

    // Build the BOM tree from parsing an inventory dump file
    AIRINV::AIRINV_Master_Service airinvService (lLogParams);

    // DEBUG
    STDAIR_LOG_DEBUG ("Welcome to airinv");

    // Build the sample BOM tree for RMOL
    airinvService.buildSampleBom();

    // Make a booking
    const bool isSellSuccessful =
      airinvService.sell (lSegmentDateKey, lClassCode, lPartySize);

    // DEBUG
    STDAIR_LOG_DEBUG ("Sale ('" << lSegmentDateKey << "', " << lClassCode << ": "
                      << lPartySize << ") successful? " << isSellSuccessful);

    // DEBUG: Display the whole BOM tree
    const std::string& lCSVDump = airinvService.csvDisplay();
    STDAIR_LOG_DEBUG (lCSVDump);

  } else {
    if (isForSchedule == true) {
      // Build the BOM tree from parsing a schedule file (and O&D list)
      AIRINV::AIRINV_Master_Service airinvService (lLogParams,
                                                   lScheduleInputFilename,
                                                   lODInputFilename);

      // DEBUG
      STDAIR_LOG_DEBUG ("Welcome to airinv");

      // Make a booking
      const bool isSellSuccessful =
        airinvService.sell (lSegmentDateKey, lClassCode, lPartySize);

      // DEBUG
      STDAIR_LOG_DEBUG("Sale ('" << lSegmentDateKey << "', " << lClassCode<< ": "
                       << lPartySize << ") successful? " << isSellSuccessful);

      // DEBUG: Display the whole BOM tree
      const std::string& lCSVDump = airinvService.csvDisplay();
      STDAIR_LOG_DEBUG (lCSVDump);

    } else {
      // Build the BOM tree from parsing an inventory dump file
      AIRINV::AIRINV_Master_Service airinvService (lLogParams,
                                                   lInventoryFilename);

      // DEBUG
      STDAIR_LOG_DEBUG ("Welcome to airinv");

      // Make a booking
      const bool isSellSuccessful =
        airinvService.sell (lSegmentDateKey, lClassCode, lPartySize);

      // DEBUG
      STDAIR_LOG_DEBUG("Sale ('" << lSegmentDateKey << "', " << lClassCode<< ": "
                       << lPartySize << ") successful? " << isSellSuccessful);

      // DEBUG: Display the whole BOM tree
      const std::string& lCSVDump = airinvService.csvDisplay();
      STDAIR_LOG_DEBUG (lCSVDump);
    }
  }

  // Close the Log outputFile
  logOutputFile.close();

  /*
    Note: as that program is not intended to be run on a server in
    production, it is better not to catch the exceptions. When it
    happens (that an exception is throwned), that way we get the
    call stack.
  */

  return 0;
}
<commit_msg>[AirInv][Dev] Fixed the default segment-date key for the AirInv batch.<commit_after>/*!
 * \page batch_airinv_cpp Command-Line Utility to Demonstrate Typical AirInv Usage
 * \code
 */
// STL
#include <cassert>
#include <iostream>
#include <sstream>
#include <fstream>
#include <string>
// Boost (Extended STL)
#include <boost/program_options.hpp>
#include <boost/tokenizer.hpp>
// StdAir
#include <stdair/basic/BasLogParams.hpp>
#include <stdair/basic/BasDBParams.hpp>
#include <stdair/service/Logger.hpp>
// AirInv
#include <airinv/AIRINV_Master_Service.hpp>
#include <airinv/config/airinv-paths.hpp>

// //////// Constants //////
/** Default name and location for the log file. */
const std::string K_AIRINV_DEFAULT_LOG_FILENAME ("airinv.log");

/** Default name and location for the (CSV) input files. */
const std::string K_AIRINV_DEFAULT_INVENTORY_FILENAME (STDAIR_SAMPLE_DIR
                                                       "/invdump01.csv");
/** Default name and location for the (CSV) input files. */
const std::string K_AIRINV_DEFAULT_SCHEDULE_FILENAME (STDAIR_SAMPLE_DIR
                                                      "/schedule01.csv");
/** Default name and location for the (CSV) input files. */
const std::string K_AIRINV_DEFAULT_OND_FILENAME (STDAIR_SAMPLE_DIR "/ond01.csv");

/** Default segment-date key on which the sale should be made. */
const std::string K_AIRINV_DEFAULT_SEGMENT_DATE_KEY ("SV,5,2010-03-11,KBP,JFK");

/** Default class code for which the sale should be made. */
const stdair::ClassCode_T K_AIRINV_DEFAULT_CLASS_CODE ("Y");

/** Default party size for the sale. */
const stdair::PartySize_T K_AIRINV_DEFAULT_PARTY_SIZE (2);

/** Default for the input type. It can be either built-in or provided by an
    input file. That latter must then be given with the -i option. */
const bool K_AIRINV_DEFAULT_BUILT_IN_INPUT = false;

/** Default for the input type. The BOM tree can be built from either an
    inventory dump or from a schedule file (and, potentially, an O&D list). */
const bool K_AIRINV_DEFAULT_FOR_SCHEDULE = false;

/** Early return status (so that it can be differentiated from an
    error). */
const int K_AIRINV_EARLY_RETURN_STATUS = 99;

// ///////// Parsing of Options & Configuration /////////
// A helper function to simplify the main part.
template<class T> std::ostream& operator<< (std::ostream& os,
                                            const std::vector<T>& v) {
  std::copy (v.begin(), v.end(), std::ostream_iterator<T> (std::cout, " "));
  return os;
}

/** Read and parse the command line options. */
int readConfiguration (int argc, char* argv[],
                       bool& ioIsBuiltin, bool& ioIsForSchedule,
                       stdair::Filename_T& ioInventoryFilename,
                       stdair::Filename_T& ioScheduleInputFilename,
                       stdair::Filename_T& ioODInputFilename,
                       std::string& ioSegmentDateKey,
                       stdair::ClassCode_T& ioClassCode,
                       stdair::PartySize_T& ioPartySize,
                       std::string& ioLogFilename) {
  // Default for the built-in input
  ioIsBuiltin = K_AIRINV_DEFAULT_BUILT_IN_INPUT;

  // Default for the inventory or schedule option
  ioIsForSchedule = K_AIRINV_DEFAULT_FOR_SCHEDULE;

  // Declare a group of options that will be allowed only on command line
  boost::program_options::options_description generic ("Generic options");
  generic.add_options()
    ("prefix", "print installation prefix")
    ("version,v", "print version string")
    ("help,h", "produce help message");

  // Declare a group of options that will be allowed both on command
  // line and in config file

  boost::program_options::options_description config ("Configuration");
  config.add_options()
    ("builtin,b",
     "The sample BOM tree can be either built-in or parsed from an input file. That latter must then be given with the -i/--inventory or -s/--schedule option")
    ("for_schedule,f",
     "The BOM tree should be built from a schedule file (instead of from an inventory dump)")
    ("inventory,i",
     boost::program_options::value< std::string >(&ioInventoryFilename)->default_value(K_AIRINV_DEFAULT_INVENTORY_FILENAME),
     "(CVS) input file for the inventory")
    ("schedule,s",
     boost::program_options::value< std::string >(&ioScheduleInputFilename)->default_value(K_AIRINV_DEFAULT_SCHEDULE_FILENAME),
     "(CVS) input file for the schedule")
    ("ond,o",
     boost::program_options::value< std::string >(&ioODInputFilename)->default_value(K_AIRINV_DEFAULT_OND_FILENAME),
     "(CVS) input file for the O&D")
    ("segment_date_key,k",
     boost::program_options::value< std::string >(&ioSegmentDateKey)->default_value(K_AIRINV_DEFAULT_SEGMENT_DATE_KEY),
     "Segment-date key")
    ("class_code,c",
     boost::program_options::value< stdair::ClassCode_T >(&ioClassCode)->default_value(K_AIRINV_DEFAULT_CLASS_CODE),
     "Class code")
    ("party_size,p",
     boost::program_options::value< stdair::PartySize_T >(&ioPartySize)->default_value(K_AIRINV_DEFAULT_PARTY_SIZE),
     "Party size")
    ("log,l",
     boost::program_options::value< std::string >(&ioLogFilename)->default_value(K_AIRINV_DEFAULT_LOG_FILENAME),
     "Filename for the logs")
    ;

  // Hidden options, will be allowed both on command line and
  // in config file, but will not be shown to the user.
  boost::program_options::options_description hidden ("Hidden options");
  hidden.add_options()
    ("copyright",
     boost::program_options::value< std::vector<std::string> >(),
     "Show the copyright (license)");

  boost::program_options::options_description cmdline_options;
  cmdline_options.add(generic).add(config).add(hidden);

  boost::program_options::options_description config_file_options;
  config_file_options.add(config).add(hidden);
  boost::program_options::options_description visible ("Allowed options");
  visible.add(generic).add(config);

  boost::program_options::positional_options_description p;
  p.add ("copyright", -1);

  boost::program_options::variables_map vm;
  boost::program_options::
    store (boost::program_options::command_line_parser (argc, argv).
           options (cmdline_options).positional(p).run(), vm);

  std::ifstream ifs ("airinv.cfg");
  boost::program_options::store (parse_config_file (ifs, config_file_options),
                                 vm);
  boost::program_options::notify (vm);

  if (vm.count ("help")) {
    std::cout << visible << std::endl;
    return K_AIRINV_EARLY_RETURN_STATUS;
  }

  if (vm.count ("version")) {
    std::cout << PACKAGE_NAME << ", version " << PACKAGE_VERSION << std::endl;
    return K_AIRINV_EARLY_RETURN_STATUS;
  }

  if (vm.count ("prefix")) {
    std::cout << "Installation prefix: " << PREFIXDIR << std::endl;
    return K_AIRINV_EARLY_RETURN_STATUS;
  }

  if (vm.count ("builtin")) {
    ioIsBuiltin = true;
  }
  const std::string isBuiltinStr = (ioIsBuiltin == true)?"yes":"no";
  std::cout << "The BOM should be built-in? " << isBuiltinStr << std::endl;

  if (vm.count ("for_schedule")) {
    ioIsForSchedule = true;
  }
  const std::string isForScheduleStr = (ioIsForSchedule == true)?"yes":"no";
  std::cout << "The BOM should be built from schedule? " << isForScheduleStr
            << std::endl;

  if (ioIsBuiltin == false) {

    if (ioIsForSchedule == false) {
      // The BOM tree should be built from parsing an inventory dump
      if (vm.count ("inventory")) {
        ioInventoryFilename = vm["inventory"].as< std::string >();
        std::cout << "Input inventory filename is: " << ioInventoryFilename
                  << std::endl;

      } else {
        // The built-in option is not selected. However, no inventory dump
        // file is specified
        std::cerr << "Either one among the -b/--builtin, -i/--inventory or "
                  << " -f/--for_schedule and -s/--schedule options "
                  << "must be specified" << std::endl;
      }

    } else {
      // The BOM tree should be built from parsing a schedule (and O&D) file
      if (vm.count ("schedule")) {
        ioScheduleInputFilename = vm["schedule"].as< std::string >();
        std::cout << "Input schedule filename is: " << ioScheduleInputFilename
                  << std::endl;

      } else {
        // The built-in option is not selected. However, no schedule file
        // is specified
        std::cerr << "Either one among the -b/--builtin, -i/--inventory or "
                  << " -f/--for_schedule and -s/--schedule options "
                  << "must be specified" << std::endl;
      }

      if (vm.count ("ond")) {
        ioODInputFilename = vm["ond"].as< std::string >();
        std::cout << "Input O&D filename is: " << ioODInputFilename << std::endl;
      }
    }
  }

  if (vm.count ("log")) {
    ioLogFilename = vm["log"].as< std::string >();
    std::cout << "Log filename is: " << ioLogFilename << std::endl;
  }

  return 0;
}

// ///////// M A I N ////////////
int main (int argc, char* argv[]) {

  // State whether the BOM tree should be built-in or parsed from an
  // input file
  bool isBuiltin;
  bool isForSchedule;

  // Input file names
  stdair::Filename_T lInventoryFilename;
  stdair::Filename_T lScheduleInputFilename;
  stdair::Filename_T lODInputFilename;

  // Parameters for the sale
  std::string lSegmentDateKey;
  stdair::ClassCode_T lClassCode;
  stdair::PartySize_T lPartySize;

  // Output log File
  stdair::Filename_T lLogFilename;

  // Call the command-line option parser
  const int lOptionParserStatus =
    readConfiguration (argc, argv, isBuiltin, isForSchedule, lInventoryFilename,
                       lScheduleInputFilename, lODInputFilename,
                       lSegmentDateKey, lClassCode, lPartySize, lLogFilename);

  if (lOptionParserStatus == K_AIRINV_EARLY_RETURN_STATUS) {
    return 0;
  }

  // Set the log parameters
  std::ofstream logOutputFile;
  // Open and clean the log outputfile
  logOutputFile.open (lLogFilename.c_str());
  logOutputFile.clear();

  // Initialise the inventory service
  const stdair::BasLogParams lLogParams (stdair::LOG::DEBUG, logOutputFile);

  // Check wether or not a (CSV) input file should be read
  if (isBuiltin == true) {

    // Build the BOM tree from parsing an inventory dump file
    AIRINV::AIRINV_Master_Service airinvService (lLogParams);

    // DEBUG
    STDAIR_LOG_DEBUG ("Welcome to airinv");

    // Build the sample BOM tree for RMOL
    airinvService.buildSampleBom();

    // Make a booking
    const bool isSellSuccessful =
      airinvService.sell (lSegmentDateKey, lClassCode, lPartySize);

    // DEBUG
    STDAIR_LOG_DEBUG ("Sale ('" << lSegmentDateKey << "', " << lClassCode << ": "
                      << lPartySize << ") successful? " << isSellSuccessful);

    // DEBUG: Display the whole BOM tree
    const std::string& lCSVDump = airinvService.csvDisplay();
    STDAIR_LOG_DEBUG (lCSVDump);

  } else {
    if (isForSchedule == true) {
      // Build the BOM tree from parsing a schedule file (and O&D list)
      AIRINV::AIRINV_Master_Service airinvService (lLogParams,
                                                   lScheduleInputFilename,
                                                   lODInputFilename);

      // DEBUG
      STDAIR_LOG_DEBUG ("Welcome to airinv");

      // Make a booking
      const bool isSellSuccessful =
        airinvService.sell (lSegmentDateKey, lClassCode, lPartySize);

      // DEBUG
      STDAIR_LOG_DEBUG("Sale ('" << lSegmentDateKey << "', " << lClassCode<< ": "
                       << lPartySize << ") successful? " << isSellSuccessful);

      // DEBUG: Display the whole BOM tree
      const std::string& lCSVDump = airinvService.csvDisplay();
      STDAIR_LOG_DEBUG (lCSVDump);

    } else {
      // Build the BOM tree from parsing an inventory dump file
      AIRINV::AIRINV_Master_Service airinvService (lLogParams,
                                                   lInventoryFilename);

      // DEBUG
      STDAIR_LOG_DEBUG ("Welcome to airinv");

      // Make a booking
      const bool isSellSuccessful =
        airinvService.sell (lSegmentDateKey, lClassCode, lPartySize);

      // DEBUG
      STDAIR_LOG_DEBUG("Sale ('" << lSegmentDateKey << "', " << lClassCode<< ": "
                       << lPartySize << ") successful? " << isSellSuccessful);

      // DEBUG: Display the whole BOM tree
      const std::string& lCSVDump = airinvService.csvDisplay();
      STDAIR_LOG_DEBUG (lCSVDump);
    }
  }

  // Close the Log outputFile
  logOutputFile.close();

  /*
    Note: as that program is not intended to be run on a server in
    production, it is better not to catch the exceptions. When it
    happens (that an exception is throwned), that way we get the
    call stack.
  */

  return 0;
}
<|endoftext|>