Esempio n. 1
0
/**
 * DESC: Returns the distance traveled from a point p1 to another point p2.
 *   This is retrieved from the distTable hashtable.
 */
float lookup_distance(int p1, int p2)
{
#if USE_DISTANCE_TABLE
#if USE_BIG_TABLE
	return distTable[p1*CitiesA->size+p2];
#else
	if (p1<p2)
	{
#if ENFORCE_LOOKUP_TABLE_CORRECTNESS
		if (distTable[(p2*(p2-1)/2)+p1] != get_distance_between(p1, p2, Cities))
		{
			ERROR_TEXT;
			printf("INVALID VALUE IN DISTANCE TABLE OR INVALID LOOKUP: p1=%i p2=%i\n", p1, p2);
			NORMAL_TEXT;
			terminate_program(783);
		}
#endif
		return distTable[(p2*(p2-1)/2)+p1];
	}
	else if (p1>p2)
	{
#if ENFORCE_LOOKUP_TABLE_CORRECTNESS
		if (distTable[(p1*(p1-1)/2)+p2] != get_distance_between(p1, p2, Cities))
		{
			ERROR_TEXT;
			printf("INVALID VALUE IN DISTANCE TABLE OR INVALID LOOKUP: p1=%i p2=%i\n", p1, p2);
			NORMAL_TEXT;
			terminate_program(784);
		}
#endif
		return distTable[(p1*(p1-1)/2)+p2];
	}
	else
	{
		ERROR_TEXT;
		DPRINTF("WARNING -- THIS SHOULD NEVER HAPPEN (p1[%i]==p2[%i]); terminating...\n", p1, p2);
		NORMAL_TEXT;
		terminate_program(787);
		return 0.0;
	}
#endif// don't use big table
#else // don't use distance table
#if USE_NAIVE_DISTANCE
	int x, y, mask;
	// dist x
	x = CitiesA->city[p1]->x - CitiesA->city[p2]->x;
	// absolute value
	mask = x >> (sizeof(int)*8 - 1);
	x = (x+mask) ^ mask;
	// dist y
	y = CitiesA->city[p1]->y - CitiesA->city[p2]->y;
	// absolute value
	mask = y >> (sizeof(int)*8 - 1);
	y = (y+mask) ^ mask;
	return x + y;
#else
	return get_distance_between(p1, p2, CitiesA);
#endif// use_naive_distance
#endif// don't use distance table
} // lookup_distance()
/**
 * handler for the SIGUSR1 signal. this signal is used to inform this process
 *   that its client process has ended.
 *
 * @function   sigusr1_handler
 *
 * @date       2015-02-11
 *
 * @revision   none
 *
 * @designer   EricTsang
 *
 * @programmer EricTsang
 *
 * @note       none
 *
 * @signature  static void sigusr1_handler(int sigNum)
 *
 * @param      sigNum nimber that indicates which signal this is. in this case,
 *   this number will always be SIGUSR1
 */
static void sigusr1_handler(int sigNum)
{
    if(sigNum == SIGUSR1)
    {
        terminate_program(false);
    }
}
Esempio n. 3
0
/**
 * DESC: Loads cities from a file.
 *
 * mpi_rank : the rank of the mpi process
 * citiesFile : the string that is the file name
 * arr_cities : a pointer, passed by reference (so whatever pointer was passed in will now point to the cities loaded)
 */
