<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: ETable.hxx,v $
 *
 *  $Revision: 1.13 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-08 07:13:22 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

#ifndef _CONNECTIVITY_FLAT_TABLE_HXX_
#define _CONNECTIVITY_FLAT_TABLE_HXX_

#ifndef _CONNECTIVITY_FILE_TABLE_HXX_
#include "file/FTable.hxx"
#endif
#ifndef _CONNECTIVITY_SDBCX_COLUMN_HXX_
#include "connectivity/sdbcx/VColumn.hxx"
#endif
#ifndef _CONNECTIVITY_COMMONTOOLS_HXX_
#include "connectivity/CommonTools.hxx"
#endif
#ifndef _URLOBJ_HXX //autogen wg. INetURLObject
#include <tools/urlobj.hxx>
#endif

namespace connectivity
{
    namespace flat
    {
        //==================================================================
        // Ableitung von String mit ueberladenen GetToken/GetTokenCount-Methoden
        // Speziell fuer FLAT FILE-Format: Strings koennen gequotet sein
        //==================================================================
        class OFlatString : public String
        {
        public:
            OFlatString(){}

            xub_StrLen  GetTokenCount( sal_Unicode cTok = ';', sal_Unicode cStrDel = '\0' ) const;
            void        GetTokenSpecial( String& _rStr,xub_StrLen& nStartPos, sal_Unicode cTok = ';', sal_Unicode cStrDel = '\0' ) const;
        };

        typedef file::OFileTable OFlatTable_BASE;
        class OFlatConnection;

        typedef ::std::map< ::rtl::OUString,
                        ::com::sun::star::uno::Reference< ::com::sun::star::container::XNamed>, comphelper::UStringMixLess > OContainer;

        class OFlatTable :  public OFlatTable_BASE
        {
            // maps a row postion to a file position
            ::std::map<sal_Int32,sal_Int32> m_aRowToFilePos;
            ::std::vector<sal_Int32>        m_aTypes;       // holds all type for columns just to avoid to ask the propertyset
            ::std::vector<sal_Int32>        m_aPrecisions;  // same as aboth
            ::std::vector<sal_Int32>        m_aScales;
            OFlatString                     m_aCurrentLine;
            ::com::sun::star::uno::Reference< ::com::sun::star::util::XNumberFormatter > m_xNumberFormatter;
            sal_Int32                       m_nRowPos;
            sal_Int32                       m_nMaxRowCount; // will be set if stream is once eof
        public:

        private:
            void fillColumns();
            BOOL CreateFile(const INetURLObject& aFile, BOOL& bCreateMemo);

            sal_Bool checkHeaderLine();
        public:
            virtual void refreshColumns();

        public:
            //  DECLARE_CTY_DEFAULTS( OFlatTable_BASE);
            OFlatTable( sdbcx::OCollection* _pTables,OFlatConnection* _pConnection);
            OFlatTable( sdbcx::OCollection* _pTables,OFlatConnection* _pConnection,
                    const ::rtl::OUString& _Name,
                    const ::rtl::OUString& _Type,
                    const ::rtl::OUString& _Description = ::rtl::OUString(),
                    const ::rtl::OUString& _SchemaName = ::rtl::OUString(),
                    const ::rtl::OUString& _CatalogName = ::rtl::OUString()
                );

            void construct(); // can throw any exception

            virtual sal_Bool seekRow(IResultSetHelper::Movement eCursorPosition, sal_Int32 nOffset, sal_Int32& nCurPos);
            virtual sal_Bool fetchRow(OValueRefRow& _rRow,const OSQLColumns& _rCols, sal_Bool bIsTable,sal_Bool bRetrieveData);

            virtual ::com::sun::star::uno::Any SAL_CALL queryInterface( const ::com::sun::star::uno::Type & rType ) throw(::com::sun::star::uno::RuntimeException);
            //XTypeProvider
            virtual ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Type > SAL_CALL getTypes(  ) throw(::com::sun::star::uno::RuntimeException);
            virtual void SAL_CALL disposing(void);

            // com::sun::star::lang::XUnoTunnel
            virtual sal_Int64 SAL_CALL getSomething( const ::com::sun::star::uno::Sequence< sal_Int8 >& aIdentifier ) throw(::com::sun::star::uno::RuntimeException);
            static ::com::sun::star::uno::Sequence< sal_Int8 > getUnoTunnelImplementationId();

            String getEntry();
        };
    }
}
#endif // _CONNECTIVITY_FLAT_TABLE_HXX_

<commit_msg>INTEGRATION: CWS dba202a (1.13.36); FILE MERGED 2005/11/25 08:33:08 oj 1.13.36.1: #126933# check if char is > 127<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: ETable.hxx,v $
 *
 *  $Revision: 1.14 $
 *
 *  last change: $Author: obo $ $Date: 2005-12-21 13:18:27 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

#ifndef _CONNECTIVITY_FLAT_TABLE_HXX_
#define _CONNECTIVITY_FLAT_TABLE_HXX_

#ifndef _CONNECTIVITY_FILE_TABLE_HXX_
#include "file/FTable.hxx"
#endif
#ifndef _CONNECTIVITY_SDBCX_COLUMN_HXX_
#include "connectivity/sdbcx/VColumn.hxx"
#endif
#ifndef _CONNECTIVITY_COMMONTOOLS_HXX_
#include "connectivity/CommonTools.hxx"
#endif
#ifndef _URLOBJ_HXX //autogen wg. INetURLObject
#include <tools/urlobj.hxx>
#endif

namespace connectivity
{
    namespace flat
    {
        //==================================================================
        // Ableitung von String mit ueberladenen GetToken/GetTokenCount-Methoden
        // Speziell fuer FLAT FILE-Format: Strings koennen gequotet sein
        //==================================================================
        class OFlatString : public String
        {
        public:
            OFlatString(){}

            xub_StrLen  GetTokenCount( sal_Unicode cTok = ';', sal_Unicode cStrDel = '\0' ) const;
            void        GetTokenSpecial( String& _rStr,xub_StrLen& nStartPos, sal_Unicode cTok = ';', sal_Unicode cStrDel = '\0' ) const;
        };

        typedef file::OFileTable OFlatTable_BASE;
        class OFlatConnection;

        typedef ::std::map< ::rtl::OUString,
                        ::com::sun::star::uno::Reference< ::com::sun::star::container::XNamed>, comphelper::UStringMixLess > OContainer;

        class OFlatTable :  public OFlatTable_BASE
        {
            // maps a row postion to a file position
            ::std::map<sal_Int32,sal_Int32> m_aRowToFilePos;
            ::std::vector<sal_Int32>        m_aTypes;       // holds all type for columns just to avoid to ask the propertyset
            ::std::vector<sal_Int32>        m_aPrecisions;  // same as aboth
            ::std::vector<sal_Int32>        m_aScales;
            OFlatString                     m_aCurrentLine;
            ::com::sun::star::uno::Reference< ::com::sun::star::util::XNumberFormatter > m_xNumberFormatter;
            sal_Int32                       m_nRowPos;
            sal_Int32                       m_nMaxRowCount; // will be set if stream is once eof
        public:

        private:
            void fillColumns(const ::com::sun::star::lang::Locale& _aLocale);
            BOOL CreateFile(const INetURLObject& aFile, BOOL& bCreateMemo);

            sal_Bool checkHeaderLine();
        public:
            virtual void refreshColumns();

        public:
            //  DECLARE_CTY_DEFAULTS( OFlatTable_BASE);
            OFlatTable( sdbcx::OCollection* _pTables,OFlatConnection* _pConnection);
            OFlatTable( sdbcx::OCollection* _pTables,OFlatConnection* _pConnection,
                    const ::rtl::OUString& _Name,
                    const ::rtl::OUString& _Type,
                    const ::rtl::OUString& _Description = ::rtl::OUString(),
                    const ::rtl::OUString& _SchemaName = ::rtl::OUString(),
                    const ::rtl::OUString& _CatalogName = ::rtl::OUString()
                );

            void construct(); // can throw any exception

            virtual sal_Bool seekRow(IResultSetHelper::Movement eCursorPosition, sal_Int32 nOffset, sal_Int32& nCurPos);
            virtual sal_Bool fetchRow(OValueRefRow& _rRow,const OSQLColumns& _rCols, sal_Bool bIsTable,sal_Bool bRetrieveData);

            virtual ::com::sun::star::uno::Any SAL_CALL queryInterface( const ::com::sun::star::uno::Type & rType ) throw(::com::sun::star::uno::RuntimeException);
            //XTypeProvider
            virtual ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Type > SAL_CALL getTypes(  ) throw(::com::sun::star::uno::RuntimeException);
            virtual void SAL_CALL disposing(void);

            // com::sun::star::lang::XUnoTunnel
            virtual sal_Int64 SAL_CALL getSomething( const ::com::sun::star::uno::Sequence< sal_Int8 >& aIdentifier ) throw(::com::sun::star::uno::RuntimeException);
            static ::com::sun::star::uno::Sequence< sal_Int8 > getUnoTunnelImplementationId();

            String getEntry();
        };
    }
}
#endif // _CONNECTIVITY_FLAT_TABLE_HXX_

<|endoftext|>


<commit_before>#include "interpreter.h"

#include "details/autoconfigurer.h"
#include "details/robotImplementations/unrealRobotModelImplementation.h"
#include "details/robotCommunication/bluetoothRobotCommunicationThread.h"
#include "details/robotCommunication/usbRobotCommunicationThread.h"
#include "details/tracer.h"
#include "details/debugHelper.h"

#include <QtGui/QAction>

using namespace qReal;
using namespace interpreters::robots;
using namespace interpreters::robots::details;

const Id startingElementType = Id("RobotsMetamodel", "RobotsDiagram", "InitialNode");
const Id startingElementType1 = Id("RobotsMetamodel", "RobotsDiagram", "InitialBlock");

Interpreter::Interpreter()
	: mGraphicalModelApi(NULL)
	, mLogicalModelApi(NULL)
	, mInterpretersInterface(NULL)
	, mState(idle)
	, mRobotModel(new RobotModel())
	, mBlocksTable(NULL)
	, mRobotCommunication(new RobotCommunicator(SettingsManager::value("valueOfCommunication", "bluetooth").toString()))
	, mImplementationType(robotModelType::null)
	, mWatchListWindow(NULL)
	, mActionConnectToRobot(NULL)
{
	mParser = NULL;
	mBlocksTable = NULL;
	mTimer = new QTimer();

	mD2RobotModel = new d2Model::D2RobotModel();
	mD2ModelWidget = mD2RobotModel->createModelWidget();

	connect(mRobotModel, SIGNAL(disconnected()), this, SLOT(disconnectSlot()));
	connect(mRobotModel, SIGNAL(sensorsConfigured()), this, SLOT(sensorsConfiguredSlot()));
	connect(mRobotModel, SIGNAL(connected(bool)), this, SLOT(connectedSlot(bool)));
}

void Interpreter::init(GraphicalModelAssistInterface const &graphicalModelApi
	, LogicalModelAssistInterface const &logicalModelApi
	, qReal::gui::MainWindowInterpretersInterface &interpretersInterface)
{
	mGraphicalModelApi = &graphicalModelApi;
	mLogicalModelApi = &logicalModelApi;
	mInterpretersInterface = &interpretersInterface;

	mParser = new RobotsBlockParser(mInterpretersInterface->errorReporter());
	mBlocksTable = new BlocksTable(graphicalModelApi, logicalModelApi, mRobotModel, mInterpretersInterface->errorReporter(), mParser);

	robotModelType::robotModelTypeEnum const modelType = static_cast<robotModelType::robotModelTypeEnum>(SettingsManager::value("robotModel", "1").toInt());
	Tracer::debug(tracer::initialization, "Interpreter::init", "Going to set robot implementation, model type is " + DebugHelper::toString(modelType));
	setRobotImplementation(modelType);
}

Interpreter::~Interpreter()
{
	foreach (Thread * const thread, mThreads)
		delete thread;
	delete mBlocksTable;
}

