Example #1
0
int TestHashTable_Int()
{
	HashTable<unsigned long, unsigned long> ht;

	const unsigned long                     max = 1000;
	unsigned long                           i;
	for (i = 0; i < max; i++) {
		ht.insert(i, max - i);
	}

	for (i = 0; i < max; i += 2) {
		TEST_ASSERT(ht.find(i) != 0);
	}

	for (i = 0; i < max; i += 2) {
		TEST_ASSERT(ht.erase(i));
	}

	for (i = 0; i < max; i += 2) {
		TEST_ASSERT(ht.find(i) == 0);
	}

	for (i = 1; i < max; i += 2) {
		TEST_ASSERT(ht.find(i) == max - i);
	}

	return 0;
}
Example #2
0
int main() {
    int value, result;
    bool found;
    
    HashTable A;
    
    value = 55;
    for (int i = 1; i < 21; i++) {      //Populates table with multiples of 55
        A.insert(value * i); 
    } 
        
    A.print();                          //Tests prints function
    
    value = A.size();
    cout << "Size is: " << value << endl;   //Tests size function
    
    //Code below tests that find works appropriately. Test values are reset
    //before each function call so as to ensure that values are being modified
    //appropriately.
    value = 165;
    result = 100;
    found = false;
    
    A.find(value, found, result);
    cout << "Value: " << value << endl;
    if (found) {
        cout << "Found: True" << endl;
    } else {
        cout << "Found: False" << endl;
    }
    cout << "Found at index: " << result << endl;
    
    value = 131;
    result = 100;
    found = false;
    
    A.find(value, found, result);
    cout << "Value: " << value << endl;
    if (found) {
        cout << "Found: True" << endl;
    } else {
        cout << "Found: False" << endl;
    }
    cout << "Found at index: " << result << endl;
    
    value = 1045;
    result = 100;
    found = false;
    
    A.find(value, found, result);
    cout << "Value: " << value << endl;
    if (found) {
        cout << "Found: True" << endl;
    } else {
        cout << "Found: False" << endl;
    }
    cout << "Found at index: " << result << endl;
    
    return 0;
}
Example #3
0
TEST(hashtable_test, simple_condition)
{
    HashTable *hashtable = new HashTable(4);
    EXPECT_EQ(hashtable->find(1, 5), -1);
    hashtable->insert(1, 5, 7);
    EXPECT_EQ(hashtable->find(1, 5), 7);
    hashtable->insert(2, 4, 8);
    hashtable->remove(1, 5);
    EXPECT_EQ(hashtable->find(1, 5), -1);
    delete hashtable;
}
int main(){
  cout << "Hello World\n";
  HashTable<int>* HT = new HashTable<int>(0);
  HT->insert("taco", 3);
  HT->insert("banana", 4);
  HT->insert("taco", 5);
  cout << HT->find("taco") << "\n";
  cout << HT->find("banana") << "\n";
  HT->remove("banana");
  cout << HT->find("banana") << "\n";
  delete HT;
}
Example #5
0
void
CHooker::HookModule(TCHAR *name)
{
	HMODULE h = LoadLibrary(name);
	if (h == NULL)
		return;

	IMAGE_DOS_HEADER *dosHeader = (IMAGE_DOS_HEADER *) h;
	IMAGE_NT_HEADERS *peHeader = (IMAGE_NT_HEADERS *) ((char *) h + dosHeader->e_lfanew);
	IMAGE_EXPORT_DIRECTORY *expDir = (IMAGE_EXPORT_DIRECTORY *) ((char *) h + peHeader->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT].VirtualAddress);

	DWORD *names = (DWORD *) ((char *) h + expDir->AddressOfNames);
	WORD *ordinals = (WORD *) ((char *) h + expDir->AddressOfNameOrdinals);
	DWORD *functions = (DWORD *) ((char *) h + expDir->AddressOfFunctions);

	size_t hookCountBefore = m_hookedAddrToName.size();

	for (unsigned int i = 0; i < expDir->NumberOfNames; i++)
	{
		char *name = (char *) h + names[i];
		void *addr = (unsigned char *) h + functions[ordinals[i]];

		if (m_hookedAddrToName.find(addr) == m_hookedAddrToName.end())
			HookFunction(name, addr);
	}

	cout << "CHooker::HookModule: <" << name << "> hooked " << m_hookedAddrToName.size() - hookCountBefore << " functions" << endl;
}
Example #6
0
		/// <summary>
		/// 最初のシーンを初期化します。
		/// </summary>
		/// <param name="state">
		/// 最初のシーン
		/// </param>
		/// <returns>
		/// 初期化に成功した場合 true, それ以外の場合は false
		/// </returns>
		bool init(const State& state)
		{
			if (m_current)
			{
				return false;
			}

			auto it = m_factories.find(state);

			if (it == m_factories.end())
			{
				return false;
			}

			m_currentState = state;

			m_current = it->second();

			if (hasError())
			{
				return false;
			}

			m_transitionState = TransitionState::FadeIn;

			m_stopwatch.restart();

			return true;
		}
Example #7
0
		SceneManager& add(const State& state)
		{
			typename Scene::InitData initData{ state, m_data, this };
			
			auto factory = [=](){
				return std::make_shared<Scene>(initData);
			};
		
			auto it = m_factories.find(state);
			
			if (it != m_factories.end())
			{
				it.value() = factory;
			}
			else
			{
				m_factories.emplace(state, factory);

				if (!m_first)
				{
					m_first = state;
				}
			}

			return *this;
		}
