idx
int64
0
251k
question
stringlengths
53
3.53k
target
stringlengths
5
1.23k
len_question
int64
20
893
len_target
int64
3
238
247,200
def extract_message_info ( ) : base_path = BASE_PACKAGE . replace ( '.' , '/' ) filename = os . path . join ( base_path , 'ProtocolMessage.proto' ) with open ( filename , 'r' ) as file : types_found = False for line in file : stripped = line . lstrip ( ) . rstrip ( ) # Look for the Type enum if stripped == 'enum Type {...
Get information about all messages of interest .
233
8
247,201
def main ( ) : message_names = set ( ) packages = [ ] messages = [ ] extensions = [ ] constants = [ ] # Extract everything needed to generate output file for info in extract_message_info ( ) : message_names . add ( info . title ) packages . append ( 'from {0} import {1}' . format ( BASE_PACKAGE , info . module ) ) mess...
Script starts somewhere around here .
343
6
247,202
def hkdf_expand ( salt , info , shared_secret ) : from cryptography . hazmat . primitives import hashes from cryptography . hazmat . primitives . kdf . hkdf import HKDF from cryptography . hazmat . backends import default_backend hkdf = HKDF ( algorithm = hashes . SHA512 ( ) , length = 32 , salt = salt . encode ( ) , i...
Derive encryption keys from shared secret .
114
8
247,203
def parse ( cls , detail_string ) : split = detail_string . split ( ':' ) if len ( split ) != 4 : raise Exception ( 'invalid credentials' ) # TODO: other exception ltpk = binascii . unhexlify ( split [ 0 ] ) ltsk = binascii . unhexlify ( split [ 1 ] ) atv_id = binascii . unhexlify ( split [ 2 ] ) client_id = binascii ....
Parse a string represention of Credentials .
144
12
247,204
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 .
140
8
247,205
def verify1 ( self , credentials , session_pub_key , encrypted ) : # No additional hashing used 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 . _sha...
First verification step .
409
4
247,206
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 .
109
4
247,207
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 .
93
4
247,208
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 .
204
4
247,209
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 .
308
4
247,210
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' ) # TODO: new exception decrypted_tlv =...
Last pairing step .
292
4
247,211
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 .
95
8
247,212
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 .
105
9
247,213
def new_credentials ( ) : identifier = binascii . b2a_hex ( os . urandom ( 8 ) ) . decode ( ) . upper ( ) seed = binascii . b2a_hex ( os . urandom ( 32 ) ) # Corresponds to private key return identifier , seed
Generate a new identifier and seed for authentication .
69
10
247,214
def initialize ( self , seed = None ) : self . seed = seed or os . urandom ( 32 ) # Generate new seed if not provided 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_binar...
Initialize handler operation .
123
5
247,215
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 .
143
5
247,216
def verify2 ( self , atv_public_key , data ) : self . _check_initialized ( ) log_binary ( _LOGGER , 'Verify' , PublicSecret = atv_public_key , Data = data ) # Generate a shared secret key public = curve25519 . Public ( atv_public_key ) shared = self . _verify_private . get_shared_key ( public , hashfunc = lambda x : x ...
Last device verification step .
351
5
247,217
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 .
91
4
247,218
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 .
222
4
247,219
def step3 ( self ) : self . _check_initialized ( ) # TODO: verify: self.client_session_key same as self.session.key_b64()? 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' , sessio...
Last authentication step .
256
4
247,220
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 .
58
5
247,221
async def finish_authentication ( self , username , password ) : # Step 1 self . srp . step1 ( username , password ) data = await self . _send_plist ( 'step1' , method = 'pin' , user = username ) resp = plistlib . loads ( data ) # Step 2 pub_key , key_proof = self . srp . step2 ( resp [ 'pk' ] , resp [ 'salt' ] ) await...
Finish authentication process .
194
4
247,222
async def verify_authed ( self ) : resp = await self . _send ( self . srp . verify1 ( ) , 'verify1' ) atv_public_secret = resp [ 0 : 32 ] data = resp [ 32 : ] # TODO: what is this? await self . _send ( self . srp . verify2 ( atv_public_secret , data ) , 'verify2' ) return True
Verify if device is allowed to use AirPlau .
95
12
247,223
async def generate_credentials ( self ) : identifier , seed = new_credentials ( ) return '{0}:{1}' . format ( identifier , seed . decode ( ) . upper ( ) )
Create new credentials for authentication .
47
6
247,224
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 .
73
4
247,225
def enable_encryption ( self , output_key , input_key ) : self . _chacha = chacha20 . Chacha20Cipher ( output_key , input_key )
Enable encryption with the specified keys .
41
7
247,226
def connect ( self ) : return self . loop . create_connection ( lambda : self , self . host , self . port )
Connect to device .
27
4
247,227
def close ( self ) : if self . _transport : self . _transport . close ( ) self . _transport = None self . _chacha = None
Close connection to device .
36
5
247,228
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 .
123
5
247,229
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 .
147
6
247,230
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 .
179
6
247,231
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 .
35
11
247,232
def read_bplist ( data , start , length ) : # TODO: pylint doesn't find FMT_BINARY, why? # pylint: disable=no-member return plistlib . loads ( data [ start : start + length ] , fmt = plistlib . FMT_BINARY )
Extract a binary plist from a position in a sequence .
72
13
247,233
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 .
42
9
247,234
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 .
51
9
247,235
def create ( message_type , priority = 0 ) : message = protobuf . ProtocolMessage ( ) message . type = message_type message . priority = priority return message
Create a ProtocolMessage .
36
5
247,236
def device_information ( name , identifier ) : # pylint: disable=no-member message = create ( protobuf . DEVICE_INFO_MESSAGE ) info = message . inner ( ) info . uniqueIdentifier = identifier info . name = name info . localizedModelName = 'iPhone' info . systemBuildVersion = '14G60' info . applicationBundleIdentifier = ...
Create a new DEVICE_INFO_MESSAGE .
129
13
247,237
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 .
54
11
247,238
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 .
64
16
247,239
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 .
89
17
247,240
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 .
101
17
247,241
def send_packed_virtual_touch_event ( xpos , ypos , phase , device_id , finger ) : message = create ( protobuf . SEND_PACKED_VIRTUAL_TOUCH_EVENT_MESSAGE ) event = message . inner ( ) # The packed version of VirtualTouchEvent contains X, Y, phase, deviceID # and finger stored as a byte array. Each value is written as 16...
Create a new WAKE_DEVICE_MESSAGE .
204
14
247,242
def send_hid_event ( use_page , usage , down ) : message = create ( protobuf . SEND_HID_EVENT_MESSAGE ) event = message . inner ( ) # TODO: This should be generated somehow. I guess it's mach AbsoluteTime # which is tricky to generate. The device does not seem to care much about # the value though, so hardcode somethin...
Create a new SEND_HID_EVENT_MESSAGE .
266
17
247,243
def command ( cmd ) : message = create ( protobuf . SEND_COMMAND_MESSAGE ) send_command = message . inner ( ) send_command . command = cmd return message
Playback command request .
44
5
247,244
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 .
57
7
247,245
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 .
50
7
247,246
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 .
51
9
247,247
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 .
226
8
247,248
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 .
69
11
247,249
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 .
112
9
247,250
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 .
81
10
247,251
async def start ( self ) : if self . connection . connected : return await self . connection . connect ( ) # In case credentials have been given externally (i.e. not by pairing # with a device), then use that client id if self . service . device_credentials : self . srp . pairing_id = Credentials . parse ( self . servi...
Connect to device and listen to incoming messages .
400
9
247,252
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 .
71
5
247,253
async def send_and_receive ( self , message , generate_identifier = True , timeout = 5 ) : await self . _connect_and_encrypt ( ) # Some messages will respond with the same identifier as used in the # corresponding request. Others will not and one example is the crypto # message (for pairing). They will never include an...
Send a message and wait for a response .
192
9
247,254
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 .
92
9
247,255
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 .
56
9
247,256
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 .
65
9
247,257
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 .
129
4
247,258
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 .
129
4
247,259
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 .
129
4
247,260
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 .
129
4
247,261
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 .
48
8
247,262
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 .
127
8
247,263
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 .
87
10
247,264
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' ) # TODO...
Decrypt data with counter or specified nounce .
115
10
247,265
def auto_connect ( handler , timeout = 5 , not_found = None , event_loop = None ) : # A coroutine is used so we can connect to the device while being inside # the event loop async def _handle ( loop ) : atvs = await pyatv . scan_for_apple_tvs ( loop , timeout = timeout , abort_on_found = True ) # Take the first device ...
Short method for connecting to a device .
184
8
247,266
async def login ( self ) : # Do not use session.get_data(...) in login as that would end up in # an infinte loop. 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 , i...
Login to Apple TV using specified login id .
165
9
247,267
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 .
102
8
247,268
def get_url ( self , cmd , * * args ) : return self . http . base_url + self . _mkurl ( cmd , * args )
Expand the request URL for a request .
34
9
247,269
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 ) awai...
Perform DAAP POST command with optional data .
121
10
247,270
def set_repeat ( self , repeat_mode ) : # TODO: extract to convert module 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: ' +...
Change repeat mode .
120
4
247,271
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 .
54
8
247,272
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 .
45
6
247,273
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 .
39
7
247,274
def repeat ( self ) : info = self . _get_command_info ( CommandInfo_pb2 . ChangeRepeatMode ) return None if info is None else info . repeatMode
Repeat mode .
38
3
247,275
async def playing ( self ) : # TODO: This is hack-ish if self . _setstate is None : await self . protocol . start ( ) # No SET_STATE_MESSAGE received yet, use default if self . _setstate is None : return MrpPlaying ( protobuf . SetStateMessage ( ) , None ) return MrpPlaying ( self . _setstate , self . _nowplaying )
Return what is currently playing .
92
6
247,276
async def stop ( self , * * kwargs ) : if not self . _pin_code : raise Exception ( 'no pin given' ) # TODO: new exception self . service . device_credentials = await self . pairing_procedure . finish_pairing ( self . _pin_code )
Stop pairing process .
69
4
247,277
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 # value > 255 is split up else : result [...
Parse TLV8 bytes into a dict .
126
10
247,278
def write_tlv ( data ) : tlv = b'' for key , value in data . items ( ) : tag = bytes ( [ int ( key ) ] ) length = len ( value ) pos = 0 # A tag with length > 255 is added multiple times and concatenated into # one buffer when reading the TLV again. while pos < len ( value ) : size = min ( length , 255 ) tlv += tag tlv ...
Convert a dict to TLV8 bytes .
120
10
247,279
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 .
41
12
247,280
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 .
350
18
247,281
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 .
355
28
247,282
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 = [ # Propagate any comments to...
Builds a doc that looks like a function call from docs that represent the function arguments and keyword arguments .
556
21
247,283
def assoc ( self , key , value ) : return self . _replace ( user_ctx = { * * self . user_ctx , key : value , } )
Return a modified PrettyContext with key set to value
36
10
247,284
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 .
46
14
247,285
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 .
656
19
247,286
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 .
99
17
247,287
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
43
14
247,288
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 .
235
23
247,289
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 .
244
25
247,290
def install_extras ( include = ALL_EXTRAS , * , exclude = EMPTY_SET , raise_on_error = False , warn_on_error = True ) : # noqa include = set ( include ) exclude = set ( exclude ) unexisting_extras = ( include | exclude ) - ALL_EXTRAS if unexisting_extras : raise ValueError ( "The following extras don't exist: {}" . for...
Installs extras .
320
4
247,291
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 = { * * _defa...
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 .
290
36
247,292
def package_maven ( ) : if not os . getenv ( 'JAVA_HOME' ) : # make sure Maven uses the same JDK which we have used to compile # and link the C-code os . environ [ 'JAVA_HOME' ] = jdk_home_dir mvn_goal = 'package' log . info ( "Executing Maven goal '" + mvn_goal + "'" ) code = subprocess . call ( [ 'mvn' , 'clean' , mv...
Run maven package lifecycle
355
6
247,293
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 .
180
21
247,294
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 .
117
11
247,295
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 .
288
15
247,296
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
269
17
247,297
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
314
23
247,298
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
85
6
247,299
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
198
19