void Interpreter::interpret()
{
	Tracer::debug(tracer::initialization, "Interpreter::interpret", "Preparing for interpretation");

	mInterpretersInterface->errorReporter()->clear();

	Id const &currentDiagramId = mInterpretersInterface->activeDiagram();

	if (!mConnected) {
		mInterpretersInterface->errorReporter()->addInformation(tr("No connection to robot"));
		return;
	}
	if (mState != idle) {
		mInterpretersInterface->errorReporter()->addInformation(tr("Interpreter is already running"));
		return;
	}

	mState = waitingForSensorsConfiguredToLaunch;

	mBlocksTable->setIdleForBlocks();

	Id const startingElement = findStartingElement(currentDiagramId);
	if (startingElement == Id()) {
		mInterpretersInterface->errorReporter()->addError(tr("No entry point found, please add Initial Node to a diagram"));
		mState = idle;
		return;
	}

	Autoconfigurer configurer(*mGraphicalModelApi, mBlocksTable, mInterpretersInterface->errorReporter(), mRobotModel);
	if (!configurer.configure(currentDiagramId))
		return;
}

void Interpreter::stopRobot()
{
	mRobotModel->stopRobot();
	mState = idle;
	foreach (Thread *thread, mThreads) {
		delete thread;
		mThreads.removeAll(thread);
	}
	mBlocksTable->setFailure();
	/*mBlocksTable->clear();
	mThreads.clear();
	mTimer->stop();*/
}

void Interpreter::showWatchList() {
	if (mWatchListWindow != NULL) {
		mWatchListWindow->close();
	}
	mWatchListWindow = new watchListWindow(mParser);
	mWatchListWindow->show();
}

void Interpreter::closeD2ModelWidget()
{
	if (mD2ModelWidget)
		mD2ModelWidget->close();
}

void Interpreter::showD2ModelWidget(bool isVisible)
{
	mD2ModelWidget->init(isVisible);
	mD2ModelWidget->activateWindow();
	mD2ModelWidget->showNormal();
}

void Interpreter::setD2ModelWidgetActions(QAction *runAction, QAction *stopAction)
{
	mD2ModelWidget->setD2ModelWidgetActions(runAction, stopAction);
}

void Interpreter::enableD2ModelWidgetRunStopButtons()
{
	mD2ModelWidget->enableRunStopButtons();
}

void Interpreter::disableD2ModelWidgetRunStopButtons()
{
	mD2ModelWidget->disableRunStopButtons();
}

void Interpreter::setRobotImplementation(robotModelType::robotModelTypeEnum implementationType)
{
	mConnected = false;
	robotImplementations::AbstractRobotModelImplementation *robotImpl =
			robotImplementations::AbstractRobotModelImplementation::robotModel(implementationType, mRobotCommunication, mD2RobotModel);
	setRobotImplementation(robotImpl);
	mImplementationType = implementationType;
	if (mImplementationType != robotModelType::real)
		mRobotModel->init();
}

void Interpreter::connectedSlot(bool success)
{
	if (success) {
		if (mRobotModel->needsConnection()) {
			mInterpretersInterface->errorReporter()->addInformation(tr("Connected successfully"));
		}
	} else {
		Tracer::debug(tracer::initialization, "Interpreter::connectedSlot", "Robot connection status: " + QString::number(success));
		mInterpretersInterface->errorReporter()->addError(tr("Can't connect to a robot."));
	}
	mConnected = success;
	mActionConnectToRobot->setChecked(success);
}

void Interpreter::sensorsConfiguredSlot()
{
	Tracer::debug(tracer::initialization, "Interpreter::sensorsConfiguredSlot", "Sensors are configured");

	mConnected = true;
	mActionConnectToRobot->setChecked(mConnected);

	if (mState == waitingForSensorsConfiguredToLaunch) {
		mState = interpreting;

		Tracer::debug(tracer::initialization, "Interpreter::sensorsConfiguredSlot", "Starting interpretation");
		mRobotModel->startInterpretation();

		Id const &currentDiagramId = mInterpretersInterface->activeDiagram();
		Id const startingElement = findStartingElement(currentDiagramId);
		Thread * const initialThread = new Thread(*mInterpretersInterface, *mBlocksTable, startingElement);
		addThread(initialThread);
	}
}

Id const Interpreter::findStartingElement(Id const &diagram) const
{
	IdList const children = mGraphicalModelApi->graphicalRepoApi().children(diagram);

	foreach (Id const child, children) {
		if (child.type() == startingElementType || child.type() == startingElementType1)
			return child;
	}

	return Id();
}

void Interpreter::threadStopped()
{
	Thread *thread = static_cast<Thread *>(sender());

	mThreads.removeAll(thread);
	delete thread;

	if (mThreads.isEmpty()) {
		stopRobot();
	}
}

void Interpreter::newThread(details::blocks::Block * const startBlock)
{
	Thread * const thread = new Thread(*mInterpretersInterface, *mBlocksTable, startBlock->id());
	addThread(thread);
}

void Interpreter::configureSensors(sensorType::SensorTypeEnum const &port1
		, sensorType::SensorTypeEnum const &port2
		, sensorType::SensorTypeEnum const &port3
		, sensorType::SensorTypeEnum const &port4)
{
	mRobotModel->configureSensors(port1, port2, port3, port4);
}

void Interpreter::addThread(details::Thread * const thread)
{
	mThreads.append(thread);
	connect(thread, SIGNAL(stopped()), this, SLOT(threadStopped()));
	connect(thread, SIGNAL(newThread(details::blocks::Block*const)), this, SLOT(newThread(details::blocks::Block*const)));

	thread->interpret();
}

interpreters::robots::details::RobotModel *Interpreter::robotModel()
{
	return mRobotModel;
}

void Interpreter::setRobotModel(details::RobotModel * const robotModel)
{
	mRobotModel = robotModel;
}

void Interpreter::setRobotImplementation(details::robotImplementations::AbstractRobotModelImplementation *robotImpl)
{
	mRobotModel->setRobotImplementation(robotImpl);
	if (robotImpl)
		connect(mRobotModel, SIGNAL(connected(bool)), this, SLOT(runTimer()));
}

void Interpreter::runTimer()
{
	mTimer->start(1000);
	connect(mTimer, SIGNAL(timeout()), this, SLOT(readSensorValues()));
	if (mRobotModel->sensor(inputPort::port1)) {
		connect(mRobotModel->sensor(inputPort::port1)->sensorImpl(), SIGNAL(response(int)), this, SLOT(responseSlot1(int)));
		connect(mRobotModel->sensor(inputPort::port1)->sensorImpl(), SIGNAL(failure()), this, SLOT(slotFailure()));
	}
	if (mRobotModel->sensor(inputPort::port2)) {
		connect(mRobotModel->sensor(inputPort::port2)->sensorImpl(), SIGNAL(response(int)), this, SLOT(responseSlot2(int)));
		connect(mRobotModel->sensor(inputPort::port2)->sensorImpl(), SIGNAL(failure()), this, SLOT(slotFailure()));
	}
	if (mRobotModel->sensor(inputPort::port3)) {
		connect(mRobotModel->sensor(inputPort::port3)->sensorImpl(), SIGNAL(response(int)), this, SLOT(responseSlot3(int)));
		connect(mRobotModel->sensor(inputPort::port3)->sensorImpl(), SIGNAL(failure()), this, SLOT(slotFailure()));
	}
	if (mRobotModel->sensor(inputPort::port4)) {
		connect(mRobotModel->sensor(inputPort::port4)->sensorImpl(), SIGNAL(response(int)), this, SLOT(responseSlot4(int)));
		connect(mRobotModel->sensor(inputPort::port4)->sensorImpl(), SIGNAL(failure()), this, SLOT(slotFailure()));
	}
}

void Interpreter::readSensorValues()
{
	if (mState == idle)
		return;

	if (mRobotModel->sensor(inputPort::port1))
		mRobotModel->sensor(inputPort::port1)->read();
	if (mRobotModel->sensor(inputPort::port2))
		mRobotModel->sensor(inputPort::port2)->read();
	if (mRobotModel->sensor(inputPort::port3))
		mRobotModel->sensor(inputPort::port3)->read();
	if (mRobotModel->sensor(inputPort::port4))
		mRobotModel->sensor(inputPort::port4)->read();
}

void Interpreter::slotFailure()
{
	Tracer::debug(tracer::autoupdatedSensorValues, "Interpreter::slotFailure", "");
}

void Interpreter::responseSlot1(int sensorValue)
{
	updateSensorValues(QObject::tr("Sensor1"), sensorValue);
}

void Interpreter::responseSlot2(int sensorValue)
{
	updateSensorValues(QObject::tr("Sensor2"), sensorValue);
}

void Interpreter::responseSlot3(int sensorValue)
{
	updateSensorValues(QObject::tr("Sensor3"), sensorValue);
}

void Interpreter::responseSlot4(int sensorValue)
{
	updateSensorValues(QObject::tr("Sensor4"), sensorValue);
}

void Interpreter::updateSensorValues(QString const &sensorVariableName, int sensorValue)
{
	(*(mParser->getVariables()))[sensorVariableName] = utils::Number(sensorValue, utils::Number::intType);
	Tracer::debug(tracer::autoupdatedSensorValues, "Interpreter::updateSensorValues", sensorVariableName + QString::number(sensorValue));
}

void Interpreter::connectToRobot()
{
	if (mConnected) {
		mRobotModel->stopRobot();
		mRobotModel->disconnectFromRobot();
	} else {
		mRobotModel->init();
	}
	mActionConnectToRobot->setChecked(mConnected);
}

void Interpreter::disconnectSlot()
{
	mActionConnectToRobot->setChecked(false);
	mConnected = false;
}

void Interpreter::setRobotModelType(robotModelType::robotModelTypeEnum robotModelType)
{
	setRobotImplementation(robotModelType);
}

void Interpreter::setCommunicator(QString const &valueOfCommunication, QString const &portName)
{
	RobotCommunicationThreadInterface *communicator = NULL;
	if (valueOfCommunication == "bluetooth")
		communicator = new BluetoothRobotCommunicationThread();
	else
		communicator = new UsbRobotCommunicationThread();

	mRobotCommunication->setRobotCommunicationThreadObject(communicator);
	mRobotCommunication->setPortName(portName);

	disconnectSlot();
}

void Interpreter::setConnectRobotAction(QAction *actionConnect)
{
	mActionConnectToRobot = actionConnect;
}
<commit_msg>fixed 2d model window<commit_after>#include "interpreter.h"

#include "details/autoconfigurer.h"
#include "details/robotImplementations/unrealRobotModelImplementation.h"
#include "details/robotCommunication/bluetoothRobotCommunicationThread.h"
#include "details/robotCommunication/usbRobotCommunicationThread.h"
#include "details/tracer.h"
#include "details/debugHelper.h"

#include <QtGui/QAction>

using namespace qReal;
using namespace interpreters::robots;
using namespace interpreters::robots::details;

const Id startingElementType = Id("RobotsMetamodel", "RobotsDiagram", "InitialNode");
const Id startingElementType1 = Id("RobotsMetamodel", "RobotsDiagram", "InitialBlock");

Interpreter::Interpreter()
	: mGraphicalModelApi(NULL)
	, mLogicalModelApi(NULL)
	, mInterpretersInterface(NULL)
	, mState(idle)
	, mRobotModel(new RobotModel())
	, mBlocksTable(NULL)
	, mRobotCommunication(new RobotCommunicator(SettingsManager::value("valueOfCommunication", "bluetooth").toString()))
	, mImplementationType(robotModelType::null)
	, mWatchListWindow(NULL)
	, mActionConnectToRobot(NULL)
{
	mParser = NULL;
	mBlocksTable = NULL;
	mTimer = new QTimer();

	mD2RobotModel = new d2Model::D2RobotModel();
	mD2ModelWidget = mD2RobotModel->createModelWidget();

	connect(mRobotModel, SIGNAL(disconnected()), this, SLOT(disconnectSlot()));
	connect(mRobotModel, SIGNAL(sensorsConfigured()), this, SLOT(sensorsConfiguredSlot()));
	connect(mRobotModel, SIGNAL(connected(bool)), this, SLOT(connectedSlot(bool)));
}

