Example #1
0
void Graph::read(const char * fn) {
    std::ifstream inf (fn);
    std::string line;
    int n;
    node_number = 0;
    std::vector<int> tmp;
    while (std::getline(inf, line)) {
	read_line(line, &tmp);
	if ( tmp.size() == 2 ) {
	    if( node_order.find(tmp.at(0)) == node_order.end() ) {
		node_order[tmp.at(0)] = node_number;
		node_number++;
	    };
	    if( node_order.find(tmp.at(1)) == node_order.end() ) {
		node_order[tmp.at(1)] = node_number;
		node_number++;
	    };
	};
	tmp.clear();
    };
    nodes.resize(node_number);
    times.resize(node_number);
    visited.insert(visited.begin(), node_number, false);
    inf.clear();
    inf.seekg(0);
    while (std::getline(inf, line)) {
	read_line(line, &tmp);
	if ( tmp.size() == 2 ) {
	    nodes.at(node_order[tmp.at(1)]).add_reverse_edge(node_order[tmp.at(0)]);
	    nodes.at(node_order[tmp.at(0)]).add_edge(node_order[tmp.at(1)]);
	    };
	tmp.clear();
    };
    node_order.clear();
};
void Streamer::processPickups(Player &player, const std::vector<SharedCell> &cells)
{
	static boost::unordered_map<int, Item::SharedPickup> discoveredPickups;
	for (std::vector<SharedCell>::const_iterator c = cells.begin(); c != cells.end(); ++c)
	{
		for (boost::unordered_map<int, Item::SharedPickup>::const_iterator p = (*c)->pickups.begin(); p != (*c)->pickups.end(); ++p)
		{
			boost::unordered_map<int, Item::SharedPickup>::iterator d = discoveredPickups.find(p->first);
			if (d == discoveredPickups.end())
			{
				if (checkPlayer(p->second->players, player.playerID, p->second->interiors, player.interiorID, p->second->worlds, player.worldID))
				{
					if (boost::geometry::comparable_distance(player.position, p->second->position) <= p->second->streamDistance)
					{
						boost::unordered_map<int, int>::iterator i = internalPickups.find(p->first);
						if (i == internalPickups.end())
						{
							p->second->worldID = !p->second->worlds.empty() ? player.worldID : -1;
						}
						discoveredPickups.insert(*p);
					}
				}
			}
		}
	}
	if (processingFinalPlayer)
	{
		boost::unordered_map<int, int>::iterator i = internalPickups.begin();
		while (i != internalPickups.end())
		{
			boost::unordered_map<int, Item::SharedPickup>::iterator d = discoveredPickups.find(i->first);
			if (d == discoveredPickups.end())
			{
				DestroyPickup(i->second);
				i = internalPickups.erase(i);
			}
			else
			{
				discoveredPickups.erase(d);
				++i;
			}
		}
		for (boost::unordered_map<int, Item::SharedPickup>::iterator d = discoveredPickups.begin(); d != discoveredPickups.end(); ++d)
		{
			if (internalPickups.size() == visiblePickups)
			{
				break;
			}
			int internalID = CreatePickup(d->second->modelID, d->second->type, d->second->position[0], d->second->position[1], d->second->position[2], d->second->worldID);
			if (internalID == INVALID_ALTERNATE_ID)
			{
				break;
			}
			internalPickups.insert(std::make_pair(d->second->pickupID, internalID));
		}
		discoveredPickups.clear();
	}
}
Example #3
0
static double
score2(const boost::unordered_map<int, double> &m0,
       const boost::unordered_map<int, double> &m1)
{
  int tmp = 0;
  auto i0 = m0.begin();
  auto i1 = m1.begin();
  while (i0 != m0.end() && i1 != m1.end()) {
    if (i0->first < i1->first) ++i0;
    else if (i0->first > i1->first) ++i1;
    else ++tmp, ++i0, ++i1;
  }
  return m0.size() + m1.size() - tmp;
}
Example #4
0
 size_t count(std::string const& x) const {
     auto iter = counts.find(x);
     if (iter != counts.end()) {
         return iter->second;
     }
     return 0;
 }
