Beispiel #1
0
void AlexSim::simScenario1()
{
    simInit();
    double muTimestep=2*burstDuration;

    background(muTimestep);
    burst();
    background(muTimestep);
    burst();
    background(muTimestep);
    burstBleachingDonor();
    background(muTimestep);
    burstBlinkingAcceptor();
    background(muTimestep);
    burst();
    background(muTimestep);
    burst();
    background(muTimestep);
    burstCoincidenceDonor();
    background(muTimestep);
    burst();
    background(muTimestep);

    writeHist("AlexSimHist.txt");
    writeArrivalTimes("./AlexSimPhotonTimes.txt");
}
Beispiel #2
0
void AlexSim::simScenario3(int nBursts, bool writeToFile)
{
    simInit();
    double muTimestep=2*burstDuration;
    qDebug("simScenario3 time t=%.2f",t);
    for(int j=0; j<nBursts; j++) {
        background(muTimestep);
        burst(false);
    }

    qDebug("time t=%.2f",t);
    for(int j=0; j<nBursts; j++) {
        background(muTimestep);
        burstCoincidenceAcceptor(3.0);
    }

    qDebug("time t=%.2f",t);
    for(int j=0; j<nBursts; j++) {
        background(muTimestep);
        burst(false);
    }

    qDebug("time t=%.2f",t);
    for(int j=0; j<nBursts; j++) {
        background(muTimestep);
        burstCoincidenceDonor(3.0);
    }
    qDebug("time t=%.2f",t);
    for(int j=0; j<nBursts; j++) {
        background(muTimestep);
        burst(false);
    }

}
 int burst(vector<int> &nums, int left, int right, vector<vector<int>> &memo)
 {
     if (left+1 == right) return 0;
     if (memo[left][right] > 0) return memo[left][right];
     int ret = 0;
     for (int i = left+1; i < right; ++i)
         ret = max(ret, nums[i]*nums[left]*nums[right] + 
             burst(nums, left, i, memo) + burst(nums, i, right, memo));
         
     return memo[left][right] = ret;
 }
Beispiel #4
0
void AlexSim::simScenario2(bool writeToFile)
{
    simInit();
    double muTimestep=5*burstDuration;

    background(muTimestep);    burst();
    background(muTimestep);    burst();
    background(muTimestep);    burstFRET(0.5);
    background(muTimestep);    burstFRET(0.5);
    background(muTimestep);    burst();
    background(muTimestep);    burstAcceptorOnly();
    background(muTimestep);    burstAcceptorOnly();
    background(muTimestep);    burstDonorOnly();
    background(muTimestep);    burstDonorOnly();

    background(muTimestep);    burstDelayedDonor();
    background(muTimestep);    burstDelayedDonor();
    background(muTimestep);    burstDelayedAcceptor();
    background(muTimestep);    burstDelayedAcceptor();

    background(muTimestep);    burstBleachingDonor();
    background(muTimestep);    burstBleachingDonor();
    background(muTimestep);    burstBleachingAcceptor();
    background(muTimestep);    burstBleachingAcceptor();

    background(muTimestep);    burstBlinkingDonor();
    background(muTimestep);    burstBlinkingDonor();
    background(muTimestep);    burstBlinkingAcceptor();
    background(muTimestep);    burstBlinkingAcceptor();

    background(muTimestep);    burstDelayedDonor();     burstAcceptorOnly();
    background(muTimestep);    burstDelayedDonor();     burstAcceptorOnly();
    background(muTimestep);    burstDelayedAcceptor();  burstDonorOnly();
    background(muTimestep);    burstDelayedAcceptor();  burstDonorOnly();

    background(muTimestep);    burstDelayedDonor();     burstDonorOnly();
    background(muTimestep);    burstDelayedDonor();     burstDonorOnly();
    background(muTimestep);    burstDelayedAcceptor();  burstAcceptorOnly();
    background(muTimestep);    burstDelayedAcceptor();  burstAcceptorOnly();

    background(muTimestep);    burstCoincidenceDonor();
    background(muTimestep);    burstCoincidenceDonor();
    background(muTimestep);    burstCoincidenceAcceptor();
    background(muTimestep);    burstCoincidenceAcceptor();

    background(muTimestep);

    writeHist("AlexSimHist.txt");
    if (writeToFile) writeArrivalTimes("./AlexSimPhotonTimes.csv");
}
Beispiel #5
0
void AlexSim::simBurstDuration(int nBursts,bool writeToFile)
{
    // simulate many photon bursts and write their sampled duration and burst size to file --> linear relationship?

    simInit();
//    photonArrivalTimeDonor.reserve((int)(nBursts*burstDuration*rateDemDex));
//    photonArrivalTimeAcceptor.reserve((int)(nBursts*burstDuration*rateAemAex));

    if(writeToFile) {
        QFile file("./AlexSimBurstDuration.txt");
        file.open(QIODevice::WriteOnly | QIODevice::Text);
        QTextStream out(&file);
        out <<"# Simulation data. All times in ms.Parameters are:\n";
        out <<"# rateDonor="<<rateDemDex<<"\trateAcceptor="<<rateAemAex<<"/trateBackground="<<rateBackground<<"\tburstDuration="<<burstDuration<<"\tvariance="<<burstDurationVar<<"\ttStart="<<tStart<<"\ttEnd="<<tEnd()<<"\n";
        out.setRealNumberPrecision(11);
        out <<"#  time \tburst duration\t#photons\n";

        for(int i=0;i<nBursts;i++) {
            burstCount(out);
            background(burstDuration);
        }

        file.close();
        writeArrivalTimes("./AlexSimPhotonTimes.txt");
    } else {
        for(int i=0;i<nBursts;i++) {
            burst(false);
            background(burstDuration);
        }

    }

}
 int maxCoins(vector<int>& nums) 
 {
     nums.insert(nums.begin(), 1);
     nums.push_back(1);
     vector<vector<int>> memo(nums.size(), vector<int>(nums.size(), 0));
     return burst(nums, 0, (int)nums.size()-1, memo);
 }