void Interpreter::init(GraphicalModelAssistInterface const &graphicalModelApi
	, LogicalModelAssistInterface const &logicalModelApi
	, qReal::gui::MainWindowInterpretersInterface &interpretersInterface)
{
	mGraphicalModelApi = &graphicalModelApi;
	mLogicalModelApi = &logicalModelApi;
	mInterpretersInterface = &interpretersInterface;

	mParser = new RobotsBlockParser(mInterpretersInterface->errorReporter());
	mBlocksTable = new BlocksTable(graphicalModelApi, logicalModelApi, mRobotModel, mInterpretersInterface->errorReporter(), mParser);

	robotModelType::robotModelTypeEnum const modelType = static_cast<robotModelType::robotModelTypeEnum>(SettingsManager::value("robotModel", "1").toInt());
	Tracer::debug(tracer::initialization, "Interpreter::init", "Going to set robot implementation, model type is " + DebugHelper::toString(modelType));
	setRobotImplementation(modelType);
}

Interpreter::~Interpreter()
{
	foreach (Thread * const thread, mThreads)
		delete thread;
	delete mBlocksTable;
}

void Interpreter::interpret()
{
	Tracer::debug(tracer::initialization, "Interpreter::interpret", "Preparing for interpretation");

	mInterpretersInterface->errorReporter()->clear();

	Id const &currentDiagramId = mInterpretersInterface->activeDiagram();

	if (!mConnected) {
		mInterpretersInterface->errorReporter()->addInformation(tr("No connection to robot"));
		return;
	}
	if (mState != idle) {
		mInterpretersInterface->errorReporter()->addInformation(tr("Interpreter is already running"));
		return;
	}

	mState = waitingForSensorsConfiguredToLaunch;

	mBlocksTable->setIdleForBlocks();

	Id const startingElement = findStartingElement(currentDiagramId);
	if (startingElement == Id()) {
		mInterpretersInterface->errorReporter()->addError(tr("No entry point found, please add Initial Node to a diagram"));
		mState = idle;
		return;
	}

	Autoconfigurer configurer(*mGraphicalModelApi, mBlocksTable, mInterpretersInterface->errorReporter(), mRobotModel);
	if (!configurer.configure(currentDiagramId))
		return;
}

void Interpreter::stopRobot()
{
	mRobotModel->stopRobot();
	mState = idle;
	foreach (Thread *thread, mThreads) {
		delete thread;
		mThreads.removeAll(thread);
	}
	mBlocksTable->setFailure();
	/*mBlocksTable->clear();
	mThreads.clear();
	mTimer->stop();*/
}

void Interpreter::showWatchList() {
	if (mWatchListWindow != NULL) {
		mWatchListWindow->close();
	}
	mWatchListWindow = new watchListWindow(mParser);
	mWatchListWindow->show();
}

void Interpreter::closeD2ModelWidget()
{
	if (mD2ModelWidget)
		mD2ModelWidget->close();
}

void Interpreter::showD2ModelWidget(bool isVisible)
{
	mD2ModelWidget->init(isVisible);
	if (isVisible) {
		mD2ModelWidget->activateWindow();
		mD2ModelWidget->showNormal();
	}
}

void Interpreter::setD2ModelWidgetActions(QAction *runAction, QAction *stopAction)
{
	mD2ModelWidget->setD2ModelWidgetActions(runAction, stopAction);
}

void Interpreter::enableD2ModelWidgetRunStopButtons()
{
	mD2ModelWidget->enableRunStopButtons();
}

void Interpreter::disableD2ModelWidgetRunStopButtons()
{
	mD2ModelWidget->disableRunStopButtons();
}

void Interpreter::setRobotImplementation(robotModelType::robotModelTypeEnum implementationType)
{
	mConnected = false;
	robotImplementations::AbstractRobotModelImplementation *robotImpl =
			robotImplementations::AbstractRobotModelImplementation::robotModel(implementationType, mRobotCommunication, mD2RobotModel);
	setRobotImplementation(robotImpl);
	mImplementationType = implementationType;
	if (mImplementationType != robotModelType::real)
		mRobotModel->init();
}

void Interpreter::connectedSlot(bool success)
{
	if (success) {
		if (mRobotModel->needsConnection()) {
			mInterpretersInterface->errorReporter()->addInformation(tr("Connected successfully"));
		}
	} else {
		Tracer::debug(tracer::initialization, "Interpreter::connectedSlot", "Robot connection status: " + QString::number(success));
		mInterpretersInterface->errorReporter()->addError(tr("Can't connect to a robot."));
	}
	mConnected = success;
	mActionConnectToRobot->setChecked(success);
}

void Interpreter::sensorsConfiguredSlot()
{
	Tracer::debug(tracer::initialization, "Interpreter::sensorsConfiguredSlot", "Sensors are configured");

	mConnected = true;
	mActionConnectToRobot->setChecked(mConnected);

	if (mState == waitingForSensorsConfiguredToLaunch) {
		mState = interpreting;

		Tracer::debug(tracer::initialization, "Interpreter::sensorsConfiguredSlot", "Starting interpretation");
		mRobotModel->startInterpretation();

		Id const &currentDiagramId = mInterpretersInterface->activeDiagram();
		Id const startingElement = findStartingElement(currentDiagramId);
		Thread * const initialThread = new Thread(*mInterpretersInterface, *mBlocksTable, startingElement);
		addThread(initialThread);
	}
}

Id const Interpreter::findStartingElement(Id const &diagram) const
{
	IdList const children = mGraphicalModelApi->graphicalRepoApi().children(diagram);

	foreach (Id const child, children) {
		if (child.type() == startingElementType || child.type() == startingElementType1)
			return child;
	}

	return Id();
}

void Interpreter::threadStopped()
{
	Thread *thread = static_cast<Thread *>(sender());

	mThreads.removeAll(thread);
	delete thread;

	if (mThreads.isEmpty()) {
		stopRobot();
	}
}

void Interpreter::newThread(details::blocks::Block * const startBlock)
{
	Thread * const thread = new Thread(*mInterpretersInterface, *mBlocksTable, startBlock->id());
	addThread(thread);
}

void Interpreter::configureSensors(sensorType::SensorTypeEnum const &port1
		, sensorType::SensorTypeEnum const &port2
		, sensorType::SensorTypeEnum const &port3
		, sensorType::SensorTypeEnum const &port4)
{
	mRobotModel->configureSensors(port1, port2, port3, port4);
}

void Interpreter::addThread(details::Thread * const thread)
{
	mThreads.append(thread);
	connect(thread, SIGNAL(stopped()), this, SLOT(threadStopped()));
	connect(thread, SIGNAL(newThread(details::blocks::Block*const)), this, SLOT(newThread(details::blocks::Block*const)));

	thread->interpret();
}

interpreters::robots::details::RobotModel *Interpreter::robotModel()
{
	return mRobotModel;
}

void Interpreter::setRobotModel(details::RobotModel * const robotModel)
{
	mRobotModel = robotModel;
}

void Interpreter::setRobotImplementation(details::robotImplementations::AbstractRobotModelImplementation *robotImpl)
{
	mRobotModel->setRobotImplementation(robotImpl);
	if (robotImpl)
		connect(mRobotModel, SIGNAL(connected(bool)), this, SLOT(runTimer()));
}

void Interpreter::runTimer()
{
	mTimer->start(1000);
	connect(mTimer, SIGNAL(timeout()), this, SLOT(readSensorValues()));
	if (mRobotModel->sensor(inputPort::port1)) {
		connect(mRobotModel->sensor(inputPort::port1)->sensorImpl(), SIGNAL(response(int)), this, SLOT(responseSlot1(int)));
		connect(mRobotModel->sensor(inputPort::port1)->sensorImpl(), SIGNAL(failure()), this, SLOT(slotFailure()));
	}
	if (mRobotModel->sensor(inputPort::port2)) {
		connect(mRobotModel->sensor(inputPort::port2)->sensorImpl(), SIGNAL(response(int)), this, SLOT(responseSlot2(int)));
		connect(mRobotModel->sensor(inputPort::port2)->sensorImpl(), SIGNAL(failure()), this, SLOT(slotFailure()));
	}
	if (mRobotModel->sensor(inputPort::port3)) {
		connect(mRobotModel->sensor(inputPort::port3)->sensorImpl(), SIGNAL(response(int)), this, SLOT(responseSlot3(int)));
		connect(mRobotModel->sensor(inputPort::port3)->sensorImpl(), SIGNAL(failure()), this, SLOT(slotFailure()));
	}
	if (mRobotModel->sensor(inputPort::port4)) {
		connect(mRobotModel->sensor(inputPort::port4)->sensorImpl(), SIGNAL(response(int)), this, SLOT(responseSlot4(int)));
		connect(mRobotModel->sensor(inputPort::port4)->sensorImpl(), SIGNAL(failure()), this, SLOT(slotFailure()));
	}
}

void Interpreter::readSensorValues()
{
	if (mState == idle)
		return;

	if (mRobotModel->sensor(inputPort::port1))
		mRobotModel->sensor(inputPort::port1)->read();
	if (mRobotModel->sensor(inputPort::port2))
		mRobotModel->sensor(inputPort::port2)->read();
	if (mRobotModel->sensor(inputPort::port3))
		mRobotModel->sensor(inputPort::port3)->read();
	if (mRobotModel->sensor(inputPort::port4))
		mRobotModel->sensor(inputPort::port4)->read();
}

void Interpreter::slotFailure()
{
	Tracer::debug(tracer::autoupdatedSensorValues, "Interpreter::slotFailure", "");
}

void Interpreter::responseSlot1(int sensorValue)
{
	updateSensorValues(QObject::tr("Sensor1"), sensorValue);
}

void Interpreter::responseSlot2(int sensorValue)
{
	updateSensorValues(QObject::tr("Sensor2"), sensorValue);
}

void Interpreter::responseSlot3(int sensorValue)
{
	updateSensorValues(QObject::tr("Sensor3"), sensorValue);
}

void Interpreter::responseSlot4(int sensorValue)
{
	updateSensorValues(QObject::tr("Sensor4"), sensorValue);
}

void Interpreter::updateSensorValues(QString const &sensorVariableName, int sensorValue)
{
	(*(mParser->getVariables()))[sensorVariableName] = utils::Number(sensorValue, utils::Number::intType);
	Tracer::debug(tracer::autoupdatedSensorValues, "Interpreter::updateSensorValues", sensorVariableName + QString::number(sensorValue));
}

void Interpreter::connectToRobot()
{
	if (mConnected) {
		mRobotModel->stopRobot();
		mRobotModel->disconnectFromRobot();
	} else {
		mRobotModel->init();
	}
	mActionConnectToRobot->setChecked(mConnected);
}

void Interpreter::disconnectSlot()
{
	mActionConnectToRobot->setChecked(false);
	mConnected = false;
}

void Interpreter::setRobotModelType(robotModelType::robotModelTypeEnum robotModelType)
{
	setRobotImplementation(robotModelType);
}

void Interpreter::setCommunicator(QString const &valueOfCommunication, QString const &portName)
{
	RobotCommunicationThreadInterface *communicator = NULL;
	if (valueOfCommunication == "bluetooth")
		communicator = new BluetoothRobotCommunicationThread();
	else
		communicator = new UsbRobotCommunicationThread();

	mRobotCommunication->setRobotCommunicationThreadObject(communicator);
	mRobotCommunication->setPortName(portName);

	disconnectSlot();
}

void Interpreter::setConnectRobotAction(QAction *actionConnect)
{
	mActionConnectToRobot = actionConnect;
}
<|endoftext|>


<commit_before>#include "AT91.h"

#ifdef INCLUDE_SD
// stm32f4

static TinyCLR_SdCard_Provider sdCardProvider;
static TinyCLR_Api_Info sdApi;

