output: None -> valid API frame (binary data)

        output will produce a valid API frame for transmission to an
        XBee module.
961871
def output(self):
        
        # start is one byte long, length is two bytes
        # data is n bytes long (indicated by length)
        # chksum is one byte long
        data = self.len_bytes() + self.data + self.checksum()

        # Only run the escaoe process if it hasn't been already
        if self.escaped and len(self.raw_data) < 1:
            self.raw_data = APIFrame.escape(data)

        if self.escaped:
            data = self.raw_data

        # Never escape start byte
        return APIFrame.START_BYTE + data
236715
def _get_response_frame(self, uuid):
        
        frame = None
        frames = self._response.get(uuid, None)
        if frames:
            frame = frames.pop(0)
        return frame
1274929
def recv(self, full_frame=False):
		
		payloadbuffer = b''
		tries = 3
		while tries:
			tmpbuffer = self.serial_h.read(1)
			if tmpbuffer != b'\xee':
				self.loggerio.error('did not receive \\xee as the first byte of the frame')
				self.loggerio.debug('received \\x' + binascii.b2a_hex(tmpbuffer).decode('utf-8') + ' instead')
				tries -= 1
				continue
			tmpbuffer += self.serial_h.read(5)
			sequence, length = struct.unpack('>xxxBH', tmpbuffer)
			payload = self.serial_h.read(length)
			tmpbuffer += payload
			chksum = self.serial_h.read(2)
			if chksum == packet_checksum(tmpbuffer):
				self.serial_h.write(ACK)
				data = tmpbuffer + chksum
				self.loggerio.debug("received frame, length: {0:<3} data: {1}".format(len(data), binascii.b2a_hex(data).decode('utf-8')))
				payloadbuffer += payload
				if sequence == 0:
					if full_frame:
						payloadbuffer = data
					if sys.version_info[0] == 2:
						payloadbuffer = bytearray(payloadbuffer)
					return payloadbuffer
				else:
					tries = 3
			else:
				self.serial_h.write(NACK)
				self.loggerio.warning('crc does not match on received frame')
				tries -= 1
		self.loggerio.critical('failed 3 times to correctly receive a frame')
		raise C1218IOError('failed 3 times to correctly receive a frame')
1359669
def to_frame(self, slot=SLOT.SCAN_MAP):
        
        payload = self.scanmap.ljust(64, b'\0')
        return yubikey_frame.YubiKeyFrame(command=slot, payload=payload)
684843
async def read_data_frame(self, max_size: int) -> Optional[Frame]:
        
        # 6.2. Receiving Data
        while True:
            frame = await self.read_frame(max_size)

            # 5.5. Control Frames
            if frame.opcode == OP_CLOSE:
                # 7.1.5.  The WebSocket Connection Close Code
                # 7.1.6.  The WebSocket Connection Close Reason
                self.close_code, self.close_reason = parse_close(frame.data)
                # Echo the original data instead of re-serializing it with
                # serialize_close() because that fails when the close frame is
                # empty and parse_close() synthetizes a 1005 close code.
                await self.write_close_frame(frame.data)
                return None

            elif frame.opcode == OP_PING:
                # Answer pings.
                ping_hex = frame.data.hex() or "[empty]"
                logger.debug(
                    "%s - received ping, sending pong: %s", self.side, ping_hex
                )
                await self.pong(frame.data)

            elif frame.opcode == OP_PONG:
                # Acknowledge pings on solicited pongs.
                if frame.data in self.pings:
                    # Acknowledge all pings up to the one matching this pong.
                    ping_id = None
                    ping_ids = []
                    while ping_id != frame.data:
                        ping_id, pong_waiter = self.pings.popitem(last=False)
                        ping_ids.append(ping_id)
                        pong_waiter.set_result(None)
                    pong_hex = binascii.hexlify(frame.data).decode() or "[empty]"
                    logger.debug(
                        "%s - received solicited pong: %s", self.side, pong_hex
                    )
                    ping_ids = ping_ids[:-1]
                    if ping_ids:
                        pings_hex = ", ".join(
                            binascii.hexlify(ping_id).decode() or "[empty]"
                            for ping_id in ping_ids
                        )
                        plural = "s" if len(ping_ids) > 1 else ""
                        logger.debug(
                            "%s - acknowledged previous ping%s: %s",
                            self.side,
                            plural,
                            pings_hex,
                        )
                else:
                    pong_hex = binascii.hexlify(frame.data).decode() or "[empty]"
                    logger.debug(
                        "%s - received unsolicited pong: %s", self.side, pong_hex
                    )

            # 5.6. Data Frames
            else:
                return frame