void load_cities(int mpi_rank, char *citiesFile, tour_t **arr_cities)
{
	// if master...
	if (mpi_rank==0)
	{
		// load the cities specified by the file
		DPRINTF("Loading cities...");
		*arr_cities = loadCities(citiesFile);
		if (!(*arr_cities))
		{
			printf("Error while loading cities. refer to error log? halting.\n");
			terminate_program(5); // ERROR: error while loading cities
		}
		DPRINTF("done! (loaded %i cities from the file)\n",
			(*arr_cities)->size);
	}
	DPRINTF("done! (loaded %i cities from the file)\n",
		(*arr_cities)->size);
	// process the cities
	int N = (*arr_cities)->size;

	// output the city information to the console
#if PRINT_CITIES
	DPRINTF("\nNum Cities: %04i\n", (*arr_cities)->size);
	DPRINTF("---------------------------\n");
	int i;
	for (i=0; i < (*arr_cities)->size; i++)
	{
		DPRINTF("City[%04i] at %04i, %04i   [id: %04i]\n", i,
			(*arr_cities)->city[i]->x, (*arr_cities)->city[i]->y,
			(*arr_cities)->city[i]->id);
	}
	DPRINTF("\n");
#endif
}
Esempio n. 4
0
void keyboard_event(const SDL_KeyboardEvent &ev)
{
  switch(ev.keysym.sym)
    {
    case SDLK_ESCAPE:
      terminate_program(0);// never returns
    case SDLK_PAUSE:
    case SDLK_p:
      GAME_STATE.toggle_pause();
      toggle_play_music();
      break;
    case SDLK_RETURN:
      GAME_STATE.reset();
      reset_music();
      break;
      // Game control
    case SDLK_q:
    case SDLK_UP:
      if(GAME_STATE.running)
	{
	  GAME_STATE.game.queueInput(rotate_ccw);
	}
      break;
    case SDLK_a:
    case SDLK_LEFT:
      if(GAME_STATE.running)
	{
	  GAME_STATE.game.queueInput(shift_left);
	}
      break;
    case SDLK_e:
      if(GAME_STATE.running)
	{
	  GAME_STATE.game.queueInput(rotate_cw);
	}
      break;
    case SDLK_d:
    case SDLK_RIGHT:
      if(GAME_STATE.running)
	{
	  GAME_STATE.game.queueInput(shift_right);
	}
      break;
    case SDLK_x:
    case SDLK_DOWN:
      if(GAME_STATE.running)
	{
	  GAME_STATE.game.queueInput(hard_drop);
	}
      break;
    default:
      break;
    }
  GAME_STATE.checkGameOver();
}
/**
 * takes care of the client process.
 *
 * @function   serve_client
 *
 * @date       2015-02-11
 *
 * @revision   none
 *
 * @designer   EricTsang
 *
 * @programmer EricTsang
 *
 * @note
 *
 * reads the contents at the location specified by filePath, and sets the
 *   process's priority to the passed one then writes the contents of the file
 *   to the message queue for the client process to read.
 *
 * @signature  static int serve_client(pid_t clntPid, int priority, char*
 *   filePath)
 *
 * @param      clntPid process id of the child process
 * @param      priority priority of this client object
 * @param      filePath path to file to send to client through IPC
 *
 * @return     returns 0, normal exit return code.
 */
int serve_client(pid_t clntPid, int priority, char* filePath)
{
    /* obtain system resources for the process */
    initialize(clntPid, priority, filePath);

    /* do the read loop */
    read_loop(priority);

    /* terminate program... */
    terminate_program(true);

    return 0;
}
/**
 * prints the passed message, and ends the program while cleaning up.
 *
 * @function   fatal
 *
 * @date       2015-02-11
 *
 * @revision   none
 *
 * @designer   EricTsang
 *
 * @programmer EricTsang
 *
 * @note       none
 *
 * @signature  static void fatal(char* str)
 *
 * @param      str pointer to the first character of a string to send to the
 *   client to print on exit.
 */
static void fatal(char* str)
{
    /* declare and initialize a print & stop message structures */
    Message prntMsg;
    prntMsg.dataType = MSG_DATA_PRINT;

    /* send a print message as well as an stop message to the client */
    sprintf(prntMsg.data.printMsg.str, "fatal: %s", str);
    msg_send(msgQId, &prntMsg, clientPid);

    /* terminate program... */
    terminate_program(true);
}
Esempio n. 7
0
/*
 * Read the entry line-by-line and add the information in scp
 * Use defaults to initialize modifiable entry fields.
 */
static status_e parse_entry( entry_e entry_type,
                             int fd,
                             struct service_config *scp )
{
    static pset_h      attr_values = NULL;
    char               *line ;
    char               *attr_name ;
    enum assign_op      op ;
    const char         *func = "parse_entry" ;

    if ( ! attr_values && ( attr_values = pset_create( 10, 10 ) ) == NULL )
    {
        out_of_memory( func ) ;
        return( FAILED ) ;
    }

