<commit_before>/******************************************************************************
*       SOFA, Simulation Open-Framework Architecture, version 1.0 beta 3      *
*                (c) 2006-2008 MGH, INRIA, USTL, UJF, CNRS                    *
*                                                                             *
* This library is free software; you can redistribute it and/or modify it     *
* under the terms of the GNU Lesser General Public License as published by    *
* the Free Software Foundation; either version 2.1 of the License, or (at     *
* your option) any later version.                                             *
*                                                                             *
* This library is distributed in the hope that it will be useful, but WITHOUT *
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or       *
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License *
* for more details.                                                           *
*                                                                             *
* You should have received a copy of the GNU Lesser General Public License    *
* along with this library; if not, write to the Free Software Foundation,     *
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301 USA.          *
*******************************************************************************
*                               SOFA :: Modules                               *
*                                                                             *
* Authors: The SOFA Team and external contributors (see Authors.txt)          *
*                                                                             *
* Contact information: contact@sofa-framework.org                             *
******************************************************************************/
#ifndef SOFA_COMPONENT_CONSTRAINT_LINEARMOVEMENTCONSTRAINT_INL
#define SOFA_COMPONENT_CONSTRAINT_LINEARMOVEMENTCONSTRAINT_INL

#include <sofa/core/componentmodel/behavior/Constraint.inl>
#include <sofa/component/constraint/LinearMovementConstraint.h>
#include <sofa/helper/gl/template.h>
#include <sofa/defaulttype/RigidTypes.h>
#include <iostream>

#include <sofa/component/topology/PointSubset.h>

using std::cerr;
using std::endl;

namespace sofa
{

namespace component
{

namespace constraint
{

using namespace core::componentmodel::topology;

using namespace sofa::defaulttype;
using namespace sofa::helper;
using namespace sofa::core::componentmodel::behavior;

// Define TestNewPointFunction
template< class DataTypes>
bool LinearMovementConstraint<DataTypes>::FCTestNewPointFunction(int /*nbPoints*/, void* param, const sofa::helper::vector< unsigned int > &, const sofa::helper::vector< double >& )
{
    LinearMovementConstraint<DataTypes> *fc= (LinearMovementConstraint<DataTypes> *)param;
    if (fc)
    {
        return true;
    }
    else
    {
        return false;
    }
}

// Define RemovalFunction
template< class DataTypes>
void LinearMovementConstraint<DataTypes>::FCRemovalFunction(int pointIndex, void* param)
{
    LinearMovementConstraint<DataTypes> *fc= (LinearMovementConstraint<DataTypes> *)param;
    if (fc)
    {
        fc->removeIndex((unsigned int) pointIndex);
    }
    return;
}

template <class DataTypes>
LinearMovementConstraint<DataTypes>::LinearMovementConstraint()
    : core::componentmodel::behavior::Constraint<DataTypes>(NULL)
    , m_indices( initData(&m_indices,"indices","Indices of the constrained points") )
    , m_keyTimes(  initData(&m_keyTimes,"keyTimes","key times for the movements") )
    , m_keyMovements(  initData(&m_keyMovements,"movements","movements corresponding to the key times") )
{
    // default to indice 0
    m_indices.beginEdit()->push_back(0);
    m_indices.endEdit();

    //default valueEvent to 0
    m_keyTimes.beginEdit()->push_back( 0.0 );
    m_keyTimes.endEdit();
    m_keyMovements.beginEdit()->push_back( Deriv() );
    m_keyMovements.endEdit();
}

// Handle topological changes
template <class DataTypes> void LinearMovementConstraint<DataTypes>::handleTopologyChange()
{
    sofa::core::componentmodel::topology::BaseMeshTopology* topology = getContext()->getMeshTopology();

    std::list<const TopologyChange *>::const_iterator itBegin=topology->firstChange();
    std::list<const TopologyChange *>::const_iterator itEnd=topology->lastChange();

    m_indices.beginEdit()->handleTopologyEvents(itBegin,itEnd,this->getMState()->getSize());

}

template <class DataTypes>
LinearMovementConstraint<DataTypes>::~LinearMovementConstraint()
{
}

template <class DataTypes>
void LinearMovementConstraint<DataTypes>::clearIndices()
{
    m_indices.beginEdit()->clear();
    m_indices.endEdit();
}

template <class DataTypes>
void LinearMovementConstraint<DataTypes>::addIndex(unsigned int index)
{
    m_indices.beginEdit()->push_back(index);
    m_indices.endEdit();
}

template <class DataTypes>
void LinearMovementConstraint<DataTypes>::removeIndex(unsigned int index)
{
    removeValue(*m_indices.beginEdit(),index);
    m_indices.endEdit();
}

template <class DataTypes>
void LinearMovementConstraint<DataTypes>::clearKeyMovements()
{
    m_keyTimes.beginEdit()->clear();
    m_keyTimes.endEdit();
    m_keyMovements.beginEdit()->clear();
    m_keyMovements.endEdit();
}

template <class DataTypes>
void LinearMovementConstraint<DataTypes>::addKeyMovement(Real time, Deriv movement)
{
    m_keyTimes.beginEdit()->push_back( time );
    m_keyTimes.endEdit();
    m_keyMovements.beginEdit()->push_back( movement );
    m_keyMovements.endEdit();
}

// -- Constraint interface

template <class DataTypes>
void LinearMovementConstraint<DataTypes>::init()
{
    this->core::componentmodel::behavior::Constraint<DataTypes>::init();

    // Initialize functions and parameters
    topology::PointSubset my_subset = m_indices.getValue();

    my_subset.setTestFunction(FCTestNewPointFunction);
    my_subset.setRemovalFunction(FCRemovalFunction);

    my_subset.setTestParameter( (void *) this );
    my_subset.setRemovalParameter( (void *) this );

    x0.resize(0);
    nextM = prevM = Deriv();

}

template <class DataTypes>
void LinearMovementConstraint<DataTypes>::projectResponse(VecDeriv& )
{

}

template <class DataTypes>
void LinearMovementConstraint<DataTypes>::projectVelocity(VecDeriv& dx)
{
    Real cT = (Real) this->getContext()->getTime();
    if(cT >= *m_keyTimes.getValue().begin() && cT <= *m_keyTimes.getValue().rbegin())
    {
        const SetIndexArray & indices = m_indices.getValue().getArray();

        bool finished=false;

        typename helper::vector<Real>::const_iterator it_t = m_keyTimes.getValue().begin();
        typename VecDeriv::const_iterator it_m = m_keyMovements.getValue().begin();

        //WARNING : we consider that the key-events are in chronological order
        //here we search between which keyTimes we are, to know which are the motion to interpolate
        while( it_t != m_keyTimes.getValue().end() && !finished)
        {
            if( *it_t <= cT)
            {
                prevT = *it_t;
                prevM = *it_m;
            }
            else
            {
                nextT = *it_t;
                nextM = *it_m;
                finished = true;
            }
            it_t++;
            it_m++;
        }

        //if we found 2 keyTimes, we have to interpolate a velocity (linear interpolation)
        if(finished)
        {
            Real dTsimu = (Real) this->getContext()->getDt();
            Real dt = (cT - prevT) / (nextT - prevT);
            Deriv m= (nextM-prevM)*dt;
            Deriv mPrev= (nextM-prevM)*(((cT-dTsimu) - prevT) / (nextT - prevT));

            //set the motion to the Dofs
            for (SetIndexArray::const_iterator it = indices.begin(); it != indices.end(); ++it)
            {
                dx[*it] = (m - mPrev) * (1/dTsimu);
            }
        }
    }
}

template <class DataTypes>
void LinearMovementConstraint<DataTypes>::projectPosition(VecCoord& x)
{
    Real cT = (Real) this->getContext()->getTime();

    //initialize initial Dofs positions, if it's not done
    if (x0.size() == 0)
    {
        const SetIndexArray & indices = m_indices.getValue().getArray();
        x0.resize( x.size() );
        for (SetIndexArray::const_iterator it = indices.begin(); it != indices.end(); ++it)
            x0[*it] = x[*it];
    }

    //if we found 2 keyTimes, we have to interpolate a position (linear interpolation)
    if(cT >= *m_keyTimes.getValue().begin() && cT <= *m_keyTimes.getValue().rbegin() && nextT!=prevT)
    {
        const SetIndexArray & indices = m_indices.getValue().getArray();

        Real dt = (cT - prevT) / (nextT - prevT);
        Deriv m = prevM + (nextM-prevM)*dt;

        //set the motion to the Dofs
        for (SetIndexArray::const_iterator it = indices.begin(); it != indices.end(); ++it)
        {
            x[*it] = x0[*it] + m ;
        }
    }
}

//display the path the constrained dofs will go through
template <class DataTypes>
void LinearMovementConstraint<DataTypes>::draw()
{
    if (!getContext()->
        getShowBehaviorModels()) return;
    glDisable (GL_LIGHTING);
    glPointSize(10);
    glColor4f (1,0.5,0.5,1);
    glBegin (GL_LINES);
    const SetIndexArray & indices = m_indices.getValue().getArray();
    for (unsigned int i=0 ; i<m_keyMovements.getValue().size()-1 ; i++)
    {
        for (SetIndexArray::const_iterator it = indices.begin(); it != indices.end(); ++it)
        {
            gl::glVertexT(x0[*it]+m_keyMovements.getValue()[i]);
            gl::glVertexT(x0[*it]+m_keyMovements.getValue()[i+1]);
        }
    }
    glEnd();
}

// Specialization for rigids
template <>
void LinearMovementConstraint<Rigid3dTypes >::draw();
template <>
void LinearMovementConstraint<Rigid3fTypes >::draw();

} // namespace constraint

} // namespace component

} // namespace sofa

