Example #1
0
bool ltr_int_broadcast_pose(linuxtrack_full_pose_t &pose)
{
    pthread_mutex_lock(&send_mx);
    std::multimap<std::string, int>::iterator i;
    int res;
    bool checkSlaves = false;
    //Send updated pose to all clients
    //printf("Master: %g  %g  %g\n", pose.pose.raw_pitch, pose.pose.raw_yaw, pose.pose.raw_roll);
    for(i = slaves.begin(); i != slaves.end();) {
        res = ltr_int_send_data(i->second, &pose);
        if(res == -EPIPE) {
            ltr_int_log_message("Slave @socket %d left!\n", i->second);
            close(i->second);
            i->second = -1;
            slaves.erase(i++);
            checkSlaves = true;
        } else {
            ++i;
        }
    }
    if(checkSlaves && (slaves.size() == 0)) {
        no_slaves = true;
    }
    pthread_mutex_unlock(&send_mx);
    return true;
}
Example #2
0
void AMQPAbstractPublishNotifier::Shutdown()
{
    LogPrint("amqp", "amqp: Shutdown notifier %s at %s\n", GetType(), GetAddress());

    int count = mapPublishNotifiers.count(address);

    // remove this notifier from the list of publishers using this address
    typedef std::multimap<std::string, AMQPAbstractPublishNotifier*>::iterator iterator;
    std::pair<iterator, iterator> iterpair = mapPublishNotifiers.equal_range(address);

    for (iterator it = iterpair.first; it != iterpair.second; ++it) {
        if (it->second == this) {
            mapPublishNotifiers.erase(it);
            break;
        }
    }

    // terminate the connection if this is the last publisher using this address
    if (count == 1) {
        handler_->terminate();
        if (thread_.get() != nullptr) {
            if (thread_->joinable()) {
                thread_->join();
            }
        }
    }
}
Example #3
0
 void flush_immediate_sync() {
   auto seq_no = processor_.max_finished_seq_no();
   for (auto it = immediate_sync_promises_.begin(), end = immediate_sync_promises_.end();
        it != end && it->first <= seq_no; it = immediate_sync_promises_.erase(it)) {
     do_immediate_sync(std::move(it->second));
   }
 }
    void updateEvent(int id, int idx, float val, int activate_cmd)
    {
        idmap_t id_iter = idmap.find(id);
        if (id_iter != idmap.end())
        {
            //this is a new id
            iter_t e_iter = id_iter->second;
            Event * e = e_iter->second;
            int onset = e->onset;
            e->update(idx, val);
            e->activate_cmd(activate_cmd);
            if (onset != e->onset)
            {
                ev.erase(e_iter);

                e_iter = ev.insert(pair_t(e->onset, e));

                //TODO: optimize by thinking about whether to do ev_pos = e_iter
                ev_pos = ev.upper_bound( tick_prev );
                idmap[id] = e_iter;
            }
        }
        else
        {
            g_log->printf(1, "%s unknown note %i\n", __FUNCTION__, id);
        }
    }
Example #5
0
  void query_recommender::merge_recommended_queries(std::multimap<double,std::string,std::less<double> > &related_queries,
      hash_map<const char*,double,hash<const char*>,eqstr> &update)
  {
    hash_map<const char*,double,hash<const char*>,eqstr>::iterator hit;
    std::multimap<double,std::string,std::less<double> >::iterator mit
    = related_queries.begin();
    while(mit!=related_queries.end())
      {
        std::string rquery = (*mit).second;
        if ((hit = update.find(rquery.c_str()))!=update.end())
          {
            (*hit).second = std::min((*mit).first,(*hit).second);
            std::multimap<double,std::string,std::less<double> >::iterator mit2 = mit;
            ++mit;
            related_queries.erase(mit2);
          }
        else ++mit;
      }
    hit = update.begin();
    hash_map<const char*,double,hash<const char*>,eqstr>::iterator chit;
    while(hit!=update.end())
      {
        related_queries.insert(std::pair<double,std::string>((*hit).second,std::string((*hit).first)));
        chit = hit;
        ++hit;
        free_const((*chit).first);
      }

  }
