idx int64 0 252k | question stringlengths 48 5.28k | target stringlengths 5 1.23k |
|---|---|---|
248,200 | def parse ( cls , detail_string ) : split = detail_string . split ( ':' ) if len ( split ) != 4 : raise Exception ( 'invalid credentials' ) ltpk = binascii . unhexlify ( split [ 0 ] ) ltsk = binascii . unhexlify ( split [ 1 ] ) atv_id = binascii . unhexlify ( split [ 2 ] ) client_id = binascii . unhexlify ( split [ 3 ]... | Parse a string represention of Credentials . |
248,201 | def initialize ( self ) : self . _signing_key = SigningKey ( os . urandom ( 32 ) ) self . _auth_private = self . _signing_key . to_seed ( ) self . _auth_public = self . _signing_key . get_verifying_key ( ) . to_bytes ( ) self . _verify_private = curve25519 . Private ( secret = os . urandom ( 32 ) ) self . _verify_publi... | Initialize operation by generating new keys . |
248,202 | def verify1 ( self , credentials , session_pub_key , encrypted ) : self . _shared = self . _verify_private . get_shared_key ( curve25519 . Public ( session_pub_key ) , hashfunc = lambda x : x ) session_key = hkdf_expand ( 'Pair-Verify-Encrypt-Salt' , 'Pair-Verify-Encrypt-Info' , self . _shared ) chacha = chacha20 . Cha... | First verification step . |
248,203 | def verify2 ( self ) : output_key = hkdf_expand ( 'MediaRemote-Salt' , 'MediaRemote-Write-Encryption-Key' , self . _shared ) input_key = hkdf_expand ( 'MediaRemote-Salt' , 'MediaRemote-Read-Encryption-Key' , self . _shared ) log_binary ( _LOGGER , 'Keys' , Output = output_key , Input = input_key ) return output_key , i... | Last verification step . |
248,204 | def step1 ( self , pin ) : context = SRPContext ( 'Pair-Setup' , str ( pin ) , prime = constants . PRIME_3072 , generator = constants . PRIME_3072_GEN , hash_func = hashlib . sha512 ) self . _session = SRPClientSession ( context , binascii . hexlify ( self . _auth_private ) . decode ( ) ) | First pairing step . |
248,205 | def step2 ( self , atv_pub_key , atv_salt ) : pk_str = binascii . hexlify ( atv_pub_key ) . decode ( ) salt = binascii . hexlify ( atv_salt ) . decode ( ) self . _client_session_key , _ , _ = self . _session . process ( pk_str , salt ) if not self . _session . verify_proof ( self . _session . key_proof_hash ) : raise e... | Second pairing step . |
248,206 | def step3 ( self ) : ios_device_x = hkdf_expand ( 'Pair-Setup-Controller-Sign-Salt' , 'Pair-Setup-Controller-Sign-Info' , binascii . unhexlify ( self . _client_session_key ) ) self . _session_key = hkdf_expand ( 'Pair-Setup-Encrypt-Salt' , 'Pair-Setup-Encrypt-Info' , binascii . unhexlify ( self . _client_session_key ) ... | Third pairing step . |
248,207 | def step4 ( self , encrypted_data ) : chacha = chacha20 . Chacha20Cipher ( self . _session_key , self . _session_key ) decrypted_tlv_bytes = chacha . decrypt ( encrypted_data , nounce = 'PS-Msg06' . encode ( ) ) if not decrypted_tlv_bytes : raise Exception ( 'data decrypt failed' ) decrypted_tlv = tlv8 . read_tlv ( dec... | Last pairing step . |
248,208 | def hash_sha512 ( * indata ) : hasher = hashlib . sha512 ( ) for data in indata : if isinstance ( data , str ) : hasher . update ( data . encode ( 'utf-8' ) ) elif isinstance ( data , bytes ) : hasher . update ( data ) else : raise Exception ( 'invalid input data: ' + str ( data ) ) return hasher . digest ( ) | Create SHA512 hash for input arguments . |
248,209 | def aes_encrypt ( mode , aes_key , aes_iv , * data ) : encryptor = Cipher ( algorithms . AES ( aes_key ) , mode ( aes_iv ) , backend = default_backend ( ) ) . encryptor ( ) result = None for value in data : result = encryptor . update ( value ) encryptor . finalize ( ) return result , None if not hasattr ( encryptor , ... | Encrypt data with AES in specified mode . |
248,210 | def new_credentials ( ) : identifier = binascii . b2a_hex ( os . urandom ( 8 ) ) . decode ( ) . upper ( ) seed = binascii . b2a_hex ( os . urandom ( 32 ) ) return identifier , seed | Generate a new identifier and seed for authentication . |
248,211 | def initialize ( self , seed = None ) : self . seed = seed or os . urandom ( 32 ) signing_key = SigningKey ( self . seed ) verifying_key = signing_key . get_verifying_key ( ) self . _auth_private = signing_key . to_seed ( ) self . _auth_public = verifying_key . to_bytes ( ) log_binary ( _LOGGER , 'Authentication keys' ... | Initialize handler operation . |
248,212 | def verify1 ( self ) : self . _check_initialized ( ) self . _verify_private = curve25519 . Private ( secret = self . seed ) self . _verify_public = self . _verify_private . get_public ( ) log_binary ( _LOGGER , 'Verification keys' , Private = self . _verify_private . serialize ( ) , Public = self . _verify_public . ser... | First device verification step . |
248,213 | def verify2 ( self , atv_public_key , data ) : self . _check_initialized ( ) log_binary ( _LOGGER , 'Verify' , PublicSecret = atv_public_key , Data = data ) public = curve25519 . Public ( atv_public_key ) shared = self . _verify_private . get_shared_key ( public , hashfunc = lambda x : x ) log_binary ( _LOGGER , 'Share... | Last device verification step . |
248,214 | def step1 ( self , username , password ) : self . _check_initialized ( ) context = AtvSRPContext ( str ( username ) , str ( password ) , prime = constants . PRIME_2048 , generator = constants . PRIME_2048_GEN ) self . session = SRPClientSession ( context , binascii . hexlify ( self . _auth_private ) . decode ( ) ) | First authentication step . |
248,215 | def step2 ( self , pub_key , salt ) : self . _check_initialized ( ) pk_str = binascii . hexlify ( pub_key ) . decode ( ) salt = binascii . hexlify ( salt ) . decode ( ) self . client_session_key , _ , _ = self . session . process ( pk_str , salt ) _LOGGER . debug ( 'Client session key: %s' , self . client_session_key )... | Second authentication step . |
248,216 | def step3 ( self ) : self . _check_initialized ( ) session_key = binascii . unhexlify ( self . client_session_key ) aes_key = hash_sha512 ( 'Pair-Setup-AES-Key' , session_key ) [ 0 : 16 ] tmp = bytearray ( hash_sha512 ( 'Pair-Setup-AES-IV' , session_key ) [ 0 : 16 ] ) tmp [ - 1 ] = tmp [ - 1 ] + 1 aes_iv = bytes ( tmp ... | Last authentication step . |
248,217 | async def start_authentication ( self ) : _ , code = await self . http . post_data ( 'pair-pin-start' , headers = _AIRPLAY_HEADERS ) if code != 200 : raise DeviceAuthenticationError ( 'pair start failed' ) | Start the authentication process . |
248,218 | async def finish_authentication ( self , username , password ) : self . srp . step1 ( username , password ) data = await self . _send_plist ( 'step1' , method = 'pin' , user = username ) resp = plistlib . loads ( data ) pub_key , key_proof = self . srp . step2 ( resp [ 'pk' ] , resp [ 'salt' ] ) await self . _send_plis... | Finish authentication process . |
248,219 | async def verify_authed ( self ) : resp = await self . _send ( self . srp . verify1 ( ) , 'verify1' ) atv_public_secret = resp [ 0 : 32 ] data = resp [ 32 : ] await self . _send ( self . srp . verify2 ( atv_public_secret , data ) , 'verify2' ) return True | Verify if device is allowed to use AirPlau . |
248,220 | async def generate_credentials ( self ) : identifier , seed = new_credentials ( ) return '{0}:{1}' . format ( identifier , seed . decode ( ) . upper ( ) ) | Create new credentials for authentication . |
248,221 | async def load_credentials ( self , credentials ) : split = credentials . split ( ':' ) self . identifier = split [ 0 ] self . srp . initialize ( binascii . unhexlify ( split [ 1 ] ) ) _LOGGER . debug ( 'Loaded AirPlay credentials: %s' , credentials ) | Load existing credentials . |
248,222 | def enable_encryption ( self , output_key , input_key ) : self . _chacha = chacha20 . Chacha20Cipher ( output_key , input_key ) | Enable encryption with the specified keys . |
248,223 | def connect ( self ) : return self . loop . create_connection ( lambda : self , self . host , self . port ) | Connect to device . |
248,224 | def close ( self ) : if self . _transport : self . _transport . close ( ) self . _transport = None self . _chacha = None | Close connection to device . |
248,225 | def send ( self , message ) : serialized = message . SerializeToString ( ) log_binary ( _LOGGER , '>> Send' , Data = serialized ) if self . _chacha : serialized = self . _chacha . encrypt ( serialized ) log_binary ( _LOGGER , '>> Send' , Encrypted = serialized ) data = write_variant ( len ( serialized ) ) + serialized ... | Send message to device . |
248,226 | async def get_data ( self , path , headers = None , timeout = None ) : url = self . base_url + path _LOGGER . debug ( 'GET URL: %s' , url ) resp = None try : resp = await self . _session . get ( url , headers = headers , timeout = DEFAULT_TIMEOUT if timeout is None else timeout ) if resp . content_length is not None : ... | Perform a GET request . |
248,227 | async def post_data ( self , path , data = None , headers = None , timeout = None ) : url = self . base_url + path _LOGGER . debug ( 'POST URL: %s' , url ) self . _log_data ( data , False ) resp = None try : resp = await self . _session . post ( url , headers = headers , data = data , timeout = DEFAULT_TIMEOUT if timeo... | Perform a POST request . |
248,228 | def read_uint ( data , start , length ) : return int . from_bytes ( data [ start : start + length ] , byteorder = 'big' ) | Extract a uint from a position in a sequence . |
248,229 | def read_bplist ( data , start , length ) : return plistlib . loads ( data [ start : start + length ] , fmt = plistlib . FMT_BINARY ) | Extract a binary plist from a position in a sequence . |
248,230 | def raw_tag ( name , value ) : return name . encode ( 'utf-8' ) + len ( value ) . to_bytes ( 4 , byteorder = 'big' ) + value | Create a DMAP tag with raw data . |
248,231 | def string_tag ( name , value ) : return name . encode ( 'utf-8' ) + len ( value ) . to_bytes ( 4 , byteorder = 'big' ) + value . encode ( 'utf-8' ) | Create a DMAP tag with string data . |
248,232 | def create ( message_type , priority = 0 ) : message = protobuf . ProtocolMessage ( ) message . type = message_type message . priority = priority return message | Create a ProtocolMessage . |
248,233 | def device_information ( name , identifier ) : message = create ( protobuf . DEVICE_INFO_MESSAGE ) info = message . inner ( ) info . uniqueIdentifier = identifier info . name = name info . localizedModelName = 'iPhone' info . systemBuildVersion = '14G60' info . applicationBundleIdentifier = 'com.apple.TVRemote' info . ... | Create a new DEVICE_INFO_MESSAGE . |
248,234 | def set_connection_state ( ) : message = create ( protobuf . ProtocolMessage . SET_CONNECTION_STATE_MESSAGE ) message . inner ( ) . state = protobuf . SetConnectionStateMessage . Connected return message | Create a new SET_CONNECTION_STATE . |
248,235 | def crypto_pairing ( pairing_data ) : message = create ( protobuf . CRYPTO_PAIRING_MESSAGE ) crypto = message . inner ( ) crypto . status = 0 crypto . pairingData = tlv8 . write_tlv ( pairing_data ) return message | Create a new CRYPTO_PAIRING_MESSAGE . |
248,236 | def client_updates_config ( artwork = True , now_playing = True , volume = True , keyboard = True ) : message = create ( protobuf . CLIENT_UPDATES_CONFIG_MESSAGE ) config = message . inner ( ) config . artworkUpdates = artwork config . nowPlayingUpdates = now_playing config . volumeUpdates = volume config . keyboardUpd... | Create a new CLIENT_UPDATES_CONFIG_MESSAGE . |
248,237 | def register_hid_device ( screen_width , screen_height , absolute = False , integrated_display = False ) : message = create ( protobuf . REGISTER_HID_DEVICE_MESSAGE ) descriptor = message . inner ( ) . deviceDescriptor descriptor . absolute = 1 if absolute else 0 descriptor . integratedDisplay = 1 if integrated_display... | Create a new REGISTER_HID_DEVICE_MESSAGE . |
248,238 | def send_packed_virtual_touch_event ( xpos , ypos , phase , device_id , finger ) : message = create ( protobuf . SEND_PACKED_VIRTUAL_TOUCH_EVENT_MESSAGE ) event = message . inner ( ) event . data = xpos . to_bytes ( 2 , byteorder = 'little' ) event . data += ypos . to_bytes ( 2 , byteorder = 'little' ) event . data += ... | Create a new WAKE_DEVICE_MESSAGE . |
248,239 | def send_hid_event ( use_page , usage , down ) : message = create ( protobuf . SEND_HID_EVENT_MESSAGE ) event = message . inner ( ) abstime = binascii . unhexlify ( b'438922cf08020000' ) data = use_page . to_bytes ( 2 , byteorder = 'big' ) data += usage . to_bytes ( 2 , byteorder = 'big' ) data += ( 1 if down else 0 ) ... | Create a new SEND_HID_EVENT_MESSAGE . |
248,240 | def command ( cmd ) : message = create ( protobuf . SEND_COMMAND_MESSAGE ) send_command = message . inner ( ) send_command . command = cmd return message | Playback command request . |
248,241 | def repeat ( mode ) : message = command ( protobuf . CommandInfo_pb2 . ChangeShuffleMode ) send_command = message . inner ( ) send_command . options . externalPlayerCommand = True send_command . options . repeatMode = mode return message | Change repeat mode of current player . |
248,242 | def shuffle ( enable ) : message = command ( protobuf . CommandInfo_pb2 . ChangeShuffleMode ) send_command = message . inner ( ) send_command . options . shuffleMode = 3 if enable else 1 return message | Change shuffle mode of current player . |
248,243 | def seek_to_position ( position ) : message = command ( protobuf . CommandInfo_pb2 . SeekToPlaybackPosition ) send_command = message . inner ( ) send_command . options . playbackPosition = position return message | Seek to an absolute position in stream . |
248,244 | async def pair_with_device ( loop ) : my_zeroconf = Zeroconf ( ) details = conf . AppleTV ( '127.0.0.1' , 'Apple TV' ) details . add_service ( conf . DmapService ( 'login_id' ) ) atv = pyatv . connect_to_apple_tv ( details , loop ) atv . pairing . pin ( PIN_CODE ) await atv . pairing . start ( zeroconf = my_zeroconf , ... | Make it possible to pair with device . |
248,245 | def read_variant ( variant ) : result = 0 cnt = 0 for data in variant : result |= ( data & 0x7f ) << ( 7 * cnt ) cnt += 1 if not data & 0x80 : return result , variant [ cnt : ] raise Exception ( 'invalid variant' ) | Read and parse a binary protobuf variant value . |
248,246 | async def print_what_is_playing ( loop ) : details = conf . AppleTV ( ADDRESS , NAME ) details . add_service ( conf . DmapService ( HSGID ) ) print ( 'Connecting to {}' . format ( details . address ) ) atv = pyatv . connect_to_apple_tv ( details , loop ) try : print ( ( await atv . metadata . playing ( ) ) ) finally : ... | Connect to device and print what is playing . |
248,247 | def add_listener ( self , listener , message_type , data = None , one_shot = False ) : lst = self . _one_shots if one_shot else self . _listeners if message_type not in lst : lst [ message_type ] = [ ] lst [ message_type ] . append ( Listener ( listener , data ) ) | Add a listener that will receice incoming messages . |
248,248 | async def start ( self ) : if self . connection . connected : return await self . connection . connect ( ) if self . service . device_credentials : self . srp . pairing_id = Credentials . parse ( self . service . device_credentials ) . client_id msg = messages . device_information ( 'pyatv' , self . srp . pairing_id . ... | Connect to device and listen to incoming messages . |
248,249 | def stop ( self ) : if self . _outstanding : _LOGGER . warning ( 'There were %d outstanding requests' , len ( self . _outstanding ) ) self . _initial_message_sent = False self . _outstanding = { } self . _one_shots = { } self . connection . close ( ) | Disconnect from device . |
248,250 | async def send_and_receive ( self , message , generate_identifier = True , timeout = 5 ) : await self . _connect_and_encrypt ( ) if generate_identifier : identifier = str ( uuid . uuid4 ( ) ) message . identifier = identifier else : identifier = 'type_' + str ( message . type ) self . connection . send ( message ) retu... | Send a message and wait for a response . |
248,251 | async def playstatus ( self , use_revision = False , timeout = None ) : cmd_url = _PSU_CMD . format ( self . playstatus_revision if use_revision else 0 ) resp = await self . daap . get ( cmd_url , timeout = timeout ) self . playstatus_revision = parser . first ( resp , 'cmst' , 'cmsr' ) return resp | Request raw data about what is currently playing . |
248,252 | def ctrl_int_cmd ( self , cmd ) : cmd_url = 'ctrl-int/1/{}?[AUTH]&prompt-id=0' . format ( cmd ) return self . daap . post ( cmd_url ) | Perform a ctrl - int command . |
248,253 | def controlprompt_cmd ( self , cmd ) : data = tags . string_tag ( 'cmbe' , cmd ) + tags . uint8_tag ( 'cmcc' , 0 ) return self . daap . post ( _CTRL_PROMPT_CMD , data = data ) | Perform a controlpromptentry command . |
248,254 | async def up ( self ) : await self . _send_commands ( self . _move ( 'Down' , 0 , 20 , 275 ) , self . _move ( 'Move' , 1 , 20 , 270 ) , self . _move ( 'Move' , 2 , 20 , 265 ) , self . _move ( 'Move' , 3 , 20 , 260 ) , self . _move ( 'Move' , 4 , 20 , 255 ) , self . _move ( 'Move' , 5 , 20 , 250 ) , self . _move ( 'Up' ... | Press key up . |
248,255 | async def down ( self ) : await self . _send_commands ( self . _move ( 'Down' , 0 , 20 , 250 ) , self . _move ( 'Move' , 1 , 20 , 255 ) , self . _move ( 'Move' , 2 , 20 , 260 ) , self . _move ( 'Move' , 3 , 20 , 265 ) , self . _move ( 'Move' , 4 , 20 , 270 ) , self . _move ( 'Move' , 5 , 20 , 275 ) , self . _move ( 'Up... | Press key down . |
248,256 | async def left ( self ) : await self . _send_commands ( self . _move ( 'Down' , 0 , 75 , 100 ) , self . _move ( 'Move' , 1 , 70 , 100 ) , self . _move ( 'Move' , 3 , 65 , 100 ) , self . _move ( 'Move' , 4 , 60 , 100 ) , self . _move ( 'Move' , 5 , 55 , 100 ) , self . _move ( 'Move' , 6 , 50 , 100 ) , self . _move ( 'Up... | Press key left . |
248,257 | async def right ( self ) : await self . _send_commands ( self . _move ( 'Down' , 0 , 50 , 100 ) , self . _move ( 'Move' , 1 , 55 , 100 ) , self . _move ( 'Move' , 3 , 60 , 100 ) , self . _move ( 'Move' , 4 , 65 , 100 ) , self . _move ( 'Move' , 5 , 70 , 100 ) , self . _move ( 'Move' , 6 , 75 , 100 ) , self . _move ( 'U... | Press key right . |
248,258 | def set_position ( self , pos ) : time_in_ms = int ( pos ) * 1000 return self . apple_tv . set_property ( 'dacp.playingtime' , time_in_ms ) | Seek in the current playing media . |
248,259 | async def authenticate_with_device ( atv ) : credentials = await atv . airplay . generate_credentials ( ) await atv . airplay . load_credentials ( credentials ) try : await atv . airplay . start_authentication ( ) pin = input ( 'PIN Code: ' ) await atv . airplay . finish_authentication ( pin ) print ( 'Credentials: {0}... | Perform device authentication and print credentials . |
248,260 | def encrypt ( self , data , nounce = None ) : if nounce is None : nounce = self . _out_counter . to_bytes ( length = 8 , byteorder = 'little' ) self . _out_counter += 1 return self . _enc_out . seal ( b'\x00\x00\x00\x00' + nounce , data , bytes ( ) ) | Encrypt data with counter or specified nounce . |
248,261 | def decrypt ( self , data , nounce = None ) : if nounce is None : nounce = self . _in_counter . to_bytes ( length = 8 , byteorder = 'little' ) self . _in_counter += 1 decrypted = self . _enc_in . open ( b'\x00\x00\x00\x00' + nounce , data , bytes ( ) ) if not decrypted : raise Exception ( 'data decrypt failed' ) return... | Decrypt data with counter or specified nounce . |
248,262 | def auto_connect ( handler , timeout = 5 , not_found = None , event_loop = None ) : async def _handle ( loop ) : atvs = await pyatv . scan_for_apple_tvs ( loop , timeout = timeout , abort_on_found = True ) if atvs : atv = pyatv . connect_to_apple_tv ( atvs [ 0 ] , loop ) try : await handler ( atv ) finally : await atv ... | Short method for connecting to a device . |
248,263 | async def login ( self ) : def _login_request ( ) : return self . http . get_data ( self . _mkurl ( 'login?[AUTH]&hasFP=1' , session = False , login_id = True ) , headers = _DMAP_HEADERS ) resp = await self . _do ( _login_request , is_login = True ) self . _session_id = parser . first ( resp , 'mlog' , 'mlid' ) _LOGGER... | Login to Apple TV using specified login id . |
248,264 | async def get ( self , cmd , daap_data = True , timeout = None , ** args ) : def _get_request ( ) : return self . http . get_data ( self . _mkurl ( cmd , * args ) , headers = _DMAP_HEADERS , timeout = timeout ) await self . _assure_logged_in ( ) return await self . _do ( _get_request , is_daap = daap_data ) | Perform a DAAP GET command . |
248,265 | def get_url ( self , cmd , ** args ) : return self . http . base_url + self . _mkurl ( cmd , * args ) | Expand the request URL for a request . |
248,266 | async def post ( self , cmd , data = None , timeout = None , ** args ) : def _post_request ( ) : headers = copy ( _DMAP_HEADERS ) headers [ 'Content-Type' ] = 'application/x-www-form-urlencoded' return self . http . post_data ( self . _mkurl ( cmd , * args ) , data = data , headers = headers , timeout = timeout ) await... | Perform DAAP POST command with optional data . |
248,267 | def set_repeat ( self , repeat_mode ) : if int ( repeat_mode ) == const . REPEAT_STATE_OFF : state = 1 elif int ( repeat_mode ) == const . REPEAT_STATE_ALL : state = 2 elif int ( repeat_mode ) == const . REPEAT_STATE_TRACK : state = 3 else : raise ValueError ( 'Invalid repeat mode: ' + str ( repeat_mode ) ) return self... | Change repeat mode . |
248,268 | def genre ( self ) : if self . _metadata : from pyatv . mrp . protobuf import ContentItem_pb2 transaction = ContentItem_pb2 . ContentItem ( ) transaction . ParseFromString ( self . _metadata ) | Genre of the currently playing song . |
248,269 | def total_time ( self ) : now_playing = self . _setstate . nowPlayingInfo if now_playing . HasField ( 'duration' ) : return int ( now_playing . duration ) return None | Total play time in seconds . |
248,270 | def shuffle ( self ) : info = self . _get_command_info ( CommandInfo_pb2 . ChangeShuffleMode ) return None if info is None else info . shuffleMode | If shuffle is enabled or not . |
248,271 | def repeat ( self ) : info = self . _get_command_info ( CommandInfo_pb2 . ChangeRepeatMode ) return None if info is None else info . repeatMode | Repeat mode . |
248,272 | async def playing ( self ) : if self . _setstate is None : await self . protocol . start ( ) if self . _setstate is None : return MrpPlaying ( protobuf . SetStateMessage ( ) , None ) return MrpPlaying ( self . _setstate , self . _nowplaying ) | Return what is currently playing . |
248,273 | async def stop ( self , ** kwargs ) : if not self . _pin_code : raise Exception ( 'no pin given' ) self . service . device_credentials = await self . pairing_procedure . finish_pairing ( self . _pin_code ) | Stop pairing process . |
248,274 | def read_tlv ( data ) : def _parse ( data , pos , size , result = None ) : if result is None : result = { } if pos >= size : return result tag = str ( data [ pos ] ) length = data [ pos + 1 ] value = data [ pos + 2 : pos + 2 + length ] if tag in result : result [ tag ] += value else : result [ tag ] = value return _par... | Parse TLV8 bytes into a dict . |
248,275 | def write_tlv ( data ) : tlv = b'' for key , value in data . items ( ) : tag = bytes ( [ int ( key ) ] ) length = len ( value ) pos = 0 while pos < len ( value ) : size = min ( length , 255 ) tlv += tag tlv += bytes ( [ size ] ) tlv += value [ pos : pos + size ] pos += size length -= size return tlv | Convert a dict to TLV8 bytes . |
248,276 | def comment ( value , comment_text ) : if isinstance ( value , Doc ) : return comment_doc ( value , comment_text ) return comment_value ( value , comment_text ) | Annotates a value or a Doc with a comment . |
248,277 | def register_pretty ( type = None , predicate = None ) : if type is None and predicate is None : raise ValueError ( "You must provide either the 'type' or 'predicate' argument." ) if type is not None and predicate is not None : raise ValueError ( "You must provide either the 'type' or 'predicate' argument," "but not bo... | Returns a decorator that registers the decorated function as the pretty printer for instances of type . |
248,278 | def commentdoc ( text ) : if not text : raise ValueError ( 'Expected non-empty comment str, got {}' . format ( repr ( text ) ) ) commentlines = [ ] for line in text . splitlines ( ) : alternating_words_ws = list ( filter ( None , WHITESPACE_PATTERN_TEXT . split ( line ) ) ) starts_with_whitespace = bool ( WHITESPACE_PA... | Returns a Doc representing a comment text . text is treated as words and any whitespace may be used to break the comment to multiple lines . |
248,279 | def build_fncall ( ctx , fndoc , argdocs = ( ) , kwargdocs = ( ) , hug_sole_arg = False , trailing_comment = None , ) : if callable ( fndoc ) : fndoc = general_identifier ( fndoc ) has_comment = bool ( trailing_comment ) argdocs = list ( argdocs ) kwargdocs = list ( kwargdocs ) kwargdocs = [ ( comment_doc ( concat ( [ ... | Builds a doc that looks like a function call from docs that represent the function arguments and keyword arguments . |
248,280 | def assoc ( self , key , value ) : return self . _replace ( user_ctx = { ** self . user_ctx , key : value , } ) | Return a modified PrettyContext with key set to value |
248,281 | def align ( doc ) : validate_doc ( doc ) def evaluator ( indent , column , page_width , ribbon_width ) : return Nest ( column - indent , doc ) return contextual ( evaluator ) | Aligns each new line in doc with the first new line . |
248,282 | def smart_fitting_predicate ( page_width , ribbon_frac , min_nesting_level , max_width , triplestack ) : chars_left = max_width while chars_left >= 0 : if not triplestack : return True indent , mode , doc = triplestack . pop ( ) if doc is NIL : continue elif isinstance ( doc , str ) : chars_left -= len ( doc ) elif isi... | Lookahead until the last doc at the current indentation level . Pretty but not as fast . |
248,283 | def set_default_style ( style ) : global default_style if style == 'dark' : style = default_dark_style elif style == 'light' : style = default_light_style if not issubclass ( style , Style ) : raise TypeError ( "style must be a subclass of pygments.styles.Style or " "one of 'dark', 'light'. Got {}" . format ( repr ( st... | Sets default global style to be used by prettyprinter . cpprint . |
248,284 | def intersperse ( x , ys ) : it = iter ( ys ) try : y = next ( it ) except StopIteration : return yield y for y in it : yield x yield y | Returns an iterable where x is inserted between each element of ys |
248,285 | def pprint ( object , stream = _UNSET_SENTINEL , indent = _UNSET_SENTINEL , width = _UNSET_SENTINEL , depth = _UNSET_SENTINEL , * , compact = False , ribbon_width = _UNSET_SENTINEL , max_seq_len = _UNSET_SENTINEL , sort_dict_keys = _UNSET_SENTINEL , end = '\n' ) : sdocs = python_to_sdocs ( object , ** _merge_defaults (... | Pretty print a Python value object to stream which defaults to sys . stdout . The output will not be colored . |
248,286 | def cpprint ( object , stream = _UNSET_SENTINEL , indent = _UNSET_SENTINEL , width = _UNSET_SENTINEL , depth = _UNSET_SENTINEL , * , compact = False , ribbon_width = _UNSET_SENTINEL , max_seq_len = _UNSET_SENTINEL , sort_dict_keys = _UNSET_SENTINEL , style = None , end = '\n' ) : sdocs = python_to_sdocs ( object , ** _... | Pretty print a Python value object to stream which defaults to sys . stdout . The output will be colored and syntax highlighted . |
248,287 | def install_extras ( include = ALL_EXTRAS , * , exclude = EMPTY_SET , raise_on_error = False , warn_on_error = True ) : include = set ( include ) exclude = set ( exclude ) unexisting_extras = ( include | exclude ) - ALL_EXTRAS if unexisting_extras : raise ValueError ( "The following extras don't exist: {}" . format ( '... | Installs extras . |
248,288 | def set_default_config ( * , style = _UNSET_SENTINEL , max_seq_len = _UNSET_SENTINEL , width = _UNSET_SENTINEL , ribbon_width = _UNSET_SENTINEL , depth = _UNSET_SENTINEL , sort_dict_keys = _UNSET_SENTINEL ) : global _default_config if style is not _UNSET_SENTINEL : set_default_style ( style ) new_defaults = { ** _defau... | Sets the default configuration values used when calling pprint cpprint or pformat if those values weren t explicitly provided . Only overrides the values provided in the keyword arguments . |
248,289 | def package_maven ( ) : if not os . getenv ( 'JAVA_HOME' ) : os . environ [ 'JAVA_HOME' ] = jdk_home_dir mvn_goal = 'package' log . info ( "Executing Maven goal '" + mvn_goal + "'" ) code = subprocess . call ( [ 'mvn' , 'clean' , mvn_goal , '-DskipTests' ] , shell = platform . system ( ) == 'Windows' ) if code : exit (... | Run maven package lifecycle |
248,290 | def _write_jpy_config ( target_dir = None , install_dir = None ) : if not target_dir : target_dir = _build_dir ( ) args = [ sys . executable , os . path . join ( target_dir , 'jpyutil.py' ) , '--jvm_dll' , jvm_dll_file , '--java_home' , jdk_home_dir , '--log_level' , 'DEBUG' , '--req_java' , '--req_py' ] if install_dir... | Write out a well - formed jpyconfig . properties file for easier Java integration in a given location . |
248,291 | def _get_module_path ( name , fail = False , install_path = None ) : import imp module = imp . find_module ( name ) if not module and fail : raise RuntimeError ( "can't find module '" + name + "'" ) path = module [ 1 ] if not path and fail : raise RuntimeError ( "module '" + name + "' is missing a file path" ) if insta... | Find the path to the jpy jni modules . |
248,292 | def init_jvm ( java_home = None , jvm_dll = None , jvm_maxmem = None , jvm_classpath = None , jvm_properties = None , jvm_options = None , config_file = None , config = None ) : if not config : config = _get_python_api_config ( config_file = config_file ) cdll = preload_jvm_dll ( jvm_dll_file = jvm_dll , java_home_dir ... | Creates a configured Java virtual machine which will be used by jpy . |
248,293 | def run_lint_command ( ) : lint , app_dir , lint_result , ignore_layouts = parse_args ( ) if not lint_result : if not distutils . spawn . find_executable ( lint ) : raise Exception ( '`%s` executable could not be found and path to lint result not specified. See --help' % lint ) lint_result = os . path . join ( app_dir ... | Run lint command in the shell and save results to lint - result . xml |
248,294 | def parse_lint_result ( lint_result_path , manifest_path ) : unused_string_pattern = re . compile ( 'The resource `R\.string\.([^`]+)` appears to be unused' ) mainfest_string_refs = get_manifest_string_refs ( manifest_path ) root = etree . parse ( lint_result_path ) . getroot ( ) issues = [ ] for issue_xml in root . fi... | Parse lint - result . xml and create Issue for every problem found except unused strings referenced in AndroidManifest |
248,295 | def remove_resource_file ( issue , filepath , ignore_layouts ) : if os . path . exists ( filepath ) and ( ignore_layouts is False or issue . elements [ 0 ] [ 0 ] != 'layout' ) : print ( 'removing resource: {0}' . format ( filepath ) ) os . remove ( os . path . abspath ( filepath ) ) | Delete a file from the filesystem |
248,296 | def remove_resource_value ( issue , filepath ) : if os . path . exists ( filepath ) : for element in issue . elements : print ( 'removing {0} from resource {1}' . format ( element , filepath ) ) parser = etree . XMLParser ( remove_blank_text = False , remove_comments = False , remove_pis = False , strip_cdata = False ,... | Read an xml file and remove an element which is unused then save the file back to the filesystem |
248,297 | def remove_unused_resources ( issues , app_dir , ignore_layouts ) : for issue in issues : filepath = os . path . join ( app_dir , issue . filepath ) if issue . remove_file : remove_resource_file ( issue , filepath , ignore_layouts ) else : remove_resource_value ( issue , filepath ) | Remove the file or the value inside the file depending if the whole file is unused or not . |
248,298 | def _encryption_context_hash ( hasher , encryption_context ) : serialized_encryption_context = serialize_encryption_context ( encryption_context ) hasher . update ( serialized_encryption_context ) return hasher . finalize ( ) | Generates the expected hash for the provided encryption context . |
248,299 | def build_encryption_materials_cache_key ( partition , request ) : if request . algorithm is None : _algorithm_info = b"\x00" else : _algorithm_info = b"\x01" + request . algorithm . id_as_bytes ( ) hasher = _new_cache_key_hasher ( ) _partition_hash = _partition_name_hash ( hasher = hasher . copy ( ) , partition_name =... | Generates a cache key for an encrypt request . |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.