Return a list of peers from whom we can request pieces. These are peers for whom we have an established connection, and
 are not marked as bad. See markPeerBad.
543457
def findRequestablePeers(classifiedPeers)
      result = []

      classifiedPeers.establishedPeers.each do |peer|
        result.push peer if ! @badPeers.findByAddr(peer.trackerPeer.ip, peer.trackerPeer.port)
      end

      result
    end
39698
def computePeersHavingPiece(classifiedPeers)
      # Make a list of each peer having the specified piece
      peersHavingPiece = Array.new(@numPieces)
      # This first list represents rarity by number if peers having that piece. 1 = rarest.
      classifiedPeers.requestablePeers.each do |peer|
        @numPieces.times do |i|
          if peer.bitfield.set?(i)
            if peersHavingPiece[i]
              peersHavingPiece[i].push peer
            else
              peersHavingPiece[i] = [peer]
            end
          end
        end
      end
      peersHavingPiece
    end
249929
def get_atlas_peers(hostport, timeout=30, my_hostport=None, proxy=None):
    
    assert hostport or proxy, 'need either hostport or proxy'

    peers_schema = {
        'type': 'object',
        'properties': {
            'peers': {
                'type': 'array',
                'items': {
                    'type': 'string',
                    'pattern': '^([^:]+):([1-9][0-9]{1,4})$',
                },
            },
        },
        'required': [
            'peers'
        ],
    }

    schema = json_response_schema( peers_schema )

    if proxy is None:
        proxy = connect_hostport(hostport)

    peers = None
    try:
        peer_list_resp = proxy.get_atlas_peers()
        peer_list_resp = json_validate(schema, peer_list_resp)
        if json_is_error(peer_list_resp):
            return peer_list_resp

        # verify that all strings are host:ports
        for peer_hostport in peer_list_resp['peers']:
            peer_host, peer_port = url_to_host_port(peer_hostport)
            if peer_host is None or peer_port is None:
                return {'error': 'Server did not return valid Atlas peers', 'http_status': 503}

        peers = peer_list_resp

    except ValidationError as ve:
        if BLOCKSTACK_DEBUG:
            log.exception(ve)

        resp = {'error': 'Server response did not match expected schema.  You are likely communicating with an out-of-date Blockstack node.', 'http_status': 502}
        return resp

    except socket.timeout:
        log.error("Connection timed out")
        resp = {'error': 'Connection to remote host timed out.', 'http_status': 503}
        return resp

    except socket.error as se:
        log.error("Connection error {}".format(se.errno))
        resp = {'error': 'Connection to remote host failed.', 'http_status': 502}
        return resp

    except Exception as ee:
        if BLOCKSTACK_DEBUG:
            log.exception(ee)

        log.error("Caught exception while connecting to Blockstack node: {}".format(ee))
        resp = {'error': 'Failed to contact Blockstack node {}.  Try again with `--debug`.'.format(hostport), 'http_status': 500}
        return resp

    return peers
972607
def get(self, name, mask=None):
        
        mypeer = self.transport.getQ2QPeer()
        tl = self.nexus.transloads[name]
        peerz = tl.peers
        if mypeer in peerz:
            peerk = peerz[mypeer]
        else:
            # all turned on initially; we aren't going to send them anything.
            peerk = PeerKnowledge(bits.BitArray(size=len(tl.mask), default=1))
            peerz[mypeer] = peerk
        peerk.sentGet = True
        return self.callRemote(
            Get, name=name, mask=mask).addCallback(lambda r: r['size'])
919936
async def _nodes_found(self, responses):
        
        toremove = []
        found_values = []
        for peerid, response in responses.items():
            response = RPCFindResponse(response)
            if not response.happened():
                toremove.append(peerid)
            elif response.has_value():
                found_values.append(response.get_value())
            else:
                peer = self.nearest.get_node(peerid)
                self.nearest_without_value.push(peer)
                self.nearest.push(response.get_node_list())
        self.nearest.remove(toremove)

        if found_values:
            return await self._handle_found_values(found_values)
        if self.nearest.have_contacted_all():
            # not found!
            return None
        return await self.find()
