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

#include <boost/python.hpp>

#include "IECoreGL/IECoreGL.h"

#include "IECoreGL/bindings/RendererBinding.h"
#include "IECoreGL/bindings/BindableBinding.h"
#include "IECoreGL/bindings/ShaderBinding.h"
#include "IECoreGL/bindings/TextureBinding.h"
#include "IECoreGL/bindings/WindowBinding.h"
#include "IECoreGL/bindings/StateBinding.h"
#include "IECoreGL/bindings/RenderableBinding.h"
#include "IECoreGL/bindings/SceneBinding.h"
#include "IECoreGL/bindings/SceneViewerBinding.h"
#include "IECoreGL/bindings/ShaderManagerBinding.h"
#include "IECoreGL/bindings/TextureLoaderBinding.h"
#include "IECoreGL/bindings/GroupBinding.h"
#include "IECoreGL/bindings/FrameBufferBinding.h"
#include "IECoreGL/bindings/ColorTextureBinding.h"
#include "IECoreGL/bindings/DepthTextureBinding.h"
#include "IECoreGL/bindings/CameraBinding.h"
#include "IECoreGL/bindings/OrthographicCameraBinding.h"
#include "IECoreGL/bindings/PerspectiveCameraBinding.h"
#include "IECoreGL/bindings/CameraControllerBinding.h"
#include "IECoreGL/bindings/StateComponentBinding.h"
#include "IECoreGL/bindings/TypedStateComponentBinding.h"
#include "IECoreGL/bindings/NameStateComponentBinding.h"
#include "IECoreGL/bindings/HitRecordBinding.h"
#include "IECoreGL/bindings/ToGLConverterBinding.h"
#include "IECoreGL/bindings/ToGLCameraConverterBinding.h"
#include "IECoreGL/bindings/AlphaTextureBinding.h"
#include "IECoreGL/bindings/LuminanceTextureBinding.h"
#include "IECoreGL/bindings/ToGLTextureConverterBinding.h"
#include "IECoreGL/bindings/PrimitiveBinding.h"
#include "IECoreGL/bindings/PointsPrimitiveBinding.h"

using namespace IECoreGL;
using namespace boost::python;

BOOST_PYTHON_MODULE( _IECoreGL )
{
	bindRenderer();
	bindBindable();
	bindShader();
	bindTexture();
	bindWindow();
	bindState();
	bindRenderable();
	bindScene();
	bindSceneViewer();
	bindShaderManager();
	bindTextureLoader();
	bindGroup();
	bindFrameBuffer();
	bindColorTexture();
	bindDepthTexture();
	bindCamera();
	bindOrthographicCamera();
	bindPerspectiveCamera();
	bindCameraController();
	bindStateComponent();
	bindTypedStateComponents();
	bindNameStateComponent();
	bindHitRecord();
	bindToGLConverter();
	bindToGLCameraConverter();
	bindAlphaTexture();
	bindLuminanceTexture();
	bindToGLTextureConverter();
	bindPrimitive();
	bindPointsPrimitive();

	def( "init", &IECoreGL::init );
}
<commit_msg>Adding missing changes which should have been in revision 4552.<commit_after>//////////////////////////////////////////////////////////////////////////
//
//  Copyright (c) 2007-2012, Image Engine Design Inc. All rights reserved.
//
//  Redistribution and use in source and binary forms, with or without
//  modification, are permitted provided that the following conditions are
//  met:
//
//     * Redistributions of source code must retain the above copyright
//       notice, this list of conditions and the following disclaimer.
//
//     * Redistributions in binary form must reproduce the above copyright
//       notice, this list of conditions and the following disclaimer in the
//       documentation and/or other materials provided with the distribution.
//
//     * Neither the name of Image Engine Design nor the names of any
//       other contributors to this software may be used to endorse or
//       promote products derived from this software without specific prior
//       written permission.
//
//  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
//  IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
//  THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
//  PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
//  CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
//  EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
//  PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
//  PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
//  LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
//  NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
//  SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
//////////////////////////////////////////////////////////////////////////

#include <boost/python.hpp>

#include "IECoreGL/IECoreGL.h"

#include "IECoreGL/bindings/RendererBinding.h"
#include "IECoreGL/bindings/BindableBinding.h"
#include "IECoreGL/bindings/ShaderBinding.h"
#include "IECoreGL/bindings/TextureBinding.h"
#include "IECoreGL/bindings/WindowBinding.h"
#include "IECoreGL/bindings/StateBinding.h"
#include "IECoreGL/bindings/RenderableBinding.h"
#include "IECoreGL/bindings/SceneBinding.h"
#include "IECoreGL/bindings/SceneViewerBinding.h"
#include "IECoreGL/bindings/ShaderManagerBinding.h"
#include "IECoreGL/bindings/TextureLoaderBinding.h"
#include "IECoreGL/bindings/GroupBinding.h"
#include "IECoreGL/bindings/FrameBufferBinding.h"
#include "IECoreGL/bindings/ColorTextureBinding.h"
#include "IECoreGL/bindings/DepthTextureBinding.h"
#include "IECoreGL/bindings/CameraBinding.h"
#include "IECoreGL/bindings/OrthographicCameraBinding.h"
#include "IECoreGL/bindings/PerspectiveCameraBinding.h"
#include "IECoreGL/bindings/CameraControllerBinding.h"
#include "IECoreGL/bindings/StateComponentBinding.h"
#include "IECoreGL/bindings/TypedStateComponentBinding.h"
#include "IECoreGL/bindings/NameStateComponentBinding.h"
#include "IECoreGL/bindings/HitRecordBinding.h"
#include "IECoreGL/bindings/ToGLConverterBinding.h"
#include "IECoreGL/bindings/ToGLCameraConverterBinding.h"
#include "IECoreGL/bindings/AlphaTextureBinding.h"
#include "IECoreGL/bindings/LuminanceTextureBinding.h"
#include "IECoreGL/bindings/ToGLTextureConverterBinding.h"
#include "IECoreGL/bindings/PrimitiveBinding.h"
#include "IECoreGL/bindings/PointsPrimitiveBinding.h"
#include "IECoreGL/bindings/SelectorBinding.h"

using namespace IECoreGL;
using namespace boost::python;

BOOST_PYTHON_MODULE( _IECoreGL )
{
	bindRenderer();
	bindBindable();
	bindShader();
	bindTexture();
	bindWindow();
	bindState();
	bindRenderable();
	bindScene();
	bindSceneViewer();
	bindShaderManager();
	bindTextureLoader();
	bindGroup();
	bindFrameBuffer();
	bindColorTexture();
	bindDepthTexture();
	bindCamera();
	bindOrthographicCamera();
	bindPerspectiveCamera();
	bindCameraController();
	bindStateComponent();
	bindTypedStateComponents();
	bindNameStateComponent();
	bindHitRecord();
	bindToGLConverter();
	bindToGLCameraConverter();
	bindAlphaTexture();
	bindLuminanceTexture();
	bindToGLTextureConverter();
	bindPrimitive();
	bindPointsPrimitive();
	bindSelector();

	def( "init", &IECoreGL::init );
}
<|endoftext|>


<commit_before>#include <ORM/backends/Sqlite3/Sqlite3Query.hpp>
#include <ORM/backends/Sqlite3/Sqlite3Bdd.hpp>

namespace orm
{
    Sqlite3Query::Sqlite3Query(Bdd* bdd,const std::string& query) : Query(bdd,query), statement(0)
    {
        int result = sqlite3_prepare_v2(static_cast<Sqlite3Bdd*>(bdd)->dbConn,query.c_str(),query.size()+1, &statement, NULL);

        #if ORM_VERBOSITY & ORM_ERROR
        if (result != SQLITE_OK)
        {
            ORM_PRINT_ERROR("Sqlite3Query::Sqlite3Query(bdd,string&) Failed to make the statment")
            /// \todo <<sqlite3_errstr(result)<<std::endl;
        }
        #endif
    };

    Sqlite3Query::Sqlite3Query(Bdd* bdd,std::string&& query) : Query(bdd,query), statement(0)
    {
        int result = sqlite3_prepare_v2(static_cast<Sqlite3Bdd*>(bdd)->dbConn,query.c_str(),query.size()+1, &statement, NULL);

        #if ORM_VERBOSITY & ORM_ERROR
        if (result != SQLITE_OK)
        {
            ORM_PRINT_ERROR("Sqlite3Query::Sqlite3Query(bdd,string&&) Failed to make the statment")
            /// \todo <<sqlite3_errstr(result)<<std::endl;
        }
        #endif
    };

    Sqlite3Query::~Sqlite3Query()
    {
        if(statement)
        {
            int result = sqlite3_finalize(statement);

            #if ORM_VERBOSITY & ORM_ERROR
            if(result != SQLITE_OK)
            {
                ORM_PRINT_ERROR("Sqlite3Query::~Sqlite3Query() Failed to close the statement")
                /// \todo <<sqlite3_errstr(result)<<std::endl;
            }
            #endif
        }
    };

    int Sqlite3Query::count()const
    {
        return sqlite3_data_count(statement);
    };

    bool Sqlite3Query::get(bool& value,const int& column)const
    {
        value = (bool)sqlite3_column_int(statement,column);
        return true;
    };

    bool Sqlite3Query::get(int& value,const int& column)const
    {
        value = sqlite3_column_int(statement,column);
        return true;
    };

    bool Sqlite3Query::get(unsigned int& value,const int& column)const
    {
        value = (unsigned int)sqlite3_column_int(statement,column);
        return true;
    };

    bool Sqlite3Query::get(long long int& value,const int& column)const
    {
        value = (long long int)sqlite3_column_int64(statement,column);
        return true;
    };

    bool Sqlite3Query::get(long long unsigned int& value,const int& column)const
    {
        value = (unsigned long long int)sqlite3_column_int64(statement,column);

        return true;
    };

    bool Sqlite3Query::get(float& value,const int& column)const
    {
        value = (float)sqlite3_column_double(statement,column);
        return true;
    };

    bool Sqlite3Query::get(long double& value,const int& column)const
    {
        value = (long double)sqlite3_column_double(statement,column);
        return true;
    };

    bool Sqlite3Query::get(std::string& value,const int& column)const
    {
        const unsigned char* res = sqlite3_column_text(statement,column);

        if (res)
            value = (const char*)res;
        else
            value = "";

        return true;
    };

    bool Sqlite3Query::next()
    {
        int result = sqlite3_step(statement);
        if(result == SQLITE_ROW)
            return true;

        ORM_PRINT_WARNING("Sqlite3Query::next() imposible to get next row")
        ///\ todo sqlite3_errstr(result)<<std::endl;

        return false;

    }

    bool Sqlite3Query::set(const bool& value,const unsigned int& column)
    {
        if(not prepared)
            return false;
        return (sqlite3_bind_int(statement,(int)column,(int)value)== SQLITE_OK);
    };

    bool Sqlite3Query::set(const int& value,const unsigned int& column)
    {
        if(not prepared)
            return false;
        return (sqlite3_bind_int(statement,(int)column,(int)value)== SQLITE_OK);
    };

    bool Sqlite3Query::set(const unsigned int& value,const unsigned int& column)
    {
        if(not prepared)
            return false;
        return (sqlite3_bind_int(statement,(int)column,(int)value)== SQLITE_OK);
    };

    bool Sqlite3Query::set(const long long int& value,const unsigned int& column)
    {
        if(not prepared)
            return false;
        return (sqlite3_bind_int64(statement,(int)column,(sqlite3_int64)value)== SQLITE_OK);
    };

    bool Sqlite3Query::set(const long long unsigned int& value,const unsigned int& column)
    {
        if(not prepared)
            return false;
        return (sqlite3_bind_int64(statement,(int)column,(sqlite3_int64)value)== SQLITE_OK);
    };

    bool Sqlite3Query::set(const float& value,const unsigned int& column)
    {
        if(not prepared)
            return false;
        return (sqlite3_bind_double(statement,(int)column,(double)value)== SQLITE_OK);
    };

    bool Sqlite3Query::set(const long double& value,const unsigned int& column)
    {
        if(not prepared)
            return false;
        return (sqlite3_bind_double(statement,(int)column,(double)value)== SQLITE_OK);
    };