Example #8
0
void Graph::unweighted( const string & startName )
{
    clearAll( );

    const MapEntry & match = vertexMap.find( MapEntry( startName ) );
    if( match == ITEM_NOT_FOUND )
    {
        cout << startName << " is not a vertex in this graph" << endl;
        return;
    }

    Vertex *start = match.storedVertex;
    Queue<Vertex *> q( numVertices );
    q.enqueue( start ); start->dist = 0;

    while( !q.isEmpty( ) )
    {
        Vertex *v = q.dequeue( );

        ListItr<Vertex *> itr;
        for( itr = v->adj.first( ); !itr.isPastEnd( ); itr.advance( ) )
        {
            Vertex *w = itr.retrieve( );
            if( w->dist == INFINITY )
            {
                w->dist = v->dist + 1;
                w->path = v;
                q.enqueue( w );
            }
        }
    }
}
void
Filtered_UniqueGlobalIndexer<LocalOrdinalT,GlobalOrdinalT>::
initialize(const Teuchos::RCP<const UniqueGlobalIndexer<LocalOrdinalT,GlobalOrdinalT> > & ugi,
           const std::vector<GlobalOrdinalT> & filtered)
{ 
  typedef std::unordered_set<GlobalOrdinalT> HashTable;

  base_ = ugi;

  // ensure the localIDs match with the users 
  // this is essential for a class to be a decorator
  this->shareLocalIDs(*base_);

  // from base global indexer build the filtered owned indices
  std::vector<GlobalOrdinalT> baseOwned;
  base_->getOwnedIndices(baseOwned);

  // build a hash table for fast searching
  HashTable filteredHash;
  for(std::size_t i=0;i<filtered.size();i++)
    filteredHash.insert(filtered[i]);

  // search for indices in filtered array, add to owned_ if not found
  for(std::size_t i=0;i<baseOwned.size();i++) {
    typename HashTable::const_iterator itr = filteredHash.find(baseOwned[i]);    

    if(itr==filteredHash.end())
      owned_.push_back(baseOwned[i]);
  }
}
Example #10
0
 // looks up an element.  Returns null if the element did not exist.
 // returns an empty string if the element exists but has a null value
 // otherwise returns the value
 const char * lookup(ParmStr key) const 
 {
   CIter_ i = lookup_.find(key);
   if (i == lookup_.end())
     return 0;
   else
     return i->second;
 }  