    for ( ;; )
    {
        line = next_line( fd ) ;
        if ( line == CHAR_NULL )
        {
            parsemsg( LOG_ERR, func, "incomplete entry" ) ;
            return( FAILED ) ;
        }

        if ( line_has_only_1_char( line, ENTRY_END ) )
            return( OK ) ;

        if ( parse_line( line, &attr_name, &op, attr_values ) == FAILED )
        {
            pset_clear( attr_values ) ;
            return( FAILED ) ;
        }

        if (identify_attribute( entry_type,
                                scp, attr_name, op, attr_values ) == FAILED )
        {
            /*
             * An error was detected in the default section. We will terminate
             * since whatever attribute being specified cannot be propagated.
             */
            msg(LOG_ERR, func,
                "A fatal error was encountered while parsing the default section."
                " xinetd will exit.");
            Sclose( fd );
            terminate_program();
        }
        pset_clear( attr_values ) ;
    }
}
Esempio n. 8
0
void check_pipe(void)
{
   int i;
#if NSIG < 256
   unsigned char sig;
#else
   int sig;
#endif
   const char *func = "check_pipe";

   if (signals_pending[0] < 0) return;

   if( ioctl(signals_pending[0], FIONREAD, &i) != 0 ) {
      msg(LOG_ERR, func, "Can't get the number of pending signals: %m");
      return;
   }
#if NSIG >= 256
   i /= sizeof(int);
#endif

   while( --i >= 0 ) {
      ssize_t ret_val;
      do
      {
         ret_val = read(signals_pending[0], &sig, sizeof(sig));
      } while (ret_val == (ssize_t)-1 && errno == EINTR);
      if (ret_val != (ssize_t)sizeof(sig) ) {
         msg(LOG_ERR, func, "Error retrieving pending signal: %m");
         return;
      }

      if( debug.on ) {
         msg(LOG_DEBUG, func, "Got signal %s", sig_name(sig));
      }

      switch(sig) {
         case SERVER_EXIT_SIG:       child_exit();           break;
         case RECONFIG_HARD_SIG:     hard_reconfig();        break;
         case OLD_RECONFIG_HARD_SIG: hard_reconfig();        break;
         case TERMINATION_SIG:       terminate_program();    break;
         case STATE_DUMP_SIG:        dump_internal_state();  break;
         case CONSISTENCY_CHECK_SIG: user_requested_check(); break;
         case QUIT_SIG:              quit_program();         break;
         default:
            msg(LOG_ERR, func, "unexpected signal: %s in signal pipe", 
               sig_name(sig));
      }
   }
}
Esempio n. 9
0
void process_events()
{
  SDL_Event ev;

  while( SDL_PollEvent( &ev ) )
    {
      switch(ev.type)
	{
	case SDL_QUIT:
	  terminate_program(0);// never returns
	case SDL_KEYDOWN:
	  keyboard_event(ev.key);
	  break;
	default:
	  break;
	}
    }
}
Esempio n. 10
0
edge_t* lookup_edge(int p1, int p2)
{
	if (p1<p2)
	{
		return edgeTable[(p2*(p2-1)/2)+p1];
	}
	else if (p1>p2)
	{
		return edgeTable[(p1*(p1-1)/2)+p2];
	}
	else
	{
		ERROR_TEXT;
		DPRINTF("WARNING IN LOOKUP_EDGE -- THIS SHOULD NEVER HAPPEN (p1[%i]==p2[%i]); terminating...\n", p1, p2);
		NORMAL_TEXT;
		
		terminate_program(787);
		return 0;
	}
} // lookup_edge()
void Program::link()
{
  dnload_glAttachShader(m_id, m_vertex_shader->getId());
  dnload_glAttachShader(m_id, m_fragment_shader->getId());

  dnload_glLinkProgram(m_id);

#if defined(USE_LD)
  std::string log = GlslShaderSource::get_program_info_log(m_id);

  if(0 < log.length())
  {
    std::cout << log << std::endl;
  }

  if(!GlslShaderSource::get_program_link_status(m_id))
  {
    terminate_program();
  }

  std::cout << "|program(" << m_id << ")\n";
#endif

  for(int ii = 0; (ii < PROGRAM_MAX_IDENTIFIERS); ++ii)
  {
    char identifier_string[] = { static_cast<char>(ii), 0 };
    m_attributes[ii] = dnload_glGetAttribLocation(m_id, identifier_string);
    m_uniforms[ii] = dnload_glGetUniformLocation(m_id, identifier_string);
#if defined(USE_LD)
    if(m_attributes[ii] >= 0)
    {
      std::cout << "|attribute '" << identifier_string << "': " << m_attributes[ii] << std::endl;
    }
    if(m_uniforms[ii] >= 0)
    {
      std::cout << "|uniform '" << identifier_string << "': " << m_uniforms[ii] << std::endl;
    }
#endif
  }
}
float *  nlfit
(
    int ts_length,                     /* length of time series data */
    float * ts_array,                  /* input time series array */
    char ** label                      /* label output for this voxel */
)

