signature
stringlengths
29
44.1k
implementation
stringlengths
0
85.2k
def run ( self ) : """Run the process . Iterate the GLib main loop and process the task queue ."""
loop = GLib . MainLoop ( ) context = loop . get_context ( ) while True : time . sleep ( 0.1 ) if context . pending ( ) : context . iteration ( ) self . _manager [ ATTR_POSITION ] = self . _position ( ) try : method , args = self . _task_queue . get ( False ) getattr ( self , ...
def boot_device ( name = 'default' , ** kwargs ) : '''Request power state change name = ` ` default ` ` * network - - Request network boot * hd - - Boot from hard drive * safe - - Boot from hard drive , requesting ' safe mode ' * optical - - boot from CD / DVD / BD drive * setup - - Boot into setup util...
ret = { 'name' : name , 'result' : False , 'comment' : '' , 'changes' : { } } org = __salt__ [ 'ipmi.get_bootdev' ] ( ** kwargs ) if 'bootdev' in org : org = org [ 'bootdev' ] if org == name : ret [ 'result' ] = True ret [ 'comment' ] = 'system already in this state' return ret if __opts__ [ 'test' ] : ...
def get_instance ( self , payload ) : """Build an instance of WorkspaceStatisticsInstance : param dict payload : Payload response from the API : returns : twilio . rest . taskrouter . v1 . workspace . workspace _ statistics . WorkspaceStatisticsInstance : rtype : twilio . rest . taskrouter . v1 . workspace . ...
return WorkspaceStatisticsInstance ( self . _version , payload , workspace_sid = self . _solution [ 'workspace_sid' ] , )
def configurate_app ( config_file = '' ) : """Configures Flask app : param config _ file : Absolute path to Py config file , optional : returns : App object , host and port"""
# Load config app . config . from_pyfile ( 'defaults.py' ) app . config . from_pyfile ( config_file , silent = True ) if app . config . get ( 'MINIFY_HTML' , False ) : app . jinja_env . add_extension ( 'flask_utils.jinja2htmlcompress.HTMLCompress' ) # Setup web assets assets = Environment ( app ) js = Bundle ( 'com...
def set_response_cookie ( response , cookie_name , cookie_value ) : """Common function for setting the cookie in the response . Provides a common policy of setting cookies for last used project and region , can be reused in other locations . This method will set the cookie to expire in 365 days ."""
now = timezone . now ( ) expire_date = now + datetime . timedelta ( days = 365 ) response . set_cookie ( cookie_name , cookie_value , expires = expire_date )
def check_signature ( token , signature , timestamp , nonce ) : """Check WeChat callback signature , raises InvalidSignatureException if check failed . : param token : WeChat callback token : param signature : WeChat callback signature sent by WeChat server : param timestamp : WeChat callback timestamp sent...
signer = WeChatSigner ( ) signer . add_data ( token , timestamp , nonce ) if signer . signature != signature : from wechatpy . exceptions import InvalidSignatureException raise InvalidSignatureException ( )
def power_elements ( elements : list , power : int ) -> list : """The function calculates power of each element in a provided list . This function utilizes a lambda function for the power calculation . Args : elements : A list of integers . power : The power to which each element should be raised . Return...
powered_elements = list ( map ( lambda x : x ** power , elements ) ) return powered_elements
def move ( self , target_parent , name = None , include_children = True , include_instances = True ) : """Move the ` Part ` to target parent , both of them the same category . . . versionadded : : 2.3 : param target _ parent : ` Part ` object under which the desired ` Part ` is moved : type target _ parent : ...
if not name : name = self . name if self . category == Category . MODEL and target_parent . category == Category . MODEL : moved_model = relocate_model ( part = self , target_parent = target_parent , name = name , include_children = include_children ) if include_instances : retrieve_instances_to_cop...
def get_child_content ( self , children , element_name ) : """Get the requested element content from a list of children ."""
# Loop through the children and get the specified element . for child in children : # If the child is the requested element , return its content . if child . tag == element_name : return child . content return ''
def sample_row_keys ( self ) : """Read a sample of row keys in the table . For example : . . literalinclude : : snippets _ table . py : start - after : [ START bigtable _ sample _ row _ keys ] : end - before : [ END bigtable _ sample _ row _ keys ] The returned row keys will delimit contiguous sections of...
data_client = self . _instance . _client . table_data_client response_iterator = data_client . sample_row_keys ( self . name , app_profile_id = self . _app_profile_id ) return response_iterator
def _pathway_feature_permutation ( pathway_feature_tuples , permutation_max_iters ) : """Permute the pathways across features for one side in the network . Used in ` permute _ pathways _ across _ features ` Parameters pathway _ feature _ tuples : list ( tup ( str , int ) ) a tuple list [ ( pathway , feature...
pathways , features = [ list ( elements_at_position ) for elements_at_position in zip ( * pathway_feature_tuples ) ] original_pathways = pathways [ : ] random . shuffle ( pathways ) feature_block_locations = { } i = 0 while i < len ( pathways ) : starting_index = i current_feature = features [ i ] pathway_s...
def export_disks ( self , standalone = True , dst_dir = None , compress = False , collect_only = False , with_threads = True , * args , ** kwargs ) : """Thin method that just uses the provider"""
return self . provider . export_disks ( standalone , dst_dir , compress , collect_only , with_threads , * args , ** kwargs )
def plateid6 ( self , filetype , ** kwargs ) : """Print plate ID , accounting for 5-6 digit plate IDs . Parameters filetype : str File type parameter . plateid : int or str Plate ID number . Will be converted to int internally . Returns plateid6 : str Plate ID formatted to a string of 6 characters ....
plateid = int ( kwargs [ 'plateid' ] ) if plateid < 10000 : return "{:0>6d}" . format ( plateid ) else : return "{:d}" . format ( plateid )
def hog ( img , options = None ) : """HOG feature extractor . : param img : : param options : : return : HOG Feature for given image The output will have channels same as number of orientations . Height and Width will be reduced based on block - size and cell - size"""
op = _DEF_HOG_OPTS . copy ( ) if options is not None : op . update ( options ) img = gray ( img ) img_fd = skimage . feature . hog ( img , orientations = op [ 'orientations' ] , pixels_per_cell = op [ 'cell_size' ] , cells_per_block = op [ 'block_size' ] , visualise = False ) h , w = img . shape cx , cy = op [ 'cel...
def changeThreadTitle ( self , title , thread_id = None , thread_type = ThreadType . USER ) : """Changes title of a thread . If this is executed on a user thread , this will change the nickname of that user , effectively changing the title : param title : New group thread title : param thread _ id : Group ID ...
thread_id , thread_type = self . _getThread ( thread_id , thread_type ) if thread_type == ThreadType . USER : # The thread is a user , so we change the user ' s nickname return self . changeNickname ( title , thread_id , thread_id = thread_id , thread_type = thread_type ) data = { "thread_name" : title , "thread_id...
def import_signed ( cls , name , certificate , private_key , intermediate = None ) : """Import a signed certificate and private key to SMC , and optionally an intermediate certificate . The certificate and the associated private key must be compatible with OpenSSL and be in PEM format . The certificate and pr...
tls = TLSServerCredential . create ( name ) try : tls . import_certificate ( certificate ) tls . import_private_key ( private_key ) if intermediate is not None : tls . import_intermediate_certificate ( intermediate ) except CertificateImportError : tls . delete ( ) raise return tls
def get ( * dataset , ** kwargs ) : '''Displays properties for the given datasets . dataset : string name of snapshot ( s ) , filesystem ( s ) , or volume ( s ) properties : string comma - separated list of properties to list , defaults to all recursive : boolean recursively list children depth : int ...
# # Configure command # NOTE : initialize the defaults flags = [ '-H' ] opts = { } # NOTE : set extra config from kwargs if kwargs . get ( 'depth' , False ) : opts [ '-d' ] = kwargs . get ( 'depth' ) elif kwargs . get ( 'recursive' , False ) : flags . append ( '-r' ) fields = kwargs . get ( 'fields' , 'value,so...
def bcftoolsMpileup ( outFile , referenceFile , alignmentFile , executor ) : """Use bcftools mpileup to generate VCF . @ param outFile : The C { str } name to write the output to . @ param referenceFile : The C { str } name of the FASTA file with the reference sequence . @ param alignmentFile : The C { str ...
executor . execute ( 'bcftools mpileup -Ov -f %s %s > %s' % ( referenceFile , alignmentFile , outFile ) )
def left_outer ( self ) : """Performs Left Outer Join : return left _ outer : dict"""
self . get_collections_data ( ) left_outer_join = self . merge_join_docs ( set ( self . collections_data [ 'left' ] . keys ( ) ) ) return left_outer_join
def schema ( self ) : """The generated budget data package schema for this resource . If the resource has any fields that do not conform to the provided specification this will raise a NotABudgetDataPackageException ."""
if self . headers is None : raise exceptions . NoResourceLoadedException ( 'Resource must be loaded to find schema' ) try : fields = self . specification . get ( 'fields' , { } ) parsed = { 'primaryKey' : 'id' , 'fields' : [ { 'name' : header , 'type' : fields [ header ] [ 'type' ] , 'description' : fields ...
def _from_objects ( cls , objects ) : """Private constructor : create graph from the given Python objects . The constructor examines the referents of each given object to build up a graph showing the objects and their links ."""
vertices = ElementTransformSet ( transform = id ) out_edges = KeyTransformDict ( transform = id ) in_edges = KeyTransformDict ( transform = id ) for obj in objects : vertices . add ( obj ) out_edges [ obj ] = [ ] in_edges [ obj ] = [ ] # Edges are identified by simple integers , so # we can use plain dictio...
def reset_to_default ( self ) : """Restore initial values for default color schemes ."""
# Checks that this is indeed a default scheme scheme = self . current_scheme names = self . get_option ( 'names' ) if scheme in names : for key in syntaxhighlighters . COLOR_SCHEME_KEYS : option = "{0}/{1}" . format ( scheme , key ) value = CONF . get_default ( self . CONF_SECTION , option ) ...
def request_token ( ) : """通过帐号 , 密码请求token , 返回一个dict " user _ info " : { " ck " : " - VQY " , " play _ record " : { " fav _ chls _ count " : 4, " liked " : 802, " banned " : 162, " played " : 28368 " is _ new _ user " : 0, " uid " : " taizilongxu " , " third _ party _ info " : null , " url "...
while True : email , password , captcha_solution , captcha_id = win_login ( ) options = { 'source' : 'radio' , 'alias' : email , 'form_password' : password , 'captcha_solution' : captcha_solution , 'captcha_id' : captcha_id , 'task' : 'sync_channel_list' } r = requests . post ( 'https://douban.fm/j/login' ,...
def geo_search ( user_id , search_location ) : """Search for a location - free form"""
url = "https://api.twitter.com/1.1/geo/search.json" params = { "query" : search_location } response = make_twitter_request ( url , user_id , params ) . json ( ) return response
def reset ( self ) : """Reset the game so the grid is zeros ( or default items )"""
self . grid = [ [ 0 for dummy_l in range ( self . grid_width ) ] for dummy_l in range ( self . grid_height ) ]
def drop ( self , format_p , action ) : """Informs the source that a drop event occurred for a pending drag and drop operation . in format _ p of type str The mime type the data must be in . in action of type : class : ` DnDAction ` The action to use . return progress of type : class : ` IProgress ` P...
if not isinstance ( format_p , basestring ) : raise TypeError ( "format_p can only be an instance of type basestring" ) if not isinstance ( action , DnDAction ) : raise TypeError ( "action can only be an instance of type DnDAction" ) progress = self . _call ( "drop" , in_p = [ format_p , action ] ) progress = I...
def read ( self , n = None ) : """Read at most * n * characters from this stream . If * n * is ` ` None ` ` , return all available characters ."""
response = b"" while len ( self . streams ) > 0 and ( n is None or n > 0 ) : txt = self . streams [ 0 ] . read ( n ) response += txt if n is not None : n -= len ( txt ) if n is None or n > 0 : del self . streams [ 0 ] return response
def recall_score ( gold , pred , pos_label = 1 , ignore_in_gold = [ ] , ignore_in_pred = [ ] ) : """Calculate recall for a single class . Args : gold : A 1d array - like of gold labels pred : A 1d array - like of predicted labels ( assuming abstain = 0) ignore _ in _ gold : A list of labels for which elemen...
gold , pred = _preprocess ( gold , pred , ignore_in_gold , ignore_in_pred ) positives = np . where ( pred == pos_label , 1 , 0 ) . astype ( bool ) trues = np . where ( gold == pos_label , 1 , 0 ) . astype ( bool ) TP = np . sum ( positives * trues ) FN = np . sum ( np . logical_not ( positives ) * trues ) if TP or FN :...
def run ( self , points = 25 , start = None , stop = None ) : r"""Runs the percolation algorithm to determine which pores and throats will be invaded at each given pressure point . Parameters points : int or array _ like An array containing the pressure points to apply . If a scalar is given then an array...
phase = self . project . find_phase ( self ) # Parse inputs and generate list of invasion points if necessary if self . settings [ 'mode' ] == 'bond' : self [ 'throat.entry_pressure' ] = phase [ self . settings [ 'throat_entry_threshold' ] ] if start is None : start = sp . amin ( self [ 'throat.entry_pr...
def solve ( self , value , args = None , kwargs = None ) : """Try to get the current attribute / function result for the given value . If ` ` args ` ` or ` ` kwargs ` ` are passed , the attribute got from ` ` value ` ` must be callable . They will be passed anyway ( using ` ` [ ] ` ` and ` ` { } ` ` as default ...
# If we have a function , apply this , using the value as first argument , # then args and kwargs . if self . function : try : return self . function ( value , * ( args or [ ] ) , ** ( kwargs or { } ) ) except Exception as ex : raise CallableError ( self , value , args , kwargs , ex ) # Manage a...
def fetch ( self , seq_id , start = None , end = None ) : """fetch sequence by seq _ id , optionally with start , end bounds"""
rec = self . _db . execute ( """select * from seqinfo where seq_id = ? order by added desc""" , [ seq_id ] ) . fetchone ( ) if rec is None : raise KeyError ( seq_id ) if self . _writing and self . _writing [ "relpath" ] == rec [ "relpath" ] : logger . warning ( """Fetching from file opened for writing; ...
def _quit ( self , * args ) : """quit crash"""
self . logger . warn ( 'Bye!' ) sys . exit ( self . exit ( ) )
def getargspec_no_self ( func ) : """inspect . getargspec replacement using inspect . signature . inspect . getargspec is deprecated in python 3 . This is a replacement based on the ( new in python 3.3 ) ` inspect . signature ` . Parameters func : callable A callable to inspect Returns argspec : ArgSp...
sig = inspect . signature ( func ) args = [ p . name for p in sig . parameters . values ( ) if p . kind == inspect . Parameter . POSITIONAL_OR_KEYWORD ] varargs = [ p . name for p in sig . parameters . values ( ) if p . kind == inspect . Parameter . VAR_POSITIONAL ] varargs = varargs [ 0 ] if varargs else None varkw = ...
def pic_loggedrequiredremoterelease_v2 ( self ) : """Update the receiver link sequence ."""
log = self . sequences . logs . fastaccess rec = self . sequences . receivers . fastaccess log . loggedrequiredremoterelease [ 0 ] = rec . s [ 0 ]
def resume_job ( job_id ) : """Resumes a job ."""
try : current_app . apscheduler . resume_job ( job_id ) job = current_app . apscheduler . get_job ( job_id ) return jsonify ( job ) except JobLookupError : return jsonify ( dict ( error_message = 'Job %s not found' % job_id ) , status = 404 ) except Exception as e : return jsonify ( dict ( error_mes...
def endpoint_name ( self , endpoint_name ) : """Sets the endpoint _ name of this PreSharedKey . The unique endpoint identifier that this pre - shared key applies to . 16-64 [ printable ] ( https : / / en . wikipedia . org / wiki / ASCII # Printable _ characters ) ( non - control ) ASCII characters . : param end...
if endpoint_name is None : raise ValueError ( "Invalid value for `endpoint_name`, must not be `None`" ) if endpoint_name is not None and not re . search ( '^[ -~]{16,64}$' , endpoint_name ) : raise ValueError ( "Invalid value for `endpoint_name`, must be a follow pattern or equal to `/^[ -~]{16,64}$/`" ) self ....
def hangup ( self ) : """End the phone call . Does nothing if the call is already inactive ."""
if self . active : self . _gsmModem . write ( 'ATH' ) self . answered = False self . active = False if self . id in self . _gsmModem . activeCalls : del self . _gsmModem . activeCalls [ self . id ]
def describe_api_keys ( region = None , key = None , keyid = None , profile = None ) : '''Gets information about the defined API Keys . Return list of apiKeys . CLI Example : . . code - block : : bash salt myminion boto _ apigateway . describe _ api _ keys'''
try : conn = _get_conn ( region = region , key = key , keyid = keyid , profile = profile ) apikeys = _multi_call ( conn . get_api_keys , 'items' ) return { 'apiKeys' : [ _convert_datetime_str ( apikey ) for apikey in apikeys ] } except ClientError as e : return { 'error' : __utils__ [ 'boto3.get_error' ...
def close ( self ) : """Cleanly shut down the SSL protocol and close the transport ."""
if self . _closing or self . _handle . closed : return self . _closing = True self . _write_backlog . append ( [ b'' , False ] ) self . _process_write_backlog ( )
def export_obj ( surface , file_name , ** kwargs ) : """Exports surface ( s ) as a . obj file . Keyword Arguments : * ` ` vertex _ spacing ` ` : size of the triangle edge in terms of surface points sampled . * Default : 2* * ` ` vertex _ normals ` ` : if True , then computes vertex normals . * Default : False...
content = export_obj_str ( surface , ** kwargs ) return exch . write_file ( file_name , content )
def verify_proxy_ticket ( ticket , service ) : """Verifies CAS 2.0 + XML - based proxy ticket . : param : ticket : param : service Returns username on success and None on failure ."""
params = { 'ticket' : ticket , 'service' : service } url = ( urljoin ( settings . CAS_SERVER_URL , 'proxyValidate' ) + '?' + urlencode ( params ) ) page = urlopen ( url ) try : response = page . read ( ) tree = ElementTree . fromstring ( response ) if tree [ 0 ] . tag . endswith ( 'authenticationSuccess' ) ...
def cli ( env , identifier , ack ) : """Details of a specific event , and ability to acknowledge event ."""
# Print a list of all on going maintenance manager = AccountManager ( env . client ) event = manager . get_event ( identifier ) if ack : manager . ack_event ( identifier ) env . fout ( basic_event_table ( event ) ) env . fout ( impacted_table ( event ) ) env . fout ( update_table ( event ) )
def funTransEdgeY ( theta , rho ) : """Fringe matrix in Y : param theta : fringe angle , in [ rad ] : param rho : bend radius , in [ m ] : return : 2x2 numpy array"""
return np . matrix ( [ [ 1 , 0 ] , [ - np . tan ( theta ) / rho , 1 ] ] , dtype = np . double )
def _cmd_run ( cmd , as_json = False ) : '''Ensure that the Pki module is loaded , and convert to and extract data from Json as needed .'''
cmd_full = [ 'Import-Module -Name PKI; ' ] if as_json : cmd_full . append ( r'ConvertTo-Json -Compress -Depth 4 -InputObject ' r'@({0})' . format ( cmd ) ) else : cmd_full . append ( cmd ) cmd_ret = __salt__ [ 'cmd.run_all' ] ( six . text_type ( ) . join ( cmd_full ) , shell = 'powershell' , python_shell = True...
def rc ( self ) : """Flip the direction"""
ntx = self . copy ( ) newstrand = '+' if ntx . strand == '+' : newstrand = '-' ntx . _options = ntx . _options . _replace ( direction = newstrand ) return ntx
def get_gui_hint ( self , hint ) : """Returns the value for specified gui hint ( or a sensible default value , if this argument doesn ' t specify the hint ) . Args : hint : name of the hint to get value for Returns : value of the hint specified in yaml or a sensible default"""
if hint == 'type' : # ' self . kwargs . get ( ' nargs ' ) = = 0 ' is there for default _ iff _ used , which may # have nargs : 0 , so that it works similarly to ' store _ const ' if self . kwargs . get ( 'action' ) == 'store_true' or self . kwargs . get ( 'nargs' ) == 0 : return 'bool' # store _ const i...
def FileEntryExistsByPathSpec ( self , path_spec ) : """Determines if a file entry for a path specification exists . Args : path _ spec ( PathSpec ) : path specification . Returns : bool : True if the file entry exists . Raises : BackEndError : if the file entry cannot be opened ."""
# Opening a file by identifier is faster than opening a file by location . fsapfs_file_entry = None location = getattr ( path_spec , 'location' , None ) identifier = getattr ( path_spec , 'identifier' , None ) try : if identifier is not None : fsapfs_file_entry = self . _fsapfs_volume . get_file_entry_by_id...
def recompute_mag ( mpc_in , skip_centroids = False ) : """Get the mag of the object given the mp _ ephem . ephem . Observation"""
# TODO this really shouldn ' t need to build a ' reading ' to get the cutout . . . from ossos . downloads . cutouts import downloader dlm = downloader . ImageCutoutDownloader ( ) mpc_obs = deepcopy ( mpc_in ) assert isinstance ( mpc_obs , mp_ephem . ephem . Observation ) assert isinstance ( mpc_obs . comment , mp_ephem...
def on_batch_begin ( self , last_input , last_target , train , ** kwargs ) : "Applies mixup to ` last _ input ` and ` last _ target ` if ` train ` ."
if not train : return lambd = np . random . beta ( self . alpha , self . alpha , last_target . size ( 0 ) ) lambd = np . concatenate ( [ lambd [ : , None ] , 1 - lambd [ : , None ] ] , 1 ) . max ( 1 ) lambd = last_input . new ( lambd ) shuffle = torch . randperm ( last_target . size ( 0 ) ) . to ( last_input . devi...
def _function ( self ) : """This is the actual function that will be executed . It uses only information that is provided in the settings property will be overwritten in the _ _ init _ _"""
# some generic function import time import random self . data [ 'random data' ] = None self . data [ 'image data' ] = None count = self . settings [ 'count' ] name = self . settings [ 'name' ] wait_time = self . settings [ 'wait_time' ] data = [ ] self . log ( 'I ({:s}) am a test function counting to {:d} and creating ...
def load_cloudupdrs_data ( filename , convert_times = 1000000000.0 ) : """This method loads data in the cloudupdrs format Usually the data will be saved in a csv file and it should look like this : . . code - block : : json timestamp _ 0 , x _ 0 , y _ 0 , z _ 0 timestamp _ 1 , x _ 1 , y _ 1 , z _ 1 timest...
# data _ m = pd . read _ table ( filename , sep = ' , ' , header = None ) try : data_m = np . genfromtxt ( filename , delimiter = ',' , invalid_raise = False ) date_times = pd . to_datetime ( ( data_m [ : , 0 ] - data_m [ 0 , 0 ] ) ) time_difference = ( data_m [ : , 0 ] - data_m [ 0 , 0 ] ) / convert_times ...
def run_via_api ( self , container_params = None ) : """create a container using this image and run it in background via Docker - py API . https : / / docker - py . readthedocs . io / en / stable / api . html Note : If you are using Healthchecks , be aware that support of some options were introduced just wit...
if not container_params : container_params = DockerContainerParameters ( ) # Host - specific configuration host_config = self . d . create_host_config ( auto_remove = container_params . remove , cap_add = container_params . cap_add , cap_drop = container_params . cap_drop , devices = container_params . devices , dn...
def get_bin_indices ( self , values ) : """Returns index tuple in histogram of bin which contains value"""
return tuple ( [ self . get_axis_bin_index ( values [ ax_i ] , ax_i ) for ax_i in range ( self . dimensions ) ] )
def palette ( self ) : """Converts the current color data to a QPalette . : return < QPalette >"""
palette = QPalette ( ) for colorGroup , qColorGroup in self . GroupMapping . items ( ) : for colorRole , qColorRole in self . RoleMapping . items ( ) : color = self . color ( colorRole , colorGroup ) palette . setColor ( qColorGroup , qColorRole , color ) return palette
def train_phrases ( paths , out = 'data/bigram_model.phrases' , tokenizer = word_tokenize , ** kwargs ) : """Train a bigram phrase model on a list of files ."""
n = 0 for path in paths : print ( 'Counting lines for {0}...' . format ( path ) ) n += sum ( 1 for line in open ( path , 'r' ) ) print ( 'Processing {0} lines...' . format ( n ) ) # Change to use less memory . Default is 40m . kwargs = { 'max_vocab_size' : 40000000 , 'threshold' : 8. } . update ( kwargs ) print...
def as_artist ( self , origin = ( 0 , 0 ) , ** kwargs ) : """Matplotlib Text object for this region ( ` matplotlib . text . Text ` ) . Parameters origin : array _ like , optional The ` ` ( x , y ) ` ` pixel position of the origin of the displayed image . Default is ( 0 , 0 ) . kwargs : ` dict ` All keyw...
from matplotlib . text import Text mpl_params = self . mpl_properties_default ( 'text' ) mpl_params . update ( kwargs ) text = Text ( self . center . x - origin [ 0 ] , self . center . y - origin [ 1 ] , self . text , ** mpl_params ) return text
def enable_tk ( self , app = None ) : """Enable event loop integration with Tk . Parameters app : toplevel : class : ` Tkinter . Tk ` widget , optional . Running toplevel widget to use . If not given , we probe Tk for an existing one , and create a new one if none is found . Notes If you have already cr...
self . _current_gui = GUI_TK if app is None : try : import Tkinter as _TK except : # Python 3 import tkinter as _TK # @ UnresolvedImport app = _TK . Tk ( ) app . withdraw ( ) self . _apps [ GUI_TK ] = app from pydev_ipython . inputhooktk import create_inputhook_tk self . set_...
def describe ( self , name = None ) : """Cleanly show what the four displayed distribution moments are : - Mean - Variance - Standardized Skewness Coefficient - Standardized Kurtosis Coefficient For a standard Normal distribution , these are [ 0 , 1 , 0 , 3 ] . If the object has an associated tag , this...
mn , vr , sk , kt = self . stats if name is not None : s = "MCERP Uncertain Value (" + name + "):\n" elif self . tag is not None : s = "MCERP Uncertain Value (" + self . tag + "):\n" else : s = "MCERP Uncertain Value:\n" s += " > Mean................... {: }\n" . format ( mn ) s += " > Variance................
def create_singlefile_standard ( archive , compression , cmd , verbosity , interactive , filenames ) : """Standard routine to create a singlefile archive ( like gzip ) ."""
cmdlist = [ util . shell_quote ( cmd ) ] if verbosity > 1 : cmdlist . append ( '-v' ) cmdlist . extend ( [ '-c' , '--' ] ) cmdlist . extend ( [ util . shell_quote ( x ) for x in filenames ] ) cmdlist . extend ( [ '>' , util . shell_quote ( archive ) ] ) return ( cmdlist , { 'shell' : True } )
def delete ( self , lookup ) : """If exactly one quote matches , delete it . Otherwise , raise a ValueError ."""
lookup , num = self . split_num ( lookup ) if num : result = self . find_matches ( lookup ) [ num - 1 ] else : result , = self . find_matches ( lookup ) self . db . delete_one ( result )
def _Uniform ( self , triplist ) : """Fallback to assuming uniform distance between stations"""
# This should not be neseccary , but we are in fallback mode longest = max ( [ len ( t . GetTimeStops ( ) ) for t in triplist ] ) return [ 100 ] * longest
def global_pool_1d ( inputs , pooling_type = "MAX" , mask = None ) : """Pool elements across the last dimension . Useful to convert a list of vectors into a single vector so as to get a representation of a set . Args : inputs : A tensor of shape [ batch _ size , sequence _ length , input _ dims ] containi...
with tf . name_scope ( "global_pool" , values = [ inputs ] ) : if mask is not None : mask = tf . expand_dims ( mask , axis = 2 ) inputs = tf . multiply ( inputs , mask ) if pooling_type == "MAX" : # A tf . pool can be used here , but reduce is cleaner output = tf . reduce_max ( inputs , ...
def read ( self ) : """We have been called to read ! As a consumer , continue to read for the length of the packet and then pass to the callback ."""
data = self . dev . read ( ) if len ( data ) == 0 : self . log . warning ( "READ : Nothing received" ) return if data == b'\x00' : self . log . warning ( "READ : Empty packet (Got \\x00)" ) return pkt = bytearray ( data ) data = self . dev . read ( pkt [ 0 ] ) pkt . extend ( bytearray ( data ) ) self . ...
def check_password ( self , raw_password ) : """Validates the given raw password against the intance ' s encrypted one . : param raw _ password : Raw password to be checked against . : type raw _ password : unicode : returns : True if comparison was successful , False otherwise . : rtype : bool : raises :...
bcrypt = self . get_bcrypt ( ) return bcrypt . hashpw ( raw_password , self . value ) == self . value
def fpp_config ( koi , ** kwargs ) : """returns config object for given KOI"""
folder = os . path . join ( KOI_FPPDIR , ku . koiname ( koi ) ) if not os . path . exists ( folder ) : os . makedirs ( folder ) config = ConfigObj ( os . path . join ( folder , 'fpp.ini' ) ) koi = ku . koiname ( koi ) rowefit = jrowe_fit ( koi ) config [ 'name' ] = koi ra , dec = ku . radec ( koi ) config [ 'ra' ] ...
def run ( self ) : """Main service entrypoint . Called via Thread . start ( ) via PantsDaemon . run ( ) ."""
if not ( self . _watchman and self . _watchman . is_alive ( ) ) : raise PantsService . ServiceError ( 'watchman is not running, bailing!' ) # Enable watchman for the build root . self . _watchman . watch_project ( self . _build_root ) subscriptions = list ( self . _handlers . values ( ) ) # Setup subscriptions and ...
def get_inline_choice_ids ( self ) : """stub"""
return_data = { } for inline_region , data in self . my_osid_object . _my_map [ 'inlineRegions' ] . items ( ) : return_data [ inline_region ] = { 'choiceIds' : IdList ( data [ 'choiceIds' ] ) } return return_data
def _generate_identifier_name ( self , columns , prefix = "" , max_size = 30 ) : """Generates an identifier from a list of column names obeying a certain string length ."""
hash = "" for column in columns : hash += "%x" % binascii . crc32 ( encode ( str ( column ) ) ) return ( prefix + "_" + hash ) [ : max_size ]
def bz2_pack ( source ) : """Returns ' source ' as a bzip2 - compressed , self - extracting python script . . . note : : This method uses up more space than the zip _ pack method but it has the advantage in that the resulting . py file can still be imported into a python program ."""
import bz2 , base64 out = "" # Preserve shebangs ( don ' t care about encodings for this ) first_line = source . split ( '\n' ) [ 0 ] if analyze . shebang . match ( first_line ) : if py3 : if first_line . rstrip ( ) . endswith ( 'python' ) : # Make it python3 first_line = first_line . rstrip ( )...
def brpop ( self , keys , timeout = 0 ) : """Emulate brpop"""
return self . _blocking_pop ( self . rpop , keys , timeout )
def _exclude ( self , member ) : '''Exclude based on opts'''
if isinstance ( member , string_types ) : return None for item in self . opts [ 'spm_build_exclude' ] : if member . name . startswith ( '{0}/{1}' . format ( self . formula_conf [ 'name' ] , item ) ) : return None elif member . name . startswith ( '{0}/{1}' . format ( self . abspath , item ) ) : ...
def _generate_doxygen ( doxygen_input ) : '''This method executes doxygen based off of the specified input . By the time this method is executed , it is assumed that Doxygen is intended to be run in the * * current working directory * * . Search for ` ` returnPath ` ` in the implementation of : func : ` ~ exh...
if not isinstance ( doxygen_input , six . string_types ) : return "Error: the `doxygen_input` variable must be of type `str`." doxyfile = doxygen_input == "Doxyfile" try : # Setup the arguments to launch doxygen if doxyfile : args = [ "doxygen" ] kwargs = { } else : args = [ "doxygen...
def row ( cls , pitch , pa , pitch_list , ball_tally , strike_tally ) : """Pitching Result Pitch f / x fields : https : / / fastballs . wordpress . com / category / pitchfx - glossary / : param pitch : pitch object ( type : Beautifulsoup ) : param pa : At bat data for pa ( dict ) : param pitch _ list : Pitc...
pitch_res = MlbamUtil . get_attribute_stats ( pitch , 'type' , str , MlbamConst . UNKNOWN_FULL ) pitch_seq = [ pitch [ 'pitch_res' ] for pitch in pitch_list ] pitch_seq . extend ( [ pitch_res ] ) pitch_type = MlbamUtil . get_attribute_stats ( pitch , 'pitch_type' , str , MlbamConst . UNKNOWN_SHORT ) pitch_type_seq = [ ...
def _expand_placeholder_value ( value ) : """Return the SQL string representation of the specified placeholder ' s value . @ param value : the value of a placeholder such as a simple element , a list , or a tuple of one string . @ note : by convention , a tuple of one string indicates that this string MUS...
if isinstance ( value , ( list , set ) ) or ( isinstance ( value , tuple ) and len ( value ) != 1 ) : sql_value = ',' . join ( [ RdbmsConnection . _to_sql_value ( element if not isinstance ( element , tuple ) else element [ 0 ] , noquote = isinstance ( element , tuple ) ) for element in value ] ) elif isinstance ( ...
def _inherit_attr ( klass , attr , default , cp ) : """Inherit the attribute from the base class Copy ` attr ` from base class ( otherwise use ` default ` ) . Copying is done using the passed ` cp ` function . The motivation behind writing this function is to allow inheritance among Cmdln classes where base...
if attr not in klass . __dict__ : if hasattr ( klass , attr ) : value = cp ( getattr ( klass , attr ) ) else : value = default setattr ( klass , attr , value )
def init ( self , force_deploy = False , client = None ) : """Reserve and deploys the nodes according to the resources section In comparison to the vagrant provider , networks must be characterized as in the networks key . Args : force _ deploy ( bool ) : True iff the environment must be redeployed Raises...
_force_deploy = self . provider_conf . force_deploy self . provider_conf . force_deploy = _force_deploy or force_deploy self . _provider_conf = self . provider_conf . to_dict ( ) r = api . Resources ( self . _provider_conf , client = client ) r . launch ( ) roles = r . get_roles ( ) networks = r . get_networks ( ) retu...
def get_primary_key ( model ) : """Get the name of the field in a model that has primary _ key = True"""
model = get_model ( model ) return ( field . name for field in model . _meta . fields if field . primary_key ) . next ( )
def configure_typogrify ( pelicanobj , mathjax_settings ) : """Instructs Typogrify to ignore math tags - which allows Typogrify to play nicely with math related content"""
# If Typogrify is not being used , then just exit if not pelicanobj . settings . get ( 'TYPOGRIFY' , False ) : return try : import typogrify from distutils . version import LooseVersion if LooseVersion ( typogrify . __version__ ) < LooseVersion ( '2.0.7' ) : raise TypeError ( 'Incorrect version ...
def recClearTag ( element ) : """Applies maspy . xml . clearTag ( ) to the tag attribute of the " element " and recursively to all child elements . : param element : an : instance : ` xml . etree . Element `"""
children = element . getchildren ( ) if len ( children ) > 0 : for child in children : recClearTag ( child ) element . tag = clearTag ( element . tag )
async def save_session ( # type : ignore self , app : 'Quart' , session : SecureCookieSession , response : Response , ) -> None : """Saves the session to the response in a secure cookie ."""
domain = self . get_cookie_domain ( app ) path = self . get_cookie_path ( app ) if not session : if session . modified : response . delete_cookie ( app . session_cookie_name , domain = domain , path = path ) return if session . accessed : response . vary . add ( 'Cookie' ) if not self . should_set_c...
def _edge_in_front ( self , edge ) : """Return the index where * edge * appears in the current front . If the edge is not in the front , return - 1"""
e = ( list ( edge ) , list ( edge ) [ : : - 1 ] ) for i in range ( len ( self . _front ) - 1 ) : if self . _front [ i : i + 2 ] in e : return i return - 1
def read_laminaprop ( laminaprop = None , rho = None ) : """Returns a ` ` MatLamina ` ` object based on an input ` ` laminaprop ` ` tuple Parameters laminaprop : list or tuple Tuple containing the folliwing entries : ( e1 , e2 , nu12 , g12 , g13 , g23 , e3 , nu13 , nu23) for othotropic materials the user ...
matlam = MatLamina ( ) # laminaProp = ( e1 , e2 , nu12 , g12 , g13 , g23 , e3 , nu13 , nu23) if laminaprop == None : error ( 'laminaprop must be a tuple in the following format:\n\t' + '(e1, e2, nu12, g12, g13, g23, e3, nu13, nu23)' ) if len ( laminaprop ) == 3 : # ISOTROPIC e = laminaprop [ 0 ] nu = lamina...
def get_time ( self , idx ) : """Return time of data at index ` idx ` Returns nan if the time is not defined"""
# raw data qpi = self . get_qpimage_raw ( idx ) if "time" in qpi . meta : thetime = qpi . meta [ "time" ] else : thetime = np . nan return thetime
def create ( cls , * args , ** kwargs ) : """Creates an LXC"""
container = LXC . create ( * args , ** kwargs ) return container
def _ttr ( self , kloc , cache , ** kwargs ) : """Example : > > > dist = chaospy . J ( chaospy . Uniform ( ) , chaospy . Normal ( ) , chaospy . Exponential ( ) ) > > > print ( numpy . around ( dist . ttr ( [ [ 1 , 2 , 3 ] , [ 1 , 2 , 3 ] , [ 1 , 2 , 3 ] ] ) , 4 ) ) [ [ [ 0.5 0.5 0.5 ] [0.0833 0.0667 0.0643]...
if evaluation . get_dependencies ( * list ( self . inverse_map ) ) : raise StochasticallyDependentError ( "Joint distribution with dependencies not supported." ) output = numpy . zeros ( ( 2 , ) + kloc . shape ) for dist in evaluation . sorted_dependencies ( self ) : if dist not in self . inverse_map : ...
def split_before ( iterable , pred ) : """Yield lists of items from * iterable * , where each list starts with an item where callable * pred * returns ` ` True ` ` : > > > list ( split _ before ( ' OneTwo ' , lambda s : s . isupper ( ) ) ) [ [ ' O ' , ' n ' , ' e ' ] , [ ' T ' , ' w ' , ' o ' ] ] > > > list...
buf = [ ] for item in iterable : if pred ( item ) and buf : yield buf buf = [ ] buf . append ( item ) yield buf
def safe_dump_all ( documents , stream = None , ** kwds ) : """Serialize a sequence of Python objects into a YAML stream . Produce only basic YAML tags . If stream is None , return the produced string instead ."""
return dump_all ( documents , stream , Dumper = SafeDumper , ** kwds )
def format_instance ( instance ) : """Serialise ` instance ` For children to be visualised and modified , they must provide an appropriate implementation of _ _ str _ _ . Data that isn ' t JSON compatible cannot be visualised nor modified . Attributes : name ( str ) : Name of instance niceName ( str...
instance = { "name" : instance . name , "id" : instance . id , "data" : format_data ( instance . data ) , "children" : list ( ) , } if os . getenv ( "PYBLISH_SAFE" ) : schema . validate ( instance , "instance" ) return instance
def super_mro ( self ) : """Get the MRO which will be used to lookup attributes in this super ."""
if not isinstance ( self . mro_pointer , scoped_nodes . ClassDef ) : raise exceptions . SuperError ( "The first argument to super must be a subtype of " "type, not {mro_pointer}." , super_ = self , ) if isinstance ( self . type , scoped_nodes . ClassDef ) : # ` super ( type , type ) ` , most likely in a class metho...
def sendNotification ( snmpDispatcher , authData , transportTarget , notifyType , * varBinds , ** options ) : """Creates a generator to send one or more SNMP notifications . On each iteration , new SNMP TRAP or INFORM notification is send ( : RFC : ` 1905 # section - 4,2,6 ` ) . The iterator blocks waiting for ...
def cbFun ( * args , ** kwargs ) : response [ : ] = args options [ 'cbFun' ] = cbFun errorIndication , errorStatus , errorIndex = None , 0 , 0 response = [ None , 0 , 0 , [ ] ] while True : if varBinds : ntforg . sendNotification ( snmpDispatcher , authData , transportTarget , notifyType , * varBinds , ...
def serial_login ( self ) : """Attempt to log into the meter over the C12.18 protocol . Returns True on success , False on a failure . This can be called by modules in order to login with a username and password configured within the framework instance ."""
if not self . _serial_connected : raise termineter . errors . FrameworkRuntimeError ( 'the serial interface is disconnected' ) username = self . options [ 'USERNAME' ] user_id = self . options [ 'USER_ID' ] password = self . options [ 'PASSWORD' ] if self . options [ 'PASSWORD_HEX' ] : hex_regex = re . compile ...
def insertOutputModuleConfig ( self , remoteConfig , migration = False ) : """Insert Release version , application , parameter set hashes and the map ( output module config ) ."""
otptIdList = [ ] missingList = [ ] conn = self . dbi . connection ( ) try : for c in remoteConfig : cfgid = self . otptModCfgid . execute ( conn , app = c [ "app_name" ] , release_version = c [ "release_version" ] , pset_hash = c [ "pset_hash" ] , output_label = c [ "output_module_label" ] , global_tag = c ...
def rarity ( brands , exemplars ) : """Compute a score for each follower that is sum _ i ( 1 / n _ i ) , where n _ i is the degree of the ith exemplar they follow . The score for a brand is then the average of their follower scores ."""
rarity = compute_rarity_scores ( exemplars ) scores = { } for brand , followers in brands : scores [ brand ] = sum ( rarity [ f ] for f in followers ) / len ( followers ) return scores
def _check_mode ( stream ) : """Check that a stream was opened in read - binary mode . : type stream : IO [ bytes ] : param stream : A bytes IO object open for reading . : raises : : exc : ` ValueError ` if the ` ` stream . mode ` ` is a valid attribute and is not among ` ` rb ` ` , ` ` r + b ` ` or ` ` rb ...
mode = getattr ( stream , "mode" , None ) if isinstance ( stream , gzip . GzipFile ) : if mode != gzip . READ : raise ValueError ( "Cannot upload gzip files opened in write mode: use " "gzip.GzipFile(filename, mode='rb')" ) else : if mode is not None and mode not in ( "rb" , "r+b" , "rb+" ) : r...
def p_single_statement_disable ( self , p ) : 'single _ statement : disable SEMICOLON'
p [ 0 ] = SingleStatement ( p [ 1 ] , lineno = p . lineno ( 1 ) ) p . set_lineno ( 0 , p . lineno ( 1 ) )
def is_published ( self ) : """Return True if a record is published . We say that a record is published if it is citeable , which means that it has enough information in a ` ` publication _ info ` ` , or if we know its DOI and a ` ` journal _ title ` ` , which means it is in press . Returns : bool : wheth...
citeable = 'publication_info' in self . record and is_citeable ( self . record [ 'publication_info' ] ) submitted = 'dois' in self . record and any ( 'journal_title' in el for el in force_list ( self . record . get ( 'publication_info' ) ) ) return citeable or submitted
def multi30k_dataset ( directory = 'data/multi30k/' , train = False , dev = False , test = False , train_filename = 'train' , dev_filename = 'val' , test_filename = 'test' , check_files = [ 'train.de' , 'val.de' ] , urls = [ 'http://www.quest.dcs.shef.ac.uk/wmt16_files_mmt/training.tar.gz' , 'http://www.quest.dcs.shef....
download_files_maybe_extract ( urls = urls , directory = directory , check_files = check_files ) ret = [ ] splits = [ ( train , train_filename ) , ( dev , dev_filename ) , ( test , test_filename ) ] splits = [ f for ( requested , f ) in splits if requested ] for filename in splits : examples = [ ] en_path = os ...
def defer ( self , func , * args , ** kwargs ) : """Arrange for ` func ( ) ` to execute on the broker thread . This function returns immediately without waiting the result of ` func ( ) ` . Use : meth : ` defer _ sync ` to block until a result is available . : raises mitogen . core . Error : : meth : ` defe...
if thread . get_ident ( ) == self . broker_ident : _vv and IOLOG . debug ( '%r.defer() [immediate]' , self ) return func ( * args , ** kwargs ) if self . _broker . _exitted : raise Error ( self . broker_shutdown_msg ) _vv and IOLOG . debug ( '%r.defer() [fd=%r]' , self , self . transmit_side . fd ) self . _...
def parse_rune_html ( html : str , url : str ) -> dict : """A function that returns a dict representation of the Runeforge . gg page for a specific champ Parameters html : str The string representation of the html obtained via a GET request url : str The URL for the runeforge page being parsed . Returns...
soup = BeautifulSoup ( html , 'lxml' ) # The soup stuff champ = soup . find ( 'h1' , class_ = 'champion-header--title' ) . text title = soup . find ( 'h2' , class_ = 'loadout-title' ) . text description = soup . find ( 'p' ) . text # Names of the Rune trees p_tree , s_tree = [ x . text for x in soup . find_all ( 'h2' ,...
def _keyDown ( key ) : """Performs a keyboard key press without the release . This will put that key in a held down state . NOTE : For some reason , this does not seem to cause key repeats like would happen if a keyboard key was held down on a text field . Args : key ( str ) : The key to be pressed down ....
if key not in keyboardMapping or keyboardMapping [ key ] is None : return if type ( key ) == int : fake_input ( _display , X . KeyPress , key ) _display . sync ( ) return needsShift = pyautogui . isShiftCharacter ( key ) if needsShift : fake_input ( _display , X . KeyPress , keyboardMapping [ 'shift...