Exemple #1
0
	FieldInfo TypeBuilder::DefineField(const std::string && name, const TypeInfo && type, const std::function<Object(const Object &&)> && accessor)
	{
		FieldInfo field(std::move(name), std::move(type), std::move(accessor));
		m_pImpl->m_parameters.m_fields.push_back(field);
		return field;
	}
Exemple #2
0
void Port::Field::operator =(unsigned value) const {
  ControlWord field(at);
  field = mask & ((unsigned(~value << 16) | value) << lsb); // read the stm32 manual for this.
}
Exemple #3
0
static boolean isCtagsLine (const char *const line)
{
	enum fieldList { TAG, TAB1, SRC_FILE, TAB2, EXCMD, NUM_FIELDS };
	boolean ok = FALSE;  /* we assume not unless confirmed */
	const size_t fieldLength = strlen (line) + 1;
	char *const fields = xMalloc (NUM_FIELDS * fieldLength, char);

	if (fields == NULL)
		error (FATAL, "Cannot analyze tag file");
	else
	{
#define field(x)		(fields + ((size_t) (x) * fieldLength))

		const int numFields = sscanf (
			line, "%[^\t]%[\t]%[^\t]%[\t]%[^\r\n]",
			field (TAG), field (TAB1), field (SRC_FILE),
			field (TAB2), field (EXCMD));

		/*  There must be exactly five fields: two tab fields containing
		 *  exactly one tab each, the tag must not begin with "#", and the
		 *  file name should not end with ";", and the excmd must be
		 *  accceptable.
		 *
		 *  These conditions will reject tag-looking lines like:
		 *      int a;        <C-comment>
		 *      #define LABEL <C-comment>
		 */
		if (numFields == NUM_FIELDS   &&
			strlen (field (TAB1)) == 1  &&
			strlen (field (TAB2)) == 1  &&
			field (TAG) [0] != '#'      &&
			field (SRC_FILE) [strlen (field (SRC_FILE)) - 1] != ';'  &&
			isValidTagAddress (field (EXCMD)))
				ok = TRUE;

		eFree (fields);
	}
	return ok;
}
void PageOffer_Accounts::on_pushButtonSelectCurrencyAcct_clicked()
{
    QString qstrNymID    = field("NymID")      .toString();
    QString qstrAssetID  = field("CurrencyID") .toString();
    QString qstrServerID = field("ServerID")   .toString();
    // -------------------------------------------
    QString qstr_current_id = field("CurrencyAcctID").toString();
    // -------------------------------------------
    if (qstr_current_id.isEmpty() && (OTAPI_Wrap::It()->GetAccountCount() > 0))
        qstr_current_id = QString::fromStdString(OTAPI_Wrap::It()->GetAccountWallet_ID(0));
    // -------------------------------------------
    // Select from currency accounts in local wallet.
    //
    DlgChooser theChooser(this);
    // -----------------------------------------------
    mapIDName & the_map = theChooser.m_map;

    bool bFoundDefault = false;
    // -----------------------------------------------
    const int32_t the_count = OTAPI_Wrap::It()->GetAccountCount();
    // -----------------------------------------------
    for (int32_t ii = 0; ii < the_count; ++ii)
    {
        QString OT_id = QString::fromStdString(OTAPI_Wrap::It()->GetAccountWallet_ID(ii));
        QString OT_name("");
        // -----------------------------------------------
        if (!OT_id.isEmpty())
        {
            // Filter the accounts shown based on asset type, server ID, and Nym ID.
            //
            QString qstrAcctNymID    = QString::fromStdString(OTAPI_Wrap::It()->GetAccountWallet_NymID       (OT_id.toStdString()));
            QString qstrAcctAssetID  = QString::fromStdString(OTAPI_Wrap::It()->GetAccountWallet_AssetTypeID (OT_id.toStdString()));
            QString qstrAcctServerID = QString::fromStdString(OTAPI_Wrap::It()->GetAccountWallet_ServerID    (OT_id.toStdString()));
            // -----------------------------------------------
            if ((qstrAcctNymID    != qstrNymID)   ||
                (qstrAcctAssetID  != qstrAssetID) ||
                (qstrAcctServerID != qstrServerID))
                continue;
            // -----------------------------------------------
            if (!qstr_current_id.isEmpty() && (OT_id == qstr_current_id))
                bFoundDefault = true;
            // -----------------------------------------------
            OT_name = QString::fromStdString(OTAPI_Wrap::It()->GetAccountWallet_Name(OT_id.toStdString()));
            // -----------------------------------------------
            the_map.insert(OT_id, OT_name);
        }
    }
    // -----------------------------------------------
    if (bFoundDefault)
        theChooser.SetPreSelected(qstr_current_id);
    // -----------------------------------------------
    theChooser.setWindowTitle(tr("Select the Currency Account"));
    // -----------------------------------------------
    if (theChooser.exec() == QDialog::Accepted)
    {
        if (!theChooser.m_qstrCurrentID  .isEmpty() &&
            !theChooser.m_qstrCurrentName.isEmpty())
        {
            setField("CurrencyAcctName", theChooser.m_qstrCurrentName);
            setField("CurrencyAcctID",   theChooser.m_qstrCurrentID);
            // -----------------------------------------
            ui->lineEditCurrencyAcctID->home(false);
            // -----------------------------------------
            int64_t     lBalance      = OTAPI_Wrap::It()->GetAccountWallet_Balance(theChooser.m_qstrCurrentID.toStdString());
            std::string str_formatted = OTAPI_Wrap::It()->FormatAmount(qstrAssetID.toStdString(), lBalance);
            QString     qstrBalance   = QString::fromStdString(str_formatted);

            setField("CurrencyAcctBalance", qstrBalance);
        }
    }
}
bool NewBuildingWizard::IsNewOMT()
{
    return field("NewOMT").toBool();
}
Exemple #6
0
PyObject* Load::create(PyTypeObject* pytype, PyObject* args, PyObject* kwds)
{
  try
  {
    // Pick up the operation
    PyObject* oper = PyDict_GetItemString(kwds,"operation");
    if (!oper)
      throw DataException("missing operation on Load");
    if (!PyObject_TypeCheck(oper, Operation::metadata->pythonClass))
      throw DataException("load operation must be of type operation");

    // Pick up the resource
    PyObject* res = PyDict_GetItemString(kwds,"resource");
    if (!res)
      throw DataException("missing resource on Load");
    if (!PyObject_TypeCheck(res, Resource::metadata->pythonClass))
      throw DataException("load resource must be of type resource");

    // Pick up the quantity
    PyObject* q1 = PyDict_GetItemString(kwds,"quantity");
    double q2 = q1 ? PythonData(q1).getDouble() : 1.0;

    // Pick up the effective dates
    DateRange eff;
    PyObject* eff_start = PyDict_GetItemString(kwds,"effective_start");
    if (eff_start)
    {
      PythonData d(eff_start);
      eff.setStart(d.getDate());
    }
    PyObject* eff_end = PyDict_GetItemString(kwds,"effective_end");
    if (eff_end)
    {
      PythonData d(eff_end);
      eff.setEnd(d.getDate());
    }

    // Create the load
    Load *l = new LoadDefault(
      static_cast<Operation*>(oper),
      static_cast<Resource*>(res),
      q2, eff
    );

    // Iterate over extra keywords, and set attributes.   @todo move this responsibility to the readers...
    if (l)
    {
      PyObject *key, *value;
      Py_ssize_t pos = 0;
      while (PyDict_Next(kwds, &pos, &key, &value))
      {
        PythonData field(value);
        PyObject* key_utf8 = PyUnicode_AsUTF8String(key);
        DataKeyword attr(PyBytes_AsString(key_utf8));
        Py_DECREF(key_utf8);
        if (!attr.isA(Tags::effective_end) && !attr.isA(Tags::effective_start)
          && !attr.isA(Tags::operation) && !attr.isA(Tags::resource)
          && !attr.isA(Tags::quantity) && !attr.isA(Tags::type)
          && !attr.isA(Tags::action))
        {
          const MetaFieldBase* fmeta = l->getType().findField(attr.getHash());
          if (!fmeta && l->getType().category)
            fmeta = l->getType().category->findField(attr.getHash());
          if (fmeta)
            // Update the attribute
            fmeta->setField(l, field);
          else
            l->setProperty(attr.getName(), value);;
        }
      };
    }

    // Return the object
    Py_INCREF(l);
    return static_cast<PyObject*>(l);
  }
  catch (...)
  {
    PythonType::evalException();
    return NULL;
  }
}
Exemple #7
0
//------------------------------------------------------------------------------
int main( int argc, char * argv[] )
{
    //--------------------------------------------------------------------------
    const unsigned    geomDeg   = 1;
    const unsigned    dim       = 2;
    // degrees of lowest-order TH element
    const unsigned    fieldDegU = 2; 
    const unsigned    fieldDegP = 1;

    const unsigned    tiOrder   = 1;
    typedef  base::time::BDF<tiOrder> MSM;
    
    const base::Shape shape     = base::SimplexShape<dim>::value;
    const base::Shape surfShape = base::SimplexShape<dim-1>::value;

    //--------------------------------------------------------------------------
    if ( argc != 2 ) {
        std::cout << "Usage:  " << argv[0] << " input.dat \n\n";
        return -1;
    }

    const std::string inputFile = boost::lexical_cast<std::string>( argv[1] );

    //--------------------------------------------------------------------------
    std::string meshFile, surfFile;
    double viscosity, density, tolerance, penaltyFactor, stepSize;
    unsigned maxIter, numSteps;
    {    
        //Feed properties parser with the variables to be read
        base::io::PropertiesParser prop;
        prop.registerPropertiesVar( "meshFile",         meshFile );
        prop.registerPropertiesVar( "surfFile",         surfFile );
        prop.registerPropertiesVar( "viscosity",        viscosity );
        prop.registerPropertiesVar( "density",          density );
        prop.registerPropertiesVar( "maxIter",          maxIter );
        prop.registerPropertiesVar( "tolerance",        tolerance );
        prop.registerPropertiesVar( "penaltyFactor",    penaltyFactor );
        prop.registerPropertiesVar( "stepSize",         stepSize );
        prop.registerPropertiesVar( "numSteps",         numSteps );

        // Read variables from the input file
        std::ifstream inp( inputFile.c_str()  );
        VERIFY_MSG( inp.is_open(), "Cannot open input file" );
        prop.readValues( inp );
        inp.close( );

        // Make sure all variables have been found
        if ( not prop.isEverythingRead() ) {
            prop.writeUnread( std::cerr );
            VERIFY_MSG( false, "Could not find above variables" );
        }
    }

    const std::string baseName = base::io::baseName( meshFile, ".smf" );

    //--------------------------------------------------------------------------
    typedef base::Unstructured<shape,geomDeg>     Mesh;

    Mesh mesh;
    {
        std::ifstream smf( meshFile.c_str() );
        VERIFY_MSG( smf.is_open(), "Cannot open mesh file" );
        base::io::smf::readMesh( smf, mesh );
        smf.close();
    }

    //--------------------------------------------------------------------------
    // Surface mesh
    typedef base::Unstructured<surfShape,1,dim>    SurfMesh;

    SurfMesh surfMesh;
    {
        std::ifstream smf( surfFile.c_str() );
        base::io::smf::readMesh( smf, surfMesh );
        smf.close();
    }

    //--------------------------------------------------------------------------
    // Compute the level set data
    typedef base::cut::LevelSet<dim> LevelSet;
    std::vector<LevelSet> levelSet;
    const bool isSigned = true;
    base::cut::bruteForce( mesh, surfMesh, isSigned, levelSet );

    const unsigned kernelDegEstimate = 5;

    //--------------------------------------------------------------------------
    // Make cut cell structure
    typedef base::cut::Cell<shape> Cell;
    std::vector<Cell> cells;
    base::cut::generateCutCells( mesh, levelSet, cells );

    // Quadrature 
    typedef base::cut::Quadrature<kernelDegEstimate,shape> CutQuadrature;
    CutQuadrature quadrature( cells, true );

    // for surface
    typedef base::SurfaceQuadrature<kernelDegEstimate,shape> SurfaceQuadrature;
    SurfaceQuadrature surfaceQuadrature;

    //------------------------------------------------------------------------------
    // Finite element bases
    const unsigned    nHist = MSM::numSteps;
    
    const unsigned    doFSizeU = dim;
    typedef base::fe::Basis<shape,fieldDegU>                FEBasisU;
    typedef base::cut::ScaledField<FEBasisU,doFSizeU,nHist> Velocity;
    Velocity velocity;
    base::dof::generate<FEBasisU>( mesh, velocity );
    
    const unsigned    doFSizeP = 1;
    typedef base::fe::Basis<shape,fieldDegP>                FEBasisP;
    typedef base::cut::ScaledField<FEBasisP,doFSizeP,nHist> Pressure;
    Pressure pressure;
    base::dof::generate<FEBasisP>( mesh, pressure );

    const unsigned    doFSizeS = dim;
    typedef base::fe::Basis<surfShape,1>              FEBasisS;
    typedef base::Field<FEBasisS,doFSizeS>            SurfField;
    SurfField surfVelocity, surfForces;
    base::dof::generate<FEBasisS>( surfMesh, surfVelocity );
    base::dof::generate<FEBasisS>( surfMesh, surfForces   );

    // set initial condition to the identity 
    base::dof::setField( surfMesh, surfVelocity,
                         boost::bind( &surfaceVelocity<dim,
                                      SurfField::DegreeOfFreedom>, _1, _2 ) );


    // boundary datum    
    base::cut::TransferSurfaceDatum<SurfMesh,SurfField,Mesh::Element>
        s2d( surfMesh, surfVelocity, levelSet );
    
    //--------------------------------------------------------------------------
    //  surface mesh
    typedef base::mesh::BoundaryMeshBinder<Mesh>::Type BoundaryMesh;
    BoundaryMesh boundaryMesh, immersedMesh;

    // from boundary
    {
        // identify list of element boundary faces
        base::mesh::MeshBoundary meshBoundary;
        meshBoundary.create( mesh.elementsBegin(), mesh.elementsEnd() );

        // generate a mesh from that list (with a filter)
        base::mesh::generateBoundaryMesh( meshBoundary.begin(),
                                          meshBoundary.end(),
                                          mesh, boundaryMesh,
                                          boost::bind( &boundaryFilter<dim>, _1 ) );

        // make a surface mesh from the implicit surface
        base::cut::generateSurfaceMesh<Mesh,Cell>( mesh, cells, immersedMesh );
    }

    // the composite field with geometry, velocity and pressure
    typedef base::asmb::FieldBinder<Mesh,Velocity,Pressure> Field;
    Field field( mesh, velocity, pressure );

    // define the system blocks (U,U), (U,P), and (P,U)
    typedef Field::TupleBinder<1,1,1>::Type TopLeft;
    typedef Field::TupleBinder<1,2>::Type   TopRight;
    typedef Field::TupleBinder<2,1>::Type   BotLeft;


    std::vector<double> supportsU, supportsP;
    std::size_t numDoFsU = std::distance( velocity.doFsBegin(), velocity.doFsEnd() );
    supportsU.resize( numDoFsU );
    std::size_t numDoFsP = std::distance( pressure.doFsBegin(), pressure.doFsEnd() );
    supportsP.resize( numDoFsP );

    base::cut::supportComputation( mesh, velocity, quadrature, supportsU );
    base::cut::supportComputation( mesh, pressure, quadrature, supportsP );

    velocity.scaleAndTagBasis( supportsU, 1.e-8 );
    pressure.scaleAndTagBasis( supportsP, 1.e-8 ); 
    //velocity.tagBasis( supportsU, 1.e-8 );
    //pressure.tagBasis( supportsP, 1.e-8 ); 

    // Fix one pressure dof
    // Pressure::DoFPtrIter pIter = pressure.doFsBegin();
    // std::advance( pIter, std::distance( pressure.doFsBegin(), pressure.doFsEnd() )/5 );
    // (*pIter) -> constrainValue( 0, 0.0 );

    // Number of DoFs after constraint application!
    numDoFsU =
        base::dof::numberDoFsConsecutively( velocity.doFsBegin(), velocity.doFsEnd() );
    std::cout << "# Number of velocity dofs " << numDoFsU << std::endl;

    numDoFsP =
        base::dof::numberDoFsConsecutively( pressure.doFsBegin(), pressure.doFsEnd(),
            numDoFsU );
    std::cout << "# Number of pressure dofs " << numDoFsP << std::endl;

    // kernels
    typedef fluid::StressDivergence<  TopLeft::Tuple>  StressDivergence;
    typedef fluid::Convection<        TopLeft::Tuple>  Convection;
    typedef fluid::PressureGradient<  TopRight::Tuple> GradP;
    typedef fluid::VelocityDivergence<BotLeft::Tuple>  DivU;

    StressDivergence stressDivergence( viscosity );
    Convection       convection(       density );
    GradP            gradP;
    DivU             divU( true );

    // for surface fields
    typedef base::asmb::SurfaceFieldBinder<BoundaryMesh,Velocity,Pressure> SurfaceFieldBinder;
    typedef SurfaceFieldBinder::TupleBinder<1,1,1>::Type STBUU;
    typedef SurfaceFieldBinder::TupleBinder<1,2  >::Type STBUP;
    SurfaceFieldBinder   boundaryFieldBinder(  boundaryMesh, velocity, pressure );
    SurfaceFieldBinder   immersedFieldBinder(  immersedMesh, velocity, pressure );

    std::ofstream forces( "forces.dat" );

    for ( unsigned step = 0; step < numSteps; step++ ) {

        const double time = step * stepSize;
        const double factor = ( time < 1.0 ? time : 1.0 );
    
        std::cout << step << ":  time=" << time << ", factor=" << factor
                  << "\n";

        //base::dof::clearDoFs( velocity );
        //base::dof::clearDoFs( pressure );
        
        //--------------------------------------------------------------------------
        // Nonlinear iterations
        unsigned iter = 0;
        while( iter < maxIter ) {

            // Create a solver object
            typedef base::solver::Eigen3           Solver;
            Solver solver( numDoFsU + numDoFsP );

            std::cout << "* Iteration " << iter << std::flush;

            // compute inertia terms, d/dt, due to time integration
            base::time::computeInertiaTerms<TopLeft,MSM>( quadrature, solver,
                                                          field, stepSize, step,
                                                          density );
    
            // Compute system matrix
            base::asmb::stiffnessMatrixComputation<TopLeft>( quadrature, solver,
                                                             field, stressDivergence );

            base::asmb::stiffnessMatrixComputation<TopLeft>( quadrature, solver,
                                                             field, convection );

            base::asmb::stiffnessMatrixComputation<TopRight>( quadrature, solver,
                                                              field, gradP );

            base::asmb::stiffnessMatrixComputation<BotLeft>( quadrature, solver,
                                                             field, divU );
            // compute residual forces
            base::asmb::computeResidualForces<TopLeft >( quadrature, solver, field,
                                                         stressDivergence );
            base::asmb::computeResidualForces<TopLeft >( quadrature, solver, field, convection );
            base::asmb::computeResidualForces<TopRight>( quadrature, solver, field, gradP );
            base::asmb::computeResidualForces<BotLeft >( quadrature, solver, field, divU );
        
            // Parameter classes
            base::nitsche::OuterBoundary ob( viscosity );
            base::nitsche::ImmersedBoundary<Cell> ib( viscosity, cells );

            // Penalty method
            base::nitsche::penaltyLHS<STBUU>( surfaceQuadrature, solver,
                                              boundaryFieldBinder, ob, penaltyFactor );
        
            base::nitsche::penaltyRHS<STBUU>( surfaceQuadrature, solver, boundaryFieldBinder, 
                                              boost::bind( &dirichlet<dim>, _1, factor),
                                              ob, penaltyFactor );

            base::nitsche::penaltyLHS<STBUU>( surfaceQuadrature, solver,
                                              immersedFieldBinder, ib, penaltyFactor );
        
            base::nitsche::penaltyRHS2<STBUU>( surfaceQuadrature, solver, immersedFieldBinder,
                                               s2d, ib, penaltyFactor );

            // Nitsche terms
            base::nitsche::primalEnergyLHS<STBUU>( stressDivergence, surfaceQuadrature, solver,
                                                   boundaryFieldBinder, ob );
            base::nitsche::dualEnergyLHS<STBUU>( stressDivergence, surfaceQuadrature, solver,
                                                 boundaryFieldBinder, ob );
            base::nitsche::energyRHS<STBUU>( stressDivergence, surfaceQuadrature, solver,
                                             boundaryFieldBinder,
                                             boost::bind( &dirichlet<dim>, _1, factor),
                                             ob );
        
            base::nitsche::primalEnergyLHS<STBUP>( gradP, surfaceQuadrature, solver,
                                                   boundaryFieldBinder, ob );
            base::nitsche::dualEnergyLHS<STBUP>( gradP, surfaceQuadrature, solver,
                                                 boundaryFieldBinder, ob );
         
            base::nitsche::energyRHS<STBUP>( gradP, surfaceQuadrature, solver,
                                             boundaryFieldBinder,
                                             boost::bind( &dirichlet<dim>, _1, factor), ob );

            base::nitsche::energyResidual<STBUU>( stressDivergence, surfaceQuadrature, solver,
                                                  boundaryFieldBinder, ob );
            
            base::nitsche::energyResidual<STBUP>( gradP, surfaceQuadrature, solver,
                                                  boundaryFieldBinder, ob );

            base::nitsche::primalEnergyLHS<STBUU>( stressDivergence, surfaceQuadrature, solver,
                                                   immersedFieldBinder, ib );
            base::nitsche::dualEnergyLHS<STBUU>( stressDivergence, surfaceQuadrature, solver,
                                                 immersedFieldBinder, ib );

            base::nitsche::energyRHS2<STBUU>( stressDivergence, surfaceQuadrature, solver,
                                              immersedFieldBinder, s2d, ib );
            
            base::nitsche::primalEnergyLHS<STBUP>( gradP, surfaceQuadrature, solver,
                                                   immersedFieldBinder, ib );
            base::nitsche::dualEnergyLHS<STBUP>( gradP, surfaceQuadrature, solver,
                                                 immersedFieldBinder, ib );

            base::nitsche::energyRHS2<STBUP>( gradP, surfaceQuadrature, solver,
                                              immersedFieldBinder, s2d, ib );

            base::nitsche::energyResidual<STBUU>( stressDivergence, surfaceQuadrature, solver,
                                                  immersedFieldBinder, ib );

            base::nitsche::energyResidual<STBUP>( gradP, surfaceQuadrature, solver,
                                                  immersedFieldBinder, ib );
        
            // Finalise assembly
            solver.finishAssembly();

            // check convergence via solver norms
            const double residualNorm = solver.norm();
            std::cout << " |R| = " << residualNorm << std::flush;

            if ( residualNorm < tolerance * viscosity) {
                std::cout << std::endl;
                break;
            }

            // Solve
            solver.superLUSolve();

            // distribute results back to dofs
            base::dof::addToDoFsFromSolver( solver, velocity );
            base::dof::addToDoFsFromSolver( solver, pressure );
            //base::dof::setDoFsFromSolver( solver, pressure );
        
            // check convergence via solver norms
            const double incrementNorm = solver.norm(0, numDoFsU );
            std::cout << " |dU| = " << incrementNorm << std::endl;

            // push history
            base::dof::pushHistory( velocity );
            base::dof::pushHistory( pressure );
        
            if ( incrementNorm < tolerance ) break;

            iter++;

        }

        writeVTKFile( baseName, step, mesh, velocity, pressure, levelSet, viscosity );
        {
            base::Vector<dim>::Type sumOfForces = base::constantVector<dim>( 0. );
            
            typedef Field::TupleBinder<1,2>::Type UP;
            //typedef fluid::Stress<UP::Tuple> Stress;
            //Stress stress( viscosity );
            typedef fluid::Traction<UP::Tuple> Traction;
            Traction traction( viscosity );
                
            base::cut::ComputeSurfaceForces<SurfMesh,SurfField,
                                            SurfaceQuadrature,STBUP::Tuple,Traction>
                computeSurfaceForces( surfMesh, surfForces, surfaceQuadrature, levelSet, traction );

            SurfaceFieldBinder::FieldIterator first = immersedFieldBinder.elementsBegin();
            SurfaceFieldBinder::FieldIterator  last = immersedFieldBinder.elementsEnd();
            for ( ; first != last; ++first ) {
                
                sumOfForces +=
                    computeSurfaceForces( STBUP::makeTuple( *first ) );
                
            }

            writeSurfaceVTKFile( baseName, step, surfMesh, surfVelocity, surfForces );


            std::cout << "  F= " << sumOfForces.transpose() << " \n";

            forces << time << " " << sumOfForces.transpose() << std::endl;;
        }

    }

    forces.close();

    return 0;
}
Exemple #8
0
void OAuthWizard::onFirstPageCommitted(QString username, QString server) {
  m_username = username;
  m_server = siteUrlFixer(server, field("useSsl").toBool());
  m_clientRegTryCount = 0;
  registerOAuthClient();
}
int main(int argc, char *argv[])
{
#   include "addRegionOption.H"
    timeSelector::addOptions();
    argList::validArgs.append("fieldName");
    argList::validArgs.append("patchName");
#   include "setRootCase.H"
#   include "createTime.H"
    instantList timeDirs = timeSelector::select0(runTime, args);
#   include "createNamedMesh.H"

    const word fieldName = args[1];
    const word patchName = args[2];

    forAll(timeDirs, timeI)
    {
        runTime.setTime(timeDirs[timeI], timeI);
        Info<< "Time = " << runTime.timeName() << endl;

        IOobject fieldHeader
        (
            fieldName,
            runTime.timeName(),
            mesh,
            IOobject::MUST_READ
        );

        // Check field exists
        if (fieldHeader.headerOk())
        {
            mesh.readUpdate();

            const label patchI = mesh.boundaryMesh().findPatchID(patchName);
            if (patchI < 0)
            {
                FatalError
                    << "Unable to find patch " << patchName << nl
                    << exit(FatalError);
            }

            // Give patch area
            Info<< "    Area vector of patch "
                << patchName << '[' << patchI << ']' << " = "
                << gSum(mesh.Sf().boundaryField()[patchI]) << endl;
            Info<< "    Area magnitude of patch "
                << patchName << '[' << patchI << ']' << " = "
                << gSum(mesh.magSf().boundaryField()[patchI]) << endl;

            // Read field and calc integral
            if (fieldHeader.headerClassName() == volScalarField::typeName)
            {
                Info<< "    Reading " << volScalarField::typeName << " "
                    << fieldName << endl;

                volScalarField field(fieldHeader, mesh);

                Info<< "    Integral of " << fieldName
                    << " over vector area of patch "
                    << patchName << '[' << patchI << ']' << " = "
                    << gSum
                       (
                           mesh.Sf().boundaryField()[patchI]
                          *field.boundaryField()[patchI]
                       )
                    << nl;

                Info<< "    Integral of " << fieldName
                    << " over area magnitude of patch "
                    << patchName << '[' << patchI << ']' << " = "
                    << gSum
                       (
                           mesh.magSf().boundaryField()[patchI]
                          *field.boundaryField()[patchI]
                       )
                    << nl;
            }
            else if
            (
                fieldHeader.headerClassName() == surfaceScalarField::typeName
            )
            {
                Info<< "    Reading " << surfaceScalarField::typeName << " "
                    << fieldName << endl;

                surfaceScalarField field(fieldHeader, mesh);
                scalar sumField = gSum(field.boundaryField()[patchI]);

                Info<< "    Integral of " << fieldName << " over patch "
                    << patchName << '[' << patchI << ']' << " = "
                    << sumField << nl;
            }
            else
            {
                FatalError
                    << "Only possible to integrate "
                    << volScalarField::typeName << "s "
                    << "and " << surfaceScalarField::typeName << "s"
                    << nl << exit(FatalError);
            }
        }
        else
        {
            Info<< "    No field " << fieldName << endl;
        }

        Info<< endl;
    }
Exemple #10
0
bool map::process_fields_in_submap(game *g, int gridn)
{
 bool found_field = false;
 field *cur;
 field_id curtype;
 for (int locx = 0; locx < SEEX; locx++) {
  for (int locy = 0; locy < SEEY; locy++) {
   cur = &(grid[gridn]->fld[locx][locy]);
   int x = locx + SEEX * (gridn % my_MAPSIZE),
       y = locy + SEEY * int(gridn / my_MAPSIZE);
   
   curtype = cur->type;
   if (!found_field && curtype != fd_null)
    found_field = true;
   if (cur->density > 3 || cur->density < 1)
    debugmsg("Whoooooa density of %d", cur->density);

  if (cur->age == 0)	// Don't process "newborn" fields
   curtype = fd_null;

  int part;
  vehicle *veh;
  switch (curtype) {

   case fd_null:
    break;	// Do nothing, obviously.  OBVIOUSLY.

   case fd_blood:
   case fd_bile:
    if (has_flag(swimmable, x, y))	// Dissipate faster in water
     cur->age += 250;
    break;

   case fd_acid:
    if (has_flag(swimmable, x, y))	// Dissipate faster in water
     cur->age += 20;
    for (int i = 0; i < i_at(x, y).size(); i++) {
     item *melting = &(i_at(x, y)[i]);
     if (melting->made_of(LIQUID) || melting->made_of(VEGGY)   ||
         melting->made_of(FLESH)  || melting->made_of(POWDER)  ||
         melting->made_of(COTTON) || melting->made_of(WOOL)    ||
         melting->made_of(PAPER)  || melting->made_of(PLASTIC) ||
         (melting->made_of(GLASS) && !one_in(3)) || one_in(4)) {
// Acid destructable objects here
      melting->damage++;
      if (melting->damage >= 5 ||
          (melting->made_of(PAPER) && melting->damage >= 3)) {
       cur->age += melting->volume();
       for (int m = 0; m < i_at(x, y)[i].contents.size(); m++)
        i_at(x, y).push_back( i_at(x, y)[i].contents[m] );
       i_at(x, y).erase(i_at(x, y).begin() + i);
       i--;
      }
     }
    }
    break;

   case fd_sap:
    break; // It doesn't do anything.

   case fd_fire: {
// Consume items as fuel to help us grow/last longer.
    bool destroyed = false;
    int vol = 0, smoke = 0, consumed = 0;
    for (int i = 0; i < i_at(x, y).size() && consumed < cur->density * 2; i++) {
     destroyed = false;
     vol = i_at(x, y)[i].volume();
     item *it = &(i_at(x, y)[i]);

     if (it->is_ammo() && it->ammo_type() != AT_BATT &&
         it->ammo_type() != AT_NAIL && it->ammo_type() != AT_BB &&
         it->ammo_type() != AT_BOLT && it->ammo_type() != AT_ARROW) {
      cur->age /= 2;
      cur->age -= 600;
      destroyed = true;
      smoke += 6;
      consumed++;

     } else if (it->made_of(PAPER)) {
      destroyed = it->burn(cur->density * 3);
      consumed++;
      if (cur->density == 1)
       cur->age -= vol * 10;
      if (vol >= 4)
       smoke++;

     } else if ((it->made_of(WOOD) || it->made_of(VEGGY))) {
      if (vol <= cur->density * 10 || cur->density == 3) {
       cur->age -= 4;
       destroyed = it->burn(cur->density);
       smoke++;
       consumed++;
      } else if (it->burnt < cur->density) {
       destroyed = it->burn(1);
       smoke++;
      }

     } else if ((it->made_of(COTTON) || it->made_of(WOOL))) {
      if (vol <= cur->density * 5 || cur->density == 3) {
       cur->age--;
       destroyed = it->burn(cur->density);
       smoke++;
       consumed++;
      } else if (it->burnt < cur->density) {
       destroyed = it->burn(1);
       smoke++;
      }

     } else if (it->made_of(FLESH)) {
      if (vol <= cur->density * 5 || (cur->density == 3 && one_in(vol / 20))) {
       cur->age--;
       destroyed = it->burn(cur->density);
       smoke += 3;
       consumed++;
      } else if (it->burnt < cur->density * 5 || cur->density >= 2) {
       destroyed = it->burn(1);
       smoke++;
      }

     } else if (it->made_of(LIQUID)) {
      switch (it->type->id) { // TODO: Make this be not a hack.
       case itm_whiskey:
       case itm_vodka:
       case itm_rum:
       case itm_tequila:
        cur->age -= 300;
        smoke += 6;
        break;
       default:
        cur->age += rng(80 * vol, 300 * vol);
        smoke++;
      }
      destroyed = true;
      consumed++;

     } else if (it->made_of(POWDER)) {
      cur->age -= vol;
      destroyed = true;
      smoke += 2;

     } else if (it->made_of(PLASTIC)) {
      smoke += 3;
      if (it->burnt <= cur->density * 2 || (cur->density == 3 && one_in(vol))) {
       destroyed = it->burn(cur->density);
       if (one_in(vol + it->burnt))
        cur->age--;
      }
     }

     if (destroyed) {
      for (int m = 0; m < i_at(x, y)[i].contents.size(); m++)
       i_at(x, y).push_back( i_at(x, y)[i].contents[m] );
      i_at(x, y).erase(i_at(x, y).begin() + i);
      i--;
     }
    }

    veh = veh_at(x, y, part);
    if (veh)
     veh->damage (part, cur->density * 10, false);
// Consume the terrain we're on
    if (has_flag(explodes, x, y)) {
     ter(x, y) = ter_id(int(ter(x, y)) + 1);
     cur->age = 0;
     cur->density = 3;
     g->explosion(x, y, 40, 0, true);

    } else if (has_flag(flammable, x, y) && one_in(32 - cur->density * 10)) {
     cur->age -= cur->density * cur->density * 40;
     smoke += 15;
     if (cur->density == 3)
      ter(x, y) = t_rubble;

    } else if (has_flag(l_flammable, x, y) && one_in(62 - cur->density * 10)) {
     cur->age -= cur->density * cur->density * 30;
     smoke += 10;
     if (cur->density == 3)
      ter(x, y) = t_rubble;

    } else if (terlist[ter(x, y)].flags & mfb(swimmable))
     cur->age += 800;	// Flames die quickly on water

// If we consumed a lot, the flames grow higher
    while (cur->density < 3 && cur->age < 0) {
     cur->age += 300;
     cur->density++;
    }
// If the flames are in a pit, it can't spread to non-pit
    bool in_pit = (ter(x, y) == t_pit);
// If the flames are REALLY big, they contribute to adjacent flames
    if (cur->density == 3 && cur->age < 0) {
// Randomly offset our x/y shifts by 0-2, to randomly pick a square to spread to
     int starti = rng(0, 2);
     int startj = rng(0, 2);
     for (int i = 0; i < 3 && cur->age < 0; i++) {
      for (int j = 0; j < 3 && cur->age < 0; j++) {
       int fx = x + ((i + starti) % 3) - 1, fy = y + ((j + startj) % 3) - 1;
       if (field_at(fx, fy).type == fd_fire && field_at(fx, fy).density < 3 &&
           (!in_pit || ter(fx, fy) == t_pit)) {
        field_at(fx, fy).density++; 
        field_at(fx, fy).age = 0;
        cur->age = 0;
       }
      }
     }
    }
// Consume adjacent fuel / terrain / webs to spread.
// Randomly offset our x/y shifts by 0-2, to randomly pick a square to spread to
    int starti = rng(0, 2);
    int startj = rng(0, 2);
    for (int i = 0; i < 3; i++) {
     for (int j = 0; j < 3; j++) {
      int fx = x + ((i + starti) % 3) - 1, fy = y + ((j + startj) % 3) - 1;
      if (INBOUNDS(fx, fy)) {
       int spread_chance = 20 * (cur->density - 1) + 10 * smoke;
       if (field_at(fx, fy).type == fd_web)
        spread_chance = 50 + spread_chance / 2;
       if (has_flag(explodes, fx, fy) && one_in(8 - cur->density)) {
        ter(fx, fy) = ter_id(int(ter(fx, fy)) + 1);
        g->explosion(fx, fy, 40, 0, true);
       } else if ((i != 0 || j != 0) && rng(1, 100) < spread_chance &&
                  (!in_pit || ter(fx, fy) == t_pit) &&
                  ((cur->density == 3 &&
                    (has_flag(flammable, fx, fy) || one_in(20))) ||
                   (cur->density == 3 &&
                    (has_flag(l_flammable, fx, fy) && one_in(10))) ||
                   flammable_items_at(fx, fy) ||
                   field_at(fx, fy).type == fd_web)) {
        if (field_at(fx, fy).type == fd_smoke ||
            field_at(fx, fy).type == fd_web)
         field_at(fx, fy) = field(fd_fire, 1, 0);
        else
         add_field(g, fx, fy, fd_fire, 1);
       } else {
        bool nosmoke = true;
        for (int ii = -1; ii <= 1; ii++) {
         for (int jj = -1; jj <= 1; jj++) {
          if (field_at(x+ii, y+jj).type == fd_fire &&
              field_at(x+ii, y+jj).density == 3)
           smoke++;
          else if (field_at(x+ii, y+jj).type == fd_smoke)
           nosmoke = false;
         }
        }
// If we're not spreading, maybe we'll stick out some smoke, huh?
        if (move_cost(fx, fy) > 0 &&
            (!one_in(smoke) || (nosmoke && one_in(40))) && 
            rng(3, 35) < cur->density * 10 && cur->age < 1000) {
         smoke--;
         add_field(g, fx, fy, fd_smoke, rng(1, cur->density));
        }
       }
      }
     }
    }
   } break;
  
   case fd_smoke:
    for (int i = -1; i <= 1; i++) {
     for (int j = -1; j <= 1; j++)
      g->scent(x+i, y+j) = 0;
    }
    if (is_outside(x, y))
     cur->age += 50;
    if (one_in(2)) {
     std::vector <point> spread;
     for (int a = -1; a <= 1; a++) {
      for (int b = -1; b <= 1; b++) {
       if ((field_at(x+a, y+b).type == fd_smoke &&
             field_at(x+a, y+b).density < 3       ) ||
           (field_at(x+a, y+b).is_null() && move_cost(x+a, y+b) > 0))
        spread.push_back(point(x+a, y+b));
      }
     }
     if (cur->density > 0 && cur->age > 0 && spread.size() > 0) {
      point p = spread[rng(0, spread.size() - 1)];
      if (field_at(p.x, p.y).type == fd_smoke &&
          field_at(p.x, p.y).density < 3) {
        field_at(p.x, p.y).density++;
        cur->density--;
      } else if (cur->density > 0 && move_cost(p.x, p.y) > 0 &&
                 add_field(g, p.x, p.y, fd_smoke, 1)){
       cur->density--;
       field_at(p.x, p.y).age = cur->age;
      }
     }
    }
   break;

   case fd_tear_gas:
// Reset nearby scents to zero
    for (int i = -1; i <= 1; i++) {
     for (int j = -1; j <= 1; j++)
      g->scent(x+i, y+j) = 0;
    }
    if (is_outside(x, y))
     cur->age += 30;
// One in three chance that it spreads (less than smoke!)
    if (one_in(3)) {
     std::vector <point> spread;
// Pick all eligible points to spread to
     for (int a = -1; a <= 1; a++) {
      for (int b = -1; b <= 1; b++) {
       if (((field_at(x+a, y+b).type == fd_smoke ||
             field_at(x+a, y+b).type == fd_tear_gas) &&
             field_at(x+a, y+b).density < 3            )      ||
           (field_at(x+a, y+b).is_null() && move_cost(x+a, y+b) > 0))
        spread.push_back(point(x+a, y+b));
      }
     }
// Then, spread to a nearby point
     if (cur->density > 0 && cur->age > 0 && spread.size() > 0) {
      point p = spread[rng(0, spread.size() - 1)];
// Nearby teargas grows thicker
      if (field_at(p.x, p.y).type == fd_tear_gas &&
          field_at(p.x, p.y).density < 3) {
        field_at(p.x, p.y).density++;
        cur->density--;
// Nearby smoke is converted into teargas
      } else if (field_at(p.x, p.y).type == fd_smoke) {
       field_at(p.x, p.y).type = fd_tear_gas;
// Or, just create a new field.
      } else if (cur->density > 0 && move_cost(p.x, p.y) > 0 &&
                 add_field(g, p.x, p.y, fd_tear_gas, 1)) {
       cur->density--;
       field_at(p.x, p.y).age = cur->age;
      }
     }
    }
    break;

   case fd_toxic_gas:
// Reset nearby scents to zero
    for (int i = -1; i <= 1; i++) {
     for (int j = -1; j <= 1; j++)
      g->scent(x+i, y+j) = 0;
    }
    if (is_outside(x, y))
     cur->age += 40;
    if (one_in(2)) {
     std::vector <point> spread;
// Pick all eligible points to spread to
     for (int a = -1; a <= 1; a++) {
      for (int b = -1; b <= 1; b++) {
       if (((field_at(x+a, y+b).type == fd_smoke ||
             field_at(x+a, y+b).type == fd_tear_gas ||
             field_at(x+a, y+b).type == fd_toxic_gas ||
             field_at(x+a, y+b).type == fd_nuke_gas   ) &&
             field_at(x+a, y+b).density < 3            )      ||
           (field_at(x+a, y+b).is_null() && move_cost(x+a, y+b) > 0))
        spread.push_back(point(x+a, y+b));
      }
     }
// Then, spread to a nearby point
     if (cur->density > 0 && cur->age > 0 && spread.size() > 0) {
      point p = spread[rng(0, spread.size() - 1)];
// Nearby toxic gas grows thicker
      if (field_at(p.x, p.y).type == fd_toxic_gas &&
          field_at(p.x, p.y).density < 3) {
        field_at(p.x, p.y).density++;
        cur->density--;
// Nearby smoke & teargas is converted into toxic gas
      } else if (field_at(p.x, p.y).type == fd_smoke ||
                 field_at(p.x, p.y).type == fd_tear_gas) {
       field_at(p.x, p.y).type = fd_toxic_gas;
// Or, just create a new field.
      } else if (cur->density > 0 && move_cost(p.x, p.y) > 0 &&
                 add_field(g, p.x, p.y, fd_toxic_gas, 1)) {
       cur->density--;
       field_at(p.x, p.y).age = cur->age;
      }
     }
    }
    break;


   case fd_nuke_gas:
// Reset nearby scents to zero
    for (int i = -1; i <= 1; i++) {
     for (int j = -1; j <= 1; j++)
      g->scent(x+i, y+j) = 0;
    }
    if (is_outside(x, y))
     cur->age += 40;
// Increase long-term radiation in the land underneath
    radiation(x, y) += rng(0, cur->density);
    if (one_in(2)) {
     std::vector <point> spread;
// Pick all eligible points to spread to
     for (int a = -1; a <= 1; a++) {
      for (int b = -1; b <= 1; b++) {
       if (((field_at(x+a, y+b).type == fd_smoke ||
             field_at(x+a, y+b).type == fd_tear_gas ||
             field_at(x+a, y+b).type == fd_toxic_gas ||
             field_at(x+a, y+b).type == fd_nuke_gas   ) &&
             field_at(x+a, y+b).density < 3            )      ||
           (field_at(x+a, y+b).is_null() && move_cost(x+a, y+b) > 0))
        spread.push_back(point(x+a, y+b));
      }
     }
// Then, spread to a nearby point
     if (cur->density > 0 && cur->age > 0 && spread.size() > 0) {
      point p = spread[rng(0, spread.size() - 1)];
// Nearby nukegas grows thicker
      if (field_at(p.x, p.y).type == fd_nuke_gas &&
          field_at(p.x, p.y).density < 3) {
        field_at(p.x, p.y).density++;
        cur->density--;
// Nearby smoke, tear, and toxic gas is converted into nukegas
      } else if (field_at(p.x, p.y).type == fd_smoke ||
                 field_at(p.x, p.y).type == fd_toxic_gas ||
                 field_at(p.x, p.y).type == fd_tear_gas) {
       field_at(p.x, p.y).type = fd_nuke_gas;
// Or, just create a new field.
      } else if (cur->density > 0 && move_cost(p.x, p.y) > 0 &&
                 add_field(g, p.x, p.y, fd_nuke_gas, 1)) {
       cur->density--;
       field_at(p.x, p.y).age = cur->age;
      }
     }
    }
    break;

   case fd_gas_vent:
    for (int i = x - 1; i <= x + 1; i++) {
     for (int j = y - 1; j <= y + 1; j++) {
      if (field_at(i, j).type == fd_toxic_gas && field_at(i, j).density < 3)
       field_at(i, j).density++;
      else
       add_field(g, i, j, fd_toxic_gas, 3);
     }
    }
    break;

   case fd_fire_vent:
    if (cur->density > 1) {
     if (one_in(3))
      cur->density--;
    } else {
     cur->type = fd_flame_burst;
     cur->density = 3;
    }
    break;

   case fd_flame_burst:
    if (cur->density > 1)
     cur->density--;
    else {
     cur->type = fd_fire_vent;
     cur->density = 3;
    }
    break;

   case fd_electricity:
    if (!one_in(5)) {	// 4 in 5 chance to spread
     std::vector<point> valid;
     if (move_cost(x, y) == 0 && cur->density > 1) { // We're grounded
      int tries = 0;
      while (tries < 10 && cur->age < 50) {
       int cx = x + rng(-1, 1), cy = y + rng(-1, 1);
       if (move_cost(cx, cy) != 0 && field_at(cx, cy).is_null()) {
        add_field(g, cx, cy, fd_electricity, 1);
        cur->density--;
        tries = 0;
       } else
        tries++;
      }
     } else {	// We're not grounded; attempt to ground
      for (int a = -1; a <= 1; a++) {
       for (int b = -1; b <= 1; b++) {
        if (move_cost(x + a, y + b) == 0 && // Grounded tiles first
            field_at(x + a, y + b).is_null())
         valid.push_back(point(x + a, y + b));
       }
      }
      if (valid.size() == 0) {	// Spread to adjacent space, then
       int px = x + rng(-1, 1), py = y + rng(-1, 1);
       if (move_cost(px, py) > 0 && field_at(px, py).type == fd_electricity &&
           field_at(px, py).density < 3)
        field_at(px, py).density++;
       else if (move_cost(px, py) > 0)
        add_field(g, px, py, fd_electricity, 1);
       cur->density--;
      }
      while (valid.size() > 0 && cur->density > 0) {
       int index = rng(0, valid.size() - 1);
       add_field(g, valid[index].x, valid[index].y, fd_electricity, 1);
       cur->density--;
       valid.erase(valid.begin() + index);
      }
     }
    }
    break;

   case fd_fatigue:
    if (cur->density < 3 && int(g->turn) % 3600 == 0 && one_in(10))
     cur->density++;
    else if (cur->density == 3 && one_in(600)) { // Spawn nether creature!
     mon_id type = mon_id(rng(mon_flying_polyp, mon_blank));
     monster creature(g->mtypes[type]);
     creature.spawn(x + rng(-3, 3), y + rng(-3, 3));
     g->z.push_back(creature);
    }
    break;

   case fd_push_items: {
    std::vector<item> *it = &(i_at(x, y));
    for (int i = 0; i < it->size(); i++) {
     if ((*it)[i].type->id != itm_rock || (*it)[i].bday >= int(g->turn) - 1)
      i++;
     else {
      item tmp = (*it)[i];
      tmp.bday = int(g->turn);
      it->erase(it->begin() + i);
      i--;
      std::vector<point> valid;
      for (int xx = x - 1; xx <= x + 1; xx++) {
       for (int yy = y - 1; yy <= y + 1; yy++) {
        if (field_at(xx, yy).type == fd_push_items)
         valid.push_back( point(xx, yy) );
       }
      }
      if (!valid.empty()) {
       point newp = valid[rng(0, valid.size() - 1)];
       add_item(newp.x, newp.y, tmp);
       if (g->u.posx == newp.x && g->u.posy == newp.y) {
        g->add_msg("A %s hits you!", tmp.tname().c_str());
        g->u.hit(g, random_body_part(), rng(0, 1), 6, 0);
       }
       int npcdex = g->npc_at(newp.x, newp.y),
           mondex = g->mon_at(newp.x, newp.y);

       if (npcdex != -1) {
        int junk;
        npc *p = &(g->active_npc[npcdex]);
        p->hit(g, random_body_part(), rng(0, 1), 6, 0);
        if (g->u_see(newp.x, newp.y, junk))
         g->add_msg("A %s hits %s!", tmp.tname().c_str(), p->name.c_str());
       }

       if (mondex != -1) {
        int junk;
        monster *mon = &(g->z[mondex]);
        mon->hurt(6 - mon->armor_bash());
        if (g->u_see(newp.x, newp.y, junk))
         g->add_msg("A %s hits the %s!", tmp.tname().c_str(),
                                         mon->name().c_str());
       }
      }
     }
    }
   } break;

   case fd_shock_vent:
    if (cur->density > 1) {
     if (one_in(5))
      cur->density--;
    } else {
     cur->density = 3;
     int num_bolts = rng(3, 6);
     for (int i = 0; i < num_bolts; i++) {
      int xdir = 0, ydir = 0;
      while (xdir == 0 && ydir == 0) {
       xdir = rng(-1, 1);
       ydir = rng(-1, 1);
      }
      int dist = rng(4, 12);
      int boltx = x, bolty = y;
      for (int n = 0; n < dist; n++) {
       boltx += xdir;
       bolty += ydir;
       add_field(g, boltx, bolty, fd_electricity, rng(2, 3));
       if (one_in(4)) {
        if (xdir == 0)
         xdir = rng(0, 1) * 2 - 1;
        else
         xdir = 0;
       }
       if (one_in(4)) {
        if (ydir == 0)
         ydir = rng(0, 1) * 2 - 1;
        else
         ydir = 0;
       }
      }
     }
    }
    break;

   case fd_acid_vent:
    if (cur->density > 1) {
     if (cur->age >= 10) {
      cur->density--;
      cur->age = 0;
     }
    } else {
     cur->density = 3;
     for (int i = x - 5; i <= x + 5; i++) {
      for (int j = y - 5; j <= y + 5; j++) {
       if (field_at(i, j).type == fd_null || field_at(i, j).density == 0) {
        int newdens = 3 - (rl_dist(x, y, i, j) / 2) + (one_in(3) ? 1 : 0);
        if (newdens > 3)
         newdens = 3;
        if (newdens > 0)
         add_field(g, i, j, fd_acid, newdens);
       }
      }
     }
    }
    break;

   } // switch (curtype)
  
   cur->age++;
   if (fieldlist[cur->type].halflife > 0) {
    if (cur->age > 0 &&
        dice(3, cur->age) > dice(3, fieldlist[cur->type].halflife)) {
     cur->age = 0;
     cur->density--;
    }
    if (cur->density <= 0) { // Totally dissapated.
     grid[gridn]->field_count--;
     grid[gridn]->fld[locx][locy] = field();
    }
   }
  }
 }
 return found_field;
}
// -----------------------------------------------------------------------------
// Set attribute of top stack element to given value.
// -----------------------------------------------------------------------------
void SimXMLDocument::setObjectAttributes(const char* objectID)
{
   if( !objectID || !objectID[0] )
      return;

   if(m_paNode.empty())
      return;

   SimObject *pObject = Sim::findObject( objectID );

   if( pObject == NULL )
      return;

   const int iLastElement = m_paNode.size() - 1;
   TiXmlElement* pElement = m_paNode[iLastElement];
   if(!pElement)
      return;

   char textbuf[1024];
   TiXmlElement field( "Field" );
   TiXmlElement group( "FieldGroup" );
   pElement->SetAttribute( "Name", pObject->getName() );


      // Iterate over our filed list and add them to the XML document...
      AbstractClassRep::FieldList fieldList = pObject->getFieldList();
      AbstractClassRep::FieldList::iterator itr;
      for(itr = fieldList.begin(); itr != fieldList.end(); itr++)
      {

         if( itr->type == AbstractClassRep::DepricatedFieldType ||
            itr->type == AbstractClassRep::StartGroupFieldType ||
            itr->type == AbstractClassRep::EndGroupFieldType) continue;

         // Not an Array
         if(itr->elementCount == 1)
         {
            // get the value of the field as a string.
            ConsoleBaseType *cbt = ConsoleBaseType::getType(itr->type);

            const char *val = Con::getData(itr->type, (void *) (((const char *)pObject) + itr->offset), 0, itr->table, itr->flag);

            // Make a copy for the field check.
            if (!val)
               continue;

            FrameTemp<char> valCopy( dStrlen( val ) + 1 );
            dStrcpy( (char *)valCopy, val );

            if (!pObject->writeField(itr->pFieldname, valCopy))
               continue;

            val = valCopy;


            expandEscape(textbuf, val);

            if( !pObject->writeField( itr->pFieldname, textbuf ) )
               continue;

            field.SetValue( "Property" );
            field.SetAttribute( "name",  itr->pFieldname );
            if( cbt != NULL )
               field.SetAttribute( "type", cbt->getTypeName() );
            else
               field.SetAttribute( "type", "TypeString" );
            field.SetAttribute( "data", textbuf );

            pElement->InsertEndChild( field );

            continue;
         }
      }

      //// IS An Array
      //for(U32 j = 0; S32(j) < f->elementCount; j++)
      //{

      //   // If the start of a group create an element for the group and
      //   // the our chache to it
      //   const char *val = Con::getData(itr->type, (void *) (((const char *)pObject) + itr->offset), j, itr->table, itr->flag);

      //   // Make a copy for the field check.
      //   if (!val)
      //      continue;

      //   FrameTemp<char> valCopy( dStrlen( val ) + 1 );
      //   dStrcpy( (char *)valCopy, val );

      //   if (!pObject->writeField(itr->pFieldname, valCopy))
      //      continue;

      //   val = valCopy;

      //      // get the value of the field as a string.
      //      ConsoleBaseType *cbt = ConsoleBaseType::getType(itr->type);
      //      const char * dstr = Con::getData(itr->type, (void *)(((const char *)pObject) + itr->offset), 0, itr->table, itr->flag);
      //      if(!dstr)
      //         dstr = "";
      //      expandEscape(textbuf, dstr);


      //      if( !pObject->writeField( itr->pFieldname, dstr ) )
      //         continue;

      //      field.SetValue( "Property" );
      //      field.SetAttribute( "name",  itr->pFieldname );
      //      if( cbt != NULL )
      //         field.SetAttribute( "type", cbt->getTypeName() );
      //      else
      //         field.SetAttribute( "type", "TypeString" );
      //      field.SetAttribute( "data", textbuf );

      //      pElement->InsertEndChild( field );
      //}

}
void PageOffer_Amounts::initializePage()
{
    const bool bIsBid = field("bid").toBool();

    if (bIsBid)
    {
        ui->labelPrice   ->setText(QString("%1:").arg(tr("At Maximum Price")));
        ui->labelQuantity->setText(QString("%1:").arg(tr("Units Buying")));
        ui->labelTotal   ->setText(QString("%1:").arg(tr("Total Quantity for Purchase")));
    }
    else
    {
        ui->labelPrice   ->setText(QString("%1:").arg(tr("At Minimum Price")));
        ui->labelQuantity->setText(QString("%1:").arg(tr("Units Selling")));
        ui->labelTotal   ->setText(QString("%1:").arg(tr("Total Quantity for Sale")));
    }
    // ----------------------------------------------
//    QString qstrAssetName    = field("AssetName")   .toString();
//    QString qstrCurrencyName = field("CurrencyName").toString();

//    ui->labelAssetName   ->setText(qstrAssetName);
//    ui->labelCurrencyName->setText(qstrCurrencyName);
    // ----------------------------------------------
    QString qstrAssetID = field("AssetID").toString();
    const std::string str_asset(qstrAssetID.toStdString());
    // ----------------------------------------------
    // Populate the Combo Box
    //
    ui->comboBox->blockSignals(true);

    ui->comboBox->clear();

    for (int ii = 0; ii < 8; ++ii)
    {
        float   dValue = std::pow(10.0, ii);
        long    lScale = static_cast<long>(dValue);

        OTString strTemp;
        strTemp.Format("%ld.", lScale); // So 1 becomes "1." which StringToAmount makes into 1.000 which is actually 1000

        const std::string str_input(strTemp.Get());

        int64_t lAmount = OTAPI_Wrap::It()->StringToAmount(str_asset, str_input);

        std::string str_formatted = OTAPI_Wrap::It()->FormatAmount(str_asset, lAmount);
        QString qstrFormatted(QString::fromStdString(str_formatted));

        QVariant qvarVal(static_cast<qlonglong>(lAmount));

        ui->comboBox->addItem(qstrFormatted, qvarVal);
    }
    // ----------------------------------------------
    ui->comboBox->blockSignals(false);

    ui->comboBox->setCurrentIndex(-1);
    ui->comboBox->setCurrentIndex(0);
    // ----------------------------------------------
    const QString array_timename[] = {
        QString(tr("one minute")),
        QString(tr("one hour")),
        QString(tr("one day")),
        QString(tr("one month")),
        QString(tr("three months")),
        QString(tr("six months")),
        QString(tr("one year"))
    };

    ui->comboBoxExpiration->clear();

    for (int ii = 0; ii < 7; ++ii)
    {
        QVariant qvarTime(static_cast<qlonglong>(array_timespan[ii]));
        ui->comboBoxExpiration->addItem(array_timename[ii], qvarTime);
    }

    if (ui->comboBoxExpiration->count() >= 3)
        ui->comboBoxExpiration->setCurrentIndex(2);
    else if (ui->comboBoxExpiration->count() >= 1)
        ui->comboBoxExpiration->setCurrentIndex(0);
    // ----------------------------------------------
    ui->lineEditPrice->setText("");
    // ----------------------------------------------
    RadioChanged();
}
Exemple #13
0
bool CNetScheduleKey::ParseJobKey(const string& key_str,
        CCompoundIDPool::TInstance id_pool)
{
    // Parses several notations for job id:
    // version 1:
    //   JSID_01_JOBNUMBER_IP_PORT_QUEUE
    // "version 0", or just a job number.

    const char* ch = key_str.c_str();
    if (key_str.compare(0, NS_KEY_V1_PREFIX_LEN, NS_KEY_V1_PREFIX) == 0) {
        // Version 1 key
        version = 1;
        ch += NS_KEY_V1_PREFIX_LEN;

        // Extract the job number field.
        if ((id = (unsigned) atoi(ch)) == 0)
            return false;
        do
            if (*++ch == '\0')
                return false;
        while (*ch != '_');

        // Find the host name field boundaries.
        const char* token_begin = ++ch;
        while (*ch != '\0' && *ch++ != '_')
            /* noop */;

        // Extract the server port number.
        if ((port = (unsigned short) atoi(ch)) == 0)
            return false;

        // Everything's OK so far, save the host name/IP.
        host.assign(token_begin, ch - token_begin - 1);
        if (host.empty())
            return false;

        // Skip to the queue name.
        while (*++ch != '_')
            if (*ch < '0' || *ch > '9')
                return *ch == '\0';

        // Queue name is specified - extract it.
        int underscores_to_skip = 0;
        while (*++ch == '_')
            ++underscores_to_skip;
        if (*ch == '\0')
            return false;
        // At this point, *ch is neither '_' nor '\0'.
        token_begin = ch;
        while (*++ch != '\0')
            if ((*ch < '0' || *ch > '9') && (*ch < 'a' || *ch > 'z') &&
                    (*ch < 'A' || *ch > 'Z') && *ch != '-') {
                if (*ch != '_')
                    return false;
                else if (--underscores_to_skip < 0)
                    break;
            }
        if (underscores_to_skip > 0)
            return false;
        queue.assign(token_begin, ch - token_begin);

        return true;
    } else if (id_pool != NULL) {
        try {
            CCompoundIDPool pool_obj(id_pool);
            CCompoundID cid(pool_obj.FromString(key_str));
            version = 2;
            CCompoundIDField field(cid.GetFirst(eCIT_ID));
            if (field) {
                id = (unsigned) field.GetID();
                field = cid.GetFirst(eCIT_DatabaseName);
                if (field)
                    queue = field.GetDatabaseName();
                field = cid.GetFirst(eCIT_IPv4SockAddr);
                if (field) {
                    host = CSocketAPI::ntoa(field.GetIPv4Address());
                    port = field.GetPort();
                    return true;
                } else {
                    field = cid.GetFirst(eCIT_Host);
                    if (field) {
                        host = field.GetHost();
                        field = cid.GetFirst(eCIT_Port);
                        if (field) {
                            port = field.GetPort();
                            return true;
                        }
                    }
                }
            }
        }
        catch (CCompoundIDException&) {
            // Do not exit the function yet -- check if
            // it's a verbatim job ID.
        }
    }

    if (isdigit(*ch)) {
        version = 0;
        id = (unsigned) atoi(ch);
        return true;
    }

    return false;
}
uint16 PPUcounter::hdot() const {
  if(system.region.i == System::Region::NTSC && status.interlace == false && vcounter() == 240 && field() == 1) {
    return (hcounter() >> 2);
  } else {
    return (hcounter() - ((hcounter() > 1292) << 1) - ((hcounter() > 1310) << 1)) >> 2;
Exemple #15
0
bool PHIWizardInstall::validatePage()
{
    if ( _readme->isChecked() ) {
        QDialog dlg( this );
        dlg.setWindowTitle( tr( "README" ) );
        dlg.setSizeGripEnabled( true );
        dlg.resize( 400, 300 );
        QFile f( QDir::currentPath()+"/README.txt" );
        if ( f.open( QIODevice::ReadOnly ) ) {
            QTextStream t( &f );
            QString readme=t.readAll();
            readme.replace( "\r\n", "\n" );
            f.close();
            QPlainTextEdit *edit=new QPlainTextEdit( &dlg );
            edit->setPlainText( readme );
            edit->setReadOnly( true );
            QPushButton *close=new QPushButton( tr( "Close" ) );
            connect( close, SIGNAL( clicked() ), &dlg, SLOT( accept() ) );
            QVBoxLayout *vbox=new QVBoxLayout();
            vbox->addWidget( edit );
            QHBoxLayout *hbox=new QHBoxLayout();
            hbox->addStretch();
            hbox->addWidget( close );
            vbox->addLayout( hbox );
            dlg.setLayout( vbox );
            dlg.exec();
        }
    }
    QProcessEnvironment env=QProcessEnvironment::systemEnvironment();
    QString libpath=env.value( "LD_LIBRARY_PATH" );
    libpath=field( "rootdir" ).toString()+"/lib:"+libpath;
    env.insert( "LD_LIBRARY_PATH", libpath );
    env.insert( "LD_LIBRARY_PATH_64", libpath );
    env.insert( "QT_PLUGIN_PATH", field( "rootdir" ).toString()+"/plugins" );
    if ( _phis->isChecked() ) {
        QProcess p_phis;
        p_phis.setProcessEnvironment( env );
        p_phis.start( "/usr/bin/killall -q -w phis" );
        p_phis.waitForFinished( 10000 );
        p_phis.startDetached( field( "rootdir" ).toString()+"/bin/phis -platform minimal" );
    }
    if ( _artephis->isChecked() ) {
        QProcess p_artephis;
        p_artephis.setProcessEnvironment( env );
        p_artephis.startDetached( field( "rootdir" ).toString()+"/bin/artephis" );
    }
    if ( _daemon->isChecked() ) {
        QFile f( "/etc/init.d/phis" );
        if ( !f.exists() ) {
            QMessageBox::warning( this, tr( "Daemon" ), tr( "Could not find the daemon"
               " script '%1'. Phis daemon will not be installed." )
               .arg( f.fileName() ), QMessageBox::Ok );
        } else {
            f.link( "/etc/rc0.d/K10phis" );
            f.link( "/etc/rc1.d/K10phis" );
            f.link( "/etc/rc2.d/S90phis" );
            f.link( "/etc/rc3.d/S90phis" );
            f.link( "/etc/rc4.d/S90phis" );
            f.link( "/etc/rc5.d/S90phis" );
            f.link( "/etc/rc6.d/K10phis" );
        }
    }
    if ( field( "apache" ).toBool() ) {
        QString adir=field( "apachedir" ).toString();
        if ( !QFile::exists( adir ) ) {
            QMessageBox::warning( this, tr( "Apache" ), tr( "The provided Apache dir '%1' "
                "is not found. The Phi module for apache could not be linked. "
                "You need to setup the module manually." ).arg( adir ), QMessageBox::Ok  );
        } else {
            QFile f( field( "rootdir" ).toString()+"/lib/libmod_phi.so.1" );
            if ( f.exists() ) {
                if ( QFile::exists( adir+"/modules" ) ) adir=adir+"/modules";
                QFile modphi( adir+"/mod_phi.so" );
                if ( modphi.exists() ) modphi.remove();
                f.link( adir+"/mod_phi.so" );
            } else {
                QMessageBox::warning( this, tr( "Apache" ), tr( "Could not find '%1' "
                    "You need to setup the Phi module manually." )
                    .arg( f.fileName() ), QMessageBox::Ok );
            }
        }
    }
    return true;
}
Exemple #16
0
unsigned int Parser::arg2() const {
	assert(fields(current_line_) >= 2);
	return std::stoi(field(current_line_, 2));
}
Exemple #17
0
//-------------------------------------------
//  i/o operation (octet string)
//-------------------------------------------
void bn254_fp2_to_mpz(mpz_t a, const Element x)
{
    mpz_set(a, rep(rep0(x)));   // a = rep0
    mpz_addmul(a, rep(rep1(x)), field(x)->base->order);   //a = a + rep1*p
}
Exemple #18
0
CommandType Parser::commandType() const {
// PRE:	current_line_ is a validCommand()
	assert(validCommand(current_line_));
	return commands_.at(field(current_line_, 0)).first;
}
Exemple #19
0
bool ScriptRunPage::forkScp(QString nextFile)
{
	QString srcFile, destFile;
	const int num_chars_from_right = nextFile.length() - field("fileBase").toString().length();

	QString port, rsaKey, nameAtHost;

	if(field("btnFriendList").toBool())
	{
		// TODO (FRIEND): Read these values from DB
	}
	else
	{
		port = field("port").toString();
		rsaKey = field("rsaKey").toString();
		nameAtHost = field("nameAtHost").toString();
	}
	const QString ip = field("ip").toString();

	puts("forkScp");
	scps_pid=fork();
	if(scps_pid < 0) {
		QMessageBox::information(this, "Sorry...", "... fork() ging leider nicht, kann scp nicht starten :(");
		return false;
	}	
	else if(scps_pid == 0) {

		{
		QString appendix = nextFile.right(num_chars_from_right);
		QString destDir = appendix.left(appendix.lastIndexOf('/'));
		destDir.replace("'", "'");
		destDir.replace(" ", " ");
		QString mkdirCommand = QString("mkdir -p \"%6/%7\"").arg(
			globals::MUSIC_ROOT,
			destDir);

		nextFile.replace("'", "'");
		nextFile.replace(" ", " ");
		printf("%s\n",mkdirCommand.toAscii().data());
		QString scpCommand = QString("scp -P %1 -i %2 %3@%4:\"%5\" \"%6/%7\"")
				.arg(	port,
					rsaKey,
					nameAtHost,
					ip,
					nextFile,globals::MUSIC_ROOT,
					destDir);
		//sleep(1);
//		printf("%s\n",scpCommand.toAscii().data());
		scpCommand.replace("'", "'");
		scpCommand.replace(" ", " ");
		system(mkdirCommand.toAscii().data()); // TODO: use execv
//		system(scpCommand.toAscii().data());
//		progressBar.setValue(progressBar.value()+1);

		// TODO: full path for first argument
		srcFile = QString("%1@%2:\"%3\"").arg(nameAtHost,
				ip,
				nextFile);
		destFile = QString("%6/%7").arg(globals::MUSIC_ROOT,
			destDir);

		}

		printf("scp -P %s -i %s %s %s\n",
			port.toAscii().data(), rsaKey.toAscii().data(),
			srcFile.toAscii().data(), destFile.toAscii().data());

		execlp("scp", "scp",
			"-P", port.toAscii().data(),
			"-i", rsaKey.toAscii().data(),
			srcFile.toAscii().data(),
			destFile.toAscii().data(),
			NULL);

		exit(0);
	}
	return true;
}
Exemple #20
0
QString UIWizardExportApp::uri(bool fWithFile) const
{
    StorageType type = field("storageType").value<StorageType>();

    QString path = field("path").toString();
    if (!fWithFile)
    {
        QFileInfo fi(path);
        path = fi.path();
    }
    switch (type)
    {
        case Filesystem:
        {
            return path;
        }
        case SunCloud:
        {
            QString uri("SunCloud://");
            if (!field("username").toString().isEmpty())
                uri = QString("%1%2").arg(uri).arg(field("username").toString());
            if (!field("password").toString().isEmpty())
                uri = QString("%1:%2").arg(uri).arg(field("password").toString());
            if (!field("username").toString().isEmpty() || !field("username").toString().isEmpty())
                uri = QString("%1@").arg(uri);
            uri = QString("%1%2/%3/%4").arg(uri).arg("object.storage.network.com").arg(field("bucket").toString()).arg(path);
            return uri;
        }
        case S3:
        {
            QString uri("S3://");
            if (!field("username").toString().isEmpty())
                uri = QString("%1%2").arg(uri).arg(field("username").toString());
            if (!field("password").toString().isEmpty())
                uri = QString("%1:%2").arg(uri).arg(field("password").toString());
            if (!field("username").toString().isEmpty() || !field("password").toString().isEmpty())
                uri = QString("%1@").arg(uri);
            uri = QString("%1%2/%3/%4").arg(uri).arg(field("hostname").toString()).arg(field("bucket").toString()).arg(path);
            return uri;
        }
    }
    return QString();
}
Exemple #21
0
int main(int argc, char** argv)
{
    try
    {
        nitf_Error e;

//        Foo<int>* foo = new Bar<int>();
//        delete foo;

        nitf_Field* cField = nitf_Field_construct(100, NITF_BCS_N, &e);
        nitf::Field field(cField);

        {
            nitf::Field field2(cField);
        }

        std::cout << field.isValid() << std::endl;


        nitf_BandInfo* cBandInfo = nitf_BandInfo_construct(&e);
        assert(cBandInfo);

        nitf::BandInfo info(cBandInfo);

        std::cout << (int)info.getNumLUTs() << std::endl;

        std::cout << "HERE!!!!!!!!!!!!!!!!!!!!" << std::endl;
        nitf::SubWindow sub;
        nitf::SubWindow sub2 = sub;
        sub.setNumRows(5);

        nitf::PixelSkip p(1, 1);
        sub.setDownSampler(p);
        sub.setDownSampler(p);
        sub.setDownSampler(p);
        sub.setDownSampler(p);

        nitf::PixelSkip p2(1, 1);
        sub.setDownSampler(p2);
        sub.setDownSampler(p);


        nitf_SubWindow* subw = nitf_SubWindow_construct(&e);
        nitf::SubWindow sub3(subw);
        std::cout << sub.getNumRows() <<  " == " << sub2.getNumRows() << std::endl;


        nitf::List list;
        nitf::List list2 = list;

        {
            nitf::FileHeader header;
            nitf::FileHeader header2(header.clone());
            //should be not equal
            std::cout << "Equal? " << (header == header2) << std::endl;
            nitf::FileHeader header3(header2);
            //these two should be equal
            std::cout << "Equal? " << (header3 == header2) << std::endl;
        }

        nitf::HashTable hash;

        nitf::Extensions extensions;
        {
            nitf::ImageSegment imageSeg;
            nitf::ImageSubheader imageSub;

            imageSeg.getSubheader().getImageId() = "Test Image";
            std::cout << imageSeg.getSubheader().getImageId().toString() << std::endl;
            nitf::Field f = imageSeg.getSubheader().getImageId();
            std::cout << f.toString() << std::endl;

            nitf::ImageSegment imageSeg2 = imageSeg.clone();
            nitf::ImageSubheader imageSub2(imageSub.clone());

            extensions = imageSub.getExtendedSection();
        }

        nitf::TextSegment tSeg;
        nitf::TextSubheader tSub;

        nitf::GraphicSegment gSeg;
        nitf::GraphicSubheader gSub;

        nitf::DESegment dSeg;
        nitf::DESubheader dSub;

        nitf::LabelSegment rSeg;
        nitf::LabelSubheader rSub;

        nitf::TRE tre("JITCID");
        //tre.print();
        std::cout << "HERE!!!!!" << std::endl;

        nitf::Reader reader;
        nitf::Writer writer;


        //open a file
        sys::OS os;
        std::vector< std::string > files;
        for (int i = 1; i < argc; ++i)
        {
            if (!os.exists(argv[i]))
                std::cout << "Error -> File does not exist: " << argv[i] << std::endl;
            else
                files.push_back(argv[i]);
        }

        for (std::vector< std::string >::iterator it = files.begin(); it != files.end(); ++it)
        {
            nitf::IOHandle handle(*it);
            nitf::Reader rdr;
            nitf::Record rec = rdr.read(handle);

            std::cout << "CODEWORDS: " << rec.getHeader().getSecurityGroup().getCodewords().toString() << std::endl;
            rec.getHeader().getSecurityGroup().getCodewords() = "TEST";
            std::cout << "CODEWORDS: " << rec.getHeader().getSecurityGroup().getCodewords().toString() << std::endl;
            nitf::FileSecurity security;
            rec.getHeader().setSecurityGroup(security);
            std::cout << "CODEWORDS: " << rec.getHeader().getSecurityGroup().getCodewords().toString() << std::endl;
            std::cout << "Num Images: " << rec.getImages().getSize() << std::endl;
        }

        nitf_SubWindow_destruct(&subw);
        nitf_Field_destruct(&cField);
        nitf_BandInfo_destruct(&cBandInfo);
    }
    catch(except::Exception& ex)
    {
        std::cerr << "ERROR: " << ex.getMessage() << std::endl;
        return 1;
    }

    return 0;
}
Exemple #22
0
bool UIWizardExportApp::exportAppliance()
{
    /* Get export appliance widget: */
    UIApplianceExportEditorWidget *pExportApplianceWidget = field("applianceWidget").value<ExportAppliancePointer>();
    /* Fetch all settings from the appliance editor. */
    pExportApplianceWidget->prepareExport();
    /* Get the appliance. */
    CAppliance *pAppliance = pExportApplianceWidget->appliance();
    /* We need to know every filename which will be created, so that we can
     * ask the user for confirmation of overwriting. For that we iterating
     * over all virtual systems & fetch all descriptions of the type
     * HardDiskImage. Also add the manifest file to the check. In the ova
     * case only the target file itself get checked. */
    QFileInfo fi(field("path").toString());
    QVector<QString> files;
    files << fi.fileName();
    if (fi.suffix().toLower() == "ovf")
    {
        if (field("manifestSelected").toBool())
            files << fi.baseName() + ".mf";
        CVirtualSystemDescriptionVector vsds = pAppliance->GetVirtualSystemDescriptions();
        for (int i = 0; i < vsds.size(); ++ i)
        {
            QVector<KVirtualSystemDescriptionType> types;
            QVector<QString> refs, origValues, configValues, extraConfigValues;
            vsds[i].GetDescriptionByType(KVirtualSystemDescriptionType_HardDiskImage, types,
                                         refs, origValues, configValues, extraConfigValues);
            foreach (const QString &s, origValues)
                files << QString("%2").arg(s);
        }
    }
    CVFSExplorer explorer = pAppliance->CreateVFSExplorer(uri(false /* fWithFile */));
    CProgress progress = explorer.Update();
    bool fResult = explorer.isOk();
    if (fResult)
    {
        /* Show some progress, so the user know whats going on: */
        msgCenter().showModalProgressDialog(progress, QApplication::translate("UIWizardExportApp", "Checking files ..."),
                                            ":/refresh_32px.png", this);
        if (progress.GetCanceled())
            return false;
        if (!progress.isOk() || progress.GetResultCode() != 0)
        {
            msgCenter().cannotCheckFiles(progress, this);
            return false;
        }
    }
    QVector<QString> exists = explorer.Exists(files);
    /* Check if the file exists already, if yes get confirmation for overwriting from the user. */
    if (!msgCenter().confirmOverridingFiles(exists, this))
        return false;
    /* Ok all is confirmed so delete all the files which exists: */
    if (!exists.isEmpty())
    {
        CProgress progress1 = explorer.Remove(exists);
        fResult = explorer.isOk();
        if (fResult)
        {
            /* Show some progress, so the user know whats going on: */
            msgCenter().showModalProgressDialog(progress1, QApplication::translate("UIWizardExportApp", "Removing files ..."),
                                                ":/vm_delete_32px.png", this);
            if (progress1.GetCanceled())
                return false;
            if (!progress1.isOk() || progress1.GetResultCode() != 0)
            {
                msgCenter().cannotRemoveFiles(progress1, this);
                return false;
            }
        }
    }

    /* Export the VMs, on success we are finished: */
    if (exportVMs(*pAppliance))
    {
#if 0
        /* Save attributes to GUI extra data: */
        StorageType storageType = field("storageType").value<StorageType>();
        vboxGlobal().virtualBox().SetExtraData(GUI_Export_StorageType, QString::number(storageType));
        vboxGlobal().virtualBox().SetExtraData(GUI_Export_Username, m_pLeUsername->text());
        vboxGlobal().virtualBox().SetExtraData(GUI_Export_Hostname, m_pLeHostname->text());
        vboxGlobal().virtualBox().SetExtraData(GUI_Export_Bucket, m_pLeBucket->text());
#endif
        return true;
    }
    return false;
}
bool NewBuildingWizard::IsExistingOMT()
{
    return field("ExistingOMT").toBool();
}
void
DijkstraPathfinder::make_neighbors_open(Node& cnode)
{
  // FIXME: We don't handle neightbors with smaller cost here
  /*
    if n' is in Open
    and n'.cost < = newcost
    continue
  */
  if (cnode.x > 0)
    {
      if (field(cnode.x - 1, cnode.y) == 0) // node is walkable
        {
          Node& west = node_field(cnode.x - 1, cnode.y);

          if (west.visited == 0 && west.parent == PARENT_NONE)
            {
              west.parent = PARENT_EAST;
              //west.cost   = cnode.cost + 1;
              west.cost = int(PosDistance(Pos(cnode.x - 1, cnode.y), end));
              add_to_open_nodes(west);
            }
        }
    }

  if (int(cnode.x) < node_field.get_width()-1  && field(cnode.x+1, cnode.y) == 0)
    {
      Node& east = node_field(cnode.x + 1, cnode.y);
      if (east.visited == 0  && east.parent == PARENT_NONE) 
        {
          east.parent = PARENT_WEST;
          //east.cost   = cnode.cost + 1;
          east.cost     = int(PosDistance(Pos(cnode.x + 1, cnode.y), end));
          add_to_open_nodes(east);
        }
    }

  if (cnode.y > 0 && field(cnode.x, cnode.y - 1) == 0)
    {
      Node& north = node_field(cnode.x, cnode.y - 1);
      if (north.visited == 0  && north.parent == PARENT_NONE)
        {
          north.parent = PARENT_SOUTH;
          //north.cost   = cnode.cost + 1;
          north.cost     = int(PosDistance(Pos(cnode.x, cnode.y-1), end));
          add_to_open_nodes(north);
        }
    }
  
  if (int(cnode.y) < node_field.get_height() - 1  && field(cnode.x, cnode.y+1) == 0)
    {
      Node& south = node_field(cnode.x, cnode.y + 1);
      if (south.visited == 0  && south.parent == PARENT_NONE)
        {
          south.parent = PARENT_NORTH;
          //south.cost   = cnode.cost + 1;
          south.cost     = int(PosDistance(Pos(cnode.x, cnode.y+1), end));
          add_to_open_nodes(south);
        }
    }
}
bool NewBuildingWizard::IsNewSpecial()
{
    return field("NewSpecial").toBool();
}
/*
  .2msec for 256x256 grid
*/
int main()
{
  CL_SetupCore::init();

  srand(time(NULL));
  Field<int> field(80, 50);

  unsigned int start_time = CL_System::get_time();
  unsigned int end_time;

  for(int y = 0; y < field.get_height(); ++y)
    for(int x = 0; x < field.get_width(); ++x)
      {
        field(x,y) = (rand()%100) > 40 ? 0 : 1;
      }

  DijkstraPathfinder pathfinder(&field);

  Pos start;
  Pos end;

  for(int count = 0; count < 1000; ++count)
    {
  start.x = rand()%field.get_width();
  start.y = rand()%field.get_height();
  
  end.x = rand()%field.get_width();
  end.y = rand()%field.get_height();

      pathfinder.init(start, end);
      //pathfinder.display();

      //int i = 0;
      //std::cout << "Start: " << start.x << " " << start.y << std::endl;
      //std::cout << "End:   " << end.x << " " << end.y << std::endl;

      while(!pathfinder.finished())
        {
          //for(int i = 0; i < 10 && !pathfinder.finished(); ++i)
          pathfinder.process_one_open_node();

          //getchar();
        }
      if (1)
        {
          std::cout << "c" << std::endl;
          pathfinder.display();
          getchar();
        }
 
      //pathfinder.display();
      
      /*
        if (pathfinder.get_state() != DijkstraPathfinder::PATH_FOUND)
        {
        std::cout << "No Path could be found" << std::endl;
        }
        else
        {
        std::cout << "Found path" << std::endl;
        std::vector<Pos>& path = pathfinder.get_path();
        for (std::vector<Pos>::iterator i = path.begin(); i != path.end(); ++i)
        {
        std::cout << "[" << i->x << ", " << i->y << "] ";
        }       
        std::cout << std::endl;
        }
      */

      //      getchar();
      //std::cout << "round: " << ++i << std::endl;
    }
  end_time = CL_System::get_time();
  std::cout << "Msec: " << end_time - start_time << std::endl;

  CL_SetupCore::deinit();
}
Exemple #27
0
/*! \overload
    Returns the field called \a name.
 */
QSqlField QSqlRecord::field(const QString &name) const
{
    return field(indexOf(name));
}
Exemple #28
0
int PHIWizardPhis::nextId() const
{
    if ( field( "apache" ).toBool() ) return static_cast<int>(PHIWizard::Apache);
    return static_cast<int>(PHIWizard::Commit);
}
bool EncounterFile::open()
{
	return open(field()->sectionData(Field::Encounter));
}
Exemple #30
0
/*
    Make sure the row is internally consistent. If so then fix it so the
    parent class has a valid row to insert (some of the SELECTed columns
    shouldn't be directly modified in the db 'cause they're not part of the
    model's current table).
*/
bool PoitemTableModel::validRow(QSqlRecord& record)
{
  QString errormsg;
  QString warningmsg;

  // TODO: what is a better way to decide if this is an inventory item or not?
  bool inventoryItem = ! record.value("item_number").toString().isEmpty();

  if (! inventoryItem &&
      record.value("poitem_expcat_id").toInt() < 0)
    errormsg = tr("<p>You must specify an Expense Category for this "
		  "non-Inventory Item before you may save it.");

  else if (inventoryItem &&
	   record.value("item_number").toString().isEmpty())
    errormsg = tr("<p>You must select an Item Number before you may save.");

  else if (inventoryItem &&
	   record.value("warehous_id").toInt() <= 0)
    errormsg = tr("<p>You must select a Supplying Site before you may save.");

  else if (record.value("poitem_qty_ordered").toDouble() <= 0)
    errormsg = tr("<p>You must enter a quantity before you may save this "
		  "Purchase Order Item.");

  else if (record.value("itemsrc_minordqty").toDouble() > 0 &&
	   record.value("poitem_qty_ordered").toDouble() < record.value("itemsrc_minordqty").toDouble())
    warningmsg = tr("<p>The quantity that you are ordering is below the "
		    "Minimum Order Quantity for this Item Source.  You may "
		    "continue but this Vendor may not honor pricing or "
		    "delivery quotations. ");

  else if (record.value("itemsrc_multordqty").toDouble() > 0 &&
	   record.value("poitem_qty_ordered").toInt() % (int)(record.value("itemsrc_multordqty").toDouble()))
    warningmsg = tr("<p>The quantity that you are ordering does not fall "
		    "within the Order Multiple for this Item Source.  You may "
		    "continue but this Vendor may not honor pricing or "
		    "delivery quotations.");

  else if (! record.value("poitem_duedate").toDate().isValid())
    errormsg = tr("<p>You must enter a due date.");

  else if (record.value("earliestDate").toDate().isValid() &&
	   record.value("poitem_duedate").toDate() < record.value("earliestDate").toDate())
    warningmsg = tr("<p>The Due Date that you are requesting does not fall "
		    "within the Lead Time Days for this Item Source.  You may "
		    "continue but this Vendor may not honor pricing or "
		    "delivery quotations or may not be able to deliver by the "
		    "requested Due Date.");

  else if (record.value("poitem_pohead_id").toInt() <= 0 &&
	   _poheadid <= 0)
    errormsg = tr("<p>There is no Purchase Order header yet. "
	     "Try entering a Vendor if you are using the Purchase Order "
	     "window.");

  else if (inventoryItem &&
	   record.value("item_id").toInt() > 0 &&
	   record.value("warehous_id").toInt() > 0)
  {
    XSqlQuery isq;
    isq.prepare("SELECT itemsite_id, item_id "
		"FROM itemsite, item "
		"WHERE ((itemsite_item_id=item_id)"
		"  AND  (itemsite_warehous_id=:whs_id)"
		"  AND  (item_id=:item_id));");
    isq.bindValue(":whs_id", record.value("warehous_id").toInt());
    isq.bindValue(":item_id", record.value("item_id").toInt());
    isq.exec();
    if (isq.first())
    {
      int itemsiteid = isq.value("itemsite_id").toInt();
      if (itemsiteid != record.value("poitem_itemsite_id").toInt())
	record.setValue("poitem_itemsite_id", itemsiteid);
    }
    else if (isq.lastError().type() != QSqlError::NoError)
      errormsg = isq.lastError().databaseText();
    else
      errormsg = tr("<p>There is no Item Site for this Site (%1) and "
	       "Item Number (%2).")
	       .arg(record.value("warehous_code").toInt())
	       .arg(record.value("item_number").toString());
  }

  int index = record.indexOf("poitem_pohead_id");
  if (index < 0)
  {
    QSqlField field("poitem_pohead_id", QVariant::Int);
    field.setValue(_poheadid);
    record.append(field);
  }
  else
    record.setValue(index, _poheadid);

  XSqlQuery ln;
  /*
  ln.prepare("SELECT MAX(poitem_linenumber) + 1 AS newln "
	     "FROM poitem "
	     "WHERE (poitem_pohead_id=:pohead_id);");
             */
  // get the smallest available line number
  ln.prepare("SELECT MIN(sequence_value) AS newln "
             "FROM sequence "
             "WHERE sequence_value NOT IN (SELECT poitem_linenumber "
             "                             FROM poitem"
             "                             WHERE (poitem_pohead_id=:pohead_id));");
  ln.bindValue(":pohead_id", _poheadid);
  if (record.indexOf("poitem_linenumber") < 0)
  {
    ln.exec();
    if (ln.first())
    {
      QSqlField field("poitem_linenumber", QVariant::Int);
      field.setValue(ln.value("newln"));
      record.append(field);
    }
    else if (ln.lastError().type() != QSqlError::NoError)
    {
      errormsg = ln.lastError().databaseText();
    }
  }
  else if (record.value("poitem_linenumber").toInt() <= 0)
  {
    ln.exec();
    if (ln.first())
      record.setValue("poitem_linenumber", ln.value("newln"));
    else if (ln.lastError().type() != QSqlError::NoError)
    {
      errormsg = ln.lastError().databaseText();
    }
  }

  if (record.value("poitem_id").isNull())
  {
    XSqlQuery idq("SELECT NEXTVAL('poitem_poitem_id_seq') AS poitem_id;");
    if (idq.first())
      record.setValue("poitem_id", idq.value("poitem_id"));
    else
    {
      errormsg = idq.lastError().databaseText();
    }
  }

  if (_postatus.isEmpty())
    findHeadData();

  index = record.indexOf("poitem_status");
  if (index < 0)
  {
    QSqlField field("poitem_status", QVariant::String);
    field.setValue(_postatus);
    record.append(field);
  }
  else if (record.field(index).value().toString().isEmpty())
    record.setValue(index, _postatus);

  if (record.field("poitem_invvenduomratio").value().isNull() &&
      record.field("itemsrc_invvendoruomratio").value().isNull())
    record.setValue("poitem_invvenduomratio", 1);
  else if (record.field("poitem_invvenduomratio").value().isNull())
    record.setValue("poitem_invvenduomratio", record.value("itemsrc_invvendoruomratio"));

  if (! errormsg.isEmpty())
  {
    setLastError(QSqlError(QString("PoitemTableModel::validRow() error"),
			   errormsg, QSqlError::UnknownError));
    return false;
  }
  else if (! warningmsg.isEmpty())
  {
    if (QMessageBox::question(0, tr("Are you sure you want to continue?"),
		    warningmsg + tr("<p>Do you wish to Save this Order?"),
		    QMessageBox::Yes,
		    QMessageBox::No | QMessageBox::Default) == QMessageBox::No)
    return false;
  }

  record.remove(record.indexOf("earliestdate"));
  record.remove(record.indexOf("itemsrc_invvendoruomratio"));
  record.remove(record.indexOf("itemsrc_multordqty"));
  record.remove(record.indexOf("itemsrc_minordqty"));
  record.remove(record.indexOf("expcat_code"));
  record.remove(record.indexOf("prj_number"));
  record.remove(record.indexOf("extprice"));
  record.remove(record.indexOf("warehous_code"));
  record.remove(record.indexOf("warehous_id"));
  record.remove(record.indexOf("item_number"));
  record.remove(record.indexOf("item_id"));
  record.remove(record.indexOf("pohead_number"));

  return true;
}