signature stringlengths 29 44.1k | implementation stringlengths 0 85.2k |
|---|---|
def ReadPermission ( self , permission_link , options = None ) :
"""Reads a permission .
: param str permission _ link :
The link to the permission .
: param dict options :
The request options for the request .
: return :
The read permission .
: rtype :
dict""" | if options is None :
options = { }
path = base . GetPathFromLink ( permission_link )
permission_id = base . GetResourceIdOrFullNameFromLink ( permission_link )
return self . Read ( path , 'permissions' , permission_id , None , options ) |
def setJoiner ( self , joiner ) :
"""Sets the join operator type for this entry widget to the given value .
: param joiner | < QueryCompound . Op >""" | text = QueryCompound . Op [ joiner ] . upper ( )
if self . _first :
if self . _last :
self . uiJoinSBTN . setCurrentAction ( None )
else :
act = self . uiJoinSBTN . findAction ( text )
self . uiJoinSBTN . setCurrentAction ( act )
else :
self . uiJoinSBTN . actions ( ) [ 0 ] . setText... |
def deepcopy ( original_obj ) :
"""Creates a deep copy of an object with no crossed referenced lists or dicts ,
useful when loading from yaml as anchors generate those cross - referenced
dicts and lists
Args :
original _ obj ( object ) : Object to deep copy
Return :
object : deep copy of the object""" | if isinstance ( original_obj , list ) :
return list ( deepcopy ( item ) for item in original_obj )
elif isinstance ( original_obj , dict ) :
return dict ( ( key , deepcopy ( val ) ) for key , val in original_obj . items ( ) )
else :
return original_obj |
def _diversity_metric ( solution , population ) :
"""Return diversity value for solution compared to given population .
Metric is sum of distance between solution and each solution in population ,
normalized to [ 0.0 , 1.0 ] .""" | # Edge case for empty population
# If there are no other solutions , the given solution has maximum diversity
if population == [ ] :
return 1.0
return ( sum ( [ _manhattan_distance ( solution , other ) for other in population ] ) # Normalize ( assuming each value in solution is in range [ 0.0 , 1.0 ] )
# NOTE : len... |
def run_diff_umap ( self , use_rep = 'X_pca' , metric = 'euclidean' , n_comps = 15 , method = 'gauss' , ** kwargs ) :
"""Experimental - - running UMAP on the diffusion components""" | import scanpy . api as sc
sc . pp . neighbors ( self . adata , use_rep = use_rep , n_neighbors = self . k , metric = self . distance , method = method )
sc . tl . diffmap ( self . adata , n_comps = n_comps )
sc . pp . neighbors ( self . adata , use_rep = 'X_diffmap' , n_neighbors = self . k , metric = 'euclidean' , met... |
def serialize ( cls , share_detail ) :
""": type share _ detail : object _ . ShareDetail
: rtype : dict""" | return { cls . _FIELD_PAYMENT : converter . serialize ( share_detail . _payment_field_for_request ) , cls . _FIELD_READ_ONLY : converter . serialize ( share_detail . _read_only_field_for_request ) , cls . _FIELD_DRAFT_PAYMENT : converter . serialize ( share_detail . _draft_payment ) , } |
def date_from_string ( string , format_string = None ) :
"""Runs through a few common string formats for datetimes ,
and attempts to coerce them into a datetime . Alternatively ,
format _ string can provide either a single string to attempt
or an iterable of strings to attempt .""" | if isinstance ( format_string , str ) :
return datetime . datetime . strptime ( string , format_string ) . date ( )
elif format_string is None :
format_string = [ "%Y-%m-%d" , "%m-%d-%Y" , "%m/%d/%Y" , "%d/%m/%Y" , ]
for format in format_string :
try :
return datetime . datetime . strptime ( string ... |
def _GetNormalizedTimestamp ( self ) :
"""Retrieves the normalized timestamp .
Returns :
decimal . Decimal : normalized timestamp , which contains the number of
seconds since January 1 , 1970 00:00:00 and a fraction of second used
for increased precision , or None if the normalized timestamp cannot be
det... | if self . _normalized_timestamp is None :
if self . _timestamp is not None :
self . _normalized_timestamp = decimal . Decimal ( self . _timestamp )
return self . _normalized_timestamp |
def _prep_vrn_file ( in_file , vcaller , work_dir , somatic_info , ignore_file , config ) :
"""Create a variant file to feed into the PhyloWGS prep script , limiting records .
Sorts by depth , adding top covered samples up to the sample _ size supported
by PhyloWGS . The logic is that the higher depth samples w... | if vcaller . startswith ( "vardict" ) :
variant_type = "vardict"
elif vcaller == "mutect" :
variant_type = "mutect-smchet"
else :
raise ValueError ( "Unexpected variant caller for PhyloWGS prep: %s" % vcaller )
out_file = os . path . join ( work_dir , "%s-%s-prep.vcf" % ( utils . splitext_plus ( os . path .... |
def send_to ( self , content , search ) :
"""向指定好友发送消息
: param content : ( 必填 | str ) - 需要发送的消息内容
: param search : ( 必填 | str | dict | list ) - 搜索对象 , 同 wxpy . chats . search 使用方法一样 。 例如 , 可以使用字符串进行搜索好友或群 , 或指定具体属性搜索 , 如 puid = xxx 的字典
: return : * status : 发送状态 , True 发送成 , False 发送失败
* message : 发送失败详情""" | url = '{0}send_to_message' . format ( self . remote )
if isinstance ( search , dict ) :
search = json . dumps ( search )
elif isinstance ( search , list ) :
search = reduce ( lambda x , y : '{0} {1}' . format ( x , y ) , search )
data = self . _wrap_post_data ( content = content , search = search )
res = reques... |
def parse_parameters ( cls , parameters , possible_fields ) :
"""Parses a list of parameters to get the list of fields needed in
order to evaluate those parameters .
Parameters
parameters : ( list of ) string ( s )
The list of desired parameters . These can be ( functions of ) fields
or virtual fields .
... | if isinstance ( possible_fields , string_types ) :
possible_fields = [ possible_fields ]
possible_fields = map ( str , possible_fields )
# we ' ll just use float as the dtype , as we just need this for names
arr = cls ( 1 , dtype = zip ( possible_fields , len ( possible_fields ) * [ float ] ) )
# try to perserve or... |
def assertSignalFired ( self , signal , * args , ** kwargs ) :
"""Assert that a signal was fired with appropriate arguments .
: param signal :
The : class : ` Signal ` that should have been fired .
Typically this is ` ` SomeClass . on _ some _ signal ` ` reference
: param args :
List of positional argumen... | event = ( signal , args , kwargs )
self . assertIn ( event , self . _events_seen , "\nSignal unexpectedly not fired: {}\n" . format ( event ) )
return event |
def command_line ( ) :
'''Parses users command line arguments and returns the namespace
containing parsed values .''' | description = 'Kan helps you find the book'
version = ' ' . join ( [ __version__ , __release__ ] )
parser = ArgumentParser ( prog = 'kan' , description = description )
subparser = parser . add_subparsers ( help = 'Search by' )
by_title = subparser . add_parser ( 'title' , help = 'Book title' , )
by_title . add_argument... |
async def debug ( self , conn_id , name , cmd_args ) :
"""Asynchronously complete a named debug command .
The command name and arguments are passed to the underlying device adapter
and interpreted there .
Args :
conn _ id ( int ) : A unique identifer that will refer to this connection
name ( string ) : th... | device = self . _get_property ( conn_id , 'device' )
retval = None
try :
if name == 'dump_state' :
retval = device . dump_state ( )
elif name == 'restore_state' :
state = cmd_args [ 'snapshot' ]
device . restore_state ( state )
elif name == 'load_scenario' :
scenario = cmd_ar... |
def boxplot ( self , ** vargs ) :
"""Plots a boxplot for the table .
Every column must be numerical .
Kwargs :
vargs : Additional arguments that get passed into ` plt . boxplot ` .
See http : / / matplotlib . org / api / pyplot _ api . html # matplotlib . pyplot . boxplot
for additional arguments that can... | # Check for non - numerical values and raise a ValueError if any found
for col in self :
if any ( isinstance ( cell , np . flexible ) for cell in self [ col ] ) :
raise ValueError ( "The column '{0}' contains non-numerical " "values. A histogram cannot be drawn for this table." . format ( col ) )
columns = ... |
def _get_part_reader ( self , headers : 'CIMultiDictProxy[str]' ) -> Any :
"""Dispatches the response by the ` Content - Type ` header , returning
suitable reader instance .
: param dict headers : Response headers""" | ctype = headers . get ( CONTENT_TYPE , '' )
mimetype = parse_mimetype ( ctype )
if mimetype . type == 'multipart' :
if self . multipart_reader_cls is None :
return type ( self ) ( headers , self . _content )
return self . multipart_reader_cls ( headers , self . _content , _newline = self . _newline )
el... |
def add_edge_fun ( graph ) :
"""Returns a function that adds an edge to the ` graph ` checking only the out
node .
: param graph :
A directed graph .
: type graph : networkx . classes . digraph . DiGraph
: return :
A function that adds an edge to the ` graph ` .
: rtype : callable""" | # Namespace shortcut for speed .
succ , pred , node = graph . _succ , graph . _pred , graph . _node
def add_edge ( u , v , ** attr ) :
if v not in succ : # Add nodes .
succ [ v ] , pred [ v ] , node [ v ] = { } , { } , { }
succ [ u ] [ v ] = pred [ v ] [ u ] = attr
# Add the edge .
return add_edge |
def _return_parsed_timezone_results ( result , timezones , box , tz , name ) :
"""Return results from array _ strptime if a % z or % Z directive was passed .
Parameters
result : ndarray
int64 date representations of the dates
timezones : ndarray
pytz timezone objects
box : boolean
True boxes result as... | if tz is not None :
raise ValueError ( "Cannot pass a tz argument when " "parsing strings with timezone " "information." )
tz_results = np . array ( [ Timestamp ( res ) . tz_localize ( zone ) for res , zone in zip ( result , timezones ) ] )
if box :
from pandas import Index
return Index ( tz_results , name ... |
def cache_from_names ( self ) :
"""Yield the image names to do - - cache - from from""" | cache_from = self . cache_from ( )
if not cache_from or cache_from is NotSpecified :
return
if cache_from is True :
yield self . image_name
return
for thing in cache_from :
if not isinstance ( thing , six . string_types ) :
yield thing . image_name
else :
yield thing |
def method2png ( output , mx , raw = False ) :
"""Export method to a png file format
: param output : output filename
: type output : string
: param mx : specify the MethodAnalysis object
: type mx : : class : ` MethodAnalysis ` object
: param raw : use directly a dot raw buffer
: type raw : string""" | buff = raw
if not raw :
buff = method2dot ( mx )
method2format ( output , "png" , mx , buff ) |
def tofile ( self , path_to_file , replace_file = False ) :
"""save blob content from StorageBlobModel instance to file in given path / file . Parameters are :
- path _ to _ file ( required ) : local path or file""" | # create full path
if os . path . isdir ( path_to_file ) :
if self . filename != '' :
path_to_file = os . path . join ( path_to_file , self . filename )
else : # guess extention from mimetype
path_to_file = os . path . join ( path_to_file , self . name + guess_extension ( self . properties . con... |
def default_filter_filename ( filename ) : # type : ( Optional [ str ] ) - > Optional [ str ]
"""Default filter for filenames .
Returns either a normalized filename or None .
You can pass your own filter to init _ types _ collection ( ) .""" | if filename is None :
return None
elif filename . startswith ( TOP_DIR ) :
if filename . startswith ( TOP_DIR_DOT ) : # Skip subdirectories starting with dot ( e . g . . vagrant ) .
return None
else : # Strip current directory and following slashes .
return filename [ TOP_DIR_LEN : ] . lstri... |
def daofind_marginal_fit ( self , axis = 0 ) :
"""Fit 1D Gaussians , defined from the marginal x / y kernel
distributions , to the marginal x / y distributions of the original
( unconvolved ) image .
These fits are used calculate the star centroid and roundness
( " GROUND " ) properties .
Parameters
axi... | # define triangular weighting functions along each axis , peaked
# in the middle and equal to one at the edge
x = self . xcenter - np . abs ( np . arange ( self . nx ) - self . xcenter ) + 1
y = self . ycenter - np . abs ( np . arange ( self . ny ) - self . ycenter ) + 1
xwt , ywt = np . meshgrid ( x , y )
if axis == 0... |
def parse_length_dist ( self , f ) :
"""Parse HOMER tagdirectory tagLengthDistribution file .""" | parsed_data = dict ( )
firstline = True
for l in f [ 'f' ] :
if firstline : # skip first line
firstline = False
continue
s = l . split ( "\t" )
if len ( s ) > 1 :
k = float ( s [ 0 ] . strip ( ) )
v = float ( s [ 1 ] . strip ( ) )
parsed_data [ k ] = v
return parsed_d... |
def renew_voms_proxy ( passwd = "" , vo = None , lifetime = "196:00" ) :
"""Renews the voms proxy using a password * passwd * , an optional virtual organization name * vo * , and
a default * lifetime * of 8 days . The password is written to a temporary file first and piped into
the renewal commad to ensure it i... | with tmp_file ( ) as ( _ , tmp ) :
with open ( tmp , "w" ) as f :
f . write ( passwd )
cmd = "cat '{}' | voms-proxy-init --valid '{}'" . format ( tmp , lifetime )
if vo :
cmd += " -voms '{}'" . format ( vo )
code , out , _ = interruptable_popen ( cmd , shell = True , executable = "/bin/b... |
def get ( self , key , prompt_default = '' , prompt_help = '' ) :
"""Return a value from the environ or keyring""" | value = os . getenv ( key )
if not value :
ns = self . namespace ( key )
value = self . keyring . get_password ( ns , key )
else :
ns = 'environ'
if not value :
ns = self . namespace ( key , glob = True )
value = self . keyring . get_password ( ns , key )
if not value :
ns = ''
if not value and ... |
def refresh ( self ) :
"""GET / : login / machines / : id / snapshots / : name
Fetch the existing state and values for the snapshot
and commit the values locally .""" | data = self . machine . raw_snapshot_data ( self . name )
self . _save ( data ) |
def add_child ( self , * sprites ) :
"""Add child sprite . Child will be nested within parent""" | for sprite in sprites :
self . _add ( sprite )
self . _sort ( )
self . redraw ( ) |
def probe ( filename , cmd = 'ffprobe' , ** kwargs ) :
"""Run ffprobe on the specified file and return a JSON representation of the output .
Raises :
: class : ` ffmpeg . Error ` : if ffprobe returns a non - zero exit code ,
an : class : ` Error ` is returned with a generic error message .
The stderr output... | args = [ cmd , '-show_format' , '-show_streams' , '-of' , 'json' ]
args += convert_kwargs_to_cmd_line_args ( kwargs )
args += [ filename ]
p = subprocess . Popen ( args , stdout = subprocess . PIPE , stderr = subprocess . PIPE )
out , err = p . communicate ( )
if p . returncode != 0 :
raise Error ( 'ffprobe' , out ... |
def list_backups ( self , encrypted = None , compressed = None , content_type = None , database = None , servername = None ) :
"""List stored files except given filter . If filter is None , it won ' t be
used . ` ` content _ type ` ` must be ` ` ' db ' ` ` for database backups or
` ` ' media ' ` ` for media bac... | if content_type not in ( 'db' , 'media' , None ) :
msg = "Bad content_type %s, must be 'db', 'media', or None" % ( content_type )
raise TypeError ( msg )
# TODO : Make better filter for include only backups
files = [ f for f in self . list_directory ( ) if utils . filename_to_datestring ( f ) ]
if encrypted is ... |
def pop ( self , instance ) :
'''Remove ` ` instance ` ` from the : class : ` SessionModel ` . Instance
could be a : class : ` Model ` or an id .
: parameter instance : a : class : ` Model ` or an ` ` id ` ` .
: rtype : the : class : ` Model ` removed from session or ` ` None ` ` if
it was not in the sessio... | if isinstance ( instance , self . model ) :
iid = instance . get_state ( ) . iid
else :
iid = instance
instance = None
for d in ( self . _new , self . _modified , self . _deleted ) :
if iid in d :
inst = d . pop ( iid )
if instance is None :
instance = inst
elif inst is n... |
def _wrap_element ( self , result ) :
"""Wrap single element in Parser instance""" | if isinstance ( result , lxml . html . HtmlElement ) :
return Parser ( result )
else :
return result |
def visit_generatorexp ( self , node , parent ) :
"""visit a GeneratorExp node by returning a fresh instance of it""" | newnode = nodes . GeneratorExp ( node . lineno , node . col_offset , parent )
newnode . postinit ( self . visit ( node . elt , newnode ) , [ self . visit ( child , newnode ) for child in node . generators ] , )
return newnode |
def _remove_boundaries ( self , interval ) :
"""Removes the boundaries of the interval from the boundary table .""" | begin = interval . begin
end = interval . end
if self . boundary_table [ begin ] == 1 :
del self . boundary_table [ begin ]
else :
self . boundary_table [ begin ] -= 1
if self . boundary_table [ end ] == 1 :
del self . boundary_table [ end ]
else :
self . boundary_table [ end ] -= 1 |
def shutdown ( self ) :
"""Wait for all threads to complete""" | # cleanup
self . started = False
try : # nice way of doing things - let ' s wait until all items
# in the queue are processed
for t in self . _threads :
t . join ( )
finally : # Emergency brake - if a KeyboardInterrupt is raised ,
# threads will finish processing current task and exit
self . stopped = T... |
def ConsultarTiposContingencia ( self , sep = "||" ) :
"Obtener el código y descripción para cada tipo de contingencia que puede reportar" | ret = self . client . consultarTiposContingencia ( authRequest = { 'token' : self . Token , 'sign' : self . Sign , 'cuitRepresentada' : self . Cuit , } , ) [ 'consultarTiposContingenciaReturn' ]
self . __analizar_errores ( ret )
array = ret . get ( 'arrayTiposContingencia' , [ ] )
lista = [ it [ 'codigoDescripcion' ] f... |
def as_dataframe ( self , time_index = False , absolute_time = False ) :
"""Converts the TDMS file to a DataFrame
: param time _ index : Whether to include a time index for the dataframe .
: param absolute _ time : If time _ index is true , whether the time index
values are absolute times or relative to the s... | import pandas as pd
dataframe_dict = OrderedDict ( )
for key , value in self . objects . items ( ) :
if value . has_data :
index = value . time_track ( absolute_time ) if time_index else None
dataframe_dict [ key ] = pd . Series ( data = value . data , index = index )
return pd . DataFrame . from_di... |
def _hack_namedtuple ( cls ) :
"""Make class generated by namedtuple picklable""" | name = cls . __name__
fields = cls . _fields
def __reduce__ ( self ) :
return ( _restore , ( name , fields , tuple ( self ) ) )
cls . __reduce__ = __reduce__
cls . _is_namedtuple_ = True
return cls |
def total_power ( self ) :
"""Total power used .""" | power = self . average_current * self . voltage
return round ( power , self . sr ) |
def _parse_optimization ( optimization ) :
'''Turns an optimization of the form
my _ optim
my _ package . my _ optim
into the associated symbol''' | splitted = optimization . split ( '.' )
if len ( splitted ) == 1 :
splitted = [ 'pythran' , 'optimizations' ] + splitted
return reduce ( getattr , splitted [ 1 : ] , __import__ ( splitted [ 0 ] ) ) |
def buffer_stream ( stream , buffer_size , partial = False , axis = None ) :
'''Buffer " data " from an stream into one data object .
Parameters
stream : stream
The stream to buffer
buffer _ size : int > 0
The number of examples to retain per batch .
partial : bool , default = False
If True , yield a ... | data = [ ]
count = 0
for item in stream :
data . append ( item )
count += 1
if count < buffer_size :
continue
try :
yield __stack_data ( data , axis = axis )
except ( TypeError , AttributeError ) :
raise DataError ( "Malformed data stream: {}" . format ( data ) )
finally ... |
def get_nucsat_subtrees ( parented_tree ) :
"""Return all direct children of the given tree , that are either
a nucleus , satellite or a leaf node ( i . e . all children except
for relation nodes . )""" | if is_leaf ( parented_tree ) :
return [ parented_tree ]
nucsat_children = [ ]
for child in parented_tree :
if is_leaf ( child ) or child . label ( ) in ( 'N' , 'S' ) :
nucsat_children . append ( child )
else :
nucsat_children . extend ( get_nucsat_subtrees ( child ) )
return nucsat_children |
def nonDefaults ( self ) :
"""Get a dictionary of all attributes that differ from the default .""" | nonDefaults = { }
for k , d in self . __class__ . defaults . items ( ) :
v = getattr ( self , k )
if v != d and ( v == v or d == d ) : # tests for NaN too
nonDefaults [ k ] = v
return nonDefaults |
def _build_url ( self , endpoint ) :
"""Returns a fully qualified URL""" | server = None
if "://" in endpoint : # looks like an url , let ' s break it down
server , endpoint = self . _deconstruct_url ( endpoint )
endpoint = endpoint . lstrip ( "/" )
url = "{proto}://{server}/{endpoint}" . format ( proto = self . protocol , server = self . client . server if server is None else server , en... |
def _fail ( self , event , message = 'Invalid credentials' ) :
"""Sends a failure message to the requesting client""" | notification = { 'component' : 'auth' , 'action' : 'fail' , 'data' : message }
ip = event . sock . getpeername ( ) [ 0 ]
self . failing_clients [ ip ] = event
Timer ( 3 , Event . create ( 'notify_fail' , event . clientuuid , notification , ip ) ) . register ( self ) |
def deauth ( self ) :
"""Resets authentication info . Calls stop _ crypto ( ) if RFID is in auth state""" | self . method = None
self . key = None
self . last_auth = None
if self . debug :
print ( "Changing auth key and method to None" )
if self . rfid . authed :
self . rfid . stop_crypto ( )
if self . debug :
print ( "Stopping crypto1" ) |
def get_function_node ( self , node ) :
"""Process a function node .
: sig : ( Union [ ast . FunctionDef , ast . AsyncFunctionDef ] ) - > FunctionNode
: param node : Node to process .
: return : Generated function node in stub tree .""" | decorators = [ ]
for d in node . decorator_list :
if hasattr ( d , "id" ) :
decorators . append ( d . id )
elif hasattr ( d , "func" ) :
decorators . append ( d . func . id )
elif hasattr ( d , "value" ) :
decorators . append ( d . value . id + "." + d . attr )
signature = get_signat... |
def post_process ( self , dir_name , d ) :
"""Simple post - processing for various files other than the vasprun . xml .
Called by generate _ task _ doc . Modify this if your runs have other
kinds of processing requirements .
Args :
dir _ name :
The dir _ name .
Current doc generated .""" | logger . info ( "Post-processing dir:{}" . format ( dir_name ) )
fullpath = os . path . abspath ( dir_name )
# VASP input generated by pymatgen ' s alchemy has a
# transformations . json file that keeps track of the origin of a
# particular structure . This is extremely useful for tracing back a
# result . If such a fi... |
def fight ( self , moves = 10 ) :
"""runs a series of fights""" | for i in range ( 1 , moves ) : # player 1
result , dmg = self . calc_move ( self . c1 , self . c2 )
print ( self . c1 . name + ' ' + result + ' for ' + str ( dmg ) )
self . c1 . sta = self . c1 . sta - dmg
if self . is_character_dead ( self . c1 ) :
print ( self . c1 . name + ' has died' )
... |
def select_args ( xmrs , nodeid = None , rargname = None , value = None ) :
"""Return the list of matching ( nodeid , role , value ) triples in * xmrs * .
Predication arguments in * xmrs * match if the ` nodeid ` of the
: class : ` ~ delphin . mrs . components . ElementaryPredication ` they are
arguments of m... | argmatch = lambda a : ( ( nodeid is None or a [ 0 ] == nodeid ) and ( rargname is None or a [ 1 ] . upper ( ) == rargname . upper ( ) ) and ( value is None or a [ 2 ] == value ) )
all_args = ( ( nid , role , val ) for nid in xmrs . nodeids ( ) for role , val in sorted ( xmrs . args ( nid ) . items ( ) , key = lambda i ... |
def child_get ( self , child , * prop_names ) :
"""Returns a list of child property values for the given names .""" | return [ self . child_get_property ( child , name ) for name in prop_names ] |
def _ssweek_info ( ssweek_year , ssweek_week ) :
"Give all the ssweek info we need from one calculation" | prev_year_start = _ssweek_year_start ( ssweek_year - 1 )
year_start = _ssweek_year_start ( ssweek_year )
next_year_start = _ssweek_year_start ( ssweek_year + 1 )
first_day = year_start + dt . timedelta ( weeks = ssweek_week - 1 )
last_day = first_day + dt . timedelta ( days = 6 )
prev_year_num_weeks = ( ( year_start - ... |
def build_indentation_list ( parser : str = 'github' ) :
r"""Create a data structure that holds the state of indentations .
: parameter parser : decides the length of the list .
Defaults to ` ` github ` ` .
: type parser : str
: returns : indentation _ list , a list that contains the state of
indentations... | indentation_list = list ( )
if ( parser == 'github' or parser == 'cmark' or parser == 'gitlab' or parser == 'commonmarker' or parser == 'redcarpet' ) :
for i in range ( 0 , md_parser [ parser ] [ 'header' ] [ 'max_levels' ] ) :
indentation_list . append ( False )
return indentation_list |
def assignCurrentRecord ( self , text ) :
"""Assigns the current record from the inputed text .
: param text | < str >""" | if self . showTreePopup ( ) :
item = self . _treePopupWidget . currentItem ( )
if item :
self . _currentRecord = item . record ( )
else :
self . _currentRecord = None
return
# look up the record for the given text
if text :
index = self . findText ( text )
elif self . isRequired ( ) ... |
def APFSContainerPathSpecGetVolumeIndex ( path_spec ) :
"""Retrieves the volume index from the path specification .
Args :
path _ spec ( PathSpec ) : path specification .
Returns :
int : volume index or None if the index cannot be determined .""" | volume_index = getattr ( path_spec , 'volume_index' , None )
if volume_index is not None :
return volume_index
location = getattr ( path_spec , 'location' , None )
if location is None or not location . startswith ( '/apfs' ) :
return None
try :
volume_index = int ( location [ 5 : ] , 10 ) - 1
except ( TypeE... |
def _remove_files ( self , predicate ) :
"""Remove all files from the file list that match the predicate .
Return True if any matching files were removed""" | found = False
for i in range ( len ( self . files ) - 1 , - 1 , - 1 ) :
if predicate ( self . files [ i ] ) :
self . debug_print ( " removing " + self . files [ i ] )
del self . files [ i ]
found = True
return found |
def get_anki_phrases_english ( limit = None ) :
"""Return all the English phrases in the Anki translation flashcards
> > > len ( get _ anki _ phrases _ english ( limit = 100 ) ) > 700
True""" | texts = set ( )
for lang in ANKI_LANGUAGES :
df = get_data ( lang )
phrases = df . eng . str . strip ( ) . values
texts = texts . union ( set ( phrases ) )
if limit and len ( texts ) >= limit :
break
return sorted ( texts ) |
async def async_request ( session , url , ** kwargs ) :
"""Do a web request and manage response .""" | _LOGGER . debug ( "Sending %s to %s" , kwargs , url )
try :
res = await session ( url , ** kwargs )
if res . content_type != 'application/json' :
raise ResponseError ( "Invalid content type: {}" . format ( res . content_type ) )
response = await res . json ( )
_LOGGER . debug ( "HTTP request res... |
def trigger ( self , name , * args , ** kwargs ) :
"""Triggers an event to run through middleware . This method will execute
a chain of relevant trigger callbacks , until one of the callbacks
returns the ` break _ trigger ` .""" | # Relevant middleware is cached so we don ' t have to rediscover it
# every time . Fetch the cached value if possible .
listeners = self . _triggers . get ( name , [ ] )
# Execute each piece of middleware
for listener in listeners :
result = listener ( * args , ** kwargs )
if result == break_trigger :
r... |
def SmartConnectNoSSL ( protocol = 'https' , host = 'localhost' , port = 443 , user = 'root' , pwd = '' , service = "hostd" , path = "/sdk" , connectionPoolTimeout = CONNECTION_POOL_IDLE_TIMEOUT_SEC , preferredApiVersions = None , keyFile = None , certFile = None , thumbprint = None , b64token = None , mechanism = 'use... | if hasattr ( ssl , '_create_unverified_context' ) :
sslContext = ssl . _create_unverified_context ( )
else :
sslContext = None
return SmartConnect ( protocol = protocol , host = host , port = port , user = user , pwd = pwd , service = service , path = path , connectionPoolTimeout = connectionPoolTimeout , prefe... |
def get_facts ( state , name , args = None , ensure_hosts = None ) :
'''Get a single fact for all hosts in the state .''' | # Create an instance of the fact
fact = FACTS [ name ] ( )
if isinstance ( fact , ShortFactBase ) :
return get_short_facts ( state , fact , args = args , ensure_hosts = ensure_hosts )
logger . debug ( 'Getting fact: {0} (ensure_hosts: {1})' . format ( name , ensure_hosts , ) )
args = args or [ ]
# Apply args or def... |
def is_scheme ( scheme , slashes = True ) :
"""Return whether * scheme * is valid for external links .""" | scheme = scheme . lower ( )
if slashes :
return scheme in URI_SCHEMES
return scheme in URI_SCHEMES and not URI_SCHEMES [ scheme ] |
def index_worker_output ( self , worker_name , md5 , index_name , subfield ) :
"""Index worker output with the Indexer .
Args :
worker _ name : ' strings ' , ' pe _ features ' , whatever
md5 : the md5 of the sample
index _ name : the name of the index
subfield : index just this subfield ( None for all )
... | # Grab the data
if subfield :
data = self . work_request ( worker_name , md5 ) [ worker_name ] [ subfield ]
else :
data = self . work_request ( worker_name , md5 ) [ worker_name ]
# Okay now index the data
self . indexer . index_data ( data , index_name = index_name , doc_type = 'unknown' ) |
def write_bubble ( self , filename : str ) :
"""Write in given filename the lines of bubble describing this instance""" | from bubbletools import converter
converter . tree_to_bubble ( self , filename ) |
def real_time_statistics ( self ) :
"""Access the real _ time _ statistics
: returns : twilio . rest . taskrouter . v1 . workspace . worker . workers _ real _ time _ statistics . WorkersRealTimeStatisticsList
: rtype : twilio . rest . taskrouter . v1 . workspace . worker . workers _ real _ time _ statistics . W... | if self . _real_time_statistics is None :
self . _real_time_statistics = WorkersRealTimeStatisticsList ( self . _version , workspace_sid = self . _solution [ 'workspace_sid' ] , )
return self . _real_time_statistics |
def brain ( draw = True , show = True , fiducial = True , flat = True , inflated = True , subject = 'S1' , interval = 1000 , uv = True , color = None ) :
"""Show a human brain model .
Requirement :
$ pip install https : / / github . com / gallantlab / pycortex""" | import ipyvolume as ipv
try :
import cortex
except :
warnings . warn ( "it seems pycortex is not installed, which is needed for this example" )
raise
xlist , ylist , zlist = [ ] , [ ] , [ ]
polys_list = [ ]
def add ( pts , polys ) :
xlist . append ( pts [ : , 0 ] )
ylist . append ( pts [ : , 1 ] )
... |
def get_crawler_class ( self , crawler ) :
"""Searches through the modules in self . _ _ crawer _ module for a crawler with
the name passed along .
: param str crawler : Name of the crawler to load
: rtype : crawler - class""" | settings = Settings ( )
settings . set ( 'SPIDER_MODULES' , [ self . __crawer_module ] )
spider_loader = SpiderLoader ( settings )
return spider_loader . load ( crawler ) |
def eventFilter ( self , object , event ) :
"""Sets the completion prefor this instance , triggering a search query
for the search query .
: param prefix | < str >""" | result = super ( XOrbSearchCompleter , self ) . eventFilter ( object , event )
# update the search results
if event . type ( ) == event . KeyPress : # ignore return keys
if event . key ( ) in ( Qt . Key_Return , Qt . Key_Enter ) :
return False
# ignore navigation keys
if event . key ( ) in ( Qt . Ke... |
def create ( self , graph ) :
"""Create a new scoped component .""" | scoped_config = self . get_scoped_config ( graph )
scoped_graph = ScopedGraph ( graph , scoped_config )
return self . func ( scoped_graph ) |
def as_of ( self , date ) :
"""Get a snapshot as of a specific date .
Returns an instance , or an iterable of the instances , of the
original model with all the attributes set according to what
was present on the object on the date provided .""" | if not self . instance :
return self . _as_of_set ( date )
queryset = self . get_queryset ( ) . filter ( history_date__lte = date )
try :
history_obj = queryset [ 0 ]
except IndexError :
raise self . instance . DoesNotExist ( "%s had not yet been created." % self . instance . _meta . object_name )
if histor... |
def doc_subst ( snippets ) :
"""Substitute format strings in class or function docstring""" | def decorator ( cls ) : # Strip the snippets to avoid trailing new lines and whitespace
stripped_snippets = { key : snippet . strip ( ) for ( key , snippet ) in snippets . items ( ) }
cls . __doc__ = cls . __doc__ . format ( ** stripped_snippets )
return cls
return decorator |
def request_leadership ( self , opt_count , skip_brokers , skip_partitions ) :
"""Under - balanced broker requests leadership from current leader , on the
pretext that it recursively can maintain its leadership count as optimal .
: key _ terms :
leader - balanced : Count of brokers as leader is at least opt -... | # Possible partitions which can grant leadership to broker
owned_partitions = list ( filter ( lambda p : self is not p . leader and len ( p . replicas ) > 1 , self . partitions , ) )
for partition in owned_partitions : # Partition not available to grant leadership when :
# 1 . Broker is already under leadership change ... |
def usb ( self , state ) :
"""Sets the monsoon ' s USB passthrough mode . This is specific to the
USB port in front of the monsoon box which connects to the powered
device , NOT the USB that is used to talk to the monsoon itself .
" Off " means USB always off .
" On " means USB always on .
" Auto " means ... | state_lookup = { "off" : 0 , "on" : 1 , "auto" : 2 }
state = state . lower ( )
if state in state_lookup :
current_state = self . mon . GetUsbPassthrough ( )
while ( current_state != state_lookup [ state ] ) :
self . mon . SetUsbPassthrough ( state_lookup [ state ] )
time . sleep ( 1 )
cu... |
def pca ( U , centre = False ) :
"""Compute the PCA basis for columns of input array ` U ` .
Parameters
U : array _ like
2D data array with rows corresponding to different variables and
columns corresponding to different observations
center : bool , optional ( default False )
Flag indicating whether to ... | if centre :
C = np . mean ( U , axis = 1 , keepdims = True )
U = U - C
else :
C = None
B , S , _ = np . linalg . svd ( U , full_matrices = False , compute_uv = True )
return B , S ** 2 , C |
def jsd ( p1 , p2 ) :
"""Compute Jensen - Shannon divergence between p1 and p2.
It assumes that p1 and p2 are already normalized that each of them sums to 1.""" | m = ( p1 + p2 ) / 2
return ( kld ( p1 , m ) + kld ( p2 , m ) ) / 2 |
def get_containers ( self , scope = None , artifact_uris = None ) :
"""GetContainers .
[ Preview API ] Gets containers filtered by a comma separated list of artifact uris within the same scope , if not specified returns all containers
: param str scope : A guid representing the scope of the container . This is ... | query_parameters = { }
if scope is not None :
query_parameters [ 'scope' ] = self . _serialize . query ( 'scope' , scope , 'str' )
if artifact_uris is not None :
query_parameters [ 'artifactUris' ] = self . _serialize . query ( 'artifact_uris' , artifact_uris , 'str' )
response = self . _send ( http_method = 'G... |
def clear ( ) :
"""Clears the terminal screen . This will have the effect of clearing
the whole visible space of the terminal and moving the cursor to the
top left . This does not do anything if not connected to a terminal .
. . versionadded : : 2.0""" | if not isatty ( sys . stdout ) :
return
# If we ' re on Windows and we don ' t have colorama available , then we
# clear the screen by shelling out . Otherwise we can use an escape
# sequence .
if WIN :
os . system ( 'cls' )
else :
sys . stdout . write ( '\033[2J\033[1;1H' ) |
def initialize_users ( self ) -> None :
"""Load device user data and initialize user management .""" | users = self . request ( 'get' , pwdgrp_url )
self . users = Users ( users , self . request ) |
def refresh_ip ( self , context , cancellation_context , ports ) :
"""Refresh IP Command , will refresh the ip of the vm and will update it on the resource
: param ResourceRemoteCommandContext context : the context the command runs on
: param cancellation _ context :
: param list [ string ] ports : the ports ... | resource_details = self . _parse_remote_model ( context )
# execute command
res = self . command_wrapper . execute_command_with_connection ( context , self . refresh_ip_command . refresh_ip , resource_details , cancellation_context , context . remote_endpoints [ 0 ] . app_context . app_request_json )
return set_command... |
def _assert_git_repo ( target ) :
"""Asserts that a given target directory is a git repository""" | hooks_dir = os . path . abspath ( os . path . join ( target , HOOKS_DIR_PATH ) )
if not os . path . isdir ( hooks_dir ) :
raise GitHookInstallerError ( u"{0} is not a git repository." . format ( target ) ) |
def build_list ( self , manifests ) :
"""Builds a manifest list or OCI image out of the given manifests""" | media_type = manifests [ 0 ] [ 'media_type' ]
if ( not all ( m [ 'media_type' ] == media_type for m in manifests ) ) :
raise PluginFailedException ( 'worker manifests have inconsistent types: {}' . format ( manifests ) )
if media_type == MEDIA_TYPE_DOCKER_V2_SCHEMA2 :
list_type = MEDIA_TYPE_DOCKER_V2_MANIFEST_L... |
def list_datacenters ( host , username , password , protocol = None , port = None ) :
'''Returns a list of datacenters for the the specified host .
host
The location of the host .
username
The username used to login to the host , such as ` ` root ` ` .
password
The password used to login to the host .
... | service_instance = salt . utils . vmware . get_service_instance ( host = host , username = username , password = password , protocol = protocol , port = port )
return salt . utils . vmware . list_datacenters ( service_instance ) |
def _get_2d_plot ( self , label_stable = True , label_unstable = True , ordering = None , energy_colormap = None , vmin_mev = - 60.0 , vmax_mev = 60.0 , show_colorbar = True , process_attributes = False , plt = None ) :
"""Shows the plot using pylab . Usually I won ' t do imports in methods ,
but since plotting i... | if plt is None :
plt = pretty_plot ( 8 , 6 )
from matplotlib . font_manager import FontProperties
if ordering is None :
( lines , labels , unstable ) = self . pd_plot_data
else :
( _lines , _labels , _unstable ) = self . pd_plot_data
( lines , labels , unstable ) = order_phase_diagram ( _lines , _labels... |
def delete_thing_type ( thingTypeName , region = None , key = None , keyid = None , profile = None ) :
'''Given a thing type name , delete it .
Returns { deleted : true } if the thing type was deleted and returns
{ deleted : false } if the thing type was not deleted .
. . versionadded : : 2016.11.0
CLI Exam... | try :
conn = _get_conn ( region = region , key = key , keyid = keyid , profile = profile )
conn . delete_thing_type ( thingTypeName = thingTypeName )
return { 'deleted' : True }
except ClientError as e :
err = __utils__ [ 'boto3.get_error' ] ( e )
if e . response . get ( 'Error' , { } ) . get ( 'Cod... |
def logged_query ( cr , query , args = None , skip_no_result = False ) :
"""Logs query and affected rows at level DEBUG .
: param query : a query string suitable to pass to cursor . execute ( )
: param args : a list , tuple or dictionary passed as substitution values
to cursor . execute ( ) .
: param skip _... | if args is None :
args = ( )
args = tuple ( args ) if type ( args ) == list else args
try :
cr . execute ( query , args )
except ( ProgrammingError , IntegrityError ) :
logger . error ( 'Error running %s' % cr . mogrify ( query , args ) )
raise
if not skip_no_result or cr . rowcount :
logger . debug... |
def parse_file ( self , name ) :
"""Parse the content of a file .
See ' parse ' method for information .
: param name : the pathname of the file to parse
: return : True on success ( no error detected ) , False otherwise""" | with open ( name , "rb" ) as fp :
return self . parse ( fp . read ( ) ) |
def table_context ( request , table , links = None , paginate_by = None , page = None , extra_context = None , paginator = None , show_hits = False , hit_label = 'Items' ) :
""": type table : Table""" | from django import __version__ as django_version
django_version = tuple ( [ int ( x ) for x in django_version . split ( '.' ) ] )
if django_version < ( 2 , 0 ) :
return django_pre_2_0_table_context ( request , table , links = links , paginate_by = paginate_by , extra_context = extra_context , paginator = paginator ... |
def rhochange ( self ) :
"""Re - factorise matrix when rho changes .""" | self . lu , self . piv = sl . cho_factor ( self . D , self . rho )
self . lu = np . asarray ( self . lu , dtype = self . dtype ) |
def make_dataclass ( cls_name , fields , * , bases = ( ) , namespace = None , init = True , repr = True , eq = True , order = False , unsafe_hash = False , frozen = False ) :
"""Return a new dynamically created dataclass .
The dataclass name will be ' cls _ name ' . ' fields ' is an iterable
of either ( name ) ... | if namespace is None :
namespace = { }
else : # Copy namespace since we ' re going to mutate it .
namespace = namespace . copy ( )
# While we ' re looking through the field names , validate that they
# are identifiers , are not keywords , and not duplicates .
seen = set ( )
anns = { }
for item in fields :
i... |
def reindex ( self ) :
"""Squeeze the indices of this blackboxing to ` ` 0 . . n ` ` .
Returns :
Blackbox : a new , reindexed | Blackbox | .
Example :
> > > partition = ( ( 3 , ) , ( 2 , 4 ) )
> > > output _ indices = ( 2 , 3)
> > > blackbox = Blackbox ( partition , output _ indices )
> > > blackbox .... | _map = dict ( zip ( self . micro_indices , reindex ( self . micro_indices ) ) )
partition = tuple ( tuple ( _map [ index ] for index in group ) for group in self . partition )
output_indices = tuple ( _map [ i ] for i in self . output_indices )
return Blackbox ( partition , output_indices ) |
def bin_laid_out_activations ( layout , activations , grid_size , threshold = 5 ) :
"""Given a layout and activations , overlays a grid on the layout and returns
averaged activations for each grid cell . If a cell contains less than ` threshold `
activations it will be discarded , so the number of returned data... | assert layout . shape [ 0 ] == activations . shape [ 0 ]
# calculate which grid cells each activation ' s layout position falls into
# first bin stays empty because nothing should be < 0 , so we add an extra bin
bins = np . linspace ( 0 , 1 , num = grid_size + 1 )
bins [ - 1 ] = np . inf
# last bin should include all h... |
def _issubclass_2 ( subclass , superclass , bound_Generic , bound_typevars , bound_typevars_readonly , follow_fwd_refs , _recursion_check ) :
"""Helper for _ issubclass , a . k . a pytypes . issubtype .""" | if is_Tuple ( superclass ) :
return _issubclass_Tuple ( subclass , superclass , bound_Generic , bound_typevars , bound_typevars_readonly , follow_fwd_refs , _recursion_check )
if is_Union ( superclass ) :
return _issubclass_Union ( subclass , superclass , bound_Generic , bound_typevars , bound_typevars_readonly... |
def preparse ( self , context ) :
"""Parse a portion of command line arguments with the early parser .
This method relies on ` ` context . argv ` ` and ` ` context . early _ parser ` `
and produces ` ` context . early _ args ` ` .
The ` ` context . early _ args ` ` object is the return value from argparse .
... | context . early_args , unused = ( context . early_parser . parse_known_args ( context . argv ) ) |
def lambdef_check ( self , original , loc , tokens ) :
"""Check for Python - style lambdas .""" | return self . check_strict ( "Python-style lambda" , original , loc , tokens ) |
def axisangledottoang_vel ( angle , axis , angle_dot , axis_dot ) :
"""Convert axis angle represetnation to angular velocity in body frame""" | Omega = angle_dot * axis + np . sin ( angle ) * axis_dot - ( 1 - np . cos ( angle ) ) * hat_map ( axis ) . dot ( axis_dot )
return Omega |
def remove_config ( reset = False ) :
'''Remove the current DSC Configuration . Removes current , pending , and previous
dsc configurations .
. . versionadded : : 2017.7.5
Args :
reset ( bool ) :
Attempts to reset the DSC configuration by removing the following
from ` ` C : \\ Windows \\ System32 \\ Con... | # Stopping a running config ( not likely to occur )
cmd = 'Stop-DscConfiguration'
log . info ( 'DSC: Stopping Running Configuration' )
try :
_pshell ( cmd )
except CommandExecutionError as exc :
if exc . info [ 'retcode' ] != 0 :
raise CommandExecutionError ( 'Failed to Stop DSC Configuration' , info = ... |
def base64url_decode ( input ) :
"""Helper method to base64url _ decode a string .
Args :
input ( str ) : A base64url _ encoded string to decode .""" | rem = len ( input ) % 4
if rem > 0 :
input += b'=' * ( 4 - rem )
return base64 . urlsafe_b64decode ( input ) |
def _set_permit_list ( self , v , load = False ) :
"""Setter method for permit _ list , mapped from YANG variable / arp / access _ list / permit / permit _ list ( list )
If this variable is read - only ( config : false ) in the
source YANG file , then _ set _ permit _ list is considered as a private
method . ... | if hasattr ( v , "_utype" ) :
v = v . _utype ( v )
try :
t = YANGDynClass ( v , base = YANGListType ( "ip_type host_ip mac_type host_mac" , permit_list . permit_list , yang_name = "permit-list" , rest_name = "ip" , parent = self , is_container = 'list' , user_ordered = False , path_helper = self . _path_helper ... |
def bundle_examples_with_goal ( sess , model , adv_x_list , y , goal , report_path , batch_size = BATCH_SIZE ) :
"""A post - processor version of attack bundling , that chooses the strongest
example from the output of multiple earlier bundling strategies .
: param sess : tf . session . Session
: param model :... | # Check the input
num_attacks = len ( adv_x_list )
assert num_attacks > 0
adv_x_0 = adv_x_list [ 0 ]
assert isinstance ( adv_x_0 , np . ndarray )
assert all ( adv_x . shape == adv_x_0 . shape for adv_x in adv_x_list )
# Allocate the output
out = np . zeros_like ( adv_x_0 )
m = adv_x_0 . shape [ 0 ]
# Initialize with ne... |
def removed ( self ) :
"""Returns list of removed ` ` FileNode ` ` objects .""" | if not self . parents :
return [ ]
return RemovedFileNodesGenerator ( [ n for n in self . _get_paths_for_status ( 'deleted' ) ] , self ) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.