Example #6
0
bool World::DeletePersistentData(const PersistentDataItem &item)
{
    int id = item.raw_id();
    if (id > -100)
        return false;
    if (!BuildPersistentCache())
        return false;

    stl::vector<df::historical_figure*> &hfvec = df::historical_figure::get_vector();

    auto eqrange = persistent_index.equal_range(item.key());

    for (auto it2 = eqrange.first; it2 != eqrange.second; )
    {
        auto it = it2; ++it2;

        if (it->second != -id)
            continue;

        persistent_index.erase(it);

        int idx = binsearch_index(hfvec, id);

        if (idx >= 0) {
            delete hfvec[idx];
            hfvec.erase(hfvec.begin()+idx);
        }

        return true;
    }

    return false;
}
Example #7
0
    virtual void Run()
    {
        now = v8::base::OS::TimeCurrentMillis();

        while (1)
        {
            AsyncEvent *p;
            std::multimap<double, AsyncEvent *>::iterator e;

            wait();

            now = v8::base::OS::TimeCurrentMillis();

            while (1)
            {
                p = s_acSleep.get();
                if (p == NULL)
                    break;

                s_tms.insert(std::make_pair(now + p->result(), p));
            }

            while (1)
            {
                e = s_tms.begin();
                if (e == s_tms.end())
                    break;
                if (e->first > now)
                    break;

                e->second->apost(0);
                s_tms.erase(e);
            }
        }
    }
Example #8
0
    static void PASCAL Timer(unsigned int uTimerID, unsigned int uMsg,
                             DWORD_PTR dwUser, DWORD_PTR dw1, DWORD_PTR dw2)
    {
        AsyncEvent *p;
        double tm;
        std::multimap<double, AsyncEvent *>::iterator e;

        while (1)
        {
            p = s_acSleep.get();
            if (p == NULL)
                break;

            tm = s_time + s_now + p->result();
            s_tms.insert(std::make_pair(tm, p));
        }

        atom_xchg(&s_now, (int)(v8::internal::OS::TimeCurrentMillis() - s_time));

        while (1)
        {
            e = s_tms.begin();
            if (e == s_tms.end())
                break;
            if (e->first > s_time + s_now)
                break;

            e->second->apost(0);
            s_tms.erase(e);
        }
    }
Example #9
0
void *MemoryPool::pop(size_t s, int loc) {
    void *addr = nullptr;

    if ((s > MIN_BLOCK_SIZE) && (s < MAX_BLOCK_SIZE)) {
        locker_.lock();

        // find MemoryPool block which is not smaller than demand size
        auto pt = pool_.lower_bound(s);

        if (pt != pool_.end()) {
            size_t ts = 0;
            std::tie(ts, addr) = *pt;
            if (ts < s * 2) {
                s = ts;
                pool_.erase(pt);
                pool_depth_ -= s;
            } else {
                addr = nullptr;
            }
        }
        locker_.unlock();
    }

    if (addr == nullptr) {
        try {
#ifdef __CUDA__
            SP_DEVICE_CALL(cudaMallocManaged(&addr, s));
#else
            addr = malloc(s);
#endif
        } catch (std::bad_alloc const &error) { THROW_EXCEPTION_BAD_ALLOC(s); }
    }
    return addr;
}
void CZMQAbstractPublishNotifier::Shutdown()
{
    assert(psocket);

    int count = mapPublishNotifiers.count(address);

    // remove this notifier from the list of publishers using this address
    typedef std::multimap<std::string, CZMQAbstractPublishNotifier*>::iterator iterator;
    std::pair<iterator, iterator> iterpair = mapPublishNotifiers.equal_range(address);

    for (iterator it = iterpair.first; it != iterpair.second; ++it)
    {
        if (it->second==this)
        {
            mapPublishNotifiers.erase(it);
            break;
        }
    }

    if (count == 1)
    {
        LogPrint("zmq", "Close socket at address %s\n", address);
        int linger = 0;
        zmq_setsockopt(psocket, ZMQ_LINGER, &linger, sizeof(linger));
        zmq_close(psocket);
    }

    psocket = 0;
}
/**
 * @param name A string containing the algorithm name
 * @param version The version to remove. -1 indicates all instances
 * @param typedLoaders A map of names to version numbers
 **/