#endif

<commit_msg>r2787/sofa-dev : FIX: missing include<commit_after>/******************************************************************************
*       SOFA, Simulation Open-Framework Architecture, version 1.0 beta 3      *
*                (c) 2006-2008 MGH, INRIA, USTL, UJF, CNRS                    *
*                                                                             *
* This library is free software; you can redistribute it and/or modify it     *
* under the terms of the GNU Lesser General Public License as published by    *
* the Free Software Foundation; either version 2.1 of the License, or (at     *
* your option) any later version.                                             *
*                                                                             *
* This library is distributed in the hope that it will be useful, but WITHOUT *
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or       *
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License *
* for more details.                                                           *
*                                                                             *
* You should have received a copy of the GNU Lesser General Public License    *
* along with this library; if not, write to the Free Software Foundation,     *
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301 USA.          *
*******************************************************************************
*                               SOFA :: Modules                               *
*                                                                             *
* Authors: The SOFA Team and external contributors (see Authors.txt)          *
*                                                                             *
* Contact information: contact@sofa-framework.org                             *
******************************************************************************/
#ifndef SOFA_COMPONENT_CONSTRAINT_LINEARMOVEMENTCONSTRAINT_INL
#define SOFA_COMPONENT_CONSTRAINT_LINEARMOVEMENTCONSTRAINT_INL

#include <sofa/core/componentmodel/behavior/Constraint.inl>
#include <sofa/core/componentmodel/topology/BaseMeshTopology.h>
#include <sofa/component/constraint/LinearMovementConstraint.h>
#include <sofa/helper/gl/template.h>
#include <sofa/defaulttype/RigidTypes.h>
#include <iostream>

#include <sofa/component/topology/PointSubset.h>

using std::cerr;
using std::endl;

namespace sofa
{

namespace component
{

namespace constraint
{

using namespace core::componentmodel::topology;

using namespace sofa::defaulttype;
using namespace sofa::helper;
using namespace sofa::core::componentmodel::behavior;

// Define TestNewPointFunction
template< class DataTypes>
bool LinearMovementConstraint<DataTypes>::FCTestNewPointFunction(int /*nbPoints*/, void* param, const sofa::helper::vector< unsigned int > &, const sofa::helper::vector< double >& )
{
    LinearMovementConstraint<DataTypes> *fc= (LinearMovementConstraint<DataTypes> *)param;
    if (fc)
    {
        return true;
    }
    else
    {
        return false;
    }
}

// Define RemovalFunction
template< class DataTypes>
void LinearMovementConstraint<DataTypes>::FCRemovalFunction(int pointIndex, void* param)
{
    LinearMovementConstraint<DataTypes> *fc= (LinearMovementConstraint<DataTypes> *)param;
    if (fc)
    {
        fc->removeIndex((unsigned int) pointIndex);
    }
    return;
}

template <class DataTypes>
LinearMovementConstraint<DataTypes>::LinearMovementConstraint()
    : core::componentmodel::behavior::Constraint<DataTypes>(NULL)
    , m_indices( initData(&m_indices,"indices","Indices of the constrained points") )
    , m_keyTimes(  initData(&m_keyTimes,"keyTimes","key times for the movements") )
    , m_keyMovements(  initData(&m_keyMovements,"movements","movements corresponding to the key times") )
{
    // default to indice 0
    m_indices.beginEdit()->push_back(0);
    m_indices.endEdit();

    //default valueEvent to 0
    m_keyTimes.beginEdit()->push_back( 0.0 );
    m_keyTimes.endEdit();
    m_keyMovements.beginEdit()->push_back( Deriv() );
    m_keyMovements.endEdit();
}

// Handle topological changes
template <class DataTypes> void LinearMovementConstraint<DataTypes>::handleTopologyChange()
{
    sofa::core::componentmodel::topology::BaseMeshTopology* topology = getContext()->getMeshTopology();

    std::list<const TopologyChange *>::const_iterator itBegin=topology->firstChange();
    std::list<const TopologyChange *>::const_iterator itEnd=topology->lastChange();

    m_indices.beginEdit()->handleTopologyEvents(itBegin,itEnd,this->getMState()->getSize());

}

template <class DataTypes>
LinearMovementConstraint<DataTypes>::~LinearMovementConstraint()
{
}

template <class DataTypes>
void LinearMovementConstraint<DataTypes>::clearIndices()
{
    m_indices.beginEdit()->clear();
    m_indices.endEdit();
}

template <class DataTypes>
void LinearMovementConstraint<DataTypes>::addIndex(unsigned int index)
{
    m_indices.beginEdit()->push_back(index);
    m_indices.endEdit();
}

template <class DataTypes>
void LinearMovementConstraint<DataTypes>::removeIndex(unsigned int index)
{
    removeValue(*m_indices.beginEdit(),index);
    m_indices.endEdit();
}

template <class DataTypes>
void LinearMovementConstraint<DataTypes>::clearKeyMovements()
{
    m_keyTimes.beginEdit()->clear();
    m_keyTimes.endEdit();
    m_keyMovements.beginEdit()->clear();
    m_keyMovements.endEdit();
}

template <class DataTypes>
void LinearMovementConstraint<DataTypes>::addKeyMovement(Real time, Deriv movement)
{
    m_keyTimes.beginEdit()->push_back( time );
    m_keyTimes.endEdit();
    m_keyMovements.beginEdit()->push_back( movement );
    m_keyMovements.endEdit();
}

// -- Constraint interface

template <class DataTypes>
void LinearMovementConstraint<DataTypes>::init()
{
    this->core::componentmodel::behavior::Constraint<DataTypes>::init();

    // Initialize functions and parameters
    topology::PointSubset my_subset = m_indices.getValue();

    my_subset.setTestFunction(FCTestNewPointFunction);
    my_subset.setRemovalFunction(FCRemovalFunction);

    my_subset.setTestParameter( (void *) this );
    my_subset.setRemovalParameter( (void *) this );

    x0.resize(0);
    nextM = prevM = Deriv();

}

template <class DataTypes>
void LinearMovementConstraint<DataTypes>::projectResponse(VecDeriv& )
{

}

template <class DataTypes>
void LinearMovementConstraint<DataTypes>::projectVelocity(VecDeriv& dx)
{
    Real cT = (Real) this->getContext()->getTime();
    if(cT >= *m_keyTimes.getValue().begin() && cT <= *m_keyTimes.getValue().rbegin())
    {
        const SetIndexArray & indices = m_indices.getValue().getArray();

        bool finished=false;

        typename helper::vector<Real>::const_iterator it_t = m_keyTimes.getValue().begin();
        typename VecDeriv::const_iterator it_m = m_keyMovements.getValue().begin();

        //WARNING : we consider that the key-events are in chronological order
        //here we search between which keyTimes we are, to know which are the motion to interpolate
        while( it_t != m_keyTimes.getValue().end() && !finished)
        {
            if( *it_t <= cT)
            {
                prevT = *it_t;
                prevM = *it_m;
            }
            else
            {
                nextT = *it_t;
                nextM = *it_m;
                finished = true;
            }
            it_t++;
            it_m++;
        }

        //if we found 2 keyTimes, we have to interpolate a velocity (linear interpolation)
        if(finished)
        {
            Real dTsimu = (Real) this->getContext()->getDt();
            Real dt = (cT - prevT) / (nextT - prevT);
            Deriv m= (nextM-prevM)*dt;
            Deriv mPrev= (nextM-prevM)*(((cT-dTsimu) - prevT) / (nextT - prevT));

            //set the motion to the Dofs
            for (SetIndexArray::const_iterator it = indices.begin(); it != indices.end(); ++it)
            {
                dx[*it] = (m - mPrev) * (1/dTsimu);
            }
        }
    }
}

template <class DataTypes>
void LinearMovementConstraint<DataTypes>::projectPosition(VecCoord& x)
{
    Real cT = (Real) this->getContext()->getTime();

    //initialize initial Dofs positions, if it's not done
    if (x0.size() == 0)
    {
        const SetIndexArray & indices = m_indices.getValue().getArray();
        x0.resize( x.size() );
        for (SetIndexArray::const_iterator it = indices.begin(); it != indices.end(); ++it)
            x0[*it] = x[*it];
    }

    //if we found 2 keyTimes, we have to interpolate a position (linear interpolation)
    if(cT >= *m_keyTimes.getValue().begin() && cT <= *m_keyTimes.getValue().rbegin() && nextT!=prevT)
    {
        const SetIndexArray & indices = m_indices.getValue().getArray();

        Real dt = (cT - prevT) / (nextT - prevT);
        Deriv m = prevM + (nextM-prevM)*dt;

        //set the motion to the Dofs
        for (SetIndexArray::const_iterator it = indices.begin(); it != indices.end(); ++it)
        {
            x[*it] = x0[*it] + m ;
        }
    }
}

//display the path the constrained dofs will go through
template <class DataTypes>
void LinearMovementConstraint<DataTypes>::draw()
{
    if (!getContext()->
        getShowBehaviorModels()) return;
    glDisable (GL_LIGHTING);
    glPointSize(10);
    glColor4f (1,0.5,0.5,1);
    glBegin (GL_LINES);
    const SetIndexArray & indices = m_indices.getValue().getArray();
    for (unsigned int i=0 ; i<m_keyMovements.getValue().size()-1 ; i++)
    {
        for (SetIndexArray::const_iterator it = indices.begin(); it != indices.end(); ++it)
        {
            gl::glVertexT(x0[*it]+m_keyMovements.getValue()[i]);
            gl::glVertexT(x0[*it]+m_keyMovements.getValue()[i+1]);
        }
    }
    glEnd();
}

// Specialization for rigids
template <>
void LinearMovementConstraint<Rigid3dTypes >::draw();
template <>
void LinearMovementConstraint<Rigid3fTypes >::draw();

} // namespace constraint

} // namespace component

} // namespace sofa

