Example #1
0
char           *
random_string(unsigned length)
{

    char           *state = (char *) malloc(sizeof(char) * STATES);
    char           *result = (char *) malloc(length + 1);
    int             i, number;
    unsigned        seed = (unsigned) time((time_t *) NULL);

    /* printf ("Seed is %u\n", seed); */

    /* Initialize random generator */
    (void) initstate(seed, state, STATES);

    for (i = 0; i < length; i++) {
        number = (random() % 94) + 33;
        /* printf ("Number for %d is %d\n", i, number); */
        result[i] = (char) number;
    }
    result[length] = '\0';

    /* printf ("Result is %s\n", result); */

    return result;

}
Example #2
0
// render the globe
void miniglobe::render()
   {
   if (DONE==0)
      {
      switch (SHAPE)
         {
         case SHAPE_SUN: create_sun(); break;
         case SHAPE_MERCURY: create_orb(minicoord::MINICOORD_ORB_MERCURY); break;
         case SHAPE_VENUS: create_orb(minicoord::MINICOORD_ORB_VENUS); break;
         case SHAPE_EARTH: create_earth(); break;
         case SHAPE_MARS: create_orb(minicoord::MINICOORD_ORB_MARS); break;
         case SHAPE_JUPITER: create_orb(minicoord::MINICOORD_ORB_JUPITER); break;
         case SHAPE_SATURN: create_orb(minicoord::MINICOORD_ORB_SATURN); break;
         case SHAPE_URANUS: create_orb(minicoord::MINICOORD_ORB_URANUS); break;
         case SHAPE_NEPTUNE: create_orb(minicoord::MINICOORD_ORB_NEPTUNE); break;
         case SHAPE_CERES: create_orb(minicoord::MINICOORD_ORB_CERES); break;
         case SHAPE_PLUTO: create_orb(minicoord::MINICOORD_ORB_PLUTO); break;
         case SHAPE_ERIS: create_orb(minicoord::MINICOORD_ORB_ERIS); break;
         case SHAPE_MOON: create_moon(); break;
         default: ERRORMSG();
         }

      create_shader(CONFIGURE_FRONTNAME,CONFIGURE_BACKNAME,
                    CONFIGURE_FRONTBUF,CONFIGURE_BACKBUF);

      DONE=1;
      }

   initstate();
   STRIP->render();
   exitstate();
   }
Example #3
0
// signpost init method
BOOLINT minipointrndr_signpost::init(minipoint *points,
                                     float ex,float ey,float ez,
                                     float dx,float dy,float dz,
                                     float nearp,float farp,float fovy,float aspect,
                                     double time,minipointopts *global,
                                     BOOLINT usewarp)
   {
   if (dx==MAXFLOAT || dy==MAXFLOAT || dz==MAXFLOAT ||
       nearp<=0.0f || farp<=0.0f || fovy<=0.0f || aspect<=0.0f ||
       time<0.0) ERRORMSG();

   if (usewarp) return(FALSE);

   POINTS=points;

   EX=ex;
   EY=ey;
   EZ=ez;

   GLOBAL=global;

   SCALEELEV=points->getscaleelev();

   NEAREST=points->getnearest(ex,ez,ey);

   initstate();
   disableculling();
   enableblending();

   return(TRUE);
   }
Example #4
0
void ActivityManagerApp::InitRNG()
{
	memset(m_rngState, 0, sizeof(m_rngState));

	bool initialized = false;

	unsigned int rngSeed;

	if (!initialized) {
		struct timeval tv;
		gettimeofday(&tv, NULL);

		rngSeed = (unsigned)(tv.tv_sec ^ tv.tv_usec);

		initialized = true;

		LOG_AM_DEBUG("Seeding RNG using time: sec %u, usec %u, seed %u",
			(unsigned)tv.tv_sec, (unsigned)tv.tv_usec, rngSeed);
	}

	char *oldstate = initstate(rngSeed, m_rngState, sizeof(m_rngState));

	if (!oldstate) {
		LOG_AM_ERROR(MSGID_INIT_RNG_FAIL, 0, "Failed to initialize the RNG state");
	}
}
Example #5
0
// render ecef geometry
void miniview::render_ecef_geometry(double)
   {
   // render plain globe for z-values:

   static miniglobe globe;

   static const int gltess = 32;
   static const double glscale = 0.999;
   static const double glzscale = 1.05;

   globe.settess(gltess);
   globe.setscale(1.0);
   globe.setdynscale(glscale);
   globe.setZscale(glzscale);

   disableRGBAwriting();
   globe.render();
   enableRGBAwriting();

   initstate();

   // render ecef z-axis:

   linewidth(2);
   enablelinesmooth();

   static const miniv3d zacolor(0.25, 0.25, 0.5);

   color(zacolor);
   renderline(miniv3d(0.0, 0.0, -1.1*getorbradius()),
              miniv3d(0.0, 0.0, -getorbradius()));
   renderline(miniv3d(0.0, 0.0, getorbradius()),
              miniv3d(0.0, 0.0, 1.1*getorbradius()));

   // render equator:

   linewidth(1);
   disableZwriting();

   static const int eqlines = 100;
   static const miniv3d eqcolor(0.25, 0.25, 0.25);

   color(eqcolor);
   for (int i=0; i<=eqlines; i++)
      {
      minicoord c(miniv3d((double)i/eqlines*360*3600, 0.0, 0.0),minicoord::MINICOORD_LLH);
      c.convert2(minicoord::MINICOORD_ECEF);

      static minicoord c0;

      if (i>0) renderline(c0.vec, c.vec);
      c0 = c;
      }

   enableZwriting();
   disablelinesmooth();

   exitstate();
   }
Example #6
0
/* initialize random() */
void
setRandom(void)
{

  struct timeval	now;

  gettimeofday (&now, NULL);
  initstate((now.tv_usec/16000), (char *) rstate, 32);
  setstate(rstate);
}
Example #7
0
rng_t* posix_rng_new(size_t state_size)
{
  static const int num_bytes = 256;
  char* state = polymec_malloc(sizeof(char) * num_bytes);
  rng_vtable vtable = {.set_seed = posix_set_seed,
                       .get = posix_get,
                       .dtor = posix_free};
  initstate(random(), state, num_bytes);
  return rng_new("posix RNG", state, 0, posix_max, vtable, true, false);
}
static int32_t
FcRandom(void)
{
    int32_t result;

#if HAVE_RANDOM_R
    static struct random_data fcrandbuf;
    static char statebuf[256];
    static FcBool initialized = FcFalse;

    if (initialized != FcTrue)
    {
	initstate_r(time(NULL), statebuf, 256, &fcrandbuf);
	initialized = FcTrue;
    }

    random_r(&fcrandbuf, &result);
#elif HAVE_RANDOM
    static char statebuf[256];
    char *state;
    static FcBool initialized = FcFalse;

    if (initialized != FcTrue)
    {
	state = initstate(time(NULL), statebuf, 256);
	initialized = FcTrue;
    }
    else
	state = setstate(statebuf);

    result = random();

    setstate(state);
#elif HAVE_LRAND48
    result = lrand48();
#elif HAVE_RAND_R
    static unsigned int seed = time(NULL);

    result = rand_r(&seed);
#elif HAVE_RAND
    static FcBool initialized = FcFalse;

    if (initialized != FcTrue)
    {
	srand(time(NULL));
	initialized = FcTrue;
    }
    result = rand();
#else
# error no random number generator function available.
#endif

    return result;
}
Example #9
0
nsresult
nsUUIDGenerator::Init()
{
    mLock = PR_NewLock();

    NS_ENSURE_TRUE(mLock, NS_ERROR_OUT_OF_MEMORY);

    // We're a service, so we're guaranteed that Init() is not going
    // to be reentered while we're inside Init().
    
#if !defined(XP_WIN) && !defined(XP_MACOSX) && !defined(ANDROID)
    /* initialize random number generator using NSPR random noise */
    unsigned int seed;

    PRSize bytes = 0;
    while (bytes < sizeof(seed)) {
        PRSize nbytes = PR_GetRandomNoise(((unsigned char *)&seed)+bytes,
                                          sizeof(seed)-bytes);
        if (nbytes == 0) {
            return NS_ERROR_FAILURE;
        }
        bytes += nbytes;
    }

    /* Initialize a new RNG state, and immediately switch
     * back to the previous one -- we want to use mState
     * only for our own calls to random().
     */
    mSavedState = initstate(seed, mState, sizeof(mState));
    setstate(mSavedState);

    mRBytes = 4;
#ifdef RAND_MAX
    if ((unsigned long) RAND_MAX < (unsigned long)0xffffffff)
        mRBytes = 3;
    if ((unsigned long) RAND_MAX < (unsigned long)0x00ffffff)
        mRBytes = 2;
    if ((unsigned long) RAND_MAX < (unsigned long)0x0000ffff)
        mRBytes = 1;
    if ((unsigned long) RAND_MAX < (unsigned long)0x000000ff)
        return NS_ERROR_FAILURE;
#endif

#endif /* non XP_WIN and non XP_MACOSX */

    return NS_OK;
}
Example #10
0
static void random_init(void)
{
	int f, n;
	unsigned int seed = time(NULL) & getpid();
	char rand_state[256];

	f = open("/dev/urandom", O_RDONLY);
	if (f > 0) {
		n = read(f, rand_state, sizeof(rand_state));
		close(f);
		if (n > 32) {
			initstate(seed, rand_state, n);
			return;
		}
	}
	srandom(seed);
}
Example #11
0
// Seed random with hash of hostname combined with current time.
void seed() {
  struct utsname name;
  if (uname(&name) == -1) {
    perror("uname");
    exit(-1);
  }
  printf("Hostname=%s\n", name.nodename);

  unsigned seed;
  Hash(sizeof(unsigned) * 8, (BitSequence *)name.nodename,
       strlen(name.nodename) * 8, (BitSequence *)&seed);
  seed += time(NULL);

  printf("seed=%u\n", seed);

  static char state[256];
  initstate(seed, state, 256);
}
Example #12
0
int createUUID(char uuid[UUID_LEN]){
	static u8 _rand_init = 0;
	static char randstate[2048];
	if(_rand_init == 0){
		initstate(time(NULL), randstate, 2048);
		setstate(randstate);
		_rand_init = 1;
	}
	
	u32 r[8];
	for(int x=0;x<8;x++){
		r[x] = random();
	}
	//Make repres
	//Fix this
	sprintf(uuid, "%02X%02X%02X%02X-%02X%02X-%02X%02X-%02X%02X%02X%02X%02X%02X", r[0], r[1], r[2], r[3], r[4], r[5], r[6], r[7], r[0], r[1], r[2], r[3], r[4], r[5], r[6], r[7]);

	return 0;
}
Example #13
0
int deletefile(char *file, BCoptions options, char *key, struct stat statbuf) {
  int lsize;
  long g;
  uLong j = 0, k = 0;
  signed char i;
  char *state, *garbage;
  FILE *fd;

  if (options.securedelete > 0) {
    lsize = sizeof(long);
    k = (statbuf.st_size / lsize) + 1;
    if ((state = malloc(257)) == NULL)
      memerror();

    initstate((unsigned long) key, state, 256);
    if ((garbage = malloc(lsize)) == NULL)
      memerror();

    fd = fopen(file, "r+b");
    if (!fd) {
        fprintf(stderr, "Error deleting file %s: %s\n", file, strerror(errno));
        return(1);
    }
    for (i = options.securedelete; i > 0; i--) {
      fseek(fd, 0, SEEK_SET);

      for (j = 0; j < k; j += lsize) {
        g = random();
        memcpy(garbage, &g, lsize);
        fwrite(garbage, lsize, 1, fd);
      }
      fflush(fd);
    }
    fclose(fd);
  }

  if (unlink(file)) {
    fprintf(stderr, "Error deleting file %s: %s\n", file, strerror(errno));
    return(1);
  }
  return(0);
}
/* Derived from lc_random_seed_nonblocking().
 */
