idx
int64
0
251k
question
stringlengths
53
3.53k
target
stringlengths
5
1.23k
len_question
int64
20
893
len_target
int64
3
238
3,100
def users_text ( self ) : if self . _users_text is None : self . chain . connection . log ( "Getting connected users text" ) self . _users_text = self . driver . get_users_text ( ) if self . _users_text : self . chain . connection . log ( "Users text collected" ) else : self . chain . connection . log ( "Users text not...
Return connected users information and collect if not available .
97
10
3,101
def get_protocol_name ( self ) : protocol_name = self . node_info . protocol if self . is_console : protocol_name += '_console' return protocol_name
Provide protocol name based on node_info .
41
10
3,102
def update_udi ( self ) : self . chain . connection . log ( "Parsing inventory" ) # TODO: Maybe validate if udi is complete self . udi = parse_inventory ( self . inventory_text )
Update udi .
49
4
3,103
def update_config_mode ( self , prompt = None ) : # TODO: Fix the conflict with config mode attribute at connection if prompt : self . mode = self . driver . update_config_mode ( prompt ) else : self . mode = self . driver . update_config_mode ( self . prompt )
Update config mode .
66
4
3,104
def update_driver ( self , prompt ) : prompt = prompt . lstrip ( ) self . chain . connection . log ( "({}): Prompt: '{}'" . format ( self . driver . platform , prompt ) ) self . prompt = prompt driver_name = self . driver . update_driver ( prompt ) if driver_name is None : self . chain . connection . log ( "New driver ...
Update driver based on new prompt .
113
7
3,105
def prepare_terminal_session ( self ) : for cmd in self . driver . prepare_terminal_session : try : self . send ( cmd ) except CommandSyntaxError : self . chain . connection . log ( "Command not supported or not authorized: '{}'. Skipping" . format ( cmd ) ) pass
Send commands to prepare terminal session configuration .
69
8
3,106
def update_os_type ( self ) : self . chain . connection . log ( "Detecting os type" ) os_type = self . driver . get_os_type ( self . version_text ) if os_type : self . chain . connection . log ( "SW Type: {}" . format ( os_type ) ) self . os_type = os_type
Update os_type attribute .
81
6
3,107
def update_os_version ( self ) : self . chain . connection . log ( "Detecting os version" ) os_version = self . driver . get_os_version ( self . version_text ) if os_version : self . chain . connection . log ( "SW Version: {}" . format ( os_version ) ) self . os_version = os_version
Update os_version attribute .
81
6
3,108
def update_family ( self ) : self . chain . connection . log ( "Detecting hw family" ) family = self . driver . get_hw_family ( self . version_text ) if family : self . chain . connection . log ( "HW Family: {}" . format ( family ) ) self . family = family
Update family attribute .
71
4
3,109
def update_platform ( self ) : self . chain . connection . log ( "Detecting hw platform" ) platform = self . driver . get_hw_platform ( self . udi ) if platform : self . chain . connection . log ( "HW Platform: {}" . format ( platform ) ) self . platform = platform
Update platform attribute .
70
4
3,110
def update_console ( self ) : self . chain . connection . log ( "Detecting console connection" ) is_console = self . driver . is_console ( self . users_text ) if is_console is not None : self . is_console = is_console
Update is_console whether connected via console .
58
9
3,111
def reload ( self , reload_timeout , save_config , no_reload_cmd ) : if not no_reload_cmd : self . ctrl . send_command ( self . driver . reload_cmd ) return self . driver . reload ( reload_timeout , save_config )
Reload device .
62
4
3,112
def run_fsm ( self , name , command , events , transitions , timeout , max_transitions = 20 ) : self . ctrl . send_command ( command ) return FSM ( name , self , events , transitions , timeout = timeout , max_transitions = max_transitions ) . run ( )
Wrap the FSM code .
67
7
3,113
def config ( self , configlet , plane , * * attributes ) : try : config_text = configlet . format ( * * attributes ) except KeyError as exp : raise CommandSyntaxError ( "Configuration template error: {}" . format ( str ( exp ) ) ) return self . driver . config ( config_text , plane )
Apply config to the device .
71
6
3,114
def device_gen ( chain , urls ) : itr = iter ( urls ) last = next ( itr ) for url in itr : yield Device ( chain , make_hop_info_from_url ( last ) , driver_name = 'jumphost' , is_target = False ) last = url yield Device ( chain , make_hop_info_from_url ( last ) , driver_name = 'generic' , is_target = True )
Device object generator .
101
4
3,115
def connect ( self ) : device = None # logger.debug("Connecting to: {}".format(str(self))) for device in self . devices : if not device . connected : self . connection . emit_message ( "Connecting {}" . format ( str ( device ) ) , log_level = logging . INFO ) protocol_name = device . get_protocol_name ( ) device . prot...
Connect to the target device using the intermediate jumphosts .
406
13
3,116
def disconnect ( self ) : self . target_device . disconnect ( ) self . ctrl . disconnect ( ) self . tail_disconnect ( - 1 )
Disconnect from the device .
33
6
3,117
def is_discovered ( self ) : if self . target_device is None : return False if None in ( self . target_device . version_text , self . target_device . os_type , self . target_device . os_version , self . target_device . inventory_text , self . target_device . family , self . target_device . platform ) : return False ret...
Return if target device is discovered .
85
7
3,118
def get_previous_prompts ( self , device ) : device_index = self . devices . index ( device ) prompts = [ re . compile ( "(?!x)x" ) ] + [ dev . prompt_re for dev in self . devices [ : device_index ] if dev . prompt_re is not None ] return prompts
Return the list of intermediate prompts . All except target .
73
11
3,119
def get_device_index_based_on_prompt ( self , prompt ) : conn_info = "" for device in self . devices : conn_info += str ( device ) + "->" if device . prompt == prompt : self . connection . log ( "Connected: {}" . format ( conn_info ) ) return self . devices . index ( device ) else : return None
Return the device index in the chain based on prompt .
83
11
3,120
def tail_disconnect ( self , index ) : try : for device in self . devices [ index + 1 : ] : device . connected = False except IndexError : pass
Mark all devices disconnected except target in the chain .
36
10
3,121
def send ( self , cmd , timeout , wait_for_string , password ) : return self . target_device . send ( cmd , timeout = timeout , wait_for_string = wait_for_string , password = password )
Send command to the target device .
49
7
3,122
def update ( self , data ) : if data is None : for device in self . devices : device . clear_info ( ) else : for device , device_info in zip ( self . devices , data ) : device . device_info = device_info self . connection . log ( "Device information updated -> [{}]" . format ( device ) )
Update the chain object with the predefined data .
75
10
3,123
def action ( func ) : @ wraps ( func ) def call_action ( * args , * * kwargs ) : """Wrap the function with logger debug.""" try : ctx = kwargs [ 'ctx' ] except KeyError : ctx = None if ctx is None : try : ctx = args [ - 1 ] except IndexError : ctx = None if ctx : if func . __doc__ is None : ctx . device . chain . conne...
Wrap the FSM action function providing extended logging information based on doc string .
175
16
3,124
def run ( self ) : ctx = FSM . Context ( self . name , self . device ) transition_counter = 0 timeout = self . timeout self . log ( "{} Start" . format ( self . name ) ) while transition_counter < self . max_transitions : transition_counter += 1 try : start_time = time ( ) if self . init_pattern is None : ctx . event =...
Start the FSM .
616
5
3,125
def build ( port = 8000 , fixtures = None ) : extractor = Extractor ( ) parser = Parser ( extractor . url_details , fixtures ) parser . parse ( ) url_details = parser . results _store = get_store ( url_details ) store = json . dumps ( _store ) variables = str ( Variable ( 'let' , 'store' , store ) ) functions = DATA_FI...
Builds a server file .
714
6
3,126
def preferred ( self ) : if 'Preferred-Value' in self . data [ 'record' ] : preferred = self . data [ 'record' ] [ 'Preferred-Value' ] type = self . data [ 'type' ] if type == 'extlang' : type = 'language' return Subtag ( preferred , type ) return None
Get the preferred subtag .
74
6
3,127
def format ( self ) : subtag = self . data [ 'subtag' ] if self . data [ 'type' ] == 'region' : return subtag . upper ( ) if self . data [ 'type' ] == 'script' : return subtag . capitalize ( ) return subtag
Get the subtag code conventional format according to RFC 5646 section 2 . 1 . 1 .
63
19
3,128
def AuthorizingClient ( domain , auth , request_encoder , response_decoder , user_agent = None ) : http_transport = transport . HttpTransport ( api_url ( domain ) , build_headers ( auth , user_agent ) ) return client . Client ( request_encoder , http_transport , response_decoder )
Creates a Freshbooks client for a freshbooks domain using an auth object .
76
16
3,129
def TokenClient ( domain , token , user_agent = None , request_encoder = default_request_encoder , response_decoder = default_response_decoder , ) : return AuthorizingClient ( domain , transport . TokenAuthorization ( token ) , request_encoder , response_decoder , user_agent = user_agent )
Creates a Freshbooks client for a freshbooks domain using token - based auth . The optional request_encoder and response_decoder parameters can be passed the logging_request_encoder and logging_response_decoder objects from this module or custom encoders to aid debugging or change the behaviour of refreshbooks request ...
74
108
3,130
def OAuthClient ( domain , consumer_key , consumer_secret , token , token_secret , user_agent = None , request_encoder = default_request_encoder , response_decoder = default_response_decoder ) : return _create_oauth_client ( AuthorizingClient , domain , consumer_key , consumer_secret , token , token_secret , user_agent...
Creates a Freshbooks client for a freshbooks domain using OAuth . Token management is assumed to have been handled out of band . The optional request_encoder and response_decoder parameters can be passed the logging_request_encoder and logging_response_decoder objects from this module or custom encoders to aid debuggin...
109
118
3,131
def gpg_decrypt ( cfg , gpg_config = None ) : def decrypt ( obj ) : """Decrypt the object. It is an inner function because we must first verify that gpg is ready. If we did them in the same function we would end up calling the gpg checks several times, potentially, since we are calling this recursively. """ if isinstan...
Decrypt GPG objects in configuration .
566
8
3,132
def kms_decrypt ( cfg , aws_config = None ) : def decrypt ( obj ) : """Decrypt the object. It is an inner function because we must first configure our KMS client. Then we call this recursively on the object. """ if isinstance ( obj , list ) : res_v = [ ] for item in obj : res_v . append ( decrypt ( item ) ) return res_...
Decrypt KMS objects in configuration .
303
8
3,133
def get_version_text ( self ) : show_version_brief_not_supported = False version_text = None try : version_text = self . device . send ( "show version brief" , timeout = 120 ) except CommandError : show_version_brief_not_supported = True if show_version_brief_not_supported : try : # IOS Hack - need to check if show ver...
Return the version information from the device .
140
8
3,134
def get_inventory_text ( self ) : inventory_text = None if self . inventory_cmd : try : inventory_text = self . device . send ( self . inventory_cmd , timeout = 120 ) self . log ( 'Inventory collected' ) except CommandError : self . log ( 'Unable to collect inventory' ) else : self . log ( 'No inventory command for {}'...
Return the inventory information from the device .
95
8
3,135
def get_users_text ( self ) : users_text = None if self . users_cmd : try : users_text = self . device . send ( self . users_cmd , timeout = 60 ) except CommandError : self . log ( 'Unable to collect connected users information' ) else : self . log ( 'No users command for {}' . format ( self . platform ) ) return users...
Return the users logged in information from the device .
87
10
3,136
def get_os_type ( self , version_text ) : # pylint: disable=no-self-use os_type = None if version_text is None : return os_type match = re . search ( "(XR|XE|NX-OS)" , version_text ) if match : os_type = match . group ( 1 ) else : os_type = 'IOS' if os_type == "XR" : match = re . search ( "Build Information" , version_...
Return the OS type information from the device .
158
9
3,137
def get_os_version ( self , version_text ) : os_version = None if version_text is None : return os_version match = re . search ( self . version_re , version_text , re . MULTILINE ) if match : os_version = match . group ( 1 ) return os_version
Return the OS version information from the device .
70
9
3,138
def get_hw_family ( self , version_text ) : family = None if version_text is None : return family match = re . search ( self . platform_re , version_text , re . MULTILINE ) if match : self . platform_string = match . group ( ) self . log ( "Platform string: {}" . format ( match . group ( ) ) ) self . raw_family = match...
Return the HW family information from the device .
188
9
3,139
def get_hw_platform ( self , udi ) : platform = None try : pid = udi [ 'pid' ] if pid == '' : self . log ( "Empty PID. Use the hw family from the platform string." ) return self . raw_family match = re . search ( self . pid2platform_re , pid ) if match : platform = match . group ( 1 ) except KeyError : pass return plat...
Return th HW platform information from the device .
91
9
3,140
def is_console ( self , users_text ) : if users_text is None : self . log ( "Console information not collected" ) return None for line in users_text . split ( '\n' ) : if '*' in line : match = re . search ( self . vty_re , line ) if match : self . log ( "Detected connection to vty" ) return False else : match = re . se...
Return if device is connected over console .
132
8
3,141
def wait_for_string ( self , expected_string , timeout = 60 ) : # 0 1 2 3 events = [ self . syntax_error_re , self . connection_closed_re , expected_string , self . press_return_re , # 4 5 6 7 self . more_re , pexpect . TIMEOUT , pexpect . EOF , self . buffer_overflow_re ] # add detected prompts chain events += self . ...
Wait for string FSM .
481
6
3,142
def reload ( self , reload_timeout = 300 , save_config = True ) : self . log ( "Reload not implemented on {} platform" . format ( self . platform ) )
Reload the device and waits for device to boot up .
39
12
3,143
def base_prompt ( self , prompt ) : if prompt is None : return None if not self . device . is_target : return prompt pattern = pattern_manager . pattern ( self . platform , "prompt_dynamic" , compiled = False ) pattern = pattern . format ( prompt = "(?P<prompt>.*?)" ) result = re . search ( pattern , prompt ) if result...
Extract the base prompt pattern .
136
7
3,144
def update_config_mode ( self , prompt ) : # pylint: disable=no-self-use mode = 'global' if prompt : if 'config' in prompt : mode = 'config' elif 'admin' in prompt : mode = 'admin' self . log ( "Mode: {}" . format ( mode ) ) return mode
Update config mode based on the prompt analysis .
74
9
3,145
def update_hostname ( self , prompt ) : result = re . search ( self . prompt_re , prompt ) if result : hostname = result . group ( 'hostname' ) self . log ( "Hostname detected: {}" . format ( hostname ) ) else : hostname = self . device . hostname self . log ( "Hostname not set: {}" . format ( prompt ) ) return hostnam...
Update the hostname based on the prompt analysis .
90
10
3,146
def enter_plane ( self , plane ) : try : cmd = CONF [ 'driver' ] [ self . platform ] [ 'planes' ] [ plane ] self . plane = plane except KeyError : cmd = None if cmd : self . log ( "Entering the {} plane" . format ( plane ) ) self . device . send ( cmd )
Enter the device plane .
74
5
3,147
def handle_other_factory_method ( attr , minimum , maximum ) : if attr == 'percentage' : if minimum : minimum = ast . literal_eval ( minimum ) else : minimum = 0 if maximum : maximum = ast . literal_eval ( maximum ) else : maximum = 100 val = random . uniform ( minimum , maximum ) return val # If `attr` isn't specified...
This is a temporary static method when there are more factory methods we can move this to another class or find a way to maintain it in a scalable manner
112
30
3,148
def _parse_syntax ( self , raw ) : raw = str ( raw ) # treat the value as a string regardless of its actual data type has_syntax = re . findall ( r'<(\^)?(fk__)?(\w+)?([0-9]*[.]?[0-9]+?)?(\:)?([0-9]*[.]?[0-9]+?)?(\:)?([0-9]*[.]?[0-9]+?)?>' , raw , flags = re . DOTALL ) if has_syntax : fake_val = re . sub ( r'\'?\"?<(\^...
Retrieves the syntax from the response and goes through each one to generate and replace it with mock values
275
21
3,149
def count ( self , source , target ) : try : source_value = self . _response_holder [ source ] except KeyError : # Source value hasn't been determined yet, we need # to generate the source value first raw = self . fake_response [ source ] source_value = self . _parse_syntax ( raw ) if isinstance ( source_value , str ) ...
The count relationship is used for listing endpoints where a specific attribute might hold the value to the number of instances of another attribute .
272
26
3,150
def get_command ( self , version = 2 ) : try : options = _C [ 'options' ] options_str = " -o " . join ( options ) if options_str : options_str = "-o " + options_str + " " except KeyError : options_str = "" if self . username : # Not supported on SunOS # "-o ConnectTimeout={} command = "ssh {}" "-{} " "-p {} {}@{}" . fo...
Return the SSH protocol specific command to connect .
158
9
3,151
def connect ( self , driver ) : # 0 1 2 events = [ driver . password_re , self . device . prompt_re , driver . unable_to_connect_re , # 3 4 5 6 7 NEWSSHKEY , KNOWN_HOSTS , HOST_KEY_FAILED , MODULUS_TOO_SMALL , PROTOCOL_DIFFER , # 8 9 10 driver . timeout_re , pexpect . TIMEOUT , driver . syntax_error_re ] transitions = ...
Connect using the SSH protocol specific FSM .
607
9
3,152
def authenticate ( self , driver ) : # 0 1 2 3 events = [ driver . press_return_re , driver . password_re , self . device . prompt_re , pexpect . TIMEOUT ] transitions = [ ( driver . press_return_re , [ 0 , 1 ] , 1 , partial ( a_send , "\r\n" ) , 10 ) , ( driver . password_re , [ 0 ] , 1 , partial ( a_send_password , s...
Authenticate using the SSH protocol specific FSM .
301
10
3,153
def disconnect ( self , driver ) : self . log ( "SSH disconnect" ) try : self . device . ctrl . sendline ( '\x03' ) self . device . ctrl . sendline ( '\x04' ) except OSError : self . log ( "Protocol already disconnected" )
Disconnect using the protocol specific method .
69
8
3,154
def fallback_to_sshv1 ( self , ctx ) : command = self . get_command ( version = 1 ) ctx . spawn_session ( command ) return True
Fallback to SSHv1 .
39
7
3,155
def search_meta_tag ( html_doc , prefix , code ) : regex = '<meta\s+(?:name=([\'\"]){0}\\1\s+content=([\'\"]){1}\\2|content=([\'\"]){1}\\3\s+name=([\'\"]){0}\\4)\s*/?>' . format ( prefix , code ) meta = re . compile ( regex , flags = re . MULTILINE | re . IGNORECASE ) m = meta . search ( html_doc ) if m : head = re . s...
Checks whether the html_doc contains a meta matching the prefix & code
171
15
3,156
def find_postgame ( data , size ) : pos = None for i in range ( size - SEARCH_MAX_BYTES , size - LOOKAHEAD ) : op_type , length , action_type = struct . unpack ( '<IIB' , data [ i : i + LOOKAHEAD ] ) if op_type == 0x01 and length == POSTGAME_LENGTH and action_type == 0xFF : LOGGER . debug ( "found postgame candidate @ ...
Find postgame struct .
129
5
3,157
def parse_postgame ( handle , size ) : data = handle . read ( ) postgame = find_postgame ( data , size ) if postgame : pos , length = postgame try : return mgz . body . actions . postgame . parse ( data [ pos : pos + length ] ) except construct . core . ConstructError : raise IOError ( "failed to parse postgame" ) rais...
Parse postgame structure .
96
6
3,158
def ach ( structure , fields ) : field = fields . pop ( 0 ) if structure : if hasattr ( structure , field ) : structure = getattr ( structure , field ) if not fields : return structure return ach ( structure , fields ) return None
Get field from achievements structure .
54
6
3,159
def get_postgame ( self ) : if self . _cache [ 'postgame' ] is not None : return self . _cache [ 'postgame' ] self . _handle . seek ( 0 ) try : self . _cache [ 'postgame' ] = parse_postgame ( self . _handle , self . size ) return self . _cache [ 'postgame' ] except IOError : self . _cache [ 'postgame' ] = False return ...
Get postgame structure .
115
5
3,160
def get_duration ( self ) : postgame = self . get_postgame ( ) if postgame : return postgame . duration_int * 1000 duration = self . _header . initial . restore_time try : while self . _handle . tell ( ) < self . size : operation = mgz . body . operation . parse_stream ( self . _handle ) if operation . type == 'sync' :...
Get game duration .
183
4
3,161
def get_restored ( self ) : return self . _header . initial . restore_time > 0 , self . _header . initial . restore_time
Check for restored game .
33
5
3,162
def get_version ( self ) : return mgz . const . VERSIONS [ self . _header . version ] , str ( self . _header . sub_version ) [ : 5 ]
Get game version .
40
4
3,163
def get_dataset ( self ) : sample = self . _header . initial . players [ 0 ] . attributes . player_stats if 'mod' in sample and sample . mod [ 'id' ] > 0 : return sample . mod elif 'trickle_food' in sample and sample . trickle_food : return { 'id' : 1 , 'name' : mgz . const . MODS . get ( 1 ) , 'version' : '<5.7.2' } r...
Get dataset .
139
3
3,164
def get_teams ( self ) : if self . _cache [ 'teams' ] : return self . _cache [ 'teams' ] teams = [ ] for j , player in enumerate ( self . _header . initial . players ) : added = False for i in range ( 0 , len ( self . _header . initial . players ) ) : if player . attributes . my_diplomacy [ i ] == 'ally' : inner_team =...
Get teams .
260
3
3,165
def get_achievements ( self , name ) : postgame = self . get_postgame ( ) if not postgame : return None for achievements in postgame . achievements : # achievements player name can be shorter if name . startswith ( achievements . player_name . replace ( b'\x00' , b'' ) ) : return achievements return None
Get achievements for a player .
76
6
3,166
def _process_body ( self ) : start_time = time . time ( ) ratings = { } encoding = self . get_encoding ( ) checksums = [ ] ladder = None voobly = False rated = False i = 0 while self . _handle . tell ( ) < self . size : try : op = mgz . body . operation . parse_stream ( self . _handle ) if op . type == 'sync' : i += 1 ...
Get Voobly ladder .
554
6
3,167
def get_settings ( self ) : postgame = self . get_postgame ( ) return { 'type' : ( self . _header . lobby . game_type_id , self . _header . lobby . game_type ) , 'difficulty' : ( self . _header . scenario . game_settings . difficulty_id , self . _header . scenario . game_settings . difficulty ) , 'population_limit' : s...
Get settings .
389
3
3,168
def get_map ( self ) : if self . _cache [ 'map' ] : return self . _cache [ 'map' ] map_id = self . _header . scenario . game_settings . map_id instructions = self . _header . scenario . messages . instructions size = mgz . const . MAP_SIZES . get ( self . _header . map_info . size_x ) dimension = self . _header . map_i...
Get the map metadata .
631
5
3,169
def get_completed ( self ) : postgame = self . get_postgame ( ) if postgame : return postgame . complete else : return True if self . _cache [ 'resigned' ] else False
Determine if the game was completed .
46
9
3,170
def get_mirror ( self ) : mirror = False if self . get_diplomacy ( ) [ '1v1' ] : civs = set ( ) for data in self . get_players ( ) : civs . add ( data [ 'civilization' ] ) mirror = ( len ( civs ) == 1 ) return mirror
Determine mirror match .
73
6
3,171
def guess_winner ( self , i ) : for team in self . get_teams ( ) : if i not in team : continue for p in team : if p in self . _cache [ 'resigned' ] : return False return True
Guess if a player won .
52
7
3,172
def trigger ( self , * args , * * kwargs ) : for h in self . handlers : h ( * args , * * kwargs )
Execute the handlers with a message if any .
33
10
3,173
def on ( self , event , handler = None ) : if isinstance ( event , str ) and ' ' in event : # event is list str-based self . on ( event . split ( ' ' ) , handler ) elif isinstance ( event , list ) : # many events contains same handler for each in event : self . on ( each , handler ) elif isinstance ( event , dict ) : #...
Create add or update an event with a handler or more attached .
244
13
3,174
def off ( self , event , handler = None ) : if handler : self . events [ event ] . off ( handler ) else : del self . events [ event ] delattr ( self , event )
Remove an event or a handler from it .
42
9
3,175
def trigger ( self , * args , * * kargs ) : event = args [ 0 ] if isinstance ( event , str ) and ' ' in event : event = event . split ( ' ' ) # split event names ... if isinstance ( event , list ) : # event is a list of events for each in event : self . events [ each ] . trigger ( * args [ 1 : ] , * * kargs ) else : se...
Execute all event handlers with optional arguments for the observable .
113
12
3,176
def _initializer_wrapper ( initializer , * args ) : signal . signal ( signal . SIGINT , signal . SIG_IGN ) if initializer is not None : initializer ( * args )
Ignore SIGINT . During typical keyboard interrupts the parent does the killing .
42
15
3,177
def _col_type_set ( self , col , df ) : type_set = set ( ) if df [ col ] . dtype == np . dtype ( object ) : unindexed_col = list ( df [ col ] ) for i in range ( 0 , len ( df [ col ] ) ) : if unindexed_col [ i ] == np . nan : continue else : type_set . add ( type ( unindexed_col [ i ] ) ) return type_set else : type_set...
Determines the set of types present in a DataFrame column .
127
14
3,178
def raw ( self , drop_collections = False ) : base_df = self . _data if drop_collections is True : out_df = self . _drop_collections ( base_df ) else : out_df = base_df return out_df
Produces the extractor object s data as it is stored internally .
58
14
3,179
def _walk ( path , follow_links = False , maximum_depth = None ) : root_level = path . rstrip ( os . path . sep ) . count ( os . path . sep ) for root , dirs , files in os . walk ( path , followlinks = follow_links ) : yield root , dirs , files if maximum_depth is None : continue if root_level + maximum_depth <= root ....
A modified os . walk with support for maximum traversal depth .
106
13
3,180
def update ( self , * sources , follow_symlinks : bool = False , maximum_depth : int = 20 ) : for source in sources : if isinstance ( source , self . klass ) : self . path_map [ source . this . name . value ] = source self . class_cache [ source . this . name . value ] = source continue # Explicit cast to str to suppor...
Add one or more ClassFile sources to the class loader .
254
12
3,181
def open ( self , path : str , mode : str = 'r' ) -> IO : entry = self . path_map . get ( path ) if entry is None : raise FileNotFoundError ( ) if isinstance ( entry , str ) : with open ( entry , 'rb' if mode == 'r' else mode ) as source : yield source elif isinstance ( entry , ZipFile ) : yield io . BytesIO ( entry . ...
Open an IO - like object for path .
110
9
3,182
def load ( self , path : str ) -> ClassFile : # Try to refresh the class from the cache, loading it from disk # if not found. try : r = self . class_cache . pop ( path ) except KeyError : with self . open ( f'{path}.class' ) as source : r = self . klass ( source ) r . classloader = self # Even if it was found re-set th...
Load the class at path and return it .
190
9
3,183
def dependencies ( self , path : str ) -> Set [ str ] : return set ( c . name . value for c in self . search_constant_pool ( path = path , type_ = ConstantClass ) )
Returns a set of all classes referenced by the ClassFile at path without reading the entire ClassFile .
46
20
3,184
def search_constant_pool ( self , * , path : str , * * options ) : with self . open ( f'{path}.class' ) as source : # Skip over the magic, minor, and major version. source . read ( 8 ) pool = ConstantPool ( ) pool . unpack ( source ) yield from pool . find ( * * options )
Partially load the class at path yield all matching constants from the ConstantPool .
78
16
3,185
def classes ( self ) -> Iterator [ str ] : yield from ( c [ : - 6 ] for c in self . path_map . keys ( ) if c . endswith ( '.class' ) )
Yield the name of all classes discovered in the path map .
45
13
3,186
def _make_object_dict ( self , obj ) : data = { } for attr in dir ( obj ) : if attr [ 0 ] is not '_' and attr is not 'status' : datum = getattr ( obj , attr ) if not isinstance ( datum , types . MethodType ) : data . update ( self . _handle_object ( attr , datum ) ) return data
Processes an object exporting its data as a nested dictionary .
91
12
3,187
def unpack ( self , source : IO ) : self . access_flags . unpack ( source . read ( 2 ) ) self . _name_index , self . _descriptor_index = unpack ( '>HH' , source . read ( 4 ) ) self . attributes . unpack ( source )
Read the Field from the file - like object fio .
67
12
3,188
def pack ( self , out : IO ) : out . write ( self . access_flags . pack ( ) ) out . write ( pack ( '>HH' , self . _name_index , self . _descriptor_index ) ) self . attributes . pack ( out )
Write the Field to the file - like object out .
60
11
3,189
def remove ( self , field : Field ) : self . _table = [ fld for fld in self . _table if fld is not field ]
Removes a Field from the table by identity .
33
10
3,190
def unpack ( self , source : IO ) : field_count = unpack ( '>H' , source . read ( 2 ) ) [ 0 ] for _ in repeat ( None , field_count ) : field = Field ( self . _cf ) field . unpack ( source ) self . append ( field )
Read the FieldTable from the file - like object source .
67
12
3,191
def pack ( self , out : IO ) : out . write ( pack ( '>H' , len ( self ) ) ) for field in self . _table : field . pack ( out )
Write the FieldTable to the file - like object out .
41
12
3,192
def find ( self , * , name : str = None , type_ : str = None , f : Callable = None ) -> Iterator [ Field ] : for field in self . _table : if name is not None and field . name . value != name : continue descriptor = field . descriptor . value if type_ is not None and type_ != descriptor : continue if f is not None and n...
Iterates over the fields table yielding each matching method . Calling without any arguments is equivalent to iterating over the table .
92
24
3,193
def is_valid_host ( value ) : host_validators = validators . ipv4 , validators . ipv6 , validators . domain return any ( f ( value ) for f in host_validators )
Check if given value is a valid host string .
48
10
3,194
def is_valid_url ( value ) : match = URL_REGEX . match ( value ) host_str = urlparse ( value ) . hostname return match and is_valid_host ( host_str )
Check if given value is a valid URL string .
46
10
3,195
def accepts_valid_host ( func ) : @ functools . wraps ( func ) def wrapper ( obj , value , * args , * * kwargs ) : """Run the function and return a value for a valid host. :param obj: an object in whose class the func is defined :param value: a value expected to be a valid host string :returns: a return value of the fu...
Return a wrapper that runs given method only for valid hosts .
133
12
3,196
def accepts_valid_urls ( func ) : @ functools . wraps ( func ) def wrapper ( obj , urls , * args , * * kwargs ) : """Run the function and return a value for valid URLs. :param obj: an object in whose class f is defined :param urls: an iterable containing URLs :returns: a return value of the function f :raises InvalidUR...
Return a wrapper that runs given method only for valid URLs .
192
12
3,197
def get ( self , index ) : constant = self . _pool [ index ] if not isinstance ( constant , Constant ) : constant = _constant_types [ constant [ 0 ] ] ( self , index , * constant [ 1 : ] ) self . _pool [ index ] = constant return constant
Returns the Constant at index raising a KeyError if it does not exist .
63
15
3,198
def find ( self , type_ = None , f = None ) : for constant in self : if type_ is not None and not isinstance ( constant , type_ ) : continue if f is not None and not f ( constant ) : continue yield constant
Iterates over the pool yielding each matching Constant . Calling without any arguments is equivalent to iterating over the pool .
53
23
3,199
def pack ( self , fout ) : write = fout . write write ( pack ( '>H' , self . raw_count ) ) for constant in self : write ( constant . pack ( ) )
Write the ConstantPool to the file - like object fout .
44
13