Exemple #1
0
int handleSendmsg( void *fcb, double time, unsigned int sender,
		unsigned int receiver, int communicator, int msgtype,
		int msglength, int scltoken ) {


	uint32_t tmp;
	
	if ( receiver == (uint32_t) -1 || sender == (uint32_t) -1 )
		fprintf( stderr, "cpuid is not supposed to be -1" );

	/* map it */
	tmp= searchHash( ((fcbT*)fcb)->pghash, (uint32_t) communicator );
	if( 0 != tmp ) {
		communicator= tmp;
	}
	
	
	++receiver;
	++sender;

	OTF_Writer_writeSendMsg( ((fcbT*)fcb)->writer, (uint64_t) time, sender,
		receiver, communicator, msgtype, msglength, scltoken );

	return 0;
}
Exemple #2
0
void search(DATA_HEAD *data)
{
    COMPANY companyPtr;
    int len;
    char name[MAX_CHARS];
    int success = 0;

    printf("Enter name of company: ");
    fgets(name, MAX_CHARS, stdin);
    len = strlen(name);

    //Chanages \n or \r (depending on OS) to \0
    if(name[len-1] == '\n' || name[len-1]=='\r')
        name[len-1]='\0';

    //if search tree function returns succes
    success = searchHash(data, name, &companyPtr);
    if(success == 1)
    {
        printf("Company Name:           Revenue(Billion)   Profits(Million)    # of Employees\n");
        printf("%-30s%d               %d             %d\n", companyPtr.companyName, companyPtr.revenuePerBillion, companyPtr.profitPerMillion, companyPtr.numberOfEmployees);
    }
    else
        printf("Company is not in the list.\n");

    printf("\n");
}
Exemple #3
0
int handleGlobalop( void *fcb, double time, int globaloptoken,
		unsigned int cpuid, int communicator, unsigned int rootcpuid, 
		int bytessent, int bytesreceived, double durationtimesteps, 
		int scltoken ) {


	uint32_t tmp;
	
	++cpuid;
	

	/* map it */
	tmp= searchHash( ((fcbT*)fcb)->pghash, (uint32_t) communicator );
	if( 0 != tmp ) {
		communicator= tmp;
	}
	
	
	if ( rootcpuid >= (unsigned int)((fcbT*)fcb)->processcount ) {

		/* invalid root cpu id => translate to '0' */
		rootcpuid= 0;

	} else {

		++rootcpuid;
	}

	OTF_Writer_writeCollectiveOperation( ((fcbT*)fcb)->writer, (uint64_t) time,
		cpuid, globaloptoken + 1, communicator, rootcpuid, bytessent, bytesreceived,
		(uint64_t) durationtimesteps, scltoken );

	return 0;
}
Exemple #4
0
Packet *newPacketIHAVE(Packet *pktWHOHAS)
{
    uint8_t numHash = getPacketNumHash(pktWHOHAS);
    int i = 0;
    int idx;
    uint8_t *hash;
    Packet *thisObj = newPacketDefault();
    incPacketSize(thisObj, 4);
    setPacketType(thisObj, "IHAVE");
    for(i = 0; i < numHash; i++) {
        hash = getPacketHash(pktWHOHAS, i);
        idx = searchHash(hash, &hasChunk, -1);
        if(idx >= 0) {
            printf("Has[%d]", i);
            insertPacketHash(thisObj, hash);
        }
    }

    if(i == 0 || getPacketSize(thisObj) == 20) {
        freePacket(thisObj);
        return NULL;
    } else {
      setPacketDest(thisObj, &(pktWHOHAS->src), sizeof(pktWHOHAS->src));
      return thisObj;
    }
}
Exemple #5
0
//===================================================================
// Function to undo a delete of a company.  Does not allow to undo
// delete of a company that is already in the BST
//===================================================================
void undoDelete(DATA_HEAD *data)
{
    COMPANY* companyNode;
    int isDuplicate;

    //If there is something in the stack
    if(!emptyStack(data->pStack))
    {
        companyNode = (COMPANY*)popStack(data->pStack);

        //Check to see if there is duplicate
        isDuplicate = searchHash(data, companyNode->companyName, companyNode);

        //If there is, print and error, else, insert into the hashed array
        if(isDuplicate == 1)
        {
            printf("ERROR: DUPLICATE DATA\n");
            printf("%s has already been entered into the system\n", companyNode->companyName);
            free(companyNode);
        }
        else
        {
            printf("%s reinserted into the system\n", companyNode->companyName);
            insertManager(data, companyNode);
            updateCollision(data);
            (data->count)++;
            printf("\nNumber Of Data Records: %d\n", data->count);
        }
    }
    else
        printf("Nothing to undo.\n"); //nothing in the stack

    printf("\n");
}
Exemple #6
0
// 输出关键字和标识符的函数
void print_word(char* token)
{
    // 首先判断是不是关键字
    int key;
    key = searchHash(token, HashTable);

    if( key != -1 )
    {
        // 是关键字
        toUp(token);                    // 将小写字母转换为大写字母
        printf("(%s,0)\n",token);
    }
    else                                // 不是关键字,是标识符
    {

        int key = searchHash(token,IdTable);
        if(key == -1)                   //判断该标识符是否已插入“标识符哈希表”
            key = createHash(token,IdTable); // 不在哈希表中

        printf("(ID,%d)\n",key);    // 输出该标识符在哈希表中的位置
    }
}
Exemple #7
0
int handleSamp( void *fcb, double time, unsigned int cpuorcpugrpid,
		int samplearraydim, const int *sampletokenarray,
		const int *samplevaluetypearray, const void *samplevaluearray ) {


	int i;
	uint64_t tmp;
	uint32_t tmp2;

	/* group means first bit equals 1 */
	if ( (cpuorcpugrpid&0x80000000) == 0) {

		if ( cpuorcpugrpid == (uint32_t) -1 ) {

			fprintf( stderr, "cpuid is not supposed to be -1" );
		}

		++cpuorcpugrpid;
	} else {
	
		/* map it */
		tmp2= searchHash( ((fcbT*)fcb)->pghash, (uint32_t) cpuorcpugrpid );
		if( 0 != tmp2 ) {
			cpuorcpugrpid= tmp2;
		}
	
	}

	for( i = 0; i < samplearraydim; ++i ) {

		if ( samplevaluetypearray[i] == VTF3_VALUETYPE_FLOAT ) {
		
			tmp = (uint64_t) ( ((double*) samplevaluearray)[i] + 0.5f );
		} else {
		
			tmp = ( (uint64_t*) samplevaluearray )[i];
		}
		
		OTF_Writer_writeCounter( ((fcbT*)fcb)->writer, (uint64_t) time,
			cpuorcpugrpid, sampletokenarray[i] + 1, tmp );
	}

	return 0;
}
Exemple #8
0
void newPacketDATA(Packet *pkt, queue *dataQueue)
{
  uint8_t *hash = pkt->payload + 16;
  int idx = searchHash(hash, &masterChunk, -1);
  Packet *newPkt;
  if(idx >= 0) {
    int i = 0;
    int numPacket = BT_CHUNK_SIZE / PACKET_DATA_SIZE;
    if(BT_CHUNK_SIZE % PACKET_DATA_SIZE > 0) {
      numPacket++;
    }
    for(i = 0; i < numPacket; i++) {
      if(i == numPacket - 1) {
	newPkt = newPacketSingleDATA(i + 1, idx, BT_CHUNK_SIZE % PACKET_DATA_SIZE);
      } else {
	newPkt = newPacketSingleDATA(i + 1, idx, PACKET_DATA_SIZE);
      }
      enqueue(dataQueue, newPkt);
    }
  }
}
Exemple #9
0
int newPacketGET(Packet *pkt, queue *getQueue)
{
  int ret = 0;
  uint8_t numHash = getPacketNumHash(pkt);
  int i, idx;
  uint8_t *hash;
  for(i = 0; i < numHash; i++) {
    hash = getPacketHash(pkt, i);
    printHash(hash);
    idx = searchHash(hash, &getChunk, -1);
    printf("idx %d hashSeq %d getState %d\n", idx, getChunk.list[idx].seq, getChunk.list[idx].fetchState);
    //Only GET when chunk hasn't been fetched
    if(idx >= 0 && getChunk.list[idx].fetchState == 0) {
      printf("geting chunk %d\n",getChunk.list[idx].seq);
      Packet *thisObj = newPacketSingleGET(hash);
      enqueue(getQueue, (void *)thisObj);
      ret = 1;
    }
  }
  return ret;
}
/**
 *  哈希表的插入算法
 */