145329
def to_bytes_or_none(value):
    """"""
    if value == ffi.NULL:
        return None
    elif isinstance(value, ffi.CData):
        return ffi.string(value)
    else:
        raise ValueError('Value must be char[] or NULL')
1064916
def _btc_script_serialize_unit(unit):
    
    
    if isinstance(unit, int):
        # cannot be less than -1, since btc_script_deserialize() never returns such numbers
        if unit < -1:
            raise ValueError('Invalid integer: {}'.format(unit))

        if unit < 16:
            if unit == 0:
                # OP_RESERVED
                return encoding.from_int_to_byte(OPCODE_VALUES['OP_RESERVED'])
            else:
                # OP_1 thru OP_16, or OP_1NEGATE
                return encoding.from_int_to_byte(unit + 80)
        else:
            # pass as numeric literal or raw opcode
            return encoding.from_int_to_byte(unit)

    elif unit is None:
        # None means OP_0
        return b'\x00'

    else:
        if len(unit) <= 75:
            # length + payload
            return encoding.from_int_to_byte(len(unit)) + unit

        elif len(unit) < 256:
            # OP_PUSHDATA1 + length (1 byte) + payload
            return encoding.from_int_to_byte(OPCODE_VALUES['OP_PUSHDATA1']) + encoding.from_int_to_byte(len(unit)) + unit

        elif len(unit) < 65536:
            # OP_PUSHDATA2 + length (2 bytes, big-endian) + payload
            return encoding.from_int_to_byte(OPCODE_VALUES['OP_PUSHDATA2']) + encoding.encode(len(unit), 256, 2)[::-1] + unit
        else:
            # OP_PUSHDATA4 + length (4 bytes, big-endian) + payload
            return encoding.from_int_to_byte(OPCODE_VALUES['OP_PUSHDATA4']) + encoding.encode(len(unit), 256, 4)[::-1] + unit
1276015
def make_pkh_output_script(pubkey, witness=False):
    '''
    
    '''
    if witness and not riemann.network.SEGWIT:
        raise ValueError(
            'Network {} does not support witness scripts.'
            .format(riemann.get_current_network_name()))

    output_script = bytearray()

    if type(pubkey) is not bytearray and type(pubkey) is not bytes:
        raise ValueError('Unknown pubkey format. '
                         'Expected bytes. Got: {}'.format(type(pubkey)))

    pubkey_hash = utils.hash160(pubkey)

    if witness:
        output_script.extend(riemann.network.P2WPKH_PREFIX)
        output_script.extend(pubkey_hash)
    else:
        output_script.extend(b'\x76\xa9\x14')  # OP_DUP OP_HASH160 PUSH14
        output_script.extend(pubkey_hash)
        output_script.extend(b'\x88\xac')  # OP_EQUALVERIFY OP_CHECKSIG
    return output_script
749364
def _send_mbus(self, frame):
        
        # for auto_open mode, check TCP and open if need
        if self.__auto_open and not self.is_open():
            self.open()
        # send request
        bytes_send = self._send(frame)
        if bytes_send:
            if self.__debug:
                self._pretty_dump('Tx', frame)
            return bytes_send
        else:
            return None
1169349
def frame_from_raw(raw):
    """"""
    command, payload = extract_from_frame(raw)
    frame = create_frame(command)
    if frame is None:
        PYVLXLOG.warning("Command %s not implemented, raw: %s", command, ":".join("{:02x}".format(c) for c in raw))
        return None
    frame.validate_payload_len(payload)
    frame.from_payload(payload)
    return frame
455070
def _prep_binary_content(self):

		'''
		
		'''

		# nothing present
		if not self.data and not self.location and 'Content-Location' not in self.resource.headers.keys():
			raise Exception('creating/updating NonRDFSource requires content from self.binary.data, self.binary.location, or the Content-Location header')

		elif 'Content-Location' in self.resource.headers.keys():
			logger.debug('Content-Location header found, using')
			self.delivery = 'header'

		# if Content-Location is not set, look for self.data_location then self.data
		elif 'Content-Location' not in self.resource.headers.keys():

			# data_location set, trumps Content self.data
			if self.location:
				# set appropriate header
				self.resource.headers['Content-Location'] = self.location
				self.delivery = 'header'

			# data attribute is plain text, binary, or file-like object
			elif self.data:

				# if file-like object, set flag for api.http_request
				if isinstance(self.data, io.BufferedIOBase):
					logger.debug('detected file-like object')
					self.delivery = 'payload'

				# else, just bytes
				else:
					logger.debug('detected bytes')
					self.delivery = 'payload'
