signature stringlengths 29 44.1k | implementation stringlengths 0 85.2k |
|---|---|
def API_GET ( self , courseid , taskid , submissionid ) : # pylint : disable = arguments - differ
"""List all the submissions that the connected user made . Returns list of the form
" id " : " submission _ id1 " ,
" submitted _ on " : " date " ,
" status " : " done " , # can be " done " , " waiting " , " erro... | with_input = "input" in web . input ( )
return _get_submissions ( self . course_factory , self . submission_manager , self . user_manager , self . app . _translations , courseid , taskid , with_input , submissionid ) |
def spec_sum ( ph2 ) :
"""Compute total spectral sum of the real spectral quantity ` ` ph ^ 2 ` ` .
Parameters
model : pyqg . Model instance
The model object from which ` ph ` originates
ph2 : real array
The field on which to compute the sum
Returns
var _ dens : float
The sum of ` ph2 `""" | ph2 = 2. * ph2
ph2 [ ... , 0 ] = ph2 [ ... , 0 ] / 2.
ph2 [ ... , - 1 ] = ph2 [ ... , - 1 ] / 2.
return ph2 . sum ( axis = ( - 1 , - 2 ) ) |
def configfile ( f ) :
"""This decorator will parse a configuration file in YAML format
and store the dictionary in ` ` ctx . blockchain . config ` `""" | @ click . pass_context
def new_func ( ctx , * args , ** kwargs ) :
ctx . config = yaml . load ( open ( ctx . obj [ "configfile" ] ) )
return ctx . invoke ( f , * args , ** kwargs )
return update_wrapper ( new_func , f ) |
def request_will_echo ( self ) :
"""Tell the DE that we would like to echo their text . See RFC 857.""" | self . _iac_will ( ECHO )
self . _note_reply_pending ( ECHO , True )
self . telnet_echo = True |
def _create_overrides_from_config ( config ) :
"""Creates a two - level dictionary of d [ section ] [ option ] from a config parser object .""" | d = { }
for s in config . sections ( ) :
d [ s ] = { }
for opt in config . options ( s ) :
d [ s ] [ opt ] = config . get ( s , opt )
return d |
def materialize_as_ndarray ( a ) :
"""Convert distributed arrays to ndarrays .""" | if type ( a ) in ( list , tuple ) :
if da is not None and any ( isinstance ( arr , da . Array ) for arr in a ) :
return da . compute ( * a , sync = True )
return tuple ( np . asarray ( arr ) for arr in a )
return np . asarray ( a ) |
def to_excel ( self , * args ) :
"""Dump all the data to excel , fname and path can be passed as args""" | path = os . getcwd ( )
fname = self . fname . replace ( ".tpl" , "_tpl" ) + ".xlsx"
idxs = self . filter_trends ( "" )
for idx in idxs :
self . extract ( idx )
data_df = pd . DataFrame ( self . data )
data_df . columns = self . label . values ( )
data_df . insert ( 0 , "Time [s]" , self . time )
if len ( args ) > 0... |
def get_parties ( self , obj ) :
"""All parties .""" | return PartySerializer ( Party . objects . all ( ) , many = True ) . data |
def system_info ( url , auth , verify_ssl ) :
"""Retrieve SDC system information .
Args :
url ( str ) : the host url .
auth ( tuple ) : a tuple of username , and password .""" | sysinfo_response = requests . get ( url + '/info' , headers = X_REQ_BY , auth = auth , verify = verify_ssl )
sysinfo_response . raise_for_status ( )
return sysinfo_response . json ( ) |
def get_reports ( self , ** params ) :
"""https : / / developers . coinbase . com / api / v2 # list - all - reports""" | response = self . _get ( 'v2' , 'reports' , data = params )
return self . _make_api_object ( response , Report ) |
def get_default_client ( path = None , ui = None , ** kwargs ) :
"""Get a client for a connected Trezor device .
Returns a TrezorClient instance with minimum fuss .
If no path is specified , finds first connected Trezor . Otherwise performs
a prefix - search for the specified device . If no UI is supplied , i... | from . transport import get_transport
from . ui import ClickUI
transport = get_transport ( path , prefix_search = True )
if ui is None :
ui = ClickUI ( )
return TrezorClient ( transport , ui , ** kwargs ) |
def typelogged_module ( md ) :
"""Works like typelogged , but is only applicable to modules by explicit call ) .
md must be a module or a module name contained in sys . modules .""" | if not pytypes . typelogging_enabled :
return md
if isinstance ( md , str ) :
if md in sys . modules :
md = sys . modules [ md ]
if md is None :
return md
elif md in pytypes . typechecker . _pending_modules : # if import is pending , we just store this call for later
pyty... |
def _write_rigid_information ( xml_file , rigid_bodies ) :
"""Write rigid body information .
Parameters
xml _ file : file object
The file object of the hoomdxml file being written
rigid _ bodies : list , len = n _ particles
The rigid body that each particle belongs to ( - 1 for none )""" | if not all ( body is None for body in rigid_bodies ) :
xml_file . write ( '<body>\n' )
for body in rigid_bodies :
if body is None :
body = - 1
xml_file . write ( '{}\n' . format ( int ( body ) ) )
xml_file . write ( '</body>\n' ) |
def write_diversity_metrics ( data , sample_ids , fp = None ) :
"""Given a dictionary of diversity calculations ( keyed by method )
write out the data to a file .""" | if fp is None :
fp = "./diversity_data.txt"
with open ( fp , "w" ) as outf :
out = csv . writer ( outf , delimiter = "\t" )
out . writerow ( [ "SampleID" , "Group" , "Calculation" ] )
for group , d in data . iteritems ( ) :
for sid , value in d . iteritems ( ) :
out . writerow ( [ si... |
def format_options ( self , ctx , formatter ) :
"""Writes SCL related options into the formatter as a separate
group .""" | super ( Pyp2rpmCommand , self ) . format_options ( ctx , formatter )
scl_opts = [ ]
for param in self . get_params ( ctx ) :
if isinstance ( param , SclizeOption ) :
scl_opts . append ( param . get_scl_help_record ( ctx ) )
if scl_opts :
with formatter . section ( 'SCL related options' ) :
forma... |
def on_site ( self , site_id = None ) :
"""Return a : class : ` QuerySet ` of pages that are published on the site
defined by the ` ` SITE _ ID ` ` setting .
: param site _ id : specify the id of the site object to filter with .""" | if settings . PAGE_USE_SITE_ID :
if not site_id :
site_id = settings . SITE_ID
return self . filter ( sites = site_id )
return self . all ( ) |
def get_user_token ( ) :
"""Return the authenticated user ' s auth token""" | if not hasattr ( stack . top , 'current_user' ) :
return ''
current_user = stack . top . current_user
return current_user . get ( 'token' , '' ) |
def convertTranscriptEffect ( self , annStr , hgvsG ) :
"""Takes the ANN string of a SnpEff generated VCF , splits it
and returns a populated GA4GH transcript effect object .
: param annStr : String
: param hgvsG : String
: return : effect protocol . TranscriptEffect ( )""" | effect = self . _createGaTranscriptEffect ( )
effect . hgvs_annotation . CopyFrom ( protocol . HGVSAnnotation ( ) )
annDict = dict ( )
if self . _annotationType == ANNOTATIONS_SNPEFF :
annDict = dict ( zip ( self . SNPEFF_FIELDS , annStr . split ( "|" ) ) )
elif self . _annotationType == ANNOTATIONS_VEP_V82 :
a... |
def endpoint_present ( name , publicurl = None , internalurl = None , adminurl = None , region = None , profile = None , url = None , interface = None , ** connection_args ) :
'''Ensure the specified endpoints exists for service
name
The Service name
publicurl
The public url of service endpoint ( for V2 API... | ret = { 'name' : name , 'changes' : { } , 'result' : True , 'comment' : '' }
_api_version ( profile = profile , ** connection_args )
endpoint = __salt__ [ 'keystone.endpoint_get' ] ( name , region , profile = profile , interface = interface , ** connection_args )
def _changes ( desc ) :
return ret . get ( 'comment'... |
def getRelativePath ( basepath , path ) :
"""Get a path that is relative to the given base path .""" | basepath = splitpath ( os . path . abspath ( basepath ) )
path = splitpath ( os . path . abspath ( path ) )
afterCommon = False
for c in basepath :
if afterCommon or path [ 0 ] != c :
path . insert ( 0 , os . path . pardir )
afterCommon = True
else :
del path [ 0 ]
return os . path . joi... |
def cut_video_stream ( stream , start , end , fmt ) :
"""cut video stream from ` start ` to ` end ` time
Parameters
stream : bytes
video file content
start : float
start time
end : float
end time
Returns
result : bytes
content of cut video""" | with TemporaryDirectory ( ) as tmp :
in_file = Path ( tmp ) / f"in{fmt}"
out_file = Path ( tmp ) / f"out{fmt}"
in_file . write_bytes ( stream )
try :
ret = subprocess . run ( [ "ffmpeg" , "-ss" , f"{start}" , "-i" , f"{in_file}" , "-to" , f"{end}" , "-c" , "copy" , f"{out_file}" , ] , capture_ou... |
def generate_module ( spec , out ) :
"""Given an AMQP spec parsed into an xml . etree . ElemenTree ,
and a file - like ' out ' object to write to , generate
the skeleton of a Python module .""" | # HACK THE SPEC so that ' access ' is handled by ' channel ' instead of ' connection '
for amqp_class in spec . findall ( 'class' ) :
if amqp_class . attrib [ 'name' ] == 'access' :
amqp_class . attrib [ 'handler' ] = 'channel'
# Build up some helper dictionaries
for domain in spec . findall ( 'domain' ) :
... |
def Insert ( self , key , value , row_index ) :
"""Inserts new values at a specified offset .
Args :
key : string for header value .
value : string for a data value .
row _ index : Offset into row for data .
Raises :
IndexError : If the offset is out of bands .""" | if row_index < 0 :
row_index += len ( self )
if not 0 <= row_index < len ( self ) :
raise IndexError ( 'Index "%s" is out of bounds.' % row_index )
new_row = Row ( )
for idx in self . header :
if self . index ( idx ) == row_index :
new_row [ key ] = value
new_row [ idx ] = self [ idx ]
self . _k... |
def write_dat ( self ) :
"""Write ` ` system . Varout . vars ` ` to a ` ` . dat ` ` file
: return :""" | logger . warn ( 'This function is deprecated and replaced by `write_np_dat`.' )
ret = False
system = self . system
# compute the total number of columns , excluding time
if not system . Recorder . n :
n_vars = system . dae . m + system . dae . n
# post - computed power flows include :
# bus - ( Pi , Qi )
... |
def markdown_toclify ( input_file , output_file = None , github = False , back_to_top = False , nolink = False , no_toc_header = False , spacer = 0 , placeholder = None , exclude_h = None , remove_dashes = False ) :
"""Function to add table of contents to markdown files .
Parameters
input _ file : str
Path to... | raw_contents = read_lines ( input_file )
cleaned_contents = remove_lines ( raw_contents , remove = ( '[[back to top]' , '<a class="mk-toclify"' ) )
processed_contents , raw_headlines = tag_and_collect ( cleaned_contents , id_tag = not github , back_links = back_to_top , exclude_h = exclude_h , remove_dashes = remove_da... |
def email_action_view ( self , id , action ) :
"""Perform action ' action ' on UserEmail object ' id '""" | # Retrieve UserEmail by id
user_email = self . db_manager . get_user_email_by_id ( id = id )
# Users may only change their own UserEmails
if not user_email or user_email . user_id != current_user . id :
return self . unauthorized_view ( )
# Delete UserEmail
if action == 'delete' : # Primary UserEmail can not be del... |
def announce ( self , discovery ) :
"""With the passed in Discovery class , attempt to announce to the host agent .""" | try :
url = self . __discovery_url ( )
logger . debug ( "making announce request to %s" % ( url ) )
response = None
response = self . client . put ( url , data = self . to_json ( discovery ) , headers = { "Content-Type" : "application/json" } , timeout = 0.8 )
if response . status_code is 200 :
... |
def get_bins ( self ) :
"""Gets the bin list resulting from the search .
return : ( osid . resource . BinList ) - the bin list
raise : IllegalState - list already retrieved
* compliance : mandatory - - This method must be implemented . *""" | if self . retrieved :
raise errors . IllegalState ( 'List has already been retrieved.' )
self . retrieved = True
return objects . BinList ( self . _results , runtime = self . _runtime ) |
def init_notification ( self , playingsong ) :
'''第一次桌面通知时加入图片''' | logger . debug ( 'init_notification' )
old_title = playingsong [ 'title' ]
self . cover_file = tempfile . NamedTemporaryFile ( suffix = '.jpg' , dir = self . _tempdir )
if not self . get_pic ( playingsong , self . cover_file . name ) :
return
title = playingsong [ 'title' ]
if old_title != title : # 已切换至下一首歌
re... |
def render ( self , ** kwargs ) :
"""Plots the curve and the control points polygon .""" | # Calling parent function
super ( VisCurve2D , self ) . render ( ** kwargs )
# Initialize variables
plot_data = [ ]
for plot in self . _plots :
pts = np . array ( plot [ 'ptsarr' ] , dtype = self . vconf . dtype )
# Plot control points
if plot [ 'type' ] == 'ctrlpts' and self . vconf . display_ctrlpts :
... |
def _decode ( data ) :
"""Decode the base - 64 encoded string
: param data :
: return : decoded data""" | if not isinstance ( data , bytes_types ) :
data = six . b ( str ( data ) )
return base64 . b64decode ( data . decode ( "utf-8" ) ) |
def price ( self , from_ = None , ** kwargs ) :
"""Check pricing for a new outbound message .
An useful synonym for " message " command with " dummy " parameters set to true .
: Example :
message = client . messages . price ( from _ = " 447624800500 " , phones = " 999000001 " , text = " Hello ! " , lists = " ... | if from_ :
kwargs [ "from" ] = from_
uri = "%s/%s" % ( self . uri , "price" )
response , instance = self . request ( "GET" , uri , params = kwargs )
return instance |
def connect_callbacks ( self , callbacks_bag ) :
"""Connect callbacks specified in callbacks _ bag with callbacks
defined in the ui definition .
Return a list with the name of the callbacks not connected .""" | notconnected = [ ]
for wname , builderobj in self . objects . items ( ) :
missing = builderobj . connect_commands ( callbacks_bag )
if missing is not None :
notconnected . extend ( missing )
missing = builderobj . connect_bindings ( callbacks_bag )
if missing is not None :
notconnected .... |
def get_data_pct ( self , xpct , ypct ) :
"""Calculate new data size for the given axis ratios .
See : meth : ` get _ limits ` .
Parameters
xpct , ypct : float
Ratio for X and Y , respectively , where 1 is 100 % .
Returns
x , y : int
Scaled dimensions .""" | xy_mn , xy_mx = self . get_limits ( )
width = abs ( xy_mx [ 0 ] - xy_mn [ 0 ] )
height = abs ( xy_mx [ 1 ] - xy_mn [ 1 ] )
x , y = int ( float ( xpct ) * width ) , int ( float ( ypct ) * height )
return ( x , y ) |
def add_metadata ( self , observation , info , available_at = None ) :
"""Extract metadata from a pixel observation and add it to the info""" | observation = observation [ 'vision' ]
if observation is None :
return
if self . network is not None and not self . network . active ( ) :
return
elif self . metadata_decoder is None :
return
elif observation is None :
return
# should return a dict with now / probe _ received _ at keys
with pyprofile . ... |
def rest_post ( self , url , params = None , headers = None , auth = None , verify = True , cert = None ) :
"""Perform a PUT request to url with optional authentication""" | res = requests . post ( url , params = params , headers = headers , auth = auth , verify = verify , cert = cert )
return res . text , res . status_code |
def _filter ( request , object_ , tags = None , more = False , orderby = 'created' ) :
"""Filters Piece objects from self based on filters , search , and range
: param tags : List of tag IDs to filter
: type tags : list
: param more - - bool , Returns more of the same filtered set of images based on session r... | res = Result ( )
models = QUERY_MODELS
idDict = { }
objDict = { }
data = { }
modelmap = { }
length = 75
# - - Get all IDs for each model
for m in models :
modelmap [ m . model_class ( ) ] = m . model
if object_ :
idDict [ m . model ] = m . model_class ( ) . objects . filter ( gallery = object_ )
els... |
def make_filter ( ** tests ) :
"""Create a filter from keyword arguments .""" | tests = [ AttrTest ( k , v ) for k , v in tests . items ( ) ]
return Filter ( tests ) |
def instance_of ( klass , arg ) :
"""Require that a value has a particular Python type .""" | if not isinstance ( arg , klass ) :
raise com . IbisTypeError ( 'Given argument with type {} is not an instance of {}' . format ( type ( arg ) , klass ) )
return arg |
def createOptimizer ( self , model ) :
"""Create a new instance of the optimizer""" | return torch . optim . SGD ( model . parameters ( ) , lr = self . lr , momentum = self . momentum , weight_decay = self . weight_decay ) |
def connection_made ( self ) :
"""Protocols connection established handler""" | LOG . info ( 'Connection to peer: %s established' , self . _neigh_conf . ip_address , extra = { 'resource_name' : self . _neigh_conf . name , 'resource_id' : self . _neigh_conf . id } ) |
def ida_connect ( host = 'localhost' , port = 18861 , retry = 10 ) :
"""Connect to an instance of IDA running our server . py .
: param host : The host to connect to
: param port : The port to connect to
: param retry : How many times to try after errors before giving up""" | for i in range ( retry ) :
try :
LOG . debug ( 'Connectint to %s:%d, try %d...' , host , port , i + 1 )
link = rpyc_classic . connect ( host , port )
link . eval ( '2 + 2' )
except socket . error :
time . sleep ( 1 )
continue
else :
LOG . debug ( 'Connected to... |
def get_image_path ( definition ) :
"""Helper to get path of image from a definition in resource directory .
: param definition : A definition ( hazard , exposure ) .
: type definition : dict
: returns : The definition ' s image path .
: rtype : str""" | path = resources_path ( 'img' , 'wizard' , 'keyword-subcategory-%s.svg' % definition [ 'key' ] )
if os . path . exists ( path ) :
return path
else :
return not_set_image_path |
def __add_recent_file ( self , fname ) :
"""Add to recent file list""" | if fname is None :
return
if fname in self . recent_files :
self . recent_files . remove ( fname )
self . recent_files . insert ( 0 , fname )
if len ( self . recent_files ) > self . get_option ( 'max_recent_files' ) :
self . recent_files . pop ( - 1 ) |
def kernel_pixelsize_change ( kernel , deltaPix_in , deltaPix_out ) :
"""change the pixel size of a given kernel
: param kernel :
: param deltaPix _ in :
: param deltaPix _ out :
: return :""" | numPix = len ( kernel )
numPix_new = int ( round ( numPix * deltaPix_in / deltaPix_out ) )
if numPix_new % 2 == 0 :
numPix_new -= 1
x_in = np . linspace ( - ( numPix - 1 ) / 2 * deltaPix_in , ( numPix - 1 ) / 2 * deltaPix_in , numPix )
x_out = np . linspace ( - ( numPix_new - 1 ) / 2 * deltaPix_out , ( numPix_new -... |
def set_defaults ( lvm_data ) :
"""dict : Sets all existing null string values to None .""" | for l in lvm_data :
for k , v in lvm_data [ l ] . items ( ) :
if v == '' :
lvm_data [ l ] [ k ] = None
return lvm_data |
def sample_stats_prior_to_xarray ( self ) :
"""Extract sample _ stats _ prior from prior .""" | prior = self . prior
data = get_sample_stats ( prior )
return dict_to_dataset ( data , library = self . pystan , coords = self . coords , dims = self . dims ) |
def id_name ( label , namespace = None ) :
"""Given a name and a namespace , resolves
returns the name as namespace + ' . ' + name . If namespace
is none , the current NAMESPACE is used""" | if not label . startswith ( DOT ) :
if namespace is None :
namespace = NAMESPACE
ex_label = namespace + label
# The mangled namespace . labelname label
else :
if namespace is None :
namespace = GLOBAL_NAMESPACE
# Global namespace
ex_label = label
return ex_label , namespace |
def sync ( ) :
"""Copy host - > device only if changed
: return : result of _ exec _ command ( ) execution""" | adb_full_cmd = [ v . ADB_COMMAND_PREFIX , v . ADB_COMMAND_SHELL , v . ADB_COMMAND_SYNC ]
return _exec_command ( adb_full_cmd ) |
def random_mini_batches ( X , Y , minibatch_size , seed = None ) :
"""Compute a list of minibatches from inputs X and targets Y .
A datapoint is expected to be represented as a column in
the data matrices X and Y .""" | d = X . shape [ 1 ]
size = minibatch_size
minibatches = [ ]
if Y is None :
Y = np . zeros ( ( 1 , d ) )
np . random . seed ( seed )
perm = np . random . permutation ( d )
for t in range ( 0 , d , size ) :
subset = perm [ t : t + size ]
minibatches . append ( ( X [ : , subset ] , Y [ : , subset ] ) )
return ... |
def create_item_returning_id ( self , api ) :
"""Create this item in the D4S2 service .
: param api : D4S2Api object who communicates with D4S2 server .
: return str newly created id for this item""" | resp = api . create_item ( self )
item = resp . json ( )
return item [ 'id' ] |
def files_mv ( self , source , dest , ** kwargs ) :
"""Moves files and directories within the MFS .
. . code - block : : python
> > > c . files _ mv ( " / test / file " , " / bla / file " )
Parameters
source : str
Existing filepath within the MFS
dest : str
Destination to which the file will be moved ... | args = ( source , dest )
return self . _client . request ( '/files/mv' , args , ** kwargs ) |
def txt_line_iterator ( txt_path ) :
"""Iterate through lines of file .""" | with tf . gfile . Open ( txt_path ) as f :
for line in f :
yield line . strip ( ) |
def get_label_at_address ( self , address , offset = None ) :
"""Creates a label from the given memory address .
If the address belongs to the module , the label is made relative to
it ' s base address .
@ type address : int
@ param address : Memory address .
@ type offset : None or int
@ param offset :... | # Add the offset to the address .
if offset :
address = address + offset
# Make the label relative to the base address if no match is found .
module = self . get_name ( )
function = None
offset = address - self . get_base ( )
# Make the label relative to the entrypoint if no other match is found .
# Skip if the ent... |
def _isnull ( expr ) :
"""Return a sequence or scalar according to the input indicating if the values are null .
: param expr : sequence or scalar
: return : sequence or scalar""" | if isinstance ( expr , SequenceExpr ) :
return IsNull ( _input = expr , _data_type = types . boolean )
elif isinstance ( expr , Scalar ) :
return IsNull ( _input = expr , _value_type = types . boolean ) |
def setup_tempdir ( dir , models , wav , alphabet , lm_binary , trie , binaries ) :
r'''Copy models , libs and binary to a directory ( new one if dir is None )''' | if dir is None :
dir = tempfile . mkdtemp ( suffix = 'dsbench' )
sorted_models = all_files ( models = models )
if binaries is None :
maybe_download_binaries ( dir )
else :
print ( 'Using local binaries: %s' % ( binaries ) )
shutil . copy2 ( binaries , dir )
extract_native_client_tarball ( dir )
filename... |
def _data_update ( subjects , queue , run_flag ) :
"""Get data from backgound process and notify all subscribed observers with the new data""" | while run_flag . running :
while not queue . empty ( ) :
data = queue . get ( )
for subject in [ s for s in subjects if not s . is_disposed ] :
subject . on_next ( data )
time . sleep ( 0.1 ) |
def to_short_time_string ( self ) -> str :
"""Return the iso time string only""" | hour = self . time . hour
minute = self . time . minute
return f"{hour:02}:{minute:02}" |
def config ( name , config ) :
'''Ensure that the chronos job with the given name is present and is configured
to match the given config values .
: param name : The job name
: param config : The configuration to apply ( dict )
: return : A standard Salt changes dictionary''' | # setup return structure
ret = { 'name' : name , 'changes' : { } , 'result' : False , 'comment' : '' , }
# get existing config if job is present
existing_config = None
if __salt__ [ 'chronos.has_job' ] ( name ) :
existing_config = __salt__ [ 'chronos.job' ] ( name ) [ 'job' ]
# compare existing config with defined ... |
def create_for_collection_items ( item_type , hint ) :
"""Helper method for collection items
: param item _ type :
: return :""" | # this leads to infinite loops
# try :
# prt _ type = get _ pretty _ type _ str ( item _ type )
# except :
# prt _ type = str ( item _ type )
return TypeInformationRequiredError ( "Cannot parse object of type {t} as a collection: this type has no valid " "PEP484 type hint about its contents: found {h}. Please use a sta... |
def stack ( args ) :
"""% prog stack fastafile
Create landscape plots that show the amounts of genic sequences , and repetitive
sequences along the chromosomes .""" | p = OptionParser ( stack . __doc__ )
p . add_option ( "--top" , default = 10 , type = "int" , help = "Draw the first N chromosomes [default: %default]" )
p . add_option ( "--stacks" , default = "Exons,Introns,DNA_transposons,Retrotransposons" , help = "Features to plot in stackplot [default: %default]" )
p . add_option... |
def wait_for_single_device ( self , timeout = None , interval = 0.5 ) :
"""Waits until a Myo is was paired * * and * * connected with the Hub and returns
it . If the * timeout * is exceeded , returns None . This function will not
return a Myo that is only paired but not connected .
# Parameters
timeout : Th... | timer = TimeoutManager ( timeout )
with self . _cond : # As long as there are no Myo ' s connected , wait until we
# get notified about a change .
while not timer . check ( ) : # Check if we found a Myo that is connected .
for device in self . _devices . values ( ) :
if device . connected :
... |
def cigar_array ( self ) :
"""cache this one to speed things up a bit""" | if self . _cigar :
return self . _cigar
self . _cigar = [ CIGARDatum ( int ( m [ 0 ] ) , m [ 1 ] ) for m in re . findall ( '([0-9]+)([MIDNSHP=X]+)' , self . entries . cigar ) ]
return self . _cigar |
def get_sql_statement_with_environment ( item , args = None ) :
"""Given a SQLStatement , string or module plus command line args or a dictionary ,
return a SqlStatement and final dictionary for variable resolution .
Args :
item : a SqlStatement , % % sql module , or string containing a query .
args : a str... | if isinstance ( item , basestring ) :
item = _sql_statement . SqlStatement ( item )
elif not isinstance ( item , _sql_statement . SqlStatement ) :
item = SqlModule . get_default_query_from_module ( item )
if not item :
raise Exception ( 'Expected a SQL statement or module but got %s' % str ( item ) ... |
def argument_parser ( version = None ) :
"""Create the argument parser for ncbi - genome - download .""" | parser = argparse . ArgumentParser ( )
parser . add_argument ( 'group' , default = NgdConfig . get_default ( 'group' ) , help = 'The NCBI taxonomic group to download (default: %(default)s). ' 'A comma-separated list of taxonomic groups is also possible. For example: "bacteria,viral"' 'Choose from: {choices}' . format (... |
def output ( stream ) :
"""Write the contents of the given stream to stdout .""" | while True :
content = stream . read ( 1024 )
if len ( content ) == 0 :
break
sys . stdout . write ( content ) |
def children ( self ) :
"""Returns list of children changesets .""" | return [ self . repository . get_changeset ( child . rev ( ) ) for child in self . _ctx . children ( ) if child . rev ( ) >= 0 ] |
def entrypoint ( args = None ) :
"""Main callable for " bonobo " entrypoint .
Will load commands from " bonobo . commands " entrypoints , using stevedore .""" | mondrian . setup ( excepthook = True )
logger = logging . getLogger ( )
logger . setLevel ( settings . LOGGING_LEVEL . get ( ) )
parser = argparse . ArgumentParser ( )
parser . add_argument ( "--debug" , "-D" , action = "store_true" )
subparsers = parser . add_subparsers ( dest = "command" )
subparsers . required = Tru... |
def db_exists ( name , user = None , host = None , port = None , maintenance_db = None , password = None , runas = None ) :
'''Checks if a database exists on the Postgres server .
CLI Example :
. . code - block : : bash
salt ' * ' postgres . db _ exists ' dbname ' ''' | databases = db_list ( user = user , host = host , port = port , maintenance_db = maintenance_db , password = password , runas = runas )
return name in databases |
def pandoc_process ( app , what , name , obj , options , lines ) :
"""" Convert docstrings in Markdown into reStructureText using pandoc""" | if not lines :
return None
input_format = app . config . mkdsupport_use_parser
output_format = 'rst'
# Since default encoding for sphinx . ext . autodoc is unicode and pypandoc . convert _ text , which will always return a
# unicode string , expects unicode or utf - 8 encodes string , there is on need for dealing w... |
def read ( self , filename ) :
"""Read detector from a file , must be HDF5 format .
Reads a Detector object from an HDF5 file , usually created by eqcorrscan .
: type filename : str
: param filename : Filename to save the detector to .""" | f = h5py . File ( filename , "r" )
self . data = [ ]
for i in range ( f [ 'data' ] . attrs [ 'length' ] ) :
self . data . append ( f [ 'data' ] [ 'data_' + str ( i ) ] . value )
self . u = [ ]
for i in range ( f [ 'u' ] . attrs [ 'length' ] ) :
self . u . append ( f [ 'u' ] [ 'u_' + str ( i ) ] . value )
self .... |
def init_app ( self , app ) : # type : ( Flask ) - > None
"""Init the Flask - MQTT addon .""" | self . client_id = app . config . get ( "MQTT_CLIENT_ID" , "" )
if isinstance ( self . client_id , unicode ) :
self . client . _client_id = self . client_id . encode ( 'utf-8' )
else :
self . client . _client_id = self . client_id
self . client . _transport = app . config . get ( "MQTT_TRANSPORT" , "tcp" ) . lo... |
def append ( self , resultFile , resultElem , all_columns = False ) :
"""Append the result for one run . Needs to be called before collect _ data ( ) .""" | self . _xml_results += [ ( result , resultFile ) for result in _get_run_tags_from_xml ( resultElem ) ]
for attrib , values in RunSetResult . _extract_attributes_from_result ( resultFile , resultElem ) . items ( ) :
self . attributes [ attrib ] . extend ( values )
if not self . columns :
self . columns = RunSetR... |
def get_instance ( self , payload ) :
"""Build an instance of ThisMonthInstance
: param dict payload : Payload response from the API
: returns : twilio . rest . api . v2010 . account . usage . record . this _ month . ThisMonthInstance
: rtype : twilio . rest . api . v2010 . account . usage . record . this _ m... | return ThisMonthInstance ( self . _version , payload , account_sid = self . _solution [ 'account_sid' ] , ) |
def MAP_ADD ( self , instr ) :
key = self . ast_stack . pop ( )
value = self . ast_stack . pop ( )
self . ast_stack . append ( ( key , value ) )
'NOP' | |
def _to_dict ( self ) :
"""Return a json dictionary representing this model .""" | _dict = { }
if hasattr ( self , 'concepts' ) and self . concepts is not None :
_dict [ 'concepts' ] = self . concepts . _to_dict ( )
if hasattr ( self , 'emotion' ) and self . emotion is not None :
_dict [ 'emotion' ] = self . emotion . _to_dict ( )
if hasattr ( self , 'entities' ) and self . entities is not No... |
def main ( ) :
"Process CLI arguments and call appropriate functions ." | try :
args = docopt . docopt ( __doc__ , version = __about__ . __version__ )
except docopt . DocoptExit :
if len ( sys . argv ) > 1 :
print ( f"{Fore.RED}Invalid command syntax, " f"check help:{Fore.RESET}\n" )
print ( __doc__ )
sys . exit ( 1 )
print_all = False
if not ( args [ "--int-width" ] ... |
def is_single_file_metadata_valid ( file_metadata , project_member_id , filename ) :
"""Check if metadata fields like project member id , description , tags , md5 and
creation date are valid for a single file .
: param file _ metadata : This field is metadata of file .
: param project _ member _ id : This fie... | if project_member_id is not None :
if not project_member_id . isdigit ( ) or len ( project_member_id ) != 8 :
raise ValueError ( 'Error: for project member id: ' , project_member_id , ' and filename: ' , filename , ' project member id must be of 8 digits from 0 to 9' )
if 'description' not in file_metadata ... |
def public_keys ( self ) :
"""Return a list of SSH public keys ( in textual format ) .""" | if not self . public_keys_cache :
conn = self . conn_factory ( )
self . public_keys_cache = conn . export_public_keys ( self . identities )
return self . public_keys_cache |
def attention_lm_moe_small ( ) :
"""Cheap model for single - gpu training .
on lm1b _ 32k :
~ 312M params
1.6 steps / sec on [ GeForce GTX TITAN X ]
After 50K steps on 8 GPUs ( synchronous ) :
eval _ log _ ppl _ per _ token = 3.31
Returns :
an hparams object .""" | hparams = attention_lm_moe_base ( )
hparams . num_hidden_layers = 4
hparams . hidden_size = 512
hparams . filter_size = 2048
hparams . moe_num_experts = 128
hparams . moe_layers = "2"
return hparams |
def get_hist ( self , observable : Any , ** kwargs : Dict [ str , Any ] ) -> Any :
"""Get the histogram that may be stored in some object .
This histogram is used to project from .
Note :
The output object could just be the raw ROOT histogram .
Note :
This function is just a basic placeholder and likely s... | return observable |
def lookup ( cls , name ) :
"""Try to find field C { name } .
@ return : Field descriptions , see C { matching . ConditionParser } for details .""" | try :
field = cls . FIELDS [ name ]
except KeyError : # Is it a custom attribute ?
field = TorrentProxy . add_manifold_attribute ( name )
return { "matcher" : field . _matcher } if field else None |
def _add_to_quick_menu ( self , key , wf ) :
"""Appends menu entries to dashboard quickmenu according
to : attr : ` zengine . settings . QUICK _ MENU `
Args :
key : workflow name
wf : workflow menu entry""" | if key in settings . QUICK_MENU :
self . output [ 'quick_menu' ] . append ( wf ) |
def ls ( name , path ) :
"""List files in a path of a virtual folder .
NAME : Name of a virtual folder .
PATH : Path inside vfolder .""" | with Session ( ) as session :
try :
print_wait ( 'Retrieving list of files in "{}"...' . format ( path ) )
result = session . VFolder ( name ) . list_files ( path )
if 'error_msg' in result and result [ 'error_msg' ] :
print_fail ( result [ 'error_msg' ] )
return
... |
def get_page ( self , page_id ) :
"""Get short page info and body html code""" | try :
result = self . _request ( '/getpage/' , { 'pageid' : page_id } )
return TildaPage ( ** result )
except NetworkError :
return [ ] |
def usearch61_smallmem_cluster ( intermediate_fasta , percent_id = 0.97 , minlen = 64 , rev = False , output_dir = "." , remove_usearch_logs = False , wordlength = 8 , usearch61_maxrejects = 32 , usearch61_maxaccepts = 1 , sizeorder = False , HALT_EXEC = False , output_uc_filepath = None , log_name = "smallmem_clustere... | log_filepath = join ( output_dir , log_name )
params = { '--minseqlength' : minlen , '--cluster_smallmem' : intermediate_fasta , '--id' : percent_id , '--uc' : output_uc_filepath , '--wordlength' : wordlength , '--maxrejects' : usearch61_maxrejects , '--maxaccepts' : usearch61_maxaccepts , '--usersort' : True }
if size... |
def apply_trapping ( self , outlets ) :
"""Apply trapping based on algorithm described by Y . Masson [ 1 ] .
It is applied as a post - process and runs the percolation algorithm in
reverse assessing the occupancy of pore neighbors . Consider the
following scenario when running standard IP without trapping ,
... | # First see if network is fully invaded
net = self . project . network
invaded_ps = self [ 'pore.invasion_sequence' ] > - 1
if ~ np . all ( invaded_ps ) : # Put defending phase into clusters
clusters = net . find_clusters2 ( ~ invaded_ps )
# Identify clusters that are connected to an outlet and set to - 2
#... |
def _phi ( p ) : # this function is faster than using scipy . stats . norm . isf ( p )
# but the permissity of the license isn ' t explicitly listed .
# using scipy . stats . norm . isf ( p ) is an acceptable alternative
"""Modified from the author ' s original perl code ( original comments follow below )
by dfie... | if p <= 0 or p >= 1 : # The original perl code exits here , we ' ll throw an exception instead
raise ValueError ( "Argument to ltqnorm %f must be in open interval (0,1)" % p )
# Coefficients in rational approximations .
a = ( - 3.969683028665376e+01 , 2.209460984245205e+02 , - 2.759285104469687e+02 , 1.383577518672... |
def set_system_conf ( self , key = None , value = None , d = None ) :
"""Sets a java system property as a ( ' key ' , ' value ' ) pair of using a dictionary
{ ' key ' : ' value ' , . . . }
: param key : string
: param value : string
: param d : dictionary
: return : None""" | if isinstance ( d , dict ) :
self . _system . update ( d )
elif isinstance ( key , str ) and isinstance ( value , str ) :
self . _system [ key ] = value
else :
raise TypeError ( "key, value must be strings" ) |
def hexstr_if_str ( to_type , hexstr_or_primitive ) :
"""Convert to a type , assuming that strings can be only hexstr ( not unicode text )
@ param to _ type is a function that takes the arguments ( primitive , hexstr = hexstr , text = text ) ,
eg ~ to _ bytes , to _ text , to _ hex , to _ int , etc
@ param te... | if isinstance ( hexstr_or_primitive , str ) :
( primitive , hexstr ) = ( None , hexstr_or_primitive )
if remove_0x_prefix ( hexstr ) and not is_hex ( hexstr ) :
raise ValueError ( "when sending a str, it must be a hex string. Got: {0!r}" . format ( hexstr_or_primitive , ) )
else :
( primitive , hexs... |
def read_ecmwf_macc ( filename , latitude , longitude , utc_time_range = None ) :
"""Read data from ECMWF MACC reanalysis netCDF4 file .
Parameters
filename : string
full path to netCDF4 data file .
latitude : float
latitude in degrees
longitude : float
longitude in degrees
utc _ time _ range : sequ... | ecmwf_macc = ECMWF_MACC ( filename )
try :
ilat , ilon = ecmwf_macc . get_nearest_indices ( latitude , longitude )
nctime = ecmwf_macc . data [ 'time' ]
if utc_time_range :
start_idx = netCDF4 . date2index ( utc_time_range [ 0 ] , nctime , select = 'before' )
stop_idx = netCDF4 . date2index ... |
def metric_update ( self , project , metric_name , filter_ , description ) :
"""API call : update a metric resource .
: type project : str
: param project : ID of the project containing the metric .
: type metric _ name : str
: param metric _ name : the name of the metric
: type filter _ : str
: param f... | path = "projects/%s/metrics/%s" % ( project , metric_name )
metric_pb = LogMetric ( name = path , filter = filter_ , description = description )
metric_pb = self . _gapic_api . update_log_metric ( path , metric_pb )
# NOTE : LogMetric message type does not have an ` ` Any ` ` field
# so ` MessageToDict ` ` can safely b... |
def create_record_ptr ( self , record , data , ttl = 60 ) :
"""Create a reverse record .
: param record : the public ip address of device for which you would like to manage reverse DNS .
: param data : the record ' s value
: param integer ttl : the TTL or time - to - live value ( default : 60)""" | resource_record = self . _generate_create_dict ( record , 'PTR' , data , ttl )
return self . record . createObject ( resource_record ) |
def _locate_repo_files ( repo , rewrite = False ) :
'''Find what file a repo is called in .
Helper function for add _ repo ( ) and del _ repo ( )
repo
url of the repo to locate ( persistent ) .
rewrite
Whether to remove matching repository settings during this process .
Returns a list of absolute paths ... | ret_val = [ ]
files = [ ]
conf_dirs = [ '/etc/xbps.d/' , '/usr/share/xbps.d/' ]
name_glob = '*.conf'
# Matches a line where first printing is " repository " and there is an equals
# sign before the repo , an optional forwardslash at the end of the repo name ,
# and it ' s possible for there to be a comment after reposi... |
def execute_migration ( self , migration_file_relative ) :
"""This recognizes migration type and executes either
: method : ` execute _ python _ migration ` or : method : ` execute _ native _ migration `""" | migration_file = os . path . join ( self . db_config [ 'migrations_dir' ] , migration_file_relative )
m_type = self . repository . migration_type ( migration_file )
if m_type == 'native' :
return self . execute_native_migration ( migration_file )
if m_type == 'py' :
module = imp . load_source ( 'migration_modul... |
def main ( ) :
"""Setup . py entry point .""" | import codecs
setuptools . setup ( name = 'wcwidth' , version = '0.1.7' , description = ( "Measures number of Terminal column cells " "of wide-character codes" ) , long_description = codecs . open ( os . path . join ( HERE , 'README.rst' ) , 'r' , 'utf8' ) . read ( ) , author = 'Jeff Quast' , author_email = 'contact@je... |
def cart_add ( self , items , CartId = None , HMAC = None , ** kwargs ) :
"""CartAdd .
: param items :
A dictionary containing the items to be added to the cart .
Or a list containing these dictionaries .
It is not possible to create an empty cart !
example : [ { ' offer _ id ' : ' rt2ofih3f389nwiuhf8934z... | if not CartId or not HMAC :
raise CartException ( 'CartId and HMAC required for CartAdd call' )
if isinstance ( items , dict ) :
items = [ items ]
if len ( items ) > 10 :
raise CartException ( "You can't add more than 10 items at once" )
offer_id_key_template = 'Item.{0}.OfferListingId'
quantity_key_templat... |
def _identify_heterogeneity_blocks_hmm ( in_file , params , work_dir , somatic_info ) :
"""Use a HMM to identify blocks of heterogeneity to use for calculating allele frequencies .
The goal is to subset the genome to a more reasonable section that contains potential
loss of heterogeneity or other allele frequen... | def _segment_by_hmm ( chrom , freqs , coords ) :
cur_coords = [ ]
for j , state in enumerate ( _predict_states ( freqs ) ) :
if state == 0 : # heterozygote region
if len ( cur_coords ) == 0 :
num_misses = 0
cur_coords . append ( coords [ j ] )
else :
... |
def get_os ( detailed = False ) :
"""Summary :
Retrieve local operating system environment characteristics
Args :
: user ( str ) : USERNAME , only required when run on windows os
Returns :
TYPE : dict object containing key , value pairs describing
os information""" | try :
os_type = platform . system ( )
if os_type == 'Linux' :
os_detail = platform . uname ( )
distribution = platform . linux_distribution ( )
HOME = os . environ [ 'HOME' ]
username = os . getenv ( 'USER' )
elif os_type == 'Windows' :
username = os . getenv ( 'usern... |
def activate ( self , experiment_key , user_id , attributes = None ) :
"""Buckets visitor and sends impression event to Optimizely .
Args :
experiment _ key : Experiment which needs to be activated .
user _ id : ID for user .
attributes : Dict representing user attributes and values which need to be recorde... | if not self . is_valid :
self . logger . error ( enums . Errors . INVALID_DATAFILE . format ( 'activate' ) )
return None
if not validator . is_non_empty_string ( experiment_key ) :
self . logger . error ( enums . Errors . INVALID_INPUT_ERROR . format ( 'experiment_key' ) )
return None
if not isinstance ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.