int main(int argc, char *argv[]) { QCoreApplication a(argc, argv); if (qApp->arguments().indexOf(QRegExp("-help"))!=-1 || qApp->arguments().length()==1) { qDebug() << "bundler (-nodes <nodes> -cons <connections> / -fib <.fib-file>) [-c_thr <compatibility threshold>] [-start_i <iterations in 1st cycle>] [-numcycles <number of cycles>]"; return 1; } qDebug() << "nodesname: " + arg("nodes"); qDebug() << "consname: " + arg("cons"); Connections* cons; if (arg("cons")!="") { cons = new Connections(arg("nodes"),arg("cons")); } else if (arg("fib")!="") { cons = new Connections(arg("fib")); } else { qDebug() << "no dataset given"; return 0; } if (arg("c_thr")!="") cons->c_thr = arg("c_thr").toDouble(); if (arg("start_i")!="") cons->start_i = arg("start_i").toInt(); if (arg("numcycles")!="") cons->numcycles = arg("numcycles").toInt(); qDebug() << cons->name(); cons->fullAttract(); if (arg("out")!="") { cons->writeBinaryVTK(arg("out")); } else { cons->writeBinaryVTK(); } return 1; }
void P2PConnectionsWindow::refreshConnections() { Connections connections; // Effettua una copia per evitare una lock durante il check getConnections(connections); wxWindowUpdateLocker windowLocker(m_connectionsCtrl); uint32 connectionsCount = static_cast<uint32>(connections.size()); uint32 connectionsLimit = getConnectionsLimit(); bool pendingRefresh = false; for(Connections::iterator i = connections.begin(); i != connections.end(); ++i) { if(i->second->getRemoved()) { if(i->second->isElapsed() || (connectionsCount > connectionsLimit)) { doRemoveConnection(i->first); connectionsCount--; } else { markConnectionRemoved(i->first); } } else { refreshConnectionItem(i->first); } } }
bool Connection::send( const Connections& connections, Packet& packet, const void* data, const uint64_t dataSize, const bool isLocked ) { if( connections.empty( )) return true; if( dataSize <= 8 ) // fits in existing packet { if( dataSize != 0 ) memcpy( (char*)(&packet) + packet.size-8, data, dataSize ); return send( connections, packet, isLocked ); } const uint64_t headerSize = packet.size - 8; const uint64_t size = headerSize + dataSize; if( size > EQ_ASSEMBLE_THRESHOLD ) { // OPT: lock the connection and use two send() to avoid big memcpy packet.size = size; bool success = true; for( Connections::const_iterator i= connections.begin(); i<connections.end(); ++i ) { ConnectionPtr connection = *i; if( !isLocked ) connection->lockSend(); if( !connection->send( &packet, headerSize, true ) || !connection->send( data, dataSize, true )) { success = false; } if( !isLocked ) connection->unlockSend(); } return success; } char* buffer = (char*)alloca( size ); memcpy( buffer, &packet, packet.size-8 ); memcpy( buffer + packet.size-8, data, dataSize ); ((Packet*)buffer)->size = size; bool success = true; for( Connections::const_iterator i = connections.begin(); i < connections.end(); ++i ) { ConnectionPtr connection = *i; if( !connection->send( buffer, size, isLocked )) success = false; } return success; }
/// Get connection by owner instance (0=ALL) StagedIODataManager::Connections StagedIODataManager::connections(const IInterface* owner) const { Connections conns; for(ConnectionMap::const_iterator i=m_connectionMap.begin(); i!=m_connectionMap.end();++i) { IDataConnection* c = (*i).second->connection; if ( 0 == owner || c->owner() == owner ) conns.push_back(c); } return conns; }
void Block(const std::string& signalnamespace){ //matching namespace? don't block global (non-namespaced) signals if(signalnamespace == this->signalnamespace && this->signalnamespace != ""){ //signalbroker.InvokeSignal<OutputStreamView::LogHandler>("/log/output", // "SignalSubsriber<" + childname + ">::Block("+this->signalnamespace+")"); Connections::iterator itr = connections.begin(); for(; itr!= connections.end(); itr++){ itr->second.block(); } } }
void remove(const std::string &connectionName, const std::string& buddyName) { auto cn = p_connections.find(connectionName); if(p_connections.end() != cn) { /*auto buddy = cn->second.find(buddyName); if(cn->second.end() != buddy) { cn->second.erase(buddy); }*/ cn->second.erase(buddyName); } }
Buddy* get(const std::string &connectionName, const std::string &buddyName) { auto cn = p_connections.find(connectionName); if(p_connections.end() != cn) { auto buddy = cn->second.find(buddyName); if(cn->second.end() != buddy) { return &(buddy->second); } } return NULL; }
void ConnectionSet::_createThread( const Connections& connections ) { Thread* thread = new Thread( this ); for ( ConnectionsCIter it = connections.begin(); it != connections.end(); ++it ) { ConnectionPtr connection = *it; thread->set.addConnection( connection ); } _impl->threads.push_back( thread ); thread->start(); }
void createBlockRow(size_t i, const Connections& conn, size_t ndof) { assert (ndof == 1); (void) ndof; assert (i == i_prev_ + 1); (void) i ; ISTLTypeDetails::ScalarBCRSMatrix::CreateIterator ci(mat_, i); for (typename Connections::const_iterator c = conn.begin(), e = conn.end(); c != e; ++c) { ci.insert(*c); } ++i_prev_; ++ci; }
bool Connection::send( const Connections& connections, const Packet& packet, const bool isLocked ) { if( connections.empty( )) return true; bool success = true; for( Connections::const_iterator i= connections.begin(); i<connections.end(); ++i ) { ConnectionPtr connection = *i; if( !connection->send( &packet, packet.size, isLocked )) success = false; } return success; }
void removeFromConnectionTable(int socketDescriptor){ /* Remove the user with the closed socket */ Connections::iterator it = conn.begin(); while(it!=conn.end()){ if(it->second == socketDescriptor){ #ifdef __INFO__ std::cout<<"\""<<it->first<<"\" went offline on socket "<<socketDescriptor<<"."<<std::endl; #endif conn.erase(it); break; } ++it; } }
static void adaptSegment( Connections& connections, Segment segment, const vector<CellIdx>& prevActiveCells, Permanence permanenceIncrement, Permanence permanenceDecrement) { const vector<Synapse>& synapses = connections.synapsesForSegment(segment); for (SynapseIdx i = 0; i < synapses.size();) { const SynapseData& synapseData = connections.dataForSynapse(synapses[i]); const bool isActive = std::binary_search(prevActiveCells.begin(), prevActiveCells.end(), synapseData.presynapticCell); Permanence permanence = synapseData.permanence; if (isActive) { permanence += permanenceIncrement; } else { permanence -= permanenceDecrement; } permanence = min(permanence, (Permanence)1.0); permanence = max(permanence, (Permanence)0.0); if (permanence < EPSILON) { connections.destroySynapse(synapses[i]); // Synapses vector is modified in-place, so don't update `i`. } else { connections.updateSynapsePermanence(synapses[i], permanence); i++; } } if (synapses.size() == 0) { connections.destroySegment(segment); } }
/* * Returns list of online nicknames as * ONLINE: <user1> : <user2> : ... */ std::string getOnlineList(std::string curUser){ std::string response = "ONLINE: "; Connections::iterator it = conn.begin(); while(it!=conn.end()){ if(it->first!=curUser){ bool online = isOnline(it->first); if(online){ response += it->first; response += ":"; } } ++it; } return response; }
static CellIdx getLeastUsedCell( Random& rng, UInt column, const Connections& connections, UInt cellsPerColumn) { const CellIdx start = column * cellsPerColumn; const CellIdx end = start + cellsPerColumn; UInt32 minNumSegments = UINT_MAX; UInt32 numTiedCells = 0; for (CellIdx cell = start; cell < end; cell++) { const UInt32 numSegments = connections.numSegments(cell); if (numSegments < minNumSegments) { minNumSegments = numSegments; numTiedCells = 1; } else if (numSegments == minNumSegments) { numTiedCells++; } } const UInt32 tieWinnerIndex = rng.getUInt32(numTiedCells); UInt32 tieIndex = 0; for (CellIdx cell = start; cell < end; cell++) { if (connections.numSegments(cell) == minNumSegments) { if (tieIndex == tieWinnerIndex) { return cell; } else { tieIndex++; } } } NTA_THROW << "getLeastUsedCell failed to find a cell"; }
boost::signals::connection AddConnection(const std::string& name, boost::signals::connection connection){ connections.insert(Connections::value_type(name, connection)); //block if signalbroker says so, but do not block global signals if(signalbroker.IsBlocked(signalnamespace) && signalnamespace != ""){ connection.block(); } return connection; }
void addToConnectionTable(std::string username, int socketDescriptor){ std::pair<Connections::iterator,bool> retVal = conn.insert(std::make_pair(username, socketDescriptor)); /* Update if key already exists to new socket Descriptor */ if(!retVal.second){ retVal.first->second = socketDescriptor; } #ifdef __INFO__ std::cout<<"New user \""<<username<<"\" on socket "<<socketDescriptor<<"."<<std::endl; #endif }
static void growSynapses( Connections& connections, Random& rng, Segment segment, UInt32 nDesiredNewSynapses, const vector<CellIdx>& prevWinnerCells, Permanence initialPermanence) { // It's possible to optimize this, swapping candidates to the end as // they're used. But this is awkward to mimic in other // implementations, especially because it requires iterating over // the existing synapses in a particular order. vector<CellIdx> candidates(prevWinnerCells.begin(), prevWinnerCells.end()); NTA_ASSERT(std::is_sorted(candidates.begin(), candidates.end())); // Remove cells that are already synapsed on by this segment for (Synapse synapse : connections.synapsesForSegment(segment)) { CellIdx presynapticCell = connections.dataForSynapse(synapse).presynapticCell; auto ineligible = std::lower_bound(candidates.begin(), candidates.end(), presynapticCell); if (ineligible != candidates.end() && *ineligible == presynapticCell) { candidates.erase(ineligible); } } const UInt32 nActual = std::min(nDesiredNewSynapses, (UInt32)candidates.size()); // Pick nActual cells randomly. for (UInt32 c = 0; c < nActual; c++) { size_t i = rng.getUInt32(candidates.size()); connections.createSynapse(segment, candidates[i], initialPermanence); candidates.erase(candidates.begin() + i); } }
bool Connection::send( const Connections& connections, Packet& packet, const void* const* items, const uint64_t* sizes, const size_t nItems ) { if( connections.empty( )) return true; packet.size -= 8; const uint64_t headerSize = packet.size; for( size_t i = 0; i < nItems; ++i ) { EQASSERT( sizes[i] > 0 ); packet.size += sizes[ i ] + sizeof( uint64_t ); } bool success = true; for( Connections::const_iterator i = connections.begin(); i < connections.end(); ++i ) { ConnectionPtr connection = *i; connection->lockSend(); if( !connection->send( &packet, headerSize, true )) success = false; for( size_t j = 0; j < nItems; ++j ) if( !connection->send( &sizes[j], sizeof(uint64_t), true ) || !connection->send( items[j], sizes[j], true )) { success = false; } connection->unlockSend(); } return success; }
/* Get socket descriptor of the username */ int getFromConnectionTable(std::string username){ Connections::iterator it = conn.find(username); if(it == conn.end()) return -1; return it->second; }
/* * Parse incoming data * Types of messages and their responses are: * NEW: <from> * Response --> NEW: <status> * CHNAME: <old> : <new> * Response --> CHNAME: <status> * QUERY: <from> * Response --> ONLINE: <user1> : <user2> : <user3> : .... * SEND: <from> : <to> : <message> * Response --> SENT: <to> : <statusMessage> * BCAST: <from> : <message> * Response --> SENT: <from> : <status> * * /toclient/ RECV: <from> : <message> */ void processRequest(int fromSocket, char* stream){ std::vector<std::string> tokens; char* dump = strdup(stream); /* Create a duplicate stream */ splitCharStream(dump, DELIM, 1, &tokens); /* Retrieve the kind of message */ delete dump; std::string reqType = tokens[0]; int TYPE_FLAG = -1, delimCount=-1; if(reqType=="CHNAME"){ TYPE_FLAG = TYPE_CHNAME; delimCount = 1; } else if(reqType=="NEW"){ TYPE_FLAG = TYPE_NEW; delimCount = 0; } else if(reqType=="QUERY"){ TYPE_FLAG = TYPE_QUERY; delimCount = 0; } else if(reqType=="SEND"){ TYPE_FLAG = TYPE_SEND; delimCount = 2; } else if(reqType=="BCAST"){ TYPE_FLAG = TYPE_BCAST; delimCount = 1; } if(TYPE_FLAG==-1) return; #ifdef __DEBUG__ std::cout<<TYPE_FLAG<<" --- "; #endif splitCharStream(strdup(tokens[1].c_str()), DELIM, delimCount, &tokens); /* Based on kind retrieve other param list */ std::string fromUser = tokens[0]; std::string toUser, message; if(TYPE_FLAG == TYPE_CHNAME){ toUser = tokens[1]; #ifdef __INFO__ std::cout<<"\""<<fromUser<<"\" changing name to \""<<toUser<<"\"."<<std::endl; #endif int curSock = getFromConnectionTable(fromUser); std::string reply = "CHNAME:"+toUser+":"; if(curSock==-1){ reply += "fail"; } else{ curSock = getFromConnectionTable(toUser); if(curSock==-1){ removeFromConnectionTable(fromSocket); addToConnectionTable(toUser, fromSocket); reply += "success"; } else{ reply += "duplicate"; } } int s = send(fromSocket, reply.c_str(), reply.length(), 0); if(s<0){ ERROR = E_SEND; error_message = "Unable to send query reply."; #ifdef __DEBUG__ std::cout<<error_message<<std::endl; #endif } } else if(TYPE_FLAG == TYPE_NEW){ #ifdef __INFO__ std::cout<<"\""<<fromUser<<"\" new registration."<<std::endl; #endif int oldSock = getFromConnectionTable(fromUser); std::string reply = "duplicate"; if(oldSock==-1){ addToConnectionTable(fromUser, fromSocket); /* Add user socket pair to table */ reply = "registered"; } #ifdef __INFO__ std::cout<<"\""<<fromUser<<"\" reg. status: "<<reply<<"."<<std::endl; #endif int s = send(fromSocket, reply.c_str(), reply.length(), 0); if(s<0){ ERROR = E_SEND; error_message = "Unable to send query reply."; #ifdef __DEBUG__ std::cout<<error_message<<std::endl; #endif } } else if(TYPE_FLAG == TYPE_QUERY){ #ifdef __INFO__ std::cout<<"\""<<fromUser<<"\" queried."<<std::endl; #endif std::string onlineList = getOnlineList(fromUser); int s = send(fromSocket, onlineList.c_str(), onlineList.length(), 0); if(s<0){ ERROR = E_SEND; error_message = "Unable to send query reply."; #ifdef __DEBUG__ std::cout<<error_message<<std::endl; #endif } } else if(TYPE_FLAG == TYPE_SEND){ toUser = tokens[1]; message = tokens[2]; #ifdef __INFO__ std::cout<<"\""<<fromUser<<"\" sending message to \""<<toUser<<"\"."<<std::endl; #endif /* Send message to desired target username */ int status = sendMessage(toUser, fromUser, message); std::string reply = "SENT: "+toUser+" : "; if(status==-1){ reply += error_message; #ifdef __DEBUG__ std::cout<<"\""<<fromUser<<"\" could not send a message to \""<<toUser<<"\". "<<std::endl; #endif } else{ reply += "success"; #ifdef __DEBUG__ std::cout<<"\""<<fromUser<<"\" sent a message to \""<<toUser<<"\"."<<std::endl; #endif } /* Report back to the sender */ int s = send(fromSocket, reply.c_str(), reply.length(), 0); if(s<0){ ERROR = E_SEND; error_message = "Unable to send message status."; #ifdef __DEBUG__ std::cout<<error_message<<std::endl; #endif } } else if(TYPE_FLAG == TYPE_BCAST){ message = tokens[1]; std::string bcast = "RECV:"+fromUser+":"+message; #ifdef __INFO__ std::cout<<"Broadcast from \""+fromUser+"\" : "<<message<<std::endl; #endif int status; Connections::iterator it = conn.begin(); while(it!=conn.end()){ if(it->first != fromUser){ status = send(it->second, bcast.c_str(), bcast.length(), 0 ); } ++it; } std::string reply = "SENT:"+fromUser+":b_success"; /* Report back to the broadcaster */ int s = send(fromSocket, reply.c_str(), reply.length(), 0); if(s<0){ ERROR = E_SEND; error_message = "Unable to send message status."; #ifdef __DEBUG__ std::cout<<error_message<<std::endl; #endif } } }
/** * @brief Closes and deletes a connection. * * @param[in] conn A ptr to a Connection */ void close_connection(const tcp::Connection* conn) { unbind(conn->local()); connections_.erase(conn->tuple()); }
void close(const std::string &connection) { p_connections.erase(connection); }
NNTPConnection* ServerPool::GetConnection(int iLevel, NewsServer* pWantServer, Servers* pIgnoreServers) { PooledConnection* pConnection = NULL; m_mutexConnections.Lock(); time_t tCurTime = time(NULL); if (iLevel < (int)m_Levels.size() && m_Levels[iLevel] > 0) { Connections candidates; candidates.reserve(m_Connections.size()); for (Connections::iterator it = m_Connections.begin(); it != m_Connections.end(); it++) { PooledConnection* pCandidateConnection = *it; NewsServer* pCandidateServer = pCandidateConnection->GetNewsServer(); if (!pCandidateConnection->GetInUse() && pCandidateServer->GetActive() && pCandidateServer->GetNormLevel() == iLevel && (!pWantServer || pCandidateServer == pWantServer || (pWantServer->GetGroup() > 0 && pWantServer->GetGroup() == pCandidateServer->GetGroup())) && (pCandidateConnection->GetStatus() == Connection::csConnected || !pCandidateServer->GetBlockTime() || pCandidateServer->GetBlockTime() + m_iRetryInterval <= tCurTime || pCandidateServer->GetBlockTime() > tCurTime)) { // free connection found, check if it's not from the server which should be ignored bool bUseConnection = true; if (pIgnoreServers && !pWantServer) { for (Servers::iterator it = pIgnoreServers->begin(); it != pIgnoreServers->end(); it++) { NewsServer* pIgnoreServer = *it; if (pIgnoreServer == pCandidateServer || (pIgnoreServer->GetGroup() > 0 && pIgnoreServer->GetGroup() == pCandidateServer->GetGroup() && pIgnoreServer->GetNormLevel() == pCandidateServer->GetNormLevel())) { bUseConnection = false; break; } } } pCandidateServer->SetBlockTime(0); if (bUseConnection) { candidates.push_back(pCandidateConnection); } } } if (!candidates.empty()) { // Peeking a random free connection. This is better than taking the first // available connection because provides better distribution across news servers, // especially when one of servers becomes unavailable or doesn't have requested articles. int iRandomIndex = rand() % candidates.size(); pConnection = candidates[iRandomIndex]; pConnection->SetInUse(true); } if (pConnection) { m_Levels[iLevel]--; } } m_mutexConnections.Unlock(); return pConnection; }
void clear() { p_connections.clear(); }