idx int64 0 63k | question stringlengths 53 5.28k | target stringlengths 5 805 |
|---|---|---|
10,600 | def setUser ( self , * args , ** kwargs ) : try : user = self . mambuuserclass ( entid = self [ 'assignedUserKey' ] , * args , ** kwargs ) except KeyError as kerr : err = MambuError ( "La cuenta %s no tiene asignado un usuario" % self [ 'id' ] ) err . noUser = True raise err except AttributeError as ae : from . mambuuser import MambuUser self . mambuuserclass = MambuUser try : user = self . mambuuserclass ( entid = self [ 'assignedUserKey' ] , * args , ** kwargs ) except KeyError as kerr : err = MambuError ( "La cuenta %s no tiene asignado un usuario" % self [ 'id' ] ) err . noUser = True raise err self [ 'user' ] = user return 1 | Adds the user for this loan to a user field . |
10,601 | def setProduct ( self , cache = False , * args , ** kwargs ) : if cache : try : prods = self . allmambuproductsclass ( * args , ** kwargs ) except AttributeError as ae : from . mambuproduct import AllMambuProducts self . allmambuproductsclass = AllMambuProducts prods = self . allmambuproductsclass ( * args , ** kwargs ) for prod in prods : if prod [ 'encodedKey' ] == self [ 'productTypeKey' ] : self [ 'product' ] = prod try : prods . noinit except AttributeError : return 1 return 0 try : product = self . mambuproductclass ( entid = self [ 'productTypeKey' ] , * args , ** kwargs ) except AttributeError as ae : from . mambuproduct import MambuProduct self . mambuproductclass = MambuProduct product = self . mambuproductclass ( entid = self [ 'productTypeKey' ] , * args , ** kwargs ) self [ 'product' ] = product return 1 | Adds the product for this loan to a product field . |
10,602 | def getClientDetails ( self , * args , ** kwargs ) : loannames = [ ] holder = kwargs [ 'holder' ] for client in holder [ 'clients' ] : loannames . append ( { 'id' : client [ 'id' ] , 'name' : client [ 'name' ] , 'client' : client , 'amount' : self [ 'loanAmount' ] } ) return loannames | Gets the loan details for every client holder of the account . |
10,603 | def get_fields_for_keyword ( self , keyword , mode = 'a' ) : field = self . keyword_to_fields . get ( keyword , keyword ) if isinstance ( field , dict ) : return field [ mode ] elif isinstance ( field , ( list , tuple ) ) : return field return [ field ] | Convert keyword to fields . |
10,604 | def merge_dict ( a , b , path = None ) : if not path : path = [ ] for key in b : if key in a : if isinstance ( a [ key ] , dict ) and isinstance ( b [ key ] , dict ) : merge_dict ( a [ key ] , b [ key ] , path + [ str ( key ) ] ) else : continue else : a [ key ] = b [ key ] return a | Merge dict b into a |
10,605 | def make_date ( obj : Union [ date , datetime , Text ] , timezone : tzinfo = None ) : if isinstance ( obj , datetime ) : if hasattr ( obj , 'astimezone' ) and timezone : obj = obj . astimezone ( timezone ) return obj . date ( ) elif isinstance ( obj , date ) : return obj elif isinstance ( obj , str ) : return make_date ( parse_date ( obj ) , timezone ) | A flexible method to get a date object . |
10,606 | def format_date ( self , value , format_ ) : date_ = make_date ( value ) return dates . format_date ( date_ , format_ , locale = self . lang ) | Format the date using Babel |
10,607 | def format_datetime ( self , value , format_ ) : date_ = make_datetime ( value ) return dates . format_datetime ( date_ , format_ , locale = self . lang ) | Format the datetime using Babel |
10,608 | def format_field ( self , value , spec ) : if spec . startswith ( 'date:' ) : _ , format_ = spec . split ( ':' , 1 ) return self . format_date ( value , format_ ) elif spec . startswith ( 'datetime:' ) : _ , format_ = spec . split ( ':' , 1 ) return self . format_datetime ( value , format_ ) elif spec == 'number' : return self . format_number ( value ) else : return super ( I18nFormatter , self ) . format_field ( value , spec ) | Provide the additional formatters for localization . |
10,609 | def _decode ( cls , value ) : value = cls . _DEC_RE . sub ( lambda x : '%c' % int ( x . group ( 1 ) , 16 ) , value ) return json . loads ( value ) | Decode the given value reverting % - encoded groups . |
10,610 | def decode ( cls , key ) : prefix , sep , param_str = key . partition ( ':' ) if sep != ':' or prefix not in cls . _prefix_to_version : raise ValueError ( "%r is not a bucket key" % key ) version = cls . _prefix_to_version [ prefix ] parts = param_str . split ( '/' ) uuid = parts . pop ( 0 ) params = { } for part in parts : name , sep , value = part . partition ( '=' ) if sep != '=' : raise ValueError ( "Cannot interpret parameter expression %r" % part ) params [ name ] = cls . _decode ( value ) return cls ( uuid , params , version = version ) | Decode a bucket key into a BucketKey instance . |
10,611 | def need_summary ( self , now , max_updates , max_age ) : if self . summarized is True and self . last_summarize_ts + max_age <= now : return True return self . summarized is False and self . updates >= max_updates | Helper method to determine if a summarize record should be added . |
10,612 | def dehydrate ( self ) : result = { } for attr in self . attrs : result [ attr ] = getattr ( self , attr ) return result | Return a dict representing this bucket . |
10,613 | def delay ( self , params , now = None ) : if now is None : now = time . time ( ) if not self . last : self . last = now elif now < self . last : now = self . last leaked = now - self . last self . last = now self . level = max ( self . level - leaked , 0 ) difference = self . level + self . limit . cost - self . limit . unit_value if difference >= self . eps : self . next = now + difference return difference self . level += self . limit . cost self . next = now return None | Determine delay until next request . |
10,614 | def messages ( self ) : return int ( math . floor ( ( ( self . limit . unit_value - self . level ) / self . limit . unit_value ) * self . limit . value ) ) | Return remaining messages before limiting . |
10,615 | def dehydrate ( self ) : result = dict ( limit_class = self . _limit_full_name ) for attr in self . attrs : result [ attr ] = getattr ( self , attr ) return result | Return a dict representing this limit . |
10,616 | def load ( self , key ) : if isinstance ( key , basestring ) : key = BucketKey . decode ( key ) if key . uuid != self . uuid : raise ValueError ( "%s is not a bucket corresponding to this limit" % key ) if key . version == 1 : raw = self . db . get ( str ( key ) ) if raw is None : return self . bucket_class ( self . db , self , str ( key ) ) return self . bucket_class . hydrate ( self . db , msgpack . loads ( raw ) , self , str ( key ) ) records = self . db . lrange ( str ( key ) , 0 , - 1 ) loader = BucketLoader ( self . bucket_class , self . db , self , str ( key ) , records ) return loader . bucket | Given a bucket key load the corresponding bucket . |
10,617 | def decode ( self , key ) : key = BucketKey . decode ( key ) if key . uuid != self . uuid : raise ValueError ( "%s is not a bucket corresponding to this limit" % key ) return key . params | Given a bucket key compute the parameters used to compute that key . |
10,618 | def _filter ( self , environ , params ) : if self . queries : if 'QUERY_STRING' not in environ : return False available = set ( qstr . partition ( '=' ) [ 0 ] for qstr in environ [ 'QUERY_STRING' ] . split ( '&' ) ) required = set ( self . queries ) if not required . issubset ( available ) : return False unused = { } for key , value in params . items ( ) : if key not in self . use : unused [ key ] = value for key in unused : del params [ key ] try : additional = self . filter ( environ , params , unused ) or { } except DeferLimit : return False key = self . key ( params ) params . update ( unused ) params . update ( additional ) now = time . time ( ) self . db . expire ( key , 60 ) update_uuid = str ( uuid . uuid4 ( ) ) update = { 'uuid' : update_uuid , 'update' : { 'params' : params , 'time' : now , } , } self . db . rpush ( key , msgpack . dumps ( update ) ) records = self . db . lrange ( key , 0 , - 1 ) loader = BucketLoader ( self . bucket_class , self . db , self , key , records ) if 'turnstile.conf' in environ : config = environ [ 'turnstile.conf' ] [ 'compactor' ] try : max_updates = int ( config [ 'max_updates' ] ) except ( KeyError , ValueError ) : max_updates = None try : max_age = int ( config [ 'max_age' ] ) except ( KeyError , ValueError ) : max_age = 600 if max_updates and loader . need_summary ( now , max_updates , max_age ) : summarize = dict ( summarize = now , uuid = str ( uuid . uuid4 ( ) ) ) self . db . rpush ( key , msgpack . dumps ( summarize ) ) compactor_key = config . get ( 'compactor_key' , 'compactor' ) self . db . zadd ( compactor_key , int ( math . ceil ( now ) ) , key ) self . db . expireat ( key , loader . bucket . expire ) if loader . delay is not None : environ . setdefault ( 'turnstile.delay' , [ ] ) environ [ 'turnstile.delay' ] . append ( ( loader . delay , self , loader . bucket ) ) set_name = environ . get ( 'turnstile.bucket_set' ) if set_name : self . db . zadd ( set_name , loader . bucket . expire , key ) return not self . continue_scan | Performs final filtering of the request to determine if this limit applies . Returns False if the limit does not apply or if the call should not be limited or True to apply the limit . |
10,619 | def format ( self , status , headers , environ , bucket , delay ) : entity = ( "This request was rate-limited. " "Please retry your request after %s." % time . strftime ( "%Y-%m-%dT%H:%M:%SZ" , time . gmtime ( bucket . next ) ) ) headers [ 'Content-Type' ] = 'text/plain' return status , entity | Formats a response entity . Returns a tuple of the desired status code and the formatted entity . The default status code is passed in as is a dictionary of headers . |
10,620 | def drop_prefix ( strings ) : strings_without_extensions = [ s . split ( "." , 2 ) [ 0 ] for s in strings ] if len ( strings_without_extensions ) == 1 : return [ os . path . basename ( strings_without_extensions [ 0 ] ) ] prefix_len = len ( os . path . commonprefix ( strings_without_extensions ) ) result = [ string [ prefix_len : ] for string in strings_without_extensions ] if len ( set ( result ) ) != len ( strings ) : return strings return result | Removes common prefix from a collection of strings |
10,621 | def count ( self ) : "Return how many nodes this contains, including self." if self . _nodes is None : return 1 return sum ( i . count ( ) for i in self . _nodes ) | Return how many nodes this contains including self . |
10,622 | def app_size ( self ) : "Return the total apparent size, including children." if self . _nodes is None : return self . _app_size return sum ( i . app_size ( ) for i in self . _nodes ) | Return the total apparent size including children . |
10,623 | def use_size ( self ) : "Return the total used size, including children." if self . _nodes is None : return self . _use_size return sum ( i . use_size ( ) for i in self . _nodes ) | Return the total used size including children . |
10,624 | def _prune_all_if_small ( self , small_size , a_or_u ) : "Return True and delete children if small enough." if self . _nodes is None : return True total_size = ( self . app_size ( ) if a_or_u else self . use_size ( ) ) if total_size < small_size : if a_or_u : self . _set_size ( total_size , self . use_size ( ) ) else : self . _set_size ( self . app_size ( ) , total_size ) return True return False | Return True and delete children if small enough . |
10,625 | def _prune_some_if_small ( self , small_size , a_or_u ) : "Merge some nodes in the directory, whilst keeping others." prev_app_size = self . app_size ( ) prev_use_size = self . use_size ( ) keep_nodes = [ ] prune_app_size = 0 prune_use_size = 0 for node in self . _nodes : node_size = node . app_size ( ) if a_or_u else node . use_size ( ) if node_size < small_size : if a_or_u : prune_app_size += node_size prune_use_size += node . use_size ( ) else : prune_app_size += node . app_size ( ) prune_use_size += node_size else : keep_nodes . append ( node ) if len ( keep_nodes ) == 1 and keep_nodes [ - 1 ] . _isdir is None : prune_app_size += keep_nodes [ - 1 ] . _app_size prune_use_size += keep_nodes [ - 1 ] . _use_size keep_nodes = [ ] if prune_app_size : if not keep_nodes : keep_nodes = None assert self . _isdir and self . _nodes is not None self . _set_size ( prune_app_size , prune_use_size ) elif keep_nodes and keep_nodes [ - 1 ] . _isdir is None : keep_nodes [ - 1 ] . _add_size ( prune_app_size , prune_use_size ) else : keep_nodes . append ( DuNode . new_leftovers ( self . _path , prune_app_size , prune_use_size ) ) self . _nodes = keep_nodes assert prev_app_size == self . app_size ( ) , ( prev_app_size , self . app_size ( ) ) assert prev_use_size == self . use_size ( ) , ( prev_use_size , self . use_size ( ) ) | Merge some nodes in the directory whilst keeping others . |
10,626 | def merge_upwards_if_smaller_than ( self , small_size , a_or_u ) : prev_app_size = self . app_size ( ) prev_use_size = self . use_size ( ) small_nodes = self . _find_small_nodes ( small_size , ( ) , a_or_u ) for node , parents in small_nodes : if len ( parents ) >= 2 : tail = parents [ - 2 ] . _nodes [ - 1 ] if tail . _isdir is None : assert tail . _app_size is not None , tail tail . _add_size ( node . app_size ( ) , node . use_size ( ) ) parents [ - 1 ] . _nodes . remove ( node ) assert len ( parents [ - 1 ] . _nodes ) assert prev_app_size == self . app_size ( ) , ( prev_app_size , self . app_size ( ) ) assert prev_use_size == self . use_size ( ) , ( prev_use_size , self . use_size ( ) ) | After prune_if_smaller_than is run we may still have excess nodes . |
10,627 | def as_tree ( self ) : "Return the nodes as a list of lists." if self . _nodes is None : return [ self ] ret = [ self ] for node in self . _nodes : ret . append ( node . as_tree ( ) ) return ret | Return the nodes as a list of lists . |
10,628 | def _check_path ( self ) : "Immediately check if we can access path. Otherwise bail." if not path . isdir ( self . _path or '/' ) : raise OSError ( 'Path {!r} is not a directory' . format ( self . _path ) ) | Immediately check if we can access path . Otherwise bail . |
10,629 | def version ( command = 'dmenu' ) : args = [ command , '-v' ] try : proc = subprocess . Popen ( args , universal_newlines = True , stdout = subprocess . PIPE , stderr = subprocess . PIPE ) except OSError as err : raise DmenuCommandError ( args , err ) if proc . wait ( ) == 0 : return proc . stdout . read ( ) . rstrip ( '\n' ) raise DmenuCommandError ( args , proc . stderr . read ( ) ) | The dmenu command s version message . |
10,630 | def show ( items , command = 'dmenu' , bottom = None , fast = None , case_insensitive = None , lines = None , monitor = None , prompt = None , font = None , background = None , foreground = None , background_selected = None , foreground_selected = None ) : args = [ command ] if bottom : args . append ( '-b' ) if fast : args . append ( '-f' ) if case_insensitive : args . append ( '-i' ) if lines is not None : args . extend ( ( '-l' , str ( lines ) ) ) if monitor is not None : args . extend ( ( '-m' , str ( monitor ) ) ) if prompt is not None : args . extend ( ( '-p' , prompt ) ) if font is not None : args . extend ( ( '-fn' , font ) ) if background is not None : args . extend ( ( '-nb' , background ) ) if foreground is not None : args . extend ( ( '-nf' , foreground ) ) if background_selected is not None : args . extend ( ( '-sb' , background_selected ) ) if foreground_selected is not None : args . extend ( ( '-sf' , foreground_selected ) ) try : proc = subprocess . Popen ( args , universal_newlines = True , stdin = subprocess . PIPE , stdout = subprocess . PIPE , stderr = subprocess . PIPE ) except OSError as err : raise DmenuCommandError ( args , err ) with proc . stdin : for item in items : proc . stdin . write ( item ) proc . stdin . write ( '\n' ) if proc . wait ( ) == 0 : return proc . stdout . read ( ) . rstrip ( '\n' ) stderr = proc . stderr . read ( ) if stderr == '' : return None if re . match ( 'usage' , stderr , re . I ) : raise DmenuUsageError ( args , stderr ) raise DmenuCommandError ( args , stderr ) | Present a dmenu to the user . |
10,631 | def get_upregulated_genes_network ( self ) -> Graph : logger . info ( "In get_upregulated_genes_network()" ) deg_graph = self . graph . copy ( ) not_diff_expr = self . graph . vs ( up_regulated_eq = False ) deg_graph . delete_vertices ( not_diff_expr . indices ) deg_graph . delete_vertices ( deg_graph . vs . select ( _degree_eq = 0 ) ) return deg_graph | Get the graph of up - regulated genes . |
10,632 | def get_downregulated_genes_network ( self ) -> Graph : logger . info ( "In get_downregulated_genes_network()" ) deg_graph = self . graph . copy ( ) not_diff_expr = self . graph . vs ( down_regulated_eq = False ) deg_graph . delete_vertices ( not_diff_expr . indices ) deg_graph . delete_vertices ( deg_graph . vs . select ( _degree_eq = 0 ) ) return deg_graph | Get the graph of down - regulated genes . |
10,633 | def make_parser ( ) : parser = argparse . ArgumentParser ( description = 'BERNARD CLI utility' ) sp = parser . add_subparsers ( help = 'Sub-command' ) parser_run = sp . add_parser ( 'run' , help = 'Run the BERNARD server' ) parser_run . set_defaults ( action = 'run' ) parser_sheet = sp . add_parser ( 'sheet' , help = 'Import files from Google ' 'Sheets' ) parser_sheet . set_defaults ( action = 'sheet' ) parser_sheet . add_argument ( '--auth_host_name' , default = 'localhost' , help = 'Hostname when running a local web server.' ) parser_sheet . add_argument ( '--noauth_local_webserver' , action = 'store_true' , default = False , help = 'Do not run a local web server.' ) parser_sheet . add_argument ( '--auth_host_port' , default = [ 8080 , 8090 ] , type = int , nargs = '*' , help = 'Port web server should listen on.' ) parser_sheet . add_argument ( '--logging_level' , default = 'ERROR' , choices = [ 'DEBUG' , 'INFO' , 'WARNING' , 'ERROR' , 'CRITICAL' ] , help = 'Set the logging level of detail.' ) parser_sp = sp . add_parser ( 'start_project' , help = 'Starts a project' ) parser_sp . set_defaults ( action = 'start_project' ) parser_sp . add_argument ( 'project_name' , help = 'A snake-case name for your project' ) parser_sp . add_argument ( 'dir' , help = 'Directory to store the project' ) return parser | Generate the parser for all sub - commands |
10,634 | def main ( ) : parser = make_parser ( ) args = parser . parse_args ( ) if not hasattr ( args , 'action' ) : parser . print_help ( ) exit ( 1 ) if args . action == 'sheet' : from bernard . misc . sheet_sync import main as main_sheet main_sheet ( args ) elif args . action == 'run' : from bernard . cli import main as main_run main_run ( ) elif args . action == 'start_project' : from bernard . misc . start_project import main as main_sp main_sp ( args ) | Run the appropriate main function according to the output of the parser . |
10,635 | def load_dotenv ( dotenv_path , verbose = False ) : if not os . path . exists ( dotenv_path ) : if verbose : warnings . warn ( f"Not loading {dotenv_path}, it doesn't exist." ) return None for k , v in dotenv_values ( dotenv_path ) . items ( ) : os . environ . setdefault ( k , v ) return True | Read a . env file and load into os . environ . |
10,636 | def get_key ( dotenv_path , key_to_get , verbose = False ) : key_to_get = str ( key_to_get ) if not os . path . exists ( dotenv_path ) : if verbose : warnings . warn ( f"Can't read {dotenv_path}, it doesn't exist." ) return None dotenv_as_dict = dotenv_values ( dotenv_path ) if key_to_get in dotenv_as_dict : return dotenv_as_dict [ key_to_get ] else : if verbose : warnings . warn ( f"key {key_to_get} not found in {dotenv_path}." ) return None | Gets the value of a given key from the given . env |
10,637 | def _get_format ( value , quote_mode = 'always' ) : formats = { 'always' : '{key}="{value}"\n' , 'auto' : '{key}={value}\n' } if quote_mode not in formats . keys ( ) : return KeyError ( f'quote_mode {quote_mode} is invalid' ) _mode = quote_mode if quote_mode == 'auto' and ' ' in value : _mode = 'always' return formats . get ( _mode ) | Returns the quote format depending on the quote_mode . This determines if the key value will be quoted when written to the env file . |
10,638 | def find_dotenv ( filename = '.env' , raise_error_if_not_found = False , usecwd = False ) : if usecwd or '__file__' not in globals ( ) : path = os . getcwd ( ) else : frame_filename = sys . _getframe ( ) . f_back . f_code . co_filename path = os . path . dirname ( os . path . abspath ( frame_filename ) ) for dirname in _walk_to_root ( path ) : check_path = os . path . join ( dirname , filename ) if os . path . exists ( check_path ) : return check_path if raise_error_if_not_found : raise IOError ( 'File not found' ) return '' | Search in increasingly higher folders for the given file |
10,639 | def reducer ( * tokens ) : def wrapper ( func ) : if not hasattr ( func , 'reducers' ) : func . reducers = [ ] func . reducers . append ( list ( tokens ) ) return func return wrapper | Decorator for reduction methods . |
10,640 | def parse_rule ( rule : str , raise_error = False ) : parser = Parser ( raise_error ) return parser . parse ( rule ) | Parses policy to a tree of Check objects . |
10,641 | def _reduce ( self ) : for reduction , methname in self . reducers : token_num = len ( reduction ) if ( len ( self . tokens ) >= token_num and self . tokens [ - token_num : ] == reduction ) : meth = getattr ( self , methname ) results = meth ( * self . values [ - token_num : ] ) self . tokens [ - token_num : ] = [ r [ 0 ] for r in results ] self . values [ - token_num : ] = [ r [ 1 ] for r in results ] return self . _reduce ( ) | Perform a greedy reduction of token stream . |
10,642 | def _parse_check ( self , rule ) : for check_cls in ( checks . FalseCheck , checks . TrueCheck ) : check = check_cls ( ) if rule == str ( check ) : return check try : kind , match = rule . split ( ':' , 1 ) except Exception : if self . raise_error : raise InvalidRuleException ( rule ) else : LOG . exception ( 'Failed to understand rule %r' , rule ) return checks . FalseCheck ( ) if kind in checks . registered_checks : return checks . registered_checks [ kind ] ( kind , match ) elif None in checks . registered_checks : return checks . registered_checks [ None ] ( kind , match ) elif self . raise_error : raise InvalidRuleException ( rule ) else : LOG . error ( 'No handler for matches of kind %r' , kind ) return checks . FalseCheck ( ) | Parse a single base check rule into an appropriate Check object . |
10,643 | def _parse_tokenize ( self , rule ) : for token in self . _TOKENIZE_RE . split ( rule ) : if not token or token . isspace ( ) : continue clean = token . lstrip ( '(' ) for i in range ( len ( token ) - len ( clean ) ) : yield '(' , '(' if not clean : continue else : token = clean clean = token . rstrip ( ')' ) trail = len ( token ) - len ( clean ) lowered = clean . lower ( ) if lowered in ( 'and' , 'or' , 'not' ) : yield lowered , clean elif clean : if len ( token ) >= 2 and ( ( token [ 0 ] , token [ - 1 ] ) in [ ( '"' , '"' ) , ( "'" , "'" ) ] ) : yield 'string' , token [ 1 : - 1 ] else : yield 'check' , self . _parse_check ( clean ) for i in range ( trail ) : yield ')' , ')' | Tokenizer for the policy language . |
10,644 | def parse ( self , rule : str ) : if not rule : return checks . TrueCheck ( ) for token , value in self . _parse_tokenize ( rule ) : self . _shift ( token , value ) try : return self . result except ValueError : LOG . exception ( 'Failed to understand rule %r' , rule ) return checks . FalseCheck ( ) | Parses policy to tree . |
10,645 | def _mix_or_and_expr ( self , or_expr , _and , check ) : or_expr , check1 = or_expr . pop_check ( ) if isinstance ( check1 , checks . AndCheck ) : and_expr = check1 and_expr . add_check ( check ) else : and_expr = checks . AndCheck ( check1 , check ) return [ ( 'or_expr' , or_expr . add_check ( and_expr ) ) ] | Modify the case A or B and C |
10,646 | def build_valid_keywords_grammar ( keywords = None ) : from invenio_query_parser . parser import KeywordQuery , KeywordRule , NotKeywordValue , SimpleQuery , ValueQuery if keywords : KeywordRule . grammar = attr ( 'value' , re . compile ( r"(\d\d\d\w{{0,3}}|{0})\b" . format ( "|" . join ( keywords ) , re . I ) ) ) NotKeywordValue . grammar = attr ( 'value' , re . compile ( r'\b(?!\d\d\d\w{{0,3}}|{0}:)\S+\b:' . format ( ":|" . join ( keywords ) ) ) ) SimpleQuery . grammar = attr ( 'op' , [ NotKeywordValue , KeywordQuery , ValueQuery ] ) else : KeywordRule . grammar = attr ( 'value' , re . compile ( r"[\w\d]+(\.[\w\d]+)*" ) ) SimpleQuery . grammar = attr ( 'op' , [ KeywordQuery , ValueQuery ] ) | Update parser grammar to add a list of allowed keywords . |
10,647 | def render ( self , element ) : if not self . root_node : self . root_node = element render_func = getattr ( self , self . _cls_to_func_name ( element . __class__ ) , None ) if not render_func : render_func = self . render_children return render_func ( element ) | Renders the given element to string . |
10,648 | def render_children ( self , element ) : rendered = [ self . render ( child ) for child in element . children ] return '' . join ( rendered ) | Recursively renders child elements . Joins the rendered strings with no space in between . |
10,649 | def setGroups ( self , * args , ** kwargs ) : try : groups = self . mambugroupsclass ( creditOfficerUsername = self [ 'username' ] , * args , ** kwargs ) except AttributeError as ae : from . mambugroup import MambuGroups self . mambugroupsclass = MambuGroups groups = self . mambugroupsclass ( creditOfficerUsername = self [ 'username' ] , * args , ** kwargs ) self [ 'groups' ] = groups return 1 | Adds the groups assigned to this user to a groups field . |
10,650 | def setRoles ( self , * args , ** kwargs ) : try : role = self . mamburoleclass ( entid = self [ 'role' ] [ 'encodedKey' ] , * args , ** kwargs ) except KeyError : return 0 except AttributeError as ae : from . mamburoles import MambuRole self . mamburoleclass = MambuRole try : role = self . mamburoleclass ( entid = self [ 'role' ] [ 'encodedKey' ] , * args , ** kwargs ) except KeyError : return 0 self [ 'role' ] [ 'role' ] = role return 1 | Adds the role assigned to this user to a role field . |
10,651 | def create ( self , data , * args , ** kwargs ) : super ( MambuUser , self ) . create ( data ) self [ 'user' ] [ self . customFieldName ] = self [ 'customInformation' ] self . init ( attrs = self [ 'user' ] ) | Creates an user in Mambu |
10,652 | def write_attribute_adj_list ( self , path ) : att_mappings = self . get_attribute_mappings ( ) with open ( path , mode = "w" ) as file : for k , v in att_mappings . items ( ) : print ( "{} {}" . format ( k , " " . join ( str ( e ) for e in v ) ) , file = file ) | Write the bipartite attribute graph to a file . |
10,653 | def get_attribute_mappings ( self ) : att_ind_start = len ( self . graph . vs ) att_mappings = defaultdict ( list ) att_ind_end = self . _add_differential_expression_attributes ( att_ind_start , att_mappings ) if "associated_diseases" in self . graph . vs . attributes ( ) : self . _add_disease_association_attributes ( att_ind_end , att_mappings ) return att_mappings | Get a dictionary of mappings between vertices and enumerated attributes . |
10,654 | def _add_differential_expression_attributes ( self , att_ind_start , att_mappings ) : up_regulated_ind = self . graph . vs . select ( up_regulated_eq = True ) . indices down_regulated_ind = self . graph . vs . select ( down_regulated_eq = True ) . indices rest_ind = self . graph . vs . select ( diff_expressed_eq = False ) . indices self . _add_attribute_values ( att_ind_start + 1 , att_mappings , up_regulated_ind ) self . _add_attribute_values ( att_ind_start + 2 , att_mappings , down_regulated_ind ) self . _add_attribute_values ( att_ind_start + 3 , att_mappings , rest_ind ) return att_ind_start + 4 | Add differential expression information to the attribute mapping dictionary . |
10,655 | def _add_attribute_values ( self , value , att_mappings , indices ) : for i in indices : att_mappings [ i ] . append ( value ) | Add an attribute value to the given vertices . |
10,656 | def _add_disease_association_attributes ( self , att_ind_start , att_mappings ) : disease_mappings = self . get_disease_mappings ( att_ind_start ) for vertex in self . graph . vs : assoc_diseases = vertex [ "associated_diseases" ] if assoc_diseases is not None : assoc_disease_ids = [ disease_mappings [ disease ] for disease in assoc_diseases ] att_mappings [ vertex . index ] . extend ( assoc_disease_ids ) | Add disease association information to the attribute mapping dictionary . |
10,657 | def get_disease_mappings ( self , att_ind_start ) : all_disease_ids = self . get_all_unique_diseases ( ) disease_enum = enumerate ( all_disease_ids , start = att_ind_start ) disease_mappings = { } for num , dis in disease_enum : disease_mappings [ dis ] = num return disease_mappings | Get a dictionary of enumerations for diseases . |
10,658 | def get_all_unique_diseases ( self ) : all_disease_ids = self . graph . vs [ "associated_diseases" ] all_disease_ids = [ lst for lst in all_disease_ids if lst is not None ] all_disease_ids = list ( set ( [ id for sublist in all_disease_ids for id in sublist ] ) ) return all_disease_ids | Get all unique diseases that are known to the network . |
10,659 | def page_view ( url ) : def decorator ( func ) : @ wraps ( func ) async def wrapper ( self : BaseState , * args , ** kwargs ) : user_id = self . request . user . id try : user_lang = await self . request . user . get_locale ( ) except NotImplementedError : user_lang = '' title = self . __class__ . __name__ async for p in providers ( ) : await p . page_view ( url , title , user_id , user_lang ) return await func ( self , * args , ** kwargs ) return wrapper return decorator | Page view decorator . |
10,660 | def parse_cobol ( lines ) : output = [ ] intify = [ "level" , "occurs" ] for row in lines : match = CobolPatterns . row_pattern . match ( row . strip ( ) ) if not match : _logger ( ) . warning ( "Found unmatched row %s" % row . strip ( ) ) continue match = match . groupdict ( ) for i in intify : match [ i ] = int ( match [ i ] ) if match [ i ] is not None else None if match [ 'pic' ] is not None : match [ 'pic_info' ] = parse_pic_string ( match [ 'pic' ] ) output . append ( match ) return output | Parses the COBOL - converts the COBOL line into a dictionary containing the information - parses the pic information into type length precision - ~~handles redefines~~ - > our implementation does not do that anymore because we want to display item that was redefined . |
10,661 | def clean_names ( lines , ensure_unique_names = False , strip_prefix = False , make_database_safe = False ) : names = { } for row in lines : if strip_prefix : row [ 'name' ] = row [ 'name' ] [ row [ 'name' ] . find ( '-' ) + 1 : ] if row [ 'indexed_by' ] is not None : row [ 'indexed_by' ] = row [ 'indexed_by' ] [ row [ 'indexed_by' ] . find ( '-' ) + 1 : ] if ensure_unique_names : i = 1 while ( row [ 'name' ] if i == 1 else row [ 'name' ] + "-" + str ( i ) ) in names : i += 1 names [ row [ 'name' ] if i == 1 else row [ 'name' ] + "-" + str ( i ) ] = 1 if i > 1 : row [ 'name' ] = row [ 'name' ] + "-" + str ( i ) if make_database_safe : row [ 'name' ] = row [ 'name' ] . replace ( "-" , "_" ) return lines | Clean the names . |
10,662 | def create_app_from_yml ( path ) : try : with open ( path , "rt" , encoding = "UTF-8" ) as f : try : interpolated = io . StringIO ( f . read ( ) % { "here" : os . path . abspath ( os . path . dirname ( path ) ) } ) interpolated . name = f . name conf = yaml . safe_load ( interpolated ) except yaml . YAMLError as exc : raise RuntimeError ( "Cannot parse a configuration file. Context: " + str ( exc ) ) except FileNotFoundError : conf = { "metadata" : None , "pipes" : { } } return core . create_app ( conf [ "metadata" ] , pipes = conf [ "pipes" ] ) | Return an application instance created from YAML . |
10,663 | def configure_logger ( level ) : class _Formatter ( logging . Formatter ) : def format ( self , record ) : record . levelname = record . levelname [ : 4 ] return super ( _Formatter , self ) . format ( record ) stream_handler = logging . StreamHandler ( ) stream_handler . setFormatter ( _Formatter ( "[%(levelname)s] %(message)s" ) ) logger = logging . getLogger ( ) logger . addHandler ( stream_handler ) logger . setLevel ( level ) logging . captureWarnings ( True ) | Configure a root logger to print records in pretty format . |
10,664 | def parse_command_line ( args ) : parser = argparse . ArgumentParser ( description = ( "Holocron is an easy and lightweight static blog generator, " "based on markup text and Jinja2 templates." ) , epilog = ( "With no CONF, read .holocron.yml in the current working dir. " "If no CONF found, the default settings will be used." ) ) parser . add_argument ( "-c" , "--conf" , dest = "conf" , default = ".holocron.yml" , help = "set path to the settings file" ) parser . add_argument ( "-q" , "--quiet" , dest = "verbosity" , action = "store_const" , const = logging . CRITICAL , help = "show only critical errors" ) parser . add_argument ( "-v" , "--verbose" , dest = "verbosity" , action = "store_const" , const = logging . INFO , help = "show additional messages" ) parser . add_argument ( "-d" , "--debug" , dest = "verbosity" , action = "store_const" , const = logging . DEBUG , help = "show all messages" ) parser . add_argument ( "--version" , action = "version" , version = pkg_resources . get_distribution ( "holocron" ) . version , help = "show the holocron version and exit" ) command_parser = parser . add_subparsers ( dest = "command" , help = "command to execute" ) run_parser = command_parser . add_parser ( "run" ) run_parser . add_argument ( "pipe" , help = "a pipe to run" ) arguments = parser . parse_args ( args ) if arguments . command is None : parser . print_help ( ) parser . exit ( 1 ) return arguments | Builds a command line interface and parses its arguments . Returns an object with attributes that are represent CLI arguments . |
10,665 | def _list_syntax_error ( ) : _ , e , _ = sys . exc_info ( ) if isinstance ( e , SyntaxError ) and hasattr ( e , 'filename' ) : yield path . dirname ( e . filename ) | If we re going through a syntax error add the directory of the error to the watchlist . |
10,666 | def list_dirs ( ) : out = set ( ) out . update ( _list_config_dirs ( ) ) out . update ( _list_module_dirs ( ) ) out . update ( _list_syntax_error ( ) ) return out | List all directories known to hold project code . |
10,667 | async def start_child ( ) : logger . info ( 'Started to watch for code changes' ) loop = asyncio . get_event_loop ( ) watcher = aionotify . Watcher ( ) flags = ( aionotify . Flags . MODIFY | aionotify . Flags . DELETE | aionotify . Flags . ATTRIB | aionotify . Flags . MOVED_TO | aionotify . Flags . MOVED_FROM | aionotify . Flags . CREATE | aionotify . Flags . DELETE_SELF | aionotify . Flags . MOVE_SELF ) watched_dirs = list_dirs ( ) for dir_name in watched_dirs : watcher . watch ( path = dir_name , flags = flags ) await watcher . setup ( loop ) while True : evt = await watcher . get_event ( ) file_path = path . join ( evt . alias , evt . name ) if file_path in watched_dirs or file_path . endswith ( '.py' ) : await asyncio . sleep ( settings . CODE_RELOAD_DEBOUNCE ) break watcher . close ( ) exit_for_reload ( ) | Start the child process that will look for changes in modules . |
10,668 | def start_parent ( ) : while True : args = [ sys . executable ] + sys . argv new_environ = environ . copy ( ) new_environ [ "_IN_CHILD" ] = 'yes' ret = subprocess . call ( args , env = new_environ ) if ret != settings . CODE_RELOAD_EXIT : return ret | Start the parent that will simply run the child forever until stopped . |
10,669 | def get_from_params ( request , key ) : data = getattr ( request , 'json' , None ) or request . values value = data . get ( key ) return to_native ( value ) | Try to read a value named key from the GET parameters . |
10,670 | def get_from_headers ( request , key ) : value = request . headers . get ( key ) return to_native ( value ) | Try to read a value named key from the headers . |
10,671 | async def async_init ( self ) : self . pool = await aioredis . create_pool ( ( self . host , self . port ) , db = self . db_id , minsize = self . min_pool_size , maxsize = self . max_pool_size , loop = asyncio . get_event_loop ( ) , ) | Handle here the asynchronous part of the init . |
10,672 | def serialize ( d ) : ret = { } for k , v in d . items ( ) : if not k . startswith ( '_' ) : ret [ k ] = str ( d [ k ] ) return ret | Attempts to serialize values from a dictionary skipping private attrs . |
10,673 | def user_config ( ** kwargs ) : for kw in kwargs : git ( 'config --global user.%s "%s"' % ( kw , kwargs . get ( kw ) ) ) . wait ( ) | Initialize Git user config file . |
10,674 | def _make_header ( self , token_type = None , signing_algorithm = None ) : if not token_type : token_type = self . token_type if not signing_algorithm : signing_algorithm = self . signing_algorithm header = { 'typ' : token_type , 'alg' : signing_algorithm } return header | Make a JWT header |
10,675 | def _make_signature ( self , header_b64 , payload_b64 , signing_key ) : token_segments = [ header_b64 , payload_b64 ] signing_input = b'.' . join ( token_segments ) signer = self . _get_signer ( signing_key ) signer . update ( signing_input ) signature = signer . finalize ( ) raw_signature = der_to_raw_signature ( signature , signing_key . curve ) return base64url_encode ( raw_signature ) | Sign a serialized header and payload . Return the urlsafe - base64 - encoded signature . |
10,676 | def _sign_multi ( self , payload , signing_keys ) : if not isinstance ( payload , Mapping ) : raise TypeError ( 'Expecting a mapping object, as only ' 'JSON objects can be used as payloads.' ) if not isinstance ( signing_keys , list ) : raise TypeError ( "Expecting a list of keys" ) headers = [ ] signatures = [ ] payload_b64 = base64url_encode ( json_encode ( payload ) ) for sk in signing_keys : signing_key = load_signing_key ( sk , self . crypto_backend ) header = self . _make_header ( ) header_b64 = base64url_encode ( json_encode ( header ) ) signature_b64 = self . _make_signature ( header_b64 , payload_b64 , signing_key ) headers . append ( header_b64 ) signatures . append ( signature_b64 ) jwt = { "header" : headers , "payload" : payload_b64 , "signature" : signatures } return jwt | Make a multi - signature JWT . Returns a JSON - structured JWT . |
10,677 | def sign ( self , payload , signing_key_or_keys ) : if isinstance ( signing_key_or_keys , list ) : return self . _sign_multi ( payload , signing_key_or_keys ) else : return self . _sign_single ( payload , signing_key_or_keys ) | Create a JWT with one or more keys . Returns a compact - form serialized JWT if there is only one key to sign with Returns a JSON - structured serialized JWT if there are multiple keys to sign with |
10,678 | def parse_reqs ( req_path = './requirements/requirements.txt' ) : install_requires = [ ] with codecs . open ( req_path , 'r' ) as handle : lines = ( line . strip ( ) for line in handle if line . strip ( ) and not line . startswith ( '#' ) ) for line in lines : if line . startswith ( '-r' ) : install_requires += parse_reqs ( req_path = line [ 3 : ] ) else : install_requires . append ( line ) return install_requires | Recursively parse requirements from nested pip files . |
10,679 | def report ( self , request : 'Request' = None , state : Text = None ) : self . _make_context ( request , state ) self . client . captureException ( ) self . _clear_context ( ) | Report current exception to Sentry . |
10,680 | def vary_name ( name : Text ) : snake = re . match ( r'^[a-z][a-z0-9]*(?:_[a-z0-9]+)*$' , name ) if not snake : fail ( 'The project name is not a valid snake-case Python variable name' ) camel = [ x [ 0 ] . upper ( ) + x [ 1 : ] for x in name . split ( '_' ) ] return { 'project_name_snake' : name , 'project_name_camel' : '' . join ( camel ) , 'project_name_readable' : ' ' . join ( camel ) , } | Validates the name and creates variations |
10,681 | def make_random_key ( ) -> Text : r = SystemRandom ( ) allowed = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_+/[]' return '' . join ( [ r . choice ( allowed ) for _ in range ( 0 , 50 ) ] ) | Generates a secure random string |
10,682 | def make_dir_path ( project_dir , root , project_name ) : root = root . replace ( '__project_name_snake__' , project_name ) real_dir = path . realpath ( project_dir ) return path . join ( real_dir , root ) | Generates the target path for a directory |
10,683 | def make_file_path ( project_dir , project_name , root , name ) : return path . join ( make_dir_path ( project_dir , root , project_name ) , name ) | Generates the target path for a file |
10,684 | def generate_vars ( project_name , project_dir ) : out = vary_name ( project_name ) out [ 'random_key' ] = make_random_key ( ) out [ 'settings_file' ] = make_file_path ( project_dir , project_name , path . join ( 'src' , project_name ) , 'settings.py' , ) return out | Generates the variables to replace in files |
10,685 | def get_files ( ) : files_root = path . join ( path . dirname ( __file__ ) , 'files' ) for root , dirs , files in walk ( files_root ) : rel_root = path . relpath ( root , files_root ) for file_name in files : try : f = open ( path . join ( root , file_name ) , 'r' , encoding = 'utf-8' ) with f : yield rel_root , file_name , f . read ( ) , True except UnicodeError : f = open ( path . join ( root , file_name ) , 'rb' ) with f : yield rel_root , file_name , f . read ( ) , False | Read all the template s files |
10,686 | def check_target ( target_path ) : if not path . exists ( target_path ) : return with scandir ( target_path ) as d : for entry in d : if not entry . name . startswith ( '.' ) : fail ( f'Target directory "{target_path}" is not empty' ) | Checks that the target path is not empty |
10,687 | def replace_content ( content , project_vars ) : for k , v in project_vars . items ( ) : content = content . replace ( f'__{k}__' , v ) return content | Replaces variables inside the content . |
10,688 | def copy_files ( project_vars , project_dir , files ) : for root , name , content , is_unicode in files : project_name = project_vars [ 'project_name_snake' ] if is_unicode : content = replace_content ( content , project_vars ) file_path = make_file_path ( project_dir , project_name , root , name ) makedirs ( make_dir_path ( project_dir , root , project_name ) , exist_ok = True ) if is_unicode : with open ( file_path , 'w' ) as f : f . write ( content ) if content . startswith ( '#!' ) : chmod ( file_path , 0o755 ) else : with open ( file_path , 'wb' ) as f : f . write ( content ) | Copies files from the template into their target location . Unicode files get their variables replaced here and files with a shebang are set to be executable . |
10,689 | def connect ( self ) : for m in self . params [ 'MEMBERS' ] : m [ 'ONLINE' ] = 0 m . setdefault ( 'STATUS' , 'INVITED' ) self . client = xmpp . Client ( self . jid . getDomain ( ) , debug = [ ] ) conn = self . client . connect ( server = self . params [ 'SERVER' ] ) if not conn : raise Exception ( "could not connect to server" ) auth = self . client . auth ( self . jid . getNode ( ) , self . params [ 'PASSWORD' ] ) if not auth : raise Exception ( "could not authenticate as chat server" ) self . client . RegisterHandler ( 'message' , self . on_message ) self . client . RegisterHandler ( 'presence' , self . on_presence ) self . client . sendInitPresence ( requestRoster = 0 ) roster = self . client . getRoster ( ) for m in self . params [ 'MEMBERS' ] : self . invite_user ( m , roster = roster ) | Connect to the chatroom s server sets up handlers invites members as needed . |
10,690 | def get_member ( self , jid , default = None ) : member = filter ( lambda m : m [ 'JID' ] == jid , self . params [ 'MEMBERS' ] ) if len ( member ) == 1 : return member [ 0 ] elif len ( member ) == 0 : return default else : raise Exception ( 'Multple members have the same JID of [%s]' % ( jid , ) ) | Get a chatroom member by JID |
10,691 | def is_member ( self , m ) : if not m : return False elif isinstance ( m , basestring ) : jid = m else : jid = m [ 'JID' ] is_member = len ( filter ( lambda m : m [ 'JID' ] == jid and m . get ( 'STATUS' ) in ( 'ACTIVE' , 'INVITED' ) , self . params [ 'MEMBERS' ] ) ) > 0 return is_member | Check if a user is a member of the chatroom |
10,692 | def invite_user ( self , new_member , inviter = None , roster = None ) : roster = roster or self . client . getRoster ( ) jid = new_member [ 'JID' ] logger . info ( 'roster %s %s' % ( jid , roster . getSubscription ( jid ) ) ) if jid in roster . keys ( ) and roster . getSubscription ( jid ) in [ 'both' , 'to' ] : new_member [ 'STATUS' ] = 'ACTIVE' if inviter : self . send_message ( '%s is already a member' % ( jid , ) , inviter ) else : new_member [ 'STATUS' ] = 'INVITED' self . broadcast ( 'inviting %s to the room' % ( jid , ) ) subscribe_presence = xmpp . dispatcher . Presence ( to = jid , typ = 'subscribe' ) if 'NICK' in self . params : subscribe_presence . addChild ( name = 'nick' , namespace = xmpp . protocol . NS_NICK , payload = self . params [ 'NICK' ] ) self . client . send ( subscribe_presence ) if not self . is_member ( new_member ) : new_member . setdefault ( 'NICK' , jid . split ( '@' ) [ 0 ] ) self . params [ 'MEMBERS' ] . append ( new_member ) | Invites a new member to the chatroom |
10,693 | def kick_user ( self , jid ) : for member in filter ( lambda m : m [ 'JID' ] == jid , self . params [ 'MEMBERS' ] ) : member [ 'STATUS' ] = 'KICKED' self . send_message ( 'You have been kicked from %s' % ( self . name , ) , member ) self . client . sendPresence ( jid = member [ 'JID' ] , typ = 'unsubscribed' ) self . client . sendPresence ( jid = member [ 'JID' ] , typ = 'unsubscribe' ) self . broadcast ( 'kicking %s from the room' % ( jid , ) ) | Kicks a member from the chatroom . Kicked user will receive no more messages . |
10,694 | def send_message ( self , body , to , quiet = False , html_body = None ) : if to . get ( 'MUTED' ) : to [ 'QUEUED_MESSAGES' ] . append ( body ) else : if not quiet : logger . info ( 'message on %s to %s: %s' % ( self . name , to [ 'JID' ] , body ) ) message = xmpp . protocol . Message ( to = to [ 'JID' ] , body = body , typ = 'chat' ) if html_body : html = xmpp . Node ( 'html' , { 'xmlns' : 'http://jabber.org/protocol/xhtml-im' } ) html . addChild ( node = xmpp . simplexml . XML2Node ( "<body xmlns='http://www.w3.org/1999/xhtml'>" + html_body . encode ( 'utf-8' ) + "</body>" ) ) message . addChild ( node = html ) self . client . send ( message ) | Send a message to a single member |
10,695 | def broadcast ( self , body , html_body = None , exclude = ( ) ) : logger . info ( 'broadcast on %s: %s' % ( self . name , body , ) ) for member in filter ( lambda m : m . get ( 'STATUS' ) == 'ACTIVE' and m not in exclude , self . params [ 'MEMBERS' ] ) : logger . debug ( member [ 'JID' ] ) self . send_message ( body , member , html_body = html_body , quiet = True ) | Broadcast a message to users in the chatroom |
10,696 | def do_invite ( self , sender , body , args ) : for invitee in args : new_member = { 'JID' : invitee } self . invite_user ( new_member , inviter = sender ) | Invite members to the chatroom on a user s behalf |
10,697 | def do_kick ( self , sender , body , args ) : if sender . get ( 'ADMIN' ) != True : return for user in args : self . kick_user ( user ) | Kick a member from the chatroom . Must be Admin to kick users |
10,698 | def do_mute ( self , sender , body , args ) : if sender . get ( 'MUTED' ) : self . send_message ( 'you are already muted' , sender ) else : self . broadcast ( '%s has muted this chatroom' % ( sender [ 'NICK' ] , ) ) sender [ 'QUEUED_MESSAGES' ] = [ ] sender [ 'MUTED' ] = True | Temporarily mutes chatroom for a user |
10,699 | def do_unmute ( self , sender , body , args ) : if sender . get ( 'MUTED' ) : sender [ 'MUTED' ] = False self . broadcast ( '%s has unmuted this chatroom' % ( sender [ 'NICK' ] , ) ) for msg in sender . get ( 'QUEUED_MESSAGES' , [ ] ) : self . send_message ( msg , sender ) sender [ 'QUEUED_MESSAGES' ] = [ ] else : self . send_message ( 'you were not muted' , sender ) | Unmutes the chatroom for a user |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.