void DeformationGraph::GenerateRandomNodes()
{
	std::list<PointWithID> pointcoll;
	// compute the sampledelta.
	const double samplelamada = 0.62; // this is a magic num, should not be modified.
	double surfacearea = dmesh.surfaceArea();
	int sizeOfVertices = dmesh.pMesh->n_vertices();
	double sampledelta = sqrt(surfacearea / (samplelamada * samplescale * sizeOfVertices));
	// sample points on surface.
	GenerateDensePointSet(pointcoll, sampledelta);
	// compute the deleteradius.
	const double pi = acos(-1.0);
	const double deleteradius = sqrt(surfacearea / pi / deletearearate);
	// generate nodes.
	edges.reserve(nodenum);
#ifdef DEBUGTRACE
	meshtalent::DebugTrace dt("./pointleft.log");
#endif
	RandUIntGenerator bigrand; 
	bigrand.srand(time(NULL));
	for (int i = 0; i < nodenum; ++i) {
		// adjust nodenum automatically.
		if (pointcoll.empty()) {
			const_cast<int&>(nodenum) = i;
			break;
		}
#ifdef DEBUGTRACE
		dt.Trace("%d\n", pointcoll.size());
#endif
		// randomly select a point.
		int ranindex = bigrand() % static_cast<long>(pointcoll.size());
		std::list<PointWithID>::iterator it = pointcoll.begin();
		advance(it, ranindex);
		// add to Graph.
		GraphNode tnode(it->p, i);
		switch (it->from) {
		case PointWithID::VERTEX:
			tnode.vertexID = it->id;
			break;
		case PointWithID::EDGE:
			moveFromEdgeToVertex(&tnode, *it);
			break;
		case PointWithID::FACE:
			moveFromFaceToVertex(&tnode, *it);
			break;
		default:
			assert(false);
			break;
		}
		edges.push_back(make_pair(tnode, std::vector<int>()));
		pointcoll.remove_if(WithinCircle(it->p, deleteradius)); // remove nearby points.
	}

#ifndef NDEBUG
	// assert the distance between each two Graph nodes is larger than radius.
	for (int i = 0; i < static_cast<int>(edges.size()); ++i) {
		for (int j = i + 1; j < static_cast<int>(edges.size()); ++j) {
			//assert((edges[i].first.g - edges[j].first.g).mag() >= deleteradius);
		}
	}
#endif
	
}
Example #2
0
bool decode_url(wxString surl, wxString& prefix, wxString &window, PeriodType& period, time_t& time, int& selected_draw, bool xml) {


	wxString url;
	if(xml)
		url = decode_string_xml(surl);
	else
		url = decode_string(surl);
	selected_draw = -1;

	url.Trim(true);
	url.Trim(false);

	/* draw://<prefix>/<window>/<period>/time */
	wxStringTokenizer tok(url, _T("/"));

	if (tok.CountTokens() != 6 && tok.CountTokens() != 7)
		return false;

	tok.GetNextToken();
	tok.GetNextToken();

	prefix = tok.GetNextToken();
	window = tok.GetNextToken();

	wxString pstr = tok.GetNextToken();
	if (pstr == _T("E")) 
		period = PERIOD_T_DECADE;
	else if (pstr == _T("Y")) 
		period = PERIOD_T_YEAR;
	else if (pstr == _T("M"))
		period = PERIOD_T_MONTH;
	else if (pstr == _T("W"))
		period = PERIOD_T_WEEK;
	else if (pstr == _T("S"))
		period = PERIOD_T_SEASON;
	else if (pstr == _T("D"))
		period = PERIOD_T_DAY;
	else if (pstr == _T("10M"))
		period = PERIOD_T_30MINUTE;
	else
		return false;

	long rtime;
	if (tok.GetNextToken().ToLong(&rtime) == false)
		return false;

	wxDateTime dt(rtime);
	if (rtime <= 0 || 
#ifdef __WXMSW__
		 	rtime >= 2147483647
#else
			rtime == std::numeric_limits<time_t>::max()
#endif
			|| dt.GetYear() < 1980 || dt.GetYear() > 2037)
		time = wxDateTime::Now().GetTicks();
	else
		time = rtime;

	if (tok.HasMoreTokens()) {
		long tmpval;
		if (tok.GetNextToken().ToLong(&tmpval) == false)
			return false;
		selected_draw = tmpval;
	}

	return true;
}
Example #3
0
void
Console::writeTimestepInformation()
{
  // Stream to build the time step information
  std::stringstream oss;

  // Write timestep data for transient executioners
  if (_transient)
  {
    // Get the length of the time step string
    std::ostringstream time_step_string;
    time_step_string << timeStep();
    unsigned int n = time_step_string.str().size();
    if (n < 2)
      n = 2;

    // Write time step and time information
    oss << std::endl << "Time Step " << std::setw(n) << timeStep();

    // Set precision
    if (_precision > 0)
      oss << std::setw(_precision) << std::setprecision(_precision) << std::setfill('0')
          << std::showpoint;

    // Show scientific notation
    if (_scientific_time)
      oss << std::scientific;

    // Print the time
    oss << ", time = " << time() << std::endl;

    // Show old time information, if desired
    if (_verbose)
      oss << std::right << std::setw(21) << std::setfill(' ') << "old time = " << std::left
          << timeOld() << '\n';

    // Show the time delta information
    oss << std::right << std::setw(21) << std::setfill(' ') << "dt = " << std::left << dt() << '\n';

    // Show the old time delta information, if desired
    if (_verbose)
      oss << std::right << std::setw(21) << std::setfill(' ') << "old dt = " << _dt_old << '\n';
  }

  // Output to the screen
  _console << oss.str();
}
Example #4
0
 /**
  * get next time (t + dt).
  * @return next time Real
  */
 inline Real next_time() const
 {
     return t() + dt();
 }
Example #5
0
void SMTPChannel::log(const Message& msg)
{
	try
	{
		MailMessage message;
		message.setSender(_sender);
		message.addRecipient(MailRecipient(MailRecipient::PRIMARY_RECIPIENT, _recipient));
		message.setSubject("Log Message from " + _sender);
		std::stringstream content;
		content << "Log Message\r\n"
			<< "===========\r\n\r\n"
			<< "Host: " << Environment::nodeName() << "\r\n"
			<< "Logger: " << msg.getSource() << "\r\n";

		if (_local)
		{
			DateTime dt(msg.getTime());
			content	<< "Timestamp: " << DateTimeFormatter::format(LocalDateTime(dt), DateTimeFormat::RFC822_FORMAT) << "\r\n";
		}
		else
			content	<< "Timestamp: " << DateTimeFormatter::format(msg.getTime(), DateTimeFormat::RFC822_FORMAT) << "\r\n";

		content	<< "Priority: " << NumberFormatter::format(msg.getPriority()) << "\r\n"
			<< "Process ID: " << NumberFormatter::format(msg.getPid()) << "\r\n"
			<< "Thread: " << msg.getThread() << " (ID: " << msg.getTid() << ")\r\n"
			<< "Message text: " << msg.getText() << "\r\n\r\n";

		message.addContent(new StringPartSource(content.str()));
	
		if (!_attachment.empty())
		{
			{
				Poco::FileInputStream fis(_attachment, std::ios::in | std::ios::binary | std::ios::ate);
				if (fis.good())
				{
					typedef std::allocator<std::string::value_type>::size_type SST;

					std::streamoff size = fis.tellg();
					poco_assert (std::numeric_limits<unsigned int>::max() >= size);
					poco_assert (std::numeric_limits<SST>::max() >= size);
					char* pMem = new char [static_cast<unsigned int>(size)];
					fis.seekg(std::ios::beg);
					fis.read(pMem, size);
					message.addAttachment(_attachment,
						new StringPartSource(std::string(pMem, static_cast<SST>(size)), 
							_type,
							_attachment));

					delete [] pMem;
				}
			}
			if (_delete) File(_attachment).remove();
		}

		SMTPClientSession session(_mailHost);
		session.login();
		session.sendMessage(message);
		session.close();
	} 
	catch (Exception&) 
	{ 
		if (_throw) throw; 
	}
}
main(int argc, char *argv[]) {

  FILE *totalwordcountinptr;
  FILE *dateinptr;
  FILE *currentshinglefileinptr;
  FILE *shinglefileinptr;
  FILE *wordcountfileinptr;
  FILE *dateestfileoutptr;
  FILE *testoutputptr;
  FILE *randomnumfileinptr;


  char shinglefile[30];
  char totalwordcount[30];
  char randomnumfile[30];
  char aawmaster[30];
  char dateest[30];

  char *basedirectory="/u/gelila/computation/dictionary/dateshingprobdir/";
  char *wordcountfile="count";
  char *shingled=".shingled";
  char *basename="aaw";
  char *at="@";
  char currentfilename[200];
  char *currentstring;
  char tempcurrentstring[100];

  /*char currentstring[10];*/
  char dummystring1[20];
  char dummystring2[20];
  char dummystring3[20];

  char shingle[300];
  char *shinglearray[500000];

  int i, j, l,k, t, count,wordcount, ti,freq, date, remainder, lengthshingarray,location, optdate, randomnum;

  int randomnumvec[1500000];
  int traindate[3000];
  int bootvector[3000];
  int Occvector[3000];
  int Occvectortotal[3000];
  int ns[3000];
  int Nt[3000];
  int indicator[3000];

  int sizeoftrain=2608;
  int /* mindatedata=1050;*/ mindatedata=1089;
  int /* maxdatedata=1500; */ maxdatedata=1466;
  int mindate=1089;
  int maxdate=1466;
  int RESIDUEval=8;
  int RESIDUEtest=9;
  int bootstrapsample=500;

  float h, sum, Num[400], Den[400], probs[400], probdoc[400], kernelvalue[378];
  float bottomline;
 
  strcpy(shinglefile, argv[1]); /* mergershing3onlysortuniq */
  strcpy(randomnumfile, argv[2]); /* randomnumberfile */
  strcpy(totalwordcount, argv[3]); /*  totaldocboot */
  strcpy(aawmaster, argv[4]); /* aawmaster */
  h=atoi(argv[5]); /* bandwidth value h */
  strcpy(dateest, argv[6]); /* dateestboot */ 
 

  currentstring = malloc(11*sizeof(char));

  totalwordcountinptr=fopen(totalwordcount, "r");
  for(i=0; i<sizeoftrain; i++){
    fscanf(totalwordcountinptr, "%d",  &wordcount);
    Occvectortotal[i]=wordcount;
  }
  fclose(totalwordcountinptr);
  
  for(i=0; i<=500000; i++){
    shinglearray[i]=malloc(200*sizeof(char));
  }
  
  i=0; 
  shinglefileinptr=fopen(shinglefile, "r");
  fscanf(shinglefileinptr, "%s", shingle);
  while(!feof(shinglefileinptr)){
    /*printf("%s \n", shingle);*/
    strcpy(shinglearray[i],shingle);
    fscanf(shinglefileinptr, "%s", shingle);
    i++;
  }
  fclose(shinglefileinptr);
  lengthshingarray=i;


  randomnumfileinptr=fopen(randomnumfile, "r");
  j=0;
  while(!feof(randomnumfileinptr)){
    fscanf(randomnumfileinptr, "%d", &randomnum);
    randomnumvec[j]=randomnum;
    j++;
  }
  printf("%d \n", j);


  dateinptr=fopen(aawmaster, "r");
  j=0;
  for(i=1; i<=3353; i++){
    fscanf(dateinptr, "%s %d %s", dummystring1, &date, dummystring2); 
    if( (i%RESIDUEval)!=0 && (i%RESIDUEtest)!=0 ){
      traindate[j]=date;
      j++;
    }
  }
  fclose(dateinptr);

  /* PUT THE KERNEL VALUES HERE */
  for(i=0; i<=maxdate-mindate;i++){
    kernelvalue[i]= dt((float)(i/h),10.5);
    /*printf("%.12f \n",  kernelvalue[i]);*/
  }
  bottomline=/*exp(-pow(378/5,2))/(450*378);*/ log(pow(5,-30));
  dateestfileoutptr=fopen(dateest, "w");
  /* this comand just wipes out the previous contents of the file.   later it will
     be re-opened in append mode */
  fclose(dateestfileoutptr);


  for(k=0; k<bootstrapsample; k++){ /* AN OUTER LOOP HERE FOR REPEATING BOOTSTRAP SAMPLING */
    for(i=0; i<sizeoftrain; i++){
      bootvector[i]=0;
    }
    for(i=0; i<sizeoftrain; i++){  /* THE END OF THE LOOP DOESN'T HAVE TO BE sizeoftrain....SHOULD
				      PERHAPSE BE MUCH LARGER */
      bootvector[i]=randomnumvec[i + sizeoftrain * k];
      /* printf("%d ",  bootvector[i]); */
    }
    /* printf("\n"); */
    if(k>=0){  /* for debugging purposes ....since it crashes after k>=854 */
    
      for(i=1; i<=1026/*3353*/; i++){ /* to obtain 100 test documents */ 
	if( (i%RESIDUEtest)==0 && (i%RESIDUEval)!=0 ){
	  inttostring(i, currentstring);  /* TAKING A DOC FROM THE TEST SET */
	  currentstring = currentstring + 2*sizeof(char);
	  strcpy(currentfilename, basename);
	  strcat(currentfilename, currentstring);
	  strcat(currentfilename, shingled);
	  currentstring = currentstring - 2*sizeof(char);  /* reset the pointer for currentstring */
	  currentshinglefileinptr=fopen(currentfilename, "r"); /* SUCH AS AAW0009.SHINGLED */ 
	  for(t=0; t<=maxdate-mindate; t++){
	    probdoc[t]=0;
	  }
	  while(!feof(currentshinglefileinptr)){
	    fscanf(currentshinglefileinptr, "%s %s %s", dummystring1, dummystring2, dummystring3); 
	    strcpy(shingle, dummystring1);
	    strcat(shingle, at);
	    strcat(shingle, dummystring2);
	    strcat(shingle, at);
	    strcat(shingle, dummystring3);
	    location=binarystringsearch(shinglearray, shingle, lengthshingarray); 
	    /* printf("%s %d \n", shingle, location); */
	    if(location!=0){
	      inttostring(location, currentstring);
	      strcpy(tempcurrentstring, basedirectory);
	      strcat(tempcurrentstring, wordcountfile);
	      strcat(tempcurrentstring, currentstring);
	      /*printf("%s %d %s \n", shingle, location, tempcurrentstring);*/
	      wordcountfileinptr=fopen(tempcurrentstring, "r");
	      count=0;
	      fscanf(wordcountfileinptr, "%d", &freq); 
	      while(!feof(wordcountfileinptr)){
		Occvector[count]=freq;
		fscanf(wordcountfileinptr, "%d", &freq);
		count++;
	      }
	      fclose(wordcountfileinptr);
	      /*printf("count=%d \n", count);*/
	      /* NEED TO SET UP dateshingresultfileboot FROM THE PREVIOUS PROGRAM INTO FILE
		 AND THEN USE mergershing2onlysortuniq AS AN INPUT IN ORDER TO USE THE BINARY SEARCH
		 ALGORITHM */
	      /* ASSUMING THE LOCATION OF THE SHINGLE HAS BEEN FOUND, (NEED TO PUT STATEMENT IF NOT FOUND) */
	      
	      /* YOU THEN PUT ALL THE 2608 COLUMNS INTO AN ARRAY CALLED Occvector */
	      
	      for(l=0; l<sizeoftrain; l++){
		ns[l]=Occvector[l]*bootvector[l];
	      }
	      
	      for(t=0; t<=maxdate-mindate; t++){
		sum=0;
		for(j=0; j<sizeoftrain; j++){
		  sum=sum+((float) ns[j])*kernelvalue[abs( (traindate[j]-mindate)-t )]; 
		  /*printf("kernelvalue[traindate[j]-t]=%.20f \n", 
		    kernelvalue[abs( (traindate[j]-mindate)-t )]);*/
		}
		Num[t]=sum;
	      }
	      
	      
	      for(l=0; l<sizeoftrain; l++){
		Nt[l]=Occvectortotal[l]*bootvector[l];
		/*printf("occvectortotal[%d] = %d \t bootvector[%d] = %d \n", l, Occvectortotal[l], l, 
		  bootvector[l] );*/
	      }
	      
	      for(t=0; t<=maxdate-mindate; t++){
		sum=0;
		for(j=0; j<sizeoftrain; j++){
		  sum=sum+((float) Nt[j])*kernelvalue[abs( (traindate[j]-mindate)-t )]; 
		}
		Den[t]=sum;
	      }
	      for(t=0; t<=maxdate-mindate; t++){
		/*printf("%.20f %.20f \n", Num[t], Den[t]);*/
	      }
	      
	      for(t=0; t<=maxdate-mindate; t++){
		if(log((float)(Num[t]/Den[t])) <bottomline){
		  probs[t]=bottomline;
		}
		else{
		  probs[t]=log((float)(Num[t]/Den[t]));
		}
	      }
	      /*printf("%f %f %f \n", Num[t], Den[t],probs[t]);*/
	      for(t=0; t<=maxdate-mindate; t++){
		probdoc[t]=probdoc[t]+probs[t];
	      }
	    } /* if(location!=0) */
	  } /*while(!feof(currentshinglefileinptr)) */
	  fclose(currentshinglefileinptr);
	  optdate=0;
	  for(t=0;  t<=maxdatedata-mindatedata ; t++){ 
	    /*printf("%.12f \n", probdoc[t]);*/
	    if(probdoc[t]>=probdoc[optdate]){
	      optdate=t; 
	    }
	  }
	  
	  dateestfileoutptr=fopen(dateest, "a");
	  fprintf(dateestfileoutptr, "%d\t%d\n", optdate+1089, i);
	  fclose(dateestfileoutptr);
	  
	  /* printf("%d %d\n",optdate+1089, i); */
	}
      } /* for(i=1; i<=3353; i++) */
    }
    /*fclose(dateestfileoutptr);*/
  } /* for(k=1; k<=bootstrapsample; k++) */
}
Example #7
0
int main()
{
	int pid1 = 0;
	int pid2 = 0;
	try {
		std::cout << "Cancel before" << std::endl;
		io::io_service srv;
		the_service = &srv;
		io::acceptor ac(srv);
		the_socket = &ac;
		ac.open(io::pf_inet);
		ac.set_option(io::basic_socket::reuse_address,true);
		io::endpoint ep("127.0.0.1",8080);
		ac.bind(ep);
		ac.listen(5);
		io::stream_socket s1(srv);
		ac.async_accept(s1,socket_accept_failer);
		ac.cancel();
		srv.run();
		TEST(called); called=false;
		srv.reset();
		std::cout << "Cancel by timer" << std::endl;
		
		io::deadline_timer dt(srv);
		dt.expires_from_now(booster::ptime::milliseconds(100));
		dt.async_wait(socket_canceler);
		ac.async_accept(s1,socket_accept_failer);
		srv.run();
		TEST(called); called=false;
		srv.reset();

		std::cout << "Cancel by thread" << std::endl;
		booster::thread t1(thread_socket_canceler);
		ac.async_accept(s1,socket_accept_failer);
		srv.run();
		TEST(called); called=false;
		t1.join();
		srv.reset();
		
		std::cout << "Accept by thread" << std::endl;
		booster::thread t2(thread_socket_connector);
		ac.async_accept(s1,async_socket_writer);
		accepted_socket=&s1;
		srv.run();
		TEST(called); called=false;
		t2.join();
		srv.reset();
		s1.close();
		std::cout << "Acceptor is shared" << std::endl;
		
		pid1=fork();
		if(pid1==0) {
			child();
			return 0;
		}
		pid2=fork();
		if(pid2==0) {
			child();
			return 0;
		}

		booster::ptime::millisleep(100);
		s1.open(io::pf_inet);
		s1.connect(ep);
		int in_pid1=0;
		s1.read(io::buffer(&in_pid1,sizeof(int)));
		s1.close();
		s1.open(io::pf_inet);
		s1.connect(ep);
		int in_pid2=0;
		s1.read(io::buffer(&in_pid2,sizeof(int)));
		s1.close();

		TEST((in_pid1==pid1 && in_pid2==pid2) || (in_pid1==pid2 && in_pid2==pid1));
	
	}
	catch(std::exception const &e) {
		std::cerr << e.what() << std::endl;
		if(pid1!=0) {
			kill(pid1,SIGKILL);
			int r;
			wait(&r);
		}
		if(pid2!=0) {
			kill(pid2,SIGKILL);
			int r;
			wait(&r);
		}
		return 1;
	}
	if(pid1!=0 && pid2!=0) {
		int r1=0,r2=0;
		::wait(&r1);
		::wait(&r2);
		if(	WIFEXITED(r1) && WEXITSTATUS(r1)==0 
			&& WIFEXITED(r2) && WEXITSTATUS(r2)==0) 
		{
			std::cerr << "Ok" <<std::endl;
			return 0;
		}
		return 1;
	}
	return 0;
}
void PsyUtils::TPositionInfo2QGeoPositionInfo(TPositionInfoBase &aPosInfoBase, QGeoPositionInfo& aQPosInfo)
{
    if (aPosInfoBase.PositionClassType() & EPositionInfoClass  ||
            aPosInfoBase.PositionClassType() & EPositionSatelliteInfoClass) {
        TPositionInfo *posInfo = static_cast<TPositionInfo*>(&aPosInfoBase);
        TPosition pos;
        QGeoCoordinate  coord;

        posInfo->GetPosition(pos);
        coord.setLatitude(pos.Latitude());
        coord.setLongitude(pos.Longitude());
        coord.setAltitude(pos.Altitude());

        //store the QGeoCoordinate values
        aQPosInfo.setCoordinate(coord);

        TDateTime datetime = pos.Time().DateTime();
        QDateTime dt(QDate(datetime.Year() , datetime.Month() + 1, datetime.Day() + 1),
                     QTime(datetime.Hour() , datetime.Minute(), datetime.Second(),
                           datetime.MicroSecond() / 1000),
                     Qt::UTC);

        //store the time stamp
        aQPosInfo.setTimestamp(dt);

        //store the horizontal accuracy
        aQPosInfo.setAttribute(QGeoPositionInfo::HorizontalAccuracy, pos.HorizontalAccuracy());

        //store the vertical accuracy
        aQPosInfo.setAttribute(QGeoPositionInfo::VerticalAccuracy, pos.VerticalAccuracy());

        if (aPosInfoBase.PositionClassType() & EPositionSatelliteInfoClass) {
            TCourse course;
            TPositionSatelliteInfo *satInfo = static_cast<TPositionSatelliteInfo*>(&aPosInfoBase);
            satInfo->GetCourse(course);
            aQPosInfo.setAttribute(QGeoPositionInfo::Direction, course.Heading());
            aQPosInfo.setAttribute(QGeoPositionInfo::GroundSpeed, course.Speed());
            aQPosInfo.setAttribute(QGeoPositionInfo::VerticalSpeed, course.VerticalSpeed());
        }
    }

    if (aPosInfoBase.PositionClassType() & EPositionGenericInfoClass) {
        HPositionGenericInfo *genInfo = static_cast<HPositionGenericInfo*>(&aPosInfoBase);
        float val;
        //check for the horizontal speed
        if (genInfo->IsFieldAvailable(EPositionFieldHorizontalSpeed)) {
            genInfo->GetValue(EPositionFieldHorizontalSpeed, val);
            aQPosInfo.setAttribute(QGeoPositionInfo::GroundSpeed, val);
        }
        //check for the vertcal speed
        if (genInfo->IsFieldAvailable(EPositionFieldVerticalSpeed)) {
            genInfo->GetValue(EPositionFieldVerticalSpeed, val);
            aQPosInfo.setAttribute(QGeoPositionInfo::VerticalSpeed, val);
        }

        //check for the magnetic variation
        if (genInfo->IsFieldAvailable(EPositionFieldMagneticCourseError)) {
            genInfo->GetValue(EPositionFieldMagneticCourseError, val);
            aQPosInfo.setAttribute(QGeoPositionInfo::MagneticVariation, val);
        }

        //check for the heading
        if (genInfo->IsFieldAvailable(EPositionFieldHeading)) {
            genInfo->GetValue(EPositionFieldHeading, val);
            aQPosInfo.setAttribute(QGeoPositionInfo::Direction, val);
        }
    }
}
Example #9
0
void modCalcDayLength::showCurrentDate (void)
{
	KStarsDateTime dt( KStarsDateTime::currentDateTime() );
	datBox->setDate( dt.date() );
}
Example #10
0
 time_t DateTime::GetGMTTime() const
 {
    DateTime dt(GetTime());
    dt.IncrementClock(3600.0f * -1.0f * mGMTOffset);
    return dt.GetTime();
 }