Beispiel #7
0
// main function
int main(void)
{
	init();

	while(1)
	{
		burst();
		burst();
		burst();

		off();
	}
	
	while(1);

	return 0;
}
Beispiel #8
0
void AlexSim::burstBlinkingAcceptor()
{
    double tstart=t;
    double burstDurationSample=gsl_ran_lognormal(r, mu, sigma);
    double tend = tstart + burstDurationSample;
    double tBlinkStart=gsl_ran_flat(r, tstart, tend);
    double tBlinkEnd=tBlinkStart + gsl_ran_exponential(r, lifetimeBlinking);
    if (tBlinkEnd>tend) tBlinkEnd=tend;
    qDebug()<<"burst at"<<t*1e3<<"ms for"<<burstDurationSample*1e3<<"ms. Acceptor blinks after"<<(tBlinkStart-tstart)*1e3<<"ms for"<<(tBlinkEnd-tBlinkStart)*1e3<<"ms";

    Photons photonsTemp;
    photonsTemp<<burst(tstart, tBlinkStart);
    photonsTemp<<donorOnly(tBlinkStart, tBlinkEnd);
    photonsTemp<<burst(tBlinkEnd, tend);
    photonsTemp.sort();
    photons<<photonsTemp;
}
Beispiel #9
0
void AlexSim::burstFRET(const double FRET)
{
    double tstart=t;
    double burstDurationSample=gsl_ran_lognormal(r, mu, sigma);
    double tend = tstart + burstDurationSample;
    Photons photonsTemp;
    photonsTemp<<burst(tstart, tend,FRET);
    photonsTemp.sort();
    photons<<photonsTemp;
}
Beispiel #10
0
// a burst from tstart with length of burstDuration
// interphoton times are assumed to be exponentially distributed
void AlexSim::burst(bool debug)
{
    double tstart=t;
    double burstDurationSample=gsl_ran_lognormal(r, mu, sigma);
    double tend = tstart + burstDurationSample;
    if(debug) qDebug()<<"burst at"<<t*1e3<<"ms for"<<burstDurationSample*1e3<<"ms";

    Photons photonsTemp;
    photonsTemp<<burst(tstart, tend);
    photonsTemp.sort();
    photons<<photonsTemp;
}
Beispiel #11
0
inline int foo( int x, int y ) {
    int r;
    r = sub( x, y );
    if( r != (x-y) ) _fail;
    r = burst( x, y );
    if( r != ((( x^y ) & y ) | y ) ) _fail;
    r = uses_burst( x, y );
    x++;
    y-=2;
    if( r != ((( x^y ) & y ) | y ) ) _fail;
    return( r );
}
Beispiel #12
0
void AlexSim::burstBlinkingDonor() // The time a flourophore blinks during a burst is chosen at random (from a uniform distribtion) and its length is drawn from an exponential distribution with mean value of the triplet lifetime.
{
    double tstart=t;
    double burstDurationSample=gsl_ran_lognormal(r, mu, sigma);
    double tend = tstart + burstDurationSample;
    double tBlinkStart=gsl_ran_flat(r, tstart, tend);
    double tBlinkEnd=tBlinkStart + gsl_ran_exponential(r, lifetimeBlinking);
    qDebug()<<"burst at"<<t*1e3<<"ms for"<<burstDurationSample*1e3<<"ms. Donor blinks after"<<(tBlinkStart-tstart)*1e3<<"ms for"<<(tBlinkEnd-tBlinkStart)*1e3<<"ms";

    burst(tstart, tBlinkStart);
    acceptorOnly(tBlinkStart, tBlinkEnd);
    burst(tBlinkEnd, tend);

    Photons photonsTemp;
    photonsTemp<<burst(tstart, tBlinkStart);
    photonsTemp<<acceptorOnly(tBlinkStart, tBlinkEnd);
    photonsTemp<<burst(tBlinkEnd, tend);
    photonsTemp.sort();
    photons<<photonsTemp;

}
/* 
blinking the firefly :

my basic concept is that fireflies fade up at different speeds, then hold that glow
for a random period of time, then fade down at a speed quicker then they faded up.

also, on occasion - they get real bright in the middle briefly.
*/
void Firefly::firefly_blink()
{
    // first select a color to light up the firefly with
    boolean color_ok = false;
    unsigned char red, green, blue;

    /* 
    i do this to keep the overall value down so they don't
    all come out white
    */
    while(!color_ok) {
        red = random(0,255);
        green = random(0,255);
        blue = random(0,255);

        if(red + green + blue < _max_color_value) {
            color_ok = true;
        }
    }

    // set the delays
    int fade_up_speed = random(4,15);
    int hold_delay = random(0,500);
    int fade_down_speed = random(1,fade_up_speed);

                                                  // light up the firefly
    fade_to(red, green, blue, fade_up_speed);

    delay(random(1,500));

    // do random event on occasion

    int event_trigger = random(1,20);

    if(event_trigger == 5) {
        burst();
    }

    if(event_trigger == 10) {
        sparkle();
    }

    if(event_trigger == 15) {
        go_full_color(random(0,3));
    }

    if(event_trigger == 12 || event_trigger == 6) {
        delay(random(300,800));
    }

    fade_to(0 , 0 ,0 , fade_down_speed);
}
Beispiel #14
0
void AlexSim::burstBleachingAcceptor()
{
    double tstart=t;
    double burstDurationSample=gsl_ran_lognormal(r, mu, sigma);
    double tend = tstart + burstDurationSample;
    double tBleach=gsl_ran_flat(r, tstart, tend);
    qDebug()<<"burst at"<<t*1e3<<"ms for"<<burstDurationSample*1e3<<"ms. Acceptor bleaching after "<<(tBleach-tstart)*1e3<<"ms";

    Photons photonsTemp;
    photonsTemp<<burst(tstart, tBleach);
    photonsTemp<<donorOnly(tBleach, tend);
    photonsTemp.sort();
    photons<<photonsTemp;
}
Beispiel #15
0
void AlexSim::burstDelayedAcceptor()
{
    double tstart=t;
    double burstDurationSample=gsl_ran_lognormal(r, mu, sigma);
    double tend = tstart + burstDurationSample;
    double tDelayed=gsl_ran_flat(r, tstart, tend);
    qDebug()<<"burst at"<<t*1e3<<"ms for"<<burstDurationSample*1e3<<"ms. Acceptor delayed for"<<(tDelayed-tstart)*1e3<<"ms";

    Photons photonsTemp;
    photonsTemp<<acceptorOnly(tstart, tDelayed);
    photonsTemp<<burst(tDelayed, tend);
    photonsTemp.sort();
    photons<<photonsTemp;
}
Beispiel #16
0
void AlexSim::burstCoincidenceDonor(double scale)
{
    double tstart=t;
    double burstDurationSample=gsl_ran_lognormal(r, mu, sigma);
    double tend = tstart + burstDurationSample;
    double tCoincidenceStart=gsl_ran_flat(r, tstart, tend);
    double tCoincidenceEnd=gsl_ran_flat(r, tCoincidenceStart, tend);
    qDebug()<<"burst at"<<t*1e3<<"ms for"<<burstDurationSample*1e3<<"ms. Donor coincidence after"<<(tCoincidenceStart-tstart)*1e3<<"ms for"<<(tCoincidenceEnd-tCoincidenceStart)*1e3<<"ms with scale parameter"<<scale;

    Photons photonsTemp;
    photonsTemp<<burst(tstart, tend);
    photonsTemp<<donorOnly(tCoincidenceStart,tCoincidenceEnd);
    photonsTemp.sort();
    photons<<photonsTemp;
}
int max_score(vector<int>& nums) {
  int n = nums.size();
  int dp[n][n];
  for (int l = 0; l < n; ++l) {
    for (int i = 0, j = l; j < n; ++i, ++j) {
      dp[i][j] = -1;
      for (int k = i; k <= j; ++k) {
        int cur_ans = k - 1 < i ? 0 : dp[i][k - 1];
        cur_ans += k + 1 > j ? 0 : dp[k + 1][j];
        cur_ans += burst(nums, k, i - 1, j + 1);
        dp[i][j] = max(dp[i][j], cur_ans);
      }
    }
  }
  return n == 0 ? 0 : dp[0][n - 1];
}
Beispiel #18
0
void WorkerThread::run()
{
  L_FUNC(QString("_id='%1'").arg(_id));
  qDebug("WorkerThread::run"); // TODO comment this

  msleep(500); // [ms]
  QString result = QString("%1: Calculate: 6! = %2").arg(_id).arg(factorial(6));
  L_INFO(result);
  msleep(250); // [ms]
#if TEST_BURST > 0
  burst(10*1000); // queue full at ~49'000 ?!
#endif
  msleep(250); // [ms]

  emit resultReady(result);
}
Beispiel #19
0
void sendCode() {  //sends 0b00101010 -> 42
	burst(1000);
	_delay_us(500);
	burst(1000);
	_delay_us(500);
	burst(1500);
	_delay_us(500);
	burst(1000);
	_delay_us(500);
	burst(1500);
	_delay_us(500);
	burst(1000);
	_delay_us(500);
	burst(1500);
	_delay_us(500);
	burst(1000);
	_delay_us(500);
}
Beispiel #20
0
static PTEXT CPROC ParseCommand( PMYDATAPATH pdp, PTEXT buffer )
{
	if( buffer )
	{
		PTEXT pCommand;
     	//Log2( WIDE("buffer: %s(%d)"), GetText( buffer ), GetTextSize( buffer ) );
     	//LogBinary( buffer );
      pCommand = burst( buffer );
      LineRelease( buffer );
      if( pCommand )
      {
         PTEXT pTemp, pStart;
         int bEscaped = FALSE;
         pStart = pTemp = pCommand;
         while( pTemp )
         {
            if( TextIs( pTemp, WIDE("\\") ) )
            {
               if( !bEscaped )
               {
                  PTEXT pNext;
                  pNext = NEXTLINE( pTemp );
                  pNext->format.position.offset.spaces = pTemp->format.position.offset.spaces;
                  LineRelease( SegGrab( pTemp ) );
                  bEscaped = TRUE;
                  pTemp = pNext;
                  continue;
               }
            }
            if( !bEscaped && TextIs( pTemp, WIDE(";") ) )
            {
               PTEXT pPrior;
	           	//Log( WIDE("Splitting the line and enqueing it...") );
               pPrior = pTemp;
               SegBreak( pTemp );
               if( pStart != pTemp )
               {
               	// end of line included!
               	pStart = SegAppend( pStart, SegCreate(0) ); 
                  EnqueLink( &pdp->output, pStart );
               }
               pStart = pTemp = NEXTLINE( pTemp );
               SegBreak( pTemp );
               LineRelease( pPrior ); // remove ';'
               bEscaped = FALSE;
               continue;
            }
            bEscaped = FALSE;
            pTemp = NEXTLINE( pTemp );
         }
         if( pStart )
         {
         	PTEXT line;
         	line = BuildLine( pStart );
         	//Log1( WIDE("Enqueu: %s"), GetText( line ) );
         	LineRelease( line );
            EnqueLink( &pdp->output, pStart );
         }
      }
      else
      {
         // well what now?  I guess pLine got put into Partial...
         // next pass through this all for command recall will blow...
         Log( WIDE("No information from the burst!") );
      }
	}
	return (PTEXT)DequeLink( &pdp->output );
}
Beispiel #21
0
int
main( int argc, char *argv[] )
{
  if( argc == 4 )
  {
    stream_t *in = stream_string( argv[2] );
    stream_t *gen = stream_string( argv[3] );
    
    /** Process the transmit option */
    if( 0 == strncmp( argv[1], "transmit", 8 ) )
    {
      stream_t *out = transmit( in, gen );
      stream_print( out ); printf( "\n" );
    }

    /** Process the check option */
    else if( 0 == strncmp( argv[1], "check", 5 ) )
    {
      printf( "%s\n", check( in, gen )? "error detected" : "no error detected" );
    }
    else
    {
      usage();
    }
  }
  else if( argc == 2 )
  {
    /** Process the test option */
    if( 0 == strncmp( argv[1], "test", 4 ) )
    {
      stream_t *gen = stream_string( CRC32_GEN );
      srand( time( NULL ) );

      int errorslt = 0; int countlt = 0;
      int errorseq = 0; int counteq = 0;
      int errorsgt = 0; int countgt = 0;

      /** Generate test cases */
      for( int i = 0; i < NTEST; i++ )
      {
        stream_t *in = stream_random( FRAME_SIZE * 8 );
        stream_t *out = transmit( in, gen );
        
        /** mod by 3 to resolve the <, =, > 32 cases */
        int cat = i % 3;
        switch( cat )
        {
          case 0:
            countlt++;
            burst( out, 1 + ( rand() % 31 ) );
            errorslt += check( out, gen )? 1 : 0;
            break;
          case 1:
            counteq++;
            burst( out, 32 );
            errorseq += check( out, gen )? 1 : 0;
            break;
          case 2:
            countgt++;
            burst( out, 33 + ( rand() % ( FRAME_SIZE * 8 - 34 ) ) );
            errorsgt += check( out, gen )? 1 : 0;
            break;
        }
        free( in );
        free( out );
      }
      printf( "%d/%d burst errors < 32 were detected.\n", errorslt, countlt );
      printf( "%d/%d burst errors = 32 were detected.\n", errorseq, counteq );
      printf( "%d/%d burst errors > 32 were detected.\n", errorsgt, countgt );
    }
    else
    {
      usage();
    }
  }
  else
  {
    usage();
  }
}
Beispiel #22
0
int main(int argc, char *argv[])
{
	if (argc < 5)	/* Test for correct number of arguments */
		usage();

	/* get info from parameters , or default to defaults if they're not specified */
	char *server_ip = argv[1];		   /* First arg: server IP address (dotted quad) */
	Parameter<uint16_t>		server_port("server port", 0, 65535, atoi(argv[2]));
	Parameter<int>			num_bursts("number of bursts", 1, MAX_NUM_BURSTS, atoi(argv[3]));
	Parameter<int>			burst_delay("burst iteration delay", 0, MAX_BURST_DELAY, atoi(argv[4]));
	Parameter<int>			payload_len("payload length", 0, ECHOMAX-48, 0);
	Parameter<int>			requested_burst_len("burst length", -1, -1, MAX_BURST_LEN);

	if (argc >= 6) // allow specifying payload length
		payload_len.value(atoi(argv[5]));

	if (argc >= 7) // specify burst length to repeat
		requested_burst_len.value(atoi(argv[6]));

	// set up CNT-C catcher
	signal(SIGINT, cntc);

	/* Construct the server address structure */
	struct sockaddr_in server_address; /* Echo server address */
	memset(&server_address, 0, sizeof(server_address));	/* Zero out structure */
	server_address.sin_family = AF_INET;				 /* Internet addr family */

	int address = inet_addr(server_ip);

	/* If user gave a dotted decimal address, we need to resolve it  */
	if (address == -1) {
		struct hostent *thehost = gethostbyname(server_ip);
		address = *((unsigned long *) thehost->h_addr_list[0]);
	}

	server_address.sin_addr.s_addr = address;  /* Server IP address */
	server_address.sin_port = htons(server_port.value());

	/* Create a datagram/UDP socket */
	int sock;
	if ((sock = socket(PF_INET, SOCK_DGRAM, IPPROTO_UDP)) < 0)
		throw DieException("socket() failed");

	// set up message bytes with header pointing at beginning 20
	char message_buffer[ECHOMAX];
//	int message_len = sizeof(burst_protocol_header_t) + payload_len.value();
	memset(&message_buffer, 0, sizeof(message_buffer));

	burst_protocol_header_t *header = (burst_protocol_header_t *)message_buffer;
	header->test_type = htons(1);
	header->message_type = htons(MSG_PROBE);
	header->payload_len = htonl(payload_len.value());

	int bursts_sent = 0;
	int messages_sent = 0;
	int burst_len = requested_burst_len.value() == -1 ? 100 : requested_burst_len.value();

	// send the begin message

	// wait for the begin_ack

	int burst_num;
	for (burst_num = 0; !stopping && burst_num < num_bursts.value(); burst_num++) {
		header->burst_num = htonl(burst_num);

		Burst burst(TEST_TYPE, burst_num, burst_len, payload_len.value());
		burst.send(sock, server_address);

		messages_sent += burst_len;
		bursts_sent++;

		printf("burst %d sent, %d messages\n", burst_num, burst_len);
		sleep(burst_delay.value());
	}

	// send the complete message

	// wait for complete_ack

	printf("\ntotal of %d bursts sent, totalling %d messages\n", bursts_sent, messages_sent);

	close(sock);
	exit(0);
}
Beispiel #23
0
void ParseURI( CTEXTSTR string )
{
   int state;
	PTEXT words;
	PTEXT delete_seg = NULL;
	PTEXT line = SegCreateFromText( string );
	PTEXT filename = NULL;
   PTEXT varname = NULL;
	PTEXT varvalue = NULL;
   PTEXT content = NULL;
   int content_length;

	struct {
		uint32_t bInvalid : 1;
		uint32_t bGet : 1;
		uint32_t bPost : 1;
		uint32_t bBinary : 1; // reading the content...
		uint32_t bValue : 1;
	} flags;
// we got a line, therefore we can process it...
	// only thing then is the last line in the block ...

	state = GET_FILENAME;

	words = burst( line );
	delete_seg = words;
	// though...
	LineRelease( line );
	flags.bValue = 0;

	while( words )
	{
		DECLTEXT( page, WIDE("page") );
		DECLTEXT( CGI, WIDE("CGI") );
		//printf( "state:%d word:%s \r\n",state, GetText(words ) );
		// what does stuff have now?  the whole thign?  a line?
		if( !GetTextSize( words ) ) switch( state )
		{
		case GET_HTTP_EOL:
			state = GET_HTTP_METAVAR;
			break;
		case GET_HTTP_METAVAR:
		case GET_CGI:
			goto AddCGIVariable;
			break;
		}
		else switch( state )
		{
		case RESET:
			state = GET_COMMAND;
			continue;  // skip ahead  and try new state;
			break;
		case GET_COMMAND:
			if( TextLike( words, WIDE("GET") ) )
			{
				state = GET_FILENAME;
				//flags.bGet = TRUE;
			}
			else if( TextLike( words, WIDE("POST") ) )
			{
				state = GET_FILENAME;
				//flags.bPost = TRUE;
			}
			else
			{
				flags.bInvalid = TRUE;
			}
			break;
		case GET_FILENAME:
			if( !filename && TextIs( words, WIDE("/") ) )
			{
				// this is rude, and should never be done,
				// however this filter consumes all data anyhow, SO
				// mangling this will not hurt much...
				words->format.position.offset.spaces = 0;
			}
			if( TextIs( words, WIDE("?") ) || words->format.position.offset.spaces )
			{
				if( !words->format.position.offset.spaces )
					state = GET_CGI;
				else
					state = GET_HTTP_VERSION;
				filename = NEXTLINE( filename );
				LineRelease( SegBreak( filename ) );
				HTTPCollapse( &filename );
				//AddVariableExxx( ps, ps->Current, (PTEXT)&page, filename, FALSE,TRUE,TRUE DBG_SRC );
				//AddVariable( ps, ps->Current, (PTEXT)&CGI, TextDuplicate( NEXTLINE( words ), FALSE ) );
				LineRelease( filename );
				filename = NULL;
			}
			else
			{
				filename = SegAppend( filename, SegDuplicate( words ) );
			}
			break;
		case GET_CGI:
			if( words->format.position.offset.spaces )
			{
				state = GET_HTTP_VERSION;
				goto AddCGIVariable;
			}
			else
			{
				if( TextIs( words, WIDE("=") ) )
				{
					HTTPCollapse( &varname );
					flags.bValue = 1;
				}
				else if( TextIs( words, WIDE("&") ) )
				{
				AddCGIVariable:
					HTTPCollapse( &varvalue );
					HTTPCollapse( &varname );
					if( TextLike( varname, WIDE("content-length") ) )
					{
						content_length= IntCreateFromText( GetText( varvalue ) );
					}
					{
						struct VAR *v = New( struct VAR );
						v->varname = varname;
						varname = NULL;
						v->varvalue = varvalue;
						varvalue = NULL;
						AddLink( &l.vars, v );
					}
					//AddVariableExxx( ps, ps->Current, pmdp->varname, pmdp->varvalue, FALSE,TRUE,TRUE DBG_SRC );
					//LineRelease( varname );
					//LineRelease( varvalue );
					//varname = NULL;
					//varvalue = NULL;
					flags.bValue = 0;
				}
				else
				{
					if( flags.bValue )
					{
						varvalue = SegAppend( varvalue, SegDuplicate( words ) );
					}
					else
					{
						//printf( "add var" );
						varname = SegAppend( varname, SegDuplicate( words ) );
					}
				}
			}
			break;
		case GET_HTTP_VERSION:
			if( TextIs( words, WIDE("HTTP") ) )
					{
						// okay - don't really do anything... next word is the version...
					}
					else
					{
                  // TextIs( words, "/" ); // this is a token before the number...
						// Version better be something like 1.1 1.0?
						// well wait for EOL...
						state = GET_HTTP_EOL;
					}
					break;
				case GET_HTTP_EOL:
					if( !GetTextSize( words ) )
					{
						state = GET_HTTP_METAVAR;
					}
					break;
				case GET_HTTP_METAVAR:
					{
						if( !flags.bValue && TextIs( words, WIDE(":") ) )
						{
                     flags.bValue = TRUE;
						}
						else
						{
							if( flags.bValue )
							{
                        varvalue = SegAppend( varvalue, SegDuplicate( words ) );
							}
							else
							{
                        varname = SegAppend( varname, SegDuplicate( words ) );
							}
						}
					}
               break;
				case GET_HTTP_CONTENT:
					if( !content_length )
					{
                  DebugBreak();
                  state = RESET;
					}
					else
					{
						// hmm we've parsed everything up to here, but now we need blocks, binary blocks.
						content = SegAppend( content, words );
						if( LineLength( content ) == content_length )
						{
							//ProcessPostCGI( common.Owner, content );
							//AddVariableExxx( ps, ps->Current, (PTEXT)&CGI, content, FALSE,TRUE,TRUE DBG_SRC );
							//AddVariable( ps, ps->Current, (PTEXT)&CGI, content );
							LineRelease( content );

							//InvokeBehavior( "http.request", common.Owner->Current, common.Owner, NULL );
							//InvokeBehavior( "http_request", common.Owner->Current, common.Owner, NULL );
							state = RESET;
						}
                  words = NULL;
					}
					break;
		}
Beispiel #24
0
int main(int argc, char *argv[])
{
    try {
        if (argc < 5)	/* Test for correct number of arguments */
            usage();

        /* get info from parameters , or default to defaults if they're not specified */
        char *server_ip = argv[1];		   /* First arg: server IP address (dotted quad) */
        Parameter<uint16_t>		server_port("server port", 0, 65535, atoi(argv[2]));
        Parameter<int>			num_bursts("number of bursts", 1, TestData::MAX_LEN, atoi(argv[3]));
        Parameter<int>			burst_delay("burst iteration delay", 0, TestData::MAX_DELAY, atoi(argv[4]));
        Parameter<int>			payload_len("payload length", 0, Message::MAX_PAYLOAD, 0);
        Parameter<int>			initial_burst_len("initial burst length", 1, Burst::MAX_LEN, 100);
        Parameter<float>		burst_len_multiplier("burst length multiplier", 0, 100, 0);

        if (argc >= 6) // allow specifying payload length
            payload_len.value(atoi(argv[5]));

        if (argc >= 7) // specify burst length to repeat
            initial_burst_len.value(atoi(argv[6]));

        if (argc >= 8)
            burst_len_multiplier.value(atof(argv[7]));

        // other (currently constant) parameters
        int test_type = TestData::BUFFER_SIZE_TEST;
        int client_port = server_port.value()+1;

        SignalHandler cntlcCatcher(SIGINT);

        // open a socket, bind for control messages
        UDPSocket socket(client_port);

        const unsigned int bufferSize = Message::MAX_SIZE;
        unsigned char controlBuffer[bufferSize];
        unsigned char responseBuffer[bufferSize];

        // first burst length
        int burst_len = initial_burst_len.value();

        Message controlMessage(controlBuffer, 0);
        controlMessage.setAddress(server_ip, server_port.value());

        // send the begin message
        controlMessage.header().message_type(Message::BEGIN);
        controlMessage.header().test_type(test_type);
        controlMessage.header().burst_num(num_bursts.value());
        // seq_num set in sending
        controlMessage.header().burst_len(burst_len);

        bool gotResponse = false;

        for (int i = 0; i < Socket::MAX_RETRIES; i++) {
            controlMessage.header().seq_num(i+1);
            socket.send(controlMessage);

            // wait for the begin_ack
            Message responseMessage(responseBuffer, bufferSize);
            socket.receive(responseMessage, 1);

            if (responseMessage.size() <= 0)
                continue;

            if (!Message::isResponsePair(controlMessage, responseMessage))
                throw std::runtime_error("Got an unexpected response to begin message.");

            gotResponse = true;
            break;
        }

        if (!gotResponse)
            throw std::runtime_error("Didn't get a response to the begin message from the server.");

        int bursts_sent = 0;
        int messages_sent = 0;

        // send the bursts
        for (int burst_num = 0; !cntlcCatcher.receivedSignal() && burst_num < num_bursts.value(); burst_num++) {
            Burst burst(test_type, burst_num, burst_len, payload_len.value(), server_ip, server_port.value());
            burst.send(socket);

            messages_sent += burst_len;
            bursts_sent++;

//		printf("burst %d sent, %d messages\n", burst_num, burst_len);
            burst_len += burst_len * burst_len_multiplier.value();
            usleep(burst_delay.value());
        }

//	printf("\nTotal of %d bursts sent, totalling %d messages\n", bursts_sent, messages_sent);

        // send the complete message
        controlMessage.header().message_type(Message::COMPLETE);
        controlMessage.header().burst_num(num_bursts.value());
        // seq_num set in sending
        controlMessage.header().burst_len(burst_len);

        gotResponse = false;

        for (int i = 0; i < Socket::MAX_RETRIES; i++) {
            controlMessage.header().seq_num(i+1);
            socket.send(controlMessage);

            // wait for the complete_ack
            Message responseMessage(responseBuffer, bufferSize);
            socket.receive(responseMessage, 1);

            if (responseMessage.size() <= 0)
                continue;

            if (!Message::isResponsePair(controlMessage, responseMessage))
                throw std::runtime_error("Got an unexpected response to complete message.");

            TestResults results(responseMessage.payload(), responseMessage.header().payload_len());
            std::cout << results;

            gotResponse = true;
            break;
        }

        if (!gotResponse)
            throw std::runtime_error("Didn't get a response to the complete message from the server.");

    } catch (std::exception &e) {
        std::cerr << "exception caught: " << e.what() << std::endl;
    }
    exit(0);
}
Beispiel #25
0
int inline uses_burst( int a, int b ) {
    ++a;
    b -= 2;
    return burst( a, b );
}
Beispiel #26
0
CGEventRef processEvent(CGEventType type,  CGEventRef event) {
	CGKeyCode keycode = (CGKeyCode) CGEventGetIntegerValueField(event, kCGKeyboardEventKeycode);
	CGKeyCode autorepeat = (CGKeyCode) CGEventGetIntegerValueField(event, kCGKeyboardEventAutorepeat);		
	
	if (outsideMirror) {
		// Outside mirror...
		
		if (type == kCGEventKeyDown) {
			if (autorepeat) {
				if (marked(outside, keycode)) {
					return passEvent(event);
				
				} else {
					return remapEvent(event);
				}
				
			} else {
				if (keycode == 49) { // space
					goInside(event);
					spaceDown = CGEventCreateCopy(event);
					return swallowEvent(event);
					
				} else {
					mark(outside, keycode);
					return passEvent(event);
				}				
			}
			
			
		} else if (type == kCGEventKeyUp) {
			if (marked(outside, keycode)) {
				unmark(outside, keycode);
				return passEvent(event);
				
			} else {
				unmark(inside, keycode);
				return remapEvent(event);
			}
			
		}
				
	} else {
		// Inside mirror
		
		if (type == kCGEventKeyDown) {
			if (autorepeat) {
				if (keycode == 49) { // space
					return swallowEvent(event);
					
				} else {
					if (marked(inside, keycode)) {
						return remapEvent(event);
						
					} else {
						return passEvent(event);
					}
				}
				
			} else {
				mark(inside, keycode);
				mirrorCount++;
				return remapEvent(event);
			}
			
		} else if (type == kCGEventKeyUp) {
			if (keycode == 49) { // space
				goOutside();
				if (burst(event)) {
					return emitSpace(event);
					
				} else {
					return swallowEvent(event);
				}
				
			} else {
				if (marked(inside, keycode)) {
					unmark(inside, keycode);
					return remapEvent(event);
					
				} else {
					return passEvent(event);
				}
			}
		}
	}
	
	printf("Leaking events?!\n");
	return event;
}
Beispiel #27
0
void Enemy::onUpdate()
{
	if(invisibility) invisibility--;

	Vec2i facing = intToDir(dir);

	if(level.getAIFlags(position) & 2)
	{
		// Vergiftung
		contamination--;
	}

	if(contamination <= 0) burst();

	if(!thinkCounter--)
	{
		// den nächsten Spieler suchen, der für den Gegner sichtbar ist
		Player* p_closestPlayer = 0;
		int closestDist = 0;
		const std::list<Player*>& players = Player::getInstances();
		for(std::list<Player*>::const_iterator i = players.begin(); i != players.end(); ++i)
		{
			if(!(*i)->isTeleporting())
			{
				int dist = (position - (*i)->getPosition()).lengthSq();
				if(dist < closestDist || !p_closestPlayer)
				{
					if(canSee((*i)->getPosition()))
					{
						p_closestPlayer = *i;
						closestDist = dist;
					}
				}
			}
		}

		if(p_closestPlayer)
		{
			targetPosition = p_closestPlayer->getPosition();
			interest += 2225 - closestDist;
		}

		thinkCounter = random(2, 5);
	}

	if(subType == 0)
	{
		int oldDir = dir;

		if(moveCounter-- <= 0 && fabs(shownDir - dir) < 0.4)
		{
			int r = random(0, 8);
			if(interest >= 10000) r = random(0, 40);

			if(contamination < 50)
			{
				if(random() % 2) r = 0;
			}

			interest /= 2;

			switch(r)
			{
			case 0:
				{
					int d = random(-22, 22) / 10;
					if(d) dir += d, anim += 16;
				}
				break;
			case 1:
			case 2:
			case 3:
				if(!tryToMove(facing)) dir += random(-22, 22) / 10;
				anim += 16;
				break;
			default:
				if(r >= 6 && targetPosition.x != -1)
				{
					// zum Ziel laufen
					Vec2i toTarget = targetPosition - position;
					if(toTarget.x && toTarget.y) toTarget.value[random(0, 1)] = 0;
					int d = dirToInt(toTarget);
					toTarget = intToDir(d);
					if(tryToMove(toTarget))
					{
						dir = d;
						anim += 16;
						interest *= 2;
					}
				}
				break;
			}

			if(position == targetPosition || interest < 10)
			{
				targetPosition = Vec2i(-1, -1);
				interest = 0;
			}

			while(dir < 0) dir += 4, shownDir += 4.0;
			dir %= 4;

			moveCounter = random(4, 7);
		}

		if(anim) anim--;

		double dd = static_cast<double>(dir) - shownDir;
		if(dd > 2.0) shownDir += 4.0;
		else if(dd < -2.0) shownDir -= 4.0;
		shownDir = 0.125 * dir + 0.875 * shownDir;

		if(!soundCounter)
		{
			if(oldDir != dir)
			{
				// Kratz-Sound abspielen
				Engine::inst().playSound("enemy1_turn.ogg", false, 0.1, -100);
				soundCounter = random(15, 55);
			}
		}
		else soundCounter--;

		if(burpCounter)
		{
			burpCounter--;
			if(!burpCounter)
			{
				int s = random(0, 1);
				std::string sound;
				if(s == 0) sound = "enemy1_burp1.ogg";
				else if(s == 1) sound = "enemy1_burp2.ogg";
				Engine::inst().playSound(sound, false, 0.1);

				// Rülpspartikel erzeugen
				ParticleSystem* p_particleSystem = level.getParticleSystem();
				ParticleSystem::Particle p;
				for(int i = 0; i < 10; i++)
				{
					p.lifetime = random(50, 75);
					p.damping = 0.99f;
					p.gravity = random(-0.005f, -0.02f);
					p.positionOnTexture = Vec2b(96, 32);
					p.sizeOnTexture = Vec2b(16, 16);
					p.position = position * 16 + Vec2i(8 + random(-4, 4), 6);
					p.velocity = Vec2d(random(-0.5, 0.5), random(-1.0, -0.5));
					p.color = Vec4d(random(0.8, 1.0), random(0.8, 1.0), random(0.8, 1.0), 0.25);
					p.deltaColor = Vec4d(0.0, 0.0, 0.0, -p.color.a / p.lifetime);
					p.rotation = random(-0.5f, 0.5f);
					p.deltaRotation = random(-0.05f, 0.05f);
					p.size = random(0.2f, 1.0f);
					p.deltaSize = random(0.0f, 0.01f);
					p_particleSystem->addParticle(p);
				}
			}
		}
	}
	else if(subType == 1)
	{
		if(random() % 2) anim++;

		if(moveCounter-- <= 0)
		{
			int r = random(0, 1);
			if(interest > 6000) r = random(0, 50);

			if(contamination < 50)
			{
				if(random() % 2) r = 0;
			}

			interest /= 2;

			switch(r)
			{
			case 0:
				tryToMove(intToDir(random(0, 4)));
				break;
			default:
				if(targetPosition.x != -1)
				{
					// zum Ziel laufen
					Vec2i toTarget = targetPosition - position;
					if(toTarget.x && toTarget.y) toTarget.value[random(0, 1)] = 0;
					int d = dirToInt(toTarget);
					toTarget = intToDir(d);
					if(tryToMove(toTarget)) interest *= 2;
				}
				else
				{
					// Wo ist die Spur am heißesten?
					int bestDir = 0;
					uint bestTrace = 0;
					for(int dir = 0; dir < 4; dir++)
					{
						uint trace = level.getAITrace(position + intToDir(dir));
						if(trace > bestTrace)
						{
							bestTrace = trace;
							bestDir = dir;
						}
					}

					if(bestTrace)
					{
						Vec2i bestDirV = intToDir(bestDir);
						if(!tryToMove(bestDirV))
						{
							// Das ging nicht. Ist da ein anderer Gegner?
							bool reduceTrace = true;
							Object* p_obj = level.getFrontObjectAt(position + bestDirV);
							if(p_obj)
							{
								// Wenn da ein anderer Gegner ist, ist es egal.
								if(p_obj->getType() == "Enemy") reduceTrace = false;
							}

							if(reduceTrace)
							{
								// Die Spur dort etwas uninteressanter machen!
								level.setAITrace(position + bestDirV, bestTrace / 2);
							}
						}
						else
						{
							if(bestTrace > 850) interest = 160000;
							else if(bestTrace > 100) interest = 20000;
						}
					}
				}
				break;
			}

			if(position == targetPosition || interest < 10)
			{
				targetPosition = Vec2i(-1, -1);
				interest = 0;
			}

			moveCounter = random(4, 7);
		}

		if(height == 0.0)
		{
			if(!(random() % 25))
			{
				vy = random(40.0, 80.0);
				height = 0.5;
			}
		}
		else
		{
			height += 0.02 * vy;
			vy -= 0.02 * 400.0;

			if(height < 0.5)
			{
				height = 0.0;
				vy = 0.0;
			}
		}

		int pr = 700;
		if(interest >= 10000) pr = 350;
		if(!(random() % pr))
		{
			// Lachen abspielen
			Engine::inst().playSound("enemy2_laugh.ogg", false, 0.15, -100);
		}

		if(interest >= 40000)
		{
			if(!(random() % 200))
			{
				// Knurren abspielen
				Engine::inst().playSound("enemy2_growl.ogg", false, 0.15, -100);
			}
		}

		if(interest >= 10000)
		{
			// Feuer
			ParticleSystem* p_particleSystem = level.getParticleSystem();
			ParticleSystem* p_fireParticleSystem = level.getFireParticleSystem();
			ParticleSystem::Particle p;
			p.lifetime = random(40, 50);
			p.damping = 0.9f;
			p.gravity = -0.04f;
			p.positionOnTexture = Vec2b(32, 0);
			p.sizeOnTexture = Vec2b(16, 16);
			const double r = random(0.0, 6.283);
			const Vec2d vr(sin(r), cos(r));
			p.position = position * 16 + Vec2d(7.5, 7.5 - height) + 7.5 * vr;
			p.velocity = vr;
			p.color = Vec4d(random(0.5, 1.0), random(0.8, 1.0), random(0.0, 0.25), random(0.2, 0.4));
			const double dc = -1.5 / (p.lifetime + random(-25, 25));
			p.deltaColor = Vec4d(dc, dc, dc, -p.color.a / p.lifetime);
			p.rotation = random(0.0f, 10.0f);
			p.deltaRotation = random(-0.1f, 0.1f);
			p.size = random(0.5f, 0.9f);
			p.deltaSize = random(0.0075f, 0.015f);
			if(random() % 2) p_particleSystem->addParticle(p);
			else p_fireParticleSystem->addParticle(p);
		}
	}

	if(eatCounter) eatCounter--;
}