Beispiel #1
0
// eg 74 converts to "01:14"
bool minutesToString(int16_t minutesSinceMidnight, char *buffer) {
    Appender ap(buffer, 6);

    return hoursAndMinutesString(minutesSinceMidnight, &ap);
}
Beispiel #2
0
AutoPtr<Elem> InfPrism::side (const unsigned int i) const
{
  libmesh_assert_less (i, this->n_sides());

  switch (i)
    {
    case 0:  // the triangular face at z=-1, base face
      {
        Elem* face = new Tri3;
        AutoPtr<Elem> ap_face(face);
	//AutoPtr<Elem> face(new Tri3);

	// Note that for this face element, the normal points inward
	face->set_node(0) = this->get_node(0);
	face->set_node(1) = this->get_node(1);
	face->set_node(2) = this->get_node(2);

	return ap_face;
      }

    case 1:  // the quad face at y=0
      {
        Elem* face = new InfQuad4;
        AutoPtr<Elem> ap_face(face);
	//AutoPtr<Elem> face(new InfQuad4);

	face->set_node(0) = this->get_node(0);
	face->set_node(1) = this->get_node(1);
	face->set_node(2) = this->get_node(3);
	face->set_node(3) = this->get_node(4);

	return ap_face;
      }

    case 2:  // the other quad face
      {
        Elem* face = new InfQuad4;
        AutoPtr<Elem> ap_face(face);
	//AutoPtr<Elem> face(new InfQuad4);

	face->set_node(0) = this->get_node(1);
	face->set_node(1) = this->get_node(2);
	face->set_node(2) = this->get_node(4);
	face->set_node(3) = this->get_node(5);

	return ap_face;
      }

    case 3: // the quad face at x=0
      {
        Elem* face = new InfQuad4;
        AutoPtr<Elem> ap_face(face);
	//AutoPtr<Elem> face(new InfQuad4);

	face->set_node(0) = this->get_node(2);
	face->set_node(1) = this->get_node(0);
	face->set_node(2) = this->get_node(5);
	face->set_node(3) = this->get_node(3);

	return ap_face;
      }

    default:
      {
	libmesh_error();
	AutoPtr<Elem> ap(NULL);  return ap;
      }
    }

  // We'll never get here.
  libmesh_error();
  AutoPtr<Elem> ap(NULL);  return ap;
}
Beispiel #3
0
void hyp2F1(T& result, const T& a, const T& b, const T& c, const T& x)
{
  // Compute the series representation of hyperg_2f1 taken from
  // Abramowitz and Stegun 15.1.1.
  // There are no checks on input range or parameter boundaries.

   typedef typename boost::multiprecision::detail::canonical<boost::int32_t, T>::type si_type;
   typedef typename boost::multiprecision::detail::canonical<boost::uint32_t, T>::type ui_type;
   typedef typename T::exponent_type exp_type;
   typedef typename boost::multiprecision::detail::canonical<exp_type, T>::type canonical_exp_type;
   typedef typename mpl::front<typename T::float_types>::type fp_type;

   T x_pow_n_div_n_fact(x);
   T pochham_a         (a);
   T pochham_b         (b);
   T pochham_c         (c);
   T ap                (a);
   T bp                (b);
   T cp                (c);

   eval_multiply(result, pochham_a, pochham_b);
   eval_divide(result, pochham_c);
   eval_multiply(result, x_pow_n_div_n_fact);
   eval_add(result, ui_type(1));

   T lim;
   eval_ldexp(lim, result, 1 - boost::multiprecision::detail::digits2<number<T, et_on> >::value);

   if(eval_get_sign(lim) < 0)
      lim.negate();

   ui_type n;
   T term;

   static const unsigned series_limit = 
      boost::multiprecision::detail::digits2<number<T, et_on> >::value < 100
      ? 100 : boost::multiprecision::detail::digits2<number<T, et_on> >::value;
   // Series expansion of hyperg_2f1(a, b; c; x).
   for(n = 2; n < series_limit; ++n)
   {
      eval_multiply(x_pow_n_div_n_fact, x);
      eval_divide(x_pow_n_div_n_fact, n);

      eval_increment(ap);
      eval_multiply(pochham_a, ap);
      eval_increment(bp);
      eval_multiply(pochham_b, bp);
      eval_increment(cp);
      eval_multiply(pochham_c, cp);

      eval_multiply(term, pochham_a, pochham_b);
      eval_divide(term, pochham_c);
      eval_multiply(term, x_pow_n_div_n_fact);
      eval_add(result, term);

      if(eval_get_sign(term) < 0)
         term.negate();
      if(lim.compare(term) >= 0)
         break;
   }
   if(n > series_limit)
      BOOST_THROW_EXCEPTION(std::runtime_error("H2F1 failed to converge."));
}
int main(int argc, char *argv[])
{
    #include "setRootCase.H"
    #include "createTime.H"
    #include "createDynamicFvMesh.H"
    #include "createFields.H"
    #include "readTimeControls.H"

    // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //

    #include "readFluxScheme.H"

    dimensionedScalar v_zero("v_zero", dimVolume/dimTime, 0.0);

    // Courant numbers used to adjust the time-step
    scalar CoNum = 0.0;
    scalar meanCoNum = 0.0;

    Info<< "\nStarting time loop\n" << endl;

    while (runTime.run())
    {
        #include "readTimeControls.H"
        #include "setDeltaT.H"

        runTime++;

        Info<< "Time = " << runTime.timeName() << nl << endl;

        // Do any mesh changes
        mesh.update();

        // --- Directed interpolation of primitive fields onto faces

        surfaceScalarField rho_pos(interpolate(rho, pos));
        surfaceScalarField rho_neg(interpolate(rho, neg));

        surfaceVectorField rhoU_pos(interpolate(rhoU, pos, U.name()));
        surfaceVectorField rhoU_neg(interpolate(rhoU, neg, U.name()));

        volScalarField rPsi("rPsi", 1.0/psi);
        surfaceScalarField rPsi_pos(interpolate(rPsi, pos, T.name()));
        surfaceScalarField rPsi_neg(interpolate(rPsi, neg, T.name()));

        surfaceScalarField e_pos(interpolate(e, pos, T.name()));
        surfaceScalarField e_neg(interpolate(e, neg, T.name()));

        surfaceVectorField U_pos("U_pos", rhoU_pos/rho_pos);
        surfaceVectorField U_neg("U_neg", rhoU_neg/rho_neg);

        surfaceScalarField p_pos("p_pos", rho_pos*rPsi_pos);
        surfaceScalarField p_neg("p_neg", rho_neg*rPsi_neg);

        surfaceScalarField phiv_pos("phiv_pos", U_pos & mesh.Sf());
        surfaceScalarField phiv_neg("phiv_neg", U_neg & mesh.Sf());

        // Make fluxes relative to mesh-motion
        if (mesh.moving())
        {
            phiv_pos -= mesh.phi();
            phiv_neg -= mesh.phi();
        }

        volScalarField c("c", sqrt(thermo.Cp()/thermo.Cv()*rPsi));
        surfaceScalarField cSf_pos
        (
            "cSf_pos",
            interpolate(c, pos, T.name())*mesh.magSf()
        );
        surfaceScalarField cSf_neg
        (
            "cSf_neg",
            interpolate(c, neg, T.name())*mesh.magSf()
        );

        surfaceScalarField ap
        (
            "ap",
            max(max(phiv_pos + cSf_pos, phiv_neg + cSf_neg), v_zero)
        );
        surfaceScalarField am
        (
            "am",
            min(min(phiv_pos - cSf_pos, phiv_neg - cSf_neg), v_zero)
        );

        surfaceScalarField a_pos("a_pos", ap/(ap - am));

        surfaceScalarField amaxSf("amaxSf", max(mag(am), mag(ap)));

        surfaceScalarField aSf("aSf", am*a_pos);

        if (fluxScheme == "Tadmor")
        {
            aSf = -0.5*amaxSf;
            a_pos = 0.5;
        }

        surfaceScalarField a_neg("a_neg", 1.0 - a_pos);

        phiv_pos *= a_pos;
        phiv_neg *= a_neg;

        surfaceScalarField aphiv_pos("aphiv_pos", phiv_pos - aSf);
        surfaceScalarField aphiv_neg("aphiv_neg", phiv_neg + aSf);

        // Reuse amaxSf for the maximum positive and negative fluxes
        // estimated by the central scheme
        amaxSf = max(mag(aphiv_pos), mag(aphiv_neg));

        #include "centralCourantNo.H"

        phi = aphiv_pos*rho_pos + aphiv_neg*rho_neg;

        surfaceVectorField phiUp
        (
            (aphiv_pos*rhoU_pos + aphiv_neg*rhoU_neg)
          + (a_pos*p_pos + a_neg*p_neg)*mesh.Sf()
        );

        surfaceScalarField phiEp
        (
            "phiEp",
            aphiv_pos*(rho_pos*(e_pos + 0.5*magSqr(U_pos)) + p_pos)
          + aphiv_neg*(rho_neg*(e_neg + 0.5*magSqr(U_neg)) + p_neg)
          + aSf*p_pos - aSf*p_neg
        );

        // Make flux for pressure-work absolute
        if (mesh.moving())
        {
            phiEp += mesh.phi()*(a_pos*p_pos + a_neg*p_neg);
        }

        volScalarField muEff("muEff", turbulence->muEff());
        volTensorField tauMC("tauMC", muEff*dev2(Foam::T(fvc::grad(U))));

        // --- Solve density
        solve(fvm::ddt(rho) + fvc::div(phi));

        // --- Solve momentum
        solve(fvm::ddt(rhoU) + fvc::div(phiUp));

        U.dimensionedInternalField() =
            rhoU.dimensionedInternalField()
           /rho.dimensionedInternalField();
        U.correctBoundaryConditions();
        rhoU.boundaryField() = rho.boundaryField()*U.boundaryField();

        if (!inviscid)
        {
            solve
            (
                fvm::ddt(rho, U) - fvc::ddt(rho, U)
              - fvm::laplacian(muEff, U)
              - fvc::div(tauMC)
            );
            rhoU = rho*U;
        }

        // --- Solve energy
        surfaceScalarField sigmaDotU
        (
            "sigmaDotU",
            (
                fvc::interpolate(muEff)*mesh.magSf()*fvc::snGrad(U)
              + (mesh.Sf() & fvc::interpolate(tauMC))
            )
            & (a_pos*U_pos + a_neg*U_neg)
        );

        solve
        (
            fvm::ddt(rhoE)
          + fvc::div(phiEp)
          - fvc::div(sigmaDotU)
        );

        e = rhoE/rho - 0.5*magSqr(U);
        e.correctBoundaryConditions();
        thermo.correct();
        rhoE.boundaryField() =
            rho.boundaryField()*
            (
                e.boundaryField() + 0.5*magSqr(U.boundaryField())
            );

        if (!inviscid)
        {
            solve
            (
                fvm::ddt(rho, e) - fvc::ddt(rho, e)
              - fvm::laplacian(turbulence->alphaEff(), e)
            );
            thermo.correct();
            rhoE = rho*(e + 0.5*magSqr(U));
        }

        p.dimensionedInternalField() =
            rho.dimensionedInternalField()
           /psi.dimensionedInternalField();
        p.correctBoundaryConditions();
        rho.boundaryField() = psi.boundaryField()*p.boundaryField();

        turbulence->correct();

        runTime.write();

        Info<< "ExecutionTime = " << runTime.elapsedCpuTime() << " s"
            << "  ClockTime = " << runTime.elapsedClockTime() << " s"
            << nl << endl;
    }

    Info<< "End\n" << endl;

    return 0;
}
Beispiel #5
0
  ParticleSet* ParticleSetPool::createESParticleSet(xmlNodePtr cur, const string& target)
  {
    TinyVector<int,OHMMS_DIM> tilefactor;
    Tensor<int,OHMMS_DIM> tilematrix(1,0,0,0,1,0,0,0,1);
    double lr_cut=10;
    string h5name;
    string source("i");
    string bc("p p p");

    OhmmsAttributeSet attribs;
    attribs.add(h5name, "href");
    attribs.add(tilefactor, "tile");
    attribs.add(tilematrix, "tilematrix");
    attribs.add(source, "source");
    attribs.add(bc, "bconds");
    attribs.add(lr_cut, "LR_dim_cutoff");
    attribs.put(cur);

    ParticleSet* ions=getParticleSet(source);
    if(ions==0)
    {
      ions=new MCWalkerConfiguration;
      ions->setName(source);
    }

    //set the boundary condition
    ions->Lattice.LR_dim_cutoff=lr_cut;
    std::istringstream  is(bc);
    char c;
    int idim=0;
    while(!is.eof() && idim<OHMMS_DIM) 
    { 
      if(is>>c) ions->Lattice.BoxBConds[idim++]=(c=='p');
    }
    
    //initialize ions from hdf5
    hid_t h5=-1;
    if(myComm->rank()==0)
      h5 = H5Fopen(h5name.c_str(),H5F_ACC_RDONLY,H5P_DEFAULT);
    ESHDFIonsParser ap(*ions,h5,myComm);
    ap.put(cur);
    ap.expand(tilematrix);
    if(h5>-1) H5Fclose(h5);

    //failed to initialize the ions
    if(ions->getTotalNum() == 0) return 0;

    typedef ParticleSet::SingleParticleIndex_t SingleParticleIndex_t;
    vector<SingleParticleIndex_t> grid(OHMMS_DIM,SingleParticleIndex_t(1));
    ions->Lattice.reset();
    ions->Lattice.makeGrid(grid);

    if(SimulationCell==0)
    {
      SimulationCell = new ParticleSet::ParticleLayout_t(ions->Lattice);
    }

    //create the electrons
    MCWalkerConfiguration* qp = new MCWalkerConfiguration;
    qp->setName(target);
    qp->Lattice.copy(ions->Lattice);

    //qp->Lattice.reset();
    //qp->Lattice.makeGrid(grid);

    app_log() << "  Simulation cell radius = " << qp->Lattice.SimulationCellRadius << endl;
    app_log() << "  Wigner-Seitz    radius = " << qp->Lattice.WignerSeitzRadius    << endl;
    SimulationCell->print(app_log());

    myPool[target]=qp;
    myPool[source]=ions;
    //addParticleSet(qp);
    //addParticleSet(ions);

    {//get the number of electrons per spin
      vector<int> num_spin;
      xmlNodePtr cur1=cur->children;
      while(cur1!=NULL)
      {
        string cname1((const char*)cur1->name);
        if(cname1 == OrbitalBuilderBase::sd_tag)
        {
          num_spin.clear();
          xmlNodePtr cur2=cur1->children;
          while(cur2!=NULL)
          {
            string cname2((const char*)cur2->name);
            if(cname2 == OrbitalBuilderBase::det_tag)
            {
              int n=0;
              OhmmsAttributeSet a;
              a.add(n,"size");
              a.put(cur2);
              if(num_spin.size()<2) num_spin.push_back(n);
            }
            cur2=cur2->next;
          }
        }
        cur1=cur1->next;
      }
      //create species
      SpeciesSet& species=qp->getSpeciesSet();
      //add up and down
      species.addSpecies("u");
      if(num_spin.size()>1) species.addSpecies("d");
      int chid=species.addAttribute("charge");
      for(int i=0; i<num_spin.size(); ++i) species(chid,i)=-1.0;
      int mid=species.addAttribute("membersize");
      for(int i=0; i<num_spin.size(); ++i) species(mid,i)=num_spin[i];
      mid=species.addAttribute("mass");
      for(int i=0; i<num_spin.size(); ++i) species(mid,i)=1.0;
      qp->create(num_spin);
    }
    //name it with the target
    qp->setName(target);

    //assign non-trivial positions for the quanmtum particles
    if(qp->Lattice.SuperCellEnum)
    {
      makeUniformRandom(qp->R);
      qp->R.setUnit(PosUnit::LatticeUnit);
      qp->convert2Cart(qp->R);
      qp->createSK();
    }
    else
    {
      InitMolecularSystem mole(this);
      if(ions->getTotalNum()>1)
        mole.initMolecule(ions,qp);
      else
        mole.initAtom(ions,qp);
    }

    //for(int i=0; i<qp->getTotalNum(); ++i)
    //  cout << qp->GroupID[i] << " " << qp->R[i] << endl;

    if(qp->getTotalNum() == 0 || ions->getTotalNum() == 0)
    {
      delete qp;
      delete ions;
      APP_ABORT("ParticleSetPool failed to create particlesets for the electron structure calculation");
      return 0;
    }
    return qp;
  }