    bool Sqlite3Query::set(const std::string& value,const unsigned int& column)
    {
        if(not prepared)
            return false;
        return (sqlite3_bind_text(statement,(int)column,value.c_str(),value.size()+1,SQLITE_TRANSIENT)== SQLITE_OK);
    };

    bool Sqlite3Query::setNull(const int& value,const unsigned int& column)
    {
        if(not prepared)
            return false;
        return (sqlite3_bind_null(statement,(int)column)== SQLITE_OK);
    };

    void Sqlite3Query::executeQuery()
    {
    };

};
<commit_msg>fix bug with sqlite string<commit_after>#include <ORM/backends/Sqlite3/Sqlite3Query.hpp>
#include <ORM/backends/Sqlite3/Sqlite3Bdd.hpp>

namespace orm
{
    Sqlite3Query::Sqlite3Query(Bdd* bdd,const std::string& query) : Query(bdd,query), statement(0)
    {
        int result = sqlite3_prepare_v2(static_cast<Sqlite3Bdd*>(bdd)->dbConn,query.c_str(),query.size()+1, &statement, NULL);

        #if ORM_VERBOSITY & ORM_ERROR
        if (result != SQLITE_OK)
        {
            ORM_PRINT_ERROR("Sqlite3Query::Sqlite3Query(bdd,string&) Failed to make the statment")
            /// \todo <<sqlite3_errstr(result)<<std::endl;
        }
        #endif
    };

    Sqlite3Query::Sqlite3Query(Bdd* bdd,std::string&& query) : Query(bdd,query), statement(0)
    {
        int result = sqlite3_prepare_v2(static_cast<Sqlite3Bdd*>(bdd)->dbConn,query.c_str(),query.size()+1, &statement, NULL);

        #if ORM_VERBOSITY & ORM_ERROR
        if (result != SQLITE_OK)
        {
            ORM_PRINT_ERROR("Sqlite3Query::Sqlite3Query(bdd,string&&) Failed to make the statment")
            /// \todo <<sqlite3_errstr(result)<<std::endl;
        }
        #endif
    };

    Sqlite3Query::~Sqlite3Query()
    {
        if(statement)
        {
            int result = sqlite3_finalize(statement);

            #if ORM_VERBOSITY & ORM_ERROR
            if(result != SQLITE_OK)
            {
                ORM_PRINT_ERROR("Sqlite3Query::~Sqlite3Query() Failed to close the statement")
                /// \todo <<sqlite3_errstr(result)<<std::endl;
            }
            #endif
        }
    };

    int Sqlite3Query::count()const
    {
        return sqlite3_data_count(statement);
    };

    bool Sqlite3Query::get(bool& value,const int& column)const
    {
        value = (bool)sqlite3_column_int(statement,column);
        return true;
    };

    bool Sqlite3Query::get(int& value,const int& column)const
    {
        value = sqlite3_column_int(statement,column);
        return true;
    };

    bool Sqlite3Query::get(unsigned int& value,const int& column)const
    {
        value = (unsigned int)sqlite3_column_int(statement,column);
        return true;
    };

    bool Sqlite3Query::get(long long int& value,const int& column)const
    {
        value = (long long int)sqlite3_column_int64(statement,column);
        return true;
    };

    bool Sqlite3Query::get(long long unsigned int& value,const int& column)const
    {
        value = (unsigned long long int)sqlite3_column_int64(statement,column);

        return true;
    };

    bool Sqlite3Query::get(float& value,const int& column)const
    {
        value = (float)sqlite3_column_double(statement,column);
        return true;
    };

    bool Sqlite3Query::get(long double& value,const int& column)const
    {
        value = (long double)sqlite3_column_double(statement,column);
        return true;
    };

    bool Sqlite3Query::get(std::string& value,const int& column)const
    {
        const unsigned char* res = sqlite3_column_text(statement,column);

        if (res)
            value = (const char*)res;
        else
            value = "";

        return true;
    };

    bool Sqlite3Query::next()
    {
        int result = sqlite3_step(statement);
        if(result == SQLITE_ROW)
            return true;

        ORM_PRINT_WARNING("Sqlite3Query::next() imposible to get next row")
        ///\ todo sqlite3_errstr(result)<<std::endl;

        return false;

    }

    bool Sqlite3Query::set(const bool& value,const unsigned int& column)
    {
        if(not prepared)
            return false;
        return (sqlite3_bind_int(statement,(int)column,(int)value)== SQLITE_OK);
    };

    bool Sqlite3Query::set(const int& value,const unsigned int& column)
    {
        if(not prepared)
            return false;
        return (sqlite3_bind_int(statement,(int)column,(int)value)== SQLITE_OK);
    };

    bool Sqlite3Query::set(const unsigned int& value,const unsigned int& column)
    {
        if(not prepared)
            return false;
        return (sqlite3_bind_int(statement,(int)column,(int)value)== SQLITE_OK);
    };

    bool Sqlite3Query::set(const long long int& value,const unsigned int& column)
    {
        if(not prepared)
            return false;
        return (sqlite3_bind_int64(statement,(int)column,(sqlite3_int64)value)== SQLITE_OK);
    };

    bool Sqlite3Query::set(const long long unsigned int& value,const unsigned int& column)
    {
        if(not prepared)
            return false;
        return (sqlite3_bind_int64(statement,(int)column,(sqlite3_int64)value)== SQLITE_OK);
    };

    bool Sqlite3Query::set(const float& value,const unsigned int& column)
    {
        if(not prepared)
            return false;
        return (sqlite3_bind_double(statement,(int)column,(double)value)== SQLITE_OK);
    };

    bool Sqlite3Query::set(const long double& value,const unsigned int& column)
    {
        if(not prepared)
            return false;
        return (sqlite3_bind_double(statement,(int)column,(double)value)== SQLITE_OK);
    };

    bool Sqlite3Query::set(const std::string& value,const unsigned int& column)
    {
        if(not prepared)
            return false;
        return (sqlite3_bind_text(statement,(int)column,value.c_str(),-1,SQLITE_TRANSIENT)== SQLITE_OK);
    };

    bool Sqlite3Query::setNull(const int& value,const unsigned int& column)
    {
        if(not prepared)
            return false;
        return (sqlite3_bind_null(statement,(int)column)== SQLITE_OK);
    };

    void Sqlite3Query::executeQuery()
    {
    };

};
<|endoftext|>


<commit_before>#include "BathRoomMirrorHeatingCtrl.h"

#include <HardwareSerial.h>
#include <stdio.h>

#include "C:/eclipseArduino/sloeber/arduinoPlugin/packages/arduino/hardware/avr/1.6.18/variants/standard/pins_arduino.h"
#include "D:/HomeAutomation/ArduinoLibs/DHT/DHT.h"
#include "D:/HomeAutomation/ArduinoLibs/Timer/Timer.h"

Timer resetAnalogPinTimer;
Timer offTimer;
Timer humiditySensorReadTimer;
DHT dhtSensor(DHT_PIN, DHT22);
volatile DhtSensorData sensorData;
volatile boolean isHeatingAndLightDesired;
volatile int analogSensorReading;

bool debug = true;
bool ignoreHumiditySensor = true;

//The setup function is called once at startup of the sketch
void setup() {
	Serial.begin(115200);
	Serial.println("Setup starts here...");

	isHeatingAndLightDesired = false;
	sensorData.temperature = 25;
	sensorData.humidity = 55;

	pinMode(INPUT_PIN_IR_TRIGGER, INPUT);
	analogReadInputPin();
	resetAnalogPinTimer.every(RESET_ANALOG_SENSOR_READING, resetReadingAndUpdateDecision);

	pinMode(LIGHTS_PIN, OUTPUT);
	setRelay(LIGHTS_PIN, OFF);

	pinMode(HEAT_PIN, OUTPUT);
	setRelay(HEAT_PIN, OFF);

	dhtSensor.begin();
	readDhtInfo();
	humiditySensorReadTimer.every(DHT_TIMER_EVERY, readDhtInfo);
	Serial.println("Setup ends here...");
}

// The loop function is called in an endless loop
void loop() {
	offTimer.update();
	humiditySensorReadTimer.update();
	resetAnalogPinTimer.update();
	decisionMaker();
	analogReadInputPin();
}

void resetReadingAndUpdateDecision() {
	if(analogSensorReading > ANALOG_TRESHOLD) {
		isHeatingAndLightDesired = !isHeatingAndLightDesired;
	}
	Serial.print("AnalogSensor last value:");
	Serial.println(analogSensorReading);
	analogSensorReading = 0;
	Serial.print("AnalogSensor new value:");
	Serial.println(analogSensorReading);
}

void offTimerExpired() {
	isHeatingAndLightDesired = false;;
}

void reattachInterrupt() {
	if(debug) {
		Serial.println("ReattachInterrupt triggered");
	}
	attachInterrupt(digitalPinToInterrupt(INPUT_PIN_IR_TRIGGER), userInputDetected, RISING);
	resetAnalogPinTimer.stop(millis());
}

void readDhtInfo() {
	float humidity = dhtSensor.readHumidity();
	float temperature = dhtSensor.readTemperature();

	// simple error check. Do not update data if sensor reading is wrong.
	if(humidity > 0 && temperature > -30) {
		sensorData.humidity = humidity;
		sensorData.temperature = temperature;
		ignoreHumiditySensor = false;
	} else  {
		ignoreHumiditySensor = true;
		if(debug) {
			Serial.println("DHT wrong data received...");
			Serial.print("Humidity:"); Serial.println(humidity);
			Serial.print("Temperature:"); Serial.println(temperature);
		}
	}
	if(debug) {
//		sensorData.humidity = random(100);
//		sensorData.temperature = random(30);
		Serial.print("Humidity:");Serial.println(sensorData.humidity);
		Serial.print("Temperature:");Serial.println(sensorData.temperature);
		return;
	}
}

void decisionMaker() {
	if(isHeatingAndLightDesired) {
		if(!lightIsOn()) {
			setRelay(LIGHTS_PIN, ON);
		}
		if((sensorData.humidity > HUMIDITY_TRESHOLD || ignoreHumiditySensor) && !heatingIsOn()) {
			setRelay(HEAT_PIN, ON);
		}
	} else {
		if(lightIsOn()) {
			setRelay(LIGHTS_PIN, OFF);
		}
		if(heatingIsOn()) {
			setRelay(HEAT_PIN, OFF);
		}
	}
}

void setRelay(byte pin, byte state) {
	digitalWrite(pin, state);
	if (debug) {
		Serial.print("Pin ");Serial.print(pin);Serial.print(" state changed to ");Serial.println(state);
	}
}

boolean lightIsOn() {
	return digitalRead(LIGHTS_PIN);
}

boolean heatingIsOn() {
	return digitalRead(HEAT_PIN);
}

void analogReadInputPin() {
	int sensorReading = analogRead(INPUT_PIN_IR_TRIGGER);
	if(sensorReading > 100 && sensorReading > analogSensorReading) {
		analogSensorReading = sensorReading;
	}
}
<commit_msg>Added off-timer 15 mins<commit_after>#include "BathRoomMirrorHeatingCtrl.h"

#include <HardwareSerial.h>
#include <stdio.h>

#include "C:/eclipseArduino/sloeber/arduinoPlugin/packages/arduino/hardware/avr/1.6.18/variants/standard/pins_arduino.h"
#include "D:/HomeAutomation/ArduinoLibs/DHT/DHT.h"
#include "D:/HomeAutomation/ArduinoLibs/Timer/Timer.h"

Timer resetAnalogPinTimer;
Timer offTimer;
Timer humiditySensorReadTimer;
DHT dhtSensor(DHT_PIN, DHT22);
volatile DhtSensorData sensorData;
volatile boolean isHeatingAndLightDesired;
volatile int analogSensorReading;

bool debug = true;
bool ignoreHumiditySensor = true;