void FileLoaderRegistryImpl::removeAlgorithm(
    const std::string &name, const int version,
    std::multimap<std::string, int> &typedLoaders) {
  if (version == -1) // remove all
  {
    typedLoaders.erase(name);
  } else // find the right version
  {
    auto range = typedLoaders.equal_range(name);
    for (auto ritr = range.first; ritr != range.second; ++ritr) {
      if (ritr->second == version) {
        typedLoaders.erase(ritr);
        break;
      }
    }
  }
}
Example #12
0
void GameDB::deleteGame(std::multimap<Reference<Team>, Reference<Game>>& map, Reference<Team> team, Reference<Game> game) {
  auto range = map.equal_range(team);
  for (auto i = range.first; i != range.second; ++i) {
    if (i->second == game) {
      map.erase(i);
      return;
    }
  }
}
 	bool removeExampleHandler (T eventName, Handle handler) {
		auto ret = map.equal_range(eventName);
		for(auto it = ret.first;it != ret.second;++it) {
			if(it->second == handler) {
				it = map.erase(it);
				return true;
			}
		}
		return false;
	}
    // msgpack::type::MAP is converted to std::multimap, not std::map.
    void operator()(std::multimap<msgpack::type::variant_ref, msgpack::type::variant_ref>& v) const {
        std::cout << "match map" << std::endl;
        std::multimap<msgpack::type::variant_ref, msgpack::type::variant_ref>::iterator it = v.begin();
        std::multimap<msgpack::type::variant_ref, msgpack::type::variant_ref>::iterator end = v.end();
        while(it != end) {
            boost::string_ref const& key = it->first.as_boost_string_ref();
            if (key == "name") {
                boost::string_ref const& value = it->second.as_boost_string_ref();
                if (value == "Takatoshi Kondo") {
                    // You can add values to msgpack::type::variant_ref.
                    v.insert(
                        std::multimap<msgpack::type::variant_ref, msgpack::type::variant_ref>::value_type(
                            "role",
                            "msgpack-c committer"
                        )
                    );
                }
                ++it;
            }
            else if (key == "age") {
                // You can remove key-value pair from msgpack::type::variant_ref

#if defined(MSGPACK_USE_CPP03)
                v.erase(it++);
#else  // defined(MSGPACK_USE_CPP03)
#  if MSGPACK_LIB_STD_CXX
                it = v.erase(std::multimap<msgpack::type::variant_ref, msgpack::type::variant_ref>::const_iterator(it));
#  else  // MSGPACK_LIB_STD_CXX
                it = v.erase(it);
#  endif // MSGPACK_LIB_STD_CXX
#endif // defined(MSGPACK_USE_CPP03)
            }
            else if (key == "address") {
                // When you want to append string
                // "Tokyo" -> "Tokyo, JAPAN"
                // Use msgpack::type::variant instead of msgpack::type::variant_ref
                // or do as follows:
                boost::string_ref const& value = it->second.as_boost_string_ref();
                it->second = std::string(&value.front(), value.size()) + ", JAPAN";
                ++it;
            }
        }
    }
Example #15
0
 static void sort_by_location(std::multimap<std::string, Species> location_map,
         std::vector<Species>& species, const std::string location="")
 {
     std::multimap<std::string, Species>::iterator itr;
     while ((itr = location_map.find(location)) != location_map.end())
     {
         const Species sp((*itr).second);
         species.push_back(sp);
         sort_by_location(location_map, species, sp.serial());
         location_map.erase(itr);
     }
 }