#define AT91_SD_SECTOR_SIZE 512
#define AT91_SD_TIMEOUT 5000000

struct SdController {
    int32_t controller;
    size_t  sectorCount;

    size_t  *sectorSizes;
    uint8_t *pBuffer;
};

static const AT91_Gpio_Pin g_AT91_SdCard_Data0_Pins[] = AT91_SD_DATA0_PINS;
static const AT91_Gpio_Pin g_AT91_SdCard_Data1_Pins[] = AT91_SD_DATA1_PINS;
static const AT91_Gpio_Pin g_AT91_SdCard_Data2_Pins[] = AT91_SD_DATA2_PINS;
static const AT91_Gpio_Pin g_AT91_SdCard_Data3_Pins[] = AT91_SD_DATA3_PINS;
static const AT91_Gpio_Pin g_AT91_SdCard_Clk_Pins[] = AT91_SD_CLK_PINS;
static const AT91_Gpio_Pin g_AT91_SdCard_Cmd_Pins[] = AT91_SD_CMD_PINS;

SdController sdController[1];

void AT91_SdCard_Interrupt(void* param) {
    SD_ProcessIRQSrc();
}

const TinyCLR_Api_Info* AT91_SdCard_GetApi() {
    sdCardProvider.Parent = &sdApi;

    sdCardProvider.Acquire = &AT91_SdCard_Acquire;
    sdCardProvider.Release = &AT91_SdCard_Release;
    sdCardProvider.GetControllerCount = &AT91_SdCard_GetControllerCount;

    sdCardProvider.WriteSectors = &AT91_SdCard_WriteSector;
    sdCardProvider.ReadSectors = &AT91_SdCard_ReadSector;
    sdCardProvider.EraseSectors = &AT91_SdCard_EraseSector;
    sdCardProvider.IsSectorErased = &AT91_SdCard_IsSectorErased;
    sdCardProvider.GetSectorMap = &AT91_SdCard_GetSectorMap;

    sdApi.Author = "GHI Electronics, LLC";
    sdApi.Name = "GHIElectronics.TinyCLR.NativeApis.AT91.SdCardProvider";
    sdApi.Type = TinyCLR_Api_Type::SdCardProvider;
    sdApi.Version = 0;
    sdApi.Implementation = &sdCardProvider;

    return &sdApi;
}

TinyCLR_Result AT91_SdCard_Acquire(const TinyCLR_SdCard_Provider* self, int32_t controller) {
    sdController[controller].controller = controller;
    // Initialize hal layer here

    auto d0 = g_AT91_SdCard_Data0_Pins[controller];
    auto d1 = g_AT91_SdCard_Data1_Pins[controller];
    auto d2 = g_AT91_SdCard_Data2_Pins[controller];
    auto d3 = g_AT91_SdCard_Data3_Pins[controller];
    auto clk = g_AT91_SdCard_Clk_Pins[controller];
    auto cmd = g_AT91_SdCard_Cmd_Pins[controller];

    if (!AT91_GpioInternal_OpenPin(d0.number)
        || !AT91_GpioInternal_OpenPin(d1.number)
        || !AT91_GpioInternal_OpenPin(d2.number)
        || !AT91_GpioInternal_OpenPin(d3.number)
        || !AT91_GpioInternal_OpenPin(clk.number)
        || !AT91_GpioInternal_OpenPin(cmd.number)
        )
        return TinyCLR_Result::SharingViolation;

    AT91_GpioInternal_ConfigurePin(d0.number, AT91_Gpio_PortMode::AlternateFunction, AT91_Gpio_OutputType::PushPull, AT91_Gpio_OutputSpeed::High, AT91_Gpio_PullDirection::PullUp, d0.alternateFunction);
    AT91_GpioInternal_ConfigurePin(d1.number, AT91_Gpio_PortMode::AlternateFunction, AT91_Gpio_OutputType::PushPull, AT91_Gpio_OutputSpeed::High, AT91_Gpio_PullDirection::PullUp, d1.alternateFunction);
    AT91_GpioInternal_ConfigurePin(d2.number, AT91_Gpio_PortMode::AlternateFunction, AT91_Gpio_OutputType::PushPull, AT91_Gpio_OutputSpeed::High, AT91_Gpio_PullDirection::PullUp, d2.alternateFunction);
    AT91_GpioInternal_ConfigurePin(d3.number, AT91_Gpio_PortMode::AlternateFunction, AT91_Gpio_OutputType::PushPull, AT91_Gpio_OutputSpeed::High, AT91_Gpio_PullDirection::PullUp, d3.alternateFunction);
    AT91_GpioInternal_ConfigurePin(clk.number, AT91_Gpio_PortMode::AlternateFunction, AT91_Gpio_OutputType::PushPull, AT91_Gpio_OutputSpeed::High, AT91_Gpio_PullDirection::None, clk.alternateFunction);
    AT91_GpioInternal_ConfigurePin(cmd.number, AT91_Gpio_PortMode::AlternateFunction, AT91_Gpio_OutputType::PushPull, AT91_Gpio_OutputSpeed::High, AT91_Gpio_PullDirection::PullUp, cmd.alternateFunction);

    RCC->APB2ENR |= (1 << 11);

    auto memoryProvider = (const TinyCLR_Memory_Provider*)apiProvider->FindDefault(apiProvider, TinyCLR_Api_Type::MemoryProvider);

    sdController[controller].pBuffer = (uint8_t*)memoryProvider->Allocate(memoryProvider, AT91_SD_SECTOR_SIZE);
    sdController[controller].sectorSizes = (size_t*)memoryProvider->Allocate(memoryProvider, sizeof(size_t));

    SD_DeInit();

    int32_t to = 2;

    SD_Error error = SD_Init();

    if (error != SD_OK) // try one more time
        return SD_Init() == SD_OK ? TinyCLR_Result::Success : TinyCLR_Result::InvalidOperation;

    return TinyCLR_Result::Success;
}

TinyCLR_Result AT91_SdCard_Release(const TinyCLR_SdCard_Provider* self, int32_t controller) {
    auto d0 = g_AT91_SdCard_Data0_Pins[controller];
    auto d1 = g_AT91_SdCard_Data1_Pins[controller];
    auto d2 = g_AT91_SdCard_Data2_Pins[controller];
    auto d3 = g_AT91_SdCard_Data3_Pins[controller];
    auto clk = g_AT91_SdCard_Clk_Pins[controller];
    auto cmd = g_AT91_SdCard_Cmd_Pins[controller];

    SD_DeInit();

    RCC->APB2ENR &= ~(1 << 11);

    auto memoryProvider = (const TinyCLR_Memory_Provider*)apiProvider->FindDefault(apiProvider, TinyCLR_Api_Type::MemoryProvider);

    memoryProvider->Free(memoryProvider, sdController[controller].pBuffer);
    memoryProvider->Free(memoryProvider, sdController[controller].sectorSizes);

    AT91_GpioInternal_ClosePin(d0.number);
    AT91_GpioInternal_ClosePin(d1.number);
    AT91_GpioInternal_ClosePin(d2.number);
    AT91_GpioInternal_ClosePin(d3.number);
    AT91_GpioInternal_ClosePin(clk.number);
    AT91_GpioInternal_ClosePin(cmd.number);

    return TinyCLR_Result::Success;
}

TinyCLR_Result AT91_SdCard_GetControllerCount(const TinyCLR_SdCard_Provider* self, int32_t& count) {
    count = SIZEOF_ARRAY(g_AT91_SdCard_Data0_Pins);

    return TinyCLR_Result::Success;
}

TinyCLR_Result AT91_SdCard_WriteSector(const TinyCLR_SdCard_Provider* self, int32_t controller, uint64_t sector, size_t& count, const uint8_t* data, int32_t timeout) {
    int32_t index = 0;

    int32_t to;

    auto sectorCount = count;

    auto sectorNum = sector;

    uint8_t* pData = (uint8_t*)data;

    while (sectorCount) {
        to = timeout;

        while (SD_GetStatus() != SD_TRANSFER_OK && to--) {
            AT91_Time_Delay(nullptr, 1);
        }

        if (to > 0 && SD_WriteBlock(&pData[index], sectorNum * AT91_SD_SECTOR_SIZE, AT91_SD_SECTOR_SIZE) == SD_OK) {
            index += AT91_SD_SECTOR_SIZE;
            sectorNum++;
            sectorCount--;
        }
        else {
            SD_StopTransfer();
        }

        if (!to) {
            return TinyCLR_Result::InvalidOperation;
        }
    }

    return TinyCLR_Result::Success;

}

TinyCLR_Result AT91_SdCard_ReadSector(const TinyCLR_SdCard_Provider* self, int32_t controller, uint64_t sector, size_t& count, uint8_t* data, int32_t timeout) {
    int32_t index = 0;

    int32_t to;

    auto sectorCount = count;

    auto sectorNum = sector;

    while (sectorCount) {
        to = timeout;

        while (SD_GetStatus() != SD_TRANSFER_OK && to--) {
            AT91_Time_Delay(nullptr, 1);
        }

        if (to > 0 && SD_ReadBlock(&data[index], sectorNum * AT91_SD_SECTOR_SIZE, AT91_SD_SECTOR_SIZE) == SD_OK) {

            index += AT91_SD_SECTOR_SIZE;
            sectorNum++;
            sectorCount--;
        }
        else {
            SD_StopTransfer();
        }

        if (!to) {
            return TinyCLR_Result::InvalidOperation;
        }
    }

    return TinyCLR_Result::Success;
}

TinyCLR_Result AT91_SdCard_IsSectorErased(const TinyCLR_SdCard_Provider* self, int32_t controller, uint64_t sector, bool& erased) {
    erased = true;
    return TinyCLR_Result::Success;
}

TinyCLR_Result AT91_SdCard_EraseSector(const TinyCLR_SdCard_Provider* self, int32_t controller, uint64_t sector, size_t& count, int32_t timeout) {
    uint32_t addressStart = sector * AT91_SD_SECTOR_SIZE;

    uint32_t addressEnd = addressStart + (count * AT91_SD_SECTOR_SIZE);

    return SD_Erase(addressStart, addressEnd) == SD_OK ? TinyCLR_Result::Success : TinyCLR_Result::InvalidOperation;
}

TinyCLR_Result AT91_SdCard_GetSectorMap(const TinyCLR_SdCard_Provider* self, int32_t controller, const size_t*& sizes, size_t& count, bool& isUniform) {
    sdController[controller].sectorSizes[0] = AT91_SD_SECTOR_SIZE;

    sizes = sdController[controller].sectorSizes;
    count = SDCardInfo.CardCapacity / AT91_SD_SECTOR_SIZE;

    return TinyCLR_Result::Success;
}

TinyCLR_Result AT91_SdCard_Reset() {
    return TinyCLR_Result::Success;
}
#endif // INCLUDE_SD<commit_msg>FileSystem: Returns NotImplemented for Hydra<commit_after>#include "AT91.h"

#ifdef INCLUDE_SD
// stm32f4

static TinyCLR_SdCard_Provider sdCardProvider;
static TinyCLR_Api_Info sdApi;

#define AT91_SD_SECTOR_SIZE 512
#define AT91_SD_TIMEOUT 5000000

struct SdController {
    int32_t controller;
    size_t  sectorCount;

    size_t  *sectorSizes;
    uint8_t *pBuffer;
};

static const AT91_Gpio_Pin g_AT91_SdCard_Data0_Pins[] = AT91_SD_DATA0_PINS;
static const AT91_Gpio_Pin g_AT91_SdCard_Data1_Pins[] = AT91_SD_DATA1_PINS;
static const AT91_Gpio_Pin g_AT91_SdCard_Data2_Pins[] = AT91_SD_DATA2_PINS;
static const AT91_Gpio_Pin g_AT91_SdCard_Data3_Pins[] = AT91_SD_DATA3_PINS;
static const AT91_Gpio_Pin g_AT91_SdCard_Clk_Pins[] = AT91_SD_CLK_PINS;
static const AT91_Gpio_Pin g_AT91_SdCard_Cmd_Pins[] = AT91_SD_CMD_PINS;

