Esempio n. 1
0
void print_set(const std::set<int>& s) {
	cout << "(";
	if (!s.empty()) {
		size_t size = s.size();
		size_t i = 0;
		for (::mpl::lexer::detail::States::const_iterator it = s.begin();
			it != s.end(); ++it) {
			if (i > 0) {
				cout << ", ";
			}
			cout << *it;
			i++;
		}
	}
	cout << ")";
}
Esempio n. 2
0
    std::shared_ptr<context> get_current_context()
    {
        if (all_contexts.size() == 0)
        {
            current_context = create_context(nullptr);
        }

        std::shared_ptr<context> current_locked_context = current_context.lock();

        if (!current_locked_context)
        {
            throw no_context_error();
        }

        return current_locked_context;
    }
Esempio n. 3
0
  bool ZeroPadding::JudgeZP(const itpp::bvec& input, const std::set< int > &padPositions)
  {
    int numZeros = 0;
    int threshold = PresetPaddingThreshold.at(padPositions.size());

    for (auto curPosition = padPositions.begin(); curPosition != padPositions.end(); ++curPosition){
      numZeros += static_cast< int >(!input[*curPosition]);
    } // for i

    if (numZeros >= threshold){
      return true;
    } // if
    else{
      return false;
    } // else 
  }
Esempio n. 4
0
size_t numberOfEdgesOutsideTriangle(std::set<Edge *> &edges) {
    std::set<int> nodes;
    
    std::set<Edge *> edgesPartOfTriangle;
    
    for (std::set<Edge *>::iterator it=edges.begin(); it != edges.end(); ++it) {
        Edge *edge = *it;
        nodes.insert(edge->source);
        nodes.insert(edge->destination);
    }
    
    for (std::set<Edge *>::iterator it=edges.begin(); it != edges.end(); ++it){
        for (std::set<int>::iterator jt=nodes.begin(); jt != nodes.end(); ++jt) {
            Edge *edge1 = nullptr, *edge2 = nullptr;
            
            for (std::set<Edge *>::iterator kt=edges.begin(); kt != edges.end(); ++kt) {
                Edge *edge = *kt;
                Edge *initialEdge = *it;
                int node = *jt;
                if ((initialEdge->source == edge->source && node == edge->destination) || (initialEdge->source == edge->destination && node == edge->source)) {
                    edge1 = edge;
                    break;
                }
            }
            
            for (std::set<Edge *>::iterator kt=edges.begin(); kt != edges.end(); ++kt) {
                Edge *edge = *kt;
                Edge *initialEdge = *it;
                int node = *jt;
                if ((initialEdge->destination == edge->source && node == edge->destination) || (initialEdge->destination == edge->destination && node == edge->source)) {
                    edge2 = edge;
                    break;
                }
            }
            
            if (edge1 != nullptr && edge2 != nullptr) {
                edgesPartOfTriangle.insert(edge1);
                edgesPartOfTriangle.insert(edge2);
                Edge *edge3 = *it;
                edgesPartOfTriangle.insert(edge3);
            }
            
        }
    }
    
    return edges.size() - edgesPartOfTriangle.size();
}
Esempio n. 5
0
void SimpleIndexSearcher::search(std::vector<DocId> &docIds,
        const std::set<Term> &terms) const
{
    std::set<Term>::const_iterator termsIter = terms.begin();
    if(termsIter == terms.end())
        return;

    //TODO: optimize it
    docIds = getIndex().getPostings(*termsIter);
    ++termsIter;

    for(; termsIter != terms.end(); ++termsIter)
        docIds = docIds & getIndex().getPostings(*termsIter);

    base::Log().debug("find %lu documents for %lu terms", docIds.size(),
            terms.size());
}
Esempio n. 6
0
bool SelectiveClustering::AddCluster(vtkIdType key, std::set<vtkIdType> ClusterSelectionSet)
{
	/*! 
	* Adds a unique new cluster
	* replaces cluster if one with the key currently exists
	*/
	this->iter = this->ClusterMap.find(key);
	if ((this->ClusterMap.size() > 0) && (this->iter != this->ClusterMap.end()))
	{
		//Remove old item
		this->ClusterMap.erase(iter);
	}
	this->ClusterMap[key] = ClusterSelectionSet;
	this->AddRowToClusterTable(key, vtkVariant(ClusterSelectionSet.size()), NULL);
	emit ClusterChanged();
	return true;
}
Esempio n. 7
0
int main()
{
    for (int i = 0; i < 20; ++i)
    {
        boost::shared_ptr<GameObject> p(new Tank);
        all_targets.insert(p);
    }

    while (all_targets.size())
    {
        std::for_each(
            all_targets.begin(),
            all_targets.end(),
            boost::bind(&GameObject::time_slice,_1)
        );
    }
}
Esempio n. 8
0
void ConsoleView::showCourses(std::set<std::shared_ptr<Course>> courses)
{
    if(courses.size() == 0)
        cerr << "No course to show." << endl;
    else
    {
        for(auto i = courses.begin(); i != courses.end(); ++i)
        {
            cout << "Title : " << (*i)->getTitle() << endl;
            cout << "Author : " << (*i)->getAuthor() << endl;
            cout << "Duration : " << (*i)->getDuration() << endl;
            cout << "Price : " << (*i)->getPrice() << endl;
            cout << "Description : " << (*i)->getDescription() << endl;
            cout << endl;
        }
    }
}
Esempio n. 9
0
  bool CoordDataFile::Get(const std::set<OSMId>& ids, ResultMap& resultMap) const
  {
    assert(isOpen);

    resultMap.clear();
    resultMap.reserve(ids.size());

    try {
      for (const auto& id : ids) {
        PageId relatedId=id+std::numeric_limits<OSMId>::min();
        PageId pageId=relatedId/pageSize;

        PageIdFileOffsetMap::const_iterator pageOffset=pageFileOffsetMap.find(pageId);

        if (pageOffset==pageFileOffsetMap.end()) {
          continue;
        }

        FileOffset offset=pageOffset->second+(relatedId%pageSize)*(coordByteSize+1);

        scanner.SetPos(offset);

        uint8_t  serial;
        bool     isSet;
        GeoCoord coord;

        scanner.Read(serial);
        scanner.ReadConditionalCoord(coord,
                                     isSet);

        if (!isSet) {
          continue;
        }

        resultMap.insert(std::make_pair(id,
                                        Coord(serial,
                                              coord)));
      }
    }
    catch (IOException& e) {
      log.Error() << e.GetDescription();
      return false;
    }

    return true;
  }
		void collect_garbage ( singlethreaded_marksweep::stats *s )
		{
			size_t precollection_heap_bytes = m_current_heap_bytes;
			mark_live_objects();
			sweep_dead_objects();
			m_last_collection_heap_size = m_current_heap_bytes;
			set_collection_rate ( m_percent_growth );

			if ( s )
			{
				s->live_heap_bytes = m_current_heap_bytes;
				s->garbage_bytes = precollection_heap_bytes - s->live_heap_bytes;
				s->root_pointers = m_roots.size();
				s->live_pointers = s->root_pointers + m_heap_ptrs.size();
				s->root_containers = m_root_containers.size();
			}
		}
