Exemple #1
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;
		}
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]);
  }
}
void Foam::distributedTriSurfaceMesh::distributeFields
(
    const mapDistribute& map
)
{
    typedef DimensionedField<Type, triSurfaceGeoMesh> DimensionedSurfField;

    HashTable<DimensionedSurfField*> fields
    (
        objectRegistry::lookupClass<DimensionedSurfField>()
    );

    for
    (
        typename HashTable<DimensionedSurfField*>::iterator fieldIter =
            fields.begin();
        fieldIter != fields.end();
        ++fieldIter
    )
    {
        DimensionedSurfField& field = *fieldIter();

        label oldSize = field.size();

        map.distribute(field);

        if (debug)
        {
            Info<< "Mapped " << field.typeName << ' ' << field.name()
                << " from size " << oldSize << " to size " << field.size()
                << endl;
        }
    }
}
Exemple #4
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;
}
Exemple #5
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;
		}
Exemple #6
0
 void operator()(SV **&sp, HashTable &result) {
     EXTEND(sp, result.length() * 2);
     for (HashTableIterator it = result.begin(); it != result.end(); ++it) {
         PUSHs(String((*it).first).dispose());
         PUSHs((*it).second);
     }
 }
Exemple #7
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;
 }  
bool StaticHashTableBuilder::generateHashCode (FILE * out, const std::string& typeName) {
	if (mHashes.empty()) return false;
	int mod = calcBestModulus();
	HashTable table;
	calcHashTable(mod, &table);

	// Lookup structure
	fprintf (out, "\t// hash table lookup structure\n");
	fprintf (out, "\tconst int hashTable[] = {0");
	{
		int current     = table[0].size() + 1; // + null element
		int nullElement = table[0].size();
		for (int i = 1; i < mod; i++) {
			if (table[i].empty()){
				fprintf (out, ", %d", nullElement); // just point to null element
			} else {
				fprintf (out, ", %d", current);     // full entry.
				current+=table[i].size() + 1;
			}
		}
		fprintf (out, "};\n");
	}

	// Table
	fprintf (out, "\t// hash table\n");
	fprintf (out, "\tstruct HashEntry { const char * name; %s value; };\n", typeName.c_str());
	fprintf (out, "\tconst HashEntry entries[] = {\n");
	bool firstOutElement = true;
	bool firstInElement  = true;
	for (HashTable::const_iterator i = table.begin(); i != table.end(); i++){
		if (!firstInElement && i->empty()) continue;
		for (std::vector<StaticHashTableBuilder::KeyValue>::const_iterator j = i->begin(); j != i->end(); j++){
			fprintf (out, "\t\t");
			if (!firstOutElement) { fprintf (out, ","); }
			firstOutElement = false;
			fprintf (out, "{\"%s\", %s}\n", j->first.c_str(), j->second.c_str());
		}
		fprintf (out, "\t\t");
		if (!firstOutElement) { fprintf (out, ","); }
		firstOutElement = false;
		fprintf (out, "{0, %s()}\n", typeName.c_str());
		firstInElement = false;
	}
	fprintf (out, "\t};\n");

	// Lookup function
	fprintf (out, "\t// lookup\n");
	fprintf (out, "\t%s value;\n", typeName.c_str());
	fprintf (out, "\tbool foundKey = false;\n");
	fprintf (out, "\tint hashCode = sf::hash ((unsigned char*) key) %% %d;\n", mod);
	fprintf (out, "\tconst HashEntry * entry = entries + hashTable[hashCode];\n");
	fprintf (out, "\twhile (entry->name != 0){\n");
	fprintf (out, "\t\tif(strcmp (entry->name, key) == 0) {value = entry->value; foundKey = true; break; }\n");
	fprintf (out, "\t\tentry++;\n");
	fprintf (out, "\t}\n");
	return true;
}
Exemple #9
0
void free_hashtab(HashTable &hashtab) {
    llist* temp;
    for ( auto it = hashtab.begin(); it != hashtab.end(); ++it ) {
        while(it->second!=NULL) {
            temp=it->second;
            it->second = it->second->next;
            delete temp;
        }
    }
}
Exemple #10
0
void collisionTest() {
    printf("test collision add/remove\n");
    
    HashTable<int,collisionHash,intEqual> collisiontable;
    for(int i=0;i<100;i++) {
	collisiontable.add(i);
    }
    for(int i=0;i<100;i+=2) {
	collisiontable.remove(i);
	size_t count = 0;
	for (HashTable<int,collisionHash,intEqual>::iterator i = collisiontable.begin();
	     i != collisiontable.end();i++) {
	    count++;
	}
	INVARIANT(count == collisiontable.size(),
		  boost::format("?! %d %d") % count % collisiontable.size());
    }

    // multiple adds of the same key are *supposed* to add multiple times.
    collisiontable.clear();
    SINVARIANT(collisiontable.size() == 0);
    for(int i=0;i<100;i++) {
	collisiontable.add(i);
	collisiontable.add(i);
    }
    SINVARIANT(collisiontable.size() == 200);

    // remove the keys (each twice)
    for(int i=0;i<100;i++) {
	collisiontable.remove(i, true);
	collisiontable.remove(i, true);
    }
    SINVARIANT(collisiontable.size() == 0);

    // an efficient way to do add/replace
    collisiontable.clear();
    SINVARIANT(collisiontable.size() == 0);
    for(int i=0;i<100;i++) {
	bool replaced;
	collisiontable.addOrReplace(i, replaced);
	SINVARIANT(replaced == false);
	collisiontable.addOrReplace(i, replaced);
	SINVARIANT(replaced == true);
    }
    SINVARIANT(collisiontable.size() == 100);

    // remove, add, remove the keys
    for(int i=0;i<100;i++) {
	collisiontable.remove(i, true);
	collisiontable.add(i);
	collisiontable.remove(i);
    }
    SINVARIANT(collisiontable.size() == 0);
}
Exemple #11
0
void print_hashtab(const HashTable &hashtab) {
    llist* temp;
    for ( auto it = hashtab.begin(); it != hashtab.end(); ++it ) {
        std::cout << it->first << ":";
        temp=it->second;
        while(temp!=NULL) {
            std::cout <<"--> [ " << temp->readid << "," << temp->pos <<" ] " ;
            temp=temp->next;
        }
        std::cout << "\n";
    }
}
Exemple #12
0
static bool dumpEngineDocs( const char *outputFile )
{
   // Create the output stream.
   FileStream stream;
   if ( !stream.open( outputFile, Torque::FS::File::Write ) )
   {
      Con::errorf( "dumpEngineDocs - Failed to open output file." );
      return false;
   }

   // First dump all global ConsoleDoc fragments.
   
   for( ConsoleDocFragment* fragment = ConsoleDocFragment::smFirst; fragment != NULL; fragment = fragment->mNext )
      if( !fragment->mClass )
         dumpFragment( stream, fragment );
   
   // Clear the doc groups before continuing,
   smDocGroups.clear();
   
   // Dump enumeration types.
   dumpEnums( stream );
   
   // Dump all global variables.
   dumpVariables( stream );

   // Now dump the global functions.
   Namespace *g = Namespace::find( NULL );
   while( g ) 
   {
      dumpNamespaceEntries( stream, g );
      
      // Dump callbacks.
      dumpGroupStart( stream, "Callbacks" );
      dumpNamespaceEntries( stream, g, true );
      dumpGroupEnd( stream );

      g = g->mParent;
   }

   // Now dump all the classes.
   dumpClasses( stream );

   // Dump pre-declarations for any groups we encountered
   // so that we don't have to explicitly define them.
   HashTable<String,U32>::Iterator iter = smDocGroups.begin();
   for ( ; iter != smDocGroups.end(); iter++ )
      stream.writeText( String::ToString( "/*! @addtogroup %s */\r\n\r\n", iter->key.c_str() ) );

   return true;
}
Exemple #13
0
int main()
{
    HashTable mHash; // C++ hash table
    mHash["Mike C"] = 1234;
    mHash["Charlie M"] = 5678;
    
    mHash.insert(make_pair("peter q", 3456));

    cout << "Hash Table size: " << mHash.size() << endl;

    for(HashTable::iterator hIter= mHash.begin(); hIter != mHash.end(); ++hIter)
    {
	cout << hIter->first << " : " << hIter->second << endl;
    }

    return 0;
}
Exemple #14
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;
		}