#endif

<|endoftext|>


<commit_before>#include "bloomierFilter.h"

BloomierFilter::BloomierFilter(size_t pHashSeed, std::map<size_t, size_t> pKeyDict, size_t pM, size_t pK, size_t pQ){
	mHashSeed = pHashSeed;
	mM = pM;;
	mK = pK;
	mQ = pQ;
	mKeyDict = pKeyDict;
	mBloomierHash = new BloomierHash(pHashSeed, pM, pK, pQ);
	mOrderAndMatchFinder = new OrderAndMatchFinder(pHashSeed, pKeyDict, pM, pK, pQ);
	vsize_t orderAndMatch = mOrderAndMatchFinder.find(); // datatype?
	mByteSize = this->getByteSize(pQ);
	mTable = new vvsize_t(pM, vsize_t(mByteSize, 0));
    mValueTable = new vsize_t(pM, 0);
    this->create(pKeyDict, orderAndMatch);
}

BloomierFilter::~BloomierFilter(){

}

vvsize_t* BloomierFilter::getTable() {
	return mTable;
}

void BloomierFilter::setTable(vvsize_t* pTable) {
	mTable = pTable;
}

vsize_t* BloomierFilter::getValueTable() {
	return mValueTablel
}
void BloomierFilter::setValueTable(vsize_t* pTable) {
	mValueTable = pTable;
}

size_t BloomierFilter::xorOperation(size_t pValue, size_t pM, vsize_t pNeighbors) {

}
vsize_t BloomierFilter::get(size_t pKey) {

}
void BloomierFilter::set(size_t pKey, size_t pValue) {

}

void BloomierFilter::create(std::map<size_t, size_t> pAssignment, OrderAndMatchFinder pPiTau) {

}

std::string BloomierFilter::tableToString() {

}
std::pair<vsize_t, vsize_t > stringToTable(std::string pString) {

}

size_t BloomierFilter::getByteSize(size_t pQ) {

}

void BloomierFilter::byteArrayXor(vsize_t* pResult, vsize_t pInput) {
	size_t length = min(pResult->size(), pInput->size());
	for (size_t i = 0; i < length; ++i) {
		(*pResult)[i] = (*pResult)[i] ^ (*pInput)[i];
	}
}<commit_msg>Changed datatyps and added implementation of function xorOperation<commit_after>#include "bloomierFilter.h"

BloomierFilter::BloomierFilter(size_t pHashSeed, std::map<size_t, size_t> pKeyDict, size_t pM, size_t pK, size_t pQ){
	mHashSeed = pHashSeed;
	mM = pM;;
	mK = pK;
	mQ = pQ;
	mKeyDict = pKeyDict;
	mBloomierHash = new BloomierHash(pHashSeed, pM, pK, pQ);
	mOrderAndMatchFinder = new OrderAndMatchFinder(pHashSeed, pKeyDict, pM, pK, pQ);
	vsize_t orderAndMatch = mOrderAndMatchFinder.find(); // datatype?
	mByteSize = this->getByteSize(pQ);
	mTable = new vvsize_t(pM, vsize_t(mByteSize, 0));
    mValueTable = new vsize_t(pM, 0);
    this->create(pKeyDict, orderAndMatch);
}

BloomierFilter::~BloomierFilter(){

}

vvsize_t* BloomierFilter::getTable() {
	return mTable;
}

void BloomierFilter::setTable(vvsize_t* pTable) {
	mTable = pTable;
}

vsize_t* BloomierFilter::getValueTable() {
	return mValueTablel
}
void BloomierFilter::setValueTable(vsize_t* pTable) {
	mValueTable = pTable;
}

vsize_t* BloomierFilter::xorOperation(vsize_t* pValue, vsize_t* pM, vsize_t* pNeighbors) {
	this->byteArrayXor(pValue, pM);
	for (auto it = pNeighbors->begin(); it != pNeighbors->end(); ++it) {
		this->byteArrayXor(pValue, mTable[(*it)]);
	}
	return pValue;
}
vsize_t BloomierFilter::get(size_t pKey) {

}
void BloomierFilter::set(size_t pKey, size_t pValue) {

}

void BloomierFilter::create(std::map<size_t, size_t> pAssignment, OrderAndMatchFinder pPiTau) {

}

std::string BloomierFilter::tableToString() {

}
std::pair<vsize_t, vsize_t > stringToTable(std::string pString) {

}

size_t BloomierFilter::getByteSize(size_t pQ) {

}

