Performs defragmentation of a list of IPv6 packets. Packets are reordered.
    Crap is dropped. What lacks is completed by 'X' characters.
512802
def defragment6(pktlist):
    
    
    l = [ x for x in pktlist if IPv6ExtHdrFragment in x ] # remove non fragments
    if not l:
        return []

    id = l[0][IPv6ExtHdrFragment].id 

    llen = len(l)
    l = [ x for x in l if x[IPv6ExtHdrFragment].id == id ]
    if len(l) != llen:
        warning("defragment6: some fragmented packets have been removed from list")
    llen = len(l)

    # reorder fragments 
    i = 0 
    res = []
    while l:
        min_pos = 0
        min_offset  = l[0][IPv6ExtHdrFragment].offset
        for p in l:
            cur_offset = p[IPv6ExtHdrFragment].offset
            if cur_offset < min_offset:
                min_pos = 0
                min_offset  = cur_offset
        res.append(l[min_pos])
        del(l[min_pos])

    # regenerate the fragmentable part
    fragmentable = b""
    for p in res:
        q=p[IPv6ExtHdrFragment]
        offset = 8*q.offset
        if offset != len(fragmentable):
            warning("Expected an offset of %d. Found %d. Padding with XXXX" % (len(fragmentable), offset))
        fragmentable += b"X"*(offset - len(fragmentable))
        fragmentable += bytes(q.payload)

    # Regenerate the unfragmentable part.
    q = res[0]
    nh = q[IPv6ExtHdrFragment].nh
    q[IPv6ExtHdrFragment].underlayer.nh = nh
    q[IPv6ExtHdrFragment].underlayer.payload = None
    q /= conf.raw_layer(load=fragmentable)
    
    return IPv6(bytes(q))
2614
void drainBuffers() {
        // A mostly strict ordering is achieved by observing that each buffer
        // contains tasks in a weakly sorted order starting from the last drain.
        // The buffers can be merged into a sorted array in O(n) time by using
        // counting sort and chaining on a collision.

        // Moves the tasks into the output array, applies them, and updates the
        // marker for the starting order of the next drain.
        int maxTaskIndex = moveTasksFromBuffers(tasks);
        updateDrainedOrder(tasks, maxTaskIndex);
        runTasks(tasks, maxTaskIndex);
    }
205676
def ipv4_reassembly(packet, *, count=NotImplemented):
    """"""
    if 'IP' in packet:
        ipv4 = packet['IP']
        if ipv4.flags.DF:       # dismiss not fragmented packet
            return False, None
        data = dict(
            bufid=(
                ipaddress.ip_address(ipv4.src),         # source IP address
                ipaddress.ip_address(ipv4.dst),         # destination IP address
                ipv4.id,                                # identification
                TP_PROTO.get(ipv4.proto).name,          # payload protocol type
            ),
            num=count,                                  # original packet range number
            fo=ipv4.frag,                               # fragment offset
            ihl=ipv4.ihl,                               # internet header length
            mf=bool(ipv4.flags.MF),                     # more fragment flag
            tl=ipv4.len,                                # total length, header includes
            header=bytearray(ipv4.raw_packet_cache),    # raw bytearray type header
            payload=bytearray(bytes(ipv4.payload)),     # raw bytearray type payload
        )
        return True, data
    return False, None
482951
def reset(self, addresses):
        
        request = self._call(SetEnqueueResetReverseDns.SetEnqueueResetReverseDns, IPs=addresses)
        response = request.commit()
        return response['Success']
613551
def cleanup(self):
        
        for future in self.futures:
            future.cancel()
        self.executor.shutdown(wait=10)
        if self.ssh.get_transport() != None:
            self.ssh.close()
762945
def _cleanup(self, kill, verbose):
        
        if kill:
            removed_indices = self.g.prune()

            self.nout -= len(removed_indices)

            if verbose and removed_indices:
                print('Removing %s' % removed_indices)

            for j in removed_indices:
                self.inv_map.pop(j[0])
993711
static void drop6(FileDescriptor fd, byte[] group, int index, byte[] source)
        throws IOException
    {
        joinOrDrop6(false, fd, group, index, source);
    }
958339
def cleanup():
    """"""
    for sck in list(Wdb._sockets):
        try:
            sck.close()
        except Exception:
            log.warn('Error in cleanup', exc_info=True)
233502
def flush(self):
        ''''''
        # When profiling, we found that while there was some efficiency to be
        # gained elsewhere, the big performance hit is sending lots of small
        # messages at a time. In particular, consumers send many 'FIN' messages
        # which are very small indeed and the cost of dispatching so many system
        # calls is very high. Instead, we prefer to glom together many messages
        # into a single string to send at once.
        total = 0
        for sock in self.socket(blocking=False):
            # If there's nothing left in the out buffer, take whatever's in the
            # pending queue.
            #
            # When using SSL, if the socket throws 'SSL_WANT_WRITE', then the
            # subsequent send requests have to send the same buffer.
            pending = self._pending
            data = self._out_buffer or ''.join(
                pending.popleft() for _ in xrange(len(pending)))
            try:
                # Try to send as much of the first message as possible
                total = sock.send(data)
            except socket.error as exc:
                # Catch (errno, message)-type socket.errors
                if exc.args[0] not in self.WOULD_BLOCK_ERRS:
                    raise
                self._out_buffer = data
            else:
                self._out_buffer = None
            finally:
                if total < len(data):
                    # Save the rest of the message that could not be sent
                    self._pending.appendleft(data[total:])
        return total
