Esempio n. 1
0
int main ( )

/******************************************************************************/
/*
  Purpose:

    D_SAMPLE_ST tests the SUPERLU solver with a 5x5 double precision real matrix.

  Discussion:

    The general (GE) representation of the matrix is:

      [ 19  0 21 21  0
        12 21  0  0  0
         0 12 16  0  0 
         0  0  0  5 21
        12 12  0  0 18 ]

    The (0-based) compressed column (CC) representation of this matrix is:

      I  CC   A
     --  --  --
      0   0  19
      1      12
      4      12

      1   3  21
      2      12
      4      12

      0   6  21
      2      16

      0   8  21
      3       5

      3  10  21
      4      18

      *  12   *

    The right hand side B and solution X are

      #   B     X
     --  --  ----------
      0   1  -0.03125
      1   1   0.0654762
      2   1   0.0133929
      3   1   0.0625
      4   1   0.0327381 

  Licensing:

    This code is distributed under the GNU LGPL license. 

  Modified:

    18 July 2014

  Author:

    John Burkardt

  Reference:

    James Demmel, John Gilbert, Xiaoye Li,
    SuperLU Users's Guide.
*/
{
  SuperMatrix A;
  double *acc;
  double *b;
  double *b2;
  SuperMatrix B;
  int *ccc;
  int i;
  int *icc;
  int info;
  int j;
  SuperMatrix L;
  int m;
  int n;
  int nrhs = 1;
  int ncc;
  superlu_options_t options;
  int *perm_c;
  int permc_spec;
  int *perm_r;
  SuperLUStat_t stat;
  SuperMatrix U;

  timestamp ( );
  printf ( "\n" );
  printf ( "D_SAMPLE_ST:\n" );
  printf ( "  C version\n" );
  printf ( "  SUPERLU solves a double precision real linear system.\n" );
  printf ( "  The matrix is read from a Sparse Triplet (ST) file.\n" );
/*
  Read the matrix from a file associated with standard input,
  in sparse triplet (ST) format, into compressed column (CC) format.
*/
  dreadtriple ( &m, &n, &ncc, &acc, &icc, &ccc );
/*
  Print the matrix.
*/
  cc_print ( m, n, ncc, icc, ccc, acc, "  CC Matrix:" );
/*
  Convert the compressed column (CC) matrix into a SuperMatrix A. 
*/
  dCreate_CompCol_Matrix ( &A, m, n, ncc, acc, icc, ccc, SLU_NC, SLU_D, SLU_GE );    
/*
  Create the right-hand side matrix.
*/
  b = ( double * ) malloc ( m * sizeof ( double ) );
  for ( i = 0; i < m; i++ )
  {
    b[i] = 1.0;
  }
  printf ( "\n" );
  printf ( "  Right hand side:\n" );
  printf ( "\n" );
  for ( i = 0; i < m; i++ )
  {
    printf ( "%g\n", b[i] );
  }
/*
  Create Super Right Hand Side.
*/
  dCreate_Dense_Matrix ( &B, m, nrhs, b, m, SLU_DN, SLU_D, SLU_GE );
/*
  Set space for the permutations.
*/
  perm_r = ( int * ) malloc ( m * sizeof ( int ) );
  perm_c = ( int * ) malloc ( n * sizeof ( int ) );
/*
  Set the input options. 
*/
  set_default_options ( &options );
  options.ColPerm = NATURAL;
/*
  Initialize the statistics variables. 
*/
  StatInit ( &stat );
/*
  Solve the linear system. 
*/
  dgssv ( &options, &A, perm_c, perm_r, &L, &U, &B, &stat, &info );
    
  dPrint_CompCol_Matrix ( ( char * ) "A", &A );
  dPrint_CompCol_Matrix ( ( char * ) "U", &U );
  dPrint_SuperNode_Matrix ( ( char * ) "L", &L );
  print_int_vec ( ( char * ) "\nperm_r", m, perm_r );
/*
  By some miracle involving addresses, 
  the solution has been put into the B vector.
*/
  printf ( "\n" );
  printf ( "  Computed solution:\n" );
  printf ( "\n" );
  for ( i = 0; i < m; i++ )
  {
    printf ( "%g\n", b[i] );
  }
/*
  Demonstrate that RHS is really the solution now.
  Multiply it by the matrix.
*/
  b2 = cc_mv ( m, n, ncc, icc, ccc, acc, b );
  printf ( "\n" );
  printf ( "  Product A*X:\n" );
  printf ( "\n" );
  for ( i = 0; i < m; i++ )
  {
    printf ( "%g\n", b2[i] );
  }
/*
  Free memory.
*/
  free ( b );
  free ( b2 );
  free ( perm_c );
  free ( perm_r );

  Destroy_SuperMatrix_Store ( &A );
  Destroy_SuperMatrix_Store ( &B );
  Destroy_SuperNode_Matrix ( &L );
  Destroy_CompCol_Matrix ( &U );
  StatFree ( &stat );
/*
  Terminate.
*/
  printf ( "\n" );
  printf ( "D_SAMPLE_ST:\n" );
  printf ( "  Normal end of execution.\n" );
  printf ( "\n" );
  timestamp ( );

  return 0;
}
Esempio n. 2
0
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */

#include "MAC.h"
#include "PHY.h"
#include "Terminal.h"
#include "Profiler.h"
#include "Standard.h"

////////////////////////////////////////////////////////////////////////////////
// IEEE 802.11a constant parameters                                           //
////////////////////////////////////////////////////////////////////////////////
const timestamp aSlotTime = timestamp(9.0e-6);
const timestamp DIFS = timestamp(34.0e-6);
const timestamp SIFS = timestamp(16.0e-6);

// timeout intervals
inline timestamp ACK_Timeout(transmission_mode m) {
	return SIFS + ack_duration(m) + 5;
}
inline timestamp BA_Timeout(transmission_mode m) {
	return SIFS + ba_duration(m) + 5;
}