Example #16
0
void intersect(int a, int b, const Point & I, std::vector<Segment> & segments, std::multimap<Point, int> & sweep, std::multimap<std::pair<double,int>, int,event_less> & events, bool print)
{
	//remove event of ending of old segment
	{
		int rem_end_events[2];
		rem_end_events[0] = a;
		rem_end_events[1] = b;
		for (int k = 0; k < 2; ++k)
		{
			std::pair< std::multimap<std::pair<double,int>, int,event_less>::iterator, std::multimap<std::pair<double,int>,int,event_less>::iterator > del = events.equal_range(std::make_pair(segments[rem_end_events[k]].end.x,SEG_END)); //get all events at position of the end
			bool flag = false;
			for (std::multimap<std::pair<double,int>, int,event_less>::iterator it = del.first; it != del.second; ++it) //search over all events
			{
				if (it->first.second == SEG_END && it->second == rem_end_events[k]) //event is end of segment and segment matches current
				{
					events.erase(it); //remove that segment
					flag = true;
					break; //do not expect any more
				}
			}
			if (!flag) std::cout << "Cannot find proper ending event for segment" << std::endl;
		}
	}
	//add new segment with intersection point up to end
	segments.push_back(Segment(I, segments[a].end));
	//add event of starting of new segment
	events.insert(std::make_pair(std::make_pair(I.x,SEG_START), (int)segments.size() - 1));
	//add event of ending of new segment
	events.insert(std::make_pair(std::make_pair(segments.back().end.x,SEG_END),(int)segments.size() - 1));
	//change ending point for current segment
	segments[a].end = I;
	//add event of ending of old segment
	events.insert(std::make_pair(std::make_pair(I.x,SEG_END), a));
	//add new segment with intersection point up to end
	segments.push_back(Segment(I, segments[b].end));
	//add event of starting of new segment
	events.insert(std::make_pair(std::make_pair(I.x,SEG_START), (int)segments.size() - 1));
	//add event of ending of new segment
	events.insert(std::make_pair(std::make_pair(segments.back().end.x,SEG_END), (int)segments.size() - 1));
	//change ending point for current segment
	segments[b].end = I;
	//add event of ending of old segment
	events.insert(std::make_pair(std::make_pair(I.x,SEG_END), b));
	if (print)
	{
		std::cout << "Number of events: " << events.size() << std::endl;
		for (std::multimap<std::pair<double, int>, int,event_less>::iterator it = events.begin(); it != events.end(); ++it)
			std::cout << "x: " << it->first.first << " type " << (it->first.second == SEG_START ? "start" : "end") << " segment " << it->second << std::endl;
	}
}
Example #17
0
 static void save_molecular_type_recursively(const Species& location,
         std::multimap<Species, const MolecularTypeBase*>& location_map,
         Tspace_& space, H5::Group* root)
 {
     std::multimap<Species, const MolecularTypeBase*>::iterator itr;
     while ((itr = location_map.find(location)) != location_map.end())
     {
         const MolecularTypeBase* mtb((*itr).second);
         const Species species(mtb->species());
         save_molecular_type(mtb, space.list_voxels_exact(species), root);
         save_molecular_type_recursively(species, location_map, space, root);
         location_map.erase(itr);
     }
 }
	ExampleEventDispatcherTpl() {
		ExampleEventEmitter<T, Rest...>::onExample([&](T eventName, Rest... fargs) {
 			auto ret = map.equal_range(eventName);
 			for(auto it = ret.first;it != ret.second;) {
 				(it->second)(fargs...);
				if(eraseLast) {
					it = map.erase(it);
					eraseLast = false;
				}
				else {
					++it;
				}
 			}
		});
	}