//The setup function is called once at startup of the sketch
void setup() {
	Serial.begin(115200);
	Serial.println("Setup starts here...");

	isHeatingAndLightDesired = false;
	sensorData.temperature = 25;
	sensorData.humidity = 55;

	pinMode(INPUT_PIN_IR_TRIGGER, INPUT);
	analogReadInputPin();
	resetAnalogPinTimer.every(RESET_ANALOG_SENSOR_READING, resetReadingAndUpdateDecision);

	pinMode(LIGHTS_PIN, OUTPUT);
	setRelay(LIGHTS_PIN, OFF);

	pinMode(HEAT_PIN, OUTPUT);
	setRelay(HEAT_PIN, OFF);

	dhtSensor.begin();
	readDhtInfo();
	humiditySensorReadTimer.every(DHT_TIMER_EVERY, readDhtInfo);
	Serial.println("Setup ends here...");
}

// The loop function is called in an endless loop
void loop() {
	offTimer.update();
	humiditySensorReadTimer.update();
	resetAnalogPinTimer.update();
	decisionMaker();
	analogReadInputPin();
}

void resetReadingAndUpdateDecision() {
	if(analogSensorReading > ANALOG_TRESHOLD) {
		isHeatingAndLightDesired = !isHeatingAndLightDesired;
		if(isHeatingAndLightDesired) {
			offTimer.after(OFF_TIME_TIMER_OFFSET, offTimerExpired);
		} else {
			offTimer.stop(0);
		}
	}

	if(debug) {
		Serial.print("AnalogSensor last value:");
		Serial.println(analogSensorReading);
	}

	analogSensorReading = 0;
}

void offTimerExpired() {
	isHeatingAndLightDesired = false;;
}

void reattachInterrupt() {
	if(debug) {
		Serial.println("ReattachInterrupt triggered");
	}
	attachInterrupt(digitalPinToInterrupt(INPUT_PIN_IR_TRIGGER), userInputDetected, RISING);
	resetAnalogPinTimer.stop(millis());
}

void readDhtInfo() {
	float humidity = dhtSensor.readHumidity();
	float temperature = dhtSensor.readTemperature();

	// simple error check. Do not update data if sensor reading is wrong.
	if(humidity > 0 && temperature > -30) {
		sensorData.humidity = humidity;
		sensorData.temperature = temperature;
		ignoreHumiditySensor = false;
	} else  {
		ignoreHumiditySensor = true;
		if(debug) {
			Serial.println("DHT wrong data received...");
			Serial.print("Humidity:"); Serial.println(humidity);
			Serial.print("Temperature:"); Serial.println(temperature);
		}
	}
	if(debug) {
//		sensorData.humidity = random(100);
//		sensorData.temperature = random(30);
		Serial.print("Humidity:");Serial.println(sensorData.humidity);
		Serial.print("Temperature:");Serial.println(sensorData.temperature);
		return;
	}
}

void decisionMaker() {
	if(isHeatingAndLightDesired) {
		if(!lightIsOn()) {
			setRelay(LIGHTS_PIN, ON);
		}
		if((sensorData.humidity > HUMIDITY_TRESHOLD || ignoreHumiditySensor) && !heatingIsOn()) {
			setRelay(HEAT_PIN, ON);
		}
	} else {
		if(lightIsOn()) {
			setRelay(LIGHTS_PIN, OFF);
		}
		if(heatingIsOn()) {
			setRelay(HEAT_PIN, OFF);
		}
	}
}

void setRelay(byte pin, byte state) {
	digitalWrite(pin, state);
	if (debug) {
		Serial.print("Pin ");Serial.print(pin);Serial.print(" state changed to ");Serial.println(state);
	}
}

boolean lightIsOn() {
	return digitalRead(LIGHTS_PIN);
}

boolean heatingIsOn() {
	return digitalRead(HEAT_PIN);
}

void analogReadInputPin() {
	int sensorReading = analogRead(INPUT_PIN_IR_TRIGGER);
	if(sensorReading > 100 && sensorReading > analogSensorReading) {
		analogSensorReading = sensorReading;
	}
}
<|endoftext|>


<commit_before>/****************************************************************************
Copyright (c) 2016 Yuji Toki(tokineco)
- MIT license
****************************************************************************/

#pragma execution_character_set("utf-8")

#include "Converter.h"

USING_NS_CC;

// "0xARGB"の文字列からアルファ付きのColor4Bを返す
cocos2d::Color4B Converter::fromARGB(std::string code) {

    // 0xARGBコードが見つかったら
    if (code.find("0x") == 0 && code.length() == 10) {

        try {
            // A
            int a = (int)strtol(code.substr(2, 2).c_str(), nullptr, 16);
            // R
            int r = (int)strtol(code.substr(4, 2).c_str(), nullptr, 16);
            // G
            int g = (int)strtol(code.substr(6, 2).c_str(), nullptr, 16);
            // B
            int b = (int)strtol(code.substr(8, 2).c_str(), nullptr, 16);

            return cocos2d::Color4B(r, g, b, a);

        } catch (...) {
            // Error
            CCLOG("illegal color code : %s", code.c_str());
        }
    } else {
        // Error
        CCLOG("not supeert format : %s", code.c_str());
    }

    return cocos2d::Color4B::BLACK;
}

// 文字列の "true" or "false" を bool型の true or false に変換する
// "1"もtrueとして扱う
bool Converter::stringToBool(std::string strBool, bool def) {

    if (strBool == "true" || strBool == "1") {
        return true;
    } else if (strBool == "false" || strBool == "0") {
        return false;
    }

    return def;
}

bool Converter::stringToBool(std::string strBool) {
    return stringToBool(strBool, false);
}

// 文字列のSplit
std::vector<std::string> Converter::split(std::string str, char delim) {

    std::vector<std::string> result;
    std::string::size_type current = 0, delimIdx;

    while ((delimIdx = str.find_first_of(delim, current)) != std::string::npos) {
        result.push_back(std::string(str, current, delimIdx - current));
        current = delimIdx + 1;
    }
    result.push_back(std::string(str, current, str.size() - current));

    return result;
}

// 文字列の全置換
std::string Converter::replaceAll(std::string str, std::string before, std::string after) {

    std::string::size_type pos(str.find(before));

    while (pos != std::string::npos) {
        str.replace(pos, before.length(), after);
        pos = str.find(before, pos + after.length());
    }

    return str;
}

// 文字列の先頭と末尾にあるホワイトスペースを取り除く
std::string Converter::trim(const std::string& str, const char* trimChars /* = " \t\v\r\n" */) {

    std::string result;
    std::string::size_type left = str.find_first_not_of(trimChars);

    if (left != std::string::npos) {
        std::string::size_type right = str.find_last_not_of(trimChars);
        result = str.substr(left, right - left + 1);
    }

    return result;
}
<commit_msg>Fixed error message typo<commit_after>/****************************************************************************
Copyright (c) 2016 Yuji Toki(tokineco)
- MIT license
****************************************************************************/

#pragma execution_character_set("utf-8")

#include "Converter.h"

USING_NS_CC;

// "0xARGB"の文字列からアルファ付きのColor4Bを返す
cocos2d::Color4B Converter::fromARGB(std::string code) {

    // 0xARGBコードが見つかったら
    if (code.find("0x") == 0 && code.length() == 10) {

        try {
            // A
            int a = (int)strtol(code.substr(2, 2).c_str(), nullptr, 16);
            // R
            int r = (int)strtol(code.substr(4, 2).c_str(), nullptr, 16);
            // G
            int g = (int)strtol(code.substr(6, 2).c_str(), nullptr, 16);
            // B
            int b = (int)strtol(code.substr(8, 2).c_str(), nullptr, 16);

            return cocos2d::Color4B(r, g, b, a);

        } catch (...) {
            // Error
            CCLOG("illegal color code : %s", code.c_str());
        }
    } else {
        // Error
        CCLOG("not support format : %s", code.c_str());
    }

    return cocos2d::Color4B::BLACK;
}

// 文字列の "true" or "false" を bool型の true or false に変換する
// "1"もtrueとして扱う
bool Converter::stringToBool(std::string strBool, bool def) {

    if (strBool == "true" || strBool == "1") {
        return true;
    } else if (strBool == "false" || strBool == "0") {
        return false;
    }

    return def;
}

bool Converter::stringToBool(std::string strBool) {
    return stringToBool(strBool, false);
}

// 文字列のSplit
std::vector<std::string> Converter::split(std::string str, char delim) {

    std::vector<std::string> result;
    std::string::size_type current = 0, delimIdx;

    while ((delimIdx = str.find_first_of(delim, current)) != std::string::npos) {
        result.push_back(std::string(str, current, delimIdx - current));
        current = delimIdx + 1;
    }
    result.push_back(std::string(str, current, str.size() - current));

    return result;
}

// 文字列の全置換
std::string Converter::replaceAll(std::string str, std::string before, std::string after) {

    std::string::size_type pos(str.find(before));

    while (pos != std::string::npos) {
        str.replace(pos, before.length(), after);
        pos = str.find(before, pos + after.length());
    }

    return str;
}

// 文字列の先頭と末尾にあるホワイトスペースを取り除く
std::string Converter::trim(const std::string& str, const char* trimChars /* = " \t\v\r\n" */) {

    std::string result;
    std::string::size_type left = str.find_first_not_of(trimChars);

    if (left != std::string::npos) {
        std::string::size_type right = str.find_last_not_of(trimChars);
        result = str.substr(left, right - left + 1);
    }

    return result;
}
<|endoftext|>