int HashTable::insertHash(int e)
{
	int c = 0;
	int p = searchHash(e, c);
	if (this->search_OK == 1)
	{
		//已经存在
		return -1;
	}//if
	else if (c < h->sizeindex / 2)
	{
		//插入数据
		h->elem[p] = e;
		++h->count;
		return 1;
	}//else if
	else
	{
		//需要重建哈希表
		return -1;
	}//else
}
Exemple #11
0
//===================================================================
// Prompts for a new company to insert.  If already exists, return
// error. If does not exist, ask user for all information for company
// and inserts into the BST and hashed array
//===================================================================
void insertCompany(DATA_HEAD *data)
{
    COMPANY *newCompany;
    int len;
    char name[MAX_CHARS];

    printf("Enter name of company: ");
    fgets(name, MAX_CHARS, stdin);
    len = strlen(name);
    if(name[len-1] == '\n' || name[len-1]=='\r')
            name[len-1]='\0'; // change '\n' to '\0'

    newCompany = (COMPANY*)malloc(sizeof(COMPANY));
    if(newCompany == NULL)
    {
        printf("Not enough memory, exiting program...\n");
        exit(1);
    }
    newCompany->companyName = allocateString(name);
    //if search tree function returns succes
    if(!searchHash(data, name, newCompany)) //company name has not been found, therefore does not exist in tree.
    {
        printf("Enter revenue per billion: ");
        scanf("%d", &(newCompany->revenuePerBillion));
        printf("Enter profits per million: ");
        scanf("%d", &(newCompany->profitPerMillion));
        printf("Enter number of employees: ");
        scanf("%d", &(newCompany->numberOfEmployees));
        insertManager(data, newCompany);
        (data->count)++;
        printf("%s added!\n", newCompany->companyName);
        printf("\nNumber Of Data Records: %d\n\n", data->count);
    }
    else
        printf("ERROR: DUPLICATE DATA\n");

    printf("\n");
}
/* Search the data based on the CCN (the user's input from keyboard)
   PRE:  hash - the pointer to the header of the hash table
   POST: data printed out if found
		 print the notification if wrong input
*/
void searchManager(HASH *hash)
{
	char target[20];

	do
	{
		printf("Enter the target (no space) or 0 to stop: ");
		scanf("%s", target);

		if(strcmp("0", target))
		{
			if(isInteger(target) && strlen(target) == 16)
			{
				convertStr(target);
				//printf("%s\n", target);
				searchHash(hash, target);
			}
			else
				printf ("Invalid input!!!\n");
		}
	}while(strcmp("0", target));

	return;
}
Exemple #13
0
void newPacketWHOHAS(queue *sendQueue)
{
    int i, j;
    int pktIndex = 0;
    int needToFetch = 0;
    int numHash = getChunk.numChunk;
    int numPacket = numHash / MAX_HASH_PER_PACKET;
    if(getChunk.numChunk % MAX_HASH_PER_PACKET > 0) {
        numPacket++;
    }

    for(i = 0; i < numPacket; i++) {
      int num;
      Packet *thisObj = newPacketDefault();
      incPacketSize(thisObj, 4);
      setPacketType(thisObj, "WHOHAS");
      if(i < numPacket - 1) {
	num = MAX_HASH_PER_PACKET;
      } else {
	num = getChunk.numChunk % MAX_HASH_PER_PACKET;
      }
      for(j = 0; j < num; j++) {
	while(getChunk.list[pktIndex].fetchState == 1
	      || (searchHash(getChunk.list[pktIndex].hash, &hasChunk, -1) >= 0)) {
	  pktIndex++;
	}
	if(pktIndex == numHash)
	  break;
	insertPacketHash(thisObj, getChunk.list[pktIndex].hash);
	needToFetch = 1;
	pktIndex++;
      }
      if(needToFetch)
	enqueue(sendQueue, (void *)thisObj);
    }
}
Exemple #14
0
void prepare (int len)

  { int i,id;
    Tpair pair;
    c = u = len;

    INI_c = c;  //fari... para mostrar numero de iteracion y progreso durante repair (mejora por cada nueva regla)
    
    alph = 0;
    for (i=0;i<u;i++) 
	{ if (C[i] > alph) alph = C[i];
	}
    n = ++alph;
    Rec = createRecords(factor,minsize);
    Heap = createHeap(u,&Rec,factor,minsize);
    Hash = createHash(256*256,&Rec);
    L = (void*)malloc(u*sizeof(Tlist));
    assocRecords (&Rec,&Hash,&Heap,L);
    for (i=0;i<c-1;i++) 
	{ pair.left = C[i]; pair.right = C[i+1];
	  id = searchHash (Hash,pair);
    	  if (id == -1) // new pair, insert
	     { id = insertRecord (&Rec,pair);
	       L[i].next = -1;
	     }
	  else 
	     { L[i].next = Rec.records[id].cpos;
	       L[L[i].next].prev = i;
	       incFreq (&Heap,id);
	     }
	  L[i].prev = -id-1;
	  Rec.records[id].cpos = i;
if (PRNL && (i%10000 == 0)) printf ("Processed %i chars\n",i);
	}
    purgeHeap (&Heap);
  }