SdController sdController[1];

void AT91_SdCard_Interrupt(void* param) {
    SD_ProcessIRQSrc();
}

const TinyCLR_Api_Info* AT91_SdCard_GetApi() {
    sdCardProvider.Parent = &sdApi;

    sdCardProvider.Acquire = &AT91_SdCard_Acquire;
    sdCardProvider.Release = &AT91_SdCard_Release;
    sdCardProvider.GetControllerCount = &AT91_SdCard_GetControllerCount;

    sdCardProvider.WriteSectors = &AT91_SdCard_WriteSector;
    sdCardProvider.ReadSectors = &AT91_SdCard_ReadSector;
    sdCardProvider.EraseSectors = &AT91_SdCard_EraseSector;
    sdCardProvider.IsSectorErased = &AT91_SdCard_IsSectorErased;
    sdCardProvider.GetSectorMap = &AT91_SdCard_GetSectorMap;

    sdApi.Author = "GHI Electronics, LLC";
    sdApi.Name = "GHIElectronics.TinyCLR.NativeApis.AT91.SdCardProvider";
    sdApi.Type = TinyCLR_Api_Type::SdCardProvider;
    sdApi.Version = 0;
    sdApi.Implementation = &sdCardProvider;

    return &sdApi;
}

TinyCLR_Result AT91_SdCard_Acquire(const TinyCLR_SdCard_Provider* self, int32_t controller) {
    sdController[controller].controller = controller;
    // Initialize hal layer here

    auto d0 = g_AT91_SdCard_Data0_Pins[controller];
    auto d1 = g_AT91_SdCard_Data1_Pins[controller];
    auto d2 = g_AT91_SdCard_Data2_Pins[controller];
    auto d3 = g_AT91_SdCard_Data3_Pins[controller];
    auto clk = g_AT91_SdCard_Clk_Pins[controller];
    auto cmd = g_AT91_SdCard_Cmd_Pins[controller];

    if (!AT91_GpioInternal_OpenPin(d0.number)
        || !AT91_GpioInternal_OpenPin(d1.number)
        || !AT91_GpioInternal_OpenPin(d2.number)
        || !AT91_GpioInternal_OpenPin(d3.number)
        || !AT91_GpioInternal_OpenPin(clk.number)
        || !AT91_GpioInternal_OpenPin(cmd.number)
        )
        return TinyCLR_Result::SharingViolation;

    return TinyCLR_Result::NotImplemented;
}

TinyCLR_Result AT91_SdCard_Release(const TinyCLR_SdCard_Provider* self, int32_t controller) {
    auto d0 = g_AT91_SdCard_Data0_Pins[controller];
    auto d1 = g_AT91_SdCard_Data1_Pins[controller];
    auto d2 = g_AT91_SdCard_Data2_Pins[controller];
    auto d3 = g_AT91_SdCard_Data3_Pins[controller];
    auto clk = g_AT91_SdCard_Clk_Pins[controller];
    auto cmd = g_AT91_SdCard_Cmd_Pins[controller];

    auto memoryProvider = (const TinyCLR_Memory_Provider*)apiProvider->FindDefault(apiProvider, TinyCLR_Api_Type::MemoryProvider);

    memoryProvider->Free(memoryProvider, sdController[controller].pBuffer);
    memoryProvider->Free(memoryProvider, sdController[controller].sectorSizes);

    AT91_GpioInternal_ClosePin(d0.number);
    AT91_GpioInternal_ClosePin(d1.number);
    AT91_GpioInternal_ClosePin(d2.number);
    AT91_GpioInternal_ClosePin(d3.number);
    AT91_GpioInternal_ClosePin(clk.number);
    AT91_GpioInternal_ClosePin(cmd.number);

    return TinyCLR_Result::NotImplemented;
}

TinyCLR_Result AT91_SdCard_GetControllerCount(const TinyCLR_SdCard_Provider* self, int32_t& count) {
    count = SIZEOF_ARRAY(g_AT91_SdCard_Data0_Pins);

    return TinyCLR_Result::NotImplemented;
}

TinyCLR_Result AT91_SdCard_WriteSector(const TinyCLR_SdCard_Provider* self, int32_t controller, uint64_t sector, size_t& count, const uint8_t* data, int32_t timeout) {
    return TinyCLR_Result::NotImplemented;
}

TinyCLR_Result AT91_SdCard_ReadSector(const TinyCLR_SdCard_Provider* self, int32_t controller, uint64_t sector, size_t& count, uint8_t* data, int32_t timeout) {
    return TinyCLR_Result::NotImplemented;
}

TinyCLR_Result AT91_SdCard_IsSectorErased(const TinyCLR_SdCard_Provider* self, int32_t controller, uint64_t sector, bool& erased) {
    erased = true;
    return TinyCLR_Result::NotImplemented;
}

TinyCLR_Result AT91_SdCard_EraseSector(const TinyCLR_SdCard_Provider* self, int32_t controller, uint64_t sector, size_t& count, int32_t timeout) {
    uint32_t addressStart = sector * AT91_SD_SECTOR_SIZE;

    uint32_t addressEnd = addressStart + (count * AT91_SD_SECTOR_SIZE);

    return TinyCLR_Result::NotImplemented;
}

TinyCLR_Result AT91_SdCard_GetSectorMap(const TinyCLR_SdCard_Provider* self, int32_t controller, const size_t*& sizes, size_t& count, bool& isUniform) {
    return TinyCLR_Result::NotImplemented;
}

TinyCLR_Result AT91_SdCard_Reset() {
    return TinyCLR_Result::NotImplemented;
}
#endif // INCLUDE_SD<|endoftext|>


<commit_before>
//
// This source file is part of appleseed.
// Visit http://appleseedhq.net/ for additional information and resources.
//
// This software is released under the MIT license.
//
// Copyright (c) 2010-2011 Francois Beaune
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//

// appleseed.renderer headers.
#include "renderer/global/global.h"

// appleseed.foundation headers.
#include "foundation/utility/containers/dictionary.h"
#include "foundation/utility/test.h"

// Standard headers.
#include <string>

using namespace foundation;
using namespace renderer;
using namespace std;

TEST_SUITE(Renderer_Global_ParamArray)
{
    TEST_CASE(GetPath_GivenItemName_ReturnsItemValue)
    {
        ParamArray params;
        params.insert("x", 42);

        const char* value = params.get_path("x");

        EXPECT_EQ("42", string(value));
    }

    TEST_CASE(GetPath_GivenParentNameAndItemName_ReturnsItemValue)
    {
        ParamArray params;
        params.push("parent").insert("x", 42);

        const char* value = params.get_path("parent.x");

        EXPECT_EQ("42", string(value));
    }

    TEST_CASE(GetPath_GivenInvalidItemName_ThrowsExceptionDictionaryItemNotFound)
    {
        ParamArray params;
        params.insert("x", 42);

        EXPECT_EXCEPTION(ExceptionDictionaryItemNotFound,
        {
            const char* value = params.get_path("y");
        });
    }

    TEST_CASE(GetPath_GivenInvalidParentName_ThrowsExceptionDictionaryItemNotFound)
    {
        ParamArray params;
        params.push("parent").insert("x", 42);

        EXPECT_EXCEPTION(ExceptionDictionaryItemNotFound,
        {
            const char* value = params.get_path("other.x");
        });
    }

    TEST_CASE(Merge_GivenOneIntInSourceAndOneIntInDestWithDifferentNames_InsertsDestIntIntoSource)
    {
        ParamArray dst;
        dst.insert("A", 1);

        ParamArray src;
        src.insert("B", 2);

        dst.merge(src);

        EXPECT_EQ(2, dst.size());
        EXPECT_EQ(1, dst.get<int>("A"));
        EXPECT_EQ(2, dst.get<int>("B"));
    }

    TEST_CASE(Merge_GivenOneIntInSourceAndOneIntInDestWithSameNames_OverwritesDestValueWithSourceValue)
    {
        ParamArray dst;
        dst.insert("A", 1);

        ParamArray src;
        src.insert("A", 2);

        dst.merge(src);

        EXPECT_EQ(1, dst.size());
        EXPECT_EQ(2, dst.get<int>("A"));
    }

    TEST_CASE(Merge_GivenOneDicInSourceAndOneDicInDestWithDifferentNames_MergesDestDicIntoSource)
    {
        ParamArray dst_child;
        dst_child.insert("AA", 1);

        ParamArray dst;
        dst.dictionaries().insert("A", dst_child);

        ParamArray src_child;
        src_child.insert("BB", 2);

        ParamArray src;
        src.dictionaries().insert("B", src_child);

        dst.merge(src);

        EXPECT_EQ(2, dst.size());
        EXPECT_EQ(1, dst.dictionary("A").get<int>("AA"));
        EXPECT_EQ(2, dst.dictionary("B").get<int>("BB"));
    }

    TEST_CASE(Merge_GivenOneDicInSourceAndOneDicInDestWithSameNames_MergesDicContents)
    {
        ParamArray dst_child;
        dst_child.insert("AA", 1);

        ParamArray dst;
        dst.dictionaries().insert("A", dst_child);

        ParamArray src_child;
        src_child.insert("BB", 2);

        ParamArray src;
        src.dictionaries().insert("A", src_child);

        dst.merge(src);

        EXPECT_EQ(1, dst.size());
        EXPECT_EQ(1, dst.dictionary("A").get<int>("AA"));
        EXPECT_EQ(2, dst.dictionary("A").get<int>("BB"));
    }

    TEST_CASE(TestConstructionOfDictionaryFromParamArray)
    {
        ParamArray params;
        params.insert("x", 42);

        const Dictionary dic = params;

        ASSERT_EQ(1, dic.strings().size());
        EXPECT_EQ(42, dic.get<int>("x"));
    }
}
<commit_msg>added unit tests for renderer::ParamArray::insert_path().<commit_after>
//
// This source file is part of appleseed.
// Visit http://appleseedhq.net/ for additional information and resources.
//
// This software is released under the MIT license.
//
// Copyright (c) 2010-2011 Francois Beaune
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//

// appleseed.renderer headers.
#include "renderer/global/global.h"

// appleseed.foundation headers.
#include "foundation/utility/containers/dictionary.h"
#include "foundation/utility/test.h"

// Standard headers.
#include <string>

using namespace foundation;
using namespace renderer;
using namespace std;