Example #5
0
bool TwoSum::find_sum(long int target) {
    long int bucket;
    for( auto it = numbers_to_check.begin(); it != numbers_to_check.end(); it++ ) {
	if( numbers.find((*it) - target) == numbers.end() ) { continue; };
	bucket = numbers.bucket( (*it) - target );
	for(auto it_local = numbers.begin(bucket); it_local != numbers.end(bucket); ++it_local) {
	    if ( ( it_local->first + target ) != (*it) ) { continue; }; 
	    if ( it_local->first != target || (it_local->first == target && multi_numbers.find(target) != multi_numbers.end()) ) {
		std::cout << target << " + " << it_local->first << " = " << (*it) << " ( " << target + it_local->first << std::endl;
		numbers_to_check.erase(it);
		return true; 
	    };
	};
    };
    return false;
};
std::string RippleAddress::humanAccountID () const
{
    switch (nVersion)
    {
    case VER_NONE:
        throw std::runtime_error ("unset source - humanAccountID");

    case VER_ACCOUNT_ID:
    {
        boost::mutex::scoped_lock sl (rncLock);
        boost::unordered_map< Blob , std::string >::iterator it = rncMap.find (vchData);

        if (it != rncMap.end ())
            return it->second;

        if (rncMap.size () > 10000)
            rncMap.clear ();

        return rncMap[vchData] = ToString ();
    }

    case VER_ACCOUNT_PUBLIC:
    {
        RippleAddress   accountID;

        (void) accountID.setAccountID (getAccountID ());

        return accountID.ToString ();
    }

    default:
        throw std::runtime_error (str (boost::format ("bad source: %d") % int (nVersion)));
    }
}
void IndexingVariables::set(
    boost::unordered_map<std::string, boost::shared_ptr<ArrayStorage> > as,
    int offset) {
  hm.clear();
  hm.insert(as.begin(), as.end());
  this->offset = offset;
}
Example #8
0
File: var.cpp Project: hyln9/nV
wcs Symbol::name() const {
    boost::unordered_map<sym, wcs>::const_iterator
    iter = names.find(this);
    if (iter != names.end())
        return iter->second;
    return 0;
}
DataProperty MessageConversions::dataPropertyFromMessage(const
    semantic_map_msgs::DataProperty& message, boost::unordered_map<
    std::string, Entity>& entities) const {
  boost::unordered_map<std::string, Entity>::iterator it = entities.
    find(message.subject);
  
  if ((it == entities.end()) || !it->second.isValid())
    throw ConversionFailed("Entity with identifier ["+
      message.subject+"] is undefined.");
    
  if (message.value_type == semantic_map_msgs::DataProperty::
      VALUE_TYPE_STRING)
    return it->second.addProperty(message.id, message.value);
  else if (message.value_type == semantic_map_msgs::DataProperty::
      VALUE_TYPE_BOOL)
    return it->second.addProperty(message.id, boost::lexical_cast<bool>(
      message.value));
  else if (message.value_type == semantic_map_msgs::DataProperty::
      VALUE_TYPE_FLOAT)
    return it->second.addProperty(message.id, boost::lexical_cast<double>(
      message.value));
  else if (message.value_type == semantic_map_msgs::DataProperty::
      VALUE_TYPE_INT)
    return it->second.addProperty(message.id, boost::lexical_cast<int>(
      message.value));
  else
    return DataProperty();
}
//! Dump Legendre polynomial cache data to stream (table and history).
void dumpLegendrePolynomialCacheData( std::ostream& outputStream,
                                      boost::unordered_map< Point, double > cacheTable,
                                      boost::circular_buffer< Point > cacheHistory )
{
    outputStream << "Table:\n";

    for ( boost::unordered_map< Point, double >::iterator iteratorCacheTable = cacheTable.begin( );
          iteratorCacheTable != cacheTable.end( ); iteratorCacheTable++ )
    {
        outputStream << "\t" << writeLegendrePolynomialStructureToString(
                            iteratorCacheTable->first ).c_str( ) << " => "
                     << iteratorCacheTable->second << std::endl;
    }

    outputStream << "History:\n";

    for ( boost::circular_buffer< Point >::iterator iteratorCacheHistory = cacheHistory.begin( );
          iteratorCacheHistory != cacheHistory.end( ); iteratorCacheHistory++ )
    {
        outputStream << "\t"
                     << writeLegendrePolynomialStructureToString( *iteratorCacheHistory ).c_str( )
                     << ", ";
    }

    outputStream << std::endl;
}
Example #11
0
	bool dbconn_pool::init_pool(boost::unordered_map<std::string, std::string>& cfg)
	{
		std::vector<std::string> keys;
		{
			keys.push_back("host");
			keys.push_back("userid");
			keys.push_back("passwd");
			keys.push_back("database");
			keys.push_back("port");
			keys.push_back("charset");
			keys.push_back("pool_size");
			keys.push_back("wait_timeout_sec");
		}

		boost::unordered_map<std::string, std::string>::iterator found;
		for (std::size_t i = 0; i < keys.size(); ++i)
		{
			found = cfg.find(keys[i]);
			if (found == cfg.end())
			{
				return false;
			}

			if (keys[i] == "host")
			{
				host = found->second;
			}
			else if (keys[i] == "userid")
			{
				userid = found->second;
			}
			else if (keys[i] == "passwd")
			{
				passwd = found->second;
			}
			else if (keys[i] == "database")
			{
				database = found->second;
			}
			else if (keys[i] == "port")
			{
				port = boost::lexical_cast<unsigned int>(found->second);
			}
			else if (keys[i] == "charset")
			{
				charset = found->second;
			}
			else if (keys[i] == "pool_size")
			{
				pool_size = boost::lexical_cast<std::size_t>(found->second);
			}
			else if (keys[i] == "wait_timeout_sec")
			{
				wait_timeout_sec = boost::lexical_cast<double>(found->second);
			}
		}

		return true;
	}