1203910
def get_peercred(sock):
    """"""
    buf = sock.getsockopt(_PEERCRED_LEVEL, _PEERCRED_OPTION, struct.calcsize('3i'))
    return struct.unpack('3i', buf)
1053805
public void peers(List<TcpEndpoint> value) {
        tcp_endpoint_vector v = new tcp_endpoint_vector();

        for (TcpEndpoint endp : value) {
            v.push_back(endp.swig());
        }

        p.set_peers(v);
    }
86367
def _get_peer_connection(self, blacklist=None):
        

        blacklist = blacklist or set()

        peer = None
        connection = None

        while connection is None:
            peer = self._choose(blacklist)

            if not peer:
                raise NoAvailablePeerError(
                    "Can't find an available peer for '%s'" % self.service
                )

            try:
                connection = yield peer.connect()
            except NetworkError as e:
                log.info(
                    'Failed to connect to %s. Trying a different host.',
                    peer.hostport,
                    exc_info=e,
                )
                connection = None
                blacklist.add(peer.hostport)

        raise gen.Return((peer, connection))
1014499
async def _nodes_found(self, responses):
        
        toremove = []
        for peerid, response in responses.items():
            response = RPCFindResponse(response)
            if not response.happened():
                toremove.append(peerid)
            else:
                self.nearest.push(response.get_node_list())
        self.nearest.remove(toremove)

        if self.nearest.have_contacted_all():
            return list(self.nearest)
        return await self.find()
237592
public BitSet getAvailablePieces() {
    if (!this.isInitialized()) {
      throw new IllegalStateException("Torrent not yet initialized!");
    }

    BitSet availablePieces = new BitSet(this.pieces.length);

    synchronized (this.pieces) {
      for (Piece piece : this.pieces) {
        if (piece.available()) {
          availablePieces.set(piece.getIndex());
        }
      }
    }

    return availablePieces;
  }
65488
def selectPeerToIntroduce(self, otherPeers):
        
        for peer in otherPeers:
            if peer not in self.otherPeers:
                self.otherPeers.append(peer)
                return peer
1354378
@Override
  public synchronized void handlePeerDisconnected(SharingPeer peer) {
    BitSet availablePieces = peer.getAvailablePieces();

    for (int i = availablePieces.nextSetBit(0); i >= 0;
         i = availablePieces.nextSetBit(i + 1)) {
      this.pieces[i].noLongerAt(peer);
    }

    Set<Piece> requested = peer.getRequestedPieces();
    if (requested != null) {
      for (Piece piece : requested) {
        this.requestedPieces.set(piece.getIndex(), false);
      }
    }

    myDownloaders.remove(peer);

    try {
      closeFileChannelIfNecessary();
    } catch (IOException e) {
      logger.info("I/O error on attempt to close file storage: " + e.toString());
    }

    logger.debug("Peer {} went away with {} piece(s) [{}/{}].",
            new Object[]{
                    peer,
                    availablePieces.cardinality(),
                    this.completedPieces.cardinality(),
                    this.pieces.length
            });
    logger.trace("We now have {} piece(s) and {} outstanding request(s): {}",
            new Object[]{
                    this.completedPieces.cardinality(),
                    this.requestedPieces.cardinality(),
                    this.requestedPieces
            });
    eventDispatcher.multicaster().peerDisconnected(peer);
  }