TEST_SUITE(Renderer_Global_ParamArray)
{
    TEST_CASE(InsertPath_GivenItemName_InsertsItem)
    {
        ParamArray params;
        params.insert_path("x", 42);

        const char* value = params.strings().get("x");

        EXPECT_EQ("42", string(value));
    }

    TEST_CASE(InsertPath_GivenParentNameAndItemName_InsertsItem)
    {
        ParamArray params;
        params.insert_path("parent.x", 42);

        const char* value = params.dictionaries().get("parent").strings().get("x");

        EXPECT_EQ("42", string(value));
    }

    TEST_CASE(GetPath_GivenItemName_ReturnsItemValue)
    {
        ParamArray params;
        params.insert("x", 42);

        const char* value = params.get_path("x");

        EXPECT_EQ("42", string(value));
    }

    TEST_CASE(GetPath_GivenParentNameAndItemName_ReturnsItemValue)
    {
        ParamArray params;
        params.push("parent").insert("x", 42);

        const char* value = params.get_path("parent.x");

        EXPECT_EQ("42", string(value));
    }

    TEST_CASE(GetPath_GivenInvalidItemName_ThrowsExceptionDictionaryItemNotFound)
    {
        ParamArray params;
        params.insert("x", 42);

        EXPECT_EXCEPTION(ExceptionDictionaryItemNotFound,
        {
            const char* value = params.get_path("y");
        });
    }

    TEST_CASE(GetPath_GivenInvalidParentName_ThrowsExceptionDictionaryItemNotFound)
    {
        ParamArray params;
        params.push("parent").insert("x", 42);

        EXPECT_EXCEPTION(ExceptionDictionaryItemNotFound,
        {
            const char* value = params.get_path("other.x");
        });
    }

    TEST_CASE(Merge_GivenOneIntInSourceAndOneIntInDestWithDifferentNames_InsertsDestIntIntoSource)
    {
        ParamArray dst;
        dst.insert("A", 1);

        ParamArray src;
        src.insert("B", 2);

        dst.merge(src);

        EXPECT_EQ(2, dst.size());
        EXPECT_EQ(1, dst.get<int>("A"));
        EXPECT_EQ(2, dst.get<int>("B"));
    }

    TEST_CASE(Merge_GivenOneIntInSourceAndOneIntInDestWithSameNames_OverwritesDestValueWithSourceValue)
    {
        ParamArray dst;
        dst.insert("A", 1);

        ParamArray src;
        src.insert("A", 2);

        dst.merge(src);

        EXPECT_EQ(1, dst.size());
        EXPECT_EQ(2, dst.get<int>("A"));
    }

    TEST_CASE(Merge_GivenOneDicInSourceAndOneDicInDestWithDifferentNames_MergesDestDicIntoSource)
    {
        ParamArray dst_child;
        dst_child.insert("AA", 1);

        ParamArray dst;
        dst.dictionaries().insert("A", dst_child);

        ParamArray src_child;
        src_child.insert("BB", 2);

        ParamArray src;
        src.dictionaries().insert("B", src_child);

        dst.merge(src);

        EXPECT_EQ(2, dst.size());
        EXPECT_EQ(1, dst.dictionary("A").get<int>("AA"));
        EXPECT_EQ(2, dst.dictionary("B").get<int>("BB"));
    }

    TEST_CASE(Merge_GivenOneDicInSourceAndOneDicInDestWithSameNames_MergesDicContents)
    {
        ParamArray dst_child;
        dst_child.insert("AA", 1);

        ParamArray dst;
        dst.dictionaries().insert("A", dst_child);

        ParamArray src_child;
        src_child.insert("BB", 2);

        ParamArray src;
        src.dictionaries().insert("A", src_child);

        dst.merge(src);

        EXPECT_EQ(1, dst.size());
        EXPECT_EQ(1, dst.dictionary("A").get<int>("AA"));
        EXPECT_EQ(2, dst.dictionary("A").get<int>("BB"));
    }

    TEST_CASE(TestConstructionOfDictionaryFromParamArray)
    {
        ParamArray params;
        params.insert("x", 42);

        const Dictionary dic = params;

        ASSERT_EQ(1, dic.strings().size());
        EXPECT_EQ(42, dic.get<int>("x"));
    }
}
<|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.

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

#ifndef __mitkTbssImporter_cpp
#define __mitkTbssImporter_cpp

#include "mitkTbssImporter.h"
#include <mitkPixelTypeMultiplex.h>
#include "mitkImagePixelReadAccessor.h"

namespace mitk
{

TbssImage::Pointer TbssImporter::Import()
{
  mitk::TbssImage::Pointer tbssImg = mitk::TbssImage::New();
  mitkPixelTypeMultiplex1( Import, m_InputVolume->GetPixelType(), tbssImg);
  return tbssImg;
}

template <typename TPixel>
void TbssImporter::Import(const mitk::PixelType , mitk::TbssImage::Pointer tbssImg)
{
  // read all images with all_*.nii.gz
  MITK_INFO << "called import ...";
  m_Data = DataImageType::New();

  mitk::Geometry3D* geo = m_InputVolume->GetGeometry();
  mitk::Vector3D spacing = geo->GetSpacing();
  mitk::Point3D origin = geo->GetOrigin();

  //Size size
  DataImageType::SizeType dataSize;
  dataSize[0] = m_InputVolume->GetDimension(0);
  dataSize[1] = m_InputVolume->GetDimension(1);
  dataSize[2] = m_InputVolume->GetDimension(2);

  m_Data->SetRegions(dataSize);

  // Set spacing
  DataImageType::SpacingType dataSpacing;
  dataSpacing[0] = spacing[0];
  dataSpacing[1] = spacing[1];
  dataSpacing[2] = spacing[2];
  m_Data->SetSpacing(dataSpacing);

  DataImageType::PointType dataOrigin;
  dataOrigin[0] = origin[0];
  dataOrigin[1] = origin[1];
  dataOrigin[2] = origin[2];
  m_Data->SetOrigin(dataOrigin);

  //Direction must be set
  DataImageType::DirectionType dir;
  const itk::Transform<float, 3, 3>* transform3D = geo->GetParametricTransform();
  itk::Transform<float,3,3>::ParametersType p = transform3D->GetParameters();
  int t=0;
  for(int i=0; i<3; i++)
  {
    for(int j=0; j<3; j++)
    {
      dir[i][j] = p[t]; // row-major order (where the column index varies the fastest)
      t++;
    }
  }

  m_Data->SetDirection(dir);

  // Set the length to one because otherwise allocate fails. Should be changed when groups/measurements are added
  m_Data->SetVectorLength(m_InputVolume->GetDimension(3));
  m_Data->Allocate();

  // Determine vector size of m_Data

  int vecSize = m_Data->GetVectorLength();

  MITK_INFO << "vecsize " <<vecSize;
  try {
    mitk::ImagePixelReadAccessor<TPixel,4> readTbss( m_InputVolume );

    for(int i=0; i<dataSize[0]; i++)
    {
      MITK_INFO << "i " << i << " / " << dataSize[0];
      for(int j=0; j<dataSize[1]; j++)
      {
        for(int k=0; k<dataSize[2]; k++)
        {
          itk::VariableLengthVector<float> pixel;
          itk::Index<3> id;
          itk::Index<4> ix;

          ix[0] = id[0] = i;
          ix[1] = id[1] = j;
          ix[2] = id[2] = k;
          for(int z=0; z<vecSize; z++)
          {
            ix[3] = z;
            float value = readTbss.GetPixelByIndex(ix);

            pixel = m_Data->GetPixel(id);
            pixel.SetElement(z, value);
          }
          m_Data->SetPixel(id, pixel);
        }
      }
    }
  }
  catch ( mitk::Exception& e )
  {
    MITK_ERROR << "TbssImporter::Import: No read access to tbss image. " << e.what() ;
  }

  tbssImg->SetGroupInfo(m_Groups);
  tbssImg->SetMeasurementInfo(m_MeasurementInfo);
  tbssImg->SetImage(m_Data);

  tbssImg->InitializeFromVectorImage();

}

}
#endif // __mitkTbssImporter_cpp
<commit_msg>prevent overwriting of edited pixel<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.

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

#ifndef __mitkTbssImporter_cpp
#define __mitkTbssImporter_cpp

#include "mitkTbssImporter.h"
#include <mitkPixelTypeMultiplex.h>
#include "mitkImagePixelReadAccessor.h"

namespace mitk
{

TbssImage::Pointer TbssImporter::Import()
{
  mitk::TbssImage::Pointer tbssImg = mitk::TbssImage::New();
  mitkPixelTypeMultiplex1( Import, m_InputVolume->GetPixelType(), tbssImg);
  return tbssImg;
}

template <typename TPixel>
void TbssImporter::Import(const mitk::PixelType , mitk::TbssImage::Pointer tbssImg)
{
  // read all images with all_*.nii.gz
  MITK_INFO << "called import ...";
  m_Data = DataImageType::New();

  mitk::Geometry3D* geo = m_InputVolume->GetGeometry();
  mitk::Vector3D spacing = geo->GetSpacing();
  mitk::Point3D origin = geo->GetOrigin();

  //Size size
  DataImageType::SizeType dataSize;
  dataSize[0] = m_InputVolume->GetDimension(0);
  dataSize[1] = m_InputVolume->GetDimension(1);
  dataSize[2] = m_InputVolume->GetDimension(2);

  m_Data->SetRegions(dataSize);

  // Set spacing
  DataImageType::SpacingType dataSpacing;
  dataSpacing[0] = spacing[0];
  dataSpacing[1] = spacing[1];
  dataSpacing[2] = spacing[2];
  m_Data->SetSpacing(dataSpacing);

  DataImageType::PointType dataOrigin;
  dataOrigin[0] = origin[0];
  dataOrigin[1] = origin[1];
  dataOrigin[2] = origin[2];
  m_Data->SetOrigin(dataOrigin);

  //Direction must be set
  DataImageType::DirectionType dir;
  const itk::Transform<float, 3, 3>* transform3D = geo->GetParametricTransform();
  itk::Transform<float,3,3>::ParametersType p = transform3D->GetParameters();
  int t=0;
  for(int i=0; i<3; i++)
  {
    for(int j=0; j<3; j++)
    {
      dir[i][j] = p[t]; // row-major order (where the column index varies the fastest)
      t++;
    }
  }

  m_Data->SetDirection(dir);

  // Set the length to one because otherwise allocate fails. Should be changed when groups/measurements are added
  m_Data->SetVectorLength(m_InputVolume->GetDimension(3));
  m_Data->Allocate();

  // Determine vector size of m_Data

  int vecSize = m_Data->GetVectorLength();

  MITK_INFO << "vecsize " <<vecSize;
  try {
    mitk::ImagePixelReadAccessor<TPixel,4> readTbss( m_InputVolume );

    for(int i=0; i<dataSize[0]; i++)
    {
      MITK_INFO << "i " << i << " / " << dataSize[0];
      for(int j=0; j<dataSize[1]; j++)
      {
        for(int k=0; k<dataSize[2]; k++)
        {
          itk::VariableLengthVector<float> pixel;
          itk::Index<3> id;
          itk::Index<4> ix;

          ix[0] = id[0] = i;
          ix[1] = id[1] = j;
          ix[2] = id[2] = k;

          pixel = m_Data->GetPixel(id);

          for(int z=0; z<vecSize; z++)
          {
            ix[3] = z;
            float value = readTbss.GetPixelByIndex(ix);

            pixel.SetElement(z, value);
          }
          m_Data->SetPixel(id, pixel);
        }
      }
    }
  }
  catch ( mitk::Exception& e )
  {
    MITK_ERROR << "TbssImporter::Import: No read access to tbss image. " << e.what() ;
  }

  tbssImg->SetGroupInfo(m_Groups);
  tbssImg->SetMeasurementInfo(m_MeasurementInfo);
  tbssImg->SetImage(m_Data);

  tbssImg->InitializeFromVectorImage();

}

}
#endif // __mitkTbssImporter_cpp
<|endoftext|>


<commit_before>#include <stdio.h>
#include <typeinfo>
#include "inlineFunctions.h"
#include "stringutil.h"
#include "symtab.h"
#include "replaceReturns.h"

void InlineFunctions::postProcessExpr(Expr* expr) {
  //no inlining compiler flag was set on the command-line
  if (no_inline)
    return;
  //function call
  if (CallExpr* fn_call = dynamic_cast<CallExpr*>(expr)) {
    if (fn_call->isPrimitive() || fn_call->opTag != OP_NONE) {
      return;
    }
    //for now, only leaf getter/setter functions will be inlined
    FnSymbol* fn_sym = fn_call->findFnSymbol();
    if (fn_sym->hasPragma("inline") && isCodegened(fn_sym)) {
      _ok_to_inline = true;
      //map formal parameters to actual arguments
      Map<BaseAST*,BaseAST*>* formal_to_actual_arg_map = createFormalToActualArgMappings(fn_call, fn_sym->formals);
      //inline body if it is ok to do so even after examining the actual arguments
      if (_ok_to_inline) {
        Stmt* inlined_body = fn_sym->body->copy(true,formal_to_actual_arg_map,NULL);
        ReplaceReturns* rep_returns;
        if (fn_sym->retType && (fn_sym->retType != dtVoid)) {
          DefExpr* temp_def = createTempVariable(fn_sym->retType);
          fn_call->parentStmt->insertBefore(new ExprStmt(temp_def));
          //replace all returns in the inlined function body
          //with an assignment the return expression
          rep_returns = new ReplaceReturns(temp_def->sym);
          inlined_body->traverse(rep_returns);
          //inlined function
          fn_call->parentStmt->insertBefore(inlined_body);
          fn_call->replace(new Variable(temp_def->sym));
        }
        else {
          //inlined function
          fn_call->parentStmt->insertBefore(inlined_body);
          fn_call->parentStmt->remove();
        }
        //report inlining compiler flag was set of the command-line
        if (report_inlining)
          printf("chapel compiler: reporting inlining, %s function was inlined \n", fn_sym->name);
      }
    }
  }
}

