コード例 #1
0
JDMainWin::JDMainWin(const QString &name, const QString &jid, int acc, QWidget *p)
	: QDialog(p, Qt::Window)
	, model_(0)
	, commands_(0)
	, refreshInProgres_(false)
	, yourJid_(name)
{
	setAttribute(Qt::WA_DeleteOnClose);
	ui_.setupUi(this);

	setWindowTitle(tr("Jabber Disk - %1").arg(name));

	model_ = new JDModel(jid, this);
	ui_.lv_disk->setModel(model_);

	commands_ = new JDCommands(acc, jid, this);

	ui_.pb_send->setShortcut(QKeySequence("Ctrl+Return"));
	connect(commands_, SIGNAL(incomingMessage(QString,JDCommands::Command)), SLOT(incomingMessage(QString,JDCommands::Command)));
	connect(commands_, SIGNAL(outgoingMessage(QString)), SLOT(outgoingMessage(QString)));
	connect(ui_.pb_refresh, SIGNAL(clicked()), SLOT(refresh()));
	connect(ui_.pb_send, SIGNAL(clicked()), SLOT(doSend()));
	connect(ui_.pb_clear, SIGNAL(clicked()), SLOT(clearLog()));

	connect(ui_.lv_disk, SIGNAL(newIndex(QModelIndex)), SLOT(indexChanged(QModelIndex)));
	connect(ui_.lv_disk, SIGNAL(contextMenu(QModelIndex)), SLOT(indexContextMenu(QModelIndex)));

	connect(model_, SIGNAL(moveItem(QString,QString)), SLOT(moveItem(QString,QString)));

	show();

	QTimer::singleShot(0, this, SLOT(refresh()));
}
コード例 #2
0
ファイル: Utils.cpp プロジェクト: sudarsun/c48
int_array Utils::Sort(int_array &array_Renamed)
{

    int_array index = initialIndex((int)array_Renamed.size());
    int_array newIndex(array_Renamed.size());
    int_array helpIndex;
    int numEqual;

    quickSort(array_Renamed, index, 0, (int)array_Renamed.size() - 1);

    // Make sort stable
    int i = 0;
    while (i < index.size()) {
        numEqual = 1;
        for (int j = i + 1; ((j < index.size()) && (array_Renamed[index[i]] == array_Renamed[index[j]])); j++) {
            numEqual++;
        }
        if (numEqual > 1) {
            helpIndex = int_array(numEqual);
            for (int j = 0; j < numEqual; j++) {
                helpIndex[j] = i + j;
            }
            quickSort(index, helpIndex, 0, numEqual - 1);
            for (int j = 0; j < numEqual; j++) {
                newIndex[i + j] = index[helpIndex[j]];
            }
            i += numEqual;
        }
        else {
            newIndex[i] = index[i];
            i++;
        }
    }
    return newIndex;
}
コード例 #3
0
ファイル: API.cpp プロジェクト: HBzju/minisql
void API_Create_Table(string tablename,FieldTree *T)
{
//	try{
		//catalog meta data
		Table tbl(tablename);
		tbl.initializeTable(T);
		tbl.createTable();
		string primaryIdxName=tablename+"PRIMARY_INDEX";
		Index newIndex(primaryIdxName);
		IndexStruct Idx;
		Idx.attr_name = tbl.getPrimaryKey();
		Idx.index_name = primaryIdxName;
		Idx.table_name = tablename;

		newIndex.initializeIndex(&Idx);
		newIndex.createIndex();
		//End of catalog do
		//IndexManager do
		IndexInfo idxInfo;
		idxInfo.indexname = Idx.table_name + "PRIMARY_INDEX";
		idxInfo.attr_size=tbl.getPrimaryKeySize();
		idxInfo.maxKeyNum=(BLOCKSIZE-INDEX_BLOCK_INFO-4)/(4+idxInfo.attr_size);
		Create_Index_Init(idxInfo);
		//End of IndexManager do
/*	}
	catch(...){
		cout<<"Failed to Create Table."<<endl;
	}*/
}
コード例 #4
0
ファイル: CatalogManager.cpp プロジェクト: cszqwe/MINISQL
int CatalogManager::creatTable(string tableName, int attrNum, string *attrName, int* attrType){
	int id = bufferManager->newPage();
	page* thisPage = bufferManager->findPage(id);
	string content = "";
	char temp[64];
	sprintf(temp,"%d",id);
	string pageID(temp);

	content= "[{\"TableName\": \"" + tableName+"\",\"pageID\": \"" + pageID+"\"}]";
	jsonReader.parse(content,jsonContent);
	for (int i = 0; i < attrNum; i++){
		char* newNumber;
		sprintf(newNumber,"%d",attrType[i]);
		char* index;
		sprintf(index,"%d",i);
		if ((attrType[i]>=10)&&(attrType[i]<20)){
			
			sprintf(temp,"%d",i);
			string pkPosition(temp);
			jsonContent.append("{\"AttrName\": \"" + attrName[i]+"\",\"AttrType\": \"" + newNumber+"\",\"PrimaryKey\": \"" + pkPosition+"\",\"index\": \"" + string(index)+"\"}");
			newIndex(tableName, attrName[i], attrName[i]);
		}else
			jsonContent.append("{\"AttrName\": \"" + attrName[i]+"\",\"AttrType\": \"" + newNumber+"\",\"index\": \"" + string(index)+"\"}");
	}
	save(id);
	return id;
}
コード例 #5
0
 void ImageStackDirectoryDatasource::convertToOneDimension()
 {
     auto oldProjectionProperties = metaDataNodes;
     metaDataNodes.clear();
     auto oldImageLocations = imageLocations;
     imageLocations.clear();
     for ( auto it = oldProjectionProperties.begin(); it != oldProjectionProperties.end(); ++it )
     {
         HyperStackIndex oldIndex = it->first;
         HyperStackIndex newIndex(oldIndex[0]);
         metaDataNodes[newIndex] = oldProjectionProperties[oldIndex];
         imageLocations[newIndex] = oldImageLocations[oldIndex];
     }
 }
