idx int64 0 63k | question stringlengths 53 5.28k | target stringlengths 5 805 |
|---|---|---|
56,500 | def init_default ( self ) : import f311 if self . default_filename is None : raise RuntimeError ( "Class '{}' has no default filename" . format ( self . __class__ . __name__ ) ) fullpath = f311 . get_default_data_path ( self . default_filename , class_ = self . __class__ ) self . load ( fullpath ) self . filename = Non... | Initializes object with its default values |
56,501 | def availability ( self , availability ) : allowed_values = [ "available" , "comingSoon" , "retired" ] if availability is not None and availability not in allowed_values : raise ValueError ( "Invalid value for `availability` ({0}), must be one of {1}" . format ( availability , allowed_values ) ) self . _availability = ... | Sets the availability of this Product . |
56,502 | def stock_status ( self , stock_status ) : allowed_values = [ "available" , "alert" , "unavailable" ] if stock_status is not None and stock_status not in allowed_values : raise ValueError ( "Invalid value for `stock_status` ({0}), must be one of {1}" . format ( stock_status , allowed_values ) ) self . _stock_status = s... | Sets the stock_status of this Product . |
56,503 | def asserts ( input_value , rule , message = '' ) : assert callable ( rule ) or type ( rule ) == bool , 'asserts needs rule to be a callable function or a test boolean' assert isinstance ( message , str ) , 'asserts needs message to be a string' if len ( message ) == 0 and callable ( rule ) : try : s = getsource ( rule... | this function allows you to write asserts in generators since there are moments where you actually want the program to halt when certain values are seen . |
56,504 | def print ( * a ) : try : _print ( * a ) return a [ 0 ] if len ( a ) == 1 else a except : _print ( * a ) | print just one that returns what you give it instead of None |
56,505 | def pattern2re ( pattern ) : pattern_segs = filter ( None , pattern . split ( '/' ) ) if not pattern : return '' , re . compile ( '' ) , None elif '/' in pattern : full_regex = '^' int_regex = [ ] int_regex_done = False start_dir = [ ] start_dir_done = False else : full_regex = '(?:^|/)' int_regex = None int_regex_done... | Makes a unicode regular expression from a pattern . |
56,506 | def _to_backend ( self , p ) : if isinstance ( p , self . _cmp_base ) : return p . path elif isinstance ( p , self . _backend ) : return p elif self . _backend is unicode and isinstance ( p , bytes ) : return p . decode ( self . _encoding ) elif self . _backend is bytes and isinstance ( p , unicode ) : return p . encod... | Converts something to the correct path representation . |
56,507 | def parent ( self ) : p = self . _lib . dirname ( self . path ) p = self . __class__ ( p ) return p | The parent directory of this path . |
56,508 | def unicodename ( self ) : n = self . _lib . basename ( self . path ) if self . _backend is unicode : return n else : return n . decode ( self . _encoding , 'replace' ) | The name of this path as unicode . |
56,509 | def rel_path_to ( self , dest ) : dest = self . __class__ ( dest ) orig_list = self . norm_case ( ) . _components ( ) dest_list = dest . _components ( ) i = - 1 for i , ( orig_part , dest_part ) in enumerate ( zip ( orig_list , dest_list ) ) : if orig_part != self . _normcase ( dest_part ) : up = [ '..' ] * ( len ( ori... | Builds a relative path leading from this one to the given dest . |
56,510 | def lies_under ( self , prefix ) : orig_list = self . norm_case ( ) . _components ( ) pref_list = self . __class__ ( prefix ) . norm_case ( ) . _components ( ) return ( len ( orig_list ) >= len ( pref_list ) and orig_list [ : len ( pref_list ) ] == pref_list ) | Indicates if the prefix is a parent of this path . |
56,511 | def tempfile ( cls , suffix = '' , prefix = None , dir = None , text = False ) : if prefix is None : prefix = tempfile . template if dir is not None : dir = str ( Path ( dir ) ) fd , filename = tempfile . mkstemp ( suffix , prefix , dir , text ) return fd , cls ( filename ) . absolute ( ) | Returns a new temporary file . |
56,512 | def tempdir ( cls , suffix = '' , prefix = None , dir = None ) : if prefix is None : prefix = tempfile . template if dir is not None : dir = str ( Path ( dir ) ) dirname = tempfile . mkdtemp ( suffix , prefix , dir ) return cls ( dirname ) . absolute ( ) | Returns a new temporary directory . |
56,513 | def rel_path_to ( self , dest ) : return super ( Path , self . absolute ( ) ) . rel_path_to ( Path ( dest ) . absolute ( ) ) | Builds a relative path leading from this one to another . |
56,514 | def listdir ( self , pattern = None ) : files = [ self / self . __class__ ( p ) for p in os . listdir ( self . path ) ] if pattern is None : pass elif callable ( pattern ) : files = filter ( pattern , files ) else : if isinstance ( pattern , backend_types ) : if isinstance ( pattern , bytes ) : pattern = pattern . deco... | Returns a list of all the files in this directory . |
56,515 | def recursedir ( self , pattern = None , top_down = True , follow_links = False , handle_errors = None ) : if not self . is_dir ( ) : raise ValueError ( "recursedir() called on non-directory %s" % self ) start = '' int_pattern = None if pattern is None : pattern = lambda p : True elif callable ( pattern ) : pass else :... | Recursively lists all files under this directory . |
56,516 | def mkdir ( self , name = None , parents = False , mode = 0o777 ) : if name is not None : return ( self / name ) . mkdir ( parents = parents , mode = mode ) if self . exists ( ) : return if parents : os . makedirs ( self . path , mode ) else : os . mkdir ( self . path , mode ) return self | Creates that directory or a directory under this one . |
56,517 | def rmdir ( self , parents = False ) : if parents : os . removedirs ( self . path ) else : os . rmdir ( self . path ) | Removes this directory provided it is empty . |
56,518 | def rename ( self , new , parents = False ) : if parents : os . renames ( self . path , self . _to_backend ( new ) ) else : os . rename ( self . path , self . _to_backend ( new ) ) | Renames this path to the given new location . |
56,519 | def copyfile ( self , target ) : shutil . copyfile ( self . path , self . _to_backend ( target ) ) | Copies this file to the given target location . |
56,520 | def copymode ( self , target ) : shutil . copymode ( self . path , self . _to_backend ( target ) ) | Copies the mode of this file on the target file . |
56,521 | def copystat ( self , target ) : shutil . copystat ( self . path , self . _to_backend ( target ) ) | Copies the permissions times and flags from this to the target . |
56,522 | def copy ( self , target ) : shutil . copy ( self . path , self . _to_backend ( target ) ) | Copies this file the target which might be a directory . |
56,523 | def copytree ( self , target , symlinks = False ) : shutil . copytree ( self . path , self . _to_backend ( target ) , symlinks ) | Recursively copies this directory to the target location . |
56,524 | def move ( self , target ) : shutil . move ( self . path , self . _to_backend ( target ) ) | Recursively moves a file or directory to the given target location . |
56,525 | def open ( self , mode = 'r' , name = None , ** kwargs ) : if name is not None : return io . open ( ( self / name ) . path , mode = mode , ** kwargs ) else : return io . open ( self . path , mode = mode , ** kwargs ) | Opens this file or a file under this directory . |
56,526 | def rewrite ( self , mode = 'r' , name = None , temp = None , tempext = '~' , ** kwargs ) : r if name is not None : pathr = self / name else : pathr = self for m in 'war+' : mode = mode . replace ( m , '' ) common_kwargs = { } readable_kwargs = { } writable_kwargs = { } for key , value in kwargs . items ( ) : if key . ... | r Replaces this file with new content . |
56,527 | def matches ( self , path ) : path = self . _prepare_path ( path ) return self . full_regex . search ( path ) is not None | Tests if the given path matches the pattern . |
56,528 | def may_contain_matches ( self , path ) : path = self . _prepare_path ( path ) return self . int_regex . search ( path ) is not None | Tests whether it s possible for paths under the given one to match . |
56,529 | def tgcanrecruit ( self , region = None ) : params = { 'from' : normalize ( region ) } if region is not None else { } @ api_query ( 'tgcanrecruit' , ** params ) async def result ( _ , root ) : return bool ( int ( root . find ( 'TGCANRECRUIT' ) . text ) ) return result ( self ) | Whether the nation will receive a recruitment telegram . |
56,530 | async def govt ( self , root ) : elem = root . find ( 'GOVT' ) result = OrderedDict ( ) result [ 'Administration' ] = float ( elem . find ( 'ADMINISTRATION' ) . text ) result [ 'Defense' ] = float ( elem . find ( 'DEFENCE' ) . text ) result [ 'Education' ] = float ( elem . find ( 'EDUCATION' ) . text ) result [ 'Enviro... | Nation s government expenditure as percentages . |
56,531 | async def sectors ( self , root ) : elem = root . find ( 'SECTORS' ) result = OrderedDict ( ) result [ 'Black Market (estimated)' ] = float ( elem . find ( 'BLACKMARKET' ) . text ) result [ 'Government' ] = float ( elem . find ( 'GOVERNMENT' ) . text ) result [ 'Private Industry' ] = float ( elem . find ( 'INDUSTRY' ) ... | Components of the nation s economy as percentages . |
56,532 | async def deaths ( self , root ) : return { elem . get ( 'type' ) : float ( elem . text ) for elem in root . find ( 'DEATHS' ) } | Causes of death in the nation as percentages . |
56,533 | async def endorsements ( self , root ) : text = root . find ( 'ENDORSEMENTS' ) . text return [ Nation ( name ) for name in text . split ( ',' ) ] if text else [ ] | Regional neighbours endorsing the nation . |
56,534 | async def description ( self ) : resp = await self . _call_web ( f'nation={self.id}' ) return html . unescape ( re . search ( '<div class="nationsummary">(.+?)<p class="nationranktext">' , resp . text , flags = re . DOTALL ) . group ( 1 ) . replace ( '\n' , '' ) . replace ( '</p>' , '' ) . replace ( '<p>' , '\n\n' ) . ... | Nation s full description as seen on its in - game page . |
56,535 | def accept ( self ) : return self . _issue . _nation . _accept_issue ( self . _issue . id , self . _id ) | Accept the option . |
56,536 | def pip_upgrade_all ( line ) : from pip import get_installed_distributions user = set ( d . project_name for d in get_installed_distributions ( user_only = True ) ) all = set ( d . project_name for d in get_installed_distributions ( ) ) for dist in all - user : do_pip ( [ "install" , "--upgrade" , dist ] ) for dist in ... | Attempt to upgrade all packages |
56,537 | def enc_name_descr ( name , descr , color = a99 . COLOR_DESCR ) : return enc_name ( name , color ) + "<br>" + descr | Encodes html given name and description . |
56,538 | def style_checkboxes ( widget ) : ww = widget . findChildren ( QCheckBox ) for w in ww : w . setStyleSheet ( "QCheckBox:focus {border: 1px solid #000000;}" ) | Iterates over widget children to change checkboxes stylesheet . The default rendering of checkboxes does not allow to tell a focused one from an unfocused one . |
56,539 | def reset_table_widget ( t , rowCount , colCount ) : t . reset ( ) t . horizontalHeader ( ) . reset ( ) t . clear ( ) t . sortItems ( - 1 ) t . setRowCount ( rowCount ) t . setColumnCount ( colCount ) | Clears and resizes a table widget . |
56,540 | def place_center ( window , width = None , height = None ) : screenGeometry = QApplication . desktop ( ) . screenGeometry ( ) w , h = window . width ( ) , window . height ( ) if width is not None or height is not None : w = width if width is not None else w h = height if height is not None else h window . setGeometry (... | Places window in the center of the screen . |
56,541 | def get_QApplication ( args = [ ] ) : global _qapp if _qapp is None : QCoreApplication . setAttribute ( Qt . AA_X11InitThreads ) _qapp = QApplication ( args ) return _qapp | Returns the QApplication instance creating it is does not yet exist . |
56,542 | def get_frame ( ) : ret = QFrame ( ) ret . setLineWidth ( 1 ) ret . setMidLineWidth ( 0 ) ret . setFrameShadow ( QFrame . Sunken ) ret . setFrameShape ( QFrame . Box ) return ret | Returns a QFrame formatted in a particular way |
56,543 | def add_signal ( self , signal ) : self . __signals . append ( signal ) if self . __connected : self . __connect_signal ( signal ) | Adds input signal to connected signals . Internally connects the signal to a control slot . |
56,544 | def disconnect_all ( self ) : if not self . __connected : return self . __disconnecting = True try : for signal in self . __signals : signal . disconnect ( self . __signalReceived ) if self . __slot is not None : self . __sigDelayed . disconnect ( self . __slot ) self . __connected = False finally : self . __disconnect... | Disconnects all signals and slots . If already in disconnected state ignores the call . |
56,545 | def __signalReceived ( self , * args ) : if self . __disconnecting : return with self . __lock : self . __args = args if self . __rateLimit == 0 : self . __timer . stop ( ) self . __timer . start ( ( self . __delay * 1000 ) + 1 ) else : now = time . time ( ) if self . __lastFlushTime is None : leakTime = 0 else : lastF... | Received signal . Cancel previous timer and store args to be forwarded later . |
56,546 | def __flush ( self ) : if self . __args is None or self . __disconnecting : return False self . __sigDelayed . emit ( self . __args ) self . __args = None self . __timer . stop ( ) self . __lastFlushTime = time . time ( ) return True | If there is a signal queued up send it now . |
56,547 | def clean_indicators ( indicators ) : output = list ( ) for indicator in indicators : strip = [ 'http://' , 'https://' ] for item in strip : indicator = indicator . replace ( item , '' ) indicator = indicator . strip ( '.' ) . strip ( ) parts = indicator . split ( '/' ) if len ( parts ) > 0 : indicator = parts . pop ( ... | Remove any extra details from indicators . |
56,548 | def hash_values ( values , alg = "md5" ) : import hashlib if alg not in [ 'md5' , 'sha1' , 'sha256' ] : raise Exception ( "Invalid hashing algorithm!" ) hasher = getattr ( hashlib , alg ) if type ( values ) == str : output = hasher ( values ) . hexdigest ( ) elif type ( values ) == list : output = list ( ) for item in ... | Hash a list of values . |
56,549 | def check_whitelist ( values ) : import os import tldextract whitelisted = list ( ) for name in [ 'alexa.txt' , 'cisco.txt' ] : config_path = os . path . expanduser ( '~/.config/blockade' ) file_path = os . path . join ( config_path , name ) whitelisted += [ x . strip ( ) for x in open ( file_path , 'r' ) . readlines (... | Check the indicators against known whitelists . |
56,550 | def cache_items ( values ) : import os config_path = os . path . expanduser ( '~/.config/blockade' ) file_path = os . path . join ( config_path , 'cache.txt' ) if not os . path . isfile ( file_path ) : file ( file_path , 'w' ) . close ( ) written = [ x . strip ( ) for x in open ( file_path , 'r' ) . readlines ( ) ] han... | Cache indicators that were successfully sent to avoid dups . |
56,551 | def prune_cached ( values ) : import os config_path = os . path . expanduser ( '~/.config/blockade' ) file_path = os . path . join ( config_path , 'cache.txt' ) if not os . path . isfile ( file_path ) : return values cached = [ x . strip ( ) for x in open ( file_path , 'r' ) . readlines ( ) ] output = list ( ) for item... | Remove the items that have already been cached . |
56,552 | def get_logger ( name ) : import logging import sys logger = logging . getLogger ( name ) logger . setLevel ( logging . DEBUG ) shandler = logging . StreamHandler ( sys . stdout ) fmt = "" fmt += '\033[1;32m%(levelname)-5s %(module)s:%(funcName)s():' fmt += '%(lineno)d %(asctime)s\033[0m| %(message)s' fmtr = logging . ... | Get a logging instance we can use . |
56,553 | def process_whitelists ( ) : import csv import grequests import os import StringIO import zipfile mapping = { 'http://s3.amazonaws.com/alexa-static/top-1m.csv.zip' : { 'name' : 'alexa.txt' } , 'http://s3-us-west-1.amazonaws.com/umbrella-static/top-1m.csv.zip' : { 'name' : 'cisco.txt' } } rs = ( grequests . get ( u ) fo... | Download approved top 1M lists . |
56,554 | def mode ( self , mode ) : allowed_values = [ "test" , "live" ] if mode is not None and mode not in allowed_values : raise ValueError ( "Invalid value for `mode` ({0}), must be one of {1}" . format ( mode , allowed_values ) ) self . _mode = mode | Sets the mode of this BraintreeGateway . |
56,555 | def diagnose ( df , preview_rows = 2 , display_max_cols = 0 , display_width = None ) : assert type ( df ) is pd . DataFrame initial_max_cols = pd . get_option ( 'display.max_columns' ) initial_max_rows = pd . get_option ( 'display.max_rows' ) initial_width = pd . get_option ( 'display.width' ) pd . set_option ( 'displa... | Prints information about the DataFrame pertinent to data cleaning . |
56,556 | def cut_spectrum ( sp , l0 , lf ) : if l0 >= lf : raise ValueError ( "l0 must be lower than lf" ) idx0 = np . argmin ( np . abs ( sp . x - l0 ) ) idx1 = np . argmin ( np . abs ( sp . x - lf ) ) out = copy . deepcopy ( sp ) out . x = out . x [ idx0 : idx1 ] out . y = out . y [ idx0 : idx1 ] return out | Cuts spectrum given a wavelength interval leaving origina intact |
56,557 | def skip_first ( pipe , items = 1 ) : pipe = iter ( pipe ) for i in skip ( pipe , items ) : yield i | this is an alias for skip to parallel the dedicated skip_last function to provide a little more readability to the code . the action of actually skipping does not occur until the first iteration is done |
56,558 | def find ( self , query = None , ** kwargs ) : url = self . getUrl ( ) if query is not None : if isinstance ( query , queries . SlickQuery ) : url = url + "?" + urlencode ( query . to_dict ( ) ) elif isinstance ( query , dict ) : url = url + "?" + urlencode ( query ) elif len ( kwargs ) > 0 : url = url + "?" + urlencod... | You can pass in the appropriate model object from the queries module or a dictionary with the keys and values for the query or a set of key = value parameters . |
56,559 | def findOne ( self , query = None , mode = FindOneMode . FIRST , ** kwargs ) : results = self . find ( query , ** kwargs ) if len ( results ) is 0 : return None elif len ( results ) is 1 or mode == FindOneMode . FIRST : return results [ 0 ] elif mode == FindOneMode . LAST : return results [ - 1 ] | Perform a find with the same options present but only return a maximum of one result . If find returns an empty array then None is returned . |
56,560 | def lookup_cc_partner ( nu_pid ) : neutrino_type = math . fabs ( nu_pid ) assert neutrino_type in [ 12 , 14 , 16 ] cc_partner = neutrino_type - 1 cc_partner = math . copysign ( cc_partner , nu_pid ) cc_partner = int ( cc_partner ) return cc_partner | Lookup the charge current partner |
56,561 | def block_comment ( solver , start , end ) : text , pos = solver . parse_state length = len ( text ) startlen = len ( start ) endlen = len ( end ) if pos == length : return if not text [ pos : ] . startswith ( start ) : return level = 1 p = pos + 1 while p < length : if text [ p : ] . startswith ( end ) : level -= 1 p ... | embedable block comment |
56,562 | def pip_install ( * args ) : pip_cmd = os . path . join ( os . path . dirname ( sys . executable ) , 'pip' ) with set_env ( 'PIP_CONFIG_FILE' , os . devnull ) : cmd = [ pip_cmd , 'install' ] + list ( args ) print_command ( cmd ) subprocess . call ( cmd , stdout = sys . stdout , stderr = sys . stderr ) | Run pip install ... |
56,563 | def indent_text ( text , nb_tabs = 0 , tab_str = " " , linebreak_input = "\n" , linebreak_output = "\n" , wrap = False ) : r if not wrap : lines = text . split ( linebreak_input ) tabs = nb_tabs * tab_str output = "" for line in lines : output += tabs + line + linebreak_output return output else : return wrap_text_in_... | r Add tabs to each line of text . |
56,564 | def wait_for_user ( msg = "" ) : if '--yes-i-know' in sys . argv : return print ( msg ) try : answer = raw_input ( "Please confirm by typing 'Yes, I know!': " ) except KeyboardInterrupt : print ( ) answer = '' if answer != 'Yes, I know!' : sys . stderr . write ( "ERROR: Aborted.\n" ) sys . exit ( 1 ) return | Print MSG and a confirmation prompt . |
56,565 | def guess_minimum_encoding ( text , charsets = ( 'ascii' , 'latin1' , 'utf8' ) ) : text_in_unicode = text . decode ( 'utf8' , 'replace' ) for charset in charsets : try : return ( text_in_unicode . encode ( charset ) , charset ) except ( UnicodeEncodeError , UnicodeDecodeError ) : pass return ( text_in_unicode . encode ... | Try to guess the minimum charset that is able to represent . |
56,566 | def encode_for_xml ( text , wash = False , xml_version = '1.0' , quote = False ) : text = text . replace ( '&' , '&' ) text = text . replace ( '<' , '<' ) if quote : text = text . replace ( '"' , '"' ) if wash : text = wash_for_xml ( text , xml_version = xml_version ) return text | Encode special characters in a text so that it would be XML - compliant . |
56,567 | def wash_for_xml ( text , xml_version = '1.0' ) : if xml_version == '1.0' : return RE_ALLOWED_XML_1_0_CHARS . sub ( '' , unicode ( text , 'utf-8' ) ) . encode ( 'utf-8' ) else : return RE_ALLOWED_XML_1_1_CHARS . sub ( '' , unicode ( text , 'utf-8' ) ) . encode ( 'utf-8' ) | Remove any character which isn t a allowed characters for XML . |
56,568 | def wash_for_utf8 ( text , correct = True ) : if isinstance ( text , unicode ) : return text . encode ( 'utf-8' ) errors = "ignore" if correct else "strict" return text . decode ( "utf-8" , errors ) . encode ( "utf-8" , errors ) | Return UTF - 8 encoded binary string with incorrect characters washed away . |
56,569 | def nice_number ( number , thousands_separator = ',' , max_ndigits_after_dot = None ) : if isinstance ( number , float ) : if max_ndigits_after_dot is not None : number = round ( number , max_ndigits_after_dot ) int_part , frac_part = str ( number ) . split ( '.' ) return '%s.%s' % ( nice_number ( int ( int_part ) , th... | Return nicely printed number NUMBER in language LN . |
56,570 | def nice_size ( size ) : unit = 'B' if size > 1024 : size /= 1024.0 unit = 'KB' if size > 1024 : size /= 1024.0 unit = 'MB' if size > 1024 : size /= 1024.0 unit = 'GB' return '%s %s' % ( nice_number ( size , max_ndigits_after_dot = 2 ) , unit ) | Nice size . |
56,571 | def remove_line_breaks ( text ) : return unicode ( text , 'utf-8' ) . replace ( '\f' , '' ) . replace ( '\n' , '' ) . replace ( '\r' , '' ) . replace ( u'\xe2\x80\xa8' , '' ) . replace ( u'\xe2\x80\xa9' , '' ) . replace ( u'\xc2\x85' , '' ) . encode ( 'utf-8' ) | Remove line breaks from input . |
56,572 | def decode_to_unicode ( text , default_encoding = 'utf-8' ) : if not text : return "" try : return text . decode ( default_encoding ) except ( UnicodeError , LookupError ) : pass detected_encoding = None if CHARDET_AVAILABLE : res = chardet . detect ( text ) if res [ 'confidence' ] >= 0.8 : detected_encoding = res [ 'e... | Decode input text into Unicode representation . |
56,573 | def to_unicode ( text ) : if isinstance ( text , unicode ) : return text if isinstance ( text , six . string_types ) : return decode_to_unicode ( text ) return unicode ( text ) | Convert to unicode . |
56,574 | def translate_latex2unicode ( text , kb_file = None ) : if kb_file is None : kb_file = get_kb_filename ( ) try : text = decode_to_unicode ( text ) except UnicodeDecodeError : text = unicode ( wash_for_utf8 ( text ) ) if CFG_LATEX_UNICODE_TRANSLATION_CONST == { } : _load_latex2unicode_constants ( kb_file ) for match in ... | Translate latex text to unicode . |
56,575 | def _load_latex2unicode_constants ( kb_file = None ) : if kb_file is None : kb_file = get_kb_filename ( ) try : data = open ( kb_file ) except IOError : sys . stderr . write ( "\nCould not open LaTeX to Unicode KB file. " "Aborting translation.\n" ) return CFG_LATEX_UNICODE_TRANSLATION_CONST latex_symbols = [ ] transla... | Load LaTeX2Unicode translation table dictionary . |
56,576 | def translate_to_ascii ( values ) : r if not values and not isinstance ( values , str ) : return values if isinstance ( values , str ) : values = [ values ] for index , value in enumerate ( values ) : if not value : continue unicode_text = decode_to_unicode ( value ) if u"[?]" in unicode_text : decoded_text = [ ] for u... | r Transliterate the string into ascii representation . |
56,577 | def xml_entities_to_utf8 ( text , skip = ( 'lt' , 'gt' , 'amp' ) ) : def fixup ( m ) : text = m . group ( 0 ) if text [ : 2 ] == "&#" : try : if text [ : 3 ] == "&#x" : return unichr ( int ( text [ 3 : - 1 ] , 16 ) ) . encode ( "utf-8" ) else : return unichr ( int ( text [ 2 : - 1 ] ) ) . encode ( "utf-8" ) except Valu... | Translate HTML or XML character references to UTF - 8 . |
56,578 | def strip_accents ( x ) : u x = re_latex_lowercase_a . sub ( "a" , x ) x = re_latex_lowercase_ae . sub ( "ae" , x ) x = re_latex_lowercase_oe . sub ( "oe" , x ) x = re_latex_lowercase_e . sub ( "e" , x ) x = re_latex_lowercase_i . sub ( "i" , x ) x = re_latex_lowercase_o . sub ( "o" , x ) x = re_latex_lowercase_u . sub... | u Strip accents in the input phrase X . |
56,579 | def show_diff ( original , modified , prefix = '' , suffix = '' , prefix_unchanged = ' ' , suffix_unchanged = '' , prefix_removed = '-' , suffix_removed = '' , prefix_added = '+' , suffix_added = '' ) : import difflib differ = difflib . Differ ( ) result = [ prefix ] for line in differ . compare ( modified . splitlines... | Return the diff view between original and modified strings . |
56,580 | def escape_latex ( text ) : r text = unicode ( text . decode ( 'utf-8' ) ) CHARS = { '&' : r'\&' , '%' : r'\%' , '$' : r'\$' , '#' : r'\#' , '_' : r'\_' , '{' : r'\{' , '}' : r'\}' , '~' : r'\~{}' , '^' : r'\^{}' , '\\' : r'\textbackslash{}' , } escaped = "" . join ( [ CHARS . get ( char , char ) for char in text ] ) r... | r Escape characters of given text . |
56,581 | def _copy_attr ( self , module , varname , cls , attrname = None ) : if not hasattr ( module , varname ) : raise RuntimeError ( "Variable '{}' not found" . format ( varname ) ) obj = getattr ( module , varname ) if not isinstance ( obj , cls ) : raise RuntimeError ( "Expecting fobj to be a {}, not a '{}'" . format ( cl... | Copies attribute from module object to self . Raises if object not of expected class |
56,582 | def __check_to_permit ( self , entry_type , entry_filename ) : rules = self . __filter_rules [ entry_type ] for pattern in rules [ fss . constants . FILTER_INCLUDE ] : if fnmatch . fnmatch ( entry_filename , pattern ) : _LOGGER_FILTER . debug ( "Entry explicitly INCLUDED: [%s] [%s] " "[%s]" , entry_type , pattern , ent... | Applying the filter rules . |
56,583 | def census ( self , * scales ) : params = { 'mode' : 'score+rank+rrank+prank+prrank' } if scales : params [ 'scale' ] = '+' . join ( str ( x ) for x in scales ) @ api_query ( 'census' , ** params ) async def result ( _ , root ) : return [ CensusScaleCurrent ( scale_elem ) for scale_elem in root . find ( 'CENSUS' ) ] re... | Current World Census data . |
56,584 | def censushistory ( self , * scales ) : params = { 'mode' : 'history' } if scales : params [ 'scale' ] = '+' . join ( str ( x ) for x in scales ) @ api_query ( 'census' , ** params ) async def result ( _ , root ) : return [ CensusScaleHistory ( scale_elem ) for scale_elem in root . find ( 'CENSUS' ) ] return result ( s... | Historical World Census data . |
56,585 | async def censusranks ( self , scale ) : order = count ( 1 ) for offset in count ( 1 , 20 ) : census_ranks = await self . _get_censusranks ( scale = scale , start = offset ) for census_rank in census_ranks : assert census_rank . rank == next ( order ) yield census_rank if len ( census_ranks ) < 20 : break | Iterate through nations ranked on the World Census scale . |
56,586 | def loads ( astring ) : try : return marshal . loads ( zlib . decompress ( astring ) ) except zlib . error as e : raise SerializerError ( 'Cannot decompress object ("{}")' . format ( str ( e ) ) ) except Exception as e : raise SerializerError ( 'Cannot restore object ("{}")' . format ( str ( e ) ) ) | Decompress and deserialize string into Python object via marshal . |
56,587 | def loads ( astring ) : try : return pickle . loads ( zlib . decompress ( astring ) ) except zlib . error as e : raise SerializerError ( 'Cannot decompress object ("{}")' . format ( str ( e ) ) ) except pickle . UnpicklingError as e : raise SerializerError ( 'Cannot restore object ("{}")' . format ( str ( e ) ) ) | Decompress and deserialize string into Python object via pickle . |
56,588 | def loads ( astring ) : try : return pickle . loads ( lzma . decompress ( astring ) ) except lzma . LZMAError as e : raise SerializerError ( 'Cannot decompress object ("{}")' . format ( str ( e ) ) ) except pickle . UnpicklingError as e : raise SerializerError ( 'Cannot restore object ("{}")' . format ( str ( e ) ) ) | Decompress and deserialize string into a Python object via pickle . |
56,589 | def search ( self , path_expression , mode = UXP , values = None , ifunc = lambda x : x ) : path_and_value_list = iterutils . search ( self . data , path_expression = path_expression , required_values = values , exact = ( mode [ 1 ] == "x" ) ) return self . __return_value ( path_and_value_list , mode , ifunc ) | find matches for the given path expression in the data |
56,590 | def __visit_index_path ( self , src , p , k , v ) : cp = p + ( k , ) self . path_index [ cp ] = self . indexed_obj_factory ( p , k , v , self . path_index . get ( cp ) ) if cp in self . path_index : self . path_index [ cp ] . add_src ( src ) else : self . path_index [ cp ] = Flobject ( val = v , path = cp , srcs = set ... | Called during processing of source data |
56,591 | def get_default_data_path ( * args , module = None , class_ = None , flag_raise = True ) : if module is None : module = __get_filetypes_module ( ) if class_ is not None : pkgname = class_ . __module__ mseq = pkgname . split ( "." ) if len ( mseq ) < 2 or mseq [ 1 ] != "filetypes" : raise ValueError ( "Invalid module na... | Returns path to default data directory |
56,592 | def copy_default_data_file ( filename , module = None ) : if module is None : module = __get_filetypes_module ( ) fullpath = get_default_data_path ( filename , module = module ) shutil . copy ( fullpath , "." ) | Copies file from default data directory to local directory . |
56,593 | def _find_display ( self ) : self . display_num = 2 while os . path . isdir ( XVFB_PATH % ( self . display_num , ) ) : self . display_num += 1 | Find a usable display which doesn t have an existing Xvfb file |
56,594 | def comments ( recid ) : from invenio_access . local_config import VIEWRESTRCOLL from invenio_access . mailcookie import mail_cookie_create_authorize_action from . api import check_user_can_view_comments auth_code , auth_msg = check_user_can_view_comments ( current_user , recid ) if auth_code and current_user . is_gues... | Display comments . |
56,595 | def getattr ( self , key , default = None , callback = None ) : u value = self . _xml . text if key == 'text' else self . _xml . get ( key , default ) return callback ( value ) if callback else value | u Getting the attribute of an element . |
56,596 | def setattr ( self , key , value ) : u if key == 'text' : self . _xml . text = str ( value ) else : self . _xml . set ( key , str ( value ) ) | u Sets an attribute on a node . |
56,597 | def get ( self , default = None , callback = None ) : u value = self . _xml . text if self . _xml . text else default return callback ( value ) if callback else value | u Returns leaf s value . |
56,598 | def to_str ( self , pretty_print = False , encoding = None , ** kw ) : u if kw . get ( 'without_comments' ) and not kw . get ( 'method' ) : kw . pop ( 'without_comments' ) kw [ 'method' ] = 'c14n' kw [ 'with_comments' ] = False return etree . tostring ( self . _xml , pretty_print = pretty_print , encoding = encoding , ... | u Converts a node with all of it s children to a string . |
56,599 | def iter_children ( self , key = None ) : u tag = None if key : tag = self . _get_aliases ( ) . get ( key ) if not tag : raise KeyError ( key ) for child in self . _xml . iterchildren ( tag = tag ) : if len ( child ) : yield self . __class__ ( child ) else : yield Literal ( child ) | u Iterates over children . |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.