Example #11
0
 void DateTime::GetGMTTime(tm& timeParts) const
 {
    DateTime dt(GetTime());
    dt.IncrementClock(double(3600.0f * -mGMTOffset));
    dt.GetTime(timeParts);
 }
Example #12
0
bool DocumentSaverDB::saveDocument(KraftDoc *doc )
{
    bool result = false;
    if( ! doc ) return result;

    QSqlTableModel model;
    model.setTable("document");

    QSqlRecord record;

    kDebug() << "############### Document Save ################" << endl;

    if( doc->isNew() ) {
        record = model.record();
    } else {
      model.setFilter("docID=" + doc->docID().toString());
      model.select();
      if ( model.rowCount() > 0 ) {
        record = model.record(0);
      } else {
        kError() << "Could not select document record" << endl;
        return result;
      }
       // The document was already saved.
    }

    if( !doc->isNew() && doc->docTypeChanged() && doc->newIdent() ) {
        // an existing doc has a new document type. Fix the doc number cycle and pick a new ident
        DocType dt( doc->docType() );
        QString ident = dt.generateDocumentIdent( doc );
        doc->setIdent( ident );
    }

    fillDocumentBuffer( record, doc );

    if( doc->isNew() ) {
      kDebug() << "Doc is new, inserting" << endl;
      if( !model.insertRecord(-1, record)) {
          QSqlError err = model.lastError();
          kDebug() << "################# SQL Error: " << err.text();
      }
      model.submitAll();

      dbID id = KraftDB::self()->getLastInsertID();
      doc->setDocID( id );

      // get the uniq id and write it into the db
      DocType dt( doc->docType() );
      QString ident = dt.generateDocumentIdent( doc );
      doc->setIdent( ident );
      model.setFilter("docID=" + id.toString());
      model.select();
      if ( model.rowCount() > 0 ) {
        model.setData(model.index(0, 1), ident);
        model.submitAll();
      }

    } else {
      kDebug() << "Doc is not new, updating #" << doc->docID().intID() << endl;

      record.setValue( "docID", doc->docID().toString() );

      model.setRecord(0, record);
      model.submitAll();
    }

    saveDocumentPositions( doc );

    kDebug() << "Saved document no " << doc->docID().toString() << endl;

    return result;
}
Example #13
0
void toyMCGen(const int nsig, const float wtag, const float purity){
    TFile* file = new TFile("toyMC.root","RECREATE");

//    gROOT->ProcessLine(".L ../PDFs/Faddeeva.hh+");
    gROOT->LoadMacro("../PDFs/libFadeeva.so");
    gROOT->ProcessLine(".L ../PDFs/RooBtoDhFadeeva.cxx++");

    RooRealVar tau("tau","tau",_tau,"ps"); tau.setConstant(kTRUE);
    RooRealVar dm("dm","dm",_dm,"ps^{-1}"); dm.setConstant(kTRUE);
    RooRealVar sin2beta("sin2beta","sin2beta",_sin2beta); sin2beta.setConstant(kTRUE);
    RooRealVar cos2beta("cos2beta","cos2beta",_cos2beta); cos2beta.setConstant(kTRUE);
    RooRealVar dt("dt","dt",-3.,3.,"ps");

    RooRealVar moment("moment","moment",-1.); moment.setConstant(kTRUE);
    RooRealVar parity("parity","parity",0.); parity.setConstant(kTRUE);

    RooRealVar* K[8];
    RooRealVar* Kb[8];
    RooRealVar* C[8];
    RooRealVar* S[8];
    RooRealVar* Sb[8];
    stringstream out;
    for(int i=0; i<8; i++){
        out.str("");
        out << "K" << i;
        K[i] = new RooRealVar(out.str().c_str(),out.str().c_str(),_K[i]); K[i]->setConstant(kTRUE);
        out.str("");
        out << "Kb" << i;
        Kb[i] = new RooRealVar(out.str().c_str(),out.str().c_str(),_Kb[i]); Kb[i]->setConstant(kTRUE);
        out.str("");
        out << "C" << i;
        C[i] = new RooRealVar(out.str().c_str(),out.str().c_str(),_C[i]); C[i]->setConstant(kTRUE);
        out.str("");
        out << "S" << i;
        S[i] = new RooRealVar(out.str().c_str(),out.str().c_str(),_S[i]); S[i]->setConstant(kTRUE);
        out.str("");
        out << "Sb" << i;
        Sb[i] = new RooRealVar(out.str().c_str(),out.str().c_str(),-_S[i]); Sb[i]->setConstant(kTRUE);
    }
    cout << "Hello world!" << endl;

    RooCategory tag("tag","tag");
    tag.defineType("B0",1);
    tag.defineType("anti-B0",-1);

    RooCategory bin("bin","bin");
    bin.defineType("1",1);
    bin.defineType("2",2);
    bin.defineType("3",3);
    bin.defineType("4",4);
    bin.defineType("5",5);
    bin.defineType("6",6);
    bin.defineType("7",7);
    bin.defineType("8",8);
    bin.defineType("-1",-1);
    bin.defineType("-2",-2);
    bin.defineType("-3",-3);
    bin.defineType("-4",-4);
    bin.defineType("-5",-5);
    bin.defineType("-6",-6);
    bin.defineType("-7",-7);
    bin.defineType("-8",-8);

    RooRealVar mean("mean","mean",0.,"ps"); mean.setConstant(kTRUE);
    RooRealVar sigma("sigma","sigma",_tau,"ps"); sigma.setConstant(kTRUE);
//    RooGaussModel rf("rf","rf",dt,mean,sigma);
//    RooTruthModel rf("rf","rf",dt);

    cout << "Raw PDFs..." << endl;

    RooBtoDhFadeeva pdfs[16];
    RooBtoDhFadeeva pdfsb[16];
    for(int i=0; i<8; i++){
        out.str("");
        out << "B0 pdf " << i+1;
        pdfs[i]   = RooBtoDhFadeeva(out.str().c_str(),out.str().c_str(),dt,tau,dm,sin2beta,cos2beta,*K[i],*Kb[i],*C[i],*S[i],moment,parity);
        out.str("");
        out << "B0 pdf " << -(i+1);
        pdfs[i+8] = RooBtoDhFadeeva(out.str().c_str(),out.str().c_str(),dt,tau,dm,sin2beta,cos2beta,*Kb[i],*K[i],*C[i],*Sb[i],moment,parity);
        out.str("");
        out << "anti-B0 pdf " << i+1;
        pdfsb[i]  = RooBtoDhFadeeva(out.str().c_str(),out.str().c_str(),dt,tau,dm,sin2beta,cos2beta,*K[i],*Kb[i],*C[i],*Sb[i],moment,parity);
        out.str("");
        out << "anti-B0 pdf " << -(i+1);
        pdfsb[i+8]= RooBtoDhFadeeva(out.str().c_str(),out.str().c_str(),dt,tau,dm,sin2beta,cos2beta,*Kb[i],*K[i],*C[i],*S[i],moment,parity);
    }

    cout << "Numerical convolution..." << endl;

//    RooFFTConvPdf PDFs[16];
//    RooFFTConvPdf PDFsb[16];
//    for(int i=0; i<8; i++){
//        out.str("");
//        out << "B0 PDF " << i+1;
//        PDFs[i]   = RooFFTConvPdf(out.str().c_str(),out.str().c_str(),dt,pdfs[i],rf);
//        out.str("");
//        out << "B0 PDF " << -(i+1);
//        PDFs[i+8] = RooFFTConvPdf(out.str().c_str(),out.str().c_str(),dt,pdfs[i+8],rf);
//        out.str("");
//        out << "anti-B0 PDF " << i+1;
//        PDFsb[i]  = RooFFTConvPdf(out.str().c_str(),out.str().c_str(),dt,pdfsb[i],rf);
//        out.str("");
//        out << "anti-B0 PDF " << -(i+1);
//        PDFsb[i+8]= RooFFTConvPdf(out.str().c_str(),out.str().c_str(),dt,pdfsb[i+8],rf);
//    }

    cout << "Filling dataset..." << endl;

    RooDataSet d("data","data",RooArgSet(dt,bin,tag));
    RooDataSet *data;
    int N;
    for(int i=0; i<8; i++){
        out.str("");
        out << i+1;
        bin.setLabel(out.str().c_str());
        // Signal with true tag
        N = (int)(nsig*(1.-wtag)*_K[i]*0.5);
        // B0
        data = PDFs[i].generate(RooArgSet(dt),N);
        tag.setLabel("B0");
        for(int j=0; j<N; j++){
            dt = data->get(j)->find(dt.GetName())->getVal();
            d.add(RooArgSet(dt,bin,tag));
        }

        // anti-B0
        data = PDFsb[i].generate(RooArgSet(dt),N);
        tag.setLabel("anti-B0");
        for(int j=0; j<N; j++){
            dt = data->get(j)->find(dt.GetName())->getVal();
            d.add(RooArgSet(dt,bin,tag));
        }

        // Signal with wrong tag
        N = (int)(nsig*wtag*_K[i]*0.5);
        // B0
        data = PDFsb[i].generate(RooArgSet(dt),N);
        tag.setLabel("B0");
        for(int j=0; j<N; j++){
            dt = data->get(j)->find(dt.GetName())->getVal();
            d.add(RooArgSet(dt,bin,tag));
        }

        // anti-B0
        data = PDFs[i].generate(RooArgSet(dt),N);
        tag.setLabel("anti-B0");
        for(int j=0; j<N; j++){
            dt = data->get(j)->find(dt.GetName())->getVal();
            d.add(RooArgSet(dt,bin,tag));
        }

        //Background
        N = (int)(nsig/purity*_K[i]*0.5);
        // B0
        data = rf.generate(RooArgSet(dt),N);
        tag.setLabel("B0");
        for(int j=0; j<N; j++){
            dt = data->get(j)->find(dt.GetName())->getVal();
            d.add(RooArgSet(dt,bin,tag));
        }

        // anti-B0
        data = rf.generate(RooArgSet(dt),N);
        tag.setLabel("anti-B0");
        for(int j=0; j<N; j++){
            dt = data->get(j)->find(dt.GetName())->getVal();
            d.add(RooArgSet(dt,bin,tag));
        }
        //////////////
        // anti-bin //
        //////////////
        out.str("");
        out << -(i+1);
        bin.setLabel(out.str().c_str());
        // Signal with true tag
        N = (int)(nsig*(1.-wtag)*_Kb[i]*0.5);
        // B0
        data = PDFs[i+8].generate(RooArgSet(dt),N);
        tag.setLabel("B0");
        for(int j=0; j<N; j++){
            dt = data->get(j)->find(dt.GetName())->getVal();
            d.add(RooArgSet(dt,bin,tag));
        }

        // anti-B0
        data = PDFsb[i+8].generate(RooArgSet(dt),N);
        tag.setLabel("anti-B0");
        for(int j=0; j<N; j++){
            dt = data->get(j)->find(dt.GetName())->getVal();
            d.add(RooArgSet(dt,bin,tag));
        }

        // Signal with wrong tag
        N = (int)(nsig*wtag*_Kb[i]*0.5);
        // B0
        data = PDFsb[i+8].generate(RooArgSet(dt),N);
        tag.setLabel("B0");
        for(int j=0; j<N; j++){
            dt = data->get(j)->find(dt.GetName())->getVal();
            d.add(RooArgSet(dt,bin,tag));
        }

        // anti-B0
        data = PDFs[i+8].generate(RooArgSet(dt),N);
        tag.setLabel("anti-B0");
        for(int j=0; j<N; j++){
            dt = data->get(j)->find(dt.GetName())->getVal();
            d.add(RooArgSet(dt,bin,tag));
        }

        //Background
        N = (int)(nsig/purity*_Kb[i]*0.5);
        // B0
        data = rf.generate(RooArgSet(dt),N);
        tag.setLabel("B0");
        for(int j=0; j<N; j++){
            dt = data->get(j)->find(dt.GetName())->getVal();
            d.add(RooArgSet(dt,bin,tag));
        }

        // anti-B0
        data = rf.generate(RooArgSet(dt),N);
        tag.setLabel("anti-B0");
        for(int j=0; j<N; j++){
            dt = data->get(j)->find(dt.GetName())->getVal();
            d.add(RooArgSet(dt,bin,tag));
        }
    }

    d.Print();
    d.Write();
    file->Close();

    return;
}
void DeformationGraph::GenerateDensePointSet(std::list<PointWithID>& pointcoll, double delta)
{
#ifdef DEBUGTRACE
	meshtalent::DebugTrace dt("./sample.log");
#endif
	assert(pointcoll.size() == 0);

	typedef DeformableMesh3d::InterMesh InterMesh;
	InterMesh* pMesh = dmesh.pMesh;
	int vertexnum = pMesh->n_vertices();
	//int edgenum = pMesh->n_edges();
	//int facetnum = pMesh->n_faces();
	// sample points on vertices.
	InterMesh::VertexIter v_it, v_end(pMesh->vertices_end());
	for (v_it = pMesh->vertices_begin(); v_it != v_end; ++v_it) {
		InterMesh::Point& p = pMesh->point(v_it);
		P3d p3d(p[0], p[1], p[2]);
		pointcoll.push_back(PointWithID(p3d, PointWithID::VERTEX, v_it.handle().idx()));
	}
#ifdef DEBUGTRACE
	dt.Trace("There %d vertex_points sampled.\n", vertexnum);
#endif
	// sample points on edges.
	int epcount = 0;
	InterMesh::EdgeIter e_it, e_end(pMesh->edges_end());
	for (e_it = pMesh->edges_begin(); e_it != e_end; ++e_it) {
		InterMesh::EdgeHandle eh = pMesh->handle(*e_it);
		InterMesh::HalfedgeHandle heh = pMesh->halfedge_handle(eh, 0); // always select the first edge, but if it's a boundary??
		InterMesh::VertexHandle phfrom = pMesh->from_vertex_handle(heh);
		InterMesh::VertexHandle phto = pMesh->to_vertex_handle(heh);
		InterMesh::Point pf = pMesh->point(phfrom);
		InterMesh::Point pt = pMesh->point(phto);
		P3d p3dfrom(pf[0], pf[1], pf[2]);
		P3d p3dto(pt[0], pt[1], pt[2]);
		double dist = (p3dto - p3dfrom).mag();
		//compute delta vector and sample on this edge.
		V3d deltaV = (p3dto - p3dfrom) * delta;
		int times = static_cast<int>(dist / delta) - 1;
		P3d p3dnow = p3dfrom;
		for (int j = 0; j < times; ++j) {
			p3dnow += deltaV;
			pointcoll.push_back(PointWithID(p3dnow, PointWithID::EDGE, e_it.handle().idx()));
		}
		epcount += (times < 0 ? 0 : times);
	}
#ifdef DEBUGTRACE
	dt.Trace("There are %d edge_points sampled.\n", epcount);
#endif
	// sample points on facet.
	int fpcount = 0;
	InterMesh::FaceIter f_it, f_end(pMesh->faces_end());
	for (f_it = pMesh->faces_begin(); f_it != f_end; ++f_it) {
		P3d trivertices[3];
		//assert((*f_it).is_triangle());
		InterMesh::FaceVertexIter fv_it(pMesh->fv_iter(f_it.handle()));
		int j = 0;
		for (; fv_it; ++fv_it, ++j) {
			InterMesh::Point& p = pMesh->point(fv_it);
			trivertices[j] = P3d(p[0], p[1], p[2]);
		}
		// compute num should be sampled.
		V3d v1 = trivertices[1] - trivertices[0];
		V3d v2 = trivertices[2] - trivertices[0];
		//double lenv1 = v1.mag();
		//double lenv2 = v2.mag();
		double area = (v1 % v2).mag() / 2;
		int samplenum = static_cast<int>(area / (delta * delta));
		fpcount += samplenum;
		RandDoubleGenerator drand;
		drand.srand(time(NULL));
		while (samplenum > 0) {
			double lamada1 = drand(0, 1);
			double lamada2 = drand(0, 1);
			if (lamada1 + lamada2 >= 1) { // judge if this point is not in triangle.
				continue;
			}
			P3d tp3d = trivertices[0] + (v1 * lamada1 + v2 * lamada2);
			pointcoll.push_back(PointWithID(tp3d, PointWithID::FACE, f_it.handle().idx()));
			--samplenum;
		} // end of while.
	} // end of for.
#ifdef DEBUGTRACE
	dt.Trace("There are %d facet_points sampled.\n", fpcount);
	dt.Trace("There are %d points sampled totally.\n", pointcoll.size());
#endif
}
Example #15
0
std::string CmdPrint::FormatResult(const char *format, CVarRef ret) {
  if (format == nullptr) {
    String sret = DebuggerClient::FormatVariable(ret, -1);
    return string(sret.data(), sret.size());
  }

  if (strcmp(format, "v") == 0) {
    String sret = DebuggerClient::FormatVariable(ret, -1, true);
    return string(sret.data(), sret.size());
  }

  if (strcmp(format, "dec") == 0 ||
      strcmp(format, "unsigned") == 0 ||
      ret.isInteger()) {
    int64_t nret = ret.toInt64();
    char buf[64];
    if (strcmp(format, "hex") == 0 || strcmp(format, "x") == 0) {
      snprintf(buf, sizeof(buf), "%" PRIx64, nret);
      return buf;
    }
    if (strcmp(format, "oct") == 0) {
      snprintf(buf, sizeof(buf), "%" PRIo64, nret);
      return buf;
    }
    if (strcmp(format, "dec") == 0) {
      snprintf(buf, sizeof(buf), "%" PRId64, nret);
      return buf;
    }
    if (strcmp(format, "unsigned") == 0) {
      snprintf(buf, sizeof(buf), "%" PRIu64, nret);
      return buf;
    }
    if (strcmp(format, "time") == 0) {
      StringBuffer sb;
      DateTime dt(nret);
      sb.append("RFC822:            ");
      sb.append(dt.toString(DateTime::RFC822));
      sb.append("\nRFC850:            ");
      sb.append(dt.toString(DateTime::RFC850));
      sb.append("\nRFC1036:           ");
      sb.append(dt.toString(DateTime::RFC1036));
      sb.append("\nRFC1123/RSS:       ");
      sb.append(dt.toString(DateTime::RFC1123));
      sb.append("\nRFC2822:           ");
      sb.append(dt.toString(DateTime::RFC2822));
      sb.append("\nRFC3339/ATOM/W3C:  ");
      sb.append(dt.toString(DateTime::RFC3339));
      sb.append("\nISO8601:           ");
      sb.append(dt.toString(DateTime::ISO8601));
      sb.append("\nCookie:            ");
      sb.append(dt.toString(DateTime::Cookie));
      sb.append("\nHttpHeader:        ");
      sb.append(dt.toString(DateTime::HttpHeader));
      return sb.data();
    }

    assert(false);
  }

  String sret = DebuggerClient::FormatVariable(ret, -1);
  if (strcmp(format, "hex") == 0 || strcmp(format, "x") == 0 ||
      strcmp(format, "oct") == 0) {
    StringBuffer sb;
    for (int i = 0; i < sret.size(); i++) {
      char ch = sret[i];
      if (isprint(ch)) {
        sb.append(ch);
      } else {
        char buf[6];
        if (strcmp(format, "oct") == 0) {
          snprintf(buf, sizeof(buf), "\\%03o", ch);
        } else {
          snprintf(buf, sizeof(buf), "\\x%02x", ch);
        }
        sb.append(buf);
      }
    }
    return sb.data() ? sb.data() : "";
  }
  if (strcmp(format, "time") == 0) {
    DateTime dt;
    int64_t ts = -1;
    if (dt.fromString(ret.toString(), SmartObject<TimeZone>())) {
      bool err;
      ts = dt.toTimeStamp(err);
    }
    return String(ts).data();
  }

  assert(false);
  return "";
}
Example #16
0
void PrintTime(const TDesC& aName, const TTime& aTime)
	{
	TDateTime dt(aTime.DateTime());
	test.Printf(_L("%S = %02d:%02d:%02d:%06d\n"),&aName,dt.Hour(),dt.Minute(),dt.Second(),dt.MicroSecond());
	}
