void listdisk(int nlist) { int i; real r, phi, vcir, omega, Adisk, kappa, sigma1, sigma2, mu_eff, sig_r, sig_p, sig_z, vrad, vorb2, vorb; printf("#%5s %6s %6s %6s %6s %6s %6s %6s %6s %6s %6s\n", "r", "vcir", "omega", "kappa", "sig_z", "sig_r", "sig_p", "vorb", "Q", "rhomid", "fmax"); for (i = 1; i <= nlist; i++) { /* loop over radii */ r = (i * rcut) / ((real) nlist); vcir = seval(r, &rdtab[0], &vctab[0], &vctab[NTAB], NTAB); omega = vcir / r; Adisk = (omega - spldif(r, &rdtab[0], &vctab[0], &vctab[NTAB], NTAB)) / 2; if (omega - Adisk < 0.0) error("%s: kappa undefined (omega - Adisk < 0)\n" " r, omega, Adisk = %f %f %f\n", getargv0(), r, omega, Adisk); kappa = 2 * rsqrt(rsqr(omega) - Adisk * omega); sigma1 = rsqr(alpha1) * mdisk1 * rexp(- alpha1 * r) / TWO_PI; sigma2 = rsqr(alpha2) * mdisk2 * rexp(- alpha2 * r) / TWO_PI; mu_eff = (r_mu>0 ? 1 + (mu - 1) * (r / (r + r_mu)) : mu); sig_z = rsqrt(PI * (sigma1 + sigma2) * zdisk); sig_r = mu_eff * sig_z; sig_p = (0.5 * kappa / omega) * sig_r; vorb2 = rsqr(vcir) + rsqr(sig_r) * (1 - 2 * alpha1 * r) - rsqr(sig_p) + (r_mu>0 ? rsqr(sig_z) * r * mu_eff*(2*mu-2)*r_mu/rsqr(r+r_mu) : 0); vorb = rsqrt(MAX(vorb2, 0.0)); printf("%6.4f %6.4f %6.2f %6.2f %6.4f %6.4f %6.4f %6.4f " "%6.3f %6.1f %6.1f\n", r, vcir, omega, kappa, sig_z, sig_r, sig_p, vorb, kappa * sig_r / (3.358*(sigma1+sigma2)), sigma1/(2*zdisk), sigma1 / (2*zdisk * rsqrt(rqbe(2*PI)) * sig_z*sig_r*sig_p)); } }
/** * * * @param N number of samples * @param theta mutation rate * @param Tb "bottleneck" time * @param f fraction of bottleneck population compared to current * * @return root node * */ struct Node *coalescent_tree(unsigned int N, double theta, double Tb, double f) { // http://users.stat.umn.edu/~geyer/rc/ GetRNGstate(); int k; unsigned int i, j, n_nodes; // there are 2N-2 branches (rooted tree), which implies 2N-1 nodes n_nodes = 2*N - 1; struct Node *nodes[n_nodes]; for (k=0; k < n_nodes; k++) nodes[k] = new_node(k); double rate, Ti, Ttot; Ttot = 0.0; i = j = N; while (i > 1) { // Set the coalescence time rate = i * (i - 1) / 2.0; Ti = rexp(1/rate); if (f != 1.0) { // this part models expansion/bottleneck if (Ttot > Tb) { rate = f * i * (i - 1) / 2.0; Ti = rexp(1/rate) + Tb; } } /* rate is in unit 1/s; want unit s so invert */ Ttot += Ti; nodes[j]->time = Ttot; // Make a number of mutations and sprinkle them out int n_mut, l; // Remember; we need to multiply rate also by the number of // branches; otherwise we're only generating a number of // mutations proportional to TMRCA, not TBL n_mut = (int) rpois((double) (theta / 2 * Ti * i)); for (k=0; k<n_mut; k++) { l = (int) runif(0.0, (double) i); nodes[l]->mutations++; } // Note that the coalescent event can be performed after // setting the time and placing mutations as we know the id of // the parent beforehand coalesce(nodes, j, i); i--; j++; } PutRNGstate(); for (k=0; k < n_nodes; k++) { if (isroot(nodes[k])) return nodes[k]; } }
double sTruncNorm( double bd, /* bound */ double mu, double var, int lower /* 1 = x > bd, 0 = x < bd */ ) { double z, logb, lambda, u; double sigma = sqrt(var); double stbd = (bd - mu)/sigma; if (lower == 0) { stbd = (mu - bd)/sigma; } if (stbd > 0) { lambda = 0.5*(stbd + sqrt(stbd*stbd + 4)); logb = 0.5*(lambda*lambda-2*lambda*stbd); do { z = rexp(1/lambda); /* Rprintf("%5g\n", exp(-0.5*(z+stbd)*(z+stbd)+lambda*z-logb)); */ } while (unif_rand() > exp(-0.5*(z+stbd)*(z+stbd)+lambda*z-logb)); } else { do z = norm_rand(); while(z < stbd); } if (lower == 1) { return(z*sigma + mu); } else { return(-z*sigma + mu); } }
Mirror Sites::parseLine(const QString& line) { Mirror m; QRegExp rexp("([^ ]+) (cddbp|http) (\\d+) ([^ ]+) [N|S]\\d{3}.\\d{2} [E|W]\\d{3}.\\d{2} (.*)"); if (rexp.search(line) != -1) { m.address = rexp.cap(1); if (rexp.cap(2) == "cddbp") m.transport = Lookup::CDDBP; else m.transport = Lookup::HTTP; m.port = rexp.cap(3).toUInt(); if (m.transport == Lookup::HTTP && rexp.cap(4) != "/~cddb/cddb.cgi") kdWarning() << "Non default urls are not supported for http" << endl; m.description = rexp.cap(5); } return m; }
//---------------------------------------------------------------------- // attempts to draw Sigma using a slice sampling scheme. returns // true if draw succeeds bool SepStratSampler::fast_draw(){ count_ = 0; double d = mod_->dim(); double slice = logp0(mod_->Sigma(), alpha_) - rexp(1); while(count_++ < max_tries_){ double a = 1-alpha_; double df = a * n_ - d - 1; if(df <= 1){ ostringstream err; err << "the 'alpha' parameter is set too small in SepStratSampler, " << "causing the resulting degrees of freedom to be less than " << "the dimension of the matrix." <<endl << "dim = " << d << endl << "n = " << n_ << endl << "alpha = " << alpha_ << endl << "(1-alpha) * n = " << a * n_; throw_exception<std::runtime_error>(err.str()); } cand_ = rWishChol(df, sqrt(a) * sumsq_upper_chol_, true); if(logp0(cand_, alpha_) > slice){ mod_->set_Sigma(cand_); return true; } } return false; }
void leftTruncNorm(double *mu, double *sigma2, double *x){ int check1, check2; double alphaStar, u, muMinus, z; muMinus = -*mu/sqrt(*sigma2); if (muMinus <= 0.0){ check1 = FALSE; while(check1 == FALSE){ GetRNGstate(); z = rnorm(0.0,1.0); PutRNGstate(); check1 = (z > muMinus); } } else { alphaStar = 0.5 * (muMinus + sqrt(muMinus * muMinus + 4.0)); check2 = FALSE; while(check2 == FALSE){ GetRNGstate(); z = muMinus + rexp(1/alphaStar); PutRNGstate(); GetRNGstate(); u = runif(0.0,1.0); PutRNGstate(); check2 = (u <= exp(-0.5*(z-alphaStar) * (z-alphaStar))); } } *x = *mu + z * sqrt(*sigma2); }
void predictExtrapUp(double *alpha, double *lambda, double *beta, double *predictPositions, int *NpredictPositions, double *currPositions1, double *theta1, int *maxExtrap, double *extractDate, double *predvals) { // Runs the prediction code when we are extrapolating up beyond the first date int bad=1,count=0,i; double depthEvents[*maxExtrap],timeEvents[*maxExtrap]; depthEvents[0] = *currPositions1; timeEvents[0] = *theta1; while(bad==1) { for(i=1;i<*maxExtrap;i++) { depthEvents[i] = depthEvents[i-1]-rexp(1/(*lambda)); timeEvents[i] = timeEvents[i-1]-rgamma(*alpha,1/(*beta)); } for(i=0;i<*NpredictPositions;i++) { linInterp(maxExtrap,&predictPositions[i],depthEvents,timeEvents,&predvals[i]); } count+=1; bad=0; for(i=0;i<*NpredictPositions;i++) { if(predvals[i]<*extractDate) bad=1; } if(count==50) { for(i=0;i<*NpredictPositions;i++) { if(predvals[i]<*extractDate) predvals[i] = *extractDate; } bad=0; warning("Unable to find suitable chronologies for top of core - truncated to date of extraction"); } } }
double rinvexp(double scale) { if (!R_FINITE(scale) || scale <= 0.0) return R_NaN; return scale / rexp(1.0); }
real pickdist(real eta, real sigma) { static real eta0 = -1.0, sigcorr; int niter; real x, y, q; if (eta != eta0) { sigcorr = rsqrt(8 * eta / (bessel_K(0.75, 1/(32*eta)) / bessel_K(0.25, 1/(32*eta)) - 1)); eprintf("[%s: sigma correction factor = %f]\n", getargv0(), sigcorr); eta0 = eta; } niter = 0; do { x = xrandom(-1.0, 1.0); y = xrandom(0.0, YMAX); q = rexp(- 0.5 * rsqr(fmap(x)) - eta * rsqr(rsqr(fmap(x)))) * (1 + x*x) / rsqr(1 - x*x); if (q > YMAX) /* should not ever happen */ error("%s: guess out of bounds\n x = %f q = %f > %f\n", getargv0(), x, q, YMAX); niter++; if (niter > 1000) error("%s: 1000 iterations without success\n", getargv0()); } while (y > q || x*x == 1); /* 2nd test prevents infty */ return (sigcorr * sigma * fmap(x)); }
void makedisk(void) { real m, r, phi, vcir, omega, Adisk, kappa, sigma1, sigma2, mu_eff, sig_r, sig_p, sig_z, vrad, vorb2, vorb, vphi; double Trr = 0.0, Tpp = 0.0, Tzz = 0.0; int i; bodyptr dp; for (i = 0; i < ndisk; i++) { /* loop initializing bodies */ m = mdtab[NTAB-1] * ((real) i + 0.5) / ndisk; r = seval(m, &mdtab[0], &rdtab[0], &rdtab[NTAB], NTAB); vcir = seval(r, &rdtab[0], &vctab[0], &vctab[NTAB], NTAB); omega = vcir / r; Adisk = (omega - spldif(r, &rdtab[0], &vctab[0], &vctab[NTAB], NTAB)) / 2; if (omega - Adisk < 0.0) error("%s: kappa undefined (omega - Adisk < 0)\n" " r, omega, Adisk = %f %f %f\n", getargv0(), r, omega, Adisk); kappa = 2 * rsqrt(rsqr(omega) - Adisk * omega); sigma1 = rsqr(alpha1) * mdisk1 * rexp(- alpha1 * r) / TWO_PI; sigma2 = rsqr(alpha2) * mdisk2 * rexp(- alpha2 * r) / TWO_PI; mu_eff = (r_mu>0 ? 1 + (mu - 1) * (r / (r + r_mu)) : mu); sig_z = rsqrt(PI * (sigma1 + sigma2) * zdisk); sig_r = mu_eff * sig_z; sig_p = (0.5 * kappa / omega) * sig_r; vorb2 = rsqr(vcir) + rsqr(sig_r) * (1 - 2 * alpha1 * r) - rsqr(sig_p) + (r_mu>0 ? rsqr(sig_z) * r * mu_eff*(2*mu-2)*r_mu/rsqr(r+r_mu) : 0); vorb = rsqrt(MAX(vorb2, 0.0)); dp = NthBody(disk, i); /* set up ptr to disk body */ Mass(dp) = mdisk1 / ndisk; phi = xrandom(0.0, TWO_PI); Pos(dp)[0] = r * rsin(phi); Pos(dp)[1] = r * rcos(phi); Pos(dp)[2] = zdisk * ratanh(xrandom(-1.0, 1.0)); vrad = (eta > 0 ? pickdist(eta, sig_r) : grandom(0.0, sig_r)); vphi = (eta > 0 ? pickdist(eta, sig_p) : grandom(0.0, sig_p)) + vorb; Vel(dp)[0] = vrad * rsin(phi) + vphi * rcos(phi); Vel(dp)[1] = vrad * rcos(phi) - vphi * rsin(phi); Vel(dp)[2] = grandom(0.0, sig_z); Trr += Mass(dp) * rsqr(sig_r) / 2; Tpp += Mass(dp) * (rsqr(vorb) + rsqr(sig_p)) / 2; Tzz += Mass(dp) * rsqr(sig_z) / 2; } eprintf("[%s: Trr = %f Tpp = %f Tzz = %f]\n", getargv0(), Trr, Tpp, Tzz); }
/* Exponential rejection sampling (a,inf) */ static R_INLINE double ers_a_inf(double a) { SAMPLER_DEBUG("ers_a_inf", a, R_PosInf); const double ainv = 1.0 / a; double x, rho; do { x = rexp(ainv) + a; /* rexp works with 1/lambda */ rho = exp(-0.5 * pow((x - a), 2)); } while (runif(0, 1) > rho); return x; }
/* Exponential rejection sampling (a,b) */ static R_INLINE double ers_a_b(double a, double b) { SAMPLER_DEBUG("ers_a_b", a, b); const double ainv = 1.0 / a; double x, rho; do { x = rexp(ainv) + a; /* rexp works with 1/lambda */ rho = exp(-0.5 * pow((x - a), 2)); } while (runif(0, 1) > rho || x > b); return x; }
real sigeff(real sig, real vmax) { real x, y, z, Q; x = vmax / sig; y = (SQRTPI / SQRT2) * erf(x / SQRT2); z = rexp(rsqr(x) / 2); Q = ((-3 * x - rqbe(x)) / z + 3 * y) / (- x / z + y); return (sig * rsqrt(Q / 3)); }
void setprof(void) { int j; real r, msphr; rdtab[0] = mdtab[0] = vctab[0] = 0.0; for (j = 1; j < NTAB; j++) { r = rcut * rpow(((real) j) / (NTAB - 1), 2.0); rdtab[j] = r; mdtab[j] = 1 - rexp(- alpha1 * r) - alpha1 * r * rexp(- alpha1 * r); msphr = (sphr != NULL ? mass_gsp(sphr, r) : 0.0); vctab[j] = rsqrt(msphr / r - gdisk(r) * r); } eprintf("[%s: rcut = %8.4f/alpha M(rcut) = %8.6f mdisk]\n", getargv0(), rdtab[NTAB-1] * alpha1, mdtab[NTAB-1]); if ((mdtab[0] == mdtab[1]) || (mdtab[NTAB-2] == mdtab[NTAB-1])) error("%s: disk mass table is degenerate\n", getargv0()); spline(&rdtab[NTAB], &mdtab[0], &rdtab[0], NTAB); /* for r_d = r_d(m) */ spline(&vctab[NTAB], &rdtab[0], &vctab[0], NTAB); /* for v_c = v_c(r) */ }
// ====================================================================== // exp_rs(a, b) // generates a sample from a N(0,1) RV restricted to the interval // (a,b) using exponential rejection sampling. // This function should be called by rnorm_truncated (where Get/PutRNGstate // are invoked) // ====================================================================== double exp_rs(double a, double b) { double z, u, scale; scale = 1.0/a; // Generate a proposal on (0, b-a) z = rexp(scale); while(z > (b-a)) z = rexp(scale); u = runif(0.0, 1.0); while( log(u) > (-0.5*z*z)) { z = rexp(scale); while(z > (b-a)) z = rexp(scale); u = runif(0.0,1.0); } return(z+a); }
/* Simulation code Note the orders of mm and mr */ void staySim(int *n, double *s, double *mm, double *mr, double *t) { /* starting from moving state, return simulated time length spent in moving state during time (0, s) 1/mr: mean of exp time for resting 1/mm: mean of exp time for moving t[i]: total moving time in (0, s) for t[i] */ int i, ind; double tr, tm; for (i = 0; i < *n; i++) { tr = 0.0; tm = 0.0; while (1) { tm += rexp(*mm); ind = 1; /* time in moving */ if (tm + tr > *s) break; tr += rexp(*mr); ind = 2; /* time in resting */ if (tm + tr > *s) break; } if (ind == 1) t[i] = *s - tr; /* last period is moving */ else t[i] = tm; /* last period is resting */ } }
void predictExtrapDown(double *alpha, double *lambda, double *beta, double *predictPositions, int *NpredictPositions, double *currPositionsn, double *thetan, int *maxExtrap, double *predvals) { // Runs the prediction code when we are extrapolating down below the bottom date double depthEvents[*maxExtrap],timeEvents[*maxExtrap]; int i; depthEvents[0] = *currPositionsn; timeEvents[0] = *thetan; for(i=1;i<*maxExtrap;i++) { depthEvents[i] = depthEvents[i-1]+rexp(1/(*lambda)); timeEvents[i] = timeEvents[i-1]+rgamma(*alpha,1/(*beta)); } for(i=0;i<*NpredictPositions;i++) { linInterp(maxExtrap,&predictPositions[i],depthEvents,timeEvents,&predvals[i]); } }
//---------------------------------------------------------------------- // driver function to draw a single element of the correlation // matrix conditional on the variances. void SepStratSampler::draw_R(int i, int j){ i_ = i; j_ = j; double oldr = R_(i,j); double slice = logp_slice_R(oldr) - rexp(); find_limits(); double rcand = runif(lo_, hi_); while(logp_slice_R(rcand) < slice && hi_ > lo_){ if(rcand > oldr) hi_ = rcand; else lo_ = rcand; rcand = runif(lo_,hi_); } set_R(rcand); }
OfxAccountData::AccountType MyMoneyOfxConnector::accounttype(void) const { OfxAccountData::AccountType result = OfxAccountData::OFX_CHECKING; QString type = m_account.onlineBankingSettings()["type"]; if(type == "CHECKING") result = OfxAccountData::OFX_CHECKING; else if(type == "SAVINGS") result = OfxAccountData::OFX_SAVINGS; else if(type == "MONEY MARKET") result = OfxAccountData::OFX_MONEYMRKT; else if(type == "CREDIT LINE") result = OfxAccountData::OFX_CREDITLINE; else if(type == "CMA") result = OfxAccountData::OFX_CMA; else if(type == "CREDIT CARD") result = OfxAccountData::OFX_CREDITCARD; else if(type == "INVESTMENT") result = OfxAccountData::OFX_INVESTMENT; else { switch( m_account.accountType()) { case MyMoneyAccount::Investment: result = OfxAccountData::OFX_INVESTMENT; break; case MyMoneyAccount::CreditCard: result = OfxAccountData::OFX_CREDITCARD; break; case MyMoneyAccount::Savings: result = OfxAccountData::OFX_SAVINGS; break; default: break; } } // This is a bit of a personalized hack. Sometimes we may want to override the // ofx type for an account. For now, I will stash it in the notes! QRegExp rexp("OFXTYPE:([A-Z]*)"); if ( rexp.search(m_account.description()) != -1 ) { QString override = rexp.cap(1); kdDebug(2) << "MyMoneyOfxConnector::accounttype() overriding to " << result << endl; if ( override == "BANK" ) result = OfxAccountData::OFX_CHECKING; else if ( override == "CC" )
double rgamma(double alpha, double beta) /* * Generates from a general gamma(alpha,beta) distribution */ { double random; if (alpha < 1) do { random = rgamma1(alpha)/beta; } while (random < 0 ); if (alpha == 1) random = rexp(1)/beta; if (alpha > 1) do { random = rgamma2(alpha)/beta; } while (random < 0); return random; }
void MainWindow::txtFilter(const QString& str) { ui->listFiles->clear(); QStringList list = dirwatch.scan(); QString rstr; for(int i = 0; i < str.length(); i++) rstr += (QString)".*" + str[i]; rstr += ".*"; QRegExp rexp(rstr, Qt::CaseInsensitive, QRegExp::RegExp); if(ui->txtEdit->text().length() == 0) { ui->listFiles->addItems(list); } else { ui->listFiles->addItems(list.filter(rexp)); } }
Vec SliceSampler::draw(const Vec &t){ theta = t; z = t; initialize(); pstar = f(theta) - rexp(1); find_limits(); Vec tstar(theta.size(), 0.0); double p = pstar -1; do{ double lam = runif_mt(rng(), -lo, hi); tstar = theta + lam*z; // randomly chosen point in the slice p = f(tstar); if(p<pstar) contract(lam,p); else theta = tstar; }while(p < pstar); scale = hi+lo; // both hi and lo >0 return theta; }
orQuery::orQuery( const QString &qstrPName, const QString &qstrSQL, ParameterList qstrlstParams, bool doexec, QSqlDatabase pDb ) { QString qstrParsedSQL(qstrSQL); QString qstrParam; int intParamNum; int intStartIndex = 0; qryQuery = 0; _database = pDb; // Initialize some privates qstrName = qstrPName; QRegExp rexp("<\\?.*\\?>"); if(rexp.indexIn(qstrParsedSQL) == -1) { // Parse through the passed SQL populating the parameters QRegExp re("(?:%(\\d+))|(?:\\$\"([^\"]*)\")"); while ((intStartIndex = re.indexIn(qstrParsedSQL,intStartIndex)) != -1) { QString val = " "; QString match = re.cap(0); if(match[0] == '$') { QString n = re.cap(2).toLower(); val = qstrlstParams.value(n).toString(); if(val.isNull()) { // add this to the list of missing parameters if(!missingParamList.contains(n)) missingParamList.append(n); } } else if(match[0] == '%') { // Grab the parameter number intParamNum = re.cap(1).toInt(); // Replace the parameter hold with the specified paramemter // Verify the parameter index if (intParamNum <= (int)qstrlstParams.count()) val = qstrlstParams.value(intParamNum - 1).toString(); else { // add this to the list of missing parameters QString s = QString("%%1").arg(intParamNum); if(!missingParamList.contains(s)) missingParamList.append(s); } } else { // ?!?!? How did we get here. qDebug("Match did not start with $ or %%..."); } QString qstrWork = qstrParsedSQL.left(intStartIndex) + val + qstrParsedSQL.right(qstrParsedSQL.length() - intStartIndex - re.matchedLength()); intStartIndex += val.length(); qstrParsedSQL = qstrWork; } qstrQuery = qstrParsedSQL; if(doexec) execute(); } else { qstrQuery = qstrParsedSQL; MetaSQLQuery mql(qstrParsedSQL); qryQuery = new XSqlQuery(mql.toQuery(qstrlstParams, _database, doexec)); if (doexec) qryQuery->first(); // TODO: actually look for missing parameters? } }
real dgdisk(real k, real r, real alpha, real eps) { return (rexp(- k*eps) * j1(k*r) * k / rsqrt(rqbe(alpha*alpha + k*k))); }
/*! * \en Sets widget visual type, depend of property fieldType. * This property must be set above call this function. \_en * \ru Устанавливает визуальный тип виджета в зависимости от свойства * `fieldType'. Это свойсто должно быть установлено до вызова этой функции, * иначе тип виджета будет установлен в Unknown. \_ru */ void wField::widgetInit() { QString str; char s1[20]; int n1=0, n2=0; lineEdit->hide(); disconnect( lineEdit, SIGNAL( textChanged( const QString & ) ), this, SLOT( setValue( const QString & ) ) ); disconnect( lineEdit, SIGNAL( lostFocus() ), this, SLOT( focusOutEvent()) ); // lineEdit->disconnect(); lineEdit->setReadOnly(false); layout()->remove(lineEdit); dateEdit->hide();// = new QDateEdit(this); disconnect(dateEdit, SIGNAL( valueChanged ( const QDate&) ), this, SLOT( setValue( const QDate & ) ) ); disconnect(dateEdit, SIGNAL( lostFocus() ), this, SLOT( focusOutEvent() ) ); layout()->remove(dateEdit); objLabel->hide();// = new QLabel(this); objLabel->disconnect(); layout()->remove(objLabel); objButton->hide();// = new wCatButton("...",this); disconnect( objButton, SIGNAL( clicked() ), this, SLOT( fieldSelect() ) ); // objButton->disconnect(); layout()->remove(objButton); checkBox->hide(); disconnect( checkBox, SIGNAL( valueChanged ( const QString & ) ), this, SLOT( setValue( const QString & ) ) ); disconnect( checkBox, SIGNAL( toggled (bool) ), checkBox, SLOT( on_toggled() ) ); // checkBox->disconnect(); layout()->remove(checkBox); //TODO: need rewrite if (!vFieldType.isEmpty()) sscanf((const char *)vFieldType,"%s %i %i", s1, &n1, &n2); qDebug() << "vEditorType " << vEditorType; switch (vEditorType) { case Numberic: lineEdit->setText(vValue); if(vFieldType.isEmpty()) { // set validator for numeric type QString str = tr("^\\-{0,1}\\d{0,%1}\\.{1}\\d{0,%2}$").arg(3).arg(3); QRegExp rexp( str ); lineEdit->setValidator(new QRegExpValidator(rexp,lineEdit)); } else { if(n2==0) { // set default validator for integer type QString str = tr("^\\-{0,1}\\d{0,%1}$").arg(n1); QRegExp rexp( str ); lineEdit->setValidator(new QRegExpValidator(rexp,lineEdit)); } else { // set default validator for float type QString str = tr("^\\-{0,1}\\d{0,%1}\\.{1}\\d{0,%2}$").arg(n1).arg(n2); QRegExp rexp( str ); lineEdit->setValidator(new QRegExpValidator(rexp,lineEdit)); } } connect( lineEdit, SIGNAL( textChanged( const QString & ) ), this, SLOT( setValue( const QString & ) ) ); connect( lineEdit, SIGNAL( lostFocus() ), this, SLOT( focusOutEvent()) ); setFocusProxy(lineEdit); layout()->add( lineEdit ); lineEdit->show(); break; case String: if(vFieldType.isEmpty()) { // set default validator for string lineEdit->setMaxLength(20); } else { // set validator for string lineEdit->setMaxLength(n1); } connect( lineEdit, SIGNAL( textChanged( const QString & ) ), this, SLOT( setValue( const QString & ) ) ); connect( lineEdit, SIGNAL( lostFocus() ), this, SLOT( focusOutEvent()) ); setFocusProxy(lineEdit); layout()->add( lineEdit ); lineEdit->show(); break; case Date: case DateTime: // used object wDateTime, inherits QDateTime //dateEdit->setSeparator("."); //dateEdit->setOrder( Q3DateEdit::DMY ); dateEdit->setDisplayFormat("dd.MM.YYYY"); connect(dateEdit, SIGNAL( valueChanged ( const QDate&) ), this, SLOT( setValue( const QDate & ) ) ); connect(dateEdit, SIGNAL( lostFocus() ), this, SLOT( focusOutEvent() ) ); setFocusProxy( dateEdit ); layout()->add( dateEdit ); dateEdit->show(); break; case Catalogue: md_oid = n1; objLabel->setFrameShape( QFrame::Box ); objLabel->setLineWidth( 1 ); objLabel->setFocusPolicy(Qt::NoFocus); objButton->setMaximumWidth(25); objButton->setFocusPolicy(Qt::StrongFocus); connect( objButton, SIGNAL( clicked() ), this, SLOT( fieldSelect() ) ); setFocusProxy(objButton); layout()->add( objLabel ); layout()->add( objButton ); objLabel->show(); objButton->show(); break; case Document: //>>>>>>> 1.49.2.4 // Field type = Document md_oid = n1; objLabel->setFrameStyle( QFrame::Panel | QFrame::Sunken ); objLabel->setLineWidth( 1 ); objLabel->setFocusPolicy(Qt::NoFocus); objButton->setMaximumWidth(25); objButton->setFocusPolicy(Qt::StrongFocus); connect( objButton, SIGNAL( clicked() ), this, SLOT( fieldSelect() ) ); setFocusProxy(objButton); layout()->add( objLabel ); layout()->add( objButton ); objLabel->show(); objButton->show(); break; case Boolean: // connect( checkBox, SIGNAL( lostFocus() ), this, SLOT( focusOutEvent()) ); connect( checkBox, SIGNAL( valueChanged ( const QString & ) ), this, SLOT( setValue( const QString & ) ) ); connect( checkBox, SIGNAL( toggled (bool) ), checkBox, SLOT( on_toggled() ) ); setFocusProxy(checkBox); layout()->add(checkBox); checkBox->show(); break; default: objLabel->setText("UnknownField"); objLabel->setFrameShape(QFrame::Box); setFocusPolicy(Qt::NoFocus); layout()->add( objLabel ); objLabel->show(); break; } setValue(vValue); }
/** Adds a file to the tree widget * * \param fi A QFileInfo object pointing the file to add * */ void RainbruRPG::Gui::QuarantineList::addFile(QFileInfo fi){ LOGI("Addfile called"); QBrush red(QColor(250,0,0)); QBrush orange(QColor(0, 0, 240)); QBrush green(QColor(0,250,0)); bool fileInTransfer; if (fi.isFile()){ // Is this file is in storedFile list QRegExp rexp(fi.fileName()); if (storedFiles.indexOf(rexp)==-1){ LOGI("The file is NOT being stored"); LOGCATS("filename="); LOGCATS(fi.fileName().toLatin1()); LOGCAT(); LOGCATS("storedFiles="); LOGCATS(storedFiles.join(";").toLatin1()); LOGCAT(); fileInTransfer=false; } else{ LOGI("The file is being stored"); fileInTransfer=true; labStillInTransfer->setVisible(true); } // adding it to the list QTreeWidgetItem *it= new QTreeWidgetItem(tree); it->setText(0,fi.fileName() ); it->setText(1,fileSizeToString(fi.size()) ); // Get the mime-type FileTypeGuesser ftg; std::string stdFn(fi.absoluteFilePath().toLatin1()); std::string strMime=ftg.getMimeType(stdFn); it->setText(2,strMime.c_str() ); tQuarantineFileStatus status=ftg.getFileStatus(stdFn); std::string strStatus; switch(status){ case QFS_ACCEPTED: strStatus="Accepted"; it->setForeground ( 0, green); it->setForeground ( 1, green); it->setForeground ( 2, green); it->setForeground ( 3, green); break; case QFS_REFUSED: strStatus="Refused"; it->setForeground ( 0, red); it->setForeground ( 1, red); it->setForeground ( 2, red); it->setForeground ( 3, red); break; case QFS_UNKNOWN: strStatus="Unknown"; it->setForeground ( 0, orange); it->setForeground ( 1, orange); it->setForeground ( 2, orange); it->setForeground ( 3, orange); break; case QFS_WRONGEXT: strStatus="Wrong extension"; it->setForeground ( 0, orange); it->setForeground ( 1, orange); it->setForeground ( 2, orange); it->setForeground ( 3, orange); break; case QFS_TESTEDEXT: strStatus="Tested but unlisted extension"; break; default: strStatus="ERROR"; it->setForeground ( 0, red); it->setForeground ( 1, red); it->setForeground ( 2, red); it->setForeground ( 3, red); } it->setText(3,strStatus.c_str() ); // if (fileInTransfer){ // it->setText(3,"Still in transfer..."); // } tree->addTopLevelItem( it ); } }
double rtnorm(double mu, double sd, double lower, double upper) { double z,pz,u,slower,supper,tr,alpha; int sample=1; if(lower>=upper){ return((lower+upper)/2); } if(lower < -1e+32 || upper > 1e+32){ if(lower < -1e+32 && upper > 1e+32){ z = rnorm(mu, sd); return(z); }else{ if(upper > 1e+32){ tr = (lower-mu)/sd; }else{ tr = (mu-upper)/sd; } if(tr<0){ // if sampling >0.5 of a normal density possibly quicker just to sample and reject while(sample==1){ z = rnorm(0.0,1.0); if(z>tr){ sample = 0; } } }else{ alpha = (tr+sqrt((tr*tr)+4.0))/2.0; while(sample==1){ z = rexp(1.0/alpha)+tr; pz = -((alpha-z)*(alpha-z)/2.0); u = -rexp(1.0); if(u<=pz){ sample = 0; } } } } }else{ slower = (lower-mu)/sd; supper = (upper-mu)/sd; tr = pnorm(supper, 0.0,1.0, TRUE, FALSE)-pnorm(slower, 0.0,1.0, TRUE, FALSE); if(tr>0.5){ // if sampling >0.5 of a normal density possibly quicker just to sample and reject while(sample==1){ z = rnorm(0.0,1.0); if(z>slower && z<supper){ sample = 0; } } }else{ while(sample==1){ z = runif(slower,supper); if(slower<=0.0 && 0.0<=supper){ pz = -z*z/2.0; }else{ if(supper<0.0){ pz = (supper*supper-z*z)/2.0; }else{ pz = (slower*slower-z*z)/2.0; } } u = -rexp(1.0); if(u<pz){ sample=0; } } } } if(lower < -1e+32){ return(mu-z*sd); }else{ return(z*sd+mu); } }
/* Susceptible-Infectious-Removed MCMC analysis: . Exponentially distributed infectiousness periods */ SEXP expMH_SIR(SEXP N, SEXP removalTimes, SEXP otherParameters, SEXP priorValues, SEXP initialValues, SEXP bayesReps, SEXP bayesStart, SEXP bayesThin, SEXP bayesOut){ /* Declarations */ int ii, jj, kk, ll, nInfected, nRemoved, nProtected=0, initialInfected; SEXP infRateSIR, remRateSIR, logLikelihood;/*, timeInfected, timeDim, initialInf ; */ SEXP parameters, infectionTimes, candidateTimes, infectedBeforeDay; SEXP allTimes, indicator, SS, II; double infRate, remRate, oldLkhood, newLkhood, minimumLikelyInfectionTime; /* starting values */ double infRatePrior[2], remRatePrior[2], thetaprior; /* priors values */ double sumSI, sumDurationInfectious, likelihood,logR; int acceptRate=0, consistent=0, verbose, missingInfectionTimes; SEXP retParameters, parNames, acceptanceRate; SEXP infTimes; /* Code */ GetRNGstate(); /* should be before a call to a random number generator */ initialInfected = INTEGER(getListElement(otherParameters, "initialInfected"))[0]; verbose = INTEGER(getListElement(otherParameters, "verbose"))[0]; missingInfectionTimes = INTEGER(getListElement(otherParameters, "missingInfectionTimes"))[0]; PROTECT(N = AS_INTEGER(N)); ++nProtected; PROTECT(removalTimes = AS_NUMERIC(removalTimes)); ++nProtected; /* priors and starting values */ PROTECT(priorValues = AS_LIST(priorValues)); ++nProtected; PROTECT(initialValues = AS_LIST(initialValues)); ++nProtected; nRemoved = LENGTH(removalTimes); /* number of individuals removed */ /* bayes replications, thin, etc */ PROTECT(bayesReps = AS_INTEGER(bayesReps)); ++nProtected; PROTECT(bayesStart = AS_INTEGER(bayesStart)); ++nProtected; PROTECT(bayesThin = AS_INTEGER(bayesThin)); ++nProtected; PROTECT(bayesOut = AS_INTEGER(bayesOut)); ++nProtected; PROTECT(infRateSIR = allocVector(REALSXP, INTEGER(bayesOut)[0])); ++nProtected; PROTECT(remRateSIR = allocVector(REALSXP, INTEGER(bayesOut)[0])); ++nProtected; PROTECT(logLikelihood = allocVector(REALSXP, INTEGER(bayesOut)[0])); ++nProtected; /* PROTECT(timeInfected = allocVector(REALSXP, nRemoved * INTEGER(bayesOut)[0])); ++nProtected; PROTECT(timeDim = allocVector(INTSXP, 2)); ++nProtected; INTEGER(timeDim)[0] = nRemoved; INTEGER(timeDim)[1] = INTEGER(bayesOut)[0]; setAttrib(timeInfected, R_DimSymbol, timeDim); PROTECT(initialInf = allocVector(REALSXP, INTEGER(bayesOut)[0])); ++nProtected; */ PROTECT(parameters = allocVector(REALSXP,2)); ++nProtected; PROTECT(infectionTimes = allocVector(REALSXP,nRemoved)); ++nProtected; PROTECT(candidateTimes = allocVector(REALSXP,nRemoved)); ++nProtected; PROTECT(infectedBeforeDay = allocVector(REALSXP,nRemoved)); ++nProtected; PROTECT(infTimes = allocVector(REALSXP,nRemoved)); ++nProtected; for(jj = 0; jj < nRemoved; ++jj){ REAL(infectionTimes)[jj] = REAL(getListElement(initialValues, "infectionTimes"))[jj]; REAL(candidateTimes)[jj] = REAL(infectionTimes)[jj]; REAL(infectedBeforeDay)[jj] = REAL(getListElement(otherParameters, "infectedBeforeDay"))[jj]; REAL(infTimes)[jj] = 0; } nInfected = LENGTH(infectionTimes); PROTECT(allTimes = allocVector(REALSXP,nRemoved+nInfected)); ++nProtected; PROTECT(indicator = allocVector(INTSXP,nRemoved+nInfected)); ++nProtected; PROTECT(SS = allocVector(INTSXP,nRemoved+nInfected+1)); ++nProtected; PROTECT(II = allocVector(INTSXP,nRemoved+nInfected+1)); ++nProtected; /* working variables */ infRate = REAL(getListElement(initialValues, "infectionRate"))[0]; remRate = REAL(getListElement(initialValues, "removalRate"))[0]; minimumLikelyInfectionTime = REAL(getListElement(otherParameters, "minimumLikelyInfectionTime"))[0]; for(ii = 0; ii < 2; ++ii){ infRatePrior[ii] = REAL(getListElement(priorValues, "infectionRate"))[ii]; remRatePrior[ii] = REAL(getListElement(priorValues, "removalRate"))[ii]; } thetaprior = REAL(getListElement(priorValues, "theta"))[0]; REAL(parameters)[0] = infRate; REAL(parameters)[1] = remRate; expLikelihood_SIR(REAL(parameters),REAL(infectionTimes), REAL(removalTimes), &INTEGER(N)[0], &nInfected, &nRemoved, &sumSI, &sumDurationInfectious, &likelihood, REAL(allTimes),INTEGER(indicator),INTEGER(SS),INTEGER(II)); oldLkhood = likelihood; for(ii = 1; ii <= INTEGER(bayesReps)[0]; ++ii){ infRate = rgamma(nInfected-1+infRatePrior[0],1/(sumSI+infRatePrior[1])); /* update infRate */ remRate = rgamma(nRemoved+remRatePrior[0],1/(sumDurationInfectious+remRatePrior[1]));/*remRate */ /*Rprintf("SI = %f : I = %f\n",sumSI,sumDurationInfectious);*/ REAL(parameters)[0] = infRate; REAL(parameters)[1] = remRate; if(missingInfectionTimes){ expLikelihood_SIR(REAL(parameters),REAL(infectionTimes), REAL(removalTimes), &INTEGER(N)[0], &nInfected, &nRemoved, &sumSI, &sumDurationInfectious, &likelihood, REAL(allTimes),INTEGER(indicator),INTEGER(SS),INTEGER(II)); oldLkhood = likelihood; kk = ceil(unif_rand()*(nRemoved-1)); /* initial infection time excluded */ consistent=0; if(kk == nRemoved-1){ REAL(candidateTimes)[kk] = runif(REAL(infectionTimes)[kk-1], REAL(infectedBeforeDay)[kk]);} else if((REAL(infectionTimes)[kk+1] > REAL(infectedBeforeDay)[kk])){ REAL(candidateTimes)[kk] = runif(REAL(infectionTimes)[kk-1], REAL(infectedBeforeDay)[kk]);} else{REAL(candidateTimes)[kk] = runif(REAL(infectionTimes)[kk-1], REAL(infectionTimes)[kk+1]);} expLikelihood_SIR(REAL(parameters),REAL(candidateTimes), REAL(removalTimes), &INTEGER(N)[0], &nInfected, &nRemoved, &sumSI, &sumDurationInfectious, &likelihood, REAL(allTimes),INTEGER(indicator),INTEGER(SS),INTEGER(II)); newLkhood = likelihood; logR = (newLkhood-oldLkhood); if(log(unif_rand()) <= logR){ REAL(infectionTimes)[kk] = REAL(candidateTimes)[kk]; ++acceptRate; } REAL(candidateTimes)[kk] = REAL(infectionTimes)[kk];/* update candidate times */ REAL(infectionTimes)[0] = REAL(infectionTimes)[1] -rexp(1/(infRate*INTEGER(N)[0]+remRate+thetaprior)); REAL(candidateTimes)[0] = REAL(infectionTimes)[0]; } expLikelihood_SIR(REAL(parameters),REAL(infectionTimes), REAL(removalTimes), &INTEGER(N)[0], &nInfected, &nRemoved, &sumSI, &sumDurationInfectious, &likelihood, REAL(allTimes),INTEGER(indicator),INTEGER(SS),INTEGER(II)); oldLkhood = likelihood; kk = ceil(INTEGER(bayesReps)[0]/100); ll = ceil(INTEGER(bayesReps)[0]/ 10); if(verbose == 1){ if((ii % kk) == 0){Rprintf(".");} if((ii % ll) == 0){Rprintf(" %d\n",ii);} } if((ii >= (INTEGER(bayesStart)[0])) && ((ii-INTEGER(bayesStart)[0]) % INTEGER(bayesThin)[0] == 0)){ ll = (ii - (INTEGER(bayesStart)[0]))/INTEGER(bayesThin)[0]; /* REAL(initialInf)[ll] = REAL(infectionTimes)[0]; */ REAL(logLikelihood)[ll] = likelihood; REAL(infRateSIR)[ll] = infRate; REAL(remRateSIR)[ll] = remRate; for(jj = 0; jj < nRemoved; ++jj){ REAL(infTimes)[jj] += REAL(infectionTimes)[jj]; } /* for(jj = 0; jj < nRemoved; ++jj){ REAL(timeInfected)[(nRemoved*ll+jj)] = REAL(infectionTimes)[jj]; } */ } } PutRNGstate(); /* after using random number generators. */ /* Print infection times and removal times at last iteration */ for(jj = 0; jj < nRemoved; ++jj){ REAL(infTimes)[jj] = REAL(infTimes)[jj]/INTEGER(bayesOut)[0]; } if(verbose){ for(jj = 0; jj < nRemoved; ++jj){ Rprintf("%2d %8.4f %2.0f\n",jj, REAL(infTimes)[jj],REAL(removalTimes)[jj]); } } PROTECT(retParameters = NEW_LIST(5)); ++nProtected; PROTECT(acceptanceRate = allocVector(INTSXP,1)); ++nProtected; INTEGER(acceptanceRate)[0] = acceptRate; PROTECT(parNames = allocVector(STRSXP,5)); ++nProtected; SET_STRING_ELT(parNames, 0, mkChar("logLikelihood")); SET_STRING_ELT(parNames, 1, mkChar("infRateSIR")); SET_STRING_ELT(parNames, 2, mkChar("remRateSIR")); SET_STRING_ELT(parNames, 3, mkChar("infectionTimes")); SET_STRING_ELT(parNames, 4, mkChar("acceptanceRate")); setAttrib(retParameters, R_NamesSymbol,parNames); SET_ELEMENT(retParameters, 0, logLikelihood); SET_ELEMENT(retParameters, 1, infRateSIR); SET_ELEMENT(retParameters, 2, remRateSIR); SET_ELEMENT(retParameters, 3, infTimes); SET_ELEMENT(retParameters, 4, acceptanceRate); /* SET_ELEMENT(retParameters, 3, initialInf); SET_ELEMENT(retParameters, 4, timeInfected); */ UNPROTECT(nProtected); return(retParameters); }
unsigned int run(mytime length){ RNGScope scope; if(mean_stay<=0) throw runtime_error("mean_stay not a positive value."); double drate = 1/mean_stay; double arate = drate*balance*current.maxSize(); mytime now=end; end += length; while(now<end){ possibleStep step=snone; mytime t=0, next=time_unknown; if(lambda>0 && current.nSusceptible()!=0 && current.nInfected()!=0){ next=t=rexp(1, lambda * current.nSusceptible() * current.nInfected() )[0]; step=sinfect; } if(!current.full()){ t=rexp(1, arate)[0]; if(t<next){ next=t; step=sadmit; } } if(!current.empty()){ t=rexp(1,drate*current.size())[0]; if(t<next){ next=t; step=sdischarge; } } if(!current.empty() && test_rate>0){ t=rexp(1,test_perpd ? (test_rate * current.size()) : test_rate)[0]; if(t<next){ next=t; step=stest; } } now+=next; switch(step){ case sadmit: { pp pat = new patient(now); if(runif(1,0,1)[0]<importation) pat->infect(now); current.add(pat); all.push_back(pat); } break; case sdischarge: current.dischargeRandom(now); break; case sinfect: current.infectRandom(now); break; case stest: current.testSomeone(now, false_negative_rate, false_positive_rate); break; default: break; } } end = now; return all.size(); }
int main() { SPList<int> il, il1, il2, il3; SPStringList x, y, z; int n; if(x) cout << "x is not empty" << endl; else cout << "x is empty" << endl; if(x.isempty()) cout << "x.isempty() is true" << endl; else cout << "x.isempty() is false" << endl; n= x.split("a b c d e f"); if(x) cout << "x is not empty" << endl; else cout << "x is empty" << endl; if(x.isempty()) cout << "x.isempty() is true" << endl; else cout << "x.isempty() is false" << endl; cout << "x.split(a b c d e f)= " << n << ": " << x << endl; cout << "x[0] = " << x[0] << endl; z= x; z[0]= "x"; cout << "z= x; z[0]=\"x\" " << "z: " << z << endl; SPString ss("1.2.3.4.5.6.7.8.9.0"); y= ss.split("\\."); cout << "ss= " << ss << ", y= ss.split(\"\\.\"), y=" << endl << y << endl; cout << "y.join(\" \")" << y.join(" ") << endl; { SPString xx= "a b c\nd e\tf g"; cout << xx << endl << "xx.split()= " << xx.split() << endl; xx= "a b c d e f g"; cout << xx << endl << "xx.split(\",\")= " << xx.split(",") << endl; xx= " a b c d e f g hi "; cout << xx << endl << "xx.split(\"\")= " << xx.split("") << endl; xx= "a,b,c,d,,e,f,g,,,,"; cout << xx << endl << "xx.split(\",\")= " << xx.split(",") << endl; xx= "a,b,c,d,,e,f,g,,"; cout << xx << endl << "xx.split(\",\", 5)= " << xx.split(",", 5) << endl; xx= " a b c d e f g "; cout << xx << endl << "xx.split(\" \")= " << xx.split(" ") << endl; xx= "a b c d,e,f g"; cout << xx << endl << "xx.split(\"([ ,])+\")= " << xx.split("([ ,])+") << endl; xx= ",,,,"; cout << xx << endl << "xx.split(\",\")= " << xx.split(",") << endl; xx= ""; cout << xx << endl << "xx.split(\",\")= " << xx.split(",") << endl; xx= " a b c\td e\nf g "; cout << xx << endl << "xx.split(\"' '\")= " << xx.split("' '") << endl; } cout << "x = " << x << endl; cout << "x.pop() : " << x.pop() << ", " ; cout << x.pop() << endl << "x= " << x << endl;; cout << "x.shift() : " << x.shift() << ", "; cout << x.shift() << endl<< "x= " << x << endl; x.unshift(y); cout << "x.unshift(y): " << x << endl; if(il) cout << "il is not empty" << endl; else cout << "il is empty" << endl; il.push(1); il.push(2); il.push(3); il.push(4); if(il) cout << "il is not empty" << endl; else cout << "il is empty" << endl; cout << "il(1, 2, 3, 4) : " << il << endl; il3= il; il3[0]= 9999; cout << "il3= il; il3[0]= 9999; il3 = " << il3 << endl << "il= " << il << endl; il1= il.reverse(); cout << "il.reverse: " << il1 << endl; cout << "il1.sort(): " << il1.sort() << endl; y.reset(); y.push("one"); y.push("two"); y.push("three"); y.push("four"); cout << "y = " << endl << y; cout << "y.reverse() " << y.reverse() << endl; cout << "y.sort() " << y.sort() << endl; cout << "y.sort().reverse() " << y.sort().reverse() << endl; il2.push(3); il2.push(4); cout << "il2.push(3, 4) : " << il2 << endl; il.push(il2); cout << "il.push(il2) : " << il << endl; cout << "il.pop() : " << il.pop() << ", "; cout << il.pop() << endl; il.unshift(il2); cout << "il.unshift(il2) : " << il << endl; cout << "il.shift() : " << il.shift() << ", "; cout << il.shift() << endl; il.reset(); il.push(1); il.push(2); if(il.shift() != 1) cout << "FIFO1 error" << endl; if(il.shift() != 2) cout << "FIFO2 error" << endl; int i; for(i=0;i<100;i++) il.push(i); i= 0; while(il){ if(il.shift() != i) cout << "FIFO3 error" << endl; i++; } if(i != 100) cout << "FIFO over/under run" << endl; cout << "testing splice:" << endl; x.reset(); x.split("a b c d e f g h i"); cout << "x = " << x << endl; z= x.splice(2, 3); cout << "z= x.splice(2, 3): z= " << z << endl << "x = " << x << endl; cout << "x.splice(2, 0, z): " << x.splice(2, 0, z); cout << "x= " << x << endl; cout << "z.splice(1, 1, x): " << z.splice(1, 1, x); cout << "z= " << z << endl; cout << "x= " << x << endl; cout << "z.splice(20, 1, x): " << z.splice(20, 1, x); cout << "z= " << z << endl; // test auto expand SPList<int> ile; ile[3]= 3; cout << ile.scalar() << ", " << ile[3] << endl; ile[100]= 1234; ile[0]= 5678; cout << ile.scalar() << ", " << ile[0] << ", " << ile[100] << endl; SPList<int> ile2; for(i=0;i<=100;i++) ile2[i]= i; for(i=200;i>100;i--) ile2[i]= i; for(i=0;i<=200;i++) if(ile2[i] != i) cout << "error at index " << i << endl; cout << "Index check done" << endl; cout << ile2.scalar() << ", " << ile2[0] << ", " << ile2[200] << endl; // test Regexp stuff cout << endl << "testing regexp stuff:" << endl; x.reset(); cout << "x.m(\".*X((...)...(...))\", \"12345Xabcxyzdef\") returns " << x.m(".*X((...)...(...))", "12345Xabcxyzdef") << endl; cout << "subs matched = " << x << endl; Regexp rexp("abc"); SPString rst("12345Xabcxyzdef"); cout << "rst.m(rexp) returns " << rst.m(rexp) << endl; cout << endl << "testing grep:" << endl; x.reset(); x.push("abcd"); x.push("a2345"); x.push("X2345"); x.push("Xaaaaa"); x.push("aaaaa"); y= x.grep("^a.*"); cout << "x: " << endl << x << endl << "grep(^a.*)" << endl; cout << "Expect 3 matches:" << endl << y << endl; { SPString s1("abcdef"); cout << "s1= " << s1 << ", s1.m(\"^cde\") : " << s1.m("^cde") << endl; cout << "s1= " << s1 << ", s1.m(\"^..cde\") : " << s1.m("^..cde") << endl; } { SPStringList sl; SPString str= "ab cd ef"; sl = m("(..) (..)", str); cout << "sl = m(\"(..) (..)\", \"ab cd ef\"); sl = " << endl << sl << endl; } { Regexp ncr("abc", Regexp::nocase); Regexp cr("abc"); SPString s= "ABC"; cout << "s= " << s << ": s.m(ncr)= " << s.m(ncr) << endl; cout << "s= " << s << ": s.m(cr)= " << s.m(cr) << endl; cout << "s.m(\"abc\", \"i\")= " << s.m("abc", "i") << endl; cout << "s.m(\"abc\")= " << s.m("abc") << endl; } // Test strings cout << "test string stuff:" << endl; SPString s1("string1"), s2, s3; const char *s= s1; cout << "Empty string: " << s2 << " length= " << s2.length() << ", strlen(s2) = " << strlen(s2) << endl; cout << "s1:" << s1 << endl; cout << "s[0]= " << s[0] << ", s[5]= " << s[5] << endl; // s[2]= 'X'; // cout << "s[2]= 'X', s= " << s << endl; // s[2]= 'r'; cout << "const char *s= s1: s= " << s << endl; s2= s1; cout << "s2=s1, s2:" << s2 << endl; s1.chop(); cout << "s1.chop()" << s1 << endl; s3= s; cout << "s3= s: s3 = " << s3 << endl; cout << "index(\"ri\") in " << s1 << ": " << s1.index("ri") << endl; s3= "1"; cout << "index(" << s3 << ") in " << s1 << ": " << s1.index(s3) << endl; s3= "abcabcabc"; cout << "rindex(abc) in" << s3 << ": " << s3.rindex("abc") << endl; cout << "rindex(abc, 5) in" << s3 << ": " << s3.rindex("abc", 5) << endl; // test substrings cout << "substr(5, 3) in " << s3 << ": " << s3.substr(5, 3) << endl; s3.substr(5, 3)= "XXX"; cout << "s3.substr(5, 3) = \"XXX\"" << s3 << endl; s3.substr(5, 3)= s1; cout << "s3.substr(5, 3) = s1" << s3 << endl; s3.substr(5, 3)= s1.substr(1, 3); cout << "s3.substr(5, 3) = s1.substr(1, 3)" << s3 << endl; s3.substr(0, 6)= s1.substr(0, 3); cout << "s3.substr(0, 6) = s1.substr(0, 3)" << s3 << endl; s3.substr(-3, 2)= s1.substr(0, 2); cout << "s3.substr(-3, 2) = s1.substr(0, 2)" << s3 << endl; // test overlapping substrings s1= "1234567890"; cout << "s1 = " << s1 << endl; s1.substr(0, 10)= s1.substr(1, 9); cout << "s1.substr(0, 10)= s1.substr(1, 9) " << s1 << endl; s1= "1234567890"; cout << "s1 = " << s1 << endl; s1.substr(1, 9)= s1.substr(0, 10); cout << "s1.substr(1, 9)= s1.substr(0, 10) " << s1 << endl; // test over-large substrings s1= "1234567890"; s1.substr(7, 10)= "abcdefghij"; cout << "s1.substr(7, 10)= \"abcdefghij\" " << s1 << endl; s1= "1234567890"; s1.substr(10, 5)= "abcdefghij"; cout << "s1.substr(10, 5)= \"abcdefghij\" " << s1 << endl; s1= "1234567890"; s1.substr(20, 1)= "abcdefghij"; cout << "s1.substr(20, 1)= \"abcdefghij\" " << s1 << endl; s1= "abcdef"; s2= "123456"; cout << s1 << " + " << s2 << ": " << s1 + s2 << endl; cout << s1 << " + " << "\"hello\"= " << s1 + "hello" << endl; cout << "\"hello\"" << " + " << s1 << "= " << "hello" + s1 << endl; cout << s1 << " + \'x\' = " << s1 + 'x' << endl; s1= "abc"; s2= "def"; s3= "abc"; cout << s1 << " == " << s2 << ": " << (s1 == s2) << endl; cout << s1 << " != " << s2 << ": " << (s1 != s2) << endl; cout << s1 << " == " << s3 << ": " << (s1 == s3) << endl; cout << s1 << " != " << s3 << ": " << (s1 != s3) << endl; cout << s1 << " < " << s2 << ": " << (s1 < s2) << endl; cout << s1 << " > " << s2 << ": " << (s1 > s2) << endl; cout << s1 << " <= " << s2 << ": " << (s1 <= s2) << endl; cout << s1 << " >= " << s3 << ": " << (s1 >= s3) << endl; // Test the tr() functions s1= "abcdefghi"; cout << "s1 = " << s1; cout << ", s1.tr(\"ceg\", \"123\") = " << s1.tr("ceg", "123"); cout << ", s1 = " << s1 << endl; s1= "abcdefghi"; cout << "s1.tr(\"a-z\", \"A-Z\") = " << s1.tr("a-z", "A-Z"); cout << ", s1 = " << s1 << endl; s1= "abcdefghi"; cout << "s1.tr(\"efg\", \"\") = " << s1.tr("efg", ""); cout << ", s1 = " << s1 << endl; s1= "abcdefghi"; cout << "s1.tr(\"ac-e\", \"X\") = " << s1.tr("ac-e", "X"); cout << ", s1 = " << s1 << endl; s1= "abcdefghiiii"; cout << "s1 = " << s1; cout << ", s1.tr(\"ac-e\", \"X\", \"s\") = " << s1.tr("ac-e", "X", "s"); cout << ", s1 = " << s1 << endl; s1= "abcdefghi"; cout << "s1.tr(\"ac-e\", \"\", \"d\") = " << s1.tr("ac-e", "", "d"); cout << ", s1 = " << s1 << endl; s1= "abcdefghi"; cout << "s1.tr(\"ac-e\", \"d\", \"d\") = " << s1.tr("ac-e", "d", "d"); cout << ", s1 = " << s1 << endl; s1= "abcdefghi"; cout << "s1.tr(\"ac-e\", \"\", \"cd\") = " << s1.tr("ac-e", "", "cd"); cout << ", s1 = " << s1 << endl; s1= "bookkeeper"; cout << s1; cout << ": s1.tr(\"a-zA-Z\", \"\", \"s\") = " << s1.tr("a-zA-Z", "", "s"); cout << ", s1 = " << s1 << endl; s1= "abc123def456ghi"; cout << s1; cout << ": s1.tr(\"a-zA-Z\", \" \", \"c\") = " << s1.tr("a-zA-Z", " ", "c"); cout << ", s1 = " << s1 << endl; s1= "abc123def456ghi789aaa"; cout << s1; cout << ": s1.tr(\"a-zA-Z\", \" \", \"cs\") = " << s1.tr("a-zA-Z", " ", "cs"); cout << ", s1 = " << s1 << endl; s1= "abcdddaaaxxx"; cout << s1; cout << ": s1.tr(\"a\", \"d\", \"s\") = " << s1.tr("a", "d", "s"); cout << ", s1 = " << s1 << endl; // Test substitute command s1= "abcdefghi"; cout << s1; cout <<" s1.s(\"def\", \"FED\") = " << s1.s("def", "FED"); cout << ", s1= " << s1 << endl; s1= "abcDEFghi"; cout << s1; cout <<" s1.s(\"def\", \"FED\") = " << s1.s("def", "FED"); cout << ", s1= " << s1 << endl; s1= "abcDEFghi"; cout << s1; cout <<" s1.s(\"def\", \"FED\", \"i\") = " << s1.s("def", "FED", "i"); cout << ", s1= " << s1 << endl; s1= "abcdefghi"; cout << s1; cout <<" s1.s(\"(...)(...)\", \"\\$,$&,$2 $1\") = " << s1.s("(...)(...)", "\\$,$&,$2 $1"); cout << ", s1= " << s1 << endl; s1= "abcdefabcghiabc"; cout << s1; cout <<" s1.s(\"abc\", \"XabcX\", \"g\") = " << s1.s("abc", "XabcX", "g"); cout << ", s1= " << s1 << endl; s1= "abcdefabcghiabc"; cout << s1; cout <<" s1.s(\"abc\", \"X\", \"g\") = " << s1.s("abc", "X", "g"); cout << ", s1= " << s1 << endl; s1= "abcdefabcghiabc"; cout << s1; cout <<" s1.s(\"abc(.)\", \"X$1abcX$1\", \"g\") = " << s1.s("abc(.)", "X$1abcX$1", "g"); cout << ", s1= " << s1 << endl; s1= "abcdefabcghiabc"; cout << s1; cout <<" s1.s(\"(.)abc\", \"$1X$1abcX\", \"g\") = " << s1.s("(.)abc", "$1X$1abcX", "g"); cout << ", s1= " << s1 << endl; s1= "1234567890"; cout << s1; cout <<" s1.s(\"(.)(.)\", \"$2$1\", \"g\") = " << s1.s("(.)(.)", "$2$1", "g"); cout << ", s1= " << s1 << endl; return 0; }