Parse the given packet and update properties accordingly
342253
def from_bytes(cls, bitstream):
        '''
        
        '''
        packet = cls()

        # Convert to ConstBitStream (if not already provided)
        if not isinstance(bitstream, ConstBitStream):
            if isinstance(bitstream, Bits):
                bitstream = ConstBitStream(auto=bitstream)
            else:
                bitstream = ConstBitStream(bytes=bitstream)

        # Read the source and destination ports
        (packet.source_port,
         packet.destination_port) = bitstream.readlist('2*uint:16')

        # Store the length
        length = bitstream.read('uint:16')
        if length < 8:
            raise ValueError('Invalid UDP length')

        # Read the checksum
        packet.checksum = bitstream.read('uint:16')

        # And the rest is payload
        payload_bytes = length - 8
        packet.payload = bitstream.read('bytes:%d' % payload_bytes)

        # LISP-specific handling
        if packet.source_port == 4341 or packet.destination_port == 4341:
            # Payload is a LISP data packet
            from pylisp.packet.lisp.data import DataPacket
            packet.payload = DataPacket.from_bytes(packet.payload)
        elif packet.source_port == 4342 or packet.destination_port == 4342:
            # Payload is a LISP control message
            from pylisp.packet.lisp.control.base import ControlMessage
            packet.payload = ControlMessage.from_bytes(packet.payload)

        # There should be no remaining bits
        if bitstream.pos != bitstream.len:
            raise ValueError('Bits remaining after processing packet')

        # Verify that the properties make sense
        packet.sanitize()

        return packet
941737
def stream_to_packet(data):
    
    if len(data) < 6:
        return None

    # unpack the length
    pktlen = struct.unpack(">H", data[4:6])[0] + 6
    if (len(data) < pktlen):
        return None

    return (data[:pktlen], data[pktlen:])
362387
def raise_on_packet(self, pkt_cls, state, get_next_msg=True):
        
        # Maybe we already parsed the expected packet, maybe not.
        if get_next_msg:
            self.get_next_msg()
        if (not self.buffer_in or
                not isinstance(self.buffer_in[0], pkt_cls)):
            return
        self.cur_pkt = self.buffer_in[0]
        self.buffer_in = self.buffer_in[1:]
        raise state()
1145358
async def receive(self, pkt):
        """"""
        self.server.logger.info('%s: Received packet %s data %s',
                                self.sid, packet.packet_names[pkt.packet_type],
                                pkt.data if not isinstance(pkt.data, bytes)
                                else '<binary>')
        if pkt.packet_type == packet.PING:
            self.last_ping = time.time()
            await self.send(packet.Packet(packet.PONG, pkt.data))
        elif pkt.packet_type == packet.MESSAGE:
            await self.server._trigger_event(
                'message', self.sid, pkt.data,
                run_async=self.server.async_handlers)
        elif pkt.packet_type == packet.UPGRADE:
            await self.send(packet.Packet(packet.NOOP))
        elif pkt.packet_type == packet.CLOSE:
            await self.close(wait=False, abort=True)
        else:
            raise exceptions.UnknownPacketError()
518604
function EnvPacket(env) {
  Packet.call(this);
  this.env = env || {};
  this.json = JSON.stringify(this.env);
}
951166
def parse_packet(packet):
    """"""
    frame = parse_ltv_packet(packet)
    if frame is None:
        frame = parse_ibeacon_packet(packet)
    return frame
367798
def parse_headers(self, use_cookies, raw):
        
        if not raw:
            packet = helper.to_str(helper.read_file(self.fpth))
        else:
            packet = raw
        dat = {}

        pks = [x for x in packet.split('\n') if x.replace(' ', '')]
        url = pks[0].split(' ')[1]

        for i, cnt in enumerate(pks[1:]):
            arr = cnt.split(':')
            if len(arr) < 2:
                continue
            arr = [x.replace(' ', '') for x in arr]
            _k, v = arr[0], ':'.join(arr[1:])
            dat[_k] = v

        if use_cookies:
            try:
                self.fmt_cookies(dat.pop('Cookie'))
            except:
                pass
        self.headers = dat
        self.url = 'https://{}{}'.format(self.headers.get('Host'), url)
        return url, dat
146547
def parse_packets(self, binary_packets):
        
        if not binary_packets:
            raise ValueError("Must supply at least one packet")
        parsed_packets = []

        if not self._current_tshark:
            self.eventloop.run_until_complete(self._get_tshark_process())
        for binary_packet in binary_packets:
            self._write_packet(binary_packet)

        def callback(pkt):
            parsed_packets.append(pkt)
            if len(parsed_packets) == len(binary_packets):
                raise StopCapture()

        self.eventloop.run_until_complete(self._get_parsed_packet_from_tshark(callback))
        return parsed_packets