Example #11
0
int TestHashTable_CString()
{
	HashTable<const char *, const char *> ht;

	char                                  buffer1[32];
	char                                  buffer2[32];
	const unsigned long                   max = 1000;
	unsigned long                         i;

	for (i = 0; i < max; i++) {
		sprintf(buffer1, "%lu", i);
		sprintf(buffer2, "%lu", max - i);
		ht.insert(buffer1, (const char *)cc_strdup(buffer2));
	}

	for (i = 0; i < max; i += 2) {
		sprintf(buffer1, "%lu", i);
		TEST_ASSERT(ht.find(buffer1) != 0);
	}

	for (i = 0; i < max; i += 2) {
		sprintf(buffer1, "%lu", i);
		free((void *)ht.find(buffer1));
		TEST_ASSERT(ht.erase(buffer1));
	}

	for (i = 0; i < max; i += 2) {
		sprintf(buffer1, "%lu", i);
		TEST_ASSERT(ht.find(buffer1) == 0);
	}

	for (i = 1; i < max; i += 2) {
		sprintf(buffer1, "%lu", i);
		sprintf(buffer2, "%lu", max - i);
		TEST_ASSERT(strcmp(ht.find(buffer1), buffer2) == 0);
	}

	/* Rest of the cleanup */
	for (i = 1; i < max; i += 2) {
		sprintf(buffer1, "%lu", i);
		free((void *)ht.find(buffer1));
		TEST_ASSERT(ht.erase(buffer1));
	}

	return 0;
}
Example #12
0
int main() {

    HashTable<int>* h = new HashTable<int>(47);

    h->insert("sylvan",10);
    h->insert("lora",5);
    h->insert("jake",15);
    h->insert("kiran",20);
    h->insert("theo",16);
    h->insert("sylvan",41);
    h->insert("lora",39);
    h->insert("jake",6);
    h->insert("kiran",3);
    h->insert("theo",1);

    h->insert("will",10);
    h->insert("kelly",5);
    h->insert("nadine",15);
    h->insert("nick",20);
    h->insert("zoe",16);
    h->print();

    if (h->find("sylvan")!=0)
        cout << *(h->find("sylvan")) << endl;

    h->remove("sylvan");
    h->remove("lora");
    h->remove("will");
    h->print();

    h->insert("sylvan",30);
    h->insert("lora",28);
    h->insert("aili",0);
    h->insert("richard",70);
    h->insert("robert",70);
    h->insert("sandie",73);
    h->print();

    delete h;

}
Example #13
0
void UnionHash(HashTable & h1, HashTable & h2)
{
  HashIterator iter(h2);
  iter.first();
  while (iter.isValid())
  {
    IMapping & cur = iter.query();
    IMapping * matched = h1.find(cur.getKey());
    if (!matched)
      h1.add(cur);
    iter.next();
  }
}
Example #14
0
void SubtractHash(HashTable & main, HashTable & sub)
{
  HashIterator iter(sub);
  iter.first();
  while (iter.isValid())
  {
    IMapping & cur = iter.query();
    IMapping * matched = main.find(cur.getKey());
    iter.next();
    if (matched)
      main.removeExact(&cur);
  }
}
Example #15
0
void IntersectHash(HashTable & h1, HashTable & h2)
{
  HashIterator iter(h1);
  iter.first();
  while (iter.isValid())
  {
    IMapping & cur = iter.query();
    IMapping * matched = h2.find(cur.getKey());
    iter.next();
    if (!matched)
      h1.removeExact(&cur);
  }
}
Example #16
0
void findEntry(HashTable<int> &HT, int x)			//remove entry
{
	try
	{
		HashItem<int>* HI = HT.find(x);				//find key if possible
		cout << "The entry " << HI->entry << 
			" has been found." << endl << endl;
	}
	catch (NonexistentEntry& err)					//show error if not
	{
		cout << "Exception: " << err.getMessage()
			<< endl << endl;						
	}
}
Example #17
0
// If vertexName is not present, add it to vertexMap
// In either case, return the Vertex
Vertex * Graph::getVertex( const string & vertexName )
{
    static MapEntry entry;
    entry.vertexName = vertexName;
    
    const MapEntry & match = vertexMap.find( entry );
    if( match == ITEM_NOT_FOUND )
    {
        entry.storedVertex = new Vertex( vertexName );
        allVertices.insert( entry.storedVertex, allVertices.zeroth( ) );
        numVertices++;
        vertexMap.insert( entry );
        return entry.storedVertex;
    }
    return match.storedVertex;
}
Example #18
0
void Graph::printPath( const string & destName ) const
{
    const MapEntry & match = vertexMap.find( MapEntry( destName ) );
    if( match == ITEM_NOT_FOUND )
    {
        cout << "Destination vertex not found" << endl;
        return;
    }

    const Vertex & w = *match.storedVertex;
    if( w.dist == INFINITY )
        cout << destName << " is unreachable";
    else
        printPath( w );
    cout << endl;
}
Example #19
0
int TestHashTable_String()
{
	HashTable<std::string, std::string> ht;

	char                                buffer1[32];
	char                                buffer2[32];
	const unsigned long                 max = 1000;
	unsigned long                       i;

	for (i = 0; i < max; i++) {
		sprintf(buffer1, "%lu", i);
		sprintf(buffer2, "%lu", max - i);
		ht.insert(std::string(buffer1), std::string(buffer2));
	}

	for (i = 0; i < max; i += 2) {
		sprintf(buffer1, "%lu", i);
		TEST_ASSERT(ht.exists(std::string(buffer1)));
	}

	for (i = 0; i < max; i += 2) {
		sprintf(buffer1, "%lu", i);
		TEST_ASSERT(ht.erase(std::string(buffer1)));
	}

	for (i = 0; i < max; i += 2) {
		sprintf(buffer1, "%lu", i);
		TEST_ASSERT(!ht.exists(std::string(buffer1)));
	}

	std::string rec;
	for (i = 1; i < max; i += 2) {
		sprintf(buffer1, "%lu", i);
		sprintf(buffer2, "%lu", max - i);
		TEST_ASSERT(ht.find(std::string(buffer1), rec));
		TEST_ASSERT(std::string(rec) == std::string(buffer2));
	}

	/* Rest of the cleanup */
	for (i = 1; i < max; i += 2) {
		sprintf(buffer1, "%lu", i);
		TEST_ASSERT(ht.erase(std::string(buffer1)));
	}

	return 0;
}
Example #20
0
		/// <summary>
		/// シーンを変更します。
		/// </summary>
		/// <param name="state">
		/// 次のシーンのキー
		/// </param>
		/// <param name="transitionTimeMillisec">
		/// フェードイン・アウトの時間(ミリ秒)
		/// </param>
		/// <param name="crossFade">
		/// クロスフェードを有効にするか
		/// </param>
		/// <returns>
		/// シーンの変更が可能でフェードイン・アウトが開始される場合 true, それ以外の場合は false
		/// </returns>
		bool changeScene(const State& state, int32 transitionTimeMillisec, bool crossFade)
		{
			if (state == m_currentState)
			{
				crossFade = false;
			}

			if (m_factories.find(state) == m_factories.end())
			{
				return false;
			}

			m_nextState = state;

			m_crossFade = crossFade;

			if (crossFade)
			{
				m_transitionTimeMillisec = transitionTimeMillisec;

				m_transitionState = TransitionState::FadeInOut;

				m_next = m_factories[m_nextState]();

				if (hasError())
				{
					return false;
				}

				m_currentState = m_nextState;

				m_stopwatch.restart();
			}
			else
			{
				m_transitionTimeMillisec = (transitionTimeMillisec / 2);

				m_transitionState = TransitionState::FadeOut;

				m_stopwatch.restart();
			}

			return true;
		}