<commit_before>void Draw(string s_Exo, string s_Run)
{
gStyle->SetOptStat(0);

string s_TFile_Cyclus = s_Exo + "/" + s_Run + "/cyclus.root";
string s_TFile_Class = s_Exo + "/" + s_Run + "/Scenario.root";

cout<<s_TFile_Cyclus<<endl;
cout<<s_TFile_Class<<endl;

TFile *FCy = new TFile(s_TFile_Cyclus.c_str());
TFile *FCl = new TFile(s_TFile_Class.c_str());

TTree *TCy = (TTree *) FCy->Get("TT");
TTree *TCl = (TTree *) FCl->Get("TreeScenario");

TCy->SetLineColor(kRed); TCy->SetMarkerColor(kRed); TCy->SetLineWidth(3);
TCl->SetLineColor(kBlue); TCl->SetMarkerColor(kBlue); TCl->SetLineWidth(3);

// ################################################################################
// Legend
// ################################################################################

    TLegend *L01 = new TLegend(0.75,0.10,0.90,0.25);
    L01->AddEntry(TCy, "Cyclus", "L");
    L01->AddEntry(TCl, "CLASS", "L");

// ################################################################################
// ENERGY
// ################################################################################

    TCanvas *C00 = new TCanvas("C00","C00",700,500);
    TCy->Draw("P:T","","L");
    TCl->Draw("P:T","","Lsame");
    TH1F *tmp0 = (TH1F*)gPad->GetPrimitive("htemp"); tmp0->SetTitle("Thermal Power");
    tmp0->GetXaxis()->SetTitle("Time (y)");          tmp0->GetXaxis()->CenterTitle();    tmp0->GetXaxis()->SetTitleOffset(0.8);  tmp0->GetXaxis()->SetTitleSize(0.05);
    tmp0->GetYaxis()->SetTitle("Power (W)");         tmp0->GetYaxis()->CenterTitle();    tmp0->GetYaxis()->SetTitleOffset(0.8);  tmp0->GetYaxis()->SetTitleSize(0.05);
    gPad->Update();
    L01->Draw();

// ################################################################################
// Plutonium
// ################################################################################

    TCanvas *C0 = new TCanvas("C0","Pu",1400,900);
    C0->Divide(2,2,0.01,0.01);

    C0->cd(1);
    TCy->Draw("B93/1000:T","","L");
    TCl->Draw("B93:T","","Lsame");
    tmp0 = (TH1F*)gPad->GetPrimitive("htemp"); tmp0->SetTitle("Total Pu");
    tmp0->GetXaxis()->SetTitle("Time (y)");    tmp0->GetXaxis()->CenterTitle();    tmp0->GetXaxis()->SetTitleOffset(0.8);  tmp0->GetXaxis()->SetTitleSize(0.05);
    tmp0->GetYaxis()->SetTitle("Mass (tons)"); tmp0->GetYaxis()->CenterTitle();    tmp0->GetYaxis()->SetTitleOffset(0.8);  tmp0->GetYaxis()->SetTitleSize(0.05);
    gPad->Update();
    L01->Draw();

    C0->cd(2);
    TCy->Draw("B3/1000:T","","L");
    TCl->Draw("B3:T","","Lsame");
    tmp0 = (TH1F*)gPad->GetPrimitive("htemp"); tmp0->SetTitle("Pu in Stock");
    tmp0->GetXaxis()->SetTitle("Time (y)");    tmp0->GetXaxis()->CenterTitle();    tmp0->GetXaxis()->SetTitleOffset(0.8);  tmp0->GetXaxis()->SetTitleSize(0.05);
    tmp0->GetYaxis()->SetTitle("Mass (tons)"); tmp0->GetYaxis()->CenterTitle();    tmp0->GetYaxis()->SetTitleOffset(0.8);  tmp0->GetYaxis()->SetTitleSize(0.05);
    gPad->Update();
    L01->Draw();

    C0->cd(3);
    TCy->Draw("B98/1000:T","","L");
    TCl->Draw("B98:T","","Lsame");
    tmp0 = (TH1F*)gPad->GetPrimitive("htemp"); tmp0->SetTitle("Total Pu9");
    tmp0->GetXaxis()->SetTitle("Time (y)");    tmp0->GetXaxis()->CenterTitle();    tmp0->GetXaxis()->SetTitleOffset(0.8);  tmp0->GetXaxis()->SetTitleSize(0.05);
    tmp0->GetYaxis()->SetTitle("Mass (tons)"); tmp0->GetYaxis()->CenterTitle();    tmp0->GetYaxis()->SetTitleOffset(0.8);  tmp0->GetYaxis()->SetTitleSize(0.05);
    gPad->Update();
    L01->Draw();

    C0->cd(4);
    TCy->Draw("B8/1000:T","","L");
    TCl->Draw("B8:T","","Lsame");
    tmp0 = (TH1F*)gPad->GetPrimitive("htemp"); tmp0->SetTitle("Pu9 in Stock");
    tmp0->GetXaxis()->SetTitle("Time (y)");    tmp0->GetXaxis()->CenterTitle();    tmp0->GetXaxis()->SetTitleOffset(0.8);  tmp0->GetXaxis()->SetTitleSize(0.05);
    tmp0->GetYaxis()->SetTitle("Mass (tons)"); tmp0->GetYaxis()->CenterTitle();    tmp0->GetYaxis()->SetTitleOffset(0.8);  tmp0->GetYaxis()->SetTitleSize(0.05);
    gPad->Update();
    L01->Draw();

// ################################################################################
// MA
// ################################################################################

    TCanvas *C1 = new TCanvas("C1","MA",1400,900);
    C1->Divide(2,2,0.01,0.01);

    C1->cd(1);
    TCy->Draw("B96/1000:T","","L");
    TCl->Draw("B96:T","","Lsame");
    tmp0 = (TH1F*)gPad->GetPrimitive("htemp"); tmp0->SetTitle("Total MA");
    tmp0->GetXaxis()->SetTitle("Time (y)");    tmp0->GetXaxis()->CenterTitle();    tmp0->GetXaxis()->SetTitleOffset(0.8);  tmp0->GetXaxis()->SetTitleSize(0.05);
    tmp0->GetYaxis()->SetTitle("Mass (tons)"); tmp0->GetYaxis()->CenterTitle();    tmp0->GetYaxis()->SetTitleOffset(0.8);  tmp0->GetYaxis()->SetTitleSize(0.05);
    gPad->Update();
    L01->Draw();

    C1->cd(2);
    TCy->Draw("B94/1000:T","","L");
    TCl->Draw("B94:T","","Lsame");
    tmp0 = (TH1F*)gPad->GetPrimitive("htemp"); tmp0->SetTitle("Total Am");
    tmp0->GetXaxis()->SetTitle("Time (y)");    tmp0->GetXaxis()->CenterTitle();    tmp0->GetXaxis()->SetTitleOffset(0.8);  tmp0->GetXaxis()->SetTitleSize(0.05);
    tmp0->GetYaxis()->SetTitle("Mass (tons)"); tmp0->GetYaxis()->CenterTitle();    tmp0->GetYaxis()->SetTitleOffset(0.8);  tmp0->GetYaxis()->SetTitleSize(0.05);
    gPad->Update();
    L01->Draw();

    C1->cd(3);
    TCy->Draw("B92/1000:T","","L");
    TCl->Draw("B92:T","","Lsame");
    tmp0 = (TH1F*)gPad->GetPrimitive("htemp"); tmp0->SetTitle("Total Np");
    tmp0->GetXaxis()->SetTitle("Time (y)");    tmp0->GetXaxis()->CenterTitle();    tmp0->GetXaxis()->SetTitleOffset(0.8);  tmp0->GetXaxis()->SetTitleSize(0.05);
    tmp0->GetYaxis()->SetTitle("Mass (tons)"); tmp0->GetYaxis()->CenterTitle();    tmp0->GetYaxis()->SetTitleOffset(0.8);  tmp0->GetYaxis()->SetTitleSize(0.05);
    gPad->Update();
    L01->Draw();

    C1->cd(4);
    TCy->Draw("B95/1000:T","","L");
    TCl->Draw("B95:T","","Lsame");
    tmp0 = (TH1F*)gPad->GetPrimitive("htemp"); tmp0->SetTitle("Total Cm");
    tmp0->GetXaxis()->SetTitle("Time (y)");    tmp0->GetXaxis()->CenterTitle();    tmp0->GetXaxis()->SetTitleOffset(0.8);  tmp0->GetXaxis()->SetTitleSize(0.05);
    tmp0->GetYaxis()->SetTitle("Mass (tons)"); tmp0->GetYaxis()->CenterTitle();    tmp0->GetYaxis()->SetTitleOffset(0.8);  tmp0->GetYaxis()->SetTitleSize(0.05);
    gPad->Update();
    L01->Draw();
}
<commit_msg>Update general Draw script<commit_after>void Draw(string s_Exo, string s_Run)
{
gStyle->SetOptStat(0);

string s_TFile_Cyclus = s_Exo + "/" + s_Run + "/cyclus.root";
string s_TFile_Class = s_Exo + "/" + s_Run + "/Scenario.root";

cout<<s_TFile_Cyclus<<endl;
cout<<s_TFile_Class<<endl;

TFile *FCy = new TFile(s_TFile_Cyclus.c_str());
TFile *FCl = new TFile(s_TFile_Class.c_str());

TTree *TCy = (TTree *) FCy->Get("TT");
TTree *TCl = (TTree *) FCl->Get("TreeScenario");

TCy->SetLineColor(kRed); TCy->SetMarkerColor(kRed); TCy->SetLineWidth(3);
TCl->SetLineColor(kBlue); TCl->SetMarkerColor(kBlue); TCl->SetLineWidth(3);

// ################################################################################
// Legend
// ################################################################################

    TLegend *L01 = new TLegend(0.75,0.10,0.90,0.25);
    L01->AddEntry(TCy, "Cyclus", "L");
    L01->AddEntry(TCl, "CLASS", "L");

// ################################################################################
// ENERGY
// ################################################################################

    TCanvas *C00 = new TCanvas("C00","C00",700,500);
    TCy->Draw("P:T","","L");
    TCl->Draw("P:T","","Lsame");
    TH1F *tmp0 = (TH1F*)gPad->GetPrimitive("htemp"); tmp0->SetTitle("Thermal Power");
    tmp0->GetXaxis()->SetTitle("Time (y)");          tmp0->GetXaxis()->CenterTitle();    tmp0->GetXaxis()->SetTitleOffset(0.8);  tmp0->GetXaxis()->SetTitleSize(0.05);
    tmp0->GetYaxis()->SetTitle("Power (W)");         tmp0->GetYaxis()->CenterTitle();    tmp0->GetYaxis()->SetTitleOffset(0.8);  tmp0->GetYaxis()->SetTitleSize(0.05);
    gPad->Update();
    L01->Draw();

// ################################################################################
// Plutonium
// ################################################################################

    TCanvas *C0 = new TCanvas("C0","Pu",1500,900);
    C0->Divide(2,2,0.01,0.01);

    C0->cd(1);
    TCy->Draw("B93/1000:T","","L");
    TCl->Draw("B93:T","","Lsame");
    tmp0 = (TH1F*)gPad->GetPrimitive("htemp"); tmp0->SetTitle("Total Pu");
    tmp0->GetXaxis()->SetTitle("Time (y)");    tmp0->GetXaxis()->CenterTitle();    tmp0->GetXaxis()->SetTitleOffset(0.8);  tmp0->GetXaxis()->SetTitleSize(0.05);
    tmp0->GetYaxis()->SetTitle("Mass (tons)"); tmp0->GetYaxis()->CenterTitle();    tmp0->GetYaxis()->SetTitleOffset(0.8);  tmp0->GetYaxis()->SetTitleSize(0.05);
    gPad->Update();
    L01->Draw();

    C0->cd(2);
    TCy->Draw("B3/1000:T","","L");
    TCl->Draw("B3:T","","Lsame");
    tmp0 = (TH1F*)gPad->GetPrimitive("htemp"); tmp0->SetTitle("Pu in Stock");
    tmp0->GetXaxis()->SetTitle("Time (y)");    tmp0->GetXaxis()->CenterTitle();    tmp0->GetXaxis()->SetTitleOffset(0.8);  tmp0->GetXaxis()->SetTitleSize(0.05);
    tmp0->GetYaxis()->SetTitle("Mass (tons)"); tmp0->GetYaxis()->CenterTitle();    tmp0->GetYaxis()->SetTitleOffset(0.8);  tmp0->GetYaxis()->SetTitleSize(0.05);
    gPad->Update();
    L01->Draw();

    C0->cd(3);
    TCy->Draw("B98/1000:T","","L");
    TCl->Draw("B98:T","","Lsame");
    tmp0 = (TH1F*)gPad->GetPrimitive("htemp"); tmp0->SetTitle("Total Pu9");
    tmp0->GetXaxis()->SetTitle("Time (y)");    tmp0->GetXaxis()->CenterTitle();    tmp0->GetXaxis()->SetTitleOffset(0.8);  tmp0->GetXaxis()->SetTitleSize(0.05);
    tmp0->GetYaxis()->SetTitle("Mass (tons)"); tmp0->GetYaxis()->CenterTitle();    tmp0->GetYaxis()->SetTitleOffset(0.8);  tmp0->GetYaxis()->SetTitleSize(0.05);
    gPad->Update();
    L01->Draw();

    C0->cd(4);
    TCy->Draw("B8/1000:T","","L");
    TCl->Draw("B8:T","","Lsame");
    tmp0 = (TH1F*)gPad->GetPrimitive("htemp"); tmp0->SetTitle("Pu9 in Stock");
    tmp0->GetXaxis()->SetTitle("Time (y)");    tmp0->GetXaxis()->CenterTitle();    tmp0->GetXaxis()->SetTitleOffset(0.8);  tmp0->GetXaxis()->SetTitleSize(0.05);
    tmp0->GetYaxis()->SetTitle("Mass (tons)"); tmp0->GetYaxis()->CenterTitle();    tmp0->GetYaxis()->SetTitleOffset(0.8);  tmp0->GetYaxis()->SetTitleSize(0.05);
    gPad->Update();
    L01->Draw();

// ################################################################################
// MA
// ################################################################################

    TCanvas *C1 = new TCanvas("C1","MA",1500,900);
    C1->Divide(2,2,0.01,0.01);

    C1->cd(1);
    TCy->Draw("B96/1000:T","","L");
    TCl->Draw("B96:T","","Lsame");
    tmp0 = (TH1F*)gPad->GetPrimitive("htemp"); tmp0->SetTitle("Total MA");
    tmp0->GetXaxis()->SetTitle("Time (y)");    tmp0->GetXaxis()->CenterTitle();    tmp0->GetXaxis()->SetTitleOffset(0.8);  tmp0->GetXaxis()->SetTitleSize(0.05);
    tmp0->GetYaxis()->SetTitle("Mass (tons)"); tmp0->GetYaxis()->CenterTitle();    tmp0->GetYaxis()->SetTitleOffset(0.8);  tmp0->GetYaxis()->SetTitleSize(0.05);
    gPad->Update();
    L01->Draw();

    C1->cd(2);
    TCy->Draw("B94/1000:T","","L");
    TCl->Draw("B94:T","","Lsame");
    tmp0 = (TH1F*)gPad->GetPrimitive("htemp"); tmp0->SetTitle("Total Am");
    tmp0->GetXaxis()->SetTitle("Time (y)");    tmp0->GetXaxis()->CenterTitle();    tmp0->GetXaxis()->SetTitleOffset(0.8);  tmp0->GetXaxis()->SetTitleSize(0.05);
    tmp0->GetYaxis()->SetTitle("Mass (tons)"); tmp0->GetYaxis()->CenterTitle();    tmp0->GetYaxis()->SetTitleOffset(0.8);  tmp0->GetYaxis()->SetTitleSize(0.05);
    gPad->Update();
    L01->Draw();

    C1->cd(3);
    TCy->Draw("B92/1000:T","","L");
    TCl->Draw("B92:T","","Lsame");
    tmp0 = (TH1F*)gPad->GetPrimitive("htemp"); tmp0->SetTitle("Total Np");
    tmp0->GetXaxis()->SetTitle("Time (y)");    tmp0->GetXaxis()->CenterTitle();    tmp0->GetXaxis()->SetTitleOffset(0.8);  tmp0->GetXaxis()->SetTitleSize(0.05);
    tmp0->GetYaxis()->SetTitle("Mass (tons)"); tmp0->GetYaxis()->CenterTitle();    tmp0->GetYaxis()->SetTitleOffset(0.8);  tmp0->GetYaxis()->SetTitleSize(0.05);
    gPad->Update();
    L01->Draw();

    C1->cd(4);
    TCy->Draw("B95/1000:T","","L");
    TCl->Draw("B95:T","","Lsame");
    tmp0 = (TH1F*)gPad->GetPrimitive("htemp"); tmp0->SetTitle("Total Cm");
    tmp0->GetXaxis()->SetTitle("Time (y)");    tmp0->GetXaxis()->CenterTitle();    tmp0->GetXaxis()->SetTitleOffset(0.8);  tmp0->GetXaxis()->SetTitleSize(0.05);
    tmp0->GetYaxis()->SetTitle("Mass (tons)"); tmp0->GetYaxis()->CenterTitle();    tmp0->GetYaxis()->SetTitleOffset(0.8);  tmp0->GetYaxis()->SetTitleSize(0.05);
    gPad->Update();
    L01->Draw();
}
<|endoftext|>


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