Exemple #15
0
// Fari:
// Posto que alpha = num_terminais = valor do primeiro non-terminal.
//  ** a primeira regla sería: alpha <-- left1,right1
//  ** a  segunda regla sería: alpha +1 <-- left2, right2
// por iso no ficheiro de reglas só garda <alpha> e despois: left1, right1, left2, right2,... 
// pois xa sabe que os valores alpha, alpha+1,... son contiguos ;)
int repair (FILE *R)

  { int oid,id,cpos;
    Trecord *rec,*orec;
    Tpair pair;
    if (fwrite(&alph,sizeof(int),1,R) != 1) return -1;
if (PRNC) prnC();

int i=0;  //fari... solo para mostrar numero de iteracion
double prev_ratio =100.0;

while (n+1 > 0)
{ 
	if (PRNR) prnRec();
		oid = extractMax(&Heap);
		if (oid == -1) break; // the end!!
		orec = &Rec.records[oid];
		cpos = orec->cpos;
		if (fwrite (&orec->pair,sizeof(Tpair),1,R) != 1) return -1;
	if (PRNP) 
		{ printf("Chosen pair %i = (",n);
		  prnSym(orec->pair.left);
		  printf(",");
		  prnSym(orec->pair.right);
		  printf(") (%i occs)\n",orec->freq);
		}
	while (cpos != -1)
	   { int ant,sgte,ssgte; 
		// replacing bc->e in abcd, b = cpos, c = sgte, d = ssgte
	     if (C[cpos+1] < 0) sgte = -C[cpos+1]-1; 
	     else sgte = cpos+1; 
	     if ((sgte+1 < u) && (C[sgte+1] < 0)) ssgte = -C[sgte+1]-1;
	     else ssgte = sgte+1; 
		// remove bc from L
	     if (L[cpos].next != -1) L[L[cpos].next].prev = -oid-1;
	     orec->cpos = L[cpos].next;
	     if (ssgte != u) // there is ssgte
		{ 	// remove occ of cd
		  pair.left = C[sgte]; pair.right = C[ssgte];
		  id = searchHash(Hash,pair);
		  if (id != -1) // may not exist if purgeHeap'd
	             { if (id != oid) decFreq (&Heap,id); // not to my pair!
		       if (L[sgte].prev != NullFreq) //still exists(not removed)
 		          { rec = &Rec.records[id];
		            if (L[sgte].prev < 0) // this cd is head of its list
		               rec->cpos = L[sgte].next;
		            else L[L[sgte].prev].next = L[sgte].next;
		            if (L[sgte].next != -1) // not tail of its list
		               L[L[sgte].next].prev = L[sgte].prev;
			  }
		     }
			// create occ of ed
	          pair.left = n;
		  id = searchHash(Hash,pair);
	          if (id == -1) // new pair, insert
		     { id = insertRecord (&Rec,pair);
 		       rec = &Rec.records[id];
	               L[cpos].next = -1;
		     }
	          else 
 		     { incFreq (&Heap,id);
 		       rec = &Rec.records[id]; 
	               L[cpos].next = rec->cpos;
	               L[L[cpos].next].prev = cpos;
	             }
	          L[cpos].prev = -id-1;
	          rec->cpos = cpos;
		}
	     if (cpos != 0) // there is ant
		{ 	// remove occ of ab
	          if (C[cpos-1] < 0) 
		     { ant = -C[cpos-1]-1; 
		       if (ant == cpos) // sgte and ant clashed -> 1 hole
			  ant = cpos-2;
		     }
	          else ant = cpos-1; 
		  pair.left = C[ant]; pair.right = C[cpos];
		  id = searchHash(Hash,pair);
		  if (id != -1) // may not exist if purgeHeap'd
	             { if (id != oid) decFreq (&Heap,id); // not to my pair!
		       if (L[ant].prev != NullFreq) //still exists (not removed)
 		          { rec = &Rec.records[id];
		            if (L[ant].prev < 0) // this ab is head of its list
		                 rec->cpos = L[ant].next;
		            else L[L[ant].prev].next = L[ant].next;
		            if (L[ant].next != -1) // it is not tail of its list
		               L[L[ant].next].prev = L[ant].prev;
			  }
		     }
			// create occ of ae
	          pair.right = n;
		  id = searchHash(Hash,pair);
	          if (id == -1) // new pair, insert
		     { id = insertRecord(&Rec,pair);
 		       rec = &Rec.records[id];
	               L[ant].next = -1;
	             }
	          else 
	             { incFreq (&Heap,id);
 		       rec = &Rec.records[id];
	               L[ant].next = rec->cpos;
	               L[L[ant].next].prev = ant;
	             }
	          L[ant].prev = -id-1;
	          rec->cpos = ant;
		}
	     C[cpos] = n;
	     if (ssgte != u) C[ssgte-1] = -cpos-1;
	     C[cpos+1] = -ssgte-1;
	     c--;
 	     orec = &Rec.records[oid]; // just in case of Rec.records realloc'd
	     cpos = orec->cpos;
	   }
	   
	if (PRNC) prnC();
	 removeRecord (&Rec,oid);
	 n++;
	 purgeHeap(&Heap); // remove freq 1 from heap
	 if (c < factor * u) // compact C
	    { int i,ni;
	      i = 0;
	      for (ni=0;ni<c-1;ni++) 
		{ C[ni] = C[i];
		  L[ni] = L[i];
		  if (L[ni].prev < 0) 
		     { if (L[ni].prev != NullFreq) // real ptr
			  Rec.records[-L[ni].prev-1].cpos = ni; 
		     }
		  else L[L[ni].prev].next = ni;
		  if (L[ni].next != -1) L[L[ni].next].prev = ni;
		  i++; if (C[i] < 0) i = -C[i]-1;
		}
	      C[ni] = C[i];
	      u = c;
	      C = realloc (C, c * sizeof(int));
	      L = realloc (L, c * sizeof(Tlist));
              assocRecords (&Rec,&Hash,&Heap,L);
	    }
       
       
    //*fari*/  
    i++;  //fari... para mostrar numero de iteracion 
    if ( ( i<10) || (! ((i-1)%100)) ) 
    	printf("Repair.compress: It: %d compressed: %3.15f %% |c| = %d , diff prev iter = %2.15f\n", i, 100.0*c/INI_c, c, (prev_ratio - (100.0*c/INI_c)) );
     //cout << "Repair.compress: It: " << i++ << " compressed: " << 100.*c/INI_c << "%" << " |c|=" << c << endl;
	//if ((100.*m/n)<43.0) break;
	//if ((100.0*c/INI_c)< CORTE_REPAIR) break;

	//if  (  ((prev_ratio - (100.0*c/INI_c)) < 0.00000009 )  ||  ((100.0*c/INI_c)< CORTE_REPAIR) ) break;
	
	//if  (  ((prev_ratio - (100.0*c/INI_c)) < 0.000000005 )  ||  (((prev_ratio - (100.0*c/INI_c)) < CORTE_REPAIR) ) ) 
	if    (((prev_ratio - (100.0*c/INI_c)) < CORTE_REPAIR) ) 
	break;

	  	
	prev_ratio = (100.0*c/INI_c);
	  	
} //while 
printf("Repair.compress: It: %d compressed: %3.15f %% |c| = %d , diff prev iter = %2.15f \n", i, 100.0*c/INI_c, c, (prev_ratio - (100.0*c/INI_c)) );
//printf("Repair.compress: It: %d compressed: %3.8f %% |c| = %d \n", i, 100.0*c/INI_c, c);
     return 0;
   }