377043
function parsePacket(packet) {
  var parsedPacket = loopPacket.parse(packet);
  var convertedPacket = {};
  for(var property in parsedPacket) {
    var value = parsedPacket[property];
    switch (property){
      case "BarTrend":
        value = _convertBarTrend(value);
        break;
      case "TempIn":
      case "TempOut":
        value = Convert(value/10).from('F').to('C');
        break;
      case "BatteryVolts":
	value = _convertToVoltage(value);
	break;	
      case "ForecastRuleNo":
	value = _getForecastString(value);
	break;
      case "ForecastIcon":
	value = _parseIconValue(value);
	break;
      case "SunRise":
      case "SunSet":
	value = _convertTime(value);
        break;
      case "WindSpeed":
      case "WindSpeed10Min":
	value = Convert(value).from('m/h').to('m/s');
	break;
	
    }
    convertedPacket[property] = value;

  }

  return parsedPacket;
}
408853
def parse_subpackets(s):
    """"""
    subpackets = []
    total_size = s.readfmt('>H')
    data = s.read(total_size)
    s = util.Reader(io.BytesIO(data))

    while True:
        try:
            first = s.readfmt('B')
        except EOFError:
            break

        if first < 192:
            subpacket_len = first
        elif first < 255:
            subpacket_len = ((first - 192) << 8) + s.readfmt('B') + 192
        else:  # first == 255
            subpacket_len = s.readfmt('>L')

        subpackets.append(s.read(subpacket_len))

    return subpackets
631006
def packetToDict(pkt):
	

	d = {
		'id': pkt[4],
		'instruction': xl320.InstrToStr[pkt[7]],
		'length': (pkt[6] << 8) + pkt[5],
		'params': pkt[8:-2],
		'crc': pkt[-2:]
	}

	return d
344886
def _sense_packet_to_data(packet):
        """"""
        data = bytearray(0)
        last = 0
        i = 1
        while (i < len(packet)):
            if not (last == 2 and packet[i] == 0):
                data.append(packet[i])
            last = packet[i]
            i += 1

        return data
882766
def decode_file(fname):
    """"""
    if _debug: decode_file._debug("decode_file %r", fname)

    if not pcap:
        raise RuntimeError("failed to import pcap")

    # create a pcap object, reading from the file
    p = pcap.pcap(fname)

    # loop through the packets
    for i, (timestamp, data) in enumerate(p):
        try:
            pkt = decode_packet(data)
            if not pkt:
                continue
        except Exception as err:
            if _debug: decode_file._debug("    - exception decoding packet %d: %r", i+1, err)
            continue

        # save the packet number (as viewed in Wireshark) and timestamp
        pkt._number = i + 1
        pkt._timestamp = timestamp

        yield pkt
1221920
def handle_packet(self, packet):
        """"""
        if self.packet_callback:
            # forward to callback
            self.packet_callback(packet)
        else:
            print('packet', packet)
839402
def packet(tag, blob):
    """"""
    assert len(blob) < 2**32

    if len(blob) < 2**8:
        length_type = 0
    elif len(blob) < 2**16:
        length_type = 1
    else:
        length_type = 2

    fmt = ['>B', '>H', '>L'][length_type]
    leading_byte = 0x80 | (tag << 2) | (length_type)
    return struct.pack('>B', leading_byte) + util.prefix_len(fmt, blob)
826861
def from_bytes(cls, bitstream):
        '''
        
        '''
        packet = cls()

        # Convert to ConstBitStream (if not already provided)
        if not isinstance(bitstream, ConstBitStream):
            if isinstance(bitstream, Bits):
                bitstream = ConstBitStream(auto=bitstream)
            else:
                bitstream = ConstBitStream(bytes=bitstream)

        # Read the type
        type_nr = bitstream.read('uint:4')
        if type_nr != packet.message_type:
            msg = 'Invalid bitstream for a {0} packet'
            class_name = packet.__class__.__name__
            raise ValueError(msg.format(class_name))

        # Read if this is a reply
        packet.is_reply = bitstream.read('bool')

        # Skip reserved bits
        packet._reserved1 = bitstream.read(27)

        # Read the nonce
        packet.nonce = bitstream.read('bytes:8')

        # Read the key id
        packet.key_id = bitstream.read('uint:16')

        # Read the authentication data
        data_length = bitstream.read('uint:16')
        packet.authentication_data = bitstream.read('bytes:%d' % data_length)

        # Read the TTL
        packet.ttl = bitstream.read('uint:32')

        # Skip reserved bits
        packet._reserved2 = bitstream.read(8)

        # Store the EID prefix mask length until we need it
        eid_prefix_len = bitstream.read('uint:8')

        # Read the EID prefix
        packet.eid_prefix = read_afi_address_from_bitstream(bitstream, eid_prefix_len)

        # Read the reply
        packet.reply = read_afi_address_from_bitstream(bitstream)

        # Verify that the properties make sense
        packet.sanitize()

        return packet
111199
def digest_packets(packets, hasher):
    """"""
    data_to_hash = io.BytesIO()
    for p in packets:
        data_to_hash.write(p['_to_hash'])
    hasher.update(data_to_hash.getvalue())
    return hasher.digest()