Example #12
0
 bool operator()(boost::any & x) {
     boost::unordered_map<boost::reference_wrapper<std::type_info const>, boost::function<void(boost::any&)>, type_info_hash, equal_ref>::iterator it = fs.find(boost::ref(x.type()));
     if (it != fs.end()) {
         it->second(x);
         return true;
     } else {
         return false;
     }
 }
Example #13
0
///Calculates the Gini impurity of a node. The impurity is defined as
///1-sum_j p(j|t)^2
///i.e the 1 minus the sum of the squared probability of observing class j in node t
double CARTTrainer::gini(boost::unordered_map<std::size_t, std::size_t>& countMatrix, std::size_t n){
	double res = 0;
	boost::unordered_map<std::size_t, std::size_t>::iterator it;
	double denominator = n;
	for ( it=countMatrix.begin() ; it != countMatrix.end(); it++ ){
		res += sqr(it->second/denominator);
	}
	return 1-res;
}
Example #14
0
bool buildNameLookupTable(Kompex::SQLiteStatement * stmt,
                          boost::unordered_map<std::string,int32_t> &table_names)
{
    std::string stmt_insert = "INSERT INTO name_lookup";
    stmt_insert += "(name_id,name_lookup) VALUES(@name_id,@name_lookup);";

    try   {
        stmt->BeginTransaction();
        stmt->Sql(stmt_insert);
    }
    catch(Kompex::SQLiteException &exception)   {
        qDebug() << "ERROR: SQLite exception with insert statement:"
                 << QString::fromStdString(exception.GetString());
        return false;
    }

    // keep track of the number of transactions and
    // commit after a certain limit
    size_t transaction_limit=5000;
    size_t transaction_count=0;

    // write name lookup info the database
    boost::unordered_map<std::string,int32_t>::iterator it;
    for(it  = table_names.begin(); it != table_names.end(); ++it)   {
        // prepare sql
        try   {
            //[name_id, name_lookup]
            stmt->BindInt(1,it->second);
            stmt->BindString(2,it->first);
            stmt->Execute();
            stmt->Reset();

            if(transaction_count > transaction_limit)   {
                stmt->FreeQuery();
                stmt->CommitTransaction();

                stmt->BeginTransaction();
                stmt->Sql(stmt_insert);
                transaction_count=0;
            }
            transaction_count++;
        }
        catch(Kompex::SQLiteException &exception)   {
            qDebug() << "ERROR: SQLite exception writing tile data:"
                     << QString::fromStdString(exception.GetString());
            qDebug() << "ERROR: name_id:" << it->second;
            qDebug() << "ERROR: name_lookup:" << QString::fromStdString(it->first);
            return false;
        }
    }

    stmt->FreeQuery();
    stmt->CommitTransaction();

    return true;
}
Example #15
0
	operators from_name( const std::string& name){
		boost::unordered_map< std::string, operators >::const_iterator
			find_result_it = name_to_enum.find(name);
			
		if ( find_result_it != name_to_enum.end() ){
			return find_result_it->second;
		}

		throw "unexcepted enumuration name!";
	}