コード例 #6
0
ファイル: Utils.cpp プロジェクト: sudarsun/c48
int_array Utils::stableSort(double_array &array_Renamed)
{

    int_array index = initialIndex((int)array_Renamed.size());

    if (array_Renamed.size() > 1) {

        int_array newIndex(array_Renamed.size());
        int_array helpIndex;
        int numEqual;

        //array_Renamed = array_Renamed.clone();
        replaceMissingWithMAX_VALUE(array_Renamed);
        quickSort(array_Renamed, index, 0, (int)array_Renamed.size() - 1);

        // Make sort stable

        int i = 0;
        while (i < index.size()) {
            numEqual = 1;
            for (int j = i + 1; ((j < index.size()) && Utils::eq(array_Renamed[index[i]], array_Renamed[index[j]])); j++) {
                numEqual++;
            }
            if (numEqual > 1) {
                helpIndex = int_array(numEqual);
                for (int j = 0; j < numEqual; j++) {
                    helpIndex[j] = i + j;
                }
                quickSort(index, helpIndex, 0, numEqual - 1);
                for (int j = 0; j < numEqual; j++) {
                    newIndex[i + j] = index[helpIndex[j]];
                }
                i += numEqual;
            }
            else {
                newIndex[i] = index[i];
                i++;
            }
        }
        return newIndex;
    }
    else {
        return index;
    }
}
コード例 #7
0
static void AddDependency( 
	CVertInfo *dependencies, 
	int sideLength,
	CVertIndex const &nodeIndex,
	CVertIndex const &dependency,
	int iMaxPower,
	bool bCheckNeighborDependency,
	bool bAddReverseDependency )
{
	int iNodeIndex = VertIndex( nodeIndex, iMaxPower );
	CVertInfo *pNode = &dependencies[iNodeIndex];

	int iDep = GetFreeDependency( pNode->m_Dependencies, sizeof(pNode->m_Dependencies)/sizeof(pNode->m_Dependencies[0]) );
	pNode->m_Dependencies[iDep].m_iVert = dependency;
	pNode->m_Dependencies[iDep].m_iNeighbor = -1;

	if( bAddReverseDependency )
	{
		CVertInfo *pDep = &dependencies[VertIndex( dependency, iMaxPower )];
		iDep = GetFreeDependency( pDep->m_ReverseDependencies, CVertInfo::NUM_REVERSE_DEPENDENCIES );
		pDep->m_ReverseDependencies[iDep].m_iVert = nodeIndex;
		pDep->m_ReverseDependencies[iDep].m_iNeighbor = -1;
	}

	// Edge verts automatically add a dependency for the neighbor.
	// Internal verts wind up in here twice anyway so it doesn't need to 
	if( bCheckNeighborDependency )
	{
		int iConnection = GetEdgeIndexFromPoint( nodeIndex, iMaxPower );
		if( iConnection != -1 )
		{
			Assert( !pNode->m_Dependencies[1].IsValid() );

			CVertIndex delta( nodeIndex.x - dependency.x, nodeIndex.y - dependency.y );
			CVertIndex newIndex( nodeIndex.x + delta.x, nodeIndex.y + delta.y );
			
			int fullSideLength = (1 << iMaxPower) + 1;
			pNode->m_Dependencies[1].m_iVert = WrapVertIndex( CVertIndex( newIndex.x, newIndex.y ), fullSideLength );
			pNode->m_Dependencies[1].m_iNeighbor = iConnection;
		}
	}
}
コード例 #8
0
ファイル: mlogsup.c プロジェクト: kkaempf/openwbem
static MLogHeader *newMLogHeader(int s)
{
   MLogHeader *ah;
   int l;

   if (lindex==NULL) newIndex();

   if (freeHdrs) {
      ah=freeHdrs;
      freeHdrs=ah->area[0];
      ah->cur=0;
      if (debug) printf("--- newMLogHeader() reuse: %p\n",ah);
   }
   else {
      l=sizeof(MLogHeader)+((s-1)*sizeof(void*));
      ah=(MLogHeader*)malloc(l);
      memset(ah,0,l);
      ah->max=s;
      if (debug) if (debug) printf("--- newMLogHeader() new: %p\n",ah);
   }
   ah->cur=0;
   return ah;
}
コード例 #9
0
ファイル: Modedit.cpp プロジェクト: Sappharad/modizer
// Base code for adding, removing, moving and duplicating instruments. Returns new number of instruments on success, INSTRUMENTINDEX_INVALID otherwise.
// The new instrument vector can contain INSTRUMENTINDEX_INVALID for adding new (empty) instruments.
// newOrder indices are zero-based, i.e. newOrder[0] will define the contents of the first instrument slot.
INSTRUMENTINDEX CModDoc::ReArrangeInstruments(const std::vector<INSTRUMENTINDEX> &newOrder, deleteInstrumentSamples removeSamples)
//--------------------------------------------------------------------------------------------------------------------------------
{
	if(newOrder.size() > m_SndFile.GetModSpecifications().instrumentsMax || GetNumInstruments() == 0)
	{
		return INSTRUMENTINDEX_INVALID;
	}

	CriticalSection cs;

	const INSTRUMENTINDEX oldNumInstruments = m_SndFile.GetNumInstruments(), newNumInstruments = static_cast<INSTRUMENTINDEX>(newOrder.size());

	std::vector<ModInstrument> instrumentHeaders(oldNumInstruments + 1);
	std::vector<INSTRUMENTINDEX> newIndex(oldNumInstruments + 1, 0);	// One of the new indexes for the old instrument
	for(INSTRUMENTINDEX i = 0; i < newNumInstruments; i++)
	{
		const INSTRUMENTINDEX origSlot = newOrder[i];
		if(origSlot > 0 && origSlot <= oldNumInstruments)
		{
			if(m_SndFile.Instruments[origSlot] != nullptr)
				instrumentHeaders[origSlot] = *m_SndFile.Instruments[origSlot];
			newIndex[origSlot] = i + 1;
		}
	}

	// Delete unused instruments first.
	for(INSTRUMENTINDEX i = 1; i <= oldNumInstruments; i++)
	{
		if(newIndex[i] == 0)
		{
			m_SndFile.DestroyInstrument(i, removeSamples);
		}
	}

	m_SndFile.m_nInstruments = newNumInstruments;

	// Now, create new instrument list.
	for(INSTRUMENTINDEX i = 0; i < newNumInstruments; i++)
	{
		ModInstrument *ins = m_SndFile.AllocateInstrument(i + 1);
		if(ins == nullptr)
		{
			continue;
		}

		const INSTRUMENTINDEX origSlot = newOrder[i];
		if(origSlot > 0 && origSlot <= oldNumInstruments)
		{
			// Copy an original instrument.
			*ins = instrumentHeaders[origSlot];
		}
	}

	// Free unused instruments
	for(INSTRUMENTINDEX i = newNumInstruments + 1; i <= oldNumInstruments; i++)
	{
		m_SndFile.DestroyInstrument(i, doNoDeleteAssociatedSamples);
	}

	PrepareUndoForAllPatterns(false, "Rearrange Instrumens");
	GetInstrumentUndo().RearrangeInstruments(newIndex);

	std::vector<ModCommand::INSTR> indices(newIndex.size(), 0);
	for(size_t i = 0; i < newIndex.size(); i++)
	{
		indices[i] = newIndex[i];
	}
	m_SndFile.Patterns.ForEachModCommand(RewriteInstrumentReferencesInPatterns(indices));

	return GetNumInstruments();
}
コード例 #10
0
ファイル: Modedit.cpp プロジェクト: Sappharad/modizer
// Base code for adding, removing, moving and duplicating samples. Returns new number of samples on success, SAMPLEINDEX_INVALID otherwise.
// The new sample vector can contain SAMPLEINDEX_INVALID for adding new (empty) samples.
// newOrder indices are zero-based, i.e. newOrder[0] will define the contents of the first sample slot.
SAMPLEINDEX CModDoc::ReArrangeSamples(const std::vector<SAMPLEINDEX> &newOrder)
//-----------------------------------------------------------------------------
{
	if(newOrder.size() > m_SndFile.GetModSpecifications().samplesMax)
	{
		return SAMPLEINDEX_INVALID;
	}

	CriticalSection cs;

	const SAMPLEINDEX oldNumSamples = m_SndFile.GetNumSamples(), newNumSamples = static_cast<SAMPLEINDEX>(newOrder.size());

	std::vector<int> sampleCount(oldNumSamples + 1, 0);
	std::vector<ModSample> sampleHeaders(oldNumSamples + 1);
	std::vector<SAMPLEINDEX> newIndex(oldNumSamples + 1, 0);	// One of the new indexes for the old sample
	std::vector<std::string> sampleNames(oldNumSamples + 1);
	std::vector<mpt::PathString> samplePaths(oldNumSamples + 1);

	for(SAMPLEINDEX i = 0; i < newNumSamples; i++)
	{
		const SAMPLEINDEX origSlot = newOrder[i];
		if(origSlot > 0 && origSlot <= oldNumSamples)
		{
			sampleCount[origSlot]++;
			sampleHeaders[origSlot] = m_SndFile.GetSample(origSlot);
			if(!newIndex[origSlot]) newIndex[origSlot] = i + 1;
		}
	}

	// First, delete all samples that will be removed anyway.
	for(SAMPLEINDEX i = 1; i < sampleCount.size(); i++)
	{
		if(sampleCount[i] == 0)
		{
			m_SndFile.DestroySample(i);
			GetSampleUndo().ClearUndo(i);
		}
		sampleNames[i] = m_SndFile.m_szNames[i];
		samplePaths[i] = m_SndFile.GetSamplePath(i);
	}

	// Remove sample data references from now unused slots.
	for(SAMPLEINDEX i = newNumSamples + 1; i <= oldNumSamples; i++)
	{
		m_SndFile.GetSample(i).pSample = nullptr;
		m_SndFile.GetSample(i).nLength = 0;
		strcpy(m_SndFile.m_szNames[i], "");
	}

	// Now, create new sample list.
	m_SndFile.m_nSamples = std::max(m_SndFile.m_nSamples, newNumSamples);	// Avoid assertions when using GetSample()...
	for(SAMPLEINDEX i = 0; i < newNumSamples; i++)
	{
		const SAMPLEINDEX origSlot = newOrder[i];
		ModSample &target = m_SndFile.GetSample(i + 1);
		if(origSlot > 0 && origSlot <= oldNumSamples)
		{
			// Copy an original sample.
			target = sampleHeaders[origSlot];
			if(--sampleCount[origSlot] > 0 && sampleHeaders[origSlot].pSample != nullptr)
			{
				// This sample slot is referenced multiple times, so we have to copy the actual sample.
				target.pSample = ModSample::AllocateSample(target.nLength, target.GetBytesPerSample());
				if(target.pSample != nullptr)
				{
					memcpy(target.pSample, sampleHeaders[origSlot].pSample, target.GetSampleSizeInBytes());
					target.PrecomputeLoops(m_SndFile, false);
				} else
				{
					Reporting::Error("Cannot duplicate sample - out of memory!");
				}
			}
			strcpy(m_SndFile.m_szNames[i + 1], sampleNames[origSlot].c_str());
			m_SndFile.SetSamplePath(i + 1, samplePaths[origSlot]);
		} else
		{
			// Invalid sample reference.
			target.Initialize(m_SndFile.GetType());
			target.pSample = nullptr;
			strcpy(m_SndFile.m_szNames[i + 1], "");
			m_SndFile.ResetSamplePath(i + 1);
		}
	}

	GetSampleUndo().RearrangeSamples(newIndex);

	for(CHANNELINDEX c = 0; c < CountOf(m_SndFile.m_PlayState.Chn); c++)
	{
		ModChannel &chn = m_SndFile.m_PlayState.Chn[c];
		for(SAMPLEINDEX i = 1; i <= oldNumSamples; i++)
		{
			if(chn.pModSample == &m_SndFile.GetSample(i))
			{
				chn.pModSample = &m_SndFile.GetSample(newIndex[i]);
				if(i == 0 || i > newNumSamples)
				{
					chn.Reset(ModChannel::resetTotal, m_SndFile, c);
				}
				break;
			}
		}
	}

	m_SndFile.m_nSamples = newNumSamples;

	if(m_SndFile.GetNumInstruments())
	{
		// Instrument mode: Update sample maps.
		for(INSTRUMENTINDEX i = 0; i <= m_SndFile.GetNumInstruments(); i++)
		{
			ModInstrument *ins = m_SndFile.Instruments[i];
			if(ins == nullptr)
			{
				continue;
			}
			GetInstrumentUndo().RearrangeSamples(i, newIndex);
			for(auto &sample : ins->Keyboard)
			{
				if(sample < newIndex.size())
					sample = newIndex[sample];
				else
					sample = 0;
			}
		}
	} else
	{
		PrepareUndoForAllPatterns(false, "Rearrange Samples");

		std::vector<ModCommand::INSTR> indices(newIndex.size(), 0);
		for(size_t i = 0; i < newIndex.size(); i++)
		{
			indices[i] = newIndex[i];
		}
		m_SndFile.Patterns.ForEachModCommand(RewriteInstrumentReferencesInPatterns(indices));
	}

	return GetNumSamples();
}
コード例 #11
0
ファイル: multiSolver.C プロジェクト: Marupio/multiSolver
void Foam::multiSolver::buildDictionary
(
    dictionary& outputDict,
    const dictionary& inputDict,
    const word& solverDomainName
)
{
    outputDict.remove("sameAs");
    outputDict.remove("multiLoad");
    wordList alreadyMerged(0);
    wordList mergeMe(0);
    if (inputDict.found("default"))
    {
        if (outputDict.found("multiLoad"))
        {
            mergeMe = wordList(outputDict.lookup("multiLoad"));
            outputDict.remove("multiLoad");
        }
        if (outputDict.found("sameAs"))
        {
            label newIndex(mergeMe.size());
            mergeMe.setSize(newIndex + 1);
            mergeMe[newIndex] = word(outputDict.lookup("sameAs"));
            outputDict.remove("sameAs");
        }
    }
    
    // We load solverDomain last, but we need its sameAs / multiLoad now
    if (inputDict.found(solverDomainName))
    {
        const dictionary& solverDict(inputDict.subDict(solverDomainName));
        if (solverDict.found("multiLoad"))
        {
            mergeMe.append(wordList(solverDict.lookup("multiLoad")));
        }
        if (solverDict.found("sameAs"))
        {
            label newIndex(mergeMe.size());
            mergeMe.setSize(newIndex + 1);
            mergeMe[newIndex] = word(solverDict.lookup("sameAs"));
        }
    }
    
    label mergeI(-1);
    while ((mergeI + 1) < mergeMe.size())
    {
        mergeI++;
        bool skipMe(false);
        forAll(alreadyMerged, alreadyI)
        {
            if (mergeMe[mergeI] == alreadyMerged[alreadyI])
            {
                skipMe = true;
                break;
            }
        }
        if (skipMe)
        {
            break;
        }
        outputDict.merge(inputDict.subDict(mergeMe[mergeI]));
        
        // Add to alreadyMerged
        label mergedIndex(alreadyMerged.size());
        alreadyMerged.setSize(mergedIndex + 1);
        alreadyMerged[mergedIndex] = mergeMe[mergeI];
        
        // Recursive search
        if (outputDict.found("multiLoad"))
        {
            mergeMe.append(wordList(outputDict.lookup("multiLoad")));
            outputDict.remove("multiLoad");
        }
        if (outputDict.found("sameAs"))
        {
            label newMergeMeIndex(mergeMe.size());
            mergeMe.setSize(newMergeMeIndex + 1);
            mergeMe[newMergeMeIndex] = word(outputDict.lookup("sameAs"));
            outputDict.remove("sameAs");
        }
    }
    
    // Merge the solverDomain name, even if it already has merged
    if (inputDict.found(solverDomainName))
    {
        outputDict.merge(inputDict.subDict(solverDomainName));

        // These have been handled already        
        outputDict.remove("sameAs");
        outputDict.remove("multiLoad");
    }
}
コード例 #12
0
/**
 * Seta o valor de uma célula da matriz. Se já existir apenas altera o valor.
 */