Example #17
0
int main(int argc, char **argv)
{
  ros::init(argc, argv, "msf_eval");
  ros::Time::init();


  enum argIndices{
    bagfile = 1,
    EVAL_topic = 2,
    GT_topic = 3,
    singleRunOnly = 4
  };

  //calibration of sensor to vicon
  Eigen::Matrix4d T_BaBg_mat;

  //this is the Vicon one - SLAM sensor V0
  ///////////////////////////////////////////////////////////////////////////////////////////
  T_BaBg_mat << 0.999706627053000, -0.022330158354000, 0.005123243528000, -0.060614697387000, 0.022650462142000, 0.997389634278000, -0.068267398302000, 0.035557942651000, -0.003589706237000, 0.068397960288000, 0.997617159323000, -0.042589657349000, 0, 0, 0, 1.000000000000000;
  ////////////////////////////////////////////////////////////////////////////////////////////

  ros::Duration dt(0.0039);
  const double timeSyncThreshold = 0.005;
  const double timeDiscretization = 10.0; //discretization step for different starting points into the dataset
  const double trajectoryTimeDiscretization = 0.049; //discretization of evaluation points (vision framerate for fair comparison)
  const double startTimeOffset = 10.0;

  if (argc < 4)
  {
    MSF_ERROR_STREAM("usage: ./"<<argv[0]<<" bagfile EVAL_topic GT_topic [singleRunOnly]");
    return -1;
  }
  bool singleRun = false;
  if (argc == 5)
  {
    singleRun = atoi(argv[singleRunOnly]);
  }

  if(singleRun){
    MSF_WARN_STREAM("Doing only a single run.");
  }else{
    MSF_WARN_STREAM("Will process the dataset from different starting points.");
  }

  typedef geometry_msgs::TransformStamped GT_TYPE;
  typedef geometry_msgs::PoseWithCovarianceStamped EVAL_TYPE;

  // output file
  std::stringstream matlab_fname;

  std::string path = ros::package::getPath("msf_eval");
  matlab_fname << path << "/Matlab/matlab_data" << ros::Time::now().sec << ".m";

  std::ofstream outfile(matlab_fname.str().c_str());

  std::stringstream poses_EVAL;
  std::stringstream poses_GT;

  assert(outfile.good());

  outfile << "data=[" << std::endl;

  ros::Duration startOffset(startTimeOffset);

  sm::kinematics::Transformation T_BaBg(T_BaBg_mat); //body aslam to body Ground Truth

  // open for reading
  rosbag::Bag bag(argv[bagfile], rosbag::bagmode::Read);

  // views on topics
  rosbag::View view_EVAL(bag, rosbag::TopicQuery(argv[EVAL_topic]));
  rosbag::View view_GT(bag, rosbag::TopicQuery(argv[GT_topic]));

  //check topics
  if (view_EVAL.size() == 0)
  {
    MSF_ERROR_STREAM("The bag you provided does not contain messages for topic "<<argv[EVAL_topic]);
    return -1;
  }
  if (view_GT.size() == 0)
  {
    MSF_ERROR_STREAM("The bag you provided does not contain messages for topic "<<argv[GT_topic]);
    return -1;
  }

  //litter console with number of messages
  MSF_INFO_STREAM("Reading from "<<argv[bagfile]);
  MSF_INFO_STREAM("Topic "<<argv[EVAL_topic]<<", size: "<<view_EVAL.size());
  MSF_INFO_STREAM("Topic "<<argv[GT_topic]<<", size: "<<view_GT.size());

  //get times of first messages
  GT_TYPE::ConstPtr GT_begin = view_GT.begin()->instantiate<GT_TYPE>();
  assert(GT_begin);
  EVAL_TYPE::ConstPtr POSE_begin = view_EVAL.begin()->instantiate<EVAL_TYPE>();
  assert(POSE_begin);

  MSF_INFO_STREAM("First GT data at "<<GT_begin->header.stamp);
  MSF_INFO_STREAM("First EVAL data at "<<POSE_begin->header.stamp);

  while (true) // start eval from different starting points
  {

    rosbag::View::const_iterator it_EVAL = view_EVAL.begin();
    rosbag::View::const_iterator it_GT = view_GT.begin();

    // read ground truth
    ros::Time start;

    // Find start time alignment: set the GT iterater to point to a time larger than the aslam time
    while (true)
    {
      GT_TYPE::ConstPtr trafo = it_GT->instantiate<GT_TYPE>();
      assert(trafo);
      ros::Time time_GT;
      time_GT = trafo->header.stamp + dt;

      EVAL_TYPE::ConstPtr pose = it_EVAL->instantiate<EVAL_TYPE>();
      assert(pose);

      ros::Time time_EKF;
      time_EKF = pose->header.stamp;

      if (time_EKF >= time_GT)
      {
        it_GT++;
        if (it_GT == view_GT.end())
        {
          MSF_ERROR_STREAM("Time synchronization failed");
          return false;
        }
      }
      else
      {
        start = time_GT;
        MSF_INFO_STREAM("Time synced! GT start: "<<start <<" EVAL start: "<<time_EKF);
        break;
      }
    }

    // world frame alignment
    sm::kinematics::Transformation T_WaBa;
    sm::kinematics::Transformation T_WgBg;
    sm::kinematics::Transformation T_WgBg_last;
    sm::kinematics::Transformation T_WaWg;

    // now find the GT/EKF pairings
    int ctr = 0; //how many meas did we add this run?
    double ds = 0.0; // distance travelled
    ros::Time lastTime(0.0);

    MSF_INFO_STREAM("Processing measurements... Current start point: "<<startOffset<<"s into the bag.");

    for (; it_GT != view_GT.end(); ++it_GT)
    {
      GT_TYPE::ConstPtr trafo = it_GT->instantiate<GT_TYPE>();
      assert(trafo);

      // find closest timestamp
      ros::Time time_GT = trafo->header.stamp + dt;

      EVAL_TYPE::ConstPtr pose = it_EVAL->instantiate<EVAL_TYPE>();
      assert(pose);

      ros::Time time_EKF = pose->header.stamp;

      bool terminate = false;
      //get the measurement close to this GT value
      while (time_GT > time_EKF)
      {
        it_EVAL++;
        if (it_EVAL == view_EVAL.end())
        {
          terminate = true;
          MSF_INFO_STREAM("done. All EKF meas processed!");
          break;
        }
        pose = it_EVAL->instantiate<EVAL_TYPE>();
        assert(pose);
        time_EKF = pose->header.stamp;
      }
      if (terminate){
        break;
      }

      // add comparison value
      if (time_GT - start >= startOffset)
      {

        T_WaBa = sm::kinematics::Transformation(
            Eigen::Vector4d(-pose->pose.pose.orientation.x, -pose->pose.pose.orientation.y,
                            -pose->pose.pose.orientation.z, pose->pose.pose.orientation.w),
                            Eigen::Vector3d(pose->pose.pose.position.x, pose->pose.pose.position.y, pose->pose.pose.position.z));

        T_WgBg = sm::kinematics::Transformation(
            Eigen::Vector4d(-trafo->transform.rotation.x, -trafo->transform.rotation.y, -trafo->transform.rotation.z,
                            trafo->transform.rotation.w),
                            Eigen::Vector3d(trafo->transform.translation.x, trafo->transform.translation.y,
                                            trafo->transform.translation.z));

        // initial alignment
        if (ctr == 0)
        {
          T_WaWg = (T_WaBa) * T_BaBg * T_WgBg.inverse();
          T_WgBg_last = T_WgBg;
        }

        sm::kinematics::Transformation dT = T_WaBa * (T_WaWg * T_WgBg * T_BaBg.inverse()).inverse();
        sm::kinematics::Transformation T_WaBa_gt = (T_WaWg * T_WgBg * T_BaBg.inverse());

        T_WaBa_gt = sm::kinematics::Transformation(T_WaBa_gt.q().normalized(), T_WaBa_gt.t());
        dT = sm::kinematics::Transformation(dT.q().normalized(), dT.t());

        // update integral
        if (trafo)
        {
          ds += (T_WgBg.t() - T_WgBg_last.t()).norm();
          // store last GT transformation
          T_WgBg_last = T_WgBg;
        }
        else
        {
          // too noisy
          if ((T_WgBg * T_WgBg_last.inverse()).t().norm() > .1)
          {
            ds += (T_WgBg.t() - T_WgBg_last.t()).norm();
            //MSF_INFO_STREAM((T_WgBg*T_WgBg_last.inverse()).t().norm());
            // store last GT transformation
            T_WgBg_last = T_WgBg;
          }
        }
        Eigen::Vector3d dalpha;
        if (dT.q().head<3>().norm() > 1e-12)
        {
          dalpha = (asin(dT.q().head<3>().norm()) * 2 * dT.q().head<3>().normalized());
        }
        else
        {
          dalpha = 2 * dT.q().head<3>();
        }
        // g-vector alignment
        Eigen::Vector3d e_z_Wg(0, 0, 1);
        Eigen::Vector3d e_z_Wa = dT.C() * e_z_Wg;
        double dalpha_e_z = acos(std::min(1.0, e_z_Wg.dot(e_z_Wa)));

        if (fabs((time_GT - time_EKF).toSec()) < timeSyncThreshold
            && (time_EKF - lastTime).toSec() > trajectoryTimeDiscretization)
        {
          if (startOffset.toSec() == startTimeOffset)
          {
            poses_EVAL << T_WaBa.t().transpose() << ";" << std::endl;
            poses_GT << T_WgBg.t().transpose() << ";" << std::endl;
          }
          Eigen::Matrix<double, 6, 6> cov = getCovariance(pose);
          outfile << (time_GT - start).toSec() << " "
              << ds << " " << (T_WaBa.t() - T_WaBa_gt.t()).norm() << " " //translation
              << 2 * acos(std::min(1.0, fabs(dT.q()[3]))) << " " << dalpha_e_z << " " //orientation
              <<cov(0, 0)<<" "<<cov(1, 1)<<" "<<cov(2, 2)<<" " //position covariances
              <<cov(3, 3)<<" "<<cov(4, 4)<<" "<<cov(5, 5)<<";" //orientation covariances
              << std::endl;

          lastTime = time_EKF; // remember
        }

        // count comparisons
        ctr++;

      }
    }

    MSF_INFO_STREAM("Added "<<ctr<<" measurement edges.");

    //where in the bag should the next eval start
    startOffset += ros::Duration(timeDiscretization);


    if (ctr == 0 || singleRun) //any new measurements this run?
    {
      break;
    }
  }

  // cleanup
  bag.close();

  outfile << "];";
  outfile << "poses = [" << poses_EVAL.str() << "];" << std::endl;
  outfile << "poses_GT = [" << poses_GT.str() << "];" << std::endl;
  outfile.close();

  return 0;
}
Example #18
0
	{"xdigit",	SPECIAL	LC_CTYPE,	TYPE_CTP},
	{"blank",	SPECIAL	LC_CTYPE,	TYPE_CTP},

	{"tolower",	SPECIAL	LC_CTYPE,	TYPE_CNVL},
	{"toupper",	SPECIAL	LC_CTYPE,	TYPE_CNVU},

	{"collating-element",	0, 0, 0, LC_COLLATE,	TYPE_COLLEL},
	{"character-collation",	0, 1, 0, LC_COLLATE,	TYPE_COLLEL},