static int
lpc_random_seed_nonblocking(void)
{
    int err = 0;
    int seed = 0;

    err = lpc_random_get_seed(&seed, 1);
    if (err) {
        goto bail;
    }

    lpc_random_old_state = initstate(seed, lpc_random_state,
                                     sizeof(lpc_random_state));
    if (lpc_random_old_state == NULL) {
        err = 1;
        goto bail;
    }

 bail:
    return(err);
}
Example #15
0
int createUUID(char uuid[UUID_LEN]){
    static u8 _rand_init = 0;
    static char randstate[2048];
    if(_rand_init == 0){
        initstate(time(NULL), randstate, 2048);
        setstate(randstate);
        _rand_init = 1;
    }

    u32 r[8];
    for(int x=0;x<8;x++){
        r[x] = random();
    }
    //Make repres
    //Fix this
    /* IcY: there are 14 arguments specified in the printf format string
     * but 16 arguments?
     */
    sprintf(uuid, "%02X%02X%02X%02X-%02X%02X-%02X%02X-%02X%02X%02X%02X%02X%02X", r[0], r[1], r[2], r[3], r[4], r[5], r[6], r[7], r[0], r[1], r[2], r[3], r[4], r[5]/*, r[6], r[7]*/);

    return 0;
}
Example #16
0
uint8_t *octo_keygen()
{
	uint8_t *output = malloc(sizeof(uint8_t) * 16);
	if(output == NULL)
	{
		DEBUG_MSG("malloc failed allocating output array");
		errno = ENOMEM;
		return NULL;
	}
	char *randstate = malloc(256);
	if(randstate == NULL)
	{
		DEBUG_MSG("malloc failed allocating random state array");
		errno = ENOMEM;
		return NULL;
	}
	initstate((unsigned int)time(NULL), randstate, 256);
	for(unsigned int i = 0; i < 16; i++)
	{
		output[i] = (uint8_t)random();
	}
	free(randstate);
	return output;
}
Example #17
0
void
sc_init(struct spe_record__conf * conf, void
        (*pe_handler)(int, siginfo_t *, void *))
{

    if (initstate(conf->period.seed, conf->period.randstate,
                  SIZE_RANDOM_STATE) == NULL)
    {
        fprintf(stderr,
                "Error while initializing the random number generator.\n");
    }

    //Set signal stuff
    struct sigaction sa;
    memset(&sa, 0, sizeof(struct sigaction));
    sa.sa_sigaction = pe_handler;
    sa.sa_flags = SA_SIGINFO;

    if (sigaction(PE_SAMPLE_SIG, &sa, NULL ) < 0)
    {
        fprintf(stderr, "Error setting up signal handler\n");
        exit(1);
    }
}
Example #18
0
int
main (void)
{
    int pass;
    int ret = 0;
    long int r[2];

    for (pass = 0; pass < 2; pass++)
    {
        srandom (0x12344321);

        int j;
        for (j = 0; j < 3; ++j)
            random ();
        if (pass == 1)
        {
            char state[128];
            char *ostate = initstate (0x34562101, state, 128);
            if (setstate (ostate) != state)
            {
                puts ("setstate (ostate) != state");
                ret = 1;
            }
        }

        random ();
        r[pass] = random ();
    }

    if (r[0] != r[1])
    {
        printf ("%ld != %ld\n", r[0], r[1]);
        ret = 1;
    }
    return ret;
}
Example #19
0
void
CreateDistribution (cluster_type cluster, model_type model)
{
    particle *particle_array;
    int global_num_particles;
    particle *new_particle;
    char particle_state[RANDOM_SIZE];
    real charge;
    real r_scale;
    real v_scale;
    vector r_sum;
    vector v_sum;
    int end_limit;
    int i;
    int j;
    real temp_r;
    real radius;
    real x_vel;
    real y_vel;
    real vel;
    real offset;
    particle *twin_particle;

    particle_array = (particle *) G_MALLOC(Total_Particles * sizeof(particle));

    Particle_List = (particle **) G_MALLOC(Total_Particles * sizeof(particle *));
    for (i = 0; i < Total_Particles; i++)
        Particle_List[i] = &particle_array[i];

    r_scale = 3 * M_PI / 16;
    v_scale = (real) sqrt(1.0 / (double) r_scale);
    r_sum.x = (real) 0.0;
    r_sum.y = (real) 0.0;
    v_sum.x = (real) 0.0;
    v_sum.y = (real) 0.0;
    initstate(0, particle_state, RANDOM_SIZE);

    switch (cluster) {
    case ONE_CLUSTER:
        end_limit = Total_Particles;
        switch (model) {
        case UNIFORM:
            printf("Creating a one cluster, uniform distribution for %d ",
                   Total_Particles);
            printf("particles\n");
            break;
        case PLUMMER:
            printf("Creating a one cluster, non uniform distribution for %d ",
                   Total_Particles);
            printf("particles\n");
            break;
        }
        break;
    case TWO_CLUSTER:
        end_limit = (Total_Particles / 2) + (Total_Particles & 0x1);
        switch (model) {
        case UNIFORM:
            printf("Creating a two cluster, uniform distribution for %d ",
                   Total_Particles);
            printf("particles\n");
            break;
        case PLUMMER:
            printf("Creating a two cluster, non uniform distribution for %d ",
                   Total_Particles);
            printf("particles\n");
            break;
        }
        break;
    }
    setstate(particle_state);
    global_num_particles = 0;
    charge = 1.0 / Total_Particles;
    charge /= Total_Particles;
    for (i = 0; i < end_limit; i++) {
        new_particle = InitParticle(charge, charge);
        switch (model) {
        case UNIFORM:
            do {
                new_particle->pos.x = XRand(-1.0, 1.0);
                new_particle->pos.y = XRand(-1.0, 1.0);
                temp_r = DOT_PRODUCT((new_particle->pos), (new_particle->pos));
            }
            while (temp_r > (real) 1.0);
            radius = sqrt(temp_r);
            break;
        case PLUMMER:
            do
                radius = (real) 1.0 / (real) sqrt(pow(XRand(0.0, MAX_FRAC),
                                                      -2.0/3.0) - 1);
            while (radius > 9.0);
            PickShell(&(new_particle->pos), r_scale * radius);
            break;
        }
        VECTOR_ADD(r_sum, r_sum, (new_particle->pos));

        do {
            x_vel = XRand(0.0, 1.0);
            y_vel = XRand(0.0, 0.1);
        }
        while (y_vel > x_vel * x_vel * (real) pow(1.0 - (x_vel * x_vel), 3.5));
        vel = (real) sqrt(2.0) * x_vel / pow(1.0 + (radius * radius), 0.25);
        PickShell(&(new_particle->vel), v_scale * vel);
        VECTOR_ADD(v_sum, v_sum, (new_particle->vel));
    }

    if (cluster == TWO_CLUSTER) {
        switch (model) {
        case UNIFORM:
            offset = 1.5;
            break;
        case PLUMMER:
            offset = 2.0;
            break;
        }
        for (i = end_limit; i < Total_Particles; i++) {
            new_particle = InitParticle(charge, charge);
            twin_particle = Particle_List[i - end_limit];
            new_particle->pos.x = twin_particle->pos.x + offset;
            new_particle->pos.y = twin_particle->pos.y + offset;
            VECTOR_ADD(r_sum, r_sum, (new_particle->pos));
            new_particle->vel.x = twin_particle->vel.x;
            new_particle->vel.y = twin_particle->vel.y;
            VECTOR_ADD(v_sum, v_sum, (new_particle->vel));
        }
    }

    VECTOR_DIV(r_sum, r_sum, (real) Total_Particles);
    VECTOR_DIV(v_sum, v_sum, (real) Total_Particles);
    for (i = 0; i < Total_Particles; i++) {
        new_particle = Particle_List[i];
        VECTOR_SUB((new_particle->pos), (new_particle->pos), r_sum);
        VECTOR_SUB((new_particle->vel), (new_particle->vel), v_sum);
    }
}
int main(int argc, char **argv)
{
	pthread_t thr;
	char	*host;
	int	port;
	int	i;
	int	c;
	char random_state[16];

	while ((c = getopt(argc, argv, "c:g:i:k:r:t:")) != EOF) {
		switch (c) {
		case 'c':
			num_connections = intarg(argv[0], optarg);
			break;
		case 'g':
			probability_get = intarg(argv[0], optarg);
			break;
		case 'i':
			num_iterations = intarg(argv[0], optarg);
			break;
		case 'k':
			num_keys = intarg(argv[0], optarg);
			break;
		case 'r':
			num_requests = intarg(argv[0], optarg);
			break;
		case 's':
			seed = intarg(argv[0], optarg);
			break;
		case 't':
			poll_wait_sec = intarg(argv[0], optarg);
			break;
		default:
			usage(argv[0]);
			break;
		}
	}

	initstate(seed, random_state, sizeof(random_state));

	if (argc < optind + 2)
		usage(argv[0]);

	host = argv[optind++];
	port = intarg(argv[0], argv[optind]);

	fds = malloc(num_connections * sizeof(int));
	if (fds == NULL) {
		perror("malloc");
		exit(1);
	}

	for (i = 0; i < num_connections; i++) {
		fds[i] = clientsock(host, port);
		if (fds[i] < 0) {
			perror(host);
			exit(1);
		}
		if ((i % 25) == 0) {
			printf("\rOpened %d connections", i);
			fflush(stdout);
		}

		set_nodelay(fds[i], 1);
		set_nonblock(fds[i]);
	}
	printf("\rOpened %d connections\n", num_connections);

	fd_in_use = calloc(1, fds[num_connections - 1]);
	if (fd_in_use == NULL) {
		perror("calloc");
		exit(1);
	}

	pthread_mutex_init(&stats_mutex, NULL);
	pthread_mutex_init(&fd_mutex, NULL);

	for (i = 0; i < num_requests; i++)
		pthread_create(&thr, NULL, thread_main, NULL);

	while (iteration_count < num_iterations) {
		poll(NULL, 0, 1000);
		stats();
	}

	stats();
	putchar('\n');
}
Example #21
0
int
main(int argc, char **argv)
{
	int	i, ch;
	char	*endp;
	char goodfile[1024];
	char logfile[1024];

	goodfile[0] = 0;
	logfile[0] = 0;

	page_size = getpagesize();
	page_mask = page_size - 1;

	setvbuf(stdout, NULL, _IOLBF, 0); /* line buffered stdout */

	while ((ch = getopt(argc, argv, "b:c:dl:m:no:p:qr:s:t:w:D:LN:OP:RS:W"))
	       != EOF)
		switch (ch) {
		case 'b':
			simulatedopcount = getnum(optarg, &endp);
			if (!quiet)
				fprintf(stdout, "Will begin at operation %ld\n",
					simulatedopcount);
			if (simulatedopcount == 0)
				usage();
			simulatedopcount -= 1;
			break;
		case 'c':
			closeprob = getnum(optarg, &endp);
			if (!quiet)
				fprintf(stdout,
					"Chance of close/open is 1 in %d\n",
					closeprob);
			if (closeprob <= 0)
				usage();
			break;
		case 'd':
			debug = 1;
			break;
		case 'l':
			maxfilelen = getnum(optarg, &endp);
			if (maxfilelen <= 0)
				usage();
			break;
		case 'm':
			monitorstart = getnum(optarg, &endp);
			if (monitorstart < 0)
				usage();
			if (!endp || *endp++ != ':')
				usage();
			monitorend = getnum(endp, &endp);
			if (monitorend < 0)
				usage();
			if (monitorend == 0)
				monitorend = -1; /* aka infinity */
			debug = 1;
		case 'n':
			sizechecks = 0;
			break;
		case 'o':
			maxoplen = getnum(optarg, &endp);
			if (maxoplen <= 0)
				usage();
			break;
		case 'p':
			progressinterval = getnum(optarg, &endp);
			if ((int)progressinterval < 0)
				usage();
			break;
		case 'q':
			quiet = 1;
			break;
		case 'r':
			readbdy = getnum(optarg, &endp);
			if (readbdy <= 0)
				usage();
			break;
		case 's':
			style = getnum(optarg, &endp);
			if (style < 0 || style > 1)
				usage();
			break;
		case 't':
			truncbdy = getnum(optarg, &endp);
			if (truncbdy <= 0)
				usage();
			break;
		case 'w':
			writebdy = getnum(optarg, &endp);
			if (writebdy <= 0)
				usage();
			break;
		case 'D':
			debugstart = getnum(optarg, &endp);
			if (debugstart < 1)
				usage();
			break;
		case 'L':
			lite = 1;
			break;
		case 'N':
			numops = getnum(optarg, &endp);
			if (numops < 0)
				usage();
			break;
		case 'O':
			randomoplen = 0;
			break;
		case 'P':
			strncpy(goodfile, optarg, sizeof(goodfile));
			strcat(goodfile, "/");
			strncpy(logfile, optarg, sizeof(logfile));
			strcat(logfile, "/");
			break;
		case 'R':
			mapped_reads = 0;
			break;
		case 'S':
			seed = getnum(optarg, &endp);
			if (seed == 0)
				seed = time(0) % 10000;
			if (!quiet)
				fprintf(stdout, "Seed set to %d\n", seed);
			if (seed < 0)
				usage();
			break;
		case 'W':
			mapped_writes = 0;
			if (!quiet)
				fprintf(stdout, "mapped writes DISABLED\n");
			break;

		default:
			usage();
			/* NOTREACHED */
		}
	argc -= optind;
	argv += optind;
	if (argc != 1)
		usage();
	fname = argv[0];

	signal(SIGHUP,	cleanup);
	signal(SIGINT,	cleanup);
	signal(SIGPIPE,	cleanup);
	signal(SIGALRM,	cleanup);
	signal(SIGTERM,	cleanup);
	signal(SIGXCPU,	cleanup);
	signal(SIGXFSZ,	cleanup);
	signal(SIGVTALRM,	cleanup);
	signal(SIGUSR1,	cleanup);
	signal(SIGUSR2,	cleanup);
	signal(SIGSEGV, segv);

	initstate(seed, state, 256);
	setstate(state);
	fd = open(fname, O_RDWR|(lite ? 0 : O_CREAT|O_TRUNC), 0666);
	if (fd < 0) {
		prterr(fname);
		exit(91);
	}
	strncat(goodfile, fname, 256);
	strcat (goodfile, ".fsxgood");
	fsxgoodfd = open(goodfile, O_RDWR|O_CREAT|O_TRUNC, 0666);
	if (fsxgoodfd < 0) {
		prterr(goodfile);
		exit(92);
	}
	strncat(logfile, fname, 256);
	strcat (logfile, ".fsxlog");
	fsxlogf = fopen(logfile, "w");
	if (fsxlogf == NULL) {
		prterr(logfile);
		exit(93);
	}
	if (lite) {
		off_t ret;
		file_size = maxfilelen = lseek(fd, (off_t)0, SEEK_END);
		if (file_size == (off_t)-1) {
			prterr(fname);
			warn("main: lseek eof");
			exit(94);
		}
		ret = lseek(fd, (off_t)0, SEEK_SET);
		if (ret == (off_t)-1) {
			prterr(fname);
			warn("main: lseek 0");
			exit(95);
		}
	}
	original_buf = (char *) malloc(maxfilelen);
	for (i = 0; i < maxfilelen; i++)
		original_buf[i] = random() % 256;
	good_buf = (char *) malloc(maxfilelen);
	memset(good_buf, '\0', maxfilelen);
	temp_buf = (char *) malloc(maxoplen);
	memset(temp_buf, '\0', maxoplen);
	if (lite) {	/* zero entire existing file */
		ssize_t written;

		written = write(fd, good_buf, (size_t)maxfilelen);
		if (written != maxfilelen) {
			if (written == -1) {
				prterr(fname);
				warn("main: error on write");
			} else
				warn("main: short write, 0x%x bytes instead of 0x%x\n",
				     (unsigned)written, maxfilelen);
			exit(98);
		}
	} else 
		check_trunc_hack();

	while (numops == -1 || numops--)
		test();

	if (close(fd)) {
		prterr("close");
		report_failure(99);
	}
	prt("All operations completed A-OK!\n");

	exit(0);
	return 0;
}
// Initialize the random number generator.
void initRandom(){
  FAILIF(NULL == initstate(2, rngState, 256));
}
Example #23
0
/*------------------------------------------------------------------------------
  Generate random az, el positions within mask defined by poly.
  The results are written to out_filename.

   Input: out_filename = name of file to write to;
			"" or "-" means write to standard output.
	  fmt = pointer to format structure.
	  npoly = number of polygons in poly array.
	  npolysmax = maximum number of polygons in poly array.
	  poly = array of pointers to polygons.
	  mtol = initial tolerance angle for multiple intersections.
  Return value: number of random points generated,
		or -1 if error occurred.
*/
int ransack(char *out_filename, format *fmt, int npoly, int npolysmax, polygon *poly[/*npolysmax*/])
{
/* number of extra caps to allocate to polygon, to allow for expansion */
#define DNP			4
/* length of state vector for random number generator */
#define STATELEN		256
    static char state[STATELEN], stateo[STATELEN];
#define AZEL_STR_LEN		32
    char output[] = "output";
    char az_str[AZEL_STR_LEN], el_str[AZEL_STR_LEN];
    int dnp, dnwl, i, idwidth, ier, in, inull, ip, ipmin, ipoly, iprune, irandom, lassoed, np, nwl, tries, verb, width, k;
    long long idmin,idmax;
    int *dlasso=0x0, *lasso=0x0;
    long double area, cmmin, cmi, phi, rpoly, si, tol, w, wcum, x, y, z;
    long double *wpoly;
    vec rp, xi, yi;
    azel v;
    char *out_fn;
    FILE *outfile;

    /* open out_filename for writing */
    if (!out_filename || strcmp(out_filename, "-") == 0) {
	outfile = stdout;
	out_fn = output;
    } else {
	outfile = fopen(out_filename, "w");
	if (!outfile) {
	    fprintf(stderr, "ransack: cannot open %s for writing\n", out_filename);
	    goto error;
	}
	out_fn = out_filename;
    }

    /* advise angular units */
    if (fmt->outunit != fmt->inunit) {
	msg("units of output az, el angles will be ");
	switch (fmt->outunit) {
#include "angunit.h"
	}
	msg("\n");
    }

    /* initialize random number generator used by ransack() */
    initstate(seed, state, STATELEN);
    /* initialize random number generator used by ikrand() */
    initstate(seed, stateo, STATELEN);

    /* prune polygons, discarding those with zero weight * area */
    msg("pruning %d polygons ...\n", npoly);
    ier = 0;
    inull = 0;
    np = 0;
    for (ipoly = 0; ipoly < npoly; ipoly++) {
	/* zero weight polygon */
	if (poly[ipoly]->weight == 0.) {
            inull++;
	    free_poly(poly[ipoly]);
	    poly[ipoly] = 0x0;
	} else {
	/* prune polygon */
	    iprune = prune_poly(poly[ipoly], mtol);
	    /* error */
	    if (iprune == -1) {
		ier++;
		free_poly(poly[ipoly]);
		poly[ipoly] = 0x0;
		fprintf(stderr, "ransack: failed to prune polygon %d; discard it\n", ipoly);
		/* goto error; */
	    /* zero area polygon */
	    } else if (iprune >= 2) {
		inull++;
		free_poly(poly[ipoly]);
		poly[ipoly] = 0x0;
	    } else {
		np++;
	    }
	}
    }
   /*copy down non-null polygons*/
    k=0;
    for(ipoly = 0; ipoly < npoly; ipoly++){
      if(poly[ipoly]){
	poly[k++]=poly[ipoly];
      }
    }
    /*after copying non-null polygons, k should be equal to np */
    if(k!=np){
      fprintf(stderr, "ransack: should be left with %d non-null polygons, but actually have %d\n",np,k);
    }

    /*nullify the rest of the array, but don't free, since pointers have been copied above*/
    for(ipoly=np; ipoly < npoly; ipoly++){
      poly[ipoly]=0x0;
    }

    if (ier > 0) {
	msg("discarding %d unprunable polygons\n", ier);
    }
    if (inull > 0) {
	msg("discarding %d polygons with zero weight * area\n", inull);
    }
    /* number of polygons with finite weight * area */
    npoly = np;

    /* no polygons */
    if (npoly == 0) {
	fprintf(stderr, "ransack: no polygons to generate random points inside!\n");
	goto error;
    }

    /* pre-lasso polygons if there are many random points */
    if (nrandom >= npoly) {
	msg("lassoing %d polygons ...\n", npoly);

	/* lasso each polygon */
	np = npoly;
	for (ipoly = 0; ipoly < npoly; ipoly++) {
	    ier = lasso_poly(&poly[ipoly], npolysmax - np, &poly[np], mtol, &dnp);
	    if (ier == -1) {
		fprintf(stderr, "ransack: UHOH at polygon %lld; continuing ...\n", poly[ipoly]->id);
	    }

	    /* lassoed polygons are an improvement over original polygon */
	    if (dnp > 0) {
		/* check whether exceeded maximum number of polygons */
		if (np + dnp > npolysmax) {
		    fprintf(stderr, "ransack: total number of polygons exceeded maximum %d\n", npolysmax);
		    fprintf(stderr, "if you need more space, enlarge NPOLYSMAX in defines.h, and recompile\n");
		    goto error;
		}

		/* decrement dnp by 1 */
		dnp--;

		/* increment number of polygons */
		np += dnp;

		/* move last polygon part into poly[ipoly] */
		free_poly(poly[ipoly]);
		poly[ipoly] = poly[np];
		poly[np] = 0x0;
	    }
	}

	/* revised number of polygons */
	npoly = np;

	/* flag that all polygons have been lassoed */
	lassoed = 1;

    /* two few random points to make it worth pre-lassoing */
    } else {
	/* flag that all polygons have not been lassoed */
	lassoed = 0;

    }

    /* allocate memory for wpoly array */
    nwl = npoly;
    wpoly = (long double *) malloc(sizeof(long double) * nwl);
    if (!wpoly) {
        fprintf(stderr, "ransack: failed to allocate memory for %d long doubles\n", nwl);
        goto error;
    }
    if (!lassoed) {
	/* allocate memory for lasso and dlasso arrays */
	lasso = (int *) malloc(sizeof(int) * nwl);
	if (!lasso) {
	    fprintf(stderr, "ransack: failed to allocate memory for %d ints\n", nwl);
	    goto error;
	}
	dlasso = (int *) malloc(sizeof(int) * nwl);
	if (!dlasso) {
	    fprintf(stderr, "ransack: failed to allocate memory for %d ints\n", nwl);
	    goto error;
	}

	/* initialize dlasso array to zero */
	for (ipoly = 0; ipoly < nwl; ipoly++) dlasso[ipoly] = 0;
    }

    /* largest width of polygon id number */
    idmin = 0;
    idmax = 0;
    for (ipoly = 0; ipoly < npoly; ipoly++) {
	if (poly[ipoly]->id < idmin) idmin = poly[ipoly]->id;
	if (poly[ipoly]->id > idmax) idmax = poly[ipoly]->id;
    }
    idmin = ((idmin < 0)? floorl(log10l((long double)-idmin)) + 2 : 1);
    idmax = ((idmax > 0)? floorl(log10l((long double)idmax)) + 1 : 1);
    idwidth = ((idmin > idmax)? idmin : idmax);

    /* write header */
    wrangle(0., fmt->outunit, fmt->outprecision, AZEL_STR_LEN, az_str);
    width = strlen(az_str);
    if (fmt->outunit == 'h') {
	sprintf(az_str, "az(hms)");
	sprintf(el_str, "el(dms)");
    } else {
	sprintf(az_str, "az(%c)", fmt->outunit);
	sprintf(el_str, "el(%c)", fmt->outunit);
    }
    fprintf(outfile, "%*s\t%*s\t%*s\n", width, az_str, width, el_str, idwidth, "id");

    /* accept error messages from garea */
    /* unprunable polygons were already discarded, so garea should give no errors */
    verb = 1;

    /* cumulative area times weight of polygons */
    w = 0.;
    for (ipoly = 0; ipoly < npoly; ipoly++) {
	/* skip null polygons */
	if (poly[ipoly]) {
	    /* area of polygon */
	    tol = mtol;
	    ier = garea(poly[ipoly], &tol, verb, &area);
	    if (ier) goto error;
	    /* accumulate weight times area */
	    w += poly[ipoly]->weight * area;
	}
	wpoly[ipoly] = w;
    }
    wcum = w;

    /* random points */
    if (strcmp(out_fn, output) != 0) {
	msg("generating %d random points from seed %u in %d polygons ...\n", nrandom, seed, npoly);
    }
    for (irandom = 0; irandom < nrandom; irandom++) {

	/* random number in interval [0, 1) wcum */
	setstate(state);
	rpoly = drandom() * wcum;
	setstate(stateo);

	/* which polygon to put random point in */
	ipoly = search(npoly, wpoly, rpoly);

	/* guard against roundoff */
	if (ipoly >= npoly) {
	    fprintf(stderr, "ransack: %d should be < %d (i.e. %.15Lg < %.15Lg)\n", ipoly, npoly, rpoly, wpoly[npoly - 1]);
	    ipoly = npoly - 1;
	}

	/* all polygons have not been lassoed */
	if (!lassoed) {

	    /* polygon has not yet been lassoed */
	    if  (dlasso[ipoly] == 0) {

		/* lasso polygon */
		ier = lasso_poly(&poly[ipoly], npolysmax - np, &poly[np], mtol, &dnp);
		if (ier == -1) {
		    fprintf(stderr, "ransack: UHOH at polygon %lld; continuing ...\n", poly[ipoly]->id);
		}

		/* go with original polygon */
		if (dnp == 0) {
		    /* lasso, dlasso */
		    lasso[ipoly] = ipoly;
		    dlasso[ipoly] = 1;

		/* lassoed polygons are an improvement over original */
		} else {
		    /* check whether exceeded maximum number of polygons */
		    if (np + dnp > npolysmax) {
			fprintf(stderr, "ransack: total number of polygons exceeded maximum %d\n", npolysmax);
			fprintf(stderr, "if you need more space, enlarge NPOLYSMAX in defines.h, and recompile\n");
			goto error;
		    }

		    /* just one lassoed polygon */
		    if (dnp == 1) {
			/* move last polygon part into poly[ipoly] */
			free_poly(poly[ipoly]);
			poly[ipoly] = poly[np];
			poly[np] = 0x0;

			/* lasso, dlasso */
			lasso[ipoly] = ipoly;
			dlasso[ipoly] = 1;

		    /* more than one lassoed polygon */
		    } else {
			/* enlarge memory for wpoly, lasso, and dlasso arrays */
			if (np + dnp > nwl) {
			    dnwl = dnp + 1024;
			    wpoly = (long double *) realloc(wpoly, sizeof(long double) * (nwl + dnwl));
			    if (!wpoly) {
				fprintf(stderr, "ransack: failed to reallocate memory for %d long doubles\n", nwl + dnwl);
				goto error;
			    }
			    lasso = (int *) realloc(lasso, sizeof(int) * (nwl + dnwl));
			    if (!lasso) {
				fprintf(stderr, "ransack: failed to reallocate memory for %d ints\n", nwl + dnwl);
				goto error;
			    }
			    dlasso = (int *) realloc(dlasso, sizeof(int) * (nwl + dnwl));
			    if (!dlasso) {
				fprintf(stderr, "ransack: failed to reallocate memory for %d ints\n", nwl + dnwl);
				goto error;
			    }

			    /* initialize new part of lasso and dlasso arrays to inconsistent values */
			    for (ipoly = nwl; ipoly < nwl + dnwl; ipoly++) lasso[ipoly] = 1;
			    for (ipoly = nwl; ipoly < nwl + dnwl; ipoly++) dlasso[ipoly] = 0;

			    /* revised size of wpoly, lasso, and dlasso arrays */
			    nwl += dnwl;
			}

			/* lasso, dlasso */
			lasso[ipoly] = np;
			dlasso[ipoly] = dnp;

			/* cumulative weight times area of lassoed polygons */
			w = (ipoly == 0)? 0. : wpoly[ipoly-1];
			for (ip = np; ip < np + dnp; ip++) {
			    /* area of polygon */
			    tol = mtol;
			    ier = garea(poly[ip], &tol, verb, &area);
			    if (ier) goto error;
			    /* accumulate area times weight */
			    w += poly[ip]->weight * area;
			    wpoly[ip] = w;
			}

			/* increment number of polygons */
			np += dnp;
		    }

		}

	    }

	    /* polygon was partitioned into at least two */
	    if (dlasso[ipoly] >= 2) {
		/* which polygon to put random point in */
		ip = search(dlasso[ipoly], &wpoly[lasso[ipoly]], rpoly);

		/* guard against roundoff */
		if (ip >= lasso[ipoly] + dlasso[ipoly]) {
		    fprintf(stderr, "ransack: %d should be < %d (i.e. %.15Lg < %.15Lg)\n", ip, lasso[ipoly] + dlasso[ipoly], rpoly, wpoly[lasso[ipoly] + dlasso[ipoly] - 1]);
		    ip = lasso[ipoly] + dlasso[ipoly] - 1;
		}

		/* revised polygon number to put random point in */
		ipoly = ip;
	    }
	}

	/* smallest cap of polygon */
	cmminf(poly[ipoly], &ipmin, &cmmin);

	/* random point within polygon */
	tries = 0;
	do {
	    tries++;
	    /* random point within smallest cap */
	    setstate(state);
	    phi = TWOPI * drandom();
	    cmi = cmmin * drandom();
	    setstate(stateo);
	    /* coordinates of random point in cap frame */
	    si=sqrtl(cmi * (2. - cmi));
	    x = si * cosl(phi);
	    y = si * sinl(phi);
	    z = 1. - cmi;
	    /* polygon has caps */
	    if (poly[ipoly]->np > 0) {
		if (poly[ipoly]->cm[ipmin] < 0.) z = -z;
		/* Cartesian axes with z-axis along cap axis */
		gaxisi_(poly[ipoly]->rp[ipmin], xi, yi);
		/* coordinates of random point */
		for (i = 0; i < 3; i++) rp[i] = x * xi[i] + y * yi[i] + z * poly[ipoly]->rp[ipmin][i];
		/* whether random point is inside polygon */
		in = gptin(poly[ipoly], rp);
	    /* polygon has no caps, so is the whole sphere */
	    } else {
		rp[0] = x;
		rp[1] = y;
		rp[2] = z;
		in = 1;
	    }
	} while (!in);

	/* convert unit vector to az, el */
	rp_to_azel(rp, &v);
	v.az -= floorl(v.az / TWOPI) * TWOPI;

	/* convert az and el from radians to output units */
	scale_azel(&v, 'r', fmt->outunit);

	/* write result */
	wrangle(v.az, fmt->outunit, fmt->outprecision, AZEL_STR_LEN, az_str);
	wrangle(v.el, fmt->outunit, fmt->outprecision, AZEL_STR_LEN, el_str);
	fprintf(outfile, "%s\t%s\t%*lld\n", az_str, el_str, idwidth, poly[ipoly]->id);
	/* fprintf(outfile, "%s %s %d %d %d %Lg %Lg %Lg %Lg %d %d\n", az_str, el_str, irandom, ipoly, tries, wcum, rpoly / wcum, area, TWOPI * cmmin / area, ipmin, poly[ipoly]->np); */

    }

    /* advise */
    if (outfile != stdout) {
	msg("ransack: %d random positions written to %s\n", nrandom, out_fn);
    }

    return(nrandom);

    /* error returns */
    error:
    return(-1);
}
void	Exp(const char* dir, const char* name, int strong, int trial, bool savevid)
{
	bool success=true; 
	randinitalize(trial);

	string dataDir= "E://miltracker//" + string(dir);
	if( dataDir[dataDir.length()-2] != '//' ) dataDir+="//";
	dataDir += (string(name) + "//");

	Matrixf frameb, initstate;
	vector<Matrixu> vid;
	
	// read in frames and ground truth
	success=frameb.DLMRead((dataDir + name + "_frames.txt").c_str());
	if( !success ) abortError(__LINE__,__FILE__,"Error: frames file not found.");
	success=initstate.DLMRead((dataDir + name + "_gt.txt").c_str());
	if( !success ) abortError(__LINE__,__FILE__,"Error: gt file not found.");

	// TRACK

	vid.clear();
	vid = Matrixu::LoadVideo((dataDir+"imgs/").c_str(),"img", "png", (int)frameb(0), (int)frameb(1), 5, false);
	SimpleTracker tr;
	SimpleTrackerParams		trparams;
	vector<Matrixu>			saveseq;
	string paramname = "";
	

	////////////////////////////////////////////////////////////////////////////////////////////
	// PARAMETERS	

	ClfStrongParams			*clfparams;
	
	// strong model
	switch( strong ){
		case 1:		// MILTrack
			clfparams = new ClfMilBoostParams();
			((ClfMilBoostParams*)clfparams)->_numSel		= 50;
			((ClfMilBoostParams*)clfparams)->_numFeat		= 250;
			paramname += "_MIL";
			trparams._posradtrain							= 4.0f;
			trparams._negnumtrain							= 65;
			((ClfMilBoostParams*)clfparams)->ifPF = false;
			break;
		case 2:		// OBA1
			clfparams = new ClfAdaBoostParams();
			((ClfAdaBoostParams*)clfparams)->_numSel		= 50;
			((ClfAdaBoostParams*)clfparams)->_numFeat		= 250;
			paramname += "_OAB1";
			trparams._posradtrain							= 1.0f;
			trparams._negnumtrain							= 65;
			break;
		case 3:		// OBA5
			clfparams = new ClfAdaBoostParams();
			((ClfAdaBoostParams*)clfparams)->_numSel		= 50;
			((ClfAdaBoostParams*)clfparams)->_numFeat		= 250;
			paramname += "_OAB5";
			trparams._posradtrain							= 4.0f;
			trparams._negnumtrain							= 65;
			break;
		case 4:		// PFMIL
		clfparams = new ClfMilBoostParams();
		((ClfMilBoostParams*)clfparams)->_numSel		= 50;
		((ClfMilBoostParams*)clfparams)->_numFeat		= 250;
		paramname += "_PFMIL";
		trparams._posradtrain							= 4.0f;
		trparams._negnumtrain							= 65;
		((ClfMilBoostParams*)clfparams)->ifPF = true;
		break;

		default:
			abortError(__LINE__,__FILE__,"Error: invalid classifier choice.");
	}

	// feature parameters
	FtrParams *ftrparams;
	HaarFtrParams haarparams;
	ftrparams = &haarparams;

	clfparams->_ftrParams	= ftrparams;

	// tracking parameters
	trparams._init_negnumtrain = 65;
	trparams._init_postrainrad = 3.0f;
	trparams._initstate[0]	= initstate(0,0);
	trparams._initstate[1]	= initstate(0,1);
	trparams._initstate[2]	= initstate(0,2);
	trparams._initstate[3]	= initstate(0,3);
	trparams._srchwinsz		= 25;
	trparams._negsamplestrat = 1;
	trparams._initWithFace	= false;

	trparams._debugv		= false;
	trparams._disp			= false; // set this to true if you want to see video output (though it slows things down)
	trparams._vidsave		= savevid? dataDir + name + paramname + "_TR" + int2str(trial,3) + ".avi" : "";
	trparams._trsave		= dataDir + name + paramname + "_TR" + int2str(trial,3) + "_c.txt";

	////////////////////////////////////////////////////////////////////////////////////////////
	// TRACK

	
	cout << "\n===============================================\nTRACKING: " << name + paramname + "_TR" + int2str(trial,3) << endl;
	cout <<   "-----------------------------------------------\n";
    
	
	//CvCapture* pCapture = cvCaptureFromFile("1.avi");

	tr.track_frames(vid, trparams, clfparams);
	cout << endl << endl;

	delete clfparams;
	
}
Example #25
0
/**
 * The main() function accepts two command-line arguments: a seed value and the size of the random array to generate.
 *  The seed value is used by the random number generator.  If you want to test with the same randomly generated array,
 *  you should use the same seed value from run to run.  To test different arrays, use different seed values.
 *   This will be useful when testing your parallel versions for correctness.
 *   For example you can invoke findminmax_seq as follows:
 *
 *   $ findminmax_seq 1 10000 1

This will use a seed value of 1 and generate an array of size 10000 with 1 process.
 *
 */
