idx int64 0 252k | question stringlengths 48 5.28k | target stringlengths 5 1.23k |
|---|---|---|
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 . mambuus... | 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 ... | 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... | 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' : ret... | 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 pa... | 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... | 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... | 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 = { } f... | 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 [ p... | 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 :... | 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 ... | 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 . ... | 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 (... | 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 :... | 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 ( _... | 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 . sele... | 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 = '... | 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 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 dot... | 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 ... | 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... | 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 [ ... | 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 t... | 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 = l... | 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 ) ) ) NotK... | 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 = se... | 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 = sel... | 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 ( ... | 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 = Fals... | 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 di... | 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 ... | 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 ( mat... | 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 [... | 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 : ... | 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] %(m... | 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... | 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 | aionoti... | 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 ( sign... | 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 = [ ] paylo... | 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_r... | 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'... | 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_n... | 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_... | 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... | 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_m... | 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 . c... | 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 ... | 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 ,... | 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... | 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.