Exemple #15
0
static const char* test_iterator()
{
    HashTable<int, int> tmp;
    size_t cnt = 0;

    for (HashTable<int, int>::iterator it = tmp.begin();
         it != tmp.end(); ++it)
    {
        ++cnt;
    }
    KJSD_CUNIT_ASSERT(cnt == 0);

    cnt = 0;
    for (HashTable<int, int>::iterator it = htv_->begin();
         it != htv_->end(); ++it)
    {
        ++cnt;
    }
    KJSD_CUNIT_ASSERT(cnt == NUM_OF_TESTELEMENT);

    cnt = 0;
    for (HashTable<string, int>::iterator it = htc_->begin();
         it != htc_->end(); ++it)
    {
        ++cnt;
    }
    KJSD_CUNIT_ASSERT(cnt == NUM_OF_TESTELEMENT);

    cnt = 0;
    for (HashTable<const char*, int>::iterator it = htp_->begin();
         it != htp_->end(); ++it)
    {
        ++cnt;
    }
    KJSD_CUNIT_ASSERT(cnt == NUM_OF_TESTELEMENT);

    HashTable<int, int>::iterator it = htv_->begin();
    int v = (*(it++)).second;
    KJSD_CUNIT_ASSERT(v != (*it).second);

    v = (*(++it)).second;
    KJSD_CUNIT_ASSERT(v == (*it).second);
    return 0;
}
void printFreq(WorkerThread* threads, int cpus, float totalCount) {
    HashTable<KEY_SIZE> sum;
    for (int i=0; i<cpus; i++) {
        merge_table(sum, *((HashTable<KEY_SIZE>*)threads[i].hashByLength(KEY_SIZE)));
    }

    typedef std::pair< Key<KEY_SIZE>, uint32_t > hash_pair_t;
    std::vector<hash_pair_t> list(sum.begin(), sum.end());
    std::sort(list.begin(), list.end(), greater_second<hash_pair_t>());

    for (typename std::vector<hash_pair_t>::iterator it = list.begin(); it < list.end(); ++it) {
        char key[KEY_SIZE+1];
        for (int i=0; i<KEY_SIZE; i++) key[i] = toupper((*it).first.key[i]);
        key[KEY_SIZE] = 0;
        printf("%s %.3f\n", key, (float)((*it).second) * 100.0f / totalCount);
    }
    printf("\n");

}
Exemple #17
0
 virtual void printResult() {
     printf("Begin-%s\n",__PRETTY_FUNCTION__);
     vector<hteData *> vals;
     for (HashTable<hteData, hteHash, hteEqual>::iterator i = stats_table.begin();
         i != stats_table.end();++i) {
         vals.push_back(&(*i));
     }
     sort(vals.begin(),vals.end(),sortByType());
     for (vector<hteData *>::iterator i = vals.begin();
         i != vals.end();++i) {
         hteData *j = *i;
         printf("%10s %ld ents, %.2f MB total size, %.2f kB avg size, %.0f max bytes\n",
                j->type.c_str(),
                j->file_size->count(),
                j->file_size->total() / (1024*1024.0),
                j->file_size->mean() / (1024.0),
                j->file_size->max());
     }
     printf("End-%s\n",__PRETTY_FUNCTION__);
 }