int main(int argc, char **argv)
{
    int *array;
    int arraysize = 0;
    int seed;
    int nprocs=1;

    /**
     * How much each process sorts and how much extra is left over that we should give to the last process
     */
    int *pipes;
    pid_t *sub_proc;
    int proc_share=0;
    int proc_leftover=0;
   	int offset=0;
   	int launched=0;
   	int * proc_results;

    char randomstate[8];
    struct results r;
    int i;

    /* process command line arguments */
    if (argc != 4) {
        printf("usage: ./findminmax <seed> <arraysize> <nprocs>\n");
        return 1;
    }

    seed = atoi(argv[1]);
    arraysize = atoi(argv[2]);
    nprocs = atoi(argv[3]);

    proc_share=arraysize/nprocs;
    proc_leftover=arraysize%nprocs;
    proc_results = (int *) malloc(sizeof(int) * nprocs*2);

    /* allocate array and populate with random values */
    array = (int *) malloc(sizeof(int) * arraysize);
    
    initstate(seed, randomstate, 8);

    for (i = 0; i < arraysize; i++) {
        array[i] = random();
    }
    
    /* begin computation */

    pipes=(int *) malloc(sizeof(int)*nprocs*2);
    sub_proc=(pid_t *) malloc(sizeof(pid_t)*nprocs);

   	mtf_measure_begin();
   	for(i=0 ; i < nprocs;i++) {
   		pipe(&pipes[i*2]);
   		int size=proc_share+(proc_leftover > i ? 1 : 0);
   		pid_t tmp_pid=fork();
   		if (!tmp_pid)  {
   		    int write_pipe=pipes[i*2+1];

   		    FILE *pipe=fdopen(write_pipe,"wb");
   			r = find_min_and_max(&array[offset], size);
   		    printf("min = %d, max = %d size->%d\n", r.min, r.max,size);
   			fwrite(&r,sizeof(struct results),1,pipe);
   			fclose(pipe);
   			return 0;
   		} else {
   			launched++;
   			sub_proc[i]=tmp_pid;
   		}
   	    offset+=size;
    }
   	while(launched>0) {
   		for(i=0 ; i < nprocs;i++) {
   			struct results tmp_result;
   			int status=0;
   			int pid=0;
   			if (sub_proc[i]==0) { continue; }
   			pid=waitpid(sub_proc[i],&status,0);
   			if (pid) {
   	   		    int read_pipe=pipes[i*2];
   	   		    FILE *pipe=fdopen(read_pipe,"rb");
   				launched--;
   				sub_proc[i]=0;
   	   			fread(&tmp_result,sizeof(struct results),1,pipe);
   	   		    printf("parent -> min = %d, max = %d\n", tmp_result.min, tmp_result.max);
   	   			fclose(pipe);
   	   			proc_results[i*2]=tmp_result.max;
   	   			proc_results[i*2+1]=tmp_result.min;
   			}
   		}
   	}
	r = find_min_and_max(proc_results, nprocs*2);


    mtf_measure_end();
    
    printf("Execution time: ");
    mtf_measure_print_seconds(1);

    printf("min = %d, max = %d\n", r.min, r.max);

	r = find_min_and_max(array, arraysize);

	printf("check -> min = %d, max = %d\n", r.min, r.max);

    return 0;
}
Example #26
0
int main(int argc, char **argv) {
    int *array;
    int *subarray;
    int arraysize = 0;
    int subarrsize = 0;
    int seed;
    int processorsize=0;
    char randomstate[8];
    struct results subr;
    char file[processorsize];
    int i;
    int status;
    pid_t pid;
    FILE *fw;
    FILE *fr;


    /* process command line arguments */
    if (argc != 4) {
        printf("usage: ./findminmax <seed> <arraysize> <nprocs>\n");
        return 1;
    }

    seed = atoi(argv[1]);
    arraysize = atoi(argv[2]);
    processorsize = atoi(argv[3]);
    subarrsize = arraysize / processorsize;

    /* allocate array and populate with random values */
    array = (int *) malloc(sizeof(int) * arraysize);
    subarray = (int *) malloc(sizeof(int) * subarrsize);

    initstate(seed, randomstate, 8);

    for (i = 0; i < arraysize; i++) {
        array[i] = random();
    }


    /* parallel Min and Max Verison 1 (results communicated via files) */
    mtf_measure_begin();
    for ( i = 0; i < processorsize; i++) {
        pid = fork();
        if (pid == -1) {
            printf("Error in generating processors!");
            exit(1);
        }
        else if (pid == 0) {
            subarray = array + i*subarrsize;
            subr = find_min_and_max(subarray, subarrsize);

            sprintf(file,"text%d.txt",i);
            fw = fopen(file, "w");
            if (fw == NULL) {
                printf("Error opening file!\n");
                return 1;
            }
            fprintf(fw, "%d\n%d", subr.min, subr.max);
            fclose(fw);
            exit(0);
        }
    }

    for (i = 0; i < processorsize; i++) {
        wait(&status);
    }

    int tmpmin,tmpmax, min, max;
    for (i = 0; i < processorsize; i++) {
        sprintf(file,"text%d.txt",i);
        fr = fopen(file, "r");
        if (fr == NULL) {
            printf("Error in opening file!\n");
            return 1;
        }

        while (!feof(fr)) {
            fscanf(fr, "%d\n%d", &tmpmin, &tmpmax);
            if (i == 0 ) {
                min = tmpmin;
                max = tmpmax;
            }
            else {
                if (tmpmin < min) {
                    min = tmpmin;
                }
                else if (tmpmax > max) {
                    max = tmpmax;
                }
            }
        }
        fclose(fr);
        remove(file);
    }


    free(array);
    mtf_measure_end();

    printf("Execution time: ");
    mtf_measure_print_seconds(1);

    printf("min = %d, max = %d\n", min, max);

    return 0;
}
Example #27
0
/* Lower level call.

   Create a temporary file with the name according to the pattern FILENAME.
   FILENAME must end with any amount of Xs, optionally followed by
   SUFLEN other characters.

   If ISDIR is not 0, create a directory (privileges 0700), otherwise
   create a file (privileges 0600).

   On success, return 0.  If pfd is not NULL (and ISDIR is 0), open the
   created file and store the descriptor in *PFD.  Return actual file
   name in FILENAME.

   On error, return error code.
*/   
int
mu_create_temp_file (char *filename, size_t suflen, int *pfd, int isdir)
{
  int rc;
  size_t len;
  char *carrybuf;
  char *p, *cp, *start, *end;
  struct stat st;
  static int first_call;
  static char randstate[256];
  static const unsigned char alphabet[] =
    "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";

  if (!first_call)
    {
      /* Initialize random number generator */
      struct timeval tv;
      gettimeofday (&tv, NULL);
      initstate (((unsigned long) tv.tv_usec << 16) ^ tv.tv_sec,
		 randstate, sizeof (randstate));
      first_call = 1;
    }
  setstate (randstate);
  
  /* Start with the last filename character before suffix */
  end = filename + strlen (filename) - suflen - 1;
  /* Fill X's with random characters */
  for (p = end; p >= filename && *p == 'X'; p--)
    *p = alphabet[random () % (sizeof (alphabet) - 1)];
  len = end - p;
  if (len == 0)
    return EINVAL;
  start = p + 1;

  carrybuf = malloc (len);
  if (!carrybuf)
    return ENOMEM;

  /* Fill in the carry buffer */
  memcpy (carrybuf, start, len);

  for (;;)
    {
      if (isdir)
	{
	  if (mkdir (filename, 0700) == 0)
	    {
	      rc = 0;
	      break;
	    }
	}
      else if (pfd)
	{
	  if ((*pfd = open (filename, O_CREAT|O_EXCL|O_RDWR, 0600)) >= 0)
	    {
	      rc = 0;
	      break;
	    }
	}
      else if (lstat (filename, &st) && errno == ENOENT)
	{
	  rc = 0;
	  break;
	}
      
      if (errno != EEXIST)
	{
	  rc = errno;
	  break;
	}

      for (p = start, cp = carrybuf;; p++, cp++)
	{
	  char *q;
	  
	  if (p == end)
	    /* All permutation exhausted */
	    return EEXIST;
	  q = strchr ((char*)alphabet, *p);
	  if (!q)
	    abort (); /* should not happen */
	  *p = (q[1] == 0) ? alphabet[0] : q[1];
	  if (*p != *cp)
	    break;
	}
    }
  free (carrybuf);
  return rc;
}
Example #28
0
/*
 * Creates 3 hashmaps with different data types and inserts elements which all have to be 
 * found afterwards.
 * The hashmap capacity is intentionally chosen too low, in order to force storage in linked lists.
 */