ObjectProperty MessageConversions::objectPropertyFromMessage(const
    semantic_map_msgs::ObjectProperty& message, boost::unordered_map<
    std::string, Entity>& entities) const {
  boost::unordered_map<std::string, Entity>::iterator it = entities.
    find(message.subject);
  
  if ((it == entities.end()) || !it->second.isValid())
    throw ConversionFailed("Entity with identifier ["+
      message.subject+"] is undefined.");
    
  boost::unordered_map<std::string, Entity>::iterator jt = entities.
    find(message.object);
  
  if ((jt == entities.end()) || !jt->second.isValid())
    throw ConversionFailed("Entity with identifier ["+
      message.object+"] is undefined.");

  return it->second.addProperty(message.id, jt->second);
}
Example #17
0
	cairo_surface_t* getImage(string path)
	{
		auto it = images.find(path);
		if (it != images.end())
			return (*it).second;

		cairo_surface_t* image = cairo_image_surface_create_from_png(path.c_str());
		images.insert(std::make_pair(path, image));
		return image;
	}
Example #18
0
	Cairo::RefPtr<Cairo::ImageSurface> getIcon(string path)
	{
		auto it = stored.find(path);
		if (it != stored.end())
			return (*it).second;

		Cairo::RefPtr<Cairo::ImageSurface> image = Cairo::ImageSurface::create_from_png(path);
		stored[path] = image;
		return image;
	}
Example #19
0
	std::string to_name( operators const& val ){
		boost::unordered_map< operators, std::string >::const_iterator
			find_result_it = enum_to_name.find(val);
			
		if ( find_result_it != enum_to_name.end() ){
			return find_result_it->second;
		}

		return "__unknown_enum_val__";
	}
Example #20
0
void read_db_users()
{
	m_read_db_users_time = srv_time();
	if (!m_use_sql)
		return;
	try
	{
		Csql_query q(m_database, "select @uid");
		if (m_read_users_can_leech)
			q += ", can_leech";
		if (m_read_users_peers_limit)
			q += ", peers_limit";
		if (m_read_users_torrent_pass)
			q += ", torrent_pass";
		q += ", torrent_pass_version";
		if (m_read_users_wait_time)
			q += ", wait_time";
		q += " from @users";
		Csql_result result = q.execute();
		// m_users.reserve(result.size());
		for (auto& i : m_users)
			i.second.marked = true;
		m_users_torrent_passes.clear();
		while (Csql_row row = result.fetch_row())
		{
			t_user& user = m_users[row[0].i()];
			user.marked = false;
			int c = 0;
			user.uid = row[c++].i();
			if (m_read_users_can_leech)
				user.can_leech = row[c++].i();
			if (m_read_users_peers_limit)
				user.peers_limit = row[c++].i();
			if (m_read_users_torrent_pass)
			{
				if (row[c].size() == 32)
					m_users_torrent_passes[to_array<char, 32>(row[c])] = &user;
				c++;
			}
			user.torrent_pass_version = row[c++].i();
			if (m_read_users_wait_time)
				user.wait_time = row[c++].i();
		}
		for (auto i = m_users.begin(); i != m_users.end(); )
		{
			if (i->second.marked)
				m_users.erase(i++);
			else
				i++;
		}
	}
	catch (bad_query&)
	{
	}
}
    // finds a promise by ID, returns and unregisters the promise
    inline boost::promise<message_reply*>* get_promise(uint64_t promise_id) {
      boost::unordered_map<uint64_t, boost::promise<message_reply*>* >
          ::iterator iter = promises.find(promise_id);
      if (iter == promises.end()) return NULL;
      else {
        boost::promise<message_reply*>* ret = iter->second;
        promises.erase(iter);
        return ret;
      }

    }