Exemple #16
0
void flushDownload(int sock)
{
  int i = 0;
  int idx;
  uint8_t *hash;
  Packet *pkt;
  connDown *pool = downloadPool;
  for(i = 0; i < peerInfo.numPeer; i++) {
    int peerID = peerInfo.peerList[i].peerID;
    Packet *ack = peek(pool[peerID].ackSendQueue);

    while(ack != NULL) {
      peerList_t *p = &(peerInfo.peerList[i]);
      fprintf(stderr,"Sending ACK %d\n", getPacketAck(ack));
      int retVal = spiffy_sendto(sock,
				 ack->payload,
				 getPacketSize(ack),
				 0,
				 (struct sockaddr *) & (p->addr),
				 sizeof(p->addr));
      fprintf(stderr,"Sent ACK %d\n", getPacketAck(ack));
      if(retVal == -1) { // spiffy_sendto() does not work!!
	fprintf(stderr,"spiffy_sendto() returned -1.\n");
	enqueue(pool[peerID].ackSendQueue, dequeue(pool[peerID].ackSendQueue));
      } else {
	dequeue(pool[peerID].ackSendQueue);
	freePacket(ack);
	ack = dequeue(pool[peerID].ackSendQueue);
      }
    }

    switch(pool[peerID].state) {
    case 0: // Ready
      pkt = dequeue(pool[peerID].getQueue);
      while(pkt != NULL) {
	hash = getPacketHash(pkt, 0);
	printHash(hash);
	idx = searchHash(hash, &getChunk, 0);
	if(idx == -1) { // Someone else is sending or has sent this chunk
	  freePacket(pkt);
	  pkt = dequeue(pool[peerID].getQueue);
	} else if(numConnDown < maxConn){
	  getChunk.list[idx].fetchState = 2;
	  if(downloadPool[peerID].connected == 1)
	    fprintf(stderr,"NOT SUPPOSED TO BE CONNECTEED! \n\n\n\n\n\n");
	  downloadPool[peerID].connected = 1;
	  numConnDown++;
	  break;
	} else { // Cannot allow more download connections
	  fprintf(stderr,"->No more download connection allowed!\n");
	  pool[peerID].state = 2;
	  break;
	}
      }
      if(pool[peerID].state == 2)
	break;
      
      if(pkt != NULL) {
	fprintf(stderr,"Sending a GET\n");
	peerList_t *p = &(peerInfo.peerList[i]);
	hash = pkt->payload + 16;
	char buf[50];
	bzero(buf, 50);
	binary2hex(hash, 20, buf);
	fprintf(stderr,"GET hash:%s\n", buf);
	pool[peerID].curChunkID = searchHash(hash, &getChunk, -1);
	
	int retVal = spiffy_sendto(sock,
				   pkt->payload,
				   getPacketSize(pkt),
				   0,
				   (struct sockaddr *) & (p->addr),
				   sizeof(p->addr));

	if(retVal == -1) { // Spiffy is broken!
	  fprintf(stderr,"spiffy_snetto() returned -1.\n");
	  newPacketWHOHAS(nonCongestQueue);
	  freePacket(pkt);
	  cleanUpConnDown(&(pool[peerID]));
	  numConnDown--;
	  return;
	}

	setPacketTime(pkt);

	enqueue(pool[peerID].timeoutQueue, pkt);
	pool[peerID].state = 1;
      }
      break;
    case 1: { // Downloading
      pkt = peek(pool[peerID].timeoutQueue);
      struct timeval curTime;
      gettimeofday(&curTime, NULL);
      long dt = diffTimeval(&curTime, &(pkt->timestamp));
      if(dt > GET_TIMEOUT_SEC) {
	pool[peerID].timeoutCount++;
	fprintf(stderr,"GET request timed out %d times!\n", pool[peerID].timeoutCount);
	setPacketTime(pkt);
	if(pool[peerID].timeoutCount == 3) {
	  getChunk.list[pool[peerID].curChunkID].fetchState = 0;
	  pool[peerID].state = 0;
	  newPacketWHOHAS(nonCongestQueue);
	  freePacket(pkt);
	  cleanUpConnDown(&(pool[peerID]));
	  numConnDown--;
	}
      }
      break;
    }
    case 2: {
      break;
    }
    default:
      break;
    }

  }
}
Exemple #17
0
//===================================================================
// Reads in the data from a file and inserts into BST and hashed
// array.
//===================================================================
void readInFile(DATA_HEAD *data) {
    FILE *dataFile;
    COMPANY *companyNode;
    char filename[MAX_CHARS], tmpName[MAX_CHARS];
    char ch;
    int tmpRev, tmpProfit, tmpNumEmployee;
    int i = 0, isDuplicate, len, size;

    do {
        printf("Please enter a filename [enter for default]:");
        fgets(filename, MAX_CHARS, stdin);

        if (filename[0] == '\n')
            strcpy(filename, default_file);
        else {
            //flush new line
            len = strlen(filename);

            if (filename[len - 1] == '\n' || filename[len - 1] == '\r')
                filename[len - 1] = '\0'; // change '\n' to '\0'
            else // no '\n' read, so flush to '\n'
                while ((ch = getchar()) != '\n' && ch != '\r');
        }

        dataFile = fopen(filename, "r");
    } while(!dataFile);

    //Creates structures
    data->pTree  = createBST(myStringCompare);
    data->pStack = createStack();

    size = getArrSize(dataFile);
    //need to reopen connection
    dataFile = fopen(filename, "r");

    data->arraySize = size;
    data->count = 0;
    data->pHash = (HASH *)malloc(sizeof(DATA_HEAD) *data->arraySize);

    //initialize hashed array
    for (i = 0; i < data->arraySize; i++) {
        data->pHash[i].status = 0;
        data->pHash[i].numOfCollisions = 0;
        data->pHash[i].numOfProbes = 0;
        data->pHash[i].hashData = NULL;
    }

    //Reads in, parses, mallocs, assigns
    while (fscanf(dataFile, " %[^,],%d,%d,%d[^\n]", tmpName, &tmpRev, &tmpProfit, &tmpNumEmployee) != EOF)
    {
        companyNode = (COMPANY *)malloc(sizeof(COMPANY));

        //Checks to see if allocated properly
        if (!companyNode)
            exit(1);

        companyNode->companyName = (char *)malloc(strlen(tmpName) + 1);

        //Checks to see if allocated properly
        if (!(companyNode->companyName))
            exit(1);

        strcpy(companyNode->companyName, tmpName);
        companyNode->numberOfEmployees = tmpNumEmployee;
        companyNode->revenuePerBillion = tmpRev;
        companyNode->profitPerMillion = tmpProfit;

        //Inserts company data (name, revenue, profit, employees) into the BST
        //If duplicate, print an error
        isDuplicate = searchHash(data, tmpName, companyNode);
        if (isDuplicate == 1)
            printf("ERROR: DUPLICATE DATA\n");
        else
        {
            insertHash(data, companyNode);
            insertBST(data->pTree, companyNode);
            data->count++;
        }
    }
    printf("\nNumber Of Data Records read in: %d\n\n", data->count);
    fclose(dataFile);
}
Exemple #18
0
int handleDefcpugrp( void *fcb, unsigned int cpugrpid,
		int cpuorcpugrpidarraydim, const unsigned int *cpuorcpugrpidarray,
		const char *cpugrpname ) {


	uint32_t* procs;
	uint32_t i;
	int existing;
	uint32_t tmp;
	/* set first bit to 1 */
	uint32_t mpg= (uint32_t) cpugrpid | 0x80000000;

	fcbT *fha= ((fcbT*)fcb);


	if ( ( 1 << 31 ) > (int)cpugrpid ) {

		fprintf( stderr, "WARNING in '%s': "
			"VTF3 cpu group id '%u' < 2^31 invalid\n", "handleDefcpugrp", cpugrpid );
	}


	/* add the mapping */
	existing= 1;
	while( 1 == existing ) {
	
		existing= 0;
	
		for( i= 0; i < (uint32_t)fha->reservedIdsc; ++i ) {
		
			if( fha->reservedIds[i] == mpg ) {
				existing= 1;
				++mpg;
				break;
			}
		}
	}
	addHash( fha->pghash, (uint32_t) cpugrpid, mpg );
	
	fha->reservedIds= (uint32_t *) realloc( fha->reservedIds, sizeof( uint32_t )
		* ( fha->reservedIdsc + 1 ) );
	fha->reservedIds[fha->reservedIdsc]= mpg;
	++fha->reservedIdsc;
	
	procs= (uint32_t*) malloc( cpuorcpugrpidarraydim * sizeof(uint32_t) );
	assert( procs );

	for ( i= 0; i < (uint32_t)cpuorcpugrpidarraydim; i++ ) {

		if( 0 == (cpuorcpugrpidarray[i]&0x80000000) ) {
		
			procs[i]= cpuorcpugrpidarray[i] +1;
			
		} else {
		
			tmp= searchHash( fha->pghash, cpuorcpugrpidarray[i] );
			if( 0 != tmp ) {
			
				procs[i]= tmp;
				
			} else {
			
				procs[i]= cpuorcpugrpidarray[i];
			}
		}
	}

	fha->processgroups= ( ProcessGroup* ) realloc( fha->processgroups,
		sizeof(ProcessGroup) * (fha->processgroupcount + 1) );
	assert( NULL != fha->processgroups );

	fha->processgroups[fha->processgroupcount].id= mpg;
	fha->processgroups[fha->processgroupcount].size= cpuorcpugrpidarraydim;
	fha->processgroups[fha->processgroupcount].procs= procs;
	fha->processgroups[fha->processgroupcount].name= strdup( cpugrpname );

	fha->processgroupcount++;

	return 0;
}