////////////////////////////////////////////////////////////////////////////////
// class MAC                                                                  //
////////////////////////////////////////////////////////////////////////////////
Esempio n. 3
0
main(
  int    argc,
  char * argv[])
{
  int    buf[Chunk / IntSize];
  int    bufindex;
  int    chars[256];
  int    child;
  char * dir;
  int    html = 0;
  int    fd;
  double first_start;
  double last_stop;
  int    lseek_count = 0;
  char * machine;
  char   name[Chunk];
  int    next;
  int    seek_control[2];
  int    seek_feedback[2];
  char   seek_tickets[Seeks + SeekProcCount];
  double seeker_report[3];
  off_t  size;
  FILE * stream;
  off_t  words;

  fd = -1;
  basetime = (int) time((time_t *) NULL);
  size = 100;
  dir = ".";
  machine = "";

  /* pick apart args */
  for (next = 1; next < argc; next++)
    if (strcmp(argv[next], "-d") == 0)
      dir = argv[++next];
    else if (strcmp(argv[next], "-s") == 0)
      size = atol(argv[++next]);
    else if (strcmp(argv[next], "-m") == 0)
      machine = argv[++next];
    else if (strcmp(argv[next], "-html") == 0)
      html = 1;
    else
      usage();

  if (size < 1)
    usage();

  /* sanity check - 32-bit machines can't handle more than 2047 Mb */
  if (sizeof(off_t) <= 4 && size > 2047)
  {
    fprintf(stderr, "File too large for 32-bit machine, sorry\n");
    exit(1);
  }

  sprintf(name, "%s/Bonnie.%d", dir, getpid());

  /* size is in meg, rounded down to multiple of Chunk */
  size *= (1024 * 1024);
  size = Chunk * (size / Chunk);
  fprintf(stderr, "File '%s', size: %ld\n", name, size);

  /* Fill up a file, writing it a char at a time with the stdio putc() call */
  fprintf(stderr, "Writing with putc()...");
  newfile(name, &fd, &stream, 1);
  timestamp();
  for (words = 0; words < size; words++)
    if (putc(words & 0x7f, stream) == EOF)
      io_error("putc");
  
  /*
   * note that we always close the file before measuring time, in an
   *  effort to force as much of the I/O out as we can
   */
  if (fclose(stream) == -1)
    io_error("fclose after putc");
  get_delta_t(Putc);
  fprintf(stderr, "done\n");

  /* Now read & rewrite it using block I/O.  Dirty one word in each block */
  newfile(name, &fd, &stream, 0);
  if (lseek(fd, (off_t) 0, 0) == (off_t) -1)
    io_error("lseek(2) before rewrite");
  fprintf(stderr, "Rewriting...");
  timestamp();
  bufindex = 0;
  if ((words = read(fd, (char *) buf, Chunk)) == -1)
    io_error("rewrite read");
  while (words == Chunk)
  { /* while we can read a block */
    if (bufindex == Chunk / IntSize)
      bufindex = 0;
    buf[bufindex++]++;
    if (lseek(fd, (off_t) -words, 1) == -1)
      io_error("relative lseek(2)");
    if (write(fd, (char *) buf, words) == -1)
      io_error("re write(2)");
    if ((words = read(fd, (char *) buf, Chunk)) == -1)
      io_error("rwrite read");
  } /* while we can read a block */
  if (close(fd) == -1)
    io_error("close after rewrite");
  get_delta_t(ReWrite);
  fprintf(stderr, "done\n");

  /* Write the whole file from scratch, again, with block I/O */
  newfile(name, &fd, &stream, 1);
  fprintf(stderr, "Writing intelligently...");
  for (words = 0; words < Chunk / IntSize; words++)
    buf[words] = 0;
  timestamp();
  for (words = bufindex = 0; words < (size / Chunk); words++)
  { /* for each word */
    if (bufindex == (Chunk / IntSize))
      bufindex = 0;
    buf[bufindex++]++;
    if (write(fd, (char *) buf, Chunk) == -1)
      io_error("write(2)");
  } /* for each word */
  if (close(fd) == -1)
    io_error("close after fast write");
  get_delta_t(FastWrite);
  fprintf(stderr, "done\n");

  /* read them all back with getc() */
  newfile(name, &fd, &stream, 0);
  for (words = 0; words < 256; words++)
    chars[words] = 0;
  fprintf(stderr, "Reading with getc()...");
  timestamp();
  for (words = 0; words < size; words++)
  { /* for each byte */
    if ((next = getc(stream)) == EOF)
      io_error("getc(3)");

    /* just to fool optimizers */
    chars[next]++;
  } /* for each byte */
  if (fclose(stream) == -1)
    io_error("fclose after getc");
  get_delta_t(Getc);
  fprintf(stderr, "done\n");

  /* use the frequency count */
  for (words = 0; words < 256; words++)
    sprintf((char *) buf, "%d", chars[words]);

  /* Now suck it in, Chunk at a time, as fast as we can */
  newfile(name, &fd, &stream, 0);
  if (lseek(fd, (off_t) 0, 0) == -1)
    io_error("lseek before read");
  fprintf(stderr, "Reading intelligently...");
  timestamp();
  do
  { /* per block */
    if ((words = read(fd, (char *) buf, Chunk)) == -1)
      io_error("read(2)");
    chars[buf[abs(buf[0]) % (Chunk / IntSize)] & 0x7f]++;
  } /* per block */
  while (words);
  if (close(fd) == -1)
    io_error("close after read");
  get_delta_t(FastRead);
  fprintf(stderr, "done\n");

  /* use the frequency count */
  for (words = 0; words < 256; words++)
    sprintf((char *) buf, "%d", chars[words]);

  /*
   * Now test random seeks; first, set up for communicating with children.
   * The object of the game is to do "Seeks" lseek() calls as quickly
   *  as possible.  So we'll farm them out among SeekProcCount processes.
   *  We'll control them by writing 1-byte tickets down a pipe which
   *  the children all read.  We write "Seeks" bytes with val 1, whichever
   *  child happens to get them does it and the right number of seeks get
   *  done.
   * The idea is that since the write() of the tickets is probably
   *  atomic, the parent process likely won't get scheduled while the
   *  children are seeking away.  If you draw a picture of the likely
   *  timelines for three children, it seems likely that the seeks will
   *  overlap very nicely with the process scheduling with the effect
   *  that there will *always* be a seek() outstanding on the file.
   * Question: should the file be opened *before* the fork, so that
   *  all the children are lseeking on the same underlying file object?
   */
  if (pipe(seek_feedback) == -1 || pipe(seek_control) == -1)
    io_error("pipe");
  for (next = 0; next < Seeks; next++)
    seek_tickets[next] = 1;
  for ( ; next < (Seeks + SeekProcCount); next++)
    seek_tickets[next] = 0;

  /* launch some parallel seek processes */
  for (next = 0; next < SeekProcCount; next++)
  { /* for each seek proc */
    if ((child = fork()) == -1)
      io_error("fork");
    else if (child == 0)
    { /* child process */

      /* set up and wait for the go-ahead */
      close(seek_feedback[0]);
      close(seek_control[1]);
      newfile(name, &fd, &stream, 0);
      srandom(getpid());
      fprintf(stderr, "Seeker %d...", next + 1);

      /* wait for the go-ahead */
      if (read(seek_control[0], seek_tickets, 1) != 1)
	io_error("read ticket");
      timestamp();
      seeker_report[StartTime] = time_so_far();

      /* loop until we read a 0 ticket back from our parent */
      while(seek_tickets[0])
      { /* until Mom says stop */
        doseek((long) (random() % (size / Chunk)), fd,
	  ((lseek_count++ % UpdateSeek) == 0));
	if (read(seek_control[0], seek_tickets, 1) != 1)
	  io_error("read ticket");
      } /* until Mom says stop */
      if (close(fd) == -1)
        io_error("close after seek");

      /* report to parent */
      get_delta_t(Lseek);
      seeker_report[EndTime] = time_so_far();
      seeker_report[CPU] = delta[(int) Lseek][CPU];
      if (write(seek_feedback[1], seeker_report, sizeof(seeker_report))
          != sizeof(seeker_report))
        io_error("pipe write");
      exit(0);
    } /* child process */
  } /* for each seek proc */

  /*
   * Back in the parent; in an effort to ensure the children get an even
   *  start, wait a few seconds for them to get scheduled, open their
   *  files & so on.
   */
  close(seek_feedback[1]);
  close(seek_control[0]);
  sleep(5);
  fprintf(stderr, "start 'em...");
  if (write(seek_control[1], seek_tickets, sizeof(seek_tickets)) 
      != sizeof(seek_tickets))
    io_error("write tickets");
  
  /* read back from children */
  for (next = 0; next < SeekProcCount; next++)
  { /* for each child */
    if (read(seek_feedback[0], (char *) seeker_report, sizeof(seeker_report))
        != sizeof(seeker_report))
      io_error("pipe read");

    /*
     * each child writes back its CPU, start & end times.  The elapsed time 
     *  to do all the seeks is the time the first child started until the 
     *  time the last child stopped
     */
    delta[(int) Lseek][CPU] += seeker_report[CPU];
    if (next == 0)
    { /* first time */
      first_start = seeker_report[StartTime];
      last_stop = seeker_report[EndTime];
    } /* first time */
    else
    { /* not first time */
      first_start = (first_start < seeker_report[StartTime]) ?
	first_start : seeker_report[StartTime]; 
      last_stop = (last_stop > seeker_report[EndTime]) ?
	last_stop : seeker_report[EndTime]; 
    } /* not first time */
    if (wait(&child) == -1)
      io_error("wait");
    fprintf(stderr, "done...");
  } /* for each child */
  fprintf(stderr, "\n");
  delta[(int) Lseek][Elapsed] = last_stop - first_start;

  if (html)
    write_html(machine, size);
  else
    report(machine, size);
  unlink(name);
}
Esempio n. 4
0
mapreducehelper::mapreducehelper(int &argc, char **&argv) {
	mrh_singleton = this;
	mapreduce_out_ = NULL;
	mode_mapreduce_ = NONE;
	mode_bangbang_ = false;
	requested_mapper_count_ = -1;
	ID_ = -1;
	ID_str_ = "";
	n_processes_written_ = 0;
	int mapreduce_argc = 0;
	const char *bangbang="-mpi";
	const char *mapper="-mapper";
	const char *reducer="-reducer";
	const char *test="-mapreduceinstalltest";
	const char *reportURL="-reportURL"; // this should appear only in final reducer call
	const char *modestr = "x!tandem";
	if ((argc > 1 && (!strcmp(argv[1],test))))	{
		std::cout << timestamp() << "mapreduce xtandem install appears to be good!\n";
		exit(0); // just making sure it can be run
	}
	if (argc > 1 && (!strcmp(argv[1],bangbang)))	{
		init_mode_bangbang(argc,argv);
		mapreduce_argc = 1; // need to eat that -mpi arg
	} else if ((argc > 1 && (!strncmp(argv[1],mapper,strlen(mapper))||!strncmp(argv[1],reducer,strlen(reducer)))))	{
		if (argc < 4) {
			cerr << "usage for mapreduce: " << argv[0] << " -<mapper|reduce><step> <outdir> <paramsFile> [-reportURL <URL>]\n";
			exit(0); // yes, an error but keep hadoop flow going so we can get logs easily
		}
		bool ismapper = !strncmp(argv[1],mapper,strlen(mapper));
		const char *num = argv[1]+(int)(ismapper?strlen(mapper):strlen(reducer));
		stdcerrcout_tee *ot,*st;
		step_mapreduce_ = atoi(num);
		modetext_ = argv[1]+1;
		// for local debugging, can specify -mapper1.2.3 to mean "pretend you are task 2 and 3 for MAPPER_1 step"
		// for reducer, can specify ideal output count, as -reducer1.50 to mean "assume 50 mappers"
		const char *dot = strchr(num,'.');
		if (dot) {
			modetext_.erase(modetext_.find("."));
			do {
				if (ismapper) {
					task_mapreduce_.push_back(atoi(dot+1));
				} else {
					requested_mapper_count_ = atoi(dot+1);
				} 
			} while (dot = strchr(dot+1,'.'));
		}
		modestr = modetext_.c_str();
		int totalproc = 0;
		bool final = false;
		std::stringstream msg;
		if (argc > 4) {  // final result URL given?
			if (strncmp(argv[4],reportURL,strlen(reportURL))) {
				fprintf(stderr, "unexpected argument \"%s\"\n",argv[4]);
				exit(0);  // yes, an error but keep hadoop flow going so we can get logs easily
			}
			// looking for possible "-reportURLS3"
			if (!strcmp(argv[4]+strlen(reportURL),"S3")) {
				report_URL_ = "s3n://";
			} 
			report_URL_ += argv[5];
			argc = 4; // done with these args
			final = true;
		}

		if (ismapper) {
			switch (step_mapreduce_) {
				case 1: 
					{
					// mapper1 expects one or more stdin lines
					// just emits a single line to tell reducer1 its here
					mode_mapreduce_ = MAPPER_1;
					std::string line;
					num_processes_ = 0;
					while (getline(cin,line)) {
						num_processes_++;
					}
					if (!num_processes_) {
						fprintf(stderr, "%s", msg.str().c_str());
					} else { // emit a line to say we're here, include any info of possible debug interest
						cout << "1\tOK_"<<(getenv("HOSTNAME")?getenv("HOSTNAME"):"");
					}
					exit(0); // that was easy...
					} 
				    break;
				case 2:
					mode_mapreduce_ = MAPPER_2;
					break;
				case 3:
					mode_mapreduce_ = MAPPER_3;
					break;
				default:
					fprintf(stderr, "tandem: unknown mapper step %d, quit\n",step_mapreduce_);
					exit(0);  // yes, an error but keep hadoop flow going so we can get logs easily
					break;
			}
		} else {
			// everybody else expects one or more stdin lines of form 
			// "<int key> <length of base64 string><tab><length of data after decompressing><tab><base64'ed data>"
			// or
			// "<int key> <filename reference>"
			switch (step_mapreduce_) {
				case 1:
					mode_mapreduce_ = REDUCER_1;
					break;
				case 2:
					mode_mapreduce_ = REDUCER_2;
					break;
				case 3:
					mode_mapreduce_ = REDUCER_3;
					break;
				case 99:  // special mode for performance comparison
					argv[1] = argv[3];
					argc = 2;
					msg << "oldSkool mode: running as normal tandem.\n";
					ot= new stdcerrcout_tee(std::cout); // write cout to stderr and stdout
					st= new stdcerrcout_tee(std::cerr); // write cerr to stderr and stdout
					mode_mapreduce_ = NONE;
					if (report_URL_.length()) {
						exit_cmd = "hadoop dfs -put ";
						exit_cmd += argv[2];
						exit_cmd += " ";
						exit_cmd += report_URL_;
						atexit(run_exit_cmd);
					}
					break;
				default:
					fprintf(stderr, "unknown reducer step %d\n",step_mapreduce_);
					exit(0);  // yes, an error but keep hadoop flow going so we can get logs easily
					break;
			   }
		}
		if (final |= (REDUCER_3==mode_mapreduce_)) {
			msg << "This reducer is running as final step.\n";
		}
		if (NONE != mode_mapreduce_) {
			// std::cout is for interprocess communication in mapreduce
			// so redirect current use of stdout to stderr instead
			glob_cerr_tee_ = new cerr_tee(final && (report_URL_ != ".")); // intercept data headed to cerr, save then pass through for heartbeat
			std::streambuf *cout_buffer = std::cout.rdbuf(std::cerr.rdbuf()); 
			mapreduce_out_ = new ostream(cout_buffer); 
			atexit(workerthread_cleanup); // push everything to stdout
		}
Esempio n. 5
0
//-------------------------------------------------------------------------------------
int SelectPoller::processPendingEvents(double maxWait)
{
	fd_set	readFDs;
	fd_set	writeFDs;
	struct timeval		nextTimeout;

	FD_ZERO(&readFDs);
	FD_ZERO(&writeFDs);

	readFDs = fdReadSet_;
	writeFDs = fdWriteSet_;

	nextTimeout.tv_sec = (int)maxWait;
	nextTimeout.tv_usec =
		(int)((maxWait - (double)nextTimeout.tv_sec) * 1000000.0);

#if ENABLE_WATCHERS
	g_idleProfile.start();
#else
	uint64 startTime = timestamp();
#endif

	KBEConcurrency::startMainThreadIdling();

	int countReady = 0;

#ifdef _WIN32
	if (fdLargest_ == -1)
	{
		// Windows can't handle it if we don't have any FDs to select on, but
		// we have a non-NULL timeout.
		Sleep(int(maxWait * 1000.0));
	}
	else
#endif
	{
		countReady = select(fdLargest_+1, &readFDs,
				fdWriteCount_ ? &writeFDs : NULL, NULL, &nextTimeout);
	}

	KBEConcurrency::endMainThreadIdling();

#if ENABLE_WATCHERS
	g_idleProfile.stop();
	spareTime_ += g_idleProfile.lastTime_;
#else
	spareTime_ += timestamp() - startTime;
#endif
	
	if (countReady > 0)
	{
		this->handleInputNotifications(countReady, readFDs, writeFDs);
	}
	else if (countReady == -1)
	{
		// TODO: Clean this up on shutdown
		// if (!breakProcessing_)
		{
			WARNING_MSG(boost::format("EventDispatcher::processContinuously: "
				"error in select(): %1%\n") % kbe_strerror());
		}
	}

	return countReady;
}
Esempio n. 6
0
 void updateLastReceivedTime()		{
     lastReceivedTime_ = timestamp();
 }
void trail_set_stamp(trail *trailp)
{
	trailp->trail_stamp = timestamp(trailp->info.stamp);
}
Esempio n. 8
0
// Initialize the dead popup data
void popupdead_start()
{
	int			i;
	UI_BUTTON	*b;

	if ( Popupdead_active ) {
		return;
	}

	// increment number of deaths
	Player->failures_this_session++;


	// create base window
	Popupdead_window.create(Popupdead_background_coords[gr_screen.res][0], Popupdead_background_coords[gr_screen.res][1], 1, 1, 0);
	Popupdead_window.set_foreground_bmap(Popupdead_background_filename[gr_screen.res]);

	Popupdead_num_choices = 0;
	Popupdead_multi_type = -1;

	if ((The_mission.max_respawn_delay >= 0) && ( Game_mode & GM_MULTIPLAYER )) {
		Popupdead_timer = timestamp(The_mission.max_respawn_delay * 1000); 
		if (Game_mode & GM_MULTIPLAYER) {
			if(!(Net_player->flags & NETINFO_FLAG_LIMBO)){
				if (The_mission.max_respawn_delay) {
					HUD_printf("Player will automatically respawn in %d seconds", The_mission.max_respawn_delay);
				}
				else {
					HUD_printf("Player will automatically respawn now"); 
				}
			}
		}
	}

	if ( Game_mode & GM_NORMAL ) {
		// also do a campaign check here?
		if (0) { //((Player->show_skip_popup) && (!Popupdead_skip_already_shown) && (Game_mode & GM_CAMPAIGN_MODE) && (Game_mode & GM_NORMAL) && (Player->failures_this_session >= PLAYER_MISSION_FAILURE_LIMIT)) {
			// init the special preliminary death popup that gives the skip option
			Popupdead_button_text[0] = XSTR( "Do Not Skip This Mission", 1473);
			Popupdead_button_text[1] = XSTR( "Advance To The Next Mission", 1474);
			Popupdead_button_text[2] = XSTR( "Don't Show Me This Again", 1475);
			Popupdead_num_choices = POPUPDEAD_NUM_CHOICES_SKIP;
			Popupdead_skip_active = 1;
		} else if(The_mission.flags & MISSION_FLAG_RED_ALERT) {
			// We can't staticly declare these because they are externalized
			Popupdead_button_text[0] = XSTR( "Quick Start Mission", 105);
			Popupdead_button_text[1] = XSTR( "Return To Flight Deck", 106);
			Popupdead_button_text[2] = XSTR( "Return To Briefing", 107);
			Popupdead_button_text[3] = XSTR( "Replay previous mission", 1432);
			Popupdead_num_choices = POPUPDEAD_NUM_CHOICES_RA;
		} else {
			Popupdead_button_text[0] = XSTR( "Quick Start Mission", 105);
			Popupdead_button_text[1] = XSTR( "Return To Flight Deck", 106);
			Popupdead_button_text[2] = XSTR( "Return To Briefing", 107);
			Popupdead_num_choices = POPUPDEAD_NUM_CHOICES;
		}
	} else {
		// in multiplayer, we have different choices depending on respawn mode, etc.

		// if the player has run out of respawns and must either quit and become an observer
		if(Net_player->flags & NETINFO_FLAG_LIMBO){

			// the master should not be able to quit the game
			if( ((Net_player->flags & NETINFO_FLAG_AM_MASTER) && (multi_num_players() > 1)) || (Net_player->flags & NETINFO_FLAG_TEAM_CAPTAIN) ) {
				Popupdead_button_text[0] = XSTR( "Observer Mode", 108);
				Popupdead_num_choices = 1;
				Popupdead_multi_type = POPUPDEAD_OBS_ONLY;
			} else {
				Popupdead_button_text[0] = XSTR( "Observer Mode", 108);
				Popupdead_button_text[1] = XSTR( "Return To Flight Deck", 106);
				Popupdead_num_choices = 2;
				Popupdead_multi_type = POPUPDEAD_OBS_QUIT;
			}
		} else {
			// the master of the game should not be allowed to quit
			if ( ((Net_player->flags & NETINFO_FLAG_AM_MASTER) && (multi_num_players() > 1)) || (Net_player->flags & NETINFO_FLAG_TEAM_CAPTAIN) ) {
				Popupdead_button_text[0] = XSTR( "Respawn", 109);
				Popupdead_num_choices = 1;
				Popupdead_multi_type = POPUPDEAD_RESPAWN_ONLY;
			} else {
				Popupdead_button_text[0] = XSTR( "Respawn", 109);
				if(!Cmdline_mpnoreturn)
				{
					Popupdead_button_text[1] = XSTR( "Return To Flight Deck", 106);
					Popupdead_num_choices = 2;
				}
				else
				{
					Popupdead_num_choices = 1;
				}
				Popupdead_multi_type = POPUPDEAD_RESPAWN_QUIT;
			}
		}
	}

	// create buttons
	for (i=0; i < Popupdead_num_choices; i++) {
		b = &Popupdead_buttons[i];
		b->create(&Popupdead_window, "", Popupdead_button_coords[gr_screen.res][i][0], Popupdead_button_coords[gr_screen.res][i][1], 30, 20, 0, 1);
		b->set_bmaps(Popupdead_button_filenames[gr_screen.res][i], 3, 0);
		b->set_highlight_action(common_play_highlight_sound);

		// create invisible buttons to detect mouse presses... can't use mask since button region is dynamically sized
		int lx, w, h;
		gr_get_string_size(&w, &h, Popupdead_button_text[i]);
		lx = Popupdead_region_coords[gr_screen.res][i][0] - w;
		b = &Popupdead_button_regions[i];	
		b->create(&Popupdead_window, "", lx, Popupdead_region_coords[gr_screen.res][i][1], Popupdead_region_coords[gr_screen.res][i][2]-lx, Popupdead_region_coords[gr_screen.res][i][3]-Popupdead_region_coords[gr_screen.res][i][1], 0, 1);
		b->hide();
	}
	
	Popupdead_default_choice = 0;
	Popupdead_choice = -1;
	Popupdead_active = 1;
}
Esempio n. 9
0
// -------------------------------------------------------------------------------------------------
// update_ets() is called once per frame for every OBJ_SHIP in the game.  The amount of energy
// to send to the weapons and shields is calculated, and the top ship speed is calculated.  The
// amount of time elapsed from the previous call is passed in as the parameter fl_frametime.
//
// parameters:   obj          ==> object that is updating their energy system
//               fl_frametime ==> game frametime (in seconds)
//
void update_ets(object* objp, float fl_frametime)
{
	float max_new_shield_energy, max_new_weapon_energy, _ss;

	if ( fl_frametime <= 0 ){
		return;
	}

	ship* ship_p = &Ships[objp->instance];
	ship_info* sinfo_p = &Ship_info[ship_p->ship_info_index];
	float max_g=sinfo_p->max_weapon_reserve,
		  max_s=ship_p->ship_max_shield_strength;

	if ( ship_p->flags & SF_DYING ){
		return;
	}

	if ( sinfo_p->power_output == 0 ){
		return;
	}

//	new_energy = fl_frametime * sinfo_p->power_output;

	// update weapon energy
	max_new_weapon_energy = fl_frametime * sinfo_p->max_weapon_regen_per_second * max_g;
	if ( objp->flags & OF_PLAYER_SHIP ) {
		ship_p->weapon_energy += Energy_levels[ship_p->weapon_recharge_index] * max_new_weapon_energy * The_mission.ai_profile->weapon_energy_scale[Game_skill_level];
	} else {
		ship_p->weapon_energy += Energy_levels[ship_p->weapon_recharge_index] * max_new_weapon_energy;
	}

	if ( ship_p->weapon_energy > sinfo_p->max_weapon_reserve ){
		ship_p->weapon_energy = sinfo_p->max_weapon_reserve;
	}

	float shield_delta;
	max_new_shield_energy = fl_frametime * sinfo_p->max_shield_regen_per_second * max_s;
	if ( objp->flags & OF_PLAYER_SHIP ) {
		shield_delta = Energy_levels[ship_p->shield_recharge_index] * max_new_shield_energy * The_mission.ai_profile->shield_energy_scale[Game_skill_level];
	} else {
		shield_delta = Energy_levels[ship_p->shield_recharge_index] * max_new_shield_energy;
	}

	shield_add_strength(objp, shield_delta);

	if ( (_ss = shield_get_strength(objp)) > ship_p->ship_max_shield_strength ){
		for (int i=0; i<objp->n_quadrants; i++){
			objp->shield_quadrant[i] *= ship_p->ship_max_shield_strength / _ss;
		}
	}

	// calculate the top speed of the ship based on the energy flow to engines
	float y = Energy_levels[ship_p->engine_recharge_index];

	ship_p->current_max_speed = ets_get_max_speed(objp, y);

	// AL 11-15-97: Rules for engine strength affecting max speed:
	//						1. if strength >= 0.5 no affect 
	//						2. if strength < 0.5 then max_speed = sqrt(strength)
	//					 
	//					 This will translate to 71% max speed at 50% engines, and 31% max speed at 10% engines
	//
	float strength = ship_get_subsystem_strength(ship_p, SUBSYSTEM_ENGINE);

	// don't let engine strength affect max speed when playing on lowest skill level
	if ( (objp != Player_obj) || (Game_skill_level > 0) ) {
		if ( strength < SHIP_MIN_ENGINES_FOR_FULL_SPEED ) {
			ship_p->current_max_speed *= fl_sqrt(strength);
		}
	}

	if ( timestamp_elapsed(ship_p->next_manage_ets) ) {
		if ( !(objp->flags & OF_PLAYER_SHIP) ) {
			ai_manage_ets(objp);
			ship_p->next_manage_ets = timestamp(AI_MODIFY_ETS_INTERVAL);
		}
		else {
			if ( Weapon_energy_cheat ){
				ship_p->weapon_energy = sinfo_p->max_weapon_reserve;
			}
		}
	}
}
Esempio n. 10
0
int main ( void )

/******************************************************************************/
/*
  Purpose:

    MAIN is the main program for FLOYD_PRB.

  Discussion:

    FLOYD_PRB calls a set of problems for FLOYD.

  Licensing:

    This code is distributed under the GNU LGPL license.

  Modified:

    20 July 2011

  Author:

    John Burkardt
*/
{
  int n;
  double ratio;
  double wtime;

  timestamp ( );

  printf ( "\n" );
  printf ( "FLOYD_PRB\n" );
  printf ( "  C version\n" );
  printf ( "  Test the FLOYD library.\n" );

  test01 ( );
  test02 ( );

  printf ( "\n" );
  printf ( "FLOYD_TEST03\n" );
  printf ( "  Test I4MAT_FLOYD on the MOD(I,J) matrix.\n" );
  printf ( "  The work is roughly N^3.\n" );
  printf ( "\n" );
  printf ( "         N   Time (seconds)  Time/N^3\n" );
  printf ( "\n" );

  n = 1;
  while ( n <= 512 )
  {
    wtime = test03 ( n );
    ratio = 1000000.0 * wtime / ( double ) ( n ) / ( double ) ( n ) / ( double ) ( n );
    printf ( "  %8d  %14f  %14f\n", n, wtime, ratio );
    n = n * 2;
  }
//
//  Terminate.
//
  printf ( "\n" );
  printf ( "FLOYD_PRB\n" );
  printf ( "  Normal end of execution.\n" );

  printf ( "\n" );
  timestamp ( );

  return 0;
}
int main ( )

/******************************************************************************/
/*
  Purpose:

    MAIN is the main program for BARYCENTRIC_INTERP_1D_PRB.

  Discussion:

    BARYCENTRIC_INTERP_1D_PRB tests the BARYCENTRIC_INTERP_1D library.

  Licensing:

    This code is distributed under the GNU LGPL license.

  Modified:

    14 October 2012

  Author:

    John Burkardt
*/
{
    int i;
    int nd;
    int nd_test[6] = { 4, 8, 16, 32, 64, 1000 };
    int nd_test_num = 6;
    int prob;
    int prob_num;

    timestamp ( );
    printf ( "\n" );
    printf ( "BARYCENTRIC_INTERP_1D_PRB:\n" );
    printf ( "  C version\n" );
    printf ( "  Test the BARYCENTRIC_INTERP_1D library.\n" );
    printf ( "  The R8LIB library is needed.\n" );
    printf ( "  These tests need the TEST_INTERP_1D library.\n" );

    prob_num = p00_prob_num ( );

    for ( prob = 1; prob <= prob_num; prob++ )
    {
        for ( i = 0; i < nd_test_num; i++ )
        {
            nd = nd_test[i];
            test01 ( prob, nd );
        }
    }

    for ( prob = 1; prob <= prob_num; prob++ )
    {
        for ( i = 0; i < nd_test_num; i++ )
        {
            nd = nd_test[i];
            test02 ( prob, nd );
        }
    }

    for ( prob = 1; prob <= prob_num; prob++ )
    {
        for ( i = 0; i < nd_test_num; i++ )
        {
            nd = nd_test[i];
            test03 ( prob, nd );
        }
    }
    /*
      Terminate.
    */
    printf ( "\n" );
    printf ( "BARYCENTRIC_INTERP_1D_PRB:\n" );
    printf ( "  Normal end of execution.\n" );
    printf ( "\n" );
    timestamp ( );

    return 0;
}
Esempio n. 12
0
StatusWith<CursorResponse> CursorResponse::parseFromBSON(const BSONObj& cmdResponse) {
    Status cmdStatus = getStatusFromCommandResult(cmdResponse);
    if (!cmdStatus.isOK()) {
        if (ErrorCodes::isStaleShardVersionError(cmdStatus.code())) {
            auto vWanted = ChunkVersion::fromBSON(cmdResponse, "vWanted");
            auto vReceived = ChunkVersion::fromBSON(cmdResponse, "vReceived");
            if (!vWanted.hasEqualEpoch(vReceived)) {
                return Status(ErrorCodes::StaleEpoch, cmdStatus.reason());
            }
        }
        return cmdStatus;
    }

    std::string fullns;
    BSONObj batchObj;
    CursorId cursorId;

    BSONElement cursorElt = cmdResponse[kCursorField];
    if (cursorElt.type() != BSONType::Object) {
        return {ErrorCodes::TypeMismatch,
                str::stream() << "Field '" << kCursorField << "' must be a nested object in: "
                              << cmdResponse};
    }
    BSONObj cursorObj = cursorElt.Obj();

    BSONElement idElt = cursorObj[kIdField];
    if (idElt.type() != BSONType::NumberLong) {
        return {
            ErrorCodes::TypeMismatch,
            str::stream() << "Field '" << kIdField << "' must be of type long in: " << cmdResponse};
    }
    cursorId = idElt.Long();

    BSONElement nsElt = cursorObj[kNsField];
    if (nsElt.type() != BSONType::String) {
        return {ErrorCodes::TypeMismatch,
                str::stream() << "Field '" << kNsField << "' must be of type string in: "
                              << cmdResponse};
    }
    fullns = nsElt.String();

    BSONElement batchElt = cursorObj[kBatchField];
    if (batchElt.eoo()) {
        batchElt = cursorObj[kBatchFieldInitial];
    }

    if (batchElt.type() != BSONType::Array) {
        return {ErrorCodes::TypeMismatch,
                str::stream() << "Must have array field '" << kBatchFieldInitial << "' or '"
                              << kBatchField
                              << "' in: "
                              << cmdResponse};
    }
    batchObj = batchElt.Obj();

    std::vector<BSONObj> batch;
    for (BSONElement elt : batchObj) {
        if (elt.type() != BSONType::Object) {
            return {ErrorCodes::BadValue,
                    str::stream() << "getMore response batch contains a non-object element: "
                                  << elt};
        }

        batch.push_back(elt.Obj());
    }

    for (auto& doc : batch) {
        doc.shareOwnershipWith(cmdResponse);
    }

    auto latestOplogTimestampElem = cmdResponse[kInternalLatestOplogTimestampField];
    if (latestOplogTimestampElem && latestOplogTimestampElem.type() != BSONType::bsonTimestamp) {
        return {
            ErrorCodes::BadValue,
            str::stream()
                << "invalid _internalLatestOplogTimestamp format; expected timestamp but found: "
                << latestOplogTimestampElem.type()};
    }

    auto writeConcernError = cmdResponse["writeConcernError"];

    if (writeConcernError && writeConcernError.type() != BSONType::Object) {
        return {ErrorCodes::BadValue,
                str::stream() << "invalid writeConcernError format; expected object but found: "
                              << writeConcernError.type()};
    }

    return {{NamespaceString(fullns),
             cursorId,
             std::move(batch),
             boost::none,
             latestOplogTimestampElem ? latestOplogTimestampElem.timestamp()
                                      : boost::optional<Timestamp>{},
             writeConcernError ? writeConcernError.Obj().getOwned() : boost::optional<BSONObj>{}}};
}
Esempio n. 13
0
int
make_connection(Peer *peerList)
{
  struct addrinfo hints, *res;
  Peer *elt, *tmp;
  int fd;
  char buf[HEADER_SIZE + PAYLOAD_SIZE];
  int offset;
  int len = HEADER_SIZE+NUM_PEERS_SIZE+IP_SIZE+PORT_SIZE+MAC_SIZE+ID_SIZE;

  LL_FOREACH_SAFE(peerList, elt, tmp)
    {

      // make connection
      memset(&hints, 0, sizeof hints);
      hints.ai_family = AF_INET; // Use IPv4
      hints.ai_socktype = SOCK_STREAM; //Use tcp

      if(getaddrinfo(elt->addr, elt->port, &hints, &res))
	{
	  ERROR("error: getaddrinfo\n", -1);
	}

      if((fd  = socket(res->ai_family, res->ai_socktype, res->ai_protocol)) < 0)
	{
	  ERROR("error: socket\n", -1);
	}

      if(connect(fd, res->ai_addr, res->ai_addrlen))
	{
	  continue;
	}
    
 
      // build packet
      *((uint16_t*)buf) = htons(LINKSTATE);
      offset = TYPE_SIZE;
      *((uint16_t*)(buf+offset)) = htons(len);
      offset += LENGTH_SIZE;
      *((uint16_t*)(buf+offset)) = htons(1);
      offset += NUM_PEERS_SIZE;
      *((uint32_t*)(buf+offset)) = htonl(host->local_ip);
      offset += IP_SIZE;
      *((uint16_t*)(buf+offset)) = htons(host->local_port);
      offset += PORT_SIZE;
      memcpy(buf+offset, host->local_mac, MAC_SIZE);
      offset += MAC_SIZE;
      *((unsigned long long*)(buf+offset)) = timestamp();

      // send the new packet on its way
      writen(fd, buf, len);

      addconnection(elt);

      // clean up
      freeaddrinfo(res);
      LL_DELETE(peerList, elt);
      free(elt->addr);
      free(elt->port);
      free(elt);
    }
int AudioDecoderMediaFoundation::read(int size, const SAMPLE *destination)
{
	assert(size < sizeof(m_destBufferShort));
    if (sDebug) { std::cout << "read() " << size << std::endl; }
	//TODO: Change this up if we want to support just short samples again -- Albert
    SHORT_SAMPLE *destBuffer = m_destBufferShort;
	size_t framesRequested(size / m_iChannels);
    size_t framesNeeded(framesRequested);

    // first, copy frames from leftover buffer IF the leftover buffer is at
    // the correct frame
    if (m_leftoverBufferLength > 0 && m_leftoverBufferPosition == m_nextFrame) {
        copyFrames(destBuffer, &framesNeeded, m_leftoverBuffer,
            m_leftoverBufferLength);
        if (m_leftoverBufferLength > 0) {
            if (framesNeeded != 0) {
                std::cerr << __FILE__ << __LINE__
                           << "WARNING: Expected frames needed to be 0. Abandoning this file.";
                m_dead = true;
            }
            m_leftoverBufferPosition += framesRequested;
        }
    } else {
        // leftoverBuffer already empty or in the wrong position, clear it
        m_leftoverBufferLength = 0;
    }

    while (!m_dead && framesNeeded > 0) {
        HRESULT hr(S_OK);
        DWORD dwFlags(0);
        __int64 timestamp(0);
        IMFSample *pSample(NULL);
        bool error(false); // set to true to break after releasing

        hr = m_pReader->ReadSample(
            MF_SOURCE_READER_FIRST_AUDIO_STREAM, // [in] DWORD dwStreamIndex,
            0,                                   // [in] DWORD dwControlFlags,
            NULL,                                // [out] DWORD *pdwActualStreamIndex,
            &dwFlags,                            // [out] DWORD *pdwStreamFlags,
            &timestamp,                          // [out] LONGLONG *pllTimestamp,
            &pSample);                           // [out] IMFSample **ppSample
        if (FAILED(hr)) {
            if (sDebug) { std::cout << "ReadSample failed." << std::endl; }
            break;
        }

        if (sDebug) {
            std::cout << "ReadSample timestamp: " << timestamp
                     << "frame: " << frameFromMF(timestamp)
                     << "dwflags: " << dwFlags
					 << std::endl;
        }

        if (dwFlags & MF_SOURCE_READERF_ERROR) {
            // our source reader is now dead, according to the docs
            std::cerr << "SSMF: ReadSample set ERROR, SourceReader is now dead";
            m_dead = true;
            break;
        } else if (dwFlags & MF_SOURCE_READERF_ENDOFSTREAM) {
            std::cout << "SSMF: End of input file." << std::endl;
            break;
        } else if (dwFlags & MF_SOURCE_READERF_CURRENTMEDIATYPECHANGED) {
            std::cerr << "SSMF: Type change";
            break;
        } else if (pSample == NULL) {
            // generally this will happen when dwFlags contains ENDOFSTREAM,
            // so it'll be caught before now -bkgood
            std::cerr << "SSMF: No sample";
            continue;
        } // we now own a ref to the instance at pSample

        IMFMediaBuffer *pMBuffer(NULL);
        // I know this does at least a memcopy and maybe a malloc, if we have
        // xrun issues with this we might want to look into using
        // IMFSample::GetBufferByIndex (although MS doesn't recommend this)
        if (FAILED(hr = pSample->ConvertToContiguousBuffer(&pMBuffer))) {
            error = true;
            goto releaseSample;
        }
        short *buffer(NULL);
        size_t bufferLength(0);
        hr = pMBuffer->Lock(reinterpret_cast<unsigned __int8**>(&buffer), NULL,
            reinterpret_cast<DWORD*>(&bufferLength));
        if (FAILED(hr)) {
            error = true;
            goto releaseMBuffer;
        }
        bufferLength /= (m_iBitsPerSample / 8 * m_iChannels); // now in frames

        if (m_seeking) {
            __int64 bufferPosition(frameFromMF(timestamp));
            if (sDebug) {
                std::cout << "While seeking to "
                         << m_nextFrame << "WMF put us at " << bufferPosition
						 << std::endl;

            }
            if (m_nextFrame < bufferPosition) {
                // Uh oh. We are farther forward than our seek target. Emit
                // silence? We can't seek backwards here.
                SHORT_SAMPLE* pBufferCurpos = destBuffer +
                        (size - framesNeeded * m_iChannels);
                __int64 offshootFrames = bufferPosition - m_nextFrame;

                // If we can correct this immediately, write zeros and adjust
                // m_nextFrame to pretend it never happened.

                if (offshootFrames <= framesNeeded) {
                    std::cerr << __FILE__ << __LINE__
                               << "Working around inaccurate seeking. Writing silence for"
                               << offshootFrames << "frames";
                    // Set offshootFrames * m_iChannels samples to zero.
                    memset(pBufferCurpos, 0,
                           sizeof(*pBufferCurpos) * offshootFrames *
                           m_iChannels);
                    // Now m_nextFrame == bufferPosition
                    m_nextFrame += offshootFrames;
                    framesNeeded -= offshootFrames;
                } else {
                    // It's more complicated. The buffer we have just decoded is
                    // more than framesNeeded frames away from us. It's too hard
                    // for us to handle this correctly currently, so let's just
                    // try to get on with our lives.
                    m_seeking = false;
                    m_nextFrame = bufferPosition;
                    std::cerr << __FILE__ << __LINE__
                               << "Seek offshoot is too drastic. Cutting losses and pretending the current decoded audio buffer is the right seek point.";
                }
            }

            if (m_nextFrame >= bufferPosition &&
                m_nextFrame < bufferPosition + bufferLength) {
                // m_nextFrame is in this buffer.
                buffer += (m_nextFrame - bufferPosition) * m_iChannels;
                bufferLength -= m_nextFrame - bufferPosition;
                m_seeking = false;
            } else {
                // we need to keep going forward
                goto releaseRawBuffer;
            }
        }

        // If the bufferLength is larger than the leftover buffer, re-allocate
        // it with 2x the space.
        if (bufferLength * m_iChannels > m_leftoverBufferSize) {
            int newSize = m_leftoverBufferSize;

            while (newSize < bufferLength * m_iChannels) {
                newSize *= 2;
            }
            SHORT_SAMPLE* newBuffer = new SHORT_SAMPLE[newSize];
            memcpy(newBuffer, m_leftoverBuffer,
                   sizeof(m_leftoverBuffer[0]) * m_leftoverBufferSize);
            delete [] m_leftoverBuffer;
            m_leftoverBuffer = newBuffer;
            m_leftoverBufferSize = newSize;
        }
        copyFrames(destBuffer + (size - framesNeeded * m_iChannels),
            &framesNeeded, buffer, bufferLength);

releaseRawBuffer:
        hr = pMBuffer->Unlock();
        // I'm ignoring this, MSDN for IMFMediaBuffer::Unlock stipulates
        // nothing about the state of the instance if this fails so might as
        // well just let it be released.
        //if (FAILED(hr)) break;
releaseMBuffer:
        safeRelease(&pMBuffer);
releaseSample:
        safeRelease(&pSample);
        if (error) break;
    }

    m_nextFrame += framesRequested - framesNeeded;
    if (m_leftoverBufferLength > 0) {
        if (framesNeeded != 0) {
            std::cerr << __FILE__ << __LINE__
				<< "WARNING: Expected frames needed to be 0. Abandoning this file." << std::endl;
            m_dead = true;
        }
        m_leftoverBufferPosition = m_nextFrame;
    }
    long samples_read = size - framesNeeded * m_iChannels;
    m_iCurrentPosition += samples_read;
    if (sDebug) { std::cout << "read() " << size << " returning " << samples_read << std::endl; }
	
	const int sampleMax = 1 << (m_iBitsPerSample-1);
	//Convert to float samples
	if (m_iChannels == 2)
	{
		SAMPLE *destBufferFloat(const_cast<SAMPLE*>(destination));
		for (unsigned long i = 0; i < samples_read; i++)
		{
			destBufferFloat[i] = destBuffer[i] / (float)sampleMax;
		}
	}
	else //Assuming mono, duplicate into stereo frames...
	{
		SAMPLE *destBufferFloat(const_cast<SAMPLE*>(destination));
		for (unsigned long i = 0; i < samples_read; i++)
		{
			destBufferFloat[i] = destBuffer[i] / (float)sampleMax;
		}
	}
    return samples_read;
}
Esempio n. 15
0
static void nmea_update(void)
{
    char **fields;

    assert(cookedwin != NULL);
    assert(nmeawin != NULL);
    assert(gpgsawin != NULL);
    assert(gpggawin != NULL);
    assert(gprmcwin != NULL);
    assert(gpgstwin != NULL);

    /* can be NULL if packet was overlong */
    fields = session.nmea.field;

    if (session.lexer.outbuffer[0] == (unsigned char)'$'
		&& fields != NULL && fields[0] != NULL) {
	int ymax, xmax;
	timestamp_t now;
	getmaxyx(nmeawin, ymax, xmax);
	assert(ymax > 0);
	if (strstr(sentences, fields[0]) == NULL) {
	    char *s_end = sentences + strlen(sentences);
	    if ((int)(strlen(sentences) + strlen(fields[0])) < xmax - 2) {
		*s_end++ = ' ';
		(void)strlcpy(s_end, fields[0], NMEA_MAX);
	    } else {
		*--s_end = '.';
		*--s_end = '.';
		*--s_end = '.';
	    }
	    (void)mvwaddstr(nmeawin, SENTENCELINE, 1, sentences);
	}

	/*
	 * If the interval between this and last update is
	 * the longest we've seen yet, boldify the corresponding
	 * tag.
	 */
	now = timestamp();
	if (now > last_tick && (now - last_tick) > tick_interval) {
	    char *findme = strstr(sentences, fields[0]);

	    tick_interval = now - last_tick;
	    if (findme != NULL) {
		(void)mvwchgat(nmeawin, SENTENCELINE, 1, xmax - 13, A_NORMAL, 0,
			       NULL);
		(void)mvwchgat(nmeawin, SENTENCELINE, 1 + (findme - sentences),
			       (int)strlen(fields[0]), A_BOLD, 0, NULL);
	    }
	}
	last_tick = now;

	if (strcmp(fields[0], "GPGSV") == 0
	    || strcmp(fields[0], "GNGSV") == 0
	    || strcmp(fields[0], "GLGSV") == 0) {
	    int i;
	    int nsats =
		(session.gpsdata.satellites_visible <
		 MAXSATS) ? session.gpsdata.satellites_visible : MAXSATS;

	    for (i = 0; i < nsats; i++) {
		(void)wmove(satwin, i + 2, 3);
		(void)wprintw(satwin, " %3d %3d%3d %3.0f",
			      session.gpsdata.skyview[i].PRN,
			      session.gpsdata.skyview[i].azimuth,
			      session.gpsdata.skyview[i].elevation,
			      session.gpsdata.skyview[i].ss);
	    }
	    /* add overflow mark to the display */
	    if (nsats <= MAXSATS)
		(void)mvwaddch(satwin, MAXSATS + 2, 18, ACS_HLINE);
	    else
		(void)mvwaddch(satwin, MAXSATS + 2, 18, ACS_DARROW);
	}

	if (strcmp(fields[0], "GPRMC") == 0
	    || strcmp(fields[0], "GNRMC") == 0
	    || strcmp(fields[0], "GLRMC") == 0) {
	    /* time, lat, lon, course, speed */
	    (void)mvwaddstr(gprmcwin, 1, 12, fields[1]);
	    (void)mvwprintw(gprmcwin, 2, 12, "%12s %s", fields[3], fields[4]);
	    (void)mvwprintw(gprmcwin, 3, 12, "%12s %s", fields[5], fields[6]);
	    (void)mvwaddstr(gprmcwin, 4, 12, fields[7]);
	    (void)mvwaddstr(gprmcwin, 5, 12, fields[8]);
	    /* the status field, FAA code, and magnetic variation */
	    (void)mvwaddstr(gprmcwin, 6, 12, fields[2]);
	    (void)mvwaddstr(gprmcwin, 6, 25, fields[12]);
	    (void)mvwprintw(gprmcwin, 7, 12, "%-5s%s", fields[10],
			    fields[11]);

	    cooked_pvt();	/* cooked version of TPV */
	}

	if (strcmp(fields[0], "GPGSA") == 0
	    || strcmp(fields[0], "GNGSA") == 0
	    || strcmp(fields[0], "GLGSA") == 0) {
	    (void)mvwprintw(gpgsawin, MODE_LINE, 7, "%1s%s", fields[1], fields[2]);
	    monitor_satlist(gpgsawin, SATS_LINE, SATS_COL+6);
	    (void)mvwprintw(gpgsawin, DOP_LINE, 8, "%-5s", fields[16]);
	    (void)mvwprintw(gpgsawin, DOP_LINE, 16, "%-5s", fields[17]);
	    (void)mvwprintw(gpgsawin, DOP_LINE, 24, "%-5s", fields[15]);
	    monitor_fixframe(gpgsawin);
	}

#ifdef NTP_ENABLE
	toff_update(gpgsawin, TOFF_LINE, 7);
#endif /* NTP_ENABLE */

	if (strcmp(fields[0], "GPGGA") == 0
	    || strcmp(fields[0], "GNGGA") == 0
	    || strcmp(fields[0], "GLGGA") == 0) {
	    (void)mvwprintw(gpggawin, 1, 12, "%-17s", fields[1]);
	    (void)mvwprintw(gpggawin, 2, 12, "%-17s", fields[2]);
	    (void)mvwprintw(gpggawin, 3, 12, "%-17s", fields[4]);
	    (void)mvwprintw(gpggawin, 4, 12, "%-17s", fields[9]);
	    (void)mvwprintw(gpggawin, 5, 12, "%1.1s", fields[6]);
	    (void)mvwprintw(gpggawin, 5, 22, "%2.2s", fields[7]);
	    (void)mvwprintw(gpggawin, 6, 12, "%-5.5s", fields[8]);
	    (void)mvwprintw(gpggawin, 7, 12, "%-5.5s", fields[11]);
	}
	if (strcmp(fields[0], "GPGST") == 0) {
	    (void)mvwprintw(gpgstwin, 1,  6, "%-10s", fields[1]);
	    (void)mvwprintw(gpgstwin, 1, 21,  "%-8s", fields[2]);
	    (void)mvwprintw(gpgstwin, 2,  6, "%-10s", fields[3]);
	    (void)mvwprintw(gpgstwin, 2, 21,  "%-8s", fields[4]);
	    (void)mvwprintw(gpgstwin, 3,  6, "%-10s", fields[5]);
	    (void)mvwprintw(gpgstwin, 3, 21,  "%-8s", fields[6]);
	    (void)mvwprintw(gpgstwin, 4,  6, "%-10s", fields[7]);
	    (void)mvwprintw(gpgstwin, 4, 21,  "%-8s", fields[8]);
	}
    }

#ifdef PPS_ENABLE
    pps_update(gpgsawin, PPS_LINE, 6);
#endif /* PPS_ENABLE */
}
Esempio n. 16
0
void rjMcMC1DSampler::sample()
{	
	mBirthDeathFromPrior = false;
	
	starttime = timestamp();
	double t1 = gettime();
	mChainInfo.resize(nchains);
	for (size_t ci = 0; ci < nchains; ci++){		
		unsigned int seed = (unsigned int)(ci + mRank + (unsigned int)time(NULL));		
		seedrand(seed);		
		
		mChainInfo[ci].reset();
		//mChainInfo[ci].modelchain.resize(nsamples);
		rjMcMC1DModel mcur;		
		for (size_t si = 0; si < nsamples; si++){

			//Initialis chain
			if (si == 0){
				mcur = choosefromprior();
				set_misfit(mcur);
			}

			//Initialise "best" models
			if (ci == 0 && si==0){
				mHighestLikelihood = mcur;
				mLowestMisfit = mcur;
			}
			
			rjMcMC1DModel mpro = mcur;
			size_t nopt = 4;
			if (mcur.nnuisances() > 0)nopt = 5;
			size_t option = irand((size_t)0, nopt - 1);
			
			bool accept = false;
			if (option == 0){
				accept = propose_valuechange(mcur, mpro);
			}
			else if (option == 1){
				accept = propose_move(mcur, mpro);
			}
			else if (option == 2){
				accept = propose_birth(mcur, mpro);
			}
			else if (option == 3){
				accept = propose_death(mcur, mpro);
			}
			else if (option == 4){
				accept=propose_nuisancechange(mcur,mpro);				
			}
			else if (option == 5){
				accept = propose_independent(mcur, mpro);
			}
			else{
				exit(1);
				break;
			}

			if (accept) mcur = mpro;				
						
			if (includeinmap(si)){
				pmap.addmodel(mcur);
				nmap.addmodel(mcur);
				mChainInfo[ci].modelchain.push_back(mcur);
			}

			if (mcur.logppd() > mHighestLikelihood.logppd()){
				mHighestLikelihood = mcur;
			}

			if (mcur.misfit() < mLowestMisfit.misfit()){
				mLowestMisfit = mcur;
			}

			if (saveconvergencerecord(si)){
				mChainInfo[ci].sample.push_back((uint32_t)si);
				mChainInfo[ci].nlayers.push_back((uint32_t)mcur.nlayers());
				mChainInfo[ci].misfit.push_back((float)mcur.misfit());
				mChainInfo[ci].logppd.push_back((float)mcur.logppd());
				mChainInfo[ci].ar_valuechange.push_back((float)ar_valuechange());
				mChainInfo[ci].ar_move.push_back((float)ar_move());
				mChainInfo[ci].ar_birth.push_back((float)ar_birth());
				mChainInfo[ci].ar_death.push_back((float)ar_death());
				mChainInfo[ci].ar_nuisancechange.push_back((float)ar_nuisancechange());
			}

			#ifdef _WIN32
			if (reportstats){
				if (mRank == 0 && isreportable(si)){
					//printstats(ci, si, mcur.nlayers(), mcur.misfit() / (double)ndata);
				}
			}
			#endif
		}
	}
	double t2 = gettime();
	endtime = timestamp();
	samplingtime = t2 - t1;
}
Esempio n. 17
0
static bool nmea_initialize(void)
{
    int i;

    cookedwin = derwin(devicewin, 3, 80, 0, 0);
    assert(cookedwin !=NULL);
    (void)wborder(cookedwin, 0, 0, 0, 0, 0, 0, 0, 0);
    (void)syncok(cookedwin, true);
    (void)wattrset(cookedwin, A_BOLD);
    (void)mvwaddstr(cookedwin, 1, 1, "Time: ");
    (void)mvwaddstr(cookedwin, 1, 32, "Lat: ");
    (void)mvwaddstr(cookedwin, 1, 55, "Lon: ");
    (void)mvwaddstr(cookedwin, 2, 34, " Cooked TPV ");
    (void)wattrset(cookedwin, A_NORMAL);

    nmeawin = derwin(devicewin, 3, 80, 3, 0);
    assert(nmeawin !=NULL);
    (void)wborder(nmeawin, 0, 0, 0, 0, 0, 0, 0, 0);
    (void)syncok(nmeawin, true);
    (void)wattrset(nmeawin, A_BOLD);
    (void)mvwaddstr(nmeawin, 2, 34, " Sentences ");
    (void)wattrset(nmeawin, A_NORMAL);

    satwin = derwin(devicewin, MAXSATS + 3, 20, 6, 0);
    assert(satwin !=NULL);
    (void)wborder(satwin, 0, 0, 0, 0, 0, 0, 0, 0), (void)syncok(satwin, true);
    (void)wattrset(satwin, A_BOLD);
    (void)mvwprintw(satwin, 1, 1, "Ch PRN  Az El S/N");
    for (i = 0; i < MAXSATS; i++)
	(void)mvwprintw(satwin, (int)(i + 2), 1, "%2d", i);
    (void)mvwprintw(satwin, 14, 7, " GSV ");
    (void)wattrset(satwin, A_NORMAL);

    gprmcwin = derwin(devicewin, 9, 30, 6, 20);
    assert(gprmcwin !=NULL);
    (void)wborder(gprmcwin, 0, 0, 0, 0, 0, 0, 0, 0),
	(void)syncok(gprmcwin, true);
    (void)wattrset(gprmcwin, A_BOLD);
    (void)mvwprintw(gprmcwin, 1, 1, "Time: ");
    (void)mvwprintw(gprmcwin, 2, 1, "Latitude: ");
    (void)mvwprintw(gprmcwin, 3, 1, "Longitude: ");
    (void)mvwprintw(gprmcwin, 4, 1, "Speed: ");
    (void)mvwprintw(gprmcwin, 5, 1, "Course: ");
    (void)mvwprintw(gprmcwin, 6, 1, "Status:            FAA: ");
    (void)mvwprintw(gprmcwin, 7, 1, "MagVar: ");
    (void)mvwprintw(gprmcwin, 8, 12, " RMC ");
    (void)wattrset(gprmcwin, A_NORMAL);

    gpgsawin = derwin(devicewin, 6, 30, 15, 20);
    assert(gpgsawin !=NULL);
    (void)wborder(gpgsawin, 0, 0, 0, 0, 0, 0, 0, 0);
    (void)syncok(gpgsawin, true);
    (void)wattrset(gpgsawin, A_BOLD);
#define MODE_LINE	1
    (void)mvwprintw(gpgsawin, MODE_LINE, 1, "Mode: ");
#define SATS_LINE	1
#define SATS_COL	10
    (void)mvwprintw(gpgsawin, SATS_LINE, SATS_COL, "Sats: ");
#define DOP_LINE	2
    (void)mvwprintw(gpgsawin, DOP_LINE, 1, "DOP: H=      V=      P=");
#define TOFF_LINE	3
    (void)mvwprintw(gpgsawin, TOFF_LINE, 1, "TOFF: ");
#ifndef PPS_ENABLE
    (void)mvwaddstr(gpgsawin, TOFF_LINE, 7, "N/A");
#endif /* PPS_ENABLE */
#define PPS_LINE	4
    (void)mvwprintw(gpgsawin, PPS_LINE, 1, "PPS: ");
#ifndef PPS_ENABLE
    (void)mvwaddstr(gpgsawin, PPS_LINE, 6, "N/A");
#endif /* PPS_ENABLE */
    (void)mvwprintw(gpgsawin, 5, 9, " GSA + PPS ");
    (void)wattrset(gpgsawin, A_NORMAL);

    gpggawin = derwin(devicewin, 9, 30, 6, 50);
    assert(gpggawin !=NULL);
    (void)wborder(gpggawin, 0, 0, 0, 0, 0, 0, 0, 0);
    (void)syncok(gpggawin, true);
    (void)wattrset(gpggawin, A_BOLD);
    (void)mvwprintw(gpggawin, 1, 1, "Time: ");
    (void)mvwprintw(gpggawin, 2, 1, "Latitude: ");
    (void)mvwprintw(gpggawin, 3, 1, "Longitude: ");
    (void)mvwprintw(gpggawin, 4, 1, "Altitude: ");
    (void)mvwprintw(gpggawin, 5, 1, "Quality:       Sats: ");
    (void)mvwprintw(gpggawin, 6, 1, "HDOP: ");
    (void)mvwprintw(gpggawin, 7, 1, "Geoid: ");
    (void)mvwprintw(gpggawin, 8, 12, " GGA ");
    (void)wattrset(gpggawin, A_NORMAL);

    gpgstwin = derwin(devicewin, 6, 30, 15, 50);
    assert(gpgstwin !=NULL);
    (void)wborder(gpgstwin, 0, 0, 0, 0, 0, 0, 0, 0);
    (void)syncok(gpgstwin, true);
    (void)wattrset(gpgstwin, A_BOLD);
    (void)mvwprintw(gpgstwin, 1,  1, "UTC: ");
    (void)mvwprintw(gpgstwin, 1, 16, "RMS: ");
    (void)mvwprintw(gpgstwin, 2,  1, "MAJ: ");
    (void)mvwprintw(gpgstwin, 2, 16, "MIN: ");
    (void)mvwprintw(gpgstwin, 3,  1, "ORI: ");
    (void)mvwprintw(gpgstwin, 3, 16, "LAT: ");
    (void)mvwprintw(gpgstwin, 4,  1, "LON: ");
    (void)mvwprintw(gpgstwin, 4, 16, "ALT: ");
    (void)mvwprintw(gpgstwin, 5, 12, " GST ");
    (void)wattrset(gpgstwin, A_NORMAL);


    last_tick = timestamp();

    sentences[0] = '\0';

    return (nmeawin != NULL);
}
Esempio n. 18
0
void spmv_sell_ocl(sell_matrix<int, float>* mat, float* vec, float* result, int dim2Size, double& opttime, double& optflop, int& optmethod, char* oclfilename, cl_device_type deviceType, int ntimes, double* floptable)
{
    cl_device_id* devices = NULL;
    cl_context context = NULL;
    cl_command_queue cmdQueue = NULL;
    cl_program program = NULL;

    assert(initialization(deviceType, devices, &context, &cmdQueue, &program, oclfilename) == 1);

    cl_int errorCode = CL_SUCCESS;

    //Create device memory objects
    cl_mem devSlicePtr;
    cl_mem devColid;
    cl_mem devData;
    cl_mem devVec;
    cl_mem devRes;
    cl_mem devTexVec;

    //Initialize values
    int nnz = mat->matinfo.nnz;
    int rownum = mat->matinfo.height;
    int vecsize = mat->matinfo.width;
    int sliceheight = mat->sell_slice_height;
    int slicenum = mat->sell_slice_num;
    int datasize = mat->sell_slice_ptr[slicenum];
    ALLOCATE_GPU_READ(devSlicePtr, mat->sell_slice_ptr, sizeof(int)*(slicenum + 1));
    ALLOCATE_GPU_READ(devColid, mat->sell_col_id, sizeof(int)*datasize);
    ALLOCATE_GPU_READ(devData, mat->sell_data, sizeof(float)*datasize);
    ALLOCATE_GPU_READ(devVec, vec, sizeof(float)*vecsize);
    int paddedres = findPaddedSize(rownum, 512);
    devRes = clCreateBuffer(context, CL_MEM_READ_WRITE, sizeof(float)*paddedres, NULL, &errorCode); CHECKERROR;
    errorCode = clEnqueueWriteBuffer(cmdQueue, devRes, CL_TRUE, 0, sizeof(float)*rownum, result, 0, NULL, NULL); CHECKERROR;
    const cl_image_format floatFormat =
    {
	CL_R,
	CL_FLOAT,
    };


    int width = VEC2DWIDTH;
    int height = (vecsize + VEC2DWIDTH - 1)/VEC2DWIDTH;
    float* image2dVec = (float*)malloc(sizeof(float)*width*height);
    memset(image2dVec, 0, sizeof(float)*width*height);
    for (int i = 0; i < vecsize; i++)
    {
	image2dVec[i] = vec[i];
    }
    size_t origin[] = {0, 0, 0};
    size_t vectorSize[] = {width, height, 1};
    devTexVec = clCreateImage2D(context, CL_MEM_READ_ONLY, &floatFormat, width, height, 0, NULL, &errorCode); CHECKERROR;
    errorCode = clEnqueueWriteImage(cmdQueue, devTexVec, CL_TRUE, origin, vectorSize, 0, 0, image2dVec, 0, NULL, NULL); CHECKERROR;
    clFinish(cmdQueue);

    //printf("\nvec length %d padded length %d", mat->matinfo.width, padveclength);

    int dim2 = dim2Size;
    if (sliceheight == WARPSIZE)
    {
	int methodid = 0;
	cl_uint work_dim = 2;
	size_t blocksize[] = {SELL_GROUP_SIZE, 1};
	int gsize = ((rownum + SELL_GROUP_SIZE - 1)/SELL_GROUP_SIZE)*SELL_GROUP_SIZE;
	size_t globalsize[] = {gsize, dim2};
	//printf("gsize %d rownum %d slicenum %d sliceheight %d datasize %d nnz %d vecsize %d \n", gsize, rownum, slicenum, sliceheight, datasize, nnz, vecsize);
	//int warpnum = SELL_GROUP_SIZE / WARPSIZE;

	cl_kernel csrKernel = NULL;
	csrKernel = clCreateKernel(program, "gpu_sell_warp", &errorCode); CHECKERROR;
	errorCode = clSetKernelArg(csrKernel, 0, sizeof(cl_mem), &devSlicePtr); CHECKERROR;
	errorCode = clSetKernelArg(csrKernel, 1, sizeof(cl_mem), &devColid); CHECKERROR;
	errorCode = clSetKernelArg(csrKernel, 2, sizeof(cl_mem), &devData); CHECKERROR;
	errorCode = clSetKernelArg(csrKernel, 3, sizeof(cl_mem), &devVec); CHECKERROR;
	errorCode = clSetKernelArg(csrKernel, 4, sizeof(cl_mem), &devRes); CHECKERROR;
	errorCode = clSetKernelArg(csrKernel, 5, sizeof(int),    &slicenum); CHECKERROR;

	for (int k = 0; k < 3; k++)
	{
	    errorCode = clEnqueueNDRangeKernel(cmdQueue, csrKernel, work_dim, NULL, globalsize, blocksize, 0, NULL, NULL); CHECKERROR;
	}
	clFinish(cmdQueue);

	double teststart = timestamp();
	for (int i = 0; i < ntimes; i++)
	{
	    errorCode = clEnqueueNDRangeKernel(cmdQueue, csrKernel, work_dim, NULL, globalsize, blocksize, 0, NULL, NULL); CHECKERROR;
	}
	clFinish(cmdQueue);
	double testend = timestamp();
	double time_in_sec = (testend - teststart)/(double)dim2;
	double gflops = (double)nnz*2/(time_in_sec/(double)ntimes)/(double)1e9;
	printf("\nSELL cpu warp time %lf ms GFLOPS %lf code %d \n\n",   time_in_sec / (double) ntimes * 1000, gflops, methodid);

	if (csrKernel)
	    clReleaseKernel(csrKernel);

	double onetime = time_in_sec / (double) ntimes;
	floptable[methodid] = gflops;
	if (onetime < opttime)
	{
	    opttime = onetime;
	    optmethod = methodid;
	    optflop = gflops;
	}

    }
    
    if (sliceheight == SELL_GROUP_SIZE)
    {
	int methodid = 1;
	cl_uint work_dim = 2;
	size_t blocksize[] = {SELL_GROUP_SIZE, 1};
	int gsize = slicenum * SELL_GROUP_SIZE;
	size_t globalsize[] = {gsize, dim2};

	cl_kernel csrKernel = NULL;
	csrKernel = clCreateKernel(program, "gpu_sell_group", &errorCode); CHECKERROR;
	errorCode = clSetKernelArg(csrKernel, 0, sizeof(cl_mem), &devSlicePtr); CHECKERROR;
	errorCode = clSetKernelArg(csrKernel, 1, sizeof(cl_mem), &devColid); CHECKERROR;
	errorCode = clSetKernelArg(csrKernel, 2, sizeof(cl_mem), &devData); CHECKERROR;
	errorCode = clSetKernelArg(csrKernel, 3, sizeof(cl_mem), &devVec); CHECKERROR;
	errorCode = clSetKernelArg(csrKernel, 4, sizeof(cl_mem), &devRes); CHECKERROR;
	errorCode = clSetKernelArg(csrKernel, 5, sizeof(int),    &slicenum); CHECKERROR;

	for (int k = 0; k < 3; k++)
	{
	    errorCode = clEnqueueNDRangeKernel(cmdQueue, csrKernel, work_dim, NULL, globalsize, blocksize, 0, NULL, NULL); CHECKERROR;
	}
	clFinish(cmdQueue);

	double teststart = timestamp();
	for (int i = 0; i < ntimes; i++)
	{
	    errorCode = clEnqueueNDRangeKernel(cmdQueue, csrKernel, work_dim, NULL, globalsize, blocksize, 0, NULL, NULL); CHECKERROR;
	}
	clFinish(cmdQueue);
	double testend = timestamp();
	double time_in_sec = (testend - teststart)/(double)dim2;
	double gflops = (double)nnz*2/(time_in_sec/(double)ntimes)/(double)1e9;
	printf("\nSELL cpu group time %lf ms GFLOPS %lf code %d \n\n",   time_in_sec / (double) ntimes * 1000, gflops, methodid);

	if (csrKernel)
	    clReleaseKernel(csrKernel);

	double onetime = time_in_sec / (double) ntimes;
	floptable[methodid] = gflops;
	if (onetime < opttime)
	{
	    opttime = onetime;
	    optmethod = methodid;
	    optflop = gflops;
	}

    }

    //Clean up
    if (image2dVec)
	free(image2dVec);

    if (devSlicePtr)
	clReleaseMemObject(devSlicePtr);
    if (devColid)
	clReleaseMemObject(devColid);
    if (devData)
	clReleaseMemObject(devData);
    if (devVec)
	clReleaseMemObject(devVec);
    if (devTexVec)
	clReleaseMemObject(devTexVec);
    if (devRes)
	clReleaseMemObject(devRes);


    freeObjects(devices, &context, &cmdQueue, &program);
}
/**
 * Maintains the objectives listing, adding, removing and updating items
 *
 * Called at same rate as goals/events are evaluated.  
 */
void training_check_objectives()
{
	int i, event_idx, event_status;

	Training_obj_num_lines = 0;
	for (event_idx=0; event_idx<Num_mission_events; event_idx++) {
		event_status = mission_get_event_status(event_idx);
		if ( (event_status != EVENT_UNBORN) && Mission_events[event_idx].objective_text && (timestamp() > Mission_events[event_idx].born_on_date + Directive_wait_time) ) {
			if (!Training_failure || !strnicmp(Mission_events[event_idx].name, XSTR( "Training failed", 423), 15)) {

				// check for the actual objective
				for (i=0; i<Training_obj_num_lines; i++) {
					if (Training_obj_lines[i] == event_idx) {
						break;
					}
				}

				// not in objective list, need to add it
				if (i == Training_obj_num_lines) {
					if (Training_obj_num_lines == TRAINING_OBJ_LINES) {

						// objective list full, remove topmost objective
						for (i=1; i<TRAINING_OBJ_LINES; i++) {
							Training_obj_lines[i - 1] = Training_obj_lines[i];
						}
						Training_obj_num_lines--;
					}
					// add the new directive
					Training_obj_lines[Training_obj_num_lines++] = event_idx;
				}

				// now check for the associated keypress text
				for (i=0; i<Training_obj_num_lines; i++) {
					if (Training_obj_lines[i] == (event_idx | TRAINING_OBJ_LINES_KEY)) {
						break;
					}
				}

				// if there is a keypress message with directive, process that too.
				if (Mission_events[event_idx].objective_key_text) {
					if (event_status == EVENT_CURRENT) {

						// not in objective list, need to add it
						if (i == Training_obj_num_lines) {
							if (Training_obj_num_lines == TRAINING_OBJ_LINES) {

								// objective list full, remove topmost objective
								for (i=1; i<Training_obj_num_lines; i++) {
									Training_obj_lines[i - 1] = Training_obj_lines[i];
								}
								Training_obj_num_lines--;
							}
							// mark objective as having key text
							Training_obj_lines[Training_obj_num_lines++] = event_idx | TRAINING_OBJ_LINES_KEY;
						}

					} else {
						// message with key press text is no longer valid, so remove it
						if (i < Training_obj_num_lines) {
							for (; i<Training_obj_num_lines - 1; i++) {
								Training_obj_lines[i] = Training_obj_lines[i + 1];
							}
							Training_obj_num_lines--;
						}
					}
				}
			}
		}
	}

	// now sort list of events
	// sort on EVENT_CURRENT and born on date, for other events (EVENT_SATISFIED, EVENT_FAILED) sort on born on date
	sort_training_objectives();
}
Esempio n. 20
0
status_t
POP3Protocol::Login(const char *uid, const char *password, int method)
{
	status_t err;

	BString error_msg, userString;
	error_msg << B_TRANSLATE("Error while authenticating user %user");

	userString << uid;
	error_msg.ReplaceFirst("%user", userString);

	if (method == 1) {	//APOP
		int32 index = fLog.FindFirst("<");
		if(index != B_ERROR) {
			ReportProgress(0, 0, B_TRANSLATE("Sending APOP authentication"
				B_UTF8_ELLIPSIS));
			int32 end = fLog.FindFirst(">",index);
			BString timestamp("");
			fLog.CopyInto(timestamp, index, end - index + 1);
			timestamp += password;
			char md5sum[33];
			MD5Digest((unsigned char*)timestamp.String(), md5sum);
			BString cmd = "APOP ";
			cmd += uid;
			cmd += " ";
			cmd += md5sum;
			cmd += CRLF;

			err = SendCommand(cmd.String());
			if (err != B_OK) {
				error_msg << B_TRANSLATE(". The server said:\n") << fLog;
				ShowError(error_msg.String());
				return err;
			}

			return B_OK;
		} else {
			error_msg << B_TRANSLATE(": The server does not support APOP.");
			ShowError(error_msg.String());
			return B_NOT_ALLOWED;
		}
	}
	ReportProgress(0, 0, B_TRANSLATE("Sending username" B_UTF8_ELLIPSIS));

	BString cmd = "USER ";
	cmd += uid;
	cmd += CRLF;

	err = SendCommand(cmd.String());
	if (err != B_OK) {
		error_msg << B_TRANSLATE(". The server said:\n") << fLog;
		ShowError(error_msg.String());
		return err;
	}

	ReportProgress(0, 0, B_TRANSLATE("Sending password" B_UTF8_ELLIPSIS));
	cmd = "PASS ";
	cmd += password;
	cmd += CRLF;

	err = SendCommand(cmd.String());
	if (err != B_OK) {
		error_msg << B_TRANSLATE(". The server said:\n") << fLog;
		ShowError(error_msg.String());
		return err;
	}

	return B_OK;
}
Esempio n. 21
0
/**
 * Do various updates to debris:  check if time to die, start fireballs
 * Maybe delete debris if it's very far away from player.
 *
 * @param obj			pointer to debris object
 * @param frame_time	time elapsed since last debris_move() called
 */
void debris_process_post(object * obj, float frame_time)
{
	int i, num;
	num = obj->instance;

	int objnum = OBJ_INDEX(obj);
	Assert( Debris[num].objnum == objnum );
	debris *db = &Debris[num];

	if ( db->is_hull ) {
		MONITOR_INC(NumHullDebris,1);
		radar_plot_object( obj );

		if ( timestamp_elapsed(db->sound_delay) ) {
			obj_snd_assign(objnum, SND_DEBRIS, &vmd_zero_vector, 0);
			db->sound_delay = 0;
		}
	} else {
		MONITOR_INC(NumSmallDebris,1);
	}

	if ( db->lifeleft >= 0.0f) {
		db->lifeleft -= frame_time;
		if ( db->lifeleft < 0.0f )	{
			debris_start_death_roll(obj, db);
		}
	}

	maybe_delete_debris(db);	//	Make this debris go away if it's very far away.

	// ================== DO THE ELECTRIC ARCING STUFF =====================
	if ( db->arc_frequency <= 0 )	{
		return;			// If arc_frequency <= 0, this piece has no arcs on it
	}

	if ( !timestamp_elapsed(db->fire_timeout) && timestamp_elapsed(db->next_fireball))	{		

		db->next_fireball = timestamp_rand(db->arc_frequency,db->arc_frequency*2 );
		db->arc_frequency += 100;	

		if (db->is_hull)	{

			int n, n_arcs = ((rand()>>5) % 3)+1;		// Create 1-3 sparks

			vec3d v1, v2, v3, v4;

			if ( Cmdline_old_collision_sys ) {
				submodel_get_two_random_points( db->model_num, db->submodel_num, &v1, &v2 );
				submodel_get_two_random_points( db->model_num, db->submodel_num, &v3, &v4 );
			} else {
				submodel_get_two_random_points_better( db->model_num, db->submodel_num, &v1, &v2 );
				submodel_get_two_random_points_better( db->model_num, db->submodel_num, &v3, &v4 );
			}

			n = 0;

			int a = 100, b = 1000;
			int lifetime = (myrand()%((b)-(a)+1))+(a);

			// Create the spark effects
			for (i=0; i<MAX_DEBRIS_ARCS; i++ )	{
				if ( !timestamp_valid( db->arc_timestamp[i] ) )	{

					db->arc_timestamp[i] = timestamp(lifetime);	// live up to a second

					switch( n )	{
					case 0:
						db->arc_pts[i][0] = v1;
						db->arc_pts[i][1] = v2;
						break;
					case 1:
						db->arc_pts[i][0] = v2;
						db->arc_pts[i][1] = v3;
						break;

					case 2:
						db->arc_pts[i][0] = v2;
						db->arc_pts[i][1] = v4;
						break;

					default:
						Int3();
					}
						
					n++;
					if ( n == n_arcs )
						break;	// Don't need to create anymore
				}
			}

	
			// rotate v2 out of local coordinates into world.
			// Use v2 since it is used in every bolt.  See above switch().
			vec3d snd_pos;
			vm_vec_unrotate(&snd_pos, &v2, &obj->orient);
			vm_vec_add2(&snd_pos, &obj->pos );

			//Play a sound effect
			if ( lifetime > 750 )	{
				// 1.00 second effect
				snd_play_3d( &Snds[SND_DEBRIS_ARC_05], &snd_pos, &View_position, obj->radius );
			} else if ( lifetime >  500 )	{
				// 0.75 second effect
				snd_play_3d( &Snds[SND_DEBRIS_ARC_04], &snd_pos, &View_position, obj->radius );
			} else if ( lifetime >  250 )	{
				// 0.50 second effect
				snd_play_3d( &Snds[SND_DEBRIS_ARC_03], &snd_pos, &View_position, obj->radius );
			} else if ( lifetime >  100 )	{
				// 0.25 second effect
				snd_play_3d( &Snds[SND_DEBRIS_ARC_02], &snd_pos, &View_position, obj->radius );
			} else {
				// 0.10 second effect
				snd_play_3d( &Snds[SND_DEBRIS_ARC_01], &snd_pos, &View_position, obj->radius );
			}
		}
Esempio n. 22
0
void InspectorTimelineAgent::didBeginFrame()
{
    TRACE_EVENT_INSTANT0("webkit", InstrumentationEvents::BeginFrame);
    m_pendingFrameRecord = TimelineRecordFactory::createGenericRecord(timestamp(), 0, TimelineRecordType::BeginFrame);
}
Esempio n. 23
0
//-------------------------------------------------------------------------------------
void ClientObject::gameTick()
{
	if(pServerChannel()->endpoint())
	{
		pServerChannel()->processPackets(NULL);
	}
	else
	{
		if(connectedGateway_)
		{
			EventData_ServerCloased eventdata;
			eventHandler_.fire(&eventdata);
			connectedGateway_ = false;
			canReset_ = true;
			state_ = C_STATE_INIT;
			
			DEBUG_MSG(fmt::format("ClientObject({})::tickSend: serverCloased! name({})!\n", 
			this->appID(), this->name()));
		}
	}

	if(locktime() > 0 && timestamp() < locktime())
	{
		return;
	}

	switch(state_)
	{
		case C_STATE_INIT:

			state_ = C_STATE_PLAY;

			if(!initCreate())
				return;

			break;
		case C_STATE_CREATE:

			state_ = C_STATE_PLAY;

			if(!createAccount())
				return;

			break;
		case C_STATE_LOGIN:

			state_ = C_STATE_PLAY;

			if(!login())
				return;

			break;
		case C_STATE_LOGIN_GATEWAY_CREATE:

			state_ = C_STATE_PLAY;

			if(!initLoginGateWay())
				return;

			break;
		case C_STATE_LOGIN_GATEWAY:

			state_ = C_STATE_PLAY;

			if(!loginGateWay())
				return;

			break;
		case C_STATE_PLAY:
			break;
		default:
			KBE_ASSERT(false);
			break;
	};

	tickSend();
}
bool RobotBallController::getKickerStatus() {
    return (timestamp() - _lastKicked) > RechargeTime ? 1 : 0;
}
Esempio n. 25
0
inline timestamp get_timestamp()
{
    return timestamp(get_tick_count());
}
Esempio n. 26
0
/* *** */
static int bam(const char *scriptfile, const char **targets, int num_targets)
{
	struct CONTEXT context;
	int build_error = 0;
	int setup_error = 0;
	int report_done = 0;

	/* build time */
	time_t starttime  = time(0x0);
	
	/* zero out and create memory heap, graph */
	memset(&context, 0, sizeof(struct CONTEXT));
	context.graphheap = mem_create();
	context.deferredheap = mem_create();
	context.graph = node_graph_create(context.graphheap);
	context.exit_on_error = option_abort_on_error;
	context.buildtime = timestamp();

	/* create lua context */
	/* HACK: Store the context pointer as the userdata pointer to the allocator to make
		sure that we have fast access to it. This makes the context_get_pointer call very fast */
	context.lua = lua_newstate(lua_alloctor_malloc, &context);

	/* install panic function */
	lua_atpanic(context.lua, lf_panicfunc);

	/* load cache (thread?) */
	if(option_no_cache == 0)
	{
		/* create a hash of all the external variables that can cause the
			script to generate different results */
		unsigned int cache_hash = 0;
		int i;
		for(i = 0; i < option_num_scriptargs; i++)
			cache_hash = string_hash_add(cache_hash, option_scriptargs[i]);
		sprintf(cache_filename, ".bam/%08x", cache_hash);
		context.cache = cache_load(cache_filename);
	}

	/* do the setup */
	setup_error = bam_setup(&context, scriptfile, targets, num_targets);

	/* done with the loopup heap */
	mem_destroy(context.deferredheap);

	/* if we have a separate lua heap, just destroy it */
	if(context.luaheap)
		mem_destroy(context.luaheap);
	else
		lua_close(context.lua);
	
	/* do actions if we don't have any errors */
	if(!setup_error)
	{
		build_error = context_build_prepare(&context);
		
		if(!build_error)
		{
			if(option_debug_nodes) /* debug dump all nodes */
				node_debug_dump(context.graph);
			else if(option_debug_nodes_detailed) /* debug dump all nodes detailed */
				node_debug_dump_detailed(context.graph);
			else if(option_debug_jobs) /* debug dump all jobs */
				node_debug_dump_jobs(context.graph);
			else if(option_debug_dot) /* debug dump all nodes as dot */
				node_debug_dump_dot(context.graph, context.target);
			else if(option_debug_jobs_dot) /* debug dump all jobs as dot */
				node_debug_dump_jobs_dot(context.graph, context.target);
			else if(option_dry)
			{
			}
			else
			{
				/* run build or clean */
				if(option_clean)
					build_error = context_build_clean(&context);
				else
				{
					build_error = context_build_make(&context);
					report_done = 1;
				}
			}
		}
	}		

	/* save cache (thread?) */
	if(option_no_cache == 0 && setup_error == 0)
	{
		/* create the cache directory */
		file_createdir(".bam");
		cache_save(cache_filename, context.graph);
	}
	
	/* clean up */
	mem_destroy(context.graphheap);

	/* print final report and return */
	if(setup_error)
	{
		/* no error message on setup error, it reports fine itself */
		return setup_error;
	}
	else if(build_error)
		printf("%s: error: a build step failed\n", session.name);
	else if(report_done)
	{
		if(context.num_commands == 0)
			printf("%s: targets are up to date already\n", session.name);
		else
		{
			time_t s = time(0x0) - starttime;
			if(s <= 1)
				printf("%s: done\n", session.name);
			else
				printf("%s: done (%d:%.2d)\n", session.name, (int)(s/60), (int)(s%60));
		}
	}

	return build_error;
}
Esempio n. 27
0
//-------------------------------------------------------------------------------------
void Channel::onPacketReceived(int bytes)
{
	lastReceivedTime_ = timestamp();
	++numPacketsReceived_;
	numBytesReceived_ += bytes;
}
Esempio n. 28
0
bool QgsMapLayer::writeLayerXML( QDomElement& layerElement, QDomDocument& document, QString relativeBasePath )
{
  // use scale dependent visibility flag
  layerElement.setAttribute( "hasScaleBasedVisibilityFlag", hasScaleBasedVisibility() ? 1 : 0 );
  layerElement.setAttribute( "minimumScale", QString::number( minimumScale() ) );
  layerElement.setAttribute( "maximumScale", QString::number( maximumScale() ) );

  // ID
  QDomElement layerId = document.createElement( "id" );
  QDomText layerIdText = document.createTextNode( id() );
  layerId.appendChild( layerIdText );

  layerElement.appendChild( layerId );

  // data source
  QDomElement dataSource = document.createElement( "datasource" );

  QString src = source();

  QgsVectorLayer *vlayer = qobject_cast<QgsVectorLayer *>( this );
  // TODO: what about postgres, mysql and others, they should not go through writePath()
  if ( vlayer && vlayer->providerType() == "spatialite" )
  {
    QgsDataSourceURI uri( src );
    QString database = QgsProject::instance()->writePath( uri.database(), relativeBasePath );
    uri.setConnection( uri.host(), uri.port(), database, uri.username(), uri.password() );
    src = uri.uri();
  }
  else if ( vlayer && vlayer->providerType() == "ogr" )
  {
    QStringList theURIParts = src.split( "|" );
    theURIParts[0] = QgsProject::instance()->writePath( theURIParts[0], relativeBasePath );
    src = theURIParts.join( "|" );
  }
  else if ( vlayer && vlayer->providerType() == "gpx" )
  {
    QStringList theURIParts = src.split( "?" );
    theURIParts[0] = QgsProject::instance()->writePath( theURIParts[0], relativeBasePath );
    src = theURIParts.join( "?" );
  }
  else if ( vlayer && vlayer->providerType() == "delimitedtext" )
  {
    QUrl urlSource = QUrl::fromEncoded( src.toAscii() );
    QUrl urlDest = QUrl::fromLocalFile( QgsProject::instance()->writePath( urlSource.toLocalFile(), relativeBasePath ) );
    urlDest.setQueryItems( urlSource.queryItems() );
    src = QString::fromAscii( urlDest.toEncoded() );
  }
  else
  {
    bool handled = false;

    if ( !vlayer )
    {
      QgsRasterLayer *rlayer = qobject_cast<QgsRasterLayer *>( this );
      // Update path for subdataset
      if ( rlayer && rlayer->providerType() == "gdal" )
      {
        if ( src.startsWith( "NETCDF:" ) )
        {
          // NETCDF:filename:variable
          // filename can be quoted with " as it can contain colons
          QRegExp r( "NETCDF:(.+):([^:]+)" );
          if ( r.exactMatch( src ) )
          {
            QString filename = r.cap( 1 );
            if ( filename.startsWith( '"' ) && filename.endsWith( '"' ) )
              filename = filename.mid( 1, filename.length() - 2 );
            src = "NETCDF:\"" + QgsProject::instance()->writePath( filename, relativeBasePath ) + "\":" + r.cap( 2 );
            handled = true;
          }
        }
        else if ( src.startsWith( "HDF4_SDS:" ) )
        {
          // HDF4_SDS:subdataset_type:file_name:subdataset_index
          // filename can be quoted with " as it can contain colons
          QRegExp r( "HDF4_SDS:([^:]+):(.+):([^:]+)" );
          if ( r.exactMatch( src ) )
          {
            QString filename = r.cap( 2 );
            if ( filename.startsWith( '"' ) && filename.endsWith( '"' ) )
              filename = filename.mid( 1, filename.length() - 2 );
            src = "HDF4_SDS:" + r.cap( 1 ) + ":\"" + QgsProject::instance()->writePath( filename, relativeBasePath ) + "\":" + r.cap( 3 );
            handled = true;
          }
        }
        else if ( src.startsWith( "HDF5:" ) )
        {
          // HDF5:file_name:subdataset
          // filename can be quoted with " as it can contain colons
          QRegExp r( "HDF5:(.+):([^:]+)" );
          if ( r.exactMatch( src ) )
          {
            QString filename = r.cap( 1 );
            if ( filename.startsWith( '"' ) && filename.endsWith( '"' ) )
              filename = filename.mid( 1, filename.length() - 2 );
            src = "HDF5:\"" + QgsProject::instance()->writePath( filename, relativeBasePath ) + "\":" + r.cap( 2 );
            handled = true;
          }
        }
        else if ( src.contains( QRegExp( "^(NITF_IM|RADARSAT_2_CALIB):" ) ) )
        {
          // NITF_IM:0:filename
          // RADARSAT_2_CALIB:?:filename
          QRegExp r( "([^:]+):([^:]+):(.+)" );
          if ( r.exactMatch( src ) )
          {
            src = r.cap( 1 ) + ":" + r.cap( 2 ) + ":" + QgsProject::instance()->writePath( r.cap( 3 ), relativeBasePath );
            handled = true;
          }
        }
      }
    }

    if ( !handled )
      src = QgsProject::instance()->writePath( src, relativeBasePath );
  }

  QDomText dataSourceText = document.createTextNode( src );
  dataSource.appendChild( dataSourceText );

  layerElement.appendChild( dataSource );


  // layer name
  QDomElement layerName = document.createElement( "layername" );
  QDomText layerNameText = document.createTextNode( originalName() );
  layerName.appendChild( layerNameText );

  // layer title
  QDomElement layerTitle = document.createElement( "title" );
  QDomText layerTitleText = document.createTextNode( title() );
  layerTitle.appendChild( layerTitleText );

  // layer abstract
  QDomElement layerAbstract = document.createElement( "abstract" );
  QDomText layerAbstractText = document.createTextNode( abstract() );
  layerAbstract.appendChild( layerAbstractText );

  layerElement.appendChild( layerName );
  layerElement.appendChild( layerTitle );
  layerElement.appendChild( layerAbstract );

  // layer keyword list
  QStringList keywordStringList = keywordList().split( "," );
  if ( keywordStringList.size() > 0 )
  {
    QDomElement layerKeywordList = document.createElement( "keywordList" );
    for ( int i = 0; i < keywordStringList.size(); ++i )
    {
      QDomElement layerKeywordValue = document.createElement( "value" );
      QDomText layerKeywordText = document.createTextNode( keywordStringList.at( i ).trimmed() );
      layerKeywordValue.appendChild( layerKeywordText );
      layerKeywordList.appendChild( layerKeywordValue );
    }
    layerElement.appendChild( layerKeywordList );
  }

  // layer metadataUrl
  QString aDataUrl = dataUrl();
  if ( !aDataUrl.isEmpty() )
  {
    QDomElement layerDataUrl = document.createElement( "dataUrl" );
    QDomText layerDataUrlText = document.createTextNode( aDataUrl );
    layerDataUrl.appendChild( layerDataUrlText );
    layerDataUrl.setAttribute( "format", dataUrlFormat() );
    layerElement.appendChild( layerDataUrl );
  }

  // layer legendUrl
  QString aLegendUrl = legendUrl();
  if ( !aLegendUrl.isEmpty() )
  {
    QDomElement layerLegendUrl = document.createElement( "legendUrl" );
    QDomText layerLegendUrlText = document.createTextNode( aLegendUrl );
    layerLegendUrl.appendChild( layerLegendUrlText );
    layerLegendUrl.setAttribute( "format", legendUrlFormat() );
    layerElement.appendChild( layerLegendUrl );
  }

  // layer attribution
  QString aAttribution = attribution();
  if ( !aAttribution.isEmpty() )
  {
    QDomElement layerAttribution = document.createElement( "attribution" );
    QDomText layerAttributionText = document.createTextNode( aAttribution );
    layerAttribution.appendChild( layerAttributionText );
    layerAttribution.setAttribute( "href", attributionUrl() );
    layerElement.appendChild( layerAttribution );
  }

  // layer metadataUrl
  QString aMetadataUrl = metadataUrl();
  if ( !aMetadataUrl.isEmpty() )
  {
    QDomElement layerMetadataUrl = document.createElement( "metadataUrl" );
    QDomText layerMetadataUrlText = document.createTextNode( aMetadataUrl );
    layerMetadataUrl.appendChild( layerMetadataUrlText );
    layerMetadataUrl.setAttribute( "type", metadataUrlType() );
    layerMetadataUrl.setAttribute( "format", metadataUrlFormat() );
    layerElement.appendChild( layerMetadataUrl );
  }

  // timestamp if supported
  if ( timestamp() > QDateTime() )
  {
    QDomElement stamp = document.createElement( "timestamp" );
    QDomText stampText = document.createTextNode( timestamp().toString( Qt::ISODate ) );
    stamp.appendChild( stampText );
    layerElement.appendChild( stamp );
  }

  layerElement.appendChild( layerName );

  // zorder
  // This is no longer stored in the project file. It is superfluous since the layers
  // are written and read in the proper order.

  // spatial reference system id
  QDomElement mySrsElement = document.createElement( "srs" );
  mCRS->writeXML( mySrsElement, document );
  layerElement.appendChild( mySrsElement );

#if 0
  // <transparencyLevelInt>
  QDomElement transparencyLevelIntElement = document.createElement( "transparencyLevelInt" );
  QDomText    transparencyLevelIntText    = document.createTextNode( QString::number( getTransparency() ) );
  transparencyLevelIntElement.appendChild( transparencyLevelIntText );
  maplayer.appendChild( transparencyLevelIntElement );
#endif

  // now append layer node to map layer node

  writeCustomProperties( layerElement, document );

  return writeXml( layerElement, document );

} // bool QgsMapLayer::writeXML
Esempio n. 29
0
int main(int argc, char *argv[])
{
    int i, iterations = 16, c;
    long stride = -1;
    unsigned int seed = 0;

    /* Check for -h parameter before MPI_Init so the binary can be
       called directly, without, for instance, mpirun */
    for (i = 1; i < argc; ++i) {
        if (!strcmp(argv[i], "-h") || !strcmp(argv[i], "--help"))
            usage(argv[0]);
    }

    MPI_Init(&argc, &argv);
    MPI_Comm_rank(MPI_COMM_WORLD, &rank);
    MPI_Comm_size(MPI_COMM_WORLD, &size);

    /* Parse command line options */
    while (1) {
        c = getopt(argc, argv, "d:e:ghn:s:vV:");
        if (c == -1)
            break;

        switch (c) {
        case 'd':
            testdir = optarg;
            break;
        case 'e':
            seed = (unsigned int)atoi(optarg);
            break;
        case 'g':
            debug = 1;
            break;
        case 'h':
            usage(argv[0]);
            break;
        case 'n':
            iterations = atoi(optarg);
            break;
        case 's':
            stride = atol(optarg);
            break;
        case 'v':
            verbose += 1;
            break;
        case 'V':
            verbose = atoi(optarg);
            break;
        }
    }

    if (rank == 0)
        printf("%s is running with %d process(es) %s\n",
               argv[0], size, debug ? "in DEBUG mode" : "\b\b");

    if (size < 2) {
        fprintf(stderr,
                "There should be at least 3 process to run the test!\n");
        MPI_Abort(MPI_COMM_WORLD, 2);
    }

    if (testdir == NULL && rank == 0) {
        fprintf(stderr, "Please specify a test directory! (\"%s -h\" for help)\n",
                argv[0]);
        MPI_Abort(MPI_COMM_WORLD, 2);
    }

    lp_gethostname();

    for (i = 0; i < iterations; ++i) {
        if (rank == 0)
            printf("%s: Running test #%s(iter %d)\n",
                   timestamp(), argv[0], i);

        cascading_rw(stride, seed);
        MPI_Barrier(MPI_COMM_WORLD);
    }

    if (rank == 0)
        printf("%s: All tests passed!\n", timestamp());
    MPI_Finalize();
    return 0;
}
int main ( int argc, char *argv[] )

/******************************************************************************/
/*
  Purpose:

    MAIN is the main program for SEARCH.

  Discussion:

    SEARCH demonstrates the use of MPI routines to carry out a search

    An array of given size is to be searched for occurrences of a
    specific value.

    The search is done in parallel.  A master process generates the
    array and the target value, then distributes the information among
    a set of worker processes, and waits for them to communicate back
    the (global) index values at which occurrences of the target value
    were found.

    An interesting feature of this program is the use of allocatable
    arrays, which allows the master program to set aside just enough
    memory for the whole array, and for each worker program to set aside
    just enough memory for its own part of the array.

  Licensing:

    This code is distributed under the GNU LGPL license. 

  Modified:

    09 October 2002

  Author:

    John Burkardt

  Reference:

    William Gropp, Ewing Lusk, Anthony Skjellum,
    Using MPI: Portable Parallel Programming with the
    Message-Passing Interface,
    Second Edition,
    MIT Press, 1999,
    ISBN: 0262571323.
*/
{
  int *a;
  int dest;
  float factor;
  int global;
  int i;
  int ierr;
  int master = 0;
  int my_id;
  int n;
  int npart;
  int num_procs;
  int source;
  int start;
  MPI_Status status;
  int tag;
  int tag_target = 1;
  int tag_size = 2;
  int tag_data = 3;
  int tag_found = 4;
  int tag_done = 5;
  int target;
  int workers_done;
  int x;
/*
  Initialize MPI.
*/
  ierr = MPI_Init ( &argc, &argv );
/*
  Get this processes's rank.
*/
  ierr = MPI_Comm_rank ( MPI_COMM_WORLD, &my_id );
/*
  Find out how many processes are available.
*/
  ierr = MPI_Comm_size ( MPI_COMM_WORLD, &num_procs );

  if ( my_id == master )
  {
    timestamp ( );
    printf ( "\n" );
    printf ( "SEARCH - Master process:\n" );
    printf ( "  C version\n" );
    printf ( "  An MPI example program to search an array.\n" );
    printf ( "\n" );
    printf ( "  Compiled on %s at %s.\n", __DATE__, __TIME__ );
    printf ( "\n" );
    printf ( "  The number of processes is %d,\n", num_procs );
  }

  printf ( "\n" );
  printf ( "Process %d is active.\n", my_id );
/*
  Have the master process generate the target and data.  In a more 
  realistic application, the data might be in a file which the master 
  process would read.  Here, the master process decides.
*/
  if ( my_id == master )
  {
/*
  Pick the number of data items per process, and set the total.
*/
    factor = ( float ) rand ( ) / ( float ) RAND_MAX;
    npart = 50 + ( int ) ( factor * 100.0E+00 );
    n = npart * num_procs;

    printf ( "\n" );
    printf ( "SEARCH - Master process:\n" );
    printf ( "  The number of data items per process is %d,\n", npart );
    printf ( "  The total number of data items is       %d.\n", n );
/*
  Now allocate the master copy of A, fill it with values, and pick 
  a value for the target.
*/
    a = ( int * ) malloc ( n * sizeof ( int ) );

    factor = ( float ) n / 10.0E+00 ;

    for ( i = 0; i < n; i++ ) 
    {
      a[i] = ( int ) ( factor * ( float ) rand ( ) / ( float ) RAND_MAX );
    }
    target = a[n/2];

    printf ( "  The target value is %d.\n", target );
/*
  The worker processes need to have the target value, the number of data items,
  and their individual chunk of the data vector.
*/
    for ( i = 1; i <= num_procs-1; i++ )
    {
      dest = i;
      tag = tag_target;

      ierr = MPI_Send ( &target, 1, MPI_INT, dest, tag, MPI_COMM_WORLD );

      tag = tag_size;

      ierr = MPI_Send ( &npart, 1, MPI_INT, dest, tag, MPI_COMM_WORLD );

      start = ( i - 1 ) * npart;
      tag = tag_data;

      ierr = MPI_Send ( a+start, npart, MPI_INT, dest, tag,
        MPI_COMM_WORLD );
    }
/*
  Now the master process simply waits for each worker process to report that 
  it is done.
*/
    workers_done = 0;

    while ( workers_done < num_procs-1 )
    {
      ierr = MPI_Recv ( &x, 1, MPI_INT, MPI_ANY_SOURCE, MPI_ANY_TAG,
        MPI_COMM_WORLD, &status );

      source = status.MPI_SOURCE;
      tag = status.MPI_TAG;
    
      if ( tag == tag_done )
      {
        workers_done = workers_done + 1;
      }
      else if ( tag == tag_found )
      {
        printf ( "P%d %d %d\n", source, x, a[x] );
      }
      else
      {
        printf ( "  Master process received message with unknown tag = %d.\n", tag );
      }

    }
/*
  The master process can throw away A now.
*/
    free ( a );
  }
/*
  Each worker process expects to receive the target value, the number of data
  items, and the data vector.
*/
  else 
  {
    source = master;
    tag = tag_target;

    ierr = MPI_Recv ( &target, 1, MPI_INT, source, tag, MPI_COMM_WORLD,
      &status );
 
    source = master;
    tag = tag_size;

    ierr = MPI_Recv ( &npart, 1, MPI_INT, source, tag, MPI_COMM_WORLD, 
      &status );

    a = ( int * ) malloc ( npart * sizeof ( int ) );

    source = master;
    tag = tag_data;

    ierr = MPI_Recv ( a, npart, MPI_INT, source, tag, MPI_COMM_WORLD,
      &status );
/*
  The worker simply checks each entry to see if it is equal to the target
  value.
*/
    for ( i = 0; i < npart; i++ )
    {
      if ( a[i] == target )
      {
        global = ( my_id - 1 ) * npart + i;
        dest = master;
        tag = tag_found;

        ierr = MPI_Send ( &global, 1, MPI_INT, dest, tag, MPI_COMM_WORLD );
      }

    }
/*
  When the worker is finished with the loop, it sends a dummy data value with
  the tag "TAG_DONE" indicating that it is done.
*/
    dest = master;
    tag = tag_done;

    ierr = MPI_Send ( &target, 1, MPI_INT, dest, tag, MPI_COMM_WORLD );

    free ( a );
     
  }
/*
  Terminate MPI.
*/
  ierr = MPI_Finalize ( );
/*
  Terminate.
*/
  if ( my_id == master )
  {
    printf ( "\n" );
    printf ( "SEARCH - Master process:\n" );
    printf ( "  Normal end of execution.\n" );
    printf ( "\n" );
    timestamp ( );
  }
  return 0;
}