signature stringlengths 29 44.1k | implementation stringlengths 0 85.2k |
|---|---|
def build ( cls : Type [ AN ] , node : ast . stmt ) -> List [ AN ] :
"""Starting at this ` ` node ` ` , check if it ' s an act node . If it ' s a context
manager , recurse into child nodes .
Returns :
List of all act nodes found .""" | if node_is_result_assignment ( node ) :
return [ cls ( node , ActNodeType . result_assignment ) ]
if node_is_pytest_raises ( node ) :
return [ cls ( node , ActNodeType . pytest_raises ) ]
if node_is_unittest_raises ( node ) :
return [ cls ( node , ActNodeType . unittest_raises ) ]
token = node . first_token... |
def ParseOptions ( cls , options , configuration_object ) :
"""Parses and validates options .
Args :
options ( argparse . Namespace ) : parser options .
configuration _ object ( CLITool ) : object to be configured by the argument
helper .
Raises :
BadConfigObject : when the configuration object is of th... | if not isinstance ( configuration_object , tools . CLITool ) :
raise errors . BadConfigObject ( 'Configuration object is not an instance of CLITool' )
process_memory_limit = cls . _ParseNumericOption ( options , 'process_memory_limit' )
if process_memory_limit and process_memory_limit < 0 :
raise errors . BadCo... |
def file_data_to_str ( data ) :
"""Convert file data to a string for display .
This function takes the file data produced by gather _ file _ data ( ) .""" | if not data :
return _ ( '<i>File name not recorded</i>' )
res = data [ 'name' ]
try :
mtime_as_str = time . strftime ( '%Y-%m-%d %H:%M:%S' , time . localtime ( data [ 'mtime' ] ) )
res += '<br><i>{}</i>: {}' . format ( _ ( 'Last modified' ) , mtime_as_str )
res += '<br><i>{}</i>: {} {}' . format ( _ ( ... |
def release_docs_side_effect ( content ) :
"""Updates the template so that curly braces are escaped correctly .
Args :
content ( str ) : The template for ` ` docs / index . rst . release . template ` ` .
Returns :
str : The updated template with properly escaped curly braces .""" | # First replace * * all * * curly braces .
result = content . replace ( "{" , "{{" ) . replace ( "}" , "}}" )
# Then reset the actual template arguments .
result = result . replace ( "{{version}}" , "{version}" )
result = result . replace ( "{{circleci_build}}" , "{circleci_build}" )
result = result . replace ( "{{trav... |
def all ( self , data = { } , ** kwargs ) :
"""Fetch All Refund
Returns :
Refund dict""" | return super ( Refund , self ) . all ( data , ** kwargs ) |
def tacacs_server_host_timeout ( self , ** kwargs ) :
"""Auto Generated Code""" | config = ET . Element ( "config" )
tacacs_server = ET . SubElement ( config , "tacacs-server" , xmlns = "urn:brocade.com:mgmt:brocade-aaa" )
host = ET . SubElement ( tacacs_server , "host" )
hostname_key = ET . SubElement ( host , "hostname" )
hostname_key . text = kwargs . pop ( 'hostname' )
timeout = ET . SubElement ... |
def has_rotational ( self ) :
"""Return true if any of the drive is HDD""" | for member in self . _drives_list ( ) :
if member . media_type == constants . MEDIA_TYPE_HDD :
return True
return False |
def checks_list ( ) :
'''List URL checked by uptime
CLI Example :
. . code - block : : bash
salt ' * ' uptime . checks _ list''' | application_url = _get_application_url ( )
log . debug ( '[uptime] get checks' )
jcontent = requests . get ( '{0}/api/checks' . format ( application_url ) ) . json ( )
return [ x [ 'url' ] for x in jcontent ] |
def mapping ( self , struct , key_depth = 1000 , tree_depth = 1 , update_callable = None ) :
"""Generates random values for dict - like objects
@ struct : the dict - like structure you want to fill with random data
@ size : # int number of random values to include in each @ tree _ depth
@ tree _ depth : # int... | if not tree_depth :
return self . _map_type ( )
_struct = struct ( )
add_struct = _struct . update if not update_callable else getattr ( _struct , update_callable )
for x in range ( key_depth ) :
add_struct ( { self . randstr : self . mapping ( struct , key_depth , tree_depth - 1 , update_callable ) } )
return ... |
def select ( self , * cluster_ids ) :
"""Select a list of clusters .""" | # HACK : allow for ` select ( 1 , 2 , 3 ) ` in addition to ` select ( [ 1 , 2 , 3 ] ) `
# This makes it more convenient to select multiple clusters with
# the snippet : ` : c 1 2 3 ` instead of ` : c 1,2,3 ` .
if cluster_ids and isinstance ( cluster_ids [ 0 ] , ( tuple , list ) ) :
cluster_ids = list ( cluster_ids ... |
def _run_command_inside_folder ( command , folder ) :
"""Run a command inside the given folder .
: param string command : the command to execute .
: param string folder : the folder where to execute the command .
: return : the return code of the process .
: rtype : Tuple [ int , str ]""" | logger . debug ( "command: %s" , command )
# avoid usage of shell = True
# see https : / / docs . openstack . org / bandit / latest / plugins / subprocess _ popen _ with _ shell _ equals _ true . html
process = subprocess . Popen ( command . split ( ) , stdout = subprocess . PIPE , cwd = folder )
stream_data = process ... |
def export_sbml ( model , y0 = None , volume = 1.0 , is_valid = True ) :
"""Export a model as a SBMLDocument .
Parameters
model : NetworkModel
y0 : dict
Initial condition .
volume : Real or Real3 , optional
A size of the simulation volume . 1 as a default .
is _ valid : bool , optional
Check if the ... | y0 = y0 or { }
import libsbml
document = libsbml . SBMLDocument ( 3 , 1 )
# ns = libsbml . XMLNamespaces ( )
# ns . add ( " http : / / www . ecell . org / ns / ecell4 " , " ecell4 " ) # XXX : DUMMY URI
# document . setNamespaces ( ns )
m = document . createModel ( )
comp1 = m . createCompartment ( )
comp1 . setId ( 'wo... |
def bisine_wave ( frequency ) :
"""Emit two sine waves , in stereo at different octaves .""" | # We can first our existing sine generator to generate two different
# waves .
f_hi = frequency
f_lo = frequency / 2.0
with tf . name_scope ( 'hi' ) :
sine_hi = sine_wave ( f_hi )
with tf . name_scope ( 'lo' ) :
sine_lo = sine_wave ( f_lo )
# Now , we have two tensors of shape [ 1 , _ samples ( ) , 1 ] . By con... |
def comicDownloaded ( self , comic , filename , text = None ) :
"""Write RSS entry for downloaded comic .""" | imageUrl = self . getUrlFromFilename ( filename )
size = None
if self . allowdownscale :
size = getDimensionForImage ( filename , MaxImageSize )
title = '%s - %s' % ( comic . name , os . path . basename ( filename ) )
pageUrl = comic . referrer
description = '<img src="%s"' % imageUrl
if size :
description += '... |
def pushprefixes ( self ) :
"""Add our prefixes to the wsdl so that when users invoke methods
and reference the prefixes , the will resolve properly .""" | for ns in self . prefixes :
self . wsdl . root . addPrefix ( ns [ 0 ] , ns [ 1 ] ) |
def get_contig_names ( fasta_file ) :
"""Gets contig names from a fasta file using SeqIO .
: param fasta _ file : Full path to uncompressed , fasta - formatted file
: return : List of contig names .""" | contig_names = list ( )
for contig in SeqIO . parse ( fasta_file , 'fasta' ) :
contig_names . append ( contig . id )
return contig_names |
def MI_getInstance ( self , env , instanceName , propertyList , cimClass ) : # pylint : disable = invalid - name
"""Return a specific CIM instance
Implements the WBEM operation GetInstance in terms
of the get _ instance method . A derived class will not normally
override this method .""" | logger = env . get_logger ( )
logger . log_debug ( 'CIMProvider MI_getInstance called...' )
keyNames = get_keys_from_class ( cimClass )
plist = None
if propertyList is not None :
lkns = [ kn . lower ( ) for kn in keyNames ]
props = pywbem . NocaseDict ( )
plist = [ s . lower ( ) for s in propertyList ]
... |
def account_representative ( self , account ) :
"""Returns the representative for * * account * *
: param account : Account to get representative for
: type account : str
: raises : : py : exc : ` nano . rpc . RPCException `
> > > rpc . account _ representative (
. . . account = " xrb _ 39a73oy5ungrhxy5z5... | account = self . _process_value ( account , 'account' )
payload = { "account" : account }
resp = self . call ( 'account_representative' , payload )
return resp [ 'representative' ] |
def action ( self ) :
"""Invoke functions according to the supplied flags""" | user = self . args [ '--user' ] if self . args [ '--user' ] else None
reset = True if self . args [ '--reset' ] else False
if self . args [ 'generate' ] :
generate_network ( user , reset )
elif self . args [ 'publish' ] :
publish_network ( user , reset ) |
def set_level ( level = 1 , logger = "TaskLogger" ) :
"""Set the logging level
Convenience function to set the logging level
Parameters
level : ` int ` or ` bool ` ( optional , default : 1)
If False or 0 , prints WARNING and higher messages .
If True or 1 , prints INFO and higher messages .
If 2 or high... | tasklogger = get_tasklogger ( logger )
tasklogger . set_level ( level )
return tasklogger |
def do_write ( self , args ) :
"""Send to the resource in use : send * IDN ?""" | if not self . current :
print ( 'There are no resources in use. Use the command "open".' )
return
try :
self . current . write ( args )
except Exception as e :
print ( e ) |
def camelcase_to_slash ( name ) :
"""Converts CamelCase to camel / case
code ripped from http : / / stackoverflow . com / questions / 1175208 / does - the - python - standard - library - have - function - to - convert - camelcase - to - camel - cas""" | s1 = re . sub ( '(.)([A-Z][a-z]+)' , r'\1/\2' , name )
return re . sub ( '([a-z0-9])([A-Z])' , r'\1/\2' , s1 ) . lower ( ) |
def include ( self , * fields , ** kwargs ) :
"""Return a new QuerySet instance that will include related objects .
If fields are specified , they must be non - hidden relationships .
If select _ related ( None ) is called , clear the list .""" | clone = self . _clone ( )
# Preserve the stickiness of related querysets
# NOTE : by default _ clone will clear this attribute
# . include does not modify the actual query , so we
# should not clear ` filter _ is _ sticky `
if self . query . filter_is_sticky :
clone . query . filter_is_sticky = True
clone . _includ... |
def _getrsyncoptions ( self ) :
"""Get options to be passed for rsync .""" | ignores = list ( self . DEFAULT_IGNORES )
ignores += self . config . option . rsyncignore
ignores += self . config . getini ( "rsyncignore" )
return { "ignores" : ignores , "verbose" : self . config . option . verbose } |
def draw_character_key ( self , surface , key , special = False ) :
"""Default drawing method for key .
Key is drawn as a simple rectangle filled using this
cell style background color attribute . Key value is printed
into drawn cell using internal font .
: param surface : Surface background should be drawn... | background_color = self . key_background_color
if special and self . special_key_background_color is not None :
background_color = self . special_key_background_color
pygame . draw . rect ( surface , background_color [ key . state ] , key . position + key . size )
size = self . font . size ( key . value )
x = key .... |
def _get_reference ( self ) :
"""Sets up necessary reference for robots , grippers , and objects .""" | super ( ) . _get_reference ( )
# indices for joints in qpos , qvel
self . robot_joints = list ( self . mujoco_robot . joints )
self . _ref_joint_pos_indexes = [ self . sim . model . get_joint_qpos_addr ( x ) for x in self . robot_joints ]
self . _ref_joint_vel_indexes = [ self . sim . model . get_joint_qvel_addr ( x ) ... |
def _get_workflow_menus ( self ) :
"""Creates menu entries for custom workflows .
Returns :
Dict of list of dicts ( ` ` { ' ' : [ { } ] , } ` ` ) . Menu entries .""" | results = defaultdict ( list )
from zengine . lib . cache import WFSpecNames
for name , title , category in WFSpecNames ( ) . get_or_set ( ) :
if self . current . has_permission ( name ) and category != 'hidden' :
wf_dict = { "text" : title , "wf" : name , "kategori" : category , "param" : "id" }
re... |
def mean_information_coefficient ( factor_data , group_adjust = False , by_group = False , by_time = None ) :
"""Get the mean information coefficient of specified groups .
Answers questions like :
What is the mean IC for each month ?
What is the mean IC for each group for our whole timerange ?
What is the m... | ic = factor_information_coefficient ( factor_data , group_adjust , by_group )
grouper = [ ]
if by_time is not None :
grouper . append ( pd . Grouper ( freq = by_time ) )
if by_group :
grouper . append ( 'group' )
if len ( grouper ) == 0 :
ic = ic . mean ( )
else :
ic = ( ic . reset_index ( ) . set_index... |
def Histograms ( self , run , tag ) :
"""Retrieve the histogram events associated with a run and tag .
Args :
run : A string name of the run for which values are retrieved .
tag : A string name of the tag for which values are retrieved .
Raises :
KeyError : If the run is not found , or the tag is not avai... | accumulator = self . GetAccumulator ( run )
return accumulator . Histograms ( tag ) |
def controls ( self , timeline_slider_args = { } , toggle_args = { } ) :
"""Creates interactive controls for the animation
Creates both a play / pause button , and a time slider at once
Parameters
timeline _ slider _ args : Dict , optional
A dictionary of arguments to be passed to timeline _ slider ( )
to... | self . timeline_slider ( ** timeline_slider_args )
self . toggle ( ** toggle_args ) |
def get_lbry_api_function_docs ( url = LBRY_API_RAW_JSON_URL ) :
"""Scrapes the given URL to a page in JSON format to obtain the documentation for the LBRY API
: param str url : URL to the documentation we need to obtain ,
pybry . constants . LBRY _ API _ RAW _ JSON _ URL by default
: return : List of functio... | try : # Grab the page content
docs_page = urlopen ( url )
# Read the contents of the actual url we grabbed and decode them into UTF - 8
contents = docs_page . read ( ) . decode ( "utf-8" )
# Return the contents loaded as JSON
return loads ( contents )
# If we get an exception , simply exit
excep... |
def cut_across_axis ( self , dim , minval = None , maxval = None ) :
'''Cut the mesh by a plane , discarding vertices that lie behind that
plane . Or cut the mesh by two parallel planes , discarding vertices
that lie outside them .
The region to keep is defined by an axis of perpendicularity ,
specified by ... | # vertex _ mask keeps track of the vertices we want to keep .
vertex_mask = np . ones ( ( len ( self . v ) , ) , dtype = bool )
if minval is not None :
predicate = self . v [ : , dim ] >= minval
vertex_mask = np . logical_and ( vertex_mask , predicate )
if maxval is not None :
predicate = self . v [ : , dim... |
def main ( ) :
"""Example program for tcod . event""" | WIDTH , HEIGHT = 120 , 60
TITLE = None
with tcod . console_init_root ( WIDTH , HEIGHT , TITLE , order = "F" , renderer = tcod . RENDERER_SDL ) as console :
tcod . sys_set_fps ( 24 )
while True :
tcod . console_flush ( )
for event in tcod . event . wait ( ) :
print ( event )
... |
def sort_kate_imports ( add_imports = ( ) , remove_imports = ( ) ) :
"""Sorts imports within Kate while maintaining cursor position and selection , even if length of file changes .""" | document = kate . activeDocument ( )
view = document . activeView ( )
position = view . cursorPosition ( )
selection = view . selectionRange ( )
sorter = SortImports ( file_contents = document . text ( ) , add_imports = add_imports , remove_imports = remove_imports , settings_path = os . path . dirname ( os . path . ab... |
def get_types_by_attr ( resource , template_id = None ) :
"""Using the attributes of the resource , get all the
types that this resource matches .
@ returns a dictionary , keyed on the template name , with the
value being the list of type names which match the resources
attributes .""" | resource_type_templates = [ ]
# Create a list of all of this resources attributes .
attr_ids = [ ]
for res_attr in resource . attributes :
attr_ids . append ( res_attr . attr_id )
all_resource_attr_ids = set ( attr_ids )
all_types = db . DBSession . query ( TemplateType ) . options ( joinedload_all ( 'typeattrs' ) ... |
def fix_e502 ( self , result ) :
"""Remove extraneous escape of newline .""" | ( line_index , _ , target ) = get_index_offset_contents ( result , self . source )
self . source [ line_index ] = target . rstrip ( '\n\r \t\\' ) + '\n' |
def _fS1 ( self , pos_pairs , A ) :
"""The gradient of the similarity constraint function w . r . t . A .
f = \ sum _ { ij } ( x _ i - x _ j ) A ( x _ i - x _ j ) ' = \ sum _ { ij } d _ ij * A * d _ ij '
df / dA = d ( d _ ij * A * d _ ij ' ) / dA
Note that d _ ij * A * d _ ij ' = tr ( d _ ij * A * d _ ij ' ) ... | dim = pos_pairs . shape [ 2 ]
diff = pos_pairs [ : , 0 , : ] - pos_pairs [ : , 1 , : ]
return np . einsum ( 'ij,ik->jk' , diff , diff ) |
def parse_cell ( self , cell , coords , cell_mode = CellMode . cooked ) :
"""Tries to convert the value first to an int , then a float and if neither is
successful it returns the string value .""" | try :
return int ( cell )
except ValueError :
pass
try :
return float ( cell )
except ValueError :
pass
# TODO Check for dates ?
return cell |
def to_java_array ( m ) :
'''to _ java _ array ( m ) yields to _ java _ ints ( m ) if m is an array of integers and to _ java _ doubles ( m ) if
m is anything else . The numpy array m is tested via numpy . issubdtype ( m . dtype , numpy . int64 ) .''' | if not hasattr ( m , '__iter__' ) :
return m
m = np . asarray ( m )
if np . issubdtype ( m . dtype , np . dtype ( int ) . type ) or all ( isinstance ( x , num . Integral ) for x in m ) :
return to_java_ints ( m )
else :
return to_java_doubles ( m ) |
def log_html ( self , log ) -> str :
"""Return single check sub - result string as HTML or not if below log
level .""" | if not self . omit_loglevel ( log [ "status" ] ) :
emoticon = EMOTICON [ log [ "status" ] ]
status = log [ "status" ]
message = html . escape ( log [ "message" ] ) . replace ( "\n" , "<br/>" )
return ( "<li class='details_item'>" f"<span class='details_indicator'>{emoticon} {status}</span>" f"<span clas... |
def standard_parsing_functions ( Block , Tx ) :
"""Return the standard parsing functions for a given Block and Tx class .
The return value is expected to be used with the standard _ streamer function .""" | def stream_block ( f , block ) :
assert isinstance ( block , Block )
block . stream ( f )
def stream_blockheader ( f , blockheader ) :
assert isinstance ( blockheader , Block )
blockheader . stream_header ( f )
def stream_tx ( f , tx ) :
assert isinstance ( tx , Tx )
tx . stream ( f )
def parse_... |
def tally_role_columns ( self ) :
"""Sum up all of the stat columns .""" | totals = self . report [ "totals" ]
roles = self . report [ "roles" ]
totals [ "dependencies" ] = sum ( roles [ item ] [ "total_dependencies" ] for item in roles )
totals [ "defaults" ] = sum ( roles [ item ] [ "total_defaults" ] for item in roles )
totals [ "facts" ] = sum ( roles [ item ] [ "total_facts" ] for item i... |
def read_string ( self , start : int , line : int , col : int , prev : Token ) -> Token :
"""Read a string token from the source file .""" | source = self . source
body = source . body
body_length = len ( body )
position = start + 1
chunk_start = position
value : List [ str ] = [ ]
append = value . append
while position < body_length :
char = body [ position ]
if char in "\n\r" :
break
if char == '"' :
append ( body [ chunk_start... |
def get_cache_key ( brain_or_object ) :
"""Generate a cache key for a common brain or object
: param brain _ or _ object : A single catalog brain or content object
: type brain _ or _ object : ATContentType / DexterityContentType / CatalogBrain
: returns : Cache Key
: rtype : str""" | key = [ get_portal_type ( brain_or_object ) , get_id ( brain_or_object ) , get_uid ( brain_or_object ) , # handle different domains gracefully
get_url ( brain_or_object ) , # Return the microsecond since the epoch in GMT
get_modification_date ( brain_or_object ) . micros ( ) , ]
return "-" . join ( map ( lambda x : str... |
def _escape_token ( token , alphabet ) :
"""Escape away underscores and OOV characters and append ' _ ' .
This allows the token to be expressed as the concatenation of a list
of subtokens from the vocabulary . The underscore acts as a sentinel
which allows us to invertibly concatenate multiple such lists .
... | if not isinstance ( token , six . text_type ) :
raise ValueError ( "Expected string type for token, got %s" % type ( token ) )
token = token . replace ( u"\\" , u"\\\\" ) . replace ( u"_" , u"\\u" )
ret = [ c if c in alphabet and c != u"\n" else r"\%d;" % ord ( c ) for c in token ]
return u"" . join ( ret ) + "_" |
def new_fully_connected ( self , name : str , output_count : int , relu = True , input_layer_name : str = None ) :
"""Creates a new fully connected layer .
: param name : name for the layer .
: param output _ count : number of outputs of the fully connected layer .
: param relu : boolean flag to set if ReLu s... | with tf . variable_scope ( name ) :
input_layer = self . __network . get_layer ( input_layer_name )
vectorized_input , dimension = self . vectorize_input ( input_layer )
weights = self . __make_var ( 'weights' , shape = [ dimension , output_count ] )
biases = self . __make_var ( 'biases' , shape = [ out... |
def retrieve ( self , * args ) :
"""Get a value previously . store ( . . . ) ' d .
Needs at least five arguments . The - 1th is the tick
within the turn you want ,
the - 2th is that turn , the - 3th is the branch ,
and the - 4th is the key . All other arguments identify
the entity that the key is in .""" | ret = self . _base_retrieve ( args )
if ret is None :
raise HistoryError ( "Set, then deleted" , deleted = True )
elif ret is KeyError :
raise ret
return ret |
def set_review_whether_correct ( self , during_attempt = None , after_attempt = None , before_deadline = None , after_deadline = None ) :
"""stub""" | whether_correct = self . my_osid_object_form . _my_map [ 'reviewOptions' ] [ 'whetherCorrect' ]
if during_attempt is not None :
whether_correct [ 'duringAttempt' ] = bool ( during_attempt )
if after_attempt is not None :
whether_correct [ 'afterAttempt' ] = bool ( after_attempt )
if before_deadline is not None ... |
def start_all ( self ) :
"""Start all nodes""" | pool = Pool ( concurrency = 3 )
for node in self . nodes . values ( ) :
pool . append ( node . start )
yield from pool . join ( ) |
def shred ( args ) :
"""% prog shred unitigfile
Shred the unitig into one fragment per unitig to fix . This is the last
resort as a desperate fix .""" | p = OptionParser ( shred . __doc__ )
opts , args = p . parse_args ( args )
if len ( args ) != 1 :
sys . exit ( not p . print_help ( ) )
s , = args
u = UnitigLayout ( s )
u . shred ( )
u . print_to_file ( inplace = True ) |
def create_table_rate_rule ( cls , table_rate_rule , ** kwargs ) :
"""Create TableRateRule
Create a new TableRateRule
This method makes a synchronous HTTP request by default . To make an
asynchronous HTTP request , please pass async = True
> > > thread = api . create _ table _ rate _ rule ( table _ rate _ r... | kwargs [ '_return_http_data_only' ] = True
if kwargs . get ( 'async' ) :
return cls . _create_table_rate_rule_with_http_info ( table_rate_rule , ** kwargs )
else :
( data ) = cls . _create_table_rate_rule_with_http_info ( table_rate_rule , ** kwargs )
return data |
def _get_column_width ( self , complete_state ) :
"""Return the width of each column .""" | return max ( get_cwidth ( c . display ) for c in complete_state . current_completions ) + 1 |
def _computeP ( self ) :
"""m . _ computeP ( ) - - [ utility ] Compute the probability matrix ( from the internal log - probability matrix )""" | P = [ ]
for i in range ( self . width ) : # print i ,
_p = { }
for L in ACGT :
_p [ L ] = math . pow ( 2.0 , self . logP [ i ] [ L ] )
P . append ( _p )
# print
self . P = P |
def beginning_of_history ( self ) :
u'''Move to the first line in the history .''' | self . history_cursor = 0
if len ( self . history ) > 0 :
self . l_buffer = self . history [ 0 ] |
def get ( self , timeout = 10 ) :
"""get ( ) - > { ' id ' : 32 - byte - md5 , ' body ' : msg - body }""" | req = self . req ( { 'op' : 'GET' , 'timeout' : timeout } )
if req . status_code != 200 :
return None
result = req . json ( )
if result . get ( 'status' ) != 'ok' :
return False
return result |
def set_dashboard_tags ( self , id , ** kwargs ) : # noqa : E501
"""Set all tags associated with a specific dashboard # noqa : E501
# noqa : E501
This method makes a synchronous HTTP request by default . To make an
asynchronous HTTP request , please pass async _ req = True
> > > thread = api . set _ dashboa... | kwargs [ '_return_http_data_only' ] = True
if kwargs . get ( 'async_req' ) :
return self . set_dashboard_tags_with_http_info ( id , ** kwargs )
# noqa : E501
else :
( data ) = self . set_dashboard_tags_with_http_info ( id , ** kwargs )
# noqa : E501
return data |
def pop ( self , index = None ) :
"""L . pop ( [ index ] ) - > item - - remove and return item at index ( default last ) .
Raises IndexError if list is empty or index is out of range .""" | if index is None :
index = len ( self . _col_list ) - 1
key = self . _get_object_key ( self . _col_list [ index ] )
del self . _col_dict [ key ]
return self . _col_list . pop ( index ) |
def printcsv ( csvdiffs ) :
"""print the csv""" | for row in csvdiffs :
print ( ',' . join ( [ str ( cell ) for cell in row ] ) ) |
def segment_curvature ( self , t , use_inf = False ) :
"""returns the curvature of the segment at t .
Notes
If you receive a RuntimeWarning , run command
> > > old = np . seterr ( invalid = ' raise ' )
This can be undone with
> > > np . seterr ( * * old )""" | dz = self . derivative ( t )
ddz = self . derivative ( t , n = 2 )
dx , dy = dz . real , dz . imag
ddx , ddy = ddz . real , ddz . imag
old_np_seterr = np . seterr ( invalid = 'raise' )
try :
kappa = abs ( dx * ddy - dy * ddx ) / sqrt ( dx * dx + dy * dy ) ** 3
except ( ZeroDivisionError , FloatingPointError ) : # t... |
def get_type ( mime = None , ext = None ) :
"""Returns the file type instance searching by
MIME type or file extension .
Args :
ext : file extension string . E . g : jpg , png , mp4 , mp3
mime : MIME string . E . g : image / jpeg , video / mpeg
Returns :
The matched file type instance . Otherwise None .... | for kind in types :
if kind . extension is ext or kind . mime is mime :
return kind
return None |
def submit_plain_query ( self , operation ) :
"""Sends a plain query to server .
This call will transition session into pending state .
If some operation is currently pending on the session , it will be
cancelled before sending this request .
Spec : http : / / msdn . microsoft . com / en - us / library / dd... | self . messages = [ ]
self . cancel_if_pending ( )
self . res_info = None
logger . info ( "Sending query %s" , operation [ : 100 ] )
w = self . _writer
with self . querying_context ( tds_base . PacketType . QUERY ) :
if tds_base . IS_TDS72_PLUS ( self ) :
self . _start_query ( )
w . write_ucs2 ( operati... |
def schedule_servicegroup_svc_downtime ( self , servicegroup , start_time , end_time , fixed , trigger_id , duration , author , comment ) :
"""Schedule a service downtime for each service of a servicegroup
Format of the line that triggers function call : :
SCHEDULE _ SERVICEGROUP _ SVC _ DOWNTIME ; < servicegro... | for serv in servicegroup . get_services ( ) :
self . schedule_svc_downtime ( serv , start_time , end_time , fixed , trigger_id , duration , author , comment ) |
def make_zip ( self , filename , files = None , path = None , clone = None , compress = True ) :
"""Create a Zip archive .
Provide any of the following :
files - A list of files
path - A directory of . txt files
clone - Copy any files from a zip archive not specified above
Duplicate files will be ignored ... | if filename and os . path . exists ( filename ) :
raise IOError ( 'File exists: %s' % filename )
files = files or [ ]
arcnames = [ ]
if path and os . path . isdir ( path ) :
files += glob . glob ( os . path . join ( path , '*.txt' ) )
if compress :
compress_level = zipfile . ZIP_DEFLATED
else :
compress... |
def get_num_confirmations ( tx_hash , coin_symbol = 'btc' , api_key = None ) :
'''Given a tx _ hash , return the number of confirmations that transactions has .
Answer is going to be from 0 - current _ block _ height .''' | return get_transaction_details ( tx_hash = tx_hash , coin_symbol = coin_symbol , limit = 1 , api_key = api_key ) . get ( 'confirmations' ) |
def _bind_service ( package_name , cls_name , binder = Injected ) :
"""Bind service to application injector .
: param package _ name : service package
: type package _ name : str
: param cls _ name : service class
: type cls _ name : str
: param binder : current application binder , injected
: type bind... | module = importlib . import_module ( package_name )
cls = getattr ( module , cls_name )
binder . bind ( cls , to = binder . injector . create_object ( cls ) , scope = singleton )
logging . debug ( "Created {0} binding." . format ( cls ) ) |
def paths ( obj , dirs = True , leaves = True , path = [ ] , skip = False ) :
"""Yield all paths of the object .
Arguments :
obj - - An object to get paths from .
Keyword Arguments :
dirs - - Yield intermediate paths .
leaves - - Yield the paths with leaf objects .
path - - A list of keys representing t... | if isinstance ( obj , MutableMapping ) : # Python 3 support
if PY3 :
iteritems = obj . items ( )
string_class = str
else : # Default to PY2
iteritems = obj . iteritems ( )
string_class = basestring
for ( k , v ) in iteritems :
if issubclass ( k . __class__ , ( string_... |
def get_linked_properties ( cli_ctx , app , resource_group , read_properties = None , write_properties = None ) :
"""Maps user - facing role names to strings used to identify them on resources .""" | roles = { "ReadTelemetry" : "api" , "WriteAnnotations" : "annotations" , "AuthenticateSDKControlChannel" : "agentconfig" }
sub_id = get_subscription_id ( cli_ctx )
tmpl = '/subscriptions/{}/resourceGroups/{}/providers/microsoft.insights/components/{}' . format ( sub_id , resource_group , app )
linked_read_properties , ... |
def _notification ( self , context , method , routers , operation , shuffle_agents ) :
"""Notify all or individual Cisco cfg agents .""" | if extensions . is_extension_supported ( self . _l3plugin , L3AGENT_SCHED ) :
adm_context = ( context . is_admin and context or context . elevated ( ) )
# This is where hosting device gets scheduled to Cisco cfg agent
self . _l3plugin . schedule_routers ( adm_context , routers )
self . _agent_notificati... |
def _dumpArrayDictToFile ( filelike , arrayDict ) :
"""Function to serialize and write ` ` numpy . array ` ` contained in a dictionary
to a file . See also : func : ` _ dumpArrayToFile ` and : func : ` _ dumpNdarrayToFile ` .
: param filelike : can be a file or a file - like object that provides the
methods `... | metadataList = list ( )
for arrayKey in sorted ( arrayDict ) :
array = arrayDict [ arrayKey ]
if array . ndim == 1 :
metadata = _dumpArrayToFile ( filelike , array )
else :
metadata = _dumpNdarrayToFile ( filelike , array )
metadata [ 'arrayKey' ] = arrayKey
metadataList . append ( m... |
def find_neighbors ( neighbors , coords , I , source_files , f , sides ) :
"""Find the tile neighbors based on filenames
Parameters
neighbors : dict
Dictionary that stores the neighbors . Format is
neighbors [ " source _ file _ name " ] [ " side " ] = " neighbor _ source _ file _ name "
coords : list
Li... | for i , c1 in enumerate ( coords ) :
me = source_files [ I [ i ] ]
# If the left neighbor has already been found . . .
if neighbors [ me ] [ sides [ 0 ] ] != '' :
continue
# could try coords [ i : ] ( + fixes ) for speed if it becomes a problem
for j , c2 in enumerate ( coords ) :
if... |
def get ( self , wrap_exception = False ) :
"""Return the return value of this Attempt instance or raise an Exception .
If wrap _ exception is true , this Attempt is wrapped inside of a
RetryError before being raised .""" | if self . has_exception :
if wrap_exception :
raise RetryError ( self )
else :
six . reraise ( self . value [ 0 ] , self . value [ 1 ] , self . value [ 2 ] )
else :
return self . value |
def summary ( self , varnames = None , ranefs = False , transformed = False , hpd = .95 , quantiles = None , diagnostics = [ 'effective_n' , 'gelman_rubin' ] ) :
'''Returns a DataFrame of summary / diagnostic statistics for the parameters .
Args :
varnames ( list ) : List of variable names to include ; if None ... | samples = self . to_df ( varnames , ranefs , transformed )
# build the basic DataFrame
df = pd . DataFrame ( { 'mean' : samples . mean ( 0 ) , 'sd' : samples . std ( 0 ) } )
# add user - specified quantiles
if quantiles is not None :
if not isinstance ( quantiles , ( list , tuple ) ) :
quantiles = [ quantil... |
def with_binaries ( self , * args , ** kw ) :
"""Add binaries tagged to this artifact .
For example : : :
provides = setup _ py (
name = ' my _ library ' ,
zip _ safe = True
) . with _ binaries (
my _ command = ' : my _ library _ bin '
This adds a console _ script entry _ point for the python _ binary... | for arg in args :
if isinstance ( arg , dict ) :
self . _binaries . update ( arg )
self . _binaries . update ( kw )
return self |
def digest ( self , hashname = "sha1" ) :
"""Compute a checksum for the data . Default uses sha1 for speed .
Examples
> > > import binascii
> > > import zarr
> > > z = zarr . empty ( shape = ( 10000 , 10000 ) , chunks = ( 1000 , 1000 ) )
> > > binascii . hexlify ( z . digest ( ) )
b ' 041f90bc7a571452af... | h = hashlib . new ( hashname )
for i in itertools . product ( * [ range ( s ) for s in self . cdata_shape ] ) :
h . update ( self . chunk_store . get ( self . _chunk_key ( i ) , b"" ) )
h . update ( self . store . get ( self . _key_prefix + array_meta_key , b"" ) )
h . update ( self . store . get ( self . attrs . k... |
def apply_boundary_conditions_to_cm ( external_indices , cm ) :
"""Remove connections to or from external nodes .""" | cm = cm . copy ( )
cm [ external_indices , : ] = 0
# Zero - out row
cm [ : , external_indices ] = 0
# Zero - out columnt
return cm |
def mkzip ( archive , items , mode = "w" , save_full_paths = False ) :
"""Recursively zip a directory .
Args :
archive ( zipfile . ZipFile or str ) : ZipFile object add to or path to the
output zip archive .
items ( str or list of str ) : Single item or list of items ( files and
directories ) to be added ... | close = False
try :
if not isinstance ( archive , zipfile . ZipFile ) :
archive = zipfile . ZipFile ( archive , mode , allowZip64 = True )
close = True
logger . info ( "mkdzip: Creating %s, from: %s" , archive . filename , items )
if isinstance ( items , str ) :
items = [ items ]
... |
def reorient_image2 ( image , orientation = 'RAS' ) :
"""Reorient an image .
Example
> > > import ants
> > > mni = ants . image _ read ( ants . get _ data ( ' mni ' ) )
> > > mni2 = mni . reorient _ image2 ( )""" | if image . dimension != 3 :
raise ValueError ( 'image must have 3 dimensions' )
inpixeltype = image . pixeltype
ndim = image . dimension
if image . pixeltype != 'float' :
image = image . clone ( 'float' )
libfn = utils . get_lib_fn ( 'reorientImage2' )
itkimage = libfn ( image . pointer , orientation )
new_img ... |
def CheckFont ( page , fontname ) :
"""Return an entry in the page ' s font list if reference name matches .""" | for f in page . getFontList ( ) :
if f [ 4 ] == fontname :
return f
if f [ 3 ] . lower ( ) == fontname . lower ( ) :
return f
return None |
def transform_around ( matrix , point ) :
"""Given a transformation matrix , apply its rotation
around a point in space .
Parameters
matrix : ( 4,4 ) or ( 3 , 3 ) float , transformation matrix
point : ( 3 , ) or ( 2 , ) float , point in space
Returns
result : ( 4,4 ) transformation matrix""" | point = np . asanyarray ( point )
matrix = np . asanyarray ( matrix )
dim = len ( point )
if matrix . shape != ( dim + 1 , dim + 1 ) :
raise ValueError ( 'matrix must be (d+1, d+1)' )
translate = np . eye ( dim + 1 )
translate [ : dim , dim ] = - point
result = np . dot ( matrix , translate )
translate [ : dim , di... |
def export ( self , top = True ) :
"""Exports object to its string representation .
Args :
top ( bool ) : if True appends ` internal _ name ` before values .
All non list objects should be exported with value top = True ,
all list objects , that are embedded in as fields inlist objects
should be exported ... | out = [ ]
if top :
out . append ( self . _internal_name )
out . append ( str ( len ( self . typical_or_extreme_periods ) ) )
for obj in self . typical_or_extreme_periods :
out . append ( obj . export ( top = False ) )
return "," . join ( out ) |
def beam_search ( self , text : str , n_words : int , no_unk : bool = True , top_k : int = 10 , beam_sz : int = 1000 , temperature : float = 1. , sep : str = ' ' , decoder = decode_spec_tokens ) :
"Return the ` n _ words ` that come after ` text ` using beam search ." | ds = self . data . single_dl . dataset
self . model . reset ( )
xb , yb = self . data . one_item ( text )
nodes = None
xb = xb . repeat ( top_k , 1 )
nodes = xb . clone ( )
scores = xb . new_zeros ( 1 ) . float ( )
with torch . no_grad ( ) :
for k in progress_bar ( range ( n_words ) , leave = False ) :
out ... |
def default_blockstack_api_opts ( working_dir , config_file = None ) :
"""Get our default blockstack RESTful API opts from a config file ,
or from sane defaults .""" | from . util import url_to_host_port , url_protocol
if config_file is None :
config_file = virtualchain . get_config_filename ( get_default_virtualchain_impl ( ) , working_dir )
parser = SafeConfigParser ( )
parser . read ( config_file )
blockstack_api_opts = { }
indexer_url = None
api_port = DEFAULT_API_PORT
api_ho... |
def frames ( self ) :
"""Retrieve a new frame from the PhoXi and convert it to a ColorImage ,
a DepthImage , and an IrImage .
Returns
: obj : ` tuple ` of : obj : ` ColorImage ` , : obj : ` DepthImage ` , : obj : ` IrImage ` , : obj : ` numpy . ndarray `
The ColorImage , DepthImage , and IrImage of the curr... | # Run a software trigger
times = [ ]
rospy . ServiceProxy ( 'phoxi_camera/start_acquisition' , Empty ) ( )
rospy . ServiceProxy ( 'phoxi_camera/trigger_image' , TriggerImage ) ( )
self . _cur_color_im = None
self . _cur_depth_im = None
self . _cur_normal_map = None
rospy . ServiceProxy ( 'phoxi_camera/get_frame' , GetF... |
def show_support_save_status_output_show_support_save_status_rbridge_id ( self , ** kwargs ) :
"""Auto Generated Code""" | config = ET . Element ( "config" )
show_support_save_status = ET . Element ( "show_support_save_status" )
config = show_support_save_status
output = ET . SubElement ( show_support_save_status , "output" )
show_support_save_status = ET . SubElement ( output , "show-support-save-status" )
rbridge_id = ET . SubElement ( s... |
def transform_package ( mtype , files , components ) :
'''Put together header and list of data into one json output .
feature _ list contains all the information about the data to be extracted :
features , feature _ names , feature _ components , feature _ min , feature _ max''' | data_dict = transform_header ( mtype )
neurons = load_neurons ( files )
for comp in components :
params = PARAM_MAP [ comp . name ]
for feature in comp . features :
result = stats . fit_results_to_dict ( extract_data ( neurons , feature . name , params ) , feature . limits . min , feature . limits . max... |
def experiments_predictions_update_state_active ( self , experiment_id , run_id ) :
"""Update state of given prediction to active .
Parameters
experiment _ id : string
Unique experiment identifier
run _ id : string
Unique model run identifier
Returns
ModelRunHandle
Handle for updated model run or No... | # Get prediction to ensure that it exists
model_run = self . experiments_predictions_get ( experiment_id , run_id )
if model_run is None :
return None
# Update predition state
return self . predictions . update_state ( run_id , modelrun . ModelRunActive ( ) ) |
def edit_matching_entry ( program , arguments ) :
"""Edit the matching entry .""" | entry = program . select_entry ( * arguments )
entry . context . execute ( "pass" , "edit" , entry . name ) |
def get_warning_choice ( self , message , short_message , style = wx . YES_NO | wx . NO_DEFAULT | wx . ICON_WARNING ) :
"""Launches proceeding dialog and returns True if ok to proceed""" | dlg = GMD . GenericMessageDialog ( self . main_window , message , short_message , style )
choice = dlg . ShowModal ( )
dlg . Destroy ( )
return choice == wx . ID_YES |
def path_localLocationCheck ( self , d_msg , ** kwargs ) :
"""Check if a path exists on the local filesystem
: param self :
: param kwargs :
: return :""" | b_pull = False
d_meta = d_msg [ 'meta' ]
if 'do' in d_meta :
if d_meta [ 'do' ] == 'pull' :
b_pull = True
if 'local' in d_meta :
d_local = d_meta [ 'local' ]
if 'to' in d_meta :
d_local = d_meta [ 'to' ]
str_localPathFull = d_local [ 'path' ]
str_localPath , str_unpack = os . path . split ( str_loca... |
def _cleanup_resources ( self , initialized_resources ) :
"""Cleanup all resources that we own that are open .""" | cleanup_errors = [ ]
# Make sure we clean up all resources that we can and don ' t error out at the
# first one .
for name , res in initialized_resources . items ( ) :
try :
if res . opened :
res . close ( )
except Exception :
_type , value , traceback = sys . exc_info ( )
cl... |
def apply_widget_template ( self , field_name ) :
"""Applies widget template overrides if available .
The method uses the ` get _ widget _ template ` method to determine if the widget
template should be exchanged . If a template is available , the template _ name
property of the widget instance is updated .
... | field = self . fields [ field_name ]
template_name = self . get_widget_template ( field_name , field )
if template_name :
field . widget . template_name = template_name |
def extract_germline_vcinfo ( data , out_dir ) :
"""Extract germline VCFs from existing tumor inputs .""" | supported_germline = set ( [ "vardict" , "octopus" , "freebayes" ] )
if dd . get_phenotype ( data ) in [ "tumor" ] :
for v in _get_variants ( data ) :
if v . get ( "variantcaller" ) in supported_germline :
if v . get ( "germline" ) :
return v
else :
d ... |
def init_domain_ledger ( self ) :
"""This is usually an implementation of Ledger""" | if self . config . primaryStorage is None :
genesis_txn_initiator = GenesisTxnInitiatorFromFile ( self . genesis_dir , self . config . domainTransactionsFile )
return Ledger ( CompactMerkleTree ( hashStore = self . getHashStore ( 'domain' ) ) , dataDir = self . dataLocation , fileName = self . config . domainTr... |
def _fill_diagonals ( self , m ) :
"""Fills diagonals of ` nsites ` matrices in ` m ` so rows sum to 0.""" | assert m . shape == ( self . nsites , N_CODON , N_CODON )
for r in range ( self . nsites ) :
scipy . fill_diagonal ( m [ r ] , 0 )
m [ r ] [ self . _diag_indices ] -= scipy . sum ( m [ r ] , axis = 1 ) |
def respond ( self ) :
"""Call the gateway and write its iterable output .""" | mrbs = self . server . max_request_body_size
if self . chunked_read :
self . rfile = ChunkedRFile ( self . conn . rfile , mrbs )
else :
cl = int ( self . inheaders . get ( "Content-Length" , 0 ) )
if mrbs and mrbs < cl :
if not self . sent_headers :
self . simple_response ( "413 Request ... |
def version ( self ) :
"""Get the QS Mobile version .""" | return self . get_json ( URL_VERSION . format ( self . _url ) , astext = True ) |
def _unescape_match ( self , match ) :
"""Given an re . Match , unescape the escape code it represents .""" | char = match . group ( 1 )
if char in self . ESCAPE_LOOKUP :
return self . ESCAPE_LOOKUP [ char ]
elif not char :
raise KatcpSyntaxError ( "Escape slash at end of argument." )
else :
raise KatcpSyntaxError ( "Invalid escape character %r." % ( char , ) ) |
def randomSplit ( self , weights , seed = None ) :
"""Randomly splits this : class : ` DataFrame ` with the provided weights .
: param weights : list of doubles as weights with which to split the DataFrame . Weights will
be normalized if they don ' t sum up to 1.0.
: param seed : The seed for sampling .
> >... | for w in weights :
if w < 0.0 :
raise ValueError ( "Weights must be positive. Found weight value: %s" % w )
seed = seed if seed is not None else random . randint ( 0 , sys . maxsize )
rdd_array = self . _jdf . randomSplit ( _to_list ( self . sql_ctx . _sc , weights ) , long ( seed ) )
return [ DataFrame ( r... |
def _create_or_update_partition ( self , org_name , part_name , desc , dci_id = UNKNOWN_DCI_ID , vrf_prof = None , service_node_ip = UNKNOWN_SRVN_NODE_IP , operation = 'POST' ) :
"""Send create or update partition request to the DCNM .
: param org _ name : name of organization
: param part _ name : name of part... | if part_name is None :
part_name = self . _part_name
if vrf_prof is None or dci_id == UNKNOWN_DCI_ID or ( service_node_ip == UNKNOWN_SRVN_NODE_IP ) :
part_info = self . _get_partition ( org_name , part_name )
if vrf_prof is None :
vrf_prof = self . get_partition_vrfProf ( org_name , part_name , part_info = ... |
def bind ( self , devices_to_bind ) :
"""This function allows an entity to list the devices to subscribe for data . This function must be called
at least once , before doing a subscribe . Subscribe function will listen to devices that are bound here .
Args :
devices _ to _ bind ( list ) : an array of devices ... | if self . entity_api_key == "" :
return { 'status' : 'failure' , 'response' : 'No API key found in request' }
url = self . base_url + "api/0.1.0/subscribe/bind"
headers = { "apikey" : self . entity_api_key }
data = { "exchange" : "amq.topic" , "keys" : devices_to_bind , "queue" : self . entity_id }
with self . no_s... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.