#define	dt(member, count) \
		(void *(*)(void))localedtconv, \
		offsetof(struct dtconv, member), \
		count, \
		LC_TIME, \
		TYPE_STR
	{"d_t_fmt",	dt(date_time_format, 1)},
	{"d_fmt",	dt(date_format, 1)},
	{"t_fmt",	dt(time_format, 1)},
	{"t_fmt_ampm",	dt(time_format_ampm, 1)},
	{"am_pm",	dt(am_string, 2)},
	{"day",		dt(day_names, 7)},
	{"abday",	dt(abbrev_day_names, 7)},
	{"mon",		dt(month_names, 12)},
	{"abmon",	dt(abbrev_month_names, 12)},
	{"era",		dt(era, 1)},
	{"era_d_fmt",	dt(era_d_fmt, 1)},
	{"era_d_t_fmt",	dt(era_d_t_fmt, 1)},
	{"era_t_fmt",	dt(era_t_fmt, 1)},
	{"alt_digits",	dt(alt_digits, 1)},

#undef dt
Example #19
0
Type objective_function<Type>::operator() ()
{
  DATA_STRING(distr);
  DATA_INTEGER(n);
  Type ans = 0;

  if (distr == "norm") {
    PARAMETER(mu);
    PARAMETER(sd);
    vector<Type> x = rnorm(n, mu, sd);
    ans -= dnorm(x, mu, sd, true).sum();
  }
  else if (distr == "gamma") {
    PARAMETER(shape);
    PARAMETER(scale);
    vector<Type> x = rgamma(n, shape, scale);
    ans -= dgamma(x, shape, scale, true).sum();
  }
  else if (distr == "pois") {
    PARAMETER(lambda);
    vector<Type> x = rpois(n, lambda);
    ans -= dpois(x, lambda, true).sum();
  }
  else if (distr == "compois") {
    PARAMETER(mode);
    PARAMETER(nu);
    vector<Type> x = rcompois(n, mode, nu);
    ans -= dcompois(x, mode, nu, true).sum();
  }
  else if (distr == "compois2") {
    PARAMETER(mean);
    PARAMETER(nu);
    vector<Type> x = rcompois2(n, mean, nu);
    ans -= dcompois2(x, mean, nu, true).sum();
  }
  else if (distr == "nbinom") {
    PARAMETER(size);
    PARAMETER(prob);
    vector<Type> x = rnbinom(n, size, prob);
    ans -= dnbinom(x, size, prob, true).sum();
  }
  else if (distr == "nbinom2") {
    PARAMETER(mu);
    PARAMETER(var);
    vector<Type> x = rnbinom2(n, mu, var);
    ans -= dnbinom2(x, mu, var, true).sum();
  }
  else if (distr == "exp") {
    PARAMETER(rate);
    vector<Type> x = rexp(n, rate);
    ans -= dexp(x, rate, true).sum();
  }
  else if (distr == "beta") {
    PARAMETER(shape1);
    PARAMETER(shape2);
    vector<Type> x = rbeta(n, shape1, shape2);
    ans -= dbeta(x, shape1, shape2, true).sum();
  }
  else if (distr == "f") {
    PARAMETER(df1);
    PARAMETER(df2);
    vector<Type> x = rf(n, df1, df2);
    ans -= df(x, df1, df2, true).sum();
  }
  else if (distr == "logis") {
    PARAMETER(location);
    PARAMETER(scale);
    vector<Type> x = rlogis(n, location, scale);
    ans -= dlogis(x, location, scale, true).sum();
  }
  else if (distr == "t") {
    PARAMETER(df);
    vector<Type> x = rt(n, df);
    ans -= dt(x, df, true).sum();
  }
  else if (distr == "weibull") {
    PARAMETER(shape);
    PARAMETER(scale);
    vector<Type> x = rweibull(n, shape, scale);
    ans -= dweibull(x, shape, scale, true).sum();
  }
  else if (distr == "AR1") {
    PARAMETER(phi);
    vector<Type> x(n);
    density::AR1(phi).simulate(x);
    ans += density::AR1(phi)(x);
  }
  else if (distr == "ARk") {
    PARAMETER_VECTOR(phi);
    vector<Type> x(n);
    density::ARk(phi).simulate(x);
    ans += density::ARk(phi)(x);
  }
  else if (distr == "MVNORM") {
    PARAMETER(phi);
    matrix<Type> Sigma(5,5);
    for(int i=0; i<Sigma.rows(); i++)
      for(int j=0; j<Sigma.rows(); j++)
        Sigma(i,j) = exp( -phi * abs(i - j) );
    density::MVNORM_t<Type> nldens = density::MVNORM(Sigma);
    for(int i = 0; i<n; i++) {
      vector<Type> x = nldens.simulate();
      ans += nldens(x);
    }
  }
  else if (distr == "SEPARABLE") {
    PARAMETER(phi1);
    PARAMETER_VECTOR(phi2);
    array<Type> x(100, 200);
    SEPARABLE( density::ARk(phi2), density::AR1(phi1) ).simulate(x);
    ans += SEPARABLE( density::ARk(phi2), density::AR1(phi1) )(x);
  }
  else if (distr == "GMRF") {
    PARAMETER(delta);
    matrix<Type> Q0(5, 5);
    Q0 <<
      1,-1, 0, 0, 0,
     -1, 2,-1, 0, 0,
      0,-1, 2,-1, 0,
      0, 0,-1, 2,-1,
      0, 0, 0,-1, 1;
    Q0.diagonal().array() += delta;
    Eigen::SparseMatrix<Type> Q = asSparseMatrix(Q0);
    vector<Type> x(5);
    for(int i = 0; i<n; i++) {
      density::GMRF(Q).simulate(x);
      ans += density::GMRF(Q)(x);
    }
  }
  else if (distr == "SEPARABLE_NESTED") {
    PARAMETER(phi1);
    PARAMETER(phi2);
    PARAMETER(delta);
    matrix<Type> Q0(5, 5);
    Q0 <<
      1,-1, 0, 0, 0,
     -1, 2,-1, 0, 0,
      0,-1, 2,-1, 0,
      0, 0,-1, 2,-1,
      0, 0, 0,-1, 1;
    Q0.diagonal().array() += delta;
    Eigen::SparseMatrix<Type> Q = asSparseMatrix(Q0);
    array<Type> x(5, 6, 7);
    for(int i = 0; i<n; i++) {
      SEPARABLE(density::AR1(phi2),
                SEPARABLE(density::AR1(phi1),
                          density::GMRF(Q) ) ).simulate(x);
      ans += SEPARABLE(density::AR1(phi2),
                       SEPARABLE(density::AR1(phi1),
                                 density::GMRF(Q) ) )(x);
    }
  }
  else error( ("Invalid distribution '" + distr + "'").c_str() );
  return ans;
}
Example #20
0
 template <> boost::posix_time::ptime as( SEXP dtsexp ) {
     Rcpp::Datetime dt(dtsexp);
     boost::posix_time::ptime pt(boost::gregorian::date(dt.getYear(), dt.getMonth(), dt.getDay()), 
                                 boost::posix_time::time_duration(dt.getHours(), dt.getMinutes(), dt.getSeconds(), dt.getMicroSeconds()/1000.0));
     return pt;
 }