Esempio n. 11
0
std::set<T> MonsterGenerator::get_set_from_tags(std::set<std::string> tags, std::map<std::string, T> conversion_map, T fallback)
{
    std::set<T> ret;

    if (tags.size() > 0){
        for (std::set<std::string>::iterator it = tags.begin(); it != tags.end(); ++it){
            if (conversion_map.find(*it) != conversion_map.end()){
                ret.insert(conversion_map[*it]);
            }
        }
    }
    if (ret.size() == 0){
        ret.insert(fallback);
    }

    return ret;
}
Esempio n. 12
0
//-----------------------------------------------
// getLodCharacterId
// Get the lod character id from the scene, according to LodCharacterName. Cached.
// -1 if id not found.
//-----------------------------------------------
sint getLodCharacterId(UScene &scene, const string &lodCharacterName)
{
	sint lodCharacterId = scene.getCLodShapeIdByName(lodCharacterName);
	// display a warning for bad character Id, only if name was setup in the sheet
	if(lodCharacterId==-1 && !lodCharacterName.empty() )
	{
		// Limited to 100 missing Lod to avoid memories problems
		if(LodCharactersNotFound.size() < 100)
		{
			// Insert and display a waring
			if(LodCharactersNotFound.insert(lodCharacterName).second)
				nlwarning("getLodCharacterId: Not found A Character LodCharacter in the Manager: %s", lodCharacterName.c_str());
		}
	}

	return lodCharacterId;
}// getLodCharacterId //
Esempio n. 13
0
Nucleotide Nucleotide::singleNucleotide(std::set<Nucleotide>& nucleotides)
{
	std::set<Nucleotide>::iterator itgap = nucleotides.find(GAP);
	if(itgap != nucleotides.end())
		nucleotides.erase(itgap);

	if (nucleotides.size() == 1)
		return *nucleotides.begin();
	
	std::set<Nucleotide> all;
	for(std::set<Nucleotide>::iterator it = nucleotides.begin(); it != nucleotides.end(); ++it) {
		std::vector<Nucleotide> t;
		it->nonAmbiguousNucleotides(t);
		all.insert(t.begin(), t.end());
	}
	bool nta = all.find(A) != all.end();
	bool ntc = all.find(C) != all.end();
	bool ntg = all.find(G) != all.end();
	bool ntt = all.find(T) != all.end();

	if (nta && ntc && ntg && ntt)
		return N;
	if (nta && ntc && ntg)
		return V;
	if (nta && ntc && ntt)
		return H;
	if (nta && ntg && ntt)
		return D;
	if (ntc && ntg && ntt)
		return B;
 	if (nta && ntc)
		return M;
	if (ntg && ntt)
		return K;
	if (nta && ntt)
		return W;
	if (ntg && ntc)
		return S;
	if (ntc && ntt)
		return Y;
	if (nta && ntg)
		return R;		

	throw std::runtime_error
	  ("Internal error in Nucleotide::singleNucleotide()");
}
Esempio n. 14
0
void 
Network::setPhases_(Region *r, std::set<UInt32>& phases)
{
  if (phases.size() == 0)
    NTA_THROW << "Attempt to set empty phase list for region " << r->getName();

  UInt32 maxNewPhase = *(phases.rbegin());
  UInt32 nextPhase = phaseInfo_.size();
  if (maxNewPhase >= nextPhase)
  {
    // It is very unlikely that someone would add a region
    // with a phase much greater than the phase of any other
    // region. This sanity check catches such problems, 
    // though it should arguably be legal to set any phase. 
    if (maxNewPhase - nextPhase > 3)
      NTA_THROW << "Attempt to set phase of " << maxNewPhase
                << " when expected next phase is " << nextPhase
                << " -- this is probably an error.";

    phaseInfo_.resize(maxNewPhase+1);
  }
  for (UInt i = 0; i < phaseInfo_.size(); i++)
  {
    bool insertPhase = false;
    if (phases.find(i) != phases.end())
      insertPhase = true;

    // remove previous settings for this region
    std::set<Region*>::iterator item;
    item = phaseInfo_[i].find(r);
    if (item != phaseInfo_[i].end() && !insertPhase)
    {
      phaseInfo_[i].erase(item);
    } else if (insertPhase) 
    {
      phaseInfo_[i].insert(r);
    }
  }

  // keep track (redundantly) of phases inside the Region also, for serialization
  r->setPhases(phases);

  resetEnabledPhases_();

}
Esempio n. 15
0
std::vector<std::u16string> BiDi::applyLineBreaking(std::set<std::size_t> lineBreakPoints) {
    // BiDi::getLine will error if called across a paragraph boundary, so we need to ensure that all
    // paragraph boundaries are included in the set of line break points. The calling code might not
    // include the line break because it didn't need to wrap at that point, or because the text was
    // separated with a more exotic code point such as (U+001C)
    mergeParagraphLineBreaks(lineBreakPoints);

    std::vector<std::u16string> transformedLines;
    transformedLines.reserve(lineBreakPoints.size());

    std::size_t start = 0;
    for (std::size_t lineBreakPoint : lineBreakPoints) {
        transformedLines.push_back(getLine(start, lineBreakPoint));
        start = lineBreakPoint;
    }

    return transformedLines;
}
    /** @brief Wrapper for allocate resources
     *  @param jobId The id of the job to allocate resources
     *  @param machines The set of machines that will be allocated to the job
     */
    void AllocResourcesWrapper(int jobId, std::set<int32_t> & machines) {
        dbg_printf("Allocate %d machines for %d\n", (int)machines.size(),jobId);
        printRackInfo();

        int yarnport = 9090;
        shared_ptr<TTransport> socket(new TSocket("localhost", yarnport));
        shared_ptr<TTransport> transport(new TBufferedTransport(socket));
        shared_ptr<TProtocol> protocol(new TBinaryProtocol(transport));
        YARNTetrischedServiceClient client(protocol);
        // try to allocate some nodes
        try {
            transport->open();
            client.AllocResources(jobId, machines);
            transport->close();
        } catch (TException& tx) {
            dbg_printf("ERROR calling YARN : %s\n", tx.what());
        }
    }
