idx
int64
0
251k
question
stringlengths
53
3.53k
target
stringlengths
5
1.23k
len_question
int64
20
893
len_target
int64
3
238
300
def __dfs ( self , v , index , layers ) : if index == 0 : path = [ v ] while self . _dfs_parent [ v ] != v : path . append ( self . _dfs_parent [ v ] ) v = self . _dfs_parent [ v ] self . _dfs_paths . append ( path ) return True for neighbour in self . _graph [ v ] : # check the neighbours of vertex if neighbour in lay...
we recursively run dfs on each vertices in free_vertex
227
16
301
def method ( self , symbol ) : assert issubclass ( symbol , SymbolBase ) def wrapped ( fn ) : setattr ( symbol , fn . __name__ , fn ) return wrapped
Symbol decorator .
39
5
302
def _simpleparsefun ( date ) : if hasattr ( date , 'year' ) : return date try : date = datetime . datetime . strptime ( date , '%Y-%m-%d' ) except ValueError : date = datetime . datetime . strptime ( date , '%Y-%m-%d %H:%M:%S' ) return date
Simple date parsing function
88
4
303
def _connect ( cls ) : post_save . connect ( notify_items , sender = cls , dispatch_uid = 'knocker_{0}' . format ( cls . __name__ ) )
Connect signal to current model
45
5
304
def _disconnect ( cls ) : post_save . disconnect ( notify_items , sender = cls , dispatch_uid = 'knocker_{0}' . format ( cls . __name__ ) )
Disconnect signal from current model
46
6
305
def as_knock ( self , created = False ) : knock = { } if self . should_knock ( created ) : for field , data in self . _retrieve_data ( None , self . _knocker_data ) : knock [ field ] = data return knock
Returns a dictionary with the knock data built from _knocker_data
60
14
306
def send_knock ( self , created = False ) : knock = self . as_knock ( created ) if knock : gr = Group ( 'knocker-{0}' . format ( knock [ 'language' ] ) ) gr . send ( { 'text' : json . dumps ( knock ) } )
Send the knock in the associated channels Group
67
8
307
def colorize ( printable , color , style = 'normal' , autoreset = True ) : if not COLORED : # disable color return printable if color not in COLOR_MAP : raise RuntimeError ( 'invalid color set, no {}' . format ( color ) ) return '{color}{printable}{reset}' . format ( printable = printable , color = COLOR_MAP [ color ] ...
Colorize some message with ANSI colors specification
123
9
308
def color ( string , status = True , warning = False , bold = True ) : attr = [ ] if status : # green attr . append ( '32' ) if warning : # red attr . append ( '31' ) if bold : attr . append ( '1' ) return '\x1b[%sm%s\x1b[0m' % ( ';' . join ( attr ) , string )
Change text color for the linux terminal defaults to green . Set warning = True for red .
96
18
309
def _patch ( ) : if not __debug__ : # pragma: no cover import warnings warnings . warn ( "A catgirl has died." , ImportWarning ) from pymongo . collection import Collection Collection . tail = tail
Patch pymongo s Collection object to add a tail method . While not nessicarily recommended you can use this to inject tail as a method into Collection making it generally accessible .
48
37
310
def _prepare_find ( cls , * args , * * kw ) : cls , collection , query , options = cls . _prepare_query ( cls . FIND_MAPPING , cls . FIND_OPTIONS , * args , * * kw ) if 'await' in options : raise TypeError ( "Await is hard-deprecated as reserved keyword in Python 3.7, use wait instead." ) if 'cursor_type' in options an...
Execute a find and return the resulting queryset using combined plain and parametric query generation . Additionally performs argument case normalization refer to the _prepare_query method s docstring .
288
39
311
def reload ( self , * fields , * * kw ) : Doc , collection , query , options = self . _prepare_find ( id = self . id , projection = fields , * * kw ) result = collection . find_one ( query , * * options ) if fields : # Refresh only the requested data. for k in result : # TODO: Better merge algorithm. if k == ~ Doc . id...
Reload the entire document from the database or refresh specific named top - level fields .
115
17
312
def get ( cls ) : results = { } hierarchy = cls . __hierarchy hierarchy . reverse ( ) for storeMethod in hierarchy : cls . merger . merge ( results , storeMethod . get ( ) ) return results
Get values gathered from the previously set hierarchy .
49
9
313
def argv ( cls , name , short_name = None , type = None , help = None ) : cls . __hierarchy . append ( argv . Argv ( name , short_name , type , help ) )
Set command line arguments as a source
51
7
314
def env ( cls , separator = None , match = None , whitelist = None , parse_values = None , to_lower = None , convert_underscores = None ) : cls . __hierarchy . append ( env . Env ( separator , match , whitelist , parse_values , to_lower , convert_underscores ) )
Set environment variables as a source .
79
7
315
def file ( cls , path , encoding = None , parser = None ) : cls . __hierarchy . append ( file . File ( path , encoding , parser ) )
Set a file as a source .
38
7
316
def P ( Document , * fields , * * kw ) : __always__ = kw . pop ( '__always__' , set ( ) ) projected = set ( ) omitted = set ( ) for field in fields : if field [ 0 ] in ( '-' , '!' ) : omitted . add ( field [ 1 : ] ) elif field [ 0 ] == '+' : projected . add ( field [ 1 : ] ) else : projected . add ( field ) if not proj...
Generate a MongoDB projection dictionary using the Django ORM style .
197
14
317
def is_valid ( self , context , sid ) : record = self . _Document . find_one ( sid , project = ( 'expires' , ) ) if not record : return return not record . _expired
Identify if the given session ID is currently valid . Return True if valid False if explicitly invalid None if unknown .
47
23
318
def invalidate ( self , context , sid ) : result = self . _Document . get_collection ( ) . delete_one ( { '_id' : sid } ) return result . deleted_count == 1
Immediately expire a session from the backing store .
45
10
319
def persist ( self , context ) : D = self . _Document document = context . session [ self . name ] D . get_collection ( ) . replace_one ( D . id == document . id , document , True )
Update or insert the session document into the configured collection
48
10
320
def ws_connect ( message ) : prefix , language = message [ 'path' ] . strip ( '/' ) . split ( '/' ) gr = Group ( 'knocker-{0}' . format ( language ) ) gr . add ( message . reply_channel ) message . channel_session [ 'knocker' ] = language message . reply_channel . send ( { "accept" : True } )
Channels connection setup . Register the current client on the related Group according to the language
88
17
321
def ws_disconnect ( message ) : language = message . channel_session [ 'knocker' ] gr = Group ( 'knocker-{0}' . format ( language ) ) gr . discard ( message . reply_channel )
Channels connection close . Deregister the client
51
11
322
def start ( self , autopush = True ) : if self . enabled : if autopush : self . push_message ( self . message ) self . spinner . message = ' - ' . join ( self . animation . messages ) if not self . spinner . running : self . animation . thread = threading . Thread ( target = _spinner , args = ( self . spinner , ) ) sel...
Start a new animation instance
123
5
323
def stop ( cls ) : if AnimatedDecorator . _enabled : if cls . spinner . running : cls . spinner . running = False cls . animation . thread . join ( ) if any ( cls . animation . messages ) : cls . pop_message ( ) sys . stdout = sys . __stdout__
Stop the thread animation gracefully and reset_message
74
10
324
def auto_message ( self , args ) : if any ( args ) and callable ( args [ 0 ] ) and not self . message : return args [ 0 ] . __name__ elif not self . message : return self . default_message else : return self . message
Try guess the message by the args passed
58
8
325
def start ( self ) : self . streams . append ( sys . stdout ) sys . stdout = self . stream
Activate the TypingStream on stdout
25
9
326
def stop ( cls ) : if any ( cls . streams ) : sys . stdout = cls . streams . pop ( - 1 ) else : sys . stdout = sys . __stdout__
Change back the normal stdout after the end
44
9
327
def prolong ( self ) : D = self . __class__ collection = self . get_collection ( ) identity = self . Lock ( ) query = D . id == self query &= D . lock . instance == identity . instance query &= D . lock . time >= ( identity . time - identity . __period__ ) previous = collection . find_one_and_update ( query , { '$set' ...
Prolong the working duration of an already held lock . Attempting to prolong a lock not already owned will result in a Locked exception .
187
27
328
def release ( self , force = False ) : D = self . __class__ collection = self . get_collection ( ) identity = self . Lock ( ) query = D . id == self if not force : query &= D . lock . instance == identity . instance previous = collection . find_one_and_update ( query , { '$unset' : { ~ D . lock : True } } , { ~ D . loc...
Release an exclusive lock on this integration task . Unless forcing if we are not the current owners of the lock a Locked exception will be raised .
191
28
329
def write ( self , message , autoerase = True ) : super ( Animation , self ) . write ( message ) self . last_message = message if autoerase : time . sleep ( self . interval ) self . erase ( message )
Send something for stdout and erased after delay
51
9
330
def write ( self , message , flush = False ) : # this need be threadsafe because the concurrent spinning running on # the stderr with self . lock : self . paralell_stream . erase ( ) super ( Clean , self ) . write ( message , flush )
Write something on the default stream with a prefixed message
58
11
331
def write ( self , message , flush = True ) : if isinstance ( message , bytes ) : # pragma: no cover message = message . decode ( 'utf-8' ) for char in message : time . sleep ( self . delay * ( 4 if char == '\n' else 1 ) ) super ( Writting , self ) . write ( char , flush )
A Writting like write method delayed at each char
79
10
332
def _get_default_projection ( cls ) : projected = [ ] # The fields explicitly requested for inclusion. neutral = [ ] # Fields returning neutral (None) status. omitted = False # Have any fields been explicitly omitted? for name , field in cls . __fields__ . items ( ) : if field . project is None : neutral . append ( nam...
Construct the default projection document .
141
6
333
def adjust_attribute_sequence ( * fields ) : amount = None if fields and isinstance ( fields [ 0 ] , int ) : amount , fields = fields [ 0 ] , fields [ 1 : ] def adjust_inner ( cls ) : for field in fields : if field not in cls . __dict__ : # TODO: Copy the field definition. raise TypeError ( "Can only override sequence ...
Move marrow . schema fields around to control positional instantiation order .
216
13
334
def get_hashes ( path , exclude = None ) : out = { } for f in Path ( path ) . rglob ( '*' ) : if f . is_dir ( ) : # We want to watch files, not directories. continue if exclude and re . match ( exclude , f . as_posix ( ) ) : retox_log . debug ( "excluding '{}'" . format ( f . as_posix ( ) ) ) continue pytime = f . stat...
Get a dictionary of file paths and timestamps .
129
11
335
def request ( self , method , params = None , query_continue = None , files = None , auth = None , continuation = False ) : normal_params = _normalize_params ( params , query_continue ) if continuation : return self . _continuation ( method , params = normal_params , auth = auth , files = files ) else : return self . _...
Sends an HTTP request to the API .
96
9
336
def login ( self , username , password , login_token = None ) : if login_token is None : token_doc = self . post ( action = 'query' , meta = 'tokens' , type = 'login' ) login_token = token_doc [ 'query' ] [ 'tokens' ] [ 'logintoken' ] login_doc = self . post ( action = "clientlogin" , username = username , password = p...
Authenticate with the given credentials . If authentication is successful all further requests sent will be signed the authenticated user .
213
22
337
def continue_login ( self , login_token , * * params ) : login_params = { 'action' : "clientlogin" , 'logintoken' : login_token , 'logincontinue' : 1 } login_params . update ( params ) login_doc = self . post ( * * login_params ) if login_doc [ 'clientlogin' ] [ 'status' ] != 'PASS' : raise LoginError . from_doc ( logi...
Continues a login that requires an additional step . This is common for when login requires completing a captcha or supplying a two - factor authentication token .
120
29
338
def get ( self , query_continue = None , auth = None , continuation = False , * * params ) : return self . request ( 'GET' , params = params , auth = auth , query_continue = query_continue , continuation = continuation )
Makes an API request with the GET method
53
9
339
def post ( self , query_continue = None , upload_file = None , auth = None , continuation = False , * * params ) : if upload_file is not None : files = { 'file' : upload_file } else : files = None return self . request ( 'POST' , params = params , auth = auth , query_continue = query_continue , files = files , continua...
Makes an API request with the POST method
87
9
340
def promote ( self , cls , update = False , preserve = True ) : if not issubclass ( cls , self . __class__ ) : raise TypeError ( "Must promote to a subclass of " + self . __class__ . __name__ ) return self . _as ( cls , update , preserve )
Transform this record into an instance of a more specialized subclass .
69
12
341
def cut_levels ( nodes , start_level ) : final = [ ] removed = [ ] for node in nodes : if not hasattr ( node , 'level' ) : # remove and ignore nodes that don't have level information remove ( node , removed ) continue if node . attr . get ( 'soft_root' , False ) : # remove and ignore nodes that are behind a node marked...
cutting nodes away from menus
239
5
342
def from_mongo ( cls , data , expired = False , * * kw ) : value = super ( Expires , cls ) . from_mongo ( data , * * kw ) if not expired and value . is_expired : return None return value
In the event a value that has technically already expired is loaded swap it for None .
59
17
343
def S ( Document , * fields ) : result = [ ] for field in fields : if isinstance ( field , tuple ) : # Unpack existing tuple. field , direction = field result . append ( ( field , direction ) ) continue direction = ASCENDING if not field . startswith ( '__' ) : field = field . replace ( '__' , '.' ) if field [ 0 ] == '...
Generate a MongoDB sort order list using the Django ORM style .
151
15
344
def run ( self ) : self . _assure_output_dir ( self . output ) companies = self . read ( ) print '%s CNPJs found' % len ( companies ) pbar = ProgressBar ( widgets = [ Counter ( ) , ' ' , Percentage ( ) , ' ' , Bar ( ) , ' ' , Timer ( ) ] , maxval = len ( companies ) ) . start ( ) resolved = 0 runner = Runner ( companie...
Reads data from CNPJ list and write results to output directory .
161
15
345
def read ( self ) : companies = [ ] with open ( self . file ) as f : reader = unicodecsv . reader ( f ) for line in reader : if len ( line ) >= 1 : cnpj = self . format ( line [ 0 ] ) if self . valid ( cnpj ) : companies . append ( cnpj ) return companies
Reads data from the CSV file .
77
8
346
def write ( self , data ) : cnpj , data = data path = os . path . join ( self . output , '%s.json' % cnpj ) with open ( path , 'w' ) as f : json . dump ( data , f , encoding = 'utf-8' )
Writes json data to the output directory .
66
9
347
def valid ( self , cnpj ) : if len ( cnpj ) != 14 : return False tam = 12 nums = cnpj [ : tam ] digs = cnpj [ tam : ] tot = 0 pos = tam - 7 for i in range ( tam , 0 , - 1 ) : tot = tot + int ( nums [ tam - i ] ) * pos pos = pos - 1 if pos < 2 : pos = 9 res = 0 if tot % 11 < 2 else 11 - ( tot % 11 ) if res != int ( digs...
Check if a CNPJ is valid .
221
9
348
def get_default_config_filename ( ) : global _CONFIG_FN if _CONFIG_FN is not None : return _CONFIG_FN with _CONFIG_FN_LOCK : if _CONFIG_FN is not None : return _CONFIG_FN if 'PEYOTL_CONFIG_FILE' in os . environ : cfn = os . path . abspath ( os . environ [ 'PEYOTL_CONFIG_FILE' ] ) else : cfn = os . path . expanduser ( "...
Returns the configuration filepath .
353
6
349
def get_raw_default_config_and_read_file_list ( ) : global _CONFIG , _READ_DEFAULT_FILES if _CONFIG is not None : return _CONFIG , _READ_DEFAULT_FILES with _CONFIG_LOCK : if _CONFIG is not None : return _CONFIG , _READ_DEFAULT_FILES try : # noinspection PyCompatibility from ConfigParser import SafeConfigParser except I...
Returns a ConfigParser object and a list of filenames that were parsed to initialize it
193
18
350
def get_config_object ( ) : global _DEFAULT_CONFIG_WRAPPER if _DEFAULT_CONFIG_WRAPPER is not None : return _DEFAULT_CONFIG_WRAPPER with _DEFAULT_CONFIG_WRAPPER_LOCK : if _DEFAULT_CONFIG_WRAPPER is not None : return _DEFAULT_CONFIG_WRAPPER _DEFAULT_CONFIG_WRAPPER = ConfigWrapper ( ) return _DEFAULT_CONFIG_WRAPPER
Thread - safe accessor for the immutable default ConfigWrapper object
113
13
351
def get_from_config_setting_cascade ( self , sec_param_list , default = None , warn_on_none_level = logging . WARN ) : for section , param in sec_param_list : r = self . get_config_setting ( section , param , default = None , warn_on_none_level = None ) if r is not None : return r section , param = sec_param_list [ - 1...
return the first non - None setting from a series where each element in sec_param_list is a section param pair suitable for a get_config_setting call .
130
34
352
def parse ( input_ : Union [ str , FileStream ] , source : str ) -> Optional [ str ] : # Step 1: Tokenize the input stream error_listener = ParseErrorListener ( ) if not isinstance ( input_ , FileStream ) : input_ = InputStream ( input_ ) lexer = jsgLexer ( input_ ) lexer . addErrorListener ( error_listener ) tokens = ...
Parse the text in infile and save the results in outfile
236
14
353
def fetch ( self , request , callback = None , raise_error = True , * * kwargs ) : # accepts request as string then convert it to HTTPRequest if isinstance ( request , str ) : request = HTTPRequest ( request , * * kwargs ) try : # The first request calls tornado-client ignoring the # possible exception, in case of 401 ...
Executes a request by AsyncHTTPClient asynchronously returning an tornado . HTTPResponse .
224
22
354
def validate_config ( key : str , config : dict ) -> None : try : jsonschema . validate ( config , CONFIG_JSON_SCHEMA [ key ] ) except jsonschema . ValidationError as x_validation : raise JSONValidation ( 'JSON validation error on {} configuration: {}' . format ( key , x_validation . message ) ) except jsonschema . Sch...
Call jsonschema validation to raise JSONValidation on non - compliance or silently pass .
124
19
355
def __make_id ( receiver ) : if __is_bound_method ( receiver ) : return ( id ( receiver . __func__ ) , id ( receiver . __self__ ) ) return id ( receiver )
Generate an identifier for a callable signal receiver .
45
11
356
def __purge ( ) : global __receivers newreceivers = collections . defaultdict ( list ) for signal , receivers in six . iteritems ( __receivers ) : alive = [ x for x in receivers if not __is_dead ( x ) ] newreceivers [ signal ] = alive __receivers = newreceivers
Remove all dead signal receivers from the global receivers collection .
76
11
357
def __live_receivers ( signal ) : with __lock : __purge ( ) receivers = [ funcref ( ) for funcref in __receivers [ signal ] ] return receivers
Return all signal handlers that are currently still alive for the input signal .
41
14
358
def __is_bound_method ( method ) : if not ( hasattr ( method , "__func__" ) and hasattr ( method , "__self__" ) ) : return False # Bound methods have a __self__ attribute pointing to the owner instance return six . get_method_self ( method ) is not None
Return True if the method is a bound method ( attached to an class instance .
69
16
359
def disconnect ( signal , receiver ) : inputkey = __make_id ( receiver ) with __lock : __purge ( ) receivers = __receivers . get ( signal ) for idx in six . moves . range ( len ( receivers ) ) : connected = receivers [ idx ] ( ) if inputkey != __make_id ( connected ) : continue del receivers [ idx ] return True # recei...
Disconnect the receiver func from the signal identified by signal_id .
91
14
360
def emit ( signal , * args , * * kwargs ) : if signal not in __receivers : return receivers = __live_receivers ( signal ) for func in receivers : func ( * args , * * kwargs )
Emit a signal by serially calling each registered signal receiver for the signal .
52
16
361
def arrayuniqify ( X , retainorder = False ) : s = X . argsort ( ) X = X [ s ] D = np . append ( [ True ] , X [ 1 : ] != X [ : - 1 ] ) if retainorder : DD = np . append ( D . nonzero ( ) [ 0 ] , len ( X ) ) ind = [ min ( s [ x : DD [ i + 1 ] ] ) for ( i , x ) in enumerate ( DD [ : - 1 ] ) ] ind . sort ( ) return ind el...
Very fast uniqify routine for numpy arrays .
126
11
362
def equalspairs ( X , Y ) : T = Y . copy ( ) R = ( T [ 1 : ] != T [ : - 1 ] ) . nonzero ( ) [ 0 ] R = np . append ( R , np . array ( [ len ( T ) - 1 ] ) ) M = R [ R . searchsorted ( range ( len ( T ) ) ) ] D = T . searchsorted ( X ) T = np . append ( T , np . array ( [ 0 ] ) ) M = np . append ( M , np . array ( [ 0 ] )...
Indices of elements in a sorted numpy array equal to those in another .
163
16
363
def isin ( X , Y ) : if len ( Y ) > 0 : T = Y . copy ( ) T . sort ( ) D = T . searchsorted ( X ) T = np . append ( T , np . array ( [ 0 ] ) ) W = ( T [ D ] == X ) if isinstance ( W , bool ) : return np . zeros ( ( len ( X ) , ) , bool ) else : return ( T [ D ] == X ) else : return np . zeros ( ( len ( X ) , ) , bool )
Indices of elements in a numpy array that appear in another .
120
14
364
def arraydifference ( X , Y ) : if len ( Y ) > 0 : Z = isin ( X , Y ) return X [ np . invert ( Z ) ] else : return X
Elements of a numpy array that do not appear in another .
42
14
365
def arraymax ( X , Y ) : Z = np . zeros ( ( len ( X ) , ) , int ) A = X <= Y B = Y < X Z [ A ] = Y [ A ] Z [ B ] = X [ B ] return Z
Fast vectorized max function for element - wise comparison of two numpy arrays .
56
16
366
async def _seed2did ( self ) -> str : rv = None dids_with_meta = json . loads ( await did . list_my_dids_with_meta ( self . handle ) ) # list if dids_with_meta : for did_with_meta in dids_with_meta : # dict if 'metadata' in did_with_meta : try : meta = json . loads ( did_with_meta [ 'metadata' ] ) if isinstance ( meta ...
Derive DID as per indy - sdk from seed .
244
13
367
async def remove ( self ) -> None : LOGGER . debug ( 'Wallet.remove >>>' ) try : LOGGER . info ( 'Removing wallet: %s' , self . name ) await wallet . delete_wallet ( json . dumps ( self . cfg ) , json . dumps ( self . access_creds ) ) except IndyError as x_indy : LOGGER . info ( 'Abstaining from wallet removal; indy-sd...
Remove serialized wallet if it exists .
127
8
368
def loadSV ( fname , shape = None , titles = None , aligned = False , byteorder = None , renamer = None , * * kwargs ) : [ columns , metadata ] = loadSVcols ( fname , * * kwargs ) if 'names' in metadata . keys ( ) : names = metadata [ 'names' ] else : names = None if 'formats' in metadata . keys ( ) : formats = metadat...
Load a delimited text file to a numpy record array .
303
13
369
def loadSVrecs ( fname , uselines = None , skiprows = 0 , linefixer = None , delimiter_regex = None , verbosity = DEFAULT_VERBOSITY , * * metadata ) : if delimiter_regex and isinstance ( delimiter_regex , types . StringType ) : import re delimiter_regex = re . compile ( delimiter_regex ) [ metadata , inferedlines , WHO...
Load a separated value text file to a list of lists of strings of records .
500
16
370
def parsetypes ( dtype ) : return [ dtype [ i ] . name . strip ( '1234567890' ) . rstrip ( 'ing' ) for i in range ( len ( dtype ) ) ]
Parse the types from a structured numpy dtype object .
48
13
371
def thresholdcoloring ( coloring , names ) : for key in coloring . keys ( ) : if len ( [ k for k in coloring [ key ] if k in names ] ) == 0 : coloring . pop ( key ) else : coloring [ key ] = utils . uniqify ( [ k for k in coloring [ key ] if k in names ] ) return coloring
Threshold a coloring dictionary for a given list of column names .
77
13
372
def makedir ( dir_name ) : if os . path . exists ( dir_name ) : delete ( dir_name ) os . mkdir ( dir_name )
Strong directory maker .
37
4
373
def pass_community ( f ) : @ wraps ( f ) def inner ( community_id , * args , * * kwargs ) : c = Community . get ( community_id ) if c is None : abort ( 404 ) return f ( c , * args , * * kwargs ) return inner
Decorator to pass community .
65
7
374
def permission_required ( action ) : def decorator ( f ) : @ wraps ( f ) def inner ( community , * args , * * kwargs ) : permission = current_permission_factory ( community , action = action ) if not permission . can ( ) : abort ( 403 ) return f ( community , * args , * * kwargs ) return inner return decorator
Decorator to require permission .
82
7
375
def format_item ( item , template , name = 'item' ) : ctx = { name : item } return render_template_to_string ( template , * * ctx )
Render a template to a string with the provided item in context .
40
13
376
def new ( ) : form = CommunityForm ( formdata = request . values ) ctx = mycommunities_ctx ( ) ctx . update ( { 'form' : form , 'is_new' : True , 'community' : None , } ) if form . validate_on_submit ( ) : data = copy . deepcopy ( form . data ) community_id = data . pop ( 'identifier' ) del data [ 'logo' ] community = ...
Create a new community .
295
5
377
def edit ( community ) : form = EditCommunityForm ( formdata = request . values , obj = community ) deleteform = DeleteCommunityForm ( ) ctx = mycommunities_ctx ( ) ctx . update ( { 'form' : form , 'is_new' : False , 'community' : community , 'deleteform' : deleteform , } ) if form . validate_on_submit ( ) : for field ...
Create or edit a community .
270
6
378
def delete ( community ) : deleteform = DeleteCommunityForm ( formdata = request . values ) ctx = mycommunities_ctx ( ) ctx . update ( { 'deleteform' : deleteform , 'is_new' : False , 'community' : community , } ) if deleteform . validate_on_submit ( ) : community . delete ( ) db . session . commit ( ) flash ( "Communi...
Delete a community .
148
4
379
def ot_find_tree ( arg_dict , exact = True , verbose = False , oti_wrapper = None ) : if oti_wrapper is None : from peyotl . sugar import oti oti_wrapper = oti return oti_wrapper . find_trees ( arg_dict , exact = exact , verbose = verbose , wrap_response = True )
Uses a peyotl wrapper around an Open Tree web service to get a list of trees including values value for a given property to be searched on porperty .
84
34
380
def is_iterable ( etype ) -> bool : return type ( etype ) is GenericMeta and issubclass ( etype . __extra__ , Iterable )
Determine whether etype is a List or other iterable
36
13
381
def main ( argv ) : import argparse description = 'Uses Open Tree of Life web services to the MRCA for a set of OTT IDs.' parser = argparse . ArgumentParser ( prog = 'ot-tree-of-life-mrca' , description = description ) parser . add_argument ( 'ottid' , nargs = '*' , type = int , help = 'OTT IDs' ) parser . add_argument...
This function sets up a command - line option parser and then calls fetch_and_write_mrca to do all of the real work .
352
30
382
async def send_schema ( self , schema_data_json : str ) -> str : LOGGER . debug ( 'Origin.send_schema >>> schema_data_json: %s' , schema_data_json ) schema_data = json . loads ( schema_data_json ) s_key = schema_key ( schema_id ( self . did , schema_data [ 'name' ] , schema_data [ 'version' ] ) ) with SCHEMA_CACHE . lo...
Send schema to ledger then retrieve it as written to the ledger and return it . If schema already exists on ledger log error and return schema .
438
28
383
def _locked_refresh_doc_ids ( self ) : d = { } for s in self . _shards : for k in s . doc_index . keys ( ) : if k in d : raise KeyError ( 'doc "{i}" found in multiple repos' . format ( i = k ) ) d [ k ] = s self . _doc2shard_map = d
Assumes that the caller has the _index_lock !
85
12
384
def push_doc_to_remote ( self , remote_name , doc_id = None ) : if doc_id is None : ret = True # @TODO should spawn a thread of each shard... for shard in self . _shards : if not shard . push_to_remote ( remote_name ) : ret = False return ret shard = self . get_shard ( doc_id ) return shard . push_to_remote ( remote_na...
This will push the master branch to the remote named remote_name using the mirroring strategy to cut down on locking of the working repo .
105
28
385
def iter_doc_filepaths ( self , * * kwargs ) : for shard in self . _shards : for doc_id , blob in shard . iter_doc_filepaths ( * * kwargs ) : yield doc_id , blob
Generator that iterates over all detected documents . and returns the filesystem path to each doc . Order is by shard but arbitrary within shards .
59
29
386
def data ( self ) : d = super ( CommunityForm , self ) . data d . pop ( 'csrf_token' , None ) return d
Form data .
32
3
387
def validate_identifier ( self , field ) : if field . data : field . data = field . data . lower ( ) if Community . get ( field . data , with_deleted = True ) : raise validators . ValidationError ( _ ( 'The identifier already exists. ' 'Please choose a different one.' ) )
Validate field identifier .
70
5
388
def read_filepath ( filepath , encoding = 'utf-8' ) : with codecs . open ( filepath , 'r' , encoding = encoding ) as fo : return fo . read ( )
Returns the text content of filepath
44
7
389
def download ( url , encoding = 'utf-8' ) : import requests response = requests . get ( url ) response . encoding = encoding return response . text
Returns the text fetched via http GET from URL read as encoding
33
13
390
def pretty_dict_str ( d , indent = 2 ) : b = StringIO ( ) write_pretty_dict_str ( b , d , indent = indent ) return b . getvalue ( )
shows JSON indented representation of d
43
7
391
def write_pretty_dict_str ( out , obj , indent = 2 ) : json . dump ( obj , out , indent = indent , sort_keys = True , separators = ( ',' , ': ' ) , ensure_ascii = False , encoding = "utf-8" )
writes JSON indented representation of obj to out
64
10
392
def community_responsify ( schema_class , mimetype ) : def view ( data , code = 200 , headers = None , links_item_factory = None , page = None , urlkwargs = None , links_pagination_factory = None ) : """Generate the response object.""" if isinstance ( data , Community ) : last_modified = data . updated response_data = ...
Create a community response serializer .
278
7
393
def from_error ( exc_info , json_encoder , debug_url = None ) : exc = exc_info [ 1 ] data = exc . __dict__ . copy ( ) for key , value in data . items ( ) : try : json_encoder . encode ( value ) except TypeError : data [ key ] = repr ( value ) data [ "traceback" ] = "" . join ( traceback . format_exception ( * exc_info ...
Wraps another Exception in an InternalError .
127
9
394
def contains ( self , index : Union [ SchemaKey , int , str ] ) -> bool : LOGGER . debug ( 'SchemaCache.contains >>> index: %s' , index ) rv = None if isinstance ( index , SchemaKey ) : rv = ( index in self . _schema_key2schema ) elif isinstance ( index , int ) or ( isinstance ( index , str ) and ':2:' not in index ) :...
Return whether the cache contains a schema for the input key sequence number or schema identifier .
185
17
395
def cull ( self , delta : bool ) -> None : LOGGER . debug ( 'RevoCacheEntry.cull >>> delta: %s' , delta ) rr_frames = self . rr_delta_frames if delta else self . rr_state_frames mark = 4096 ** 0.5 # max rev reg size = 4096; heuristic: hover max around sqrt(4096) = 64 if len ( rr_frames ) > int ( mark * 1.25 ) : rr_fram...
Cull cache entry frame list to size favouring most recent query time .
226
15
396
def dflt_interval ( self , cd_id : str ) -> ( int , int ) : LOGGER . debug ( 'RevocationCache.dflt_interval >>>' ) fro = None to = None for rr_id in self : if cd_id != rev_reg_id2cred_def_id ( rr_id ) : continue entry = self [ rr_id ] if entry . rr_delta_frames : to = max ( entry . rr_delta_frames , key = lambda f : f ...
Return default non - revocation interval from latest to times on delta frames of revocation cache entries on indices stemming from input cred def id .
244
26
397
def parse ( base_dir : str , timestamp : int = None ) -> int : LOGGER . debug ( 'parse >>> base_dir: %s, timestamp: %s' , base_dir , timestamp ) if not isdir ( base_dir ) : LOGGER . info ( 'No cache archives available: not feeding cache' ) LOGGER . debug ( 'parse <<< None' ) return None if not timestamp : timestamps = ...
Parse and update from archived cache files . Only accept new content ; do not overwrite any existing cache content .
769
22
398
def detect_nexson_version ( blob ) : n = get_nexml_el ( blob ) assert isinstance ( n , dict ) return n . get ( '@nexml2json' , BADGER_FISH_NEXSON_VERSION )
Returns the nexml2json attribute or the default code for badgerfish
55
15
399
def _add_value_to_dict_bf ( d , k , v ) : prev = d . get ( k ) if prev is None : d [ k ] = v elif isinstance ( prev , list ) : if isinstance ( v , list ) : prev . extend ( v ) else : prev . append ( v ) else : if isinstance ( v , list ) : x = [ prev ] x . extend ( v ) d [ k ] = x else : d [ k ] = [ prev , v ]
Adds the k - > v mapping to d but if a previous element exists it changes the value of for the key to list .
111
26