Example #19
0
void splitDrumTracks(std::multimap<int, MTrack> &tracks)
      {
      for (auto it = tracks.begin(); it != tracks.end(); ++it) {
            if (!it->second.mtrack->drumTrack())
                  continue;
            const auto &opers = preferences.midiImportOperations.data()->trackOpers;
            if (!opers.doStaffSplit.value(it->second.indexOfOperation))
                  continue;
            const auto newTracks = splitDrumTrack(it->second);
            const int trackIndex = it->first;
            it = tracks.erase(it);
            for (auto i = newTracks.rbegin(); i != newTracks.rend(); ++i)
                  it = tracks.insert({trackIndex, i->second});
            }
      }
Example #20
0
	void EventManager::runTimedEvents(TimePoint now) {
		//run all the events ready to run
		for (auto&& event : mEvents) {
			if (event->isReady(now)) {
				event->run();
			}
		}

		if (mSimpleTasks.size()) {
			auto top = mSimpleTasks.begin();
			if (now >= top->first) {
				top->second();
				mSimpleTasks.erase(top);
			}
		}
	}
    void delEvent(int id)
    {
        idmap_t id_iter = idmap.find(id);
        if (id_iter != idmap.end())
        {
            iter_t e_iter = id_iter->second;//idmap[id];
            if (e_iter == ev_pos) ++ev_pos;

            delete e_iter->second;
            ev.erase(e_iter);
            idmap.erase(id_iter);
        }
        else
        {
            g_log->printf( 1, "%s unknown note %i\n", __FUNCTION__, id);
        }
    }
Example #22
0
static void run_timers(color_ostream &out, lua_State *L,
                       std::multimap<int,int> &timers, int table, int bound)
{
    while (!timers.empty() && timers.begin()->first <= bound)
    {
        int id = timers.begin()->second;
        timers.erase(timers.begin());

        lua_rawgeti(L, table, id);

        if (lua_isnil(L, -1))
            lua_pop(L, 1);
        else
        {
            lua_pushnil(L);
            lua_rawseti(L, table, id);

            Lua::SafeCall(out, L, 0, 0);
        }
    }
}
void process_ongoing_requests(std::multimap<addr_type, int> & ongoing_requests,
                                                int fake_stamp,
                                                std::vector<Tree> & Bs,
                                                std::vector<std::map<addr_type, int>> & Ps,
                                                std::vector<int> & set_counters,
                                                ModelConfig & model_config) {
    std::multimap<addr_type, int>::iterator it;

    it = ongoing_requests.begin();
    while (it != ongoing_requests.end()) {
        if (it->second <= fake_stamp) {
            //  If the model is configed not allocate_on_miss, need to update stack tree here
            if (! model_config.allocate_on_miss) {
                update_stack_tree(it->first, Bs, Ps, set_counters, model_config);
            }

            it = ongoing_requests.erase(it);
        }
        else {
            it ++;
        }
    }
}
    // Only call on io_service
    void ResetTimer()
    {
        const auto now = std::chrono::steady_clock::now();

        UniqueLock unique_lock(mutex_);

        while (running_ && !data_.empty())
        {
            auto map_front_it = data_.begin();
            const auto timeout = map_front_it->first;
            if ( timeout <= now )
            {
                // Effeciently extract the value so we can move it.
                auto event = std::move( map_front_it->second );
                data_.erase(map_front_it);

                // Unlock incase callback calls a TimedActions method.
                unique_lock.unlock();
                event_processor_(std::move(event), std::error_code());
                unique_lock.lock();
            }
            else
            {
                timeout_timer_.expires_at(timeout);

                timeout_timer_.async_wait(
                    boost::bind(
                        &TimedEvents<Event>::HandleTimeout,
                        this->shared_from_this(),
                        boost::asio::placeholders::error
                    )
                );
                break;
            }
        }
    }
Example #25
0
File: main.cpp Project: CCJY/coliru
 void disconnect(Class& obj, void (Class::*func)(Params...)) {
     m_functions.erase(Key { &obj, getHash(func) });
 }
