idx
int64
0
63k
question
stringlengths
53
5.28k
target
stringlengths
5
805
34,200
def is_date ( v ) -> ( bool , date ) : if isinstance ( v , date ) : return True , v try : reg = r'^([0-9]{4})(?:-(0[1-9]|1[0-2])(?:-(0[1-9]|[1-2][0-9]|3[0-1])(?:T' r'([0-5][0-9])(?::([0-5][0-9])(?::([0-5][0-9]))?)?)?)?)?$' match = re . match ( reg , v ) if match : groups = match . groups ( ) patterns = [ '%Y' , '%m' , ...
Boolean function for checking if v is a date
34,201
def is_location ( v ) -> ( bool , str ) : def convert2float ( value ) : try : float_num = float ( value ) return float_num except ValueError : return False if not isinstance ( v , str ) : return False , v split_lst = v . split ( ":" ) if len ( split_lst ) != 5 : return False , v if convert2float ( split_lst [ 3 ] ) : l...
Boolean function for checking if v is a location format
34,202
def select_segments ( self , jsonpath : str ) -> List [ Segment ] : path = self . etk . parse_json_path ( jsonpath ) matches = path . find ( self . cdr_document ) segments = list ( ) for a_match in matches : this_segment = Segment ( str ( a_match . full_path ) , a_match . value , self ) segments . append ( this_segment...
Dereferences the json_path inside the document and returns the selected elements . This method should compile and cache the compiled json_path in case the same path is reused by multiple extractors .
34,203
def attribute_value ( self , doc : Document , attribute_name : str ) : return doc . cdr_document . get ( self . header_translation_table [ attribute_name ] )
Access data using attribute name rather than the numeric indices
34,204
def all_cities ( ) : cities = [ ] fname = pkg_resources . resource_filename ( __name__ , 'resources/CityPops.csv' ) with open ( fname , 'rU' ) as csvfile : reader = csv . reader ( csvfile , delimiter = ',' ) for row in reader : cities . append ( row [ 0 ] ) cities . sort ( ) return cities
Get a list of all Backpage city names .
34,205
def city_nums ( ) : city_nums = { } first_row = 1 num = 0 fname = pkg_resources . resource_filename ( __name__ , 'resources/Distance_Matrix.csv' ) with open ( fname , 'rU' ) as csvfile : reader = csv . reader ( csvfile , delimiter = ',' ) for row in reader : if first_row == 1 : first_row = 0 else : city_nums [ row [ 0 ...
Get a dictionary of Backpage city names mapped to their legend value .
34,206
def date_clean ( date , dashboard_style = False ) : if dashboard_style : dt = str ( date ) out = dt [ 4 : 6 ] + '/' + dt [ 6 : ] + '/' + dt [ : 4 ] else : dt = str ( date ) out = dt [ : 4 ] + '-' + dt [ 4 : 6 ] + '-' + dt [ 6 : ] return out
Clean the numerical date value in order to present it .
34,207
def date_range ( start , end , boo ) : earliest = datetime . strptime ( start . replace ( '-' , ' ' ) , '%Y %m %d' ) latest = datetime . strptime ( end . replace ( '-' , ' ' ) , '%Y %m %d' ) num_days = ( latest - earliest ) . days + 1 all_days = [ latest - timedelta ( days = x ) for x in range ( num_days ) ] all_days ....
Return list of dates within a specified range inclusive .
34,208
def ethnicities_clean ( ) : eths_clean = { } fname = pkg_resources . resource_filename ( __name__ , 'resources/Ethnicity_Groups.csv' ) with open ( fname , 'rU' ) as csvfile : reader = csv . reader ( csvfile , delimiter = ',' ) first = [ ] for row in reader : if first : for i in range ( len ( first ) ) : if first [ i ] ...
Get dictionary of unformatted ethnicity types mapped to clean corresponding ethnicity strings
34,209
def formal_cities ( reverse = False ) : output = { } fname = pkg_resources . resource_filename ( __name__ , 'resources/Formal_City_Name_Pairs.csv' ) with open ( fname , 'rU' ) as csvfile : reader = csv . reader ( csvfile , delimiter = ',' ) for row in reader : if not reverse : output [ row [ 0 ] ] = row [ 1 ] else : ou...
Get a dictionary that maps all Backpage city names to their presentable formal names .
34,210
def get_lats ( ) : lats = { } fname = pkg_resources . resource_filename ( __name__ , 'resources/Latitudes-Longitudes.csv' ) with open ( fname , 'rb' ) as csvfile : reader = csv . reader ( csvfile , delimiter = ',' ) for row in reader : word = row [ 0 ] . lower ( ) word = re . sub ( ' ' , '' , word ) lats [ word ] = flo...
Get a dictionary that maps Backpage city names to their respective latitudes .
34,211
def get_longs ( ) : longs = { } fname = pkg_resources . resource_filename ( __name__ , 'resources/Latitudes-Longitudes.csv' ) with open ( fname , 'rb' ) as csvfile : reader = csv . reader ( csvfile , delimiter = ',' ) for row in reader : word = row [ 0 ] . lower ( ) word = re . sub ( ' ' , '' , word ) longs [ word ] = ...
Get a dictionary that maps Backpage city names to their respective longitudes .
34,212
def get_regions ( ) : new_england = [ 'Connecticut' , 'Maine' , 'Massachusetts' , 'New Hampshire' , 'Rhode Island' , 'Vermont' ] mid_atlantic = [ 'New Jersey' , 'New York' , 'Pennsylvania' , 'Delaware' , 'Maryland' , 'District of Columbia' ] midwest_east = [ 'Illinois' , 'Indiana' , 'Michigan' , 'Ohio' , 'Wisconsin' ] ...
Get a dictionary of state names mapped to their respective region numeric values .
34,213
def populations ( ) : city_pops = { } fname = pkg_resources . resource_filename ( __name__ , 'resources/CityPops.csv' ) with open ( fname , 'rU' ) as csvfile : reader = csv . reader ( csvfile , delimiter = ',' ) for row in reader : city_pops [ row [ 0 ] ] = int ( row [ 1 ] ) return city_pops
Get a dictionary of Backpage city names mapped to their citizen populations .
34,214
def state_names ( ) : names = set ( ) fname = pkg_resources . resource_filename ( __name__ , 'resources/States.csv' ) with open ( fname , 'rU' ) as csvfile : reader = csv . reader ( csvfile , delimiter = ',' ) for row in reader : names . add ( row [ 0 ] ) return names
Get the set of all US state names
34,215
def state_nums ( ) : st_nums = { } fname = pkg_resources . resource_filename ( __name__ , 'resources/States.csv' ) with open ( fname , 'rU' ) as csvfile : reader = csv . reader ( csvfile , delimiter = ',' ) i = 0 for row in reader : st_nums [ row [ 0 ] ] = i i = i + 1 return st_nums
Get a dictionary of state names mapped to their legend value .
34,216
def states ( ) : states = { } fname = pkg_resources . resource_filename ( __name__ , 'resources/City_State_Pairs.csv' ) with open ( fname , 'rU' ) as csvfile : reader = csv . reader ( csvfile , delimiter = ',' ) for row in reader : states [ row [ 0 ] ] = row [ 1 ] return states
Get a dictionary of Backpage city names mapped to their respective states .
34,217
def today ( boo ) : tod = datetime . strptime ( datetime . today ( ) . date ( ) . isoformat ( ) . replace ( '-' , ' ' ) , '%Y %m %d' ) if boo : return int ( str ( tod ) . replace ( '-' , '' ) [ : 8 ] ) else : return str ( tod ) [ : 10 ]
Return today s date as either a String or a Number as specified by the User .
34,218
def _generate_ngrams_with_context ( self , tokens : List [ Token ] ) -> chain : chained_ngrams_iter = self . _generate_ngrams_with_context_helper ( iter ( tokens ) , 1 ) for n in range ( 2 , self . _ngrams + 1 ) : ngrams_iter = tee ( tokens , n ) for j in range ( 1 , n ) : for k in range ( j ) : next ( ngrams_iter [ j ...
Generates the 1 - gram to n - grams tuples of the list of tokens
34,219
def _populate_trie ( self , values : List [ str ] ) -> CharTrie : if self . _default_tokenizer : return reduce ( self . _populate_trie_reducer , iter ( values ) , CharTrie ( ) ) return reduce ( self . _populate_trie_reducer_regex , iter ( values ) , CharTrie ( ) )
Takes a list and inserts its elements into a new trie and returns it
34,220
def _generate_ngrams_with_context_helper ( ngrams_iter : iter , ngrams_len : int ) -> map : return map ( lambda term : ( term [ 1 ] , term [ 0 ] , term [ 0 ] + ngrams_len ) , enumerate ( ngrams_iter ) )
Updates the end index
34,221
def _combine_ngrams ( ngrams , joiner ) -> str : if isinstance ( ngrams , str ) : return ngrams else : combined = joiner . join ( ngrams ) return combined
Construct keys for checking in trie
34,222
def extract ( self , text : str ) -> List [ Extraction ] : doc = self . _tokenizer . tokenize_to_spacy_doc ( text ) self . _load_matcher ( ) matches = [ x for x in self . _matcher ( doc ) if x [ 1 ] != x [ 2 ] ] pos_filtered_matches = [ ] neg_filtered_matches = [ ] for idx , start , end in matches : span_doc = self . _...
Extract from text
34,223
def _load_matcher ( self ) -> None : for id_key in self . _rule_lst : if self . _rule_lst [ id_key ] . active : pattern_lst = [ a_pattern . spacy_token_lst for a_pattern in self . _rule_lst [ id_key ] . patterns ] for spacy_rule_id , spacy_rule in enumerate ( itertools . product ( * pattern_lst ) ) : self . _matcher . ...
Add constructed spacy rule to Matcher
34,224
def make_json_serializable ( doc : Dict ) : for k , v in doc . items ( ) : if isinstance ( v , datetime . date ) : doc [ k ] = v . strftime ( "%Y-%m-%d" ) elif isinstance ( v , datetime . datetime ) : doc [ k ] = v . isoformat ( )
Make the document JSON serializable . This is a poor man s implementation that handles dates and nothing else . This method modifies the given document in place .
34,225
def filter ( self , extractions , case_sensitive = False ) -> List [ Extraction ] : filtered_extractions = [ ] if not isinstance ( extractions , list ) : extractions = [ extractions ] for extraction in extractions : if case_sensitive : try : if extraction . value . lower ( ) not in self . black_list : filtered_extracti...
filters out the extraction if extracted value is in the blacklist
34,226
def rdf_generation ( kg_object ) -> str : import json if isinstance ( kg_object , dict ) : kg_object = json . dumps ( kg_object ) g = Graph ( ) g . parse ( data = kg_object , format = 'json-ld' ) return g . serialize ( format = 'nt' ) . decode ( 'utf-8' )
Convert input knowledge graph object into n - triples RDF
34,227
def is_legal_object ( self , data_type : str ) -> bool : data_type = str ( data_type ) ranges = self . included_ranges ( ) return not ranges or data_type in ranges or self . super_properties ( ) and any ( x . is_legal_object ( data_type ) for x in self . super_properties ( ) )
Do data_type validation according to the rules of the XML xsd schema .
34,228
def get_entity ( self , uri : str ) -> OntologyClass : return self . entities . get ( str ( uri ) , None )
Find an ontology entity based on URI
34,229
def merge_with_master_config ( self , config , defaults = { } , delete_orphan_fields = False ) -> dict : if isinstance ( config , str ) : import json config = json . loads ( config ) properties = self . all_properties ( ) config [ 'fields' ] = config . get ( 'fields' , dict ( ) ) fields = config [ 'fields' ] d_color = ...
Merge current ontology with input master config .
34,230
def phone_text_subs ( ) : Small = { 'zero' : 0 , 'zer0' : 0 , 'one' : 1 , 'two' : 2 , 'three' : 3 , 'four' : 4 , 'fuor' : 4 , 'five' : 5 , 'fith' : 5 , 'six' : 6 , 'seven' : 7 , 'sven' : 7 , 'eight' : 8 , 'nine' : 9 , 'ten' : 10 , 'eleven' : 11 , 'twelve' : 12 , 'thirteen' : 13 , 'fourteen' : 14 , 'fifteen' : 15 , 'six...
Gets a dictionary of dictionaries that each contain alphabetic number manifestations mapped to their actual Number value .
34,231
def extract ( self , text : str ) -> List [ Extraction ] : doc = self . _parser ( text ) extractions = list ( ) for sent in doc . sents : this_extraction = Extraction ( value = sent . text , extractor_name = self . name , start_token = sent [ 0 ] , end_token = sent [ - 1 ] , start_char = sent . text [ 0 ] , end_char = ...
Splits text by sentences .
34,232
def gen_html ( row_list ) : table = "<table>" for row in row_list : table += "<tr>" cells = row [ "cells" ] for c in cells : t = c [ 'cell' ] if c else '' table += t table += "</tr>" table += "</table>" return table
Return html table string from a list of data rows
34,233
def extract ( self , html_text : str , strategy : Strategy = Strategy . ALL_TEXT ) -> List [ Extraction ] : if html_text : if strategy == Strategy . ALL_TEXT : soup = BeautifulSoup ( html_text , 'html.parser' ) texts = soup . findAll ( text = True ) visible_texts = filter ( self . _tag_visible , texts ) all_text = u" "...
Extracts text from an HTML page using a variety of strategies
34,234
def clean_part_ethn ( body ) : patterns_to_remove = [ r'black ?or ?african' , r'african ?or ?black' , r'no ?black' , r'no ?african' , r'no ?aa' , r'white ?men' , r'white ?gentlemen' , r'no ?spanish' , r'speak ?spanish' , r'black ?(guys|men|hair|client)' , r'dark ?hair' , r'(dark ?)?brown ?hair' , r'white ?tie' ] indian...
Prepare a string to be parsed for ethnicities .
34,235
def _add_doc_value ( self , field_name : str , jsonpath : str ) -> None : path = self . origin_doc . etk . parse_json_path ( jsonpath ) matches = path . find ( self . origin_doc . value ) all_valid = True invalid = [ ] for a_match in matches : if a_match . value : valid = self . _add_value ( field_name , a_match . valu...
Add a value to knowledge graph by giving a jsonpath
34,236
def add_value ( self , field_name : str , value : object = None , json_path : str = None , json_path_extraction : str = None , keep_empty : bool = False ) -> None : def validate ( v ) : if v is not None : if isinstance ( v , str ) : if v . strip ( ) != "" or keep_empty : return True else : return False else : return Tr...
Add a value to knowledge graph . Input can either be a value or a json_path . If the input is json_path the helper function _add_doc_value is called . If the input is a value then it is handled
34,237
def get_values ( self , field_name : str ) -> List [ object ] : result = list ( ) if self . validate_field ( field_name ) : for value_key in self . _kg . get ( field_name ) : result . append ( value_key [ "value" ] ) return result
Get a list of all the values of a field .
34,238
def context_resolve ( self , field_uri : str ) -> str : from rdflib . namespace import split_uri context = self . _kg [ "@context" ] = self . _kg . get ( "@context" , dict ( ) ) nm = self . ontology . g . namespace_manager space , name = split_uri ( field_uri ) if "@vocab" not in context and None in nm . namespaces ( )...
According to field_uri to add corresponding context and return a resolvable field_name
34,239
def tokenize_to_spacy_doc ( self , text : str ) -> Doc : if not self . keep_multi_space : text = re . sub ( ' +' , ' ' , text ) doc = self . nlp ( text , disable = [ 'parser' ] ) for a_token in doc : self . custom_token ( a_token ) return doc
Tokenize the given text returning a spacy doc . Used for spacy rule extractor
34,240
def reconstruct_text ( tokens : List [ Token ] ) -> str : return "" . join ( [ x . text_with_ws for x in tokens ] )
Given a list of tokens reconstruct the original text with as much fidelity as possible .
34,241
def _removecleaner ( self , cleaner ) : oldlen = len ( self . _old_cleaners ) self . _old_cleaners = [ oldc for oldc in self . _old_cleaners if not oldc . issame ( cleaner ) ] return len ( self . _old_cleaners ) != oldlen
Remove the cleaner from the list if it already exists . Returns True if the cleaner was removed .
34,242
def add ( repo_path , dest_path ) : mkcfgdir ( ) try : repo = getrepohandler ( repo_path ) except NotARepo as err : echo ( "ERROR: {}: {}" . format ( ERR_NOT_A_REPO , err . repo_path ) ) sys . exit ( 1 ) if repo . isremote : localrepo , needpull = addfromremote ( repo , dest_path ) elif dest_path : raise UsageError ( "...
Registers a git repository with homely so that it will run its HOMELY . py script on each invocation of homely update . homely add also immediately executes a homely update so that the dotfiles are installed straight away . If the git repository is hosted online a local clone will be created first .
34,243
def forget ( identifier ) : errors = False for one in identifier : cfg = RepoListConfig ( ) info = cfg . find_by_any ( one , "ilc" ) if not info : warn ( "No repos matching %r" % one ) errors = True continue note ( "Removing record of repo [%s] at %s" % ( info . shortid ( ) , info . localrepo . repo_path ) ) with savec...
Tells homely to forget about a dotfiles repository that was previously added . You can then run homely update to have homely perform automatic cleanup of anything that was installed by that dotfiles repo .
34,244
def update ( identifiers , nopull , only ) : mkcfgdir ( ) setallowpull ( not nopull ) cfg = RepoListConfig ( ) if len ( identifiers ) : updatedict = { } for identifier in identifiers : repo = cfg . find_by_any ( identifier , "ilc" ) if repo is None : hint = "Try running %s add /path/to/this/repo first" % CMD raise Fata...
Performs a git pull in each of the repositories registered with homely add runs all of their HOMELY . py scripts and then performs automatic cleanup as necessary .
34,245
def pipinstall ( packagename , pips = None , trypips = [ ] , scripts = None ) : if scripts is None : scripts = { } if pips is None : pips = [ ] if len ( trypips ) else [ 'pip' ] engine = getengine ( ) for pip in pips : helper = PIPInstall ( packagename , pip , mustinstall = True , scripts = scripts . get ( pip ) ) engi...
Install packages from pip .
34,246
def getstatus ( ) : if exists ( RUNFILE ) : mtime = os . stat ( RUNFILE ) . st_mtime with open ( SECTIONFILE ) as f : section = f . read ( ) . strip ( ) return UpdateStatus . RUNNING , mtime , section if exists ( PAUSEFILE ) : return UpdateStatus . PAUSED , None , None mtime = None if exists ( TIMEFILE ) : mtime = os ....
Get the status of the previous homely update or any homely update that may be running in another process .
34,247
def find_by_any ( self , identifier , how ) : if "i" in how : match = self . find_by_id ( identifier ) if match : return match if "l" in how : match = self . find_by_localpath ( identifier ) if match : return match if "c" in how : match = self . find_by_canonical ( identifier ) if match : return match
how should be a string with any or all of the characters ilc
34,248
def isOriginalLocation ( attr ) : sourceModule = inspect . getmodule ( attr . load ( ) ) if sourceModule is None : return False currentModule = attr while not isinstance ( currentModule , PythonModule ) : currentModule = currentModule . onObject return currentModule . name == sourceModule . __name__
Attempt to discover if this appearance of a PythonAttribute representing a class refers to the module where that class was defined .
34,249
def initialState ( self , state ) : if self . _initialState is not _NO_STATE : raise ValueError ( "initial state already set to {}" . format ( self . _initialState ) ) self . _initialState = state
Set this automaton s initial state . Raises a ValueError if this automaton already has an initial state .
34,250
def addTransition ( self , inState , inputSymbol , outState , outputSymbols ) : for ( anInState , anInputSymbol , anOutState , _ ) in self . _transitions : if ( anInState == inState and anInputSymbol == inputSymbol ) : raise ValueError ( "already have transition from {} via {}" . format ( inState , inputSymbol ) ) self...
Add the given transition to the outputSymbol . Raise ValueError if there is already a transition with the same inState and inputSymbol .
34,251
def outputAlphabet ( self ) : return set ( chain . from_iterable ( outputSymbols for ( inState , inputSymbol , outState , outputSymbols ) in self . _transitions ) )
The full set of symbols which can be produced by this automaton .
34,252
def states ( self ) : return frozenset ( chain . from_iterable ( ( inState , outState ) for ( inState , inputSymbol , outState , outputSymbol ) in self . _transitions ) )
All valid states ; Q in the mathematical description of a state machine .
34,253
def transition ( self , inputSymbol ) : outState , outputSymbols = self . _automaton . outputForInput ( self . _state , inputSymbol ) outTracer = None if self . _tracer : outTracer = self . _tracer ( self . _state . _name ( ) , inputSymbol . _name ( ) , outState . _name ( ) ) self . _state = outState return ( outputSym...
Transition between states returning any outputs .
34,254
def _getArgSpec ( func ) : spec = getArgsSpec ( func ) return ArgSpec ( args = tuple ( spec . args ) , varargs = spec . varargs , varkw = spec . varkw if six . PY3 else spec . keywords , defaults = spec . defaults if spec . defaults else ( ) , kwonlyargs = tuple ( spec . kwonlyargs ) if six . PY3 else ( ) , kwonlydefau...
Normalize inspect . ArgSpec across python versions and convert mutable attributes to immutable types .
34,255
def _getArgNames ( spec ) : return set ( spec . args + spec . kwonlyargs + ( ( '*args' , ) if spec . varargs else ( ) ) + ( ( '**kwargs' , ) if spec . varkw else ( ) ) + spec . annotations )
Get the name of all arguments defined in a function signature .
34,256
def _keywords_only ( f ) : @ wraps ( f ) def g ( self , ** kw ) : return f ( self , ** kw ) return g
Decorate a function so all its arguments must be passed by keyword .
34,257
def _filterArgs ( args , kwargs , inputSpec , outputSpec ) : named_args = tuple ( zip ( inputSpec . args [ 1 : ] , args ) ) if outputSpec . varargs : return_args = args else : return_args = [ v for n , v in named_args if n in outputSpec . args ] passed_arg_names = tuple ( kwargs ) for name , value in named_args : passe...
Filter out arguments that were passed to input that output won t accept .
34,258
def state ( self , initial = False , terminal = False , serialized = None ) : def decorator ( stateMethod ) : state = MethodicalState ( machine = self , method = stateMethod , serialized = serialized ) if initial : self . _automaton . initialState = state return state return decorator
Declare a state possibly an initial state or a terminal state .
34,259
def input ( self ) : def decorator ( inputMethod ) : return MethodicalInput ( automaton = self . _automaton , method = inputMethod , symbol = self . _symbol ) return decorator
Declare an input .
34,260
def output ( self ) : def decorator ( outputMethod ) : return MethodicalOutput ( machine = self , method = outputMethod ) return decorator
Declare an output .
34,261
def elementMaker ( name , * children , ** attrs ) : formattedAttrs = ' ' . join ( '{}={}' . format ( key , _gvquote ( str ( value ) ) ) for key , value in sorted ( attrs . items ( ) ) ) formattedChildren = '' . join ( children ) return u'<{name} {attrs}>{children}</{name}>' . format ( name = name , attrs = formattedAtt...
Construct a string from the HTML element description .
34,262
def tableMaker ( inputLabel , outputLabels , port , _E = elementMaker ) : colspan = { } if outputLabels : colspan [ 'colspan' ] = str ( len ( outputLabels ) ) inputLabelCell = _E ( "td" , _E ( "font" , inputLabel , face = "menlo-italic" ) , color = "purple" , port = port , ** colspan ) pointSize = { "point-size" : "9" ...
Construct an HTML table to label a state transition .
34,263
def preserveName ( f ) : def decorator ( decorated ) : return copyfunction ( decorated , dict ( name = f . __name__ ) , dict ( name = f . __name__ ) ) return decorator
Preserve the name of the given function on the decorated function .
34,264
def get_kafka_ssl_context ( ) : with NamedTemporaryFile ( suffix = '.crt' ) as cert_file , NamedTemporaryFile ( suffix = '.key' ) as key_file , NamedTemporaryFile ( suffix = '.crt' ) as trust_file : cert_file . write ( os . environ [ 'KAFKA_CLIENT_CERT' ] . encode ( 'utf-8' ) ) cert_file . flush ( ) passwd = standard_b...
Returns an SSL context based on the certificate information in the Kafka config vars .
34,265
def get_kafka_producer ( acks = 'all' , value_serializer = lambda v : json . dumps ( v ) . encode ( 'utf-8' ) ) : producer = KafkaProducer ( bootstrap_servers = get_kafka_brokers ( ) , security_protocol = 'SSL' , ssl_context = get_kafka_ssl_context ( ) , value_serializer = value_serializer , acks = acks ) return produc...
Return a KafkaProducer that uses the SSLContext created with create_ssl_context .
34,266
def get_kafka_consumer ( topic = None , value_deserializer = lambda v : json . loads ( v . decode ( 'utf-8' ) ) ) : consumer = KafkaConsumer ( topic , bootstrap_servers = get_kafka_brokers ( ) , security_protocol = 'SSL' , ssl_context = get_kafka_ssl_context ( ) , value_deserializer = value_deserializer ) return consum...
Return a KafkaConsumer that uses the SSLContext created with create_ssl_context .
34,267
def replace_body_vars ( self , body ) : for key , val in self . job_vars . items ( ) : body = body . replace ( key , val ) return body
Given a multiline string that is the body of the job script replace the placeholders for environment variables with backend - specific realizations and return the modified body . See the job_vars attribute for the mappings that are performed .
34,268
def set_executable ( filename ) : st = os . stat ( filename ) os . chmod ( filename , st . st_mode | stat . S_IEXEC )
Set the exectuable bit on the given filename
34,269
def split_seq ( seq , n_chunks ) : newseq = [ ] splitsize = 1.0 / n_chunks * len ( seq ) for i in range ( n_chunks ) : newseq . append ( seq [ int ( round ( i * splitsize ) ) : int ( round ( ( i + 1 ) * splitsize ) ) ] ) return newseq
Split the given sequence into n_chunks . Suitable for distributing an array of jobs over a fixed number of workers .
34,270
def status ( self ) : if self . _status >= COMPLETED : return self . _status else : cmd = self . backend . cmd_status ( self , finished = False ) response = self . _run_cmd ( cmd , self . remote , ignore_exit_code = True , ssh = self . ssh ) status = self . backend . get_status ( response , finished = False ) if status...
Return the job status as one of the codes defined in the clusterjob . status module . finished communicate with the cluster to determine the job s status .
34,271
def dump ( self , cache_file = None ) : if cache_file is None : cache_file = self . cache_file if cache_file is not None : self . cache_file = cache_file with open ( cache_file , 'wb' ) as pickle_fh : pickle . dump ( ( self . remote , self . backend . name , self . max_sleep_interval , self . job_id , self . _status , ...
Write dump out to file cache_file defaulting to self . cache_file
34,272
def load ( cls , cache_file , backend = None ) : with open ( cache_file , 'rb' ) as pickle_fh : ( remote , backend_name , max_sleep_interval , job_id , status , epilogue , ssh , scp ) = pickle . load ( pickle_fh ) if backend is None : backend = JobScript . _backends [ backend_name ] ar = cls ( backend ) ( ar . remote ,...
Instantiate AsyncResult from dumped cache_file .
34,273
def wait ( self , timeout = None ) : logger = logging . getLogger ( __name__ ) if int ( self . max_sleep_interval ) < int ( self . _min_sleep_interval ) : self . max_sleep_interval = int ( self . _min_sleep_interval ) t0 = time . time ( ) sleep_seconds = min ( 5 , self . max_sleep_interval ) status = self . status prev...
Wait until the result is available or until roughly timeout seconds pass .
34,274
def successful ( self ) : status = self . status assert status >= COMPLETED , "status is %s" % status return ( self . status == COMPLETED )
Return True if the job finished with a COMPLETED status False if it finished with a CANCELLED or FAILED status . Raise an AssertionError if the job has not completed
34,275
def cancel ( self ) : if self . status > COMPLETED : return cmd = self . backend . cmd_cancel ( self ) self . _run_cmd ( cmd , self . remote , ignore_exit_code = True , ssh = self . ssh ) self . _status = CANCELLED self . dump ( )
Instruct the cluster to cancel the running job . Has no effect if job is not running
34,276
def run_epilogue ( self ) : logger = logging . getLogger ( __name__ ) if self . epilogue is not None : with tempfile . NamedTemporaryFile ( 'w' , delete = False ) as epilogue_fh : epilogue_fh . write ( self . epilogue ) tempfilename = epilogue_fh . name set_executable ( tempfilename ) try : sp . check_output ( [ tempfi...
Run the epilogue script in the current working directory .
34,277
def t_ID ( self , t ) : r'[a-zA-Z_@][a-zA-Z0-9_@\-]*' t . type = self . reserved_words . get ( t . value , 'ID' ) return t
r [ a - zA - Z_
34,278
def t_newline ( self , t ) : r'\n' t . lexer . lineno += 1 t . lexer . latest_newline = t . lexpos
r \ n
34,279
def id_pseudopath ( self ) : try : pseudopath = Fields ( str ( self . value [ auto_id_field ] ) ) except ( TypeError , AttributeError , KeyError ) : pseudopath = self . path if self . context : return self . context . id_pseudopath . child ( pseudopath ) else : return pseudopath
Looks like a path but with ids stuck in when available
34,280
def bind ( value , name ) : if isinstance ( value , Markup ) : return value elif requires_in_clause ( value ) : raise MissingInClauseException ( ) else : return _bind_param ( _thread_local . bind_params , name , value )
A filter that prints %s and stores the value in an array so that it can be bound using a prepared statement
34,281
def inject ( function ) : try : bindings = _infer_injected_bindings ( function ) except _BindingNotYetAvailable : bindings = 'deferred' return method_wrapper ( function , bindings )
Decorator declaring parameters to be injected .
34,282
def noninjectable ( * args ) : def decorator ( function ) : argspec = inspect . getfullargspec ( inspect . unwrap ( function ) ) for arg in args : if arg not in argspec . args and arg not in argspec . kwonlyargs : raise UnknownArgument ( 'Unable to mark unknown argument %s ' 'as non-injectable.' % arg ) existing = geta...
Mark some parameters as not injectable .
34,283
def bind ( self , interface , to = None , scope = None ) : if type ( interface ) is type and issubclass ( interface , ( BaseMappingKey , BaseSequenceKey ) ) : return self . multibind ( interface , to , scope = scope ) key = BindingKey . create ( interface ) self . _bindings [ key ] = self . create_binding ( interface ,...
Bind an interface to an implementation .
34,284
def multibind ( self , interface , to , scope = None ) : key = BindingKey . create ( interface ) if key not in self . _bindings : if isinstance ( interface , dict ) or isinstance ( interface , type ) and issubclass ( interface , dict ) : provider = MapBindProvider ( ) else : provider = MultiBindProvider ( ) binding = s...
Creates or extends a multi - binding .
34,285
def install ( self , module ) : if type ( module ) is type and issubclass ( module , Module ) : instance = module ( ) else : instance = module instance ( self )
Install a module into this binder .
34,286
def get ( self , interface : Type [ T ] , scope = None ) -> T : key = BindingKey . create ( interface ) binding , binder = self . binder . get_binding ( None , key ) scope = scope or binding . scope if isinstance ( scope , ScopeDecorator ) : scope = scope . scope scope_key = BindingKey . create ( scope ) scope_binding ...
Get an instance of the given interface .
34,287
def create_object ( self , cls : Type [ T ] , additional_kwargs = None ) -> T : additional_kwargs = additional_kwargs or { } log . debug ( '%sCreating %r object with %r' , self . _log_prefix , cls , additional_kwargs ) try : instance = cls . __new__ ( cls ) except TypeError as e : reraise ( e , CallError ( cls , getatt...
Create a new instance satisfying any dependencies on cls .
34,288
def call_with_injection ( self , callable , self_ = None , args = ( ) , kwargs = { } ) : def _get_callable_bindings ( callable ) : if not hasattr ( callable , '__bindings__' ) : return { } if callable . __bindings__ == 'deferred' : read_and_store_bindings ( callable , _infer_injected_bindings ( callable ) ) return call...
Call a callable and provide it s dependencies if needed .
34,289
def args_to_inject ( self , function , bindings , owner_key ) : dependencies = { } key = ( owner_key , function , tuple ( sorted ( bindings . items ( ) ) ) ) def repr_key ( k ) : owner_key , function , bindings = k return '%s.%s(injecting %s)' % ( tuple ( map ( _describe , k [ : 2 ] ) ) + ( dict ( k [ 2 ] ) , ) ) log ....
Inject arguments into a function .
34,290
def scrub_output_pre_save ( model , ** kwargs ) : if model [ 'type' ] != 'notebook' : return if model [ 'content' ] [ 'nbformat' ] != 4 : return for cell in model [ 'content' ] [ 'cells' ] : if cell [ 'cell_type' ] != 'code' : continue cell [ 'outputs' ] = [ ] cell [ 'execution_count' ] = None
scrub output before saving notebooks
34,291
def close ( self ) : if not self . closed : self . _ipython . events . unregister ( 'post_run_cell' , self . _fill ) self . _box . close ( ) self . closed = True
Close and remove hooks .
34,292
def _fill ( self ) : types_to_exclude = [ 'module' , 'function' , 'builtin_function_or_method' , 'instance' , '_Feature' , 'type' , 'ufunc' ] values = self . namespace . who_ls ( ) def eval ( expr ) : return self . namespace . shell . ev ( expr ) var = [ ( v , type ( eval ( v ) ) . __name__ , str ( _getsizeof ( eval ( ...
Fill self with variable information .
34,293
def set_var ( var , set_ = '""' ) : if isinstance ( set_ , str ) : to_set = json . dumps ( set_ ) elif isinstance ( set_ , dict ) or isinstance ( set_ , list ) : try : to_set = json . dumps ( set_ ) except ValueError : raise Exception ( 'var not jsonable' ) else : raise Exception ( 'var must be jsonable list or dict' )...
set var outside notebook
34,294
def get_var ( var , default = '""' ) : ret = os . environ . get ( 'NBCONVERT_' + var ) if ret is None : return default return json . loads ( ret )
get var inside notebook
34,295
def align_yaxis_np ( axes ) : axes = np . array ( axes ) extrema = np . array ( [ ax . get_ylim ( ) for ax in axes ] ) for i in range ( len ( extrema ) ) : if np . isclose ( extrema [ i , 0 ] , 0.0 ) : extrema [ i , 0 ] = - 1 if np . isclose ( extrema [ i , 1 ] , 0.0 ) : extrema [ i , 1 ] = 1 lowers = extrema [ : , 0 ]...
Align zeros of the two axes zooming them out by same ratio
34,296
def make_dash_table ( df ) : table = [ ] for index , row in df . iterrows ( ) : html_row = [ ] for i in range ( len ( row ) ) : html_row . append ( html . Td ( [ row [ i ] ] ) ) table . append ( html . Tr ( html_row ) ) return table
Return a dash definitio of an HTML table for a Pandas dataframe
34,297
def script_post_save ( model , os_path , contents_manager , ** kwargs ) : from nbconvert . exporters . script import ScriptExporter if model [ 'type' ] != 'notebook' : return global _script_exporter if _script_exporter is None : _script_exporter = ScriptExporter ( parent = contents_manager ) log = contents_manager . lo...
convert notebooks to Python script after save with nbconvert
34,298
def copy ( string , xsel = False ) : try : _cmd = [ "xclip" , "-selection" , "clipboard" ] subprocess . Popen ( _cmd , stdin = subprocess . PIPE ) . communicate ( string . encode ( 'utf-8' ) ) if xsel : _cmd = [ "xclip" , "-selection" , "primary" ] subprocess . Popen ( _cmd , stdin = subprocess . PIPE ) . communicate (...
Copy given string into system clipboard . If xsel is True this will also copy into the primary x selection for middle click .
34,299
def main ( ) : if sys . argv [ 1 : ] : copy ( ' ' . join ( sys . argv [ 1 : ] ) ) elif not sys . stdin . isatty ( ) : copy ( '' . join ( sys . stdin . readlines ( ) ) . rstrip ( '\n' ) ) else : print ( paste ( ) )
Entry point for cli .