Esempio n. 17
0
std::string const &Reference::readItem(size_t i)
{
    if (i >= readItems_.size())
    {
        throw std::runtime_error("readItem() argument out of bounds");
    }
    if (i < readItemsIterPos_ || readItemsIterPos_ == 0)
    {
        readItemsIterPos_ = 0;
        readItemsIter_ = readItems_.begin();
    }
    while (i > readItemsIterPos_)
    {
        ++readItemsIter_;
        ++readItemsIterPos_;
    }
    return *readItemsIter_;
}
bool StringCipherWithPermutationKey::isUniqueWithoutMissingIntegers(const KeyType &key)
{
    const uint32_t key_len = key.size();
    const std::set<int32_t> sorted_key(key.begin(), key.end());
    if (key_len != sorted_key.size())
    {
        return false;
    }

    // Check if all integers are between 0 and the size of the key.
    const uint32_t max_int = *std::max_element(sorted_key.begin(), sorted_key.end());
    if (max_int >= key_len)
    {
        return false;
    }

    return true;
}
std::string CmdLineParserHelper::GetChoice(const std::string& param, const std::set<std::string>& choices, const std::string& def_value)
{
    std::string ret = GetString(param, def_value);
    if (choices.find(ret) == choices.end())
    {
        std::stringstream choices_str;
        unsigned int i = 0;
        for (const auto& choice : choices)
        {
            choices_str << choice;
            if (i != choices.size() - 1)
                choices_str << ",";
            i++;
        }
        FatalLog("Invalid choice given for %s.  Valid choices are [%s].", param.c_str(), choices_str.str().c_str());
    }
    return ret;
}
void ScoutManager::update(const std::set<BWAPI::UnitInterface*> & scoutUnits)
{
	if (scoutUnits.size() == 1)
	{
		BWAPI::UnitInterface* scoutUnit = *scoutUnits.begin();

		if (scoutUnit->getType().isWorker())
		{
			if (scoutUnit != workerScout)
			{
				numWorkerScouts++;
				workerScout = scoutUnit;
			}
		}
	}

	moveScouts();
}
Esempio n. 21
0
//-*****************************************************************************
void simpleTestIn( const std::string &iArchiveName )
{
    IArchive archive( Alembic::AbcCoreHDF5::ReadArchive(),
                      iArchiveName, ErrorHandler::kThrowPolicy );

    IObject archiveTop = archive.getTop();

    TESTING_ASSERT( archiveTop.getNumChildren() == NUM_TOP_CHILDREN );

    for ( int i = 0 ; i < NUM_TOP_CHILDREN ; i++ )
    {
        std::string cname = boost::lexical_cast<std::string>( i );
        IObject obj( archiveTop, cname );
        readDeepHierarchy( obj, 0, obj  );
    }

    TESTING_ASSERT( PATHS.size() == NUM_TOP_CHILDREN );
}
Esempio n. 22
0
vtkIdType SelectiveClustering::AddCluster(std::set<vtkIdType> ClusterSelectionSet)
{
	/*! 
	* Create a new cluster from a selection
	*/
	vtkIdType newKey = this->ClusterMap.size();
	this->iter = this->ClusterMap.find(newKey);
	while ((this->ClusterMap.size() > 0) &&(this->iter != this->ClusterMap.end()))
	{
		newKey++;
		this->iter = this->ClusterMap.find(newKey);
	}
	this->ClusterMap[newKey] = ClusterSelectionSet;
	this->AddRowToClusterTable(newKey, vtkVariant(ClusterSelectionSet.size()), NULL);

	emit ClusterChanged();
	return newKey;
}
Esempio n. 23
0
int CHeroClass::chooseSecSkill(const std::set<int> & possibles) const //picks secondary skill out from given possibilities
{
	if(possibles.size()==1)
		return *possibles.begin();
	int totalProb = 0;
	for(std::set<int>::const_iterator i=possibles.begin(); i!=possibles.end(); i++)
	{
		totalProb += proSec[*i];
	}
	int ran = rand()%totalProb;
	for(std::set<int>::const_iterator i=possibles.begin(); i!=possibles.end(); i++)
	{
		ran -= proSec[*i];
		if(ran<0)
			return *i;
	}
	throw std::string("Cannot pick secondary skill!");
}
Esempio n. 24
0
SecondarySkill CHeroClass::chooseSecSkill(const std::set<SecondarySkill> & possibles) const //picks secondary skill out from given possibilities
{
	if(possibles.size()==1)
		return *possibles.begin();
	int totalProb = 0;
	for(auto & possible : possibles)
	{
		totalProb += secSkillProbability[possible];
	}
	int ran = rand()%totalProb;
	for(auto & possible : possibles)
	{
		ran -= secSkillProbability[possible];
		if(ran<0)
			return possible;
	}
	throw std::runtime_error("Cannot pick secondary skill!");
}
Esempio n. 25
0
void CFileItemHandler::FillDetails(const ISerializable *info, const CFileItemPtr &item, std::set<std::string> &fields, CVariant &result, CThumbLoader *thumbLoader /* = NULL */)
{
  if (info == NULL || fields.size() == 0)
    return;

  CVariant serialization;
  info->Serialize(serialization);

  bool fetchedArt = false;

  std::set<std::string> originalFields = fields;

  for (std::set<std::string>::const_iterator fieldIt = originalFields.begin(); fieldIt != originalFields.end(); ++fieldIt)
  {
    if (GetField(*fieldIt, serialization, item, result, fetchedArt, thumbLoader) && result.isMember(*fieldIt) && !result[*fieldIt].empty())
      fields.erase(*fieldIt);
  }
}
Esempio n. 26
0
    /**
      * Pagerank update function.
	  */
	void update(graphchi_vertex<VertexDataType, EdgeDataType> &v, graphchi_context &ginfo) {
		//array[v.id()]++;		
		if (ginfo.iteration == 0 && v.num_edges() > 0) {
			
			nbs.clear();
			for(int i=0; i<v.num_edges(); i++){
				nbs.insert(v.edge(i)->vertex_id());	
			}
			num_edges += nbs.size(); 
			/*
			if(v.num_inedges() > 0){
				//lock.lock();
				num_edges += v.num_inedges();
				//lock.unlock();
			}
			*/
		} else if(ginfo.iteration == 1){
			if(v.id() == 0){
				fprintf(fp_metis, "%u %u\n", num_vertices, num_edges/2);	
			}
			if(v.num_edges() > 0){	
				nbs.clear();
				for(int i=0; i<v.num_edges(); i++){
					nbs.insert(v.edge(i)->vertex_id());	
					/*
					graphchi_edge<EdgeDataType> * edge = v.edge(i);
					//EdgeDataType edata = edge->get_data();
					vid_t nb_id = edge->vertex_id();
					//lock.lock();
					fprintf(fp_metis, "%u ", nb_id+1);		
					//lock.unlock();
					//edge->set_data(edata);	
					*/
				}
				std::set<vid_t>::iterator it;
				for(it = nbs.begin(); it != nbs.end(); it++){
					fprintf(fp_metis, "%u ", (*it)+1);		
				}
				fprintf(fp_metis, "\n");
			}else{
				fprintf(fp_metis, "\n");
			}
		}
	}