The Medical Imaging Interaction Toolkit (MITK)

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

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

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

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

#include "mitkNavigationToolStorage.h"

//Microservices
#include <usGetModuleContext.h>
#include <usModule.h>
#include <usModuleContext.h>

const std::string  mitk::NavigationToolStorage::US_INTERFACE_NAME = "org.mitk.services.NavigationToolStorage"; // Name of the interface
const std::string  mitk::NavigationToolStorage::US_PROPKEY_SOURCE_ID = US_INTERFACE_NAME + ".sourceID";
const std::string  mitk::NavigationToolStorage::US_PROPKEY_STORAGE_NAME = US_INTERFACE_NAME + ".name";

mitk::NavigationToolStorage::NavigationToolStorage()
  : m_ToolCollection(std::vector<mitk::NavigationTool::Pointer>()),
    m_DataStorage(NULL),
    m_storageLocked(false)
  {
  this->SetName("ToolStorage (no name given)");
  }

mitk::NavigationToolStorage::NavigationToolStorage(mitk::DataStorage::Pointer ds)
  : m_storageLocked(false)
  {
  m_ToolCollection = std::vector<mitk::NavigationTool::Pointer>();
  this->m_DataStorage = ds;
  this->SetName("Tool Storage (no name given)");
  }

void mitk::NavigationToolStorage::SetName(std::string n)
  {
  m_Name = n;
  m_props[ US_PROPKEY_STORAGE_NAME ] = m_Name;
  }

std::string mitk::NavigationToolStorage::GetName() const
{
  return m_Name;
}

 void mitk::NavigationToolStorage::UpdateMicroservice()
  {
  if (m_ServiceRegistration) {m_ServiceRegistration.SetProperties(m_props);}
  }

mitk::NavigationToolStorage::~NavigationToolStorage()
  {
  if (m_DataStorage.IsNotNull()) //remove all nodes from the data storage
    {
    for(std::vector<mitk::NavigationTool::Pointer>::iterator it = m_ToolCollection.begin(); it != m_ToolCollection.end(); it++)
        m_DataStorage->Remove((*it)->GetDataNode());
    }
  }

void mitk::NavigationToolStorage::RegisterAsMicroservice(std::string sourceID){

  if ( sourceID.empty() ) mitkThrow() << "Empty or null string passed to NavigationToolStorage::registerAsMicroservice().";

  // Get Context
  us::ModuleContext* context = us::GetModuleContext();

  // Define ServiceProps
  m_props[ US_PROPKEY_SOURCE_ID ] = sourceID;
  m_ServiceRegistration = context->RegisterService(this, m_props);
}

void mitk::NavigationToolStorage::UnRegisterMicroservice(){
  if ( ! m_ServiceRegistration )
  {
    MITK_WARN("NavigationToolStorage")
        << "Cannot unregister microservice as it wasn't registered before.";
    return;
  }

  m_ServiceRegistration.Unregister();
  m_ServiceRegistration = 0;
}

bool mitk::NavigationToolStorage::DeleteTool(int number)
  {
    if (m_storageLocked)
    {
      MITK_WARN << "Storage is locked, cannot modify it!";
      return false;
    }

    else if ((unsigned int)number > m_ToolCollection.size())
    {
      MITK_WARN << "Tool no " << number << "doesn't exist, can't delete it!";
      return false;
    }
    std::vector<mitk::NavigationTool::Pointer>::iterator it = m_ToolCollection.begin() + number;
    if(m_DataStorage.IsNotNull())
      m_DataStorage->Remove((*it)->GetDataNode());
    m_ToolCollection.erase(it);

    return true;
  }

bool mitk::NavigationToolStorage::DeleteAllTools()
  {
   if (m_storageLocked)
    {
    MITK_WARN << "Storage is locked, cannot modify it!";
    return false;
    }

  while(m_ToolCollection.size() > 0) if (!DeleteTool(0)) return false;
  return true;
  }

bool mitk::NavigationToolStorage::AddTool(mitk::NavigationTool::Pointer tool)
  {
  if (m_storageLocked)
    {
    MITK_WARN << "Storage is locked, cannot modify it!";
    return false;
    }
  else if (GetTool(tool->GetIdentifier()).IsNotNull())
    {
    MITK_WARN << "Tool ID already exists in storage, can't add!";
    return false;
    }
  else
    {
    m_ToolCollection.push_back(tool);
    if(m_DataStorage.IsNotNull())
      {
      if (!m_DataStorage->Exists(tool->GetDataNode()))
        m_DataStorage->Add(tool->GetDataNode());
      }
    return true;
    }
  }

mitk::NavigationTool::Pointer mitk::NavigationToolStorage::GetTool(int number)
  {
  return m_ToolCollection.at(number);
  }

mitk::NavigationTool::Pointer mitk::NavigationToolStorage::GetTool(std::string identifier)
  {
  for (int i=0; i<GetToolCount(); i++) if ((GetTool(i)->GetIdentifier())==identifier) return GetTool(i);
  return NULL;
  }

mitk::NavigationTool::Pointer mitk::NavigationToolStorage::GetToolByName(std::string name)
  {
  for (int i=0; i<GetToolCount(); i++) if ((GetTool(i)->GetToolName())==name) return GetTool(i);
  return NULL;
  }

int mitk::NavigationToolStorage::GetToolCount()
  {
  return m_ToolCollection.size();
  }

bool mitk::NavigationToolStorage::isEmpty()
  {
  return m_ToolCollection.empty();
  }

void mitk::NavigationToolStorage::LockStorage()
  {
  m_storageLocked = true;
  }

void mitk::NavigationToolStorage::UnLockStorage()
  {
  m_storageLocked = false;
  }

bool mitk::NavigationToolStorage::isLocked()
  {
  return m_storageLocked;
  }