340916
def binary2pb(b, proto_id, proto_fmt_type):
    
    rsp = pb_map[proto_id]
    if rsp is None:
        return None
    if proto_fmt_type == ProtoFMT.Json:
        return json2pb(type(rsp), b.decode('utf-8'))
    elif proto_fmt_type == ProtoFMT.Protobuf:
        rsp = type(rsp)()
        # logger.debug((proto_id))
        if IS_PY2:
            rsp.ParseFromString(str(b))
        else:
            rsp.ParseFromString(b)
        return rsp
    else:
        raise Exception("binary2str: unknown proto format.")
12817
def _recv_sf(self, data):
        """"""
        self.rx_timer.cancel()
        if self.rx_state != ISOTP_IDLE:
            warning("RX state was reset because single frame was received")
            self.rx_state = ISOTP_IDLE

        length = six.indexbytes(data, 0) & 0xf
        if len(data) - 1 < length:
            return 1

        msg = data[1:1 + length]
        self.rx_queue.put(msg)
        for cb in self.rx_callbacks:
            cb(msg)
        self.call_release()
        return 0
673517
def _default_read_frame(self, *, frame=None, mpkit=None):
        
        from pcapkit.toolkit.default import (ipv4_reassembly, ipv6_reassembly,
                                             tcp_reassembly, tcp_traceflow)

        # read frame header
        if not self._flag_m:
            frame = Frame(self._ifile, num=self._frnum+1, proto=self._dlink,
                          layer=self._exlyr, protocol=self._exptl, nanosecond=self._nnsec)
            self._frnum += 1

        # verbose output
        if self._flag_v:
            print(f' - Frame {self._frnum:>3d}: {frame.protochain}')

        # write plist
        frnum = f'Frame {self._frnum}'
        if not self._flag_q:
            if self._flag_f:
                ofile = self._ofile(f'{self._ofnm}/{frnum}.{self._fext}')
                ofile(frame.info, name=frnum)
            else:
                self._ofile(frame.info, name=frnum)

        # record fragments
        if self._ipv4:
            flag, data = ipv4_reassembly(frame)
            if flag:
                self._reasm[0](data)  # pylint: disable=E1102
        if self._ipv6:
            flag, data = ipv6_reassembly(frame)
            if flag:
                self._reasm[1](data)  # pylint: disable=E1102
        if self._tcp:
            flag, data = tcp_reassembly(frame)
            if flag:
                self._reasm[2](data)  # pylint: disable=E1102

        # trace flows
        if self._flag_t:
            flag, data = tcp_traceflow(frame, data_link=self._dlink)
            if flag:
                self._trace(data)

        # record frames
        if self._exeng == 'pipeline':
            if self._flag_d:
                # frame._file = NotImplemented
                mpkit.frames[self._frnum] = frame
                # print(self._frnum, 'stored')
            mpkit.current += 1
        elif self._exeng == 'server':
            # record frames
            if self._flag_d:
                # frame._file = NotImplemented
                self._frame.append(frame)
                # print(self._frnum, 'stored')
            self._frnum += 1
        else:
            if self._flag_d:
                self._frame.append(frame)
            self._proto = frame.protochain.chain

        # return frame record
        return frame
432641
def binary(self):
        
        if isinstance(self.value, bytes):
            length = len(self.value)
            if length > 4294967295:
                raise OutputException('uint32 overflow')
            elif self.bits != 8:
                return (
                    b_chr(_TAG_BIT_BINARY_EXT) +
                    struct.pack(b'>I', length) +
                    b_chr(self.bits) + self.value
                )
            else:
                return (
                    b_chr(_TAG_BINARY_EXT) +
                    struct.pack(b'>I', length) +
                    self.value
                )
        else:
            raise OutputException('unknown binary type')
1245530
def serialize_output(output):
    
    if not ('value' in output and 'script_hex' in output):
        raise Exception('Invalid output')

    return ''.join([
        hexlify(struct.pack('<Q', output['value'])), # pack into 8 bites
        hexlify(variable_length_int(len(output['script_hex'])/2)),
        output['script_hex']
    ])
1252445
def write_frames(self, channel_id, frames_out):
        
        data_out = EMPTY_BUFFER
        for single_frame in frames_out:
            data_out += pamqp_frame.marshal(single_frame, channel_id)
        self.heartbeat.register_write()
        self._io.write_to_socket(data_out)