bool InlineFunctions::isCodegened(FnSymbol* fn_sym) {
  //do not inline methods that are not codegened (e.g. prelude)
  ModuleSymbol* mod_sym = fn_sym->paramScope->getModule();
  return (!fn_sym->hasPragma("no codegen") && (mod_sym->modtype != MOD_INTERNAL));
}

DefExpr* InlineFunctions::createTempVariable(Type* type, Expr* init) {
  static int id = 1;
  char* temp_name =  glomstrings(2, "_inline_temp_", intstring(id++));
  DefExpr* temp_def = Symboltable::defineSingleVarDef(temp_name,
                                                      type,
                                                      init,
                                                      VAR_NORMAL,
                                                      VAR_VAR);
  dynamic_cast<VarSymbol*>(temp_def->sym)->noDefaultInit = true;
  return temp_def;
}

bool InlineFunctions::isFormalParamOut(ParamSymbol* p_sym) {
  return ((p_sym->intent == PARAM_INOUT) || (p_sym->intent == PARAM_OUT));
}

bool InlineFunctions::isFormalParamRef(ParamSymbol* p_sym) {
  return (p_sym->intent == PARAM_REF) || dynamic_cast<ClassType*>(p_sym->type);
}

bool InlineFunctions::isTypeVar(ParamSymbol* p_sym) {
  return (p_sym->typeVariable != NULL);
}

Map<BaseAST*,BaseAST*>* InlineFunctions::createFormalToActualArgMappings(CallExpr* fn_call, AList<DefExpr>* formal_params) {
  Expr* curr_arg;
  DefExpr* curr_param;
  AList<Expr>* actual_args = fn_call->argList;

  if (actual_args) {
    curr_arg = actual_args->first();
    curr_param = formal_params->first();
  }
  //go through all the actual arguments
  Map<BaseAST*,BaseAST*>* formal_to_actual_arg_map = new Map<BaseAST*,BaseAST*>();
  while(curr_arg) {
    bool param_ref = isFormalParamRef(dynamic_cast<ParamSymbol*>(curr_param->sym));
    bool param_intent_out = isFormalParamOut(dynamic_cast<ParamSymbol*>(curr_param->sym));
    bool typeVar = isTypeVar(dynamic_cast<ParamSymbol*>(curr_param->sym));
    //do not inline the function call if an argument is a ref to a expression that is no
    //a variable
    Variable* variable;
    if (param_ref || typeVar) {
      variable = dynamic_cast<Variable*>(curr_arg);
      if (!variable) {
        _ok_to_inline = false;
        return NULL;
      }
    }

    //create temporary variable and initialize it with the actual argument
    DefExpr* temp_def;
    if (!param_ref && !typeVar) {
      temp_def = createTempVariable(curr_arg->typeInfo(), curr_arg->copy());
      fn_call->parentStmt->insertBefore(new ExprStmt(temp_def));
      //map variable of param symbol to temp symbol so that when copy is passed the map, it
      //will replace the formal parameter symbol with the temp symbol
      formal_to_actual_arg_map->put(curr_param->sym, temp_def->sym);
    }
    //since a temporary variable was not created, map the actual argument to the formal parameter
    else
      formal_to_actual_arg_map->put(curr_param->sym, variable->var);

      //copy temp back to actual arg if formal param out
    if (param_intent_out)
      if (Variable* v = dynamic_cast<Variable*>(curr_arg))
        fn_call->parentStmt->insertAfter(new ExprStmt(new CallExpr(OP_GETSNORM, new Variable(v->var), new Variable(temp_def->sym))));

    curr_arg = actual_args->next();
    curr_param = formal_params->next();
  }
  return formal_to_actual_arg_map;
}

<commit_msg>Added line that ensures that pragmas have been copied to function symbol for uniformity sake.  Currently, pragmas sometime appear on the function symbol and sometime appear on the function definition statement.<commit_after>#include <stdio.h>
#include <typeinfo>
#include "inlineFunctions.h"
#include "stringutil.h"
#include "symtab.h"
#include "replaceReturns.h"

void InlineFunctions::postProcessExpr(Expr* expr) {
  //no inlining compiler flag was set on the command-line
  if (no_inline)
    return;
  //function call
  if (CallExpr* fn_call = dynamic_cast<CallExpr*>(expr)) {
    if (fn_call->isPrimitive() || fn_call->opTag != OP_NONE) {
      return;
    }
    FnSymbol* fn_sym = fn_call->findFnSymbol();
    //copy pragmas from function definition stmt to its function symbol
    fn_sym->copyPragmas(fn_sym->defPoint->parentStmt->pragmas);
    //inline function
    if (fn_sym->hasPragma("inline") && isCodegened(fn_sym)) {
      _ok_to_inline = true;
      //map formal parameters to actual arguments
      Map<BaseAST*,BaseAST*>* formal_to_actual_arg_map = createFormalToActualArgMappings(fn_call, fn_sym->formals);
      //inline body if it is ok to do so even after examining the actual arguments
      if (_ok_to_inline) {
        Stmt* inlined_body = fn_sym->body->copy(true,formal_to_actual_arg_map,NULL);
        ReplaceReturns* rep_returns;
        if (fn_sym->retType && (fn_sym->retType != dtVoid)) {
          DefExpr* temp_def = createTempVariable(fn_sym->retType);
          fn_call->parentStmt->insertBefore(new ExprStmt(temp_def));
          //replace all returns in the inlined function body
          //with an assignment the return expression
          rep_returns = new ReplaceReturns(temp_def->sym);
          inlined_body->traverse(rep_returns);
          //inlined function
          fn_call->parentStmt->insertBefore(inlined_body);
          fn_call->replace(new Variable(temp_def->sym));
        }
        else {
          //inlined function
          fn_call->parentStmt->insertBefore(inlined_body);
          fn_call->parentStmt->remove();
        }
        //report inlining compiler flag was set of the command-line
        if (report_inlining)
          printf("chapel compiler: reporting inlining, %s function was inlined \n", fn_sym->name);
      }
    }
  }
}

bool InlineFunctions::isCodegened(FnSymbol* fn_sym) {
  //do not inline methods that are not codegened (e.g. prelude)
  ModuleSymbol* mod_sym = fn_sym->paramScope->getModule();
  return (!fn_sym->hasPragma("no codegen") && (mod_sym->modtype != MOD_INTERNAL));
}

DefExpr* InlineFunctions::createTempVariable(Type* type, Expr* init) {
  static int id = 1;
  char* temp_name =  glomstrings(2, "_inline_temp_", intstring(id++));
  DefExpr* temp_def = Symboltable::defineSingleVarDef(temp_name,
                                                      type,
                                                      init,
                                                      VAR_NORMAL,
                                                      VAR_VAR);
  dynamic_cast<VarSymbol*>(temp_def->sym)->noDefaultInit = true;
  return temp_def;
}

bool InlineFunctions::isFormalParamOut(ParamSymbol* p_sym) {
  return ((p_sym->intent == PARAM_INOUT) || (p_sym->intent == PARAM_OUT));
}

bool InlineFunctions::isFormalParamRef(ParamSymbol* p_sym) {
  return (p_sym->intent == PARAM_REF) || dynamic_cast<ClassType*>(p_sym->type);
}

bool InlineFunctions::isTypeVar(ParamSymbol* p_sym) {
  return (p_sym->typeVariable != NULL);
}

Map<BaseAST*,BaseAST*>* InlineFunctions::createFormalToActualArgMappings(CallExpr* fn_call, AList<DefExpr>* formal_params) {
  Expr* curr_arg;
  DefExpr* curr_param;
  AList<Expr>* actual_args = fn_call->argList;

  if (actual_args) {
    curr_arg = actual_args->first();
    curr_param = formal_params->first();
  }
  //go through all the actual arguments
  Map<BaseAST*,BaseAST*>* formal_to_actual_arg_map = new Map<BaseAST*,BaseAST*>();
  while(curr_arg) {
    bool param_ref = isFormalParamRef(dynamic_cast<ParamSymbol*>(curr_param->sym));
    bool param_intent_out = isFormalParamOut(dynamic_cast<ParamSymbol*>(curr_param->sym));
    bool typeVar = isTypeVar(dynamic_cast<ParamSymbol*>(curr_param->sym));
    //do not inline the function call if an argument is a ref to a expression that is no
    //a variable
    Variable* variable;
    if (param_ref || typeVar) {
      variable = dynamic_cast<Variable*>(curr_arg);
      if (!variable) {
        _ok_to_inline = false;
        return NULL;
      }
    }

    //create temporary variable and initialize it with the actual argument
    DefExpr* temp_def;
    if (!param_ref && !typeVar) {
      temp_def = createTempVariable(curr_arg->typeInfo(), curr_arg->copy());
      fn_call->parentStmt->insertBefore(new ExprStmt(temp_def));
      //map variable of param symbol to temp symbol so that when copy is passed the map, it
      //will replace the formal parameter symbol with the temp symbol
      formal_to_actual_arg_map->put(curr_param->sym, temp_def->sym);
    }
    //since a temporary variable was not created, map the actual argument to the formal parameter
    else
      formal_to_actual_arg_map->put(curr_param->sym, variable->var);

      //copy temp back to actual arg if formal param out
    if (param_intent_out)
      if (Variable* v = dynamic_cast<Variable*>(curr_arg))
        fn_call->parentStmt->insertAfter(new ExprStmt(new CallExpr(OP_GETSNORM, new Variable(v->var), new Variable(temp_def->sym))));

    curr_arg = actual_args->next();
    curr_param = formal_params->next();
  }
  return formal_to_actual_arg_map;
}

<|endoftext|>


<commit_before>/*
 * Copyright (C) 2008-2015 The Communi Project
 *
 * This test is free, and not covered by the BSD license. There is no
 * restriction applied to their modification, redistribution, using and so on.
 * You can study them, modify them, use them in your own program - either
 * completely or partially.
 */

#include "ircbuffer.h"
#include "ircmessage.h"
#include <QtTest/QtTest>
#include <QtCore/QRegExp>

class tst_IrcBuffer : public QObject
{
    Q_OBJECT

private slots:
    void testDefaults();
    void testTitleNamePrefix();
    void testSticky();
    void testPersistent();
    void testReceive();
    void testDebug();
};

void tst_IrcBuffer::testDefaults()
{
    IrcBuffer buffer;
    QVERIFY(buffer.title().isEmpty());
    QVERIFY(buffer.name().isEmpty());
    QVERIFY(buffer.prefix().isEmpty());
    QVERIFY(!buffer.isChannel());
    QVERIFY(!buffer.toChannel());
    QVERIFY(!buffer.connection());
    QVERIFY(!buffer.network());
    QVERIFY(!buffer.model());
    QVERIFY(!buffer.isActive());
    QVERIFY(!buffer.isSticky());
    QVERIFY(!buffer.isPersistent());
}