void BloomierFilter::byteArrayXor(vsize_t* pResult, vsize_t* pInput) {
	size_t length = min(pResult->size(), pInput->size());
	for (size_t i = 0; i < length; ++i) {
		(*pResult)[i] = (*pResult)[i] ^ (*pInput)[i];
	}
}<|endoftext|>


<commit_before>#include <chrono>
#include <cstdlib>
#include <fstream>
#include <iostream>
#include <math.h>
#include <stdexcept>
#include <string>
#include <thread>
#include <vector>

#include "adios2.h"
#include "mpi.h"

#include "decomp.h"
#include "processConfig.h"
#include "settings.h"
#include "stream.h"

int main(int argc, char *argv[])
{
    MPI_Init(&argc, &argv);

    Settings settings;
    if (!settings.processArguments(argc, argv, MPI_COMM_WORLD) &&
        !settings.extraArgumentChecks())
    {
        adios2::ADIOS adios;
        if (settings.adiosConfigFileName.empty())
        {
            if (!settings.myRank && settings.verbose)
            {
                std::cout << "Use ADIOS without XML configuration "
                          << std::endl;
            }
            adios = adios2::ADIOS(settings.appComm, adios2::DebugON);
        }
        else
        {
            if (!settings.myRank && settings.verbose)
            {
                std::cout << "Use ADIOS xml file "
                          << settings.adiosConfigFileName << std::endl;
            }
            adios = adios2::ADIOS(settings.adiosConfigFileName,
                                  settings.appComm, adios2::DebugON);
        }
        Config cfg;
        size_t currentConfigLineNumber = 0;

        try
        {
            cfg = processConfig(settings, &currentConfigLineNumber);
        }
        catch (std::invalid_argument &e) // config file processing errors
        {
            if (!settings.myRank)
            {
                if (!currentConfigLineNumber)
                {
                    std::cout << "Config file error: " << e.what() << std::endl;
                }
                else
                {
                    std::cout << "Config file error in line "
                              << currentConfigLineNumber << ": " << e.what()
                              << std::endl;
                }
            }
            MPI_Abort(settings.appComm, -1);
        }

        try
        {
            /* writing to one stream using two groups is not supported.
             * FIXME: we need to check for this condition and raise error
             */
            /* 1. Assign stream names with group names that appear in
               commands */
            // map of <streamName, groupName>
            std::map<std::string, std::string> groupMap;
            // a vector of streams in the order they appear
            std::vector<std::pair<std::string, Operation>> streamsInOrder;
            for (const auto &cmd : cfg.commands)
            {
                if (cmd->op == Operation::Write)
                {
                    auto cmdW = dynamic_cast<CommandWrite *>(cmd.get());
                    groupMap[cmdW->streamName] = cmdW->groupName;
                    streamsInOrder.push_back(
                        std::make_pair(cmdW->streamName, Operation::Write));
                }
                else if (cmd->op == Operation::Read)
                {
                    auto cmdR = dynamic_cast<CommandRead *>(cmd.get());
                    groupMap[cmdR->streamName] = cmdR->groupName;
                    streamsInOrder.push_back(
                        std::make_pair(cmdR->streamName, Operation::Read));
                }
            }

            std::map<std::string, std::shared_ptr<ioGroup>> ioMap;

            /* 2. Declare/define groups and open streams in the order they
             * appear */
            std::map<std::string, std::shared_ptr<Stream>> readStreamMap;
            std::map<std::string, std::shared_ptr<Stream>> writeStreamMap;

            for (const auto &st : streamsInOrder)
            {
                const std::string &streamName = st.first;
                std::shared_ptr<ioGroup> io;
                auto &groupName = groupMap[streamName];
                auto it = ioMap.find(groupName);
                if (it == ioMap.end())
                {
                    io = createGroup(groupName, settings.iolib, adios);
                    ioMap[groupName] = io;
                }
                else
                {
                    io = it->second;
                }
                const bool isWrite = (st.second == Operation::Write);
                if (isWrite)
                {
                    auto it = writeStreamMap.find(streamName);
                    if (it == writeStreamMap.end())
                    {
                        std::shared_ptr<Stream> writer =
                            openStream(streamName, io, adios2::Mode::Write,
                                       settings.iolib, settings.appComm);
                        writeStreamMap[streamName] = writer;
                    }
                }
                else /* Read */
                {
                    auto it = readStreamMap.find(streamName);
                    if (it == readStreamMap.end())
                    {
                        std::shared_ptr<Stream> reader =
                            openStream(streamName, io, adios2::Mode::Read,
                                       settings.iolib, settings.appComm);
                        readStreamMap[streamName] = reader;
                    }
                }
            }

            /* Execute commands */
            bool exitLoop = false;
            size_t step = 1;
            while (!exitLoop)
            {
                if (!settings.myRank)
                {
                    std::cout << "Step " << step << ": " << std::endl;
                }
                for (const auto cmd : cfg.commands)
                {
                    if (!cmd->conditionalStream.empty() &&
                        cfg.condMap.at(cmd->conditionalStream) !=
                            adios2::StepStatus::OK)
                    {
                        if (!settings.myRank && settings.verbose)
                        {
                            std::cout << "    Skip command because of status "
                                         "of stream "
                                      << cmd->conditionalStream << std::endl;
                        }
                        continue;
                    }

                    switch (cmd->op)
                    {
                    case Operation::Sleep:
                    {
                        auto cmdS =
                            dynamic_cast<const CommandSleep *>(cmd.get());
                        if (!settings.myRank && settings.verbose)
                        {
                            double t = static_cast<double>(cmdS->sleepTime_us) /
                                       1000000.0;
                            std::cout << "    Sleep for " << t << "  seconds "
                                      << std::endl;
                        }
                        std::this_thread::sleep_for(
                            std::chrono::microseconds(cmdS->sleepTime_us));
                        break;
                    }
                    case Operation::Busy:
                    {
                        auto cmdS =
                            dynamic_cast<const CommandBusy *>(cmd.get());
                        std::chrono::high_resolution_clock::time_point start =
                            std::chrono::high_resolution_clock::now();
                        if (!settings.myRank && settings.verbose)
                        {
                            double t = static_cast<double>(cmdS->busyTime_us) /
                                       1000000.0;
                            std::cout << "    Be busy for " << t << "  seconds "
                                      << std::endl;
                        }
                        while (std::chrono::high_resolution_clock::now() <
                               start +
                                   std::chrono::microseconds(cmdS->busyTime_us))
                            ;
                        break;
                    }
                    case Operation::Write:
                    {
                        auto cmdW = dynamic_cast<CommandWrite *>(cmd.get());
                        auto stream = writeStreamMap[cmdW->streamName];
                        // auto io = ioMap[cmdW->groupName];
                        stream->Write(cmdW, cfg, settings, step);
                        break;
                    }
                    case Operation::Read:
                    {
                        auto cmdR = dynamic_cast<CommandRead *>(cmd.get());
                        auto statusIt = cfg.condMap.find(cmdR->streamName);
                        if (statusIt->second == adios2::StepStatus::OK ||
                            statusIt->second == adios2::StepStatus::NotReady)
                        {
                            auto stream = readStreamMap[cmdR->streamName];
                            // auto io = ioMap[cmdR->groupName];
                            adios2::StepStatus status =
                                stream->Read(cmdR, cfg, settings, step);
                            statusIt->second = status;
                            switch (status)
                            {
                            case adios2::StepStatus::OK:
                                break;
                            case adios2::StepStatus::NotReady:
                                if (!settings.myRank && settings.verbose)
                                {
                                    std::cout << "    Nonblocking read status: "
                                                 "Not Ready "
                                              << std::endl;
                                }
                                break;
                            case adios2::StepStatus::EndOfStream:
                            case adios2::StepStatus::OtherError:
                                cfg.stepOverStreams.erase(cmdR->streamName);
                                if (!settings.myRank && settings.verbose)
                                {
                                    std::cout << "    Nonblocking read status: "
                                                 "Terminated "
                                              << std::endl;
                                }
                                break;
                            }
                        }
                        break;
                    }
                    }
                    if (!settings.myRank && settings.verbose)
                    {
                        std::cout << std::endl;
                    }
                }
                if (!cfg.stepOverStreams.size() && step >= cfg.nSteps)
                {
                    exitLoop = true;
                }
                ++step;
            }

            /* Close all streams in order of opening */
            for (const auto &st : streamsInOrder)
            {
                const std::string &streamName = st.first;
                const bool isWrite = (st.second == Operation::Write);
                if (isWrite)
                {
                    auto writerIt = writeStreamMap.find(streamName);
                    if (writerIt != writeStreamMap.end())
                    {
                        auto writer = writeStreamMap[streamName];
                        writerIt->second->Close();
                        writeStreamMap.erase(writerIt);
                    }
                }
                else /* Read */
                {
                    auto readerIt = readStreamMap.find(streamName);
                    if (readerIt != readStreamMap.end())
                    {
                        auto reader = readStreamMap[streamName];
                        readerIt->second->Close();
                        readStreamMap.erase(readerIt);
                    }
                }
            }
        }
        catch (std::exception &e) // config file processing errors
        {
            if (!settings.myRank)
            {
                std::cout << "ADIOS " << e.what() << std::endl;
            }
            MPI_Abort(settings.appComm, -1);
        }
    }
    else
        MPI_Abort (settings.appComm, -1);

    MPI_Finalize();
    return 0;
}
<commit_msg>Replaced MPI_Abort with MPI_Finalize for adios_iotest wherever sensible to avoid large core dumps on the screen. Re-worked if loop to remove unnecessary indentation.<commit_after>#include <chrono>
#include <cstdlib>
#include <fstream>
#include <iostream>
#include <math.h>
#include <stdexcept>
#include <string>
#include <thread>
#include <vector>