Beispiel #6
0
AbstractProjectionPtr
LastProjection::copy()
{
    AbstractProjectionPtr ap( new LastProjection( d_->src_ ));
    return ap;
}
Beispiel #7
0
// release/reset
    std::auto_ptr<Clonable> release()
    {
        std::auto_ptr<Clonable> ap(m_ptr);
        m_ptr = PSTADE_NULLPTR;
        return ap;
    }
Beispiel #8
0
static int
run_notify_purge_test (void)
{
  int status;
  ACE_Reactor *r = ACE_Reactor::instance ();
  {
    Purged_Notify n1;
    Purged_Notify *n2;

    ACE_NEW_RETURN (n2, Purged_Notify, -1);
    auto_ptr<Purged_Notify> ap (n2);

    // First test:
    // Notify EXCEPT, and purge ALL
    r->notify (&n1); // the mask is EXCEPT_MASK

    status = r->purge_pending_notifications (&n1);
    if (status == -1 && errno == ENOTSUP)
      return 0;         // Select Reactor w/o ACE_HAS_REACTOR_NOTIFICATION_QUEUE
    if (status != 1)
      ACE_ERROR ((LM_ERROR,
                  ACE_TEXT ("Purged %d notifies; expected 1\n"),
                  status));
    // Second test:
    // Notify READ twice, and WRITE once, and purge READ and WRITE - should purge 3 times.
    r->notify (&n1, ACE_Event_Handler::READ_MASK);
    r->notify (&n1, ACE_Event_Handler::READ_MASK);
    r->notify (&n1, ACE_Event_Handler::WRITE_MASK);
    status = r->purge_pending_notifications
      (&n1, ACE_Event_Handler::READ_MASK | ACE_Event_Handler::WRITE_MASK);
    if (status != 3)
      ACE_ERROR ((LM_ERROR,
                  ACE_TEXT ("Purged %d notifies; expected 3\n"),
                  status));
    // Third test:
    // Notify READ on 2 handlers, and purge READ|WRITE on all handlers. Should purge 2
    r->notify (&n1, ACE_Event_Handler::READ_MASK);
    r->notify (n2, ACE_Event_Handler::READ_MASK);
    status = r->purge_pending_notifications
      (0, ACE_Event_Handler::READ_MASK | ACE_Event_Handler::WRITE_MASK);
    if (status != 2)
      ACE_ERROR ((LM_ERROR,
                  ACE_TEXT ("Purged %d notifies; expected 2\n"),
                  status));
    // Forth test:
    // Notify EXCEPT and WRITE, purge READ. Should not purge
    r->notify (&n1); // the mask is EXCEPT_MASK
    r->notify (&n1, ACE_Event_Handler::WRITE_MASK);
    status = r->purge_pending_notifications
      (&n1, ACE_Event_Handler::READ_MASK);
    if (status != 0)
      ACE_ERROR ((LM_ERROR,
                  ACE_TEXT ("Purged %d notifies; expected 0\n"),
                  status));
    // Fifth test:
    r->notify (n2);

    // The destructor of the event handler no longer removes the
    // notifications.  It is the application's responsability to do
    // so.
    r->purge_pending_notifications(n2,
                                   ACE_Event_Handler::ALL_EVENTS_MASK);
    r->purge_pending_notifications(&n1,
                                   ACE_Event_Handler::ALL_EVENTS_MASK);
  }

  ACE_Time_Value t (1);
  status = r->handle_events (t);  // Should be nothing to do, and time out
  return status < 0 ? 1 : 0;     // Return 0 for all ok, else error
}
    //--------------------------------------------------------------------------
    Distribution LossDistBucketing::operator()(const vector<Real>& nominals,
                                    const vector<Real>& probabilities) const {
    //--------------------------------------------------------------------------
        QL_REQUIRE (nominals.size() == probabilities.size(), "sizes differ: "
                    << nominals.size() << " vs " << probabilities.size());

        vector<Real> p (nBuckets_, 0.0);
        vector<Real> a (nBuckets_, 0.0);
        vector<Real> ap (nBuckets_, 0.0);

        p[0] = 1.0;
        a[0] = 0.0;
        Real dx = maximum_ / nBuckets_;
        for (Size k = 1; k < nBuckets_; k++)
            a[k] = dx * k + dx/2;

        for (Size i = 0; i < nominals.size(); i++) {
            Real L = nominals[i];
            Real P = probabilities[i];
            for (int k = a.size()-1; k >= 0; k--) {
                if (p[k] > 0) {
                    int u = locateTargetBucket (a[k] + L, k);
                    QL_REQUIRE (u >= 0, "u=" << u << " at i=" << i << " k=" << k);
                    QL_REQUIRE (u >= k, "u=" << u << "<k=" << k << " at i=" << i);

                    Real dp = p[k] * P;
                    if (u == k)
                        a[k] += P * L;
                    else {
                        // no update of a[u] and p[u] if u is beyond grid end
                        if (u < int(nBuckets_)) {
                            // a[u] remains unchanged, if dp = 0
                            if (dp > 0.0) {
                                // on Windows, p[u]/dp could cause a NaN for
                                // some very small values of p[k].
                                // Writing the above as (p[u]/p[k])/P prevents
                                // the NaN. What can I say?
                                Real f = 1.0 / (1.0 + (p[u]/p[k]) / P);
                                a[u] = (1.0 - f) * a[u] + f * (a[k] + L);
                            }
                            /* formulation of Hull-White:
                               if (p[u] + dp > 0)
                                  a[u] = (p[u] * a[u] + dp * (a[k] + L))
                                         / (p[u] + dp);
                            */
                            p[u] += dp;
                        }
                        p[k] -= dp;
                    }
                }
                QL_REQUIRE(a[k] + epsilon_ >= dx * k && a[k] < dx * (k+1),
                           "a out of range at k=" << k << ", contract " << i);
            }
        }

        Distribution dist (nBuckets_, 0.0, maximum_);
        for (Size i = 0; i < nBuckets_; i++) {
            dist.addDensity (i, p[i] / dx);
            dist.addAverage (i, a[i]);
        }

        return dist;
    }