{
    float * fit;                       /* nonlinear fit of time series data */

    /*----- declare input option variables -----*/
    int nabs;                /* use absolute constraints for noise parameters */
    int  nrand;              /* number of random vectors to generate */
    int  nbest;              /* number of random vectors to keep */
    float rms_min;           /* minimum rms error to reject reduced model */

    /*----- declare time series variables -----*/
    int im1;                 /* index of 1st image in time series for analysis */
    float ** x_array = NULL;     /* independent variable matrix */
    char * tfilename = NULL;     /* file name of time points */

    /*----- declare reduced (noise) model variables -----*/
    char * nname = NULL;         /* noise model name */
    vfp nmodel;                  /* pointer to noise model */
    int r;                       /* number of parameters in the noise model */
    char ** npname = NULL;       /* noise parameter labels */
    float * par_rdcd = NULL;     /* estimated parameters for the reduced model */
    float sse_rdcd;              /* error sum of squares for the reduced model */
    float * min_nconstr = NULL;  /* min parameter constraints for noise model */
    float * max_nconstr = NULL;  /* max parameter constraints for noise model */

    /*----- declare full (signal+noise) model variables -----*/
    char * sname = NULL;         /* signal model name */
    vfp smodel;                  /* pointer to signal model */
    int p;                       /* number of parameters in the signal model */
    char ** spname = NULL;       /* signal parameter labels */
    float * par_full = NULL;     /* estimated parameters for the full model */
    float sse_full;              /* error sum of squares for the full model */
    float * tpar_full = NULL;    /* t-statistic of parameters in full model */
    float freg;                  /* f-statistic for the full regression model */
    float rmsreg;                /* rms for the full regression model */
    float rsqr;                  /* R^2 (coef. of multiple determination) */
    float smax;                  /* signed maximum of signal */
    float tmax;                  /* epoch of signed maximum of signal */
    float pmax;                  /* percentage change due to signal */
    float area;                  /* area between signal and baseline */
    float parea;                 /* percent area between signal and baseline */
    float * min_sconstr = NULL;  /* min parameter constraints for signal model */
    float * max_sconstr = NULL;  /* max parameter constraints for signal model */

    int novar;               /* flag for insufficient variation in the data */


    /*----- program initialization -----*/
    initialize_program (&im1, &nname, &sname, &nmodel, &smodel,
                        &r, &p, &npname, &spname,
                        &min_nconstr, &max_nconstr, &min_sconstr, &max_sconstr,
                        &nabs, &nrand, &nbest, &rms_min,
                        &par_rdcd, &par_full, &tpar_full,
                        ts_length, &tfilename, &x_array, &fit);


    /*----- calculate the reduced (noise) model -----*/
    calc_reduced_model (ts_length, r, x_array, ts_array,
                        par_rdcd, &sse_rdcd);


    /*----- calculate the full (signal+noise) model -----*/
    calc_full_model (nmodel, smodel, r, p,
                     min_nconstr, max_nconstr, min_sconstr, max_sconstr,
                     ts_length, x_array, ts_array, par_rdcd, sse_rdcd,
                     nabs, nrand, nbest, rms_min, par_full, &sse_full, &novar);


    /*----- create estimated time series using the full model parameters -----*/
    full_model (nmodel, smodel, par_full, par_full + r,
                ts_length, x_array, fit);


    /*----- calculate statistics for the full model -----*/
    analyze_results (nmodel, smodel, r, p, novar,
                     min_nconstr, max_nconstr, min_sconstr, max_sconstr,
                     ts_length, x_array,
                     par_rdcd, sse_rdcd, par_full, sse_full,
                     &rmsreg, &freg, &rsqr, &smax, &tmax, &pmax, &area, &parea,
                     tpar_full);


    /*----- report results for this voxel -----*/
    report_results (nname, sname, r, p, npname, spname, ts_length,
                    par_rdcd, sse_rdcd, par_full, sse_full, tpar_full,
                    rmsreg, freg, rsqr, smax, tmax, pmax, area, parea, label);
    printf ("\nVoxel Results: \n");
    printf ("%s \n", *label);


    /*----- end of program -----*/
    terminate_program (r, p, ts_length, &x_array,
                       &par_rdcd, &min_nconstr, &max_nconstr,
                       &par_full, &tpar_full,
                       &min_sconstr, &max_sconstr);

    return (fit);

}
Esempio n. 13
0
/**
 * DESC: Given an array of yours and the number of tours in the array, randomly
 *	choose one of the tours. The choice is weighted based on the fitness
 *	of the function, inversely. In other words, for fitness F1 for tour T1,
 *	your probability of receiving tour T1 is (1/F1) / sum( 1/Fi ).
 *
 * tours : the array of tours to choose from
 * num_tours : the number of tours to choose from
 * ignore_tour [optional] : a tour to ignore for choosing, set to null (0)
 *	to not ignore any tours
 */