414087
def delistify(x):
    
    if isinstance(x, list):
        x = [e.replace("'", "") for e in x]
        return '-'.join(sorted(x))
    return x
679829
def cleanup(self):
        
        if self.local_port is not None:
            logger.debug(("Stopping ssh tunnel {0}:{1}:{2} for "
                          "{3}@{4}".format(self.local_port,
                                           self.remote_address,
                                           self.remote_port,
                                           self.username,
                                           self.address)))
            if self.forward is not None:
                self.forward.stop()
                self.forward.join()
            if self.transport is not None:
                self.transport.close()
316943
def defragment(self):
        """"""
        defrag_request = etcdrpc.DefragmentRequest()
        self.maintenancestub.Defragment(
            defrag_request,
            self.timeout,
            credentials=self.call_credentials,
            metadata=self.metadata
        )
573477
def cleanup(self):
        
        now = time.time()
        expired = now - NODE_TIMEOUT
        if self.conn.zremrangebyscore(self.key, 0, expired):
            self._notify()
745860
def post_dissect(self, data):
        

        # uncompress payload
        packet = IPv6()
        packet.version = IPHC_DEFAULT_VERSION
        packet.tc, packet.fl = self._getTrafficClassAndFlowLabel()
        if not self.nh:
            packet.nh = self._nhField
        # HLIM: Hop Limit
        if self.hlim == 0:
            packet.hlim = self._hopLimit
        elif self.hlim == 0x1:
            packet.hlim = 1
        elif self.hlim == 0x2:
            packet.hlim = 64
        else:
            packet.hlim = 255
        # TODO: Payload length can be inferred from lower layers from either the  # noqa: E501
        # 6LoWPAN Fragmentation header or the IEEE802.15.4 header

        packet.src = self.decompressSourceAddr(packet)
        packet.dst = self.decompressDestinyAddr(packet)

        if self.nh == 1:
            # The Next Header field is compressed and the next header is
            # encoded using LOWPAN_NHC

            packet.nh = 0x11  # UDP
            udp = UDP()
            if self.header_compression and \
               self.header_compression & 0x4 == 0x0:
                udp.chksum = self.udpChecksum

            s, d = nhc_port(self)
            if s == 16:
                udp.sport = self.udpSourcePort
            elif s == 8:
                udp.sport = 0xF000 + s
            elif s == 4:
                udp.sport = 0xF0B0 + s
            if d == 16:
                udp.dport = self.udpDestinyPort
            elif d == 8:
                udp.dport = 0xF000 + d
            elif d == 4:
                udp.dport = 0xF0B0 + d

            packet.payload = udp / data
            data = raw(packet)
        # else self.nh == 0 not necessary
        elif self._nhField & 0xE0 == 0xE0:  # IPv6 Extension Header Decompression  # noqa: E501
            warning('Unimplemented: IPv6 Extension Header decompression')  # noqa: E501
            packet.payload = conf.raw_layer(data)
            data = raw(packet)
        else:
            packet.payload = conf.raw_layer(data)
            data = raw(packet)

        return Packet.post_dissect(self, data)
901066
def deregister sock, events, fd = 0
      return unless sock || !fd.zero?

      item = @items.get(@sockets.index(sock))

      if item && (item[:events] & events) > 0
        # change the value in place
        item[:events] ^= events

        delete sock if item[:events].zero?
        true
      else
        false
      end
    end
786622
def ipv6_reassembly(packet, *, count=NotImplemented):
    """"""
    ipv6 = getattr(packet, 'ip6', None)
    if ipv6 is not None:
        ipv6_frag = ipv6.extension_hdrs.get(44)
        if ipv6_frag is None:       # dismiss not fragmented packet
            return False, None
        hdr_len = ipv6_hdr_len(ipv6)
        data = dict(
            bufid=(
                ipaddress.ip_address(ipv6.src),                     # source IP address
                ipaddress.ip_address(ipv6.dst),                     # destination IP address
                ipv6.flow,                                          # label
                TP_PROTO.get(ipv6_frag.nh).name,                    # next header field in IPv6 Fragment Header
            ),
            num=count,                                              # original packet range number
            fo=ipv6_frag.nxt,                                       # fragment offset
            ihl=hdr_len,                                            # header length, only headers before IPv6-Frag
            mf=bool(ipv6_frag.m_flag),                              # more fragment flag
            tl=len(ipv6),                                           # total length, header includes
            header=bytearray(ipv6.pack()[:hdr_len]),                # raw bytearray type header before IPv6-Frag
            payload=bytearray(ipv6.pack()[hdr_len+ipv6_frag:]),     # raw bytearray type payload after IPv6-Frag
        )
        return True, data
    return False, None
1351497
def prune_hashes(self, hashes, list_type):
        """"""
        discarded = []
        for hash in hashes:
            if (hash in self.hashes):
                self.hashes.discard(hash)
                discarded.append(hash)
        self.logger.info("Not calculating %s hash(es) on destination as not present "
                         "in source %s list" % (', '.join(sorted(discarded)), list_type))