#include "adios2.h"
#include "mpi.h"

#include "decomp.h"
#include "processConfig.h"
#include "settings.h"
#include "stream.h"

int main(int argc, char *argv[])
{
    MPI_Init(&argc, &argv);

    Settings settings;

    /* Check input arguments. Quit if something is wrong. */
    if (settings.processArguments(argc, argv, MPI_COMM_WORLD) ||
            settings.extraArgumentChecks())
    {
        MPI_Finalize();
        return 1;
    }

    adios2::ADIOS adios;
    if (settings.adiosConfigFileName.empty())
    {
        if (!settings.myRank && settings.verbose)
        {
            std::cout << "Use ADIOS without XML configuration "
                << std::endl;
        }
        adios = adios2::ADIOS(settings.appComm, adios2::DebugON);
    }
    else
    {
        if (!settings.myRank && settings.verbose)
        {
            std::cout << "Use ADIOS xml file "
                << settings.adiosConfigFileName << std::endl;
        }
        adios = adios2::ADIOS(settings.adiosConfigFileName,
                settings.appComm, adios2::DebugON);
    }
    Config cfg;
    size_t currentConfigLineNumber = 0;

    try
    {
        cfg = processConfig(settings, &currentConfigLineNumber);
    }
    catch (std::invalid_argument &e) // config file processing errors
    {
        if (!settings.myRank)
        {
            if (!currentConfigLineNumber)
            {
                std::cout << "Config file error: " << e.what() << std::endl;
            }
            else
            {
                std::cout << "Config file error in line "
                    << currentConfigLineNumber << ": " << e.what()
                    << std::endl;
            }
        }

        /* Quit calmly */
        MPI_Finalize();
        return 1;
    }

    try
    {
        /* writing to one stream using two groups is not supported.
         * FIXME: we need to check for this condition and raise error
         */
        /* 1. Assign stream names with group names that appear in
           commands */
        // map of <streamName, groupName>
        std::map<std::string, std::string> groupMap;
        // a vector of streams in the order they appear
        std::vector<std::pair<std::string, Operation>> streamsInOrder;
        for (const auto &cmd : cfg.commands)
        {
            if (cmd->op == Operation::Write)
            {
                auto cmdW = dynamic_cast<CommandWrite *>(cmd.get());
                groupMap[cmdW->streamName] = cmdW->groupName;
                streamsInOrder.push_back(
                        std::make_pair(cmdW->streamName, Operation::Write));
            }
            else if (cmd->op == Operation::Read)
            {
                auto cmdR = dynamic_cast<CommandRead *>(cmd.get());
                groupMap[cmdR->streamName] = cmdR->groupName;
                streamsInOrder.push_back(
                        std::make_pair(cmdR->streamName, Operation::Read));
            }
        }

        std::map<std::string, std::shared_ptr<ioGroup>> ioMap;

        /* 2. Declare/define groups and open streams in the order they
         * appear */
        std::map<std::string, std::shared_ptr<Stream>> readStreamMap;
        std::map<std::string, std::shared_ptr<Stream>> writeStreamMap;

        for (const auto &st : streamsInOrder)
        {
            const std::string &streamName = st.first;
            std::shared_ptr<ioGroup> io;
            auto &groupName = groupMap[streamName];
            auto it = ioMap.find(groupName);
            if (it == ioMap.end())
            {
                io = createGroup(groupName, settings.iolib, adios);
                ioMap[groupName] = io;
            }
            else
            {
                io = it->second;
            }
            const bool isWrite = (st.second == Operation::Write);
            if (isWrite)
            {
                auto it = writeStreamMap.find(streamName);
                if (it == writeStreamMap.end())
                {
                    std::shared_ptr<Stream> writer =
                        openStream(streamName, io, adios2::Mode::Write,
                                settings.iolib, settings.appComm);
                    writeStreamMap[streamName] = writer;
                }
            }
            else /* Read */
            {
                auto it = readStreamMap.find(streamName);
                if (it == readStreamMap.end())
                {
                    std::shared_ptr<Stream> reader =
                        openStream(streamName, io, adios2::Mode::Read,
                                settings.iolib, settings.appComm);
                    readStreamMap[streamName] = reader;
                }
            }
        }

        /* Execute commands */
        bool exitLoop = false;
        size_t step = 1;
        while (!exitLoop)
        {
            if (!settings.myRank)
            {
                std::cout << "Step " << step << ": " << std::endl;
            }
            for (const auto cmd : cfg.commands)
            {
                if (!cmd->conditionalStream.empty() &&
                        cfg.condMap.at(cmd->conditionalStream) !=
                        adios2::StepStatus::OK)
                {
                    if (!settings.myRank && settings.verbose)
                    {
                        std::cout << "    Skip command because of status "
                            "of stream "
                            << cmd->conditionalStream << std::endl;
                    }
                    continue;
                }

                switch (cmd->op)
                {
                    case Operation::Sleep:
                        {
                            auto cmdS =
                                dynamic_cast<const CommandSleep *>(cmd.get());
                            if (!settings.myRank && settings.verbose)
                            {
                                double t = static_cast<double>(cmdS->sleepTime_us) /
                                    1000000.0;
                                std::cout << "    Sleep for " << t << "  seconds "
                                    << std::endl;
                            }
                            std::this_thread::sleep_for(
                                    std::chrono::microseconds(cmdS->sleepTime_us));
                            break;
                        }
                    case Operation::Busy:
                        {
                            auto cmdS =
                                dynamic_cast<const CommandBusy *>(cmd.get());
                            std::chrono::high_resolution_clock::time_point start =
                                std::chrono::high_resolution_clock::now();
                            if (!settings.myRank && settings.verbose)
                            {
                                double t = static_cast<double>(cmdS->busyTime_us) /
                                    1000000.0;
                                std::cout << "    Be busy for " << t << "  seconds "
                                    << std::endl;
                            }
                            while (std::chrono::high_resolution_clock::now() <
                                    start +
                                    std::chrono::microseconds(cmdS->busyTime_us))
                                ;
                            break;
                        }
                    case Operation::Write:
                        {
                            auto cmdW = dynamic_cast<CommandWrite *>(cmd.get());
                            auto stream = writeStreamMap[cmdW->streamName];
                            // auto io = ioMap[cmdW->groupName];
                            stream->Write(cmdW, cfg, settings, step);
                            break;
                        }
                    case Operation::Read:
                        {
                            auto cmdR = dynamic_cast<CommandRead *>(cmd.get());
                            auto statusIt = cfg.condMap.find(cmdR->streamName);
                            if (statusIt->second == adios2::StepStatus::OK ||
                                    statusIt->second == adios2::StepStatus::NotReady)
                            {
                                auto stream = readStreamMap[cmdR->streamName];
                                // auto io = ioMap[cmdR->groupName];
                                adios2::StepStatus status =
                                    stream->Read(cmdR, cfg, settings, step);
                                statusIt->second = status;
                                switch (status)
                                {
                                    case adios2::StepStatus::OK:
                                        break;
                                    case adios2::StepStatus::NotReady:
                                        if (!settings.myRank && settings.verbose)
                                        {
                                            std::cout << "    Nonblocking read status: "
                                                "Not Ready "
                                                << std::endl;
                                        }
                                        break;
                                    case adios2::StepStatus::EndOfStream:
                                    case adios2::StepStatus::OtherError:
                                        cfg.stepOverStreams.erase(cmdR->streamName);
                                        if (!settings.myRank && settings.verbose)
                                        {
                                            std::cout << "    Nonblocking read status: "
                                                "Terminated "
                                                << std::endl;
                                        }
                                        break;
                                }
                            }
                            break;
                        }
                }
                if (!settings.myRank && settings.verbose)
                {
                    std::cout << std::endl;
                }
            }
            if (!cfg.stepOverStreams.size() && step >= cfg.nSteps)
            {
                exitLoop = true;
            }
            ++step;
        }

        /* Close all streams in order of opening */
        for (const auto &st : streamsInOrder)
        {
            const std::string &streamName = st.first;
            const bool isWrite = (st.second == Operation::Write);
            if (isWrite)
            {
                auto writerIt = writeStreamMap.find(streamName);
                if (writerIt != writeStreamMap.end())
                {
                    auto writer = writeStreamMap[streamName];
                    writerIt->second->Close();
                    writeStreamMap.erase(writerIt);
                }
            }
            else /* Read */
            {
                auto readerIt = readStreamMap.find(streamName);
                if (readerIt != readStreamMap.end())
                {
                    auto reader = readStreamMap[streamName];
                    readerIt->second->Close();
                    readStreamMap.erase(readerIt);
                }
            }
        }
    }
    catch (std::exception &e) // if some unknown error occurs
    {
        if (!settings.myRank)
        {
            std::cout << "ADIOS " << e.what() << std::endl;
        }

        /* Yell and quit */
        MPI_Abort(settings.appComm, -1);
    }

    MPI_Finalize();
    return 0;
}