void merge_table(HashTable<KEY_SIZE>& dest, HashTable<KEY_SIZE>& src) {
    for (typename HashTable<KEY_SIZE>::iterator it = src.begin(); it != src.end(); ++it) {
        dest[(*it).first] += (*it).second;
    }
}
Exemple #19
0
	HashTable(const HashTable& hash_table) : hasher(), n(0), table(*(new table_type(hash_table.Size())))
	{
		for (hash_iterator_type it = hash_table.begin(); it != hash_table.end(); ++it)
			Add(*it);
	}
Exemple #20
0
void setUpdater::updateSets(const mapPolyMesh& morphMap) const
{
    //
    // Update all sets in memory.
    //

    HashTable<const Type*> memSets = 
        morphMap.mesh().objectRegistry::lookupClass<Type>();

    for
    (
        typename HashTable<const Type*>::iterator iter = memSets.begin();
        iter != memSets.end();
        ++iter
    )
    {
        Type& set = const_cast<Type&>(*iter());

        if (debug)
        {
            Pout<< "Set:" << set.name() << " size:" << set.size()
                << " updated in memory" << endl;
        }

        set.updateMesh(morphMap);

        // Write or not? Debatable.
        set.write();
    }


    //
    // Update all sets on disk
    //

    // Get last valid mesh (discard points-only change)
    IOobjectList Objects
    (
        morphMap.mesh().time(),
        morphMap.mesh().time().findInstance
        (
            morphMap.mesh().meshDir(),
            "faces"
        ),
        "polyMesh/sets"
    );

    IOobjectList fileSets(Objects.lookupClass(Type::typeName));

    for
    (
        IOobjectList::const_iterator iter = fileSets.begin();
        iter != fileSets.end();
        ++iter
    )
    {
        if (!memSets.found(iter.key()))
        {
            // Not in memory. Load it.
            Type set(*iter());

            if (debug)
            {
                Pout<< "Set:" << set.name() << " size:" << set.size()
                    << " updated on disk" << endl;
            }

            set.updateMesh(morphMap);

            set.write();
        }
        else
        {
            if (debug)
            {
                Pout<< "Set:" << iter.key() << " already updated from memory"
                    << endl;
            }
        }
    }
}
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;
}
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());
        }
    }