void tst_IrcBuffer::testTitleNamePrefix()
{
    IrcBuffer buffer;

    QSignalSpy titleSpy(&buffer, SIGNAL(titleChanged(QString)));
    QSignalSpy nameSpy(&buffer, SIGNAL(nameChanged(QString)));
    QSignalSpy prefixSpy(&buffer, SIGNAL(prefixChanged(QString)));
    QVERIFY(titleSpy.isValid());
    QVERIFY(nameSpy.isValid());
    QVERIFY(prefixSpy.isValid());

    buffer.setName("name");
    QCOMPARE(buffer.title(), QString("name"));
    QCOMPARE(buffer.name(), QString("name"));
    QCOMPARE(buffer.prefix(), QString());
    QCOMPARE(titleSpy.count(), 1);
    QCOMPARE(titleSpy.last().first().toString(), QString("name"));
    QCOMPARE(nameSpy.count(), 1);
    QCOMPARE(nameSpy.last().first().toString(), QString("name"));
    QCOMPARE(prefixSpy.count(), 0);

    buffer.setPrefix("prefix");
    QCOMPARE(buffer.title(), QString("prefixname"));
    QCOMPARE(buffer.name(), QString("name"));
    QCOMPARE(buffer.prefix(), QString("prefix"));
    QCOMPARE(titleSpy.count(), 2);
    QCOMPARE(titleSpy.last().first().toString(), QString("prefixname"));
    QCOMPARE(nameSpy.count(), 1);
    QCOMPARE(prefixSpy.count(), 1);
    QCOMPARE(prefixSpy.last().first().toString(), QString("prefix"));
}

void tst_IrcBuffer::testSticky()
{
    IrcBuffer buffer;
    QVERIFY(!buffer.isSticky());

    QSignalSpy spy(&buffer, SIGNAL(stickyChanged(bool)));
    QVERIFY(spy.isValid());

    buffer.setSticky(true);
    QVERIFY(buffer.isSticky());
    QCOMPARE(spy.count(), 1);
    QVERIFY(spy.last().last().toBool());

    buffer.setSticky(false);
    QVERIFY(!buffer.isSticky());
    QCOMPARE(spy.count(), 2);
    QVERIFY(!spy.last().last().toBool());
}

void tst_IrcBuffer::testPersistent()
{
    IrcBuffer buffer;
    QVERIFY(!buffer.isPersistent());

    QSignalSpy spy(&buffer, SIGNAL(persistentChanged(bool)));
    QVERIFY(spy.isValid());

    buffer.setPersistent(true);
    QVERIFY(buffer.isPersistent());
    QCOMPARE(spy.count(), 1);
    QVERIFY(spy.last().last().toBool());

    buffer.setPersistent(false);
    QVERIFY(!buffer.isPersistent());
    QCOMPARE(spy.count(), 2);
    QVERIFY(!spy.last().last().toBool());
}

void tst_IrcBuffer::testReceive()
{
    Irc::registerMetaTypes();

    IrcBuffer buffer;

    QSignalSpy spy(&buffer, SIGNAL(messageReceived(IrcMessage*)));
    QVERIFY(spy.isValid());

    buffer.receiveMessage(0);
    QCOMPARE(spy.count(), 0);

    IrcMessage msg(0);
    buffer.receiveMessage(&msg);
    QCOMPARE(spy.count(), 1);
    QCOMPARE(spy.last().at(0).value<IrcMessage*>(), &msg);
}

void tst_IrcBuffer::testDebug()
{
    QString str;
    QDebug dbg(&str);

    dbg << static_cast<IrcBuffer*>(0);
    QCOMPARE(str.trimmed(), QString::fromLatin1("IrcBuffer(0x0)"));
    str.clear();

    IrcBuffer buffer;
    dbg << &buffer;
    QVERIFY(QRegExp("IrcBuffer\\(0x[0-9A-Fa-f]+\\) ").exactMatch(str));
    str.clear();

    buffer.setObjectName("obj");
    dbg << &buffer;
    QVERIFY(QRegExp("IrcBuffer\\(0x[0-9A-Fa-f]+, name=obj\\) ").exactMatch(str));
    str.clear();

    buffer.setName("buf");
    dbg << &buffer;
    QVERIFY(QRegExp("IrcBuffer\\(0x[0-9A-Fa-f]+, name=obj, title=buf\\) ").exactMatch(str));
    str.clear();
}

QTEST_MAIN(tst_IrcBuffer)

#include "tst_ircbuffer.moc"
<commit_msg>Test IrcBuffer::userData<commit_after>/*
 * Copyright (C) 2008-2015 The Communi Project
 *
 * This test is free, and not covered by the BSD license. There is no
 * restriction applied to their modification, redistribution, using and so on.
 * You can study them, modify them, use them in your own program - either
 * completely or partially.
 */

#include "ircbuffer.h"
#include "ircmessage.h"
#include <QtTest/QtTest>
#include <QtCore/QRegExp>

class tst_IrcBuffer : public QObject
{
    Q_OBJECT

private slots:
    void testDefaults();
    void testTitleNamePrefix();
    void testSticky();
    void testPersistent();
    void testReceive();
    void testDebug();
    void testUserData();
};

void tst_IrcBuffer::testDefaults()
{
    IrcBuffer buffer;
    QVERIFY(buffer.title().isEmpty());
    QVERIFY(buffer.name().isEmpty());
    QVERIFY(buffer.prefix().isEmpty());
    QVERIFY(!buffer.isChannel());
    QVERIFY(!buffer.toChannel());
    QVERIFY(!buffer.connection());
    QVERIFY(!buffer.network());
    QVERIFY(!buffer.model());
    QVERIFY(!buffer.isActive());
    QVERIFY(!buffer.isSticky());
    QVERIFY(!buffer.isPersistent());
    QVERIFY(buffer.userData().isEmpty());
}

void tst_IrcBuffer::testTitleNamePrefix()
{
    IrcBuffer buffer;

    QSignalSpy titleSpy(&buffer, SIGNAL(titleChanged(QString)));
    QSignalSpy nameSpy(&buffer, SIGNAL(nameChanged(QString)));
    QSignalSpy prefixSpy(&buffer, SIGNAL(prefixChanged(QString)));
    QVERIFY(titleSpy.isValid());
    QVERIFY(nameSpy.isValid());
    QVERIFY(prefixSpy.isValid());

    buffer.setName("name");
    QCOMPARE(buffer.title(), QString("name"));
    QCOMPARE(buffer.name(), QString("name"));
    QCOMPARE(buffer.prefix(), QString());
    QCOMPARE(titleSpy.count(), 1);
    QCOMPARE(titleSpy.last().first().toString(), QString("name"));
    QCOMPARE(nameSpy.count(), 1);
    QCOMPARE(nameSpy.last().first().toString(), QString("name"));
    QCOMPARE(prefixSpy.count(), 0);

    buffer.setPrefix("prefix");
    QCOMPARE(buffer.title(), QString("prefixname"));
    QCOMPARE(buffer.name(), QString("name"));
    QCOMPARE(buffer.prefix(), QString("prefix"));
    QCOMPARE(titleSpy.count(), 2);
    QCOMPARE(titleSpy.last().first().toString(), QString("prefixname"));
    QCOMPARE(nameSpy.count(), 1);
    QCOMPARE(prefixSpy.count(), 1);
    QCOMPARE(prefixSpy.last().first().toString(), QString("prefix"));
}

void tst_IrcBuffer::testSticky()
{
    IrcBuffer buffer;
    QVERIFY(!buffer.isSticky());

    QSignalSpy spy(&buffer, SIGNAL(stickyChanged(bool)));
    QVERIFY(spy.isValid());

    buffer.setSticky(true);
    QVERIFY(buffer.isSticky());
    QCOMPARE(spy.count(), 1);
    QVERIFY(spy.last().last().toBool());

    buffer.setSticky(false);
    QVERIFY(!buffer.isSticky());
    QCOMPARE(spy.count(), 2);
    QVERIFY(!spy.last().last().toBool());
}

void tst_IrcBuffer::testPersistent()
{
    IrcBuffer buffer;
    QVERIFY(!buffer.isPersistent());

    QSignalSpy spy(&buffer, SIGNAL(persistentChanged(bool)));
    QVERIFY(spy.isValid());

    buffer.setPersistent(true);
    QVERIFY(buffer.isPersistent());
    QCOMPARE(spy.count(), 1);
    QVERIFY(spy.last().last().toBool());

    buffer.setPersistent(false);
    QVERIFY(!buffer.isPersistent());
    QCOMPARE(spy.count(), 2);
    QVERIFY(!spy.last().last().toBool());
}

void tst_IrcBuffer::testReceive()
{
    Irc::registerMetaTypes();

    IrcBuffer buffer;

    QSignalSpy spy(&buffer, SIGNAL(messageReceived(IrcMessage*)));
    QVERIFY(spy.isValid());

    buffer.receiveMessage(0);
    QCOMPARE(spy.count(), 0);

    IrcMessage msg(0);
    buffer.receiveMessage(&msg);
    QCOMPARE(spy.count(), 1);
    QCOMPARE(spy.last().at(0).value<IrcMessage*>(), &msg);
}

void tst_IrcBuffer::testDebug()
{
    QString str;
    QDebug dbg(&str);

    dbg << static_cast<IrcBuffer*>(0);
    QCOMPARE(str.trimmed(), QString::fromLatin1("IrcBuffer(0x0)"));
    str.clear();

    IrcBuffer buffer;
    dbg << &buffer;
    QVERIFY(QRegExp("IrcBuffer\\(0x[0-9A-Fa-f]+\\) ").exactMatch(str));
    str.clear();

    buffer.setObjectName("obj");
    dbg << &buffer;
    QVERIFY(QRegExp("IrcBuffer\\(0x[0-9A-Fa-f]+, name=obj\\) ").exactMatch(str));
    str.clear();

    buffer.setName("buf");
    dbg << &buffer;
    QVERIFY(QRegExp("IrcBuffer\\(0x[0-9A-Fa-f]+, name=obj, title=buf\\) ").exactMatch(str));
    str.clear();
}

void tst_IrcBuffer::testUserData()
{
    QVariantMap ud;
    ud.insert("foo", "bar");

    IrcBuffer buffer;
    buffer.setUserData(ud);
    QCOMPARE(buffer.userData(), ud);

    buffer.setUserData(QVariantMap());
    QVERIFY(buffer.userData().isEmpty());
}

QTEST_MAIN(tst_IrcBuffer)

#include "tst_ircbuffer.moc"
<|endoftext|>


<commit_before>/*
 * =====================================================================================
 *
 *       Filename:  gaussian.cpp
 *
 *    Description:
 *
 *        Version:  1.0
 *        Created:  11/28/2015  9:53:55 PM
 *       Revision:  none
 *       Compiler:  gcc
 *
 *         Author:  Gabe Jespersen (), gzackwebs@tfwno.gf
 *   Organization:
 *
 * =====================================================================================
 */

#include <cmath>
#include <cstdlib>
#include <ctime>
#include <iostream>

#include "gaussian.h"

using namespace std;

double gaussian(int base, int standardDeviation)
{
    //uses box-muller transformation or something
    double u1 = (1.0+rand())/(1.0+RAND_MAX);//generating 2 linearly random numbers between 1 & 0
    double u2 = (1.0+rand())/(1.0+RAND_MAX);

    double answer = cos(8.*atan(1.)*u2)*sqrt(-2.*log(u1));//uses the box-muller transformation
    answer *= standardDeviation;//multiplies the value by the standard deviation
    answer += base;//adds the base
    return answer;
}
<commit_msg>added comments to explain stuff<commit_after>/*
 * =====================================================================================
 *
 *       Filename:  gaussian.cpp
 *
 *    Description:
 *
 *        Version:  1.0
 *        Created:  11/28/2015  9:53:55 PM
 *       Revision:  none
 *       Compiler:  gcc
 *
 *         Author:  Gabe Jespersen (), gzackwebs@tfwno.gf
 *   Organization:
 *
 * =====================================================================================
 */

#include <cmath>
#include <cstdlib>
#include <ctime>
#include <iostream>

#include "gaussian.h"

using namespace std;

double gaussian(int base, int standardDeviation)
{
    //uses box-muller transformation or something
    double u1 = (1.0+rand())/(1.0+RAND_MAX);//generating 2 linearly random numbers between 1 & 0
    double u2 = (1.0+rand())/(1.0+RAND_MAX);

    double answer = cos(8.0*atan(1.0)*u2)*sqrt(-2.0*log(u1));//uses the box-
                                                             //muller transfor-
                                                             //mation

                                                             //using decimals
                                                             //to force it to
                                                             //be a float
    answer *= standardDeviation;//multiplies the value by the standard deviation
    answer += base;//adds the base
    return answer;
}
<|endoftext|>