bool mitk::NavigationToolStorage::AssignToolNumber(std::string identifier1, int number2)
  {
  if (this->GetTool(identifier1).IsNull())
    {
    MITK_WARN << "Identifier does not exist, cannot assign new number";
    return false;
    }

  if ((number2 >= m_ToolCollection.size()) || (number2 < 0))
    {
    MITK_WARN << "Invalid number, cannot assign new number";
    return false;
    }

  mitk::NavigationTool::Pointer tool2 = m_ToolCollection.at(number2);

  int number1 = -1;

  for(int i = 0; i<m_ToolCollection.size(); i++)
    {
    if (m_ToolCollection.at(i)->GetIdentifier() == identifier1) {number1=i;}
    }

  m_ToolCollection[number2] = m_ToolCollection.at(number1);

  m_ToolCollection[number1] = tool2;

  MITK_DEBUG << "Swapped tool " << number2 << " with tool " << number1;

  return true;
}
<commit_msg>Code format for better reading. White space changes only.<commit_after>/*===================================================================

The Medical Imaging Interaction Toolkit (MITK)

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

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

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

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

#include "mitkNavigationToolStorage.h"

//Microservices
#include <usGetModuleContext.h>
#include <usModule.h>
#include <usModuleContext.h>

const std::string  mitk::NavigationToolStorage::US_INTERFACE_NAME = "org.mitk.services.NavigationToolStorage"; // Name of the interface
const std::string  mitk::NavigationToolStorage::US_PROPKEY_SOURCE_ID = US_INTERFACE_NAME + ".sourceID";
const std::string  mitk::NavigationToolStorage::US_PROPKEY_STORAGE_NAME = US_INTERFACE_NAME + ".name";

mitk::NavigationToolStorage::NavigationToolStorage()
  : m_ToolCollection(std::vector<mitk::NavigationTool::Pointer>()),
  m_DataStorage(NULL),
  m_storageLocked(false)
{
  this->SetName("ToolStorage (no name given)");
}

mitk::NavigationToolStorage::NavigationToolStorage(mitk::DataStorage::Pointer ds)
  : m_storageLocked(false)
{
  m_ToolCollection = std::vector<mitk::NavigationTool::Pointer>();
  this->m_DataStorage = ds;
  this->SetName("Tool Storage (no name given)");
}

void mitk::NavigationToolStorage::SetName(std::string n)
{
  m_Name = n;
  m_props[US_PROPKEY_STORAGE_NAME] = m_Name;
}

std::string mitk::NavigationToolStorage::GetName() const
{
  return m_Name;
}

void mitk::NavigationToolStorage::UpdateMicroservice()
{
  if (m_ServiceRegistration) { m_ServiceRegistration.SetProperties(m_props); }
}

mitk::NavigationToolStorage::~NavigationToolStorage()
{
  if (m_DataStorage.IsNotNull()) //remove all nodes from the data storage
  {
    for (std::vector<mitk::NavigationTool::Pointer>::iterator it = m_ToolCollection.begin(); it != m_ToolCollection.end(); it++)
      m_DataStorage->Remove((*it)->GetDataNode());
  }
}

void mitk::NavigationToolStorage::RegisterAsMicroservice(std::string sourceID){
  if (sourceID.empty()) mitkThrow() << "Empty or null string passed to NavigationToolStorage::registerAsMicroservice().";

  // Get Context
  us::ModuleContext* context = us::GetModuleContext();

  // Define ServiceProps
  m_props[US_PROPKEY_SOURCE_ID] = sourceID;
  m_ServiceRegistration = context->RegisterService(this, m_props);
}

void mitk::NavigationToolStorage::UnRegisterMicroservice(){
  if (!m_ServiceRegistration)
  {
    MITK_WARN("NavigationToolStorage")
      << "Cannot unregister microservice as it wasn't registered before.";
    return;
  }

  m_ServiceRegistration.Unregister();
  m_ServiceRegistration = 0;
}

bool mitk::NavigationToolStorage::DeleteTool(int number)
{
  if (m_storageLocked)
  {
    MITK_WARN << "Storage is locked, cannot modify it!";
    return false;
  }

  else if ((unsigned int)number > m_ToolCollection.size())
  {
    MITK_WARN << "Tool no " << number << "doesn't exist, can't delete it!";
    return false;
  }
  std::vector<mitk::NavigationTool::Pointer>::iterator it = m_ToolCollection.begin() + number;
  if (m_DataStorage.IsNotNull())
    m_DataStorage->Remove((*it)->GetDataNode());
  m_ToolCollection.erase(it);

  return true;
}

bool mitk::NavigationToolStorage::DeleteAllTools()
{
  if (m_storageLocked)
  {
    MITK_WARN << "Storage is locked, cannot modify it!";
    return false;
  }

  while (m_ToolCollection.size() > 0) if (!DeleteTool(0)) return false;
  return true;
}

bool mitk::NavigationToolStorage::AddTool(mitk::NavigationTool::Pointer tool)
{
  if (m_storageLocked)
  {
    MITK_WARN << "Storage is locked, cannot modify it!";
    return false;
  }
  else if (GetTool(tool->GetIdentifier()).IsNotNull())
  {
    MITK_WARN << "Tool ID already exists in storage, can't add!";
    return false;
  }
  else
  {
    m_ToolCollection.push_back(tool);
    if (m_DataStorage.IsNotNull())
    {
      if (!m_DataStorage->Exists(tool->GetDataNode()))
        m_DataStorage->Add(tool->GetDataNode());
    }
    return true;
  }
}

mitk::NavigationTool::Pointer mitk::NavigationToolStorage::GetTool(int number)
{
  return m_ToolCollection.at(number);
}

mitk::NavigationTool::Pointer mitk::NavigationToolStorage::GetTool(std::string identifier)
{
  for (int i = 0; i < GetToolCount(); i++) if ((GetTool(i)->GetIdentifier()) == identifier) return GetTool(i);
  return NULL;
}

mitk::NavigationTool::Pointer mitk::NavigationToolStorage::GetToolByName(std::string name)
{
  for (int i = 0; i < GetToolCount(); i++) if ((GetTool(i)->GetToolName()) == name) return GetTool(i);
  return NULL;
}

int mitk::NavigationToolStorage::GetToolCount()
{
  return m_ToolCollection.size();
}

bool mitk::NavigationToolStorage::isEmpty()
{
  return m_ToolCollection.empty();
}

void mitk::NavigationToolStorage::LockStorage()
{
  m_storageLocked = true;
}

void mitk::NavigationToolStorage::UnLockStorage()
{
  m_storageLocked = false;
}

bool mitk::NavigationToolStorage::isLocked()
{
  return m_storageLocked;
}

bool mitk::NavigationToolStorage::AssignToolNumber(std::string identifier1, int number2)
{
  if (this->GetTool(identifier1).IsNull())
  {
    MITK_WARN << "Identifier does not exist, cannot assign new number";
    return false;
  }

  if ((number2 >= m_ToolCollection.size()) || (number2 < 0))
  {
    MITK_WARN << "Invalid number, cannot assign new number";
    return false;
  }

  mitk::NavigationTool::Pointer tool2 = m_ToolCollection.at(number2);

  int number1 = -1;

  for (int i = 0; i < m_ToolCollection.size(); i++)
  {
    if (m_ToolCollection.at(i)->GetIdentifier() == identifier1) { number1 = i; }
  }

  m_ToolCollection[number2] = m_ToolCollection.at(number1);

  m_ToolCollection[number1] = tool2;

  MITK_DEBUG << "Swapped tool " << number2 << " with tool " << number1;

  return true;
}<|endoftext|>


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

The Medical Imaging Interaction Toolkit (MITK)

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

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

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

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

//Poco headers
#include "Poco/Zip/Decompress.h"
#include "Poco/Path.h"
#include "Poco/File.h"

#include "mitkNavigationToolStorageDeserializer.h"
#include <mitkSceneIO.h>
#include <mitkIOUtil.h>
#include "mitkNavigationToolReader.h"

//POCO
#include <Poco/Exception.h>

#include "mitkIGTException.h"
#include "mitkIGTIOException.h"

mitk::NavigationToolStorageDeserializer::NavigationToolStorageDeserializer(mitk::DataStorage::Pointer dataStorage)
  {
  m_DataStorage = dataStorage;
  //create temp directory for this reader
  m_tempDirectory = mitk::IOUtil::CreateTemporaryDirectory("NavigationToolStorageDeserializerTmp_XXXXXX",mitk::IOUtil::GetTempPath());
  }

mitk::NavigationToolStorageDeserializer::~NavigationToolStorageDeserializer()
  {
  //remove temp directory
  Poco::File myFile(m_tempDirectory);
  try
    {
    if (myFile.exists()) myFile.remove();
    }
  catch(...)
    {
    MITK_ERROR << "Can't remove temp directory " << m_tempDirectory << "!";
    }
  }

mitk::NavigationToolStorage::Pointer mitk::NavigationToolStorageDeserializer::Deserialize(std::string filename)
  {
  //decomress zip file into temporary directory
  decomressFiles(filename,m_tempDirectory);

  //now read all files and convert them to navigation tools
  mitk::NavigationToolStorage::Pointer returnValue = mitk::NavigationToolStorage::New(m_DataStorage);
  bool cont = true;
  int i;
  for (i=0; cont==true; i++)
    {
    std::string fileName = m_tempDirectory + Poco::Path::separator() + "NavigationTool" + convertIntToString(i) + ".tool";
    mitk::NavigationToolReader::Pointer myReader = mitk::NavigationToolReader::New();
    mitk::NavigationTool::Pointer readTool = myReader->DoRead(fileName);
    if (readTool.IsNull()) cont = false;
    else returnValue->AddTool(readTool);
    //delete file
    std::remove(fileName.c_str());
    }
  if(i==1)
    {
    //throw an exception here in case of not finding any tool
    m_ErrorMessage = "Error: did not find any tool. \n Is this a tool storage file?";
    mitkThrowException(mitk::IGTException)<<"Error: did not find any tool. \n Is this a tool storage file?";
    }
  return returnValue;
  }

std::string mitk::NavigationToolStorageDeserializer::convertIntToString(int i)
{
std::string s;
std::stringstream out;
out << i;
s = out.str();
return s;
}

void mitk::NavigationToolStorageDeserializer::decomressFiles(std::string filename,std::string path)
{
  std::ifstream file( filename.c_str(), std::ios::binary );
  if (!file.good())
    {
    m_ErrorMessage = "Cannot open '" + filename + "' for reading";
    mitkThrowException(mitk::IGTException)<<"Cannot open"+filename+" for reading";
    }

  try
    {
    Poco::Zip::Decompress unzipper( file, Poco::Path( path ) );
    unzipper.decompressAllFiles();
    file.close();
    }

  catch(Poco::IllegalStateException e) //temporary solution: replace this by defined exception handling later!
    {
    m_ErrorMessage = "Error: wrong file format! \n (please only load tool storage files)";
    MITK_ERROR << m_ErrorMessage;
    mitkThrowException(mitk::IGTException) << m_ErrorMessage;
    }

  }
<commit_msg>Remove logging of error message<commit_after>/*===================================================================

The Medical Imaging Interaction Toolkit (MITK)

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

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

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

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

//Poco headers
#include "Poco/Zip/Decompress.h"
#include "Poco/Path.h"
#include "Poco/File.h"

#include "mitkNavigationToolStorageDeserializer.h"
#include <mitkSceneIO.h>
#include <mitkIOUtil.h>
#include "mitkNavigationToolReader.h"

//POCO
#include <Poco/Exception.h>

#include "mitkIGTException.h"
#include "mitkIGTIOException.h"

mitk::NavigationToolStorageDeserializer::NavigationToolStorageDeserializer(mitk::DataStorage::Pointer dataStorage)
  {
  m_DataStorage = dataStorage;
  //create temp directory for this reader
  m_tempDirectory = mitk::IOUtil::CreateTemporaryDirectory("NavigationToolStorageDeserializerTmp_XXXXXX",mitk::IOUtil::GetTempPath());
  }

mitk::NavigationToolStorageDeserializer::~NavigationToolStorageDeserializer()
  {
  //remove temp directory
  Poco::File myFile(m_tempDirectory);
  try
    {
    if (myFile.exists()) myFile.remove();
    }
  catch(...)
    {
    MITK_ERROR << "Can't remove temp directory " << m_tempDirectory << "!";
    }
  }

mitk::NavigationToolStorage::Pointer mitk::NavigationToolStorageDeserializer::Deserialize(std::string filename)
  {
  //decomress zip file into temporary directory
  decomressFiles(filename,m_tempDirectory);

  //now read all files and convert them to navigation tools
  mitk::NavigationToolStorage::Pointer returnValue = mitk::NavigationToolStorage::New(m_DataStorage);
  bool cont = true;
  int i;
  for (i=0; cont==true; i++)
    {
    std::string fileName = m_tempDirectory + Poco::Path::separator() + "NavigationTool" + convertIntToString(i) + ".tool";
    mitk::NavigationToolReader::Pointer myReader = mitk::NavigationToolReader::New();
    mitk::NavigationTool::Pointer readTool = myReader->DoRead(fileName);
    if (readTool.IsNull()) cont = false;
    else returnValue->AddTool(readTool);
    //delete file
    std::remove(fileName.c_str());
    }
  if(i==1)
    {
    //throw an exception here in case of not finding any tool
    m_ErrorMessage = "Error: did not find any tool. \n Is this a tool storage file?";
    mitkThrowException(mitk::IGTException)<<"Error: did not find any tool. \n Is this a tool storage file?";
    }
  return returnValue;
  }

std::string mitk::NavigationToolStorageDeserializer::convertIntToString(int i)
{
std::string s;
std::stringstream out;
out << i;
s = out.str();
return s;
}

void mitk::NavigationToolStorageDeserializer::decomressFiles(std::string filename,std::string path)
{
  std::ifstream file( filename.c_str(), std::ios::binary );
  if (!file.good())
    {
    m_ErrorMessage = "Cannot open '" + filename + "' for reading";
    mitkThrowException(mitk::IGTException)<<"Cannot open"+filename+" for reading";
    }

  try
    {
    Poco::Zip::Decompress unzipper( file, Poco::Path( path ) );
    unzipper.decompressAllFiles();
    file.close();
    }

  catch(Poco::IllegalStateException e) //temporary solution: replace this by defined exception handling later!
    {
    m_ErrorMessage = "Error: wrong file format! \n (please only load tool storage files)";
    mitkThrowException(mitk::IGTException) << m_ErrorMessage;
    }

  }
<|endoftext|>


<commit_before>/*
Open Asset Import Library (assimp)
----------------------------------------------------------------------

Copyright (c) 2006-2016, assimp team
All rights reserved.

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

* Redistributions of source code must retain the above
  copyright notice, this list of conditions and the
  following disclaimer.

* Redistributions in binary form must reproduce the above
  copyright notice, this list of conditions and the
  following disclaimer in the documentation and/or other
  materials provided with the distribution.

* Neither the name of the assimp team, nor the names of its
  contributors may be used to endorse or promote products
  derived from this software without specific prior
  written permission of the assimp team.

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

----------------------------------------------------------------------
*/

#include "D3MFImporter.h"

#include <assimp/scene.h>
#include <assimp/IOStream.hpp>
#include <assimp/IOSystem.hpp>
#include <assimp/DefaultLogger.hpp>
#include <contrib/unzip/unzip.h>
#include "irrXMLWrapper.h"
#include "StringComparison.h"
#include "StringUtils.h"

#include <string>
#include <sstream>
#include <vector>
#include <map>
#include <algorithm>
#include <cassert>
#include <cstdlib>
#include <memory>

#include <assimp/ai_assert.h>

#include "D3MFOpcPackage.h"

