Example #1
0
void onnick(char *source, char *newnick, char *body)
{
  register aluser *user, **u;
  register asuser *suser, **s;
  register aserver *serv;
  char username[80];
  char hostname[80];
  char TS[80];
  char server[80];
  register achannelnode *chan;
  register anickchange *curr, *prec;
  char buffer[512];
  int i = 0;


#ifdef DEBUG
  printf("NICK: %s --> %s ...\n", source, newnick);
#endif

  /* a new user */
  if (!ToLuser(source))
  {	/* Not a user, so a server or nothing */
    if (strchr(source, '.') == NULL)
    {
      /* Source is not a user and not a server either */
      return;
    }

    if (!strcasecmp(newnick, mynick))
    {
      log("ERROR: I'm nick collided");
#ifdef DEBUG
      printf("ARGH!!! I'M NICK COLLIDED!\n");
#endif
      GetWord(1, body, TS);
      GetWord(2, body, username);
      GetWord(3, body, hostname);

      if (atol(TS) <= logTS &&
	strcasecmp(username, myuser) &&
	strcasecmp(hostname, mysite))
      {
	NickInUse();
	log(source);
	log(newnick);
	log(body);
      }
      else
      {
	onquit(source);
	return;		/*ignore */
      }
#ifdef BACKUP
    }
    else if (!strcasecmp(newnick, MAIN_NICK))
    {
      return;	/* ignore */
#endif
    }
    else if (ToLuser(newnick))
    {
#ifdef DEBUG
      printf("ARGH!!! NICK COLLISION\n");
#endif
      onquit(newnick);
    }
    GetWord(1, body, TS);
    GetWord(2, body, username);
    GetWord(3, body, hostname);
    GetWord(4, body, server);

#ifdef FAKE_UWORLD
    if (Uworld_status == 1 && !strcasecmp(newnick, UFAKE_NICK))
    {
      if (atol(TS) <= UworldTS && atol(TS) != 0 &&
	strcasecmp(username, UFAKE_NICK) &&
	strcasecmp(hostname, UFAKE_HOST))
      {
	sprintf(buffer, "%s nick collided", UFAKE_NICK);
	log(buffer);
	Uworld_status = 0;
	KillUworld("nick collision");
	return;		/* ignore if younger */
      }
    }
#endif

    user = (aluser *) MALLOC(sizeof(aluser));

    user->nick = (char *)MALLOC(strlen(newnick) + 1);
    strcpy(user->nick, newnick);

    user->username = (char *)MALLOC(strlen(username) + 1);
    strcpy(user->username, username);

    user->site = (char *)MALLOC(strlen(hostname) + 1);
    strcpy(user->site, hostname);

    if (*newnick == '+')
      serv = &VirtualServer;
    else
      serv = ToServer(server);

    user->server = serv;

    user->time = atol(TS);
    user->mode = 0;

    user->channel = NULL;
    user->valchan = NULL;

    user->next = Lusers[lu_hash(newnick)];
    Lusers[lu_hash(newnick)] = user;

    /* add user in server's userlist
     */
    suser = (asuser *) MALLOC(sizeof(asuser));
    suser->N = user;
    suser->next = serv->users[su_hash(newnick)];
    serv->users[su_hash(newnick)] = suser;

#ifdef NICKSERV
    nserv_nick(newnick, user);
#endif
  }
  else
  {	/* nick change */

#if 0
    if (!strcasecmp(source, DEFAULT_NICKNAME) &&
      strcasecmp(newnick, DEFAULT_NICKNAME))
    {
      ChNick(DEFAULT_NICKNAME);
    }
#endif
    if (!strcasecmp(newnick, mynick))
    {
#ifdef DEBUG
      printf("ARGH!!! I'M NICK COLLIDED!\n");
#endif
      GetWord(0, body, TS);
      if (atol(TS + 1) <= logTS)
      {
	NickInUse();
	log(source);
	log(newnick);
	log(body);
      }
      else
      {
	onquit(source);
	return;		/*ignore */
      }
    }

    u = &Lusers[lu_hash(source)];
    while (*u && strcasecmp(source, (*u)->nick))
      u = &(*u)->next;
    user = *u;

#ifdef NICKSERV
    nserv_nick(newnick, user);
#endif

    if (user == NULL)
      quit("ERROR! onnick() can't find user", 1);

    s = &user->server->users[su_hash(source)];
    while (*s && strcasecmp((*s)->N->nick, user->nick))
      s = &(*s)->next;
    suser = *s;

    /* change the nick in memory */

    TTLALLOCMEM -= strlen(user->nick) + 1;
    free(user->nick);
    user->nick = (char *)MALLOC(strlen(newnick) + 1);
    strcpy(user->nick, newnick);

    /* now relocate the structure */
    *u = user->next;
    user->next = Lusers[lu_hash(newnick)];
    Lusers[lu_hash(newnick)] = user;

    *s = suser->next;
    suser->next = user->server->users[su_hash(newnick)];
    user->server->users[su_hash(newnick)] = suser;

    /* NICK FLOOD PROTECTION */
    /* 1st wipe old nick changes off */
    chan = user->channel;
    while (chan)
    {
      curr = chan->nickhist;
      prec = NULL;

      /* if not on channel.. ignore nick flood pro */
      if (!chan->N->on)
      {
	chan = chan->next;
	continue;	/* yurk.. as bad as a goto ;) */
      }

      while (curr)
      {
	if (curr->time < (now - 15))
	{
	  if (prec)
	  {
	    prec->next = curr->next;
	    TTLALLOCMEM -= sizeof(anickchange);
	    free(curr);
	    curr = prec->next;
	  }
	  else
	  {
	    chan->nickhist = curr->next;
	    TTLALLOCMEM -= sizeof(anickchange);
	    free(curr);
	    curr = chan->nickhist;
	  }
	}
	else
	{
	  prec = curr;
	  curr = curr->next;
	}
      }

      /* now add the new nick change to the history */
      curr = (anickchange *) MALLOC(sizeof(anickchange));
      strcpy(curr->nick, source);
      curr->time = now;		/* a lil confusing :( */
      curr->next = chan->nickhist;
      chan->nickhist = curr;

      /* now count the nick changes in history
         if there are more than allowed.. grrrr */
      for (i = 0, curr = chan->nickhist; curr;
	curr = curr->next, i++);

      if (i == chan->N->NickFloodPro && chan->N->NickFloodPro != 0
	&& chan->N->on)
      {
	sprintf(buffer, "%s!%[email protected]%s", user->nick, user->username, user->site);
	notice(newnick,
	  "### NICK FLOOD PROTECTION ACTIVATED ###");
	sprintf(buffer, "%s %d", newnick,
	  NICK_FLOOD_SUSPEND_TIME);
	suspend("", chan->N->name, buffer);
	ban("", chan->N->name, newnick);
      }
      chan = chan->next;
    }
  }
}
Example #2
0
int
main(int argc, char *argv[])
{
	int fd;
	size_t mapped_len;
	char *dest;
	char *dest1;
	char *ret;

	START(argc, argv, "pmem_memset");

	if (argc != 4)
		UT_FATAL("usage: %s file offset length", argv[0]);

	fd = OPEN(argv[1], O_RDWR);

	/* open a pmem file and memory map it */
	if ((dest = pmem_map_file(argv[1], 0, 0, 0, &mapped_len, NULL)) == NULL)
		UT_FATAL("!Could not mmap %s\n", argv[1]);

	int dest_off = atoi(argv[2]);
	size_t bytes = strtoul(argv[3], NULL, 0);

	char *buf = MALLOC(bytes);

	memset(dest, 0, bytes);
	util_persist_auto(util_fd_is_device_dax(fd), dest, bytes);
	dest1 = MALLOC(bytes);
	memset(dest1, 0, bytes);

	/*
	 * This is used to verify that the value of what a non persistent
	 * memset matches the outcome of the persistent memset. The
	 * persistent memset will match the file but may not be the
	 * correct or expected value.
	 */
	memset(dest1 + dest_off, 0x5A, bytes / 4);
	memset(dest1 + dest_off  + (bytes / 4), 0x46, bytes / 4);

	/* Test the corner cases */
	ret = pmem_memset_persist(dest + dest_off, 0x5A, 0);
	UT_ASSERTeq(ret, dest + dest_off);
	UT_ASSERTeq(*(char *)(dest + dest_off), 0);

	/*
	 * Do the actual memset with persistence.
	 */
	ret = pmem_memset_persist(dest + dest_off, 0x5A, bytes / 4);
	UT_ASSERTeq(ret, dest + dest_off);
	ret = pmem_memset_persist(dest + dest_off  + (bytes / 4),
					0x46, bytes / 4);
	UT_ASSERTeq(ret, dest + dest_off + (bytes / 4));

	if (memcmp(dest, dest1, bytes / 2))
		UT_ERR("%s: first %zu bytes do not match",
			argv[1], bytes / 2);

	LSEEK(fd, (os_off_t)0, SEEK_SET);
	if (READ(fd, buf, bytes / 2) == bytes / 2) {
		if (memcmp(buf, dest, bytes / 2))
			UT_ERR("%s: first %zu bytes do not match",
				argv[1], bytes / 2);
	}

	UT_ASSERTeq(pmem_unmap(dest, mapped_len), 0);

	FREE(dest1);
	FREE(buf);
	CLOSE(fd);

	DONE(NULL);
}
Example #3
0
struct config *
alloc_config (void)
{
	return (struct config *)MALLOC(sizeof(struct config));
}
Example #4
0
int main(int argc, char *argv[])
{
  meta_parameters *meta, *meta_old, *meta_stat;
	char fnm1[BUF],fnm2[BUF],fnm3[BUF],fnm4[BUF];
	char imgfile[BUF],metaFile[BUF],cmd[BUF],metaIn[BUF],metaOut[BUF];
	FILE *fiamp, *fiphase, *foamp, *fophase, *flas;
	int ll=0, ls=1;   /* look line and sample */
	int sl=STEPLINE, ss=STEPSAMPLE;   /* step line and sample */
	int i,line, sample;
	int row, col, ampFlag = 0;
	long long nitems, newitems, inWid, inLen, outWid, outLen;
	long long ds/*,samplesRead*/;       /* input data size, number of samples read so far.*/
	long long red_offset, grn_offset, blu_offset;
	register float *ampIn, *phaseIn, ampScale;
	float *ampOut, *phaseOut,*ampBuf,Sin[256],Cos[256];
	float avg, percent=5.0;
	RGBDATA *table, *imgData;
	Uchar *redPtr, *grnPtr, *bluPtr;
	complexFloat z;
	struct DDR newddr;
	register float tmp,zImag,zReal,ampI;
	register int index,offset;
	const float convers=256.0/(2*3.14159265358979);
   
	logflag = 0;

  /* parse command line */
  while (currArg < (argc-2)) {
    char *key = argv[currArg++];
    if (strmatch(key,"-log")) {
      CHECK_ARG(1);
      strcpy(logFile,GET_ARG(1));
      fLog = FOPEN(logFile, "a");
      logflag = 1;
    }
    else if (strmatch(key,"-look")) {
      CHECK_ARG(1);
      if (2!=sscanf(GET_ARG(1),"%dx%d",&ll,&ls)) {
        printf("   ***ERROR: -look '%s' does not look like line x sample (e.g. '10x2').\n",GET_ARG(1));
        usage(argv[0]);
      }
    }
    else if (strmatch(key,"-step")) {
      CHECK_ARG(1);
      if (2!=sscanf(GET_ARG(1),"%dx%d",&sl,&ss)) {
        printf("   ***ERROR: -step '%s' does not look like line x sample (e.g. '5x1').\n",GET_ARG(1));
        usage(argv[0]);
      }
    }
    else if (strmatch(key,"-meta")) {
      CHECK_ARG(1);
      if (1!=sscanf(GET_ARG(1),"%s",metaFile)) {
        printf("   ***ERROR: Could not open '%s'.\n",GET_ARG(1));
        usage(argv[0]);
      }
      strcat(metaFile, "");
      ls = ss = 1;
      ll = sl = lzInt(metaFile, "sar.look_count:", NULL);
    }
    else if (strmatch(key,"-amplitude")) {
      printf("   Will remove amplitude part of color image\n");
      ampFlag = 1;
    }
    else {printf("\n   ***Invalid option:  %s\n",argv[currArg-1]); usage(argv[0]);}
  }
  if ((argc-currArg) < 2) {printf("   Insufficient arguments.\n"); usage(argv[0]);}

	system("date");
	printf("Program: multilook\n\n");
	if (logflag) {
	  StartWatchLog(fLog);
	  printLog("Program: multilook\n\n");
	}

	/* Create filenames and open files for reading */
  	create_name(fnm1,argv[currArg],"_amp.img");
  	create_name(fnm2,argv[currArg],"_phase.img");
	meta_stat = meta_read(fnm1);
	meta_old = meta_read(fnm2);
	meta = meta_read(fnm2);
  	create_name(fnm3,argv[++currArg],"_amp.img");
  	create_name(fnm4,argv[currArg],"_phase.img");
  	create_name(imgfile,argv[currArg],"_rgb.img");
	create_name(metaOut,argv[currArg],"_rgb.meta");
 	
	inWid = meta->general->sample_count;
	inLen = meta->general->line_count;
  	meta->general->sample_count /= ss;
  	meta->general->line_count /= sl;
	outWid = meta->general->sample_count;
	outLen = meta->general->line_count;
  
	/* Create new metadata file for the amplitude and phase.*/
	meta->sar->line_increment = 1;
	meta->sar->sample_increment = 1;
	meta->sar->azimuth_time_per_pixel *= sl;
	meta->general->x_pixel_size *= ss;
	meta->general->y_pixel_size *= sl;
	create_name(metaIn,argv[currArg],"_amp.meta");
	meta_write(meta, metaIn);
	create_name(metaIn,argv[currArg],"_phase.meta");
	meta_write(meta, metaIn);

        meta2ddr(meta, &newddr);

	/* Create 3-band image's DDR.
	   Currently metadata file don't know anything about multiband imagery.
	   We will need to convert the current version for single band amplitude
	   image back to metadata version 0.9 and change a couple of values 
	sprintf(cmd, "convert_meta %s 1.3 %s 0.9", metaIn, metaOut);
	asfSystem(cmd);
        */
	
	newddr.dtype=EBYTE;
	newddr.nbands=3;
	c_putddr(imgfile,&newddr);
  
	fiamp = fopenImage(fnm1,"rb");
	fiphase = fopenImage(fnm2,"rb");
	foamp = fopenImage(fnm3,"wb");
	fophase = fopenImage(fnm4,"wb");
	flas = fopenImage(imgfile,"wb");

	/*
	* create data buffers 
	*/
	for (i=0;i<256;i++)
	{
		float phas=((float)i)/256.0*(2*3.14159265358979);
		Sin[i]=sin(phas);
		Cos[i]=cos(phas);
	}
  
	/* set data variables */
	ampScale = 1.0/(ll*ls);
	nitems   = (ll-sl)*inWid;
	newitems = sl*inWid;
  
	ds       = sizeof(float);
	ampIn    = (float *)MALLOC(ds*(newitems+nitems+ls));
	phaseIn  = (float *)MALLOC(ds*(newitems+nitems+ls));
	ampOut   = (float *)MALLOC(ds*outWid);
	ampBuf   = (float *)MALLOC(ds*outWid);
	phaseOut = (float *)MALLOC(ds*outWid);
	table    = (RGBDATA *)MALLOC(sizeof(RGBDATA)*MAXENTRIES);
	imgData  = (RGBDATA *)MALLOC(sizeof(RGBDATA)*outWid);
	redPtr   = (Uchar *)MALLOC(sizeof(Uchar)*outWid);
	grnPtr   = (Uchar *)MALLOC(sizeof(Uchar)*outWid);
	bluPtr   = (Uchar *)MALLOC(sizeof(Uchar)*outWid);
	
        /* calculate mean value */
        if (meta_stat->stats)
          avg = meta_stat->stats->band_stats[0].mean;
        else {
          sprintf(cmd, "stats -overmeta -overstat \"%s\"\n", fnm1);
          asfSystem(cmd);
          meta_free(meta_stat);
          meta_stat = meta_read(fnm1);
          avg = meta_stat->stats->band_stats[0].mean;
        }

	/* create a colortable to be used with c2i */
	colortable(table);
  
	/* start conversion */
/*	printf("   Skipping every %d col and %d row\n",ss,sl);
	printf("   Looking at every %d col and %d row\n",ls,ll);*/
  	printf("   Input is %lld lines by %lld samples\n",inLen,inWid);
	printf("   Ouput is %lld lines by %lld samples\n\n",outLen,outWid);
	if (logflag) {
  	  sprintf(logbuf, "   Input is %lld lines by %lld samples\n",inLen,inWid);
	  printLog(logbuf);
	  sprintf(logbuf, "   Ouput is %lld lines by %lld samples\n\n",outLen,outWid);
	  printLog(logbuf);
	}
 	
	/*
	* Run through all lines in which data needs to be read so that
	* amount of data will be equal to ll * inWid.
	*/
	for(line=0; line<outLen; line++)
	{

		/* Read in a ll*inWid size chunk */
		get_float_lines(fiamp, meta_old, line*sl, ll, ampIn);
		get_float_lines(fiphase, meta_old, line*sl, ll, phaseIn);

		/* begin adding data */
		for (sample=0; sample<outWid; sample++)
		{ 
			tmp = 0.0, zReal=0.0, zImag=0.0;
			/* add up looking area */
			for (col=0;col<ls;col++)
			{
				offset=sample*ss+col;
				for (row=0;row<ll;row++)
				{
					ampI=ampIn[offset];
					index=0xFF&((int)(phaseIn[offset]*convers));
					tmp += ampI * ampI;
					zReal += ampI * Cos[index];
					zImag += ampI * Sin[index];
					offset+=inWid;
 				}
			}
     
			/* get phase from complex values */
			z.real=zReal;
			z.imag=zImag;
			/* place in output buffer */
		/*	ampOut[sample] = sqrt(tmp*ampScale); */
			ampOut[sample] = Cabs(z)*ampScale; 
			phaseOut[sample] = Cphase(z);
			if(!ampFlag)
				ampBuf[sample]=ampOut[sample];
			else
				ampBuf[sample]=avg*1.5;		
		}
    
		/* convert amp & phase to RGB. */
		if (!c2i(ampBuf,phaseOut,imgData,table,outWid,avg))
			Exit("ml: Error in c2i()");

		/* write out data to file */
		put_float_line(foamp, meta, line, ampOut);
		put_float_line(fophase, meta, line, phaseOut);

		if ((line*100/outLen)>percent) {
			printf("   Completed %3.0f percent\n", percent);
			percent+=5.0;
		}
		
		for (i=0;i<outWid;i++)
		{
			redPtr[i] = imgData[i].red;
			grnPtr[i] = imgData[i].green;
			bluPtr[i] = imgData[i].blue;
		} 
		red_offset=(long long)(line*outWid);
		grn_offset=(long long)(line*outWid+outWid*outLen);
		blu_offset=(long long)(line*outWid+(2*outWid*outLen));

		FSEEK64(flas,red_offset,SEEK_SET);
		ASF_FWRITE(redPtr,1,outWid,flas);
		FSEEK64(flas,grn_offset,SEEK_SET);
		ASF_FWRITE(grnPtr,1,outWid,flas);
		FSEEK64(flas,blu_offset,SEEK_SET);
		ASF_FWRITE(bluPtr,1,outWid,flas);
    
		/* reposition data for next read */
		for (i=0;i<nitems;i++)
		{
			ampIn[i] = ampIn[i + newitems];
			phaseIn[i] = phaseIn[i + newitems];
		}
		
	}
  
	/* 
	* free up unneeded memory and prepare to write 
	* a 3 sequential band image
	*/
/*	printf("\n\tdone with multilook\n");
	printf("writing out LAS/RGB image file\n");*
	printf("   Completed 100 percent\n\n   Wrote %lld bytes of data\n\n", 
	       (long long)(outLen*outWid*4));
	if (logflag) {
	  sprintf(logbuf, "   Wrote %lld bytes of data\n\n", 
		  (long long)(outLen*outWid*4));
	  printLog(logbuf);
	  StopWatchLog(fLog);
	  FCLOSE(fLog);
	}
*/

	FREE(ampIn);
	FREE(phaseIn);
	FREE(ampOut);
        FREE(ampBuf);
	FREE(phaseOut);
	FREE(table);
	FCLOSE(fiamp);
	FCLOSE(fiphase);
	FCLOSE(foamp);
	FCLOSE(fophase);
  
	/* free all memory, close files, print out time elapsed */
	FREE(redPtr);
	FREE(grnPtr);
	FREE(bluPtr);
	FREE(imgData);
	FCLOSE(flas);

        meta_free(meta);
        meta_free(meta_stat);
        meta_free(meta_old);

	return 0;
}
Example #5
0
static void
create_frag_shader(struct vl_compositor *c)
{
   const unsigned max_tokens = 50;

   struct pipe_shader_state fs;
   struct tgsi_token *tokens;
   struct tgsi_header *header;

   struct tgsi_full_declaration decl;
   struct tgsi_full_instruction inst;

   unsigned ti;

   unsigned i;

   assert(c);

   tokens = (struct tgsi_token*)MALLOC(max_tokens * sizeof(struct tgsi_token));
   *(struct tgsi_version*)&tokens[0] = tgsi_build_version();
   header = (struct tgsi_header*)&tokens[1];
   *header = tgsi_build_header();
   *(struct tgsi_processor*)&tokens[2] = tgsi_build_processor(TGSI_PROCESSOR_FRAGMENT, header);

   ti = 3;

   /* decl i0             ; Texcoords for s0 */
   decl = vl_decl_interpolated_input(TGSI_SEMANTIC_GENERIC, 1, 0, 0, TGSI_INTERPOLATE_LINEAR);
   ti += tgsi_build_full_declaration(&decl, &tokens[ti], header, max_tokens - ti);

   /*
    * decl c0-c3          ; CSC matrix c0-c3
    */
   decl = vl_decl_constants(TGSI_SEMANTIC_GENERIC, 0, 0, 3);
   ti += tgsi_build_full_declaration(&decl, &tokens[ti], header, max_tokens - ti);

   /* decl o0             ; Fragment color */
   decl = vl_decl_output(TGSI_SEMANTIC_COLOR, 0, 0, 0);
   ti += tgsi_build_full_declaration(&decl, &tokens[ti], header, max_tokens - ti);

   /* decl t0 */
   decl = vl_decl_temps(0, 0);
   ti += tgsi_build_full_declaration(&decl, &tokens[ti], header, max_tokens - ti);

   /* decl s0             ; Sampler for tex containing picture to display */
   decl = vl_decl_samplers(0, 0);
   ti += tgsi_build_full_declaration(&decl, &tokens[ti], header, max_tokens - ti);

   /* tex2d t0, i0, s0    ; Read src pixel */
   inst = vl_tex(TGSI_TEXTURE_2D, TGSI_FILE_TEMPORARY, 0, TGSI_FILE_INPUT, 0, TGSI_FILE_SAMPLER, 0);
   ti += tgsi_build_full_instruction(&inst, &tokens[ti], header, max_tokens - ti);

   /*
    * dp4 o0.x, t0, c0    ; Multiply pixel by the color conversion matrix
    * dp4 o0.y, t0, c1
    * dp4 o0.z, t0, c2
    * dp4 o0.w, t0, c3
    */
   for (i = 0; i < 4; ++i) {
      inst = vl_inst3(TGSI_OPCODE_DP4, TGSI_FILE_OUTPUT, 0, TGSI_FILE_TEMPORARY, 0, TGSI_FILE_CONSTANT, i);
      inst.FullDstRegisters[0].DstRegister.WriteMask = TGSI_WRITEMASK_X << i;
      ti += tgsi_build_full_instruction(&inst, &tokens[ti], header, max_tokens - ti);
   }

   /* end */
   inst = vl_end();
   ti += tgsi_build_full_instruction(&inst, &tokens[ti], header, max_tokens - ti);
	
   assert(ti <= max_tokens);

   fs.tokens = tokens;
   c->fragment_shader = c->pipe->create_fs_state(c->pipe, &fs);
   FREE(tokens);
}
Example #6
0
static char *parse_signature_file(file_stat_t *file_stat, char *pos)
{
  while(*pos!='\0')
  {
    /* skip comments */
    while(*pos=='#')
    {
      while(*pos!='\0' && *pos!='\n')
	pos++;
      if(*pos=='\0')
	return pos;
      pos++;
    }
    /* each line is composed of "extension offset signature" */
    {
      char *extension;
      unsigned int offset=0;
      unsigned char *tmp=NULL;
      unsigned int signature_max_size=512;
      unsigned int signature_size=0;
      {
	const char *extension_start=pos;
	while(*pos!='\0' && !isspace(*pos))
	  pos++;
	if(*pos=='\0')
	  return pos;
	*pos='\0';
	extension=strdup(extension_start);
	pos++;
      }
      /* skip space */
      while(isspace(*pos))
	pos++;
      /* read offset */
      pos=str_uint(pos, &offset);
      /* read signature */
      tmp=(unsigned char *)MALLOC(signature_max_size);
      while(*pos!='\n' && *pos!='\0')
      {
	if(signature_size==signature_max_size)
	{
	  unsigned char *tmp_old=tmp;
	  signature_max_size*=2;
	  tmp=(unsigned char *)realloc(tmp, signature_max_size);
	  if(tmp==NULL)
	  {
	    free(extension);
	    free(tmp_old);
	    return pos;
	  }
	}
	if(isspace(*pos) || *pos=='\r' || *pos==',')
	  pos++;
	else if(*pos== '\'')
	{
	  pos++;
	  if(*pos=='\0')
	  {
	    free(extension);
	    free(tmp);
	    return pos;
	  }
	  else if(*pos=='\\')
	  {
	    pos++;
	    if(*pos=='\0')
	    {
	      free(extension);
	    free(tmp);
	      return pos;
	    }
	    else if(*pos=='b')
	      tmp[signature_size++]='\b';
	    else if(*pos=='n')
	      tmp[signature_size++]='\n';
	    else if(*pos=='t')
	      tmp[signature_size++]='\t';
	    else if(*pos=='r')
	      tmp[signature_size++]='\r';
	    else if(*pos=='0')
	      tmp[signature_size++]='\0';
	    else
	      tmp[signature_size++]=*pos;
	    pos++;
	  }
	  else
	  {
	    tmp[signature_size++]=*pos;
	    pos++;
	  }
	  if(*pos!='\'')
	  {
	    free(extension);
	    free(tmp);
	    return pos;
	  }
	  pos++;
	}
	else if(*pos=='"')
	{
	  pos++;
	  for(; *pos!='"' && *pos!='\0'; pos++)
	  {
	    if(signature_size==signature_max_size)
	    {
	      unsigned char *tmp_old=tmp;
	      signature_max_size*=2;
	      tmp=(unsigned char *)realloc(tmp, signature_max_size);
	      if(tmp==NULL)
	      {
		free(extension);
		free(tmp_old);
		return pos;
	      }
	    }
	    if(*pos=='\\')
	    {
	      pos++;
	      if(*pos=='\0')
	      {
		free(extension);
		free(tmp);
		return pos;
	      }
	      else if(*pos=='b')
		tmp[signature_size++]='\b';
	      else if(*pos=='n')
		tmp[signature_size++]='\n';
	      else if(*pos=='r')
		tmp[signature_size++]='\r';
	      else if(*pos=='t')
		tmp[signature_size++]='\t';
	      else if(*pos=='0')
		tmp[signature_size++]='\0';
	      else
		tmp[signature_size++]=*pos;
	    }
	    else
	      tmp[signature_size++]=*pos;;
	  }
	  if(*pos!='"')
	  {
	    free(extension);
	    free(tmp);
	    return pos;
	  }
	  pos++;
	}
	else if(*pos=='0' && (*(pos+1)=='x' || *(pos+1)=='X'))
	{
	  pos+=2;
	  while(isxdigit(*pos) && isxdigit(*(pos+1)))
	  {
	    unsigned int val=(*pos);
	    if(*pos>='0' && *pos<='9')
	      val-='0';
	    else if(*pos>='A' && *pos<='F')
	      val=val-'A'+10;
	    else if(*pos>='a' && *pos<='f')
	      val=val-'a'+10;
	    pos++;
	    val*=16;
	    val+=(*pos);
	    if(*pos>='0' && *pos<='9')
	      val-='0';
	    else if(*pos>='A' && *pos<='F')
	      val=val-'A'+10;
	    else if(*pos>='a' && *pos<='f')
	      val=val-'a'+10;
	    pos++;
	    tmp[signature_size++]=val;
	  }
	}
	else
	{
	  free(extension);
	  free(tmp);
	  return pos;
	}
      }
      if(*pos=='\n')
	pos++;
      if(signature_size>0)
      {
	/* FIXME: Small memory leak */
	unsigned char *signature=(unsigned char *)MALLOC(signature_size);
	log_info("register a signature for %s\n", extension);
	memcpy(signature, tmp, signature_size);
	register_header_check(offset, signature, signature_size, &header_check_sig, file_stat);
	signature_insert(extension, offset, signature, signature_size);
      }
      else
      {
	free(extension);
      }
      free(tmp);
    }
  }
  return pos;
}
Example #7
0
/*
 * init = 1   - initialize
 *
 * fontname == FONT_UP  - switch to bigger font
 * fontname == FONT_DN  - switch to smaller font
 */