tour_t* roulette_select(tour_t** tours, int num_tours, tour_t* ignore_tour)
{
	int i;
	float rand,rand_fit,sum_fitness,temp;
	sum_fitness=0.0;

#if CAP_ROULETTE_WHEEL
	float fitTotal = 0;
	float fitAvg = -1;
	float fitMin = -1;
	float fitMax = -1;
	for (i = 0; i < num_tours; i++)
	{
		if (tours[i] == ignore_tour)
			continue;
		temp = 1.0 / tours[i]->fitness;
		fitTotal += temp;
	}
	fitAvg = fitTotal / (num_tours - (ignore_tour?1:0));
	fitMin = RW_CAP_MIN * fitAvg;
	fitMax = RW_CAP_MAX * fitAvg;
#endif

	// sum up the inverted total fitnesses
	for (i=0;i<num_tours;i++)
	{
		if (tours[i] == ignore_tour)
			continue; // don't count ignore_tour in the fitness sum
		temp = tours[i]->fitness;
#if ENFORCE_NONZERO_FITNESS
		if (temp==0) {
			printf("tour %i has fitness zero. hex: %x\n",i, tours[i]);
		}
#endif
		temp = 1.0 / temp;
#if CAP_ROULETTE_WHEEL
		if (temp < fitMin)
			temp = fitMin;
		if (temp > fitMax)
			temp = fitMax;
#endif
		sum_fitness+= temp;
	}

	// random float from 0 to 1
	rand=frand();

	// some random point between 0 and top fitness
	rand_fit = sum_fitness * rand;

	for (i=0;i<num_tours;i++)
	{
		if (tours[i] == ignore_tour)
			continue; // don't check the ignore tour, it wasn't counted in the fitness sum
		temp = 1.0 / tours[i]->fitness;
#if CAP_ROULETTE_WHEEL
		if (temp < fitMin)
			temp = fitMin;
		if (temp > fitMax)
			temp = fitMax;
#endif
		if (rand_fit < temp) {
			// If your fitness is in this tour, return it.
			return tours[i];
		} 
		// Otherwise, subtract this tour's fitness from sum_fitness and try again.
		else rand_fit-=temp;
	}
	
	// never executes.
	ERROR_TEXT;
	DPRINTF("Reached 'unreachable' code in roullette_select.\n");
	NORMAL_TEXT;
	DPRINTF("rand: %f, rand_fit: %f, sum_fitness: %f, temp: %f, ignore_tour: m(\033[31m%i\033[0m)\n", rand, rand_fit, sum_fitness, temp, ignore_tour);
	terminate_program(543);
	return 0;
}
Esempio n. 14
0
/*!
	This is the main entry point of the runtime loader as
	specified by its ld-script.
*/
int
runtime_loader(void* _args, void* commpage)
{
	void *entry = NULL;
	int returnCode;

	gProgramArgs = (struct user_space_program_args *)_args;
	__gCommPageAddress = commpage;

	// Relocate the args and env arrays -- they are organized in a contiguous
	// buffer which the kernel just copied into user space without adjusting the
	// pointers.
	{
		int32 i;
		addr_t relocationOffset = 0;

		if (gProgramArgs->arg_count > 0)
			relocationOffset = (addr_t)gProgramArgs->args[0];
		else if (gProgramArgs->env_count > 0)
			relocationOffset = (addr_t)gProgramArgs->env[0];

		// That's basically: <new buffer address> - <old buffer address>.
		// It looks a little complicated, since we don't have the latter one at
		// hand and thus need to reconstruct it (<first string pointer> -
		// <arguments + environment array sizes>).
		relocationOffset = (addr_t)gProgramArgs->args - relocationOffset
			+ (gProgramArgs->arg_count + gProgramArgs->env_count + 2)
				* sizeof(char*);

		for (i = 0; i < gProgramArgs->arg_count; i++)
			gProgramArgs->args[i] += relocationOffset;

		for (i = 0; i < gProgramArgs->env_count; i++)
			gProgramArgs->env[i] += relocationOffset;
	}

#if DEBUG_RLD
	close(0); open("/dev/console", 0); /* stdin   */
	close(1); open("/dev/console", 0); /* stdout  */
	close(2); open("/dev/console", 0); /* stderr  */
#endif

	if (heap_init() < B_OK)
		return 1;

	rldexport_init();
	rldelf_init();

	load_program(gProgramArgs->program_path, &entry);

	if (entry == NULL)
		return -1;

	// call the program entry point (usually _start())
	returnCode = ((int (*)(int, void *, void *))entry)(gProgramArgs->arg_count,
		gProgramArgs->args, gProgramArgs->env);

	terminate_program();

	return returnCode;
}
Esempio n. 15
0
/**
 * Appelée lors Ctrl-C.
 * S'occupe du nettoyage...
 */
