idx
int64
0
252k
question
stringlengths
48
5.28k
target
stringlengths
5
1.23k
10,500
def similarity ( self , other : Trigram ) -> Tuple [ float , L ] : return max ( ( ( t % other , l ) for t , l in self . trigrams ) , key = lambda x : x [ 0 ] , )
Returns the best matching score and the associated label .
10,501
def _exception_for ( self , code ) : if code in self . errors : return self . errors [ code ] elif 500 <= code < 599 : return exceptions . RemoteServerError else : return exceptions . UnknownError
Return the exception class suitable for the specified HTTP status code .
10,502
def setGroups ( self , * args , ** kwargs ) : requests = 0 groups = [ ] try : for gk in self [ 'groupKeys' ] : try : g = self . mambugroupclass ( entid = gk , * args , ** kwargs ) except AttributeError as ae : from . mambugroup import MambuGroup self . mambugroupclass = MambuGroup g = self . mambugroupclass ( entid = g...
Adds the groups to which this client belongs .
10,503
def setBranch ( self , * args , ** kwargs ) : try : branch = self . mambubranchclass ( entid = self [ 'assignedBranchKey' ] , * args , ** kwargs ) except AttributeError as ae : from . mambubranch import MambuBranch self . mambubranchclass = MambuBranch branch = self . mambubranchclass ( entid = self [ 'assignedBranchKe...
Adds the branch to which the client belongs .
10,504
def protected ( self , * tests , ** kwargs ) : _role = kwargs . pop ( 'role' , None ) _roles = kwargs . pop ( 'roles' , None ) or [ ] _csrf = kwargs . pop ( 'csrf' , None ) _url_sign_in = kwargs . pop ( 'url_sign_in' , None ) _request = kwargs . pop ( 'request' , None ) if _role : _roles . append ( _role ) _roles = [ t...
Factory of decorators for limit the access to views .
10,505
def replace_flask_route ( self , bp , * args , ** kwargs ) : protected = self . protected def protected_route ( rule , ** options ) : def decorator ( f ) : endpoint = options . pop ( "endpoint" , f . __name__ ) protected_f = protected ( * args , ** kwargs ) ( f ) bp . add_url_rule ( rule , endpoint , protected_f , ** o...
Replace the Flask app . route or blueprint . route with a version that first apply the protected decorator to the view so all views are automatically protected .
10,506
def parse_query ( self , query ) : tree = pypeg2 . parse ( query , Main , whitespace = "" ) return tree . accept ( self . converter )
Parse query string using given grammar
10,507
def decode_token ( token ) : if isinstance ( token , ( unicode , str ) ) : return _decode_token_compact ( token ) else : return _decode_token_json ( token )
Top - level method to decode a JWT . Takes either a compact - encoded JWT with a single signature or a multi - sig JWT in the JSON - serialized format .
10,508
def _verify_multi ( self , token , verifying_keys , num_required = None ) : headers , payload , raw_signatures , signing_inputs = _unpack_token_json ( token ) if num_required is None : num_required = len ( raw_signatures ) if num_required > len ( verifying_keys ) : return False if len ( headers ) != len ( raw_signature...
Verify a JSON - formatted JWT signed by multiple keys is authentic . Optionally set a threshold of required valid signatures with num_required . Return True if valid Return False if not
10,509
def verify ( self , token , verifying_key_or_keys , num_required = None ) : if not isinstance ( verifying_key_or_keys , ( list , str , unicode ) ) : raise ValueError ( "Invalid verifying key(s): expected list or string" ) if isinstance ( verifying_key_or_keys , list ) : return self . _verify_multi ( token , verifying_k...
Verify a compact - formated JWT or a JSON - formatted JWT signed by multiple keys . Return True if valid Return False if not valid
10,510
def activate_script ( self ) : self . _add_scope ( "script" ) self . scripts = { } self . script_files = [ "./scripts/script_*.txt" , "~/.cloudmesh/scripts/script_*.txt" ] self . _load_scripts ( self . script_files )
activates the script command
10,511
def touch ( path ) : parentDirPath = os . path . dirname ( path ) PathOperations . safeMakeDirs ( parentDirPath ) with open ( path , "wb" ) : pass
Creates the given path as a file also creating intermediate directories if required .
10,512
def safeRmTree ( rootPath ) : shutil . rmtree ( rootPath , True ) return not os . path . exists ( rootPath )
Deletes a tree and returns true if it was correctly deleted
10,513
def linearWalk ( rootPath , currentDirFilter = None ) : for dirTuple in os . walk ( rootPath ) : ( dirPath , dirNames , fileNames ) = dirTuple if currentDirFilter is not None and not currentDirFilter ( dirPath , dirNames , fileNames ) : continue for fileName in fileNames : yield LinearWalkItem ( dirPath , fileName )
Returns a list of LinearWalkItem s one for each file in the tree whose root is rootPath .
10,514
def init_live_reload ( run ) : from asyncio import get_event_loop from . _live_reload import start_child loop = get_event_loop ( ) if run : loop . run_until_complete ( start_child ( ) ) else : get_event_loop ( ) . create_task ( start_child ( ) )
Start the live reload task
10,515
def cmp_name ( first_node , second_node ) : if len ( first_node . children ) == len ( second_node . children ) : for first_child , second_child in zip ( first_node . children , second_node . children ) : for key in first_child . __dict__ . keys ( ) : if key . startswith ( '_' ) : continue if first_child . __dict__ [ ke...
Compare two name recursively .
10,516
def parse_division ( l , c , line , root_node , last_section_node ) : name = line name = name . replace ( "." , "" ) tokens = [ t for t in name . split ( ' ' ) if t ] node = Name ( Name . Type . Division , l , c , '%s %s' % ( tokens [ 0 ] , tokens [ 1 ] ) ) root_node . add_child ( node ) last_div_node = node if last_se...
Extracts a division node from a line
10,517
def parse_section ( l , c , last_div_node , last_vars , line ) : name = line name = name . replace ( "." , "" ) node = Name ( Name . Type . Section , l , c , name ) last_div_node . add_child ( node ) last_section_node = node last_vars . clear ( ) return last_section_node
Extracts a section node from a line .
10,518
def parse_pic_field ( l , c , last_section_node , last_vars , line ) : parent_node = None raw_tokens = line . split ( " " ) tokens = [ ] for t in raw_tokens : if not t . isspace ( ) and t != "" : tokens . append ( t ) try : if tokens [ 0 ] . upper ( ) == "FD" : lvl = 1 else : lvl = int ( tokens [ 0 ] , 16 ) name = toke...
Parse a pic field line . Return A VariableNode or None in case of malformed code .
10,519
def parse_paragraph ( l , c , last_div_node , last_section_node , line ) : if not line . endswith ( '.' ) : return None name = line . replace ( "." , "" ) if name . strip ( ) == '' : return None if name . upper ( ) in ALL_KEYWORDS : return None parent_node = last_div_node if last_section_node is not None : parent_node ...
Extracts a paragraph node
10,520
def find ( self , name ) : for c in self . children : if c . name == name : return c result = c . find ( name ) if result : return result
Finds a possible child whose name match the name parameter .
10,521
def to_definition ( self ) : icon = { Name . Type . Root : icons . ICON_MIMETYPE , Name . Type . Division : icons . ICON_DIVISION , Name . Type . Section : icons . ICON_SECTION , Name . Type . Variable : icons . ICON_VAR , Name . Type . Paragraph : icons . ICON_FUNC } [ self . node_type ] d = Definition ( self . name ,...
Converts the name instance to a pyqode . core . share . Definition
10,522
def connectDb ( engine = dbeng , user = dbuser , password = dbpwd , host = dbhost , port = dbport , database = dbname , params = "?charset=utf8&use_unicode=1" , echoopt = False ) : return create_engine ( '%s://%s:%s@%s:%s/%s%s' % ( engine , user , password , host , port , database , params ) , echo = echoopt )
Connect to database utility function .
10,523
def getbranchesurl ( idbranch , * args , ** kwargs ) : getparams = [ ] if kwargs : try : if kwargs [ "fullDetails" ] == True : getparams . append ( "fullDetails=true" ) else : getparams . append ( "fullDetails=false" ) except Exception as ex : pass try : getparams . append ( "offset=%s" % kwargs [ "offset" ] ) except E...
Request Branches URL .
10,524
def getcentresurl ( idcentre , * args , ** kwargs ) : getparams = [ ] if kwargs : try : if kwargs [ "fullDetails" ] == True : getparams . append ( "fullDetails=true" ) else : getparams . append ( "fullDetails=false" ) except Exception as ex : pass try : getparams . append ( "offset=%s" % kwargs [ "offset" ] ) except Ex...
Request Centres URL .
10,525
def getrepaymentsurl ( idcred , * args , ** kwargs ) : url = getmambuurl ( * args , ** kwargs ) + "loans/" + idcred + "/repayments" return url
Request loan Repayments URL .
10,526
def getloansurl ( idcred , * args , ** kwargs ) : getparams = [ ] if kwargs : try : if kwargs [ "fullDetails" ] == True : getparams . append ( "fullDetails=true" ) else : getparams . append ( "fullDetails=false" ) except Exception as ex : pass try : getparams . append ( "accountState=%s" % kwargs [ "accountState" ] ) e...
Request Loans URL .
10,527
def getgroupurl ( idgroup , * args , ** kwargs ) : getparams = [ ] if kwargs : try : if kwargs [ "fullDetails" ] == True : getparams . append ( "fullDetails=true" ) else : getparams . append ( "fullDetails=false" ) except Exception as ex : pass try : getparams . append ( "creditOfficerUsername=%s" % kwargs [ "creditOff...
Request Groups URL .
10,528
def getgrouploansurl ( idgroup , * args , ** kwargs ) : getparams = [ ] if kwargs : try : if kwargs [ "fullDetails" ] == True : getparams . append ( "fullDetails=true" ) else : getparams . append ( "fullDetails=false" ) except Exception as ex : pass try : getparams . append ( "accountState=%s" % kwargs [ "accountState"...
Request Group loans URL .
10,529
def getgroupcustominformationurl ( idgroup , customfield = "" , * args , ** kwargs ) : groupidparam = "/" + idgroup url = getmambuurl ( * args , ** kwargs ) + "groups" + groupidparam + "/custominformation" + ( ( "/" + customfield ) if customfield else "" ) return url
Request Group Custom Information URL .
10,530
def gettransactionsurl ( idcred , * args , ** kwargs ) : getparams = [ ] if kwargs : try : getparams . append ( "offset=%s" % kwargs [ "offset" ] ) except Exception as ex : pass try : getparams . append ( "limit=%s" % kwargs [ "limit" ] ) except Exception as ex : pass url = getmambuurl ( * args , ** kwargs ) + "loans/"...
Request loan Transactions URL .
10,531
def getclienturl ( idclient , * args , ** kwargs ) : getparams = [ ] if kwargs : try : if kwargs [ "fullDetails" ] == True : getparams . append ( "fullDetails=true" ) else : getparams . append ( "fullDetails=false" ) except Exception as ex : pass try : getparams . append ( "firstName=%s" % kwargs [ "firstName" ] ) exce...
Request Clients URL .
10,532
def getclientloansurl ( idclient , * args , ** kwargs ) : getparams = [ ] if kwargs : try : if kwargs [ "fullDetails" ] == True : getparams . append ( "fullDetails=true" ) else : getparams . append ( "fullDetails=false" ) except Exception as ex : pass try : getparams . append ( "accountState=%s" % kwargs [ "accountStat...
Request Client loans URL .
10,533
def getclientcustominformationurl ( idclient , customfield = "" , * args , ** kwargs ) : clientidparam = "/" + idclient url = getmambuurl ( * args , ** kwargs ) + "clients" + clientidparam + "/custominformation" + ( ( "/" + customfield ) if customfield else "" ) return url
Request Client Custom Information URL .
10,534
def getuserurl ( iduser , * args , ** kwargs ) : getparams = [ ] if kwargs : try : if kwargs [ "fullDetails" ] == True : getparams . append ( "fullDetails=true" ) else : getparams . append ( "fullDetails=false" ) except Exception as ex : pass try : getparams . append ( "branchId=%s" % kwargs [ "branchId" ] ) except Exc...
Request Users URL .
10,535
def getproductsurl ( idproduct , * args , ** kwargs ) : productidparam = "" if idproduct == "" else "/" + idproduct url = getmambuurl ( * args , ** kwargs ) + "loanproducts" + productidparam return url
Request loan Products URL .
10,536
def gettasksurl ( dummyId = '' , * args , ** kwargs ) : getparams = [ ] if kwargs : try : getparams . append ( "username=%s" % kwargs [ "username" ] ) except Exception as ex : pass try : getparams . append ( "clientid=%s" % kwargs [ "clientId" ] ) except Exception as ex : pass try : getparams . append ( "groupid=%s" % ...
Request Tasks URL .
10,537
def getactivitiesurl ( dummyId = '' , * args , ** kwargs ) : from datetime import datetime getparams = [ ] if kwargs : try : getparams . append ( "from=%s" % kwargs [ "fromDate" ] ) except Exception as ex : getparams . append ( "from=%s" % '1900-01-01' ) try : getparams . append ( "to=%s" % kwargs [ "toDate" ] ) except...
Request Activities URL .
10,538
def getrolesurl ( idrole = '' , * args , ** kwargs ) : url = getmambuurl ( * args , ** kwargs ) + "userroles" + ( ( "/" + idrole ) if idrole else "" ) return url
Request Roles URL .
10,539
def strip_tags ( html ) : from html . parser import HTMLParser class MLStripper ( HTMLParser ) : def __init__ ( self ) : try : super ( ) . __init__ ( ) except TypeError as e : pass self . reset ( ) self . fed = [ ] def handle_data ( self , d ) : self . fed . append ( d ) def get_data ( self ) : return '' . join ( self ...
Stripts HTML tags from text .
10,540
def strip_consecutive_repeated_char ( s , ch ) : sdest = "" for i , c in enumerate ( s ) : if i != 0 and s [ i ] == ch and s [ i ] == s [ i - 1 ] : continue sdest += s [ i ] return sdest
Strip characters in a string which are consecutively repeated .
10,541
def encoded_dict ( in_dict ) : out_dict = { } for k , v in in_dict . items ( ) : if isinstance ( v , unicode ) : if sys . version_info < ( 3 , 0 ) : v = v . encode ( 'utf8' ) elif isinstance ( v , str ) : if sys . version_info < ( 3 , 0 ) : v . decode ( 'utf8' ) out_dict [ k ] = v return out_dict
Encode every value of a dict to UTF - 8 .
10,542
def backup_db ( callback , bool_func , output_fname , * args , ** kwargs ) : from datetime import datetime try : verbose = kwargs [ 'verbose' ] except KeyError : verbose = False try : retries = kwargs [ 'retries' ] except KeyError : retries = - 1 try : force_download_latest = bool ( kwargs [ 'force_download_latest' ] )...
Backup Mambu Database via REST API .
10,543
def memoize ( func ) : cache_name = '__CACHED_{}' . format ( func . __name__ ) def wrapper ( self , * args ) : cache = getattr ( self , cache_name , None ) if cache is None : cache = { } setattr ( self , cache_name , cache ) if args not in cache : cache [ args ] = func ( self , * args ) return cache [ args ] return wra...
Provides memoization for methods on a specific instance . Results are cached for given parameter list .
10,544
def _pathway_side_information ( pathway_positive_series , pathway_negative_series , index ) : positive_series_label = pd . Series ( [ "pos" ] * len ( pathway_positive_series ) ) negative_series_label = pd . Series ( [ "neg" ] * len ( pathway_negative_series ) ) side_information = positive_series_label . append ( negati...
Create the pandas . Series containing the side labels that correspond to each pathway based on the user - specified gene signature definition .
10,545
def _significant_pathways_dataframe ( pvalue_information , side_information , alpha ) : significant_pathways = pd . concat ( [ pvalue_information , side_information ] , axis = 1 ) below_alpha , qvalues , _ , _ = multipletests ( significant_pathways [ "p-value" ] , alpha = alpha , method = "fdr_bh" ) below_alpha = pd . ...
Create the significant pathways pandas . DataFrame . Given the p - values corresponding to each pathway in a feature apply the FDR correction for multiple testing and remove those that do not have a q - value of less than alpha .
10,546
async def flush ( self , request : Request , stacks : List [ Stack ] ) : ns = await self . expand_stacks ( request , stacks ) ns = self . split_stacks ( ns ) ns = self . clean_stacks ( ns ) await self . next ( request , [ Stack ( x ) for x in ns ] )
For all stacks to be sent append a pause after each text layer .
10,547
def split_stacks ( self , stacks : List [ List [ BaseLayer ] ] ) -> List [ List [ BaseLayer ] ] : ns : List [ List [ BaseLayer ] ] = [ ] for stack in stacks : cur : List [ BaseLayer ] = [ ] for layer in stack : if cur and isinstance ( layer , lyr . RawText ) : ns . append ( cur ) cur = [ ] cur . append ( layer ) if cur...
First step of the stacks cleanup process . We consider that if inside a stack there s a text layer showing up then it s the beginning of a new stack and split upon that .
10,548
async def expand ( self , request : Request , layer : BaseLayer ) : if isinstance ( layer , lyr . RawText ) : t = self . reading_time ( layer . text ) yield layer yield lyr . Sleep ( t ) elif isinstance ( layer , lyr . MultiText ) : texts = await render ( layer . text , request , True ) for text in texts : t = self . r...
Expand a layer into a list of layers including the pauses .
10,549
def reading_time ( self , text : TextT ) : wc = re . findall ( r'\w+' , text ) period = 60.0 / settings . USERS_READING_SPEED return float ( len ( wc ) ) * period + settings . USERS_READING_BUBBLE_START
Computes the time in seconds that the user will need to read a bubble containing the text passed as parameter .
10,550
async def flush ( self , request : Request , stacks : List [ Stack ] ) : ns : List [ Stack ] = [ ] for stack in stacks : ns . extend ( self . typify ( stack ) ) if len ( ns ) > 1 and ns [ - 1 ] == Stack ( [ lyr . Typing ( ) ] ) : ns [ - 1 ] . get_layer ( lyr . Typing ) . active = False await self . next ( request , ns ...
Add a typing stack after each stack .
10,551
async def pre_handle ( self , request : Request , responder : 'Responder' ) : responder . send ( [ lyr . Typing ( ) ] ) await responder . flush ( request ) responder . clear ( ) await self . next ( request , responder )
Start typing right when the message is received .
10,552
async def get_friendly_name ( self ) -> Text : if 'first_name' not in self . _user : user = await self . _get_full_user ( ) else : user = self . _user return user . get ( 'first_name' )
Let s use the first name of the user as friendly name . In some cases the user object is incomplete and in those cases the full user is fetched .
10,553
def _get_chat ( self ) -> Dict : if 'callback_query' in self . _update : query = self . _update [ 'callback_query' ] if 'message' in query : return query [ 'message' ] [ 'chat' ] else : return { 'id' : query [ 'chat_instance' ] } elif 'inline_query' in self . _update : return patch_dict ( self . _update [ 'inline_query...
As Telegram changes where the chat object is located in the response this method tries to be smart about finding it in the right place .
10,554
def send ( self , stack : Layers ) : if not isinstance ( stack , Stack ) : stack = Stack ( stack ) if 'callback_query' in self . _update and stack . has_layer ( Update ) : layer = stack . get_layer ( Update ) try : msg = self . _update [ 'callback_query' ] [ 'message' ] except KeyError : layer . inline_message_id = sel...
Intercept any potential AnswerCallbackQuery before adding the stack to the output buffer .
10,555
async def flush ( self , request : BernardRequest ) : if self . _acq and 'callback_query' in self . _update : try : cbq_id = self . _update [ 'callback_query' ] [ 'id' ] except KeyError : pass else : await self . platform . call ( 'answerCallbackQuery' , ** ( await self . _acq . serialize ( cbq_id ) ) ) return await su...
If there s a AnswerCallbackQuery scheduled for reply place the call before actually flushing the buffer .
10,556
async def receive_updates ( self , request : Request ) : body = await request . read ( ) try : content = ujson . loads ( body ) except ValueError : return json_response ( { 'error' : True , 'message' : 'Cannot decode body' , } , status = 400 ) logger . debug ( 'Received from Telegram: %s' , content ) message = Telegram...
Handle updates from Telegram
10,557
def make_url ( self , method ) : token = self . settings ( ) [ 'token' ] return TELEGRAM_URL . format ( token = quote ( token ) , method = quote ( method ) , )
Generate a Telegram URL for this bot .
10,558
async def call ( self , method : Text , _ignore : Set [ Text ] = None , ** params : Any ) : logger . debug ( 'Calling Telegram %s(%s)' , method , params ) url = self . make_url ( method ) headers = { 'content-type' : 'application/json' , } post = self . session . post ( url , data = ujson . dumps ( params ) , headers =...
Call a telegram method
10,559
async def _handle_telegram_response ( self , response , ignore = None ) : if ignore is None : ignore = set ( ) ok = response . status == 200 try : data = await response . json ( ) if not ok : desc = data [ 'description' ] if desc in ignore : return raise PlatformOperationError ( 'Telegram replied with an error: {}' . f...
Parse a response from Telegram . If there s an error an exception will be raised with an explicative message .
10,560
def make_hook_path ( self ) : token = self . settings ( ) [ 'token' ] h = sha256 ( ) h . update ( token . encode ( ) ) key = str ( h . hexdigest ( ) ) return f'/hooks/telegram/{key}'
Compute the path to the hook URL
10,561
async def _deferred_init ( self ) : hook_path = self . make_hook_path ( ) url = urljoin ( settings . BERNARD_BASE_URL , hook_path ) await self . call ( 'setWebhook' , url = url ) logger . info ( 'Setting Telegram webhook to "%s"' , url )
Register the web hook onto which Telegram should send its messages .
10,562
async def _send_text ( self , request : Request , stack : Stack , parse_mode : Optional [ Text ] = None ) : parts = [ ] chat_id = request . message . get_chat_id ( ) for layer in stack . layers : if isinstance ( layer , ( lyr . Text , lyr . RawText , lyr . Markdown ) ) : text = await render ( layer . text , request ) p...
Base function for sending text
10,563
async def _send_sleep ( self , request : Request , stack : Stack ) : duration = stack . get_layer ( lyr . Sleep ) . duration await sleep ( duration )
Sleep for the amount of time specified in the Sleep layer
10,564
async def _send_typing ( self , request : Request , stack : Stack ) : t = stack . get_layer ( lyr . Typing ) if t . active : await self . call ( 'sendChatAction' , chat_id = request . message . get_chat_id ( ) , action = 'typing' , )
In telegram the typing stops when the message is received . Thus there is no typing stops messages to send . The API is only called when typing must start .
10,565
def create_app ( metadata , processors = None , pipes = None ) : instance = Application ( metadata ) import_processors . process ( instance , [ ] , imports = [ "archive = holocron.processors.archive:process" , "commonmark = holocron.processors.commonmark:process" , "feed = holocron.processors.feed:process" , "frontmatt...
Return an application instance with processors & pipes setup .
10,566
async def page_view ( self , url : str , title : str , user_id : str , user_lang : str = '' ) -> None : ga_url = 'https://www.google-analytics.com/collect' args = { 'v' : '1' , 'ds' : 'web' , 'de' : 'UTF-8' , 'tid' : self . ga_id , 'cid' : self . hash_user_id ( user_id ) , 't' : 'pageview' , 'dh' : self . ga_domain , '...
Log a page view .
10,567
def get ( self , username = None , password = None , headers = { } ) : if all ( ( username , password , ) ) : return BasicAuth ( username , password , headers ) elif not any ( ( username , password , ) ) : return AnonymousAuth ( headers ) else : if username is None : data = ( "username" , username , ) else : data = ( "...
Factory method to get the correct AuthInfo object .
10,568
def populate_request_data ( self , request_args ) : request_args [ 'auth' ] = HTTPBasicAuth ( self . _username , self . _password ) return request_args
Add the authentication info to the supplied dictionary .
10,569
def register_workflow ( self , name , workflow ) : assert name not in self . workflows self . workflows [ name ] = workflow
Register an workflow to be showed in the workflows list .
10,570
def add_header ( self , name , value ) : self . _headers . setdefault ( _hkey ( name ) , [ ] ) . append ( _hval ( value ) )
Add an additional response header not removing duplicates .
10,571
def load_module ( self , path , squash = True ) : config_obj = load ( path ) obj = { key : getattr ( config_obj , key ) for key in dir ( config_obj ) if key . isupper ( ) } if squash : self . load_dict ( obj ) else : self . update ( obj ) return self
Load values from a Python module .
10,572
def _set_virtual ( self , key , value ) : if key in self and key not in self . _virtual_keys : return self . _virtual_keys . add ( key ) if key in self and self [ key ] is not value : self . _on_change ( key , value ) dict . __setitem__ ( self , key , value ) for overlay in self . _iter_overlays ( ) : overlay . _set_vi...
Recursively set or update virtual keys . Do nothing if non - virtual value is present .
10,573
def _delete_virtual ( self , key ) : if key not in self . _virtual_keys : return if key in self : self . _on_change ( key , None ) dict . __delitem__ ( self , key ) self . _virtual_keys . discard ( key ) for overlay in self . _iter_overlays ( ) : overlay . _delete_virtual ( key )
Recursively delete virtual entry . Do nothing if key is not virtual .
10,574
def meta_set ( self , key , metafield , value ) : self . _meta . setdefault ( key , { } ) [ metafield ] = value
Set the meta field for a key to a new value .
10,575
def filename ( self ) : fname = self . raw_filename if not isinstance ( fname , unicode ) : fname = fname . decode ( 'utf8' , 'ignore' ) fname = normalize ( 'NFKD' , fname ) fname = fname . encode ( 'ASCII' , 'ignore' ) . decode ( 'ASCII' ) fname = os . path . basename ( fname . replace ( '\\' , os . path . sep ) ) fna...
Name of the file on the client file system but normalized to ensure file system compatibility . An empty filename is returned as empty .
10,576
async def render ( text : TransText , request : Optional [ 'Request' ] , multi_line = False ) -> Union [ Text , List [ Text ] ] : if isinstance ( text , str ) : out = [ text ] elif isinstance ( text , StringToTranslate ) : out = await text . render_list ( request ) else : raise TypeError ( 'Provided text cannot be rend...
Render either a normal string either a string to translate into an actual string for the specified request .
10,577
def score ( self , flags : Flags ) -> int : score = 0 for k , v in flags . items ( ) : if self . flags . get ( k ) == v : score += 1 return score
Counts how many of the flags can be matched
10,578
def best_for_flags ( self , flags : Flags ) -> List [ TransItem ] : best_score : int = 0 best_list : List [ TransItem ] = [ ] for item in self . items : score = item . score ( flags ) if score == best_score : best_list . append ( item ) elif score > best_score : best_list = [ item ] best_score = score return best_list
Given flags find all items of this sentence that have an equal matching score and put them in a list .
10,579
def render ( self , flags : Flags ) -> Text : return random . choice ( self . best_for_flags ( flags ) ) . value
Chooses a random sentence from the list and returns it .
10,580
def update ( self , new : 'Sentence' , flags : Flags ) : items = [ i for i in self . items if i . flags != flags ] items . extend ( new . items ) self . items = items
Erase items with the specified flags and insert the new items from the other sentence instead .
10,581
def render ( self , flags : Flags ) -> List [ Text ] : return [ x . render ( flags ) for x in self . sentences ]
Returns a list of randomly chosen outcomes for each sentence of the list .
10,582
def append ( self , item : TransItem ) : if not ( 1 <= item . index <= settings . I18N_MAX_SENTENCES_PER_GROUP ) : return if len ( self . sentences ) < item . index : for _ in range ( len ( self . sentences ) , item . index ) : self . sentences . append ( Sentence ( ) ) self . sentences [ item . index - 1 ] . append ( ...
Append an item to the list . If there is not enough sentences in the list then the list is extended as needed .
10,583
def update ( self , group : 'SentenceGroup' , flags : Flags ) -> None : to_append = [ ] for old , new in zip_longest ( self . sentences , group . sentences ) : if old is None : old = Sentence ( ) to_append . append ( old ) if new is None : new = Sentence ( ) old . update ( new , flags ) self . sentences . extend ( to_a...
This object is considered to be a global sentence group while the other one is flags - specific . All data related to the specified flags will be overwritten by the content of the specified group .
10,584
def extract ( self ) : out = { } for key , group in self . data . items ( ) : out [ key ] = group return out
Extract only the valid sentence groups into a dictionary .
10,585
def append ( self , item : TransItem ) : self . data [ item . key ] . append ( item )
Append an item to the internal dictionary .
10,586
def _init_loaders ( self ) -> None : for loader in settings . I18N_TRANSLATION_LOADERS : loader_class = import_class ( loader [ 'loader' ] ) instance = loader_class ( ) instance . on_update ( self . update ) run ( instance . load ( ** loader [ 'params' ] ) )
This creates the loaders instances and subscribes to their updates .
10,587
def update_lang ( self , lang : Optional [ Text ] , data : List [ Tuple [ Text , Text ] ] , flags : Flags ) : sd = SortingDict ( ) for item in ( self . parse_item ( x [ 0 ] , x [ 1 ] , flags ) for x in data ) : if item : sd . append ( item ) if lang not in self . dict : self . dict [ lang ] = { } d = self . dict [ lang...
Update translations for one specific lang
10,588
def update ( self , data : TransDict , flags : Flags ) : for lang , lang_data in data . items ( ) : self . update_lang ( lang , lang_data , flags )
Update all langs at once
10,589
def get ( self , key : Text , count : Optional [ int ] = None , formatter : Formatter = None , locale : Text = None , params : Optional [ Dict [ Text , Any ] ] = None , flags : Optional [ Flags ] = None ) -> List [ Text ] : if params is None : params = { } if count is not None : raise TranslationError ( 'Count paramete...
Get the appropriate translation given the specified parameters .
10,590
async def _resolve_params ( self , params : Dict [ Text , Any ] , request : Optional [ 'Request' ] ) : out = { } for k , v in params . items ( ) : if isinstance ( v , StringToTranslate ) : out [ k ] = await render ( v , request ) else : out [ k ] = v return out
If any StringToTranslate was passed as parameter then it is rendered at this moment .
10,591
async def render_list ( self , request = None ) -> List [ Text ] : from bernard . middleware import MiddlewareManager if request : tz = await request . user . get_timezone ( ) locale = await request . get_locale ( ) flags = await request . get_trans_flags ( ) else : tz = None locale = self . wd . list_locales ( ) [ 0 ]...
Render the translation as a list if there is multiple strings for this single key .
10,592
def send ( self , stack : Layers ) : if not isinstance ( stack , Stack ) : stack = Stack ( stack ) if not self . platform . accept ( stack ) : raise UnacceptableStack ( 'The platform does not allow "{}"' . format ( stack . describe ( ) ) ) self . _stacks . append ( stack )
Add a message stack to the send list .
10,593
async def flush ( self , request : 'Request' ) : from bernard . middleware import MiddlewareManager for stack in self . _stacks : await stack . convert_media ( self . platform ) func = MiddlewareManager . instance ( ) . get ( 'flush' , self . _flush ) await func ( request , self . _stacks )
Send all queued messages .
10,594
async def make_transition_register ( self , request : 'Request' ) : register = { } for stack in self . _stacks : register = await stack . patch_register ( register , request ) return register
Use all underlying stacks to generate the next transition register .
10,595
def preloop ( self ) : lines = textwrap . dedent ( self . banner ) . split ( "\n" ) for line in lines : Console . _print ( "BLUE" , "" , line )
adds the banner to the preloop
10,596
def getDebt ( self ) : debt = float ( self [ 'principalBalance' ] ) + float ( self [ 'interestBalance' ] ) debt += float ( self [ 'feesBalance' ] ) + float ( self [ 'penaltyBalance' ] ) return debt
Sums up all the balances of the account and returns them .
10,597
def setRepayments ( self , * args , ** kwargs ) : def duedate ( repayment ) : try : return repayment [ 'dueDate' ] except KeyError as kerr : return datetime . now ( ) try : reps = self . mamburepaymentsclass ( entid = self [ 'id' ] , * args , ** kwargs ) except AttributeError as ae : from . mamburepayment import MambuR...
Adds the repayments for this loan to a repayments field .
10,598
def setTransactions ( self , * args , ** kwargs ) : def transactionid ( transaction ) : try : return transaction [ 'transactionId' ] except KeyError as kerr : return None try : trans = self . mambutransactionsclass ( entid = self [ 'id' ] , * args , ** kwargs ) except AttributeError as ae : from . mambutransaction impo...
Adds the transactions for this loan to a transactions field .
10,599
def setCentre ( self , * args , ** kwargs ) : try : centre = self . mambucentreclass ( entid = self [ 'assignedCentreKey' ] , * args , ** kwargs ) except AttributeError as ae : from . mambucentre import MambuCentre self . mambucentreclass = MambuCentre centre = self . mambucentreclass ( entid = self [ 'assignedCentreKe...
Adds the centre for this loan to a assignedCentre field .