Esempio n. 1
0
int main (void)
{
	struct entry  node0, node1, node2, node3, node4;
	root = &node0;

	node0.value = 0;
	node0.next = &node1;
	node1.value = 1;
	node1.next = &node2;
	node2.value = 2;
	node2.next = (struct entry *) 0;
	node3.value = 3;
	node4.value = 4;

	printList (root);
	
	printf("\nInserting value %i after value %i\n", node3.value, node2.value);
	insertEntry(&node2, &node3);

	printList(root);

	printf("\nInserting value %i at the beginning\n", node4.value);
	insertEntry(&node4,(struct entry *) 0 );

	printList(root);
	
	return 0;
}
Esempio n. 2
0
int main (void)
{
	struct entry root, node1, node2, node3, node4;
	struct entry *listPtr = &root;

	root.value = 0;
	root.next = &node1;
	node1.value = 1;
	node1.next = &node2;
	node2.value = 2;
	node2.next = (struct entry *) 0;
	node3.value = 3;
	node4.value = 4;

	printList (listPtr);
	//listPtr = &root;
	printf("\nInserting value %i after value %i\n", node3.value, node2.value);
	insertEntry(listPtr, &node3, 2 );

	printList(listPtr);

	printf("\nInserting value %i after value %i\n", node4.value, root.value);
	insertEntry(listPtr, &node4, root.value );

	printList(listPtr);

	return 0;
}
Esempio n. 3
0
void KMDriverDB::loadDbFile()
{
	// first clear everything
	m_entries.clear();
	m_pnpentries.clear();

	TQFile	f(dbFile());
	if (f.exists() && f.open(IO_ReadOnly))
	{
		TQTextStream	t(&f);
		TQString		line;
		TQStringList	words;
		KMDBEntry	*entry(0);

		while (!t.eof())
		{
			line = t.readLine().stripWhiteSpace();
			if (line.isEmpty())
				continue;
			int	p = line.find('=');
			if (p == -1)
				continue;
			words.clear();
			words << line.left(p) << line.mid(p+1);
			if (words[0] == "FILE")
			{
				if (entry) insertEntry(entry);
				entry = new KMDBEntry;
				entry->file = words[1];
			}
			else if (words[0] == "MANUFACTURER" && entry)
				entry->manufacturer = words[1].upper();
			else if (words[0] == "MODEL" && entry)
				entry->model = words[1];
			else if (words[0] == "MODELNAME" && entry)
				entry->modelname = words[1];
			else if (words[0] == "PNPMANUFACTURER" && entry)
				entry->pnpmanufacturer = words[1].upper();
			else if (words[0] == "PNPMODEL" && entry)
				entry->pnpmodel = words[1];
			else if (words[0] == "DESCRIPTION" && entry)
				entry->description = words[1];
			else if (words[0] == "RECOMMANDED" && entry && words[1].lower() == "yes")
				entry->recommended = true;
			else if (words[0] == "DRIVERCOMMENT" && entry)
				entry->drivercomment = ("<qt>"+words[1].replace("&lt;", "<").replace("&gt;", ">")+"</qt>");
		}
		if (entry)
			insertEntry(entry);
	}
}
Esempio n. 4
0
void main() {

	Table *table = createTable(11);
	TableEntry entry[11];
	initialize(&entry[0], "coke", 20);
	insertEntry(table, &entry[0]);
	initialize(&entry[1], "bsererreeaffsfsd", 20);
	insertEntry(table, &entry[1]);
	initialize(&entry[2], "bfdsfadsfb", 20);
	insertEntry(table, &entry[2]);
	initialize(&entry[3], "bfdafdsbb", 20);
	insertEntry(table, &entry[3]);
	initialize(&entry[4], "milk tefssfa", 15);
	insertEntry(table, &entry[4]);
	initialize(&entry[5], "apple judffice", 30);
	insertEntry(table, &entry[5]);
	initialize(&entry[6], "orange juidsce", 25);
	insertEntry(table, &entry[6]);
	initialize(&entry[7], "black tefdfdsa", 10);
	insertEntry(table, &entry[7]);


	findTable(table, "bsererreeaffsfsd");
	findTable(table, "c*k");
	findTable(table, "milk tea");
	findTable(table, "apple juice");
	findTable(table, "black tea");
	findTable(table, "b");

	system("pause");
}
Esempio n. 5
0
int main(void) {
	void insertEntry(struct entry *entryPointer, struct entry *elementPointer);
	struct entry n1, n2, n3, n4;
	struct entry *entryPointer = &n3; // pointer to the list entry to be inserted
	struct entry *elementPointer = &n2; // pointer to element after which entry has to be inserted

	n1.value = 100;
	n2.value = 200;
	n3.value = 300;
	n4.value = 400;

	n1.next = &n2;
	n2.next = &n4;
	n4.next = (struct entry *) 0;

	printf("Before insertion n2.next.value: \n");
	printf("%i\n", (*n2.next).value);

	insertEntry(entryPointer, elementPointer);
	printf("After insertion n2.next.value, n3.next.value:\n");
	printf("%i, %i\n", (n2.next)->value, (n3.next)->value);


	return 0;
}
Esempio n. 6
0
void ReducerHashPack<Q>::insert(ConstMonoRef multiple, const Poly& poly) {
  MATHICGB_ASSERT(&poly.ring() == &mRing);
  if (poly.isZero())
    return;
  NewConstTerm termMultiple = {1, multiple.ptr()};
  insertEntry(new (mPool.alloc()) MultipleWithPos(poly, termMultiple));
}
Esempio n. 7
0
Stream *ZipArchive::createNewFile(const char *filename, Compressor *method)
{
   ZipEntry *ze = new ZipEntry;
   ze->mIsDirectory = false;
   ze->mCD.setFilename(filename);
   insertEntry(ze);

   ZipTempStream *stream = new ZipTempStream(&ze->mCD);
   if(stream->open())
   {
      Stream *retStream = method->createWriteStream(&ze->mCD, stream);
      if(retStream == NULL)
      {
         delete stream;
         return NULL;
      }

      ZipStatFilter *filter = new ZipStatFilter(&ze->mCD);
      if(! filter->attachStream(retStream))
      {
         delete filter;
         delete retStream;
         delete stream;
         return NULL;
      }

      ze->mCD.mCompressMethod = method->getMethod();
      ze->mCD.mInternalFlags |= CDFileOpen;

      return filter;
   }

   return NULL;
}
Esempio n. 8
0
// Insert the key/value pair into the config database.
// If the database already contains an entry for this key, then replace it
// with the new key/value pair.
void OsConfigDb::set(const UtlString& rKey, const UtlString& rNewValue)
{
   OsWriteLock lock(mRWMutex);

   if (rKey.length() > 0) {
      insertEntry(rKey, rNewValue);
   }
}
Esempio n. 9
0
void ReducerHashPack<Q>::insertTail(NewConstTerm multiple, const Poly& poly) {
  MATHICGB_ASSERT(&poly.ring() == &mRing);
  if (poly.termCount() <= 1)
    return;
  auto entry = new (mPool.alloc()) MultipleWithPos(poly, multiple);
  ++entry->pos;
  insertEntry(entry);
}
/****************************************************************************
Desc:	Setup two child blocks for a root block.
****************************************************************************/
RCODE F_BtreeRoot::setupTree(
    FLMBYTE *		pucMidEntry,		// If !NULL entry to insert into root.
    eDynRSetBlkTypes		eBlkType,			// Leaf or non-leaf
    F_BtreeBlk **	ppLeftBlk,			// (out)
    F_BtreeBlk **	ppRightBlk)			// (out)
{
    RCODE			rc = NE_FLM_OK;
    F_BtreeBlk *	pLeftBlk = NULL;
    F_BtreeBlk *	pRightBlk = NULL;

    if (RC_BAD( rc = newBlk( &pLeftBlk, eBlkType)))
    {
        goto Exit;
    }

    if (RC_BAD( rc = newBlk( &pRightBlk, eBlkType)))
    {
        goto Exit;
    }

    if (eBlkType == ACCESS_BTREE_NON_LEAF)
    {
        ((F_BtreeNonLeaf *)pRightBlk)->lemBlk( lemBlk());
    }

    // Fix up the linkages

    pLeftBlk->nextBlk( pRightBlk->blkAddr());
    pRightBlk->prevBlk( pLeftBlk->blkAddr());
    lemBlk( pRightBlk->blkAddr());

    if (pucMidEntry)
    {

        // Add the midentry to the root block.  Search to position and insert.

        searchEntry( pucMidEntry);
        insertEntry( pucMidEntry, pLeftBlk->blkAddr());
    }
    m_uiLevels++;

    if (ppLeftBlk)
    {
        *ppLeftBlk = pLeftBlk;
    }
    if (ppRightBlk)
    {
        *ppRightBlk = pRightBlk;
    }

Exit:

    return( rc);
}
Esempio n. 11
0
int main(void)
{


  struct entry  *insertEntry (struct entry  *listPtr, struct entry  *elementInsertAfter);
  struct entry  entryToInsert, n1, n2, n3;
  // set existing node values

  n1.value = 30;
  n2.value = 40;
  n3.value = 50;

  n1.next = &n2;
  n2.next = &n3;
  n3.next = 0;

  // set entry to insert

  // entryToInsert.value = 100;
  // struct entry  *entryPtr = &entryToInsert;
  // struct entry  *elementInsertAfter = &n3;
  //
  //
  // struct entry  *listPtr;   // store result
  // listPtr = insertEntry(entryPtr, elementInsertAfter);

// insert new element at front of the list
// create new entry
  struct entry  n4;
  n4.value = 500;
  struct entry  *n4Pointer;
  n4Pointer = &n4;

  struct entry *n1Pointer;
  n1Pointer = &n1;

  struct entry  *listPtr2;
  // insert to front of list
  listPtr2 = insertEntry(n1Pointer, n4Pointer);
  
  listPtr2 = &n4;
  // print out all values in list
  while (listPtr2 != (struct entry *) 0 )
  {
    printf("Entry %i.\n", listPtr2->value);
    listPtr2 = listPtr2->next;
  }


  // printf("Entry %i.\n", listPtr->value);

}
Esempio n. 12
0
File: ex4.c Progetto: reinka/coding
int main(int argc, char const *argv[])
{
	struct entry neu, *list_pointer = &l1; //POINTER TO THE BEGINNING OF THE LIST

	l1.value = 1;
	l1.p = &l2;

	l2.value = 2;
	l2.p = &l3;

	l3.value = 3;
	l3.p = &l4;

	l4.value = 4;
	l4.p = &l5;

	l5.value = 5;
	//NULL POINTER MARKING THE END OF THE LIST
	l5.p = (struct entry *) 0; 

	neu.value = 100;
	neu.p = &neu;

	printf("Testing some stuff\n");
	printf("l1.p = %p, l2.p = %p, l3.p = %p, neu.p = %p, list_pointer = %p\n", l1.p, l2.p, l3.p, neu.p, list_pointer);
	
	//INSWERT NEW LIST ENTRY, PASSING POINTER ADDRESS TO FUNCTION
	insertEntry(&neu.p, &list_pointer);

	while(list_pointer){
		printf("%d\n", list_pointer->value);
		list_pointer = list_pointer->p;
	}

	//SINCE neu WAS INSERTED TO THE LIST:
	list_pointer = &neu;

	printf("Deleting entry now.\n");

	//REMOVING 1ST LIST ENTRY, PASSING POINTER ADDRESS TO FUNCTION
	removeEntry(&neu.p);
	//IF YOU WANNA REMOVE ONE OF THE OTHER ENTRIES,
	//USE &l1.p, &neu.p, &l2.p, &l3.p, &l4.p

	while(list_pointer){
		printf("%d\n", list_pointer->value);
		list_pointer = list_pointer->p;
	}


	return 0;
}
Esempio n. 13
0
/*
  Highscore-keeping class
*/
Highscore::Highscore()
{
  // TODO: Open and load score database
  int result = sqlite3_open("highscores.db", &db);
  if (result != SQLITE_OK)
  {
    printf("Highscore::Highscore(): Failed to open score database in 'highscores.db'! Highscore table will be empty.\n");
    printf("Error was:\n%s\n", sqlite3_errmsg(db));
    sqlite3_close(db);
    db = NULL;
  }
  else
  {
    char* error_msg = NULL;
    result = sqlite3_exec(db, "CREATE TABLE IF NOT EXISTS Highscores { scoreID INTEGER PRIMARY KEY, scoreNumber INTEGER, scoreName TEXT, scoreDate TEXT };", NULL, NULL, &error_msg);
    if (result != SQLITE_OK)
    {
      printf("Highscore::Highscore(): Failed to create highscore table in database file 'highscores.db'. Highscore table will be empty.\n");
      printf("Error was:\n%s\n", error_msg);
      sqlite3_free(error_msg);
      sqlite3_close(db);
      db = NULL;
    }
    
    {
      char** results;
      int numRows, numCols;
      result = sqlite3_get_table(db, "SELECT scoreID, scoreNumber, scoreName, scoreDate FROM Highscores ORDER BY scoreNumber;", &results, &numRows, &numCols, &error_msg);
      
      int indexID=0, indexNumber=1, indexName=2, indexDate=3;
      for (int i=0; i < numCols; i++)
      {
        if (strcmp(results[i], "scoreID") == 0)  indexID = i;
        else if (strcmp(results[i], "scoreNumber") == 0)  indexNumber = i;
        else if (strcmp(results[i], "scoreName") == 0)  indexName = i;
        else if (strcmp(results[i], "scoreDate") == 0)  indexDate = i;
      }
      // Process the table data
      for (int row=0; row < numRows; row++)
      {
        HighscoreEntry e(atol(results[numRows*(1+row)+indexNumber]),
                              string(results[numRows*(1+row)+indexName]),
                              string(results[numRows*(1+row)+indexDate]));
        insertEntry(e);
      }
      
      sqlite3_free_table(results);
    }
  }
} // end Highscore() constructor
Esempio n. 14
0
int AVL<T>::loadFromFile(string filename){
		ifstream fin;
	fin.open(filename.c_str());
	if(fin.fail()){
		return -1;
	}else{
		while(!fin.eof()){
			T word;
			fin >> word;
			insertEntry(word);
		}
	}
	return 0;
}
Esempio n. 15
0
int main(void) {
	void traverseList(struct entry *listPointer);	
	void removeEntry(struct entry *listPointer);
	void insertEntry(struct entry *listPointer, struct entry *entryPointer);
	struct entry n1, n2, n3;
	struct entry *startListPointer = &n1;
	struct entry *lastListPointer = &n3;
	struct entry *n2Pointer = &n2;

	n1.value = 100;
	n1.previous = (struct entry *) 0;
	n1.next = &n2;

	n2.value = 200;
	n2.previous = &n1;
	n2.next = &n3;

	n3.value = 300;
	n3.previous = &n2;
	n3.next = (struct entry *) 0;

	printf("First element to last traversal:\n");
	traverseList(startListPointer);

	printf("\n");

	printf("Last element to first traversal:\n");
	traverseList(lastListPointer);

	printf("\n");

	removeEntry(n2Pointer);
	printf("Traversal after removal of n2:\n");
	traverseList(startListPointer);

	printf("\n");

	insertEntry(startListPointer, n2Pointer);
	printf("Traversal after insertion of n2:\n");
	traverseList(startListPointer);

	return 0;
}
Esempio n. 16
0
bool ZipArchive::readCentralDirectory()
{
   mEntries.clear();
   SAFE_DELETE(mRoot);
   mRoot = new ZipEntry;
   mRoot->mName = "";
   mRoot->mIsDirectory = true;
   mRoot->mCD.setFilename("");

   if(! mEOCD.findInStream(mStream))
      return false;

   if(! mEOCD.read(mStream))
      return false;

   if(mEOCD.mDiskNum != mEOCD.mStartCDDiskNum ||
      mEOCD.mNumEntriesInThisCD != mEOCD.mTotalEntriesInCD)
   {
      if(isVerbose())
         Con::errorf("ZipArchive::readCentralDirectory - %s: Zips that span multiple disks are not supported.", mFilename ? mFilename : "<no filename>");
      return false;
   }

   if(! mStream->setPosition(mEOCD.mCDOffset))
      return false;

   for(S32 i = 0;i < mEOCD.mNumEntriesInThisCD;++i)
   {
      ZipEntry *ze = new ZipEntry;
      if(! ze->mCD.read(mStream))
      {
         delete ze;

         if(isVerbose())
            Con::errorf("ZipArchive::readCentralDirectory - %s: Error reading central directory.", mFilename ? mFilename : "<no filename>");
         return false;
      }

      insertEntry(ze);
   }

   return true;
}
Esempio n. 17
0
int main (void)
{
    void insertEntry (struct entry *entryPtr, struct entry *afterPtr);
    void removeEntry (struct entry *entryPtr);
    struct entry n1, n2, n3, n4;
    struct entry *listPtr = &n1;
    
    n1.value = 100;
    n1.prev = 0;
    n1.next = &n2;
    
    n2.value = 200;
    n2.prev = &n1;
    n2.next = &n3;
    
    n3.value = 300;
    n3.prev = &n2;
    n3.next = 0;
    
    n4.value = 400;
    insertEntry (&n4, &n2);
    
    while (listPtr != 0)
    {
        printf("%i\n", listPtr->value);
        listPtr = listPtr->next;
    }
    
    printf("\n");
    removeEntry (&n4);
    listPtr = &n1;
    
    while (listPtr != 0)
    {
        printf("%i\n", listPtr->value);
        listPtr = listPtr->next;
    }
    
    return 0;
}
Esempio n. 18
0
void SortedArray::add( Object& toAdd )
{
    if( toAdd.isSortable() )
        {
        if( lastElementIndex == upperbound )
            {
            reallocate( arraySize() + 1 );
            }
        int insertionPoint = lowerbound;
        while( insertionPoint <= lastElementIndex &&
               (Sortable&)objectAt( insertionPoint ) < (Sortable&)toAdd
             )
            insertionPoint++;

        insertEntry( insertionPoint );
        setData( insertionPoint, &toAdd );
        itemsInContainer++;
        lastElementIndex++;
        }
    else
        ClassLib_error( __ENOTSORT );
}
Esempio n. 19
0
int Highscore::addEntry(HighscoreEntry& he)
{
  // TODO: Insert entry (if applicable), update the database, and return the new index
  int index = insertEntry(he);
  
  if (index >= 0 && db != NULL)
  {
    char* error_msg;
    sqlite3_exec(db, "DELETE FROM Highscores WHERE scoreID = {SELECT scoreID FROM Highscores WHERE scoreNumber = {SELECT MAX(scoreNumber) FROM Highscores}};", NULL, NULL, &error_msg);
    if (error_msg != NULL)
      sqlite3_free(error_msg);
    
    ostringstream oss;
    oss << "INSERT INTO Highscores (scoreNumber, scoreName, scoreDate) VALUES (";
    oss << he.getScore() << ", '" << he.getName() << "', '" << he.getDate() << "');";
    
    sqlite3_exec(db, oss.str().c_str(), NULL, NULL, &error_msg);
    if (error_msg != NULL)
      sqlite3_free(error_msg);
  }
  
  return index;
}
Esempio n. 20
0
static matrix_t constructMat(unsigned int cols, unsigned int rows)
{
  unsigned int i;
  matrix_t m;
  size_t nbytes = matBytes(cols);
  unsigned int mat2offset = rightMatrixOffset(cols);

  /* printf("construct mat %u %u (%lu bytes)\n", cols, rows, rows*sizeof(row) + rows*(2*nbytes)); */
  /* If cols > rows, we write off the array */
  if (cols < rows) croak("SIMPQS:  cols %u > rows %u\n", cols, rows);
  New(0, m, rows, row_t);
  if (m == 0) croak("SIMPQS: Unable to allocate memory for matrix!\n");

  for (i = 0; i < rows; i++) { /* two matrices, side by side */
    Newz(0, m[i], 2*nbytes, unsigned char);
    if (m[i] == 0) croak("SIMPQS: Unable to allocate memory for matrix!\n");
  }

  /* make second matrix identity, i.e. 1's along diagonal */
  for (i = 0; i < rows; i++)
    insertEntry(m, i, mat2offset + i);

  return m;
}
void sysColumnsFunction(int choice)
{
	string fName;
	int pageSize,pNo,result;
	switch(choice)
	{
		case 1: cout<<"Enter the file name: ";
			cin>>fName;
			cout<<"Enter the page size: ";
			cin>>pageSize;
			result = createSysColumnFile(fName,pageSize);
			break;
		case 3: cout<<"Enter the file name: ";
			cin>>fName;
			cout<<"Enter the page size: ";
			cin>>pageSize;
			result = insertEntry(fName,pageSize);
			break;
		case 4: cout<<"Enter the file name: ";
			cin>>fName;
			cout<<"Enter the page size: ";
			cin>>pageSize;
			result = deleteEntry(fName,pageSize);
			break;
		case 6: cout<<"Enter the file name: ";
			cin>>fName;
			cout<<"Enter the page no.: ";
			cin>>pNo;
			cout<<"Enter the page size: ";
			cin>>pageSize;
			printhex(fName,pNo,pageSize);
			break;
		default: cout<<"Unimplemented operation..."<<endl;
			 break;
	}
}
Esempio n. 22
0
// Constructor for the Index class. The arguments passed in are 
//     'name' -- file name of the relation
//     'offset', 'length', 'type' -- describing the attribute indexed
//     'unique' -- flag for enforcing uniquess of the entries
Index::Index(const string& name, 
	     const int offset, 
	     const int length, 
	     const Datatype type, 
	     const int unique, 
	     Status& status)
{
  Page* pagePtr;
  file = 0;

  // For this assignment turn off hash indices on strings
  if (type == STRING ) 
  {
     status = NOCHARIDX;
     return;
  }
   
   
  if(name.empty()) {
    status = BADFILE;
    return;
  }
  if (offset < 0 || length < 1) {
    status = BADINDEXPARM;
    return;
  }

  if (type != STRING && type != INTEGER && type != DOUBLE){
    status = BADINDEXPARM;
    return;
  }
  if ((type == INTEGER && length != sizeof(int)) || 
      (type == DOUBLE && length != sizeof(double))) {
    status = BADINDEXPARM;
    return;
  }

  curBuc = NULL;

  recSize = length + sizeof(RID);     // size of the index entry
  numSlots = (PAGESIZE - 2*sizeof(short)) / recSize;   // # entries on a page

  status = OK;

  // get name of the index file by concatenating relation name and
  // the offset of the attribute

  ostringstream outputString;
  outputString << name << '.' << offset << ends;
  string indexName(outputString.str());

  // The constructor runs in two cases. In the first case, an index 
  // doesn't exist as detected by db.openFile. The relation file 
  // should be scanned and each tuple is inserted to the index. In
  // the second case, an index already exists. Only the headerPage
  // needs to read in and pinned down in the buffer pool.

  file = 0;
  status = db.openFile(indexName, file);
  if (status != OK) { // index doesn't exit. Create it

    status = db.createFile(indexName);
    if (status != OK)
      return;

    // open the file
    status = db.openFile(indexName, file);
    if (status != OK)
      return;

    // allocate and initialize the header page
    status = bufMgr->allocPage(file, headerPageNo, (Page*&)headerPage);
    if (status != OK)
      return;
    strcpy(headerPage->fileName, name.c_str());

    headerPage->offset = offset;
    headerPage->length = length;
    headerPage->type = type;
    headerPage->depth = 0;
    headerPage->unique = unique;
    dirSize = 1;

    // allocate and initialize the first bucket pointed by dir[0]
    int pageNo;
    Bucket* bucket;
    status = bufMgr->allocPage(file, pageNo, (Page*&)bucket);
    if (status != OK)
      return;
    bucket->depth = 0;
    bucket->slotCnt = 0;
    headerPage->dir[0] = pageNo;

    status = bufMgr->unPinPage(file, pageNo, true);
    if (status != OK)
      return;

    // build index by scanning the relation file and inserting every
    // tuple
    
    HeapFileScan heapFileScan(name, offset, length, type, NULL, EQ, status);

    if (status != OK)
      return;

    Record rec;
    RID   rid;

    while(1) {
      status = heapFileScan.scanNext(rid);
      if (status == FILEEOF)
	{
	  status = OK;
	  break;
	}
      status = heapFileScan.getRecord(rid, rec);
      if (status != OK)
	return;
      status = insertEntry((char *)rec.data + offset, rid);
      if (status != OK)
	return;
    }
  }
  else  { // file already exists.  get header page into the buffer pool

    status = file->getFirstPage(headerPageNo);
    if (status != OK) 
      {
	cerr << "fetch of first page failed\n";
        return;
      }
    status = bufMgr->readPage(file, headerPageNo, pagePtr);
    if (status != OK) 
      {
	cerr << "read of first page failed\n";
	return;
      }
    headerPage = (iHeaderPage*) pagePtr;
    dirSize = (int)pow(2.0, headerPage->depth);
  }
}
Esempio n. 23
0
/*==========================================================================
   evaluateSieve:

   Function: searches sieve for relations and sticks them into a matrix, then
             sticks their X and Y values into two arrays XArr and YArr

===========================================================================*/
static void evaluateSieve(
    unsigned long numPrimes,
    unsigned long Mdiv2,
    unsigned long * relations,
    unsigned long ctimesreps,
    unsigned long M,
    unsigned char * sieve,
    mpz_t A,
    mpz_t B,
    mpz_t C,
    unsigned long * soln1,
    unsigned long * soln2,
    unsigned char * flags,
    matrix_t m,
    mpz_t * XArr,
    unsigned long * aind,
    int min,
    int s,
    int * exponents,
    unsigned long * npartials,
    unsigned long * nrelsfound,
    unsigned long * nrelssought,
    mpz_t temp,
    mpz_t temp2,
    mpz_t temp3,
    mpz_t res)
{
     long i,j,ii;
     unsigned int k;
     unsigned int exponent, vv;
     unsigned char extra;
     unsigned int modp;
     unsigned long * sieve2;
     unsigned char bits;
     int numfactors;
     unsigned long relsFound = *nrelsfound;
     unsigned long relSought = *nrelssought;

     mpz_set_ui(temp, 0);
     mpz_set_ui(temp2, 0);
     mpz_set_ui(temp3, 0);
     mpz_set_ui(res, 0);
     i = 0;
     j = 0;
     sieve2 = (unsigned long *) sieve;
#ifdef POLS
     gmp_printf("%Zdx^2%+Zdx\n%+Zd\n",A,B,C);
#endif

     while ( (unsigned long)j < M/sizeof(unsigned long))
     {
        do
        {
           while (!(sieve2[j] & SIEVEMASK)) j++;
           i = j * sizeof(unsigned long);
           j++;
           while (((unsigned long)i < j*sizeof(unsigned long)) && (sieve[i] < threshold)) i++;
        } while (sieve[i] < threshold);

        if (((unsigned long)i<M) && (relsFound < relSought))
        {
           mpz_set_ui(temp,i+ctimesreps);
           mpz_sub_ui(temp, temp, Mdiv2); /* X         */

           mpz_set(temp3, B);             /* B          */
           mpz_addmul(temp3, A, temp);    /* AX+B       */
           mpz_add(temp2, temp3, B);      /* AX+2B      */
           mpz_mul(temp2, temp2, temp);   /* AX^2+2BX   */
           mpz_add(res, temp2, C);        /* AX^2+2BX+C */

           bits = mpz_sizeinbase(res,2) - errorbits;

           numfactors=0;
           extra = 0;
           memset(exponents, 0, firstprime * sizeof(int));

           if (factorBase[0] != 1 && mpz_divisible_ui_p(res, factorBase[0]))
           {
             extra += primeSizes[0];
             if (factorBase[0] == 2) {
                exponent = mpz_scan1(res, 0);
                mpz_tdiv_q_2exp(res, res, exponent);
             } else {
               mpz_set_ui(temp,factorBase[0]);
               exponent = mpz_remove(res,res,temp);
             }
             exponents[0] = exponent;
           }

           exponents[1] = 0;
           if (mpz_divisible_ui_p(res, factorBase[1]))
           {
             extra += primeSizes[1];
             if (factorBase[1] == 2) {
                exponent = mpz_scan1(res, 0);
                mpz_tdiv_q_2exp(res, res, exponent);
             } else {
               mpz_set_ui(temp,factorBase[1]);
               exponent = mpz_remove(res,res,temp);
             }
             exponents[1] = exponent;
           }

           for (k = 2; k < firstprime; k++)
           {
              modp=(i+ctimesreps)%factorBase[k];

              exponents[k] = 0;
              if (soln2[k] != (unsigned long)-1)
              {
                 if ((modp==soln1[k]) || (modp==soln2[k]))
                 {
                    extra+=primeSizes[k];
                    mpz_set_ui(temp,factorBase[k]);
                    exponent = mpz_remove(res,res,temp);
                    CHECK_EXPONENT(exponent, k);
                    PRINT_FB(exponent, k);
                    exponents[k] = exponent;
                 }
              } else if (mpz_divisible_ui_p(res, factorBase[k]))
              {
                 extra += primeSizes[k];
                 mpz_set_ui(temp,factorBase[k]);
                 exponent = mpz_remove(res,res,temp);
                 PRINT_FB(exponent, k);
                 exponents[k] = exponent;
              }
           }
           sieve[i]+=extra;
           if (sieve[i] >= bits)
           {
              vv=((unsigned char)1<<(i&7));
              for (k = firstprime; (k<secondprime)&&(extra<sieve[i]); k++)
              {
                 modp=(i+ctimesreps)%factorBase[k];
                 if (soln2[k] != (unsigned long)-1)
                 {
                    if ((modp==soln1[k]) || (modp==soln2[k]))
                    {
                       extra+=primeSizes[k];
                       mpz_set_ui(temp,factorBase[k]);
                       exponent = mpz_remove(res,res,temp);
                       CHECK_EXPONENT(exponent, k);
                       PRINT_FB(exponent, k);
                       if (exponent)
                         for (ii = 0; ii < (long)exponent; ii++)
                           set_relation(relations, relsFound, ++numfactors, k);
                       if (exponent & 1)
                         insertEntry(m,relsFound,k);
                    }
                 } else if (mpz_divisible_ui_p(res, factorBase[k]))
                 {
                    extra += primeSizes[k];
                    mpz_set_ui(temp,factorBase[k]);
                    exponent = mpz_remove(res,res,temp);
                    PRINT_FB(exponent, k);
                    for (ii = 0; ii < (long)exponent; ii++)
                      set_relation(relations, relsFound, ++numfactors, k);
                    if (exponent & 1)
                      insertEntry(m,relsFound,k);
                 }
              }


              for (k = secondprime; (k<numPrimes)&&(extra<sieve[i]); k++)
              {
                 if (flags[k]&vv)
                 {
                    modp=(i+ctimesreps)%factorBase[k];
                    if ((modp==soln1[k]) || (modp==soln2[k]))
                    {
                       extra+=primeSizes[k];
                       mpz_set_ui(temp,factorBase[k]);
                       exponent = mpz_remove(res,res,temp);
                       CHECK_EXPONENT(exponent, k);
                       PRINT_FB(exponent, k);
                       if (exponent)
                         for (ii = 0; ii < (long)exponent; ii++)
                           set_relation(relations, relsFound, ++numfactors, k);
                       if (exponent & 1)
                         insertEntry(m,relsFound,k);
                    }
                 }
              }

              for (ii =0; ii<s; ii++)
              {
                 xorEntry(m,relsFound,aind[ii]+min);
                 set_relation(relations, relsFound, ++numfactors, aind[ii]+min);
              }

              if (mpz_cmp_ui(res,1000)>0)
              {
                 if (mpz_cmp_ui(res,largeprime)<0)
                 {
                    (*npartials)++;
                 }
                 clearRow(m,numPrimes,relsFound);
#ifdef RELPRINT
                 gmp_printf(" %Zd\n",res);
#endif
              } else
              {
                 mpz_neg(res,res);
                 if (mpz_cmp_ui(res,1000)>0)
                 {
                    if (mpz_cmp_ui(res,largeprime)<0)
                    {
                       (*npartials)++;
                    }
                    clearRow(m,numPrimes,relsFound);
#ifdef RELPRINT
                    gmp_printf(" %Zd\n",res);
#endif
                 } else
                 {
#ifdef RELPRINT
                    printf("....R\n");
#endif
                    for (ii = 0; ii < (long)firstprime; ii++)
                    {
                       int jj;
                       for (jj = 0; jj < exponents[ii]; jj++)
                         set_relation(relations, relsFound, ++numfactors, ii);
                       if (exponents[ii] & 1)
                         insertEntry(m,relsFound,ii);
                    }
                    set_relation(relations, relsFound, 0, numfactors);

                    mpz_init_set(XArr[relsFound], temp3);  /* (AX+B) */

                    relsFound++;
#ifdef COUNT
                    if (relsFound%20==0) fprintf(stderr,"%lu relations, %lu partials.\n", relsFound, *npartials);
#endif
                 }
              }
           } else
           {
              clearRow(m,numPrimes,relsFound);
#ifdef RELPRINT
              printf("\r                                                                    \r");
#endif

           }
           i++;

        } else if (relsFound >= relSought) i++;
     }
     /* Update caller */
     *nrelsfound = relsFound;
     *nrelssought = relSought;
}
Esempio n. 24
0
UtlBoolean Listener::handleMessage(OsMsg& rMsg)
{
   // React to telephony events
   if(rMsg.getMsgSubType()== TaoMessage::EVENT)
   {
      TaoMessage* taoMessage = (TaoMessage*)&rMsg;

      TaoEventId taoEventId = taoMessage->getTaoObjHandle();
      UtlString argList(taoMessage->getArgList());
      TaoString arg(argList, TAOMESSAGE_DELIMITER);

#ifdef DEBUGGING
      dumpTaoMessageArgs(taoEventId, arg) ;
#endif        
      UtlBoolean localConnection = atoi(arg[TAO_OFFER_PARAM_LOCAL_CONNECTION]);
      UtlString  callId = arg[TAO_OFFER_PARAM_CALLID] ;
      UtlString  address = arg[TAO_OFFER_PARAM_ADDRESS] ;

      switch (taoEventId) 
      {
         case PtEvent::CONNECTION_OFFERED:
            OsSysLog::add(FAC_MEDIASERVER_VXI, PRI_DEBUG, "Call arrived: callId %s address %s\n", 
                          callId.data(), address.data());

            mpCallManager->acceptConnection(callId, address);
            mpCallManager->answerTerminalConnection(callId, address, "*");

            break;
         case PtEvent::CONNECTION_ESTABLISHED:
            if (localConnection) 
            {
               OsSysLog::add(FAC_MEDIASERVER_VXI, PRI_DEBUG, "Call connected: callId %s\n", callId.data());

               CallObject* pThisCall = new CallObject(mpCallManager, callId, mPlayfile);

               // Create a player and start to play out the file
               if (pThisCall->playAudio() == OS_SUCCESS)
               {
                  // Put it in a sorted list
                  insertEntry(callId, pThisCall);
               }
               else
               {
                  // Drop the call
                  mpCallManager->drop(callId);
                  OsSysLog::add(FAC_MEDIASERVER_VXI, PRI_WARNING, "Listener::handleMessage - drop callId %s due to failure of playing audio\n",
                                callId.data());

                  delete pThisCall;
               }
            }

            break;
            
         case PtEvent::CONNECTION_DISCONNECTED:
            if (!localConnection) 
            {
               OsSysLog::add(FAC_MEDIASERVER_VXI, PRI_DEBUG, "Call Dropped: %s\n", callId.data());

               // Remove the call from the pool and clean up the call
               CallObject* pDroppedCall = removeEntry(callId);
               if (pDroppedCall)
               {
                  pDroppedCall->cleanUp();
                  delete pDroppedCall;

                  // Drop the call
                  mpCallManager->drop(callId);
               }
               else
               {
                  OsSysLog::add(FAC_MEDIASERVER_VXI, PRI_DEBUG, "Lisenter::handleMessage - no callId %s founded in the active call list\n",
                                callId.data());
               }
            }

            break;
            
         case PtEvent::CONNECTION_FAILED:
            OsSysLog::add(FAC_MEDIASERVER_VXI, PRI_WARNING, "Dropping call: %s\n", callId.data());

            mpCallManager->drop(callId);

            break;
      }
   }
   return(TRUE);
}
/****************************************************************************
Desc:	Split the root block and make two new non-leaf blocks.
		The secret here is that the root block never moves (cheers!).
		This takes a little longer but is worth the work because the
		root block never goes out to disk and is not in the cache.
****************************************************************************/
RCODE F_BtreeRoot::split(
    void *			pvCurEntry,
    FLMUINT			uiCurChildAddr)
{
    RCODE				rc = NE_FLM_OK;
    FLMBYTE *		pucEntry;
    FLMBYTE *		pucChildAddr;
    F_BtreeBlk *		pLeftBlk;
    F_BtreeBlk *		pRightBlk;
    F_BtreeBlk *		pBlk;
    FLMUINT			uiChildAddr;
    FLMUINT			uiPos;
    FLMUINT			uiEntryCount = entryCount();
    FLMUINT			uiMid = (uiEntryCount + 1) >> 1;

    if (RC_BAD( rc = setupTree( NULL, ACCESS_BTREE_NON_LEAF,
                                &pLeftBlk, &pRightBlk)))
    {
        goto Exit;
    }

    // Call search entry once just to setup for insert.

    (void) pLeftBlk->searchEntry( ENTRY_POS( 0));

    // Take the entries from the root block and move into leafs.

    for (uiPos = 0; uiPos <= uiMid; uiPos++)
    {
        pucEntry = ENTRY_POS( uiPos);
        pucChildAddr = pucEntry + m_uiEntrySize;
        uiChildAddr = (FLMUINT)FB2UD(pucChildAddr);

        if (RC_BAD( rc = pLeftBlk->insertEntry( pucEntry, uiChildAddr)))
        {
            goto Exit;
        }
    }

    // Call search entry once just to setup for insert.

    (void) pRightBlk->searchEntry( ENTRY_POS( 0));

    for (uiPos = uiMid + 1; uiPos < uiEntryCount; uiPos++)
    {
        pucEntry = ENTRY_POS( uiPos);
        pucChildAddr = pucEntry + m_uiEntrySize;
        uiChildAddr = (FLMUINT)FB2UD(pucChildAddr);

        if ((rc = pRightBlk->searchEntry( pucEntry )) != NE_FLM_NOT_FOUND)
        {
            rc = RC_SET_AND_ASSERT( NE_FLM_FAILURE);
            goto Exit;
        }

        if (RC_BAD( rc = pRightBlk->insertEntry( pucEntry, uiChildAddr)))
        {
            goto Exit;
        }
    }

    // Reset the root block and insert new midpoint.

    entryCount( 0);
    lemBlk( pRightBlk->blkAddr());	// Duplicated just in case.
    pucEntry = ENTRY_POS( uiMid);

    if ((rc = searchEntry( pucEntry )) != NE_FLM_NOT_FOUND)
    {
        rc = RC_SET_AND_ASSERT( NE_FLM_FAILURE);
        goto Exit;
    }

    if (RC_BAD( rc = insertEntry( pucEntry, pLeftBlk->blkAddr() )))
    {
        goto Exit;
    }

    // Insert the current entry (parameters) into the left or right blk.
    // This could be done a number of different ways.
    (void) searchEntry( pvCurEntry, &uiChildAddr);
    if (RC_BAD( rc = readBlk( uiChildAddr, ACCESS_BTREE_NON_LEAF, &pBlk)))
    {
        goto Exit;
    }
    (void) pBlk->searchEntry( pvCurEntry);
    if (RC_BAD( rc = pBlk->insertEntry( pvCurEntry, uiCurChildAddr)))
    {
        goto Exit;
    }

Exit:

    return( rc);
}
/****************************************************************************
Desc:	Move first half of entries into new block.  Reset previous block
		to point to new block.  Add new last entry in new block to parent.
		Fixup prev/next linkages.
****************************************************************************/
RCODE F_BtreeBlk::split(
    F_BtreeRoot *	pRoot,
    FLMBYTE *		pucCurEntry,		// (in) Contains entry to insert
    FLMUINT			uiCurBlkAddr,		// (in) Blk addr if non-leaf
    FLMBYTE *		pucParentEntry,	// (out) Entry to insert into parent.
    FLMUINT *		puiNewBlkAddr)		// (out) New blk addr to insert into parent.
{
    RCODE				rc = NE_FLM_OK;
    F_BtreeBlk *		pPrevBlk;
    F_BtreeBlk *		pNewBlk = NULL;
    FLMBYTE *		pucEntry = NULL;
    FLMBYTE *		pucMidEntry;
    FLMBYTE *		pucChildAddr;
    FLMUINT			uiChildAddr;
    FLMUINT			uiPrevBlkAddr;
    FLMUINT			uiMid;
    FLMUINT			uiPos;
    FLMUINT			uiMoveBytes;
    FLMBOOL			bInserted = FALSE;

    // Allocate a new block for the split.

    if (RC_BAD( rc = pRoot->newBlk( &pNewBlk, blkType() )))
    {
        goto Exit;
    }
    pNewBlk->AddRef();				// Pin the block - may get flushed out.


    // the last half into the new block, but that would force the parent
    // entry to be changed.  This may take a little longer, but it is much
    // more easier to code.

    // Call search entry once just to setup for insert.

    (void) pNewBlk->searchEntry( ENTRY_POS( 0));

    // get the count and move more then half into the new block.

    uiMid = (entryCount() + 5) >> 1;
    uiChildAddr = FBTREE_END;

    for (uiPos = 0; uiPos < uiMid; uiPos++)
    {
        pucEntry = ENTRY_POS( uiPos);
        if (blkType() != ACCESS_BTREE_LEAF)
        {
            pucChildAddr = pucEntry + m_uiEntrySize;
            uiChildAddr = (FLMUINT)FB2UD(pucChildAddr);
        }

        // m_uiPosition automatically gets incremented.

        if (RC_BAD( rc = pNewBlk->insertEntry( pucEntry, uiChildAddr)))
        {
            RC_UNEXPECTED_ASSERT( rc);
            goto Exit;
        }
    }

    if (m_uiPosition < uiMid)
    {

        // Insert this entry now

        bInserted = TRUE;
        (void) pNewBlk->searchEntry( pucCurEntry);
        if (RC_BAD( rc = pNewBlk->insertEntry( pucCurEntry, uiCurBlkAddr)))
        {
            goto Exit;
        }
    }

    // Let caller insert into parent entry.  This rids us of recursion.

    f_memcpy( pucParentEntry, pucEntry, m_uiEntrySize);

    // Move the rest down

    pucEntry = ENTRY_POS( 0);
    pucMidEntry = ENTRY_POS( uiMid);

    entryCount( entryCount() - uiMid);
    uiMoveBytes = entryCount() * (m_uiEntrySize + m_uiEntryOvhd);
    flmAssert( uiMoveBytes < DYNSSET_BLOCK_SIZE - sizeof( FixedBlkHdr));
    f_memmove( pucEntry, pucMidEntry, uiMoveBytes);

    if( !bInserted)
    {

        // m_uiPosition -= uiMid;

        (void) searchEntry( pucCurEntry);
        if (RC_BAD( rc = insertEntry( pucCurEntry, uiCurBlkAddr)))
        {
            goto Exit;
        }
    }

    // VISIT: Could position stack to point to current element to insert.

    // Fixup the prev/next block linkages.

    if (prevBlk() != FBTREE_END)
    {
        if (RC_BAD( rc = pRoot->readBlk( prevBlk(), blkType(), &pPrevBlk )))
        {
            goto Exit;
        }

        pPrevBlk->nextBlk( pNewBlk->blkAddr());
        uiPrevBlkAddr = pPrevBlk->blkAddr();
    }
    else
    {
        uiPrevBlkAddr = FBTREE_END;
    }
    pNewBlk->prevBlk( uiPrevBlkAddr);
    pNewBlk->nextBlk( blkAddr());
    prevBlk( pNewBlk->blkAddr());

    *puiNewBlkAddr = pNewBlk->blkAddr();

Exit:

    if (pNewBlk)
    {
        pNewBlk->Release();
    }

    return( rc);
}
Esempio n. 27
0
int main (void)
{   
    void printEntries(struct entry *list_start);
    void printEntriesReverse(struct entry *list_start);
    struct entry *findEntry (struct entry *list_pointer, int match);
    void insertEntry (struct entry *insert_position, struct entry *new_entry);
    void removeEntry(struct entry *entry_to_remove);

    struct entry n1, n2, n3, n4, list_head, new_entry, *insert_position, *entry_to_remove;
    int new_value, insertion_place, value_remove;

    list_head.next = &n1;

    n1.value = 100;
    n1.next = &n2;
    n1.previous = (struct entry *) 0;
    
    n2.value = 200;
    n2.next = &n3;
    n2.previous = &n1;

    n3.value = 300;
    n3.next = &n4;
    n3.previous = &n2;

    n4.value = 400;
    n4.next = (struct entry *) 0;;
    n4.previous = &n3;

    // print entries
    printEntries(&n1);

    // print entries reverse
    printEntriesReverse(&n4);

    // Getting the new value
    printf("Which value to add? ");
    scanf("%i", &new_value);
    new_entry.value = new_value;

    // Getting the insertion location pointer
    printf("After which value to add it? ");
    scanf("%i", &insertion_place);
    insert_position = findEntry(&n1, insertion_place);

    //Inserting the value in the list
    insertEntry(insert_position, &new_entry);

    // printing list
    printEntries(&n1);

    // print entries reverse
    printEntriesReverse(&n4);

    // Selecting a value to remove
    printf("After which value to remove an entry? ");
    scanf("%i", &value_remove);
    entry_to_remove = findEntry(&n1, value_remove);

    // Removing the entry
    removeEntry(entry_to_remove);

    // printing list
    printEntries(&n1);
    printEntriesReverse(&n4);

    return 0;
}
int main(void)
{
	struct entry n0, n1, n2, n3, n4, nE;
	struct entry *listPtr = &n0;

	n0.value = '\0';
	n0.prev = 0;
	n0.next = &n1;

	n1.value = 100;
	n1.prev = 0;
	n1.next = &n2;

	n2.value = 200;
	n2.prev = &n1;
	n2.next = &n3;

	n3.value = 300;
	n3.prev = &n2;
	n3.next = &n4;

	n4.value = 400;
	n4.prev = &n3;
	n4.next = 0;

	nE.value = 350;

	printf("List before insertion:\n");
	while (listPtr != 0)
	{
		if (listPtr->value == 0)
		{
			listPtr = listPtr->next;
			continue;	
		}

		printf("%i\n", listPtr->value);
		listPtr = listPtr->next;
	}

	listPtr = &n0;

	insertEntry(&nE, &n3);

	printf("List after insertion:\n");
	while (listPtr != 0)
	{
		if (listPtr->value == 0)
		{
			listPtr = listPtr->next;
			continue;
		}

		printf("%i\n", listPtr->value);
		listPtr = listPtr->next;
	}

	listPtr = &n0;

	removeEntry(&n3);

	printf("List after removal:\n");
	while (listPtr != 0)
	{
		if (listPtr->value == 0)
		{
			listPtr = listPtr->next;
			continue;
		}

		printf("%i\n", listPtr->value);
		listPtr = listPtr->next;
	}

	return 0;
}
Esempio n. 29
0
void LinnCreate::insertDirectory(char *inputDir, le32 inodeNum, le32 parentNum)
{
    struct dirent *ent;
    struct stat st;
    DIR *dir;
    char path[255];
    le32 child;
    bool skip = false;

    /* Create '.' and '..' */
    insertEntry(inodeNum, inodeNum,  ".",  DirectoryFile);
    insertEntry(inodeNum, parentNum, "..", DirectoryFile);

    /* Open the input directory. */
    if ((dir = opendir(inputDir)) == NULL)
    {
	printf("%s: failed to opendir() `%s': %s\n",
		prog, inputDir, strerror(errno));
	exit(EXIT_FAILURE);
    }
    /* Read all it's entries. */
    while ((ent = readdir(dir)))
    {
	/* Hidden files. */
	skip = ent->d_name[0] == '.';
	
	/* Excluded files. */
	for (ListIterator<String *> e(&excludes); e.hasCurrent(); e++)
	{
            String dent = (const char *) ent->d_name;

	    if (dent.match(**e.current()))
	    {
		skip = true;
		break;
	    }
	}
	/* Skip file? */
	if (skip) continue;
	
	/* Construct local path. */
	snprintf(path, sizeof(path), "%s/%s",
		 inputDir, ent->d_name);

	/* Stat the file. */
	if (stat(path, &st) != 0)
	{
	    printf("%s: failed to stat() `%s': %s\n",
		    prog, path, strerror(errno));
	    exit(EXIT_FAILURE);
	}
	/* Create an inode for the child. */
	child = createInode(path, &st);
	
	/* Insert directory entry. */
	insertEntry(inodeNum, child, ent->d_name,
		    FILETYPE_FROM_ST(&st));
	
	/* Traverse down. */
	if (S_ISDIR(st.st_mode))
	{
	    insertDirectory(path, child, inodeNum);
	}
    }
    /* All done. */
    closedir(dir);
}
Esempio n. 30
0
const Status Index::insertEntry(const void *value, RID rid) 
{ 
  Bucket* bucket;
  Status status;
  Bucket *newBucket;
  int newPageNo;       
  char  data[PAGESIZE*2];
  int counter;
  int index;

  // If the 'unique' flag is set, scan the index to see if the
  // <attribute, rid> pair already exists

  if (headerPage->unique == UNIQUE) {
    RID outRid;

    if((status = startScan(value)) != OK)
      return status;
    while ((status = scanNext(outRid)) != NOMORERECS) {
      if (status != OK)
	return status;    
      if (!memcmp(&outRid, &rid, sizeof(RID)))
	return NONUNIQUEENTRY;
    }
    if((status = endScan()) != OK)
      return status;
  }
 
  // Get the bucket containing the entry into buffer pool
  status = hashIndex(value, index);
  int pageNo = headerPage->dir[index];

#ifdef DEBUGIND
  cout << "Inserting entry " << *(int*)value << " to bucket " 
    << pageNo << endl;
#endif 
 
  status = bufMgr->readPage(file, pageNo, (Page*&)bucket);
  if (status != OK) 
    return status;

  // the bucket needs to be splitted if the number of entries
  // on the bucket equals the maximum
  if (bucket->slotCnt == numSlots) { // splitting bucket
    
    // allocate a new bucket
    status = bufMgr->allocPage(file, newPageNo, (Page*&)newBucket);  
    if (status != OK)
      return status;

    // Initialize this newly allocated bucket
    newBucket->depth = ++(bucket->depth);
    newBucket->slotCnt = 0;

    // Copy all (value, rid) pairs in the old bucket and the new
    // entry to a temporary area
    memcpy(data, bucket->data, numSlots*recSize);
    memcpy(&(data[numSlots*recSize]), value, headerPage->length);
    memcpy(&(data[numSlots*recSize + headerPage->length]), &rid, sizeof(RID));

    counter = bucket->slotCnt + 1;
    bucket->slotCnt = 0;

    // the directory needs to be doubled if the depth of the bucket
    // being splitted equals the depth of the directory

    if (bucket->depth > headerPage->depth) { // doubling directory

      // The directory is doubled and the lower half of the directory
      // is copied to the upper half

      int newDirSize = 2 * dirSize;
      if (newDirSize > DIRSIZE)
	return DIROVERFLOW;
      for (int i = 0; i < dirSize; i++)
	headerPage->dir[i + dirSize] = headerPage->dir[i];

      dirSize = newDirSize;
      (headerPage->depth)++;
      headerPage->dir[index + (1 << (bucket->depth - 1))] = newPageNo;

    } else {

      // reset the appropriate directories to the new bucket
      int oldindex = index % (1 << (bucket->depth - 1));
      int newindex = oldindex + (1 << (bucket->depth - 1));
      for (int j = 0; j < dirSize; j++) 
	if ((j % (1 << (bucket->depth))) == newindex)
	  headerPage->dir[j] = newPageNo;
    }

#ifdef DEBUGIND
      printDir();
#endif 

    // call insertEntry recursively to insert all (value, rid) 
    // pairs in the temporary area to the index

    for (int k = 0; k < counter; k++) {
      value = &(data[k * recSize]);
      rid = * ((RID *)((char *)value + headerPage->length));
      status = insertEntry(value, rid);
      if (status != OK)
	return status;
    }
    status = bufMgr->unPinPage(file, newPageNo, true);
    if (status != OK)
      return status;

    } else { 
    // There is sufficient free space in the bucket. Insert (value, rid) here

    int offset = (bucket->slotCnt) * recSize;
    memcpy(&(bucket->data[offset]), value, headerPage->length);
    memcpy(&(bucket->data[offset+headerPage->length]), &rid, sizeof(RID));
    (bucket->slotCnt)++;
  }

  status = bufMgr->unPinPage(file, pageNo, true);
  return status;
}