idx
int64
0
251k
question
stringlengths
53
3.53k
target
stringlengths
5
1.23k
len_question
int64
20
893
len_target
int64
3
238
7,600
def normalize_locale ( locale ) : import re match = re . match ( r'^[a-z]+' , locale . lower ( ) ) if match : return match . group ( )
Normalize locale Extracts language code from passed in locale string to be used later for dictionaries loading .
43
21
7,601
def get_translations ( self , locale ) : locale = self . normalize_locale ( locale ) if locale in self . translations : return self . translations [ locale ] translations = { } for path in self . dirs : file = os . path . join ( path , '{}.py' . format ( locale ) ) if not os . path . isfile ( file ) : continue loader = SourceFileLoader ( locale , file ) locale_dict = loader . load_module ( ) if not hasattr ( locale_dict , 'translations' ) : continue language = getattr ( locale_dict , 'translations' ) if translations : translations = language else : merged = dict ( translations . items ( ) | language . items ( ) ) translations = merged if translations : self . translations [ locale ] = translations return translations err = 'No translations found for locale [{}]' raise NoTranslations ( err . format ( locale ) )
Get translation dictionary Returns a dictionary for locale or raises an exception if such can t be located . If a dictionary for locale was previously loaded returns that otherwise goes through registered locations and merges any found custom dictionaries with defaults .
198
45
7,602
def translate ( self , message , locale ) : translations = self . get_translations ( locale ) if message in translations : return translations [ message ] # return untranslated return message
Translate Translates a message to the given locale language . Will return original message if no translation exists for the message .
38
25
7,603
def flatten ( l ) : for el in l : # I don;t want dict to be flattened if isinstance ( el , Iterable ) and not isinstance ( el , ( str , bytes ) ) and not isinstance ( el , dict ) : yield from flatten ( el ) else : yield el
Flatten a multi - deminision list and return a iterable
65
14
7,604
def crossCombine ( l ) : resultList = [ ] firstList = l [ 0 ] rest = l [ 1 : ] if len ( rest ) == 0 : return firstList for e in firstList : for e1 in crossCombine ( rest ) : resultList . append ( combinteDict ( e , e1 ) ) return resultList
Taken a list of lists returns a big list of lists contain all the possibilities of elements of sublist combining together .
75
24
7,605
def combine ( a1 , a2 ) : if not isinstance ( a1 , list ) : a1 = [ a1 ] if not isinstance ( a2 , list ) : a2 = [ a2 ] return a1 + a2
Combine to argument into a single flat list
52
9
7,606
def singleOrPair ( obj ) : if len ( list ( obj . __class__ . __mro__ ) ) <= 2 : return 'Neither' else : # Pair check comes first for Pair is a subclass of Single if ancestorJr ( obj ) is Pair : return 'Pair' elif ancestor ( obj ) is Single : return 'Single' else : return 'Neither'
Chech an object is single or pair or neither .
80
11
7,607
def removeEverything ( toBeRemoved , l ) : successful = True while successful : try : # list.remove will remove item if equal, # which is evaluated by __eq__ l . remove ( toBeRemoved ) except : successful = False
Remove every instance that matches the input from a list
50
10
7,608
def add ( self , * value ) : flattenedValueList = list ( flatten ( value ) ) return self . _add ( flattenedValueList , self . value )
convert value and add to self . value
35
9
7,609
def _remove ( self , removeList , selfValue ) : for removeValue in removeList : print ( removeValue , removeList ) # if removeValue equal to selfValue, remove removeEverything ( removeValue , selfValue )
Remove elements from a list by matching the elements in the other list .
47
14
7,610
def remove ( self , * l ) : removeList = list ( flatten ( l ) ) self . _remove ( removeList , self . value )
remove elements from self . value by matching .
32
9
7,611
def write ( self ) : with open ( self . me , 'w' ) as f : f . write ( self . printMe ( self . tag , self . value ) )
Write the job to the corresponding plist .
38
9
7,612
def add ( self , * l ) : for a in flatten ( l ) : self . _add ( [ self . Inner ( a ) ] , self . l )
add inner to outer
36
4
7,613
def remove ( self , * l ) : for a in flatten ( l ) : self . _remove ( [ self . Inner ( a ) ] , self . l )
remove inner from outer
36
4
7,614
def add ( self , dic ) : for kw in dic : checkKey ( kw , self . keyWord ) self . _add ( [ Pair ( kw , StringSingle ( dic [ kw ] ) ) ] , self . d )
adds a dict as pair
55
6
7,615
def remove ( self , dic ) : for kw in dic : removePair = Pair ( kw , dic [ kw ] ) self . _remove ( [ removePair ] )
remove the pair by passing a identical dict
43
8
7,616
def _update ( self , baseNumber , magnification ) : interval = int ( baseNumber * magnification ) self . value = [ IntegerSingle ( interval ) ]
update self . value with basenumber and time interval
32
11
7,617
def second ( self ) : self . magnification = 1 self . _update ( self . baseNumber , self . magnification ) return self
set unit to second
27
4
7,618
def minute ( self ) : self . magnification = 60 self . _update ( self . baseNumber , self . magnification ) return self
set unit to minute
27
4
7,619
def hour ( self ) : self . magnification = 3600 self . _update ( self . baseNumber , self . magnification ) return self
set unit to hour
28
4
7,620
def day ( self ) : self . magnification = 86400 self . _update ( self . baseNumber , self . magnification ) return self
set unit to day
29
4
7,621
def week ( self ) : self . magnification = 345600 self . _update ( self . baseNumber , self . magnification ) return self
set unit to week
28
4
7,622
def add ( self , * dic ) : dicList = list ( flatten ( dic ) ) # for every dict in the list passed in for d in dicList : # make a dict single (list of pairs) di = [ ] for k in d : # checkKey(k, self.keyWord) di . append ( Pair ( k , IntegerSingle ( d [ k ] ) ) ) dictSingle = DictSingle ( di ) # append dict single to array single's value self . _add ( [ dictSingle ] , self . l )
add a config to StartCalendarInterval .
119
10
7,623
def remove ( self , * dic ) : dicList = list ( flatten ( dic ) ) for d in dicList : di = [ ] for k in d : # checkkey(k, self.keyword) di . append ( Pair ( k , IntegerSingle ( d [ k ] ) ) ) dictSingle = DictSingle ( di ) # append dict single to array single self . _remove ( [ dictSingle ] , self . l )
remove a calendar config .
98
5
7,624
def get_index_url ( self , resource = None , * * kwargs ) : default_kwargs = self . default_kwargs_for_urls ( ) if resource == self . get_resource_name ( ) else { } default_kwargs . update ( kwargs ) return self . get_full_url ( self . app . reverse ( '{}_index' . format ( resource or self . get_resource_name ( ) ) , * * default_kwargs ) )
Builds the url of the resource s index .
109
10
7,625
def get_parent ( self ) : if self . is_entity ( ) : return self . get_index_url ( * * self . default_kwargs_for_urls ( ) ) elif self . _parent is not None : resource = self . _parent . rsplit ( '_' , 1 ) [ 0 ] parts = self . default_kwargs_for_urls ( ) if '{}_id' . format ( resource ) in parts : id = parts . pop ( '{}_id' . format ( resource ) ) parts [ 'id' ] = id return self . get_full_url ( self . app . reverse ( self . _parent , * * parts ) )
Returns the url to the parent endpoint .
152
8
7,626
def export_context ( cls , context ) : if context is None : return result = [ ( x . context_name ( ) , x . context_value ( ) ) for x in context ] result . reverse ( ) return tuple ( result )
Export the specified context to be capable context transferring
52
9
7,627
def match ( self , command_context = None , * * command_env ) : spec = self . specification ( ) if command_context is None and spec is None : return True elif command_context is not None and spec is not None : return command_context == spec return False
Check if context request is compatible with adapters specification . True - if compatible False - otherwise
60
17
7,628
def any_shared ( enum_one , enum_two ) : if not is_collection ( enum_one ) or not is_collection ( enum_two ) : return False enum_one = enum_one if isinstance ( enum_one , ( set , dict ) ) else set ( enum_one ) enum_two = enum_two if isinstance ( enum_two , ( set , dict ) ) else set ( enum_two ) return any ( e in enum_two for e in enum_one )
Truthy if any element in enum_one is present in enum_two
108
15
7,629
def match ( self , request , service ) : uri = self . normalize_uri ( request . path ( ) ) if request . session ( ) . protocol ( ) not in self . protocols : return if request . method ( ) not in self . methods : return if self . virtual_hosts and request . virtual_host ( ) not in self . virtual_hosts : return if self . ports and int ( request . session ( ) . server_address ( ) . port ( ) ) not in self . ports : return match_obj = self . re_pattern . match ( uri ) if not match_obj : return presenter_action = self . action presenter_args = self . presenter_args . copy ( ) for i in range ( len ( self . route_args ) ) : if self . route_args [ i ] == 'action' : presenter_action = match_obj . group ( i + 1 ) else : presenter_args [ self . route_args [ i ] ] = match_obj . group ( i + 1 ) return WWebTargetRoute ( self . presenter , presenter_action , self , service . route_map ( ) , * * presenter_args )
Check this route for matching the given request . If this route is matched then target route is returned .
252
20
7,630
def connect ( self , pattern , presenter , * * kwargs ) : self . __routes . append ( WWebRoute ( pattern , presenter , * * kwargs ) )
Connect the given pattern with the given presenter
40
8
7,631
def import_route ( self , route_as_txt ) : route_match = WWebRouteMap . import_route_re . match ( route_as_txt ) if route_match is None : raise ValueError ( 'Invalid route code' ) pattern = route_match . group ( 1 ) presenter_name = route_match . group ( 2 ) route_args = route_match . group ( 4 ) # may be None if route_args is not None : result_args = { } for arg_declaration in route_args . split ( "," ) : arg_match = WWebRouteMap . import_route_arg_re . match ( arg_declaration ) if arg_match is None : raise RuntimeError ( 'Invalid argument declaration in route' ) result_args [ arg_match . group ( 1 ) ] = arg_match . group ( 3 ) self . connect ( pattern , presenter_name , * * result_args ) else : self . connect ( pattern , presenter_name )
Import route written as a string
215
6
7,632
def process_request ( self , session ) : debugger = self . debugger ( ) debugger_session_id = debugger . session_id ( ) if debugger is not None else None try : request = session . read_request ( ) if debugger_session_id is not None : debugger . request ( debugger_session_id , request , session . protocol_version ( ) , session . protocol ( ) ) try : target_route = self . route_map ( ) . route ( request , self ) if debugger_session_id is not None : debugger . target_route ( debugger_session_id , target_route ) if target_route is not None : response = self . execute ( request , target_route ) else : presenter_cls = self . route_map ( ) . error_presenter ( ) presenter = presenter_cls ( request ) response = presenter . error_code ( code = 404 ) if debugger_session_id is not None : debugger . response ( debugger_session_id , response ) except Exception as e : if debugger_session_id is not None : debugger . exception ( debugger_session_id , e ) presenter_cls = self . route_map ( ) . error_presenter ( ) presenter = presenter_cls ( request ) response = presenter . exception_error ( e ) session . write_response ( request , response , * response . __pushed_responses__ ( ) ) except Exception as e : if debugger_session_id is not None : debugger . exception ( debugger_session_id , e ) session . session_close ( ) if debugger_session_id is not None : debugger . finalize ( debugger_session_id )
Process single request from the given session
357
7
7,633
def create_presenter ( self , request , target_route ) : presenter_name = target_route . presenter_name ( ) if self . presenter_collection ( ) . has ( presenter_name ) is False : raise RuntimeError ( 'No such presenter: %s' % presenter_name ) presenter_class = self . presenter_collection ( ) . presenter ( presenter_name ) return self . presenter_factory ( ) . instantiate ( presenter_class , request , target_route , self )
Create presenter from the given requests and target routes
106
9
7,634
def proxy ( self , request , original_target_route , presenter_name , * * kwargs ) : action_kwargs = kwargs . copy ( ) action_name = 'index' if 'action' in action_kwargs : action_name = action_kwargs [ 'action' ] action_kwargs . pop ( 'action' ) original_route = original_target_route . route ( ) original_route_map = original_target_route . route_map ( ) target_route = WWebTargetRoute ( presenter_name , action_name , original_route , original_route_map , * * action_kwargs ) return self . execute ( request , target_route )
Execute the given presenter as a target for the given client request
152
13
7,635
def find_point_in_section_list ( point , section_list ) : if point < section_list [ 0 ] or point > section_list [ - 1 ] : return None if point in section_list : if point == section_list [ - 1 ] : return section_list [ - 2 ] ind = section_list . bisect ( point ) - 1 if ind == 0 : return section_list [ 0 ] return section_list [ ind ] try : ind = section_list . bisect ( point ) return section_list [ ind - 1 ] except IndexError : return None
Returns the start of the section the given point belongs to .
126
12
7,636
def find_range_ix_in_section_list ( start , end , section_list ) : if start > section_list [ - 1 ] or end < section_list [ 0 ] : return [ 0 , 0 ] if start < section_list [ 0 ] : start_section = section_list [ 0 ] else : start_section = find_point_in_section_list ( start , section_list ) if end > section_list [ - 1 ] : end_section = section_list [ - 2 ] else : end_section = find_point_in_section_list ( end , section_list ) return [ section_list . index ( start_section ) , section_list . index ( end_section ) + 1 ]
Returns the index range all sections belonging to the given range .
160
12
7,637
def find_range_in_section_list ( start , end , section_list ) : ind = find_range_ix_in_section_list ( start , end , section_list ) return section_list [ ind [ 0 ] : ind [ 1 ] ]
Returns all sections belonging to the given range .
57
9
7,638
def find_range_ix_in_point_list ( start , end , point_list ) : return [ point_list . bisect_left ( start ) , point_list . bisect_right ( end ) ]
Returns the index range all points inside the given range .
48
11
7,639
def split_option ( self , section , option ) : value = self [ section ] [ option ] . strip ( ) if value == "" : return [ ] return [ x . strip ( ) for x in ( value . split ( "," ) ) ]
Return list of strings that are made by splitting coma - separated option value . Method returns empty list if option value is empty string
53
25
7,640
def merge ( self , config ) : if isinstance ( config , ConfigParser ) is True : self . update ( config ) elif isinstance ( config , str ) : self . read ( config )
Load configuration from given configuration .
42
6
7,641
def merge_section ( self , config , section_to , section_from = None ) : section_from = section_from if section_from is not None else section_to if section_from not in config . sections ( ) : raise ValueError ( 'There is no such section "%s" in config' % section_from ) if section_to not in self . sections ( ) : self . add_section ( section_to ) for option in config [ section_from ] . keys ( ) : self . set ( section_to , option , config [ section_from ] [ option ] )
Load configuration section from other configuration . If specified section doesn t exist in current configuration then it will be added automatically .
127
23
7,642
def __option ( self ) : section = self . section ( ) option = self . option_prefix ( ) if self . config ( ) . has_option ( section , option ) is False : raise NoOptionError ( option , section ) return section , option
Check and return option from section from configuration . Option name is equal to option prefix
54
16
7,643
def select_options ( self , options_prefix ) : return WConfigSelection ( self . config ( ) , self . section ( ) , self . option_prefix ( ) + options_prefix )
Select options from this selection that are started with the specified prefix
42
12
7,644
def has_option ( self , option_name = None ) : if option_name is None : option_name = '' return self . config ( ) . has_option ( self . section ( ) , self . option_prefix ( ) + option_name )
Check whether configuration selection has the specified option .
55
9
7,645
def _args_checks_gen ( self , decorated_function , function_spec , arg_specs ) : inspected_args = function_spec . args args_check = { } for i in range ( len ( inspected_args ) ) : arg_name = inspected_args [ i ] if arg_name in arg_specs . keys ( ) : args_check [ arg_name ] = self . check ( arg_specs [ arg_name ] , arg_name , decorated_function ) return args_check
Generate checks for positional argument testing
111
7
7,646
def _kwargs_checks_gen ( self , decorated_function , function_spec , arg_specs ) : args_names = [ ] args_names . extend ( function_spec . args ) if function_spec . varargs is not None : args_names . append ( function_spec . args ) args_check = { } for arg_name in arg_specs . keys ( ) : if arg_name not in args_names : args_check [ arg_name ] = self . check ( arg_specs [ arg_name ] , arg_name , decorated_function ) return args_check
Generate checks for keyword argument testing
131
7
7,647
def decorator ( self , * * arg_specs ) : if self . decorate_disabled ( ) is True : def empty_decorator ( decorated_function ) : return decorated_function return empty_decorator def first_level_decorator ( decorated_function ) : function_spec = getfullargspec ( decorated_function ) args_checks = self . _args_checks_gen ( decorated_function , function_spec , arg_specs ) varargs_check = self . _varargs_checks_gen ( decorated_function , function_spec , arg_specs ) kwargs_checks = self . _kwargs_checks_gen ( decorated_function , function_spec , arg_specs ) def second_level_decorator ( original_function , * args , * * kwargs ) : self . _args_checks_test ( original_function , function_spec , args_checks , args , arg_specs ) self . _varargs_checks_test ( original_function , function_spec , varargs_check , args , arg_specs ) self . _kwargs_checks_test ( original_function , kwargs_checks , kwargs , arg_specs ) return original_function ( * args , * * kwargs ) return decorator ( second_level_decorator ) ( decorated_function ) return first_level_decorator
Return decorator that can decorate target function
307
9
7,648
def function_name ( fn ) : fn_name = fn . __name__ if hasattr ( fn , '__qualname__' ) : return fn . __qualname__ elif hasattr ( fn , '__self__' ) : owner = fn . __self__ if isclass ( owner ) is False : owner = owner . __class__ return '%s.%s' % ( owner . __name__ , fn_name ) return fn_name
Return function name in pretty style
99
6
7,649
def check ( self , type_spec , arg_name , decorated_function ) : def raise_exception ( x_spec ) : exc_text = 'Argument "%s" for function "%s" has invalid type' % ( arg_name , Verifier . function_name ( decorated_function ) ) exc_text += ' (%s should be %s)' % ( x_spec , type_spec ) raise TypeError ( exc_text ) if isinstance ( type_spec , ( tuple , list , set ) ) : for single_type in type_spec : if ( single_type is not None ) and isclass ( single_type ) is False : raise RuntimeError ( 'Invalid specification. Must be type or tuple/list/set of types' ) if None in type_spec : type_spec = tuple ( filter ( lambda x : x is not None , type_spec ) ) return lambda x : None if x is None or isinstance ( x , tuple ( type_spec ) ) is True else raise_exception ( str ( ( type ( x ) ) ) ) else : return lambda x : None if isinstance ( x , tuple ( type_spec ) ) is True else raise_exception ( str ( ( type ( x ) ) ) ) elif isclass ( type_spec ) : return lambda x : None if isinstance ( x , type_spec ) is True else raise_exception ( str ( ( type ( x ) ) ) ) else : raise RuntimeError ( 'Invalid specification. Must be type or tuple/list/set of types' )
Return callable that checks function parameter for type validity . Checks parameter if it is instance of specified class or classes
335
22
7,650
def check ( self , type_spec , arg_name , decorated_function ) : def raise_exception ( text_spec ) : exc_text = 'Argument "%s" for function "%s" has invalid type' % ( arg_name , Verifier . function_name ( decorated_function ) ) exc_text += ' (%s)' % text_spec raise TypeError ( exc_text ) if isinstance ( type_spec , ( tuple , list , set ) ) : for single_type in type_spec : if ( single_type is not None ) and isclass ( single_type ) is False : raise RuntimeError ( 'Invalid specification. Must be type or tuple/list/set of types' ) if None in type_spec : type_spec = tuple ( filter ( lambda x : x is not None , type_spec ) ) return lambda x : None if x is None or ( isclass ( x ) is True and issubclass ( x , type_spec ) is True ) else raise_exception ( str ( x ) ) else : return lambda x : None if ( isclass ( x ) is True and issubclass ( x , type_spec ) is True ) else raise_exception ( str ( x ) ) elif isclass ( type_spec ) : return lambda x : None if ( isclass ( x ) is True and issubclass ( x , type_spec ) is True ) else raise_exception ( str ( x ) ) else : raise RuntimeError ( 'Invalid specification. Must be type or tuple/list/set of types' )
Return callable that checks function parameter for class validity . Checks parameter if it is class or subclass of specified class or classes
337
24
7,651
def check ( self , value_spec , arg_name , decorated_function ) : def raise_exception ( text_spec ) : exc_text = 'Argument "%s" for function "%s" has invalid value' % ( arg_name , Verifier . function_name ( decorated_function ) ) exc_text += ' (%s)' % text_spec raise ValueError ( exc_text ) if isinstance ( value_spec , ( tuple , list , set ) ) : for single_value in value_spec : if isfunction ( single_value ) is False : raise RuntimeError ( 'Invalid specification. Must be function or tuple/list/set of functions' ) def check ( x ) : for f in value_spec : if f ( x ) is not True : raise_exception ( str ( x ) ) return check elif isfunction ( value_spec ) : return lambda x : None if value_spec ( x ) is True else raise_exception ( str ( x ) ) else : raise RuntimeError ( 'Invalid specification. Must be function or tuple/list/set of functions' )
Return callable that checks function parameter for value validity . Checks parameter if its value passes specified restrictions .
236
20
7,652
def cache_control ( validator = None , storage = None ) : def default_validator ( * args , * * kwargs ) : return True if validator is None : validator = default_validator if storage is None : storage = WGlobalSingletonCacheStorage ( ) def first_level_decorator ( decorated_function ) : def second_level_decorator ( original_function , * args , * * kwargs ) : validator_check = validator ( original_function , * args , * * kwargs ) cache_entry = storage . get_cache ( original_function , * args , * * kwargs ) if validator_check is not True or cache_entry . has_value is False : result = original_function ( * args , * * kwargs ) storage . put ( result , original_function , * args , * * kwargs ) return result else : return cache_entry . cached_value return decorator ( second_level_decorator ) ( decorated_function ) return first_level_decorator
Decorator that is used for caching result .
232
10
7,653
def has ( self , decorated_function , * args , * * kwargs ) : return self . get_cache ( decorated_function , * args , * * kwargs ) . has_value
Check if there is a result for given function
43
9
7,654
def __check ( self , decorated_function , * args , * * kwargs ) : # TODO replace this function with decorator which can be turned off like verify_* does if len ( args ) >= 1 : obj = args [ 0 ] function_name = decorated_function . __name__ if hasattr ( obj , function_name ) is True : fn = getattr ( obj , function_name ) if callable ( fn ) and fn . __self__ == obj : return raise RuntimeError ( 'Only bounded methods are allowed' )
Check whether function is a bounded method or not . If check fails then exception is raised
116
17
7,655
def ensure_dir ( directory : str ) -> None : if not os . path . isdir ( directory ) : LOG . debug ( f"Directory {directory} does not exist, creating it." ) os . makedirs ( directory )
Create a directory if it doesn t exist .
50
9
7,656
def expand ( directory : str ) -> str : temp1 = os . path . expanduser ( directory ) return os . path . expandvars ( temp1 )
Apply expanduser and expandvars to directory to expand ~ and env vars .
34
17
7,657
def generate_downloader ( headers : Dict [ str , str ] , args : Any , max_per_hour : int = 30 ) -> Callable [ ... , None ] : def _downloader ( url : str , dest : str ) -> None : @ rate_limited ( max_per_hour , args ) def _rate_limited_download ( ) -> None : # Create parent directory of file, and its parents, if they don't exist. parent = os . path . dirname ( dest ) if not os . path . exists ( parent ) : os . makedirs ( parent ) response = requests . get ( url , headers = headers , stream = True ) LOG . info ( f"Downloading from '{url}'." ) LOG . info ( f"Trying to save to '{dest}'." ) length = response . headers . get ( "content-length" ) if length is None : total_length = 0 else : total_length = int ( length ) expected_size = ( total_length / CHUNK_SIZE ) + 1 chunks = response . iter_content ( chunk_size = CHUNK_SIZE ) open ( dest , "a" , encoding = FORCED_ENCODING ) . close ( ) # per http://stackoverflow.com/a/20943461 with open ( dest , "wb" ) as stream : for chunk in tui . progress . bar ( chunks , expected_size = expected_size ) : if not chunk : return stream . write ( chunk ) stream . flush ( ) _rate_limited_download ( ) return _downloader
Create function to download with rate limiting and text progress .
343
11
7,658
def parse_int_string ( int_string : str ) -> List [ int ] : cleaned = " " . join ( int_string . strip ( ) . split ( ) ) cleaned = cleaned . replace ( " - " , "-" ) cleaned = cleaned . replace ( "," , " " ) tokens = cleaned . split ( " " ) indices : Set [ int ] = set ( ) for token in tokens : if "-" in token : endpoints = token . split ( "-" ) if len ( endpoints ) != 2 : LOG . info ( f"Dropping '{token}' as invalid - weird range." ) continue start = int ( endpoints [ 0 ] ) end = int ( endpoints [ 1 ] ) + 1 indices = indices . union ( indices , set ( range ( start , end ) ) ) else : try : indices . add ( int ( token ) ) except ValueError : LOG . info ( f"Dropping '{token}' as invalid - not an int." ) return list ( indices )
Given a string like 1 23 4 - 8 32 1 return a unique list of those integers in the string and the integers in the ranges in the string . Non - numbers ignored . Not necessarily sorted
216
39
7,659
def set_up_logging ( log_filename : str = "log" , verbosity : int = 0 ) -> logging . Logger : LOG . setLevel ( logging . DEBUG ) # Log everything verbosely to a file. file_handler = RotatingFileHandler ( filename = log_filename , maxBytes = 1024000000 , backupCount = 10 ) verbose_form = logging . Formatter ( fmt = "%(asctime)s - %(levelname)s - %(module)s - %(message)s" ) file_handler . setFormatter ( verbose_form ) file_handler . setLevel ( logging . DEBUG ) LOG . addHandler ( file_handler ) # Provide a stdout handler logging at INFO. stream_handler = logging . StreamHandler ( sys . stdout ) simple_form = logging . Formatter ( fmt = "%(message)s" ) stream_handler . setFormatter ( simple_form ) if verbosity > 0 : stream_handler . setLevel ( logging . DEBUG ) else : stream_handler . setLevel ( logging . INFO ) LOG . addHandler ( stream_handler ) return LOG
Set up proper logging .
244
5
7,660
def random_line ( file_path : str , encoding : str = FORCED_ENCODING ) -> str : # Fancy alg from http://stackoverflow.com/a/35579149 to avoid loading full file. line_num = 0 selected_line = "" with open ( file_path , encoding = encoding ) as stream : while True : line = stream . readline ( ) if not line : break line_num += 1 if random . uniform ( 0 , line_num ) < 1 : selected_line = line return selected_line . strip ( )
Get random line from a file .
122
7
7,661
def get_percentage_from_prob ( prob ) : assert isinstance ( prob , ( float , int ) ) prob = float ( prob ) assert prob >= 0 assert prob <= 1 percentages = list ( probability_list . keys ( ) ) percentages . sort ( ) for percentage in percentages : if prob < probability_list [ percentage ] : return percentage - 1 return 100
Converted probability of being treated to total percentage of clinical cases treated
78
13
7,662
def listify ( generator_func ) : def list_func ( * args , * * kwargs ) : return degenerate ( generator_func ( * args , * * kwargs ) ) return list_func
Converts generator functions into list returning functions .
46
9
7,663
def locations_within ( a , b , tolerance ) : ret = '' # Clone b so that we can destroy it. b = dict ( b ) for ( key , value ) in a . items ( ) : if key not in b : raise ValueError ( "b does not have the key: " + key ) if abs ( int ( value ) - int ( b [ key ] ) ) > tolerance : ret += 'key {0} differs: {1} {2}' . format ( key , int ( value ) , int ( b [ key ] ) ) del b [ key ] if b : raise ValueError ( "keys in b not seen in a: " + ", " . join ( b . keys ( ) ) ) return ret
Verifies whether two positions are the same . A tolerance value determines how close the two positions must be to be considered same .
156
25
7,664
def ctrl_x ( self , x , to = None ) : seq = [ Keys . CONTROL , x , Keys . CONTROL ] # This works around a bug in Selenium that happens in FF on # Windows, and in Chrome on Linux. # # The bug was reported here: # # https://code.google.com/p/selenium/issues/detail?id=7303 # if ( self . firefox and self . windows ) or ( self . linux and self . chrome ) : seq . append ( Keys . PAUSE ) if to is None : ActionChains ( self . driver ) . send_keys ( seq ) . perform ( ) else : self . send_keys ( to , seq )
Sends a character to the currently active element with Ctrl pressed . This method takes care of pressing and releasing Ctrl .
150
23
7,665
def command_x ( self , x , to = None ) : if to is None : ActionChains ( self . driver ) . send_keys ( [ Keys . COMMAND , x , Keys . COMMAND ] ) . perform ( ) else : self . send_keys ( to , [ Keys . COMMAND , x , Keys . COMMAND ] )
Sends a character to the currently active element with Command pressed . This method takes care of pressing and releasing Command .
74
23
7,666
def wait ( self , condition ) : return WebDriverWait ( self . driver , self . timeout ) . until ( condition )
Waits for a condition to be true .
26
9
7,667
def wait_until_not ( self , condition ) : return WebDriverWait ( self . driver , self . timeout ) . until_not ( condition )
Waits for a condition to be false .
32
9
7,668
def persistence2stats ( rev_docs , min_persisted = 5 , min_visible = 1209600 , include = None , exclude = None , verbose = False ) : rev_docs = mwxml . utilities . normalize ( rev_docs ) min_persisted = int ( min_persisted ) min_visible = int ( min_visible ) include = include if include is not None else lambda t : True exclude = exclude if exclude is not None else lambda t : False for rev_doc in rev_docs : persistence_doc = rev_doc [ 'persistence' ] stats_doc = { 'tokens_added' : 0 , 'persistent_tokens' : 0 , 'non_self_persistent_tokens' : 0 , 'sum_log_persisted' : 0 , 'sum_log_non_self_persisted' : 0 , 'sum_log_seconds_visible' : 0 , 'censored' : False , 'non_self_censored' : False } filtered_docs = ( t for t in persistence_doc [ 'tokens' ] if include ( t [ 'text' ] ) and not exclude ( t [ 'text' ] ) ) for token_doc in filtered_docs : if verbose : sys . stderr . write ( "." ) sys . stderr . flush ( ) stats_doc [ 'tokens_added' ] += 1 stats_doc [ 'sum_log_persisted' ] += log ( token_doc [ 'persisted' ] + 1 ) stats_doc [ 'sum_log_non_self_persisted' ] += log ( token_doc [ 'non_self_persisted' ] + 1 ) stats_doc [ 'sum_log_seconds_visible' ] += log ( token_doc [ 'seconds_visible' ] + 1 ) # Look for time threshold if token_doc [ 'seconds_visible' ] >= min_visible : stats_doc [ 'persistent_tokens' ] += 1 stats_doc [ 'non_self_persistent_tokens' ] += 1 else : # Look for review threshold stats_doc [ 'persistent_tokens' ] += token_doc [ 'persisted' ] >= min_persisted stats_doc [ 'non_self_persistent_tokens' ] += token_doc [ 'non_self_persisted' ] >= min_persisted # Check for censoring if persistence_doc [ 'seconds_possible' ] < min_visible : stats_doc [ 'censored' ] = True stats_doc [ 'non_self_censored' ] = True else : if persistence_doc [ 'revisions_processed' ] < min_persisted : stats_doc [ 'censored' ] = True if persistence_doc [ 'non_self_processed' ] < min_persisted : stats_doc [ 'non_self_censored' ] = True if verbose : sys . stderr . write ( "\n" ) sys . stderr . flush ( ) rev_doc [ 'persistence' ] . update ( stats_doc ) yield rev_doc
Processes a sorted and page - partitioned sequence of revision documents into and adds statistics to the persistence field each token added in the revision persisted through future revisions .
690
32
7,669
def healthy ( self ) : state = None for sensor in self . _sensors . values ( ) : if sensor . healthy ( ) is False : if state is None or sensor . severity ( ) . value > state . value : state = sensor . severity ( ) if state == WTaskHealthSensor . WTaskSensorSeverity . critical : break return state
Return task health . If None - task is healthy otherwise - maximum severity of sensors
76
16
7,670
def preproc ( self , which = 'sin' , * * kwargs ) : self . app_main ( * * kwargs ) config = self . exp_config config [ 'infile' ] = infile = osp . join ( config [ 'expdir' ] , 'input.dat' ) func = getattr ( np , which ) # np.sin, np.cos or np.tan data = func ( np . linspace ( - np . pi , np . pi ) ) self . logger . info ( 'Saving input data to %s' , infile ) np . savetxt ( infile , data )
Create preprocessing data
138
4
7,671
def mounts ( cls ) : result = [ ] with open ( cls . __mounts_file__ ) as f : for mount_record in f : result . append ( WMountPoint ( mount_record ) ) return tuple ( result )
Return tuple of current mount points
52
6
7,672
def mount_point ( cls , file_path ) : mount = None for mp in cls . mounts ( ) : mp_path = mp . path ( ) if file_path . startswith ( mp_path ) is True : if mount is None or len ( mount . path ( ) ) <= len ( mp_path ) : mount = mp return mount
Return mount point that where the given path is reside on
77
11
7,673
def mount ( cls , device , mount_directory , fs = None , options = None , cmd_timeout = None , sudo = False ) : cmd = [ ] if sudo is False else [ 'sudo' ] cmd . extend ( [ 'mount' , device , os . path . abspath ( mount_directory ) ] ) if fs is not None : cmd . extend ( [ '-t' , fs ] ) if options is not None and len ( options ) > 0 : cmd . append ( '-o' ) cmd . extend ( options ) subprocess . check_output ( cmd , timeout = cmd_timeout )
Mount a device to mount directory
131
6
7,674
def get_org_types ( self ) : if not self . client . session_id : self . client . request_session ( ) object_query = "SELECT Objects() FROM OrganizationType" result = self . client . execute_object_query ( object_query = object_query ) msql_result = result [ 'body' ] [ "ExecuteMSQLResult" ] return self . package_org_types ( msql_result [ "ResultValue" ] [ "ObjectSearchResult" ] [ "Objects" ] [ "MemberSuiteObject" ] )
Retrieves all current OrganizationType objects
122
8
7,675
def package_org_types ( self , obj_list ) : org_type_list = [ ] for obj in obj_list : sane_obj = convert_ms_object ( obj [ 'Fields' ] [ 'KeyValueOfstringanyType' ] ) org = OrganizationType ( sane_obj ) org_type_list . append ( org ) return org_type_list
Loops through MS objects returned from queries to turn them into OrganizationType objects and pack them into a list for later use .
82
25
7,676
def get_individuals_for_primary_organization ( self , organization ) : if not self . client . session_id : self . client . request_session ( ) object_query = ( "SELECT Objects() FROM Individual WHERE " "PrimaryOrganization = '{}'" . format ( organization . membersuite_account_num ) ) result = self . client . execute_object_query ( object_query ) msql_result = result [ "body" ] [ "ExecuteMSQLResult" ] if msql_result [ "Success" ] : membersuite_objects = ( msql_result [ "ResultValue" ] [ "ObjectSearchResult" ] [ "Objects" ] ) else : raise ExecuteMSQLError ( result = result ) individuals = [ ] if membersuite_objects is not None : for membersuite_object in membersuite_objects [ "MemberSuiteObject" ] : individuals . append ( Individual ( membersuite_object_data = membersuite_object ) ) return individuals
Returns all Individuals that have organization as a primary org .
224
11
7,677
def match ( self , keys , partial = True ) : if not partial and len ( keys ) != self . length : return False c = 0 for k in keys : if c >= self . length : return False a = self . keys [ c ] if a != "*" and k != "*" and k != a : return False c += 1 return True
Check if the value of this namespace is matched by keys
76
11
7,678
def container ( self , data = None ) : if data is None : data = { } root = p = d = { } j = 0 k = None for k in self : d [ k ] = { } p = d d = d [ k ] if k is not None : p [ k ] = data return ( root , p [ k ] )
Creates a dict built from the keys of this namespace
75
11
7,679
def update_index ( self ) : # update index idx = { } for _ , p in sorted ( self . permissions . items ( ) , key = lambda x : str ( x [ 0 ] ) ) : branch = idx parent_p = const . PERM_DENY for k in p . namespace . keys : if not k in branch : branch [ k ] = { "__" : parent_p } branch [ k ] . update ( __implicit = True ) branch = branch [ k ] parent_p = branch [ "__" ] branch [ "__" ] = p . value branch [ "__implicit" ] = False self . index = idx # update read access map ramap = { } def update_ramap ( branch_idx ) : r = { "__" : False } for k , v in list ( branch_idx . items ( ) ) : if k != "__" and k != "__implicit" : r [ k ] = update_ramap ( v ) if branch_idx [ "__" ] is not None and ( branch_idx [ "__" ] & const . PERM_READ ) != 0 : r [ "__" ] = True return r for k , v in list ( idx . items ( ) ) : ramap [ k ] = update_ramap ( v ) self . read_access_map = ramap return self . index
Regenerates the permission index for this set
306
9
7,680
def get_permissions ( self , namespace , explicit = False ) : if not isinstance ( namespace , Namespace ) : namespace = Namespace ( namespace ) keys = namespace . keys p , _ = self . _check ( keys , self . index , explicit = explicit ) return p
Returns the permissions level for the specified namespace
59
8
7,681
def check ( self , namespace , level , explicit = False ) : return ( self . get_permissions ( namespace , explicit = explicit ) & level ) != 0
Checks if the permset has permission to the specified namespace at the specified level
34
17
7,682
def hash ( self , key , message = None ) : hmac_obj = hmac . HMAC ( key , self . __digest_generator , backend = default_backend ( ) ) if message is not None : hmac_obj . update ( message ) return hmac_obj . finalize ( )
Return digest of the given message and key
68
8
7,683
def call_with_search_field ( self , name , callback ) : done = False while not done : def check ( * _ ) : if name in self . _search_fields : return True # Force a refetch self . _found_fields = None return False self . util . wait ( check ) field = self . _search_fields [ name ] try : callback ( field ) done = True except StaleElementReferenceException : # We force a refetch of the fields self . _found_fields = None
Calls a piece of code with the DOM element that corresponds to a search field of the table .
109
20
7,684
def determine_keymap ( qteMain = None ) : if qteMain is None : # This case should only happen for testing purposes. qte_global . Qt_key_map = default_qt_keymap qte_global . Qt_modifier_map = default_qt_modifier_map else : doc = 'Conversion table from local characters to Qt constants' qteMain . qteDefVar ( "Qt_key_map" , default_qt_keymap , doc = doc ) doc = 'Conversion table from local modifier keys to Qt constants' qteMain . qteDefVar ( "Qt_modifier_map" , default_qt_modifier_map , doc = doc )
Return the conversion from keys and modifiers to Qt constants .
157
11
7,685
def func ( name ) : # Raise condition evaluated in same call as exception addition pexdoc . addex ( TypeError , "Argument `name` is not valid" , not isinstance ( name , str ) ) return "My name is {0}" . format ( name )
r Print your name .
59
5
7,686
def disableHook ( self , msgObj ) : # Unpack the data structure. macroName , keysequence = msgObj . data if macroName != self . qteMacroName ( ) : self . qteMain . qtesigKeyseqComplete . disconnect ( self . disableHook ) self . killListIdx = - 1
Disable yank - pop .
72
6
7,687
def clearHighlighting ( self ) : SCI = self . qteWidget self . qteWidget . SCISetStylingEx ( 0 , 0 , self . styleOrig ) # Clear out the match set and reset the match index. self . selMatchIdx = 1 self . matchList = [ ]
Restore the original style properties of all matches .
66
10
7,688
def highlightNextMatch ( self ) : # If this method was called on an empty input field (ie. # if the user hit <ctrl>+s again) then pick the default # selection. if self . qteText . toPlainText ( ) == '' : self . qteText . setText ( self . defaultChoice ) return # If the mathIdx variable is out of bounds (eg. the last possible # match is already selected) then wrap it around. if self . selMatchIdx < 0 : self . selMatchIdx = 0 return if self . selMatchIdx >= len ( self . matchList ) : self . selMatchIdx = 0 return # Shorthand. SCI = self . qteWidget # Undo the highlighting of the previously selected match. start , stop = self . matchList [ self . selMatchIdx - 1 ] line , col = SCI . lineIndexFromPosition ( start ) SCI . SendScintilla ( SCI . SCI_STARTSTYLING , start , 0xFF ) SCI . SendScintilla ( SCI . SCI_SETSTYLING , stop - start , 30 ) # Highlight the next match. start , stop = self . matchList [ self . selMatchIdx ] SCI . SendScintilla ( SCI . SCI_STARTSTYLING , start , 0xFF ) SCI . SendScintilla ( SCI . SCI_SETSTYLING , stop - start , 31 ) # Place the cursor at the start of the currently selected match. line , col = SCI . lineIndexFromPosition ( start ) SCI . setCursorPosition ( line , col ) self . selMatchIdx += 1
Select and highlight the next match in the set of matches .
379
12
7,689
def nextMode ( self ) : # Terminate the replacement procedure if the no match was found. if len ( self . matchList ) == 0 : self . qteAbort ( QtmacsMessage ( ) ) self . qteMain . qteKillMiniApplet ( ) return self . queryMode += 1 if self . queryMode == 1 : # Disconnect the text-changed slot because no real time # highlighting is necessary when entering the replacement # string, unlike when entering the string to replace. self . qteText . textChanged . disconnect ( self . qteTextChanged ) # Store the string to replace and clear out the query field. self . toReplace = self . qteText . toPlainText ( ) self . qteText . clear ( ) self . qteTextPrefix . setText ( 'mode 1' ) elif self . queryMode == 2 : # Mode two is to replace or skip individual matches. For # this purpose rebind the "n", "!", and <space> keys # with the respective macros to facilitate it. register = self . qteMain . qteRegisterMacro bind = self . qteMain . qteBindKeyWidget # Unbind all keys from the input widget. self . qteMain . qteUnbindAllFromWidgetObject ( self . qteText ) macroName = register ( self . ReplaceAll , replaceMacro = True ) bind ( '!' , macroName , self . qteText ) macroName = register ( self . ReplaceNext , replaceMacro = True ) bind ( '<space>' , macroName , self . qteText ) macroName = register ( self . SkipNext , replaceMacro = True ) bind ( 'n' , macroName , self . qteText ) macroName = register ( self . Abort , replaceMacro = True ) bind ( 'q' , macroName , self . qteText ) bind ( '<enter>' , macroName , self . qteText ) self . toReplaceWith = self . qteText . toPlainText ( ) self . qteTextPrefix . setText ( 'mode 2' ) self . qteText . setText ( '<space> to replace, <n> to skip, ' '<!> to replace all.' ) else : self . qteAbort ( QtmacsMessage ( ) ) self . qteMain . qteKillMiniApplet ( )
Put the search - replace macro into the next stage . The first stage is the query stage to ask the user for the string to replace the second stage is to query the string to replace it with and the third allows to replace or skip individual matches or replace them all automatically .
521
55
7,690
def replaceAll ( self ) : while self . replaceSelected ( ) : pass self . qteWidget . SCISetStylingEx ( 0 , 0 , self . styleOrig ) self . qteMain . qteKillMiniApplet ( )
Replace all matches after the current cursor position .
53
10
7,691
def compileMatchList ( self ) : # Get the new sub-string to search for. self . matchList = [ ] # Return immediately if the input field is empty. numChar = len ( self . toReplace ) if numChar == 0 : return # Compile a list of all sub-string spans. stop = 0 text = self . qteWidget . text ( ) while True : start = text . find ( self . toReplace , stop ) if start == - 1 : break else : stop = start + numChar self . matchList . append ( ( start , stop ) )
Compile the list of spans of every match .
125
10
7,692
def replaceSelected ( self ) : SCI = self . qteWidget # Restore the original styling. self . qteWidget . SCISetStylingEx ( 0 , 0 , self . styleOrig ) # Select the region spanned by the string to replace. start , stop = self . matchList [ self . selMatchIdx ] line1 , col1 = SCI . lineIndexFromPosition ( start ) line2 , col2 = SCI . lineIndexFromPosition ( stop ) SCI . setSelection ( line1 , col1 , line2 , col2 ) text = SCI . selectedText ( ) text = re . sub ( self . toReplace , self . toReplaceWith , text ) # Replace that region with the new string and move the cursor # to the end of that string. SCI . replaceSelectedText ( text ) line , col = SCI . lineIndexFromPosition ( start + len ( text ) ) SCI . setCursorPosition ( line , col ) # Backup the new document style bits. line , col = SCI . getNumLinesAndColumns ( ) text , style = self . qteWidget . SCIGetStyledText ( ( 0 , 0 , line , col ) ) self . styleOrig = style # Determine if this was the last entry in the match list. if len ( self . matchList ) == self . selMatchIdx + 1 : return False else : self . highlightAllMatches ( ) return True
Replace the currently selected string with the new one .
319
11
7,693
def scan_band ( self , band , * * kwargs ) : kal_run_line = fn . build_kal_scan_band_string ( self . kal_bin , band , kwargs ) raw_output = subprocess . check_output ( kal_run_line . split ( ' ' ) , stderr = subprocess . STDOUT ) kal_normalized = fn . parse_kal_scan ( raw_output ) return kal_normalized
Run Kalibrate for a band .
108
8
7,694
def scan_channel ( self , channel , * * kwargs ) : kal_run_line = fn . build_kal_scan_channel_string ( self . kal_bin , channel , kwargs ) raw_output = subprocess . check_output ( kal_run_line . split ( ' ' ) , stderr = subprocess . STDOUT ) kal_normalized = fn . parse_kal_channel ( raw_output ) return kal_normalized
Run Kalibrate .
108
5
7,695
def get_vars ( self ) : if self . method ( ) != 'GET' : raise RuntimeError ( 'Unable to return get vars for non-get method' ) re_search = WWebRequestProto . get_vars_re . search ( self . path ( ) ) if re_search is not None : return urllib . parse . parse_qs ( re_search . group ( 1 ) , keep_blank_values = 1 )
Parse request path and return GET - vars
100
10
7,696
def post_vars ( self ) : if self . method ( ) != 'POST' : raise RuntimeError ( 'Unable to return post vars for non-get method' ) content_type = self . content_type ( ) if content_type is None or content_type . lower ( ) != 'application/x-www-form-urlencoded' : raise RuntimeError ( 'Unable to return post vars with invalid content-type request' ) request_data = self . request_data ( ) request_data = request_data . decode ( ) if request_data is not None else '' re_search = WWebRequestProto . post_vars_re . search ( request_data ) if re_search is not None : return urllib . parse . parse_qs ( re_search . group ( 1 ) , keep_blank_values = 1 )
Parse request payload and return POST - vars
189
10
7,697
def join_path ( self , * path ) : path = self . directory_sep ( ) . join ( path ) return self . normalize_path ( path )
Unite entries to generate a single path
36
8
7,698
def full_path ( self ) : return self . normalize_path ( self . directory_sep ( ) . join ( ( self . start_path ( ) , self . session_path ( ) ) ) )
Return a full path to a current session directory . A result is made by joining a start path with current session directory
46
23
7,699
def run ( self , * * kwargs ) : from calculate import compute self . app_main ( * * kwargs ) # get the default output name output = osp . join ( self . exp_config [ 'expdir' ] , 'output.dat' ) # save the paths in the configuration self . exp_config [ 'output' ] = output # run the model data = np . loadtxt ( self . exp_config [ 'infile' ] ) out = compute ( data ) # save the output self . logger . info ( 'Saving output data to %s' , osp . relpath ( output ) ) np . savetxt ( output , out ) # store some additional information in the configuration of the # experiment self . exp_config [ 'mean' ] = mean = float ( out . mean ( ) ) self . exp_config [ 'std' ] = std = float ( out . std ( ) ) self . logger . debug ( 'Mean: %s, Standard deviation: %s' , mean , std )
Run the model
223
3