Example #21
0
/**
* @brief	Handles timed events related to the King system.
*/
void CKingSystem::CheckKingTimer()
{
    // Get the current time.
    uint8	bCurMonth = g_localTime.tm_mon + 1,
            bCurDay = g_localTime.tm_mday,
            bCurHour = g_localTime.tm_hour,
            bCurMinute = g_localTime.tm_min;

    // If there's an ongoing coin or XP event...
    if (m_byNoahEvent || m_byExpEvent)
        CheckSpecialEvent();

    switch (m_byType)
    {
    case ELECTION_TYPE_NO_TERM:
    case ELECTION_TYPE_TERM_ENDED:
    {
        DateTime dt(m_sYear, m_byMonth, m_byDay, m_byHour, m_byMinute);

        // Nominations start a day before the election.
        dt.AddDays(-1);
        if (bCurMonth == dt.GetMonth()
                && bCurDay == dt.GetDay()
                && bCurHour == dt.GetHour()
                && bCurMinute == dt.GetMinute())
        {
            UpdateElectionStatus(ELECTION_TYPE_NOMINATION);

            g_pMain->SendFormattedResource(IDS_KING_RECOMMEND_TIME, m_byNation, false);
            // SendUDP_ElectionStatus(m_byType);

            ResetElectionLists();
            LoadRecommendList();
        }
    }
    break;

    case ELECTION_TYPE_NOMINATION:
    {
        DateTime dt(m_sYear, m_byMonth, m_byDay, m_byHour, m_byMinute);

        // Nominations last until an hour before the scheduled election time.
        dt.AddHours(-1);
        if (bCurMonth == dt.GetMonth()
                && bCurDay == dt.GetDay()
                && bCurHour == dt.GetHour()
                && bCurMinute == dt.GetMinute())
        {
            UpdateElectionStatus(ELECTION_TYPE_PRE_ELECTION);

            g_pMain->SendFormattedResource(IDS_KING_RECOMMEND_FINISH_TIME, m_byNation, false);
            // CheckRecommendList();
            // SendUDP_ElectionStatus(m_byType);
        }

        if (!(bCurMinute % 30) && !m_bSentFirstMessage)
        {
            m_bSentFirstMessage = true;
            g_pMain->SendFormattedResource(IDS_KING_PERIOD_OF_RECOMMEND_MESSAGE, m_byNation, true);
            break; // awkward, but official behaviour.
        }

        m_bSentFirstMessage = false;
    }
    break;

    // This state seems like it could be completely removed.
    // Leaving until the system's more complete, just in case.
    case ELECTION_TYPE_PRE_ELECTION:
    {
        DateTime dt(m_sYear, m_byMonth, m_byDay, m_byHour, m_byMinute);

        if (bCurMonth == dt.GetMonth()
                && bCurDay == dt.GetDay()
                && bCurHour == dt.GetHour()
                && bCurMinute == dt.GetMinute())
        {
            UpdateElectionStatus(ELECTION_TYPE_ELECTION);
            g_pMain->SendFormattedResource(IDS_KING_ELECTION_TIME, m_byNation, false);
            // SendUDP_ElectionStatus(m_byType);
        }
    }
    break;

    case ELECTION_TYPE_ELECTION:
    {
        DateTime dt(m_sYear, m_byMonth, m_byDay, m_byHour, m_byMinute);

        // Elections last for an hour.
        dt.AddHours(1);

        if (bCurMonth == dt.GetMonth()
                && bCurDay == dt.GetDay()
                && bCurHour == dt.GetHour()
                && bCurMinute == dt.GetMinute())
        {
            UpdateElectionStatus(ELECTION_TYPE_TERM_STARTED);
            // GetElectionResult();
            return;
        }

        if (!(bCurMinute % 30) && !m_bSentFirstMessage)
        {
            m_bSentFirstMessage = true;
            g_pMain->SendFormattedResource(IDS_KING_PERIOD_OF_ELECTION_MESSAGE, m_byNation, true);
            break; // awkward, but official behaviour.
        }

        m_bSentFirstMessage = false;
    }
    break;
    }

    switch (m_byImType)
    {
    case 1: // 47 hours after the impeachment time, call GetImpeachmentRequestResult()
    {
        DateTime dt(m_sImYear, m_byImMonth, m_byImDay, m_byImHour, m_byImMinute);
        dt.AddHours(47);
        if (bCurMonth == dt.GetMonth()
                && bCurDay == dt.GetDay()
                && bCurHour == dt.GetHour()
                && bCurMinute == dt.GetMinute())
        {
            // GetImpeachmentRequestResult();
        }
    } break;

    case 2: // 2 days (48 hours) after the impeachment time, set the impeachment type to 3
        // and send IDS_KING_IMPEACHMENT_ELECTION_MESSAGE as WAR_SYSTEM_CHAT
    {
        DateTime dt(m_sImYear, m_byImMonth, m_byImDay, m_byImHour, m_byImMinute);
        dt.AddDays(2);
        if (bCurMonth == dt.GetMonth()
                && bCurDay == dt.GetDay()
                && bCurHour == dt.GetHour()
                && bCurMinute == dt.GetMinute())
        {
            m_byImType = 3;
            g_pMain->SendFormattedResource(IDS_KING_IMPEACHMENT_ELECTION_MESSAGE, m_byNation, false);
        }
    }
    break;

    case 3: // 3 days (72 hours) after the impeachment time, set the impeachment type to 4
        // and call GetImpeachmentElectionResult()
    {
        DateTime dt(m_sImYear, m_byImMonth, m_byImDay, m_byImHour, m_byImMinute);
        dt.AddDays(3);
        if (bCurMonth == dt.GetMonth()
                && bCurDay == dt.GetDay()
                && bCurHour == dt.GetHour()
                && bCurMinute == dt.GetMinute())
        {
            m_byImType = 4;
            // GetImpeachmentElectionResult();
        }
    }
    break;
    }
}
Example #22
0
QObject *QDeclarativeVME::run(QDeclarativeVMEObjectStack &stack, 
                              QDeclarativeContextData *ctxt, 
                              QDeclarativeCompiledData *comp, 
                              int start, int count, 
                              const QBitField &bindingSkipList)
{
    Q_ASSERT(comp);
    Q_ASSERT(ctxt);
    const QList<QDeclarativeCompiledData::TypeReference> &types = comp->types;
    const QList<QString> &primitives = comp->primitives;
    const QList<QByteArray> &datas = comp->datas;
    const QList<QDeclarativeCompiledData::CustomTypeData> &customTypeData = comp->customTypeData;
    const QList<int> &intData = comp->intData;
    const QList<float> &floatData = comp->floatData;
    const QList<QDeclarativePropertyCache *> &propertyCaches = comp->propertyCaches;
    const QList<QDeclarativeParser::Object::ScriptBlock> &scripts = comp->scripts;
    const QList<QUrl> &urls = comp->urls;

    QDeclarativeEnginePrivate::SimpleList<QDeclarativeAbstractBinding> bindValues;
    QDeclarativeEnginePrivate::SimpleList<QDeclarativeParserStatus> parserStatus;

    QDeclarativeVMEStack<ListInstance> qliststack;

    vmeErrors.clear();
    QDeclarativeEnginePrivate *ep = QDeclarativeEnginePrivate::get(ctxt->engine);

    int status = -1;    //for dbus
    QDeclarativePropertyPrivate::WriteFlags flags = QDeclarativePropertyPrivate::BypassInterceptor |
                                                    QDeclarativePropertyPrivate::RemoveBindingOnAliasWrite;

    for (int ii = start; !isError() && ii < (start + count); ++ii) {
        const QDeclarativeInstruction &instr = comp->bytecode.at(ii);

        switch(instr.type) {
        case QDeclarativeInstruction::Init:
            {
                if (instr.init.bindingsSize) 
                    bindValues = QDeclarativeEnginePrivate::SimpleList<QDeclarativeAbstractBinding>(instr.init.bindingsSize);
                if (instr.init.parserStatusSize)
                    parserStatus = QDeclarativeEnginePrivate::SimpleList<QDeclarativeParserStatus>(instr.init.parserStatusSize);
                if (instr.init.contextCache != -1) 
                    ctxt->setIdPropertyData(comp->contextCaches.at(instr.init.contextCache));
                if (instr.init.compiledBinding != -1) 
                    ctxt->optimizedBindings = new QDeclarativeCompiledBindings(datas.at(instr.init.compiledBinding).constData(), ctxt, comp);
            }
            break;

        case QDeclarativeInstruction::CreateObject:
            {
                QBitField bindings;
                if (instr.create.bindingBits != -1) {
                    const QByteArray &bits = datas.at(instr.create.bindingBits);
                    bindings = QBitField((const quint32*)bits.constData(),
                                         bits.size() * 8);
                }
                if (stack.isEmpty())
                    bindings = bindings.united(bindingSkipList);

                QObject *o = 
                    types.at(instr.create.type).createInstance(ctxt, bindings, &vmeErrors);

                if (!o) {
                    VME_EXCEPTION(QCoreApplication::translate("QDeclarativeVME","Unable to create object of type %1").arg(QString::fromLatin1(types.at(instr.create.type).className)));
                }

                QDeclarativeData *ddata = QDeclarativeData::get(o);
                Q_ASSERT(ddata);

                if (stack.isEmpty()) {
                    if (ddata->context) {
                        Q_ASSERT(ddata->context != ctxt);
                        Q_ASSERT(ddata->outerContext);
                        Q_ASSERT(ddata->outerContext != ctxt);
                        QDeclarativeContextData *c = ddata->context;
                        while (c->linkedContext) c = c->linkedContext;
                        c->linkedContext = ctxt;
                    } else {
                        ctxt->addObject(o);
                    }

                    ddata->ownContext = true;
                } else if (!ddata->context) {
                    ctxt->addObject(o);
                }

                ddata->setImplicitDestructible();
                ddata->outerContext = ctxt;
                ddata->lineNumber = instr.line;
                ddata->columnNumber = instr.create.column;

                if (instr.create.data != -1) {
                    QDeclarativeCustomParser *customParser =
                        types.at(instr.create.type).type->customParser();
                    customParser->setCustomData(o, datas.at(instr.create.data));
                }
                if (!stack.isEmpty()) {
                    QObject *parent = stack.top();
                    if (o->isWidgetType()) { 
                        QWidget *widget = static_cast<QWidget*>(o); 
                        if (parent->isWidgetType()) { 
                            QWidget *parentWidget = static_cast<QWidget*>(parent); 
                            widget->setParent(parentWidget); 
                        } else { 
                            // TODO: parent might be a layout 
                        } 
                    } else { 
			    QDeclarative_setParent_noEvent(o, parent);
                    } 
                }
                stack.push(o);
            }
            break;

        case QDeclarativeInstruction::CreateSimpleObject:
            {
                QObject *o = (QObject *)operator new(instr.createSimple.typeSize + 
                                                     sizeof(QDeclarativeData));   
                ::memset(o, 0, instr.createSimple.typeSize + sizeof(QDeclarativeData));
                instr.createSimple.create(o);

                QDeclarativeData *ddata = (QDeclarativeData *)(((const char *)o) + instr.createSimple.typeSize);
                const QDeclarativeCompiledData::TypeReference &ref = types.at(instr.createSimple.type);
                if (!ddata->propertyCache && ref.typePropertyCache) {
                    ddata->propertyCache = ref.typePropertyCache;
                    ddata->propertyCache->addref();
                }
                ddata->lineNumber = instr.line;
                ddata->columnNumber = instr.createSimple.column;

                QObjectPrivate::get(o)->declarativeData = ddata;                                                      
                ddata->context = ddata->outerContext = ctxt;
                ddata->nextContextObject = ctxt->contextObjects; 
                if (ddata->nextContextObject) 
                    ddata->nextContextObject->prevContextObject = &ddata->nextContextObject; 
                ddata->prevContextObject = &ctxt->contextObjects; 
                ctxt->contextObjects = ddata; 

                QObject *parent = stack.top();                                                                    
                QDeclarative_setParent_noEvent(o, parent);                                                        

                stack.push(o);
            }
            break;

        case QDeclarativeInstruction::SetId:
            {
                QObject *target = stack.top();
                ctxt->setIdProperty(instr.setId.index, target);
            }
            break;


        case QDeclarativeInstruction::SetDefault:
            {
                ctxt->contextObject = stack.top();
            }
            break;

        case QDeclarativeInstruction::CreateComponent:
            {
                QDeclarativeComponent *qcomp = 
                    new QDeclarativeComponent(ctxt->engine, comp, ii + 1, instr.createComponent.count,
                                              stack.isEmpty() ? 0 : stack.top());

                QDeclarativeData *ddata = QDeclarativeData::get(qcomp, true);
                Q_ASSERT(ddata);

                ctxt->addObject(qcomp);

                if (stack.isEmpty()) 
                    ddata->ownContext = true;

                ddata->setImplicitDestructible();
                ddata->outerContext = ctxt;
                ddata->lineNumber = instr.line;
                ddata->columnNumber = instr.create.column;

                QDeclarativeComponentPrivate::get(qcomp)->creationContext = ctxt;

                stack.push(qcomp);
                ii += instr.createComponent.count;
            }
            break;

        case QDeclarativeInstruction::StoreMetaObject:
            {
                QObject *target = stack.top();

                QMetaObject mo;
                const QByteArray &metadata = datas.at(instr.storeMeta.data);
                QMetaObjectBuilder::fromRelocatableData(&mo, 0, metadata);

                const QDeclarativeVMEMetaData *data = 
                    (const QDeclarativeVMEMetaData *)datas.at(instr.storeMeta.aliasData).constData();

                (void)new QDeclarativeVMEMetaObject(target, &mo, data, comp);

                if (instr.storeMeta.propertyCache != -1) {
                    QDeclarativeData *ddata = QDeclarativeData::get(target, true);
                    if (ddata->propertyCache) ddata->propertyCache->release();
                    ddata->propertyCache = propertyCaches.at(instr.storeMeta.propertyCache);
                    ddata->propertyCache->addref();
                }
            }
            break;

        case QDeclarativeInstruction::StoreVariant:
            {
                QObject *target = stack.top();
                CLEAN_PROPERTY(target, instr.storeString.propertyIndex);

                // XXX - can be more efficient
                QVariant v = QDeclarativeStringConverters::variantFromString(primitives.at(instr.storeString.value));
                void *a[] = { &v, 0, &status, &flags };
                QMetaObject::metacall(target, QMetaObject::WriteProperty, 
                                      instr.storeString.propertyIndex, a);
            }
            break;

        case QDeclarativeInstruction::StoreVariantInteger:
            {
                QObject *target = stack.top();
                CLEAN_PROPERTY(target, instr.storeString.propertyIndex);

                QVariant v(instr.storeInteger.value);
                void *a[] = { &v, 0, &status, &flags };
                QMetaObject::metacall(target, QMetaObject::WriteProperty, 
                                      instr.storeString.propertyIndex, a);
            }
            break;

        case QDeclarativeInstruction::StoreVariantDouble:
            {
                QObject *target = stack.top();
                CLEAN_PROPERTY(target, instr.storeString.propertyIndex);

                QVariant v(instr.storeDouble.value);
                void *a[] = { &v, 0, &status, &flags };
                QMetaObject::metacall(target, QMetaObject::WriteProperty, 
                                      instr.storeString.propertyIndex, a);
            }
            break;

        case QDeclarativeInstruction::StoreVariantBool:
            {
                QObject *target = stack.top();
                CLEAN_PROPERTY(target, instr.storeString.propertyIndex);

                QVariant v(instr.storeBool.value);
                void *a[] = { &v, 0, &status, &flags };
                QMetaObject::metacall(target, QMetaObject::WriteProperty, 
                                      instr.storeString.propertyIndex, a);
            }
            break;

        case QDeclarativeInstruction::StoreString:
            {
                QObject *target = stack.top();
                CLEAN_PROPERTY(target, instr.storeString.propertyIndex);

                void *a[] = { (void *)&primitives.at(instr.storeString.value), 0, &status, &flags };
                QMetaObject::metacall(target, QMetaObject::WriteProperty, 
                                      instr.storeString.propertyIndex, a);
            }
            break;

        case QDeclarativeInstruction::StoreUrl:
            {
                QObject *target = stack.top();
                CLEAN_PROPERTY(target, instr.storeUrl.propertyIndex);

                void *a[] = { (void *)&urls.at(instr.storeUrl.value), 0, &status, &flags };
                QMetaObject::metacall(target, QMetaObject::WriteProperty, 
                                      instr.storeUrl.propertyIndex, a);
            }
            break;

        case QDeclarativeInstruction::StoreFloat:
            {
                QObject *target = stack.top();
                CLEAN_PROPERTY(target, instr.storeFloat.propertyIndex);

                float f = instr.storeFloat.value;
                void *a[] = { &f, 0, &status, &flags };
                QMetaObject::metacall(target, QMetaObject::WriteProperty,
                                      instr.storeFloat.propertyIndex, a);
            }
            break;

        case QDeclarativeInstruction::StoreDouble:
            {
                QObject *target = stack.top();
                CLEAN_PROPERTY(target, instr.storeDouble.propertyIndex);

                double d = instr.storeDouble.value;
                void *a[] = { &d, 0, &status, &flags };
                QMetaObject::metacall(target, QMetaObject::WriteProperty,
                                      instr.storeDouble.propertyIndex, a);
            }
            break;

        case QDeclarativeInstruction::StoreBool:
            {
                QObject *target = stack.top();
                CLEAN_PROPERTY(target, instr.storeBool.propertyIndex);

                void *a[] = { (void *)&instr.storeBool.value, 0, &status, &flags };
                QMetaObject::metacall(target, QMetaObject::WriteProperty, 
                                      instr.storeBool.propertyIndex, a);
            }
            break;

        case QDeclarativeInstruction::StoreInteger:
            {
                QObject *target = stack.top();
                CLEAN_PROPERTY(target, instr.storeInteger.propertyIndex);

                void *a[] = { (void *)&instr.storeInteger.value, 0, &status, &flags };
                QMetaObject::metacall(target, QMetaObject::WriteProperty, 
                                      instr.storeInteger.propertyIndex, a);
            }
            break;

        case QDeclarativeInstruction::StoreColor:
            {
                QObject *target = stack.top();
                CLEAN_PROPERTY(target, instr.storeColor.propertyIndex);

                QColor c = QColor::fromRgba(instr.storeColor.value);
                void *a[] = { &c, 0, &status, &flags };
                QMetaObject::metacall(target, QMetaObject::WriteProperty, 
                                      instr.storeColor.propertyIndex, a);
            }
            break;

        case QDeclarativeInstruction::StoreDate:
            {
                QObject *target = stack.top();
                CLEAN_PROPERTY(target, instr.storeDate.propertyIndex);

                QDate d = QDate::fromJulianDay(instr.storeDate.value);
                void *a[] = { &d, 0, &status, &flags };
                QMetaObject::metacall(target, QMetaObject::WriteProperty, 
                                      instr.storeDate.propertyIndex, a);
            }
            break;

        case QDeclarativeInstruction::StoreTime:
            {
                QObject *target = stack.top();
                CLEAN_PROPERTY(target, instr.storeTime.propertyIndex);

                QTime t;
                t.setHMS(intData.at(instr.storeTime.valueIndex),
                         intData.at(instr.storeTime.valueIndex+1),
                         intData.at(instr.storeTime.valueIndex+2),
                         intData.at(instr.storeTime.valueIndex+3));
                void *a[] = { &t, 0, &status, &flags };
                QMetaObject::metacall(target, QMetaObject::WriteProperty, 
                                      instr.storeTime.propertyIndex, a);
            }
            break;

        case QDeclarativeInstruction::StoreDateTime:
            {
                QObject *target = stack.top();
                CLEAN_PROPERTY(target, instr.storeDateTime.propertyIndex);

                QTime t;
                t.setHMS(intData.at(instr.storeDateTime.valueIndex+1),
                         intData.at(instr.storeDateTime.valueIndex+2),
                         intData.at(instr.storeDateTime.valueIndex+3),
                         intData.at(instr.storeDateTime.valueIndex+4));
                QDateTime dt(QDate::fromJulianDay(intData.at(instr.storeDateTime.valueIndex)), t);
                void *a[] = { &dt, 0, &status, &flags };
                QMetaObject::metacall(target, QMetaObject::WriteProperty,
                                      instr.storeDateTime.propertyIndex, a);
            }
            break;

        case QDeclarativeInstruction::StorePoint:
            {
                QObject *target = stack.top();
                CLEAN_PROPERTY(target, instr.storeRealPair.propertyIndex);

                QPoint p = QPointF(floatData.at(instr.storeRealPair.valueIndex),
                                   floatData.at(instr.storeRealPair.valueIndex+1)).toPoint();
                void *a[] = { &p, 0, &status, &flags };
                QMetaObject::metacall(target, QMetaObject::WriteProperty, 
                                      instr.storeRealPair.propertyIndex, a);
            }
            break;

        case QDeclarativeInstruction::StorePointF:
            {
                QObject *target = stack.top();
                CLEAN_PROPERTY(target, instr.storeRealPair.propertyIndex);

                QPointF p(floatData.at(instr.storeRealPair.valueIndex),
                          floatData.at(instr.storeRealPair.valueIndex+1));
                void *a[] = { &p, 0, &status, &flags };
                QMetaObject::metacall(target, QMetaObject::WriteProperty, 
                                      instr.storeRealPair.propertyIndex, a);
            }
            break;

        case QDeclarativeInstruction::StoreSize:
            {
                QObject *target = stack.top();
                CLEAN_PROPERTY(target, instr.storeRealPair.propertyIndex);

                QSize p = QSizeF(floatData.at(instr.storeRealPair.valueIndex),
                                 floatData.at(instr.storeRealPair.valueIndex+1)).toSize();
                void *a[] = { &p, 0, &status, &flags };
                QMetaObject::metacall(target, QMetaObject::WriteProperty, 
                                      instr.storeRealPair.propertyIndex, a);
            }
            break;

        case QDeclarativeInstruction::StoreSizeF:
            {
                QObject *target = stack.top();
                CLEAN_PROPERTY(target, instr.storeRealPair.propertyIndex);

                QSizeF s(floatData.at(instr.storeRealPair.valueIndex),
                         floatData.at(instr.storeRealPair.valueIndex+1));
                void *a[] = { &s, 0, &status, &flags };
                QMetaObject::metacall(target, QMetaObject::WriteProperty, 
                                      instr.storeRealPair.propertyIndex, a);
            }
            break;

        case QDeclarativeInstruction::StoreRect:
            {
                QObject *target = stack.top();
                CLEAN_PROPERTY(target, instr.storeRect.propertyIndex);

                QRect r = QRectF(floatData.at(instr.storeRect.valueIndex),
                                 floatData.at(instr.storeRect.valueIndex+1),
                                 floatData.at(instr.storeRect.valueIndex+2),
                                 floatData.at(instr.storeRect.valueIndex+3)).toRect();
                void *a[] = { &r, 0, &status, &flags };
                QMetaObject::metacall(target, QMetaObject::WriteProperty, 
                                      instr.storeRect.propertyIndex, a);
            }
            break;

        case QDeclarativeInstruction::StoreRectF:
            {
                QObject *target = stack.top();
                CLEAN_PROPERTY(target, instr.storeRect.propertyIndex);

                QRectF r(floatData.at(instr.storeRect.valueIndex),
                         floatData.at(instr.storeRect.valueIndex+1),
                         floatData.at(instr.storeRect.valueIndex+2),
                         floatData.at(instr.storeRect.valueIndex+3));
                void *a[] = { &r, 0, &status, &flags };
                QMetaObject::metacall(target, QMetaObject::WriteProperty, 
                                      instr.storeRect.propertyIndex, a);
            }
            break;

        case QDeclarativeInstruction::StoreVector3D:
            {
                QObject *target = stack.top();
                CLEAN_PROPERTY(target, instr.storeVector3D.propertyIndex);

                QVector3D p(floatData.at(instr.storeVector3D.valueIndex),
                            floatData.at(instr.storeVector3D.valueIndex+1),
                            floatData.at(instr.storeVector3D.valueIndex+2));
                void *a[] = { &p, 0, &status, &flags };
                QMetaObject::metacall(target, QMetaObject::WriteProperty, 
                                      instr.storeVector3D.propertyIndex, a);
            }
            break;

        case QDeclarativeInstruction::StoreObject:
            {
                QObject *assignObj = stack.pop();
                QObject *target = stack.top();
                CLEAN_PROPERTY(target, instr.storeObject.propertyIndex);

                void *a[] = { (void *)&assignObj, 0, &status, &flags };
                QMetaObject::metacall(target, QMetaObject::WriteProperty, 
                                      instr.storeObject.propertyIndex, a);
            }
            break;


        case QDeclarativeInstruction::AssignCustomType:
            {
                QObject *target = stack.top();
                CLEAN_PROPERTY(target, instr.assignCustomType.propertyIndex);

                QDeclarativeCompiledData::CustomTypeData data = customTypeData.at(instr.assignCustomType.valueIndex);
                const QString &primitive = primitives.at(data.index);
                QDeclarativeMetaType::StringConverter converter = 
                    QDeclarativeMetaType::customStringConverter(data.type);
                QVariant v = (*converter)(primitive);

                QMetaProperty prop = 
                        target->metaObject()->property(instr.assignCustomType.propertyIndex);
                if (v.isNull() || ((int)prop.type() != data.type && prop.userType() != data.type)) 
                    VME_EXCEPTION(QCoreApplication::translate("QDeclarativeVME","Cannot assign value %1 to property %2").arg(primitive).arg(QString::fromUtf8(prop.name())));

                void *a[] = { (void *)v.data(), 0, &status, &flags };
                QMetaObject::metacall(target, QMetaObject::WriteProperty, 
                                      instr.assignCustomType.propertyIndex, a);
            }
            break;

        case QDeclarativeInstruction::AssignSignalObject:
            {
                // XXX optimize

                QObject *assign = stack.pop();
                QObject *target = stack.top();
                int sigIdx = instr.assignSignalObject.signal;
                const QByteArray &pr = datas.at(sigIdx);

                QDeclarativeProperty prop(target, QString::fromUtf8(pr));
                if (prop.type() & QDeclarativeProperty::SignalProperty) {

                    QMetaMethod method = QDeclarativeMetaType::defaultMethod(assign);
                    if (method.signature() == 0)
                        VME_EXCEPTION(QCoreApplication::translate("QDeclarativeVME","Cannot assign object type %1 with no default method").arg(QString::fromLatin1(assign->metaObject()->className())));

                    if (!QMetaObject::checkConnectArgs(prop.method().signature(), method.signature()))
                        VME_EXCEPTION(QCoreApplication::translate("QDeclarativeVME","Cannot connect mismatched signal/slot %1 %vs. %2").arg(QString::fromLatin1(method.signature())).arg(QString::fromLatin1(prop.method().signature())));

                    QDeclarativePropertyPrivate::connect(target, prop.index(), assign, method.methodIndex());

                } else {
                    VME_EXCEPTION(QCoreApplication::translate("QDeclarativeVME","Cannot assign an object to signal property %1").arg(QString::fromUtf8(pr)));
                }


            }
            break;

        case QDeclarativeInstruction::StoreSignal:
            {
                QObject *target = stack.top();
                QObject *context = stack.at(stack.count() - 1 - instr.storeSignal.context);

                QMetaMethod signal = target->metaObject()->method(instr.storeSignal.signalIndex);

                QDeclarativeBoundSignal *bs = new QDeclarativeBoundSignal(target, signal, target);
                QDeclarativeExpression *expr = 
                    new QDeclarativeExpression(ctxt, context, primitives.at(instr.storeSignal.value));
                expr->setSourceLocation(comp->name, instr.line);
                static_cast<QDeclarativeExpressionPrivate *>(QObjectPrivate::get(expr))->name = datas.at(instr.storeSignal.name);
                bs->setExpression(expr);
            }
            break;

        case QDeclarativeInstruction::StoreImportedScript:
            {
                ctxt->addImportedScript(scripts.at(instr.storeScript.value));
            }
            break;

        case QDeclarativeInstruction::StoreScriptString:
            {
                QObject *target = stack.top();
                QObject *scope = stack.at(stack.count() - 1 - instr.storeScriptString.scope);
                QDeclarativeScriptString ss;
                ss.setContext(ctxt->asQDeclarativeContext());
                ss.setScopeObject(scope);
                ss.setScript(primitives.at(instr.storeScriptString.value));

                void *a[] = { &ss, 0, &status, &flags };
                QMetaObject::metacall(target, QMetaObject::WriteProperty, 
                                      instr.storeScriptString.propertyIndex, a);
            }
            break;

        case QDeclarativeInstruction::BeginObject:
            {
                QObject *target = stack.top();
                QDeclarativeParserStatus *status = reinterpret_cast<QDeclarativeParserStatus *>(reinterpret_cast<char *>(target) + instr.begin.castValue);
                parserStatus.append(status);
                status->d = &parserStatus.values[parserStatus.count - 1];

                status->classBegin();
            }
            break;

        case QDeclarativeInstruction::StoreBinding:
        case QDeclarativeInstruction::StoreBindingOnAlias:
            {
                QObject *target = 
                    stack.at(stack.count() - 1 - instr.assignBinding.owner);
                QObject *context = 
                    stack.at(stack.count() - 1 - instr.assignBinding.context);

                QDeclarativeProperty mp = 
                    QDeclarativePropertyPrivate::restore(datas.at(instr.assignBinding.property), target, ctxt);

                int coreIndex = mp.index();

                if ((stack.count() - instr.assignBinding.owner) == 1 && bindingSkipList.testBit(coreIndex)) 
                    break;

                QDeclarativeBinding *bind = new QDeclarativeBinding((void *)datas.at(instr.assignBinding.value).constData(), comp, context, ctxt, comp->name, instr.line, 0);
                bindValues.append(bind);
                bind->m_mePtr = &bindValues.values[bindValues.count - 1];
                bind->setTarget(mp);

                if (instr.type == QDeclarativeInstruction::StoreBindingOnAlias) {
                    QDeclarativeAbstractBinding *old = QDeclarativePropertyPrivate::setBindingNoEnable(target, coreIndex, QDeclarativePropertyPrivate::valueTypeCoreIndex(mp), bind);
                    if (old) { old->destroy(); }
                } else {
                    bind->addToObject(target, QDeclarativePropertyPrivate::bindingIndex(mp));
                }
            }
            break;

        case QDeclarativeInstruction::StoreCompiledBinding:
            {
                QObject *target = 
                    stack.at(stack.count() - 1 - instr.assignBinding.owner);
                QObject *scope = 
                    stack.at(stack.count() - 1 - instr.assignBinding.context);

                int property = instr.assignBinding.property;
                if (stack.count() == 1 && bindingSkipList.testBit(property & 0xFFFF))  
                    break;

                QDeclarativeAbstractBinding *binding = 
                    ctxt->optimizedBindings->configBinding(instr.assignBinding.value, target, scope, property);
                bindValues.append(binding);
                binding->m_mePtr = &bindValues.values[bindValues.count - 1];
                binding->addToObject(target, property);
            }
            break;

        case QDeclarativeInstruction::StoreValueSource:
            {
                QObject *obj = stack.pop();
                QDeclarativePropertyValueSource *vs = reinterpret_cast<QDeclarativePropertyValueSource *>(reinterpret_cast<char *>(obj) + instr.assignValueSource.castValue);
                QObject *target = stack.at(stack.count() - 1 - instr.assignValueSource.owner);

                QDeclarativeProperty prop = 
                    QDeclarativePropertyPrivate::restore(datas.at(instr.assignValueSource.property), target, ctxt);
                obj->setParent(target);
                vs->setTarget(prop);
            }
            break;

        case QDeclarativeInstruction::StoreValueInterceptor:
            {
                QObject *obj = stack.pop();
                QDeclarativePropertyValueInterceptor *vi = reinterpret_cast<QDeclarativePropertyValueInterceptor *>(reinterpret_cast<char *>(obj) + instr.assignValueInterceptor.castValue);
                QObject *target = stack.at(stack.count() - 1 - instr.assignValueInterceptor.owner);
                QDeclarativeProperty prop = 
                    QDeclarativePropertyPrivate::restore(datas.at(instr.assignValueInterceptor.property), target, ctxt);
                obj->setParent(target);
                vi->setTarget(prop);
                QDeclarativeVMEMetaObject *mo = static_cast<QDeclarativeVMEMetaObject *>((QMetaObject*)target->metaObject());
                mo->registerInterceptor(prop.index(), QDeclarativePropertyPrivate::valueTypeCoreIndex(prop), vi);
            }
            break;

        case QDeclarativeInstruction::StoreObjectQList:
            {
                QObject *assign = stack.pop();

                const ListInstance &list = qliststack.top();
                list.qListProperty.append((QDeclarativeListProperty<void>*)&list.qListProperty, assign);
            }
            break;

        case QDeclarativeInstruction::AssignObjectList:
            {
                // This is only used for assigning interfaces
                QObject *assign = stack.pop();
                const ListInstance &list = qliststack.top();

                int type = list.type;

                void *ptr = 0;

                const char *iid = QDeclarativeMetaType::interfaceIId(type);
                if (iid) 
                    ptr = assign->qt_metacast(iid);
                if (!ptr) 
                    VME_EXCEPTION(QCoreApplication::translate("QDeclarativeVME","Cannot assign object to list"));


                list.qListProperty.append((QDeclarativeListProperty<void>*)&list.qListProperty, ptr);
            }
            break;

        case QDeclarativeInstruction::StoreVariantObject:
            {
                QObject *assign = stack.pop();
                QObject *target = stack.top();
                CLEAN_PROPERTY(target, instr.storeObject.propertyIndex);

                QVariant v = QVariant::fromValue(assign);
                void *a[] = { &v, 0, &status, &flags };
                QMetaObject::metacall(target, QMetaObject::WriteProperty, 
                                      instr.storeObject.propertyIndex, a);
            }
            break;

        case QDeclarativeInstruction::StoreInterface:
            {
                QObject *assign = stack.pop();
                QObject *target = stack.top();
                CLEAN_PROPERTY(target, instr.storeObject.propertyIndex);

                int coreIdx = instr.storeObject.propertyIndex;
                QMetaProperty prop = target->metaObject()->property(coreIdx);
                int t = prop.userType();
                const char *iid = QDeclarativeMetaType::interfaceIId(t);
                bool ok = false;
                if (iid) {
                    void *ptr = assign->qt_metacast(iid);
                    if (ptr) {
                        void *a[] = { &ptr, 0, &status, &flags };
                        QMetaObject::metacall(target, 
                                              QMetaObject::WriteProperty,
                                              coreIdx, a);
                        ok = true;
                    }
                } 

                if (!ok) 
                    VME_EXCEPTION(QCoreApplication::translate("QDeclarativeVME","Cannot assign object to interface property"));
            }
            break;
            
        case QDeclarativeInstruction::FetchAttached:
            {
                QObject *target = stack.top();

                QObject *qmlObject = qmlAttachedPropertiesObjectById(instr.fetchAttached.id, target);

                if (!qmlObject)
                    VME_EXCEPTION(QCoreApplication::translate("QDeclarativeVME","Unable to create attached object"));

                stack.push(qmlObject);
            }
            break;

        case QDeclarativeInstruction::FetchQList:
            {
                QObject *target = stack.top();

                qliststack.push(ListInstance(instr.fetchQmlList.type));

                void *a[1];
                a[0] = (void *)&(qliststack.top().qListProperty);
                QMetaObject::metacall(target, QMetaObject::ReadProperty, 
                                      instr.fetchQmlList.property, a);
            }
            break;

        case QDeclarativeInstruction::FetchObject:
            {
                QObject *target = stack.top();

                QObject *obj = 0;
                // NOTE: This assumes a cast to QObject does not alter the 
                // object pointer
                void *a[1];
                a[0] = &obj;
                QMetaObject::metacall(target, QMetaObject::ReadProperty, 
                                      instr.fetch.property, a);

                if (!obj)
                    VME_EXCEPTION(QCoreApplication::translate("QDeclarativeVME","Cannot set properties on %1 as it is null").arg(QString::fromUtf8(target->metaObject()->property(instr.fetch.property).name())));

                stack.push(obj);
            }
            break;

        case QDeclarativeInstruction::PopQList:
            {
                qliststack.pop();
            }
            break;

        case QDeclarativeInstruction::Defer:
            {
                if (instr.defer.deferCount) {
                    QObject *target = stack.top();
                    QDeclarativeData *data = 
                        QDeclarativeData::get(target, true);
                    comp->addref();
                    data->deferredComponent = comp;
                    data->deferredIdx = ii;
                    ii += instr.defer.deferCount;
                }
            }
            break;

        case QDeclarativeInstruction::PopFetchedObject:
            {
                stack.pop();
            }
            break;

        case QDeclarativeInstruction::FetchValueType:
            {
                QObject *target = stack.top();

                if (instr.fetchValue.bindingSkipList != 0) {
                    // Possibly need to clear bindings
                    QDeclarativeData *targetData = QDeclarativeData::get(target);
                    if (targetData) {
                        QDeclarativeAbstractBinding *binding = 
                            QDeclarativePropertyPrivate::binding(target, instr.fetchValue.property, -1);

                        if (binding && binding->bindingType() != QDeclarativeAbstractBinding::ValueTypeProxy) {
                            QDeclarativePropertyPrivate::setBinding(target, instr.fetchValue.property, -1, 0);
                            binding->destroy();
                        } else if (binding) {
                            QDeclarativeValueTypeProxyBinding *proxy = 
                                static_cast<QDeclarativeValueTypeProxyBinding *>(binding);
                            proxy->removeBindings(instr.fetchValue.bindingSkipList);
                        }
                    }
                }

                QDeclarativeValueType *valueHandler = ep->valueTypes[instr.fetchValue.type];
                valueHandler->read(target, instr.fetchValue.property);
                stack.push(valueHandler);
            }
            break;

        case QDeclarativeInstruction::PopValueType:
            {
                QDeclarativeValueType *valueHandler = 
                    static_cast<QDeclarativeValueType *>(stack.pop());
                QObject *target = stack.top();
                valueHandler->write(target, instr.fetchValue.property, 
                                    QDeclarativePropertyPrivate::BypassInterceptor);
            }
            break;

        default:
            qFatal("QDeclarativeCompiledData: Internal error - unknown instruction %d", instr.type);
            break;
        }
    }

    if (isError()) {
        if (!stack.isEmpty()) {
            delete stack.at(0); // ### What about failures in deferred creation?
        } else {
            ctxt->destroy();
        }

        QDeclarativeEnginePrivate::clear(bindValues);
        QDeclarativeEnginePrivate::clear(parserStatus);
        return 0;
    }

    if (bindValues.count)
        ep->bindValues << bindValues;
    else if (bindValues.values)
        bindValues.clear();

    if (parserStatus.count)
        ep->parserStatus << parserStatus;
    else if (parserStatus.values)
        parserStatus.clear();

    Q_ASSERT(stack.count() == 1);
    return stack.top();
}
Example #23
0
File: 204.c Project: Ravenbrook/mps
static void test(void *stack_pointer)
{
 mps_thr_t thread;
 unsigned long mins;
 mps_word_t dep, frag;

 cdie(mps_arena_create(&arena, mps_arena_class_vm(), (size_t) (1024*1024*100)), "create arena");
 cdie(mps_thread_reg(&thread, arena), "register thread");

 mins = sizeof(int);

 dep = 100;

 for (frag = 40; frag >= 5; frag = (frag >> 1)) {

 comment("Frag: %i", frag);

 dt(SEQ, 8, 8, 9, dep, frag, 8, 9, 5, ITERATIONS);
 dt(RANGAP, 64, 64, 64, dep, frag, 8, 128, 100, ITERATIONS);

 dt(DUMMY, 8, 32, 64, dep, frag, 8, 64, 1000, ITERATIONS);
 dt(SEQ, 8, 32, 64, dep, frag, 8, 64, 1000, ITERATIONS);
 dt(RAN, 8, 32, 64, dep, frag, 8, 64, 1000, ITERATIONS);
 dt(SEQGAP, 8, 32, 64, dep, frag, 8, 64, 1000, ITERATIONS);
 dt(RANGAP, 8, 32, 64, dep, frag, 8, 64, 1000, ITERATIONS);

 dt(DUMMY, 100, 116, 132, dep, frag, 100, 132, 1000, ITERATIONS);
 dt(SEQ, 100, 116, 132, dep, frag, 100, 132, 1000, ITERATIONS);
 dt(RAN, 100, 116, 132, dep, frag, 100, 132, 1000, ITERATIONS);
 dt(SEQGAP, 100, 116, 132, dep, frag, 100, 132, 1000, ITERATIONS);
 dt(RANGAP, 100, 116, 132, dep, frag, 100, 132, 1000, ITERATIONS);

 dt(DUMMY, mins, 60*1024, 120*1024, dep, frag, mins, 128*1024, 100, ITERATIONS);
 dt(SEQ, mins, 60*1024, 120*1024, dep, frag, mins, 128*1024, 100, ITERATIONS);
 dt(RAN, mins, 60*1024, 120*1024, dep, frag, mins, 128*1024, 100, ITERATIONS);
 dt(SEQGAP, mins, 60*1024, 120*1024, dep, frag, mins, 128*1024, 100, ITERATIONS);
 dt(RANGAP, mins, 60*1024, 120*1024, dep, frag, mins, 128*1024, 100, ITERATIONS);

/* try again using exceptional obj for anything over 16K */

 dt(DUMMY, mins, 8*1024, 16*1024, dep, frag, mins, 128*1024, 100, ITERATIONS);
 dt(SEQ, mins, 8*1024, 16*1024, dep, frag, mins, 128*1024, 100, ITERATIONS);
 dt(RAN, mins, 8*1024, 16*1024, dep, frag, mins, 128*1024, 100, ITERATIONS);
 dt(SEQGAP, mins, 8*1024, 16*1024, dep, frag, mins, 128*1024, 100, ITERATIONS);
 dt(RANGAP, mins, 8*1024, 16*1024, dep, frag, mins, 128*1024, 100, ITERATIONS);

 }

 mps_thread_dereg(thread);
 mps_arena_destroy(arena);
}
Example #24
0
int main(int argc, char * argv [])
{
  try
  {
     ulxr::intializeLog4J(argv[0]);

     ULXR_COUT << ULXR_PCHAR("sizeof(<string>): " << sizeof(ulxr::Char) << std::endl);

     ulxr_time_t tim = ulxr_time(0);
     ulxr::DateTime dt(tim);
     ULXR_COUT << ULXR_PCHAR("Current time as DateTime: ") << dt.getDateTime() << std::endl;

     ulxr::CppString s0;
     for (unsigned ii = 0; ii < 256; ++ii)
       s0 += ii;
//     ULXR_COUT << s0 << std::endl;

     ulxr::CppString regression =
        ULXR_PCHAR("AAECAwQFBgcICQoLDA0ODxAREhMUFRYXGBkaGxwdHh8gISIjJCUmJygpKissLS4vMDEyMzQ1\r\n")
        ULXR_PCHAR("Njc4OTo7PD0+P0BBQkNERUZHSElKS0xNTk9QUVJTVFVWV1hZWltcXV5fYGFiY2RlZmdoaWpr\r\n")
        ULXR_PCHAR("bG1ub3BxcnN0dXZ3eHl6e3x9fn+AgYKDhIWGh4iJiouMjY6PkJGSk5SVlpeYmZqbnJ2en6Ch\r\n")
        ULXR_PCHAR("oqOkpaanqKmqq6ytrq+wsbKztLW2t7i5uru8vb6/wMHCw8TFxsfIycrLzM3Oz9DR0tPU1dbX\r\n")
        ULXR_PCHAR("2Nna29zd3t/g4eLj5OXm5+jp6uvs7e7v8PHy8/T19vf4+fr7/P3+/w==\r\n");


     ULXR_COUT << ULXR_PCHAR("Encode 64\n");
     ulxr::CppString s64 = ulxr::encodeBase64(s0);
     ULXR_COUT << s64 << std::endl;

     if (regression != s64)
     {
        ULXR_COUT << ULXR_PCHAR("Encode64 comparison with regression string failed.\n");
        success = false;
     }
     else
       ULXR_COUT << ULXR_PCHAR("Encode64 comparison with regression string OK.\n");

     ULXR_COUT << ULXR_PCHAR("Decode 64\n");
     ulxr::CppString ss = ulxr::decodeBase64(s64);
//     ULXR_COUT << ss << std::endl;

     if (s0 == ss)
       ULXR_COUT << ULXR_PCHAR("base ok\n");
     else
     {
       ULXR_COUT << ULXR_PCHAR("base NOT ok\n");
       success = false;
     }
// ����
     s0 = ULXR_PCHAR("-\r=\t#\n+&<>;12����\"\'contains");
     ulxr::CppString se = ulxr::xmlEscape(s0);

     std::cout << std::hex << "s0: ";
     for (unsigned i1 = 0; i1 < s0.length(); ++i1)
       std::cout << (unsigned) (0xff & s0[i1]) << " ";
     std::cout << std::endl;

     std::cout << std::hex << "se: ";
     for (unsigned i2 = 0; i2 < se.length(); ++i2)
       std::cout << (unsigned) (0xff & se[i2]) << " ";
     std::cout << std::dec << std::endl;

     if (se.find(ULXR_PCHAR("contains")) == ulxr::CppString::npos)
     {
       ULXR_COUT << ULXR_PCHAR("xmlEscape NOT ok\n");
       success = false;
     }
     else
       ULXR_COUT << ULXR_PCHAR("xmlEscape ok\n");

     ULXR_COUT << ULXR_PCHAR("Original: ") << s0 << std::endl;
     ULXR_COUT << ULXR_PCHAR("Escaped: ") << se << std::endl;

     if (s0 == ulxr::xmlUnEscape(se))
       ULXR_COUT << ULXR_PCHAR("escape ok\n");
     else
     {
       ULXR_COUT << ULXR_PCHAR("escape NOT ok\n");
       success = false;
     }

     {
       check_malformed(ULXR_PCHAR("abcd&"));
       check_malformed(ULXR_PCHAR("abcd&#x12"));
       check_malformed(ULXR_PCHAR("abcd&#12"));
       check_malformed(ULXR_PCHAR("abcd&#123456789"));
       check_malformed(ULXR_PCHAR("abcd&#x123456789"));
       check_malformed(ULXR_PCHAR("abcd&#123456789;"));
       check_malformed(ULXR_PCHAR("abcd&#x123456789;"));
     }

#if defined(HAVE_ICONV_H) || defined(HAVE_ICONV)

     ulxr::Cpp8BitString s_lat1 = "������{}[]/'����������{}[]/'����";
     ulxr::Cpp8BitString s02 = ulxr::encodingToUtf8(s_lat1, "LATIN1");
     ULXR_COUT << ULXR_PCHAR("s02: ") << ULXR_GET_STRING(s02) << std::endl;
     ULXR_COUT << ULXR_PCHAR("s_lat1: ") << ULXR_GET_STRING(s_lat1) << std::endl;
     ULXR_COUT << ULXR_PCHAR("back to orig: ")
               << ULXR_GET_STRING(ulxr::utf8ToEncoding(s02, "LATIN1"))
               << std::endl;
     if (s_lat1 == ulxr::utf8ToEncoding(s02, "LATIN1"))
       ULXR_COUT << ULXR_PCHAR("encoding ok\n");
     else
       ULXR_COUT << ULXR_PCHAR("encoding NOT ok\n");

#endif

#ifdef ULXR_UNICODE
     ulxr::Cpp16BitString ws0;
     ws0.reserve(0xd800);
     for (unsigned i = 0x00; i < 0xd800; ++i)
       ws0 += i;

     ulxr::RpcString str (ws0);
     ss = str.getString();
     ULXR_COUT << ss.length() << std::endl;

     ulxr::Cpp16BitString wss = str.getUnicodeString();

     ULXR_COUT << ws0.length() << std::endl;
     ULXR_COUT << (int) ws0[0] << std::endl;

     ULXR_COUT << wss.length() << std::endl;
     ULXR_COUT << (int) wss[0] << std::endl;

     if (ws0 == wss)
       ULXR_COUT << ULXR_PCHAR("unicode 1 ok\n");
     else
     {
       ULXR_COUT << ULXR_PCHAR("unicode 1 NOT ok\n");
       success = false;
     }

     {
        ulxr::Cpp8BitString utf8 = ulxr::unicodeToUtf8(ws0);
        wss = ulxr::utf8ToUnicode(utf8);

        if (ws0 == wss)
          ULXR_COUT << ULXR_PCHAR("unicodeToUtf8 ok\n");
        else
        {
          ULXR_COUT << ULXR_PCHAR("utf8ToUnicode NOT ok\n");
          success = false;
        }
     }
#endif

     {
        ulxr::Cpp8BitString s8;
        s8.reserve(0x100);
        for (unsigned i = 0x00; i < 0x100; ++i)
          s8 += i;

        ulxr::Cpp8BitString utf8 = ulxr::asciiToUtf8(s8);
        ulxr::Cpp8BitString s8s = ulxr::utf8ToAscii(utf8);

        if (s8 == s8s)
          ULXR_COUT << ULXR_PCHAR("asciiToUtf8 ok\n");
        else
        {
          ULXR_COUT << ULXR_PCHAR("utf8ToAscii NOT ok\n");
          success = false;
        }
     }

#ifdef ULXR_UNICODE

     ws0 = ULXR_PCHAR("khera>&sd< asd<f>e56&&& \"$����")
           ULXR_PCHAR("\"\"\'&<&>sd w45234908 0xd9f0�)/()/")
           ULXR_PCHAR("()N u6we4\"E!\"%&((>YXC>YXASESGYDX>YVBHJE%W&TW$");

     ulxr::RpcString str2 (ws0);
     ss = str2.getString();
     wss = str2.getUnicodeString();

     if (ws0 == wss)
       ULXR_COUT << ULXR_PCHAR("unicode ok\n");
     else
     {
       ULXR_COUT << ULXR_PCHAR("unicode NOT ok\n");
       success = false;
     }

#endif

     ULXR_COUT << ULXR_PCHAR("Ready.\n");
  }
  catch(ulxr::Exception &ex)
  {
     ULXR_COUT << ULXR_PCHAR("Error occured: ")
               << ULXR_GET_STRING(ex.why()) << std::endl;
     success = false;
  }

  ULXR_COUT << ULXR_PCHAR("Terminating.\n");
  return success ? 0 : 1;
}
Example #25
0
int main(int argc, char ** argv)
{
  if (argc != 2)
    return 0;
  
  if (UmlCom::connect(Q3CString(argv[1]).toUInt())) {
    try {
      //UmlCom::with_ack(FALSE);
      UmlCom::trace("<b>Java reverse</b> release 2.18<br><hr>");
      UmlCom::traceAutoRaise(FALSE);
      
      UmlItem * item = UmlCom::targetItem();
      
      if (item->kind() != aPackage)
	UmlCom::trace("<font face=helvetica><b>must be applied on a <i>package</i></b></font><br><hr><br>");
      else {
	char * argv = 0;
	int argc = 0;
				 
	QApplication * app = new QApplication(argc, &argv);
			 
	Package::init((UmlPackage *) item, app);
	
	QString here = QDir::currentDirPath();
	QString path;
	// note : QFile fp(QDir::home().absFilePath(".boumlcat")) doesn't work
	// if the path contains non latin1 characters, for instance cyrillic !
	QString s = QDir::home().absFilePath(".doumlcat");
	FILE * fp = fopen((const char *) s, "r");
  














	
	if (fp != 0) {
	  char line[512];
	  
	  if (fgets(line, sizeof(line) - 1, fp) != 0) {
	    remove_crlf(line);
	    path = line;
	  }
	  
	  fclose(fp);
	}
	
	while (!(path = 
		 Q3FileDialog::getOpenFileName(path, "*.cat",
					      0, 0,
					      "select a java catalog file to read it, or cancel"))
	       .isEmpty()) {
	  QFile f(path);
	  
	  if (f.open(QIODevice::ReadOnly)) {
	    if ((fp = fopen((const char *) s, "w")) != 0) {
	      fwrite((const char *) path, 1, path.length(), fp);
	      fputc('\n', fp);
	      fclose(fp);
	    }
	    
	    QDataStream dt(&f);
	    
	    Package::get_root()->restore_children(dt);
	  }
	}
	
	QDir::setCurrent(here);
	int n;
	
	Package * p = Package::scan_dir(n);
	
	if (p != 0) {
	  JavaSettings::set_UseDefaults(TRUE);
	  
	  p->send_dir(n);
	  Statistic::produce();
	}
      }
    }
    catch (...) {
    }
    
    try {
      // socket may be already closed
      UmlCom::message("");
      UmlCom::showTrace();
      UmlCom::bye(0);	// application must not be deleted
    }
    catch (...) {
    }
  }
  
  UmlCom::close();	// application must not be deleted
  return 0;
}
Example #26
0
File: app.c Project: youka2/fx
void loop(void)
{
	const float spd1=30.0f*dt();
	const float spd2=15.0f*dt();

	float r=0.0f;
	float dc=0.0f, ds=0.0f;
	float tc=0.0f, ts=0.0f;

	/*viewport(0,0,nsw,nsh);*/
	use_basic();
	send_lpview(pview);

	if(mm() || mw()!=0.0f)
	{
		if(mm())
		{
			dir+=mx()*spd1;
			if(dir<-0.0f)
			{
				dir+=360.0f;
				ndir+=360.0f;
			}
			else if(dir>360.0f)
			{
				dir-=360.0f;
				ndir-=360.0f;
			}

			tilt-=my()*spd1;
			if(tilt<0.001f) tilt=0.001f;
			else if(tilt>100.0f) tilt=100.0f;
		}

		if(mw()!=0.0f)
		{
			zoom-=mw();
			if(zoom<7.0f) zoom=7.0f;
			else if(zoom>12.0f) zoom=12.0f;
		}
	}
	if(mp(3)) zoom=10.0f;

	ndir-=(ndir-dir)*spd2;
	r=d2r(ndir);
	dc=cosf(r);
	ds=sinf(r);

	ntilt-=(ntilt-tilt)*spd2;
	r=d2r(ntilt);
	tc=cosf(r);
	ts=sinf(r);

	nzoom-=(nzoom-zoom)*spd2;

	look(view,v3(ds*ts*nzoom,dc*ts*nzoom,3.0f+(tc*nzoom)),v3(0.0f,0.0f,3.0f));
	mult(pview,proj,view);

	send_pview(pview);

	/* ----- */
	use_fb(fbos[0]);
	clear();
	/* ----- */
	use_tex(area_tex);
	/* ----- */
	draw_vbo(&area_mod);
	use_fb(0);

	blit_fb(fbos[0],fbos[1],nsw,nsh);
	/* ----- */

	use_fb(fbos[2]);
	set_drawbufs(2);
	clear();
	draw_vbo(&area_mod);
	use_fb(0);

	use_mblur();
	use_tex(texs[0]); /* ----- */
	active_tex(GL_TEXTURE1,texs[2]);
	default_tex();

	use_fb(fbos[3]);
	set_drawbufs(1);
	clear();
	quad();
	use_fb(0);

	active_tex(GL_TEXTURE1,0);
	default_tex();

	/*viewport(0,0,sw,sh);*/
	use_vig();
	use_tex(texs[3]);

	clear();
	quad();

	if(kp(SDL_SCANCODE_DELETE) || kp(SDL_SCANCODE_ESCAPE))
		quit();
}
Example #27
0
int
main (int argc, char **argv)
{
  /* arrays used to contain each PE's rows - specify cols, no need to spec rows */
  float **U_Curr;
  float **U_Next;
  /* helper variables */
  /* available iterator  */
  int i, j, k, m, n;
  int per_proc, remainder, my_start_row, my_end_row, my_num_rows;
  int verbose = 0;
  int show_time = 0;
  double time;
  double t, tv[2];

  /*OpenSHMEM initilization*/
  start_pes (0);
  p = _num_pes ();
  my_rank = _my_pe ();

  if (p > 8) {
      fprintf(stderr, "Ignoring test when run with more than 8 pes\n");
      return 77;
  }

  /* argument processing done by everyone */
  int c, errflg;
  extern char *optarg;
  extern int optind, optopt;

  while ((c = getopt (argc, argv, "e:h:m:tw:v")) != -1)
    {
      switch (c)
	{
	case 'e':
	  EPSILON = atof (optarg);
	  break;
	case 'h':
	  HEIGHT = atoi (optarg);
	  break;
	case 'm':
	  /* selects the numerical methods */
	  switch (atoi (optarg))
	    {
	    case 1:		/* jacobi */
	      meth = 1;
	      break;
	    case 2:		/* gauss-seidel */
	      meth = 2;
	      break;
	    case 3:		/* sor */
	      meth = 3;
	      break;
	    }
	  break;
	case 't':
	  show_time++;		/* overridden by -v (verbose) */
	  break;
	case 'w':
	  WIDTH = atoi (optarg);
	  break;
	case 'v':
	  verbose++;
	  break;
	  /* handle bad arguments */
	case ':':		/* -h or -w without operand */
	  if (ROOT == my_rank)
	    fprintf (stderr, "Option -%c requires an operand\n", optopt);
	  errflg++;
	  break;
	case '?':
	  if (ROOT == my_rank)
	    fprintf (stderr, "Unrecognized option: -%c\n", optopt);
	  errflg++;
	  break;
	}
    }

  if (ROOT == my_rank && argc < 2)
    {
      printf ("Using defaults: -h 20 -w 20 -m 2\n");
    }

//  if (0 < errflg) 
//      exit(EXIT_FAILURE);


  /* wait for user to input runtime params */
 
  for (i = 0; i < _SHMEM_REDUCE_SYNC_SIZE; i += 1)
    pSync[i] = _SHMEM_SYNC_VALUE;

  shmem_barrier_all ();


  /* broadcast method to use  */
  
  shmem_broadcast32 (&meth, &meth, 1, 0, 0, 0, p, pSync);
  switch (meth)
    {
    case 1:
      method = &jacobi;
      break;
    case 2:
      method = &gauss_seidel;
      break;
    case 3:
      method = &sor;
      break;
    }

  /* let each processor decide what rows(s) it owns */
  my_start_row = get_start (my_rank);
  my_end_row = get_end (my_rank);
  my_num_rows = get_num_rows (my_rank);

  if (0 < verbose)
    printf ("proc %d contains (%d) rows %d to %d\n", my_rank, my_num_rows,
	    my_start_row, my_end_row);
  fflush (stdout);

  /* allocate 2d array */
  U_Curr = (float **) malloc (sizeof (float *) * my_num_rows);
  U_Curr[0] =
    (float *) malloc (sizeof (float) * my_num_rows * (int) floor (WIDTH / H));
  for (i = 1; i < my_num_rows; i++)
    {
      U_Curr[i] = U_Curr[i - 1] + (int) floor (WIDTH / H);
    }

  /* allocate 2d array */
  U_Next = (float **) malloc (sizeof (float *) * my_num_rows);
  U_Next[0] =
    (float *) malloc (sizeof (float) * my_num_rows * (int) floor (WIDTH / H));
  for (i = 1; i < my_num_rows; i++)
    {
      U_Next[i] = U_Next[i - 1] + (int) floor (WIDTH / H);
    }

  /* initialize global grid */
  init_domain (U_Curr, my_rank);
  init_domain (U_Next, my_rank);

  /* iterate for solution */
  if (my_rank == ROOT)
    {
     
      tv[0] = gettime ();
    }
  k = 1;
  while (1)
    {
      method (U_Curr, U_Next);

      local_convergence_sqd = get_convergence_sqd (U_Curr, U_Next, my_rank);
     
      shmem_barrier_all ();
      shmem_float_sum_to_all (&convergence_sqd, &local_convergence_sqd, 1, 0,
			      0, p, pWrk, pSync);
      if (my_rank == ROOT)
	{
	  convergence = sqrt (convergence_sqd);
	  if (verbose == 1)
	    {
	      printf ("L2 = %f\n", convergence);
	    }
	}

      /* broadcast method to use */
     
      shmem_barrier_all ();
      shmem_broadcast32 (&convergence, &convergence, 1, 0, 0, 0, p, pSync);
      if (convergence <= EPSILON)
	{
	  break;
	}

      /* copy U_Next to U_Curr */
      for (j = my_start_row; j <= my_end_row; j++)
	{
	  for (i = 0; i < (int) floor (WIDTH / H); i++)
	    {
	      U_Curr[j - my_start_row][i] = U_Next[j - my_start_row][i];
	    }
	}
      k++;
      //MPI_Barrier(MPI_COMM_WORLD);    
      shmem_barrier_all ();
    }


  /* say something at the end */
  if (my_rank == ROOT)
    {
      //time = MPI_Wtime() - time;
      tv[1] = gettime ();
      t = dt (&tv[1], &tv[0]);
      printf
	("Estimated time to convergence in %d iterations using %d processors on a %dx%d grid is %f seconds\n",
	 k, p, (int) floor (WIDTH / H), (int) floor (HEIGHT / H),
	 t / 1000000.0);
    }

  //MPI_Finalize();
  exit (EXIT_SUCCESS);
  return 0;
}
// Flip the desired NMT flag value, and tell all the threads to begin
// taking NMT traps.
void GPGC_NewCollector::enable_NMT_traps(TimeDetailTracer* tdt)
{
assert(GPGC_Safepoint::is_at_safepoint(),"must be at safepoint");

  if ( BatchedMemoryOps ) {
    // Commit batched swap in of new read barrier trap array inside a safepoint.
    GPGC_Collector::commit_batched_memory_ops(tdt, GPGC_Collector::NewCollector);
  } else {
    // Swap in new read barrier trap array to enable new trap state:
    GPGC_ReadTrapArray::swap_readbarrier_arrays(tdt, GPGC_Collector::NewCollector);
  }

  {
    DetailTracer dt(tdt, false, "N: NMT enable: ");

    //  Setup the NMT trap for the threads
    GPGC_NMT::toggle_new_nmt_flag();
    GPGC_NMT::enable_new_trap();

    if ( mark_old_space_roots() ) {
      GPGC_NMT::toggle_old_nmt_flag();
      GPGC_NMT::enable_old_trap();
    }

    // Make sure the new desired NMT state is visible to all the threads before we start
    // telling them to update their NMT state.
    if (os::is_MP()) Atomic::membar();

    // For each JavaThread, tell them to change their NMT state, and ask them to
    // self-clean their stacks when they resume.
    long thread_count          = 0;
    long uncleaned_new_threads = 0;
    long uncleaned_old_threads = 0;

    for ( JavaThread* jt=Threads::first(); jt!=NULL; jt=jt->next() ) {
      thread_count ++;

      assert0( jt->get_new_gen_ref_buffer() && jt->get_new_gen_ref_buffer()->is_empty() );

      if ( jt->please_self_suspend() & JavaThread::gpgc_clean_new ) {
        uncleaned_new_threads++;
      } else {
        jt->set_suspend_request_no_polling( JavaThread::gpgc_clean_new );
      }

      AuditTrail::log_time(jt, AuditTrail::GPGC_TOGGLE_NMT, intptr_t(objectRef::new_space_id));

      if ( mark_old_space_roots() ) {
        assert0( jt->get_old_gen_ref_buffer() && jt->get_old_gen_ref_buffer()->is_empty() );

        if ( jt->please_self_suspend() & JavaThread::gpgc_clean_old ) {
          uncleaned_old_threads++;
        } else {
          jt->set_suspend_request_no_polling( JavaThread::gpgc_clean_old );
        }
      }
    }

dt.print("found %d unclean-new threads (%d unclean-old) out of %d",
             uncleaned_new_threads, uncleaned_old_threads, thread_count);
  }
}
Example #29
0
File: 200.c Project: Ravenbrook/mps
static void test(void *stack_pointer)
{
 mps_thr_t thread;
 unsigned long mins;

 cdie(mps_arena_create(&arena, mps_arena_class_vm(), (size_t) (1024*1024*50)), "create arena");
 cdie(mps_thread_reg(&thread, arena), "register thread");

 mins = sizeof(int);

 dt(SEQ, 4096, 32, 8, 9, 5, ITERATIONS);
 dt(RANGAP, 64, 64, 8, 128, 100, ITERATIONS);

 dt(DUMMY, 4096, 32, 8, 64, 1000, ITERATIONS);
 dt(SEQ, 4096, 32, 8, 64, 1000, ITERATIONS);
 dt(RAN, 4096, 32, 8, 64, 1000, ITERATIONS);
 dt(SEQGAP, 4096, 32, 8, 64, 1000, ITERATIONS);
 dt(RANGAP, 4096, 32, 8, 64, 1000, ITERATIONS);

 dt(DUMMY, 4096, 1024, 100, 132, 1000, ITERATIONS);
 dt(SEQ, 4096, 1024, 100, 132, 1000, ITERATIONS);
 dt(RAN, 4096, 1024, 100, 132, 1000, ITERATIONS);
 dt(SEQGAP, 4096, 1024, 100, 132, 1000, ITERATIONS);
 dt(RANGAP, 4096, 1024, 100, 132, 1000, ITERATIONS);

 dt(DUMMY, 128*1024, 64*1024, mins, 128*1024, 100, ITERATIONS);
 dt(SEQ, 128*1024, 64*1024, mins, 128*1024, 100, ITERATIONS);
 dt(RAN, 128*1024, 64*1024, mins, 128*1024, 100, ITERATIONS);
 dt(SEQGAP, 128*1024, 64*1024, mins, 128*1024, 100, ITERATIONS);
 dt(RANGAP, 128*1024, 64*1024, mins, 128*1024, 100, ITERATIONS);

 mps_thread_dereg(thread);
 mps_arena_destroy(arena);
}
Example #30
0
void ParamEdit::FormulaCompiledForExpression(DatabaseQuery *q) {

	DatabaseQuery::CompileFormula& cf = q->compile_formula;
	bool ok = cf.ok;
	if (ok == false) {
		m_error = true;
		m_error_string = wxString::Format(_("Invalid expression %s"), cf.error);
	}
	free(cf.formula);
	free(cf.error);

	delete q;
	if (!ok) {
		return;
	}

	DefinedParam* param = new DefinedParam(m_draws_ctrl->GetCurrentDrawInfo()->GetBasePrefix(),
		L"TEMPORARY:SEARCH:EXPRESSION",
		L"",
		GetFormula(),
		0,
		TParam::LUA_AV,
		-1);
	param->CreateParam();

	std::vector<DefinedParam*> dpv = std::vector<DefinedParam*>(1, param);
	m_cfg_mgr->SubstituteOrAddDefinedParams(dpv);

	DefinedDrawInfo* ddi = new DefinedDrawInfo(L"",
			L"",
			wxColour(),
			0,
			1,
			TDraw::NONE,
			L"",
			param,
			m_cfg_mgr->GetDefinedDrawsSets());

	q = new DatabaseQuery();
	q->type = DatabaseQuery::SEARCH_DATA;
	q->draw_info = ddi;
	q->param = param->GetIPKParam();
	q->draw_no = -1;
	q->search_data.end = -1;
	q->search_data.period_type = m_draws_ctrl->GetPeriod();
	q->search_data.search_condition = new non_zero_search_condition;

	wxDateTime t = m_current_search_date.IsValid() ? m_current_search_date.GetTicks() : m_draws_ctrl->GetCurrentTime();
	DTime dt(m_draws_ctrl->GetPeriod(), t);
	dt.AdjustToPeriod();
	TimeIndex time_index(m_draws_ctrl->GetPeriod());
	switch (m_search_direction) {
		case SEARCHING_LEFT:
			q->search_data.start = (dt - time_index.GetTimeRes() - time_index.GetDateRes()).GetTime().GetTicks();
			q->search_data.direction = -1;
			break;
		case SEARCHING_RIGHT:
			q->search_data.start = (dt + time_index.GetTimeRes() + time_index.GetDateRes()).GetTime().GetTicks();
			q->search_data.direction = 1;
			break;
		case NOT_SEARCHING:
			assert(false);
			break;
	}
	QueryDatabase(q);
}