int main(int argc, char *argv[]) {
  typedef struct teststruct_t {
    int a;
    char b;
  } teststruct_t;

#define start_cap_int (uint)71
#define start_cap_char (uint)91
#define start_cap_struct (uint)113
#define nof_items_int (uint)(2*start_cap_int)
#define nof_items_char (uint)(2*start_cap_char)
#define nof_items_struct (uint)(2*start_cap_struct)
  
  char state[200];
  char intkeystrings[nof_items_int][_max_keylen];
  int intdata[nof_items_int];
  char charkeystrings[nof_items_char][_max_keylen];
  char chardata[nof_items_char];
  char structkeystrings[nof_items_struct][_max_keylen];
  teststruct_t structdata[nof_items_struct];
  rh_hashmap_instance hashmap_int, hashmap_char, hashmap_struct;
  rh_hashmap_element element;
  uint i;  

  initstate(time(NULL), state, 200);

  rh_hashmap_constructor(&hashmap_int, start_cap_int, NULL);
  rh_hashmap_constructor(&hashmap_char, start_cap_char, NULL);
  rh_hashmap_constructor(&hashmap_struct, start_cap_struct, NULL);

  printf("\tReached: population of int datatype hashmap insertion\n");
  for (i = 0; i < nof_items_int; i++) {
    _generate_key(intkeystrings[i]);
    intdata[i] = (int)random();

	element.data =  &intdata[i];
    rh_hashmap_insert(&hashmap_int, &element, intkeystrings[i]);
  }  

  for (i = 0; i < nof_items_int; i++) {
    int *testptr;

    testptr = (int*)rh_hashmap_lookup(&hashmap_int, intkeystrings[i]);
    assert(intdata[i] == *testptr);
    printf("\tVerified: lookup of item %s.\n", intkeystrings[i]);
  } /* for int items to look up */
  rh_hashmap_destructor(&hashmap_int);





  printf("\tReached: population of char datatype hashmap insertion\n");
  for (i = 0; i < nof_items_char; i++) {
    _generate_key(charkeystrings[i]);
    chardata[i] = (char)(random()%('z' - 'a') + 'a');

	element.data = &chardata[i];
    rh_hashmap_insert(&hashmap_char, &element, charkeystrings[i]);
  }  

  for (i = 0; i < nof_items_char; i++) {
    char *testptr;

    testptr = (char*)rh_hashmap_lookup(&hashmap_char, charkeystrings[i]);
    assert(chardata[i] == *testptr);
    printf("\tVerified: lookup of char item %s.\n", charkeystrings[i]);
  } /* for char items to look up */
  rh_hashmap_destructor(&hashmap_char);




  printf("\tReached: population of struct datatype hashmap insertion\n");
  for (i = 0; i < nof_items_struct; i++) {
    _generate_key(structkeystrings[i]);
    structdata[i].a = (char)(random()%('z' - 'a') + 'a');
    structdata[i].b = (int)random();

	element.data =  &structdata[i];
    rh_hashmap_insert(&hashmap_struct, &element, structkeystrings[i]);
  }  

  for (i = 0; i < nof_items_struct; i++) {
    teststruct_t *testptr;

    testptr = (teststruct_t*)rh_hashmap_lookup(&hashmap_struct, structkeystrings[i]);
    assert(structdata[i].a == testptr->a && structdata[i].b == testptr->b);
    printf("\tVerified: lookup of struct item %s.\n", structkeystrings[i]);
  } /* for char items to look up */
  rh_hashmap_destructor(&hashmap_struct);
  
  return 0;
} /* main */
Example #29
0
int main(int argc, char **argv)
{
    int *array;
    int arraysize = 0;
    int seed;
    char randomstate[8];
    struct results r;
    int i, j, fd, x, y;
    int nprocs;
    int chunk;

    
    /* process command line arguments */
    if (argc != 4) {
        printf("usage: ./findminmax <seed> <arraysize> <nprocs>\n");
        return 1;
    }
    
    seed = atoi(argv[1]);
    arraysize = atoi(argv[2]);
    nprocs = atoi(argv[3]);
    
    /* allocate array and populate with random values */
    chunk = arraysize / nprocs;
    array = (int *) malloc(sizeof(int) * arraysize);
 
    
    initstate(seed, randomstate, 8);
    
    
    for (i = 0; i < arraysize; i++) {
        array[i] = random();
    }
    
    /* begin computation */
    
    mtf_measure_begin();
    
    int pid;

    for(j = 0; j < nprocs; j++) {
        pid = fork();
        
        char *file;
        file = malloc(sizeof(char) * 1);
        
        sprintf(file, "%d", j);
        
        if ( (fd = open(file, O_CREAT | O_WRONLY, 0600)) < 0) {
            printf("Cannot open %s\n", file);
            exit(1);
        }
        
        
        if(pid < 0) {
            printf("Error in making child processes.");
            exit(0);
        } else if(pid == 0) { 
            r = find_min_and_max(array, chunk);
            write(fd, &r, sizeof(struct results));
            close(fd);
            exit(0);
                
            
        } else {
            array = array + chunk;
        
    }
        
    for(x = 0; x < nprocs; x++) {
        pid = wait(NULL);
    }
       
    for(y = 0; y < nprocs; y++) {
        if ((fd = open(file, O_RDONLY)) < 0) {
            printf("Cannot open %s\n", file);
            exit(1);
        }
        
        struct results vals;
        read(fd, &vals, sizeof(struct results));
        
        if (vals.min <= r.min){
            r.min = vals.min;
        }
    
        if (vals.max >= r.max){
            r.max = vals.max;
        }
    
        }
    
  }
    
    
    
    mtf_measure_end();
    
    printf("Execution time: ");
    mtf_measure_print_seconds(1);
    
    printf("min = %d, max = %d\n", r.min, r.max);
    close(fd);
    return 0;
}
Example #30
0
int main(int argc, char *argv[]){



# ifdef UNIX
 static char state[256];
 initstate(1997,state,256);
# else
  Exit_wait(1);
# endif

 Set_comment_char(';');

 StartTime();
 char *cfgfile="Params.dta";
 if(argc>1)cfgfile=argv[1];

 int no_remove=1;
 if(argc>2)if(strstr(argv[2],"new"))no_remove=0;

 Open_param_file(cfgfile);
 int nions,i;


 Read_param("Number of ions: %d",&nions);
 Read_param("Ionisation degree: %d",&i);
 ion_charge=i;

 double imass=1.;
 Set_stop(0);
 if(Read_param("Ion mass: %lf",&imass)){
   printf("Non-symmetric plasma specified!\n");
   non_symm=1;
 }

 char tmpstr[256];

 int sep_cm=0;
 if(Read_param("Center-of-mass for components: %s",tmpstr)){
   if(strstr(tmpstr,"separate")){
     printf("Plasma with separated center of masses specified!\n");
     sep_cm=1;
   }
 }



 Plasma *TheGas;  // allocation of the Gas
 double bdens, bTv;
 int bq;
 int bunch=Read_param("Bunch propagation: %lf, %lf, %d",&bdens,&bTv,&bq);
 if(bunch>0){
   printf("Bunch in plasma specified!\n");
   if(bunch!=3){
     msg_error("Invalid bunch specification!\n");
     exit(1);
   }
   bunch=1;
   bTv=sqrt(3*nions*i*bTv); // converting temperature to velocity
   TheGas=(Plasma *)new PlasmaBunch(bdens,bTv,bq,nions,i,imass);
 }
 else{
   TheGas=new Plasma(nions,i,imass);
   bunch=0;
 }
 Plasma &Gas=*TheGas;

 Gas.non_symm=non_symm;
 Gas.one_center=1-sep_cm;

 char dataname[50];
 Read_param("Data name: %s",dataname);
 strncpy(Gas.dataname,dataname,50);

 char ofile[256], pfile[256]="poten.dat";


 strcat(strcpy(pfile,dataname),".pot");

 Read_param("Output file: %s",ofile);
 if(strstr(ofile,"default")){
   strcpy(ofile,dataname);
   strcat(ofile,".eq");
 }

 Read_param("Log file: %s",logfile);
 if(strstr(logfile,"default")){
   strcpy(logfile,dataname);
   strcat(logfile,".log");
 }



 Parameter *p;
 int np=InitParameters(&p);


 double T,Gamma;

 potspec_t reader;
 reader.read_spec(cfgfile);
 Gas.potential=reader.potential;
 strncpy(Gas.charpot,reader.charpot,50);


 /*
 Read_param("Potential: %s",tmpstr);
 strncpy(Gas.charpot,tmpstr,50);
 if(strstr(tmpstr,"Kelbg"))Gas.potential=PotentialKELBG;
 else if(strstr(tmpstr,"Lennard-Johnes"))Gas.potential=PotentialJONES;
 else if(strstr(tmpstr,"Deutsch"))Gas.potential=PotentialDEUTSCH;
 else if(strstr(tmpstr,"Erf"))Gas.potential=PotentialERF;
 else if(strstr(tmpstr,"Cutoff")){
  if(!strcmp(tmpstr,"Cutoff1")){
    Gas.potential=PotentialCUT1;
  }
  else{
    Gas.potential=PotentialCUT;
    Read_param("Cutoff value*: %lf",&E_cut);
  }
 }
 else if(strstr(tmpstr,"ln")){
  Gas.potential=PotentialLN;
  Read_param("Cutoff value*: %lf",&E_cut);
 }
 else if(strstr(tmpstr,"table")){
  Gas.potential=PotentialTAB;
  Read_param("Potential table file: %s",tmpstr);
  Close_param_file();
  ReadPotential(tmpstr);
  Open_param_file(cfgfile);
 }
 else serror("Unknown potential type specified!\n");


 Read_param("Pauli part: %s",tmpstr);
 if(strstr(tmpstr,"n"))Pauli_part=0;


 double Lambda, Lambda_set;
 Read_param("R0: %s",tmpstr);
 if(strstr(tmpstr,"default"))Lambda_set=0.;
 else Lambda_set=atof(tmpstr);

 double Clam_ep=1.,Clam_ee=1;
 Read_param("e-e R0 coefficient: %lf",&Clam_ee);
 Read_param("e-p R0 coefficient: %lf",&Clam_ep);
 */

 int ask=0;
 Read_param("Dialog: %s",tmpstr);
 if(strstr(tmpstr,"y"))ask=1;

 auto_rf=0;
 Gf=10.;
 Read_param("Random force strength: %s",tmpstr);
 if(strstr(tmpstr,"auto"))auto_rf=1;
 else if(strstr(tmpstr,"fluct"))auto_rf=2;
 if(!sscanf(tmpstr,"%lf",&Gf) && auto_rf==0)serror("Can't read Random force strength\n");



 Read_param("Scale velocities: %s",tmpstr);
 if(strstr(tmpstr,"y"))scale_vel=1;

 Read_param("Delta: %lf",&delta);

 Read_param("Trajectory write interval: %ld",&wr_int);
 if(wr_int<=0)wr_int=-1;

 int new_rec=0;
 long wr_ions=0, wr_enseq=-1;
 Set_stop(0);
 if(Read_param("Ions write interval: %ld",&wr_ions)){
   new_rec=1;
   if(!Read_param("Electrons write sequence: %ld",&wr_enseq))wr_enseq=-1;
 }
 Set_stop(1);


 Read_param("Steps to check equillibrium: %ld",&chk_nsteps);
 Read_param("Steps with random force: %ld",&rf_nsteps);
 Read_param("Check steps with random force: %ld",&tst_nsteps);
 Read_param("Steps in equillibrium: %ld",&eq_nsteps);
 Read_param("Time step in equillibrium: %lf",&eq_dt);

 Read_param("Time step for random force: %lf",&rf_dt0);


 char trfile[256]="trajectory";

 int wr_tr=0;
 Set_stop(0);

 /*int pot_corr=0;
 if(Read_param("Potential correction: %s",tmpstr)){
   if(strstr(tmpstr,"y")){
     pot_corr=1;
     strcat(Gas.charpot," corr.");
   }                                       
 }*/


 if(Read_param("Total energy stability: %lf",&stab_acc))e_stab=1;


 if(Read_param("Positive cutoff: %lf",&E_negcut))neg_cut=1;
 else neg_cut=0;

 if(!Read_param("Random generator *:>",tmpstr))strcpy(tmpstr,"3");
 cList rndlist(tmpstr);

 int nrepeats=1;
 if(!Read_param("Repeats: %d",&nrepeats))nrepeats=1;


 char mdistrfile[256]="r-r.distrib";
 double rr_r0=0., rr_r1=-1.;
 if(Read_param("Write r-r distribution: %s",tmpstr)){
   if(strstr(tmpstr,"y")){
     write_distr=1;
     if(!Read_param("r-r file: %s",mdistrfile)||strstr(mdistrfile,"default")){
       strcpy(mdistrfile,"%s%d.rr");
     }
     if(Read_param("r-r range: %lf, %lf",&rr_r0,&rr_r1)!=2){
       rr_r0=0.;
       rr_r1=-1.;
     }
   }
 }


 if(Read_param("Soft step: %s",tmpstr)){
  if(strstr(tmpstr,"n"))soft_step=0;
 }

 if(Read_param("Soft random force: %s",tmpstr)){
  if(strstr(tmpstr,"y")){
    rf_sw_off=1;
    Set_stop(1);
    Read_param("Switch off steps: %ld",&sw_nsteps);
    Set_stop(0);
  }
  else rf_sw_off=0;
 }

 if(Read_param("Relative step: %s",tmpstr)){
  if(strstr(tmpstr,"y"))rel_step=1;
 }


 if(Read_param("Animation : %s",&tmpstr)){
   if(strstr(tmpstr,"y")){
      if(!Read_param("Film directory: %s",filmdir)||strstr(filmdir,"default")){
       strcpy(filmdir,"film/");
      }
   }
 }

 in_cs=-1.;
 Read_param("Initial cluster size: %lf",&in_cs);

 int restart=0,load_fried=0;
 int new_input=0;
 char inptrj[256];

 if(Read_param("Restart: %s",tmpstr)){
  if(strstr(tmpstr,"y")){
    restart=1;
    if(Read_param("Load Friedemann: %s",tmpstr)){
      if(strstr(tmpstr,"y"))load_fried=1;
    }
    if(Read_param("Input from: %s",inptrj))new_input=1;
  }

 }

 long wtype=0;
 if(Read_param("Trajectory file: %s",&trfile)){
  if(strstr(trfile,"default"))strcpy(trfile,"%s%d.r");



  Set_stop(1);
  wr_tr=1;

  Read_param("In output:>",tmpstr);
  if(strstr(tmpstr,"vel"))wtype|=VEL;
  if(strstr(tmpstr,"coord"))wtype|=COORD;
  if(strstr(tmpstr,"flow"))wtype|=FLOW;
  Set_stop(0);

 }
 else printf("Warning: no trajectory file\n");

 int mc_one=0;
 int mc_diff=0;
 int auto_adjust=1;
 double mc_inistep;

 int no_equilibr=0;
 Set_stop(1);
 if(Read_param("Equilibration procedure: %s",tmpstr)){
   if(strstr(tmpstr,"monte-carlo")){
     Set_stop(1);
     mc_equil=1;
     Read_param("One particle MC-step: %s",tmpstr);
     if(strstr(tmpstr,"y")){
       mc_one=1;
       // rf_dt0/=Gas.n;
     }
     Read_paramn(2,"MC step mode and value: %s %lf",tmpstr, &mc_inistep);
     if(strstr(tmpstr,"auto"))auto_adjust=1;
     else if(strstr(tmpstr,"stable"))auto_adjust=0;
     else serror("Unknown MC step mode.\n");
     Set_stop(0);
     mc_diff=0;
     if(Read_param("MC different temperatures: %s",tmpstr)){
       if(strstr(tmpstr,"y")){
	 if(mc_one)serror("Can use different MC temperatures\n"
			  "only in MC one-particle mode!\n");
	 mc_diff=1;
       }
     }
   }
   else{
     mc_equil=0;
     if(strstr(tmpstr,"off"))no_equilibr=1;
     else if(!strstr(tmpstr,"random-force")){
       serror("Unknown equilibration procedure: %s\n",tmpstr);
     }
   }
 }

 

 Set_stop(0);
 mc_calc=0;
 if(Read_param("Equilibrium calculation: %s",tmpstr)){
   if(strstr(tmpstr,"monte-carlo")){
     Set_stop(1);
     mc_calc=1;
     Read_param("One particle MC-step: %s",tmpstr);
     if(strstr(tmpstr,"y")){
       mc_one=1;
       // rf_dt0/=Gas.n;
     }
     Read_paramn(2,"MC step mode and value: %s %lf",tmpstr, &mc_inistep);
     if(strstr(tmpstr,"auto"))auto_adjust=1;
     else if(strstr(tmpstr,"stable"))auto_adjust=0;
     else serror("Unknown MC step mode.\n");
     Set_stop(0);
     mc_diff=0;
     if(Read_param("MC different temperatures: %s",tmpstr)){
       if(strstr(tmpstr,"y")){
	 if(mc_one)serror("Can use different MC temperatures\n"
			  "only in MC one-particle mode!\n");
	 mc_diff=1;
       }
     }
   }
 }

//# ifdef UNIX

 char out_dirs[250]="./",out_dirl[250]="./";
 if(Read_param("Data output directory: %s",out_dirs)){
   if(out_dirs[strlen(out_dirs)-1]!='/')strcat(out_dirs,"/");
   sprintf(tmpstr,out_dirs,dataname);
   strcpy(out_dirs,tmpstr);
# ifdef UNIX
   if(mkdir(out_dirs,S_IRWXU|S_IRGRP|S_IROTH)){
     if(errno!=EEXIST)serror("Can not create directory: %s.\n%s\n",
			     out_dirs,strerror(errno));
   }
   sprintf(tmpstr,"cp %s %s%s.cfg",cfgfile,out_dirs,dataname);
   //strcat(strcat(tmpstr,dataname),".cfg");
   if(system(tmpstr)==-1)
     printf("\nExec: %s\n",strerror(errno));
# else
   if(_mkdir(out_dirs)){
     if(errno!=EEXIST)serror("Can not create directory: %s.\n%s\n",
			     out_dirs,strerror(errno));
   }
   char cfgfilef[_MAX_PATH], out_dirsf[_MAX_PATH];
   _fullpath(cfgfilef, cfgfile, _MAX_PATH);
   _fullpath(out_dirsf, out_dirs, _MAX_PATH);
   sprintf(tmpstr,"copy %s %s%s.cfg",cfgfilef,out_dirsf,dataname);
   //strcat(strcat(tmpstr,dataname),".cfg");
   if(system(tmpstr)==-1)
     printf("\nExec: %s\n",strerror(errno));
# endif

   


   strcpy(ofile,strcat(strcpy(tmpstr,out_dirs),ofile));
   strcpy(mdistrfile,strcat(strcpy(tmpstr,out_dirs),mdistrfile));
   strcpy(sfile,strcat(strcpy(tmpstr,out_dirs),sfile));
   strcpy(pfile,strcat(strcpy(tmpstr,out_dirs),pfile));
   if(wr_film){
     strcpy(filmdir,strcat(strcpy(tmpstr,out_dirs),ofile));
# ifdef UNIX
     if(mkdir(filmdir,S_IRWXU|S_IRGRP|S_IROTH)){
# else
     if(_mkdir(filmdir)){
# endif
       if(errno!=EEXIST)serror("Can not create directory: %s.\n%s\n",
			       filmdir,strerror(errno) );
     }
     strcat(filmdir,dataname);
   }
 }
 if(Read_param("Process output directory: %s",out_dirl)){
   if(out_dirl[strlen(out_dirl)]!='/')strcat(out_dirl,"/");
   sprintf(tmpstr,out_dirl,dataname);
   strcpy(out_dirl,tmpstr);


# ifdef UNIX
   if(mkdir(out_dirl,S_IRWXU|S_IRGRP|S_IROTH)){
# else
   if(_mkdir(out_dirl)){
# endif 
     if(errno!=EEXIST)serror("Can not create directory: %s.\n%s\n",
			     out_dirl,strerror(errno));
   }


   strcpy(logfile,strcat(strcpy(tmpstr,out_dirl),logfile));
   strcpy(trfile,strcat(strcpy(tmpstr,out_dirl),trfile));
 }

//# endif  // UNIX

 int spwn_trj=0;

 if(Read_param("Spawn trajectories: %s",tmpstr)){
   if(strstr(tmpstr,"y")){
    spwn_trj=1;
    //Read_paramn(1,"Spawn frame: %d",&spwn_frame);
    no_test=1; // no RF test for equilibrartion
   }
 }

 Gas.stable_ions=0;
 if(Read_param("Stable ions: %s",tmpstr)){
   if(strstr(tmpstr,"y")){
    Gas.stable_ions=1;

   }
 }

 int repc_i=0;
 if(!Read_param("Repeat counter start: %d",&repc_i))repc_i=0;

 int irescale=0;
 if(Read_param("Ion velocity rescale: %s",tmpstr)){
  if(strstr(tmpstr,"y"))irescale=1;
  if(strstr(tmpstr,"reset"))irescale=2;
 }

 /*
 int limrescale=0;
 if(Read_param("Rescale on electron temperature reached: %lf  %ld",&limTe,&limstpe)==2){
  limrescale=1;
  limspec=0x2;
  limrescale_switch(0);
 } */

 int limrescale=0;
 int inc_mes=0;

 if(Read_param("Incremental measurement (T0,dT,mes_steps): %lf,%lf,%ld",&incT0,&incdT,&incStp)==3){
   inc_mes=1;
   fixT=incT0;
   limstpe=1;
   limstpi=1;
 }



 Set_stop(1);



 Gas.ini_Te=Gas.ini_Ti=1.;  // by default equal temperatures
 Read_param("Initial velocity distribution: %s",tmpstr);
 if(strstr(tmpstr,"maxwell"))in_distr=MAXWELL;
 else if(strstr(tmpstr,"max_polak"))in_distr=MAXWELL_P;
 else if(strstr(tmpstr,"zero")){
   if(mc_equil){
     in_distr=MAXWELL;
     printf("Warning: setting 'maxwell' initial vel. distribution for MC!\n");
   }
   else in_distr=ZEROVEL;
 }
 else if(strstr(tmpstr,"separate")){
   in_distr=SEPARATE;
   int &ndistr=Gas.idistr;
   int nr;
   char relstr[200];
   for(i=0;i<2;i++){
    if(i==0)nr=  Read_param("Electron velocity distribution: %s  %lf  %s",tmpstr,&Gas.ini_Te,relstr);
    else{
     nr= Read_param("Ion velocity distribution: %s  %lf %s",tmpstr,&Gas.ini_Ti,relstr);
     Gas.edistr=ndistr;
    }
    if(nr<2){
      serror("Can't read velocity distribution parameters!\n");
    }
    if(nr>=2){
      if(strstr(relstr,"abs")){
        if(i==0)Gas.rel_Te=0;
        else Gas.rel_Ti=0;
      }
    }

    if(strstr(tmpstr,"maxwell"))ndistr=MAXWELL;
    else if(strstr(tmpstr,"max_polak"))ndistr=MAXWELL_P;
    else if(strstr(tmpstr,"zero"))ndistr=ZEROVEL;
    else {
     printf("Warning: unknown distribution '%s', setting to 'zero'\n",tmpstr);
     ndistr=ZEROVEL;
    }
   }
 }
 else{
   printf("Warning: unknown distribution '%s', setting to 'zero'\n",tmpstr);
   in_distr=ZEROVEL;
 }

 

 Close_param_file();


 Statistics sT(&Gas.T),sEcoul(&Gas.Ecoul),sEpotent(&Gas.Epotent),sQuant(&Gas.Quant), sEtot(&Gas.Etot);
 Statistics sTi(&Gas.Ti),sTe(&Gas.Te);
 const int nstat=7;
 Statistics *stats[nstat]={&sT,&sEcoul,&sEpotent,&sQuant,&sEtot,&sTi,&sTe};

 SetTableform(GNU);
 if(no_remove){
   no_remove=CheckData(sfile,ofile,dataname,np,p,ask);
 }

 if(restart && !wr_tr && !new_input)serror("No trajectory file specified, cannot restart.\n");
 if(restart && new_input && wr_tr)
   if(!strcmp(trfile,inptrj))
     serror("Equal names for input and output trj-files.\n");


 FILE *f1;
 if(!no_remove || no_remove==2){
  if(!no_remove)f1=Err_fopen(ofile,"wt");
  else f1=Err_fopen(ofile,"at");
  BeginFrame(f1,dataname,np,p);
  fprintf(f1,"%9.9s %9.9s %9.9s %9.9s %9.9s %9.9s %9.9s %9.9s\n",
             "T","Ecoul","Epotent","Equant","dT","dEcoul","dEpotent","dEquant");
  fclose(f1);
 }

 double t=0;

 f1=fopen(logfile,"rt");
 if(f1){
   if(!restart && !no_remove){
     fclose(f1);
     remove(logfile);
   }
   else {// reading 'log' time
     fseek(f1,0,SEEK_END);
     long pos=ftell(f1)-4;
     do{
       fseek(f1,pos,SEEK_SET);
       if(fgetc(f1)=='\n'){
	        fscanf(f1,"%lf",&t);
         //printf("new t: %f\n",t);
	        break;
       }
       pos--;
     }while(pos>=0);
     fclose(f1);
   }
 }


 int ccount=CurrentCount(np,p);
 WriteStatus(!ccount,sfile,dataname,np,p);



 do{

   //Gamma=get_pc(p[0]);
   //T=get_pc(p[1]);



  char ctrfile[256];
  sprintf(ctrfile,trfile,dataname,ccount);
  char ss[100];
  sprintf(ss,"%s%d",dataname,ccount);
  sprintf(distrfile,mdistrfile,dataname,ccount);

  // StatusLine(str,np,p);
  //show_status(440,str);

  long i,n,m,nf=0;

  //Gas.adjustTG(T,Gamma);

  AdjustGas(Gas,p,np);
  T=Gas.par_T;
  Gamma=Gas.par_Gamma;

  double me=0.9109534e-30;
  double qe=1.602e-19;
  double Kb=1.38e-23;
  double unit_t=qe*qe/(4*M_PI*8.854e-12)*sqrt(me);


  // overcoming g++ bug with -O3
  double jojo=Kb*T*1.e4;
  //printf("c2: %e\n",jojo);
  jojo=jojo*jojo*jojo;
  jojo=sqrt(jojo);
  //printf("c21: %e\n",jojo);
  unit_t/=jojo;
  //printf("c3:\n");

  double unit_h=Kb*T*1e4*unit_t;
  double h_qwer=1.0545887e-34;

  reader.calc_lambda(T,Gas.ini_Te,Gas.ini_Ti,Gas.mass);

  /*
  if(!non_symm){
   if(Lambda_set!=0.0){
     Lambda=Lambda_set/unit_l;
     equal_lambda=0;
   }
   else {
     Lambda=0.179*sqrt(T);
     equal_lambda=1;
   }
   Lambda_pauli=0.179*sqrt(T);
   //non_symm=0;
   Lambda_ee=Lambda_pp=Lambda*Clam_ee;
   if(fabs(Clam_ee-1.)>1e-5)equal_lambda=0;
   Lambda_ep=Lambda*Clam_ep;
  }
  else{
   if(Lambda_set!=0.0){
     serror("Can not setup lambda for nonsymmetric plasma.\n");
     //Lambda=Lambda_set/unit_l;
     //Lambda_ep=Lambda*Clam_ep;
     //Lambda_ee=Lambda*Clam_ee;
     //equal_lambda=0;
   }
   else{
     if(strstr(Gas.charpot,"Deutsch")){
       printf("Setting lambda values for Deutsch potential !!!\n");
       Lambda_pauli=h_qwer/(unit_h);
       Lambda=Lambda_pauli/sqrt(2*M_PI);
       double m_ee=0.5, m_pp=0.5*Gas.mass, m_ep=Gas.mass/(1.+Gas.mass);

       Lambda_ee=Lambda/sqrt(m_ee);
       Lambda_pp=Lambda/sqrt(m_pp);
       Lambda_ep=Lambda/sqrt(m_ep);
     }
     else { //if(strstr(Gas.charpot,"Kelbg")){
       printf("Setting lambda values for Kelbg potential !!!\n");

       Lambda_pauli=h_qwer/(unit_h);
       Lambda=Lambda_pauli;
       double m_ee=0.5, m_pp=0.5*Gas.mass, m_ep=Gas.mass/(1.+Gas.mass);
       double t_ep=Gas.ini_Te;
       double t_pp=Gas.ini_Ti;
       double t_ee=Gas.ini_Te;

       Lambda_ee=Lambda/sqrt(2*m_ee*t_ee);
       Lambda_pp=Lambda/sqrt(2*m_pp*t_pp);
       Lambda_ep=Lambda/sqrt(2*m_ep*t_ep);
     }

   }
  } */


  if(rel_step)rf_dtcoeff=1./Gas.Wpe;

  double kk=(1.602e-19)*(1.602e-19)/(4*M_PI*1.38e-23*T*1e4*8.854e-12);



  printf("Simulation parameters:\n");
  printf("Gamma =%f\n"
	 "L=%f=%12e m\n"
	 "lambda=%f=%12e m\n"
	 "1/Wp=%f\n"
	 "Rd=%f\n",Gamma,Gas.L, Gas.L*kk,reader.Lambda,reader.Lambda*kk,1./Gas.Wpe,RDebye);
  printf("Density = %1.2e cm^(-3)\n"
	 "T= %f K\n",Gas.par_density*1e19,T*1e4);

  printf("Time step relations:\n");
  printf("dtrf*Wp= %f, dteq*Wp= %f\n", (rel_step ? rf_dt0 : rf_dt0*Gas.Wpe),
	 (rel_step ? eq_dt : eq_dt*Gas.Wpe));


  double t_inter=RDebye/sqrt(2*getEmax(Gas));


  printf("dtrf/tint= %f, dteq/tint= %f\n", rf_dt0*rf_dtcoeff/t_inter,
	 eq_dt*rf_dtcoeff/t_inter);


  reader.calc_correction(Gas.par_T);
  reader.write_pot(pfile, Gas.L);

  /*
  //if(ccount==1)t/=Gas.Wpe;
  if(pot_corr){
    //Correction(IONION,Gas.potential,Gas.par_T);
    Correction(IONELC,Gas.potential,Gas.par_T);
    Correction(ELCELC,Gas.potential,Gas.par_T);
  }*/

  Statistics rs[nstat];



  int repi=0;
  int repc=repc_i;

  do{ //through nrepeats

    printf("\nStarting calculation #%d...\n",repc);
    flm_count=0;

    if(repc>0){
      repi++;
      sprintf(tmpstr,"%02d",repc);
      if(repi>1){
       distrfile[strlen(distrfile)-2]=0;
       ctrfile[strlen(ctrfile)-2]=0;
      }
      strcat(distrfile,tmpstr);
      strcat(ctrfile,tmpstr);
    }


    if(write_distr){
      DRRee.init(rr_r0,(rr_r1>0 ? rr_r1 : Gas.L/2),400);
      DRRep.init(rr_r0,(rr_r1>0 ? rr_r1 : Gas.L/2),400);
      if(non_symm)DRRpp.init(0,(rr_r1>0 ? rr_r1 : Gas.L/2),400);
    }

    long ftype=wtype;


    if(restart){
      printf("restarting...\n");
      if((mc_equil && spwn_trj) || mc_calc){
        mc_equil=-1;
        MC = new mc_simm(Gas,mc_inistep*Gas.L /*Gas.L/Gas.n*/,0.5,
			 mc_one,mc_diff);
        if(!MC)serror("Cannot allocate MCsimm\n");
        MC->auto_adjust=auto_adjust;
      }
      else mc_equil=0;

      if(!new_input)strcpy(inptrj,ctrfile);

      if(load_fried){
        LoadFriedemann(inptrj,Gas);
        Gas.dt=eq_dt;
        if(rel_step)Gas.dt/=Gas.Wpe;

        if(eq_nsteps<wr_int)eq_nsteps=wr_int;
	m=wr_int;
	n=eq_nsteps/m;
	Gas.ext_force=void_force1;
	wr_tr=0;
	ftype=0;
      }
      else{
	Gas.dt=(rel_step ? eq_dt/Gas.Wpe : eq_dt);
	Trajectory.Check(inptrj,wtype,Gas,wr_int,wr_ions,wr_enseq,new_input);
	if(Trajectory.wtype !=0 && !new_input){
	  Gas.dt=Trajectory.AdjustInterval(Gas.dt);
	}

	long stp;
	if(!new_input){
	  stp=Trajectory.ReloadGas(Gas,1);
	  t=stp*Trajectory.file_dt();
	  nf=(long)(t/Gas.dt/wr_int+0.01);
	}
	else{
	  stp=Trajectory.ReloadGas(Gas,0);
	  t=0;
	  nf=0;
	}
	printf("t= %f, nf= %ld,  %f\n",t,nf,(t/Gas.dt/wr_int));

	//serror("Restart is not yet implemented !\n");
        Gas.ext_force=void_force1;
      }
      //restart=0;
    }
    else{
      rand_init=rndlist.step();
      if(rand_init<0){
        rndlist.rewind();
        rand_init=rndlist.step();
      }

      strcat(distrfile,"e");


      if((mc_equil && (!spwn_trj || (repc==repc_i && spwn_trj))) || mc_calc){
        mc_equil=1;
        MC = new mc_simm(Gas,mc_inistep*Gas.L /*Gas.L/Gas.n*/,0.5,
			 mc_one,mc_diff);
        if(!MC)serror("Cannot allocate MCsimm\n");
        MC->auto_adjust=auto_adjust;
      }

      if(!no_equilibr){
        if(!spwn_trj || (spwn_trj && repc==repc_i)){
          limrescale_switch(0);
          Equillibrium(t,Gas,stats,nstat);
          limrescale_switch(limrescale);
        }
      }
      else{
        Gas.r0=0.05;
        Gas.init_config(in_cs,in_distr);
      }

      distrfile[strlen(distrfile)-1]=0; // deleting 'e'

      if(mc_equil){
       if(spwn_trj){
        Gas.init_vel(in_distr);
       }
       else if(!mc_calc){
	 delete MC;
	 mc_equil=-1;
       }
       else
         mc_equil=1;
      }

      Gas.dt=eq_dt;
      if(rel_step)Gas.dt/=Gas.Wpe;

    }
    if(irescale){
     if(irescale==1)Gas.ivel_scale(1.);
     else Gas.init_vel(in_distr);
    }

    if(eq_nsteps<wr_int)eq_nsteps=wr_int;
    if(wr_int>0){
      n=eq_nsteps/wr_int;
      m=wr_int;
    }
    else if(eq_nsteps>=500){
      n=eq_nsteps/500;
      m=500;
    }
    else{
      n=1;
      m=eq_nsteps;
    }

    if(wr_tr && (!restart || new_input || (restart && ftype==0))){

      //WriteHeader(ctrfile,wtype,Gas,Gamma,T, ss,m);

      // initializing PlasmaRec
      Trajectory.Clear();
      Trajectory.Init(ctrfile,wtype,Gas,wr_int,wr_ions,wr_enseq);
    }
    if(wr_tr && (restart && ftype==0)){
      //WriteStep(ctrfile,wtype,Gas,0);
    }

    Statistics statsl[nstat];

    Trajectory.valid=wr_tr;
    // new cycle

    if(bunch){
      PlasmaBunch *pb=(PlasmaBunch *)&Gas;
      pb->start_bunch();
    }
    for(i=nf;i<n;i++){
      double term_c=1.;
      if(Gas.stable_ions)term_c=(double)Gas.ne/Gas.n;
      printf("Equilibrium calculation: %f%% complete, T= %f Et=%f\n",(i+1)*100./n,Gas.T,Gas.T*3/2*term_c+Gas.Epotent/Gas.n);

      if(StopStatus(sfile,3)){
       	StopStatus(sfile,-1);
        serror("Program interrupted!\n");
      }

      if(mc_equil && spwn_trj){
        mc_equil=1;
        double ratio=MC->get_ratio();
        if(ratio<1e-10)printf("Estimated randomization steps: infinity\n");
        else printf("Estimated randomization steps: %d\n",(int)(Gas.n*Gas.L/MC->dc[1]/ratio));
      }
      MoveIt(t,m,m,Gas,stats,statsl,nstat);


      //if(wr_tr)WriteStep(ctrfile,wtype,Gas,i);
      if(write_distr)WriteDRR(distrfile);
      if(wr_film)WriteFilm(filmdir,Gas);
    }
    if(bunch){
      PlasmaBunch *pb=(PlasmaBunch *)&Gas;
      pb->stop_bunch();
    }

    if(write_distr)WriteDRR(distrfile);

    for(i=0;i<nstat;i++)rs[i]+=*(stats[i]);
    repc++;

    if(new_input)restart=0;
  }while(repc<nrepeats);

  if(spwn_trj)delete MC;

  f1=Err_fopen(ofile,"at");
  MiddleFrame(f1,np,p);
  int gn=Gas.n;
  //fprintf(f1,"%9.4f %9.4f %9.4f %9.4f %9.4f %9.4f %9.4f %9.4f\n",
  //       sT.av()*T,sEcoul.av()/gn,sEpotent.av()/gn,sQuant.av()/gn,
  //       sT.dev()*T,sEcoul.dev()/gn,sEpotent.dev()/gn,sQuant.dev()/gn);

  fprintf(f1,"%9.4f %9.4f %9.4f %9.4f %9.4f %9.4f %9.4f %9.4f\n",
         rs[0].av()*T,rs[1].av()/gn,rs[2].av()/gn,rs[3].av()/gn,
         rs[0].dev()*T,rs[1].dev()/gn,rs[2].dev()/gn,rs[3].dev()/gn);

  fclose(f1);

  ccount=CycleCount(np,p);
  WriteStatus(!ccount,sfile,dataname,np,p);

  restart=0;
  repc=0;
 }while(ccount);
 return 0;
}