void terminate_program_catch(int n)
{
    terminate_program();
}
Esempio n. 16
0
 /* Load the files retrieved from the list parallelly. */
 void threaded_bacteria_creation() {
     
     // creates the bacterias array
     Bacteria **bacterias = new Bacteria*[number_bacterias];
     
     pthread_t workers[NUM_THREADS];
     parameters params[NUM_THREADS];
     
     // enforces joinable threads
     pthread_attr_t attr;
     pthread_attr_init(&attr);
     pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
     
     int block_size = number_bacterias / NUM_THREADS;
     
     // spawns threads responsible for creating bacterias
     for (int i = 0; i < NUM_THREADS; i++) {
         
         // the thread parameters
         params[i].thread_id = i;
         params[i].bacterias = bacterias;
         
         // setting the bounds
         params[i].lower_bound = i * block_size;
         
         if (params[i].thread_id == NUM_THREADS - 1)
             params[i].upper_bound = number_bacterias;
         else
             params[i].upper_bound = params[i].lower_bound + block_size;
         
         // creating the thread
         int rc = pthread_create(&workers[i], &attr, create_bacterias, (void*)&params[i]);
         
         if (rc)
             terminate_program("Error while creating threads.");
     }
     
     // joins the worker threads without caring for the returned value
     for (long i = 0; i < NUM_THREADS; i++)
         pthread_join(workers[i], NULL);
     
     // create threads to perform the comparison
     int max_comparisons = number_bacterias * 0.5 * (number_bacterias - 1);
     block_size = max_comparisons / NUM_THREADS;
     
     for (int i = 0; i < NUM_THREADS; i++) {
         params[i].lower_bound = block_size * i;
         
         if (params[i].thread_id == NUM_THREADS - 1)
             params[i].upper_bound = max_comparisons;
         else
             params[i].upper_bound = params[i].lower_bound + block_size;
         
         int rc = pthread_create(&workers[i], &attr, threaded_compare_bacterias, (void*)&params[i]);
         
         if (rc)
             terminate_program("Error while creating comparison threads.\n");
     }
     
     // join the comparison threads
     for (long i = 0; i < NUM_THREADS; i++)
         pthread_join(workers[i], NULL);
 }