#ifndef ASSIMP_BUILD_NO_3MF_IMPORTER

namespace Assimp {

namespace D3MF {

namespace XmlTag {

    const std::string model     = "model";
    const std::string metadata  = "metadata";
    const std::string resources = "resources";
    const std::string object    = "object";
    const std::string mesh      = "mesh";
    const std::string vertices  = "vertices";
    const std::string vertex    = "vertex";
    const std::string triangles = "triangles";
    const std::string triangle  = "triangle";
    const std::string x         = "x";
    const std::string y         = "y";
    const std::string z         = "z";
    const std::string v1        = "v1";
    const std::string v2        = "v2";
    const std::string v3        = "v3";
    const std::string id        = "id";
    const std::string name      = "name";
    const std::string type      = "type";
    const std::string build     = "build";
    const std::string item      = "item";
    const std::string objectid  = "objectid";
    const std::string transform = "transform";

}

class XmlSerializer
{
public:
    XmlSerializer(XmlReader* xmlReader)
        : xmlReader(xmlReader)
    {

    }

    void ImportXml(aiScene* scene)
    {

        scene->mFlags |= AI_SCENE_FLAGS_NON_VERBOSE_FORMAT;

        scene->mRootNode = new aiNode();
        std::vector<aiNode*> children;

        while(ReadToEndElement(D3MF::XmlTag::model))
        {

            if(xmlReader->getNodeName() == D3MF::XmlTag::object)
            {
                children.push_back(ReadObject(scene));
            }
            else if(xmlReader->getNodeName() == D3MF::XmlTag::build)
            {

            }
        }

        if(scene->mRootNode->mName.length == 0)
            scene->mRootNode->mName.Set("3MF");

        scene->mNumMeshes = static_cast<unsigned int>(meshes.size());
        scene->mMeshes = new aiMesh*[scene->mNumMeshes]();

        std::copy(meshes.begin(), meshes.end(), scene->mMeshes);

        scene->mRootNode->mNumChildren = static_cast<unsigned int>(children.size());
        scene->mRootNode->mChildren = new aiNode*[scene->mRootNode->mNumChildren]();

        std::copy(children.begin(), children.end(), scene->mRootNode->mChildren);

    }

private:
    aiNode* ReadObject(aiScene* scene)
    {
        ScopeGuard<aiNode> node(new aiNode());

        std::vector<unsigned long> meshIds;

        int id = std::atoi(xmlReader->getAttributeValue(D3MF::XmlTag::id.c_str()));
        std::string name(xmlReader->getAttributeValue(D3MF::XmlTag::name.c_str()));
        std::string type(xmlReader->getAttributeValue(D3MF::XmlTag::type.c_str()));

        node->mParent = scene->mRootNode;
        node->mName.Set(name);

        unsigned long meshIdx = meshes.size();

        while(ReadToEndElement(D3MF::XmlTag::object))
        {
            if(xmlReader->getNodeName() == D3MF::XmlTag::mesh)
            {
                auto mesh = ReadMesh();

                mesh->mName.Set(name);
                meshes.push_back(mesh);
                meshIds.push_back(meshIdx);
                meshIdx++;

            }
        }

        node->mNumMeshes = static_cast<unsigned int>(meshIds.size());

        node->mMeshes = new unsigned int[node->mNumMeshes];

        std::copy(meshIds.begin(), meshIds.end(), node->mMeshes);

        return node.dismiss();

    }

    aiMesh* ReadMesh()
    {
        aiMesh* mesh = new aiMesh();

        while(ReadToEndElement(D3MF::XmlTag::mesh))
        {
            if(xmlReader->getNodeName() == D3MF::XmlTag::vertices)
            {
                ImportVertices(mesh);
            }
            else if(xmlReader->getNodeName() == D3MF::XmlTag::triangles)
            {
                ImportTriangles(mesh);
            }

        }

        return mesh;
    }

    void ImportVertices(aiMesh* mesh)
    {
        std::vector<aiVector3D> vertices;

        while(ReadToEndElement(D3MF::XmlTag::vertices))
        {
            if(xmlReader->getNodeName() == D3MF::XmlTag::vertex)
            {
                vertices.push_back(ReadVertex());
            }
        }
        mesh->mNumVertices = static_cast<unsigned int>(vertices.size());
        mesh->mVertices = new aiVector3D[mesh->mNumVertices];

        std::copy(vertices.begin(), vertices.end(), mesh->mVertices);

    }
    aiVector3D ReadVertex()
    {
        aiVector3D vertex;
        vertex.x = ai_strtof(xmlReader->getAttributeValue(D3MF::XmlTag::x.c_str()), nullptr);
        vertex.y = ai_strtof(xmlReader->getAttributeValue(D3MF::XmlTag::y.c_str()), nullptr);
        vertex.z = ai_strtof>(xmlReader->getAttributeValue(D3MF::XmlTag::z.c_str()), nullptr);

        return vertex;
    }

    void ImportTriangles(aiMesh* mesh)
    {
         std::vector<aiFace> faces;

         while(ReadToEndElement(D3MF::XmlTag::triangles))
         {
             if(xmlReader->getNodeName() == D3MF::XmlTag::triangle)
             {
                 faces.push_back(ReadTriangle());
             }
         }

        mesh->mNumFaces = static_cast<unsigned int>(faces.size());
        mesh->mFaces = new aiFace[mesh->mNumFaces];
        mesh->mPrimitiveTypes = aiPrimitiveType_TRIANGLE;

        std::copy(faces.begin(), faces.end(), mesh->mFaces);

    }

    aiFace ReadTriangle()
    {
        aiFace face;

        face.mNumIndices = 3;
        face.mIndices = new unsigned int[face.mNumIndices];
        face.mIndices[0] = static_cast<unsigned int>(std::atoi(xmlReader->getAttributeValue(D3MF::XmlTag::v1.c_str())));
        face.mIndices[1] = static_cast<unsigned int>(std::atoi(xmlReader->getAttributeValue(D3MF::XmlTag::v2.c_str())));
        face.mIndices[2] = static_cast<unsigned int>(std::atoi(xmlReader->getAttributeValue(D3MF::XmlTag::v3.c_str())));

        return face;
    }

private:

    bool ReadToStartElement(const std::string& startTag)
    {
        while(xmlReader->read())
        {
            if (xmlReader->getNodeType() == irr::io::EXN_ELEMENT && xmlReader->getNodeName() == startTag)
            {
                return true;
            }
            else if (xmlReader->getNodeType() == irr::io::EXN_ELEMENT_END &&
                     xmlReader->getNodeName() == startTag)
            {
                return false;
            }
        }
        //DefaultLogger::get()->error("unexpected EOF, expected closing <" + closeTag + "> tag");
        return false;
    }

    bool ReadToEndElement(const std::string& closeTag)
    {
        while(xmlReader->read())
        {
            if (xmlReader->getNodeType() == irr::io::EXN_ELEMENT) {
                return true;
            }
            else if (xmlReader->getNodeType() == irr::io::EXN_ELEMENT_END
                     && xmlReader->getNodeName() == closeTag)
            {
                return false;
            }
        }
        DefaultLogger::get()->error("unexpected EOF, expected closing <" + closeTag + "> tag");
        return false;
    }

private:
    std::vector<aiMesh*> meshes;
    XmlReader* xmlReader;

};

} //namespace D3MF

static const aiImporterDesc desc = {
    "3mf Importer",
    "",
    "",
    "http://3mf.io/",
    aiImporterFlags_SupportBinaryFlavour | aiImporterFlags_SupportCompressedFlavour,
    0,
    0,
    0,
    0,
    "3mf"
};

D3MFImporter::D3MFImporter()
{

}

D3MFImporter::~D3MFImporter()
{

}

bool D3MFImporter::CanRead(const std::string &pFile, IOSystem *pIOHandler, bool checkSig) const
{
    const std::string extension = GetExtension(pFile);

    if(extension == "3mf")
    {
        return true;
    }
    else if(!extension.length() || checkSig)
    {
        if(!pIOHandler)
            return true;
    }

    return false;
}

void D3MFImporter::SetupProperties(const Importer *pImp)
{

}

const aiImporterDesc *D3MFImporter::GetInfo() const
{
    return &desc;
}

void D3MFImporter::InternReadFile(const std::string &pFile, aiScene *pScene, IOSystem *pIOHandler)
{

    D3MF::D3MFOpcPackage opcPackage(pIOHandler, pFile);

    std::unique_ptr<CIrrXML_IOStreamReader> xmlStream(new CIrrXML_IOStreamReader(opcPackage.RootStream()));
    std::unique_ptr<D3MF::XmlReader> xmlReader(irr::io::createIrrXMLReader(xmlStream.get()));

    D3MF::XmlSerializer xmlSerializer(xmlReader.get());

    xmlSerializer.ImportXml(pScene);

}

}

#endif // ASSIMP_BUILD_NO_3MF_IMPORTER
<commit_msg>Fixed type in the assimp codebase (this is already fixed in more recent releases of assimp)<commit_after>/*
Open Asset Import Library (assimp)
----------------------------------------------------------------------

Copyright (c) 2006-2016, assimp team
All rights reserved.

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

* Redistributions of source code must retain the above
  copyright notice, this list of conditions and the
  following disclaimer.

* Redistributions in binary form must reproduce the above
  copyright notice, this list of conditions and the
  following disclaimer in the documentation and/or other
  materials provided with the distribution.

* Neither the name of the assimp team, nor the names of its
  contributors may be used to endorse or promote products
  derived from this software without specific prior
  written permission of the assimp team.

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

----------------------------------------------------------------------
*/

#include "D3MFImporter.h"

#include <assimp/scene.h>
#include <assimp/IOStream.hpp>
#include <assimp/IOSystem.hpp>
#include <assimp/DefaultLogger.hpp>
#include <contrib/unzip/unzip.h>
#include "irrXMLWrapper.h"
#include "StringComparison.h"
#include "StringUtils.h"

#include <string>
#include <sstream>
#include <vector>
#include <map>
#include <algorithm>
#include <cassert>
#include <cstdlib>
#include <memory>

#include <assimp/ai_assert.h>

#include "D3MFOpcPackage.h"

#ifndef ASSIMP_BUILD_NO_3MF_IMPORTER

namespace Assimp {

namespace D3MF {

namespace XmlTag {

    const std::string model     = "model";
    const std::string metadata  = "metadata";
    const std::string resources = "resources";
    const std::string object    = "object";
    const std::string mesh      = "mesh";
    const std::string vertices  = "vertices";
    const std::string vertex    = "vertex";
    const std::string triangles = "triangles";
    const std::string triangle  = "triangle";
    const std::string x         = "x";
    const std::string y         = "y";
    const std::string z         = "z";
    const std::string v1        = "v1";
    const std::string v2        = "v2";
    const std::string v3        = "v3";
    const std::string id        = "id";
    const std::string name      = "name";
    const std::string type      = "type";
    const std::string build     = "build";
    const std::string item      = "item";
    const std::string objectid  = "objectid";
    const std::string transform = "transform";

}

class XmlSerializer
{
public:
    XmlSerializer(XmlReader* xmlReader)
        : xmlReader(xmlReader)
    {

    }