<|endoftext|>


<commit_before>/*
 *  Copyright (c) 2020 The WebRTC project authors. All Rights Reserved.
 *
 *  Use of this source code is governed by a BSD-style license
 *  that can be found in the LICENSE file in the root of the source
 *  tree. An additional intellectual property rights grant can be found
 *  in the file PATENTS.  All contributing project authors may
 *  be found in the AUTHORS file in the root of the source tree.
 */

#include "call/version.h"

namespace webrtc {

// The timestamp is always in UTC.
const char* const kSourceTimestamp = "WebRTC source stamp 2020-12-30T04:03:04";

void LoadWebRTCVersionInRegister() {
  // Using volatile to instruct the compiler to not optimize `p` away even
  // if it looks unused.
  const char* volatile p = kSourceTimestamp;
  static_cast<void>(p);
}

}  // namespace webrtc
<commit_msg>Update WebRTC code version (2020-12-31T04:03:29).<commit_after>/*
 *  Copyright (c) 2020 The WebRTC project authors. All Rights Reserved.
 *
 *  Use of this source code is governed by a BSD-style license
 *  that can be found in the LICENSE file in the root of the source
 *  tree. An additional intellectual property rights grant can be found
 *  in the file PATENTS.  All contributing project authors may
 *  be found in the AUTHORS file in the root of the source tree.
 */

#include "call/version.h"

namespace webrtc {

// The timestamp is always in UTC.
const char* const kSourceTimestamp = "WebRTC source stamp 2020-12-31T04:03:29";

void LoadWebRTCVersionInRegister() {
  // Using volatile to instruct the compiler to not optimize `p` away even
  // if it looks unused.
  const char* volatile p = kSourceTimestamp;
  static_cast<void>(p);
}

}  // namespace webrtc
<|endoftext|>


<commit_before>#include <stdint.h>
#include <stdio.h>
#include <fstream>
#include <string>
#include <algorithm>

#include <Cart.h>

Cart::~Cart() {
    delete prg, chr, ram;
}

bool Cart::readFile(std::string romFileName) {
    std::ifstream romFile(romFileName.c_str(), std::ios::binary);

    char header[16];

    // verify header
    romFile.read(header, 16);
    if (header[0] != 'N' ||
        header[1] != 'E' ||
        header[2] != 'S' ||
        header[3] != 0x1A) {
        printf("ERROR: Invalid iNES header\n");
        return false;
    }

    // read header data
    prgLen = header[4];
    chrLen = header[5];
    ramLen = header[8];
    mirroring = MIRROR_HOR;
    if (header[6] & (0x1 << 3)) {
        mirroring = MIRROR_NONE;
    }
    else if (header[6] & 0x1) {
        mirroring = MIRROR_VERT;
    }
    isRamBattery = !!(header[6] & (0x1 << 1));
    isTrainer = !!(header[6] & (0x1 << 2));
    mapperNum = (header[6] >> 4) + (header[7] & 0xF0);
    if (mapperNum != 0) {
        printf("ERROR: Mapper %d not yet supported\n", mapperNum);
        return false;
    }

    // load trainer data
    if (isTrainer) {
        romFile.read((char *)trainer, 512);
    }

    // load program data
    prg = new uint8_t[prgLen * PRG_BANK_SIZE];
    std::fill_n(prg, prgLen * PRG_BANK_SIZE, 0);
    romFile.read((char *)prg, prgLen * PRG_BANK_SIZE);

    // load pattern/character data
    chr = new uint8_t[CHR_BANK_SIZE];
    std::fill_n(chr, CHR_BANK_SIZE, 0);
    // if chrLen is 0 it is simply an empty bank that
    // the program will normally copy data to from prg
    // using ppuADDR/ppuDATA
    // TODO!!!!
    if (chrLen != 1) {
        printf("ERROR: chrLen %d not yet supported\n", chrLen);
        return false;
    }
    romFile.read((char *)chr, chrLen * CHR_BANK_SIZE);

    // load ram data
    ram = new uint8_t[RAM_BANK_SIZE];
    std::fill_n(ram, RAM_BANK_SIZE, 0);
    if (isRamBattery) {
        printf("ERROR: loading battery backed ram not yet supported\n");
        return false;
    }

    romFile.close();

    return true;
}

uint8_t Cart::readPrg(int index) {
    index %= prgLen * PRG_BANK_SIZE;
    return prg[index];
}

void Cart::writePrg(int index, uint8_t value) {
    // TODO: mapper registers
    printf("Tried to write to PRG-ROM, mapper functionality incomplete\n");
}

uint8_t Cart::readChr(int index) {
    return chr[index];
}

void Cart::writeChr(int index, uint8_t value) {
    // check if chr is writeable
    if (chrLen == 0) {
        chr[index] = value;
    }
    else {
        printf("ERROR: Tried to write 0x%X to CHR-ROM: 0x%X\n", value, index);
    }
}

uint8_t Cart::readRam(int index) {
    if(index > RAM_BANK_SIZE) {
        printf("ERROR: PRG-RAM access out of bounds\n");
    }
    return ram[index];
}

void Cart::writeRam(int index, uint8_t value) {
    if(index > RAM_BANK_SIZE) {
        printf("ERROR: PRG-RAM access out of bounds\n");
    }
    ram[index] = value;
}
<commit_msg>Remove initializing of cart memory array values<commit_after>#include <stdint.h>
#include <stdio.h>
#include <fstream>
#include <string>