int main(int argc, char **argv)
{
	long int i, N;
	bool already_invaded;
	short int L, j, k, l;
	double pc = 0.49;
	L = atoi(argv[1]);

	N = L*L;

	for(j=-L/2; j < L/2; j++)
	{
		for(k=-L/2+1; k < L/2+1; k++)
		{
			Site loc = std::make_pair(j, k);
			unitCell_Square cell;
			lattice.insert(std::make_pair(loc, cell));
		}
	}

	Site start = std::make_pair(0,0);
	lattice[start].is_invaded = true;
	add_new_Bonds(start);
	try
	{
		for (i=0; i<N;)
		{
    		std::multimap<double, Bond>::iterator weakest;
    		weakest = accessible_Bonds.begin();
    		already_invaded = invade_bond(weakest->second);
    		if(!already_invaded)
    		{
    			i++;
    		}
    		accessible_Bonds.erase(weakest);
		}
		std::multimap<double, Bond>::iterator weakest = accessible_Bonds.begin();
		cluster.push_back(weakest->second);
	}
	catch (std::exception& e) {}

	std::ofstream toFile1("fractures.txt", std::ios::trunc);
	std::ofstream toFile2("trapped.txt", std::ios::trunc);
	toFile1 << cluster.size() << "\n";
	toFile2 << trappedBonds.size() << "\n";
	toFile1 << "Invasion for: temp" << "\n";
	toFile2 << "Trapping for: temp" << "\n";
	toFile1.precision(17);
	toFile2.precision(17);

	Bond current_Line;
	while (!cluster.empty())
	{
		current_Line = cluster.front();
		cluster.pop_front();
		toFile1 << get_strength(current_Line) << "\t";
		toFile1 <<  current_Line.first.first << "\t";
		toFile1 <<  current_Line.first.second << "\t";
		Site other_end = get_end(current_Line);
		toFile1 <<  other_end.first << "\t";
		toFile1 <<  other_end.second << "\n";
	}


	while (!trappedBonds.empty())
	{
		current_Line = trappedBonds.front();
		trappedBonds.pop_front();
		toFile2 << get_strength(current_Line) << "\t";
		toFile2 <<  current_Line.first.first << "\t";
		toFile2 <<  current_Line.first.second << "\t";
		Site other_end = get_end(current_Line);
		toFile2 <<  other_end.first << "\t";
		toFile2 <<  other_end.second << "\n";
	}

	toFile1.close();
	toFile2.close();


	accessible_Bonds.clear();
	for(j=-L/2; j < L/2; j++)
	{
		for(k=-L/2+1; k < L/2+1; k++)
		{
			for(l=0; l<2; l++)
			{
				Site loc = std::make_pair(j, k);
				Bond bond = std::make_pair(loc, l);
				accessible_Bonds.insert(std::make_pair(lattice[loc].bonds[l], bond));
			}
		}
	}

	std::multimap<double, Bond>::iterator weakest = accessible_Bonds.begin();
	while(weakest->first < pc)
	{	
		lattice[weakest->second.first].is_open[weakest->second.second] = grow_clusters(weakest->second);
		accessible_Bonds.erase(weakest);
		weakest = accessible_Bonds.begin();
	}


	unitCell_Square * current_cell;
	for(j=-L/2; j < L/2; j++)
	{
		for(k=-L/2+1; k < L/2+1; k++)
		{
			current_cell = &lattice[std::make_pair(j,k)];
			current_cell->clusterN = find(current_cell->clusterN);
		}
	}
	long int bond_count = 0;
	for(lattice_iterator iter = lattice.begin(); iter != lattice.end(); iter++)
	{
		current_cell = &iter->second;
		if(current_cell->is_open[0])
		{
			bond_count++;
		}
		if(current_cell->is_open[1])
		{
			bond_count++;
		}
	}


	std::ofstream toFile3("clusters.txt", std::ios::trunc);
	toFile3 << bond_count << "\n";

	unitCell_Square Line;
	Site begin;
	Site other_end;
	std::map<unsigned int, unsigned int> cluster_sizes;
	while (!lattice.empty())
	{
		begin = lattice.begin()->first;
		Line = lattice.begin()->second;
		lattice.erase(begin);
		if(Line.is_open[0])
		{
			if(cluster_sizes.count(Line.clusterN) > 0)
			{
				cluster_sizes[Line.clusterN]++;
			}
			else
			{
				cluster_sizes.insert(std::make_pair(Line.clusterN,1));
			}
			toFile3 << Line.clusterN << "\t";
			toFile3 << begin.first << "\t";
			toFile3 << begin.second << "\t";
			other_end = get_end(std::make_pair(begin, 0));
			toFile3 <<  other_end.first << "\t";
			toFile3 <<  other_end.second << "\n";
		}
		if(Line.is_open[1])
		{
			if(cluster_sizes.count(Line.clusterN) > 0)
			{
				cluster_sizes[Line.clusterN]++;
			}
			else
			{
				cluster_sizes.insert(std::make_pair(Line.clusterN,1));
			}
			toFile3 << Line.clusterN << "\t";
			toFile3 << begin.first << "\t";
			toFile3 << begin.second << "\t";
			other_end = get_end(std::make_pair(begin, 1));
			toFile3 <<  other_end.first << "\t";
			toFile3 <<  other_end.second << "\n";
		}
	}

	toFile3.close();
	unsigned int largest_cluster = 0;
	unsigned int largest_cluster_size = 0;
	std::map<unsigned int, unsigned int>::iterator iter;
	for(iter = cluster_sizes.begin(); iter != cluster_sizes.end(); iter++)
	{
		if(iter->second > largest_cluster_size)
		{
			largest_cluster = iter->first;
			largest_cluster_size = iter->second;
		}
	}

	std::map<unsigned int, unsigned int> cluster_count;
	unsigned int size, begin2;
	while (!cluster_sizes.empty())
	{
		begin2 = cluster_sizes.begin()->first;
		size = cluster_sizes.begin()->second;
		cluster_sizes.erase(begin2);
		if(cluster_count.count(size) > 0)
			{
				cluster_count[size]++;
			}
			else
			{
				cluster_count.insert(std::make_pair(size, 1));
			}
	}

	std::ofstream toFile4("cluster_distribution.txt", std::ios::trunc);
	toFile4 << cluster_count.size() << "\t" << largest_cluster << "\t";
	toFile4 << cluster_map[largest_cluster].second.first << "\t" << cluster_map[largest_cluster].second.second << "\n";

	unsigned int count;
	while (!cluster_count.empty())
	{
		size = cluster_count.begin()->first;
		count = cluster_count.begin()->second;
		cluster_count.erase(size);
		toFile4 << size << "\t" << count << "\n";
	}

	toFile4.close();

    return 0;
}
	void removeAllExampleHandlers (T eventName) {
		auto ret = map.equal_range(eventName);
		for(auto it = ret.first;it != ret.second;) {		
			it = map.erase(it);
		}
	}