void
change_font (int init, const char *fontname)
{
  const char *const msg = "can't load font \"%s\"";
  XFontStruct *xfont;
  static char *newfont[NFONTS];
#ifndef NO_BOLDFONT
  static XFontStruct *boldFont = NULL;
#endif
  static int fnum = FONT0_IDX;	/* logical font number */
  int idx = 0;			/* index into rs_font[] */

#if (FONT0_IDX == 0)
#define IDX2FNUM(i) (i)
#define FNUM2IDX(f) (f)
#else
#define IDX2FNUM(i) (i == 0? FONT0_IDX : (i <= FONT0_IDX? (i-1) : i))
#define FNUM2IDX(f) (f == FONT0_IDX ? 0 : (f < FONT0_IDX ? (f+1) : f))
#endif
#define FNUM_RANGE(i)	(i <= 0 ? 0 : (i >= NFONTS ? (NFONTS-1) : i))

  if (!init)
    {
      switch (fontname[0])
	{
	case '\0':
	  fnum = FONT0_IDX;
	  fontname = NULL;
	  break;

	  /* special (internal) prefix for font commands */
	case FONT_CMD:
	  idx = atoi (fontname + 1);
	  switch (fontname[1])
	    {
	    case '+':		/* corresponds to FONT_UP */
	      fnum += (idx ? idx : 1);
	      fnum = FNUM_RANGE (fnum);
	      break;

	    case '-':		/* corresponds to FONT_DN */
	      fnum += (idx ? idx : -1);
	      fnum = FNUM_RANGE (fnum);
	      break;

	    default:
	      if (fontname[1] != '\0' && !isdigit (fontname[1]))
		return;
	      if (idx < 0 || idx >= (NFONTS))
		return;
	      fnum = IDX2FNUM (idx);
	      break;
	    }
	  fontname = NULL;
	  break;

	default:
	  if (fontname != NULL)
	    {
	      /* search for existing fontname */
	      for (idx = 0; idx < NFONTS; idx++)
		{
		  if (!strcmp (rs_font[idx], fontname))
		    {
		      fnum = IDX2FNUM (idx);
		      fontname = NULL;
		      break;
		    }
		}
	    }
	  else
	    return;
	  break;
	}
      /* re-position around the normal font */
      idx = FNUM2IDX (fnum);

      if (fontname != NULL)
	{
	  char *name;
	  xfont = XLoadQueryFont (Xdisplay, fontname);
	  if (!xfont)
	    return;

	  name = MALLOC (strlen (fontname + 1) * sizeof (char), "font");

	  if (name == NULL)
	    {
	      XFreeFont (Xdisplay, xfont);
	      return;
	    }

	  strcpy (name, fontname);
	  if (newfont[idx] != NULL)
	    FREE (newfont[idx], "id", "fn");
	  newfont[idx] = name;
	  rs_font[idx] = newfont[idx];
	}
    }

  if (TermWin.font)
    XFreeFont (Xdisplay, TermWin.font);

  /* load font or substitute */
  xfont = XLoadQueryFont (Xdisplay, rs_font[idx]);
  if (!xfont)
    {
      print_error (msg, rs_font[idx]);
      rs_font[idx] = "fixed";
      xfont = XLoadQueryFont (Xdisplay, rs_font[idx]);
      if (!xfont)
	{
	  print_error (msg, rs_font[idx]);
	  goto Abort;
	}
    }
  TermWin.font = xfont;

#ifndef NO_BOLDFONT
  /* fail silently */
  if (init && rs_boldFont != NULL)
    boldFont = XLoadQueryFont (Xdisplay, rs_boldFont);
#endif

#ifdef KANJI
  if (TermWin.kanji)
    XFreeFont (Xdisplay, TermWin.kanji);

  /* load font or substitute */
  xfont = XLoadQueryFont (Xdisplay, rs_kfont[idx]);
  if (!xfont)
    {
      print_error (msg, rs_kfont[idx]);
      rs_kfont[idx] = "k14";
      xfont = XLoadQueryFont (Xdisplay, rs_kfont[idx]);
      if (!xfont)
	{
	  print_error (msg, rs_kfont[idx]);
	  goto Abort;
	}
    }
  TermWin.kanji = xfont;
#endif /* KANJI */

  /* alter existing GC */
  if (!init)
    {
      XSetFont (Xdisplay, TermWin.gc, TermWin.font->fid);
#ifndef NO_MENUBAR
      menubar_expose ();
#endif /* NO_MENUBAR */
    }

  /* set the sizes */
  {
    int fw = XTextWidth (TermWin.font, "MMMMMMMMMM", 10) / 10;
    int fh = TermWin.font->ascent + TermWin.font->descent;

    /* not the first time thru and sizes haven't changed */
    if (fw == TermWin.fwidth && fh == TermWin.fheight)
      return;

    TermWin.fwidth = fw;
    TermWin.fheight = fh;
  }

  /* check that size of boldFont is okay */
#ifndef NO_BOLDFONT
  if (boldFont != NULL &&
      TermWin.fwidth == (XTextWidth (boldFont, "MMMMMMMMMM", 10) / 10) &&
      TermWin.fheight == (boldFont->ascent + boldFont->descent))
    TermWin.boldFont = boldFont;
  else
    TermWin.boldFont = NULL;
#endif /* NO_BOLDFONT */

  set_colorfgbg ();

  TermWin.width = TermWin.ncol * TermWin.fwidth;
  TermWin.height = TermWin.nrow * TermWin.fheight;

  szHint.width_inc = TermWin.fwidth;
  szHint.height_inc = TermWin.fheight;

  szHint.min_width = szHint.base_width + szHint.width_inc;
  szHint.min_height = szHint.base_height + szHint.height_inc;

  szHint.width = szHint.base_width + TermWin.width;
  szHint.height = szHint.base_height + TermWin.height;

  szHint.flags = PMinSize | PResizeInc | PBaseSize | PWinGravity;

  if (!init)
    resize ();

  return;
Abort:
  print_error ("aborting");	/* fatal problem */
  exit (EXIT_FAILURE);
#undef IDX2FNUM
#undef FNUM2IDX
#undef FNUM_RANGE
}
Example #8
0
/*--------------------------------------------------------------------------*/
int main (int argc, char **argv)
{
    #define MAXCMDTOKENS 128
    int iExitCode = 0;
    UINT LastErrorMode = 0;
    HINSTANCE hinstLib = NULL; 

    BOOL fFreeResult = FALSE, fRunTimeLinkSuccess = FALSE; 

    int argcbis = -1;
    LPSTR argvbis[MAXCMDTOKENS];
    int i = 0;
    int FindNW = 0;

    if (GetWindowsVersion() == OS_ERROR	)
    {
        MessageBox(NULL, TEXT(MSG_DETECT_UNKNOW), TEXT(MSG_WARNING), MB_ICONWARNING);
        return -1;
    }

    if (GetWindowsVersion() < OS_WIN32_WINDOWS_XP	)
    {
        MessageBox(NULL, TEXT(MSG_DETECT_XP_OR_MORE), TEXT(MSG_WARNING), MB_ICONWARNING);
        return -1;
    }

    /* http://msdn.microsoft.com/en-us/library/ms724482(VS.85).aspx */
    if (!IsProcessorFeaturePresent(PF_XMMI_INSTRUCTIONS_AVAILABLE))
    {
        MessageBox(NULL, TEXT(MSG_DETECT_SSE_OR_MORE), TEXT(MSG_WARNING), MB_ICONWARNING);
        return -1;
    }

    for (i = 0; i < argc; i++)
    {
        if (_stricmp(argv[i], ARG_NW) == 0) FindNW = 1;
        if (_stricmp(argv[i], ARG_NWNI) == 0 ) FindNW = 1;
        if (_stricmp(argv[i], ARG_NOGUI) == 0 ) FindNW = 1;
    }

    if ( FindNW == 0 )
    {
        /* -nw added as first argument and not last */
        char *nwparam = NULL;
        nwparam = (char*)MALLOC((strlen(ARG_NW) + 1) * sizeof(char));
        strcpy_s(nwparam,(strlen(ARG_NW) + 1), ARG_NW);

        argvbis[0] = argv[0];
        argvbis[1] = nwparam;

        for (i = 1; i<argc; i++)
        {
            argvbis[i+1] = argv[i];
        }
        argcbis = argc+1;
    }
    else
    {
        for (i = 0; i < argc; i++)
        {
            argvbis[i] = argv[i];
        }
        argcbis = argc;
    }

    /* Disable system errors msgbox */
    LastErrorMode = SetErrorMode(SEM_FAILCRITICALERRORS);

    hinstLib = LoadLibrary(TEXT(SCILAB_LIBRARY));

    /* re enable system errors msgbox */
    SetErrorMode(LastErrorMode);

    if (hinstLib != NULL)
    {
        MYPROC1 Console_Main = NULL;

        /* launch main */
        Console_Main = (MYPROC1) GetProcAddress(hinstLib, MAIN_FUNCTION);

        if (NULL != Console_Main)
        {
            fRunTimeLinkSuccess = TRUE;

#ifndef _DEBUG
            /* catch system errors msgbox (release mode only) */
            /* http://msdn.microsoft.com/en-us/library/ms680621(VS.85).aspx */
            LastErrorMode = SetErrorMode( SEM_FAILCRITICALERRORS|SEM_NOALIGNMENTFAULTEXCEPT|SEM_NOGPFAULTERRORBOX );
            _try
            {
#endif
                iExitCode = (Console_Main)(argcbis, argvbis);

#ifndef _DEBUG
            }
            _except (EXCEPTION_EXECUTE_HANDLER)
            {
            }
#endif
        }
Example #9
0
NTSTATUS
InfWriteFile(HINF InfHandle,
             PUNICODE_STRING FileName,
             PUNICODE_STRING HeaderComment)
{
  OBJECT_ATTRIBUTES ObjectAttributes;
  IO_STATUS_BLOCK IoStatusBlock;
  HANDLE FileHandle;
  NTSTATUS Status;
  INFSTATUS InfStatus;
  PCHAR Buffer;
  ULONG BufferSize;
  PCHAR HeaderBuffer;
  ULONG HeaderBufferSize;
  UINT Index;

  InfStatus = InfpBuildFileBuffer((PINFCACHE) InfHandle, &Buffer, &BufferSize);
  if (! INF_SUCCESS(InfStatus))
    {
      DPRINT("Failed to create buffer (Status 0x%lx)\n", InfStatus);
      return InfStatus;
    }

  /* Open the inf file */
  InitializeObjectAttributes(&ObjectAttributes,
                             FileName,
                             0,
                             NULL,
                             NULL);

  Status = NtOpenFile(&FileHandle,
                      GENERIC_WRITE | SYNCHRONIZE,
                      &ObjectAttributes,
                      &IoStatusBlock,
                      0,
                      FILE_SYNCHRONOUS_IO_NONALERT | FILE_NON_DIRECTORY_FILE);
  if (!INF_SUCCESS(Status))
    {
      DPRINT1("NtOpenFile() failed (Status %lx)\n", Status);
      FREE(Buffer);
      return Status;
    }

  DPRINT("NtOpenFile() successful\n");

  if (NULL != HeaderComment && 0 != HeaderComment->Length)
    {
      /* This is just a comment header, don't abort on errors here */
      HeaderBufferSize = HeaderComment->Length / sizeof(WCHAR) + 7;
      HeaderBuffer = MALLOC(HeaderBufferSize);
      if (NULL != HeaderBuffer)
        {
          strcpy(HeaderBuffer, "; ");
          for (Index = 0; Index < HeaderComment->Length / sizeof(WCHAR); Index++)
            {
              HeaderBuffer[2 + Index] = (CHAR) HeaderComment->Buffer[Index];
            }
          strcpy(HeaderBuffer + (2 + HeaderComment->Length / sizeof(WCHAR)),
                 "\r\n\r\n");
          NtWriteFile(FileHandle,
                      NULL,
                      NULL,
                      NULL,
                      &IoStatusBlock,
                      HeaderBuffer,
                      HeaderBufferSize,
                      NULL,
                      NULL);
          FREE(HeaderBuffer);
        }
    }

  /* Write main contents */
  Status = NtWriteFile(FileHandle,
                       NULL,
                       NULL,
                       NULL,
                       &IoStatusBlock,
                       Buffer,
                       BufferSize,
                       NULL,
                       NULL);

  NtClose(FileHandle);
  FREE(Buffer);

  if (!INF_SUCCESS(Status))
    {
      DPRINT1("NtWriteFile() failed (Status %lx)\n", Status);
      FREE(Buffer);
      return(Status);
    }

  return STATUS_SUCCESS;
}
Example #10
0
static void create_file_names(void)
{
    register int len;
    register char *defines_suffix;
    register char *prefix;

    prefix = NULL;
    defines_suffix = DEFINES_SUFFIX;

    /* compute the file_prefix from the user provided output_file_name */
    if (output_file_name != 0)
    {
        defines_suffix = ".h";
	if (!(prefix = is_suffix(output_file_name, ".cpp")))
	    prefix = is_suffix(output_file_name, "");
    }

    if (prefix != NULL)
    {
	len = prefix - output_file_name;
	file_prefix = (char *)MALLOC(len + 1);
	if (file_prefix == 0)
	    no_space();
	strncpy(file_prefix, output_file_name, len)[len] = 0;
    }
    else
	len = strlen(file_prefix);

    /* if "-o filename" was not given */
    if (output_file_name == 0)
    {
	oflag = 1;
	CREATE_FILE_NAME(output_file_name, OUTPUT_SUFFIX);
    }

    if (rflag)
    {
	CREATE_FILE_NAME(code_file_name, CODE_SUFFIX);
    }
    else
	code_file_name = output_file_name;

    if (dflag)
    {
	CREATE_FILE_NAME(defines_file_name, defines_suffix);
    }

    if (vflag)
    {
	CREATE_FILE_NAME(verbose_file_name, VERBOSE_SUFFIX);
    }

    if (gflag)
    {
	CREATE_FILE_NAME(graph_file_name, GRAPH_SUFFIX);
    }

    if (prefix != NULL)
    {
	FREE(file_prefix);
    }

	create_temp_name(&text_file_name, output_file_name, ".byacc.text");
	create_temp_name(&union_file_name, output_file_name, ".byacc.union");
	create_temp_name(&action_file_name, output_file_name, ".byacc.action");
}
Example #11
0
void *mxMalloc(size_t nsize)
{
    //TODO
    return MALLOC(nsize);
}
Example #12
0
int
CKTnoise (CKTcircuit *ckt, int mode, int operation, Ndata *data)
{
    double outNdens;
    int i;
    extern SPICEdev **DEVices;
    IFvalue outData;    /* output variable (points to list of outputs)*/
    IFvalue refVal; /* reference variable (always 0)*/
    int error;

    outNdens = 0.0;

    /* let each device decide how many and what type of noise sources it has */

    for (i=0; i < DEVmaxnum; i++) {
        if ( DEVices[i] && ((*DEVices[i]).DEVnoise != NULL) && (ckt->CKThead[i] != NULL) ) {
            error = (*((*DEVices[i]).DEVnoise))(mode,operation,ckt->CKThead[i],
                                                ckt,data, &outNdens);
            if (error) return (error);
        }
    }

    switch (operation) {

    case N_OPEN:

        /* take care of the noise for the circuit as a whole */

        switch (mode) {

        case N_DENS:

            data->namelist = (IFuid *)trealloc((char *)data->namelist,
                                               (data->numPlots + 1)*sizeof(IFuid));

            (*(SPfrontEnd->IFnewUid))(ckt, &(data->namelist[data->numPlots++]),
                                      (IFuid)NULL,"onoise_spectrum",UID_OTHER,(void **)NULL);

            data->namelist = (IFuid *)trealloc((char *)data->namelist,
                                               (data->numPlots + 1)*sizeof(IFuid));

            (*(SPfrontEnd->IFnewUid))(ckt, &(data->namelist[data->numPlots++]),
                                      (IFuid)NULL,"inoise_spectrum",UID_OTHER,(void **)NULL);

            /* we've added two more plots */

            data->outpVector =
                (double *)MALLOC(data->numPlots * sizeof(double));
            break;

        case INT_NOIZ:

            data->namelist = (IFuid *)trealloc((char *)data->namelist,
                                               (data->numPlots + 1)*sizeof(IFuid));
            (*(SPfrontEnd->IFnewUid))(ckt, &(data->namelist[data->numPlots++]),
                                      (IFuid)NULL,"onoise_total",UID_OTHER,(void **)NULL);

            data->namelist = (IFuid *)trealloc((char *)data->namelist,
                                               (data->numPlots + 1)*sizeof(IFuid));
            (*(SPfrontEnd->IFnewUid))(ckt, &(data->namelist[data->numPlots++]),
                                      (IFuid)NULL,"inoise_total",UID_OTHER,(void **)NULL);
            /* we've added two more plots */

            data->outpVector =
                (double *) MALLOC(data->numPlots * sizeof(double));
            break;

        default:
            return (E_INTERN);
        }

        break;

    case N_CALC:

        switch (mode) {

        case N_DENS:
            if ((((NOISEAN*)ckt->CKTcurJob)->NStpsSm == 0)
                    || data->prtSummary)
            {
                data->outpVector[data->outNumber++] = outNdens;
                data->outpVector[data->outNumber++] =
                    (outNdens * data->GainSqInv);

                refVal.rValue = data->freq; /* the reference is the freq */
                outData.v.numValue = data->outNumber; /* vector number */
                outData.v.vec.rVec = data->outpVector; /* vector of outputs */
                (*(SPfrontEnd->OUTpData))(data->NplotPtr,&refVal,&outData);
            }
            break;

        case INT_NOIZ:
            data->outpVector[data->outNumber++] =  data->outNoiz;
            data->outpVector[data->outNumber++] =  data->inNoise;
            outData.v.vec.rVec = data->outpVector; /* vector of outputs */
            outData.v.numValue = data->outNumber; /* vector number */
            (*(SPfrontEnd->OUTpData))(data->NplotPtr,&refVal,&outData);
            break;

        default:
            return (E_INTERN);
        }
        break;

    case N_CLOSE:
        (*(SPfrontEnd->OUTendPlot))(data->NplotPtr);
        FREE(data->namelist);
        FREE(data->outpVector);
        break;

    default:
        return (E_INTERN);
    }
    return (OK);
}
Example #13
0
int main (int argc, char *argv[])
{
  char cpxName[BUF],ampName[BUF],phsName[BUF]; /* File Names                  */
  FILE *fdCpx, *fdAmp, *pdPhs;            /* File Pointers                    */
  int line, sample;                       /* Line & sample indices for looping*/
  int percentComplete;                    /* Percent of data processed        */
  int ampBlockSize, phsBlockSize;         /* Number of samples gotten         */
  float *ampBuf, *aP, *phsBuf, *pP;       /* Output data buffers              */
  complexFloat *cpxBuf, *cP;              /* Input data buffers               */
  meta_parameters *inMeta, *outMeta;      /* In/Out meta structs              */
  int i, phaseImage=FALSE;

/* Make sure there are the correct number of args in the command line */
  if (argc < 3) { usage(argv[0]); }

/* Make sure input and output names are different */
  if (strcmp(argv[1],argv[2])==0) {
    printf("p2c: Input and output names cannot be the same. Exiting.\n");
    exit(EXIT_FAILURE);
  }
  
/* Get commandline args */
  create_name (ampName,argv[1],".amp"); 
  create_name (phsName,argv[1],".phase"); 
  create_name (cpxName,argv[2],".cpx");
  
  // Check whether phase image actually exists. If it does not exist, we will 
  // generate a phase image with a constant value on the fly.
  if (fileExists(phsName))
    phaseImage = TRUE;
  else
    printf("\nCould not find phase image! Generating constant phase image on "
	   "the fly ...\n");

/* Read the meta data. Write output meta with COMPLEX_* data type. */
  inMeta = meta_read(argv[1]);
  outMeta = meta_read(argv[1]);
  outMeta->general->data_type = meta_polar2complex(inMeta->general->data_type);
  meta_write(outMeta,argv[2]);

/* malloc buffers, check and open files */
  cpxBuf = (complexFloat *)MALLOC(sizeof(complexFloat)
                         * outMeta->general->sample_count * CHUNK_OF_LINES);
  ampBuf = (float *)MALLOC(sizeof(float)
                         * inMeta->general->sample_count * CHUNK_OF_LINES);
  phsBuf = (float *)MALLOC(sizeof(float)
                         * inMeta->general->sample_count * CHUNK_OF_LINES);
  fdCpx = fopenImage(cpxName, "wb");
  fdAmp = fopenImage(ampName, "rb");  
  pdPhs = fopenImage(phsName, "rb");  

/* Run thru the complex file, writing real data to amp and imag data to phase */
  printf("\n");
  percentComplete = 0;
  for (line=0; line<inMeta->general->line_count; line+=CHUNK_OF_LINES)
  {
    if ((line*100/inMeta->general->line_count == percentComplete)) {
      printf("\rConverting amp and phase to complex: %3d%% complete.",
             percentComplete++);
      fflush(NULL);
    }
    ampBlockSize = get_float_lines(fdAmp,inMeta,line,CHUNK_OF_LINES,ampBuf);
    if (phaseImage) {
      phsBlockSize = get_float_lines(pdPhs,inMeta,line,CHUNK_OF_LINES,phsBuf);
      if (ampBlockSize != phsBlockSize) {
	printf("\n");
	printf("p2c: Failed to get the same number of samples from amplitude and phase files.\n");
	printf("p2c: Exiting...\n\n");
	exit(EXIT_FAILURE);
      }
    }
    else {
      for (i=0; i<inMeta->general->sample_count*CHUNK_OF_LINES; i++)
	phsBlockSize = 0.0;
    }
    cP = cpxBuf;
    aP = ampBuf;
    pP = phsBuf;
    for (sample=0; sample<ampBlockSize; sample++) {
      cP->real = *aP * cos(*pP);
      cP->imag = *aP * sin(*pP);
      cP++;
      aP++;
      pP++;
    }
    put_complexFloat_lines(fdCpx,outMeta,line,CHUNK_OF_LINES,cpxBuf);
  }
  printf("\rConverted amp and phase to complex:  100%% complete.\n\n");

  /* close, free, halt */
  FCLOSE(fdCpx);
  FCLOSE(fdAmp);
  FCLOSE(pdPhs);
  FREE(cpxBuf);
  FREE(ampBuf);
  FREE(phsBuf);
  meta_free(inMeta);
  meta_free(outMeta);
  
  return 0;
}
Example #14
0
static int
get_bladehpi_hostlist(struct pluginDevice *dev)
{
	struct blade_info *	bi;
	SaErrorT		ohrc;
	SaHpiEntryIdT		ohnextid;
	SaHpiRptEntryT		ohRPT;
	SaHpiDomainInfoT 	ohdi;
	SaHpiUint32T		ohupdate;

	if (Debug) {
		LOG(PIL_DEBUG, "%s: called, dev->device=%s"
		,	__FUNCTION__,	dev->device);
	}

	if (dev->device == NULL || *dev->device == 0) {
		LOG(PIL_CRIT, "Unconfigured stonith object in %s"
		,	__FUNCTION__);
		return S_BADCONFIG;
	}

	ohrc = saHpiDomainInfoGet(dev->ohsession, &ohdi);
	if (ohrc != SA_OK) {
		LOG(PIL_CRIT, "Unable to get domain info in %s (%d)"
		,	__FUNCTION__, ohrc);
		return S_BADCONFIG;
	}
	
try_again:
	ohupdate = ohdi.RptUpdateCount;
	dev->ohdevid = dev->ohsensid = dev->ohsensnum = 0;
	ohnextid = SAHPI_FIRST_ENTRY;
	do {
		char blname[SAHPI_MAX_TEXT_BUFFER_LENGTH];
		int  blnum;

		ohrc = saHpiRptEntryGet(dev->ohsession, ohnextid
				       , &ohnextid, &ohRPT);
		if (ohrc != SA_OK) {
			LOG(PIL_CRIT, "Unable to get RPT entry in %s (%d)"
			,	__FUNCTION__, ohrc);
			free_bladehpi_hostlist(dev);
			return S_BADCONFIG;
		}

		switch (get_resource_type(dev->device, &ohRPT)) {
		case OHRES_BLADECENT:
			dev->ohdevid = ohRPT.ResourceId;

			if (Debug) {
				LOG(PIL_DEBUG, "BladeCenter '%s' has id %d"
				,	(char*)ohRPT.ResourceTag.Data
				,	dev->ohdevid);
			}
			break;

		case OHRES_MGMTMOD:
			if (ohRPT.ResourceCapabilities&SAHPI_CAPABILITY_SENSOR){
 				dev->ohsensnum = get_sensor_num(dev->ohsession
							, ohRPT.ResourceId);

				if (dev->ohsensnum) {
					dev->ohsensid = ohRPT.ResourceId;

					if (Debug) {
						LOG(PIL_DEBUG
						, "MgmtModule '%s' has id %d "
						"with sensor #%d"
						, (char*)ohRPT.ResourceTag.Data
						, dev->ohsensid
						, dev->ohsensnum);
					}
				}
			} 
			break;

		case OHRES_BLADE:
			if ((bi = (struct blade_info *)
				MALLOC(sizeof(struct blade_info))) == NULL) {
			        LOG(PIL_CRIT, "Out of memory in %s"
				,	__FUNCTION__);
				free_bladehpi_hostlist(dev);
			        return S_OOPS;
			}

			/*
			 * New format consists of "Blade N - name" while older
			 * format consists only of "name"; we only need to
			 * stash name because ResourceID is the important info
			 */
			if (sscanf((char*)ohRPT.ResourceTag.Data, "Blade %d - %s"
					, &blnum, blname) == 2) {
				bi->name = STRDUP(blname);
			} else {
				bi->name = STRDUP((char*)ohRPT.ResourceTag.Data);
			}
			if (bi->name == NULL) {
				LOG(PIL_CRIT, "Out of memory for strdup in %s"
				,	__FUNCTION__);
				free_bladehpi_hostlist(dev);
			        return S_OOPS;
			}

			bi->resourceId = ohRPT.ResourceId;
			bi->resourceCaps = ohRPT.ResourceCapabilities;
			dev->hostlist = g_list_append(dev->hostlist, bi);

			if (Debug) {
				LOG(PIL_DEBUG, "Blade '%s' has id %d, caps %x"
				, bi->name, bi->resourceId, bi->resourceCaps);
			}
			break;
		}
	} while (ohrc == SA_OK && ohnextid != SAHPI_LAST_ENTRY);

	ohrc = saHpiDomainInfoGet(dev->ohsession, &ohdi);
	if (ohrc != SA_OK) {
		LOG(PIL_CRIT, "Unable to get domain info in %s (%d)"
		,	__FUNCTION__, ohrc);
		free_bladehpi_hostlist(dev);
		return S_BADCONFIG;
	}

	if (ohupdate != ohdi.RptUpdateCount) {
		free_bladehpi_hostlist(dev);
		if(Debug){
			LOG(PIL_DEBUG, "Looping through entries again,"
				" count changed from %d to %d"
			,	ohupdate, ohdi.RptUpdateCount);
		}
		goto try_again;
	}

	dev->ohrptcnt = ohupdate;

	return S_OK;
}
Example #15
0
int main (
   int argc ,    // Number of command line arguments (includes prog name)
   char *argv[]  // Arguments (prog name is argv[0])
   )

{
   int i, j, k, nvars, ncases, irep, nreps, nbins, nbins_dep, nbins_indep, *count ;
   int n_indep_vars, idep, icand, *index, *mcpt_max_counts, *mcpt_same_counts, *mcpt_solo_counts ;
   short int *bins_dep, *bins_indep ;
   double *data, *work, dtemp, *save_info, criterion, *crits ;
   double *ab, *bc, *b ;
   char filename[256], **names, depname[256] ;
   FILE *fp ;

/*
   Process command line parameters
*/

#if 1
   if (argc != 6) {
      printf ( "\nUsage: TRANSFER  datafile  n_indep  depname  nreps" ) ;
      printf ( "\n  datafile - name of the text file containing the data" ) ;
      printf ( "\n             The first line is variable names" ) ;
      printf ( "\n             Subsequent lines are the data." ) ;
      printf ( "\n             Delimiters can be space, comma, or tab" ) ;
      printf ( "\n  n_indep - Number of independent vars, starting with the first" ) ;
      printf ( "\n  depname - Name of the 'dependent' variable" ) ;
      printf ( "\n            It must be AFTER the first n_indep variables" ) ;
      printf ( "\n  nbins - Number of bins for all variables" ) ;
      printf ( "\n  nreps - Number of Monte-Carlo permutations, including unpermuted" ) ;
      exit ( 1 ) ;
      }

   strcpy ( filename , argv[1] ) ;
   n_indep_vars = atoi ( argv[2] ) ;
   strcpy ( depname , argv[3] ) ;
   nbins = atoi ( argv[4] ) ;
   nreps = atoi ( argv[5] ) ;
#else
   strcpy ( filename , "..\\SYNTH.TXT" ) ;
   n_indep_vars = 7 ;
   strcpy ( depname , "SUM1234" ) ;
   nbins = 2 ;
   nreps = 1 ;
#endif

   _strupr ( depname ) ;

/*
   These are used by MEM.CPP for runtime memory validation
*/

   _fullpath ( mem_file_name , "MEM.LOG" , 256 ) ;
   fp = fopen ( mem_file_name , "wt" ) ;
   if (fp == NULL) { // Should never happen
      printf ( "\nCannot open MEM.LOG file for writing!" ) ;
      return EXIT_FAILURE ;
      }
   fclose ( fp ) ;
   mem_keep_log = 1 ;  // Change this to 1 to keep a memory use log (slows execution!)
   mem_max_used = 0 ;

/*
   Open the text file to which results will be written
*/

   fp = fopen ( "TRANSFER.LOG" , "wt" ) ;
   if (fp == NULL) { // Should never happen
      printf ( "\nCannot open TRANSFER.LOG file for writing!" ) ;
      return EXIT_FAILURE ;
      }

/*
   Read the file and locate the index of the dependent variable
*/

   if (readfile ( filename , &nvars , &names , &ncases , &data ))
      return EXIT_FAILURE ;

   for (idep=0 ; idep<nvars ; idep++) {
      if (! strcmp ( depname , names[idep] ))
         break ;
      }

   if (idep == nvars) {
      printf ( "\nERROR... Dependent variable %s is not in file", depname ) ;
      return EXIT_FAILURE ;
      }

   if (idep < n_indep_vars) {
      printf ( "\nERROR... Dependent variable %s must be beyond independent vars",
               depname ) ;
      return EXIT_FAILURE ;
      }

/*
   Allocate scratch memory

   crits - Transfer Entropy criterion
   index - Indices that sort the criterion
   save_info - Ditto, this is univariate criteria, to be sorted
*/

   MEMTEXT ( "TRANSFER work allocs" ) ;
   work = (double *) MALLOC ( ncases * sizeof(double) ) ;
   assert ( work != NULL ) ;
   crits = (double *) MALLOC ( n_indep_vars * sizeof(double) ) ;
   assert ( crits != NULL ) ;
   index = (int *) MALLOC ( n_indep_vars * sizeof(int) ) ;
   assert ( index != NULL ) ;
   bins_indep = (short int *) MALLOC ( ncases * sizeof(short int) ) ;
   assert ( bins_indep != NULL ) ;
   bins_dep = (short int *) MALLOC ( ncases * sizeof(short int) ) ;
   assert ( bins_dep != NULL ) ;
   mcpt_max_counts = (int *) MALLOC ( n_indep_vars * sizeof(int) ) ;
   assert ( mcpt_max_counts != NULL ) ;
   mcpt_same_counts = (int *) MALLOC ( n_indep_vars * sizeof(int) ) ;
   assert ( mcpt_same_counts != NULL ) ;
   mcpt_solo_counts = (int *) MALLOC ( n_indep_vars * sizeof(int) ) ;
   assert ( mcpt_solo_counts != NULL ) ;
   save_info = (double *) MALLOC ( n_indep_vars * sizeof(double) ) ;
   assert ( save_info != NULL ) ;
   count = (int *) MALLOC ( nbins * nbins * nbins * sizeof(int) ) ;
   assert ( count != NULL ) ;
   ab = (double *) MALLOC ( nbins * nbins * sizeof(double) ) ;
   assert ( ab != NULL ) ;
   bc = (double *) MALLOC ( nbins * nbins * sizeof(double) ) ;
   assert ( bc != NULL ) ;
   b = (double *) MALLOC ( nbins * sizeof(double) ) ;
   assert ( b != NULL ) ;

/*
   Get the dependent variable and partition it
*/

   for (i=0 ; i<ncases ; i++)            // Get the 'dependent' variable
      work[i] = data[i*nvars+idep] ;

   nbins_dep = nbins ;
   partition ( ncases , work , &nbins_dep , NULL , bins_dep ) ;

/*
   Replication loop is here
*/

   for (irep=0 ; irep<nreps ; irep++) {

/*
   Compute and save the transfer entropy of the dependent variable
   with each individual independent variable candidate.
*/

      for (icand=0 ; icand<n_indep_vars ; icand++) { // Try all candidates
         for (i=0 ; i<ncases ; i++)
            work[i] = data[i*nvars+icand] ;

         //    Shuffle independent variable if in permutation run (irep>0)

         if (irep) {                   // If doing permuted runs, shuffle
            i = ncases ;               // Number remaining to be shuffled
            while (i > 1) {            // While at least 2 left to shuffle
               j = (int) (unifrand () * i) ;
               if (j >= i)
                  j = i - 1 ;
               dtemp = work[--i] ;
               work[i] = work[j] ;
               work[j] = dtemp ;
               }
            }

         nbins_indep = nbins ;
         partition ( ncases , work , &nbins_indep , NULL , bins_indep ) ;

         criterion = trans_ent ( ncases , nbins_indep , nbins_dep ,
                                 bins_indep , bins_dep ,
                                 0 , 1 , 1 , count , ab , bc , b ) ;

         save_info[icand] = criterion ; // We will sort this when all candidates are done
                                        
         if (irep == 0) {               // If doing original (unpermuted), save criterion
            index[icand] = icand ;      // Will need original indices when criteria are sorted
            crits[icand] = criterion ;
            mcpt_max_counts[icand] = mcpt_same_counts[icand] = mcpt_solo_counts[icand] = 1 ;  // This is >= itself so count it now
            }
         else {
            if (criterion >= crits[icand])
               ++mcpt_solo_counts[icand] ;
            }
         } // Initial list of all candidates

      if (irep == 0)  // Find the indices that sort the candidates per criterion
         qsortdsi ( 0 , n_indep_vars-1 , save_info , index ) ;

      else {
         qsortd ( 0 , n_indep_vars-1 , save_info ) ;
         for (icand=0 ; icand<n_indep_vars ; icand++) {
            if (save_info[icand] >= crits[index[icand]])
               ++mcpt_same_counts[index[icand]] ;
            if (save_info[n_indep_vars-1] >= crits[index[icand]]) // Valid only for largest
               ++mcpt_max_counts[index[icand]] ;
            }
         }

      }  // For all reps

   fprintf ( fp , "\nTransfer entropy of %s", depname);

   fprintf ( fp , "\n" ) ;
   fprintf ( fp , "\n" ) ;
   fprintf ( fp , "\nPredictors, in order of decreasing transfer entropy" ) ;
   fprintf ( fp , "\n" ) ;
   fprintf ( fp , "\n                       Variable   Information   Solo pval   Min pval   Max pval" ) ;

   for (icand=0 ; icand<n_indep_vars ; icand++) { // Do all candidates
      k = index[n_indep_vars-1-icand] ;           // Index of sorted candidate
      fprintf ( fp , "\n%31s %11.5lf %12.4lf %10.4lf %10.4lf", names[k], crits[k],
                (double) mcpt_solo_counts[k] / nreps,
                (double) mcpt_same_counts[k] / nreps,
                (double) mcpt_max_counts[k] / nreps ) ;
      }

   MEMTEXT ( "TRANSFER: Finish" ) ;
   fclose ( fp ) ;
   FREE ( work ) ;
   FREE ( crits ) ;
   FREE ( index ) ;
   FREE ( bins_indep ) ;
   FREE ( bins_dep ) ;
   FREE ( mcpt_max_counts ) ;
   FREE ( mcpt_same_counts ) ;
   FREE ( mcpt_solo_counts ) ;
   FREE ( save_info ) ;
   FREE ( count ) ;
   FREE ( ab ) ;
   FREE ( bc ) ;
   FREE ( b ) ;
   free_data ( nvars , names , data ) ;

   MEMCLOSE () ;
   printf ( "\n\nPress any key..." ) ;
   _getch () ;
   return EXIT_SUCCESS ;
}
/*--------------------------------------------------------------------------*/
int sci_mcisendstring(char *fname,unsigned long l)
{
	int m1,n1,l1;

	char *Output=NULL;
	int *BoolOutput=NULL;
	int *CodeOutput=NULL;

	CheckRhs(1,1);
    CheckLhs(1,3);

	if (GetType(1) == sci_strings)	
	{
		MCIERROR Error;
		char *MCICommand=NULL;
		char ReturnString[2048];

		GetRhsVar(1,STRING_DATATYPE,&m1,&n1,&l1);
		MCICommand=cstk(l1);

		Error=mciSendString(MCICommand,(LPSTR)ReturnString,sizeof(ReturnString),NULL);

		BoolOutput=(int*)MALLOC(sizeof(int));
		CodeOutput=(int*)MALLOC(sizeof(int));

		*BoolOutput=(int)0;
		*CodeOutput=(int)Error;
		if (Error)
		{
			char ErrorText[128];
			*BoolOutput=(int)FALSE;
			
			if ( mciGetErrorString(Error,ErrorText,sizeof(ErrorText)) == FALSE )
			{
				wsprintf(ErrorText,"%s","Unknown MCI error");
			}

			Output = strdup(ErrorText);
		}
		else
		{
			*BoolOutput=(int)TRUE;
			Output = strdup("OK");
		}

		n1=1;

		if ( Lhs == 1 )
		{
			CreateVarFromPtr(Rhs+1,MATRIX_OF_BOOLEAN_DATATYPE, &n1, &n1, &BoolOutput);
			LhsVar(1)=Rhs+1;
		}
		else
		if ( Lhs == 2 )
		{
			CreateVarFromPtr(Rhs+1,MATRIX_OF_BOOLEAN_DATATYPE, &n1, &n1, &BoolOutput);
			LhsVar(1)=Rhs+1;

			CreateVarFromPtr(Rhs+2,MATRIX_OF_INTEGER_DATATYPE, &n1, &n1, &CodeOutput);
			LhsVar(2)=Rhs+2;
		}
		else /* Lhs == 3 */
		{
			CreateVarFromPtr(Rhs+1,MATRIX_OF_BOOLEAN_DATATYPE, &n1, &n1, &BoolOutput);
			LhsVar(1)=Rhs+1;

			CreateVarFromPtr(Rhs+2,MATRIX_OF_INTEGER_DATATYPE, &n1, &n1, &CodeOutput);
			LhsVar(2)=Rhs+2;

			CreateVarFromPtr(Rhs+ 3,STRING_DATATYPE,(m1=(int)strlen(Output), &m1),&n1,&Output);
			LhsVar(3)=Rhs+3;
		}

		if (Output) {FREE(Output);Output=NULL;}
		if (BoolOutput) {FREE(BoolOutput);BoolOutput=NULL;}
		if (CodeOutput) {FREE(CodeOutput);Output=NULL;}

        PutLhsVar();

		return 0;
	}
	else
	{
		Scierror(999,_("%s: Wrong type for input argument #%d: String expected.\n"),fname,1);
		return 0;
	}
}
Example #17
0
/*--------------------------------------------------------------------------*/
double *getConvertedDateAsMatrixOfDouble(double *dDates, int nbElements, int *iErr)
{
    double *dResults = NULL;
    int lenResults = nbElements * NB_ELEMNT_ARRAY_GETDATE;
    *iErr = 1;

    dResults = (double*)MALLOC(sizeof(double) * lenResults);
    if (dResults)
    {
        int k = 0;
        int j = 0;

        int m = 0;
        int n = 0;

        double *dResTmp = NULL;

        for (k = 0; k < lenResults; k++)
        {
            dResults[k] = 0;
        }

        *iErr = 0;
        for (k = 0; k < nbElements; k++)
        {
            int iErr2 = 0;
            double *dConverted = getConvertedDateAsDoubleVector(dDates[k], &iErr2);
            if (iErr2 == 0)
            {
                int n = 0;
                for (n = 0; n < NB_ELEMNT_ARRAY_GETDATE; n++)
                {
                    dResults[j] = dConverted[n];
                    j++;
                }
                FREE(dConverted);
                dConverted = NULL;
            }
            else
            {
                FREE(dResults);
                FREE(dConverted);
                dResults = NULL;
                *iErr = iErr2;
                return NULL;
            }
        }

        m = nbElements;
        n = NB_ELEMNT_ARRAY_GETDATE;
        dResTmp = transposeMatrixDouble(n, m, dResults);
        if (dResTmp)
        {
            FREE(dResults);
            dResults = dResTmp;
            *iErr = 0;
        }
        else
        {
            *iErr = 1;
        }

    }
    return dResults;
}
Example #18
0
int main(int argc, char **argv)
{
    /* SOLVER choice:   1  pcg
                        2  sbcg
                        3  bcg
                        4  sqmr
                        8  gmres
                        9  fgmres */
    integer SOLVER=4; /* sqmr */

    CSRMAT A, ilutmat;
    AMGLEVELMAT PRE, *next;
    integer nlev=0, nprev, nB;
    integer (*perm0)(),(*perm)(),(*permf)();

    FILE *fp, *fo; 
    char rhstyp[3], title[73], key[9], type[3], fname[100], foname[100];
    char line[MAX_LINE], *tmpstring, timeout[7], residout[7];
    integer  i,j,k,m,fnamelen,n,nc,nz,nrhs,mynrhs=2,tmp0,tmp,tmp2,tmp3,ierr,flag,
         *invperm, *buff, *ws, *symmmd,flags,elbow,max_it,ipar[20],
         nrhsix, *rhsptr, *rhsind, sumit;
    REALS eps, DROP_TOL, CONDEST,condest,droptols[2],restol, val,vb;
    FLOAT *rhs,*sol,*w, *scale, *rhsval, *dbuff;
    float  systime, time_start,   time_stop,   secnds, secndsprep,
           timeAx_start, timeAx_stop, secndsAx, sumtime;
    integer ELBOW, nnzU, l, nAx;
    ILUPACKPARAM param;
    size_t  nibuff, ndbuff;
     
    /* the last argument passed serves as file name */
    if (argc!=5) {
      printf("usage '%s <drop tol.> <bound for L^{-1},U^{-1}> <elbow space> <matrix>'\n",argv[0]);
       exit(0);
    }
    i=0;
    while (argv[argc-1][i]!='\0')
    {
          fname[i]=argv[argc-1][i];
          i++;
    } /* end while */
    fname[i]='\0';
    fnamelen=i;
    while (i>=0 && fname[i]!='/')
          i--;
    i++;
    j=0;
    while (i<fnamelen && fname[i]!='.')
          foname[j++]=fname[i++];
    while (j<16)
          foname[j++]=' ';
    foname[j]='\0';

    ELBOW=atoi(argv[argc-2]);
    CONDEST=atof(argv[argc-3]);
    DROP_TOL=atof(argv[argc-4]);

    /* read in a symmetric matrix in Harwell-Boeing format. 
       By definition Harwell-Boeing format stores a matrix in compressed sparse
       COLUMN format. In the symmetric case this is equivalent to compressed 
       sparse ROW format which ILUPACK uses. 
       Note that only the upper triangular part is stored by rows.
                                 / 3.5 -1.0  0 \
       A symm. pos. def. matrix  |-1.0  2.0  0 | is stored as follows
                                 \  0    0  1.5/ 

       A.ia:   1  3  4  5           pointer to the start of every compressed 
                                    upper triangular row plus pointer to the
				    first space behind the compressed rows

       A.ja:   1    2    2    3     nonzero column indices

       A.a:   3.5 -1.0  2.0  1.5    nonzero numerical values

       The read part finally yields the following data structures
        -  A:  matrix in compressed sparse row format
	    o  A.nr, A.nc: number of rows and columns of A
            o  A.ia:  pointer array
            o  A.ja:  nonzero column index array 
	    o  A.a:   nonzero numerical values
	-  rhs:  right hand side(s) and additional data like exact solution
	         or initial guess
	-  n:  same as A.nr,A.nc
	-  nz:  number of nonzero entries
     */
#include "spdreadmatrix.c"

    
    // if right hand sides are provided, then run AMGSOLVER for any of these
    // right hand sides. Otherwise use own set of right hand sides

    // allocate memory for the solution vector and some buffer
    sol  =(FLOAT *) MALLOC(mynrhs*(size_t)n*sizeof(FLOAT), "mainspd:sol");
    dbuff=(FLOAT *) MALLOC(3*(size_t)n*sizeof(FLOAT),      "mainspd:dbuff");
    ndbuff=3*(size_t)n;


    // set parameters to the default settings
    MYSYMAMGINIT(A, &param);
    param.dbuff=dbuff;
    param.ndbuff=ndbuff;
    
    // select reordering functions
    perm0=SYMPERMNULL;
    perm =SYMPERMNULL;
    permf=SYMPERMNULL;
#ifdef MINIMUM_DEGREE
    perm0=SYMPERMMMD;
    perm =SYMPERMMMD;
    permf=SYMPERMMMD;
    fprintf(fo,"mmds/mmds|");
#elif defined REVERSE_CM
    perm0=SYMPERMRCM;
    perm =SYMPERMRCM;
    permf=SYMPERMRCM;
    fprintf(fo,"rcms/rcms|");
#elif defined NESTED_DISSECTION
    perm0=SYMPERMND;
    perm =SYMPERMND;
    permf=SYMPERMND;
    fprintf(fo,"nds /nds |");
#elif defined IND_SET
    perm0=SYMPERMINDSET;
    perm =SYMPERMINDSET;
    permf=SYMPERMINDSET;
    fprintf(fo,"inds/inds|");
#elif defined AMF
    perm0=SYMPERMAMF;
    perm =SYMPERMAMF;
    permf=SYMPERMAMF;
    fprintf(fo,"amfs/amfs|");
#elif defined AMD
    perm0=SYMPERMAMD;
    perm =SYMPERMAMD;
    permf=SYMPERMAMD;
    fprintf(fo,"amds/amds|");
#elif defined PP_PERM
    perm0=SPDPERMPP;
    perm =SPDPERMPP;
    permf=SPDPERMPP;
    fprintf(fo,"PPs /PPs |");
#elif defined MMD_PP
    perm0=SYMPERMMMD;
    perm =SYMPERMMMD;
    permf=SPDPERMPP;
    fprintf(fo,"mmds/PPs |");
#elif defined AMF_PP
    perm0=SYMPERMAMF;
    perm =SYMPERMAMF;
    permf=SPDPERMPP;
    fprintf(fo,"amfs/PPs |");
#elif defined AMD_PP
    perm0=SYMPERMAMD;
    perm =SYMPERMAMD;
    permf=SPDPERMPP;
    fprintf(fo,"amds/PPs |");
#elif defined RCM_PP
    perm0=SYMPERMRCM;
    perm =SYMPERMRCM;
    permf=SPDPERMPP;
    fprintf(fo,"rcms/PPs |");
#elif defined FC_PP
    perm0=SYMPERMFC;
    perm =SYMPERMFC;
    permf=SPDPERMPP;
    fprintf(fo,"FCs /PPs |");
#elif defined METIS_E_PP
    perm0=SYMPERMMETISE;
    perm =SYMPERMMETISE;
    permf=SPDPERMPP;
    fprintf(fo,"mes /PQs |");
#elif defined METIS_N_PP
    perm0=SYMPERMMETISN;
    perm =SYMPERMMETISN;
    permf=SPDPERMPP;
    fprintf(fo,"mns /PPs |");
#elif defined SMWM_MMD_PP
    perm0=PERMSMWMMMD;
    perm =PERMSMWMMMD;
    permf=SPDPERMPP;
    fprintf(fo,"mwmd/PPs |");
#elif defined SMWM_AMF_PP
    perm0=PERMSMWMAMF;
    perm =PERMSMWMAMF;
    permf=SPDPERMPP;
    fprintf(fo,"mwaf/PPs |");
#elif defined SMWM_AMD_PP
    perm0=PERMSMWMAMD;
    perm =PERMSMWMAMD;
    permf=SPDPERMPP;
    fprintf(fo,"mwad/PPs |");
#elif defined SMWM_RCM_PP
    perm0=PERMSMWMRCM;
    perm =PERMSMWMRCM;
    permf=SPDPERMPP;
    fprintf(fo,"mwrc/PPs |");
#elif defined SMWM_METIS_E_PP
    perm0=PERMSMWMMETISE;
    perm =PERMSMWMMETISE;
    permf=SPDPERMPP;
    fprintf(fo,"mwme/PQs |");
#elif defined SMWM_METIS_N_PP
    perm0=PERMSMWMMETISN;
    perm =PERMSMWMMETISN;
    permf=SPDPERMPP;
    fprintf(fo,"mwmn/PPs |");
#elif defined SMC64_MMD_PP
    perm0=PERMSMC64MMD;
    perm =PERMSMC64MMD;
    permf=SPDPERMPP;
    fprintf(fo,"mc64md/PP|");
#elif defined SMC64_AMF_PP
    perm0=PERMSMC64AMF;
    perm =PERMSMC64AMF;
    permf=SPDPERMPP;
    fprintf(fo,"mc64af/PP|");
#elif defined SMC64_AMD_PP
    perm0=PERMSMC64AMD;
    perm =PERMSMC64AMD;
    permf=SPDPERMPP;
    fprintf(fo,"mc64ad/PP|");
#elif defined SMC64_RCM_PP
    perm0=PERMSMC64RCM;
    perm =PERMSMC64RCM;
    permf=SPDPERMPP;
    fprintf(fo,"mc64rc/PP|");
#elif defined SMC64_METIS_E_PP
    perm0=PERMSMC64METISE;
    perm =PERMSMC64METISE;
    permf=SPDPERMPP;
    fprintf(fo,"mc64me/PP|");
#elif defined SMC64_METIS_N_PP
    perm0=PERMSMC64METISN;
    perm =PERMSMC64METISN;
    permf=SPDPERMPP;
    fprintf(fo,"mc64mn/PP|");
#elif defined FC_SMWM_METIS_E
    perm0=SYMPERMFC;
    perm =SYMPERMFC;
    permf=PERMSMWMMETISE;
    fprintf(fo,"fc/mwme|");
#elif defined FC_SMWM_METIS_N
    perm0=SYMPERMFC;
    perm =SYMPERMFC;
    permf=PERMSMWMMETISN;
    fprintf(fo,"fc/mwmn|");
#elif defined FC_SMWM_AMD
    perm0=SYMPERMFC;
    perm =SYMPERMFC;
    permf=PERMSMWMAMD;
    fprintf(fo,"fc/mwad|");
#elif defined FC_SMWM_AMF
    perm0=SYMPERMFC;
    perm =SYMPERMFC;
    permf=PERMSMWMAMF;
    fprintf(fo,"fc/mwaf|");
#elif defined FC_SMWM_MMD
    perm0=SYMPERMFC;
    perm =SYMPERMFC;
    permf=PERMSMWMMMD;
    fprintf(fo,"fc/mwmd|");
#elif defined FC_SMWM_RCM
    perm0=SYMPERMFC;
    perm =SYMPERMFC;
    permf=PERMSMWMRCM;
    fprintf(fo,"fc/mwrc|");
#else
    fprintf(fo,"    /    |");
#endif



    // modify the default settings
    MYSYMAMGGETPARAMS(param, &flags, &elbow, droptols, &condest,
		      &restol, &max_it);

    // ONLY for mixed reordering strategies it is useful to
    // set the 'FINAL_PIVOTING' flag
#if !defined RCM_PP && !defined AMF_PP && !defined AMD_PP && !defined MMD_PP && !defined FC_PP && !defined METIS_E_PP && !defined METIS_N_PP && !defined FC_SMWM_METIS_N && !defined FC_SMWM_METIS_E && !defined FC_SMWM_AMD  && !defined FC_SMWM_AMF && !defined FC_SMWM_MMD && !defined FC_SMWM_RCM 
    flags&=~FINAL_PIVOTING;
#endif
    // change flags if mpiluc is desired
#ifdef USE_MPILUC
    flags|=MULTI_PILUC;
#endif

    // overwrite the default drop tolerances
    droptols[1]=DROP_TOL; 

    // choose the iterative solver, default: 8 (GMRES)
    param.ipar[5]=SOLVER;

    // overwrite the default value for elbow space
    elbow=ELBOW;

    // overwrite default values for condest
    condest=CONDEST;

    // overwrite the default value for the residual norm
    // restol=1e-8;

    // turn of scaling
    // param.ipar[7]&=~(3+24+192);
    // param.ipar[8]&=~((1+32+1024)*4);
    // param.ipar[8]|=((1+32+1024)*5);

    // use Standard Schur-complement
    //flags|=TISMENETSKY_SC;
    //flags&=~SIMPLE_SC;

    // turn off aggressive dropping
    flags&=~AGGRESSIVE_DROPPING;

    // do not discard matrix entries on an early stage
    // flags&=~DISCARD_MATRIX;

    // rewrite the updated parameters
    MYSYMAMGSETPARAMS(A, &param, flags, elbow, droptols, condest,
		      restol, max_it);

    // manually change the drop tolerance for the approximate Schur complement
    // param.fpar[8]=DROP_TOL;


    // print some messages that give information about flags and reorderings
#include "symmessages.c"
       
    evaluate_time(&time_start,&systime);
    ierr=MYSYMAMGFACTOR(&A, &PRE, &nlev, &param, perm0,perm, permf);


    // convert matrix to postive definite preconditioner
    SYMSPDCONVERT(&PRE, nlev);

    // update buffer size
    nibuff=param.nibuff;
    ndbuff=param.ndbuff;
    evaluate_time(&time_stop,&systime);
    secnds=time_stop-time_start;
   

    switch (ierr)
    {
           case  0: /* perfect! */
	            break;
           case -1: /* Error. input matrix may be wrong.
                       (The elimination process has generated a
			row in L or U whose length is .gt.  n.) */
	            printf("Error. input matrix may be wrong at level %d\n",nlev);
		    fprintf(fo,"input matrix may be wrong\n");fclose(fo); 
		    break;
           case -2: /* The matrix L overflows the array alu */
	            printf("The matrix L overflows the array alu at level %d\n",nlev);
		    fprintf(fo,"out of memory\n");fclose(fo); 
		    break;
           case -3: /* The matrix U overflows the array alu */
	            printf("The matrix U overflows the array alu at level %d\n",nlev);
		    fprintf(fo,"out of memory\n");fclose(fo); 
		    break;
           case -4: /* Illegal value for lfil */
	            printf("Illegal value for lfil at level %d\n",nlev);
		    fprintf(fo,"Illegal value for lfil\n");fclose(fo); 
		    break;
           case -5: /* zero row encountered */
	            printf("zero row encountered at level %d\n",nlev);
		    fprintf(fo,"zero row encountered\n");fclose(fo); 
		    break;
           case -6: /* zero column encountered */
	            printf("zero column encountered at level %d\n",nlev);
		    fprintf(fo,"zero column encountered\n");fclose(fo); 
		    break;
           case -7: /* buffers too small */
	            printf("buffers are too small\n");
		    // This error message would not be necessary if AMGsetup is
		    // called with the correct values of nibuff, ndbuff
		    printf("increase buffer size to at least %ld (float), %ld (integer)\n",
			   ndbuff, nibuff);
		    fflush(stdout);
		    fprintf(fo,"buffers are too small\n");fclose(fo); 
           default: /* zero pivot encountered at step number ierr */
	            printf("zero pivot encountered at step number %d of level %d\n",ierr,nlev);
		    fprintf(fo,"zero pivot encountered\n");fclose(fo); 
		    break;
    } /* end switch */
    if (ierr) {
       fprintf(fo,"Iterative solver(s) cannot be applied\n");
       fflush(fo);
       exit(ierr);
    }


#ifdef PRINT_INFO
    next=&PRE;
    for (i=1; i<=nlev; i++) {
        // fill-in LU
        printf("level %3d, block size %7d\n",i,next->LU.nr); fflush(stdout);
	if (i<nlev || next->LU.ja!=NULL) {
	  printf("U-factor");
	  printf("\n");fflush(stdout);
	  for (l=0; l<next->LU.nr; ) {
	    if (next->LU.ja[next->LU.nr+1+l]==0){
	      for (j=next->LU.ja[l];j<next->LU.ja[l+1]; j++) {
		printf("%8d",next->LU.ja[j-1]);
	      }
	      printf("\n");fflush(stdout);
	      for (j=next->LU.ja[l];j<next->LU.ja[l+1]; j++) {
		printf("%8.1le",next->LU.a[j-1]);
	      }
	      l++;
	    }
	    else {
	      for (j=next->LU.ja[l];j<next->LU.ja[l+1]; j++) {
		printf("%8d",next->LU.ja[j-1]);
	      }
	      printf("\n");fflush(stdout);
	      for (j=next->LU.ja[l];j<next->LU.ja[l+1]; j++) {
		printf("%8.1le",next->LU.a[next->LU.ja[l]+2*(j-next->LU.ja[l])-1]);
	      }
	      printf("\n");fflush(stdout);
	      for (j=next->LU.ja[l];j<next->LU.ja[l+1]; j++) {
		printf("%8.1le",next->LU.a[next->LU.ja[l]+2*(j-next->LU.ja[l])]);
	      }
	      l+=2;
	    }
	    printf("\n");fflush(stdout);
	  }

	  printf("Block diagonal factor\n");
	  for (l=0; l<next->LU.nr;) {
	    if (next->LU.ja[next->LU.nr+1+l]==0){
	      printf("%8.1le",next->LU.a[l]);
	      l++;
	    }
	    else {
	      printf("%8.1le%8.1le",next->LU.a[l],next->LU.a[next->LU.nr+1+l]);
	      l+=2;
	    }
	  }
	  printf("\n");fflush(stdout);
	  for (l=0; l<next->LU.nr; ) {
	    if (next->LU.ja[next->LU.nr+1+l]==0) {
	      printf("        ");
	      l++;
	    }
	    else {
	      printf("%8.1le%8.1le",next->LU.a[next->LU.nr+1+l],next->LU.a[l+1]);
	      l+=2;
	    }
	  }
	  printf("\n");fflush(stdout);



	}
	if (i==nlev) {
	   if (next->LU.ja==NULL) {
	      printf("switched to full matrix processing\n");fflush(STDOUT);
	   }
	}

	if (i<nlev) {
	   // fill-in F
	   nnzU+=next->F.ia[next->F.nr]-1;
	   printf("level %3d->%3d, block size (%7d,%7d)\n",i,i+1,next->LU.nr,next->F.nc);
	   printf("  local fill-in F %7d(%5.1lfav pr)\n",
		  next->F.ia[next->F.nr]-1,(1.0*(next->F.ia[next->F.nr]-1))/next->LU.nr);
	}
	next=next->next;
    }
#endif



    // print some statistics about the levels, their size and the 
    // computation time
#include "symprintperformance.c"



    /* some decisions about the right hand side, the exact solution and the 
       initial guess

       - if a right hand side is provided, then solve the system according
         to this given right hand side.
	 Otherwise set x=(1,...,1)^T and use b=Ax as right hand side
	 --> rhs

       - if an initial guess is provided, then use this as starting vector.
         Otherwise use x=0 as initial guess
	 --> sol
       
       - for statistics also compute the norm of the initial residual --> val
    */
    sumtime=0.0;
    sumit=0;
    for (l=0; l<mynrhs; l++) {
#include "syminitvectors.c"


        evaluate_time(&time_start,&systime);
	ierr=MYSYMAMGSOLVER(&A, &PRE, nlev, &param, rhs+A.nr*l, sol+A.nr*l);
	evaluate_time(&time_stop,&systime);
	secnds=time_stop-time_start;

	// why did the iterative solver stop?
	switch (ierr) {
	case  0:  // everything is fine
	      sumtime+=ILUPACK_secnds[5];
	      sumit+=param.ipar[26];
	      if (l==mynrhs-1) {
		 sumtime/=mynrhs;
		 sumit   =sumit/((double)mynrhs)+.5;
		 fprintf(fo,"%7.1le|",(double)sumtime);
		 fprintf(fo," %3d|",sumit);
		 fprintf(fo,"%7.1le\n",(double)sumtime+ILUPACK_secnds[7]);
	      }
	      break;
	case -1:  // too many iterations
	      printf("number of iteration steps exceeds its limit\n");
	      fprintf(fo,"  inf  |");
	      fprintf(fo," inf|");
	      fprintf(fo,"  inf  \n");
	      break;
	case -2:  /* not enough work space */
              printf("not enough work space provided\n");
	      break;
	case -3:  /* not enough work space */
	      printf("algorithm breaks down ");
	      printf("\n");
	      fprintf(fo,"  NaN  |");
	      fprintf(fo," NaN|");
	      fprintf(fo,"  NaN  \n");
	      break;
	default:  /* unknown */
              printf("solver exited with error code %d\n",ierr);
	} // end switch 
	fflush(fo);

	// stop if necessary
	if (ierr)
	   mynrhs=l;

	printf("%3d. right hand side\n",l+1);
	printf("number of iteration steps: %d\n",param.ipar[26]);
	printf("time: %8.1le [sec]\n",  (double)secnds);
	printf("      %8.1le [sec]\n\n",(double)ILUPACK_secnds[5]); 
       
	printf("time matrix-vector multiplication: %8.1le [sec]\n",ILUPACK_secnds[6]);

	printf("residual norms:\n");
	printf("initial: %8.1le\n",val);
	printf("target:  %8.1le\n",param.fpar[23]);


	/* some final statistics 
	   - about the true current residual of the computed solution and
	   - the relative error in the solution though the exact solution is known
	*/
#include "symfinalres.c"
    } // end for l
    fclose(fo);


    // outputfile name, add ".sol" extension
    i=fnamelen;
    j=-1;
    while (j) {
          i--;
	  if (i<0)
	    j=0;
	  if (fname[i]=='.')
	    j=0;
    }
    fname[++i]='s';
    fname[++i]='o';
    fname[++i]='l';
    i++;
    j=i;
    while (i<100)
      fname[i++]='\0';

    WRITEVECTORS(fname,sol,&(A.nr),&mynrhs,
		 "solution vectors computed by ILUPACK                                    ",
		 "sol     ",
		 j, 72, 8);

    /*
      // sample code for rereading the vectors from C
      READVECTORS(fname,sol,&(A.nr),&mynrhs,title,key,j, 72, 8);
      title[72]='\0';
      key[8]='\0';
    */

    
    // finally release memory of the preconditioner
    MYSYMAMGDELETE(A,PRE,nlev,&param);

    // release memory used for the input matrix
    free(A.ia);
    free(A.ja);
    free(A.a );
    free(rhs );
} /* end mainsym */
Example #19
0
void process()
{
  clear_results_message();

  child_params_t *cp = MALLOC(sizeof(child_params_t));
  strcpy(cp->in_file, get_string_from_entry("input_file_entry"));

  char *odir = get_string_from_entry("output_directory_entry");
  char *ofile = get_string_from_entry("output_file_entry");

  if (strlen(odir) > 0) {
#ifdef win32
    if (odir[strlen(odir)-1]=='/' || odir[strlen(odir)-1]=='\\')
#else
    if (odir[strlen(odir)-1]=='/')
#endif
      sprintf(cp->out_file, "%s%s", odir, ofile);
    else
      sprintf(cp->out_file, "%s/%s", odir, ofile);
  }
  else {
    strcpy(cp->out_file, ofile);
  }

  if (strlen(cp->in_file)==0) {
    message_box("No input file specified!");
    free(cp);
    return;
  }
  else if (strlen(cp->out_file)==0) {
    message_box("No output file selected!");
    free(cp);
    return;
  }
  else if (!fileExists(cp->in_file)) {
    message_box("Input file \"%s\" not found!", cp->in_file);
    free(cp);
    return;
  }

  int input_format = get_combo_box_item("input_format_combobox");
  int output_format = get_combo_box_item("output_format_combobox");

  if (input_format==INPUT_AUTO) {
    select_defaults_by_file_type(cp->in_file, FALSE);
    input_format = get_combo_box_item("input_format_combobox");
    if (input_format==INPUT_AUTO) {
      message_box("Can't figure out which type of data this is.\n"
                  "Please select the input format manually.");
      free(cp);
      return;
    }
  }

  strcpy(cp->in_format, input_format_to_str(input_format));
  strcpy(cp->out_format, output_format_to_str(output_format));
  char *logFile = appendExt(cp->out_file, ".log");

#ifdef win32
    STARTUPINFO si;
    PROCESS_INFORMATION pi;

    memset(&si, 0, sizeof(si));
    memset(&pi, 0, sizeof(pi));
    si.cb = sizeof(si);
    
    char *cmd = MALLOC(sizeof(char)*
        (strlen(cp->in_file) + strlen(cp->out_file) + strlen(get_asf_bin_dir_win()) + 512));
    sprintf(cmd,
        "\"%s/convert2vector.exe\" "
        "-log \"%s\" "
        "-input-format %s -output-format %s \"%s\" \"%s\"",
        get_asf_bin_dir_win(),
        logFile,
        cp->in_format, cp->out_format, cp->in_file, cp->out_file);

    // clear out any previously existing log file
    fLog = fopen(logFile, "a");
    FCLOSE(fLog);

    if (!CreateProcess(NULL, cmd, NULL, NULL, FALSE, 0, NULL, NULL, &si, &pi))
    {
        DWORD dw = GetLastError();
        //printf( "CreateProcess failed (%ld)\n", dw );

        LPVOID lpMsgBuf;
        FormatMessage(
          FORMAT_MESSAGE_ALLOCATE_BUFFER |
          FORMAT_MESSAGE_FROM_SYSTEM |
          FORMAT_MESSAGE_IGNORE_INSERTS,
          NULL,
          dw,
          MAKELANGID(LANG_NEUTRAL,SUBLANG_DEFAULT),
          (LPTSTR)&lpMsgBuf,
          0,
          NULL);

        printf("CreateProcess() failed with error %ld: %s\n",
            dw, (char*)lpMsgBuf);
        printf("Failed command: %s\n", cmd);
    }

    DWORD dwWaitResult;

    // now wait for process to finish
    do {
        while (gtk_events_pending())
            gtk_main_iteration();
        dwWaitResult = WaitForSingleObject(pi.hProcess, 50);
    }
    while (dwWaitResult == WAIT_TIMEOUT);
#else
  asfFork(child_func, (void*)cp, parent_func, NULL);
#endif

  char message[1024];
  strcpy(message, "-");

  int success=FALSE;
  FILE *lfp = fopen(logFile, "r");
  if (!lfp) {
    sprintf(message, "Error Opening Log File '%s': %s\n",
            logFile, strerror(errno));
  }
  else {
    char *output = NULL;
    char line[1024];
    while (fgets(line, 1024, lfp)) {
      if (output) {
        output = realloc(output, sizeof(char)*(strlen(output)+strlen(line)+1));
        strcat(output, line);
      }
      else {
        output = malloc(sizeof(char)*(strlen(line)+1));
        strcpy(output, line);
      }
    }
    fclose(lfp);
    //unlink(logFile);

    char *p = output, *q;
    while (p) {
      q = strchr(p+1, '\n');
      if (q) {
        *q = '\0';
        if (strstr(p, "Error")!=NULL || strstr(p, "ERROR")!=NULL) {
          *q = '\n';
          int i,n = 0;
          do {
            p = q + 1;
            q = strchr(p, '\n') - 1;
            while (isspace(*q)) --q;
            if (q - p > 2) {
              // First 220 characters of the error string, unless line ends
              // first.  Don't cut off in the middle of a word, though
              strcpy(message, "Error: ");
              strncat(message, p, 220);
              while (isalnum(message[strlen(message)-1]))
                message[strlen(message)-1] = '\0';
              for (n=0; n<strlen(message); ++n)
                if (message[n] == '\n' || message[n] == '*') message[n] = ' ';
              int eating=FALSE;
              for (n=0,i=0; n<strlen(message); ++n) {
                if (isspace(message[n])) {
                  if (!eating) {
                    eating=TRUE;
                    message[i++] = message[n];
                  }
                } else {
                  eating=FALSE;
                  message[i++] = message[n];
                }
              }
              message[i]='\0';
              char *eoe = strstr(message, "End of error");
              if (eoe)
                *eoe = '\0';
              else if (strlen(message)>200)
                strcat(message, " ...");
              break;
            }
          }
          while (*p != '*' && ++n<5); // * flags the end of the error message
        }

        if (strstr(p,"Successful completion!") != NULL) {
          strcpy(message, "Processed successfully!");
          success=TRUE;
          break;
        }

        *q = '\n';
      }
      p=q;
    }

    if (strlen(message)==0) {
      // Did not find an error message, or the success message!
      // So, assume there was an error, but we don't know why
      strcpy(message, "Processing failed!");
    }

    FREE(output);
  }

  int open_output = get_checked("open_output_checkbutton");
  if (!success) open_output = FALSE;

  put_string_to_label("result_label", message);
  asfPrintStatus(message);
  asfPrintStatus("\n\nDone.\n\n");

  if (open_output) {
    switch (output_format) {
      case OUTPUT_KML:
        open_in_google_earth(cp->out_file);
        break;
      case OUTPUT_ALOS_CSV:
        open_in_excel(cp->out_file);
      default:
        // do nothing, output type has no natural associated app
        break;
    }
  }

  free(cp);
}
Example #20
0
static void eventpool_execute(uv_async_t *handle) {
	/*
	 * Make sure we execute in the main thread
	 */
	const uv_thread_t pth_cur_id = uv_thread_self();
	assert(uv_thread_equal(&pth_main_id, &pth_cur_id));

	struct threadpool_tasks_t **node = NULL;
	int nrlisteners1[REASON_END] = {0};
	int nr1 = 0, nrnodes = 16, nrnodes1 = 0, i = 0;

	if((node = MALLOC(sizeof(struct threadpool_tasks_t *)*nrnodes)) == NULL) {
		OUT_OF_MEMORY /*LCOV_EXCL_LINE*/
	}

	uv_mutex_lock(&listeners_lock);

	struct eventqueue_t *queue = NULL;
	while(eventqueue) {
		queue = eventqueue;
		uv_sem_t *ref = NULL;

#ifdef _WIN32
		if((nr1 = InterlockedExchangeAdd(&nrlisteners[queue->reason], 0)) == 0) {
#else
		if((nr1 = __sync_add_and_fetch(&nrlisteners[queue->reason], 0)) == 0) {
#endif
			if(queue->done != NULL) {
				queue->done((void *)queue->data);
			}
		} else {
			if(threads == EVENTPOOL_THREADED) {
				if((ref = MALLOC(sizeof(uv_sem_t))) == NULL) {
					OUT_OF_MEMORY /*LCOV_EXCL_LINE*/
				}
				uv_sem_init(ref, nr1-1);
			}

			struct eventpool_listener_t *listeners = eventpool_listeners;
			if(listeners == NULL) {
				if(queue->done != NULL) {
					queue->done((void *)queue->data);
				}
			}

			while(listeners) {
				if(listeners->reason == queue->reason) {
					if(nrnodes1 == nrnodes) {
						nrnodes *= 2;
						/*LCOV_EXCL_START*/
						if((node = REALLOC(node, sizeof(struct threadpool_tasks_t *)*nrnodes)) == NULL) {
							OUT_OF_MEMORY
						}
						/*LCOV_EXCL_STOP*/
					}
					if((node[nrnodes1] = MALLOC(sizeof(struct threadpool_tasks_t))) == NULL) {
						OUT_OF_MEMORY /*LCOV_EXCL_LINE*/
					}
					node[nrnodes1]->func = listeners->func;
					node[nrnodes1]->userdata = queue->data;
					node[nrnodes1]->done = queue->done;
					node[nrnodes1]->ref = ref;
					node[nrnodes1]->reason = listeners->reason;
					nrnodes1++;
					if(threads == EVENTPOOL_THREADED) {
						nrlisteners1[queue->reason]++;
					}
				}
				listeners = listeners->next;
			}
		}
		eventqueue = eventqueue->next;
		FREE(queue);
	}
	uv_mutex_unlock(&listeners_lock);

	if(nrnodes1 > 0) {
		for(i=0;i<nrnodes1;i++) {
			if(threads == EVENTPOOL_NO_THREADS) {
				nrlisteners1[node[i]->reason]++;
				node[i]->func(node[i]->reason, node[i]->userdata);

#ifdef _WIN32
				if(nrlisteners1[node[i]->reason] == InterlockedExchangeAdd(&nrlisteners[node[i]->reason], 0)) {
#else
				if(nrlisteners1[node[i]->reason] == __sync_add_and_fetch(&nrlisteners[node[i]->reason], 0)) {
#endif
					if(node[i]->done != NULL) {
						node[i]->done((void *)node[i]->userdata);
					}
					nrlisteners1[node[i]->reason] = 0;
				}
			} else {
				struct threadpool_data_t *tpdata = NULL;
				tpdata = MALLOC(sizeof(struct threadpool_data_t));
				if(tpdata == NULL) {
					OUT_OF_MEMORY /*LCOV_EXCL_LINE*/
				}
				tpdata->userdata = node[i]->userdata;
				tpdata->func = node[i]->func;
				tpdata->done = node[i]->done;
				tpdata->ref = node[i]->ref;
				tpdata->reason = node[i]->reason;
				tpdata->priority = reasons[node[i]->reason].priority;

				uv_work_t *tp_work_req = MALLOC(sizeof(uv_work_t));
				if(tp_work_req == NULL) {
					OUT_OF_MEMORY /*LCOV_EXCL_LINE*/
				}
				tp_work_req->data = tpdata;
				if(uv_queue_work(uv_default_loop(), tp_work_req, reasons[node[i]->reason].reason, fib, fib_free) < 0) {
					if(node[i]->done != NULL) {
						node[i]->done((void *)node[i]->userdata);
					}
					FREE(tpdata);
					FREE(node[i]->ref);
				}
			}
			FREE(node[i]);
		}
	}
	for(i=0;i<REASON_END;i++) {
		nrlisteners1[i] = 0;
	}
	FREE(node);
	uv_mutex_lock(&listeners_lock);
	if(eventqueue != NULL) {
		uv_async_send(async_req);
	}
	uv_mutex_unlock(&listeners_lock);
}
Example #21
0
/*{{{ main() */
int
main (int argc, char *argv[])
{
  int i;
  char *val, **cmd_argv = NULL;
  /* "WINDOWID=\0" = 10 chars, UINT_MAX = 10 chars */
  static char windowid_string[20], *display_string;

  for (i = 0; i < argc; i++)
    {
      if (!strcmp (argv[i], "-e"))
	{
	  argc = i;
	  argv[argc] = NULL;
	  if (argv[argc + 1] != NULL)
	    {
	      cmd_argv = (argv + argc + 1);
	      if (cmd_argv[0] != NULL)
		rs_iconName = rs_title = my_basename (cmd_argv[0]);
	    }
	  break;
	}
    }

  rs_name = my_basename (argv[0]);

  /*
   * Open display, get options/resources and create the window
   */
  if ((display_name = getenv ("DISPLAY")) == NULL)
    display_name = ":0";

  get_options (argc, argv);

  Xdisplay = XOpenDisplay (display_name);
  if (!Xdisplay)
    {
      print_error ("can't open display %s", display_name);
      exit (EXIT_FAILURE);
    }
  extract_resources (Xdisplay, rs_name);

  /*
   * set any defaults not already set
   */
  if (!rs_title)
    rs_title = rs_name;
  if (!rs_iconName)
    rs_iconName = rs_name;
  if (!rs_saveLines || (TermWin.saveLines = atoi (rs_saveLines)) < 0)
    TermWin.saveLines = SAVELINES;

  /* no point having a scrollbar without having any scrollback! */
  if (!TermWin.saveLines)
    Options &= ~Opt_scrollBar;

#ifdef PRINTPIPE
  if (!rs_print_pipe)
    rs_print_pipe = PRINTPIPE;
#endif
  if (!rs_cutchars)
    rs_cutchars = CUTCHARS;

#ifndef NO_BOLDFONT
  if (rs_font[0] == NULL && rs_boldFont != NULL)
    {
      rs_font[0] = rs_boldFont;
      rs_boldFont = NULL;
    }
#endif
  for (i = 0; i < NFONTS; i++)
    {
      if (!rs_font[i])
	rs_font[i] = def_fontName[i];
#ifdef KANJI
      if (!rs_kfont[i])
	rs_kfont[i] = def_kfontName[i];
#endif
    }

#ifdef XTERM_REVERSE_VIDEO
  /* this is how xterm implements reverseVideo */
  if (Options & Opt_reverseVideo)
    {
      if (!rs_color[fgColor])
	rs_color[fgColor] = def_colorName[bgColor];
      if (!rs_color[bgColor])
	rs_color[bgColor] = def_colorName[fgColor];
    }
#endif

  for (i = 0; i < NRS_COLORS; i++)
    if (!rs_color[i])
      rs_color[i] = def_colorName[i];

#ifndef XTERM_REVERSE_VIDEO
  /* this is how we implement reverseVideo */
  if (Options & Opt_reverseVideo)
    {
      const char *name;
      /* swap foreground/background colors */

      name = rs_color[fgColor];
      rs_color[fgColor] = rs_color[bgColor];
      rs_color[bgColor] = name;

      name = def_colorName[fgColor];
      def_colorName[fgColor] = def_colorName[bgColor];
      def_colorName[bgColor] = name;
    }
#endif

  /* convenient aliases for setting fg/bg to colors */
  color_aliases (fgColor);
  color_aliases (bgColor);
#ifndef NO_CURSORCOLOR
  color_aliases (cursorColor);
  color_aliases (cursorColor2);
#endif /* NO_CURSORCOLOR */
#ifndef NO_BOLDUNDERLINE
  color_aliases (colorBD);
  color_aliases (colorUL);
#endif /* NO_BOLDUNDERLINE */

  Create_Windows (argc, argv);
  scr_reset ();			/* initialize screen */
  Gr_reset ();			/* reset graphics */

  /* add scrollBar, do it directly to avoid resize() */
  scrollbar_mapping (Options & Opt_scrollBar);

#ifdef DEBUG_X
  XSynchronize (Xdisplay, True);
  XSetErrorHandler ((XErrorHandler) abort);
#else
  XSetErrorHandler ((XErrorHandler) xerror_handler);
#endif

#ifdef DISPLAY_IS_IP
  /* Fixup display_name for export over pty to any interested terminal
   * clients via "ESC[7n" (e.g. shells).  Note we use the pure IP number
   * (for the first non-loopback interface) that we get from
   * network_display().  This is more "name-resolution-portable", if you
   * will, and probably allows for faster x-client startup if your name
   * server is beyond a slow link or overloaded at client startup.  Of
   * course that only helps the shell's child processes, not us.
   *
   * Giving out the display_name also affords a potential security hole
   */
  val = display_name = network_display (display_name);
  if (val == NULL)
#endif /* DISPLAY_IS_IP */
    val = XDisplayString (Xdisplay);
  if (display_name == NULL)
    display_name = val;		/* use broken `:0' value */

  i = strlen (val);
  display_string = MALLOC ((i + 9) * sizeof (char), "display_string");

  sprintf (display_string, "DISPLAY=%s", val);
  sprintf (windowid_string, "WINDOWID=%u", (unsigned int) TermWin.parent);

  /* add entries to the environment:
   * @ DISPLAY:   in case we started with -display
   * @ WINDOWID:  X window id number of the window
   * @ COLORTERM: terminal sub-name and also indicates its color
   * @ TERM:      terminal name
   */
  putenv (display_string);
  putenv (windowid_string);
  if (Xdepth <= 2)
    {
      putenv ("COLORTERM=" COLORTERMENV "-mono");
      putenv ("TERM=" TERMENV);
    }
  else
    {
#ifdef XPM_BACKGROUND
      putenv ("COLORTERM=" COLORTERMENV "-xpm");
#else
      putenv ("COLORTERM=" COLORTERMENV);
#endif
#ifdef DEFINE_XTERM_COLOR
      putenv ("TERM=" TERMENV "-color");
#else
      putenv ("TERM=" TERMENV);
#endif
    }

  init_command (cmd_argv);
  main_loop ();			/* main processing loop */
  return EXIT_SUCCESS;
}
Example #22
0
/*--------------------------------------------------------------------------*/
static DWORD WINAPI ThreadSplashScreen(LPVOID lpParam)
{
    char *ScilabDirectory = NULL;
    char *ImageFilename = NULL;
    wchar_t *wImageFilename = NULL;

    size_t len = 0;
    Gdiplus::GdiplusStartupInput gdiplusStartupInput;

    ULONG_PTR gdiplusToken = NULL;
    Gdiplus::GdiplusStartup(&gdiplusToken, &gdiplusStartupInput, NULL);

    HINSTANCE hInstanceThisDll = (HINSTANCE)GetModuleHandle("scilab_windows");

    ScilabDirectory = getScilabDirectory(TRUE);
    if (ScilabDirectory == NULL)
    {
        return 0;
    }

    len = strlen(FORMAT_FULLPATH_SPLASH_IMAGE) + strlen(ScilabDirectory) + 1;
    ImageFilename = (char*)MALLOC(sizeof(char) * len);
    if (ImageFilename == NULL)
    {
        return 0;
    }

    sprintf(ImageFilename, FORMAT_FULLPATH_SPLASH_IMAGE, ScilabDirectory);
    FREE(ScilabDirectory);
    ScilabDirectory = NULL;

    wImageFilename = to_wide_string(ImageFilename);
    FREE(ImageFilename);
    ImageFilename = NULL;
    if (wImageFilename == NULL)
    {
        return 0;
    }

    pImage = Gdiplus::Image::FromFile((const WCHAR *)wImageFilename);
    FREE(wImageFilename);
    wImageFilename = NULL;
    if (pImage == NULL)
    {
        return 0;
    }

    WNDCLASS wndcls = {0};

    wndcls.style = CS_HREDRAW | CS_VREDRAW;
    wndcls.lpfnWndProc = SplashWndProc;
    wndcls.hInstance = GetModuleHandle(NULL);
    wndcls.hCursor = LoadCursor(NULL, IDC_APPSTARTING);
    wndcls.hbrBackground = (HBRUSH)(COLOR_WINDOW + 1);
    wndcls.lpszClassName = SPLASH_WINDOW_CLASSNAME;
    wndcls.hIcon = LoadIcon(wndcls.hInstance, MAKEINTRESOURCE(IDI_APPLICATION));

    if (!RegisterClass(&wndcls))
    {
        if (GetLastError() != 0x00000582) // already registered
        {
            return 0;
        }
    }

    // try to find monitor where mouse was last time
    POINT point = {0};
    MONITORINFO mi = {sizeof(MONITORINFO), 0};
    HMONITOR hMonitor = 0;
    RECT rcArea = {0};

    ::GetCursorPos(&point);
    hMonitor = ::MonitorFromPoint(point, MONITOR_DEFAULTTONEAREST);
    if (::GetMonitorInfo(hMonitor, &mi))
    {
        rcArea.left = (mi.rcMonitor.right + mi.rcMonitor.left - pImage->GetWidth()) / 2;
        rcArea.top = (mi.rcMonitor.top + mi.rcMonitor.bottom - pImage->GetHeight()) / 2;
    }
    else
    {
        SystemParametersInfo(SPI_GETWORKAREA, NULL, &rcArea, NULL);
        rcArea.left = (rcArea.right + rcArea.left - pImage->GetWidth()) / 2;
        rcArea.top = (rcArea.top + rcArea.bottom - pImage->GetHeight()) / 2;
    }

    HWND hdlg = CreateWindowEx(WS_EX_TOOLWINDOW,
                               SPLASH_WINDOW_CLASSNAME,
                               SPLASH_WINDOW_CLASSNAME,
                               WS_CLIPCHILDREN | WS_POPUP,
                               rcArea.left,
                               rcArea.top,
                               pImage->GetWidth(),
                               pImage->GetHeight(),
                               NULL,
                               NULL,
                               wndcls.hInstance,
                               NULL);

    if (hdlg == NULL)
    {
        return 0;
    }

    ShowWindow(hdlg, SW_SHOWNORMAL);
    UpdateWindow(hdlg);
    SetWindowPos(hdlg, HWND_TOPMOST, 0, 0, 0, 0, SWP_NOSIZE | SWP_NOMOVE);

    while (!stopSplashScreen(20, 1000))
    {
        Sleep(20);
    }

    DestroyWindow(hdlg);
    return 0;
}
/*
 * Create a new X/Mesa visual.
 * Input:  display - X11 display
 *         visinfo - an XVisualInfo pointer
 *         rgb_flag - GL_TRUE = RGB mode,
 *                    GL_FALSE = color index mode
 *         alpha_flag - alpha buffer requested?
 *         db_flag - GL_TRUE = double-buffered,
 *                   GL_FALSE = single buffered
 *         stereo_flag - stereo visual?
 *         ximage_flag - GL_TRUE = use an XImage for back buffer,
 *                       GL_FALSE = use an off-screen pixmap for back buffer
 *         depth_size - requested bits/depth values, or zero
 *         stencil_size - requested bits/stencil values, or zero
 *         accum_red_size - requested bits/red accum values, or zero
 *         accum_green_size - requested bits/green accum values, or zero
 *         accum_blue_size - requested bits/blue accum values, or zero
 *         accum_alpha_size - requested bits/alpha accum values, or zero
 *         num_samples - number of samples/pixel if multisampling, or zero
 *         level - visual level, usually 0
 *         visualCaveat - ala the GLX extension, usually GLX_NONE
 * Return;  a new XMesaVisual or 0 if error.
 */
PUBLIC
XMesaVisual XMesaCreateVisual( XMesaDisplay *display,
                               XMesaVisualInfo visinfo,
                               GLboolean rgb_flag,
                               GLboolean alpha_flag,
                               GLboolean db_flag,
                               GLboolean stereo_flag,
                               GLboolean ximage_flag,
                               GLint depth_size,
                               GLint stencil_size,
                               GLint accum_red_size,
                               GLint accum_green_size,
                               GLint accum_blue_size,
                               GLint accum_alpha_size,
                               GLint num_samples,
                               GLint level,
                               GLint visualCaveat )
{
   char *gamma;
   XMesaVisual v;
   GLint red_bits, green_bits, blue_bits, alpha_bits;

   /* For debugging only */
   if (_mesa_getenv("MESA_XSYNC")) {
      /* This makes debugging X easier.
       * In your debugger, set a breakpoint on _XError to stop when an
       * X protocol error is generated.
       */
      XSynchronize( display, 1 );
   }

   /* Color-index rendering not supported. */
   if (!rgb_flag)
      return NULL;

   v = (XMesaVisual) CALLOC_STRUCT(xmesa_visual);
   if (!v) {
      return NULL;
   }

   v->display = display;

   /* Save a copy of the XVisualInfo struct because the user may Xfree()
    * the struct but we may need some of the information contained in it
    * at a later time.
    */
   v->visinfo = (XVisualInfo *) MALLOC(sizeof(*visinfo));
   if(!v->visinfo) {
      free(v);
      return NULL;
   }
   memcpy(v->visinfo, visinfo, sizeof(*visinfo));

   /* check for MESA_GAMMA environment variable */
   gamma = _mesa_getenv("MESA_GAMMA");
   if (gamma) {
      v->RedGamma = v->GreenGamma = v->BlueGamma = 0.0;
      sscanf( gamma, "%f %f %f", &v->RedGamma, &v->GreenGamma, &v->BlueGamma );
      if (v->RedGamma<=0.0)    v->RedGamma = 1.0;
      if (v->GreenGamma<=0.0)  v->GreenGamma = v->RedGamma;
      if (v->BlueGamma<=0.0)   v->BlueGamma = v->RedGamma;
   }
   else {
      v->RedGamma = v->GreenGamma = v->BlueGamma = 1.0;
   }

   v->ximage_flag = ximage_flag;

   v->mesa_visual.redMask = visinfo->red_mask;
   v->mesa_visual.greenMask = visinfo->green_mask;
   v->mesa_visual.blueMask = visinfo->blue_mask;
   v->visualID = visinfo->visualid;
   v->screen = visinfo->screen;

#if !(defined(__cplusplus) || defined(c_plusplus))
   v->visualType = xmesa_convert_from_x_visual_type(visinfo->class);
#else
   v->visualType = xmesa_convert_from_x_visual_type(visinfo->c_class);
#endif

   v->mesa_visual.visualRating = visualCaveat;

   if (alpha_flag)
      v->mesa_visual.alphaBits = 8;

   (void) initialize_visual_and_buffer( v, NULL, 0, 0 );

   {
      const int xclass = v->visualType;
      if (xclass == GLX_TRUE_COLOR || xclass == GLX_DIRECT_COLOR) {
         red_bits   = _mesa_bitcount(GET_REDMASK(v));
         green_bits = _mesa_bitcount(GET_GREENMASK(v));
         blue_bits  = _mesa_bitcount(GET_BLUEMASK(v));
      }
      else {
         /* this is an approximation */
         int depth;
         depth = GET_VISUAL_DEPTH(v);
         red_bits = depth / 3;
         depth -= red_bits;
         green_bits = depth / 2;
         depth -= green_bits;
         blue_bits = depth;
         alpha_bits = 0;
         assert( red_bits + green_bits + blue_bits == GET_VISUAL_DEPTH(v) );
      }
      alpha_bits = v->mesa_visual.alphaBits;
   }

   if (!_mesa_initialize_visual(&v->mesa_visual,
                                db_flag, stereo_flag,
                                red_bits, green_bits,
                                blue_bits, alpha_bits,
                                depth_size,
                                stencil_size,
                                accum_red_size, accum_green_size,
                                accum_blue_size, accum_alpha_size,
                                0)) {
      FREE(v);
      return NULL;
   }

   /* XXX minor hack */
   v->mesa_visual.level = level;
   return v;
}
/*
 * Description: This function is called when the user application enables
 *              EMF on a bridge interface. It primarily allocates memory
 *              for instance data and calls the common code init function.
 *
 * Input:       emf     - EMF module global data pointer
 *              inst_id - EMF instance name
 *              br_ptr  - Bridge device pointer
 */
static emf_info_t *
emf_instance_add(emf_struct_t *emf, int8 *inst_id, struct net_device *br_ptr)
{
	emf_info_t *emfi;
	osl_t *osh;
#ifdef CONFIG_PROC_FS
	uint8 proc_name[64];
#endif /* CONFIG_PROC_FS */
	emfc_wrapper_t emfl;

	if (emf->inst_count > EMF_MAX_INST)
	{
		EMF_ERROR("Max instance limit %d exceeded\n", EMF_MAX_INST);
		return (NULL);
	}

	emf->inst_count++;

	EMF_INFO("Creating EMF instance for %s\n", inst_id);

	osh = osl_attach(NULL, PCI_BUS, FALSE);

	ASSERT(osh);

	/* Allocate os specfic EMF info object */
	emfi = MALLOC(osh, sizeof(emf_info_t));
	if (emfi == NULL)
	{
		EMF_ERROR("Out of memory allocating emf_info\n");
		osl_detach(osh);
		return (NULL);
	}

	emfi->osh = osh;

	/* Save the EMF instance identifier */
	strncpy(emfi->inst_id, inst_id, IFNAMSIZ);
	emfi->inst_id[IFNAMSIZ - 1] = 0;

	/* Save the device pointer */
	emfi->br_dev = br_ptr;

	/* Fill the linux wrapper specific functions */
	emfl.forward_fn = (forward_fn_ptr)emf_forward;
	emfl.sendup_fn = (sendup_fn_ptr)emf_sendup;
	emfl.hooks_register_fn = (hooks_register_fn_ptr)emf_hooks_register;
	emfl.hooks_unregister_fn = (hooks_unregister_fn_ptr)emf_hooks_unregister;

	/* Initialize EMFC instance */
	if ((emfi->emfci = emfc_init(inst_id, (void *)emfi, osh, &emfl)) == NULL)
	{
		EMF_ERROR("EMFC init failed\n");
		MFREE(osh, emfi, sizeof(emf_info_t));
		osl_detach(osh);
		return (NULL);
	}

	EMF_INFO("Created EMFC instance for %s\n", inst_id);

	/* Initialize the iflist head */
	emfi->iflist_head = NULL;

#ifdef CONFIG_PROC_FS
	sprintf(proc_name, "emf/emf_stats_%s", inst_id);
	create_proc_read_entry(proc_name, 0, 0, emf_stats_get, emfi);
	sprintf(proc_name, "emf/emfdb_%s", inst_id);
	create_proc_read_entry(proc_name, 0, 0, emf_mfdb_list, emfi);
#endif /* CONFIG_PROC_FS */

	/* Add to the global EMF instance list */
	emfi->next = emf->list_head;
	emf->list_head = emfi;

	return (emfi);
}
Example #25
0
static void
create_vert_shader(struct vl_compositor *c)
{
   const unsigned max_tokens = 50;

   struct pipe_shader_state vs;
   struct tgsi_token *tokens;
   struct tgsi_header *header;

   struct tgsi_full_declaration decl;
   struct tgsi_full_instruction inst;

   unsigned ti;

   unsigned i;

   assert(c);

   tokens = (struct tgsi_token*)MALLOC(max_tokens * sizeof(struct tgsi_token));
   *(struct tgsi_version*)&tokens[0] = tgsi_build_version();
   header = (struct tgsi_header*)&tokens[1];
   *header = tgsi_build_header();
   *(struct tgsi_processor*)&tokens[2] = tgsi_build_processor(TGSI_PROCESSOR_VERTEX, header);

   ti = 3;

   /*
    * decl i0             ; Vertex pos
    * decl i1             ; Vertex texcoords
    */
   for (i = 0; i < 2; i++) {
      decl = vl_decl_input(i == 0 ? TGSI_SEMANTIC_POSITION : TGSI_SEMANTIC_GENERIC, i, i, i);
      ti += tgsi_build_full_declaration(&decl, &tokens[ti], header, max_tokens - ti);
   }

   /*
    * decl c0             ; Scaling vector to scale vertex pos rect to destination size
    * decl c1             ; Translation vector to move vertex pos rect into position
    * decl c2             ; Scaling vector to scale texcoord rect to source size
    * decl c3             ; Translation vector to move texcoord rect into position
    */
   decl = vl_decl_constants(TGSI_SEMANTIC_GENERIC, 0, 0, 3);
   ti += tgsi_build_full_declaration(&decl, &tokens[ti], header, max_tokens - ti);

   /*
    * decl o0             ; Vertex pos
    * decl o1             ; Vertex texcoords
    */
   for (i = 0; i < 2; i++) {
      decl = vl_decl_output(i == 0 ? TGSI_SEMANTIC_POSITION : TGSI_SEMANTIC_GENERIC, i, i, i);
      ti += tgsi_build_full_declaration(&decl, &tokens[ti], header, max_tokens - ti);
   }

   /* decl t0, t1 */
   decl = vl_decl_temps(0, 1);
   ti += tgsi_build_full_declaration(&decl, &tokens[ti], header, max_tokens - ti);

   /*
    * mad o0, i0, c0, c1  ; Scale and translate unit output rect to destination size and pos
    * mad o1, i1, c2, c3  ; Scale and translate unit texcoord rect to source size and pos
    */
   for (i = 0; i < 2; ++i) {
      inst = vl_inst4(TGSI_OPCODE_MAD, TGSI_FILE_OUTPUT, i, TGSI_FILE_INPUT, i, TGSI_FILE_CONSTANT, i * 2, TGSI_FILE_CONSTANT, i * 2 + 1);
      ti += tgsi_build_full_instruction(&inst, &tokens[ti], header, max_tokens - ti);
   }

   /* end */
   inst = vl_end();
   ti += tgsi_build_full_instruction(&inst, &tokens[ti], header, max_tokens - ti);

   assert(ti <= max_tokens);

   vs.tokens = tokens;
   c->vertex_shader = c->pipe->create_vs_state(c->pipe, &vs);
   FREE(tokens);
}
Example #26
0
/*
 * do_memmove: Worker function for memmove.
 *
 * Always work within the boundary of bytes. Fill in 1/2 of the src
 * memory with the pattern we want to write. This allows us to check
 * that we did not overwrite anything we were not supposed to in the
 * dest. Use the non pmem version of the memset/memcpy commands
 * so as not to introduce any possible side affects.
 */
static void
do_memmove(int fd, char *dest, char *src, char *file_name, off_t dest_off,
	off_t src_off, off_t off, off_t bytes)
{
	void *ret;
	char *src1 = MALLOC(bytes);
	char *buf = MALLOC(bytes);
	char old;

	memset(buf, 0, bytes);
	memset(src1, 0, bytes);
	memset(src, 0x5A, bytes / 4);
	memset(src + bytes / 4, 0x54, bytes / 4);

	/* dest == src */
	old = *(char *)(dest + dest_off);
	ret = pmem_memmove_persist(dest + dest_off, dest + dest_off, bytes / 2);
	UT_ASSERTeq(ret, dest + dest_off);
	UT_ASSERTeq(*(char *)(dest + dest_off), old);

	/* len == 0 */
	old = *(char *)(dest + dest_off);
	ret = pmem_memmove_persist(dest + dest_off, src + src_off, 0);
	UT_ASSERTeq(ret, dest + dest_off);
	UT_ASSERTeq(*(char *)(dest + dest_off), old);

	/*
	 * A side affect of the memmove call is that
	 * src contents will be changed in the case of overlapping
	 * addresses.
	 */
	memcpy(src1, src, bytes / 2);
	ret = pmem_memmove_persist(dest + dest_off, src + src_off, bytes / 2);
	UT_ASSERTeq(ret, dest + dest_off);

	/* memcmp will validate that what I expect in memory. */
	if (memcmp(src1 + src_off, dest + dest_off, bytes / 2))
		UT_ERR("%s: %zu bytes do not match with memcmp",
			file_name, bytes / 2);

	/*
	 * This is a special case. An overlapping dest means that
	 * src is a pointer to the file, and destination is src + dest_off +
	 * overlap. This is the basis for the comparison. The use of ERR
	 * here is deliberate. This will force a failure of the test but allow
	 * it to continue until its done. The idea is that allowing some
	 * to succeed and others to fail gives more information about what
	 * went wrong.
	 */
	if (dest > src && off != 0) {
		LSEEK(fd, (off_t)dest_off + off, SEEK_SET);
		if (READ(fd, buf, bytes / 2) == bytes / 2) {
			if (memcmp(src1 + src_off, buf, bytes / 2))
				UT_ERR("%s: first %zu bytes do not match",
					file_name, bytes / 2);
		}
	} else {
		LSEEK(fd, (off_t)dest_off, SEEK_SET);
		if (READ(fd, buf, bytes / 2) == bytes / 2) {
			if (memcmp(src1 + src_off, buf, bytes / 2))
				UT_ERR("%s: first %zu bytes do not match",
					file_name, bytes / 2);
		}
	}
	FREE(src1);
	FREE(buf);
}
/*
 *  board_final_init()
 *
 *  Do any final initialization, such as adding commands to the
 *  user interface.
 *
 *  If you don't want a user interface, put the startup code here.
 *  This routine is called just before CFE starts its user interface.
 *
 *  Input parameters:
 *     nothing
 *
 *  Return value:
 *     nothing
 */
void
board_final_init(void)
{
	char *addr, *mask, *wait_time;
	char buf[512], *cur = buf;
#ifdef CFG_ROMBOOT
	char *laddr = NULL;
#endif
#if !CFG_SIM
	char *boot_cfg = NULL;
	char *go_cmd = "go;";
#endif
	int commit = 0;
	uint32 ncdl;
#if CFG_WL && CFG_WLU && CFG_SIM
	char *ssid;
#endif

	ui_init_bcm947xxcmds();

	/* Force commit of embedded NVRAM */
	commit = restore_defaults;

	/* Set the SDRAM NCDL value into NVRAM if not already done */
	if ((getintvar(NULL, "sdram_ncdl") == 0) &&
	    ((ncdl = si_memc_get_ncdl(sih)) != 0)) {
		sprintf(buf, "0x%x", ncdl);
		nvram_set("sdram_ncdl", buf);
		commit = 1;
	}

	/* Set the bootloader version string if not already done */
	sprintf(buf, "CFE %s", EPI_VERSION_STR);
	if (strcmp(nvram_safe_get("pmon_ver"), buf) != 0) {
		nvram_set("pmon_ver", buf);
		commit = 1;
	}


	/* Set the size of the nvram area if not already done */
	sprintf(buf, "%d", MAX_NVRAM_SPACE);
	if (strcmp(nvram_safe_get("nvram_space"), buf) != 0) {
		nvram_set("nvram_space", buf);
		commit = 1;
	}

#if CFG_FLASH || CFG_SFLASH || CFG_NFLASH
#if !CFG_SIM
	/* Commit NVRAM only if in FLASH */
	if (
#ifdef BCMNVRAMW
		!nvram_inotp() &&
#endif
		commit) {
		printf("Committing NVRAM...");
		nvram_commit();
		printf("done\n");
		if (restore_defaults) {
			printf("Waiting for reset button release...");
			reset_release_wait();
			printf("done\n");
		}
	}

	/* Reboot after restoring defaults */
	if (restore_defaults)
		si_watchdog(sih, 1);
#endif	/* !CFG_SIM */
#else
	if (commit)
		printf("Flash not configured, not commiting NVRAM...\n");
#endif /* CFG_FLASH || CFG_SFLASH || CFG_NFLASH */

	/*
	 * Read the wait_time NVRAM variable and set the tftp max retries.
	 * Assumption: tftp_rrq_timeout & tftp_recv_timeout are set to 1sec.
	 */
	if ((wait_time = nvram_get("wait_time")) != NULL) {
		tftp_max_retries = atoi(wait_time);
		if (tftp_max_retries > MAX_WAIT_TIME)
			tftp_max_retries = MAX_WAIT_TIME;
		else if (tftp_max_retries < MIN_WAIT_TIME)
			tftp_max_retries = MIN_WAIT_TIME;
	}
#ifdef CFG_ROMBOOT
	else if (board_bootdev_rom(sih)) {
		tftp_max_retries = 10;
	}
#endif

	/* Configure network */
	if (cfe_finddev("eth0")) {
		int res;

		if ((addr = nvram_get("lan_ipaddr")) &&
		    (mask = nvram_get("lan_netmask")))
			sprintf(buf, "ifconfig eth0 -addr=%s -mask=%s",
			        addr, mask);
		else
			sprintf(buf, "ifconfig eth0 -auto");

		res = ui_docommand(buf);

#ifdef CFG_ROMBOOT
		/* Try indefinite netboot only while booting from ROM
		 * and we are sure that we dont have valid nvram in FLASH
		 */
		while (board_bootdev_rom(sih) && !addr) {
			char ch;

			cur = buf;
			/* Check if something typed at console */
			if (console_status()) {
				console_read(&ch, 1);
				/* Check for Ctrl-C */
				if (ch == 3) {
					if (laddr)
						MFREE(osh, laddr, MAX_SCRIPT_FSIZE);
					xprintf("Stopped auto netboot!!!\n");
					return;
				}
			}

			if (!res) {
				char *bserver, *bfile, *load_ptr;

				if (!laddr)
					laddr = MALLOC(osh, MAX_SCRIPT_FSIZE);

				if (!laddr) {
					load_ptr = (char *) 0x00008000;
					xprintf("Failed malloc for boot_script, Using :0x%x\n",
						(unsigned int)laddr);
				}
				else {
					load_ptr = laddr;
				}
				bserver = (bserver = env_getenv("BOOT_SERVER"))
					? bserver:"192.168.1.1";

				if ((bfile = env_getenv("BOOT_FILE"))) {
					int len;

					if (((len = strlen(bfile)) > 5) &&
					    !strncmp((bfile + len - 5), "cfesh", 5)) {
						cur += sprintf(cur,
						"batch -raw -tftp -addr=0x%x -max=0x%x %s:%s;",
							(unsigned int)load_ptr,
							MAX_SCRIPT_FSIZE, bserver, bfile);
					}
					if (((len = strlen(bfile)) > 3)) {
						if (!strncmp((bfile + len - 3), "elf", 3)) {
							cur += sprintf(cur,
							"boot -elf -tftp -max=0x5000000 %s:%s;",
							bserver, bfile);
						}
						if (!strncmp((bfile + len - 3), "raw", 3)) {
							cur += sprintf(cur,
							"boot -raw -z -tftp -addr=0x00008000"
							" -max=0x5000000 %s:%s;",
							bserver, bfile);
						}
					}
				}
				else {  /* Make last effort */
					cur += sprintf(cur,
						"batch -raw -tftp -addr=0x%x -max=0x%x %s:%s;",
						(unsigned int)load_ptr, MAX_SCRIPT_FSIZE,
						bserver, "cfe_script.cfesh");
					cur += sprintf(cur,
						"boot -elf -tftp -max=0x5000000 %s:%s;",
						bserver, "boot_file.elf");
					cur += sprintf(cur,
						"boot -raw -z -tftp -addr=0x00008000"
						" -max=0x5000000 %s:%s;",
						bserver, "boot_file.raw");
				}

				ui_docommand(buf);
				cfe_sleep(3*CFE_HZ);
			}

			sprintf(buf, "ifconfig eth0 -auto");
			res = ui_docommand(buf);
		}
#endif /* CFG_ROMBOOT */
	}
#if CFG_WL && CFG_WLU && CFG_SIM
	if ((ssid = nvram_get("wl0_ssid"))) {
		sprintf(buf, "wl join %s", ssid);
		ui_docommand(buf);
	}
#endif

#if !CFG_SIM
	/* Try to run boot_config command if configured.
	 * make sure to leave space for "go" command.
	 */
	if ((boot_cfg = nvram_get("boot_config"))) {
		if (strlen(boot_cfg) < (sizeof(buf) - sizeof(go_cmd)))
			cur += sprintf(cur, "%s;", boot_cfg);
		else
			printf("boot_config too long, skipping to autoboot\n");
	}

	/* Boot image */
	cur += sprintf(cur, go_cmd);
#endif	/* !CFG_SIM */

	/* Startup */
	if (cur > buf)
		env_setenv("STARTUP", buf, ENV_FLG_NORMAL);
}
Example #28
0
float LayerNet::conjgrad (
   TrainingSet *tptr , // Training set to use
   int maxits ,        // Maximum iterations allowed
   float reltol ,     // Relative error change tolerance
   float errtol       // Quit if error drops this low
   )
{
   int i, j, n, iter, pnum, key, retry, max_retry ;
   float gam, *g, *h, *outdelta, *hid2delta, *grad, *base ;
   float corr, error, *cptr, *gptr, *pptr, maxgrad ;
   float prev_err ;
   char msg[80];
   max_retry = 5 ;

/*
   Allocate work memory
*/

   MEMTEXT ( "CONJGRAD work" ) ;
   if (nhid2) {
      hid2delta = (float *) MALLOC ( nhid2 * sizeof(float) ) ;
      if (hid2delta == NULL)
         return -2.0 ;
      }
   else
      hid2delta = NULL ;

   outdelta = (float *) MALLOC ( nout * sizeof(float) ) ;

   if (nhid1 == 0)               // No hidden layer
      n = nout * (nin+1) ;
   else if (nhid2 == 0)          // One hidden layer
      n = nhid1 * (nin+1) + nout * (nhid1+1) ;
   else                          // Two hidden layers
      n = nhid1 * (nin+1) + nhid2 * (nhid1+1) + nout * (nhid2+1) ;

   grad = (float *) MALLOC ( n * sizeof(float) ) ;
   base = (float *) MALLOC ( n * sizeof(float) ) ;
   g = (float *) MALLOC ( n * sizeof(float) ) ;
   h = (float *) MALLOC ( n * sizeof(float) ) ;

   if ((outdelta == NULL) || (grad == NULL) ||
       (base == NULL) || (g == NULL) || (h == NULL)) {
      if (hid2delta != NULL)
         FREE ( hid2delta ) ;
      if (outdelta != NULL)
         FREE ( outdelta ) ;
      if (grad != NULL)
         FREE ( grad ) ;
      if (base != NULL)
	 FREE ( base ) ;
      if (g != NULL)
         FREE ( g ) ;
      if (h != NULL)
         FREE ( h ) ;
      return -2.0 ;   // Flags error
      }

   prev_err = 1.e30 ;
   error = find_grad ( tptr , hid2delta , outdelta , grad ) ;

   memcpy ( g , grad , n * sizeof(float) ) ;
   memcpy ( h , grad , n * sizeof(float) ) ;

/*
   Main iteration loop is here
*/

   for (iter=0 ; iter<maxits ; iter++) {  // Each iter is an epoch

/*
   Check current error against user's max.  Abort if user pressed ESCape
*/
      sprintf ( msg , "Gradient Finding...Iter Nø %d : Error = %lf %%", iter, 100.0 * error ) ;
      normal_message ( msg ) ;
      if (error <= errtol)   // If our error is within user's limit
	 break ;             // then we are done!

      if (error <= reltol)   // Generally not necessary: reltol<errtol in
         break ;             // practice, but help silly users

      if (kbhit()) {         // Was a key pressed?
         key = getch () ;    // Read it if so
         while (kbhit())     // Flush key buffer in case function key
            getch () ;       // or key was held down
         if (key == 27) {    // ESCape
            error = -error ; // Flags user that ESCape was pressed
            break ;
            }
         }

      prev_err = error ;
      error = direcmin ( tptr , error , 10 , 1.e-10 ,
                         0.5 , base , grad ) ;
      if (error < 0.0)  // Indicates user pressed ESCape
         goto CGFINISH ;

      if ((2.0 * (prev_err - error)) <=       // If this direc gave poor result
          (reltol * (prev_err + error + 1.e-10))) { // will use random direc
         prev_err = error ;                   // But first exhaust grad
         error = find_grad ( tptr , hid2delta , outdelta , grad ) ;
         error = direcmin ( tptr , error , 15 , 1.e-10 ,
                            1.e-3 , base , grad ) ;
         for (retry=0 ; retry<max_retry ; retry++) {
            for (i=0 ; i<n ; i++)
	       grad[i] = (float) (rand() - RANDMAX/2) / (RANDMAX * 10.0) ;
            error = direcmin ( tptr , error , 10 , 1.e-10 ,
                               1.e-2 , base , grad ) ;
            if (error < 0.0)  // Indicates user pressed ESCape
               goto CGFINISH ;
            if (retry < max_retry/2)
               continue ;
            if ((2.0 * (prev_err - error)) >
                (reltol * (prev_err + error + 1.e-10)))
               break ;   // Get out of retry loop if we improved enough
            } // For retry
         if (retry == max_retry)   // If we exhausted all tries
            break ;                // probably hopeless
	 memcpy ( g , grad , n * sizeof(float) ) ;
	 memcpy ( h , grad , n * sizeof(float) ) ;
         } // If this dir gave poor result

      prev_err = error ;

/*
   Setup for next iteration
*/

      error = find_grad ( tptr , hid2delta , outdelta , grad ) ;
      gam = gamma ( g , grad ) ;
      if (gam < 0.0)
         gam = 0.0 ;
      if (gam > 1.0)
         gam = 1.0 ;

      find_new_dir ( gam , g , h , grad ) ;
      }  // This is the end of the main iteration loop

/*
   Free work memory
*/

CGFINISH:
   MEMTEXT ( "CONJGRAD work" ) ;
   if (hid2delta != NULL)
      FREE ( hid2delta ) ;
   FREE ( outdelta ) ;
   FREE ( grad ) ;
   FREE ( base ) ;
   FREE ( g ) ;
   FREE ( h ) ;

   return error ;
}
Example #29
0
void* AdrenoMM_Alloc(unsigned int size, const char *file, int line, const char *func )
{
	struct block *block;
	short size_hash = size2hash( size );
	struct unit_head *head;

	if(size == 0) {
		return NULL;
	}
	memmgr_usage_bytes += size;
	if (memmgr_usage_bytes > memmgr_max_used_bytes)
		memmgr_max_used_bytes = memmgr_usage_bytes;

	/* �u���b�N���𒴂���̈�̊m�ۂɂ́Amalloc() ��p���� */
	/* ���̍ہAunit_head.block �� NULL �������ċ�ʂ��� */
	if(hash2size(size_hash) > BLOCK_DATA_SIZE - sizeof(struct unit_head)) {
		struct unit_head_large* p = (struct unit_head_large*)MALLOC(sizeof(struct unit_head_large)+size,file,line,func);
		if(p != NULL) {
			p->size            = size;
			p->unit_head.block = NULL;
			p->unit_head.size  = 0;
			p->unit_head.file  = file;
			p->unit_head.line  = line;
			p->prev = NULL;
			if (unit_head_large_first == NULL)
				p->next = NULL;
			else {
				unit_head_large_first->prev = p;
				p->next = unit_head_large_first;
			}
			unit_head_large_first = p;
			*(long*)((char*)p + sizeof(struct unit_head_large) - sizeof(long) + size) = 0xdeadbeaf;
			return (char *)p + sizeof(struct unit_head_large) - sizeof(long);
		} else {
			printf("Memory manager::memmgr_alloc failed (allocating %ld+%d bytes at %s:%d).\n", sizeof(struct unit_head_large), size, file, line);
			exit(EXIT_FAILURE);
		}
	}

	/* ����T�C�Y�̃u���b�N���m�ۂ���Ă��Ȃ����A�V���Ɋm�ۂ��� */
	if(hash_unfill[size_hash]) {
		block = hash_unfill[size_hash];
	} else {
		block = block_malloc(size_hash);
	}

	if( block->unit_unfill == 0xFFFF ) {
		// free�ςݗ̈悪�c���Ă��Ȃ�
		memmgr_assert(block->unit_used <  block->unit_count);
		memmgr_assert(block->unit_used == block->unit_maxused);
		head = block2unit(block, block->unit_maxused);
		block->unit_used++;
		block->unit_maxused++;
	} else {
		head = block2unit(block, block->unit_unfill);
		block->unit_unfill = head->size;
		block->unit_used++;
	}

	if( block->unit_unfill == 0xFFFF && block->unit_maxused >= block->unit_count) {
		// ���j�b�g���g���ʂ������̂ŁAunfill���X�g����폜
		if( block->unfill_prev == &block_head) {
			hash_unfill[ size_hash ] = block->unfill_next;
		} else {
			block->unfill_prev->unfill_next = block->unfill_next;
		}
		if( block->unfill_next ) {
			block->unfill_next->unfill_prev = block->unfill_prev;
		}
		block->unfill_prev = NULL;
	}

#ifdef DEBUG_MEMMGR
	{
		unsigned int i, sz = hash2size( size_hash );
		for( i=0; i<sz; i++ )
		{
			if( ((unsigned char*)head)[ sizeof(struct unit_head) - sizeof(long) + i] != 0xfd )
			{
				if( head->line != 0xfdfd )
				{
					printf("Memory manager: freed-data is changed. (freed in %s line %d)\n", head->file,head->line);
				}
				else
				{
					printf("Memory manager: not-allocated-data is changed.\n");
				}
				break;
			}
		}
		memset( (char *)head + sizeof(struct unit_head) - sizeof(long), 0xcd, sz );
	}
#endif

	head->block = block;
	head->file  = file;
	head->line  = line;
	head->size  = (unsigned short)size;
	*(long*)((char*)head + sizeof(struct unit_head) - sizeof(long) + size) = 0xdeadbeaf;
	return (char *)head + sizeof(struct unit_head) - sizeof(long);
};
Example #30
0
static void get_n_most_likely_path_rerank(int n, int l, int goal_id,
        TERM *p_n_viterbi_list_ptr)
{
    TERM p_goal_path;
    TERM p_subpath_goal, p_subpath_sw;
    TERM p_tmp, p_tmp_g, p_tmp_g0, p_tmp_g1, p_tmp_sw, p_tmp_sw0, p_tmp_sw1;
    TERM p_n_viterbi, p_n_viterbi_list, p_tmp_list;
    TERM p_viterbi_prob;
    int j,m,k;
    EG_PATH_PTR path_ptr = NULL;
    int c_len, sw_len;
    V_ENT_PTR v_ent;
    int l_used;
    double n_viterbi_egraph_score;

    p_n_viterbi_list = bpx_build_list();
    p_tmp_list = p_n_viterbi_list;

    l_used = 0;
    for (j = 0; j < l; j++) {
        if (expl_graph[goal_id]->top_n[j] != NULL) l_used++;
    }

    viterbi_rank =
        (V_RANK_PTR)MALLOC(sizeof(struct ViterbiRankEntry) * l_used);

    for (j = 0; j < l_used; j++) {
        alloc_n_viterbi_egraphs();

        n_viterbi_egraph_size =
            visit_n_most_likely_path(expl_graph[goal_id]->top_n[j],0);

        viterbi_rank[j].size = n_viterbi_egraph_size;
        viterbi_rank[j].expl = n_viterbi_egraphs;
        viterbi_rank[j].score = compute_rerank_score();
    }

    qsort(viterbi_rank, l_used, sizeof(struct ViterbiRankEntry),
          compare_viterbi_rank);

    for (j = 0; j < l_used && j < n; j++) {
        n_viterbi_egraph_size = viterbi_rank[j].size;
        n_viterbi_egraphs = viterbi_rank[j].expl;
        n_viterbi_egraph_score = viterbi_rank[j].score;

        /* Build the Viterbi path as a Prolog list: */
        p_goal_path = bpx_build_list();
        p_tmp = p_goal_path;
        for (m = 0; m < n_viterbi_egraph_size; m++) {
            bpx_unify(bpx_get_car(p_tmp),
                      bpx_build_integer(n_viterbi_egraphs[m]->goal_id));

            if (m == n_viterbi_egraph_size - 1) {
                bpx_unify(bpx_get_cdr(p_tmp),bpx_build_nil());
            }
            else {
                bpx_unify(bpx_get_cdr(p_tmp),bpx_build_list());
                p_tmp = bpx_get_cdr(p_tmp);
            }
        }

        p_subpath_goal = bpx_build_list();
        p_subpath_sw = bpx_build_list();

        p_tmp_g = p_subpath_goal;
        p_tmp_sw = p_subpath_sw;

        for (m = 0; m < n_viterbi_egraph_size; m++) {
            v_ent = n_viterbi_egraphs[m];

            if (v_ent->path_ptr == NULL) {
                p_tmp_g0 = bpx_build_nil();
                p_tmp_sw0 = bpx_build_nil();
            }
            else {
                path_ptr = v_ent->path_ptr;
                c_len = path_ptr->children_len;
                sw_len = path_ptr->sws_len;

                if (c_len == 0) {
                    p_tmp_g0 = bpx_build_nil();
                }
                else {
                    p_tmp_g0 = bpx_build_list();
                    p_tmp_g1 = p_tmp_g0;
                    for (k = 0; k < c_len; k++) {
                        bpx_unify(bpx_get_car(p_tmp_g1),
                                  bpx_build_integer(path_ptr->children[k]->id));
                        if (k == c_len - 1) {
                            bpx_unify(bpx_get_cdr(p_tmp_g1),bpx_build_nil());
                        }
                        else {
                            bpx_unify(bpx_get_cdr(p_tmp_g1),bpx_build_list());
                            p_tmp_g1 = bpx_get_cdr(p_tmp_g1);
                        }
                    }
                }

                if (sw_len == 0) {
                    p_tmp_sw0 = bpx_build_nil();
                }
                else {
                    p_tmp_sw0 = bpx_build_list();
                    p_tmp_sw1 = p_tmp_sw0;
                    for (k = 0; k < sw_len; k++) {
                        bpx_unify(bpx_get_car(p_tmp_sw1),bpx_build_integer(path_ptr->sws[k]->id));
                        if (k == sw_len - 1) {
                            bpx_unify(bpx_get_cdr(p_tmp_sw1),bpx_build_nil());
                        }
                        else {
                            bpx_unify(bpx_get_cdr(p_tmp_sw1),bpx_build_list());
                            p_tmp_sw1 = bpx_get_cdr(p_tmp_sw1);
                        }
                    }
                }
            }

            bpx_unify(bpx_get_car(p_tmp_g),p_tmp_g0);
            bpx_unify(bpx_get_car(p_tmp_sw),p_tmp_sw0);

            if (m == n_viterbi_egraph_size - 1) {
                bpx_unify(bpx_get_cdr(p_tmp_g),bpx_build_nil());
                bpx_unify(bpx_get_cdr(p_tmp_sw),bpx_build_nil());
            }
            else {
                bpx_unify(bpx_get_cdr(p_tmp_g),bpx_build_list());
                bpx_unify(bpx_get_cdr(p_tmp_sw),bpx_build_list());
                p_tmp_g = bpx_get_cdr(p_tmp_g);
                p_tmp_sw = bpx_get_cdr(p_tmp_sw);
            }
        }

        p_viterbi_prob = bpx_build_float(n_viterbi_egraph_score);

        p_n_viterbi = bpx_build_structure("v_expl",5);
        bpx_unify(bpx_get_arg(1,p_n_viterbi),bpx_build_integer(j));
        bpx_unify(bpx_get_arg(2,p_n_viterbi),p_goal_path);
        bpx_unify(bpx_get_arg(3,p_n_viterbi),p_subpath_goal);
        bpx_unify(bpx_get_arg(4,p_n_viterbi),p_subpath_sw);
        bpx_unify(bpx_get_arg(5,p_n_viterbi),p_viterbi_prob);

        bpx_unify(bpx_get_car(p_tmp_list),p_n_viterbi);

        if (j == (l_used - 1) || j == (n - 1)) {
            bpx_unify(bpx_get_cdr(p_tmp_list),bpx_build_nil());
        }
        else {
            bpx_unify(bpx_get_cdr(p_tmp_list),bpx_build_list());
            p_tmp_list = bpx_get_cdr(p_tmp_list);
        }
    }

    for (j = 0; j < l_used; j++) {
        free(viterbi_rank[j].expl);
    }
    free(viterbi_rank);
    viterbi_rank = NULL;

    *p_n_viterbi_list_ptr = p_n_viterbi_list;
}