1120624
def findRequestableBlocks(classifiedPeers, numToReturn = nil)
      # Have a list of the current pieces we are working on. Each time this method is 
      # called, check the blocks in the pieces in list order to find the blocks to return
      # for requesting. If a piece is completed, remove it from this list. If we need more blocks
      # than there are available in the list, add more pieces to the end of the list (in rarest-first
      # order).
      result = []

      # Update requestable peers to only be those that we can still request pieces from.
      peersHavingPiece = computePeersHavingPiece(classifiedPeers)
      requestable = @completeBlocks.union(@requestedBlocks).compliment!
      rarityOrder = nil

      currentPiece = 0
      while true
        if currentPiece >= @currentPieces.length
          # Add more pieces in rarest-first order. If there are no more pieces, break.
          rarityOrder = computeRarity(classifiedPeers) if ! rarityOrder
          added = false
          rarityOrder.each do |pair|
            pieceIndex = pair[1]
            peersWithPiece = peersHavingPiece[pieceIndex]
            if peersWithPiece && peersWithPiece.size > 0 && !@currentPieces.index(pieceIndex) && ! pieceCompleted?(pieceIndex)
              @logger.debug "Adding piece #{pieceIndex} to the current downloading list"
              @currentPieces.push pieceIndex
              added = true
              break
            end
          end
          if ! added          
            @logger.debug "There are no more pieces to add to the current downloading list"
            break
          end
        end        
    
        currentPieceIndex = @currentPieces[currentPiece]

        if pieceCompleted?(currentPieceIndex)
          @logger.debug "Piece #{currentPieceIndex} complete so removing it from the current downloading list" 
          @currentPieces.delete_at(currentPiece)
          next
        end

        peersWithPiece = peersHavingPiece[currentPieceIndex]
        if !peersWithPiece || peersWithPiece.size == 0
          @logger.debug "No peers have piece #{currentPieceIndex}" 
          currentPiece += 1
          next
        end

        eachBlockInPiece(currentPieceIndex) do |blockIndex|
          if requestable.set?(blockIndex)
            result.push createBlockinfoByPieceAndBlockIndex(currentPieceIndex, peersWithPiece, blockIndex)
            break if numToReturn && result.size >= numToReturn
          end
        end           

        break if numToReturn && result.size >= numToReturn
        currentPiece += 1
      end

      result
    end
152693
def get_members(self, retrieve=False):

		'''
		
		'''

		if self.exists and hasattr(self.rdf.triples, 'pcdm') and hasattr(self.rdf.triples.pcdm, 'hasMember'):
			members = [ self.repo.parse_uri(uri) for uri in self.rdf.triples.pcdm.hasMember ]

			# return
			return members

		else:
			return []
106419
async def _wait_peers(self):
        
        # Make sure we remove dead peers.
        for p in self._peers[:]:
            if p.dead:
                self._peers.remove(p)

        while not self._peers:
            await self._peers.wait_not_empty()
773050
def checkPieceHash(pieceIndex)
      id = returnAndIncrRequestId
      return id if @state == :after_stop
      @requests.push [id, :hash_piece, pieceIndex]
      @requestsSemaphore.signal
      id
    end
347336
def requestMetadataPieces(infoHash)
      torrentData = @torrentData[infoHash]
      if ! torrentData
        @logger.error "Request metadata pices: torrent data for torrent #{QuartzTorrent.bytesToHex(infoHash)} not found."
        return
      end
      
      return if torrentData.paused || torrentData.queued

      # We may not have completed the extended handshake with the peer which specifies the torrent size.
      # In this case torrentData.metainfoPieceState is not yet set.
      return if ! torrentData.metainfoPieceState

      @logger.info "#{QuartzTorrent.bytesToHex(infoHash)}: Obtained all pieces of metainfo." if torrentData.metainfoPieceState.complete?

      pieces = torrentData.metainfoPieceState.findRequestablePieces
      classifiedPeers = ClassifiedPeers.new torrentData.peers.all
      peers = torrentData.metainfoPieceState.findRequestablePeers(classifiedPeers)
  
      if peers.size > 0
        # For now, just request all pieces from the first peer.
        pieces.each do |pieceIndex|
          msg = ExtendedMetaInfo.new
          msg.msgType = :request
          msg.piece = pieceIndex
          withPeersIo(peers.first, "requesting metadata piece") do |io|
            sendMessageToPeer msg, io, peers.first
            torrentData.metainfoPieceState.setPieceRequested(pieceIndex, true)
            @logger.debug "#{QuartzTorrent.bytesToHex(infoHash)}: Requesting metainfo piece from #{peers.first}: piece #{pieceIndex}"
          end
        end
      else
        @logger.error "#{QuartzTorrent.bytesToHex(infoHash)}: No peers found that have metadata."
      end

    end