signature stringlengths 29 44.1k | implementation stringlengths 0 85.2k |
|---|---|
def retrieve_all ( self , sids , default_none = False ) :
"""Retrieve all assets in ` sids ` .
Parameters
sids : iterable of int
Assets to retrieve .
default _ none : bool
If True , return None for failed lookups .
If False , raise ` SidsNotFound ` .
Returns
assets : list [ Asset or None ]
A list ... | sids = list ( sids )
hits , missing , failures = { } , set ( ) , [ ]
for sid in sids :
try :
asset = self . _asset_cache [ sid ]
if not default_none and asset is None : # Bail early if we ' ve already cached that we don ' t know
# about an asset .
raise SidsNotFound ( sids = [ si... |
def recycle ( ) :
"""the purpose of this tasks is to recycle the data from the cache
with version = 2 in the main cache""" | # http : / / niwinz . github . io / django - redis / latest / # _ scan _ delete _ keys _ in _ bulk
for service in cache . iter_keys ( 'th_*' ) :
try : # get the value from the cache version = 2
service_value = cache . get ( service , version = 2 )
# put it in the version = 1
cache . set ( se... |
def add_wic_ports ( self , wic_slot ) :
"""Add the ports for a specific WIC to the node [ ' ports ' ] dictionary
: param str wic _ slot : WIC Slot ( wic0)""" | wic_slot_number = int ( wic_slot [ 3 ] )
wic_adapter = self . node [ 'properties' ] [ wic_slot ]
num_ports = ADAPTER_MATRIX [ wic_adapter ] [ 'ports' ]
port_type = ADAPTER_MATRIX [ wic_adapter ] [ 'type' ]
ports = [ ]
# Dynamips WICs port number start on a multiple of 16.
base = 16 * ( wic_slot_number + 1 )
# WICs are ... |
def glob ( self , pathname , using = None , unite = False , basecolumn = 0 , parser = None , with_filename = False , recursive = False , natsort = True , ** kwargs ) :
"""Load data from file matched with given glob pattern .
Return value will be a list of data unless : attr : ` unite ` is ` True ` .
If : attr :... | # argument check
if unite and with_filename :
raise AttributeError ( "`with_filename` attribute cannot be set True when " "`unite` attribute was set True." )
# make sure that the pathname is absolute
pathname = os . path . abspath ( pathname )
if recursive :
filelist = rglob ( pathname )
else :
filelist = g... |
def incoming_edges ( self , node ) :
"""Returns a ` ` tuple ` ` of incoming edges for a * * node object * * .
Arguments :
- node ( ` ` object ` ` ) * * node object * * present in the graph to be queried
for incoming edges .""" | edges = self . edges ( )
in_edges = [ ]
for out_node , in_node in edges :
if node is in_node :
in_edges . append ( ( out_node , in_node ) )
return tuple ( in_edges ) |
def build_mock_open_side_effect ( string_d , stream_d ) :
"""Build a mock open side effect using a dictionary of content for the files .
: param string _ d : keys are file names , values are string file contents
: param stream _ d : keys are file names , values are stream of contents""" | assert ( len ( set ( string_d . keys ( ) ) . intersection ( set ( stream_d . keys ( ) ) ) ) == 0 )
def mock_open_side_effect ( * args , ** kwargs ) :
if args [ 0 ] in string_d :
return StringIO . StringIO ( string_d [ args [ 0 ] ] )
elif args [ 0 ] in stream_d :
return stream_d [ args [ 0 ] ]
... |
def _compute_equations ( self , x , verbose = False ) :
'''Compute the values and the normals ( gradients ) of active constraints .
Arguments :
| ` ` x ` ` - - The unknowns .''' | # compute the error and the normals .
normals = [ ]
values = [ ]
signs = [ ]
error = 0.0
if verbose :
print ( )
print ( ' ' . join ( '% 10.3e' % val for val in x ) , end = ' ' )
active_str = ''
for i , ( sign , equation ) in enumerate ( self . equations ) :
value , normal = equation ( x )
if ( i < l... |
def run_query_series ( queries , conn ) :
"""Iterates through a list of queries and runs them through the connection
Args :
queries : list of strings or tuples containing ( query _ string , kwargs )
conn : the triplestore connection to use""" | results = [ ]
for item in queries :
qry = item
kwargs = { }
if isinstance ( item , tuple ) :
qry = item [ 0 ]
kwargs = item [ 1 ]
result = conn . update_query ( qry , ** kwargs )
# pdb . set _ trace ( )
results . append ( result )
return results |
def make_thumbnail_name ( image_name , extension ) :
"""Return name of the downloaded thumbnail , based on the extension .""" | file_name , _ = os . path . splitext ( image_name )
return file_name + '.' + clean_extension ( extension ) |
def download_sample ( job , ids , input_args , sample ) :
"""Defines variables unique to a sample that are used in the rest of the pipelines
ids : dict Dictionary of fileStore IDS
input _ args : dict Dictionary of input arguments
sample : tuple Contains uuid and sample _ url""" | if len ( sample ) == 2 :
uuid , sample_location = sample
url1 , url2 = None , None
else :
uuid , url1 , url2 = sample
sample_location = None
# Update values unique to sample
sample_input = dict ( input_args )
sample_input [ 'uuid' ] = uuid
sample_input [ 'sample.tar' ] = sample_location
if sample_input ... |
def build ( self , ** values : Any ) -> str :
"""Build this rule into a path using the values given .""" | converted_values = { key : self . _converters [ key ] . to_url ( value ) for key , value in values . items ( ) if key in self . _converters }
result = self . _builder . format ( ** converted_values ) . split ( '|' , 1 ) [ 1 ]
query_string = urlencode ( { key : value for key , value in values . items ( ) if key not in s... |
def need_geocoding ( self ) :
"""Returns True if any of the required address components is missing""" | need_geocoding = False
for attribute , component in self . required_address_components . items ( ) :
if not getattr ( self , attribute ) :
need_geocoding = True
break
# skip extra loops
return need_geocoding |
def IterEnumerateInstancePaths ( self , ClassName , namespace = None , FilterQueryLanguage = None , FilterQuery = None , OperationTimeout = None , ContinueOnError = None , MaxObjectCount = DEFAULT_ITER_MAXOBJECTCOUNT , ** extra ) :
"""Enumerate the instance paths of instances of a class ( including
instances of i... | _validateIterCommonParams ( MaxObjectCount , OperationTimeout )
# Common variable for pull result tuple used by pulls and finally :
pull_result = None
try : # try / finally block to allow iter . close ( )
if ( self . _use_enum_path_pull_operations is None or self . _use_enum_path_pull_operations ) :
try : #... |
def update_estimator_from_task ( estimator , task_id , task_type ) :
"""Update training job of the estimator from a task in the DAG
Args :
estimator ( sagemaker . estimator . EstimatorBase ) : The estimator to update
task _ id ( str ) : The task id of any airflow . contrib . operators . SageMakerTrainingOpera... | if task_type is None :
return
if task_type . lower ( ) == 'training' :
training_job = "{{ ti.xcom_pull(task_ids='%s')['Training']['TrainingJobName'] }}" % task_id
job_name = training_job
elif task_type . lower ( ) == 'tuning' :
training_job = "{{ ti.xcom_pull(task_ids='%s')['Tuning']['BestTrainingJob'][... |
def notify ( self , msgtype , method , params ) :
"""Handle an incoming notify request .""" | self . dispatch . call ( method , params ) |
def get_addon_module_name ( addonxml_filename ) :
'''Attempts to extract a module name for the given addon ' s addon . xml file .
Looks for the ' xbmc . python . pluginsource ' extension node and returns the
addon ' s filename without the . py suffix .''' | try :
xml = ET . parse ( addonxml_filename ) . getroot ( )
except IOError :
sys . exit ( 'Cannot find an addon.xml file in the current working ' 'directory. Please run this command from the root directory ' 'of an addon.' )
try :
plugin_source = ( ext for ext in xml . findall ( 'extension' ) if ext . get ( ... |
def _get_env_data ( self , reload = False ) :
"""Get the data about the available environments .
env _ data is a structure { name - > ( resourcedir , kernel spec ) }""" | # This is called much too often and finding - process is really expensive : - (
if not reload and getattr ( self , "_env_data_cache" , { } ) :
return getattr ( self , "_env_data_cache" )
env_data = { }
for supplyer in ENV_SUPPLYER :
env_data . update ( supplyer ( self ) )
env_data = { name : env_data [ name ] f... |
def artist_to_ref ( artist ) :
"""Convert a mopidy artist to a mopidy ref .""" | if artist . name :
name = artist . name
else :
name = 'Unknown artist'
return Ref . directory ( uri = artist . uri , name = name ) |
def convert ( self ) :
"""Copies data from RAPID netCDF output to a CF - compliant netCDF file .""" | try :
log ( 'Processing %s ...' % self . rapid_output_file_list [ 0 ] )
time_start_conversion = datetime . utcnow ( )
# Validate the raw netCDF file
log ( 'validating input netCDF file' , 'INFO' )
id_len , time_len = self . _validate_raw_nc ( )
# Initialize the output file ( create dimensions an... |
def convert_ages ( Recs , data_model = 3 ) :
"""converts ages to Ma
Parameters
_ _ _ _ _
Recs : list of dictionaries in data model by data _ model
data _ model : MagIC data model ( default is 3)""" | if data_model == 3 :
site_key = 'site'
agekey = "age"
keybase = ""
else :
site_key = 'er_site_names'
agekey = find ( 'age' , list ( rec . keys ( ) ) )
if agekey != "" :
keybase = agekey . split ( '_' ) [ 0 ] + '_'
New = [ ]
for rec in Recs :
age = ''
if rec [ keybase + 'age' ] !=... |
def dict_match ( d , key , default = None ) :
"""Like _ _ getitem _ _ but works as if the keys ( ) are all filename patterns .
Returns the value of any dict key that matches the passed key .
Args :
d ( dict ) : A dict with filename patterns as keys
key ( str ) : A key potentially matching any of the keys
... | if key in d and "[" not in key :
return d [ key ]
else :
for pattern , value in iteritems ( d ) :
if fnmatchcase ( key , pattern ) :
return value
return default |
def find_last_character_instance ( sentence , character ) :
"""Function to locate the last instance of a character in a string .
Example :
find _ last _ character _ instance ( ' hello world ' , ' l ' ) - > 10
find _ last _ character _ instance ( ' language ' , ' g ' ) - > 7
find _ last _ character _ instanc... | last_seen = - 1
for idx in range ( len ( sentence ) ) :
if sentence [ idx ] == character :
last_seen = idx
return None if last_seen == - 1 else ( last_seen + 1 ) |
def end_time ( self ) :
"""Return the end time of the object .""" | try : # MSG :
try :
return datetime . strptime ( self . nc . attrs [ 'time_coverage_end' ] , '%Y-%m-%dT%H:%M:%SZ' )
except TypeError :
return datetime . strptime ( self . nc . attrs [ 'time_coverage_end' ] . astype ( str ) , '%Y-%m-%dT%H:%M:%SZ' )
except ValueError : # PPS :
return datetime ... |
def get_digests ( self ) :
"""Returns a map of repositories to digests""" | digests = { }
# repository - > digest
for registry in self . workflow . push_conf . docker_registries :
for image in self . workflow . tag_conf . images :
image_str = image . to_str ( )
if image_str in registry . digests :
digest = registry . digests [ image_str ]
digests [ i... |
def d ( obj , mode = 'exec' , file = None ) :
"""Interactive convenience for displaying the disassembly of a function ,
module , or code string .
Compiles ` text ` and recursively traverses the result looking for ` code `
objects to render with ` dis . dis ` .
Parameters
obj : str , CodeType , or object w... | if file is None :
file = sys . stdout
for name , co in walk_code ( extract_code ( obj , compile_mode = mode ) ) :
print ( name , file = file )
print ( '-' * len ( name ) , file = file )
dis . dis ( co , file = file )
print ( '' , file = file ) |
def zopen ( filename , * args , ** kwargs ) :
"""This function wraps around the bz2 , gzip and standard python ' s open
function to deal intelligently with bzipped , gzipped or standard text
files .
Args :
filename ( str / Path ) : filename or pathlib . Path .
\*args: Standard args for python open(..). E.... | if Path is not None and isinstance ( filename , Path ) :
filename = str ( filename )
name , ext = os . path . splitext ( filename )
ext = ext . upper ( )
if ext == ".BZ2" :
if PY_VERSION [ 0 ] >= 3 :
return bz2 . open ( filename , * args , ** kwargs )
else :
args = list ( args )
if l... |
def looking_for_pub ( self ) :
'''Look for a pub that accepts me and my friends''' | if self [ 'pub' ] != None :
return self . sober_in_pub
self . debug ( 'I am looking for a pub' )
group = list ( self . get_neighboring_agents ( ) )
for pub in self . env . available_pubs ( ) :
self . debug ( 'We\'re trying to get into {}: total: {}' . format ( pub , len ( group ) ) )
if self . env . enter (... |
def rec_split_path ( path ) :
'''将一个路径进行分隔 , 分别得到每父母的绝对路径及目录名''' | if len ( path ) > 1 and path . endswith ( '/' ) :
path = path [ : - 1 ]
if '/' not in path :
return [ path , ]
result = [ ]
while path != '/' :
parent , name = os . path . split ( path )
result . append ( ( path , name ) )
path = parent
result . append ( ( '/' , '/' ) )
result . reverse ( )
return r... |
def fuller ( target , MA , MB , vA , vB , temperature = 'pore.temperature' , pressure = 'pore.pressure' ) :
r"""Uses Fuller model to estimate diffusion coefficient for gases from first
principles at conditions of interest
Parameters
target : OpenPNM Object
The object for which these values are being calcula... | T = target [ temperature ]
P = target [ pressure ]
MAB = 2 * ( 1.0 / MA + 1.0 / MB ) ** ( - 1 )
MAB = MAB * 1e3
P = P * 1e-5
value = 0.00143 * T ** 1.75 / ( P * ( MAB ** 0.5 ) * ( vA ** ( 1. / 3 ) + vB ** ( 1. / 3 ) ) ** 2 ) * 1e-4
return value |
def inputtemplates ( self ) :
"""Return all input templates as a list ( of InputTemplate instances )""" | l = [ ]
for profile in self . profiles :
l += profile . input
return l |
def update ( gandi , domain , zone_id , file , record , new_record ) :
"""Update records entries for a domain .
You can update an individual record using - - record and - - new - record
parameters
Or you can use a plaintext file to update all records of a DNS zone at
once with - - file parameter .""" | if not zone_id :
result = gandi . domain . info ( domain )
zone_id = result [ 'zone_id' ]
if not zone_id :
gandi . echo ( 'No zone records found, domain %s doesn\'t seems to be' ' managed at Gandi.' % domain )
return
if file :
records = file . read ( )
result = gandi . record . zone_update ( zon... |
def PackagePublish ( package , classification , visibility , os ) :
"""Publishes a Blueprint Package for use within the Blueprint Designer .
https : / / t3n . zendesk . com / entries / 20426453 - Publish - Package
: param package : path to zip file containing package . manifest and supporting scripts
: param ... | r = clc . v1 . API . Call ( 'post' , 'Blueprint/PublishPackage' , { 'Classification' : Blueprint . classification_stoi [ classification ] , 'Name' : package , 'OperatingSystems' : os , 'Visibility' : Blueprint . visibility_stoi [ visibility ] } )
if int ( r [ 'StatusCode' ] ) == 0 :
return ( r ) |
def auto_zoom ( zoomx = True , zoomy = True , axes = "gca" , x_space = 0.04 , y_space = 0.04 , draw = True ) :
"""Looks at the bounds of the plotted data and zooms accordingly , leaving some
space around the data .""" | # Disable auto - updating by default .
_pylab . ioff ( )
if axes == "gca" :
axes = _pylab . gca ( )
# get the current bounds
x10 , x20 = axes . get_xlim ( )
y10 , y20 = axes . get_ylim ( )
# Autoscale using pylab ' s technique ( catches the error bars ! )
axes . autoscale ( enable = True , tight = True )
# Add padd... |
def pasa ( args ) :
"""% prog pasa pasa _ db fastafile
Run EVM in TIGR - only mode .""" | p = OptionParser ( pasa . __doc__ )
opts , args = p . parse_args ( args )
if len ( args ) != 2 :
sys . exit ( not p . print_help ( ) )
pasa_db , fastafile = args
termexons = "pasa.terminal_exons.gff3"
if need_update ( fastafile , termexons ) :
cmd = "$ANNOT_DEVEL/PASA2/scripts/pasa_asmbls_to_training_set.dbi"
... |
def block ( self ) :
"""While this context manager is active any signals for aborting
the process will be queued and exit the program once the context
is left .""" | self . _nosig = True
yield
self . _nosig = False
if self . _interrupted :
raise SystemExit ( "Aborted..." ) |
def _evaluate_one ( caller , svtype , size_range , ensemble , truth , data ) :
"""Compare a ensemble results for a caller against a specific caller and SV type .""" | def cnv_matches ( name ) :
return cnv_to_event ( name , data ) == svtype
def is_breakend ( name ) :
return name . startswith ( "BND" )
def in_size_range ( max_buffer = 0 ) :
def _work ( feat ) :
minf , maxf = size_range
buffer = min ( max_buffer , int ( ( ( maxf + minf ) / 2.0 ) / 10.0 ) )
... |
def _get_tiles ( board = None , terrain = None , numbers = None ) :
"""Generate a list of tiles using the given terrain and numbers options .
terrain options supported :
- Opt . empty - > all tiles are desert
- Opt . random - > tiles are randomized
- Opt . preset - >
- Opt . debug - > alias for Opt . rand... | if board is not None : # we have a board given , ignore the terrain and numbers opts and log warnings
# if they were supplied
tiles = _read_tiles_from_string ( board )
else : # we are being asked to generate a board
tiles = _generate_tiles ( terrain , numbers )
return tiles |
def rn_theory ( af , b ) :
"""R ( n ) ratio expected from theory for given noise type
alpha = b + 2""" | # From IEEE1139-2008
# alpha beta ADEV _ mu MDEV _ mu Rn _ mu
# -2 - 4 1 1 0 Random Walk FM
# -1 - 3 0 0 0 Flicker FM
# 0 - 2 - 1 - 1 0 White FM
# 1 - 1 - 2 - 2 0 Flicker PM
# 2 0 - 2 - 3 - 1 White PM
# ( a = - 3 flicker walk FM )
# ( a = - 4 random run FM )
if b == 0 :
return pow ( af , - 1 )
elif b == - 1 : # f _... |
def msg2long_form ( msg , processor , ** config ) :
"""Return a ' long form ' text representation of a message .
For most message , this will just default to the terse subtitle , but for
some messages a long paragraph - structured block of text may be returned .""" | result = processor . long_form ( msg , ** config )
if not result :
result = processor . subtitle ( msg , ** config )
return result |
def restore ( self ) :
"""Restores this DriveItem Version .
You can not restore the current version ( last one ) .
: return : Success / Failure
: rtype : bool""" | url = self . build_url ( self . _endpoints . get ( 'restore' ) . format ( id = self . object_id ) )
response = self . con . post ( url )
return bool ( response ) |
def towgs84 ( E , N , pkm = False , presentation = None ) :
"""Convert coordintes from TWD97 to WGS84
The east and north coordinates should be in meters and in float
pkm true for Penghu , Kinmen and Matsu area
You can specify one of the following presentations of the returned values :
dms - A tuple with deg... | _lng0 = lng0pkm if pkm else lng0
E /= 1000.0
N /= 1000.0
epsilon = ( N - N0 ) / ( k0 * A )
eta = ( E - E0 ) / ( k0 * A )
epsilonp = epsilon - beta1 * sin ( 2 * 1 * epsilon ) * cosh ( 2 * 1 * eta ) - beta2 * sin ( 2 * 2 * epsilon ) * cosh ( 2 * 2 * eta ) - beta3 * sin ( 2 * 3 * epsilon ) * cosh ( 2 * 3 * eta )
etap = et... |
def transform_incoming ( self , son , collection ) :
"""Recursively replace all keys that need transforming .""" | return self . _transform_incoming ( copy . deepcopy ( son ) , collection ) |
def check_dihedral ( self , construction_table ) :
"""Checks , if the dihedral defining atom is colinear .
Checks for each index starting from the third row of the
` ` construction _ table ` ` , if the reference atoms are colinear .
Args :
construction _ table ( pd . DataFrame ) :
Returns :
list : A lis... | c_table = construction_table
angles = self . get_angle_degrees ( c_table . iloc [ 3 : , : ] . values )
problem_index = np . nonzero ( ( 175 < angles ) | ( angles < 5 ) ) [ 0 ]
rename = dict ( enumerate ( c_table . index [ 3 : ] ) )
problem_index = [ rename [ i ] for i in problem_index ]
return problem_index |
def send_media_file ( self , filename ) :
"""Function used to send media files from the media folder to the browser .""" | cache_timeout = self . get_send_file_max_age ( filename )
return send_from_directory ( self . config [ 'MEDIA_FOLDER' ] , filename , cache_timeout = cache_timeout ) |
def has_enacted ( self , billing_cycle ) :
"""Has this recurring cost already enacted transactions for given billing cycle ?""" | return RecurredCost . objects . filter ( recurring_cost = self , billing_cycle = billing_cycle , ) . exists ( ) |
def set_log_level ( self , log_level ) :
'''Configures class log level
Arguments :
log _ level ( : obj : ` str ` ) : log level ( ' NOTSET ' , ' DEBUG ' , ' INFO ' ' WARNING ' ,
' ERROR ' , ' CRITICAL ' )''' | if log_level == 'DEBUG' :
self . log . setLevel ( logging . DEBUG )
self . log . debug ( "Changing log level to " + log_level )
elif log_level == 'INFO' :
self . log . setLevel ( logging . INFO )
self . log . info ( "Changing log level to " + log_level )
elif log_level == 'WARNING' :
self . log . se... |
def file_list_hosts ( blockchain_id , wallet_keys = None , config_path = CONFIG_PATH ) :
"""Given a blockchain ID , find out the hosts the blockchain ID owner has registered keys for .
Return { ' status ' : True , ' hosts ' : hostnames } on success
Return { ' error ' : . . . } on failure""" | config_dir = os . path . dirname ( config_path )
try :
ret = blockstack_gpg . gpg_list_app_keys ( blockchain_id , APP_NAME , wallet_keys = wallet_keys , config_dir = config_dir )
except Exception , e :
ret = { 'error' : traceback . format_exc ( e ) }
if 'error' in ret :
log . error ( "Failed to list app key... |
def cleanup_outdir ( outdir , archive ) :
"""Cleanup outdir after extraction and return target file name and
result string .""" | make_user_readable ( outdir )
# move single directory or file in outdir
( success , msg ) = move_outdir_orphan ( outdir )
if success : # msg is a single directory or filename
return msg , "`%s'" % msg
# outdir remains unchanged
# rename it to something more user - friendly ( basically the archive
# name without ext... |
def filenames ( self ) :
"""Returns the filenames that this par2 file repairs .""" | return [ p . name for p in self . packets if isinstance ( p , FileDescriptionPacket ) ] |
def set_tts ( self , level ) :
"""Set the values for
: data : ` ~ aeneas . runtimeconfiguration . RuntimeConfiguration . TTS `
and
: data : ` ~ aeneas . runtimeconfiguration . RuntimeConfiguration . TTS _ PATH `
matching the given granularity level .
Currently supported levels :
* ` ` 1 ` ` ( paragraph ... | if level in self . TTS_GRANULARITY_MAP . keys ( ) :
tts_key , tts_path_key = self . TTS_GRANULARITY_MAP [ level ]
self [ self . TTS ] = self [ tts_key ]
self [ self . TTS_PATH ] = self [ tts_path_key ] |
def browse ( package , homepage ) :
"""Browse to a package ' s PyPI or project homepage .""" | p = Package ( package )
try :
if homepage :
secho ( u'Opening homepage for "{0}"...' . format ( package ) , bold = True )
url = p . home_page
else :
secho ( u'Opening PyPI page for "{0}"...' . format ( package ) , bold = True )
url = p . package_url
except NotFoundError :
abo... |
def _fetch_url ( url , is_threaded , timeout = None ) :
"""Crawls the html content of the parameter url and saves the html in _ results
: param url :
: param is _ threaded : If True , results will be stored for later processing by the fetch _ urls method . Else not .
: param timeout : in seconds , if None , t... | headers = { 'User-Agent' : 'Mozilla/5.0' }
req = urllib . request . Request ( url , None , headers )
html = urllib . request . urlopen ( req , data = None , timeout = timeout ) . read ( )
if is_threaded :
SimpleCrawler . _results [ url ] = html
return html |
def sample_annotation ( data ) :
"""Annotate miRNAs using miRBase database with seqbuster tool""" | names = data [ "rgnames" ] [ 'sample' ]
tools = dd . get_expression_caller ( data )
work_dir = os . path . join ( dd . get_work_dir ( data ) , "mirbase" )
out_dir = os . path . join ( work_dir , names )
utils . safe_makedir ( out_dir )
out_file = op . join ( out_dir , names )
if dd . get_mirbase_hairpin ( data ) :
... |
def rpc_get_zonefiles ( self , zonefile_hashes , ** con_info ) :
"""Get zonefiles from the local zonefile set .
Only return at most 100 zonefiles .
Return { ' status ' : True , ' zonefiles ' : { zonefile _ hash : zonefile } } on success
Return { ' error ' : . . . } on error
zonefiles will be serialized to s... | conf = get_blockstack_opts ( )
if not is_atlas_enabled ( conf ) :
return { 'error' : 'No data' , 'http_status' : 400 }
if 'zonefiles' not in conf :
return { 'error' : 'No zonefiles directory (likely a configuration bug)' , 'http_status' : 404 }
if type ( zonefile_hashes ) != list :
log . error ( "Not a zone... |
def detect_microbit ( self ) :
"""Detect a microbit .""" | try :
gpad = MicroBitPad ( self )
except ModuleNotFoundError :
warn ( "The microbit library could not be found in the pythonpath. \n" "For more information, please visit \n" "https://inputs.readthedocs.io/en/latest/user/microbit.html" , RuntimeWarning )
else :
self . microbits . append ( gpad )
self . g... |
def upvote ( self ) :
"""Upvote : class : ` Issue ` .""" | self . requester . post ( '/{endpoint}/{id}/upvote' , endpoint = self . endpoint , id = self . id )
return self |
def wait_until_page_does_not_contain_these_elements ( self , timeout , * locators ) :
"""Waits until all of the specified elements are not found on the page .
| * Argument * | * Description * | * Example * |
| timeout | maximum time to wait , if set to $ { None } it will use Selenium ' s default timeout | 5s | ... | self . _wait_until_no_error ( timeout , self . _wait_for_elements_to_go_away , locators ) |
def getDiscountedBulkPrice ( self ) :
"""Compute discounted bulk discount excl . VAT""" | price = self . getBulkPrice ( )
price = price and price or 0
discount = self . bika_setup . getMemberDiscount ( )
discount = discount and discount or 0
return float ( price ) - ( float ( price ) * float ( discount ) ) / 100 |
def get_parser ( parser ) :
"""Grabs the parser .
args :
parser : The parser""" | parser . description = textwrap . dedent ( """
Segment the .po files in LOCALE(s) based on the segmenting rules in
config.yaml.
Note that segmenting is *not* idempotent: it modifies the input file, so
be careful that you don't run it twice on the same file.
""" . strip ( ) )
parser ... |
def shear_mod ( self ) :
"""Strain - compatible shear modulus [ kN / / m2 ] .""" | try :
value = self . _shear_mod . value
except AttributeError :
value = self . _shear_mod
return value |
def parse_gene_list ( path : str , graph : Graph , anno_type : str = "name" ) -> list :
"""Parse a list of genes and return them if they are in the network .
: param str path : The path of input file .
: param Graph graph : The graph with genes as nodes .
: param str anno _ type : The type of annotation with ... | # read the file
genes = pd . read_csv ( path , header = None ) [ 0 ] . tolist ( )
genes = [ str ( int ( gene ) ) for gene in genes ]
# get those genes which are in the network
ind = [ ]
if anno_type == "name" :
ind = graph . vs . select ( name_in = genes ) . indices
elif anno_type == "symbol" :
ind = graph . vs... |
def get_dependencies ( ctx , archive_name , version ) :
'''List the dependencies of an archive''' | _generate_api ( ctx )
var = ctx . obj . api . get_archive ( archive_name )
deps = [ ]
dependencies = var . get_dependencies ( version = version )
for arch , dep in dependencies . items ( ) :
if dep is None :
deps . append ( arch )
else :
deps . append ( '{}=={}' . format ( arch , dep ) )
click .... |
def _verify_nonce ( self , nonce , context ) :
"""Verify the received OIDC ' nonce ' from the ID Token .
: param nonce : OIDC nonce
: type nonce : str
: param context : current request context
: type context : satosa . context . Context
: raise SATOSAAuthenticationError : if the nonce is incorrect""" | backend_state = context . state [ self . name ]
if nonce != backend_state [ NONCE_KEY ] :
satosa_logging ( logger , logging . DEBUG , "Missing or invalid nonce in authn response for state: %s" % backend_state , context . state )
raise SATOSAAuthenticationError ( context . state , "Missing or invalid nonce in au... |
def ConnectNoSSL ( host = 'localhost' , port = 443 , user = 'root' , pwd = '' , service = "hostd" , adapter = "SOAP" , namespace = None , path = "/sdk" , version = None , keyFile = None , certFile = None , thumbprint = None , b64token = None , mechanism = 'userpass' ) :
"""Provides a standard method for connecting ... | if hasattr ( ssl , '_create_unverified_context' ) :
sslContext = ssl . _create_unverified_context ( )
else :
sslContext = None
return Connect ( host = host , port = port , user = user , pwd = pwd , service = service , adapter = adapter , namespace = namespace , path = path , version = version , keyFile = keyFil... |
def calculate_mean_edit_distance_and_loss ( iterator , dropout , reuse ) :
r'''This routine beam search decodes a mini - batch and calculates the loss and mean edit distance .
Next to total and average loss it returns the mean edit distance ,
the decoded result and the batch ' s original Y .''' | # Obtain the next batch of data
( batch_x , batch_seq_len ) , batch_y = iterator . get_next ( )
# Calculate the logits of the batch
logits , _ = create_model ( batch_x , batch_seq_len , dropout , reuse = reuse )
# Compute the CTC loss using TensorFlow ' s ` ctc _ loss `
total_loss = tf . nn . ctc_loss ( labels = batch_... |
def _repeat_length ( cls , part ) :
"""The length of the repeated portions of ` ` part ` ` .
: param part : a number
: type part : list of int
: returns : the first index at which part repeats
: rtype : int
If part does not repeat , result is the length of part .
Complexity : O ( len ( part ) ^ 2)""" | repeat_len = len ( part )
if repeat_len == 0 :
return repeat_len
first_digit = part [ 0 ]
limit = repeat_len // 2 + 1
indices = ( i for i in range ( 1 , limit ) if part [ i ] == first_digit )
for index in indices :
( quot , rem ) = divmod ( repeat_len , index )
if rem == 0 :
first_chunk = part [ 0 :... |
def undelay ( self ) :
'''resolves all delayed arguments''' | i = 0
while i < len ( self ) :
op = self [ i ]
i += 1
if hasattr ( op , 'arg1' ) :
if isinstance ( op . arg1 , DelayedArg ) :
op . arg1 = op . arg1 . resolve ( )
if isinstance ( op . arg1 , CodeBlock ) :
op . arg1 . undelay ( ) |
def getEntity ( self , id = None , uri = None , match = None ) :
"""get a generic entity with given ID or via other methods . . .""" | if not id and not uri and not match :
return None
if type ( id ) == type ( "string" ) :
uri = id
id = None
if not uri . startswith ( "http://" ) :
match = uri
uri = None
if match :
if type ( match ) != type ( "string" ) :
return [ ]
res = [ ]
if ":" in match : # qname... |
def handle ( self , connection_id , message_content ) :
"""If the connection wants to take on a role that requires a challenge to
be signed , it will request the challenge by sending an
AuthorizationChallengeRequest to the validator it wishes to connect to .
The validator will send back a random payload that ... | if self . _network . get_connection_status ( connection_id ) != ConnectionStatus . CONNECTION_REQUEST :
LOGGER . debug ( "Connection's previous message was not a" " ConnectionRequest, Remove connection to %s" , connection_id )
violation = AuthorizationViolation ( violation = RoleType . Value ( "NETWORK" ) )
... |
def quote_completions ( self , completions , cword_prequote , last_wordbreak_pos ) :
"""If the word under the cursor started with a quote ( as indicated by a nonempty ` ` cword _ prequote ` ` ) , escapes
occurrences of that quote character in the completions , and adds the quote to the beginning of each completio... | special_chars = "\\"
# If the word under the cursor was quoted , escape the quote char .
# Otherwise , escape all special characters and specially handle all COMP _ WORDBREAKS chars .
if cword_prequote == "" : # Bash mangles completions which contain characters in COMP _ WORDBREAKS .
# This workaround has the same effe... |
def hilbertrot ( n , x , y , rx , ry ) :
"""Rotates and flips a quadrant appropriately for the Hilbert scan
generator . See https : / / en . wikipedia . org / wiki / Hilbert _ curve .""" | if ry == 0 :
if rx == 1 :
x = n - 1 - x
y = n - 1 - y
return y , x
return x , y |
def getPrimaryRole ( store , primaryRoleName , createIfNotFound = False ) :
"""Get Role object corresponding to an identifier name . If the role name
passed is the empty string , it is assumed that the user is not
authenticated , and the ' Everybody ' role is primary . If the role name
passed is non - empty ,... | if not primaryRoleName :
return getEveryoneRole ( store )
ff = store . findUnique ( Role , Role . externalID == primaryRoleName , default = None )
if ff is not None :
return ff
authRole = getAuthenticatedRole ( store )
if createIfNotFound :
role = Role ( store = store , externalID = primaryRoleName )
ro... |
def get_source_link ( file , line , display_text = "[source]" , ** kwargs ) -> str :
"Returns github link for given file" | link = f"{SOURCE_URL}{file}#L{line}"
if display_text is None :
return link
return f'<a href="{link}" class="source_link" style="float:right">{display_text}</a>' |
def proxy ( self ) :
"""Return a Deferred that will result in a proxy object in the future .""" | d = Deferred ( self . loop )
self . _proxy_deferreds . append ( d )
if self . _proxy :
d . callback ( self . _proxy )
return d |
def postIncidents ( self , name , message , status , visible , ** kwargs ) :
'''Create a new incident .
: param name : Name of the incident
: param message : A message ( supporting Markdown ) to explain more .
: param status : Status of the incident .
: param visible : Whether the incident is publicly visib... | kwargs [ 'name' ] = name
kwargs [ 'message' ] = message
kwargs [ 'status' ] = status
kwargs [ 'visible' ] = visible
return self . __postRequest ( '/incidents' , kwargs ) |
def wait_for_event ( event ) :
"""Wraps a win32 event into a ` Future ` and wait for it .""" | f = Future ( )
def ready ( ) :
get_event_loop ( ) . remove_win32_handle ( event )
f . set_result ( None )
get_event_loop ( ) . add_win32_handle ( event , ready )
return f |
def _extract_translations ( self , domains ) :
"""Extract the translations into ` . pot ` files""" | for domain , options in domains . items ( ) : # Create the extractor
extractor = babel_frontend . extract_messages ( )
extractor . initialize_options ( )
# The temporary location to write the ` . pot ` file
extractor . output_file = options [ 'pot' ]
# Add the comments marked with ' tn : ' to the tr... |
def _integrate_cvode ( self , * args , ** kwargs ) :
"""Do not use directly ( use ` ` integrate ( . . . , integrator = ' cvode ' ) ` ` ) .
Uses CVode from CVodes in
` SUNDIALS < https : / / computation . llnl . gov / casc / sundials / > ` _
( via ` pycvodes < https : / / pypi . python . org / pypi / pycvodes ... | import pycvodes
# Python interface to SUNDIALS ' s cvodes integrators
kwargs [ 'with_jacobian' ] = kwargs . get ( 'method' , 'bdf' ) in pycvodes . requires_jac
if 'lband' in kwargs or 'uband' in kwargs or 'band' in kwargs :
raise ValueError ( "lband and uband set locally (set at" " initialization instead)" )
if sel... |
def validate ( self ) :
'''Perform integrity checks on the modes in this document .
Returns :
None''' | for r in self . roots :
refs = r . references ( )
check_integrity ( refs ) |
def concentric_circle ( center , radius , size = None ) :
"""Draws a circle with the given center and radius .
This is designed to ensure that concentric circles with integer radii are " airtight " ,
i . e . there are not unfilled pixels between them .
: param center : The ( x , y ) coordinates of the center ... | c_out = bresenham_circle_octant ( radius + 1 )
c_in = bresenham_circle_octant ( radius )
coords = [ ]
# note that in this loop , y also serves as the array index ,
# since it starts at 0 and increments each element .
for x , y in c_in :
for x1 in range ( x , c_out [ y ] [ 0 ] ) :
coords . append ( ( x1 , y ... |
def _lemmatise_contractions ( self , f , * args , ** kwargs ) :
"""Lemmatise un mot f avec sa contraction
: param f : Mot à lemmatiser
: yield : Match formated like in _ lemmatise ( )""" | fd = f
for contraction , decontraction in self . _contractions . items ( ) :
if fd . endswith ( contraction ) :
fd = f [ : - len ( contraction ) ]
if "v" in fd or "V" in fd :
fd += decontraction
else :
fd += deramise ( decontraction )
yield from self . _lemmat... |
def decode ( s ) :
"""Decode a string using the system encoding if needed ( ie byte strings )""" | if isinstance ( s , bytes ) :
return s . decode ( sys . getdefaultencoding ( ) )
else :
return s |
def get_signature ( func ) :
"""Gathers information about the call signature of ` func ` .""" | code = func . __code__
# Names of regular parameters
parameters = tuple ( code . co_varnames [ : code . co_argcount ] )
# Flags
has_varargs = bool ( code . co_flags & inspect . CO_VARARGS )
has_varkw = bool ( code . co_flags & inspect . CO_VARKEYWORDS )
has_kwonly = bool ( code . co_kwonlyargcount )
# A mapping of para... |
def _hook_decorator ( self , addr , length = 0 , kwargs = None ) :
"""Return a function decorator that allows easy hooking . Please refer to hook ( ) for its usage .
: return : The function decorator .""" | def hook_decorator ( func ) :
self . hook ( addr , func , length = length , kwargs = kwargs )
return func
return hook_decorator |
def full_analysis ( self , ncpus = 1 , ** kwargs ) :
"""Perform a full structural analysis of a molecule .
This invokes other methods :
1 . : attr : ` molecular _ weight ( ) `
2 . : attr : ` calculate _ centre _ of _ mass ( ) `
3 . : attr : ` calculate _ maximum _ diameter ( ) `
4 . : attr : ` calculate _... | self . molecular_weight ( )
self . calculate_centre_of_mass ( )
self . calculate_maximum_diameter ( )
self . calculate_average_diameter ( )
self . calculate_pore_diameter ( )
self . calculate_pore_volume ( )
self . calculate_pore_diameter_opt ( ** kwargs )
self . calculate_pore_volume_opt ( ** kwargs )
self . calculate... |
def organizations_search ( self , external_id = None , ** kwargs ) :
"https : / / developer . zendesk . com / rest _ api / docs / core / organizations # search - organizations - by - external - id" | api_path = "/api/v2/organizations/search.json"
api_query = { }
if "query" in kwargs . keys ( ) :
api_query . update ( kwargs [ "query" ] )
del kwargs [ "query" ]
if external_id :
api_query . update ( { "external_id" : external_id , } )
return self . call ( api_path , query = api_query , ** kwargs ) |
def filter_unnecessary_ports ( query , device_owners = None , vnic_type = None , active = True ) :
"""Filter out all ports are not needed on CVX""" | query = ( query . filter_unbound_ports ( ) . filter_by_device_owner ( device_owners ) . filter_by_device_id ( ) . filter_unmanaged_physnets ( ) )
if active :
query = query . filter_inactive_ports ( )
if vnic_type :
query = query . filter_by_vnic_type ( vnic_type )
return query |
def post_event_publish ( self , id , ** data ) :
"""POST / events / : id / publish /
Publishes an event if it has not already been deleted . In order for publish to be permitted , the event must have all
necessary information , including a name and description , an organizer , at least one ticket , and valid pa... | return self . post ( "/events/{0}/publish/" . format ( id ) , data = data ) |
def _check_contigs_to_use ( self , ref_dict ) :
'''Checks that the set of contigs to use are all in the reference
fasta lengths dict made by self . _ get _ ref _ lengths ( )''' | if self . contigs_to_use is None :
return True
for contig in self . contigs_to_use :
if contig not in ref_dict :
raise Error ( 'Requested to use contig "' + contig + '", but not found in input BAM file "' + self . bam + '"' )
return True |
def refreshUi ( self ) :
"""Matches the UI state to the current cursor positioning .""" | font = self . currentFont ( )
for name in ( 'underline' , 'bold' , 'italic' , 'strikeOut' ) :
getter = getattr ( font , name )
act = self . _actions [ name ]
act . blockSignals ( True )
act . setChecked ( getter ( ) )
act . blockSignals ( False ) |
def del_properties ( self , properties , recursive = None ) :
"""Delete properties listed in properties
properties - iterable contains the property names to delete . If it is an
str it will be casted to tuple .
recursive - on folders property attachment is recursive by default . It is
possible to force recu... | return self . _accessor . del_properties ( self , properties , recursive ) |
def get_sun_rise_set_transit ( self , times , method = 'pyephem' , ** kwargs ) :
"""Calculate sunrise , sunset and transit times .
Parameters
times : DatetimeIndex
Must be localized to the Location
method : str , default ' pyephem '
' pyephem ' , ' spa ' , or ' geometric '
kwargs are passed to the relev... | if method == 'pyephem' :
result = solarposition . sun_rise_set_transit_ephem ( times , self . latitude , self . longitude , ** kwargs )
elif method == 'spa' :
result = solarposition . sun_rise_set_transit_spa ( times , self . latitude , self . longitude , ** kwargs )
elif method == 'geometric' :
sr , ss , t... |
def parse_obj ( obj ) :
"""> > > parse _ obj ( ' bucket / key ' )
( ' bucket ' , ' key ' )
> > > parse _ obj ( ' my - bucket / path / to / file . txt ' )
( ' my - bucket ' , ' path / to / file . txt ' )
> > > parse _ obj ( ' s3 : / / this _ bucket / some / path . txt ' )
( ' this _ bucket ' , ' some / pat... | obj = obj . lstrip ( 's3://' )
if obj . startswith ( 'http' ) :
url = urlparse . urlparse ( obj )
if url . netloc == 's3.amazonaws.com' :
path = url . path [ 1 : ]
# remove leading slash
bucket , key = path . split ( '/' , 1 )
else : # bucket . s3 . amazonaws . com form
bucke... |
def convert_time ( self , time ) :
"""A helper function to convert seconds into hh : mm : ss for better
readability .
time : A string representing time in seconds .""" | time_string = str ( datetime . timedelta ( seconds = int ( time ) ) )
if time_string . split ( ':' ) [ 0 ] == '0' :
time_string = time_string . partition ( ':' ) [ 2 ]
return time_string |
def get_by_email ( cls , email ) :
"""Return a User by email address""" | return cls . query ( ) . filter ( cls . email == email ) . first ( ) |
def _find_matching_collections_internally ( collections , record ) :
"""Find matching collections with internal engine .
: param collections : set of collections where search
: param record : record to match""" | for name , data in iteritems ( collections ) :
if _build_query ( data [ 'query' ] ) . match ( record ) :
yield data [ 'ancestors' ]
raise StopIteration |
def items ( self , path = None ) :
"""Returns set of items .
: param path : Regex filter on item path .
: return : List of Item class objects .""" | items = list ( self . iteritems ( ) )
if path is not None :
path += '$'
regex = re . compile ( path )
items = [ i for i in items if regex . match ( i . path ) ]
return items |
def onSave ( self , event , alert = False , destroy = True ) :
"""Save grid data""" | # tidy up drop _ down menu
if self . drop_down_menu :
self . drop_down_menu . clean_up ( )
# then save actual data
self . grid_builder . save_grid_data ( )
if not event and not alert :
return
# then alert user
wx . MessageBox ( 'Saved!' , 'Info' , style = wx . OK | wx . ICON_INFORMATION )
if destroy :
self ... |
def autocmds ( namespace = None , args = None , command_suffix = '_command' , add_dry_run_option = True , add_verbosity_option = True ) :
"""Parse and run commands .
Will search ` ` namespace ` ` for functions that end with ` ` command _ suffix ` ` .
: param namespace : the namespace / module to search for comm... | if namespace is None :
namespace = inspect . currentframe ( ) . f_back . f_globals
elif type ( namespace ) is types . ModuleType :
namespace = namespace . __dict__
if args is None :
args = sys . argv
if len ( args ) < 2 or args [ 1 ] in ( '-h' , '--help' ) :
print_help ( namespace , command_suffix )
... |
def difference ( self , * others ) :
r"""Return a new multiset with all elements from the others removed .
> > > ms = Multiset ( ' aab ' )
> > > sorted ( ms . difference ( ' bc ' ) )
[ ' a ' , ' a ' ]
You can also use the ` ` - ` ` operator for the same effect . However , the operator version
will only ac... | result = self . __copy__ ( )
_elements = result . _elements
_total = result . _total
for other in map ( self . _as_multiset , others ) :
for element , multiplicity in other . items ( ) :
if element in _elements :
old_multiplicity = _elements [ element ]
new_multiplicity = old_multipl... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.