/*---------------------------------------------------------------------*//**
	アトムを検索する
**//*---------------------------------------------------------------------*/
const EsAtom* EsKeywordSet::findAtom(const VcString* str)
{
	// 静的キーワード検索
	for(int i = 0; i < NUM_S; i++)
	{
		if(_kwarrStatic[i].getAtom()->isSameString(str))
		{
			return _kwarrStatic[i].getAtom();
		}
	}

	// ハッシュテーブル検索
	HashTable* htbl = getHashTableInstance();
	EsAtom::EsAtomHashEntry* entity = (EsAtom::EsAtomHashEntry*)htbl->find(str);
	if(entity == 0L)
	{
		return 0L;
	}
	return entity->getAtom();
}
Example #22
0
int main()
{
	double p;
	cin>>p;
	BloomFilter F(p);
	HashTable T;
	int n,k=0;
	string s;
	freopen("dictionary+text.txt","r",stdin);
	for(int i=1;i<=99431;i++)
	{
		cin>>s;
		F.add(s);
		T.add(s);
	}
	cin>>k;
	int rightF=0,rightT=0,wrongF=0,wrongT=0,BloomLies=0;
	for(int i=1;i<=k;i++)
	{
		cin>>s;

		if(F.find(s)) 
			rightF++;
		else wrongF++;

		if(T.find(s)) 
			rightT++;
		else wrongT++;

		BloomLies=rightF-rightT;
	}

	cout<<rightF<<' '<<wrongF<<' '<<BloomLies;

	return 0;
}
Example #23
0
static Word* Word::newWord      // GET NEW WORD
    ( const char *chrs          // - characters in word
    , unsigned size )           // - # characters
{

    static HashTable wordTable  // hash table
        ( &Word::hashFun
        , &Word::hashCompare);

    Word* curr;                 // - current word
    _chr_vect vect              // - character vector
        = { chrs, size };

    curr = (Word *)wordTable.find( &vect );
    if( 0 == curr ) {
        curr = (Word*)wordCarver.alloc();
        curr = new( curr ) Word( chrs, size );
        wordRing.append( curr );
        wordTable.add( curr, &vect );
    } else {
        ++ curr->_count;
    }
    return curr;
}
Example #24
0
int main()
{

	HashTable<int> hashtable;

	int inc = 0;
	int dec = 0;
	int ninehun = 0;
	int onehun = 0;
	for (int i = 0; i < MAXHASH; i++) {
		int hashed = hashtable.hashFunct(i);
		if (hashed > 500) {
			inc++;
		}
		if (hashed <= 500) {
			dec++;
		}
		if (hashed > 900) {
			ninehun++;
		}
		if (hashed < 100) {
			onehun++;
		}
		cout << i << "----------" << hashed << endl;
	}

	cout << "Keys above 500: " << inc << " | Keys less than 500: " << dec << " | Keys above 900: " << ninehun << " | Keys below 100: " << onehun << endl;
	int collisions = 0;
	int size = 0;
	for (size_t i = 0; i < MAXHASH; ++i) {
		collisions = 0;
		bool isGud = hashtable.insert(i, MAXHASH - i, collisions);
		if (isGud) {
			size++;
		}
		cout << "Inserted? " << isGud << endl;
		cout << "Number of collisions: " << collisions << endl;
		cout << "Actual size: " << size << endl;
	}

	collisions = 0;
	hashtable.insert(777, 11025101160059, collisions);
	int newVal = 0;
	bool isFound = hashtable.find(777, newVal);
	cout << "777 is found? " << isFound << endl;
	bool isGone = hashtable.remove(777);
	cout << "777 is gone? " << isGone << endl;
	isFound = hashtable.find(777, newVal);
	cout << "777 is found? (Should return false): " << isFound << endl;

	cout << "Actual size: " << size << endl;

	//Create test function to add random keys & keep track of number of collisions
	for (size_t n = 100; n <= 1000; n = n + 100) {
		for (size_t i = 0; i < MAXHASH; ++i) {
			collisions = 0;
			bool isGud = hashtable.remove(i);
			if (isGud) {
				--size;
			}
		}
		srand(MAXHASH);
		int random = rand() % 1000;
		vector<int> coll;
		for (size_t i = 0; i < n; ++i) {
			collisions = 0;
			bool isGud = hashtable.insert(i, random, collisions);
			if (isGud) {
				size++;
			}
			coll.push_back(collisions);
			//cout << "Inserted record with key " << i << "? " << isGud << endl;
			//cout << "Number of collisions: " << collisions << endl;
		}
		cout << "Attempted to insert " << n << " items." << endl;
		cout << "Actually inserted " << size << " items." << endl;

		int avg = 0;
		int denom = coll.size();
		for (size_t i = 0; i < MAXHASH; i++) {
			avg = avg + coll.at(i);
			coll.push_back(i);
		}
		avg = avg / denom;

		cout << "Average number of collisions for " << n << " inserts: " << avg << endl;
		cout << "The alpha value is: " << hashtable.alpha() << endl;
	}

	system("pause");
	return 0;
}
int main() {
    //Integer HashTable...default value is 0
    cout << "Integer insert, find, and remove" << endl;
    HashTable<int>* intHash = new HashTable<int>(0);

    cout << "Value of f(not in table) is: " << intHash->find("f") << endl;
    cout << endl;
    
    intHash->insert("eight", 8);
    cout << endl;
    
    intHash->insert("seven", 7);
    cout << endl;
    
    cout << "Value of seven is: " << intHash->find("seven") << endl;
    cout << endl;
    
    cout << "Value of eight is: " << intHash->find("eight") << endl;
    cout << endl;
    
    intHash->remove("eight");
    cout << endl;
    
    cout << "Find value of removed key eight: " << intHash->find("eight") << endl;
    
    //Double HashTable...default value is 0.0001
    cout << "Double insert, find, and remove" << endl;
    HashTable<double>* dHash = new HashTable<double>(0.0001);
    
    cout << "Value of f(not in table) is: " << dHash->find("f") << endl;
    cout << endl;
    
    dHash->insert("say", 8.5618);
    cout << endl;
    
    dHash->insert("what", 77.777);
    cout << endl;
    
    cout << "Value of what is: " << dHash->find("what") << endl;
    cout << endl;
    
    cout << "Value of say is: " << dHash->find("say") << endl;
    cout << endl;
    
    dHash->remove("say");
    cout << endl;
    
    cout << "Find value of removed key say: " << dHash->find("say") << endl;

    //String HashTable...default value is an empty string
    cout << "String insert, find, and remove" << endl;
    HashTable<string>* strHash = new HashTable<string>(" ");
    
    cout << "Value of f(not in table) is: " << strHash->find("f") << endl;
    cout << endl;
    
    strHash->insert("hi", "hello");
    cout << endl;
    
    strHash->insert("bye", "goodbye");
    cout << endl;
    
    cout << "Value of bye is: " << strHash->find("bye") << endl;
    cout << endl;
    
    cout << "Value of hi is: " << strHash->find("hi") << endl;
    cout << endl;
    
    strHash->remove("hi");
    cout << endl;
    
    cout << "Find value of removed key hi: " << strHash->find("hi") << endl;
    
    delete intHash;
    delete dHash;
    delete strHash;
    return 0;
}
Foam::processorGAMGInterface::processorGAMGInterface
(
    const label index,
    const lduInterfacePtrsList& coarseInterfaces,
    const lduInterface& fineInterface,
    const labelField& localRestrictAddressing,
    const labelField& neighbourRestrictAddressing,
    const label fineLevelIndex,
    const label coarseComm
)
:
    GAMGInterface
    (
        index,
        coarseInterfaces
    ),
    comm_(coarseComm),
    myProcNo_(refCast<const processorLduInterface>(fineInterface).myProcNo()),
    neighbProcNo_
    (
        refCast<const processorLduInterface>(fineInterface).neighbProcNo()
    ),
    forwardT_(refCast<const processorLduInterface>(fineInterface).forwardT()),
    tag_(refCast<const processorLduInterface>(fineInterface).tag())
{
    // From coarse face to coarse cell
    DynamicList<label> dynFaceCells(localRestrictAddressing.size());
    // From fine face to coarse face
    DynamicList<label> dynFaceRestrictAddressing
    (
        localRestrictAddressing.size()
    );

    // From coarse cell pair to coarse face
    HashTable<label, labelPair, labelPair::Hash<> > cellsToCoarseFace
    (
        2*localRestrictAddressing.size()
    );

    forAll(localRestrictAddressing, ffi)
    {
        labelPair cellPair;

        // Do switching on master/slave indexes based on the owner/neighbour of
        // the processor index such that both sides get the same answer.
        if (myProcNo() < neighbProcNo())
        {
            // Master side
            cellPair = labelPair
            (
                localRestrictAddressing[ffi],
                neighbourRestrictAddressing[ffi]
            );
        }
        else
        {
            // Slave side
            cellPair = labelPair
            (
                neighbourRestrictAddressing[ffi],
                localRestrictAddressing[ffi]
            );
        }

        HashTable<label, labelPair, labelPair::Hash<> >::const_iterator fnd =
            cellsToCoarseFace.find(cellPair);

        if (fnd == cellsToCoarseFace.end())
        {
            // New coarse face
            label coarseI = dynFaceCells.size();
            dynFaceRestrictAddressing.append(coarseI);
            dynFaceCells.append(localRestrictAddressing[ffi]);
            cellsToCoarseFace.insert(cellPair, coarseI);
        }
        else
        {
            // Already have coarse face
            dynFaceRestrictAddressing.append(fnd());
        }
    }
Example #27
0
Foam::processorGAMGInterface::processorGAMGInterface
(
    const lduInterface& fineInterface,
    const labelField& localRestrictAddressing,
    const labelField& neighbourRestrictAddressing
)
:
    GAMGInterface
    (
        fineInterface,
        localRestrictAddressing,
        neighbourRestrictAddressing
    ),
    fineProcInterface_(refCast<const processorLduInterface>(fineInterface))
{
    // Make a lookup table of entries for owner/neighbour
    HashTable<SLList<label>, label, Hash<label> > neighboursTable
    (
        localRestrictAddressing.size()
    );

    // Table of face-sets to be agglomerated
    HashTable<SLList<SLList<label> >, label, Hash<label> > faceFaceTable
    (
        localRestrictAddressing.size()
    );

    label nCoarseFaces = 0;

    forAll (localRestrictAddressing, ffi)
    {
        label curMaster = -1;
        label curSlave = -1;

        // Do switching on master/slave indexes based on the owner/neighbour of
        // the processor index such that both sides get the same answer.
        if (myProcNo() < neighbProcNo())
        {
            // Master side
            curMaster = localRestrictAddressing[ffi];
            curSlave = neighbourRestrictAddressing[ffi];
        }
        else
        {
            // Slave side
            curMaster = neighbourRestrictAddressing[ffi];
            curSlave = localRestrictAddressing[ffi];
        }

        // Look for the master cell.  If it has already got a face,
        // add the coefficient to the face.  If not, create a new face.
        if (neighboursTable.found(curMaster))
        {
            // Check all current neighbours to see if the current slave already
            // exists and if so, add the fine face to the agglomeration.

            SLList<label>& curNbrs = neighboursTable.find(curMaster)();

            SLList<SLList<label> >& curFaceFaces =
                faceFaceTable.find(curMaster)();

            bool nbrFound = false;

            SLList<label>::iterator nbrsIter = curNbrs.begin();

            SLList<SLList<label> >::iterator faceFacesIter =
                curFaceFaces.begin();

            for
            (
                ;
                nbrsIter != curNbrs.end(), faceFacesIter != curFaceFaces.end();
                ++nbrsIter, ++faceFacesIter
            )
            {
                if (nbrsIter() == curSlave)
                {
                    nbrFound = true;
                    faceFacesIter().append(ffi);
                    break;
                }
            }

            if (!nbrFound)
            {
                curNbrs.append(curSlave);
                curFaceFaces.append(ffi);

                // New coarse face created
                nCoarseFaces++;
            }
        }
        else
        {
            // This master has got no neighbours yet.  Add a neighbour
            // and a coefficient, thus creating a new face
            neighboursTable.insert(curMaster, SLList<label>(curSlave));
            faceFaceTable.insert(curMaster, SLList<SLList<label> >(ffi));

            // New coarse face created
            nCoarseFaces++;
        }
    } // end for all fine faces
Example #28
0
ML_START_NAMESPACE

void AnimationExecuter::commandClip(vector<string>* tempEntryParams, kScriptFrameEntry* currentEntry, int /*frameNr*/, size_t /*FrameEntryListIter*/)
{
	//Params:					
	//on/off left/right/... percent toClip (notToClip) (aab/oab)
	if (tempEntryParams->size()>=4)
	{	
		//Parameter 1: on/off
		bool onOff = false;
		onOff=((*tempEntryParams)[0]=="ON");

		//Parameter 2: left/right/...
		//noch nicht
		string clipPlane;
		if ((*tempEntryParams)[1]=="LEFT")
			clipPlane = LAY_CLIPPINGLEFT;
		else if ((*tempEntryParams)[1]=="RIGHT")
			clipPlane = LAY_CLIPPINGRIGHT;
		else if ((*tempEntryParams)[1]=="TOP")
			clipPlane = LAY_CLIPPINGTOP;
		else if ((*tempEntryParams)[1]=="BOTTOM")
			clipPlane = LAY_CLIPPINGBOTTOM;
		else if ((*tempEntryParams)[1]=="REAR")
			clipPlane = LAY_CLIPPINGREAR;
		else clipPlane = LAY_CLIPPINGFRONT; //Front is default																			

		myObjMgr->setObjAttribute(O_CLIPPING,clipPlane,INF_CLIPPING_ON,new string((*tempEntryParams)[0]),omINFOTYPE_STRING,true,true);

		//Parameter 5: listNotToClip						
		vector<string>* listNotToClip = new vector<string>;
		if (tempEntryParams->size()>=5)
			myAnimationParser->getObjectStringList(kBasics::trimQuotatedStr((string)(*tempEntryParams)[4], kBasics::QUOTATION_SINGLE).c_str(),listNotToClip);

		//Parameter 4: listToClip, listForBB						
		HashTable<string>* listToClip = new HashTable<string>;						
		myAnimationParser->getObjectStringList(kBasics::trimQuotatedStr((string)(*tempEntryParams)[3], kBasics::QUOTATION_SINGLE).c_str(),listToClip);

		for ( size_t i = 0; i<listNotToClip->size(); i++)
			listToClip->remove((*listNotToClip)[i]);

		//Parameter 6: aab/oab

		//Transform ClippingBox
		//Get BoundingBox for objects to clip

		AnimationCache::Measures MasterBB = myCache->getMeasuresFromHT((string)(*tempEntryParams)[3]);
		SbVec3f BBCenter = myCache->getBoundingCenter(MasterBB);

		//Translation
		myObjMgr->setObjAttribute(O_CLIPPING,L_GLOBAL,INF_CLIPPING_TRANSLATION,new vec3(BBCenter[0],BBCenter[1],BBCenter[2]),omINFOTYPE_VEC3,true,true);

		//Scale
		//Scale nimmt sowieso nachher bei der ClipBox den größten der 3 werte
		SbVec3f tempScale;
		tempScale[0] = std::abs(MasterBB.BB_max[0]-MasterBB.BB_min[0])/2;
		tempScale[1] = std::abs(MasterBB.BB_max[1]-MasterBB.BB_min[1])/2;
		tempScale[2] = std::abs(MasterBB.BB_max[2]-MasterBB.BB_min[2])/2;
		myObjMgr->setObjAttribute(O_CLIPPING,L_GLOBAL,INF_CLIPPING_SCALE,new vec3(tempScale[0],tempScale[1],tempScale[2]),omINFOTYPE_VEC3,true,true);

		//Parameter 3: percent
		//left 
		//x +1 clip nothing
		//x -1 clip all
		string vecString;
		if (clipPlane == LAY_CLIPPINGLEFT)
			vecString = kBasics::FloatToString(1-2*kBasics::StringToFloat((string)(*tempEntryParams)[2]))+kScriptFrameEntry::DELIMITER_COLOR_SCRIPT+string("0")+kScriptFrameEntry::DELIMITER_COLOR_SCRIPT+string("0");
		else if (clipPlane == LAY_CLIPPINGRIGHT)
			vecString = kBasics::FloatToString(-1+2*kBasics::StringToFloat((string)(*tempEntryParams)[2]))+kScriptFrameEntry::DELIMITER_COLOR_SCRIPT+string("0")+kScriptFrameEntry::DELIMITER_COLOR_SCRIPT+string("0");
		else if (clipPlane == LAY_CLIPPINGTOP)
			vecString = string("0")+kScriptFrameEntry::DELIMITER_COLOR_SCRIPT+string("0")+kScriptFrameEntry::DELIMITER_COLOR_SCRIPT+kBasics::FloatToString(1-2*kBasics::StringToFloat((string)(*tempEntryParams)[2]));
		else if (clipPlane == LAY_CLIPPINGBOTTOM)
			vecString = string("0")+kScriptFrameEntry::DELIMITER_COLOR_SCRIPT+string("0")+kScriptFrameEntry::DELIMITER_COLOR_SCRIPT+kBasics::FloatToString(-1+2*kBasics::StringToFloat((string)(*tempEntryParams)[2]));
		else if (clipPlane == LAY_CLIPPINGREAR)							
			vecString = string("0")+kScriptFrameEntry::DELIMITER_COLOR_SCRIPT+kBasics::FloatToString(1-2*kBasics::StringToFloat((string)(*tempEntryParams)[2]))+kScriptFrameEntry::DELIMITER_COLOR_SCRIPT+string("0");
		else
			vecString = string("0")+kScriptFrameEntry::DELIMITER_COLOR_SCRIPT+kBasics::FloatToString(-1+2*kBasics::StringToFloat((string)(*tempEntryParams)[2]))+kScriptFrameEntry::DELIMITER_COLOR_SCRIPT+string("0");

		setV3ValueInterpol(O_CLIPPING, clipPlane,INF_CLIPPING_TRANSLATION, vecString, currentEntry->getCurrentFrame(), currentEntry->getFrameCount());

		//Nur beim ersten Frame einer setClipPlane-Anweisung soll er alle Clipping-Eigenschaften zurücksetzen.
		//Testen mit Anweisungen a la [1,10]
		if (currentEntry->getCurrentFrame()==0)
		{
			kDebug::Debug("Reset all Clipping to false",kDebug::DL_HIGH);
			//Get read-only access to object container
			const omObjectContainer *oc= getConstObjContainer();

			oc = getObjContainer();
			if(oc != NULL)
			{		
				omObjectContainer ::const_iterator iterObj;
				//definition in mlObjMgrObjectContainer.h: typedef std::map<omIDType, omObject> objVec;

				for ( iterObj = oc->begin(); iterObj!=oc->end(); iterObj++)
				{
					omObject tempObj = iterObj->second;
					//Als Typ für das Feld BOOL zu nehmen scheiterte daran, das nicht existente Felder bei z.B. viewer-Objekten auch TRUE zurückgeben wenn man nach dem Attribut fragt

					omAttribute attr2 = tempObj.getAttribute(LAY_DESCRIPTION,INF_NAME);
					if (attr2.getStringValue()!="")
					{
						if ((listToClip->find(kBasics::toUp(attr2.getStringValue()))!=NULL))
						{
							myObjMgr->setObjAttribute(tempObj.getID(),LAY_APPEARANCE,INF_CLIPPING,new string("ON"),omINFOTYPE_STRING,true,true);
							sendNotification();
						}
						else
						{
							if (tempObj.hasAttribute(LAY_APPEARANCE,INF_CLIPPING))
							{
								omAttribute attr1 = tempObj.getAttribute(LAY_APPEARANCE,INF_CLIPPING);
								if (kBasics::toUp(attr1.getStringValue()) == "ON")
								{			
									myObjMgr->setObjAttribute(tempObj.getID(),LAY_APPEARANCE,INF_CLIPPING,new string("OFF"),omINFOTYPE_STRING,true,true);
									sendNotification();
								}											
							}
						}
					}
				}
			}
		}

		delete listNotToClip; delete listToClip;
		sendNotification();
	}
	else kDebug::Debug("setClipPlane -> to few arguments",kDebug::DL_HIGH);					
}
bool Foam::fileFormats::TRIsurfaceFormatCore::read
(
    const fileName& filename
)
{
    this->clear();
    sorted_ = true;

    IFstream is(filename);
    if (!is.good())
    {
        FatalErrorIn
        (
            "fileFormats::TRIsurfaceFormatCore::read(const fileName&)"
        )
            << "Cannot read file " << filename
            << exit(FatalError);
    }

    // uses similar structure as STL, just some points
    // the rest of the reader resembles the STL binary reader
    DynamicList<point> dynPoints;
    DynamicList<label> dynZones;
    DynamicList<label> dynSizes;
    HashTable<label>   lookup;

    // place faces without a group in zone0
    label zoneI = 0;
    dynSizes.append(zoneI);
    lookup.insert("zoneI", zoneI);

    while (is.good())
    {
        string line = this->getLineNoComment(is);

        // handle continuations ?
        //          if (line[line.size()-1] == '\\')
        //          {
        //              line.substr(0, line.size()-1);
        //              line += this->getLineNoComment(is);
        //          }

        IStringStream lineStream(line);

        point p
        (
            readScalar(lineStream),
            readScalar(lineStream),
            readScalar(lineStream)
        );

        if (!lineStream) break;

        dynPoints.append(p);
        dynPoints.append
        (
            point
            (
                readScalar(lineStream),
                readScalar(lineStream),
                readScalar(lineStream)
            )
        );
        dynPoints.append
        (
            point
            (
                readScalar(lineStream),
                readScalar(lineStream),
                readScalar(lineStream)
            )
        );

        // zone/colour in .tri file starts with 0x. Skip.
        // ie, instead of having 0xFF, skip 0 and leave xFF to
        // get read as a word and name it "zoneFF"

        char zero;
        lineStream >> zero;

        word rawName(lineStream);
        word name("zone" + rawName(1, rawName.size()-1));

        HashTable<label>::const_iterator fnd = lookup.find(name);
        if (fnd != lookup.end())
        {
            if (zoneI != fnd())
            {
                // group appeared out of order
                sorted_ = false;
            }
            zoneI = fnd();
        }
        else
        {
            zoneI = dynSizes.size();
            lookup.insert(name, zoneI);
            dynSizes.append(0);
        }

        dynZones.append(zoneI);
        dynSizes[zoneI]++;
    }

    // skip empty groups
    label nZone = 0;
    forAll(dynSizes, zoneI)
    {
        if (dynSizes[zoneI])
        {
            if (nZone != zoneI)
            {
                dynSizes[nZone] = dynSizes[zoneI];
            }
            nZone++;
        }
    }
    // truncate addressed size
    dynSizes.setCapacity(nZone);

    // transfer to normal lists
    points_.transfer(dynPoints);
    zoneIds_.transfer(dynZones);
    sizes_.transfer(dynSizes);

    return true;
}
Example #30
0
//Add and remove some items, making sure they come back in the
// correct order
void testBasicMethods(){
  HashTable<std::string,int> testHash;
  testHash.add("how",0);
  testHash.add("now",1);
  testHash.add("brown",2);
  testHash.add("cow",3);
  testHash.add("metal",4);
  testHash.add("daffodil",5);

  if(testHash.size() == 6){
    std::cout << "SUCCESS: 6 items added" << std::endl;
  } else {
    std::cout << "ERROR: Added 6 items, but size says " << testHash.size() << std::endl;
    return;
  }
  
  int x0 = testHash.find("how");
  int x1 = testHash.find("now");
  int x2 = testHash.find("brown");
  int x3 = testHash.find("cow");
  int x4 = testHash.find("metal");
  int x5 = testHash.find("daffodil");

  if(x0 != 0 || x1 != 1 || x2 != 2 || x3 != 3 || x4 != 4 || x5 != 5){
    std::cout << "ERROR: Expected 0,1,2,3,4,5, but got " << x0 <<"," << x1 << "," << x2 << "," << x3 << "," << x4 << "," << x5 << std::endl;
    return;
  } else {
    std::cout << "SUCCESS: 6 added items came back out with correct keys" << std::endl;
  }
  
  if(testHash.keyExists("daffodil")){
    std::cout << "SUCCESS: keyExists found 'daffodil'" << std::endl;
  } else {
    std::cout << "ERROR: 'daffodil' is a valid key, but keyExists said false" << std::endl;
    return;
  }

  if(!testHash.keyExists("shiny")){
    std::cout << "SUCCESS: keyExists did not find 'shiny'" << std::endl;
  } else {
    std::cout << "ERROR: 'shiny' is not a valid key, but keyExists said true" << std::endl;
    return;
  }

  bool didException = false;
  try {

    int xq = testHash.find("shiny");

  } catch (std::string s) {
    std::cout << "SUCCESS: Caught exception: " << s << std::endl;
    didException = true;
  } catch (...) {
    std::cout << "ERROR: Caught an exception, but it wasn't a string type" << std::endl;
    return;
  }
  if(didException == false){
    std::cout << "ERROR: find did not throw an exception when given a non-existen key" << std::endl;
    return;
  }
  
  testHash.remove("how");
  testHash.remove("now");

  if(testHash.size() == 4){
    std::cout << "SUCCESS: 4 items after removing" << std::endl;
  } else {
    std::cout << "ERROR: After remove, expected 4 items, but size says " << testHash.size() << std::endl;
    return;
  }

  if(testHash.numRemoved == 2){
    std::cout << "SUCCESS: numRemoved is 2, as expected" << std::endl;
  } else {
    std::cout << "ERROR: After remove, expected numRemoved == 2, but got " << testHash.numRemoved << std::endl;
    return;
  }

  if(testHash.keyExists("how") == false){
    std::cout << "SUCCESS: Removed key 'how' is no longer in hash table." << std::endl;
  } else {
    std::cout << "ERROR: Removed key 'how' is still in the table" << std::endl;
    return;
  }

  if(testHash.keyExists("brown") && testHash.keyExists("cow") &&
       testHash.keyExists("metal") && testHash.keyExists("daffodil")){
    std::cout << "SUCCESS: The 4 items that weren't removed are still in the table." << std::endl;
  } else {
    std::cout << "ERROR: One of the 4 keys that ought to still be in the table has been lost" << std::endl;
    return;
  }
}