#include <Cart.h>

Cart::~Cart() {
    delete prg, chr, ram;
}

bool Cart::readFile(std::string romFileName) {
    std::ifstream romFile(romFileName.c_str(), std::ios::binary);

    char header[16];

    // verify header
    romFile.read(header, 16);
    if (header[0] != 'N' ||
        header[1] != 'E' ||
        header[2] != 'S' ||
        header[3] != 0x1A) {
        printf("ERROR: Invalid iNES header\n");
        return false;
    }

    // read header data
    prgLen = header[4];
    chrLen = header[5];
    ramLen = header[8];
    mirroring = MIRROR_HOR;
    if (header[6] & (0x1 << 3)) {
        mirroring = MIRROR_NONE;
    }
    else if (header[6] & 0x1) {
        mirroring = MIRROR_VERT;
    }
    isRamBattery = !!(header[6] & (0x1 << 1));
    isTrainer = !!(header[6] & (0x1 << 2));
    mapperNum = (header[6] >> 4) + (header[7] & 0xF0);
    if (mapperNum != 0) {
        printf("ERROR: Mapper %d not yet supported\n", mapperNum);
        return false;
    }

    // load trainer data
    if (isTrainer) {
        romFile.read((char *)trainer, 512);
    }

    // load program data
    prg = new uint8_t[prgLen * PRG_BANK_SIZE];
    romFile.read((char *)prg, prgLen * PRG_BANK_SIZE);

    // load pattern/character data
    chr = new uint8_t[CHR_BANK_SIZE];
    // if chrLen is 0 it is simply an empty bank that
    // the program will normally copy data to from prg
    // using ppuADDR/ppuDATA
    // TODO!!!!
    if (chrLen != 1) {
        printf("ERROR: chrLen %d not yet supported\n", chrLen);
        return false;
    }
    romFile.read((char *)chr, chrLen * CHR_BANK_SIZE);

    // load ram data
    ram = new uint8_t[RAM_BANK_SIZE];
    if (isRamBattery) {
        printf("ERROR: loading battery backed ram not yet supported\n");
        return false;
    }

    romFile.close();

    return true;
}

uint8_t Cart::readPrg(int index) {
    index %= prgLen * PRG_BANK_SIZE;
    return prg[index];
}

void Cart::writePrg(int index, uint8_t value) {
    // TODO: mapper registers
    printf("Tried to write to PRG-ROM, mapper functionality incomplete\n");
}

uint8_t Cart::readChr(int index) {
    return chr[index];
}

void Cart::writeChr(int index, uint8_t value) {
    // check if chr is writeable
    if (chrLen == 0) {
        chr[index] = value;
    }
    else {
        printf("ERROR: Tried to write 0x%X to CHR-ROM: 0x%X\n", value, index);
    }
}

uint8_t Cart::readRam(int index) {
    if(index > RAM_BANK_SIZE) {
        printf("ERROR: PRG-RAM access out of bounds\n");
    }
    return ram[index];
}

void Cart::writeRam(int index, uint8_t value) {
    if(index > RAM_BANK_SIZE) {
        printf("ERROR: PRG-RAM access out of bounds\n");
    }
    ram[index] = value;
}
<|endoftext|>


<commit_before>#include <fstream>
#include <iostream>
#include <string>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <cassert>
#include <cmath>
#include <cstdarg>

const int EXIT_AC = 42;
const int EXIT_WA = 43;

std::ifstream judgein, judgeans;
FILE *judgemessage = NULL;
FILE *diffpos = NULL;
int judgeans_pos, stdin_pos;
int judgeans_line, stdin_line;

void wrong_answer(const char *err, ...) {
	va_list pvar;
	va_start(pvar, err);
	fprintf(judgemessage, "Wrong answer on line %d of output (corresponding to line %d in answer file)\n",
			stdin_line, judgeans_line);
	vfprintf(judgemessage, err, pvar);
	fprintf(judgemessage, "\n");
	if (diffpos) {
		fprintf(diffpos, "%d %d", judgeans_pos, stdin_pos);
	}
	exit(EXIT_WA);
}

void judge_error(const char *err, ...) {
	va_list pvar;
	va_start(pvar, err);
	// If judgemessage hasn't been set up yet, write error to stderr
	if (!judgemessage) judgemessage = stderr;
	vfprintf(judgemessage, err, pvar);
	fprintf(judgemessage, "\n");
	assert(!"Judge Error");
}

bool isfloat(const char *s, double &val) {
	char trash[20];
	double v;
	if (sscanf(s, "%lf%10s", &v, trash) != 1) return false;
	val = v;
	return true;
}

template <typename Stream>
void openfile(Stream &stream, const char *file, const char *whoami) {
	stream.open(file);
	if (stream.fail()) {
		judge_error("%s: failed to open %s\n", whoami, file);
	}
}

FILE *openfeedback(const char *feedbackdir, const char *feedback, const char *whoami) {
	std::string path = std::string(feedbackdir) + "/" + std::string(feedback);
	FILE *res = fopen(path.c_str(), "w");
	if (!res) {
		judge_error("%s: failed to open %s for writing", whoami, path.c_str());
	}
	return res;
}

const char *USAGE = "Usage: %s judge_in judge_ans feedback_file [options] < team_out";

int main(int argc, char **argv) {
	if(argc < 4) {
		judge_error(USAGE, argv[0]);
	}
	judgemessage = openfeedback(argv[3], "judgemessage.txt", argv[0]);
	diffpos = openfeedback(argv[3], "diffposition.txt", argv[0]);
	openfile(judgein, argv[1], argv[0]);
	openfile(judgeans, argv[2], argv[0]);

	bool case_sensitive = false;
	bool space_change_sensitive = false;
	bool use_floats = false;
	double float_abs_tol = -1;
	double float_rel_tol = -1;

	for (int a = 4; a < argc; ++a) {
		if        (!strcmp(argv[a], "case_sensitive")) {
			case_sensitive = true;
		} else if (!strcmp(argv[a], "space_change_sensitive")) {
			space_change_sensitive = true;
		} else if (!strcmp(argv[a], "float_absolute_tolerance")) {
			if (a+1 == argc || !isfloat(argv[a+1], float_abs_tol))
				judge_error(USAGE, argv[0]);
			++a;
		} else if (!strcmp(argv[a], "float_relative_tolerance")) {
			if (a+1 == argc || !isfloat(argv[a+1], float_rel_tol))
				judge_error(USAGE, argv[0]);
			++a;
		} else if (!strcmp(argv[a], "float_tolerance")) {
			if (a+1 == argc || !isfloat(argv[a+1], float_rel_tol))
				judge_error(USAGE, argv[0]);
			float_abs_tol = float_rel_tol;
			++a;
		} else {
			judge_error(USAGE, argv[0]);
		}
	}
	use_floats = float_abs_tol >= 0 || float_rel_tol >= 0;

	judgeans_pos = stdin_pos;
	judgeans_line = stdin_line = 1;

	std::string judge, team;
	char trash[20];
	while (true) {
		// Space!  Can't live with it, can't live without it...
		while (isspace(judgeans.peek())) {
			char c = (char)judgeans.get();
			if (space_change_sensitive) {
				char d = std::cin.get();
				if (c != d) {
					wrong_answer("Space change error: got %d expected %d", d, c);
				}
				if (d == '\n') ++stdin_line;
				++stdin_pos;
			}
			if (c == '\n') ++judgeans_line;
			++judgeans_pos;
		}
		while (isspace(std::cin.peek())) {
			char d = (char)std::cin.get();
			if (space_change_sensitive) {
				wrong_answer("Space change error: judge out of space, got %d from team", d);
			}
			if (d == '\n') ++stdin_line;
			++stdin_pos;
		}

		if (!(judgeans >> judge))
			break;

		if (!(std::cin >> team)) {
			wrong_answer("User EOF while judge had more output\n(Next judge token: %s)", judge.c_str());
		}

		double jval, tval;
		if (use_floats && isfloat(judge.c_str(), jval)) {
			if (!isfloat(team.c_str(), tval)) {
				wrong_answer("Expected float, got: %s", team.c_str());
			}
			if(!(fabs(jval - tval) <= float_abs_tol) &&
			   !(fabs(jval - tval) <= float_rel_tol*fabs(jval))) {
				wrong_answer("Too large difference.\n Judge: %s\n Team: %s\n Difference: %le\n (abs tol %le rel tol %le)",
							 judge.c_str(), team.c_str(), jval-tval, float_abs_tol, float_rel_tol);
			}
		} else if (case_sensitive) {
			if (strcmp(judge.c_str(), team.c_str()) != 0) {
				wrong_answer("String tokens mismatch\nJudge: \"%s\"\nTeam: \"%s\"", judge.c_str(), team.c_str());
			}
		} else {
			if(strcasecmp(judge.c_str(), team.c_str()) != 0) {
				wrong_answer("String tokens mismatch\nJudge: \"%s\"\nTeam: \"%s\"", judge.c_str(), team.c_str());
			}
		}
		judgeans_pos += judge.length();
		stdin_pos += team.length();
	}

	if (std::cin >> team) {
		wrong_answer("Trailing output:\n%s", team.c_str());
	}

	exit(EXIT_AC);
}
<commit_msg>Fix cosmetic issue with downcasting int to char. Note that d can be set to EOF (normally represented by int(-1)), so a cast to char _should_ not cause issues as char(255) is not a space character.<commit_after>#include <fstream>
#include <iostream>
#include <string>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <cassert>
#include <cmath>
#include <cstdarg>

