idx
int64
0
252k
question
stringlengths
48
5.28k
target
stringlengths
5
1.23k
241,600
def write_source ( self , filename ) : with open ( filename , 'w' ) as fp : return json . dump ( self . message . _elem , fp , indent = 4 , sort_keys = True )
Save source to file by calling write on the root element .
241,601
def write_source ( self , filename ) : return self . message . _elem . getroottree ( ) . write ( filename , encoding = 'utf8' )
Save XML source to file by calling write on the root element .
241,602
def group_attrib ( self ) : group_attributes = [ g . attrib for g in self . dataset . groups if self in g ] if group_attributes : return concat_namedtuples ( * group_attributes )
return a namedtuple containing all attributes attached to groups of which the given series is a member for each group of which the series is a member
241,603
def read_instance ( self , cls , sdmxobj , offset = None , first_only = True ) : if offset : try : base = self . _paths [ offset ] ( sdmxobj . _elem ) [ 0 ] except IndexError : return None else : base = sdmxobj . _elem result = self . _paths [ cls ] ( base ) if result : if first_only : return cls ( self , result [ 0 ] ...
If cls in _paths and matches return an instance of cls with the first XML element or if first_only is False a list of cls instances for all elements found If no matches were found return None .
241,604
def load_agency_profile ( cls , source ) : if not isinstance ( source , str_type ) : source = source . read ( ) new_agencies = json . loads ( source ) cls . _agencies . update ( new_agencies )
Classmethod loading metadata on a data provider . source must be a json - formated string or file - like object describing one or more data providers ( URL of the SDMX web API resource types etc . The dict Request . _agencies is updated with the metadata from the source .
241,605
def series_keys ( self , flow_id , cache = True ) : cache_id = 'series_keys_' + flow_id if cache_id in self . cache : return self . cache [ cache_id ] else : resp = self . data ( flow_id , params = { 'detail' : 'serieskeysonly' } ) l = list ( s . key for s in resp . data . series ) df = PD . DataFrame ( l , columns = l...
Get an empty dataset with all possible series keys .
241,606
def preview_data ( self , flow_id , key = None , count = True , total = True ) : all_keys = self . series_keys ( flow_id ) if not key : if count : return all_keys . shape [ 0 ] else : return all_keys key_l = { k : [ v ] if isinstance ( v , str_type ) else v for k , v in key . items ( ) } dim_names = [ k for k in all_ke...
Get keys or number of series for a prospective dataset query allowing for keys with multiple values per dimension . It downloads the complete list of series keys for a dataflow rather than using constraints and DSD . This feature is however not supported by all data providers . ECB and UNSD are known to work .
241,607
def write ( self , source = None , ** kwargs ) : if not source : source = self . msg return self . _writer . write ( source = source , ** kwargs )
Wrappe r to call the writer s write method if present .
241,608
def parse_json ( path ) : with open ( path ) as f : data = json . load ( f ) result = [ ] def assert_type ( value , typ ) : assert isinstance ( value , typ ) , '%s: Unexpected type %r' % ( path , type ( value ) . __name__ ) def assert_dict_item ( dictionary , key , typ ) : assert key in dictionary , '%s: Missing dictio...
Deserialize a JSON file containing runtime collected types .
241,609
def tokenize ( s ) : original = s tokens = [ ] while True : if not s : tokens . append ( End ( ) ) return tokens elif s [ 0 ] == ' ' : s = s [ 1 : ] elif s [ 0 ] in '()[],*' : tokens . append ( Separator ( s [ 0 ] ) ) s = s [ 1 : ] elif s [ : 2 ] == '->' : tokens . append ( Separator ( '->' ) ) s = s [ 2 : ] else : m =...
Translate a type comment into a list of tokens .
241,610
def generate_annotations_json_string ( source_path , only_simple = False ) : items = parse_json ( source_path ) results = [ ] for item in items : signature = unify_type_comments ( item . type_comments ) if is_signature_simple ( signature ) or not only_simple : data = { 'path' : item . path , 'line' : item . line , 'fun...
Produce annotation data JSON file from a JSON file with runtime - collected types .
241,611
def _my_hash ( arg_list ) : res = 0 for arg in arg_list : res = res * 31 + hash ( arg ) return res
Simple helper hash function
241,612
def name_from_type ( type_ ) : if isinstance ( type_ , ( DictType , ListType , TupleType , SetType , IteratorType ) ) : return repr ( type_ ) else : if type_ . __name__ != 'NoneType' : module = type_ . __module__ if module in BUILTIN_MODULES or module == '<unknown>' : return type_ . __name__ else : name = getattr ( typ...
Helper function to get PEP - 484 compatible string representation of our internal types .
241,613
def resolve_type ( arg ) : arg_type = type ( arg ) if arg_type == list : assert isinstance ( arg , list ) sample = arg [ : min ( 4 , len ( arg ) ) ] tentative_type = TentativeType ( ) for sample_item in sample : tentative_type . add ( resolve_type ( sample_item ) ) return ListType ( tentative_type ) elif arg_type == se...
Resolve object to one of our internal collection types or generic built - in type .
241,614
def prep_args ( arg_info ) : filtered_args = [ a for a in arg_info . args if getattr ( arg_info , 'varargs' , None ) != a ] if filtered_args and ( filtered_args [ 0 ] in ( 'self' , 'cls' ) ) : filtered_args = filtered_args [ 1 : ] pos_args = [ ] if filtered_args : for arg in filtered_args : if isinstance ( arg , str ) ...
Resolve types from ArgInfo
241,615
def _flush_signature ( key , return_type ) : signatures = collected_signatures . setdefault ( key , set ( ) ) args_info = collected_args . pop ( key ) if len ( signatures ) < MAX_ITEMS_PER_FUNCTION : signatures . add ( ( args_info , return_type ) ) num_samples [ key ] = num_samples . get ( key , 0 ) + 1
Store signature for a function .
241,616
def type_consumer ( ) : while True : item = _task_queue . get ( ) if isinstance ( item , KeyAndTypes ) : if item . key in collected_args : _flush_signature ( item . key , UnknownType ) collected_args [ item . key ] = ArgTypes ( item . types ) else : assert isinstance ( item , KeyAndReturn ) if item . key in collected_a...
Infinite loop of the type consumer thread . It gets types to process from the task query .
241,617
def _make_sampling_sequence ( n ) : seq = list ( range ( 5 ) ) i = 50 while len ( seq ) < n : seq . append ( i ) i += 50 return seq
Return a list containing the proposed call event sampling sequence .
241,618
def default_filter_filename ( filename ) : if filename is None : return None elif filename . startswith ( TOP_DIR ) : if filename . startswith ( TOP_DIR_DOT ) : return None else : return filename [ TOP_DIR_LEN : ] . lstrip ( os . sep ) elif filename . startswith ( os . sep ) : return None else : return filename
Default filter for filenames .
241,619
def _filter_types ( types_dict ) : def exclude ( k ) : return k . path . startswith ( '<' ) or k . func_name == '<module>' return { k : v for k , v in iteritems ( types_dict ) if not exclude ( k ) }
Filter type info before dumping it to the file .
241,620
def _dump_impl ( ) : filtered_signatures = _filter_types ( collected_signatures ) sorted_by_file = sorted ( iteritems ( filtered_signatures ) , key = ( lambda p : ( p [ 0 ] . path , p [ 0 ] . line , p [ 0 ] . func_name ) ) ) res = [ ] for function_key , signatures in sorted_by_file : comments = [ _make_type_comment ( a...
Internal implementation for dump_stats and dumps_stats
241,621
def dump_stats ( filename ) : res = _dump_impl ( ) f = open ( filename , 'w' ) json . dump ( res , f , indent = 4 ) f . close ( )
Write collected information to file .
241,622
def init_types_collection ( filter_filename = default_filter_filename ) : global _filter_filename _filter_filename = filter_filename sys . setprofile ( _trace_dispatch ) threading . setprofile ( _trace_dispatch )
Setup profiler hooks to enable type collection . Call this one time from the main thread .
241,623
def add ( self , type ) : try : if isinstance ( type , SetType ) : if EMPTY_SET_TYPE in self . types_hashable : self . types_hashable . remove ( EMPTY_SET_TYPE ) elif isinstance ( type , ListType ) : if EMPTY_LIST_TYPE in self . types_hashable : self . types_hashable . remove ( EMPTY_LIST_TYPE ) elif isinstance ( type ...
Add type to the runtime type samples .
241,624
def merge ( self , other ) : for hashables in other . types_hashable : self . add ( hashables ) for non_hashbles in other . types : self . add ( non_hashbles )
Merge two TentativeType instances
241,625
def infer_annotation ( type_comments ) : assert type_comments args = { } returns = set ( ) for comment in type_comments : arg_types , return_type = parse_type_comment ( comment ) for i , arg_type in enumerate ( arg_types ) : args . setdefault ( i , set ( ) ) . add ( arg_type ) returns . add ( return_type ) combined_arg...
Given some type comments return a single inferred signature .
241,626
def argument_kind ( args ) : kinds = set ( arg . kind for arg in args ) if len ( kinds ) != 1 : return None return kinds . pop ( )
Return the kind of an argument based on one or more descriptions of the argument .
241,627
def combine_types ( types ) : items = simplify_types ( types ) if len ( items ) == 1 : return items [ 0 ] else : return UnionType ( items )
Given some types return a combined and simplified type .
241,628
def simplify_types ( types ) : flattened = flatten_types ( types ) items = filter_ignored_items ( flattened ) items = [ simplify_recursive ( item ) for item in items ] items = merge_items ( items ) items = dedupe_types ( items ) items = remove_redundant_items ( items ) if len ( items ) > 3 : return [ AnyType ( ) ] else...
Given some types give simplified types representing the union of types .
241,629
def simplify_recursive ( typ ) : if isinstance ( typ , UnionType ) : return combine_types ( typ . items ) elif isinstance ( typ , ClassType ) : simplified = ClassType ( typ . name , [ simplify_recursive ( arg ) for arg in typ . args ] ) args = simplified . args if ( simplified . name == 'Dict' and len ( args ) == 2 and...
Simplify all components of a type .
241,630
def remove_redundant_items ( items ) : result = [ ] for item in items : for other in items : if item is not other and is_redundant_union_item ( item , other ) : break else : result . append ( item ) return result
Filter out redundant union items .
241,631
def is_redundant_union_item ( first , other ) : if isinstance ( first , ClassType ) and isinstance ( other , ClassType ) : if first . name == 'str' and other . name == 'Text' : return True elif first . name == 'bool' and other . name == 'int' : return True elif first . name == 'int' and other . name == 'float' : return...
If union has both items is the first one redundant?
241,632
def merge_items ( items ) : result = [ ] while items : item = items . pop ( ) merged = None for i , other in enumerate ( items ) : merged = merged_type ( item , other ) if merged : break if merged : del items [ i ] items . append ( merged ) else : result . append ( item ) return list ( reversed ( result ) )
Merge union items that can be merged .
241,633
def merged_type ( t , s ) : if isinstance ( t , TupleType ) and isinstance ( s , TupleType ) : if len ( t . items ) == len ( s . items ) : return TupleType ( [ combine_types ( [ ti , si ] ) for ti , si in zip ( t . items , s . items ) ] ) all_items = t . items + s . items if all_items and all ( item == all_items [ 0 ] ...
Return merged type if two items can be merged in to a different more general type .
241,634
def dump_annotations ( type_info , files ) : with open ( type_info ) as f : data = json . load ( f ) for item in data : path , line , func_name = item [ 'path' ] , item [ 'line' ] , item [ 'func_name' ] if files and path not in files : for f in files : if path . startswith ( os . path . join ( f , '' ) ) : break else :...
Dump annotations out of type_info filtered by files .
241,635
def strip_py ( arg ) : for ext in PY_EXTENSIONS : if arg . endswith ( ext ) : return arg [ : - len ( ext ) ] return None
Strip a trailing . py or . pyi suffix . Return None if no such suffix is found .
241,636
def get_decorators ( self , node ) : if node . parent is None : return [ ] results = { } if not self . decorated . match ( node . parent , results ) : return [ ] decorators = results . get ( 'dd' ) or [ results [ 'd' ] ] decs = [ ] for d in decorators : for child in d . children : if isinstance ( child , Leaf ) and chi...
Return a list of decorators found on a function definition .
241,637
def has_return_exprs ( self , node ) : results = { } if self . return_expr . match ( node , results ) : return True for child in node . children : if child . type not in ( syms . funcdef , syms . classdef ) : if self . has_return_exprs ( child ) : return True return False
Traverse the tree below node looking for return expr .
241,638
def inform_if_paths_invalid ( egrc_path , examples_dir , custom_dir , debug = True ) : if ( not debug ) : return if ( egrc_path ) : _inform_if_path_does_not_exist ( egrc_path ) if ( examples_dir ) : _inform_if_path_does_not_exist ( examples_dir ) if ( custom_dir ) : _inform_if_path_does_not_exist ( custom_dir )
If egrc_path examples_dir or custom_dir is truthy and debug is True informs the user that a path is not set .
241,639
def get_egrc_config ( cli_egrc_path ) : resolved_path = get_priority ( cli_egrc_path , DEFAULT_EGRC_PATH , None ) expanded_path = get_expanded_path ( resolved_path ) egrc_config = get_empty_config ( ) if os . path . isfile ( expanded_path ) : egrc_config = get_config_tuple_from_egrc ( expanded_path ) return egrc_config
Return a Config namedtuple based on the contents of the egrc .
241,640
def get_resolved_config ( egrc_path , examples_dir , custom_dir , use_color , pager_cmd , squeeze , debug = True , ) : inform_if_paths_invalid ( egrc_path , examples_dir , custom_dir ) examples_dir = get_expanded_path ( examples_dir ) custom_dir = get_expanded_path ( custom_dir ) egrc_config = get_egrc_config ( egrc_pa...
Create a Config namedtuple . Passed in values will override defaults .
241,641
def get_config_tuple_from_egrc ( egrc_path ) : with open ( egrc_path , 'r' ) as egrc : try : config = ConfigParser . RawConfigParser ( ) except AttributeError : config = ConfigParser ( ) config . readfp ( egrc ) examples_dir = None custom_dir = None use_color = None pager_cmd = None squeeze = None subs = None editor_cm...
Create a Config named tuple from the values specified in the . egrc . Expands any paths as necessary .
241,642
def get_expanded_path ( path ) : if path : result = path result = os . path . expanduser ( result ) result = os . path . expandvars ( result ) return result else : return None
Expand ~ and variables in a path . If path is not truthy return None .
241,643
def get_editor_cmd_from_environment ( ) : result = os . getenv ( ENV_VISUAL ) if ( not result ) : result = os . getenv ( ENV_EDITOR ) return result
Gets and editor command from environment variables .
241,644
def _inform_if_path_does_not_exist ( path ) : expanded_path = get_expanded_path ( path ) if not os . path . exists ( expanded_path ) : print ( 'Could not find custom path at: {}' . format ( expanded_path ) )
If the path does not exist print a message saying so . This is intended to be helpful to users if they specify a custom path that eg cannot find .
241,645
def get_custom_color_config_from_egrc ( config ) : pound = _get_color_from_config ( config , CONFIG_NAMES . pound ) heading = _get_color_from_config ( config , CONFIG_NAMES . heading ) code = _get_color_from_config ( config , CONFIG_NAMES . code ) backticks = _get_color_from_config ( config , CONFIG_NAMES . backticks )...
Get the ColorConfig from the egrc config object . Any colors not defined will be None .
241,646
def _get_color_from_config ( config , option ) : if not config . has_option ( COLOR_SECTION , option ) : return None else : return ast . literal_eval ( config . get ( COLOR_SECTION , option ) )
Helper method to uet an option from the COLOR_SECTION of the config .
241,647
def parse_substitution_from_list ( list_rep ) : if type ( list_rep ) is not list : raise SyntaxError ( 'Substitution must be a list' ) if len ( list_rep ) < 2 : raise SyntaxError ( 'Substitution must be a list of size 2' ) pattern = list_rep [ 0 ] replacement = list_rep [ 1 ] is_multiline = False if ( len ( list_rep ) ...
Parse a substitution from the list representation in the config file .
241,648
def get_substitutions_from_config ( config ) : result = [ ] pattern_names = config . options ( SUBSTITUTION_SECTION ) pattern_names . sort ( ) for name in pattern_names : pattern_val = config . get ( SUBSTITUTION_SECTION , name ) list_rep = ast . literal_eval ( pattern_val ) substitution = parse_substitution_from_list ...
Return a list of Substitution objects from the config sorted alphabetically by pattern name . Returns an empty list if no Substitutions are specified . If there are problems parsing the values a help message will be printed and an error will be thrown .
241,649
def get_default_color_config ( ) : result = ColorConfig ( pound = DEFAULT_COLOR_POUND , heading = DEFAULT_COLOR_HEADING , code = DEFAULT_COLOR_CODE , backticks = DEFAULT_COLOR_BACKTICKS , prompt = DEFAULT_COLOR_PROMPT , pound_reset = DEFAULT_COLOR_POUND_RESET , heading_reset = DEFAULT_COLOR_HEADING_RESET , code_reset =...
Get a color config object with all the defaults .
241,650
def get_empty_config ( ) : empty_color_config = get_empty_color_config ( ) result = Config ( examples_dir = None , custom_dir = None , color_config = empty_color_config , use_color = None , pager_cmd = None , editor_cmd = None , squeeze = None , subs = None ) return result
Return an empty Config object with no options set .
241,651
def get_empty_color_config ( ) : empty_color_config = ColorConfig ( pound = None , heading = None , code = None , backticks = None , prompt = None , pound_reset = None , heading_reset = None , code_reset = None , backticks_reset = None , prompt_reset = None ) return empty_color_config
Return a color_config with all values set to None .
241,652
def merge_color_configs ( first , second ) : pound = get_priority ( first . pound , second . pound , None ) heading = get_priority ( first . heading , second . heading , None ) code = get_priority ( first . code , second . code , None ) backticks = get_priority ( first . backticks , second . backticks , None ) prompt =...
Merge the color configs .
241,653
def apply_and_get_result ( self , string ) : if self . is_multiline : compiled_pattern = re . compile ( self . pattern , re . MULTILINE ) else : compiled_pattern = re . compile ( self . pattern ) result = re . sub ( compiled_pattern , self . repl , string ) return result
Perform the substitution represented by this object on string and return the result .
241,654
def colorize_text ( self , text ) : result = text result = self . colorize_heading ( result ) result = self . colorize_block_indent ( result ) result = self . colorize_backticks ( result ) return result
Colorize the text .
241,655
def _recursive_get_all_file_names ( dir ) : if not dir : return [ ] result = [ ] for basedir , dirs , files in os . walk ( dir ) : result . extend ( files ) return result
Get all the file names in the directory . Gets all the top level file names only not the full path .
241,656
def edit_custom_examples ( program , config ) : if ( not config . custom_dir ) or ( not os . path . exists ( config . custom_dir ) ) : _inform_cannot_edit_no_custom_dir ( ) return resolved_program = get_resolved_program ( program , config ) custom_file_paths = get_file_paths_for_program ( resolved_program , config . cu...
Edit custom examples for the given program creating the file if it does not exist .
241,657
def get_file_paths_for_program ( program , dir_to_search ) : if dir_to_search is None : return [ ] else : wanted_file_name = program + EXAMPLE_FILE_SUFFIX result = [ ] for basedir , dirs , file_names in os . walk ( dir_to_search ) : for file_name in file_names : if file_name == wanted_file_name : result . append ( os ....
Return an array of full paths matching the given program . If no directory is present returns an empty list .
241,658
def page_string ( str_to_page , pager_cmd ) : use_fallback_page_function = False if pager_cmd is None : use_fallback_page_function = True elif pager_cmd == FLAG_FALLBACK : use_fallback_page_function = True try : if use_fallback_page_function : pydoc . pager ( str_to_page ) else : pydoc . pipepager ( str_to_page , cmd =...
Page str_to_page via the pager .
241,659
def get_list_of_all_supported_commands ( config ) : default_files = _recursive_get_all_file_names ( config . examples_dir ) custom_files = _recursive_get_all_file_names ( config . custom_dir ) default_files = [ path for path in default_files if _is_example_file ( path ) ] custom_files = [ path for path in custom_files ...
Generate a list of all the commands that have examples known to eg . The format of the list is the command names . The fact that there are examples for cp for example would mean that cp was in the list .
241,660
def get_squeezed_contents ( contents ) : line_between_example_code = substitute . Substitution ( '\n\n ' , '\n ' , True ) lines_between_examples = substitute . Substitution ( '\n\n\n' , '\n\n' , True ) lines_between_sections = substitute . Substitution ( '\n\n\n\n' , '\n\n\n' , True ) result = contents result = l...
Squeeze the contents by removing blank lines between definition and example and remove duplicate blank lines except between sections .
241,661
def get_colorized_contents ( contents , color_config ) : colorizer = color . EgColorizer ( color_config ) result = colorizer . colorize_text ( contents ) return result
Colorize the contents based on the color_config .
241,662
def get_substituted_contents ( contents , substitutions ) : result = contents for sub in substitutions : result = sub . apply_and_get_result ( result ) return result
Perform a list of substitutions and return the result .
241,663
def get_resolved_program ( program , config_obj ) : alias_dict = get_alias_dict ( config_obj ) if program in alias_dict : return alias_dict [ program ] else : return program
Take a program that may be an alias for another program and return the resolved program .
241,664
def get_alias_dict ( config_obj ) : if not config_obj . examples_dir : return { } alias_file_path = _get_alias_file_path ( config_obj ) if not os . path . isfile ( alias_file_path ) : return { } alias_file_contents = _get_contents_of_file ( alias_file_path ) result = json . loads ( alias_file_contents ) return result
Return a dictionary consisting of all aliases known to eg .
241,665
def assert_not_called ( _mock_self ) : self = _mock_self if self . call_count != 0 : msg = ( "Expected '%s' to not have been called. Called %s times." % ( self . _mock_name or 'mock' , self . call_count ) ) raise AssertionError ( msg )
assert that the mock was never called .
241,666
def assert_called ( _mock_self ) : self = _mock_self if self . call_count == 0 : msg = ( "Expected '%s' to have been called." % self . _mock_name or 'mock' ) raise AssertionError ( msg )
assert that the mock was called at least once
241,667
def assert_called_once ( _mock_self ) : self = _mock_self if not self . call_count == 1 : msg = ( "Expected '%s' to have been called once. Called %s times." % ( self . _mock_name or 'mock' , self . call_count ) ) raise AssertionError ( msg )
assert that the mock was called only once .
241,668
def assert_called_once_with ( _mock_self , * args , ** kwargs ) : self = _mock_self if not self . call_count == 1 : msg = ( "Expected '%s' to be called once. Called %s times." % ( self . _mock_name or 'mock' , self . call_count ) ) raise AssertionError ( msg ) return self . assert_called_with ( * args , ** kwargs )
assert that the mock was called exactly once and with the specified arguments .
241,669
def normalize ( self ) : chrfunc = chr if py3k else HTMLEntity . _unichr if self . named : return chrfunc ( htmlentities . name2codepoint [ self . value ] ) if self . hexadecimal : return chrfunc ( int ( self . value , 16 ) ) return chrfunc ( int ( self . value ) )
Return the unicode character represented by the HTML entity .
241,670
def _detach_children ( self ) : children = [ val [ 0 ] for val in self . _children . values ( ) ] for child in children : child ( ) . _parent = list ( self ) self . _children . clear ( )
Remove all children and give them independent parent copies .
241,671
def _handle_parameter ( self , default ) : key = None showkey = False self . _push ( ) while self . _tokens : token = self . _tokens . pop ( ) if isinstance ( token , tokens . TemplateParamEquals ) : key = self . _pop ( ) showkey = True self . _push ( ) elif isinstance ( token , ( tokens . TemplateParamSeparator , toke...
Handle a case where a parameter is at the head of the tokens .
241,672
def _handle_template ( self , token ) : params = [ ] default = 1 self . _push ( ) while self . _tokens : token = self . _tokens . pop ( ) if isinstance ( token , tokens . TemplateParamSeparator ) : if not params : name = self . _pop ( ) param = self . _handle_parameter ( default ) params . append ( param ) if not param...
Handle a case where a template is at the head of the tokens .
241,673
def _handle_argument ( self , token ) : name = None self . _push ( ) while self . _tokens : token = self . _tokens . pop ( ) if isinstance ( token , tokens . ArgumentSeparator ) : name = self . _pop ( ) self . _push ( ) elif isinstance ( token , tokens . ArgumentClose ) : if name is not None : return Argument ( name , ...
Handle a case where an argument is at the head of the tokens .
241,674
def _handle_wikilink ( self , token ) : title = None self . _push ( ) while self . _tokens : token = self . _tokens . pop ( ) if isinstance ( token , tokens . WikilinkSeparator ) : title = self . _pop ( ) self . _push ( ) elif isinstance ( token , tokens . WikilinkClose ) : if title is not None : return Wikilink ( titl...
Handle a case where a wikilink is at the head of the tokens .
241,675
def _handle_external_link ( self , token ) : brackets , url = token . brackets , None self . _push ( ) while self . _tokens : token = self . _tokens . pop ( ) if isinstance ( token , tokens . ExternalLinkSeparator ) : url = self . _pop ( ) self . _push ( ) elif isinstance ( token , tokens . ExternalLinkClose ) : if url...
Handle when an external link is at the head of the tokens .
241,676
def _handle_entity ( self , token ) : token = self . _tokens . pop ( ) if isinstance ( token , tokens . HTMLEntityNumeric ) : token = self . _tokens . pop ( ) if isinstance ( token , tokens . HTMLEntityHex ) : text = self . _tokens . pop ( ) self . _tokens . pop ( ) return HTMLEntity ( text . text , named = False , hex...
Handle a case where an HTML entity is at the head of the tokens .
241,677
def _handle_heading ( self , token ) : level = token . level self . _push ( ) while self . _tokens : token = self . _tokens . pop ( ) if isinstance ( token , tokens . HeadingEnd ) : title = self . _pop ( ) return Heading ( title , level ) else : self . _write ( self . _handle_token ( token ) ) raise ParserError ( "_han...
Handle a case where a heading is at the head of the tokens .
241,678
def _handle_comment ( self , token ) : self . _push ( ) while self . _tokens : token = self . _tokens . pop ( ) if isinstance ( token , tokens . CommentEnd ) : contents = self . _pop ( ) return Comment ( contents ) else : self . _write ( self . _handle_token ( token ) ) raise ParserError ( "_handle_comment() missed a c...
Handle a case where an HTML comment is at the head of the tokens .
241,679
def _handle_attribute ( self , start ) : name = quotes = None self . _push ( ) while self . _tokens : token = self . _tokens . pop ( ) if isinstance ( token , tokens . TagAttrEquals ) : name = self . _pop ( ) self . _push ( ) elif isinstance ( token , tokens . TagAttrQuote ) : quotes = token . char elif isinstance ( to...
Handle a case where a tag attribute is at the head of the tokens .
241,680
def _handle_tag ( self , token ) : close_tokens = ( tokens . TagCloseSelfclose , tokens . TagCloseClose ) implicit , attrs , contents , closing_tag = False , [ ] , None , None wiki_markup , invalid = token . wiki_markup , token . invalid or False wiki_style_separator , closing_wiki_markup = None , wiki_markup self . _p...
Handle a case where a tag is at the head of the tokens .
241,681
def _handle_token ( self , token ) : try : return _HANDLERS [ type ( token ) ] ( self , token ) except KeyError : err = "_handle_token() got unexpected {0}" raise ParserError ( err . format ( type ( token ) . __name__ ) )
Handle a single token .
241,682
def build ( self , tokenlist ) : self . _tokens = tokenlist self . _tokens . reverse ( ) self . _push ( ) while self . _tokens : node = self . _handle_token ( self . _tokens . pop ( ) ) self . _write ( node ) return self . _pop ( )
Build a Wikicode object from a list tokens and return it .
241,683
def _select_theory ( theories ) : if theories : values = tuple ( theories . values ( ) ) best = max ( values ) confidence = float ( best ) / sum ( values ) if confidence > 0.5 : return tuple ( theories . keys ( ) ) [ values . index ( best ) ]
Return the most likely spacing convention given different options .
241,684
def _get_spacing_conventions ( self , use_names ) : before_theories = defaultdict ( lambda : 0 ) after_theories = defaultdict ( lambda : 0 ) for param in self . params : if not param . showkey : continue if use_names : component = str ( param . name ) else : component = str ( param . value ) match = re . search ( r"^(\...
Try to determine the whitespace conventions for parameters .
241,685
def _should_remove ( self , i , name ) : if self . params [ i ] . showkey : following = self . params [ i + 1 : ] better_matches = [ after . name . strip ( ) == name and not after . showkey for after in following ] return any ( better_matches ) return False
Look ahead for a parameter with the same name but hidden .
241,686
def _push ( self , context = 0 ) : new_ident = ( self . _head , context ) if new_ident in self . _bad_routes : raise BadRoute ( context ) self . _stacks . append ( [ [ ] , context , [ ] , new_ident ] ) self . _depth += 1
Add a new token stack context and textbuffer to the list .
241,687
def _push_textbuffer ( self ) : if self . _textbuffer : self . _stack . append ( tokens . Text ( text = "" . join ( self . _textbuffer ) ) ) self . _textbuffer = [ ]
Push the textbuffer onto the stack as a Text node and clear it .
241,688
def _fail_route ( self ) : context = self . _context self . _memoize_bad_route ( ) self . _pop ( ) raise BadRoute ( context )
Fail the current tokenization route .
241,689
def _emit_all ( self , tokenlist ) : if tokenlist and isinstance ( tokenlist [ 0 ] , tokens . Text ) : self . _emit_text ( tokenlist . pop ( 0 ) . text ) self . _push_textbuffer ( ) self . _stack . extend ( tokenlist )
Write a series of tokens to the current stack at once .
241,690
def _read ( self , delta = 0 , wrap = False , strict = False ) : index = self . _head + delta if index < 0 and ( not wrap or abs ( index ) > len ( self . _text ) ) : return self . START try : return self . _text [ index ] except IndexError : if strict : self . _fail_route ( ) return self . END
Read the value at a relative point in the wikicode .
241,691
def _parse_template ( self , has_content ) : reset = self . _head context = contexts . TEMPLATE_NAME if has_content : context |= contexts . HAS_TEMPLATE try : template = self . _parse ( context ) except BadRoute : self . _head = reset raise self . _emit_first ( tokens . TemplateOpen ( ) ) self . _emit_all ( template ) ...
Parse a template at the head of the wikicode string .
241,692
def _parse_argument ( self ) : reset = self . _head try : argument = self . _parse ( contexts . ARGUMENT_NAME ) except BadRoute : self . _head = reset raise self . _emit_first ( tokens . ArgumentOpen ( ) ) self . _emit_all ( argument ) self . _emit ( tokens . ArgumentClose ( ) )
Parse an argument at the head of the wikicode string .
241,693
def _parse_template_or_argument ( self ) : self . _head += 2 braces = 2 while self . _read ( ) == "{" : self . _head += 1 braces += 1 has_content = False self . _push ( ) while braces : if braces == 1 : return self . _emit_text_then_stack ( "{" ) if braces == 2 : try : self . _parse_template ( has_content ) except BadR...
Parse a template or argument at the head of the wikicode string .
241,694
def _handle_template_param ( self ) : if self . _context & contexts . TEMPLATE_NAME : if not self . _context & ( contexts . HAS_TEXT | contexts . HAS_TEMPLATE ) : self . _fail_route ( ) self . _context ^= contexts . TEMPLATE_NAME elif self . _context & contexts . TEMPLATE_PARAM_VALUE : self . _context ^= contexts . TEM...
Handle a template parameter at the head of the string .
241,695
def _handle_template_param_value ( self ) : self . _emit_all ( self . _pop ( ) ) self . _context ^= contexts . TEMPLATE_PARAM_KEY self . _context |= contexts . TEMPLATE_PARAM_VALUE self . _emit ( tokens . TemplateParamEquals ( ) )
Handle a template parameter s value at the head of the string .
241,696
def _handle_template_end ( self ) : if self . _context & contexts . TEMPLATE_NAME : if not self . _context & ( contexts . HAS_TEXT | contexts . HAS_TEMPLATE ) : self . _fail_route ( ) elif self . _context & contexts . TEMPLATE_PARAM_KEY : self . _emit_all ( self . _pop ( ) ) self . _head += 1 return self . _pop ( )
Handle the end of a template at the head of the string .
241,697
def _handle_argument_separator ( self ) : self . _context ^= contexts . ARGUMENT_NAME self . _context |= contexts . ARGUMENT_DEFAULT self . _emit ( tokens . ArgumentSeparator ( ) )
Handle the separator between an argument s name and default .
241,698
def _parse_wikilink ( self ) : reset = self . _head + 1 self . _head += 2 try : link , extra , delta = self . _really_parse_external_link ( True ) except BadRoute : self . _head = reset + 1 try : wikilink = self . _parse ( contexts . WIKILINK_TITLE ) except BadRoute : self . _head = reset self . _emit_text ( "[[" ) els...
Parse an internal wikilink at the head of the wikicode string .
241,699
def _handle_wikilink_separator ( self ) : self . _context ^= contexts . WIKILINK_TITLE self . _context |= contexts . WIKILINK_TEXT self . _emit ( tokens . WikilinkSeparator ( ) )
Handle the separator between a wikilink s title and its text .