idx int64 0 252k | question stringlengths 48 5.28k | target stringlengths 5 1.23k |
|---|---|---|
236,600 | def strip_footer ( ref_lines , section_title ) : pattern = ur'\(?\[?\d{0,4}\]?\)?\.?\s*%s\s*$' % re . escape ( section_title ) re_footer = re . compile ( pattern , re . UNICODE ) return [ l for l in ref_lines if not re_footer . match ( l ) ] | Remove footer title from references lines |
236,601 | def extract_references_from_url ( url , headers = None , chunk_size = 1024 , ** kwargs ) : filename , filepath = mkstemp ( suffix = u"_{0}" . format ( os . path . basename ( url ) ) , ) os . close ( filename ) try : req = requests . get ( url = url , headers = headers , stream = True ) req . raise_for_status ( ) with o... | Extract references from the pdf specified in the url . |
236,602 | def extract_references_from_file ( path , recid = None , reference_format = u"{title} {volume} ({year}) {page}" , linker_callback = None , override_kbs_files = None ) : if not os . path . isfile ( path ) : raise FullTextNotAvailableError ( u"File not found: '{0}'" . format ( path ) ) docbody = get_plaintext_document_bo... | Extract references from a local pdf file . |
236,603 | def extract_references_from_string ( source , is_only_references = True , recid = None , reference_format = "{title} {volume} ({year}) {page}" , linker_callback = None , override_kbs_files = None ) : docbody = source . split ( '\n' ) if not is_only_references : reflines , dummy , dummy = extract_references_from_fulltex... | Extract references from a raw string . |
236,604 | def extract_journal_reference ( line , override_kbs_files = None ) : kbs = get_kbs ( custom_kbs_files = override_kbs_files ) references , dummy_m , dummy_c , dummy_co = parse_reference_line ( line , kbs ) for elements in references : for el in elements : if el [ 'type' ] == 'JOURNAL' : return el | Extract the journal reference from string . |
236,605 | def build_references ( citations , reference_format = False ) : return [ c for citation_elements in citations for elements in citation_elements [ 'elements' ] for c in build_reference_fields ( elements , citation_elements [ 'line_marker' ] , citation_elements [ 'raw_ref' ] , reference_format ) ] | Build list of reference dictionaries from a references list |
236,606 | def build_reference_fields ( citation_elements , line_marker , raw_ref , reference_format ) : current_field = create_reference_field ( line_marker ) current_field [ 'raw_ref' ] = [ raw_ref ] reference_fields = [ current_field ] for element in citation_elements : misc_txt = element [ 'misc_txt' ] if misc_txt . strip ( "... | Create the final representation of the reference information . |
236,607 | def extract_texkeys_from_pdf ( pdf_file ) : with open ( pdf_file , 'rb' ) as pdf_stream : try : pdf = PdfFileReader ( pdf_stream , strict = False ) destinations = pdf . getNamedDestinations ( ) except Exception : LOGGER . debug ( u"PDF: Internal PyPDF2 error, no TeXkeys returned." ) return [ ] refs = [ dest for dest in... | Extract the texkeys from the given PDF file |
236,608 | def get_reference_line_numeration_marker_patterns ( prefix = u'' ) : title = u"" if type ( prefix ) in ( str , unicode ) : title = prefix g_name = u'(?P<mark>' g_close = u')' space = ur'\s*' patterns = [ space + title + g_name + ur'\[\s*(?P<marknum>\d+)\s*\]' + g_close , space + title + g_name + ur'\[\s*[a-zA-Z:-]+\+?\... | Return a list of compiled regex patterns used to search for the marker of a reference line in a full - text document . |
236,609 | def get_post_reference_section_title_patterns ( ) : compiled_patterns = [ ] thead = ur'^\s*([\{\(\<\[]?\s*(\w|\d)\s*[\)\}\>\.\-\]]?\s*)?' ttail = ur'(\s*\:\s*)?' numatn = ur'(\d+|\w\b|i{1,3}v?|vi{0,3})[\.\,]{0,2}\b' roman_numbers = ur'[LVIX]' patterns = [ thead + _create_regex_pattern_add_optional_spaces_to_word_charac... | Return a list of compiled regex patterns used to search for the title of the section after the reference section in a full - text document . |
236,610 | def get_post_reference_section_keyword_patterns ( ) : compiled_patterns = [ ] patterns = [ u'(' + _create_regex_pattern_add_optional_spaces_to_word_characters ( u'prepared' ) + ur'|' + _create_regex_pattern_add_optional_spaces_to_word_characters ( u'created' ) + ur').*(AAS\s*)?\sLATEX' , ur'AAS\s+?LATEX\s+?' + _create_... | Return a list of compiled regex patterns used to search for various keywords that can often be found after and therefore suggest the end of a reference section in a full - text document . |
236,611 | def regex_match_list ( line , patterns ) : m = None for ptn in patterns : m = ptn . match ( line ) if m is not None : break return m | Given a list of COMPILED regex patters perform the re . match operation on the line for every pattern . Break from searching at the first match returning the match object . In the case that no patterns match the None type will be returned . |
236,612 | def get_url_repair_patterns ( ) : file_types_list = [ ur'h\s*t\s*m' , ur'h\s*t\s*m\s*l' , ur't\s*x\s*t' ur'p\s*h\s*p' ur'a\s*s\s*p\s*' ur'j\s*s\s*p' , ur'p\s*y' , ur'p\s*l' , ur'x\s*m\s*l' , ur'j\s*p\s*g' , ur'g\s*i\s*f' ur'm\s*o\s*v' ur's\s*w\s*f' ur'p\s*d\s*f' ur'p\s*s' ur'd\s*o\s*c' , ur't\s*e\s*x' , ur's\s*h\s*t\s*... | Initialise and return a list of precompiled regexp patterns that are used to try to re - assemble URLs that have been broken during a document s conversion to plain - text . |
236,613 | def join_lines ( line1 , line2 ) : if line1 == u"" : pass elif line1 [ - 1 ] == u'-' : line1 = line1 [ : - 1 ] elif line1 [ - 1 ] != u' ' : line1 = line1 + u' ' return line1 + line2 | Join 2 lines of text |
236,614 | def repair_broken_urls ( line ) : def _chop_spaces_in_url_match ( m ) : return m . group ( 1 ) . replace ( " " , "" ) for ptn in re_list_url_repair_patterns : line = ptn . sub ( _chop_spaces_in_url_match , line ) return line | Attempt to repair broken URLs in a line of text . |
236,615 | def remove_and_record_multiple_spaces_in_line ( line ) : removed_spaces = { } multispace_matches = re_group_captured_multiple_space . finditer ( line ) for multispace in multispace_matches : removed_spaces [ multispace . start ( ) ] = ( multispace . end ( ) - multispace . start ( ) - 1 ) line = re_group_captured_multip... | For a given string locate all ocurrences of multiple spaces together in the line record the number of spaces found at each position and replace them with a single space . |
236,616 | def remove_page_boundary_lines ( docbody ) : number_head_lines = number_foot_lines = 0 if not document_contains_text ( docbody ) : return docbody page_break_posns = get_page_break_positions ( docbody ) number_head_lines = get_number_header_lines ( docbody , page_break_posns ) number_foot_lines = get_number_footer_lines... | Try to locate page breaks headers and footers within a document body and remove the array cells at which they are found . |
236,617 | def get_page_break_positions ( docbody ) : page_break_posns = [ ] p_break = re . compile ( ur'^\s*\f\s*$' , re . UNICODE ) num_document_lines = len ( docbody ) for i in xrange ( num_document_lines ) : if p_break . match ( docbody [ i ] ) is not None : page_break_posns . append ( i ) return page_break_posns | Locate page breaks in the list of document lines and create a list positions in the document body list . |
236,618 | def get_number_header_lines ( docbody , page_break_posns ) : remaining_breaks = len ( page_break_posns ) - 1 num_header_lines = empty_line = 0 p_wordSearch = re . compile ( ur'([A-Za-z0-9-]+)' , re . UNICODE ) if remaining_breaks > 2 : if remaining_breaks > 3 : next_head = 2 else : next_head = 1 keep_checking = 1 while... | Try to guess the number of header lines each page of a document has . The positions of the page breaks in the document are used to try to guess the number of header lines . |
236,619 | def get_number_footer_lines ( docbody , page_break_posns ) : num_breaks = len ( page_break_posns ) num_footer_lines = 0 empty_line = 0 keep_checking = 1 p_wordSearch = re . compile ( unicode ( r'([A-Za-z0-9-]+)' ) , re . UNICODE ) if num_breaks > 2 : while keep_checking : cur_break = 1 if page_break_posns [ cur_break ]... | Try to guess the number of footer lines each page of a document has . The positions of the page breaks in the document are used to try to guess the number of footer lines . |
236,620 | def strip_headers_footers_pagebreaks ( docbody , page_break_posns , num_head_lines , num_foot_lines ) : num_breaks = len ( page_break_posns ) page_lens = [ ] for x in xrange ( 0 , num_breaks ) : if x < num_breaks - 1 : page_lens . append ( page_break_posns [ x + 1 ] - page_break_posns [ x ] ) page_lens . sort ( ) if ( ... | Remove page - break lines header lines and footer lines from the document . |
236,621 | def check_boundary_lines_similar ( l_1 , l_2 ) : num_matches = 0 if ( type ( l_1 ) != list ) or ( type ( l_2 ) != list ) or ( len ( l_1 ) != len ( l_2 ) ) : return 0 num_elements = len ( l_1 ) for i in xrange ( 0 , num_elements ) : if l_1 [ i ] . isdigit ( ) and l_2 [ i ] . isdigit ( ) : num_matches += 1 else : l1_str ... | Compare two lists to see if their elements are roughly the same . |
236,622 | def make_cache_key ( custom_kbs_files = None ) : if custom_kbs_files : serialized_args = ( '%s=%s' % v for v in iteritems ( custom_kbs_files ) ) serialized_args = ';' . join ( serialized_args ) else : serialized_args = "default" cache_key = md5 ( serialized_args ) . digest ( ) return cache_key | Create cache key for kbs caches instances |
236,623 | def create_institute_numeration_group_regexp_pattern ( patterns ) : patterns_list = [ institute_num_pattern_to_regex ( p [ 1 ] ) for p in patterns ] grouped_numeration_pattern = u"(?P<numn>%s)" % u'|' . join ( patterns_list ) return grouped_numeration_pattern | Using a list of regexp patterns for recognising numeration patterns for institute preprint references ordered by length - longest to shortest - create a grouped OR or of these patterns ready to be used in a bigger regexp . |
236,624 | def build_reportnum_kb ( fpath ) : def _add_institute_preprint_patterns ( preprint_classifications , preprint_numeration_ptns , preprint_reference_search_regexp_patterns , standardised_preprint_reference_categories , kb_line_num ) : if preprint_classifications and preprint_numeration_ptns : ordered_patterns = order_rep... | Given the path to a knowledge base file containing the details of institutes and the patterns that their preprint report numbering schemes take create a dictionary of regexp search patterns to recognise these preprint references in reference lines and a dictionary of replacements for non - standard preprint categories ... |
236,625 | def _cmp_bystrlen_reverse ( a , b ) : if len ( a ) > len ( b ) : return - 1 elif len ( a ) < len ( b ) : return 1 else : return 0 | A private cmp function to be used by the sort function of a list when ordering the titles found in a knowledge base by string - length - LONGEST - > SHORTEST . |
236,626 | def build_special_journals_kb ( fpath ) : journals = set ( ) with file_resolving ( fpath ) as fh : for line in fh : if line . startswith ( '#' ) : continue if not line . strip ( ) : continue journals . add ( line . strip ( ) ) return journals | Load special journals database from file |
236,627 | def build_journals_re_kb ( fpath ) : def make_tuple ( match ) : regexp = match . group ( 'seek' ) repl = match . group ( 'repl' ) return regexp , repl kb = [ ] with file_resolving ( fpath ) as fh : for rawline in fh : if rawline . startswith ( '#' ) : continue m_kb_line = re_kb_line . search ( rawline ) kb . append ( m... | Load journals regexps knowledge base |
236,628 | def _parse_content_type ( content_type : Optional [ str ] ) -> Tuple [ Optional [ str ] , str ] : if not content_type : return None , "utf-8" else : type_ , parameters = cgi . parse_header ( content_type ) encoding = parameters . get ( "charset" , "utf-8" ) return type_ , encoding | Tease out the content - type and character encoding . |
236,629 | def _decode_body ( content_type : Optional [ str ] , body : bytes , * , strict : bool = False ) -> Any : type_ , encoding = _parse_content_type ( content_type ) if not len ( body ) or not content_type : return None decoded_body = body . decode ( encoding ) if type_ == "application/json" : return json . loads ( decoded_... | Decode an HTTP body based on the specified content type . |
236,630 | def validate_event ( payload : bytes , * , signature : str , secret : str ) -> None : signature_prefix = "sha1=" if not signature . startswith ( signature_prefix ) : raise ValidationFailure ( "signature does not start with " f"{repr(signature_prefix)}" ) hmac_ = hmac . new ( secret . encode ( "UTF-8" ) , msg = payload ... | Validate the signature of a webhook event . |
236,631 | def accept_format ( * , version : str = "v3" , media : Optional [ str ] = None , json : bool = True ) -> str : accept = f"application/vnd.github.{version}" if media is not None : accept += f".{media}" if json : accept += "+json" return accept | Construct the specification of the format that a request should return . |
236,632 | def create_headers ( requester : str , * , accept : str = accept_format ( ) , oauth_token : Optional [ str ] = None , jwt : Optional [ str ] = None ) -> Dict [ str , str ] : if oauth_token is not None and jwt is not None : raise ValueError ( "Cannot pass both oauth_token and jwt." ) headers = { "user-agent" : requester... | Create a dict representing GitHub - specific header fields . |
236,633 | def decipher_response ( status_code : int , headers : Mapping [ str , str ] , body : bytes ) -> Tuple [ Any , Optional [ RateLimit ] , Optional [ str ] ] : data = _decode_body ( headers . get ( "content-type" ) , body ) if status_code in { 200 , 201 , 204 } : return data , RateLimit . from_http ( headers ) , _next_link... | Decipher an HTTP response for a GitHub API request . |
236,634 | def format_url ( url : str , url_vars : Mapping [ str , Any ] ) -> str : url = urllib . parse . urljoin ( DOMAIN , url ) expanded_url : str = uritemplate . expand ( url , var_dict = url_vars ) return expanded_url | Construct a URL for the GitHub API . |
236,635 | def from_http ( cls , headers : Mapping [ str , str ] , body : bytes , * , secret : Optional [ str ] = None ) -> "Event" : if "x-hub-signature" in headers : if secret is None : raise ValidationFailure ( "secret not provided" ) validate_event ( body , signature = headers [ "x-hub-signature" ] , secret = secret ) elif se... | Construct an event from HTTP headers and JSON body data . |
236,636 | def from_http ( cls , headers : Mapping [ str , str ] ) -> Optional [ "RateLimit" ] : try : limit = int ( headers [ "x-ratelimit-limit" ] ) remaining = int ( headers [ "x-ratelimit-remaining" ] ) reset_epoch = float ( headers [ "x-ratelimit-reset" ] ) except KeyError : return None else : return cls ( limit = limit , re... | Gather rate limit information from HTTP headers . |
236,637 | def add ( self , func : AsyncCallback , event_type : str , ** data_detail : Any ) -> None : if len ( data_detail ) > 1 : msg = ( ) raise TypeError ( "dispatching based on data details is only " "supported up to one level deep; " f"{len(data_detail)} levels specified" ) elif not data_detail : callbacks = self . _shallow... | Add a new route . |
236,638 | async def _make_request ( self , method : str , url : str , url_vars : Dict [ str , str ] , data : Any , accept : str , jwt : Opt [ str ] = None , oauth_token : Opt [ str ] = None , ) -> Tuple [ bytes , Opt [ str ] ] : if oauth_token is not None and jwt is not None : raise ValueError ( "Cannot pass both oauth_token and... | Construct and make an HTTP request . |
236,639 | async def getitem ( self , url : str , url_vars : Dict [ str , str ] = { } , * , accept : str = sansio . accept_format ( ) , jwt : Opt [ str ] = None , oauth_token : Opt [ str ] = None ) -> Any : data , _ = await self . _make_request ( "GET" , url , url_vars , b"" , accept , jwt = jwt , oauth_token = oauth_token ) retu... | Send a GET request for a single item to the specified endpoint . |
236,640 | async def getiter ( self , url : str , url_vars : Dict [ str , str ] = { } , * , accept : str = sansio . accept_format ( ) , jwt : Opt [ str ] = None , oauth_token : Opt [ str ] = None ) -> AsyncGenerator [ Any , None ] : data , more = await self . _make_request ( "GET" , url , url_vars , b"" , accept , jwt = jwt , oau... | Return an async iterable for all the items at a specified endpoint . |
236,641 | def quantize ( self , image ) : if get_cKDTree ( ) : return self . quantize_with_scipy ( image ) else : print ( 'Scipy not available, falling back to slower version.' ) return self . quantize_without_scipy ( image ) | Use a kdtree to quickly find the closest palette colors for the pixels |
236,642 | def inxsearch ( self , r , g , b ) : dists = ( self . colormap [ : , : 3 ] - np . array ( [ r , g , b ] ) ) a = np . argmin ( ( dists * dists ) . sum ( 1 ) ) return a | Search for BGR values 0 .. 255 and return colour index |
236,643 | def gen_filename ( endpoint ) : now = datetime . now ( ) . strftime ( '%Y%m%d_%H%M%S%f' ) [ : - 4 ] base = endpoint . split ( '://' , 1 ) [ 1 ] if base . startswith ( 'localhost:' ) : base = gethostname ( ) . split ( '.' ) [ 0 ] + base [ 9 : ] base = base . replace ( ':' , '_' ) . replace ( '/' , '_' ) return '{}_{}.h5... | Generate a filename from endpoint with timestamp . |
236,644 | def dict_to_hdf5 ( dic , endpoint ) : filename = gen_filename ( endpoint ) with h5py . File ( filename , 'w' ) as handler : walk_dict_to_hdf5 ( dic , handler ) print ( 'dumped to' , filename ) | Dump a dict to an HDF5 file . |
236,645 | def hdf5_to_dict ( filepath , group = '/' ) : if not h5py . is_hdf5 ( filepath ) : raise RuntimeError ( filepath , 'is not a valid HDF5 file.' ) with h5py . File ( filepath , 'r' ) as handler : dic = walk_hdf5_to_dict ( handler [ group ] ) return dic | load the content of an hdf5 file to a dict . |
236,646 | def print_one_train ( client , verbosity = 0 ) : ts_before = time ( ) data , meta = client . next ( ) ts_after = time ( ) if not data : print ( "Empty data" ) return train_id = list ( meta . values ( ) ) [ 0 ] . get ( 'timestamp.tid' , 0 ) print ( "Train ID:" , train_id , "--------------------------" ) delta = ts_after... | Retrieve data for one train and print it . |
236,647 | def pretty_print ( d , ind = '' , verbosity = 0 ) : assert isinstance ( d , dict ) for k , v in sorted ( d . items ( ) ) : str_base = '{} - [{}] {}' . format ( ind , type ( v ) . __name__ , k ) if isinstance ( v , dict ) : print ( str_base . replace ( '-' , '+' , 1 ) ) pretty_print ( v , ind = ind + ' ' , verbosity = ... | Pretty print a data dictionary from the bridge client |
236,648 | def start_gen ( port , ser = 'msgpack' , version = '2.2' , detector = 'AGIPD' , raw = False , nsources = 1 , datagen = 'random' , * , debug = True ) : context = zmq . Context ( ) socket = context . socket ( zmq . REP ) socket . setsockopt ( zmq . LINGER , 0 ) socket . bind ( 'tcp://*:{}' . format ( port ) ) if ser != '... | Karabo bridge server simulation . |
236,649 | def next ( self ) : if self . _pattern == zmq . REQ and not self . _recv_ready : self . _socket . send ( b'next' ) self . _recv_ready = True try : msg = self . _socket . recv_multipart ( copy = False ) except zmq . error . Again : raise TimeoutError ( 'No data received from {} in the last {} ms' . format ( self . _sock... | Request next data container . |
236,650 | def zopen ( filename , * args , ** kwargs ) : if Path is not None and isinstance ( filename , Path ) : filename = str ( filename ) name , ext = os . path . splitext ( filename ) ext = ext . upper ( ) if ext == ".BZ2" : if PY_VERSION [ 0 ] >= 3 : return bz2 . open ( filename , * args , ** kwargs ) else : args = list ( a... | This function wraps around the bz2 gzip and standard python s open function to deal intelligently with bzipped gzipped or standard text files . |
236,651 | def reverse_readline ( m_file , blk_size = 4096 , max_mem = 4000000 ) : is_text = isinstance ( m_file , io . TextIOWrapper ) try : file_size = os . path . getsize ( m_file . name ) except AttributeError : file_size = max_mem + 1 if file_size < max_mem or isinstance ( m_file , gzip . GzipFile ) : for line in reversed ( ... | Generator method to read a file line - by - line but backwards . This allows one to efficiently get data at the end of a file . |
236,652 | def get_open_fds ( ) : pid = os . getpid ( ) procs = subprocess . check_output ( [ "lsof" , '-w' , '-Ff' , "-p" , str ( pid ) ] ) procs = procs . decode ( "utf-8" ) return len ( [ s for s in procs . split ( '\n' ) if s and s [ 0 ] == 'f' and s [ 1 : ] . isdigit ( ) ] ) | Return the number of open file descriptors for current process |
236,653 | def acquire ( self ) : start_time = time . time ( ) while True : try : self . fd = os . open ( self . lockfile , os . O_CREAT | os . O_EXCL | os . O_RDWR ) break except ( OSError , ) as e : if e . errno != errno . EEXIST : raise if ( time . time ( ) - start_time ) >= self . timeout : raise FileLockException ( "%s: Time... | Acquire the lock if possible . If the lock is in use it check again every delay seconds . It does this until it either gets the lock or exceeds timeout number of seconds in which case it throws an exception . |
236,654 | def release ( self ) : if self . is_locked : os . close ( self . fd ) os . unlink ( self . lockfile ) self . is_locked = False | Get rid of the lock by deleting the lockfile . When working in a with statement this gets automatically called at the end . |
236,655 | def filter ( self , names ) : names = list_strings ( names ) fnames = [ ] for f in names : for pat in self . pats : if fnmatch . fnmatch ( f , pat ) : fnames . append ( f ) return fnames | Returns a list with the names matching the pattern . |
236,656 | def match ( self , name ) : for pat in self . pats : if fnmatch . fnmatch ( name , pat ) : return True return False | Returns True if name matches one of the patterns . |
236,657 | def deprecated ( replacement = None , message = None ) : def wrap ( old ) : def wrapped ( * args , ** kwargs ) : msg = "%s is deprecated" % old . __name__ if replacement is not None : if isinstance ( replacement , property ) : r = replacement . fget elif isinstance ( replacement , ( classmethod , staticmethod ) ) : r =... | Decorator to mark classes or functions as deprecated with a possible replacement . |
236,658 | def install_excepthook ( hook_type = "color" , ** kwargs ) : try : from IPython . core import ultratb except ImportError : import warnings warnings . warn ( "Cannot install excepthook, IPyhon.core.ultratb not available" ) return 1 hook = dict ( color = ultratb . ColorTB , verbose = ultratb . VerboseTB , ) . get ( hook_... | This function replaces the original python traceback with an improved version from Ipython . Use color for colourful traceback formatting verbose for Ka - Ping Yee s cgitb . py version kwargs are the keyword arguments passed to the constructor . See IPython . core . ultratb . py for more info . |
236,659 | def regrep ( filename , patterns , reverse = False , terminate_on_match = False , postprocess = str ) : compiled = { k : re . compile ( v ) for k , v in patterns . items ( ) } matches = collections . defaultdict ( list ) gen = reverse_readfile ( filename ) if reverse else zopen ( filename , "rt" ) for i , l in enumerat... | A powerful regular expression version of grep . |
236,660 | def cached_class ( klass ) : cache = { } @ wraps ( klass , assigned = ( "__name__" , "__module__" ) , updated = ( ) ) class _decorated ( klass ) : __doc__ = klass . __doc__ def __new__ ( cls , * args , ** kwargs ) : key = ( cls , ) + args + tuple ( kwargs . items ( ) ) try : inst = cache . get ( key , None ) except Typ... | Decorator to cache class instances by constructor arguments . This results in a class that behaves like a singleton for each set of constructor arguments ensuring efficiency . |
236,661 | def operator_from_str ( op ) : d = { "==" : operator . eq , "!=" : operator . ne , ">" : operator . gt , ">=" : operator . ge , "<" : operator . lt , "<=" : operator . le , '+' : operator . add , '-' : operator . sub , '*' : operator . mul , '%' : operator . mod , '^' : operator . xor , } try : d [ '/' ] = operator . t... | Return the operator associated to the given string op . |
236,662 | def run ( self , timeout = None , ** kwargs ) : from subprocess import Popen , PIPE def target ( ** kw ) : try : self . process = Popen ( self . command , ** kw ) self . output , self . error = self . process . communicate ( ) self . retcode = self . process . returncode except : import traceback self . error = traceba... | Run a command in a separated thread and wait timeout seconds . kwargs are keyword arguments passed to Popen . |
236,663 | def marquee ( text = "" , width = 78 , mark = '*' ) : if not text : return ( mark * width ) [ : width ] nmark = ( width - len ( text ) - 2 ) // len ( mark ) // 2 if nmark < 0 : nmark = 0 marks = mark * nmark return '%s %s %s' % ( marks , text , marks ) | Return the input string centered in a marquee . |
236,664 | def boxed ( msg , ch = "=" , pad = 5 ) : if pad > 0 : msg = pad * ch + " " + msg . strip ( ) + " " + pad * ch return "\n" . join ( [ len ( msg ) * ch , msg , len ( msg ) * ch , ] ) | Returns a string in a box |
236,665 | def indent ( lines , amount , ch = ' ' ) : padding = amount * ch return padding + ( '\n' + padding ) . join ( lines . split ( '\n' ) ) | Indent the lines in a string by padding each one with proper number of pad characters |
236,666 | def prof_main ( main ) : @ wraps ( main ) def wrapper ( * args , ** kwargs ) : import sys try : do_prof = sys . argv [ 1 ] == "prof" if do_prof : sys . argv . pop ( 1 ) except Exception : do_prof = False if not do_prof : sys . exit ( main ( ) ) else : print ( "Entering profiling mode..." ) import pstats , cProfile , te... | Decorator for profiling main programs . |
236,667 | def invalidate ( cls , inst , name ) : inst_cls = inst . __class__ if not hasattr ( inst , '__dict__' ) : raise AttributeError ( "'%s' object has no attribute '__dict__'" % ( inst_cls . __name__ , ) ) if name . startswith ( '__' ) and not name . endswith ( '__' ) : name = '_%s%s' % ( inst_cls . __name__ , name ) if not... | Invalidate a lazy attribute . |
236,668 | def as_set ( obj ) : if obj is None or isinstance ( obj , collections . Set ) : return obj if not isinstance ( obj , collections . Iterable ) : return set ( ( obj , ) ) else : return set ( obj ) | Convert obj into a set returns None if obj is None . |
236,669 | def logged ( level = logging . DEBUG ) : def wrap ( f ) : _logger = logging . getLogger ( "{}.{}" . format ( f . __module__ , f . __name__ ) ) def wrapped_f ( * args , ** kwargs ) : _logger . log ( level , "Called at {} with args = {} and kwargs = {}" . format ( datetime . datetime . now ( ) , args , kwargs ) ) data = ... | Useful logging decorator . If a method is logged the beginning and end of the method call will be logged at a pre - specified level . |
236,670 | def enable_logging ( main ) : @ functools . wraps ( main ) def wrapper ( * args , ** kwargs ) : import argparse parser = argparse . ArgumentParser ( ) parser . add_argument ( '--loglevel' , default = "ERROR" , type = str , help = "Set the loglevel. Possible values: CRITICAL, ERROR (default)," "WARNING, INFO, DEBUG" ) o... | This decorator is used to decorate main functions . It adds the initialization of the logger and an argument parser that allows one to select the loglevel . Useful if we are writing simple main functions that call libraries where the logging module is used |
236,671 | def which ( cmd ) : def is_exe ( fp ) : return os . path . isfile ( fp ) and os . access ( fp , os . X_OK ) fpath , fname = os . path . split ( cmd ) if fpath : if is_exe ( cmd ) : return cmd else : for path in os . environ [ "PATH" ] . split ( os . pathsep ) : exe_file = os . path . join ( path , cmd ) if is_exe ( exe... | Returns full path to a executable . |
236,672 | def all_subclasses ( cls ) : subclasses = cls . __subclasses__ ( ) return subclasses + [ g for s in subclasses for g in all_subclasses ( s ) ] | Given a class cls this recursive function returns a list with all subclasses subclasses of subclasses and so on . |
236,673 | def find_top_pyfile ( ) : import os frame = currentframe ( ) while True : if frame . f_back is None : finfo = getframeinfo ( frame ) return os . path . abspath ( finfo . filename ) frame = frame . f_back | This function inspects the Cpython frame to find the path of the script . |
236,674 | def pprint_table ( table , out = sys . stdout , rstrip = False ) : def max_width_col ( table , col_idx ) : return max ( [ len ( row [ col_idx ] ) for row in table ] ) if rstrip : for row_idx , row in enumerate ( table ) : table [ row_idx ] = [ c . rstrip ( ) for c in row ] col_paddings = [ ] ncols = len ( table [ 0 ] )... | Prints out a table of data padded for alignment Each row must have the same number of columns . |
236,675 | def gcd ( * numbers ) : n = numbers [ 0 ] for i in numbers : n = pygcd ( n , i ) return n | Returns the greatest common divisor for a sequence of numbers . |
236,676 | def lcm ( * numbers ) : n = 1 for i in numbers : n = ( i * n ) // gcd ( i , n ) return n | Return lowest common multiple of a sequence of numbers . |
236,677 | def gcd_float ( numbers , tol = 1e-8 ) : def pair_gcd_tol ( a , b ) : while b > tol : a , b = b , a % b return a n = numbers [ 0 ] for i in numbers : n = pair_gcd_tol ( n , i ) return n | Returns the greatest common divisor for a sequence of numbers . Uses a numerical tolerance so can be used on floats |
236,678 | def chunks ( items , n ) : it = iter ( items ) chunk = tuple ( itertools . islice ( it , n ) ) while chunk : yield chunk chunk = tuple ( itertools . islice ( it , n ) ) | Yield successive n - sized chunks from a list - like object . |
236,679 | def iterator_from_slice ( s ) : import numpy as np start = s . start if s . start is not None else 0 step = s . step if s . step is not None else 1 if s . stop is None : return itertools . count ( start = start , step = step ) else : return iter ( np . arange ( start , s . stop , step ) ) | Constructs an iterator given a slice object s . |
236,680 | def colored_map ( text , cmap ) : if not __ISON : return text for key , v in cmap . items ( ) : if isinstance ( v , dict ) : text = text . replace ( key , colored ( key , ** v ) ) else : text = text . replace ( key , colored ( key , color = v ) ) return text | Return colorized text . cmap is a dict mapping tokens to color options . |
236,681 | def cprint_map ( text , cmap , ** kwargs ) : try : print ( colored_map ( text , cmap ) , ** kwargs ) except TypeError : kwargs . pop ( "flush" , None ) print ( colored_map ( text , cmap ) , ** kwargs ) | Print colorize text . cmap is a dict mapping keys to color options . kwargs are passed to print function |
236,682 | def as_dict ( self ) : d = { "@module" : self . __class__ . __module__ , "@class" : self . __class__ . __name__ } try : parent_module = self . __class__ . __module__ . split ( '.' ) [ 0 ] module_version = import_module ( parent_module ) . __version__ d [ "@version" ] = u"{}" . format ( module_version ) except Attribute... | A JSON serializable dict representation of an object . |
236,683 | def process_decoded ( self , d ) : if isinstance ( d , dict ) : if "@module" in d and "@class" in d : modname = d [ "@module" ] classname = d [ "@class" ] else : modname = None classname = None if modname and modname not in [ "bson.objectid" , "numpy" ] : if modname == "datetime" and classname == "datetime" : try : dt ... | Recursive method to support decoding dicts and lists containing pymatgen objects . |
236,684 | def nCr ( n , r ) : f = math . factorial return int ( f ( n ) / f ( r ) / f ( n - r ) ) | Calculates nCr . |
236,685 | def nPr ( n , r ) : f = math . factorial return int ( f ( n ) / f ( n - r ) ) | Calculates nPr . |
236,686 | def copy_r ( src , dst ) : abssrc = os . path . abspath ( src ) absdst = os . path . abspath ( dst ) try : os . makedirs ( absdst ) except OSError : pass for f in os . listdir ( abssrc ) : fpath = os . path . join ( abssrc , f ) if os . path . isfile ( fpath ) : shutil . copy ( fpath , absdst ) elif not absdst . starts... | Implements a recursive copy function similar to Unix s cp - r command . Surprisingly python does not have a real equivalent . shutil . copytree only works if the destination directory is not present . |
236,687 | def gzip_dir ( path , compresslevel = 6 ) : for f in os . listdir ( path ) : full_f = os . path . join ( path , f ) if not f . lower ( ) . endswith ( "gz" ) : with open ( full_f , 'rb' ) as f_in , GzipFile ( '{}.gz' . format ( full_f ) , 'wb' , compresslevel = compresslevel ) as f_out : shutil . copyfileobj ( f_in , f_... | Gzips all files in a directory . Note that this is different from shutil . make_archive which creates a tar archive . The aim of this method is to create gzipped files that can still be read using common Unix - style commands like zless or zcat . |
236,688 | def compress_file ( filepath , compression = "gz" ) : if compression not in [ "gz" , "bz2" ] : raise ValueError ( "Supported compression formats are 'gz' and 'bz2'." ) from monty . io import zopen if not filepath . lower ( ) . endswith ( ".%s" % compression ) : with open ( filepath , 'rb' ) as f_in , zopen ( '%s.%s' % ... | Compresses a file with the correct extension . Functions like standard Unix command line gzip and bzip2 in the sense that the original uncompressed files are not retained . |
236,689 | def compress_dir ( path , compression = "gz" ) : for parent , subdirs , files in os . walk ( path ) : for f in files : compress_file ( os . path . join ( parent , f ) , compression = compression ) | Recursively compresses all files in a directory . Note that this compresses all files singly i . e . it does not create a tar archive . For that just use Python tarfile class . |
236,690 | def decompress_file ( filepath ) : toks = filepath . split ( "." ) file_ext = toks [ - 1 ] . upper ( ) from monty . io import zopen if file_ext in [ "BZ2" , "GZ" , "Z" ] : with open ( "." . join ( toks [ 0 : - 1 ] ) , 'wb' ) as f_out , zopen ( filepath , 'rb' ) as f_in : f_out . writelines ( f_in ) os . remove ( filepa... | Decompresses a file with the correct extension . Automatically detects gz bz2 or z extension . |
236,691 | def decompress_dir ( path ) : for parent , subdirs , files in os . walk ( path ) : for f in files : decompress_file ( os . path . join ( parent , f ) ) | Recursively decompresses all files in a directory . |
236,692 | def remove ( path , follow_symlink = False ) : if os . path . isfile ( path ) : os . remove ( path ) elif os . path . islink ( path ) : if follow_symlink : remove ( os . readlink ( path ) ) os . unlink ( path ) else : shutil . rmtree ( path ) | Implements an remove function that will delete files folder trees and symlink trees |
236,693 | def compute_hashes ( obj , hashes = frozenset ( [ 'md5' ] ) ) : if not ( hasattr ( obj , 'read' ) or isinstance ( obj , bytes ) ) : raise ValueError ( "Cannot compute hash for given input: a file-like object or bytes-like object is required" ) hashers = dict ( ) for alg in hashes : try : hashers [ alg ] = hashlib . new... | Digests input data read from file - like object fd or passed directly as bytes - like object . Compute hashes for multiple algorithms . Default is MD5 . Returns a tuple of a hex - encoded digest string and a base64 - encoded value suitable for an HTTP header . |
236,694 | def compute_file_hashes ( file_path , hashes = frozenset ( [ 'md5' ] ) ) : if not os . path . exists ( file_path ) : logging . warning ( "%s does not exist" % file_path ) return else : logging . debug ( "Computing [%s] hashes for file [%s]" % ( ',' . join ( hashes ) , file_path ) ) try : with open ( file_path , 'rb' ) ... | Digests data read from file denoted by file_path . |
236,695 | def validate ( self , processes = 1 , fast = False , completeness_only = False , callback = None ) : self . _validate_structure ( ) self . _validate_bagittxt ( ) self . _validate_fetch ( ) self . _validate_contents ( processes = processes , fast = fast , completeness_only = completeness_only , callback = callback ) ret... | Checks the structure and contents are valid . |
236,696 | def _validate_fetch ( self ) : for url , file_size , filename in self . fetch_entries ( ) : parsed_url = urlparse ( url ) if not all ( parsed_url . scheme ) : raise BagError ( _ ( 'Malformed URL in fetch.txt: %s' ) % url ) | Validate the fetch . txt file |
236,697 | def _validate_completeness ( self ) : errors = list ( ) only_in_manifests , only_on_fs , only_in_fetch = self . compare_manifests_with_fs_and_fetch ( ) for path in only_in_manifests : e = FileMissing ( path ) LOGGER . warning ( force_unicode ( e ) ) errors . append ( e ) for path in only_on_fs : e = UnexpectedFile ( pa... | Verify that the actual file manifests match the files in the data directory |
236,698 | def get_detection_results ( url , timeout , metadata = False , save_har = False ) : plugins = load_plugins ( ) if not plugins : raise NoPluginsError ( 'No plugins found' ) logger . debug ( '[+] Starting detection with %(n)d plugins' , { 'n' : len ( plugins ) } ) response = get_response ( url , plugins , timeout ) if sa... | Return results from detector . |
236,699 | def get_plugins ( metadata ) : plugins = load_plugins ( ) if not plugins : raise NoPluginsError ( 'No plugins found' ) results = [ ] for p in sorted ( plugins . get_all ( ) , key = attrgetter ( 'name' ) ) : if metadata : data = { 'name' : p . name , 'homepage' : p . homepage } hints = getattr ( p , 'hints' , [ ] ) if h... | Return the registered plugins . |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.