const int EXIT_AC = 42;
const int EXIT_WA = 43;

std::ifstream judgein, judgeans;
FILE *judgemessage = NULL;
FILE *diffpos = NULL;
int judgeans_pos, stdin_pos;
int judgeans_line, stdin_line;

void wrong_answer(const char *err, ...) {
	va_list pvar;
	va_start(pvar, err);
	fprintf(judgemessage, "Wrong answer on line %d of output (corresponding to line %d in answer file)\n",
			stdin_line, judgeans_line);
	vfprintf(judgemessage, err, pvar);
	fprintf(judgemessage, "\n");
	if (diffpos) {
		fprintf(diffpos, "%d %d", judgeans_pos, stdin_pos);
	}
	exit(EXIT_WA);
}

void judge_error(const char *err, ...) {
	va_list pvar;
	va_start(pvar, err);
	// If judgemessage hasn't been set up yet, write error to stderr
	if (!judgemessage) judgemessage = stderr;
	vfprintf(judgemessage, err, pvar);
	fprintf(judgemessage, "\n");
	assert(!"Judge Error");
}

bool isfloat(const char *s, double &val) {
	char trash[20];
	double v;
	if (sscanf(s, "%lf%10s", &v, trash) != 1) return false;
	val = v;
	return true;
}

template <typename Stream>
void openfile(Stream &stream, const char *file, const char *whoami) {
	stream.open(file);
	if (stream.fail()) {
		judge_error("%s: failed to open %s\n", whoami, file);
	}
}

FILE *openfeedback(const char *feedbackdir, const char *feedback, const char *whoami) {
	std::string path = std::string(feedbackdir) + "/" + std::string(feedback);
	FILE *res = fopen(path.c_str(), "w");
	if (!res) {
		judge_error("%s: failed to open %s for writing", whoami, path.c_str());
	}
	return res;
}

const char *USAGE = "Usage: %s judge_in judge_ans feedback_file [options] < team_out";

int main(int argc, char **argv) {
	if(argc < 4) {
		judge_error(USAGE, argv[0]);
	}
	judgemessage = openfeedback(argv[3], "judgemessage.txt", argv[0]);
	diffpos = openfeedback(argv[3], "diffposition.txt", argv[0]);
	openfile(judgein, argv[1], argv[0]);
	openfile(judgeans, argv[2], argv[0]);

	bool case_sensitive = false;
	bool space_change_sensitive = false;
	bool use_floats = false;
	double float_abs_tol = -1;
	double float_rel_tol = -1;

	for (int a = 4; a < argc; ++a) {
		if        (!strcmp(argv[a], "case_sensitive")) {
			case_sensitive = true;
		} else if (!strcmp(argv[a], "space_change_sensitive")) {
			space_change_sensitive = true;
		} else if (!strcmp(argv[a], "float_absolute_tolerance")) {
			if (a+1 == argc || !isfloat(argv[a+1], float_abs_tol))
				judge_error(USAGE, argv[0]);
			++a;
		} else if (!strcmp(argv[a], "float_relative_tolerance")) {
			if (a+1 == argc || !isfloat(argv[a+1], float_rel_tol))
				judge_error(USAGE, argv[0]);
			++a;
		} else if (!strcmp(argv[a], "float_tolerance")) {
			if (a+1 == argc || !isfloat(argv[a+1], float_rel_tol))
				judge_error(USAGE, argv[0]);
			float_abs_tol = float_rel_tol;
			++a;
		} else {
			judge_error(USAGE, argv[0]);
		}
	}
	use_floats = float_abs_tol >= 0 || float_rel_tol >= 0;

	judgeans_pos = stdin_pos;
	judgeans_line = stdin_line = 1;

	std::string judge, team;
	char trash[20];
	while (true) {
		// Space!  Can't live with it, can't live without it...
		while (isspace(judgeans.peek())) {
			char c = (char)judgeans.get();
			if (space_change_sensitive) {
				int d = std::cin.get();
				if (c != d) {
					wrong_answer("Space change error: got %d expected %d", d, c);
				}
				if (d == '\n') ++stdin_line;
				++stdin_pos;
			}
			if (c == '\n') ++judgeans_line;
			++judgeans_pos;
		}
		while (isspace(std::cin.peek())) {
			char d = (char)std::cin.get();
			if (space_change_sensitive) {
				wrong_answer("Space change error: judge out of space, got %d from team", d);
			}
			if (d == '\n') ++stdin_line;
			++stdin_pos;
		}

		if (!(judgeans >> judge))
			break;

		if (!(std::cin >> team)) {
			wrong_answer("User EOF while judge had more output\n(Next judge token: %s)", judge.c_str());
		}

		double jval, tval;
		if (use_floats && isfloat(judge.c_str(), jval)) {
			if (!isfloat(team.c_str(), tval)) {
				wrong_answer("Expected float, got: %s", team.c_str());
			}
			if(!(fabs(jval - tval) <= float_abs_tol) &&
			   !(fabs(jval - tval) <= float_rel_tol*fabs(jval))) {
				wrong_answer("Too large difference.\n Judge: %s\n Team: %s\n Difference: %le\n (abs tol %le rel tol %le)",
							 judge.c_str(), team.c_str(), jval-tval, float_abs_tol, float_rel_tol);
			}
		} else if (case_sensitive) {
			if (strcmp(judge.c_str(), team.c_str()) != 0) {
				wrong_answer("String tokens mismatch\nJudge: \"%s\"\nTeam: \"%s\"", judge.c_str(), team.c_str());
			}
		} else {
			if(strcasecmp(judge.c_str(), team.c_str()) != 0) {
				wrong_answer("String tokens mismatch\nJudge: \"%s\"\nTeam: \"%s\"", judge.c_str(), team.c_str());
			}
		}
		judgeans_pos += judge.length();
		stdin_pos += team.length();
	}

	if (std::cin >> team) {
		wrong_answer("Trailing output:\n%s", team.c_str());
	}

	exit(EXIT_AC);
}
<|endoftext|>


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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

  if (ioIsBuiltin == false) {

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

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

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

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

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

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

  return 0;
}

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

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

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

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

  // Output log File
  stdair::Filename_T lLogFilename;

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

  if (ioIsBuiltin == false) {

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

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

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

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

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

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

  return 0;
}

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

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

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

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

  // Output log File
  stdair::Filename_T lLogFilename;

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

  return 0;
}
<|endoftext|>