    void ImportXml(aiScene* scene)
    {

        scene->mFlags |= AI_SCENE_FLAGS_NON_VERBOSE_FORMAT;

        scene->mRootNode = new aiNode();
        std::vector<aiNode*> children;

        while(ReadToEndElement(D3MF::XmlTag::model))
        {

            if(xmlReader->getNodeName() == D3MF::XmlTag::object)
            {
                children.push_back(ReadObject(scene));
            }
            else if(xmlReader->getNodeName() == D3MF::XmlTag::build)
            {

            }
        }

        if(scene->mRootNode->mName.length == 0)
            scene->mRootNode->mName.Set("3MF");

        scene->mNumMeshes = static_cast<unsigned int>(meshes.size());
        scene->mMeshes = new aiMesh*[scene->mNumMeshes]();

        std::copy(meshes.begin(), meshes.end(), scene->mMeshes);

        scene->mRootNode->mNumChildren = static_cast<unsigned int>(children.size());
        scene->mRootNode->mChildren = new aiNode*[scene->mRootNode->mNumChildren]();

        std::copy(children.begin(), children.end(), scene->mRootNode->mChildren);

    }

private:
    aiNode* ReadObject(aiScene* scene)
    {
        ScopeGuard<aiNode> node(new aiNode());

        std::vector<unsigned long> meshIds;

        int id = std::atoi(xmlReader->getAttributeValue(D3MF::XmlTag::id.c_str()));
        std::string name(xmlReader->getAttributeValue(D3MF::XmlTag::name.c_str()));
        std::string type(xmlReader->getAttributeValue(D3MF::XmlTag::type.c_str()));

        node->mParent = scene->mRootNode;
        node->mName.Set(name);

        unsigned long meshIdx = meshes.size();

        while(ReadToEndElement(D3MF::XmlTag::object))
        {
            if(xmlReader->getNodeName() == D3MF::XmlTag::mesh)
            {
                auto mesh = ReadMesh();

                mesh->mName.Set(name);
                meshes.push_back(mesh);
                meshIds.push_back(meshIdx);
                meshIdx++;

            }
        }

        node->mNumMeshes = static_cast<unsigned int>(meshIds.size());

        node->mMeshes = new unsigned int[node->mNumMeshes];

        std::copy(meshIds.begin(), meshIds.end(), node->mMeshes);

        return node.dismiss();

    }

    aiMesh* ReadMesh()
    {
        aiMesh* mesh = new aiMesh();

        while(ReadToEndElement(D3MF::XmlTag::mesh))
        {
            if(xmlReader->getNodeName() == D3MF::XmlTag::vertices)
            {
                ImportVertices(mesh);
            }
            else if(xmlReader->getNodeName() == D3MF::XmlTag::triangles)
            {
                ImportTriangles(mesh);
            }

        }

        return mesh;
    }

    void ImportVertices(aiMesh* mesh)
    {
        std::vector<aiVector3D> vertices;

        while(ReadToEndElement(D3MF::XmlTag::vertices))
        {
            if(xmlReader->getNodeName() == D3MF::XmlTag::vertex)
            {
                vertices.push_back(ReadVertex());
            }
        }
        mesh->mNumVertices = static_cast<unsigned int>(vertices.size());
        mesh->mVertices = new aiVector3D[mesh->mNumVertices];

        std::copy(vertices.begin(), vertices.end(), mesh->mVertices);

    }
    aiVector3D ReadVertex()
    {
        aiVector3D vertex;
        vertex.x = ai_strtof(xmlReader->getAttributeValue(D3MF::XmlTag::x.c_str()), nullptr);
        vertex.y = ai_strtof(xmlReader->getAttributeValue(D3MF::XmlTag::y.c_str()), nullptr);
        vertex.z = ai_strtof(xmlReader->getAttributeValue(D3MF::XmlTag::z.c_str()), nullptr);

        return vertex;
    }

    void ImportTriangles(aiMesh* mesh)
    {
         std::vector<aiFace> faces;

         while(ReadToEndElement(D3MF::XmlTag::triangles))
         {
             if(xmlReader->getNodeName() == D3MF::XmlTag::triangle)
             {
                 faces.push_back(ReadTriangle());
             }
         }

        mesh->mNumFaces = static_cast<unsigned int>(faces.size());
        mesh->mFaces = new aiFace[mesh->mNumFaces];
        mesh->mPrimitiveTypes = aiPrimitiveType_TRIANGLE;

        std::copy(faces.begin(), faces.end(), mesh->mFaces);

    }

    aiFace ReadTriangle()
    {
        aiFace face;

        face.mNumIndices = 3;
        face.mIndices = new unsigned int[face.mNumIndices];
        face.mIndices[0] = static_cast<unsigned int>(std::atoi(xmlReader->getAttributeValue(D3MF::XmlTag::v1.c_str())));
        face.mIndices[1] = static_cast<unsigned int>(std::atoi(xmlReader->getAttributeValue(D3MF::XmlTag::v2.c_str())));
        face.mIndices[2] = static_cast<unsigned int>(std::atoi(xmlReader->getAttributeValue(D3MF::XmlTag::v3.c_str())));

        return face;
    }

private:

    bool ReadToStartElement(const std::string& startTag)
    {
        while(xmlReader->read())
        {
            if (xmlReader->getNodeType() == irr::io::EXN_ELEMENT && xmlReader->getNodeName() == startTag)
            {
                return true;
            }
            else if (xmlReader->getNodeType() == irr::io::EXN_ELEMENT_END &&
                     xmlReader->getNodeName() == startTag)
            {
                return false;
            }
        }
        //DefaultLogger::get()->error("unexpected EOF, expected closing <" + closeTag + "> tag");
        return false;
    }

    bool ReadToEndElement(const std::string& closeTag)
    {
        while(xmlReader->read())
        {
            if (xmlReader->getNodeType() == irr::io::EXN_ELEMENT) {
                return true;
            }
            else if (xmlReader->getNodeType() == irr::io::EXN_ELEMENT_END
                     && xmlReader->getNodeName() == closeTag)
            {
                return false;
            }
        }
        DefaultLogger::get()->error("unexpected EOF, expected closing <" + closeTag + "> tag");
        return false;
    }

private:
    std::vector<aiMesh*> meshes;
    XmlReader* xmlReader;

};

} //namespace D3MF

static const aiImporterDesc desc = {
    "3mf Importer",
    "",
    "",
    "http://3mf.io/",
    aiImporterFlags_SupportBinaryFlavour | aiImporterFlags_SupportCompressedFlavour,
    0,
    0,
    0,
    0,
    "3mf"
};

D3MFImporter::D3MFImporter()
{

}

D3MFImporter::~D3MFImporter()
{

}

bool D3MFImporter::CanRead(const std::string &pFile, IOSystem *pIOHandler, bool checkSig) const
{
    const std::string extension = GetExtension(pFile);

    if(extension == "3mf")
    {
        return true;
    }
    else if(!extension.length() || checkSig)
    {
        if(!pIOHandler)
            return true;
    }

    return false;
}

void D3MFImporter::SetupProperties(const Importer *pImp)
{

}

const aiImporterDesc *D3MFImporter::GetInfo() const
{
    return &desc;
}

void D3MFImporter::InternReadFile(const std::string &pFile, aiScene *pScene, IOSystem *pIOHandler)
{

    D3MF::D3MFOpcPackage opcPackage(pIOHandler, pFile);

    std::unique_ptr<CIrrXML_IOStreamReader> xmlStream(new CIrrXML_IOStreamReader(opcPackage.RootStream()));
    std::unique_ptr<D3MF::XmlReader> xmlReader(irr::io::createIrrXMLReader(xmlStream.get()));

    D3MF::XmlSerializer xmlSerializer(xmlReader.get());

    xmlSerializer.ImportXml(pScene);

}

}

#endif // ASSIMP_BUILD_NO_3MF_IMPORTER
<|endoftext|>


<commit_before>/*
 * The Apache Software License, Version 1.1
 *
 *
 * Copyright (c) 1999 The Apache Software Foundation.  All rights
 * reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 *
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in
 *    the documentation and/or other materials provided with the
 *    distribution.
 *
 * 3. The end-user documentation included with the redistribution,
 *    if any, must include the following acknowledgment:
 *       "This product includes software developed by the
 *        Apache Software Foundation (http://www.apache.org/)."
 *    Alternately, this acknowledgment may appear in the software itself,
 *    if and wherever such third-party acknowledgments normally appear.
 *
 * 4. The names "Xalan" and "Apache Software Foundation" must
 *    not be used to endorse or promote products derived from this
 *    software without prior written permission. For written
 *    permission, please contact apache@apache.org.
 *
 * 5. Products derived from this software may not be called "Apache",
 *    nor may "Apache" appear in their name, without prior written
 *    permission of the Apache Software Foundation.
 *
 * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED.  IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
 * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
 * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
 * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 * ====================================================================
 *
 * This software consists of voluntary contributions made by many
 * individuals on behalf of the Apache Software Foundation and was
 * originally based on software copyright (c) 1999, International
 * Business Machines, Inc., http://www.ibm.com.  For more
 * information on the Apache Software Foundation, please see
 * <http://www.apache.org/>.
 *
 * $ Id: $
 *
 *
 * @author David N. Bertoni
 */
#include "StdBinInputStream.hpp"

#include <cassert>

#if !defined(XALAN_OLD_STREAMS)
#if defined(XALAN_OLD_STREAM_HEADERS)
#include <iostream.h>
#else
#include <istream>
#endif
#endif

#if defined(XALAN_NO_NAMESPACES)
StdBinInputStream::StdBinInputStream(istream&		theStream) :
#else
StdBinInputStream::StdBinInputStream(std::istream&	theStream) :
#endif
	BinInputStream(),
	m_stream(theStream)
{
}

StdBinInputStream::~StdBinInputStream()
{
}

unsigned int
StdBinInputStream::curPos() const
{
	return m_stream.tellg();
}

unsigned int
StdBinInputStream::readBytes(
			XMLByte* const      toFill,
			const unsigned int	maxToRead)
{
	assert(sizeof(XMLByte) == sizeof(char));

	if (!m_stream)
	{
		return 0;
	}
	else
	{
		unsigned int	i = 0;

		while(i < maxToRead)
		{
			const int	ch = m_stream.get();

			if (ch == EOF)
			{
				break;
			}
			else
			{
				toFill[i] = XMLByte(ch);

				++i;
			}
		}

		return i;
	}
}
<commit_msg>Read bytes from the stream all at once.<commit_after>/*
 * The Apache Software License, Version 1.1
 *
 *
 * Copyright (c) 1999 The Apache Software Foundation.  All rights
 * reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 *
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in
 *    the documentation and/or other materials provided with the
 *    distribution.
 *
 * 3. The end-user documentation included with the redistribution,
 *    if any, must include the following acknowledgment:
 *       "This product includes software developed by the
 *        Apache Software Foundation (http://www.apache.org/)."
 *    Alternately, this acknowledgment may appear in the software itself,
 *    if and wherever such third-party acknowledgments normally appear.
 *
 * 4. The names "Xalan" and "Apache Software Foundation" must
 *    not be used to endorse or promote products derived from this
 *    software without prior written permission. For written
 *    permission, please contact apache@apache.org.
 *
 * 5. Products derived from this software may not be called "Apache",
 *    nor may "Apache" appear in their name, without prior written
 *    permission of the Apache Software Foundation.
 *
 * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED.  IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
 * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
 * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
 * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 * ====================================================================
 *
 * This software consists of voluntary contributions made by many
 * individuals on behalf of the Apache Software Foundation and was
 * originally based on software copyright (c) 1999, International
 * Business Machines, Inc., http://www.ibm.com.  For more
 * information on the Apache Software Foundation, please see
 * <http://www.apache.org/>.
 *
 * $ Id: $
 *
 *
 * @author David N. Bertoni
 */
#include "StdBinInputStream.hpp"

#include <cassert>

#if !defined(XALAN_OLD_STREAMS)
#if defined(XALAN_OLD_STREAM_HEADERS)
#include <iostream.h>
#else
#include <istream>
#endif
#endif

#if defined(XALAN_NO_NAMESPACES)
StdBinInputStream::StdBinInputStream(istream&		theStream) :
#else
StdBinInputStream::StdBinInputStream(std::istream&	theStream) :
#endif
	BinInputStream(),
	m_stream(theStream)
{
}

StdBinInputStream::~StdBinInputStream()
{
}

unsigned int
StdBinInputStream::curPos() const
{
	return m_stream.tellg();
}

unsigned int
StdBinInputStream::readBytes(
			XMLByte* const      toFill,
			const unsigned int	maxToRead)
{
	assert(sizeof(XMLByte) == sizeof(char));

	if (!m_stream)
	{
		return 0;
	}
	else
	{
#if defined(XALAN_OLD_STYLE_CASTS)
		return m_stream.readsome((char*)toFill, maxToRead);
#else
		return m_stream.readsome(reinterpret_cast<char*>(toFill), maxToRead);
#endif
	}
}
<|endoftext|>