void setCell(SparseMatrix* matrix, long x, long y, long value)
{
  Cell* cell = getCell(matrix, x, y);

  // Se existir, a célula troca o valor
  if (cell != NULL)
  {
    cell->_value = value;
    return;
  }

  // Verifica os índices máximos da matriz, e os troca se preciso
  if (x > matrix->_maximumX)
  {
    matrix->_maximumX = x;
  }

  if (y > matrix->_maximumY)
  {
    matrix->_maximumY = y;
  }

  // Cria uma nova célula
  cell = newCell(x, y, value);

  // Verifica se o índice (linha) atual existe
  Index* index     = matrix->_firstIndex;
  Index* cellIndex = NULL;

  while (index != NULL)
  {
    // Se a linha for igual, existe
    if (index->_value == y)
    {
      cellIndex = index;
      break;
    }

    index = index->_nextIndex;
  }

  // Se o índice não existir, cria um novo
  if (cellIndex == NULL)
  {
    cellIndex = newIndex(y);
  }

  // Adiciona o índice a matriz
  // Se o primeiro for vazio, tá certo
  if (matrix->_firstIndex == NULL)
  {
    matrix->_firstIndex = cellIndex;
  }
  // Senão insere o novo índice na ordem
  else
  {
    Index* currentIndex  = matrix->_firstIndex;
    Index* previousIndex = matrix->_firstIndex;

    while (true)
    {
      // Se for maior, vai para frente, senão insere
      if (currentIndex == NULL || cellIndex->_value < currentIndex->_value)
      {
        previousIndex->_nextIndex = cellIndex;
        cellIndex->_nextIndex     = currentIndex;
        break;
      }
      else
      {
        previousIndex = currentIndex;
        currentIndex  = currentIndex->_nextIndex;
      }
    }
  }

  // Insere a célula
  if (cellIndex->_cell == NULL)
  {
    cellIndex->_cell = cell;
  }
  else
  {
    Cell* currentCell  = cellIndex->_cell;
    Cell* previousCell = currentCell;

    while (true)
    {
      // Se o índice x for maior, vai para frente, senão insere
      if (currentCell == NULL || cell->_x < currentCell->_x)
      {
        previousCell->_nextCell = cell;
        cell->_nextCell         = currentCell;
        break;
      }
      else
      {
        previousCell = currentCell;
        currentCell  = currentCell->_nextCell;
      }
    }
  }
}
コード例 #13
0
bool ChainedIndex::insertRecord(const FRec& rec)
{
	bool inserted = true;
	filereader file;
	file.open(fileName, 'x');
	long firstIndexOffset = hash(rec.num) * sizeof(ChNode);
	ChNode firstIndexRecord;
	file.seek(firstIndexOffset, BEGIN);
	file.read_raw((char *) &firstIndexRecord, sizeof(ChNode));

	// if it is first record of the chain
	if (firstIndexRecord.key != INVALID_KEY)
	{
		long curIndexOffset = firstIndexOffset;
		ChNode curIndexRecord = firstIndexRecord;
		do
		{
			file.seek(curIndexOffset, BEGIN);
			file.read_raw((char *) &curIndexRecord, sizeof(ChNode));

			if (curIndexRecord.key == rec.num)
			{
				inserted = false;
				file.close();
				return inserted;
			}

			curIndexOffset = curIndexRecord.nextOffset;
		} while (curIndexOffset != INVALID_OFFSET);

		// we dont have duplicate
		// write the database record
		int newRecOffset = dbFile.insert(rec);
		int prevIndexOffset = file.offset() - sizeof(ChNode);

		// write new index record
		file.seek(0, END);
		int newIndexOffset = file.offset();
		ChNode newIndex(rec.num, newRecOffset);
		file.write_raw((char*) &newIndex, sizeof(ChNode));

		// write the cur index record
		curIndexRecord.nextOffset = newIndexOffset;
		file.seek(prevIndexOffset, BEGIN);
		file.write_raw((char*) &curIndexRecord, sizeof(ChNode));
	}
	else
	{
		// its the first record of the chain
		int newRecOffset = dbFile.insert(rec);
		// write the database record

		// write the prev index record
		firstIndexRecord.key = rec.num;
		firstIndexRecord.recOffset = newRecOffset;
		file.seek(firstIndexOffset, BEGIN);
		file.write_raw((char*) &firstIndexRecord, sizeof(ChNode));
	}
	file.close();
	return inserted;
}
コード例 #14
0
ファイル: treeCompressor.cpp プロジェクト: kota7/gogamer
//[[Rcpp::export]]
Rcpp::List tree_compressor(std::vector< std::vector<unsigned int> > children,
                           bool onebased = true)
{
  // Returns information to compress tree
  //
  // Args:
  //   children: a list of integer vectors of children pointers
  //   onebased: bool indicating if the children is given by one-base or zero-base
  //             default is true
  //
  // Returns:
  //   List containing
  //     indices : a list of integer vectors that specifies the index of new data
  //     parent  : an integer vector of new parent
  //     children: a list of integer vectors of new children

  std::vector< std::vector<int> > newIndices;
  std::vector<int> newParent;
  std::vector< std::vector<int> > newChildren;
  std::vector<int> newLeaf;

  // convert to zeo-based indices
  if (onebased) {
    for (unsigned int i = 0; i < children.size(); i++)
      for (unsigned int j = 0; j < children[i].size(); j++)
        children[i][j]--;
  }

  bool check = ValidateChildren(children);
  if (!check) Rcpp::stop("Invalid 'children' input");


  // make a list that maps current id to new id
  // note the difference from the newIndices, which
  // map the new id to current id
  // assume the first entry is the top node
  std::vector<int> newIndex(children.size());
  newIndex[0] = 0;
  int maxID = 0;
  AssignNewIndex(0, maxID, children, newIndex);


  // compile newIndices newParent, newChildren
  int newN = maxID + 1;
  newIndices.resize(newN);
  newParent.resize(newN);
  newChildren.resize(newN);
  unsigned int index;
  unsigned int childID;
  for (unsigned int i = 0; i < newIndex.size(); i++)
  {
    index = newIndex[i];
    newIndices[index].push_back(i + 1);
    for (unsigned int j = 0; j < children[i].size(); j++)
    {
      childID = newIndex[children[i][j]]; // new child ID
      if (index != childID) {
        // index may equal to childID, since the two may have been combined
        // if they differ, then they are parernt and child
        newChildren[index].push_back(childID + 1);
        newParent[childID] = index + 1;
      }
    }
  }
  // first entry is the root
  newParent[0] = 0;

  // compile newleaf
  for (int i = 0; i < newN; i++)
    if (newChildren[i].size() == 0) newLeaf.push_back(i + 1);

  // compile newIndex
  for (unsigned int i = 0; i < newIndex.size(); i++) newIndex[i]++;

  Rcpp::List out = Rcpp::List::create(
    Rcpp::Named("indices") = newIndices,
    Rcpp::Named("indexmap") = newIndex,
    Rcpp::Named("parent") = newParent,
    Rcpp::Named("children") = newChildren,
    Rcpp::Named("leaf") = newLeaf
  );
  return out;
}
コード例 #15
0
ファイル: Solver.cpp プロジェクト: xiaoyawei/VRPD
bool Solver::readFile(const char *filename){
    int m;
    const int buffSize = 256;
    char line[buffSize];
    std::ifstream in(filename);
    
    if (!in.is_open()) {
        std::cout << "FILE NOT FOUND!" << std::endl;
        exit(-1);
    }
    
    //skip the words
    for (int i = 0; i < 10; ++i) in.getline(line, buffSize);
    
    in.getline(line, buffSize);
    sscanf(line, "Fleet Size (k):%d\n", &numFleet);
    in.getline(line, buffSize);
    in.getline(line, buffSize);
    sscanf(line, "Alpha:%lf\n", &alpha);
    in.getline(line, buffSize);
    sscanf(line, "Drones Per Vehicle (l):%d\n", &numDrone);
    in.getline(line, buffSize);
    sscanf(line, "Drone Flight Duration (t_drone):%lf\n", &tDrone);
    in.getline(line, buffSize);
    sscanf(line, "Truck Capacity (cap_truck):%d\n", &truckCap);
    in.getline(line, buffSize);
    sscanf(line, "Depot ID(s) (d):%d\n", &depotIndex);
    in.getline(line, buffSize);
    sscanf(line, "N:%d\n", &numCustomer);
    in.getline(line, buffSize);
    sscanf(line, "M:%d\n", &m);
    droned = new bool[numCustomer];
    bestDroned = new bool[numCustomer];
    bestNextArray = new int[numCustomer];
    bestPreArray = new int[numCustomer];
    for (int i = 0; i < numCustomer; ++i) {
        droned[i] = false;
    }
//    droneDplyAtNode = new DroneDeployment[numCustomer];
    
    dist = new double*[numCustomer];
    dist[0] = new double[numCustomer * numCustomer];
    for (int i = 1; i < numCustomer; ++i)
        dist[i] = dist[i - 1] + numCustomer;
    nextNode = new int*[numCustomer];
    nextNode[0] = new int[numCustomer * numCustomer];
    for (int i = 1; i < numCustomer; ++i) {
        nextNode[i] = nextNode[i - 1] + numCustomer;
    }
    cost = new double*[numCustomer];
    cost[0] = new double[numCustomer * numCustomer];
    for (int i = 1; i < numCustomer; ++i)
        cost[i] = cost[i - 1] + numCustomer;
    pathLength = new int*[numCustomer];
    pathLength[0] = new int[numCustomer * numCustomer];
    for (int i = 1; i < numCustomer; ++i)
        pathLength[i] = pathLength[i - 1] + numCustomer;
    for (int i = 0; i < numCustomer; ++i) {
        for (int j = 0; j < numCustomer; ++j) {
            dist[i][j] = cost[i][j] = INF;
            nextNode[i][j] = 0;
            pathLength[i][j] = 0;
        }
    }
    for (int i = 0; i < numCustomer; ++i) {
        dist[i][i] = cost[i][i] = 0;
    }
    for (int i = 0; i < 4; ++i) in.getline(line, buffSize);
    for (int i = 0; i < m; ++i){
        int a, b;
        double c;
        in.getline(line, buffSize);
        sscanf(line, "%d,%d,%lf,false\n", &a, &b, &c);
        a = newIndex(a);
        b = newIndex(b);
        dist[a][b] = dist[b][a] = cost[a][b] = cost[b][a] = c;
//        dist[b][a] = c;
//        cost[a][b] = c;
//        cost[b][a] = c;
        nextNode[a][b] = b;
        nextNode[b][a] = a;
        pathLength[a][b] = pathLength[b][a] = 1;
    }
    for (int k = 0; k < numCustomer; ++k) {
        for (int i = 0; i < numCustomer; ++i) {
            for (int j = 0; j < numCustomer; ++j) {
                if (cost[i][j] > cost[i][k] + cost[k][j]) {
                    cost[i][j] = cost[i][k] + cost[k][j];
                    nextNode[i][j] = nextNode[i][k];
                    pathLength[i][j] = pathLength[i][k] + pathLength[k][j];
                }
            }
        }
    }
    
    nodes = new Coordinate[numCustomer];
    for (int i = 0; i < 4; ++i) in.getline(line, buffSize);
    for (int i = 1; i <= numCustomer; ++i) {
        double x, y;
        in.getline(line, buffSize);
        sscanf(line, "%lf,%lf\n", &x, &y);
        nodes[newIndex(i)].set(x, y);
    }
    for (int i = 1; i < numCustomer; ++i) {
        nodes[i].set(nodes[i].getX() - nodes[0].getX(), nodes[i].getY() - nodes[0].getY());
    }
    nodes[0].set(0, 0);
    
    in.close();
    createNodeInfo();
//    for (int i = 0; i < numCustomer; ++i) {
//        for (int j = 0; j < numCustomer; ++j) {
//            std::cout << cost[i][j] << " ";
//        }
//        std::cout << std::endl;
//    }
    return true;
}