Beispiel #10
0
void ComputeGlobal::sendData()
{
  DebugM(2,"sendData\n");
  // Get positions from patches
  PatchMap *patchMap = PatchMap::Object();
  int numPatches = patchMap->numPatches();
  AtomMap *atomMap = AtomMap::Object();
  const Lattice & lattice = patchList[0].p->lattice;
  ResizeArrayIter<PatchElem> ap(patchList);
  CompAtom **x = new CompAtom*[numPatches];
  FullAtom **t = new FullAtom*[numPatches];
  for ( int i = 0; i < numPatches; ++i ) { x[i] = 0; t[i] = 0; }

  int step = -1;
  for (ap = ap.begin(); ap != ap.end(); ap++) {
    x[(*ap).patchID] = (*ap).positionBox->open();
    t[(*ap).patchID] = (*ap).p->getAtomList().begin();
    step = (*ap).p->flags.step;
  }

  ComputeGlobalDataMsg *msg = new  ComputeGlobalDataMsg;

  msg->step = step;

  AtomIDList::iterator a = aid.begin();
  AtomIDList::iterator a_e = aid.end();
  for ( ; a != a_e; ++a ) {
    LocalID localID = atomMap->localID(*a);
    if ( localID.pid == notUsed || ! x[localID.pid] ) continue;
    msg->aid.add(*a);
    Position x_orig = x[localID.pid][localID.index].position;
    Transform trans = t[localID.pid][localID.index].transform;
    msg->p.add(lattice.reverse_transform(x_orig,trans));
  }

  // calculate group centers of mass
  Molecule *mol = Node::Object()->molecule;
  AtomIDList::iterator g_i, g_e;
  g_i = gdef.begin(); g_e = gdef.end();
  ResizeArray<BigReal>::iterator gm_i = gmass.begin();
  for ( ; g_i != g_e; ++g_i, ++gm_i ) {
    Vector com(0,0,0);
    for ( ; *g_i != -1; ++g_i ) {
      LocalID localID = atomMap->localID(*g_i);
      if ( localID.pid == notUsed || ! x[localID.pid] ) continue;
      Position x_orig = x[localID.pid][localID.index].position;
      Transform trans = t[localID.pid][localID.index].transform;
      com += lattice.reverse_transform(x_orig,trans) * mol->atommass(*g_i);
    }
    com /= *gm_i;
    DebugM(1,"Adding center of mass "<<com<<"\n");
    msg->gcom.add(com);
  }

  for (ap = ap.begin(); ap != ap.end(); ap++) {
    (*ap).positionBox->close(&(x[(*ap).patchID]));
  }
  
  msg->fid = *fid;
  msg->tf = *totalForce;
  delete fid;
  delete totalForce;
  fid = new AtomIDList;
  totalForce = new ForceList;

  delete [] x;
  delete [] t;

  DebugM(3,"Sending data (" << msg->aid.size() << " positions) on client\n");
  comm->sendComputeGlobalData(msg);
}
Beispiel #11
0
void ComputeGlobal::recvResults(ComputeGlobalResultsMsg *msg) {
  DebugM(3,"Receiving results (" << msg->aid.size() << " forces, "
	 << msg->newgdef.size() << " new group atoms) on client\n");

  // set the forces only if we aren't going to resend the data
  int setForces = !msg->resendCoordinates;

  if(setForces) { // we are requested to 
    // Store forces to patches
    PatchMap *patchMap = PatchMap::Object();
    int numPatches = patchMap->numPatches();
    AtomMap *atomMap = AtomMap::Object();
    const Lattice & lattice = patchList[0].p->lattice;
    ResizeArrayIter<PatchElem> ap(patchList);
    Force **f = new Force*[numPatches];
    FullAtom **t = new FullAtom*[numPatches];
    for ( int i = 0; i < numPatches; ++i ) { f[i] = 0; t[i] = 0; }
    Force extForce = 0.;
    Tensor extVirial;

    for (ap = ap.begin(); ap != ap.end(); ap++) {
      (*ap).r = (*ap).forceBox->open();
      f[(*ap).patchID] = (*ap).r->f[Results::normal];
      t[(*ap).patchID] = (*ap).p->getAtomList().begin();
    }

    AtomIDList::iterator a = msg->aid.begin();
    AtomIDList::iterator a_e = msg->aid.end();
    ForceList::iterator f2 = msg->f.begin();
    for ( ; a != a_e; ++a, ++f2 ) {
      DebugM(1,"processing atom "<<(*a)<<", F="<<(*f2)<<"...\n");
      /* XXX if (*a) is out of bounds here we get a segfault */
      LocalID localID = atomMap->localID(*a);
      if ( localID.pid == notUsed || ! f[localID.pid] ) continue;
      Force f_atom = (*f2);
      f[localID.pid][localID.index] += f_atom;
      Position x_orig = t[localID.pid][localID.index].position;
      Transform trans = t[localID.pid][localID.index].transform;
      Position x_atom = lattice.reverse_transform(x_orig,trans);
      extForce += f_atom;
      extVirial += outer(f_atom,x_atom);
    }
    DebugM(1,"done with the loop\n");

  // calculate forces for atoms in groups
    Molecule *mol = Node::Object()->molecule;
    AtomIDList::iterator g_i, g_e;
    g_i = gdef.begin(); g_e = gdef.end();
    ResizeArray<BigReal>::iterator gm_i = gmass.begin();
    ForceList::iterator gf_i = msg->gforce.begin();
    //iout << iDEBUG << "recvResults\n" << endi;
    for ( ; g_i != g_e; ++g_i, ++gm_i, ++gf_i ) {
      //iout << iDEBUG << *gf_i << '\n' << endi;
      Vector accel = (*gf_i) / (*gm_i);
      for ( ; *g_i != -1; ++g_i ) {
	//iout << iDEBUG << *g_i << '\n' << endi;
	LocalID localID = atomMap->localID(*g_i);
	if ( localID.pid == notUsed || ! f[localID.pid] ) continue;
	Force f_atom = accel * mol->atommass(*g_i);
	f[localID.pid][localID.index] += f_atom;
        Position x_orig = t[localID.pid][localID.index].position;
        Transform trans = t[localID.pid][localID.index].transform;
        Position x_atom = lattice.reverse_transform(x_orig,trans);
        extForce += f_atom;
        extVirial += outer(f_atom,x_atom);
      }
    }
    DebugM(1,"done with the groups\n");

    for (ap = ap.begin(); ap != ap.end(); ap++) {
      (*ap).forceBox->close(&((*ap).r));
    }

    delete [] f;
    delete [] t;

    ADD_VECTOR_OBJECT(reduction,REDUCTION_EXT_FORCE_NORMAL,extForce);
    ADD_TENSOR_OBJECT(reduction,REDUCTION_VIRIAL_NORMAL,extVirial);
    reduction->submit();
  }
  // done setting the forces

  // Get reconfiguration if present
  if ( msg->reconfig ) configure(msg->newaid, msg->newgdef);

  // send another round of data if requested

  if(msg->resendCoordinates) {
    DebugM(3,"Sending requested data right away\n");
    sendData();
  }

  delete msg;
  DebugM(3,"Done processing results\n");
}
Beispiel #12
0
AutoPtr<Elem> Hex::side (const unsigned int i) const
{
  libmesh_assert_less (i, this->n_sides());



  Elem* face = new Quad4;

  // Think of a unit cube: (-1,1) x (-1,1)x (-1,1)
  switch (i)
    {
    case 0:  // the face at z = -1
      {
	face->set_node(0) = this->get_node(0);
	face->set_node(1) = this->get_node(3);
	face->set_node(2) = this->get_node(2);
	face->set_node(3) = this->get_node(1);

	AutoPtr<Elem> ap(face);
        return ap;
      }
    case 1:  // the face at y = -1
      {
	face->set_node(0) = this->get_node(0);
	face->set_node(1) = this->get_node(1);
	face->set_node(2) = this->get_node(5);
	face->set_node(3) = this->get_node(4);

	AutoPtr<Elem> ap(face);
        return ap;
      }
    case 2:  // the face at x = 1
      {
	face->set_node(0) = this->get_node(1);
	face->set_node(1) = this->get_node(2);
	face->set_node(2) = this->get_node(6);
	face->set_node(3) = this->get_node(5);

	AutoPtr<Elem> ap(face);
        return ap;
      }
    case 3: // the face at y = 1
      {
	face->set_node(0) = this->get_node(2);
	face->set_node(1) = this->get_node(3);
	face->set_node(2) = this->get_node(7);
	face->set_node(3) = this->get_node(6);

	AutoPtr<Elem> ap(face);
        return ap;
      }
    case 4: // the face at x = -1
      {
	face->set_node(0) = this->get_node(3);
	face->set_node(1) = this->get_node(0);
	face->set_node(2) = this->get_node(4);
	face->set_node(3) = this->get_node(7);

	AutoPtr<Elem> ap(face);
        return ap;
      }
    case 5: // the face at z = 1
      {
	face->set_node(0) = this->get_node(4);
	face->set_node(1) = this->get_node(5);
	face->set_node(2) = this->get_node(6);
	face->set_node(3) = this->get_node(7);

	AutoPtr<Elem> ap(face);
        return ap;
      }
    default:
      {
	libmesh_error();
	AutoPtr<Elem> ap(face);
        return ap;
      }
    }

  // We'll never get here.
  libmesh_error();
  AutoPtr<Elem> ap(face);
  return ap;
}
le_uint16 LigatureSubstitutionProcessor2::processStateEntry(LEGlyphStorage &glyphStorage, le_int32 &currGlyph, EntryTableIndex2 index, LEErrorCode &success)
{
    const LigatureSubstitutionStateEntry2 *entry = entryTable.getAlias(index, success);
    if(LE_FAILURE(success)) return 0;

    le_uint16 nextStateIndex = SWAPW(entry->nextStateIndex);
    le_uint16 flags = SWAPW(entry->entryFlags);
    le_uint16 ligActionIndex = SWAPW(entry->ligActionIndex);
    
    if (flags & lsfSetComponent) {
        if (++m >= nComponents) {
            m = 0;
        }
        componentStack[m] = currGlyph;
    } else if ( m == -1) {
        // bad font- skip this glyph.
        //LE_DEBUG_BAD_FONT("m==-1 (componentCount went negative)")
        currGlyph+= dir;
        return nextStateIndex;
    }

    ByteOffset actionOffset = flags & lsfPerformAction;

    if (actionOffset != 0) {
        LEReferenceTo<LigatureActionEntry> ap(stHeader, success, ligActionOffset); // byte offset
        ap.addObject(ligActionIndex - 1, success);  // index offset ( one before the actual start, because we will pre-increment)
        LEReferenceToArrayOf<TTGlyphID> ligatureTable(stHeader, success, ligatureOffset, LE_UNBOUNDED_ARRAY);
        LigatureActionEntry action;
        le_int32 offset, i = 0;
        le_int32 stack[nComponents];
        le_int16 mm = -1;

        LEReferenceToArrayOf<le_uint16> componentTable(stHeader, success, componentOffset, LE_UNBOUNDED_ARRAY);
        if(LE_FAILURE(success)) {
          currGlyph+= dir;
          return nextStateIndex; // get out! bad font
        }
        
        do {
            le_int32 componentGlyph = componentStack[m--]; // pop off

            ap.addObject(success);
            action = SWAPL(*ap.getAlias());

            if (m < 0) {
                m = nComponents - 1;
            }

            offset = action & lafComponentOffsetMask;
            if (offset != 0) {
                if(componentGlyph > glyphStorage.getGlyphCount() || componentGlyph < 0) {
                  LE_DEBUG_BAD_FONT("preposterous componentGlyph");
                  currGlyph+= dir;
                  return nextStateIndex; // get out! bad font
                }
                i += SWAPW(componentTable(LE_GET_GLYPH(glyphStorage[componentGlyph]) + (SignExtend(offset, lafComponentOffsetMask)),success));
                       
                if (action & (lafLast | lafStore))  {
                  TTGlyphID ligatureGlyph = SWAPW(ligatureTable(i,success));
                    glyphStorage[componentGlyph] = LE_SET_GLYPH(glyphStorage[componentGlyph], ligatureGlyph);
                    if(mm==nComponents) {
                      LE_DEBUG_BAD_FONT("exceeded nComponents");
                      mm--; // don't overrun the stack.
                    }
                    stack[++mm] = componentGlyph;
                    i = 0;
                } else {
                    glyphStorage[componentGlyph] = LE_SET_GLYPH(glyphStorage[componentGlyph], 0xFFFF);
                }
            }
#if LE_ASSERT_BAD_FONT
            if(m<0) {
              LE_DEBUG_BAD_FONT("m<0")
            }
#endif
        } while (!(action & lafLast) && (m>=0) ); // stop if last bit is set, or if run out of items

        while (mm >= 0) {
            if (++m >= nComponents) {
                m = 0;
            }

            componentStack[m] = stack[mm--];
        }
    }
Beispiel #14
0
void TextureSource::buildMainAtlas() 
{
	infostream<<"TextureSource::buildMainAtlas()"<<std::endl;

	//return; // Disable (for testing)
	
	video::IVideoDriver* driver = m_device->getVideoDriver();
	assert(driver);

	JMutexAutoLock lock(m_atlaspointer_cache_mutex);

	// Create an image of the right size
	core::dimension2d<u32> atlas_dim(1024,1024);
	video::IImage *atlas_img =
			driver->createImage(video::ECF_A8R8G8B8, atlas_dim);
	//assert(atlas_img);
	if(atlas_img == NULL)
	{
		errorstream<<"TextureSource::buildMainAtlas(): Failed to create atlas "
				"image; not building texture atlas."<<std::endl;
		return;
	}

	/*
		Grab list of stuff to include in the texture atlas from the
		main content features
	*/

	core::map<std::string, bool> sourcelist;

	for(u16 j=0; j<MAX_CONTENT+1; j++)
	{
		if(j == CONTENT_IGNORE || j == CONTENT_AIR)
			continue;
		ContentFeatures *f = &content_features(j);
		for(core::map<std::string, bool>::Iterator
				i = f->used_texturenames.getIterator();
				i.atEnd() == false; i++)
		{
			std::string name = i.getNode()->getKey();
			sourcelist[name] = true;

			if(f->often_contains_mineral){
				for(int k=1; k<MINERAL_COUNT; k++){
					std::string mineraltexture = mineral_block_texture(k);
					std::string fulltexture = name + "^" + mineraltexture;
					sourcelist[fulltexture] = true;
				}
			}
		}
	}
	
	infostream<<"Creating texture atlas out of textures: ";
	for(core::map<std::string, bool>::Iterator
			i = sourcelist.getIterator();
			i.atEnd() == false; i++)
	{
		std::string name = i.getNode()->getKey();
		infostream<<"\""<<name<<"\" ";
	}
	infostream<<std::endl;

	// Padding to disallow texture bleeding
	s32 padding = 16;

	s32 column_width = 256;
	s32 column_padding = 16;

	/*
		First pass: generate almost everything
	*/
	core::position2d<s32> pos_in_atlas(0,0);
	
	pos_in_atlas.Y = padding;

	for(core::map<std::string, bool>::Iterator
			i = sourcelist.getIterator();
			i.atEnd() == false; i++)
	{
		std::string name = i.getNode()->getKey();

		/*video::IImage *img = driver->createImageFromFile(
				getTexturePath(name.c_str()).c_str());
		if(img == NULL)
			continue;
		
		core::dimension2d<u32> dim = img->getDimension();
		// Make a copy with the right color format
		video::IImage *img2 =
				driver->createImage(video::ECF_A8R8G8B8, dim);
		img->copyTo(img2);
		img->drop();*/
		
		// Generate image by name
		video::IImage *img2 = generate_image_from_scratch(name, m_device);
		if(img2 == NULL)
		{
			infostream<<"TextureSource::buildMainAtlas(): Couldn't generate texture atlas: Couldn't generate image \""<<name<<"\""<<std::endl;
			continue;
		}

		core::dimension2d<u32> dim = img2->getDimension();

		// Don't add to atlas if image is large
		core::dimension2d<u32> max_size_in_atlas(32,32);
		if(dim.Width > max_size_in_atlas.Width
		|| dim.Height > max_size_in_atlas.Height)
		{
			infostream<<"TextureSource::buildMainAtlas(): Not adding "
					<<"\""<<name<<"\" because image is large"<<std::endl;
			continue;
		}

		// Wrap columns and stop making atlas if atlas is full
		if(pos_in_atlas.Y + dim.Height > atlas_dim.Height)
		{
			if(pos_in_atlas.X > (s32)atlas_dim.Width - 256 - padding){
				errorstream<<"TextureSource::buildMainAtlas(): "
						<<"Atlas is full, not adding more textures."
						<<std::endl;
				break;
			}
			pos_in_atlas.Y = padding;
			pos_in_atlas.X += column_width + column_padding;
		}
		
        infostream<<"TextureSource::buildMainAtlas(): Adding \""<<name
                <<"\" to texture atlas"<<std::endl;

		// Tile it a few times in the X direction
		u16 xwise_tiling = column_width / dim.Width;
		if(xwise_tiling > 16) // Limit to 16 (more gives no benefit)
			xwise_tiling = 16;
		for(u32 j=0; j<xwise_tiling; j++)
		{
			// Copy the copy to the atlas
			img2->copyToWithAlpha(atlas_img,
					pos_in_atlas + v2s32(j*dim.Width,0),
					core::rect<s32>(v2s32(0,0), dim),
					video::SColor(255,255,255,255),
					NULL);
		}

		// Copy the borders a few times to disallow texture bleeding
		for(u32 side=0; side<2; side++) // top and bottom
		for(s32 y0=0; y0<padding; y0++)
		for(s32 x0=0; x0<(s32)xwise_tiling*(s32)dim.Width; x0++)
		{
			s32 dst_y;
			s32 src_y;
			if(side==0)
			{
				dst_y = y0 + pos_in_atlas.Y + dim.Height;
				src_y = pos_in_atlas.Y + dim.Height - 1;
			}
			else
			{
				dst_y = -y0 + pos_in_atlas.Y-1;
				src_y = pos_in_atlas.Y;
			}
			s32 x = x0 + pos_in_atlas.X;
			video::SColor c = atlas_img->getPixel(x, src_y);
			atlas_img->setPixel(x,dst_y,c);
		}

		img2->drop();

		/*
			Add texture to caches
		*/
		
		// Get next id
		u32 id = m_atlaspointer_cache.size();

		// Create AtlasPointer
		AtlasPointer ap(id);
		ap.atlas = NULL; // Set on the second pass
		ap.pos = v2f((float)pos_in_atlas.X/(float)atlas_dim.Width,
				(float)pos_in_atlas.Y/(float)atlas_dim.Height);
		ap.size = v2f((float)dim.Width/(float)atlas_dim.Width,
				(float)dim.Width/(float)atlas_dim.Height);
		ap.tiled = xwise_tiling;

		// Create SourceAtlasPointer and add to containers
		SourceAtlasPointer nap(name, ap, atlas_img, pos_in_atlas, dim);
		m_atlaspointer_cache.push_back(nap);
		m_name_to_id.insert(name, id);
			
		// Increment position
		pos_in_atlas.Y += dim.Height + padding * 2;
	}

	/*
		Make texture
	*/
	video::ITexture *t = driver->addTexture("__main_atlas__", atlas_img);
	assert(t);

	/*
		Second pass: set texture pointer in generated AtlasPointers
	*/
	for(core::map<std::string, bool>::Iterator
			i = sourcelist.getIterator();
			i.atEnd() == false; i++)
	{
		std::string name = i.getNode()->getKey();
		if(m_name_to_id.find(name) == NULL)
			continue;
		u32 id = m_name_to_id[name];
		//infostream<<"id of name "<<name<<" is "<<id<<std::endl;
		m_atlaspointer_cache[id].a.atlas = t;
	}

	/*
		Write image to file so that it can be inspected
	*/
	/*std::string atlaspath = porting::path_userdata
			+ DIR_DELIM + "generated_texture_atlas.png";
	infostream<<"Removing and writing texture atlas for inspection to "
			<<atlaspath<<std::endl;
	fs::RecursiveDelete(atlaspath);
	driver->writeImageToFile(atlas_img, atlaspath.c_str());*/
}
Beispiel #15
0
void TextureSource::buildMainAtlas() 
{
	infostream<<"TextureSource::buildMainAtlas()"<<std::endl;

	//return; // Disable (for testing)
	
	video::IVideoDriver* driver = m_device->getVideoDriver();
	assert(driver);

	JMutexAutoLock lock(m_atlaspointer_cache_mutex);

	// Create an image of the right size
	core::dimension2d<u32> atlas_dim(1024,1024);
	video::IImage *atlas_img =
			driver->createImage(video::ECF_A8R8G8B8, atlas_dim);
	//assert(atlas_img);
	if(atlas_img == NULL)
	{
		errorstream<<"TextureSource::buildMainAtlas(): Failed to create atlas "
				"image; not building texture atlas."<<std::endl;
		return;
	}

	/*
		A list of stuff to include in the texture atlas.

		It is a single-dimensional texture atlas due to the need to tile
		textures.
		
		It should contain as much of the stuff shown in game as possible,
		to minimize texture changes.

		It fills up quickly, so do not add anything that isn't contained
		in most MapBlocks. E.g. mese isn't suitable but stone is.
	*/

	core::array<std::string> sourcelist;

	sourcelist.push_back("stone.png");
	sourcelist.push_back("mud.png");
	sourcelist.push_back("sand.png");
	sourcelist.push_back("grass.png");
	sourcelist.push_back("grass_footsteps.png");
	sourcelist.push_back("tree.png");
	sourcelist.push_back("tree_top.png");
	sourcelist.push_back("water.png");
	sourcelist.push_back("leaves.png");
	sourcelist.push_back("glass.png");
	sourcelist.push_back("mud.png^grass_side.png");
	sourcelist.push_back("cobble.png");
	sourcelist.push_back("mossycobble.png");
	sourcelist.push_back("gravel.png");
	sourcelist.push_back("jungletree.png");
	
	sourcelist.push_back("stone.png^mineral_coal.png");
	sourcelist.push_back("stone.png^mineral_iron.png");
	
	// Padding to disallow texture bleeding
	s32 padding = 16;

	/*
		First pass: generate almost everything
	*/
	core::position2d<s32> pos_in_atlas(0,0);
	
	pos_in_atlas.Y += padding;

	for(u32 i=0; i<sourcelist.size(); i++)
	{
		std::string name = sourcelist[i];

		/*video::IImage *img = driver->createImageFromFile(
				getTexturePath(name.c_str()).c_str());
		if(img == NULL)
			continue;
		
		core::dimension2d<u32> dim = img->getDimension();
		// Make a copy with the right color format
		video::IImage *img2 =
				driver->createImage(video::ECF_A8R8G8B8, dim);
		img->copyTo(img2);
		img->drop();*/
		
		// Generate image by name
		video::IImage *img2 = generate_image_from_scratch(name, m_device);
		if(img2 == NULL)
		{
			infostream<<"TextureSource::buildMainAtlas(): Couldn't generate texture atlas: Couldn't generate image \""<<name<<"\""<<std::endl;
			continue;
		}

		core::dimension2d<u32> dim = img2->getDimension();

		// Don't add to atlas if image is large
		core::dimension2d<u32> max_size_in_atlas(32,32);
		if(dim.Width > max_size_in_atlas.Width
		|| dim.Height > max_size_in_atlas.Height)
		{
			infostream<<"TextureSource::buildMainAtlas(): Not adding "
					<<"\""<<name<<"\" because image is large"<<std::endl;
			continue;
		}

		// Stop making atlas if atlas is full
		if(pos_in_atlas.Y + dim.Height > atlas_dim.Height)
		{
			infostream<<"TextureSource::buildMainAtlas(): "
					<<"Atlas is full, not adding more textures."
					<<std::endl;
			break;
		}
		
        infostream<<"TextureSource::buildMainAtlas(): Adding \""<<name
                <<"\" to texture atlas"<<std::endl;

		// Tile it a few times in the X direction
		u16 xwise_tiling = 16;
		for(u32 j=0; j<xwise_tiling; j++)
		{
			// Copy the copy to the atlas
			img2->copyToWithAlpha(atlas_img,
					pos_in_atlas + v2s32(j*dim.Width,0),
					core::rect<s32>(v2s32(0,0), dim),
					video::SColor(255,255,255,255),
					NULL);
		}

		// Copy the borders a few times to disallow texture bleeding
		for(u32 side=0; side<2; side++) // top and bottom
		for(s32 y0=0; y0<padding; y0++)
		for(s32 x0=0; x0<(s32)xwise_tiling*(s32)dim.Width; x0++)
		{
			s32 dst_y;
			s32 src_y;
			if(side==0)
			{
				dst_y = y0 + pos_in_atlas.Y + dim.Height;
				src_y = pos_in_atlas.Y + dim.Height - 1;
			}
			else
			{
				dst_y = -y0 + pos_in_atlas.Y-1;
				src_y = pos_in_atlas.Y;
			}
			s32 x = x0 + pos_in_atlas.X * dim.Width;
			video::SColor c = atlas_img->getPixel(x, src_y);
			atlas_img->setPixel(x,dst_y,c);
		}

		img2->drop();

		/*
			Add texture to caches
		*/
		
		// Get next id
		u32 id = m_atlaspointer_cache.size();

		// Create AtlasPointer
		AtlasPointer ap(id);
		ap.atlas = NULL; // Set on the second pass
		ap.pos = v2f((float)pos_in_atlas.X/(float)atlas_dim.Width,
				(float)pos_in_atlas.Y/(float)atlas_dim.Height);
		ap.size = v2f((float)dim.Width/(float)atlas_dim.Width,
				(float)dim.Width/(float)atlas_dim.Height);
		ap.tiled = xwise_tiling;

		// Create SourceAtlasPointer and add to containers
		SourceAtlasPointer nap(name, ap, atlas_img, pos_in_atlas, dim);
		m_atlaspointer_cache.push_back(nap);
		m_name_to_id.insert(name, id);
			
		// Increment position
		pos_in_atlas.Y += dim.Height + padding * 2;
	}

	/*
		Make texture
	*/
	video::ITexture *t = driver->addTexture("__main_atlas__", atlas_img);
	assert(t);

	/*
		Second pass: set texture pointer in generated AtlasPointers
	*/
	for(u32 i=0; i<sourcelist.size(); i++)
	{
		std::string name = sourcelist[i];
		if(m_name_to_id.find(name) == NULL)
			continue;
		u32 id = m_name_to_id[name];
		//infostream<<"id of name "<<name<<" is "<<id<<std::endl;
		m_atlaspointer_cache[id].a.atlas = t;
	}

	/*
		Write image to file so that it can be inspected
	*/
	/*driver->writeImageToFile(atlas_img, 
			getTexturePath("main_atlas.png").c_str());*/
}
bool ManageSieveCommand::explain()
{
    if ( !::x )
        ::x = new ExplainStuff;

    whitespace();
    while ( d->no.isEmpty() && d->pos < d->arg.length() ) {
        EString name = string();
        whitespace();
        EString value = string();
        whitespace();
        if ( name == "from" || name == "to" ) {
            if ( value.isEmpty() ) {
                if ( name == "from" )
                    ::x->from = 0;
                else
                    ::x->to = 0;
            }
            else {
                AddressParser ap( value );
                ap.assertSingleAddress();
                if ( ap.addresses()->count() != 1 )
                    no( "Need exactly one address for " + name );
                else if ( name == "from" )
                    ::x->from = ap.addresses()->first();
                else
                    ::x->to = ap.addresses()->first();
            }
        }
        else if ( name == "keep" ) {
            if ( value.isEmpty() ) {
                ::x->keep = 0;
            }
            else {
                Utf8Codec u;
                ::x->keep = Mailbox::find( u.toUnicode( value ) );
                if ( !::x->keep )
                    no( "No such mailbox: " + value );
            }
        }
        else if ( name == "script" ) {
            if ( value.isEmpty() ) {
                ::x->script = 0;
            }
            else {
                if ( !::x->script )
                    ::x->script = new SieveScript;
                ::x->script->parse( value );
                if ( ::x->script->isEmpty() )
                    no( "Script cannot be empty" );
                EString e = ::x->script->parseErrors();
                if ( !e.isEmpty() )
                    no( e );
            }
        }
        else if ( name == "message" ) {
            if ( value.isEmpty() ) {
                ::x->message = 0;
            }
            else {
                ::x->message = new Injectee;
                ::x->message->parse( value );
                ::x->message->setRfc822Size( ::x->message->rfc822().length() );
                if ( !::x->message->error().isEmpty() )
                    no( "Message parsing: " + ::x->message->error() );
            }
        }
        else {
            no( "Unknown name: " + name );
        }
    }

    if ( !::x->script )
        no( "No sieve (yet)" );
    if ( !::x->from )
        no( "No sender address (yet)" );
    if ( !::x->to )
        no( "No recipient address (yet)" );
    if ( !::x->keep )
        no( "No keep mailbox (yet)" );

    if ( !d->no.isEmpty() )
        return true;

    Sieve s;
    s.setSender( ::x->from );
    s.addRecipient( ::x->to, ::x->keep, d->sieve->user(), ::x->script );
    s.evaluate();
    uint a = s.actions( ::x->to )->count();
    bool m = false;
    if ( ::x->message && !s.done() ) {
        s.setMessage( ::x->message, new Date );
        s.evaluate();
        m = true;
    }
    if ( ::x->message && !m )
        d->sieve->send( "Script did not need the message" );
    else if ( !s.done() )
        d->sieve->send( "Script did not complete" );

    uint n = 0;
    List<SieveAction>::Iterator sa( s.actions( ::x->to ) );
    while ( sa ) {
        EString r( "Action: " );
        switch ( sa->type() ) {
        case SieveAction::Reject:
            r.append( "reject" );
            break;
        case SieveAction::FileInto:
            r.append( "fileinto " );
            r.append( sa->mailbox()->name().utf8() );
            break;
        case SieveAction::Redirect:
            r.append( "redirect " );
            r.append( sa->recipientAddress()->localpart() );
            r.append( "@" );
            r.append( sa->recipientAddress()->domain() );
            break;
        case SieveAction::MailtoNotification:
            r.append( "mailto notification to " );
            r.append( sa->recipientAddress()->lpdomain() );
            break;
        case SieveAction::Discard:
            r.append( "discard" );
            break;
        case SieveAction::Vacation:
            r.append( "send vacation message to " );
            r.append( sa->recipientAddress()->lpdomain() );
            r.append( " with subject " );
            r.append( sa->message()->header()->subject() );
            break;
        case SieveAction::Error:
            r = "Error: ";
            r.append( sa->errorMessage().simplified() );
            break;
        }
        if ( m && a && n<a )
            r.append( " (before seeing the message text)" );
        d->sieve->send( r );
        ++sa;
        n++;
    }

    return true;
}
Beispiel #17
0
TauContribution<EvalT, Traits>::
TauContribution(Teuchos::ParameterList& p) :
tauFactor(p.get<std::string>("Tau Contribution Name"),
		 p.get<Teuchos::RCP<PHX::DataLayout> >("QP Scalar Data Layout"))
{
  Teuchos::ParameterList* elmd_list = 
    p.get<Teuchos::ParameterList*>("Parameter List");

  Teuchos::RCP<PHX::DataLayout> vector_dl =
    p.get< Teuchos::RCP<PHX::DataLayout> >("QP Vector Data Layout");
  std::vector<PHX::DataLayout::size_type> dims;
  vector_dl->dimensions(dims);
  numQPs  = dims[1];
  numDims = dims[2];

  Teuchos::RCP<ParamLib> paramLib = 
    p.get< Teuchos::RCP<ParamLib> >("Parameter Library", Teuchos::null);

  std::string type = elmd_list->get("Tau Contribution Type", "Constant");
  if (type == "Constant") {
    is_constant = true;
    constant_value = elmd_list->get("Value", 0.0);

    // Add Trapped Solvent as a Sacado-ized parameter
    new Sacado::ParameterRegistration<EvalT, SPL_Traits>(
	"Tau Contribution", this, paramLib);
  }
  else if (type == "Truncated KL Expansion") {
    is_constant = false;
    PHX::MDField<MeshScalarT,Cell,QuadPoint,Dim>
      fx(p.get<std::string>("QP Coordinate Vector Name"), vector_dl);
    coordVec = fx;
    this->addDependentField(coordVec);

    exp_rf_kl = 
      Teuchos::rcp(new Stokhos::KL::ExponentialRandomField<MeshScalarT>(*elmd_list));
    int num_KL = exp_rf_kl->stochasticDimension();

    // Add KL random variables as Sacado-ized parameters
    rv.resize(num_KL);
    for (int i=0; i<num_KL; i++) {
      std::string ss = Albany::strint("Trapped Solvent KL Random Variable",i);
      new Sacado::ParameterRegistration<EvalT, SPL_Traits>(ss, this, paramLib);
      rv[i] = elmd_list->get(ss, 0.0);
    }
  }
  else {
	  TEUCHOS_TEST_FOR_EXCEPTION(true, Teuchos::Exceptions::InvalidParameter,
		       "Invalid Trapped Solvent type " << type);
  } 

  if ( p.isType<std::string>("QP Variable Name") ) {
     Teuchos::RCP<PHX::DataLayout> scalar_dl =
       p.get< Teuchos::RCP<PHX::DataLayout> >("QP Scalar Data Layout");
     PHX::MDField<ScalarT,Cell,QuadPoint>
       tp(p.get<std::string>("QP Variable Name"), scalar_dl);
     Clattice = tp;
     this->addDependentField(Clattice);
     VmPartial = elmd_list->get("Partial Molar Volume Value", 0.0);
     new Sacado::ParameterRegistration<EvalT, SPL_Traits>(
                                 "Partial Molar Volume Value", this, paramLib);

   }
   else {
     VmPartial = 2.0e-6;
   }

  if ( p.isType<std::string>("Diffusion Coefficient Name") ) {
       Teuchos::RCP<PHX::DataLayout> scalar_dl =
         p.get< Teuchos::RCP<PHX::DataLayout> >("QP Scalar Data Layout");
       PHX::MDField<ScalarT,Cell,QuadPoint>
         ap(p.get<std::string>("Diffusion Coefficient Name"), scalar_dl);
       DL = ap;
       this->addDependentField(DL);

  }

 /*
  if ( p.isType<std::string>("Ideal Gas Constant Name") ) {
           Teuchos::RCP<PHX::DataLayout> scalar_dl =
             p.get< Teuchos::RCP<PHX::DataLayout> >("QP Scalar Data Layout");
           PHX::MDField<ScalarT,Cell,QuadPoint>
             idg(p.get<std::string>("Ideal Gas Constant Name"), scalar_dl);
           Rideal = idg;
           this->addDependentField(Rideal);

      }
  */

  if ( p.isType<std::string>("Temperature Name") ) {
         Teuchos::RCP<PHX::DataLayout> scalar_dl =
           p.get< Teuchos::RCP<PHX::DataLayout> >("QP Scalar Data Layout");
         PHX::MDField<ScalarT,Cell,QuadPoint>
           tep(p.get<std::string>("Temperature Name"), scalar_dl);
         temperature = tep;

         Rideal = p.get<RealType>("Ideal Gas Constant", 8.3144621);
         this->addDependentField(temperature);

    }




  this->addEvaluatedField(tauFactor);
  this->setName("Tau Contribution"+PHX::TypeString<EvalT>::value);
}
Beispiel #18
0
AutoPtr<QBase> QBase::build(const QuadratureType _qt,
			    const unsigned int _dim,
			    const Order _order)
{
  switch (_qt)
    {

    case QCLOUGH:
      {
#ifdef DEBUG
	if (_order > TWENTYTHIRD)
	  {
	    libMesh::out << "WARNING: Clough quadrature implemented" << std::endl
		          << " up to TWENTYTHIRD order." << std::endl;
	  }
#endif

	AutoPtr<QBase> ap(new QClough(_dim, _order));
	return ap;
      }

    case QGAUSS:
      {

#ifdef DEBUG
	if (_order > FORTYTHIRD)
	  {
	    libMesh::out << "WARNING: Gauss quadrature implemented" << std::endl
		          << " up to FORTYTHIRD order." << std::endl;
	  }
#endif

	AutoPtr<QBase> ap(new QGauss(_dim, _order));
	return ap;
      }

    case QJACOBI_1_0:
      {

#ifdef DEBUG
	if (_order > TWENTYTHIRD)
	  {
	    libMesh::out << "WARNING: Jacobi(1,0) quadrature implemented" << std::endl
		          << " up to TWENTYTHIRD order." << std::endl;
	  }

	if (_dim > 1)
	  {
	    libMesh::out << "WARNING: Jacobi(1,0) quadrature implemented" << std::endl
		          << " in 1D only." << std::endl;
	  }
#endif

	AutoPtr<QBase> ap(new QJacobi(_dim, _order, 1, 0));
	return ap;
      }

    case QJACOBI_2_0:
      {

#ifdef DEBUG
	if (_order > TWENTYTHIRD)
	  {
	    libMesh::out << "WARNING: Jacobi(2,0) quadrature implemented" << std::endl
		          << " up to TWENTYTHIRD order." << std::endl;
	  }

	if (_dim > 1)
	  {
	    libMesh::out << "WARNING: Jacobi(2,0) quadrature implemented" << std::endl
		          << " in 1D only." << std::endl;
	  }
#endif

	AutoPtr<QBase> ap(new QJacobi(_dim, _order, 2, 0));
	return ap;
      }

    case QSIMPSON:
      {

#ifdef DEBUG
	if (_order > THIRD)
	  {
	    libMesh::out << "WARNING: Simpson rule provides only" << std::endl
		          << " THIRD order!" << std::endl;
	  }
#endif

	AutoPtr<QBase> ap(new QSimpson(_dim));
	return ap;
      }

    case QTRAP:
      {

#ifdef DEBUG
	if (_order > FIRST)
	  {
	    libMesh::out << "WARNING: Trapezoidal rule provides only" << std::endl
		          << " FIRST order!" << std::endl;
	  }
#endif

	AutoPtr<QBase> ap(new QTrap(_dim));
	return ap;
      }


    default:
      {
	libMesh::err << "ERROR: Bad qt=" << _qt << std::endl;
	libmesh_error();
      }
    }


  libmesh_error();
  AutoPtr<QBase> ap(NULL);
  return ap;
}
Beispiel #19
0
AutoPtr<Elem> InfQuad4::build_side (const unsigned int i,
				    bool proxy) const
{
  // libmesh_assert_less (i, this->n_sides());

  if (proxy)
    {
      switch (i)
	{
	  // base
	case 0:
	  {
	    AutoPtr<Elem> ap(new Side<Edge2,InfQuad4>(this,i));
	    return ap;
	  }
	  // ifem edges
	case 1:
	case 2:
	  {
	    AutoPtr<Elem> ap(new Side<InfEdge2,InfQuad4>(this,i));
	    return ap;
	  }

	default:
	  libmesh_error();
	}
    }

  else
    {
      // Create NULL pointer to be initialized, returned later.
      AutoPtr<Elem> edge(NULL);

      switch (i)
	{
	case 0:
	  {
            edge.reset(new Edge2);

	    edge->set_node(0) = this->get_node(0);
	    edge->set_node(1) = this->get_node(1);

	    break;
	  }

	case 1:
	  {
	    // adjacent to another infinite element
            edge.reset(new InfEdge2);

	    edge->set_node(0) = this->get_node(1);
	    edge->set_node(1) = this->get_node(3);

	    break;
	  }

	case 2:
	  {
	    // adjacent to another infinite element
            edge.reset(new InfEdge2);

	    edge->set_node(0) = this->get_node(0);
	    edge->set_node(1) = this->get_node(2);

	    break;
	  }
	default:
	  {
	    libmesh_error();
	  }
	}

      edge->subdomain_id() = this->subdomain_id();
      return edge;
    }

  // How did we get here
  libmesh_error();
  AutoPtr<Elem> ap(NULL);  return ap;
}
Beispiel #20
0
void ClangDriver::OnPrepareTUEnded(wxCommandEvent& e)
{
    // Our thread is done
    m_isBusy = false;

    // Sanity
    ClangThreadReply* reply = (ClangThreadReply*)e.GetClientData();
    if(!reply) {
        return;
    }

    // Make sure we delete the reply at the end...
    std::auto_ptr<ClangThreadReply> ap(reply);

    // Delete the fake file...
    DoDeleteTempFile(reply->filename);

    // Just a notification without real info?
    if(reply->context == CTX_None) {
        return;
    }

    if(reply->context == ::CTX_CachePCH || reply->context == ::CTX_ReparseTU) {
        return; // Nothing more to be done
    }

    if(reply->context == CTX_GotoDecl || reply->context == CTX_GotoImpl) {
        // Unlike other context's the 'filename' specified here
        // does not belong to an editor (it could, but it is not necessarily true)
        DoGotoDefinition(reply);
        return;
    }

    // Adjust the activeEditor to fit the filename
    IEditor* editor = clMainFrame::Get()->GetMainBook()->FindEditor(reply->filename);
    if(!editor) {
        CL_DEBUG(wxT("Could not find an editor for file %s"), reply->filename.c_str());
        return;
    }

    m_activeEditor = editor;

    // What should we do with the TU?
    switch(reply->context) {
    case CTX_CachePCH:
        // Nothing more to be done
        return;
    default:
        break;
    }

    if(!reply->results && !reply->errorMessage.IsEmpty()) {
        // Notify about this error
        clCommandEvent event(wxEVT_CLANG_CODE_COMPLETE_MESSAGE);
        event.SetString(reply->errorMessage);
        event.SetInt(1); // indicates that this is an error message
        EventNotifier::Get()->AddPendingEvent(event);
        return;
    }

    if(m_activeEditor->GetCurrentPosition() < m_position) {
        CL_DEBUG(wxT("Current position is lower than the starting position, ignoring completion"));
        clang_disposeCodeCompleteResults(reply->results);
        return;
    }

    wxString typedString;
    if(m_activeEditor->GetCurrentPosition() > m_position) {
        // User kept on typing while the completion thread was working
        typedString = m_activeEditor->GetTextRange(m_position, m_activeEditor->GetCurrentPosition());
        if(typedString.find_first_not_of(wxT("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_")) !=
           wxString::npos) {
            // User typed some non valid identifier char, cancel code completion
            CL_DEBUG(
                wxT("User typed: %s since the completion thread started working until it ended, ignoring completion"),
                typedString.c_str());
            clang_disposeCodeCompleteResults(reply->results);
            return;
        }
    }

    // update the filter word
    reply->filterWord.Append(typedString);
    CL_DEBUG(wxT("clang completion: filter word is %s"), reply->filterWord.c_str());

    // For the Calltip, remove the opening brace from the filter string
    wxString filterWord = reply->filterWord;
    if(GetContext() == CTX_Calltip && filterWord.EndsWith(wxT("("))) filterWord.RemoveLast();

    wxString lowerCaseFilter = filterWord;
    lowerCaseFilter.MakeLower();

    unsigned numResults = reply->results->NumResults;
    clang_sortCodeCompletionResults(reply->results->Results, reply->results->NumResults);
    std::vector<TagEntryPtr> tags;
    for(unsigned i = 0; i < numResults; i++) {
        CXCompletionResult result = reply->results->Results[i];
        CXCompletionString str = result.CompletionString;
        CXCursorKind kind = result.CursorKind;

        if(kind == CXCursor_NotImplemented) continue;

        wxString entryName, entrySignature, entryPattern, entryReturnValue;
        DoParseCompletionString(str, 0, entryName, entrySignature, entryPattern, entryReturnValue);

        wxString lowerCaseName = entryName;
        lowerCaseName.MakeLower();

        if(!lowerCaseFilter.IsEmpty() && !lowerCaseName.StartsWith(lowerCaseFilter)) continue;

        if(clang_getCompletionAvailability(str) != CXAvailability_Available) continue;

        TagEntry* t = new TagEntry();
        TagEntryPtr tag(t);
        tag->SetIsClangTag(true);
        tag->SetName(entryName);
        tag->SetPattern(entryPattern);
        tag->SetSignature(entrySignature);

// Add support for clang comment parsing
#if HAS_LIBCLANG_BRIEFCOMMENTS
        CXString BriefComment = clang_getCompletionBriefComment(str);
        const char* comment = clang_getCString(BriefComment);
        if(comment && comment[0] != '\0') {
            tag->SetComment(wxString(comment, wxConvUTF8));
        }

        clang_disposeString(BriefComment);
#endif

        switch(kind) {
        case CXCursor_EnumConstantDecl:
            tag->SetKind(wxT("enumerator"));
            break;

        case CXCursor_EnumDecl:
            tag->SetKind(wxT("enum"));
            break;

        case CXCursor_CXXMethod:
        case CXCursor_Constructor:
        case CXCursor_Destructor:
        case CXCursor_FunctionDecl:
        case CXCursor_FunctionTemplate:
            tag->SetKind(wxT("prototype"));
            break;

        case CXCursor_MacroDefinition:
            tag->SetKind(wxT("macro"));
            break;

        case CXCursor_Namespace:
            tag->SetKind(wxT("namespace"));
            break;

        case CXCursor_ClassDecl:
        case CXCursor_ClassTemplate:
        case CXCursor_ClassTemplatePartialSpecialization:
            tag->SetKind(wxT("class"));
            break;

        case CXCursor_StructDecl:
            tag->SetKind(wxT("struct"));
            break;

        case CXCursor_TypeRef:
        case CXCursor_TypedefDecl:
            tag->SetKind(wxT("typedef"));
            tag->SetKind(wxT("typedef"));
            break;
        default:
            tag->SetKind(wxT("variable"));
            break;
        }

        tags.push_back(tag);
    }

    clang_disposeCodeCompleteResults(reply->results);

    CL_DEBUG(wxT("Building completion results... done "));
    if(GetContext() == CTX_Calltip) {
        std::vector<TagEntryPtr> tips;
        TagsManagerST::Get()->GetFunctionTipFromTags(tags, filterWord, tips);
        m_activeEditor->ShowCalltip(new clCallTip(tips));

    } else {
        wxCodeCompletionBoxManager::Get().ShowCompletionBox(
            m_activeEditor->GetCtrl(), tags, wxCodeCompletionBox::kNone, wxNOT_FOUND);
    }
}
Beispiel #21
0
AutoPtr<Elem> Prism6::build_side (const unsigned int i,
				  bool proxy) const
{
  libmesh_assert_less (i, this->n_sides());

  if (proxy)
    {
      switch(i)
	{
	case 0:
	case 4:
	  {
	    AutoPtr<Elem> face(new Side<Tri3,Prism6>(this,i));
	    return face;
	  }

	case 1:
	case 2:
	case 3:
	  {
	    AutoPtr<Elem> face(new Side<Quad4,Prism6>(this,i));
	    return face;
	  }

	default:
	  {
	    libmesh_error();
	  }
	}
    }

  else
    {
      // Create NULL pointer to be initialized, returned later.
      AutoPtr<Elem> face(NULL);

      switch (i)
	{
	case 0:  // the triangular face at z=-1
	  {
            face.reset(new Tri3);

	    face->set_node(0) = this->get_node(0);
	    face->set_node(1) = this->get_node(2);
	    face->set_node(2) = this->get_node(1);

	    break;
	  }
	case 1:  // the quad face at y=0
	  {
            face.reset(new Quad4);

	    face->set_node(0) = this->get_node(0);
	    face->set_node(1) = this->get_node(1);
	    face->set_node(2) = this->get_node(4);
	    face->set_node(3) = this->get_node(3);

	    break;
	  }
	case 2:  // the other quad face
	  {
            face.reset(new Quad4);

	    face->set_node(0) = this->get_node(1);
	    face->set_node(1) = this->get_node(2);
	    face->set_node(2) = this->get_node(5);
	    face->set_node(3) = this->get_node(4);

	    break;
	  }
	case 3: // the quad face at x=0
	  {
            face.reset(new Quad4);

	    face->set_node(0) = this->get_node(2);
	    face->set_node(1) = this->get_node(0);
	    face->set_node(2) = this->get_node(3);
	    face->set_node(3) = this->get_node(5);

	    break;
	  }
	case 4: // the triangular face at z=1
	  {
            face.reset(new Tri3);

	    face->set_node(0) = this->get_node(3);
	    face->set_node(1) = this->get_node(4);
	    face->set_node(2) = this->get_node(5);

	    break;
	  }
	default:
	  {
	    libmesh_error();
	  }
	}

      face->subdomain_id() = this->subdomain_id();
      return face;
    }

  // We'll never get here.
  libmesh_error();
  AutoPtr<Elem> ap(NULL);  return ap;
}
Beispiel #22
0
/* A new Tycon was selected */
static local VOID SetTycon(HWND hDlg, UINT currTycon, List tycons)
{
  Tycon       tc;
  Int         j;
  Type        t;
  Inst	      in;

  tc = nth(currTycon,tycons);
  numCfuns = 0;
  numSfuns = 0;

  t = tc;
  for(j=0; j<tycon(tc).arity; ++j)
    t = ap(t, mkOffset(j));

  switch(tycon(tc).what) {
   case SYNONYM:
     fprintf  (stdstr, "type ");
     printType(stdstr, t);
     fprintf  (stdstr, " = ");
     printType(stdstr, tycon(tc).defn);
     fprintf  (stdstr, "\n");

     SendDlgItemMessage(hDlg, LB_CONS ,LB_RESETCONTENT, 0, 0L);
     SendDlgItemMessage(hDlg, LB_DEF ,LB_RESETCONTENT, 0, 0L);
     SendDlgItemMessage(hDlg, LB_DEF ,LB_ADDSTRING, 0, (LONG)(LPSTR) stdstrbuff);
     break;

   case NEWTYPE:
   case DATATYPE: {
     List cs = tycon(tc).defn;

     if (tycon(tc).what==DATATYPE)
	fprintf(stdstr, "data ");
     else
	fprintf(stdstr, "newtype ");
     printType(stdstr, t);
     fprintf  (stdstr, "\n");
     SendDlgItemMessage(hDlg, LB_DEF ,LB_RESETCONTENT, 0, 0L);
     SendDlgItemMessage(hDlg, LB_DEF ,LB_ADDSTRING, 0, (LONG)(LPSTR) stdstrbuff);

     SendDlgItemMessage(hDlg, LB_CONS ,LB_RESETCONTENT, 0, 0L);

     /* Clear the redraw flag */
     SendDlgItemMessage(hDlg, LB_CONS ,WM_SETREDRAW, FALSE, 0L);

     for (; nonNull(cs); cs=tl(cs)) {
	 printExp (stdstr, hd(cs));
	 fprintf  (stdstr, " :: ");
	 printType(stdstr, name(hd(cs)).type);
	 fprintf  (stdstr, "\n");
	 SendDlgItemMessage(hDlg, LB_CONS ,LB_ADDSTRING, 0, (LONG)(LPSTR) stdstrbuff);
	 SendDlgItemMessage(hDlg, LB_CONS, LB_SETCURSEL, 0, 0L);
	 if (isCfun(hd(cs)))
	     numCfuns++;
	 else
	     numSfuns++;
     }

     /* Set the redraw flag and force repaint. */
     SendDlgItemMessage(hDlg, LB_CONS ,WM_SETREDRAW, TRUE, 0L);
     InvalidateRect(GetDlgItem(hDlg, LB_CONS), NULL, TRUE);

     break;
   }
   case RESTRICTSYN:
     fprintf  (stdstr, "type");
     printType(stdstr, t);
     fprintf  (stdstr, " = <restricted>\n");

     SendDlgItemMessage(hDlg, LB_CONS ,LB_RESETCONTENT, 0, 0L);
     SendDlgItemMessage(hDlg, LB_DEF ,LB_RESETCONTENT, 0, 0L);
     SendDlgItemMessage(hDlg, LB_DEF ,LB_ADDSTRING, 0, (LONG)(LPSTR) stdstrbuff);
     break;
  }

  /* Set instances */
  SendDlgItemMessage(hDlg, LB_TYCONSINST ,LB_RESETCONTENT, 0, 0L);
  /* Clear the redraw flag */
  SendDlgItemMessage(hDlg, LB_TYCONSINST, WM_SETREDRAW, FALSE, 0L);

  if (nonNull(in=findFirstInst(tc))) {
    do {
	SendDlgItemMessage(hDlg, LB_TYCONSINST, LB_ADDSTRING, 0, (LONG)(LPSTR) in);
	SendDlgItemMessage(hDlg, LB_TYCONSINST, LB_SETCURSEL, 0, 0L);
        in = findNextInst(tc,in);
    } while (nonNull(in));
  }
  /* Set the redraw flag and force repaint. */
  SendDlgItemMessage(hDlg, LB_TYCONSINST, WM_SETREDRAW, TRUE, 0L);
  InvalidateRect(GetDlgItem(hDlg, LB_TYCONSINST), NULL, TRUE);

}
Beispiel #23
0
void SieveCommand::parse( const EString & previous )
{
    if ( identifier().isEmpty() )
        setError( "Command name is empty" );

    bool test = false;
    bool blk = false;

    EString i = identifier();
    if ( i == "if" || i == "elsif" ) {
        test = true;
        blk = true;
        if ( i == "elsif" && previous != "if" && previous != "elsif" )
            setError( "elsif is only permitted after if/elsif" );
    }
    else if ( i == "else" ) {
        blk = true;
        if ( previous != "if" && previous != "elsif" )
            setError( "else is only permitted after if/elsif" );
    }
    else if ( i == "require" ) {
        arguments()->numberRemainingArguments();
        UStringList::Iterator i( arguments()->takeStringList( 1 ) );
        EStringList a;
        EStringList e;
        while ( i ) {
            if ( supportedExtensions()->contains( i->ascii() ) )
                a.append( i->ascii().quoted() );
            else
                e.append( i->ascii().quoted() );
            ++i;
        }
        if ( !e.isEmpty() )
            setError( "Each string must be a supported "
                      "sieve extension. "
                      "These are not: " + e.join( ", " ) );
        if ( !d->require )
            setError( "require is only permitted as the first command." );
        else if ( parent() )
            parent()->addExtensions( &a );
    }
    else if ( i == "stop" ) {
        // nothing needed
    }
    else if ( i == "reject" ) {
        require( "reject" );
        if ( arguments()->arguments()->isEmpty() ) {
            // we accept reject without reason
        }
        else {
            // if there is an argument, it must be a string
            arguments()->numberRemainingArguments();
            (void)arguments()->takeString( 1 );
        }
    }
    else if ( i == "ereject" ) {
        require( "reject" );
        arguments()->numberRemainingArguments();
        (void)arguments()->takeString( 1 );
    }
    else if ( i == "fileinto" ) {
        require( "fileinto" );
        if ( arguments()->findTag( ":copy" ) )
            require( "copy" );
        if ( arguments()->findTag( ":flags" ) ) {
            require( "imap4flags" );
            (void)arguments()->takeTaggedStringList( ":copy" );
        }
        arguments()->numberRemainingArguments();
        UString mailbox = arguments()->takeString( 1 );
        UString p;
        p.append( "/" );
        p.append( mailbox );

        if ( !Mailbox::validName( mailbox ) && !Mailbox::validName( p ) ) {
            setError( "Expected mailbox name, but got: " + mailbox.utf8() );
        }
        else if ( mailbox.startsWith( "INBOX." ) ) {
            // a sieve script which wants to reference a
            // mailbox called INBOX.X must use lower case
            // (inbox.x).
            UString aox =
                UStringList::split( '.', mailbox.mid( 6 ) )->join( "/" );
            setError( mailbox.utf8().quoted() +
                      " is Cyrus syntax. Archiveopteryx uses " +
                      aox.utf8().quoted() );
        }
    }
    else if ( i == "redirect" ) {
        (void)arguments()->findTag( ":copy" );
        arguments()->numberRemainingArguments();
        EString s = arguments()->takeString( 1 ).utf8();
        AddressParser ap( s );
        ap.assertSingleAddress();
        if ( !ap.error().isEmpty() )
            setError( "Expected one normal address (local@domain), but got: "
                      + s );
    }
    else if ( i == "keep" ) {
        // nothing needed
    }
    else if ( i == "discard" ) {
        // nothing needed
    }
    else if ( i == "vacation" ) {
        // vacation [":days" number] [":subject" string]
        //          [":from" string] [":addresses" string-list]
        //          [":mime"] [":handle" string] <reason: string>

        require( "vacation" );

        // :days
        uint days = 7;
        if ( arguments()->findTag( ":days" ) )
            days = arguments()->takeTaggedNumber( ":days" );
        if ( days < 1 || days > 365 )
            arguments()->tagError( ":days", "Number must be 1..365" );

        // :subject
        (void)arguments()->takeTaggedString( ":subject" );
        // anything is acceptable, right?

        // :from
        if ( arguments()->findTag( ":from" ) ) {
            parseAsAddress( arguments()->takeTaggedString( ":from" ),
                            ":from" );
            // XXX we don't enforce its being a local address.
        }

        // :addresses
        if ( arguments()->findTag( ":addresses" ) ) {
            UStringList * addresses
                = arguments()->takeTaggedStringList( ":addresses" );
            UStringList::Iterator i( addresses );
            while ( i ) {
                parseAsAddress( *i, ":addresses" );
                ++i;
            }
        }

        // :mime
        bool mime = false;
        if ( arguments()->findTag( ":mime" ) )
            mime = true;

        // :handle
        (void)arguments()->takeTaggedString( ":handle" );

        // reason
        arguments()->numberRemainingArguments();
        UString reason = arguments()->takeString( 1 );
        if ( mime ) {
            if ( !reason.isAscii() )
                setError( ":mime bodies must be all-ASCII, "
                          "8-bit text is not permitted" ); // so says the RFC
            EString x = reason.utf8();
            uint i = 0;
            Header * h = Message::parseHeader( i, x.length(),
                                               x, Header::Mime );
            Bodypart * bp = Bodypart::parseBodypart( i, x.length(),
                                                     x, h, 0 );
            if ( !h->error().isEmpty() )
                setError( "While parsing MIME header: " + h->error() );
            else if ( !bp->error().isEmpty() )
                setError( "While parsing MIME bodypart: " + bp->error() );

            List<HeaderField>::Iterator f( h->fields() );
            while ( f ) {
                if ( !f->name().startsWith( "Content-" ) )
                    setError( "Header field not permitted: " + f->name() );
                ++f;
            }

            if ( bp->children()->isEmpty() && bp->text().isEmpty() )
                setError( "Vacation reply does not contain any text" );
        }
        else {
            if ( reason.isEmpty() )
                setError( "Empty vacation text does not make sense" );
        }
    }
    else if ( i == "setflag" ||
              i == "addflags" ||
              i == "removeflag" ) {
        arguments()->numberRemainingArguments();
        (void)arguments()->takeStringList( 1 );
    }
    else if ( i == "notify" ) {
        require( "enotify" );
        UString from;
        if ( arguments()->findTag( ":from" ))
            from = arguments()->takeTaggedString( ":from" );

        UString importance;
        importance.append( "2" );
        if ( arguments()->findTag( ":importance" ) )
            importance = arguments()->takeTaggedString( ":from" );
        uint c = importance[0];
        if ( c < '1' || c > '3' )
            arguments()->tagError( ":importance",
                                   "Importance must be 1, 2 or 3" );

        UStringList * options;
        if ( arguments()->findTag( ":options" ) )
            options = arguments()->takeTaggedStringList( ":options" );

        UString message;
        if ( arguments()->findTag( ":message" ) )
            message = arguments()->takeTaggedString( ":message" );

        arguments()->numberRemainingArguments();
        UString method = arguments()->takeString( 1 );

        SieveNotifyMethod * m
            = new SieveNotifyMethod( method,
                                     arguments()->takeArgument( 1 ),
                                     this );

        if ( m->valid() ) {
            if ( arguments()->findTag( ":from" ) )
                m->setFrom( from, arguments()->findTag( ":from" ) );
            if ( arguments()->findTag( ":message" ) )
                m->setMessage( message, arguments()->findTag( ":message" ) );
        }
    }
    else {
        setError( "Command unknown: " + identifier() );
    }

    arguments()->flagUnparsedAsBad();

    if ( test ) {
        // we must have a test
        if ( !arguments() || arguments()->tests()->count() != 1 )
            setError( "Command " + identifier() + " requires one test" );
        if ( arguments() ) {
            List<SieveTest>::Iterator i( arguments()->tests() );
            while ( i ) {
                i->parse();
                if ( blk && block() ) {
                    if ( i->ihaveFailed() )
                        block()->setIhaveFailed();
                    else
                        block()->addExtensions( i->addedExtensions() );
                }
                ++i;
            }
        }
    }
    else {
        // we cannot have a test
        if ( arguments() && arguments()->tests()->isEmpty() ) {
            List<SieveTest>::Iterator i( arguments()->tests() );
            while ( i ) {
                i->setError( "Command " + identifier() +
                             " does not use tests" );
                ++i;
            }
        }
    }

    if ( blk ) {
        // we must have a subsidiary block
        if ( !block() ) {
            setError( "Command " + identifier() +
                      " requires a subsidiary {..} block" );
        }
        else {
            EString prev;
            List<SieveCommand>::Iterator i( block()->commands() );
            while ( i ) {
                i->parse( prev );
                prev = i->identifier();
                ++i;
            }
        }
    }
    else {
        // we cannot have a subsidiary block
        if ( block() )
            block()->setError( "Command " + identifier() +
                               " does not use a subsidiary command block" );
        // in this case we don't even bother syntax-checking the test
        // or block
    }
}
Beispiel #24
0
int main( int argc, char *argv[] )
{
  bell::set_symbols_from_env();

  arguments args;

  {
    arg_parser ap( argv[0], "musgrep -- grep rows for music", "OPTIONS" );
    args.bind( ap );

    if ( !ap.parse(argc, argv) )
      {
        ap.usage();
        return 1;
      }
    
    if ( !args.validate(ap) )
      return 1;
  }

# if RINGING_USE_TERMCAP
  if ( args.hilight )
    setupterm(NULL, 1, NULL);
# endif

  char const* seq1 = RINGING_TERMINFO_VAR( enter_standout_mode );
  char const* seq2 = RINGING_TERMINFO_VAR( exit_standout_mode );

  // Let's use an asterisk to allow 'highlighting' on platforms that 
  // don't support termcap on when stdout is not a tty.
  if (!seq2 || !isatty(1)) seq1 = NULL, seq2 = " *";

  const bool output_rows 
    = !args.count && !args.separate_scores && !args.score 
      && !args.negative && !args.positive;

  // NB: Don't use args.mus.get_count() -- that will double count 5-runs
  // when 4-runs are selected, for example.
  int count = 0, countp = 0, countn = 0;
  bool back = true;
  while ( cin ) {
    row r; 
    cin >> r;
    if ( r.bells() != args.bells ) continue;
    back = !back;

    if ( r.sign() < 0 && args.in_course ) continue;
    if ( r.sign() > 0 && args.oo_course ) continue;

    int old_score = args.mus.get_score();
    if ( args.mus.process_row(r, back) ) 
    {
      ++count;

      int delta = args.mus.get_score() - old_score;
      if (delta > 0) ++countp; else if (delta < 0) ++countn;

      if (output_rows)
      {
        if (args.hilight && seq1) cout << seq1;
        cout << r;
        if (args.hilight && seq2) cout << seq2;
        cout << "\n";
      }
    }
    else if (output_rows && args.hilight)
      cout << r << "\n";
  }

  // Print counters
  bool need_sep = false;
  if (args.positive) output_counter( cout, need_sep, countp ); 
  if (args.negative) output_counter( cout, need_sep, countn );
  if (args.count)    output_counter( cout, need_sep, count  );
  if (args.score)    output_counter( cout, need_sep, args.mus.get_score() );
  if (need_sep)      cout << endl;

  if (args.separate_scores) {
    need_sep = false;

    // We need an extra level of mapping instead of just printing 
    // music::const_iterator->count, because some named music patterns
    // such as <4-runs> us multiple details objects.
    for ( vector< pair<size_t,size_t> >::const_iterator 
            i = args.musdets.begin(), e = args.musdets.end();
            i != e; ++i ) { 
      size_t c = 0;
      for ( music::const_iterator j = args.mus.begin() + i->first,
                                  k = args.mus.begin() + i->second; 
              j != k; ++j )
        c += j->total();
      output_counter( cout, need_sep, c );
    }
    if (need_sep) cout << endl;
  }
}
Beispiel #25
0
void ComputeExt::doWork()
{
  ResizeArrayIter<PatchElem> ap(patchList);

#if 0
  // Skip computations if nothing to do.
  if ( ! patchList[0].p->flags.doFullElectrostatics )
  {
    for (ap = ap.begin(); ap != ap.end(); ap++) {
      CompAtom *x = (*ap).positionBox->open();
      Results *r = (*ap).forceBox->open();
      (*ap).positionBox->close(&x);
      (*ap).forceBox->close(&r);
    }
    reduction->submit();
    return;
  }
#endif

  // allocate message
  int numLocalAtoms = 0;
  for (ap = ap.begin(); ap != ap.end(); ap++) {
    numLocalAtoms += (*ap).p->getNumAtoms();
  }

  ExtCoordMsg *msg = new (numLocalAtoms, 0) ExtCoordMsg;
  msg->sourceNode = CkMyPe();
  msg->numAtoms = numLocalAtoms;
  msg->lattice = patchList[0].p->flags.lattice;
  ComputeExtAtom *data_ptr = msg->coord;

  // get positions
  for (ap = ap.begin(); ap != ap.end(); ap++) {
    CompAtom *x = (*ap).positionBox->open();
    CompAtomExt *xExt = (*ap).p->getCompAtomExtInfo();
#if 0
    if ( patchList[0].p->flags.doMolly ) {
      (*ap).positionBox->close(&x);
      x = (*ap).avgPositionBox->open();
    }
#endif
    int numAtoms = (*ap).p->getNumAtoms();

    for(int i=0; i<numAtoms; ++i)
    {
      data_ptr->position = x[i].position;
      data_ptr->charge = x[i].charge;
      data_ptr->id = xExt[i].id;
      ++data_ptr;
    }

#if 0
    if ( patchList[0].p->flags.doMolly ) { (*ap).avgPositionBox->close(&x); }
    else { (*ap).positionBox->close(&x); }
#endif
    (*ap).positionBox->close(&x);
  }

  CProxy_ComputeExtMgr extProxy(CkpvAccess(BOCclass_group).computeExtMgr);
  extProxy[0].recvCoord(msg);

}
Beispiel #26
0
AutoPtr<Elem> InfPrism12::build_side (const unsigned int i,
                                      bool proxy) const
{
  libmesh_assert_less (i, this->n_sides());

  if (proxy)
    {
      switch (i)
        {
          // base
        case 0:
          {
            AutoPtr<Elem> ap(new Side<Tri6,InfPrism12>(this,i));
            return ap;
          }
          // ifem sides
        case 1:
        case 2:
        case 3:
          {
            AutoPtr<Elem> ap(new Side<InfQuad6,InfPrism12>(this,i));
            return ap;
          }
        default:
          libmesh_error_msg("Invalid side i = " << i);
        }
    }

  else
    {
      // Create NULL pointer to be initialized, returned later.
      AutoPtr<Elem> face(NULL);

      switch (i)
        {
        case 0:  // the triangular face at z=-1, base face
          {
            face.reset(new Tri6);

            // Note that for this face element, the normal points inward
            face->set_node(0) = this->get_node(0);
            face->set_node(1) = this->get_node(1);
            face->set_node(2) = this->get_node(2);
            face->set_node(3) = this->get_node(6);
            face->set_node(4) = this->get_node(7);
            face->set_node(5) = this->get_node(8);

            break;
          }

        case 1:  // the quad face at y=0
          {
            face.reset(new InfQuad6);

            face->set_node(0) = this->get_node(0);
            face->set_node(1) = this->get_node(1);
            face->set_node(2) = this->get_node(3);
            face->set_node(3) = this->get_node(4);
            face->set_node(4) = this->get_node(6);
            face->set_node(5) = this->get_node(9);

            break;
          }

        case 2:  // the other quad face
          {
            face.reset(new InfQuad6);

            face->set_node(0) = this->get_node(1);
            face->set_node(1) = this->get_node(2);
            face->set_node(2) = this->get_node(4);
            face->set_node(3) = this->get_node(5);
            face->set_node(4) = this->get_node(7);
            face->set_node(5) = this->get_node(10);

            break;
          }

        case 3: // the quad face at x=0
          {
            face.reset(new InfQuad6);

            face->set_node(0) = this->get_node(2);
            face->set_node(1) = this->get_node(0);
            face->set_node(2) = this->get_node(5);
            face->set_node(3) = this->get_node(3);
            face->set_node(4) = this->get_node(8);
            face->set_node(5) = this->get_node(11);

            break;
          }

        default:
          libmesh_error_msg("Invalid side i = " << i);
        }

      face->subdomain_id() = this->subdomain_id();
      return face;
    }

  libmesh_error_msg("We'll never get here!");
  AutoPtr<Elem> ap(NULL);
  return ap;
}
Beispiel #27
0
AutoPtr<Elem> InfPrism6::build_side (const unsigned int i,
                                     bool proxy) const
{
  libmesh_assert_less (i, this->n_sides());

  if (proxy)
    {
      switch (i)
        {
          // base
        case 0:
          {
            AutoPtr<Elem> ap(new Side<Tri3,InfPrism6>(this,i));
            return ap;
          }
          // ifem sides
        case 1:
        case 2:
        case 3:
          {
            AutoPtr<Elem> ap(new Side<InfQuad4,InfPrism6>(this,i));
            return ap;
          }
        default:
          libmesh_error();
        }
    }

  else
    {
      // Create NULL pointer to be initialized, returned later.
      AutoPtr<Elem> face(NULL);

      switch (i)
        {
        case 0:  // the triangular face at z=-1, base face
          {
            face.reset(new Tri3);

            // Note that for this face element, the normal points inward
            face->set_node(0) = this->get_node(0);
            face->set_node(1) = this->get_node(1);
            face->set_node(2) = this->get_node(2);

            break;
          }

        case 1:  // the quad face at y=0
          {
            face.reset(new InfQuad4);

            face->set_node(0) = this->get_node(0);
            face->set_node(1) = this->get_node(1);
            face->set_node(2) = this->get_node(3);
            face->set_node(3) = this->get_node(4);

            break;
          }

        case 2:  // the other quad face
          {
            face.reset(new InfQuad4);

            face->set_node(0) = this->get_node(1);
            face->set_node(1) = this->get_node(2);
            face->set_node(2) = this->get_node(4);
            face->set_node(3) = this->get_node(5);

            break;
          }

        case 3: // the quad face at x=0
          {
            face.reset(new InfQuad4);

            face->set_node(0) = this->get_node(2);
            face->set_node(1) = this->get_node(0);
            face->set_node(2) = this->get_node(5);
            face->set_node(3) = this->get_node(3);

            break;
          }

        default:
          {
            libmesh_error();
          }
        }

      face->subdomain_id() = this->subdomain_id();
      return face;
    }


  // We will never get here...  Look at the code above.
  libmesh_error();
  AutoPtr<Elem> ap(NULL);  return ap;
}
Beispiel #28
0
/*
	This method generates all the textures
*/
u32 TextureSource::getTextureIdDirect(const std::string &name)
{
	//infostream<<"getTextureIdDirect(): name=\""<<name<<"\""<<std::endl;

	// Empty name means texture 0
	if(name == "")
	{
		infostream<<"getTextureIdDirect(): name is empty"<<std::endl;
		return 0;
	}
	
	/*
		Calling only allowed from main thread
	*/
	if(get_current_thread_id() != m_main_thread)
	{
		errorstream<<"TextureSource::getTextureIdDirect() "
				"called not from main thread"<<std::endl;
		return 0;
	}

	/*
		See if texture already exists
	*/
	{
		JMutexAutoLock lock(m_atlaspointer_cache_mutex);

		core::map<std::string, u32>::Node *n;
		n = m_name_to_id.find(name);
		if(n != NULL)
		{
			infostream<<"getTextureIdDirect(): \""<<name
					<<"\" found in cache"<<std::endl;
			return n->getValue();
		}
	}

	infostream<<"getTextureIdDirect(): \""<<name
			<<"\" NOT found in cache. Creating it."<<std::endl;
	
	/*
		Get the base image
	*/

	char separator = '^';

	/*
		This is set to the id of the base image.
		If left 0, there is no base image and a completely new image
		is made.
	*/
	u32 base_image_id = 0;
	
	// Find last meta separator in name
	s32 last_separator_position = -1;
	for(s32 i=name.size()-1; i>=0; i--)
	{
		if(name[i] == separator)
		{
			last_separator_position = i;
			break;
		}
	}
	/*
		If separator was found, construct the base name and make the
		base image using a recursive call
	*/
	std::string base_image_name;
	if(last_separator_position != -1)
	{
		// Construct base name
		base_image_name = name.substr(0, last_separator_position);
		/*infostream<<"getTextureIdDirect(): Calling itself recursively"
				" to get base image of \""<<name<<"\" = \""
                <<base_image_name<<"\""<<std::endl;*/
		base_image_id = getTextureIdDirect(base_image_name);
	}
	
	//infostream<<"base_image_id="<<base_image_id<<std::endl;
	
	video::IVideoDriver* driver = m_device->getVideoDriver();
	assert(driver);

	video::ITexture *t = NULL;

	/*
		An image will be built from files and then converted into a texture.
	*/
	video::IImage *baseimg = NULL;
	
	// If a base image was found, copy it to baseimg
	if(base_image_id != 0)
	{
		JMutexAutoLock lock(m_atlaspointer_cache_mutex);

		SourceAtlasPointer ap = m_atlaspointer_cache[base_image_id];

		video::IImage *image = ap.atlas_img;
		
		if(image == NULL)
		{
			infostream<<"getTextureIdDirect(): NULL image in "
					<<"cache: \""<<base_image_name<<"\""
					<<std::endl;
		}
		else
		{
			core::dimension2d<u32> dim = ap.intsize;

			baseimg = driver->createImage(video::ECF_A8R8G8B8, dim);

			core::position2d<s32> pos_to(0,0);
			core::position2d<s32> pos_from = ap.intpos;
			
			image->copyTo(
					baseimg, // target
					v2s32(0,0), // position in target
					core::rect<s32>(pos_from, dim) // from
			);

			/*infostream<<"getTextureIdDirect(): Loaded \""
					<<base_image_name<<"\" from image cache"
					<<std::endl;*/
		}
	}
	
	/*
		Parse out the last part of the name of the image and act
		according to it
	*/

	std::string last_part_of_name = name.substr(last_separator_position+1);
	//infostream<<"last_part_of_name=\""<<last_part_of_name<<"\""<<std::endl;

	// Generate image according to part of name
	if(generate_image(last_part_of_name, baseimg, m_device) == false)
	{
		infostream<<"getTextureIdDirect(): "
				"failed to generate \""<<last_part_of_name<<"\""
				<<std::endl;
	}

	// If no resulting image, print a warning
	if(baseimg == NULL)
	{
		infostream<<"getTextureIdDirect(): baseimg is NULL (attempted to"
				" create texture \""<<name<<"\""<<std::endl;
	}
	
	if(baseimg != NULL)
	{
		// Create texture from resulting image
		t = driver->addTexture(name.c_str(), baseimg);
	}
	
	/*
		Add texture to caches (add NULL textures too)
	*/

	JMutexAutoLock lock(m_atlaspointer_cache_mutex);
	
	u32 id = m_atlaspointer_cache.size();
	AtlasPointer ap(id);
	ap.atlas = t;
	ap.pos = v2f(0,0);
	ap.size = v2f(1,1);
	ap.tiled = 0;
	core::dimension2d<u32> baseimg_dim(0,0);
	if(baseimg)
		baseimg_dim = baseimg->getDimension();
	SourceAtlasPointer nap(name, ap, baseimg, v2s32(0,0), baseimg_dim);
	m_atlaspointer_cache.push_back(nap);
	m_name_to_id.insert(name, id);

	/*infostream<<"getTextureIdDirect(): "
			<<"Returning id="<<id<<" for name \""<<name<<"\""<<std::endl;*/
	
	return id;
}
Beispiel #29
0
DEM typ1 (DEM x)
{
int o, o1, o2;
DEM a, b, c, c1, f, x1, y, z, v, PIab, bz, s, tf, tf1, tz, tz1, t, n, n1, r;
#if 1
	return U(Order(0));
#else

    o = order(x);
    o1 = suc_order(o);
    o2 = suc_order(o1);

    switch (node(x))
    {
	case _Var : return subdem(0,x);

	case _It:
	    a = subdem(0,x);
	    t = Fott (o1, a, a);
	    return t;

        case _IT :
	    a = Var ("a", U(o1)); 
	    return PIott (o2, U(o1), lambda (a,
			   Fott (/*suc_order*/(o1), a, a) ));

	case _Kt:
	    a = subdem(0,x);
	    b = subdem(1,x);
	    t =  Fott (o1, a, Fott (o1, b, a));
	    return t;

        case _KT :
	    a = Var ("a", U(o1));
	    b = Var ("b", U(o1));
	    return PIott (o2, U(o1), lambda (a,
		    PIott (o2, U(o1), lambda(b,
		     Fott (o1, a, Fott (o1, b, a)) )) ));

	case _St:
	    a = subdem(0,x);
            b = subdem(1,x);
	    c = subdem(2,x);
     z = Var ("z", a);
     y = Var ("y", PIott (o1, a, b));
	    t = Fott (o1, PIott (o1, a, lambda (z,
		        PIott(o1, ap(b,z),ap(c,z)))),
		         PIott (o1, PIott (o1, a, b), lambda (y, 
			  Fott (o1, a, ap(ap(c,z),ap(y,z)))) ));
	    return t;

        case _ST :
	    a = Var ("a", U(o1));
	    b = Var ("b", Fott (o2, a, U(o1)));
            z = Var ("z", a);
	    c = Var ("c", PIott (o1, a, lambda (z, Fott (o2, ap(b,z), U(o1)))));
	    y = Var ("y", PIott (o1, a, b));
	    
	    return PIott (o2, U(o1), lambda (a,
		    Fott (o2, Fott (o2, a, U(o1)), lambda (b,
		     PIott (o1, PIott (o1, a, lambda (z, 
		      Fott (o2, ap(b,z), U(o1)))), lambda (c, 
		       Fott (o1, PIott (o1, a, lambda (z,
		        PIott(o1, ap(b,z),ap(c,z)))),
		         PIott (o1, PIott (o1, a, b), lambda (y, 
			  Fott (o1, a, ap(ap(c,z),ap(y,z)))) )))
			    ) ))));

	case _Yt:
	    a = subdem(0,x);
	    t = Fott (o1, Fott (o1, a, a), a);
	    return t;

	case _Ord:
	    return U(Order(1));

	case _Zero:
	    return Ord;

	case _Suc:
	    return Fott (Order(1), Ord, Ord);

	case _Lim:
	    return Fott (Order(1), Fott (Order(1), Ord, Ord), Ord);

	case _Rept:
	    o1 = Order(1);
	    a = subdem(0,x);
	    t = Fott (o1, Ord, 
		    Fott (o1, Fott (o1, a, a), Fott (o1, a, a)));
	    return t;

	case _Testt:
	    o1 = Order(1);
	    a = subdem(0,x);
	    n = Var ("n", Ord);
            n1 = Var ("n1", Ord);
            t = PIott (o1, Ord, lambda (n1, Fott (o1, ap (a, Zero),
                    Ftt ( PIott (o1, Ord, lambda (n, ap (a, ap (Suc, n)))),
                           ap (a, n1) ) )));
	    return t;

        case _F:
            return Fott (o1, U(o), Fott (o1, U(o), U(o)));

	case _PI:
	    a = Var ("a", U(o));
	    return PIott (o1, U(o), lambda (a,
			    Fott (o1, Fott (o1, a, U(o)), U(o)) ));
		     
        case _U: return U (suc_order (order_u (x)));

	case _ap:
            if (depth(x) == 1 && node(s=rfnc(1,x)) == _Kt)
	    {
		a = subdem(0,s);
		b = subdem(1,s);
		o = order(s);
		return Fott (o, b, a);
            }
	    if (node(subdem(0,x)) == _ap &&
	        node(subdem(0,subdem(0,x))) == _ap &&
                node(subdem(0,subdem(0,subdem(0,x)))) == _KT)
	    {
		a = subdem(1,subdem(0,subdem(0,x)));
		b = subdem(1,subdem(0,x));
		o = order(a);
		return Fott (o, b, a);
	    }
	    if (depth (x) == 2 && node(s=rfnc(2,x)) == _St)
	    {
		a = subdem(0,s);
		b = subdem(1,s);
		c = subdem(2,s);
		goto Sabc;				
	    }
            if (depth (x) == 5 && node(s=rfnc(5,x)) == _ST)
	    {
	    /* S a:Uo+1 b:(Uo(a)+1) c:(a)>\z:a.((bz)>Uo+1) 
		 x:(a)>\z:a.(cz(bz)) y:(a)>b z:a = xz(yz):cz(yz)
		 xz:(bz)>cz, yz:bz
	       S a b c x y : a ->> \z:a. cz(yz)
             */
	        a = subdem(1,rfnc(4,x));
		b = subdem(1,rfnc(3,x));
		c = subdem(1,rfnc(2,x));
	    Sabc:
		x1 = subdem(1,rfnc(1,x));
		y = subdem(1,rfnc(0,x));
		z = Var ("z", a);
		o = order(s);
		o1 = suc_order (o);
		/* t = PIott (o1, a, lambda (z, ap (ap (c, z), ap (y, z)))); */
		v = Var ("v", simplif (ap (b, z)));
		c1 = lambda (z, lambda (v, U(o1)));

		trace_dem ("c = ", c);

                t = PIott (o1, a, Sotttxx (o, a, b, c1, c, y));
		return t;
	    }
            if (node(subdem(0,x)) == _ap &&
                node(subdem(0,subdem(0,x))) == _F)
            {
                /*
                if (typ (subdem(1,subdem(0,x))) == typ (subdem(1,x)))
                    return typ (subdem(1,x)); 
                error ("F applied to different types", __LINE__, x);
                */
                return unio (typ(subdem(1,subdem(0,x))), 
                             typ(subdem(1,x)));
            }        
	    f = fnc (x);
	    z = arg (x);
	    /* PIab = typ (f);
            b = arg (PIab); */
            tf = typ (f);
            tz = typ (z);
        new_tz:
            print_string (print_param, "typ(z) = ");
            print_dem (print_param, tz);
        new_tf:    
            print_string (print_param, "  subdem(1,subdem(0,tf)) = ");
            print_dem (print_param, subdem(1,subdem(0,tf)));
            print_string (print_param, "\n");

            if (node(tf) == _ap &&
                node(subdem(0,tf)) == _ap &&
                node(subdem(0,subdem(0,tf))) == _F &&
                inclus (tz, subdem(1,subdem(0,tf))))
                return subdem(1,tf);

            if (node(tf) == _ap &&
                node(subdem(0,tf)) == _ap &&
                node(subdem(0,subdem(0,tf))) == _PI &&
                inclus (tz, subdem(1,subdem(0,tf))))
                {
                    /* return ap (subdem(1,tf), z); */
                    tf1 = subdem(1,tf);
                    print_string (print_param, "tf1 = ");
                    print_dem (print_param, tf1);
                    print_string (print_param, "\nz = ");
                    print_dem (print_param, z);
                    r = ap (tf1, z);
                    print_string (print_param, "\nr = ");
                    print_dem (print_param, r);
                    print_string (print_param, "\n");
                    return r;
                }
            print_string (print_param, "Bad type of function ");
            print_dem (print_param, f);
            print_string (print_param, " of type ");
            print_dem (print_param, tf);
            print_string (print_param, " applied to ");
            print_dem (print_param, z);
            print_string (print_param, " of type ");
            print_dem (print_param, tz);
            print_string (print_param, "\n");

            tf1 = simplif (tf);
            if (tf1 != tf)
            {
                tf = tf1;
                goto new_tf;
            }

            tz1 = simplif (tz);
            if (tz1 != tz)
            {
                tz = tz1;
                goto new_tz;
            }

            print_string (print_param, "Bad type of function ");
            print_dem (print_param, f);
            print_string (print_param, " of type ");
            print_dem (print_param, tf);
            print_string (print_param, " applied to ");
            print_dem (print_param, z);
            print_string (print_param, " of type ");
            print_dem (print_param, tz);
            print_string (print_param, "\n");

            error ("Bad type of function : ", __LINE__, tf);


                
	    /*bz = ap (b, z);
	    return bz;*/

        case _Lambda:
            z = subdem(0,x);
            r = subdem(1,x);
            a = typ (z);
            bz = typ (r);
            b = lambda (z, bz);
            t = PItt (a, b);
            return t;
            break;

        default:
	    print_string (print_param, "typ not implemented for ");
	    print_dem (print_param, x);
	    print_string (print_param, "\n");
	    return U(-1);

    }
#endif
}
Beispiel #30
0
bool ossimjni::Info::initialize(int argc, char* argv[])
{
   ossimArgumentParser ap(&argc, argv);
   return m_info->initialize(ap);
}