Esempio n. 27
0
 void operator()(msgpack::object::with_zone& o, const std::set<T>& v) const {
     o.type = msgpack::type::ARRAY;
     if(v.empty()) {
         o.via.array.ptr = nullptr;
         o.via.array.size = 0;
     } else {
         uint32_t size = checked_get_container_size(v.size());
         msgpack::object* p = static_cast<msgpack::object*>(o.zone.allocate_align(sizeof(msgpack::object)*size));
         msgpack::object* const pend = p + size;
         o.via.array.ptr = p;
         o.via.array.size = size;
         typename std::set<T>::const_iterator it(v.begin());
         do {
             *p = msgpack::object(*it, o.zone);
             ++p;
             ++it;
         } while(p < pend);
     }
 }
Esempio n. 28
0
void new_code_line (string_pos n, std::string& new_code)
{
	if (new_instanciations.size() > 0)
	{
		for (std::set<std::string>::iterator i = new_instanciations.begin(); i != new_instanciations.end(); ++i)
		{
			new_code_lines.push_back (*i);
		}
	}

	new_code_lines.push_back (new_code);
	new_code = "";

	previous_line_start = n;
	if (n > 0)
		n--;

	new_instanciations.clear();
}
Esempio n. 29
0
void SoundCache::addSoundsWithSetAsync(std::set<const char *> &set, std::function<void (CCObject *)> onComplete) {
    cocos2d::CCDictionary* dictionary = cocos2d::CCDictionary::create();
    dictionary->retain();
    int* counter = new int(set.size());
    for (std::set<const char*>::iterator it = set.begin(); it != set.end(); it++) {
        AsyncTask<Sound*>* task = this->initTaskWithFile(*it);
        task->setCompletionFunc([this, counter, dictionary, onComplete](Sound* sound) -> void {
            m_sounds->setObject(sound, sound->getFileName());
            dictionary->setObject(sound, sound->getFileName());
            if (--(*counter) <= 0) {
                onComplete(dictionary);
                delete counter;
            }
            sound->release();
        });
        m_tasks.push(task);
    }
    this->start();
}
Esempio n. 30
0
        virtual float perimeter() {
            float res = 0.0;

            if (p.size() >= 3) {
                std::set<point *>::iterator it = p.begin();
                std::set<point *>::iterator it2 = p.begin();
                it2++;

                while (it2 != p.end()) {
                    res += (*it)->distance((*it2));
                    it++;
                    it2++;
                }
                it2 = p.begin();
                res += (*it)->distance(*it2);
            }

            return res;
        };