Example #22
0
File: var.cpp Project: hyln9/nV
var Symbol::get(wcs x) const {
    boost::unordered_map<sym, Context>::const_iterator
    iter = contexts.find(this);
    if (iter != contexts.end()) {
        Context::const_iterator
        iter2 = iter->second.find(reinterpret_cast<uint>(x));
        if (iter2 != iter->second.end())
            return iter2->second;
    }
    return null;
}
Example #23
0
///Calculates the Gini impurity of a node. The impurity is defined as
///1-sum_j p(j|t)^2
///i.e the 1 minus the sum of the squared probability of observing class j in node t
double RFTrainer::gini(boost::unordered_map<std::size_t, std::size_t> & countMatrix, std::size_t n){
	double res = 0;
	boost::unordered_map<std::size_t, std::size_t>::iterator it;
	if(n){
		n = n*n;
		for ( it=countMatrix.begin() ; it != countMatrix.end(); it++ ){
			res += sqr(it->second)/(double)n;
		}
	}
	return 1-res;
}
Example #24
0
// Makes sure that no three points all on an original tile edge
// are triangulated.
bool is_legal(const Point_3& a, const Point_3& b, const Point_3& c,
	      const boost::unordered_map<Point_3, boost::unordered_set<Segment_3_undirected> >& point2edges)
{
  static log4cplus::Logger logger = log4cplus::Logger::getInstance("polygon_utils.is_legal");

  LOG4CPLUS_TRACE(logger, "is_legal: " << pp(a) << " " << pp(b) << " " << pp(c));

  if (point2edges.find(a) == point2edges.end())
    return true;
  if (point2edges.find(b) == point2edges.end())
    return true;
  if (point2edges.find(c) == point2edges.end())
    return true;

  const boost::unordered_set<Segment_3_undirected>& edgesa = point2edges.find(a)->second;
  const boost::unordered_set<Segment_3_undirected>& edgesb = point2edges.find(b)->second;
  const boost::unordered_set<Segment_3_undirected>& edgesc = point2edges.find(c)->second;

  boost::unordered_set<Segment_3_undirected> edges(set_intersection(edgesa, set_intersection(edgesb, edgesc)));
  return edges.empty();
}
void PropertyExpressionEngine::buildGraphStructures(const ObjectIdentifier & path,
                                                    const boost::shared_ptr<Expression> expression,
                                                    boost::unordered_map<ObjectIdentifier, int> & nodes,
                                                    boost::unordered_map<int, ObjectIdentifier> & revNodes,
                                                    std::vector<Edge> & edges) const
{
    std::set<ObjectIdentifier> deps;

    /* Insert target property into nodes structure */
    if (nodes.find(path) == nodes.end()) {
        int s = nodes.size();

        revNodes[s] = path;
        nodes[path] = s;
    }
    else
        revNodes[nodes[path]] = path;

    /* Get the dependencies for this expression */
    expression->getDeps(deps);

    /* Insert dependencies into nodes structure */
    std::set<ObjectIdentifier>::const_iterator di = deps.begin();
    while (di != deps.end()) {
        Property * prop = di->getProperty();

        if (prop) {
            ObjectIdentifier cPath(di->canonicalPath());

            if (nodes.find(cPath) == nodes.end()) {
                int s = nodes.size();

                nodes[cPath] = s;
            }

            edges.push_back(std::make_pair(nodes[path], nodes[cPath]));
        }
        ++di;
    }
}
Example #26
0
int TwoSum::find_range(int lower, int upper) {
    int count = 0;
    numbers_to_check.resize(upper-lower);
    for (int i=lower; i<= upper; i++ ) {
	numbers_to_check.push_back(i);
    };
    for( auto it = numbers.begin(); it != numbers.end(); ++it ) {
	if( find_sum(it->first) ) { 
	    ++count; 
	};
    };	
    return count;
};
void Task::drawKeypoints(const base::samples::frame::Frame &frame2,
                const std::vector<cv::KeyPoint> &keypoints1,
                const std::vector<cv::KeyPoint> &keypoints2,
                const std::vector<cv::DMatch> &matches,
                const boost::unordered_map<boost::uuids::uuid, StereoFeature> &hash)

