signature stringlengths 29 44.1k | implementation stringlengths 0 85.2k |
|---|---|
def add_interval_annotations ( self , temp_idx , durations , labels , values = None , colourName = 'Purple' , colour = '#c832ff' , name = '' , view = None , presentationName = None ) :
"""add a labelled interval annotation layer
Args :
temp _ idx ( float iterable ) : The temporal indices of invervals
duration... | model = self . data . appendChild ( self . doc . createElement ( 'model' ) )
imodel = self . nbdata
for atname , atval in [ ( 'id' , imodel + 1 ) , ( 'dataset' , imodel ) , ( 'name' , name ) , ( 'sampleRate' , self . samplerate ) , ( 'type' , 'sparse' ) , ( 'dimensions' , '3' ) , ( 'subtype' , 'region' ) , ( 'resolutio... |
def set_cert ( self , key_file = None , cert_file = None , cert_reqs = None , ca_certs = None , assert_hostname = None , assert_fingerprint = None , ca_cert_dir = None ) :
"""This method should only be called once , before the connection is used .""" | # If cert _ reqs is not provided , we can try to guess . If the user gave
# us a cert database , we assume they want to use it : otherwise , if
# they gave us an SSL Context object we should use whatever is set for
# it .
if cert_reqs is None :
if ca_certs or ca_cert_dir :
cert_reqs = 'CERT_REQUIRED'
el... |
def define_as_input ( self , pin , pullup = False ) :
"""Set the input or output mode for a specified pin . Mode should be
either GPIO . OUT or GPIO . IN .""" | self . _validate_channel ( pin )
# Set bit to 1 for input or 0 for output .
self . iodir [ int ( pin / 8 ) ] |= 1 << ( int ( pin % 8 ) )
self . _write_iodir ( )
self . pullup ( pin , pullup ) |
def sort ( args ) :
"""% prog sort coordsfile
Sort coordsfile based on query or ref .""" | import jcvi . formats . blast
return jcvi . formats . blast . sort ( args + [ "--coords" ] ) |
def simxCopyPasteObjects ( clientID , objectHandles , operationMode ) :
'''Please have a look at the function description / documentation in the V - REP user manual''' | c_objectHandles = ( ct . c_int * len ( objectHandles ) ) ( * objectHandles )
c_objectHandles = ct . cast ( c_objectHandles , ct . POINTER ( ct . c_int ) )
# IronPython needs this
newObjectCount = ct . c_int ( )
newObjectHandles = ct . POINTER ( ct . c_int ) ( )
ret = c_CopyPasteObjects ( clientID , c_objectHandles , le... |
def poll_blockchain_events ( self , block_number : typing . BlockNumber ) :
"""Poll for new blockchain events up to ` block _ number ` .""" | for event_listener in self . event_listeners :
assert isinstance ( event_listener . filter , StatelessFilter )
for log_event in event_listener . filter . get_new_entries ( block_number ) :
yield decode_event_to_internal ( event_listener . abi , log_event ) |
def infer ( cls , data , ** kwargs ) :
"""Create a Schema from concrete data ( e . g . an API response ) .
For example , this will take a dict like :
' foo ' : 1,
' bar ' : {
' a ' : True ,
' b ' : False
' baz ' : [ ' purple ' , ' monkey ' , ' dishwasher ' ]
And return a Schema :
' foo ' : int ,
'... | def value_to_schema_type ( value ) :
if isinstance ( value , dict ) :
if len ( value ) == 0 :
return dict
return { k : value_to_schema_type ( v ) for k , v in iteritems ( value ) }
if isinstance ( value , list ) :
if len ( value ) == 0 :
return list
else :... |
def set_string_value ( self , index , s ) :
"""Sets the string value at the specified position ( 0 - based ) .
: param index : the 0 - based index of the inernal value
: type index : int
: param s : the string value
: type s : str""" | return self . __set_string_value ( index , javabridge . get_env ( ) . new_string ( s ) ) |
def get_next_section_start_line ( self , data ) :
"""Get the starting line number of next section .
It will return - 1 if no section was found .
The section is a section key ( e . g . ' Parameters ' ) followed by underline
( made by - ) , then the content
: param data : a list of strings containing the docs... | start = - 1
for i , line in enumerate ( data ) :
if start != - 1 : # we found the key so check if this is the underline
if line . strip ( ) and isin_alone ( [ '-' * len ( line . strip ( ) ) ] , line ) :
break
else :
start = - 1
if isin_alone ( self . opt . values ( ) , li... |
def uint16_gte ( a : int , b : int ) -> bool :
"""Return a > = b .""" | return ( a == b ) or uint16_gt ( a , b ) |
def mean ( self , only_valid = True ) -> ErrorValue :
"""Calculate the mean of the pixels , not counting the masked ones if only _ valid is True .""" | if not only_valid :
intensity = self . intensity
error = self . error
else :
intensity = self . intensity [ self . mask ]
error = self . error [ self . mask ]
return ErrorValue ( intensity . mean ( ) , ( error ** 2 ) . mean ( ) ** 0.5 ) |
def get_intersectionsbysubsets ( df , cols_fracby2vals , cols_subset , col_ids ) :
"""cols _ fracby :
cols _ subset :""" | for col_fracby in cols_fracby2vals :
val = cols_fracby2vals [ col_fracby ]
ids = df . loc [ ( df [ col_fracby ] == val ) , col_ids ] . dropna ( ) . unique ( )
for col_subset in cols_subset :
for subset in dropna ( df [ col_subset ] . unique ( ) ) :
ids_subset = df . loc [ ( df [ col_subs... |
def visit_FunctionBody ( self , node ) :
"""Visitor for ` FunctionBody ` AST node .""" | for child in node . children :
return_value = self . visit ( child )
if isinstance ( child , ReturnStatement ) :
return return_value
if isinstance ( child , ( IfStatement , WhileStatement ) ) :
if return_value is not None :
return return_value
return NoneType ( ) |
def add_summary ( self , summary , global_step = None ) :
"""Adds a ` Summary ` protocol buffer to the event file .
This method wraps the provided summary in an ` Event ` protocol buffer and adds it
to the event file .
Parameters
summary : A ` Summary ` protocol buffer
Optionally serialized as a string . ... | if isinstance ( summary , bytes ) :
summ = summary_pb2 . Summary ( )
summ . ParseFromString ( summary )
summary = summ
# We strip metadata from values with tags that we have seen before in order
# to save space - we just store the metadata on the first value with a
# specific tag .
for value in summary . va... |
def _objectify ( self , json_data = None , data = { } ) :
'''Return an object derived from the given json data .''' | if json_data : # Parse the data
try :
data = json . loads ( json_data )
except ValueError : # If parsing failed , then raise the string which likely
# contains an error message instead of data
raise RedmineError ( json_data )
# Check to see if there is a data wrapper
# Some replies will have... |
def handleHTML ( self , record ) :
"""Saves the given record ' s page content to a . html file
Attributes
record ( Record ) - - The log record""" | # Create a unique file name to identify where this HTML source is coming from
fileName = datetime . today ( ) . strftime ( "Neolib %Y-%m-%d %H-%M-%S " ) + record . module + ".html"
# Sometimes module may encase the text with < > which is an invalid character for a file name
fileName = fileName . replace ( "<" , "" ) . ... |
def substatements ( self ) -> List [ Statement ] :
"""Parse substatements .
Raises :
EndOfInput : If past the end of input .""" | res = [ ]
self . opt_separator ( )
while self . peek ( ) != "}" :
res . append ( self . statement ( ) )
self . opt_separator ( )
self . offset += 1
return res |
def lal ( self ) :
"""Produces a LAL frequency series object equivalent to self .
Returns
lal _ data : { lal . * FrequencySeries }
LAL frequency series object containing the same data as self .
The actual type depends on the sample ' s dtype . If the epoch of
self was ' None ' , the epoch of the returned ... | lal_data = None
if self . _epoch is None :
ep = _lal . LIGOTimeGPS ( 0 , 0 )
else :
ep = self . _epoch
if self . _data . dtype == _numpy . float32 :
lal_data = _lal . CreateREAL4FrequencySeries ( "" , ep , 0 , self . delta_f , _lal . SecondUnit , len ( self ) )
elif self . _data . dtype == _numpy . float64 ... |
def save ( self , submission , result , grade , problems , tests , custom , archive ) : # pylint : disable = unused - argument
"""saves a new submission in the repo ( done async )""" | # Save submission to repo
self . _logger . info ( "Save submission " + str ( submission [ "_id" ] ) + " to git repo" )
# Verify that the directory for the course exists
if not os . path . exists ( os . path . join ( self . repopath , submission [ "courseid" ] ) ) :
os . mkdir ( os . path . join ( self . repopath , ... |
def get_anniversary_periods ( start , finish , anniversary = 1 ) :
"""Return a list of anniversaries periods between start and finish .""" | import sys
current = start
periods = [ ]
while current <= finish :
( period_start , period_finish ) = date_period ( DATE_FREQUENCY_MONTHLY , anniversary , current )
current = period_start + relativedelta ( months = + 1 )
period_start = period_start if period_start > start else start
period_finish = peri... |
def main ( ) :
'''main function .''' | args = parse_args ( )
if args . multi_thread :
enable_multi_thread ( )
if args . advisor_class_name : # advisor is enabled and starts to run
if args . multi_phase :
raise AssertionError ( 'multi_phase has not been supported in advisor' )
if args . advisor_class_name in AdvisorModuleName :
di... |
def nextElementSibling ( self ) :
'''nextElementSibling - Returns the next sibling that is an element .
This is the tag node following this node in the parent ' s list of children
@ return < None / AdvancedTag > - None if there are no children ( tag ) in the parent after this node ,
Otherwise the following el... | parentNode = self . parentNode
# If no parent , no siblings
if not parentNode :
return None
# Determine the index in children
myElementIdx = parentNode . children . index ( self )
# If we are last child , no next sibling
if myElementIdx == len ( parentNode . children ) - 1 :
return None
# Else , return the next... |
def needs_check ( self ) :
"""Check if enough time has elapsed to perform a check ( ) .
If this time has elapsed , a state change check through
has _ state _ changed ( ) should be performed and eventually a sync ( ) .
: rtype : boolean""" | if self . lastcheck is None :
return True
return time . time ( ) - self . lastcheck >= self . ipchangedetection_sleep |
def get_pkg_version_module ( packagename , fromlist = None ) :
"""Returns the package ' s . version module generated by
` astropy _ helpers . version _ helpers . generate _ version _ py ` . Raises an
ImportError if the version module is not found .
If ` ` fromlist ` ` is an iterable , return a tuple of the me... | version = import_file ( os . path . join ( packagename , 'version.py' ) , name = 'version' )
if fromlist :
return tuple ( getattr ( version , member ) for member in fromlist )
else :
return version |
def toRoman ( num ) :
"""convert integer to Roman numeral""" | if not 0 < num < 5000 :
raise ValueError ( "number %n out of range (must be 1..4999)" , num )
if int ( num ) != num :
raise TypeError ( "decimals %n can not be converted" , num )
result = ""
for numeral , integer in romanNumeralMap :
while num >= integer :
result += numeral
num -= integer
re... |
def lower_extension ( filename ) :
'''This is a helper used by : meth : ` Storage . save ` to provide lowercase extensions for
all processed files , to compare with configured extensions in the same
case .
: param str filename : The filename to ensure has a lowercase extension .''' | if '.' in filename :
main , ext = os . path . splitext ( filename )
return main + ext . lower ( )
# For consistency with os . path . splitext ,
# do not treat a filename without an extension as an extension .
# That is , do not return filename . lower ( ) .
return filename |
def expiration_maintenance ( self ) :
"""Decrement cell value if not zero
This maintenance process need to executed each self . compute _ refresh _ time ( )""" | if self . cellarray [ self . refresh_head ] != 0 :
self . cellarray [ self . refresh_head ] -= 1
self . refresh_head = ( self . refresh_head + 1 ) % self . nbr_bits |
def session_end ( self ) :
"""End a session . Se session _ begin for an in depth description of TREZOR sessions .""" | self . session_depth -= 1
self . session_depth = max ( 0 , self . session_depth )
if self . session_depth == 0 :
self . _session_end ( ) |
def clear_path ( path ) :
"""This will move a path to the Trash folder
: param path : str of the path to remove
: return : None""" | from time import time
if not os . path . exists ( path ) :
return
if TRASH_PATH == '.' :
shutil . rmtree ( path , ignore_errors = True )
else :
shutil . move ( path , '%s/%s_%s' % ( TRASH_PATH , os . path . basename ( path ) , time ( ) ) ) |
def main ( self , argv = None , exit = True ) :
"""Shortcut to prepare a bowl of guacamole and eat it .
: param argv :
Command line arguments or None . None means that sys . argv is used
: param exit :
Raise SystemExit after finishing execution
: returns :
Whatever is returned by the eating the guacamol... | bowl = self . prepare ( )
try :
retval = bowl . eat ( argv )
except SystemExit as exc :
if exit :
raise
else :
return exc . args [ 0 ]
else :
if retval is None :
retval = 0
if exit :
raise SystemExit ( retval )
else :
return retval |
def get_headers_from_signature ( self , signature ) :
"""Returns a list of headers fields to sign .
According to http : / / tools . ietf . org / html / draft - cavage - http - signatures - 03
section 2.1.3 , the headers are optional . If not specified , the single
value of " Date " must be used .""" | match = self . SIGNATURE_HEADERS_RE . search ( signature )
if not match :
return [ 'date' ]
headers_string = match . group ( 1 )
return headers_string . split ( ) |
def create ( rawmessage ) :
"""Return an INSTEON message class based on a raw byte stream .""" | rawmessage = _trim_buffer_garbage ( rawmessage )
if len ( rawmessage ) < 2 :
return ( None , rawmessage )
code = rawmessage [ 1 ]
msgclass = _get_msg_class ( code )
msg = None
remaining_data = rawmessage
if msgclass is None :
_LOGGER . debug ( 'Did not find message class 0x%02x' , rawmessage [ 1 ] )
rawmess... |
def merge_dict ( data , * args ) :
"""Merge any number of dictionaries""" | results = { }
for current in ( data , ) + args :
results . update ( current )
return results |
def check_reflections ( p_atoms , q_atoms , p_coord , q_coord , reorder_method = reorder_hungarian , rotation_method = kabsch_rmsd , keep_stereo = False ) :
"""Minimize RMSD using reflection planes for molecule P and Q
Warning : This will affect stereo - chemistry
Parameters
p _ atoms : array
( N , 1 ) matr... | min_rmsd = np . inf
min_swap = None
min_reflection = None
min_review = None
tmp_review = None
swap_mask = [ 1 , - 1 , - 1 , 1 , - 1 , 1 ]
reflection_mask = [ 1 , - 1 , - 1 , - 1 , 1 , 1 , 1 , - 1 ]
for swap , i in zip ( AXIS_SWAPS , swap_mask ) :
for reflection , j in zip ( AXIS_REFLECTIONS , reflection_mask ) :
... |
def get_log_hierarchy_id ( self ) :
"""Gets the hierarchy ` ` Id ` ` associated with this session .
return : ( osid . id . Id ) - the hierarchy ` ` Id ` ` associated with this
session
* compliance : mandatory - - This method must be implemented . *""" | # Implemented from template for
# osid . resource . BinHierarchySession . get _ bin _ hierarchy _ id
if self . _catalog_session is not None :
return self . _catalog_session . get_catalog_hierarchy_id ( )
return self . _hierarchy_session . get_hierarchy_id ( ) |
def callRemoteMessage ( self , mcall , timeout = None ) :
"""Uses the specified L { message . MethodCallMessage } to call a remote method
@ rtype : L { twisted . internet . defer . Deferred }
@ returns : a Deferred to the result of the remote method call""" | assert isinstance ( mcall , message . MethodCallMessage )
if mcall . expectReply :
d = defer . Deferred ( )
if timeout :
timeout = reactor . callLater ( timeout , self . _onMethodTimeout , mcall . serial , d )
self . _pendingCalls [ mcall . serial ] = ( d , timeout )
self . sendMessage ( mcall )... |
def add_entry ( self , src , dst , duration = 3600 , src_port1 = None , src_port2 = None , src_proto = 'predefined_tcp' , dst_port1 = None , dst_port2 = None , dst_proto = 'predefined_tcp' ) :
"""Create a blacklist entry .
A blacklist can be added directly from the engine node , or from
the system context . If ... | self . entries . setdefault ( 'entries' , [ ] ) . append ( prepare_blacklist ( src , dst , duration , src_port1 , src_port2 , src_proto , dst_port1 , dst_port2 , dst_proto ) ) |
def manager_post_save_handler ( sender , instance , created , ** kwargs ) :
"""Run newly created ( spawned ) processes .""" | if instance . status == Data . STATUS_DONE or instance . status == Data . STATUS_ERROR or created : # Run manager at the end of the potential transaction . Otherwise
# tasks are send to workers before transaction ends and therefore
# workers cannot access objects created inside transaction .
transaction . on_commit... |
def perform_correction ( image , output , stat = "pmode1" , maxiter = 15 , sigrej = 2.0 , lower = None , upper = None , binwidth = 0.3 , mask = None , dqbits = None , rpt_clean = 0 , atol = 0.01 , clobber = False , verbose = True ) :
"""Clean each input image .
Parameters
image : str
Input image name .
outp... | # construct the frame to be cleaned , including the
# associated data stuctures needed for cleaning
frame = StripeArray ( image )
# combine user mask with image ' s DQ array :
mask = _mergeUserMaskAndDQ ( frame . dq , mask , dqbits )
# Do the stripe cleaning
Success , NUpdRows , NMaxIter , Bkgrnd , STDDEVCorr , MaxCorr... |
def build_wheel ( wheel_directory , config_settings , metadata_directory = None ) :
"""Invoke the mandatory build _ wheel hook .
If a wheel was already built in the
prepare _ metadata _ for _ build _ wheel fallback , this
will copy it rather than rebuilding the wheel .""" | prebuilt_whl = _find_already_built_wheel ( metadata_directory )
if prebuilt_whl :
shutil . copy2 ( prebuilt_whl , wheel_directory )
return os . path . basename ( prebuilt_whl )
return _build_backend ( ) . build_wheel ( wheel_directory , config_settings , metadata_directory ) |
def to_dataframe ( self , * args , ** kwargs ) :
"""Produce a data table with records for all chemical equations .
All possible differences for numeric attributes are computed and stored
as columns in the returned ` pandas . DataFrame ` object ( see examples
below ) , whose rows represent chemical equations .... | dataframe = _pd . DataFrame ( [ equation . to_series ( * args , ** kwargs ) for equation in self . equations ] )
dataframe . index . name = "chemical_equation"
return dataframe |
def keep_entry_range ( entry , lows , highs , converter , regex ) :
"""Check if an entry falls into a desired range .
Every number in the entry will be extracted using * regex * ,
if any are within a given low to high range the entry will
be kept .
Parameters
entry : str
lows : iterable
Collection of ... | return any ( low <= converter ( num ) <= high for num in regex . findall ( entry ) for low , high in zip ( lows , highs ) ) |
def GetRawDevice ( path ) :
"""Resolves the raw device that contains the path .
Args :
path : A path to examine .
Returns :
A pathspec to read the raw device as well as the modified path to read
within the raw device . This is usually the path without the mount point .
Raises :
IOError : if the path d... | path = CanonicalPathToLocalPath ( path )
# Try to expand the shortened paths
try :
path = win32file . GetLongPathName ( path )
except pywintypes . error :
pass
try :
mount_point = win32file . GetVolumePathName ( path )
except pywintypes . error as details :
logging . info ( "path not found. %s" , detail... |
def list_nodes ( call = None ) :
'''Return a list of the VMs that are managed by the provider
CLI Example :
. . code - block : : bash
salt - cloud - Q my - proxmox - config''' | if call == 'action' :
raise SaltCloudSystemExit ( 'The list_nodes function must be called with -f or --function.' )
ret = { }
for vm_name , vm_details in six . iteritems ( get_resources_vms ( includeConfig = True ) ) :
log . debug ( 'VM_Name: %s' , vm_name )
log . debug ( 'vm_details: %s' , vm_details )
... |
def read_file ( self , start_year = None , end_year = None , use_centroid = None ) :
"""Reads the file""" | raw_data = getlines ( self . filename )
num_lines = len ( raw_data )
if ( ( float ( num_lines ) / 5. ) - float ( num_lines / 5 ) ) > 1E-9 :
raise IOError ( 'GCMT represented by 5 lines - number in file not' ' a multiple of 5!' )
self . catalogue . number_gcmts = num_lines // 5
self . catalogue . gcmts = [ None ] * ... |
async def set_googlecast_settings ( self , target : str , value : str ) :
"""Set Googlecast settings .""" | params = { "settings" : [ { "target" : target , "value" : value } ] }
return await self . services [ "system" ] [ "setWuTangInfo" ] ( params ) |
def write_gdf ( gdf , fname ) :
"""Fast line - by - line gdf - file write function
Parameters
gdf : numpy . ndarray
Column 0 is gids , columns 1 : are values .
fname : str
Path to gdf - file .
Returns
None""" | gdf_file = open ( fname , 'w' )
for line in gdf :
for i in np . arange ( len ( line ) ) :
gdf_file . write ( str ( line [ i ] ) + '\t' )
gdf_file . write ( '\n' )
return None |
def write_file ( fname , * lines ) :
'write lines to a file' | yield 'touch {}' . format ( fname )
for line in lines :
yield "echo {} >> {}" . format ( line , fname ) |
def ends ( self , layer ) :
"""Retrieve end positions of elements if given layer .""" | ends = [ ]
for data in self [ layer ] :
ends . append ( data [ END ] )
return ends |
def option_vip_by_environmentvip ( self , environment_vip_id ) :
"""List Option Vip by Environment Vip
param environment _ vip _ id : Id of Environment Vip""" | uri = 'api/v3/option-vip/environment-vip/%s/' % environment_vip_id
return super ( ApiVipRequest , self ) . get ( uri ) |
def reverse_hash ( hash , hex_format = True ) :
"""hash is in hex or binary format""" | if not hex_format :
hash = hexlify ( hash )
return "" . join ( reversed ( [ hash [ i : i + 2 ] for i in range ( 0 , len ( hash ) , 2 ) ] ) ) |
def numeric_type ( self , tchain , p_elem ) :
"""Handle numeric types .""" | typ = tchain [ 0 ] . arg
def gen_data ( ) :
elem = SchemaNode ( "data" ) . set_attr ( "type" , self . datatype_map [ typ ] )
if typ == "decimal64" :
fd = tchain [ 0 ] . search_one ( "fraction-digits" ) . arg
SchemaNode ( "param" , elem , "19" ) . set_attr ( "name" , "totalDigits" )
Schem... |
def cumulative_distribution ( self , X ) :
"""Cumulative distribution function for gaussian distribution .
Arguments :
X : ` np . ndarray ` of shape ( n , 1 ) .
Returns :
np . ndarray : Cumulative density for X .""" | self . check_fit ( )
return norm . cdf ( X , loc = self . mean , scale = self . std ) |
def camelResource ( obj ) :
"""Some sources from apis return lowerCased where as describe calls
always return TitleCase , this function turns the former to the later""" | if not isinstance ( obj , dict ) :
return obj
for k in list ( obj . keys ( ) ) :
v = obj . pop ( k )
obj [ "%s%s" % ( k [ 0 ] . upper ( ) , k [ 1 : ] ) ] = v
if isinstance ( v , dict ) :
camelResource ( v )
elif isinstance ( v , list ) :
list ( map ( camelResource , v ) )
return obj |
def _readASCII ( self , filename ) :
"""ASCII files have no headers . Following synphot , this
routine will assume the first column is wavelength in Angstroms ,
and the second column is flux in Flam .""" | self . waveunits = units . Units ( 'angstrom' )
self . fluxunits = units . Units ( 'flam' )
wlist , flist = self . _columnsFromASCII ( filename )
self . _wavetable = N . array ( wlist , dtype = N . float64 )
self . _fluxtable = N . array ( flist , dtype = N . float64 ) |
def runcall ( self , func , * args , ** kw ) :
"""Profile a single function call .""" | # XXX where is this used ? can be removed ?
self . enable_by_count ( )
try :
return func ( * args , ** kw )
finally :
self . disable_by_count ( ) |
def run_mutect ( job , tumor_bam , normal_bam , univ_options , mutect_options , chrom ) :
"""This module will run mutect on the DNA bams
ARGUMENTS
1 . tumor _ bam : REFER ARGUMENTS of spawn _ mutect ( )
2 . normal _ bam : REFER ARGUMENTS of spawn _ mutect ( )
3 . univ _ options : REFER ARGUMENTS of spawn _ ... | job . fileStore . logToMaster ( 'Running mutect on %s:%s' % ( univ_options [ 'patient' ] , chrom ) )
work_dir = job . fileStore . getLocalTempDir ( )
input_files = { 'tumor.bam' : tumor_bam [ 'tumor_dna_fix_pg_sorted.bam' ] , 'tumor.bam.bai' : tumor_bam [ 'tumor_dna_fix_pg_sorted.bam.bai' ] , 'normal.bam' : normal_bam ... |
def add_swagger_api_route ( app , target_route , swagger_json_route ) :
"""mount a swagger statics page .
app : the flask app object
target _ route : the path to mount the statics page .
swagger _ json _ route : the path where the swagger json definitions is
expected to be .""" | static_root = get_swagger_static_root ( )
swagger_body = generate_swagger_html ( STATIC_ROOT , swagger_json_route ) . encode ( "utf-8" )
def swagger_ui ( ) :
return Response ( swagger_body , content_type = "text/html" )
blueprint = Blueprint ( 'swagger' , __name__ , static_url_path = STATIC_ROOT , static_folder = s... |
def u128 ( self , name , value = None , align = None ) :
"""Add an unsigned 16 byte integer field to template .
This is an convenience method that simply calls ` Uint ` keyword with predefined length .""" | self . uint ( 16 , name , value , align ) |
def filter_nodes ( self , pattern , attribute , flags = re . IGNORECASE ) :
"""Filters the View Nodes on given attribute using given pattern .
: param pattern : Filtering pattern .
: type pattern : unicode
: param attribute : Filtering attribute .
: type attribute : unicode
: param flags : Regex filtering... | return [ node for node in self . get_nodes ( ) if re . search ( pattern , getattr ( node , attribute ) , flags ) ] |
def _run_validate ( self ) :
'''Execute the validate ( ) method in the test script belonging to this job .''' | assert ( os . path . exists ( self . validator_script_name ) )
old_path = sys . path
sys . path = [ self . working_dir ] + old_path
# logger . debug ( ' Python search path is now { 0 } . ' . format ( sys . path ) )
try :
module = importlib . import_module ( self . _validator_import_name )
except Exception as e :
... |
def SurveyOptions ( self ) :
"""List of measures in < SurveyOpions > section
Example : [ " hHost " , " nPatent " , " nUncomp " , " simulatedEIR " , " nMassGVI " ]
: rtype : list""" | list_of_measures = [ ]
if self . et . find ( "SurveyOptions" ) is None :
return list_of_measures
return self . _get_measures ( self . et . find ( "SurveyOptions" ) ) |
def postprocess_model_xml ( xml_str ) :
"""This function postprocesses the model . xml collected from a MuJoCo demonstration
in order to make sure that the STL files can be found .""" | path = os . path . split ( robosuite . __file__ ) [ 0 ]
path_split = path . split ( "/" )
# replace mesh and texture file paths
tree = ET . fromstring ( xml_str )
root = tree
asset = root . find ( "asset" )
meshes = asset . findall ( "mesh" )
textures = asset . findall ( "texture" )
all_elements = meshes + textures
for... |
def dispatch_line ( self , frame ) :
"""Handle line action and return the next line callback .""" | callback = TerminalPdb . dispatch_line ( self , frame )
# If the ipdb session ended , don ' t return a callback for the next line
if self . stoplineno == - 1 :
return None
return callback |
def value ( self ) :
"""Set a calculated value for this Expression .
Used when writing formulas using XlsxWriter to give cells
an initial value when the sheet is loaded without being calculated .""" | try :
if isinstance ( self . __value , Expression ) :
return self . __value . value
return self . __value
except AttributeError :
return 0 |
def lookup_attribute_chain ( attrname , namespace ) :
"""> > > attrname = funcname
> > > namespace = mod . _ _ dict _ _
> > > import utool as ut
> > > globals _ = ut . util _ inspect . _ _ dict _ _
> > > attrname = ' KWReg . print _ defaultkw '""" | # subdict = meta _ util _ six . get _ funcglobals ( root _ func )
subtup = attrname . split ( '.' )
subdict = namespace
for attr in subtup [ : - 1 ] :
subdict = subdict [ attr ] . __dict__
leaf_name = subtup [ - 1 ]
leaf_attr = subdict [ leaf_name ]
return leaf_attr |
def _fixup_record ( self , s ) :
"""Fixup padding on a record""" | log . debug ( 'FIXUP_STRUCT: %s %d bits' , s . name , s . size * 8 )
if s . members is None :
log . debug ( 'FIXUP_STRUCT: no members' )
s . members = [ ]
return
if s . size == 0 :
log . debug ( 'FIXUP_STRUCT: struct has size %d' , s . size )
return
# try to fix bitfields without padding first
self ... |
def sanity_check ( self ) :
"""Check block and throw PyrtlError or PyrtlInternalError if there is an issue .
Should not modify anything , only check data structures to make sure they have been
built according to the assumptions stated in the Block comments .""" | # TODO : check that the wirevector _ by _ name is sane
from . wire import Input , Const , Output
from . helperfuncs import get_stack , get_stacks
# check for valid LogicNets ( and wires )
for net in self . logic :
self . sanity_check_net ( net )
for w in self . wirevector_subset ( ) :
if w . bitwidth is None :
... |
def _joinrealpath ( self , path , rest , seen ) :
"""Join two paths , normalizing and eliminating any symbolic links
encountered in the second path .
Taken from Python source and adapted .""" | curdir = self . filesystem . _matching_string ( path , '.' )
pardir = self . filesystem . _matching_string ( path , '..' )
sep = self . filesystem . _path_separator ( path )
if self . isabs ( rest ) :
rest = rest [ 1 : ]
path = sep
while rest :
name , _ , rest = rest . partition ( sep )
if not name or n... |
def GetGroups ( r , bulk = False ) :
"""Gets all node groups in the cluster .
@ type bulk : bool
@ param bulk : whether to return all information about the groups
@ rtype : list of dict or str
@ return : if bulk is true , a list of dictionaries with info about all node
groups in the cluster , else a list ... | if bulk :
return r . request ( "get" , "/2/groups" , query = { "bulk" : 1 } )
else :
groups = r . request ( "get" , "/2/groups" )
return r . applier ( itemgetters ( "name" ) , groups ) |
def declare ( self , exchange = '' , exchange_type = 'direct' , passive = False , durable = False , auto_delete = False , arguments = None ) :
"""Declare an Exchange .
: param str exchange : Exchange name
: param str exchange _ type : Exchange type
: param bool passive : Do not create
: param bool durable :... | if not compatibility . is_string ( exchange ) :
raise AMQPInvalidArgument ( 'exchange should be a string' )
elif not compatibility . is_string ( exchange_type ) :
raise AMQPInvalidArgument ( 'exchange_type should be a string' )
elif not isinstance ( passive , bool ) :
raise AMQPInvalidArgument ( 'passive sh... |
def _cbGotHello ( self , busName ) :
"""Called in reply to the initial Hello remote method invocation""" | self . busName = busName
# print ' Connection Bus Name = ' , self . busName
self . factory . _ok ( self ) |
def get_value ( self ) :
"""Evaluate self . expr to get the parameter ' s value""" | if ( self . _value is None ) and ( self . expr is not None ) :
self . _value = self . expr . get_value ( )
return self . _value |
def fetchSynIdxCell ( self , cell , nidx , synParams ) :
"""Find possible synaptic placements for each cell
As synapses are placed within layers with bounds determined by
self . layerBoundaries , it will check this matrix accordingly , and
use the probabilities from ` self . connProbLayer to distribute .
Fo... | # segment indices in each layer is stored here , list of np . array
syn_idx = [ ]
# loop over layer bounds , find synapse locations
for i , zz in enumerate ( self . layerBoundaries ) :
if nidx [ i ] == 0 :
syn_idx . append ( np . array ( [ ] , dtype = int ) )
else :
syn_idx . append ( cell . get... |
def connect ( self , urls = None , ** overrides ) :
"""Sets the acceptable HTTP method to CONNECT""" | if urls is not None :
overrides [ 'urls' ] = urls
return self . where ( accept = 'CONNECT' , ** overrides ) |
def get_rendition_stretch_size ( spec , input_w , input_h , output_scale ) :
"""Determine the scale - crop size given the provided spec""" | width = input_w
height = input_h
scale = spec . get ( 'scale' )
if scale :
width = width / scale
height = height / scale
min_width = spec . get ( 'scale_min_width' )
if min_width and width < min_width :
width = min_width
min_height = spec . get ( 'scale_min_height' )
if min_height and height < min_height :
... |
def read ( self , entity = None , attrs = None , ignore = None , params = None ) :
"""Provide a default value for ` ` entity ` ` .
By default , ` ` nailgun . entity _ mixins . EntityReadMixin . read ` ` provides a
default value for ` ` entity ` ` like so : :
entity = type ( self ) ( )
However , : class : ` ... | # read ( ) should not change the state of the object it ' s called on , but
# super ( ) alters the attributes of any entity passed in . Creating a new
# object and passing it to super ( ) lets this one avoid changing state .
if entity is None :
entity = type ( self ) ( self . _server_config , organization = self . ... |
def plan ( description , stack_action , context , tail = None , reverse = False ) :
"""A simple helper that builds a graph based plan from a set of stacks .
Args :
description ( str ) : a description of the plan .
action ( func ) : a function to call for each stack .
context ( : class : ` stacker . context ... | def target_fn ( * args , ** kwargs ) :
return COMPLETE
steps = [ Step ( stack , fn = stack_action , watch_func = tail ) for stack in context . get_stacks ( ) ]
steps += [ Step ( target , fn = target_fn ) for target in context . get_targets ( ) ]
graph = build_graph ( steps )
return build_plan ( description = descri... |
def cut_by_plane ( self , plane , inverted = False ) :
'''Like cut _ across _ axis , but works with an arbitrary plane . Keeps
vertices that lie in front of the plane ( i . e . in the direction
of the plane normal ) .
inverted : When ` True ` , invert the logic , to keep the vertices
that lie behind the pla... | vertices_to_keep = plane . points_in_front ( self . v , inverted = inverted , ret_indices = True )
self . keep_vertices ( vertices_to_keep )
return vertices_to_keep |
def toggle_sequential_download ( self , infohash_list ) :
"""Toggle sequential download in supplied torrents .
: param infohash _ list : Single or list ( ) of infohashes .""" | data = self . _process_infohash_list ( infohash_list )
return self . _post ( 'command/toggleSequentialDownload' , data = data ) |
def dslice ( value , * args ) :
"""Returns a ' slice ' of the given dictionary value containing only the
requested keys . The keys can be requested in a variety of ways , as an
arg list of keys , as a list of keys , or as a dict whose key ( s ) represent
the source keys and whose corresponding values represen... | result = { }
for arg in args :
if isinstance ( arg , dict ) :
for k , v in six . iteritems ( arg ) :
if k in value :
result [ v ] = value [ k ]
elif isinstance ( arg , list ) :
for k in arg :
if k in value :
result [ k ] = value [ k ]
e... |
def chunk_fill ( iterable , size , fillvalue = None ) :
"""chunk _ fill ( ' ABCDEFG ' , 3 , ' x ' ) - - > ABC DEF Gxx""" | # TODO : not used
args = [ iter ( iterable ) ] * size
return itertools . zip_longest ( * args , fillvalue = fillvalue ) |
def update_search_space ( self , search_space ) :
"""Update the self . x _ bounds and self . x _ types by the search _ space . json
Parameters
search _ space : dict""" | self . x_bounds = [ [ ] for i in range ( len ( search_space ) ) ]
self . x_types = [ NONE_TYPE for i in range ( len ( search_space ) ) ]
for key in search_space :
self . key_order . append ( key )
key_type = { }
if isinstance ( search_space , dict ) :
for key in search_space :
key_type = search_space [ ... |
def center_line ( space , line ) :
"""Add leading & trailing space to text to center it within an allowed
width
Parameters
space : int
The maximum character width allowed for the text . If the length
of text is more than this value , no space will be added . line : str
The text that will be centered .
... | line = line . strip ( )
left_length = math . floor ( ( space - len ( line ) ) / 2 )
right_length = math . ceil ( ( space - len ( line ) ) / 2 )
left_space = " " * int ( left_length )
right_space = " " * int ( right_length )
line = '' . join ( [ left_space , line , right_space ] )
return line |
def set_label_list ( self , label_lists ) :
"""Set the given label - list for this utterance .
If the label - list - idx is not set , ` ` default ` ` is used .
If there is already a label - list with the given idx ,
it will be overriden .
Args :
label _ list ( LabelList , list ) : A single or multi . labe... | if isinstance ( label_lists , annotations . LabelList ) :
label_lists = [ label_lists ]
for label_list in label_lists :
if label_list . idx is None :
label_list . idx = 'default'
label_list . utterance = self
self . label_lists [ label_list . idx ] = label_list |
def output ( self , data , context ) :
"""Outputs the provided data using the transformations and output format specified for this CLI endpoint""" | if self . transform :
if hasattr ( self . transform , 'context' ) :
self . transform . context = context
data = self . transform ( data )
if hasattr ( data , 'read' ) :
data = data . read ( ) . decode ( 'utf8' )
if data is not None :
data = self . outputs ( data )
if data :
sys . std... |
def send_rpc ( self , name , rpc_id , payload , timeout = 1.0 ) :
"""Send an RPC to a service and synchronously wait for the response .
Args :
name ( str ) : The short name of the service to send the RPC to
rpc _ id ( int ) : The id of the RPC we want to call
payload ( bytes ) : Any binary arguments that we... | return self . _loop . run_coroutine ( self . _client . send_rpc ( name , rpc_id , payload , timeout ) ) |
def import_config ( config_path ) :
"""Import a Config from a given path , relative to the current directory .
The module specified by the config file must contain a variable called ` configuration ` that is
assigned to a Config object .""" | if not os . path . isfile ( config_path ) :
raise ConfigBuilderError ( 'Could not find config file: ' + config_path )
loader = importlib . machinery . SourceFileLoader ( config_path , config_path )
module = loader . load_module ( )
if not hasattr ( module , 'config' ) or not isinstance ( module . config , Config ) ... |
def ROC_AUC_analysis ( adata , groupby , group = None , n_genes = 100 ) :
"""Calculate correlation matrix .
Calculate a correlation matrix for genes strored in sample annotation using rank _ genes _ groups . py
Parameters
adata : : class : ` ~ anndata . AnnData `
Annotated data matrix .
groupby : ` str ` ... | if group is None :
pass
# TODO : Loop over all groups instead of just taking one .
# Assume group takes an int value for one group for the moment .
name_list = list ( )
for j , k in enumerate ( adata . uns [ 'rank_genes_groups_gene_names' ] ) :
if j >= n_genes :
break
name_list . append ( adata ... |
def within_set ( df , items = None ) :
"""Assert that df is a subset of items
Parameters
df : DataFrame
items : dict
mapping of columns ( k ) to array - like of values ( v ) that
` ` df [ k ] ` ` is expected to be a subset of""" | for k , v in items . items ( ) :
if not df [ k ] . isin ( v ) . all ( ) :
raise AssertionError
return df |
def load_models ( self , model_path ) :
"""Load models from pickle files .""" | condition_model_files = sorted ( glob ( model_path + "*_condition.pkl" ) )
if len ( condition_model_files ) > 0 :
for condition_model_file in condition_model_files :
model_comps = condition_model_file . split ( "/" ) [ - 1 ] [ : - 4 ] . split ( "_" )
if model_comps [ 0 ] not in self . condition_mode... |
def scrypt ( password , salt = '' , n = 2 ** 20 , r = 8 , p = 1 , maxmem = 2 ** 25 , dklen = 64 ) :
"""Derive a cryptographic key using the scrypt KDF .
Implements the same signature as the ` ` hashlib . scrypt ` ` implemented
in cpython version 3.6""" | return nacl . bindings . crypto_pwhash_scryptsalsa208sha256_ll ( password , salt , n , r , p , maxmem = maxmem , dklen = dklen ) |
def sortBy ( self , sortOptions , reverse = False ) :
"""Sort ` ` fonts ` ` with the ordering preferences defined
by ` ` sortBy ` ` . ` ` sortBy ` ` must be one of the following :
* sort description string
* : class : ` BaseInfo ` attribute name
* sort value function
* list / tuple containing sort descrip... | from types import FunctionType
from fontTools . misc . py23 import basestring
valueGetters = dict ( familyName = _sortValue_familyName , styleName = _sortValue_styleName , isRoman = _sortValue_isRoman , isItalic = _sortValue_isItalic , widthValue = _sortValue_widthValue , weightValue = _sortValue_weightValue , isPropor... |
def _emit_metrics ( self , missing_datetimes , finite_start , finite_stop ) :
"""For consistent metrics one should consider the entire range , but
it is open ( infinite ) if stop or start is None .
Hence make do with metrics respective to the finite simplification .""" | datetimes = self . finite_datetimes ( finite_start if self . start is None else min ( finite_start , self . parameter_to_datetime ( self . start ) ) , finite_stop if self . stop is None else max ( finite_stop , self . parameter_to_datetime ( self . stop ) ) )
delay_in_jobs = len ( datetimes ) - datetimes . index ( miss... |
def add_new_fields ( data , data_to_add ) :
"""Update resource data with new fields .
Args :
data : resource data
data _ to _ update : dict of data to update resource data
Returnes :
Returnes dict""" | for key , value in data_to_add . items ( ) :
if not data . get ( key ) :
data [ key ] = value
return data |
def parse_comment_node ( comment ) : # Example of a comment node . The resign threshold line appears only
# for the first move in the game ; it gets preprocessed by extract _ game _ data
"""Resign Threshold : - 0.88
-0.0662
D4 ( 100 ) = = > D16 ( 14 ) = = > Q16 ( 3 ) = = > Q4 ( 1 ) = = > Q : - 0.07149
move : ... | lines = comment . split ( '\n' )
if lines [ 0 ] . startswith ( 'Resign' ) :
lines = lines [ 1 : ]
post_Q = float ( lines [ 0 ] )
debug_rows = [ ]
comment_splitter = re . compile ( r'[ :,]' )
for line in lines [ 3 : ] :
if not line :
continue
columns = comment_splitter . split ( line )
columns = ... |
def package_list ( cls , options = None ) :
"""List possible certificate packages .""" | options = options or { }
try :
return cls . safe_call ( 'cert.package.list' , options )
except UsageError as err :
if err . code == 150020 :
return [ ]
raise |
def _build_queryset ( self , serializer = None , filters = None , queryset = None , requirements = None , extra_filters = None , disable_prefetches = False , ) :
"""Build a queryset that pulls in all data required by this request .
Handles nested prefetching of related data and deferring fields
at the queryset ... | is_root_level = False
if not serializer :
serializer = self . view . get_serializer ( )
is_root_level = True
queryset = self . _get_queryset ( queryset = queryset , serializer = serializer )
model = getattr ( serializer . Meta , 'model' , None )
if not model :
return queryset
prefetches = { }
# build a nest... |
async def items ( self , name = None , * , watch = None ) :
"""Lists the most recent events an agent has seen
Parameters :
name ( str ) : Filter events by name .
watch ( Blocking ) : Do a blocking query
Returns :
CollectionMeta : where value is a list of events
It returns a JSON body like this : :
" I... | path = "/v1/event/list"
params = { "name" : name }
response = await self . _api . get ( path , params = params , watch = watch )
results = [ format_event ( data ) for data in response . body ]
return consul ( results , meta = extract_meta ( response . headers ) ) |
def squeeze ( self ) :
"""Remove the degenerate dimensions .
Note that no changes are made in - place .
Returns
squeezed : ` IntervalProd `
Squeezed set .
Examples
> > > min _ pt , max _ pt = [ - 1 , 0 , 2 ] , [ - 0.5 , 1 , 3]
> > > rbox = IntervalProd ( min _ pt , max _ pt )
> > > rbox . collapse (... | b_new = self . min_pt [ self . nondegen_byaxis ]
e_new = self . max_pt [ self . nondegen_byaxis ]
return IntervalProd ( b_new , e_new ) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.