Example #28
0
void NodeHelper::remove(Contactable& contactable) {
    NodeItem item = name_cache[&contactable];
    name_cache.erase(&contactable);
    by_part_name.erase(item.nc.getNestedName());
    by_category.erase(item.nc.getCategory());
}
bool NodeListT::FollowToNode(const std::vector<StationID>::const_iterator &itr,
	std::multimap<UnitID, NodeListT::SuperInfoT> &supersets,
	const std::vector<StationID>::const_iterator &itr_1,
	bool neg) const
{
	const auto node_itr = nodes.find(*itr);
	if(node_itr == nodes.end())
		return false;
	const NodeInfoT* info = &node_itr->second;

	auto next = supersets.begin();
	for(auto sitr = supersets.begin(); sitr != supersets.end(); sitr = next)
	{
		++(next = sitr);

		UnitID cur_line = sitr->first;
		std::size_t& last_station_no = sitr->second.last_station_no;
		std::size_t new_last_station_no = std::numeric_limits<std::size_t>::max();

		const auto in_nodes = info->equal_range(cur_line);
		std::size_t tmp = lengths.at(cur_line);
		for(auto in_node = in_nodes.first;
			in_node != in_nodes.second; ++in_node)
		{
			tmp = value_of(supersets, cur_line, in_node->second, neg);
			if(tmp == 0)
				tmp = lengths.at(cur_line);
			if(tmp >= last_station_no && // is it a future node?
				tmp < new_last_station_no /* better than previous result? */ )
			{
				new_last_station_no = tmp;
			}
		}

		if(new_last_station_no == std::numeric_limits<std::size_t>::max())
			supersets.erase(sitr);
		else
		{
			// was the last node visited twice before we got here?
			// if so, this train can still be a short train
			const auto& last_in_nodes =
					nodes.at(*itr_1).equal_range(cur_line);

			bool no_express = true;
			if(last_station_no < new_last_station_no - 1) // some nodes between...
			{
				no_express = false;
				for(auto last_in_node = last_in_nodes.first;
					(!no_express) && last_in_node != last_in_nodes.second;
					++last_in_node)
				{
					std::size_t value_found_in_last = value_of(supersets, cur_line, last_in_node->second, neg);
					if(last_station_no < value_found_in_last
							&& value_found_in_last == (new_last_station_no-1))
					{
						// ok, it was just a slope we've left out
						no_express = true;
					}
				}
			}

			sitr->second.can_be_short_train =
					sitr->second.can_be_short_train && no_express;

			// advance
			last_station_no = new_last_station_no;
		}
	}
	return true;
}
Example #30
0
bool IndexServerConn::HandleMsg(enum IndexServerMsg msg_id)
{
  switch(msg_id)
    {
    case TS_MSG_VERSION:
      return HandShake();
      break;

    case TS_MSG_WIS_VERSION:
      {
        int version;
        if (BytesReceived() < sizeof(uint32_t)) // The message is not completely received
          return true;
        if (!ReceiveInt(version)) // Receive the version number of the server index
          return false;
        if (version > VERSION)
          {
            DPRINT(INFO,"The server at %i have a version %i, while we are only running a %i version",
                   GetIP(), version, VERSION);
            exit(EXIT_FAILURE);
          }
        else if(version < VERSION)
          {
            DPRINT(INFO,"This server is running an old version (v%i) !", version);
            return false;
          }
        DPRINT(INFO,"We are running the same version..");
      }
      break;
    case TS_MSG_JOIN_LEAVE:
      {
        int ip;
        int port;
        std::string version;

        if (!ReceiveStr(version))
            return false;

        if (BytesReceived() < 2*sizeof(uint32_t)) // The message is not completely received
          return true;
        if (!ReceiveInt(ip)) // Receive the IP of the warmux server
          return false;
        if (!ReceiveInt(port)) // Receive the port of the warmux server
          return false;

        if (port < 0) // means it disconnected
          {
	    for (std::multimap<std::string, FakeClient>::iterator serv = fake_clients.lower_bound(version);
		 serv != fake_clients.upper_bound(version);
		 serv++) {

	      if( serv->second.ip == ip
		  &&  serv->second.port == -port )
		{
		  fake_clients.erase(serv);
		  DPRINT(MSG, "A fake server disconnected");
		  break;
		}
	    }
          }
        else
          {
            HostOptions options;

	    std::string game_name;
	    if (!ReceiveStr(game_name))
	      return false;

	    int passwd;
	    if (!ReceiveInt(passwd))
	      return false;
	    options.Set(game_name, passwd);

            fake_clients.insert(std::make_pair(version, FakeClient(ip, port, options)));
            stats.NewFakeServer(version);
          }
      }
      break;
    default:
      DPRINT(INFO,"Bad message!");
      return false;
    }
  msg_id = TS_NO_MSG;
  return true;
}