idx
int64
0
251k
question
stringlengths
53
3.53k
target
stringlengths
5
1.23k
len_question
int64
20
893
len_target
int64
3
238
240,900
def info ( ctx ) : dev = ctx . obj [ 'dev' ] controller = ctx . obj [ 'controller' ] slot1 , slot2 = controller . slot_status click . echo ( 'Slot 1: {}' . format ( slot1 and 'programmed' or 'empty' ) ) click . echo ( 'Slot 2: {}' . format ( slot2 and 'programmed' or 'empty' ) ) if dev . is_fips : click . echo ( 'FIPS Approved Mode: {}' . format ( 'Yes' if controller . is_in_fips_mode else 'No' ) )
Display status of YubiKey Slots .
136
9
240,901
def swap ( ctx ) : controller = ctx . obj [ 'controller' ] click . echo ( 'Swapping slots...' ) try : controller . swap_slots ( ) except YkpersError as e : _failed_to_write_msg ( ctx , e )
Swaps the two slot configurations .
61
7
240,902
def ndef ( ctx , slot , prefix ) : dev = ctx . obj [ 'dev' ] controller = ctx . obj [ 'controller' ] if not dev . config . nfc_supported : ctx . fail ( 'NFC interface not available.' ) if not controller . slot_status [ slot - 1 ] : ctx . fail ( 'Slot {} is empty.' . format ( slot ) ) try : if prefix : controller . configure_ndef_slot ( slot , prefix ) else : controller . configure_ndef_slot ( slot ) except YkpersError as e : _failed_to_write_msg ( ctx , e )
Select slot configuration to use for NDEF .
141
9
240,903
def delete ( ctx , slot , force ) : controller = ctx . obj [ 'controller' ] if not force and not controller . slot_status [ slot - 1 ] : ctx . fail ( 'Not possible to delete an empty slot.' ) force or click . confirm ( 'Do you really want to delete' ' the configuration of slot {}?' . format ( slot ) , abort = True , err = True ) click . echo ( 'Deleting the configuration of slot {}...' . format ( slot ) ) try : controller . zap_slot ( slot ) except YkpersError as e : _failed_to_write_msg ( ctx , e )
Deletes the configuration of a slot .
142
8
240,904
def yubiotp ( ctx , slot , public_id , private_id , key , no_enter , force , serial_public_id , generate_private_id , generate_key ) : dev = ctx . obj [ 'dev' ] controller = ctx . obj [ 'controller' ] if public_id and serial_public_id : ctx . fail ( 'Invalid options: --public-id conflicts with ' '--serial-public-id.' ) if private_id and generate_private_id : ctx . fail ( 'Invalid options: --private-id conflicts with ' '--generate-public-id.' ) if key and generate_key : ctx . fail ( 'Invalid options: --key conflicts with --generate-key.' ) if not public_id : if serial_public_id : if dev . serial is None : ctx . fail ( 'Serial number not set, public ID must be provided' ) public_id = modhex_encode ( b'\xff\x00' + struct . pack ( b'>I' , dev . serial ) ) click . echo ( 'Using YubiKey serial as public ID: {}' . format ( public_id ) ) elif force : ctx . fail ( 'Public ID not given. Please remove the --force flag, or ' 'add the --serial-public-id flag or --public-id option.' ) else : public_id = click . prompt ( 'Enter public ID' , err = True ) try : public_id = modhex_decode ( public_id ) except KeyError : ctx . fail ( 'Invalid public ID, must be modhex.' ) if not private_id : if generate_private_id : private_id = os . urandom ( 6 ) click . echo ( 'Using a randomly generated private ID: {}' . format ( b2a_hex ( private_id ) . decode ( 'ascii' ) ) ) elif force : ctx . fail ( 'Private ID not given. Please remove the --force flag, or ' 'add the --generate-private-id flag or --private-id option.' ) else : private_id = click . prompt ( 'Enter private ID' , err = True ) private_id = a2b_hex ( private_id ) if not key : if generate_key : key = os . urandom ( 16 ) click . echo ( 'Using a randomly generated secret key: {}' . format ( b2a_hex ( key ) . decode ( 'ascii' ) ) ) elif force : ctx . fail ( 'Secret key not given. Please remove the --force flag, or ' 'add the --generate-key flag or --key option.' ) else : key = click . prompt ( 'Enter secret key' , err = True ) key = a2b_hex ( key ) force or click . confirm ( 'Program an OTP credential in slot {}?' . format ( slot ) , abort = True , err = True ) try : controller . program_otp ( slot , key , public_id , private_id , not no_enter ) except YkpersError as e : _failed_to_write_msg ( ctx , e )
Program a Yubico OTP credential .
697
9
240,905
def static ( ctx , slot , password , generate , length , keyboard_layout , no_enter , force ) : controller = ctx . obj [ 'controller' ] keyboard_layout = KEYBOARD_LAYOUT [ keyboard_layout ] if password and len ( password ) > 38 : ctx . fail ( 'Password too long (maximum length is 38 characters).' ) if generate and not length : ctx . fail ( 'Provide a length for the generated password.' ) if not password and not generate : password = click . prompt ( 'Enter a static password' , err = True ) elif not password and generate : password = generate_static_pw ( length , keyboard_layout ) if not force : _confirm_slot_overwrite ( controller , slot ) try : controller . program_static ( slot , password , not no_enter , keyboard_layout = keyboard_layout ) except YkpersError as e : _failed_to_write_msg ( ctx , e )
Configure a static password .
212
6
240,906
def chalresp ( ctx , slot , key , totp , touch , force , generate ) : controller = ctx . obj [ 'controller' ] if key : if generate : ctx . fail ( 'Invalid options: --generate conflicts with KEY argument.' ) elif totp : key = parse_b32_key ( key ) else : key = parse_key ( key ) else : if force and not generate : ctx . fail ( 'No secret key given. Please remove the --force flag, ' 'set the KEY argument or set the --generate flag.' ) elif totp : while True : key = click . prompt ( 'Enter a secret key (base32)' , err = True ) try : key = parse_b32_key ( key ) break except Exception as e : click . echo ( e ) else : if generate : key = os . urandom ( 20 ) click . echo ( 'Using a randomly generated key: {}' . format ( b2a_hex ( key ) . decode ( 'ascii' ) ) ) else : key = click . prompt ( 'Enter a secret key' , err = True ) key = parse_key ( key ) cred_type = 'TOTP' if totp else 'challenge-response' force or click . confirm ( 'Program a {} credential in slot {}?' . format ( cred_type , slot ) , abort = True , err = True ) try : controller . program_chalresp ( slot , key , touch ) except YkpersError as e : _failed_to_write_msg ( ctx , e )
Program a challenge - response credential .
342
7
240,907
def calculate ( ctx , slot , challenge , totp , digits ) : controller = ctx . obj [ 'controller' ] if not challenge and not totp : ctx . fail ( 'No challenge provided.' ) # Check that slot is not empty slot1 , slot2 = controller . slot_status if ( slot == 1 and not slot1 ) or ( slot == 2 and not slot2 ) : ctx . fail ( 'Cannot perform challenge-response on an empty slot.' ) # Timestamp challenge should be int if challenge and totp : try : challenge = int ( challenge ) except Exception as e : logger . error ( 'Error' , exc_info = e ) ctx . fail ( 'Timestamp challenge for TOTP must be an integer.' ) try : res = controller . calculate ( slot , challenge , totp = totp , digits = int ( digits ) , wait_for_touch = False ) except YkpersError as e : # Touch is set if e . errno == 11 : prompt_for_touch ( ) try : res = controller . calculate ( slot , challenge , totp = totp , digits = int ( digits ) , wait_for_touch = True ) except YkpersError as e : # Touch timed out if e . errno == 4 : ctx . fail ( 'The YubiKey timed out.' ) else : ctx . fail ( e ) else : ctx . fail ( 'Failed to calculate challenge.' ) click . echo ( res )
Perform a challenge - response operation .
319
8
240,908
def hotp ( ctx , slot , key , digits , counter , no_enter , force ) : controller = ctx . obj [ 'controller' ] if not key : while True : key = click . prompt ( 'Enter a secret key (base32)' , err = True ) try : key = parse_b32_key ( key ) break except Exception as e : click . echo ( e ) force or click . confirm ( 'Program a HOTP credential in slot {}?' . format ( slot ) , abort = True , err = True ) try : controller . program_hotp ( slot , key , counter , int ( digits ) == 8 , not no_enter ) except YkpersError as e : _failed_to_write_msg ( ctx , e )
Program an HMAC - SHA1 OATH - HOTP credential .
164
14
240,909
def settings ( ctx , slot , new_access_code , delete_access_code , enter , pacing , force ) : controller = ctx . obj [ 'controller' ] if ( new_access_code is not None ) and delete_access_code : ctx . fail ( '--new-access-code conflicts with --delete-access-code.' ) if not controller . slot_status [ slot - 1 ] : ctx . fail ( 'Not possible to update settings on an empty slot.' ) if new_access_code is not None : if new_access_code == '' : new_access_code = click . prompt ( 'Enter new access code' , show_default = False , err = True ) try : new_access_code = parse_access_code_hex ( new_access_code ) except Exception as e : ctx . fail ( 'Failed to parse access code: ' + str ( e ) ) force or click . confirm ( 'Update the settings for slot {}? ' 'All existing settings will be overwritten.' . format ( slot ) , abort = True , err = True ) click . echo ( 'Updating settings for slot {}...' . format ( slot ) ) if pacing is not None : pacing = int ( pacing ) try : controller . update_settings ( slot , enter = enter , pacing = pacing ) except YkpersError as e : _failed_to_write_msg ( ctx , e ) if new_access_code : try : controller . set_access_code ( slot , new_access_code ) except Exception as e : logger . error ( 'Failed to set access code' , exc_info = e ) ctx . fail ( 'Failed to set access code: ' + str ( e ) ) if delete_access_code : try : controller . delete_access_code ( slot ) except Exception as e : logger . error ( 'Failed to delete access code' , exc_info = e ) ctx . fail ( 'Failed to delete access code: ' + str ( e ) )
Update the settings for a slot .
442
7
240,910
def parse_private_key ( data , password ) : # PEM if is_pem ( data ) : if b'ENCRYPTED' in data : if password is None : raise TypeError ( 'No password provided for encrypted key.' ) try : return serialization . load_pem_private_key ( data , password , backend = default_backend ( ) ) except ValueError : # Cryptography raises ValueError if decryption fails. raise except Exception : pass # PKCS12 if is_pkcs12 ( data ) : try : p12 = crypto . load_pkcs12 ( data , password ) data = crypto . dump_privatekey ( crypto . FILETYPE_PEM , p12 . get_privatekey ( ) ) return serialization . load_pem_private_key ( data , password = None , backend = default_backend ( ) ) except crypto . Error as e : raise ValueError ( e ) # DER try : return serialization . load_der_private_key ( data , password , backend = default_backend ( ) ) except Exception : pass # All parsing failed raise ValueError ( 'Could not parse private key.' )
Identifies decrypts and returns a cryptography private key object .
253
12
240,911
def parse_certificates ( data , password ) : # PEM if is_pem ( data ) : certs = [ ] for cert in data . split ( PEM_IDENTIFIER ) : try : certs . append ( x509 . load_pem_x509_certificate ( PEM_IDENTIFIER + cert , default_backend ( ) ) ) except Exception : pass # Could be valid PEM but not certificates. if len ( certs ) > 0 : return certs # PKCS12 if is_pkcs12 ( data ) : try : p12 = crypto . load_pkcs12 ( data , password ) data = crypto . dump_certificate ( crypto . FILETYPE_PEM , p12 . get_certificate ( ) ) return [ x509 . load_pem_x509_certificate ( data , default_backend ( ) ) ] except crypto . Error as e : raise ValueError ( e ) # DER try : return [ x509 . load_der_x509_certificate ( data , default_backend ( ) ) ] except Exception : pass raise ValueError ( 'Could not parse certificate.' )
Identifies decrypts and returns list of cryptography x509 certificates .
248
13
240,912
def get_leaf_certificates ( certs ) : issuers = [ cert . issuer . get_attributes_for_oid ( x509 . NameOID . COMMON_NAME ) for cert in certs ] leafs = [ cert for cert in certs if ( cert . subject . get_attributes_for_oid ( x509 . NameOID . COMMON_NAME ) not in issuers ) ] return leafs
Extracts the leaf certificates from a list of certificates . Leaf certificates are ones whose subject does not appear as issuer among the others .
91
27
240,913
def set_lock_code ( ctx , lock_code , new_lock_code , clear , generate , force ) : dev = ctx . obj [ 'dev' ] def prompt_new_lock_code ( ) : return prompt_lock_code ( prompt = 'Enter your new lock code' ) def prompt_current_lock_code ( ) : return prompt_lock_code ( prompt = 'Enter your current lock code' ) def change_lock_code ( lock_code , new_lock_code ) : lock_code = _parse_lock_code ( ctx , lock_code ) new_lock_code = _parse_lock_code ( ctx , new_lock_code ) try : dev . write_config ( device_config ( config_lock = new_lock_code ) , reboot = True , lock_key = lock_code ) except Exception as e : logger . error ( 'Changing the lock code failed' , exc_info = e ) ctx . fail ( 'Failed to change the lock code. Wrong current code?' ) def set_lock_code ( new_lock_code ) : new_lock_code = _parse_lock_code ( ctx , new_lock_code ) try : dev . write_config ( device_config ( config_lock = new_lock_code ) , reboot = True ) except Exception as e : logger . error ( 'Setting the lock code failed' , exc_info = e ) ctx . fail ( 'Failed to set the lock code.' ) if generate and new_lock_code : ctx . fail ( 'Invalid options: --new-lock-code conflicts with --generate.' ) if clear : new_lock_code = CLEAR_LOCK_CODE if generate : new_lock_code = b2a_hex ( os . urandom ( 16 ) ) . decode ( 'utf-8' ) click . echo ( 'Using a randomly generated lock code: {}' . format ( new_lock_code ) ) force or click . confirm ( 'Lock configuration with this lock code?' , abort = True , err = True ) if dev . config . configuration_locked : if lock_code : if new_lock_code : change_lock_code ( lock_code , new_lock_code ) else : new_lock_code = prompt_new_lock_code ( ) change_lock_code ( lock_code , new_lock_code ) else : if new_lock_code : lock_code = prompt_current_lock_code ( ) change_lock_code ( lock_code , new_lock_code ) else : lock_code = prompt_current_lock_code ( ) new_lock_code = prompt_new_lock_code ( ) change_lock_code ( lock_code , new_lock_code ) else : if lock_code : ctx . fail ( 'There is no current lock code set. ' 'Use --new-lock-code to set one.' ) else : if new_lock_code : set_lock_code ( new_lock_code ) else : new_lock_code = prompt_new_lock_code ( ) set_lock_code ( new_lock_code )
Set or change the configuration lock code .
695
8
240,914
def nfc ( ctx , enable , disable , enable_all , disable_all , list , lock_code , force ) : if not ( list or enable_all or enable or disable_all or disable ) : ctx . fail ( 'No configuration options chosen.' ) if enable_all : enable = APPLICATION . __members__ . keys ( ) if disable_all : disable = APPLICATION . __members__ . keys ( ) _ensure_not_invalid_options ( ctx , enable , disable ) dev = ctx . obj [ 'dev' ] nfc_supported = dev . config . nfc_supported nfc_enabled = dev . config . nfc_enabled if not nfc_supported : ctx . fail ( 'NFC interface not available.' ) if list : _list_apps ( ctx , nfc_enabled ) for app in enable : if APPLICATION [ app ] & nfc_supported : nfc_enabled |= APPLICATION [ app ] else : ctx . fail ( '{} not supported over NFC.' . format ( app ) ) for app in disable : if APPLICATION [ app ] & nfc_supported : nfc_enabled &= ~ APPLICATION [ app ] else : ctx . fail ( '{} not supported over NFC.' . format ( app ) ) f_confirm = '{}{}Configure NFC interface?' . format ( 'Enable {}.\n' . format ( ', ' . join ( [ str ( APPLICATION [ app ] ) for app in enable ] ) ) if enable else '' , 'Disable {}.\n' . format ( ', ' . join ( [ str ( APPLICATION [ app ] ) for app in disable ] ) ) if disable else '' ) is_locked = dev . config . configuration_locked if force and is_locked and not lock_code : ctx . fail ( 'Configuration is locked - please supply the --lock-code ' 'option.' ) if lock_code and not is_locked : ctx . fail ( 'Configuration is not locked - please remove the ' '--lock-code option.' ) force or click . confirm ( f_confirm , abort = True , err = True ) if is_locked and not lock_code : lock_code = prompt_lock_code ( ) if lock_code : lock_code = _parse_lock_code ( ctx , lock_code ) try : dev . write_config ( device_config ( nfc_enabled = nfc_enabled ) , reboot = True , lock_key = lock_code ) except Exception as e : logger . error ( 'Failed to write config' , exc_info = e ) ctx . fail ( 'Failed to configure NFC applications.' )
Enable or disable applications over NFC .
584
7
240,915
def info ( ctx , check_fips ) : dev = ctx . obj [ 'dev' ] if dev . is_fips and check_fips : fips_status = get_overall_fips_status ( dev . serial , dev . config ) click . echo ( 'Device type: {}' . format ( dev . device_name ) ) click . echo ( 'Serial number: {}' . format ( dev . serial or 'Not set or unreadable' ) ) if dev . version : f_version = '.' . join ( str ( x ) for x in dev . version ) click . echo ( 'Firmware version: {}' . format ( f_version ) ) else : click . echo ( 'Firmware version: Uncertain, re-run with only one ' 'YubiKey connected' ) config = dev . config if config . form_factor : click . echo ( 'Form factor: {!s}' . format ( config . form_factor ) ) click . echo ( 'Enabled USB interfaces: {}' . format ( dev . mode ) ) if config . nfc_supported : f_nfc = 'enabled' if config . nfc_enabled else 'disabled' click . echo ( 'NFC interface is {}.' . format ( f_nfc ) ) if config . configuration_locked : click . echo ( 'Configured applications are protected by a lock code.' ) click . echo ( ) print_app_status_table ( config ) if dev . is_fips and check_fips : click . echo ( ) click . echo ( 'FIPS Approved Mode: {}' . format ( 'Yes' if all ( fips_status . values ( ) ) else 'No' ) ) status_keys = list ( fips_status . keys ( ) ) status_keys . sort ( ) for status_key in status_keys : click . echo ( ' {}: {}' . format ( status_key , 'Yes' if fips_status [ status_key ] else 'No' ) )
Show general information .
439
4
240,916
def oath ( ctx , password ) : try : controller = OathController ( ctx . obj [ 'dev' ] . driver ) ctx . obj [ 'controller' ] = controller ctx . obj [ 'settings' ] = Settings ( 'oath' ) except APDUError as e : if e . sw == SW . NOT_FOUND : ctx . fail ( "The OATH application can't be found on this YubiKey." ) raise if password : ctx . obj [ 'key' ] = controller . derive_key ( password )
Manage OATH Application .
120
6
240,917
def info ( ctx ) : controller = ctx . obj [ 'controller' ] version = controller . version click . echo ( 'OATH version: {}.{}.{}' . format ( version [ 0 ] , version [ 1 ] , version [ 2 ] ) ) click . echo ( 'Password protection ' + ( 'enabled' if controller . locked else 'disabled' ) ) keys = ctx . obj [ 'settings' ] . get ( 'keys' , { } ) if controller . locked and controller . id in keys : click . echo ( 'The password for this YubiKey is remembered by ykman.' ) if ctx . obj [ 'dev' ] . is_fips : click . echo ( 'FIPS Approved Mode: {}' . format ( 'Yes' if controller . is_in_fips_mode else 'No' ) )
Display status of OATH application .
185
7
240,918
def reset ( ctx ) : controller = ctx . obj [ 'controller' ] click . echo ( 'Resetting OATH data...' ) old_id = controller . id controller . reset ( ) settings = ctx . obj [ 'settings' ] keys = settings . setdefault ( 'keys' , { } ) if old_id in keys : del keys [ old_id ] settings . write ( ) click . echo ( 'Success! All OATH credentials have been cleared from your YubiKey.' )
Reset all OATH data .
108
7
240,919
def add ( ctx , secret , name , issuer , period , oath_type , digits , touch , algorithm , counter , force ) : oath_type = OATH_TYPE [ oath_type ] algorithm = ALGO [ algorithm ] digits = int ( digits ) if not secret : while True : secret = click . prompt ( 'Enter a secret key (base32)' , err = True ) try : secret = parse_b32_key ( secret ) break except Exception as e : click . echo ( e ) ensure_validated ( ctx ) _add_cred ( ctx , CredentialData ( secret , issuer , name , oath_type , algorithm , digits , period , counter , touch ) , force )
Add a new credential .
152
5
240,920
def uri ( ctx , uri , touch , force ) : if not uri : while True : uri = click . prompt ( 'Enter an OATH URI' , err = True ) try : uri = CredentialData . from_uri ( uri ) break except Exception as e : click . echo ( e ) ensure_validated ( ctx ) data = uri # Steam is a special case where we allow the otpauth # URI to contain a 'digits' value of '5'. if data . digits == 5 and data . issuer == 'Steam' : data . digits = 6 data . touch = touch _add_cred ( ctx , data , force = force )
Add a new credential from URI .
150
7
240,921
def list ( ctx , show_hidden , oath_type , period ) : ensure_validated ( ctx ) controller = ctx . obj [ 'controller' ] creds = [ cred for cred in controller . list ( ) if show_hidden or not cred . is_hidden ] creds . sort ( ) for cred in creds : click . echo ( cred . printable_key , nl = False ) if oath_type : click . echo ( u', {}' . format ( cred . oath_type . name ) , nl = False ) if period : click . echo ( ', {}' . format ( cred . period ) , nl = False ) click . echo ( )
List all credentials .
147
4
240,922
def code ( ctx , show_hidden , query , single ) : ensure_validated ( ctx ) controller = ctx . obj [ 'controller' ] creds = [ ( cr , c ) for ( cr , c ) in controller . calculate_all ( ) if show_hidden or not cr . is_hidden ] creds = _search ( creds , query ) if len ( creds ) == 1 : cred , code = creds [ 0 ] if cred . touch : prompt_for_touch ( ) try : if cred . oath_type == OATH_TYPE . HOTP : # HOTP might require touch, we don't know. # Assume yes after 500ms. hotp_touch_timer = Timer ( 0.500 , prompt_for_touch ) hotp_touch_timer . start ( ) creds = [ ( cred , controller . calculate ( cred ) ) ] hotp_touch_timer . cancel ( ) elif code is None : creds = [ ( cred , controller . calculate ( cred ) ) ] except APDUError as e : if e . sw == SW . SECURITY_CONDITION_NOT_SATISFIED : ctx . fail ( 'Touch credential timed out!' ) elif single : _error_multiple_hits ( ctx , [ cr for cr , c in creds ] ) if single : click . echo ( creds [ 0 ] [ 1 ] . value ) else : creds . sort ( ) outputs = [ ( cr . printable_key , c . value if c else '[Touch Credential]' if cr . touch else '[HOTP Credential]' if cr . oath_type == OATH_TYPE . HOTP else '' ) for ( cr , c ) in creds ] longest_name = max ( len ( n ) for ( n , c ) in outputs ) if outputs else 0 longest_code = max ( len ( c ) for ( n , c ) in outputs ) if outputs else 0 format_str = u'{:<%d} {:>%d}' % ( longest_name , longest_code ) for name , result in outputs : click . echo ( format_str . format ( name , result ) )
Generate codes .
478
4
240,923
def delete ( ctx , query , force ) : ensure_validated ( ctx ) controller = ctx . obj [ 'controller' ] creds = controller . list ( ) hits = _search ( creds , query ) if len ( hits ) == 0 : click . echo ( 'No matches, nothing to be done.' ) elif len ( hits ) == 1 : cred = hits [ 0 ] if force or ( click . confirm ( u'Delete credential: {} ?' . format ( cred . printable_key ) , default = False , err = True ) ) : controller . delete ( cred ) click . echo ( u'Deleted {}.' . format ( cred . printable_key ) ) else : click . echo ( 'Deletion aborted by user.' ) else : _error_multiple_hits ( ctx , hits )
Delete a credential .
179
4
240,924
def set_password ( ctx , new_password , remember ) : ensure_validated ( ctx , prompt = 'Enter your current password' ) if not new_password : new_password = click . prompt ( 'Enter your new password' , hide_input = True , confirmation_prompt = True , err = True ) controller = ctx . obj [ 'controller' ] settings = ctx . obj [ 'settings' ] keys = settings . setdefault ( 'keys' , { } ) key = controller . set_password ( new_password ) click . echo ( 'Password updated.' ) if remember : keys [ controller . id ] = b2a_hex ( key ) . decode ( ) settings . write ( ) click . echo ( 'Password remembered' ) elif controller . id in keys : del keys [ controller . id ] settings . write ( )
Password protect the OATH credentials .
183
7
240,925
def remember_password ( ctx , forget , clear_all ) : controller = ctx . obj [ 'controller' ] settings = ctx . obj [ 'settings' ] keys = settings . setdefault ( 'keys' , { } ) if clear_all : del settings [ 'keys' ] settings . write ( ) click . echo ( 'All passwords have been cleared.' ) elif forget : if controller . id in keys : del keys [ controller . id ] settings . write ( ) click . echo ( 'Password forgotten.' ) else : ensure_validated ( ctx , remember = True )
Manage local password storage .
126
6
240,926
def refresh_balance ( self ) : left_depth = self . left_node . depth if self . left_node else 0 right_depth = self . right_node . depth if self . right_node else 0 self . depth = 1 + max ( left_depth , right_depth ) self . balance = right_depth - left_depth
Recalculate self . balance and self . depth based on child node values .
73
17
240,927
def compute_depth ( self ) : left_depth = self . left_node . compute_depth ( ) if self . left_node else 0 right_depth = self . right_node . compute_depth ( ) if self . right_node else 0 return 1 + max ( left_depth , right_depth )
Recursively computes true depth of the subtree . Should only be needed for debugging . Unless something is wrong the depth field should reflect the correct depth of the subtree .
67
36
240,928
def rotate ( self ) : self . refresh_balance ( ) if abs ( self . balance ) < 2 : return self # balance > 0 is the heavy side my_heavy = self . balance > 0 child_heavy = self [ my_heavy ] . balance > 0 if my_heavy == child_heavy or self [ my_heavy ] . balance == 0 : ## Heavy sides same # self save # save -> 1 self # 1 # ## Heavy side balanced # self save save # save -> 1 self -> 1 self.rot() # 1 2 2 return self . srotate ( ) else : return self . drotate ( )
Does rotating if necessary to balance this node and returns the new top node .
132
15
240,929
def srotate ( self ) : # self save save # save 3 -> 1 self -> 1 self.rot() # 1 2 2 3 # # self save save # 3 save -> self 1 -> self.rot() 1 # 2 1 3 2 #assert(self.balance != 0) heavy = self . balance > 0 light = not heavy save = self [ heavy ] #print("srotate: bal={},{}".format(self.balance, save.balance)) #self.print_structure() self [ heavy ] = save [ light ] # 2 #assert(save[light]) save [ light ] = self . rotate ( ) # Needed to ensure the 2 and 3 are balanced under new subnode # Some intervals may overlap both self.x_center and save.x_center # Promote those to the new tip of the tree promotees = [ iv for iv in save [ light ] . s_center if save . center_hit ( iv ) ] if promotees : for iv in promotees : save [ light ] = save [ light ] . remove ( iv ) # may trigger pruning # TODO: Use Node.add() here, to simplify future balancing improvements. # For now, this is the same as augmenting save.s_center, but that may # change. save . s_center . update ( promotees ) save . refresh_balance ( ) return save
Single rotation . Assumes that balance is + - 2 .
294
12
240,930
def add ( self , interval ) : if self . center_hit ( interval ) : self . s_center . add ( interval ) return self else : direction = self . hit_branch ( interval ) if not self [ direction ] : self [ direction ] = Node . from_interval ( interval ) self . refresh_balance ( ) return self else : self [ direction ] = self [ direction ] . add ( interval ) return self . rotate ( )
Returns self after adding the interval and balancing .
95
9
240,931
def remove ( self , interval ) : # since this is a list, called methods can set this to [1], # making it true done = [ ] return self . remove_interval_helper ( interval , done , should_raise_error = True )
Returns self after removing the interval and balancing .
55
9
240,932
def discard ( self , interval ) : done = [ ] return self . remove_interval_helper ( interval , done , should_raise_error = False )
Returns self after removing interval and balancing .
35
8
240,933
def remove_interval_helper ( self , interval , done , should_raise_error ) : #trace = interval.begin == 347 and interval.end == 353 #if trace: print('\nRemoving from {} interval {}'.format( # self.x_center, interval)) if self . center_hit ( interval ) : #if trace: print('Hit at {}'.format(self.x_center)) if not should_raise_error and interval not in self . s_center : done . append ( 1 ) #if trace: print('Doing nothing.') return self try : # raises error if interval not present - this is # desired. self . s_center . remove ( interval ) except : self . print_structure ( ) raise KeyError ( interval ) if self . s_center : # keep this node done . append ( 1 ) # no rebalancing necessary #if trace: print('Removed, no rebalancing.') return self # If we reach here, no intervals are left in self.s_center. # So, prune self. return self . prune ( ) else : # interval not in s_center direction = self . hit_branch ( interval ) if not self [ direction ] : if should_raise_error : raise ValueError done . append ( 1 ) return self #if trace: # print('Descending to {} branch'.format( # ['left', 'right'][direction] # )) self [ direction ] = self [ direction ] . remove_interval_helper ( interval , done , should_raise_error ) # Clean up if not done : #if trace: # print('Rotating {}'.format(self.x_center)) # self.print_structure() return self . rotate ( ) return self
Returns self after removing interval and balancing . If interval doesn t exist raise ValueError .
379
17
240,934
def search_overlap ( self , point_list ) : result = set ( ) for j in point_list : self . search_point ( j , result ) return result
Returns all intervals that overlap the point_list .
37
10
240,935
def search_point ( self , point , result ) : for k in self . s_center : if k . begin <= point < k . end : result . add ( k ) if point < self . x_center and self [ 0 ] : return self [ 0 ] . search_point ( point , result ) elif point > self . x_center and self [ 1 ] : return self [ 1 ] . search_point ( point , result ) return result
Returns all intervals that contain point .
97
7
240,936
def prune ( self ) : if not self [ 0 ] or not self [ 1 ] : # if I have an empty branch direction = not self [ 0 ] # graft the other branch here #if trace: # print('Grafting {} branch'.format( # 'right' if direction else 'left')) result = self [ direction ] #if result: result.verify() return result else : # Replace the root node with the greatest predecessor. heir , self [ 0 ] = self [ 0 ] . pop_greatest_child ( ) #if trace: # print('Replacing {} with {}.'.format( # self.x_center, heir.x_center # )) # print('Removed greatest predecessor:') # self.print_structure() #if self[0]: self[0].verify() #if self[1]: self[1].verify() # Set up the heir as the new root node ( heir [ 0 ] , heir [ 1 ] ) = ( self [ 0 ] , self [ 1 ] ) #if trace: print('Setting up the heir:') #if trace: heir.print_structure() # popping the predecessor may have unbalanced this node; # fix it heir . refresh_balance ( ) heir = heir . rotate ( ) #heir.verify() #if trace: print('Rotated the heir:') #if trace: heir.print_structure() return heir
On a subtree where the root node s s_center is empty return a new subtree with no empty s_centers .
303
27
240,937
def contains_point ( self , p ) : for iv in self . s_center : if iv . contains_point ( p ) : return True branch = self [ p > self . x_center ] return branch and branch . contains_point ( p )
Returns whether this node or a child overlaps p .
54
11
240,938
def print_structure ( self , indent = 0 , tostring = False ) : nl = '\n' sp = indent * ' ' rlist = [ str ( self ) + nl ] if self . s_center : for iv in sorted ( self . s_center ) : rlist . append ( sp + ' ' + repr ( iv ) + nl ) if self . left_node : rlist . append ( sp + '<: ' ) # no CR rlist . append ( self . left_node . print_structure ( indent + 1 , True ) ) if self . right_node : rlist . append ( sp + '>: ' ) # no CR rlist . append ( self . right_node . print_structure ( indent + 1 , True ) ) result = '' . join ( rlist ) if tostring : return result else : print ( result )
For debugging .
190
3
240,939
def from_tuples ( cls , tups ) : ivs = [ Interval ( * t ) for t in tups ] return IntervalTree ( ivs )
Create a new IntervalTree from an iterable of 2 - or 3 - tuples where the tuple lists begin end and optionally data .
37
28
240,940
def _add_boundaries ( self , interval ) : begin = interval . begin end = interval . end if begin in self . boundary_table : self . boundary_table [ begin ] += 1 else : self . boundary_table [ begin ] = 1 if end in self . boundary_table : self . boundary_table [ end ] += 1 else : self . boundary_table [ end ] = 1
Records the boundaries of the interval in the boundary table .
84
12
240,941
def _remove_boundaries ( self , interval ) : begin = interval . begin end = interval . end if self . boundary_table [ begin ] == 1 : del self . boundary_table [ begin ] else : self . boundary_table [ begin ] -= 1 if self . boundary_table [ end ] == 1 : del self . boundary_table [ end ] else : self . boundary_table [ end ] -= 1
Removes the boundaries of the interval from the boundary table .
88
12
240,942
def add ( self , interval ) : if interval in self : return if interval . is_null ( ) : raise ValueError ( "IntervalTree: Null Interval objects not allowed in IntervalTree:" " {0}" . format ( interval ) ) if not self . top_node : self . top_node = Node . from_interval ( interval ) else : self . top_node = self . top_node . add ( interval ) self . all_intervals . add ( interval ) self . _add_boundaries ( interval )
Adds an interval to the tree if not already present .
115
11
240,943
def remove ( self , interval ) : #self.verify() if interval not in self : #print(self.all_intervals) raise ValueError self . top_node = self . top_node . remove ( interval ) self . all_intervals . remove ( interval ) self . _remove_boundaries ( interval )
Removes an interval from the tree if present . If not raises ValueError .
70
16
240,944
def discard ( self , interval ) : if interval not in self : return self . all_intervals . discard ( interval ) self . top_node = self . top_node . discard ( interval ) self . _remove_boundaries ( interval )
Removes an interval from the tree if present . If not does nothing .
52
15
240,945
def difference ( self , other ) : ivs = set ( ) for iv in self : if iv not in other : ivs . add ( iv ) return IntervalTree ( ivs )
Returns a new tree comprising all intervals in self but not in other .
40
14
240,946
def intersection ( self , other ) : ivs = set ( ) shorter , longer = sorted ( [ self , other ] , key = len ) for iv in shorter : if iv in longer : ivs . add ( iv ) return IntervalTree ( ivs )
Returns a new tree of all intervals common to both self and other .
55
14
240,947
def intersection_update ( self , other ) : ivs = list ( self ) for iv in ivs : if iv not in other : self . remove ( iv )
Removes intervals from self unless they also exist in other .
35
12
240,948
def symmetric_difference ( self , other ) : if not isinstance ( other , set ) : other = set ( other ) me = set ( self ) ivs = me . difference ( other ) . union ( other . difference ( me ) ) return IntervalTree ( ivs )
Return a tree with elements only in self or other but not both .
61
14
240,949
def symmetric_difference_update ( self , other ) : other = set ( other ) ivs = list ( self ) for iv in ivs : if iv in other : self . remove ( iv ) other . remove ( iv ) self . update ( other )
Throws out all intervals except those only in self or other not both .
56
15
240,950
def remove_overlap ( self , begin , end = None ) : hitlist = self . at ( begin ) if end is None else self . overlap ( begin , end ) for iv in hitlist : self . remove ( iv )
Removes all intervals overlapping the given point or range .
49
11
240,951
def remove_envelop ( self , begin , end ) : hitlist = self . envelop ( begin , end ) for iv in hitlist : self . remove ( iv )
Removes all intervals completely enveloped in the given range .
36
12
240,952
def find_nested ( self ) : result = { } def add_if_nested ( ) : if parent . contains_interval ( child ) : if parent not in result : result [ parent ] = set ( ) result [ parent ] . add ( child ) long_ivs = sorted ( self . all_intervals , key = Interval . length , reverse = True ) for i , parent in enumerate ( long_ivs ) : for child in long_ivs [ i + 1 : ] : add_if_nested ( ) return result
Returns a dictionary mapping parent intervals to sets of intervals overlapped by and contained in the parent .
120
19
240,953
def overlaps ( self , begin , end = None ) : if end is not None : return self . overlaps_range ( begin , end ) elif isinstance ( begin , Number ) : return self . overlaps_point ( begin ) else : return self . overlaps_range ( begin . begin , begin . end )
Returns whether some interval in the tree overlaps the given point or range .
69
15
240,954
def overlaps_point ( self , p ) : if self . is_empty ( ) : return False return bool ( self . top_node . contains_point ( p ) )
Returns whether some interval in the tree overlaps p .
38
11
240,955
def overlaps_range ( self , begin , end ) : if self . is_empty ( ) : return False elif begin >= end : return False elif self . overlaps_point ( begin ) : return True return any ( self . overlaps_point ( bound ) for bound in self . boundary_table if begin < bound < end )
Returns whether some interval in the tree overlaps the given range . Returns False if given a null interval over which to test .
73
25
240,956
def split_overlaps ( self ) : if not self : return if len ( self . boundary_table ) == 2 : return bounds = sorted ( self . boundary_table ) # get bound locations new_ivs = set ( ) for lbound , ubound in zip ( bounds [ : - 1 ] , bounds [ 1 : ] ) : for iv in self [ lbound ] : new_ivs . add ( Interval ( lbound , ubound , iv . data ) ) self . __init__ ( new_ivs )
Finds all intervals with overlapping ranges and splits them along the range boundaries .
114
15
240,957
def at ( self , p ) : root = self . top_node if not root : return set ( ) return root . search_point ( p , set ( ) )
Returns the set of all intervals that contain p .
36
10
240,958
def envelop ( self , begin , end = None ) : root = self . top_node if not root : return set ( ) if end is None : iv = begin return self . envelop ( iv . begin , iv . end ) elif begin >= end : return set ( ) result = root . search_point ( begin , set ( ) ) # bound_begin might be greater boundary_table = self . boundary_table bound_begin = boundary_table . bisect_left ( begin ) bound_end = boundary_table . bisect_left ( end ) # up to, but not including end result . update ( root . search_overlap ( # slice notation is slightly slower boundary_table . keys ( ) [ index ] for index in xrange ( bound_begin , bound_end ) ) ) # TODO: improve envelop() to use node info instead of less-efficient filtering result = set ( iv for iv in result if iv . begin >= begin and iv . end <= end ) return result
Returns the set of all intervals fully contained in the range [ begin end ) .
210
16
240,959
def defnoun ( self , singular , plural ) : self . checkpat ( singular ) self . checkpatplural ( plural ) self . pl_sb_user_defined . extend ( ( singular , plural ) ) self . si_sb_user_defined . extend ( ( plural , singular ) ) return 1
Set the noun plural of singular to plural .
66
9
240,960
def defverb ( self , s1 , p1 , s2 , p2 , s3 , p3 ) : self . checkpat ( s1 ) self . checkpat ( s2 ) self . checkpat ( s3 ) self . checkpatplural ( p1 ) self . checkpatplural ( p2 ) self . checkpatplural ( p3 ) self . pl_v_user_defined . extend ( ( s1 , p1 , s2 , p2 , s3 , p3 ) ) return 1
Set the verb plurals for s1 s2 and s3 to p1 p2 and p3 respectively .
113
23
240,961
def defadj ( self , singular , plural ) : self . checkpat ( singular ) self . checkpatplural ( plural ) self . pl_adj_user_defined . extend ( ( singular , plural ) ) return 1
Set the adjective plural of singular to plural .
47
9
240,962
def defa ( self , pattern ) : self . checkpat ( pattern ) self . A_a_user_defined . extend ( ( pattern , "a" ) ) return 1
Define the indefinate article as a for words matching pattern .
38
13
240,963
def defan ( self , pattern ) : self . checkpat ( pattern ) self . A_a_user_defined . extend ( ( pattern , "an" ) ) return 1
Define the indefinate article as an for words matching pattern .
38
13
240,964
def checkpat ( self , pattern ) : if pattern is None : return try : re . match ( pattern , "" ) except re . error : print3 ( "\nBad user-defined singular pattern:\n\t%s\n" % pattern ) raise BadUserDefinedPatternError
check for errors in a regex pattern
60
7
240,965
def classical ( self , * * kwargs ) : classical_mode = list ( def_classical . keys ( ) ) if not kwargs : self . classical_dict = all_classical . copy ( ) return if "all" in kwargs : if kwargs [ "all" ] : self . classical_dict = all_classical . copy ( ) else : self . classical_dict = no_classical . copy ( ) for k , v in list ( kwargs . items ( ) ) : if k in classical_mode : self . classical_dict [ k ] = v else : raise UnknownClassicalModeError
turn classical mode on and off for various categories
138
9
240,966
def num ( self , count = None , show = None ) : # (;$count,$show) if count is not None : try : self . persistent_count = int ( count ) except ValueError : raise BadNumValueError if ( show is None ) or show : return str ( count ) else : self . persistent_count = None return ""
Set the number to be used in other method calls .
75
11
240,967
def _get_value_from_ast ( self , obj ) : if isinstance ( obj , ast . Num ) : return obj . n elif isinstance ( obj , ast . Str ) : return obj . s elif isinstance ( obj , ast . List ) : return [ self . _get_value_from_ast ( e ) for e in obj . elts ] elif isinstance ( obj , ast . Tuple ) : return tuple ( [ self . _get_value_from_ast ( e ) for e in obj . elts ] ) # None, True and False are NameConstants in Py3.4 and above. elif sys . version_info . major >= 3 and isinstance ( obj , ast . NameConstant ) : return obj . value # For python versions below 3.4 elif isinstance ( obj , ast . Name ) and ( obj . id in [ "True" , "False" , "None" ] ) : return string_to_constant [ obj . id ] # Probably passed a variable name. # Or passed a single word without wrapping it in quotes as an argument # ex: p.inflect("I plural(see)") instead of p.inflect("I plural('see')") raise NameError ( "name '%s' is not defined" % obj . id )
Return the value of the ast object .
285
8
240,968
def _string_to_substitute ( self , mo , methods_dict ) : matched_text , f_name = mo . groups ( ) # matched_text is the complete match string. e.g. plural_noun(cat) # f_name is the function name. e.g. plural_noun # Return matched_text if function name is not in methods_dict if f_name not in methods_dict : return matched_text # Parse the matched text a_tree = ast . parse ( matched_text ) # get the args and kwargs from ast objects args_list = [ self . _get_value_from_ast ( a ) for a in a_tree . body [ 0 ] . value . args ] kwargs_list = { kw . arg : self . _get_value_from_ast ( kw . value ) for kw in a_tree . body [ 0 ] . value . keywords } # Call the corresponding function return methods_dict [ f_name ] ( * args_list , * * kwargs_list )
Return the string to be substituted for the match .
234
10
240,969
def inflect ( self , text ) : save_persistent_count = self . persistent_count # Dictionary of allowed methods methods_dict = { "plural" : self . plural , "plural_adj" : self . plural_adj , "plural_noun" : self . plural_noun , "plural_verb" : self . plural_verb , "singular_noun" : self . singular_noun , "a" : self . a , "an" : self . a , "no" : self . no , "ordinal" : self . ordinal , "number_to_words" : self . number_to_words , "present_participle" : self . present_participle , "num" : self . num , } # Regular expression to find Python's function call syntax functions_re = re . compile ( r"((\w+)\([^)]*\)*)" , re . IGNORECASE ) output = functions_re . sub ( lambda mo : self . _string_to_substitute ( mo , methods_dict ) , text ) self . persistent_count = save_persistent_count return output
Perform inflections in a string .
255
8
240,970
def plural ( self , text , count = None ) : pre , word , post = self . partition_word ( text ) if not word : return text plural = self . postprocess ( word , self . _pl_special_adjective ( word , count ) or self . _pl_special_verb ( word , count ) or self . _plnoun ( word , count ) , ) return "{}{}{}" . format ( pre , plural , post )
Return the plural of text .
98
6
240,971
def plural_noun ( self , text , count = None ) : pre , word , post = self . partition_word ( text ) if not word : return text plural = self . postprocess ( word , self . _plnoun ( word , count ) ) return "{}{}{}" . format ( pre , plural , post )
Return the plural of text where text is a noun .
70
11
240,972
def plural_verb ( self , text , count = None ) : pre , word , post = self . partition_word ( text ) if not word : return text plural = self . postprocess ( word , self . _pl_special_verb ( word , count ) or self . _pl_general_verb ( word , count ) , ) return "{}{}{}" . format ( pre , plural , post )
Return the plural of text where text is a verb .
86
11
240,973
def plural_adj ( self , text , count = None ) : pre , word , post = self . partition_word ( text ) if not word : return text plural = self . postprocess ( word , self . _pl_special_adjective ( word , count ) or word ) return "{}{}{}" . format ( pre , plural , post )
Return the plural of text where text is an adjective .
75
11
240,974
def compare ( self , word1 , word2 ) : return ( self . _plequal ( word1 , word2 , self . plural_noun ) or self . _plequal ( word1 , word2 , self . plural_verb ) or self . _plequal ( word1 , word2 , self . plural_adj ) )
compare word1 and word2 for equality regardless of plurality
72
12
240,975
def compare_nouns ( self , word1 , word2 ) : return self . _plequal ( word1 , word2 , self . plural_noun )
compare word1 and word2 for equality regardless of plurality word1 and word2 are to be treated as nouns
36
24
240,976
def compare_verbs ( self , word1 , word2 ) : return self . _plequal ( word1 , word2 , self . plural_verb )
compare word1 and word2 for equality regardless of plurality word1 and word2 are to be treated as verbs
33
23
240,977
def compare_adjs ( self , word1 , word2 ) : return self . _plequal ( word1 , word2 , self . plural_adj )
compare word1 and word2 for equality regardless of plurality word1 and word2 are to be treated as adjectives
34
24
240,978
def singular_noun ( self , text , count = None , gender = None ) : pre , word , post = self . partition_word ( text ) if not word : return text sing = self . _sinoun ( word , count = count , gender = gender ) if sing is not False : plural = self . postprocess ( word , self . _sinoun ( word , count = count , gender = gender ) ) return "{}{}{}" . format ( pre , plural , post ) return False
Return the singular of text where text is a plural noun .
105
12
240,979
def a ( self , text , count = 1 ) : mo = re . search ( r"\A(\s*)(?:an?\s+)?(.+?)(\s*)\Z" , text , re . IGNORECASE ) if mo : word = mo . group ( 2 ) if not word : return text pre = mo . group ( 1 ) post = mo . group ( 3 ) result = self . _indef_article ( word , count ) return "{}{}{}" . format ( pre , result , post ) return ""
Return the appropriate indefinite article followed by text .
117
9
240,980
def no ( self , text , count = None ) : if count is None and self . persistent_count is not None : count = self . persistent_count if count is None : count = 0 mo = re . search ( r"\A(\s*)(.+?)(\s*)\Z" , text ) pre = mo . group ( 1 ) word = mo . group ( 2 ) post = mo . group ( 3 ) if str ( count ) . lower ( ) in pl_count_zero : return "{}no {}{}" . format ( pre , self . plural ( word , 0 ) , post ) else : return "{}{} {}{}" . format ( pre , count , self . plural ( word , count ) , post )
If count is 0 no zero or nil return no followed by the plural of text .
158
17
240,981
def present_participle ( self , word ) : plv = self . plural_verb ( word , 2 ) for pat , repl in ( ( r"ie$" , r"y" ) , ( r"ue$" , r"u" ) , # TODO: isn't ue$ -> u encompassed in the following rule? ( r"([auy])e$" , r"\g<1>" ) , ( r"ski$" , r"ski" ) , ( r"[^b]i$" , r"" ) , ( r"^(are|were)$" , r"be" ) , ( r"^(had)$" , r"hav" ) , ( r"^(hoe)$" , r"\g<1>" ) , ( r"([^e])e$" , r"\g<1>" ) , ( r"er$" , r"er" ) , ( r"([^aeiou][aeiouy]([bdgmnprst]))$" , r"\g<1>\g<2>" ) , ) : ( ans , num ) = re . subn ( pat , repl , plv ) if num : return "%sing" % ans return "%sing" % ans
Return the present participle for word .
283
8
240,982
def ordinal ( self , num ) : if re . match ( r"\d" , str ( num ) ) : try : num % 2 n = num except TypeError : if "." in str ( num ) : try : # numbers after decimal, # so only need last one for ordinal n = int ( num [ - 1 ] ) except ValueError : # ends with '.', so need to use whole string n = int ( num [ : - 1 ] ) else : n = int ( num ) try : post = nth [ n % 100 ] except KeyError : post = nth [ n % 10 ] return "{}{}" . format ( num , post ) else : mo = re . search ( r"(%s)\Z" % ordinal_suff , num ) try : post = ordinal [ mo . group ( 1 ) ] return re . sub ( r"(%s)\Z" % ordinal_suff , post , num ) except AttributeError : return "%sth" % num
Return the ordinal of num .
213
7
240,983
def join ( self , words , sep = None , sep_spaced = True , final_sep = None , conj = "and" , conj_spaced = True , ) : if not words : return "" if len ( words ) == 1 : return words [ 0 ] if conj_spaced : if conj == "" : conj = " " else : conj = " %s " % conj if len ( words ) == 2 : return "{}{}{}" . format ( words [ 0 ] , conj , words [ 1 ] ) if sep is None : if "," in "" . join ( words ) : sep = ";" else : sep = "," if final_sep is None : final_sep = sep final_sep = "{}{}" . format ( final_sep , conj ) if sep_spaced : sep += " " return "{}{}{}" . format ( sep . join ( words [ 0 : - 1 ] ) , final_sep , words [ - 1 ] )
Join words into a list .
212
6
240,984
def _int ( int_or_str : Any ) -> int : if isinstance ( int_or_str , str ) : return ord ( int_or_str ) if isinstance ( int_or_str , bytes ) : return int_or_str [ 0 ] return int ( int_or_str )
return an integer where a single character string may be expected
68
11
240,985
def _console ( console : Any ) -> Any : try : return console . console_c except AttributeError : warnings . warn ( ( "Falsy console parameters are deprecated, " "always use the root console instance returned by " "console_init_root." ) , DeprecationWarning , stacklevel = 3 , ) return ffi . NULL
Return a cffi console .
74
7
240,986
def _new_from_cdata ( cls , cdata : Any ) -> "Color" : return cls ( cdata . r , cdata . g , cdata . b )
new in libtcod - cffi
41
9
240,987
def _describe_bitmask ( bits : int , table : Dict [ Any , str ] , default : str = "0" ) -> str : result = [ ] for bit , name in table . items ( ) : if bit & bits : result . append ( name ) if not result : return default return "|" . join ( result )
Returns a bitmask in human readable form .
74
9
240,988
def _pixel_to_tile ( x : float , y : float ) -> Tuple [ float , float ] : xy = tcod . ffi . new ( "double[2]" , ( x , y ) ) tcod . lib . TCOD_sys_pixel_to_tile ( xy , xy + 1 ) return xy [ 0 ] , xy [ 1 ]
Convert pixel coordinates to tile coordinates .
84
8
240,989
def get ( ) -> Iterator [ Any ] : sdl_event = tcod . ffi . new ( "SDL_Event*" ) while tcod . lib . SDL_PollEvent ( sdl_event ) : if sdl_event . type in _SDL_TO_CLASS_TABLE : yield _SDL_TO_CLASS_TABLE [ sdl_event . type ] . from_sdl_event ( sdl_event ) else : yield Undefined . from_sdl_event ( sdl_event )
Return an iterator for all pending events .
116
8
240,990
def wait ( timeout : Optional [ float ] = None ) -> Iterator [ Any ] : if timeout is not None : tcod . lib . SDL_WaitEventTimeout ( tcod . ffi . NULL , int ( timeout * 1000 ) ) else : tcod . lib . SDL_WaitEvent ( tcod . ffi . NULL ) return get ( )
Block until events exist then return an event iterator .
75
10
240,991
def get_mouse_state ( ) -> MouseState : xy = tcod . ffi . new ( "int[2]" ) buttons = tcod . lib . SDL_GetMouseState ( xy , xy + 1 ) x , y = _pixel_to_tile ( * xy ) return MouseState ( ( xy [ 0 ] , xy [ 1 ] ) , ( int ( x ) , int ( y ) ) , buttons )
Return the current state of the mouse .
97
8
240,992
def deprecate ( message : str , category : Any = DeprecationWarning , stacklevel : int = 0 ) -> Callable [ [ F ] , F ] : def decorator ( func : F ) -> F : if not __debug__ : return func @ functools . wraps ( func ) def wrapper ( * args , * * kargs ) : # type: ignore warnings . warn ( message , category , stacklevel = stacklevel + 2 ) return func ( * args , * * kargs ) return cast ( F , wrapper ) return decorator
Return a decorator which adds a warning to functions .
117
11
240,993
def pending_deprecate ( message : str = "This function may be deprecated in the future." " Consider raising an issue on GitHub if you need this feature." , category : Any = PendingDeprecationWarning , stacklevel : int = 0 , ) -> Callable [ [ F ] , F ] : return deprecate ( message , category , stacklevel )
Like deprecate but the default parameters are filled out for a generic pending deprecation warning .
77
20
240,994
def _format_char ( char ) : if char is None : return - 1 if isinstance ( char , _STRTYPES ) and len ( char ) == 1 : return ord ( char ) try : return int ( char ) # allow all int-like objects except : raise TypeError ( 'char single character string, integer, or None\nReceived: ' + repr ( char ) )
Prepares a single character for passing to ctypes calls needs to return an integer but can also pass None which will keep the current character instead of overwriting it .
84
34
240,995
def _format_str ( string ) : if isinstance ( string , _STRTYPES ) : if _IS_PYTHON3 : array = _array . array ( 'I' ) array . frombytes ( string . encode ( _utf32_codec ) ) else : # Python 2 if isinstance ( string , unicode ) : array = _array . array ( b'I' ) array . fromstring ( string . encode ( _utf32_codec ) ) else : array = _array . array ( b'B' ) array . fromstring ( string ) return array return string
Attempt fast string handing by decoding directly into an array .
129
11
240,996
def _getImageSize ( filename ) : result = None file = open ( filename , 'rb' ) if file . read ( 8 ) == b'\x89PNG\r\n\x1a\n' : # PNG while 1 : length , = _struct . unpack ( '>i' , file . read ( 4 ) ) chunkID = file . read ( 4 ) if chunkID == '' : # EOF break if chunkID == b'IHDR' : # return width, height result = _struct . unpack ( '>ii' , file . read ( 8 ) ) break file . seek ( 4 + length , 1 ) file . close ( ) return result file . seek ( 0 ) if file . read ( 8 ) == b'BM' : # Bitmap file . seek ( 18 , 0 ) # skip to size data result = _struct . unpack ( '<ii' , file . read ( 8 ) ) file . close ( ) return result
Try to get the width and height of a bmp of png image file
210
16
240,997
def init ( width , height , title = None , fullscreen = False , renderer = 'SDL' ) : RENDERERS = { 'GLSL' : 0 , 'OPENGL' : 1 , 'SDL' : 2 } global _rootinitialized , _rootConsoleRef if not _fontinitialized : # set the default font to the one that comes with tdl set_font ( _os . path . join ( __path__ [ 0 ] , 'terminal8x8.png' ) , None , None , True , True ) if renderer . upper ( ) not in RENDERERS : raise TDLError ( 'No such render type "%s", expected one of "%s"' % ( renderer , '", "' . join ( RENDERERS ) ) ) renderer = RENDERERS [ renderer . upper ( ) ] # If a console already exists then make a clone to replace it if _rootConsoleRef and _rootConsoleRef ( ) : # unhook the root console, turning into a regular console and deleting # the root console from libTCOD _rootConsoleRef ( ) . _root_unhook ( ) if title is None : # use a default title if _sys . argv : # Use the script filename as the title. title = _os . path . basename ( _sys . argv [ 0 ] ) else : title = 'python-tdl' _lib . TCOD_console_init_root ( width , height , _encodeString ( title ) , fullscreen , renderer ) #event.get() # flush the libtcod event queue to fix some issues # issues may be fixed already event . _eventsflushed = False _rootinitialized = True rootconsole = Console . _newConsole ( _ffi . NULL ) _rootConsoleRef = _weakref . ref ( rootconsole ) return rootconsole
Start the main console with the given width and height and return the root console .
401
16
240,998
def screenshot ( path = None ) : if not _rootinitialized : raise TDLError ( 'Initialize first with tdl.init' ) if isinstance ( path , str ) : _lib . TCOD_sys_save_screenshot ( _encodeString ( path ) ) elif path is None : # save to screenshot001.png, screenshot002.png, ... filelist = _os . listdir ( '.' ) n = 1 filename = 'screenshot%.3i.png' % n while filename in filelist : n += 1 filename = 'screenshot%.3i.png' % n _lib . TCOD_sys_save_screenshot ( _encodeString ( filename ) ) else : # assume file like obj #save to temp file and copy to file-like obj tmpname = _os . tempnam ( ) _lib . TCOD_sys_save_screenshot ( _encodeString ( tmpname ) ) with tmpname as tmpfile : path . write ( tmpfile . read ( ) ) _os . remove ( tmpname )
Capture the screen and save it as a png file .
229
12
240,999
def _normalizePoint ( self , x , y ) : # cast to int, always faster than type checking x = int ( x ) y = int ( y ) assert ( - self . width <= x < self . width ) and ( - self . height <= y < self . height ) , ( '(%i, %i) is an invalid postition on %s' % ( x , y , self ) ) # handle negative indexes return ( x % self . width , y % self . height )
Check if a point is in bounds and make minor adjustments .
106
12