{
    /** Convert Images to opencv **/
    cv::Mat img2 = frameHelperLeft.convertToCvMat(frame2);

    ::cv::Mat img_out(img2);
    cv::drawKeypoints (img2, keypoints1, img_out, cv::Scalar(0, 255, 0));//green previous
    for (std::vector<cv::DMatch>::const_iterator it= matches.begin(); it!= matches.end(); ++it)
    {
        cv::Point point1 = keypoints1[it->queryIdx].pt;
        cv::Point point2 = keypoints2[it->trainIdx].pt;

        //cv::circle(img_out, point1, 3, cv::Scalar(0, 255, 0), 1);// green previous
        cv::circle(img_out, point2, 3, cv::Scalar(255, 0, 0), 1);// blue current
        cv::line (img_out, point1, point2, cv::Scalar(0, 0, 255)); // red line

    }

    if (_draw_hash_uuid_features.value())
    {
        /** Draw hash features **/
        for (boost::unordered_map<boost::uuids::uuid, StereoFeature>::const_iterator
                        it = hash.begin(); it != hash.end(); ++it)
        {
            /** Only current features but with the hash id and the image frame index in the label **/
            if (it->second.img_idx == this->fcurrent_left.img_idx)
            {
                float red = 255.0 - (255.0/(this->frame_window_hash_size)*(this->ffinal_left.img_idx-it->second.img_idx));
                cv::circle(img_out, it->second.keypoint_left.pt, 5, cv::Scalar(0, 0, red), 2);
                std::vector<std::string> uuid_tokens = this->split(boost::lexical_cast<std::string>(it->first), '-');
                cv::putText(img_out, uuid_tokens[uuid_tokens.size()-1]+"["+boost::lexical_cast<std::string>(it->second.img_idx)+"]",
                        it->second.keypoint_left.pt, cv::FONT_HERSHEY_COMPLEX_SMALL, 1.0, cv::Scalar(0,0,0), 2.5);
            }
        }
    }

    ::base::samples::frame::Frame *frame_ptr = this->inter_frame_out.write_access();
    frameHelperLeft.copyMatToFrame(img_out, *frame_ptr);

    frame_ptr->time = this->frame_pair.time;
    this->inter_frame_out.reset(frame_ptr);
    _inter_frame_samples_out.write(this->inter_frame_out);

    return;
}
void save(Archive & ar, const boost::unordered_map<T,U> & t, unsigned int version)
{
    // write the size
    // TODO: should we handle bucket size as well?
    typedef typename boost::unordered_map<T, U>::size_type size_type;
    typedef typename boost::unordered_map<T,U>::const_iterator const_iterator;
    size_type size = t.size();
    ar & BOOST_SERIALIZATION_NVP(size);
    unsigned int count = 0;
    for (const_iterator it = t.begin(); it != t.end(); it++) {
        ar & boost::serialization::make_nvp("pair" + count, *it);
        count++;
    }
}
Example #29
0
RealVector CARTTrainer::hist(boost::unordered_map<std::size_t, std::size_t> countMatrix){

	//create a normed histogram
	std::size_t totalElements = 0;
	RealVector normedHistogram(m_maxLabel+1);
	normedHistogram.clear();
	boost::unordered_map<std::size_t, std::size_t>::iterator it;
	for ( it=countMatrix.begin() ; it != countMatrix.end(); it++ ){
		normedHistogram(it->first) = it->second;
		totalElements += it->second;
	}
	normedHistogram /= totalElements;
	return normedHistogram;
}
Example #30
0
static std::pair<double, double>
score(const boost::unordered_map<int, double> &real,
      const boost::unordered_map<int, double> &fake,
      double threshold = 0.0)
{
  double res = 0.0;
  int cnt = 0;
  double e = std::numeric_limits<double>::epsilon();
  for (auto i = fake.begin(); i != fake.end(); ++i)
    if (i->second >= threshold &&
        real.find(i->first) != real.end()) {
      ++cnt;

      double p = real.at(i->first);
      double q = fake.at(i->first);

      if (p <= e)
        res += (1-p) * log((1-p)/(1-q));
      else if (1-p <= e || 1-q <= e)
        res += p * log(p/q);
      else res += p * log(p/q) + (1-p) * log((1-p)/(1-q));
    }
  return {res, cnt ? res / cnt : 0.0};
}