signature stringlengths 29 44.1k | implementation stringlengths 0 85.2k |
|---|---|
def blastparser ( self , report , sample ) :
"""Parse the blast results , and store necessary data in dictionaries in sample object
: param report : Name of the blast output report being parsed
: param sample : sample object""" | # Open the sequence profile file as a dictionary
blastdict = DictReader ( open ( report ) , fieldnames = self . fieldnames , dialect = 'excel-tab' )
resultdict = dict ( )
# Initialise a dictionary to store all the target sequences
sample [ self . analysistype ] . targetsequence = dict ( )
# Go through each BLAST result... |
def __field_to_parameter_type_and_format ( self , field ) :
"""Converts the field variant type into a tuple describing the parameter .
Args :
field : An instance of a subclass of messages . Field .
Returns :
A tuple with the type and format of the field , respectively .
Raises :
TypeError : if the field... | # We use lowercase values for types ( e . g . ' string ' instead of ' STRING ' ) .
variant = field . variant
if variant == messages . Variant . MESSAGE :
raise TypeError ( 'A message variant cannot be used in a parameter.' )
# Note that the 64 - bit integers are marked as strings - - this is to
# accommodate JavaSc... |
def reversed_dotted_parts ( s ) :
"""For a string " a . b . c " , yields " a . b . c " , " a . b " , " a " .""" | idx = - 1
if s :
yield s
while s :
idx = s . rfind ( '.' , 0 , idx )
if idx == - 1 :
break
yield s [ : idx ] |
def initialize ( self , symbolic_vm : LaserEVM ) :
"""Initializes the BenchmarkPlugin
Introduces hooks in symbolic _ vm to track the desired values
: param symbolic _ vm : Symbolic virtual machine to analyze""" | self . _reset ( )
@ symbolic_vm . laser_hook ( "execute_state" )
def execute_state_hook ( _ ) :
current_time = time ( ) - self . begin
self . nr_of_executed_insns += 1
for key , value in symbolic_vm . coverage . items ( ) :
try :
self . coverage [ key ] [ current_time ] = sum ( value [ 1... |
def ensure_time_avg_has_cf_metadata ( ds ) :
"""Add time interval length and bounds coordinates for time avg data .
If the Dataset or DataArray contains time average data , enforce
that there are coordinates that track the lower and upper bounds of
the time intervals , and that there is a coordinate that trac... | # noqa : E501
if TIME_WEIGHTS_STR not in ds :
time_weights = ds [ TIME_BOUNDS_STR ] . diff ( BOUNDS_STR )
time_weights = time_weights . rename ( TIME_WEIGHTS_STR ) . squeeze ( )
if BOUNDS_STR in time_weights . coords :
time_weights = time_weights . drop ( BOUNDS_STR )
ds [ TIME_WEIGHTS_STR ] = t... |
def add_all ( self , bucket , quiet = False ) :
"""Ensures the query result is consistent with all prior
mutations performed by a given bucket .
Using this function is equivalent to keeping track of all
mutations performed by the given bucket , and passing them to
: meth : ` ~ add _ result `
: param bucke... | added = False
for mt in bucket . _mutinfo ( ) :
added = True
self . _add_scanvec ( mt )
if not added and not quiet :
raise MissingTokenError ( 'Bucket object contains no tokens!' )
return added |
def createCashContract ( self , symbol , currency = "USD" , exchange = "IDEALPRO" ) :
"""Used for FX , etc :
createCashContract ( " EUR " , currency = " USD " )""" | contract_tuple = ( symbol , "CASH" , exchange , currency , "" , 0.0 , "" )
contract = self . createContract ( contract_tuple )
return contract |
def _upload_part ( api , session , url , upload , part_number , part , retry_count , timeout ) :
"""Used by the worker to upload a part to the storage service .
: param api : Api instance .
: param session : Storage service session .
: param url : Part url .
: param upload : Upload identifier .
: param pa... | part_url = retry ( retry_count ) ( _get_part_url ) ( api , url , upload , part_number )
e_tag = retry ( retry_count ) ( _submit_part ) ( session , part_url , part , timeout )
retry ( retry_count ) ( _report_part ) ( api , url , upload , part_number , e_tag ) |
def setSize ( self , size , sizeIsEstimated ) :
"""Update size .""" | self . _size = size
self . _sizeIsEstimated = sizeIsEstimated
if self . fromVol is not None and size is not None and not sizeIsEstimated :
Diff . theKnownSizes [ self . toUUID ] [ self . fromUUID ] = size |
def create ( self , component_context , overriding_args ) :
"""Creates a new instance of the component , respecting the scope .
: param component _ context : The context to resolve dependencies from .
: param overriding _ args : Overriding arguments to use ( by name ) instead of resolving them .
: return : An... | return self . component_scope . instance ( lambda : self . _create ( component_context , overriding_args ) ) |
def form_adverb_from_adjective ( adjective ) :
"""Forms an adverb from the input adjective , f . ex . " happy " = > " happily " .
Adverbs are generated using rules from : http : / / www . edufind . com / english - grammar / forming - adverbs - adjectives /
: param adjective : adjective
: return : adverb form ... | # If the adjective ends in - able , - ible , or - le , replace the - e with - y
if adjective . endswith ( "able" ) or adjective . endswith ( "ible" ) or adjective . endswith ( "le" ) :
return adjective [ : - 1 ] + "y"
# If the adjective ends in - y , replace the y with i and add - ly
elif adjective . endswith ( "y"... |
def remove_component ( self , entity , component_type ) :
"""Remove the component of component _ type from entity .
Long - hand for : func : ` essence . Entity . remove ` .
: param entity : entity to associate
: type entity : : class : ` essence . Entity `
: param component _ type : Type of component
: ty... | relation = self . _get_relation ( component_type )
del relation [ entity ]
self . _entities_with ( component_type ) . remove ( entity ) |
def get_soup ( page = '' ) :
"""Returns a bs4 object of the page requested""" | content = requests . get ( '%s/%s' % ( BASE_URL , page ) ) . text
return BeautifulSoup ( content ) |
def _OpenFileObject ( self , path_spec ) :
"""Opens the file - like object defined by path specification .
Args :
path _ spec ( PathSpec ) : path specification .
Returns :
FileIO : a file - like object .
Raises :
PathSpecError : if the path specification is incorrect .""" | if not path_spec . HasParent ( ) :
raise errors . PathSpecError ( 'Unsupported path specification without parent.' )
resolver . Resolver . key_chain . ExtractCredentialsFromPathSpec ( path_spec )
file_object = resolver . Resolver . OpenFileObject ( path_spec . parent , resolver_context = self . _resolver_context )
... |
def server_receives_binary_from ( self , name = None , timeout = None , connection = None , label = None ) :
"""Receive raw binary message . Returns message , ip , and port .
If server ` name ` is not given , uses the latest server . Optional message
` label ` is shown on logs .
Examples :
| $ { binary } | ... | server , name = self . _servers . get_with_name ( name )
msg , ip , port = server . receive_from ( timeout = timeout , alias = connection )
self . _register_receive ( server , label , name , connection = connection )
return msg , ip , port |
def accept ( self , context ) :
"""Check if the context could be accepted by the oracle
Args :
context : s sequence same type as the oracle data
Returns :
bAccepted : whether the sequence is accepted or not
_ next : the state where the sequence is accepted""" | _next = 0
for _s in context :
_data = [ self . data [ j ] for j in self . trn [ _next ] ]
if _s in _data :
_next = self . trn [ _next ] [ _data . index ( _s ) ]
else :
return 0 , _next
return 1 , _next |
def open ( self ) :
"""Open a connection to the device .""" | device_type = 'cisco_ios'
if self . transport == 'telnet' :
device_type = 'cisco_ios_telnet'
self . device = ConnectHandler ( device_type = device_type , host = self . hostname , username = self . username , password = self . password , ** self . netmiko_optional_args )
# ensure in enable mode
self . device . enabl... |
def _surfdens ( self , R , z , phi = 0. , t = 0. ) :
"""NAME :
_ surfdens
PURPOSE :
evaluate the surface density for this potential
INPUT :
R - Galactocentric cylindrical radius
z - vertical height
phi - azimuth
t - time
OUTPUT :
the surface density
HISTORY :
2018-08-19 - Written - Bovy ( Uo... | return 2. * integrate . quad ( lambda x : self . _dens ( R , x , phi = phi , t = t ) , 0 , z ) [ 0 ] |
def delete_share ( self , share_name , fail_not_exist = False , timeout = None , snapshot = None , delete_snapshots = None ) :
'''Marks the specified share for deletion . If the share
does not exist , the operation fails on the service . By
default , the exception is swallowed by the client .
To expose the ex... | _validate_not_none ( 'share_name' , share_name )
request = HTTPRequest ( )
request . method = 'DELETE'
request . host_locations = self . _get_host_locations ( )
request . path = _get_path ( share_name )
request . headers = { 'x-ms-delete-snapshots' : _to_str ( delete_snapshots ) }
request . query = { 'restype' : 'share... |
def batch_length ( batch ) :
'''Determine the number of samples in a batch .
Parameters
batch : dict
A batch dictionary . Each value must implement ` len ` .
All values must have the same ` len ` .
Returns
n : int > = 0 or None
The number of samples in this batch .
If the batch has no fields , n is ... | n = None
for value in six . itervalues ( batch ) :
if n is None :
n = len ( value )
elif len ( value ) != n :
raise PescadorError ( 'Unequal field lengths' )
return n |
def string_to_data_time ( d ) :
'''simple parse date string , such as :
2016-5-27 21:22:20
2016-05-27 21:22:2
2016/05/27 21:22:2
2016-05-27
2016/5/27
21:22:2''' | if d :
d = d . replace ( '/' , '-' )
if ' ' in d :
_datetime = d . split ( ' ' )
if len ( _datetime ) == 2 :
_d = _string_to_date ( _datetime [ 0 ] )
_t = _string_to_time ( _datetime [ 1 ] )
return _combine_date_time ( _d , _t )
else : # no space
i... |
def get ( self , name , ** kwargs ) :
"""Get the variable given a name if one exists or create a new one if missing .
Parameters
name : str
name of the variable
* * kwargs :
more arguments that ' s passed to symbol . Variable""" | name = self . _prefix + name
if name not in self . _params :
self . _params [ name ] = symbol . Variable ( name , ** kwargs )
return self . _params [ name ] |
def _activate_texture ( mesh , name ) :
"""Grab a texture and update the active texture coordinates . This makes
sure to not destroy old texture coordinates
Parameters
name : str
The name of the texture and texture coordinates to activate
Return
vtk . vtkTexture : The active texture""" | if name == True or isinstance ( name , int ) :
keys = list ( mesh . textures . keys ( ) )
# Grab the first name availabe if True
idx = 0 if not isinstance ( name , int ) or name == True else name
if idx > len ( keys ) :
idx = 0
try :
name = keys [ idx ]
except IndexError :
... |
def atexit_register ( func ) :
"""Uses either uwsgi ' s atexit mechanism , or atexit from the stdlib .
When running under uwsgi , using their atexit handler is more reliable ,
especially when using gevent
: param func : the function to call at exit""" | try :
import uwsgi
orig = getattr ( uwsgi , "atexit" , None )
def uwsgi_atexit ( ) :
if callable ( orig ) :
orig ( )
func ( )
uwsgi . atexit = uwsgi_atexit
except ImportError :
atexit . register ( func ) |
def update_access_key ( self , access_key_id , status , user_name = None ) :
"""Changes the status of the specified access key from Active to Inactive
or vice versa . This action can be used to disable a user ' s key as
part of a key rotation workflow .
If the user _ name is not specified , the user _ name is... | params = { 'AccessKeyId' : access_key_id , 'Status' : status }
if user_name :
params [ 'UserName' ] = user_name
return self . get_response ( 'UpdateAccessKey' , params ) |
def _create_technical_words_dictionary ( spellchecker_cache_path , relative_path , user_words , shadow ) :
"""Create Dictionary at spellchecker _ cache _ path with technical words .""" | technical_terms_set = ( user_words | technical_words_from_shadow_contents ( shadow ) )
technical_words = Dictionary ( technical_terms_set , "technical_words_" + relative_path . replace ( os . path . sep , "_" ) , [ os . path . realpath ( relative_path ) ] , spellchecker_cache_path )
return technical_words |
def get_directory ( self , identifier ) :
"""Implements the policy for naming directories for image objects . Image
object directories are name by their identifier . In addition , these
directories are grouped in parent directories named by the first two
characters of the identifier . The aim is to avoid havi... | return os . path . join ( os . path . join ( self . directory , identifier [ : 2 ] ) , identifier ) |
def is_dirty ( self , index = True , working_tree = True , untracked_files = False , submodules = True , path = None ) :
""": return :
` ` True ` ` , the repository is considered dirty . By default it will react
like a git - status without untracked files , hence it is dirty if the
index or the working copy h... | if self . _bare : # Bare repositories with no associated working directory are
# always consired to be clean .
return False
# start from the one which is fastest to evaluate
default_args = [ '--abbrev=40' , '--full-index' , '--raw' ]
if not submodules :
default_args . append ( '--ignore-submodules' )
if path :
... |
def read_body ( self , request , response , file = None , raw = False ) :
'''Read the response ' s content body .
Coroutine .''' | if is_no_body ( request , response ) :
return
if not raw :
self . _setup_decompressor ( response )
read_strategy = self . get_read_strategy ( response )
if self . _ignore_length and read_strategy == 'length' :
read_strategy = 'close'
if read_strategy == 'chunked' :
yield from self . _read_body_by_chunk ... |
def _get_timestamp ( dirname_full , remove ) :
"""Get the timestamp from the timestamp file .
Optionally mark it for removal if we ' re going to write another one .""" | record_filename = os . path . join ( dirname_full , RECORD_FILENAME )
if not os . path . exists ( record_filename ) :
return None
mtime = os . stat ( record_filename ) . st_mtime
mtime_str = datetime . fromtimestamp ( mtime )
print ( 'Found timestamp {}:{}' . format ( dirname_full , mtime_str ) )
if Settings . reco... |
def squared_toroidal_dist ( p1 , p2 , world_size = ( 60 , 60 ) ) :
"""Separated out because sqrt has a lot of overhead""" | halfx = world_size [ 0 ] / 2.0
if world_size [ 0 ] == world_size [ 1 ] :
halfy = halfx
else :
halfy = world_size [ 1 ] / 2.0
deltax = p1 [ 0 ] - p2 [ 0 ]
if deltax < - halfx :
deltax += world_size [ 0 ]
elif deltax > halfx :
deltax -= world_size [ 0 ]
deltay = p1 [ 1 ] - p2 [ 1 ]
if deltay < - halfy :
... |
def force_utc ( time , name = 'field' , precision = 6 ) :
"""Appending ' Z ' to isoformatted time - explicit timezone is required for most APIs""" | if not isinstance ( time , datetime . datetime ) :
raise CloudValueError ( "%s should be of type datetime" % ( name , ) )
clip = 6 - precision
timestring = time . isoformat ( )
if clip :
timestring = timestring [ : - clip ]
return timestring + "Z" |
def getPrevUrl ( self , url , data ) :
"""Find previous URL .""" | prevUrl = None
if self . prevSearch :
try :
prevUrl = self . fetchUrl ( url , data , self . prevSearch )
except ValueError as msg : # assume there is no previous URL , but print a warning
out . warn ( u"%s Assuming no previous comic strips exist." % msg )
else :
prevUrl = self . prev... |
def execute ( self , command , * args , ** kw ) :
"""Executes redis command in a free connection and returns
future waiting for result .
Picks connection from free pool and send command through
that connection .
If no connection is found , returns coroutine waiting for
free connection to execute command .... | conn , address = self . get_connection ( command , args )
if conn is not None :
fut = conn . execute ( command , * args , ** kw )
return self . _check_result ( fut , command , args , kw )
else :
coro = self . _wait_execute ( address , command , args , kw )
return self . _check_result ( coro , command , ... |
def wrap_command ( cmds , data_dirs , cls , strict = True ) :
"""Wrap a setup command
Parameters
cmds : list ( str )
The names of the other commands to run prior to the command .
strict : boolean , optional
Wether to raise errors when a pre - command fails .""" | class WrappedCommand ( cls ) :
def run ( self ) :
if not getattr ( self , 'uninstall' , None ) :
try :
[ self . run_command ( cmd ) for cmd in cmds ]
except Exception :
if strict :
raise
else :
pa... |
def tokeniter ( self , source , name , filename = None , state = None ) :
"""This method tokenizes the text and returns the tokens in a
generator . Use this method if you just want to tokenize a template .""" | source = '\n' . join ( unicode ( source ) . splitlines ( ) )
pos = 0
lineno = 1
stack = [ 'root' ]
if state is not None and state != 'root' :
assert state in ( 'variable' , 'block' ) , 'invalid state'
stack . append ( state + '_begin' )
else :
state = 'root'
statetokens = self . rules [ stack [ - 1 ] ]
sour... |
def bdd_common_after_all ( context_or_world ) :
"""Common after all method in behave or lettuce
: param context _ or _ world : behave context or lettuce world""" | # Close drivers
DriverWrappersPool . close_drivers ( scope = 'session' , test_name = 'multiple_tests' , test_passed = context_or_world . global_status [ 'test_passed' ] )
# Update tests status in Jira
change_all_jira_status ( ) |
def getoptlist ( self , p ) :
"""Returns all option values stored that match p as a list .""" | optlist = [ ]
for k , v in self . pairs :
if k == p :
optlist . append ( v )
return optlist |
def output ( self , output , status = None ) :
"""Output text to stdout or a pager command .
The status text is not outputted to pager or files .
The message will be logged in the audit log , if enabled . The
message will be written to the tee file , if enabled . The
message will be written to the output fi... | if output :
size = self . cli . output . get_size ( )
margin = self . get_output_margin ( status )
fits = True
buf = [ ]
output_via_pager = self . explicit_pager and special . is_pager_enabled ( )
for i , line in enumerate ( output , 1 ) :
special . write_tee ( line )
special . w... |
def get_plugin_modules ( folders , package = 'plugins' , parentpackage = 'linkcheck.dummy' ) :
"""Get plugin modules for given folders .""" | for folder in folders :
for module in loader . get_folder_modules ( folder , parentpackage ) :
yield module
for module in loader . get_package_modules ( package ) :
yield module |
def pipeline ( self , source = None , phase = 'build' , ps = None ) :
"""Construct the ETL pipeline for all phases . Segments that are not used for the current phase
are filtered out later .
: param source : A source object , or a source string name
: return : an etl Pipeline""" | from ambry . etl . pipeline import Pipeline , PartitionWriter
from ambry . dbexceptions import ConfigurationError
if source :
source = self . source ( source ) if isinstance ( source , string_types ) else source
else :
source = None
sf , sp = self . source_pipe ( source , ps ) if source else ( None , None )
pl ... |
def minimize ( self , minimize ) :
'''Configures the ABC to minimize fitness function return value or
derived score
Args :
minimize ( bool ) : if True , minimizes fitness function return value ;
if False , minimizes derived score''' | self . _minimize = minimize
self . _logger . log ( 'debug' , 'Minimize set to {}' . format ( minimize ) ) |
def roc_auc_xlim ( x_bla , y_bla , xlim = 0.1 ) :
"""Computes the ROC Area Under Curve until a certain FPR value .
Parameters
fg _ vals : array _ like
list of values for positive set
bg _ vals : array _ like
list of values for negative set
xlim : float , optional
FPR value
Returns
score : float
... | x = x_bla [ : ]
y = y_bla [ : ]
x . sort ( )
y . sort ( )
u = { }
for i in x + y :
u [ i ] = 1
vals = sorted ( u . keys ( ) )
len_x = float ( len ( x ) )
len_y = float ( len ( y ) )
new_x = [ ]
new_y = [ ]
x_p = 0
y_p = 0
for val in vals [ : : - 1 ] :
while len ( x ) > 0 and x [ - 1 ] >= val :
x . pop (... |
def _subtract_timedelta ( self , delta ) :
"""Remove timedelta duration from the instance .
: param delta : The timedelta instance
: type delta : pendulum . Duration or datetime . timedelta
: rtype : DateTime""" | if isinstance ( delta , pendulum . Duration ) :
return self . subtract ( years = delta . years , months = delta . months , weeks = delta . weeks , days = delta . remaining_days , hours = delta . hours , minutes = delta . minutes , seconds = delta . remaining_seconds , microseconds = delta . microseconds , )
return ... |
def get_widget_from_id ( id ) :
"""returns widget object by id
example web - htmltextwidget - 2-2""" | res = id . split ( '-' )
try :
model_cls = apps . get_model ( res [ 0 ] , res [ 1 ] )
obj = model_cls . objects . get ( parent = res [ 2 ] , id = res [ 3 ] )
except :
obj = None
return obj |
def apply_hds_obs ( hds_file ) :
"""process a modflow head save file . A companion function to
setup _ hds _ obs that is called during the forward run process
Parameters
hds _ file : str
a modflow head save filename . if hds _ file ends with ' ucn ' ,
then the file is treated as a UcnFile type .
Note
... | try :
import flopy
except Exception as e :
raise Exception ( "apply_hds_obs(): error importing flopy: {0}" . format ( str ( e ) ) )
from . . import pst_utils
assert os . path . exists ( hds_file )
out_file = hds_file + ".dat"
ins_file = out_file + ".ins"
assert os . path . exists ( ins_file )
df = pd . DataFram... |
def _round ( self ) :
"""This is the environment implementation of
: meth : ` BaseAnchor . round ` .
Subclasses may override this method .""" | self . x = normalizers . normalizeRounding ( self . x )
self . y = normalizers . normalizeRounding ( self . y ) |
def find_root_tex_document ( base_dir = "." ) :
"""Find the tex article in the current directory that can be considered
a root . We do this by searching contents for ` ` ' \ documentclass ' ` ` .
Parameters
base _ dir : str
Directory to search for LaTeX documents , relative to the current
working director... | log = logging . getLogger ( __name__ )
for tex_path in iter_tex_documents ( base_dir = base_dir ) :
with codecs . open ( tex_path , 'r' , encoding = 'utf-8' ) as f :
text = f . read ( )
if len ( docclass_pattern . findall ( text ) ) > 0 :
log . debug ( "Found root tex {0}" . format ( tex... |
def _create_results_summary ( self ) :
"""Create the dataframe that displays the estimation results , and store
it on the model instance .
Returns
None .""" | # Make sure we have all attributes needed to create the results summary
needed_attributes = [ "params" , "standard_errors" , "tvalues" , "pvalues" , "robust_std_errs" , "robust_t_stats" , "robust_p_vals" ]
try :
assert all ( [ hasattr ( self , attr ) for attr in needed_attributes ] )
assert all ( [ isinstance (... |
def preprocess ( self , nb : "NotebookNode" , resources : dict ) -> Tuple [ "NotebookNode" , dict ] :
"""Preprocess the entire Notebook .""" | exam_num = resources [ "exam_num" ]
time = resources [ "time" ]
date = resources [ "date" ]
nb . cells . insert ( 0 , new_markdown_cell ( source = "---" ) )
nb . cells . insert ( 0 , new_markdown_cell ( source = "" ) )
nb . cells . insert ( 0 , exam_instructions_cell )
first_cell_source = ( "# ME 2233: Thermodynamic Pr... |
def extract_event_info ( dstore , eidx ) :
"""Extract information about the given event index .
Example :
http : / / 127.0.0.1:8800 / v1 / calc / 30 / extract / event _ info / 0""" | event = dstore [ 'events' ] [ int ( eidx ) ]
serial = int ( event [ 'eid' ] // TWO32 )
ridx = list ( dstore [ 'ruptures' ] [ 'serial' ] ) . index ( serial )
[ getter ] = getters . gen_rupture_getters ( dstore , slice ( ridx , ridx + 1 ) )
rupdict = getter . get_rupdict ( )
rlzi = event [ 'rlz' ]
rlzs_assoc = dstore [ '... |
def create_lzma ( archive , compression , cmd , verbosity , interactive , filenames ) :
"""Create an LZMA archive with the lzma Python module .""" | return _create ( archive , compression , cmd , 'alone' , verbosity , filenames ) |
def add_converter ( cls , klass , conv , score = 0 ) :
"""Add converter
: param klass : class or str
: param conv : callable
: param score :
: return :""" | if isinstance ( klass , str ) :
klass = import_name ( klass )
item = klass , conv , score
cls . converters . append ( item )
cls . converters . sort ( key = lambda x : x [ 0 ] )
return cls |
def normalize ( self ) :
"""Reduce trivial AVM conjunctions to just the AVM .
For example , in ` [ ATTR1 [ ATTR2 val ] ] ` the value of ` ATTR1 `
could be a conjunction with the sub - AVM ` [ ATTR2 val ] ` . This
method removes the conjunction so the sub - AVM nests directly
( equivalent to ` [ ATTR1 . ATTR... | for attr in self . _avm :
val = self . _avm [ attr ]
if isinstance ( val , Conjunction ) :
val . normalize ( )
if len ( val . terms ) == 1 and isinstance ( val . terms [ 0 ] , AVM ) :
self . _avm [ attr ] = val . terms [ 0 ]
elif isinstance ( val , AVM ) :
val . normalize... |
def _initialize ( self , boto_session , sagemaker_client , sagemaker_runtime_client ) :
"""Initialize this SageMaker Session .
Creates or uses a boto _ session , sagemaker _ client and sagemaker _ runtime _ client .
Sets the region _ name .""" | self . boto_session = boto_session or boto3 . Session ( )
self . _region_name = self . boto_session . region_name
if self . _region_name is None :
raise ValueError ( 'Must setup local AWS configuration with a region supported by SageMaker.' )
self . sagemaker_client = sagemaker_client or self . boto_session . clien... |
def set_opt ( self , name , value ) :
"""Set option .""" | self . cache [ 'opts' ] [ name ] = value
if name == 'compress' :
self . cache [ 'delims' ] = self . def_delims if not value else ( '' , '' , '' ) |
def stop ( self , nowait = False ) :
"""Stop the listener .
This asks the thread to terminate , and then waits for it to do so .
Note that if you don ' t call this before your application exits , there
may be some records still left on the queue , which won ' t be processed .
If nowait is False then thread ... | self . _stop . set ( )
if nowait :
self . _stop_nowait . set ( )
self . queue . put_nowait ( self . _sentinel_item )
if ( self . _thread . isAlive ( ) and self . _thread is not threading . currentThread ( ) ) :
self . _thread . join ( )
self . _thread = None |
def is_length_prime ( word ) :
"""Function to check if the length of a given string is a prime number .
Examples :
is _ length _ prime ( ' Hello ' ) = = True
is _ length _ prime ( ' abcdcba ' ) = = True
is _ length _ prime ( ' kittens ' ) = = True
is _ length _ prime ( ' orange ' ) = = False
: param wor... | n = len ( word )
if n < 2 :
return False
for i in range ( 2 , n ) :
if n % i == 0 :
return False
return True |
def varnames ( func ) :
"""Return tuple of positional and keywrord argument names for a function ,
method , class or callable .
In case of a class , its ` ` _ _ init _ _ ` ` method is considered .
For methods the ` ` self ` ` parameter is not included .""" | cache = getattr ( func , "__dict__" , { } )
try :
return cache [ "_varnames" ]
except KeyError :
pass
if inspect . isclass ( func ) :
try :
func = func . __init__
except AttributeError :
return ( ) , ( )
elif not inspect . isroutine ( func ) : # callable object ?
try :
func =... |
def from_dict ( data , ctx ) :
"""Instantiate a new AccountSummary from a dict ( generally from loading a
JSON response ) . The data used to instantiate the AccountSummary is a
shallow copy of the dict passed in , with any complex child types
instantiated appropriately .""" | data = data . copy ( )
if data . get ( 'balance' ) is not None :
data [ 'balance' ] = ctx . convert_decimal_number ( data . get ( 'balance' ) )
if data . get ( 'pl' ) is not None :
data [ 'pl' ] = ctx . convert_decimal_number ( data . get ( 'pl' ) )
if data . get ( 'resettablePL' ) is not None :
data [ 'res... |
def iter_groups ( self ) :
"""generator that yields channel groups as pandas DataFrames . If there
are multiple occurences for the same channel name inside a channel
group , then a counter will be used to make the names unique
( < original _ name > _ < counter > )""" | for i , _ in enumerate ( self . groups ) :
yield self . get_group ( i ) |
def send_confirmation_email ( self ) :
"""Sends an email to confirm the new email address .
This method sends out two emails . One to the new email address that
contains the ` ` email _ confirmation _ key ` ` which is used to verify this
this email address with : func : ` User . objects . confirm _ email ` . ... | context = { 'user' : self , 'new_email' : self . email_unconfirmed , 'protocol' : get_protocol ( ) , 'confirmation_key' : self . email_confirmation_key , 'site' : Site . objects . get_current ( ) }
# Email to the old address
subject_old = '' . join ( render_to_string ( 'accounts/emails/confirmation_email_subject_old.tx... |
def get_token ( self , user_id , password , redirect_uri , scope = '/activities/update' ) :
"""Get the token .
Parameters
: param user _ id : string
The id of the user used for authentication .
: param password : string
The user password .
: param redirect _ uri : string
The redirect uri of the instit... | return super ( MemberAPI , self ) . get_token ( user_id , password , redirect_uri , scope ) |
def fraction_done ( self , start = 0.0 , finish = 1.0 , stack = None ) :
''': return float : The estimated fraction of the overall task hierarchy
that has been finished . A number in the range [ 0.0 , 1.0 ] .''' | if stack is None :
stack = self . task_stack
if len ( stack ) == 0 :
return start
elif stack [ 0 ] . size == 0 : # Avoid divide by zero
return finish
else :
top_fraction = stack [ 0 ] . progress * 1.0 / stack [ 0 ] . size
next_top_fraction = ( stack [ 0 ] . progress + 1.0 ) / stack [ 0 ] . size
... |
def _delete_record ( self , identifier = None , rtype = None , name = None , content = None ) :
"""Delete a record from the hosted zone .""" | return self . _change_record_sets ( 'DELETE' , rtype , name , content ) |
def import_ecdsakey_from_pem ( pem , scheme = 'ecdsa-sha2-nistp256' ) :
"""< Purpose >
Import either a public or private ECDSA PEM . In contrast to the other
explicit import functions ( import _ ecdsakey _ from _ public _ pem and
import _ ecdsakey _ from _ private _ pem ) , this function is useful for when it... | # Does ' pem ' have the correct format ?
# This check will ensure arguments has the appropriate number
# of objects and object types , and that all dict keys are properly named .
# Raise ' securesystemslib . exceptions . FormatError ' if the check fails .
securesystemslib . formats . PEMECDSA_SCHEMA . check_match ( pem... |
def abspath ( myPath ) :
import sys , os
"""Get absolute path to resource , works for dev and for PyInstaller""" | try : # PyInstaller creates a temp folder and stores path in _ MEIPASS
base_path = sys . _MEIPASS
return os . path . join ( base_path , os . path . basename ( myPath ) )
except Exception :
base_path = os . path . abspath ( os . path . dirname ( __file__ ) )
return os . path . join ( base_path , myPath ) |
def op ( name , data , bucket_count = None , display_name = None , description = None , collections = None ) :
"""Create a legacy histogram summary op .
Arguments :
name : A unique name for the generated summary node .
data : A ` Tensor ` of any shape . Must be castable to ` float64 ` .
bucket _ count : Opt... | # TODO ( nickfelt ) : remove on - demand imports once dep situation is fixed .
import tensorflow . compat . v1 as tf
if display_name is None :
display_name = name
summary_metadata = metadata . create_summary_metadata ( display_name = display_name , description = description )
with tf . name_scope ( name ) :
ten... |
def setConfigKey ( key , value ) :
"""Sets the config data value for the specified dictionary key""" | configFile = ConfigurationManager . _configFile ( )
return JsonDataManager ( configFile ) . setKey ( key , value ) |
def start ( self ) :
"""Start the sensor""" | # open device
openni2 . initialize ( PrimesenseSensor . OPENNI2_PATH )
self . _device = openni2 . Device . open_any ( )
# open depth stream
self . _depth_stream = self . _device . create_depth_stream ( )
self . _depth_stream . configure_mode ( PrimesenseSensor . DEPTH_IM_WIDTH , PrimesenseSensor . DEPTH_IM_HEIGHT , Pri... |
def write ( self , content ) :
"""Save content on disk""" | with io . open ( self . target , 'w' , encoding = 'utf-8' ) as fp :
fp . write ( content )
if not content . endswith ( u'\n' ) :
fp . write ( u'\n' ) |
def request ( self , host , handler , request_body , verbose ) :
"""Make an xmlrpc request .""" | headers = { 'User-Agent' : self . user_agent , # Proxy - Connection ' : ' Keep - Alive ' ,
# ' Content - Range ' : ' bytes oxy1.0 / - 1 ' ,
'Accept' : 'text/xml' , 'Content-Type' : 'text/xml' }
url = self . _build_url ( host , handler )
try :
resp = requests . post ( url , data = request_body , headers = headers )
... |
def set_webhook_handler ( self , scope , callback ) :
"""Allows adding a webhook _ handler as an alternative to the decorators""" | scope = scope . lower ( )
if scope == 'after_send' :
self . _after_send = callback
return
if scope not in Page . WEBHOOK_ENDPOINTS :
raise ValueError ( "The 'scope' argument must be one of {}." . format ( Page . WEBHOOK_ENDPOINTS ) )
self . _webhook_handlers [ scope ] = callback |
def clear_provider ( self ) :
"""Removes the provider .
raise : NoAccess - ` ` Metadata . isRequired ( ) ` ` is ` ` true ` ` or
` ` Metadata . isReadOnly ( ) ` ` is ` ` true ` `
* compliance : mandatory - - This method must be implemented . *""" | if ( self . get_provider_metadata ( ) . is_read_only ( ) or self . get_provider_metadata ( ) . is_required ( ) ) :
raise errors . NoAccess ( )
self . _my_map [ 'providerId' ] = self . _provider_default |
def display_url ( target ) :
"""Displaying URL in an IPython notebook to allow the user to click and check on information . With thanks to Fernando Perez for putting together the implementation !
: param target : the url to display .
: type target : string .""" | prefix = u"http://" if not target . startswith ( "http" ) else u""
target = prefix + target
display ( HTML ( u'<a href="{t}" target=_blank>{t}</a>' . format ( t = target ) ) ) |
def get_readonly_fields ( self , request , obj = None ) :
"""Set all fields readonly .""" | return list ( self . readonly_fields ) + [ field . name for field in obj . _meta . fields ] |
def remove_edge ( self , p_from , p_to , p_remove_unconnected_nodes = True ) :
"""Removes an edge from the graph .
When remove _ unconnected _ nodes is True , then the nodes are also removed
if they become isolated .""" | if self . has_edge ( p_from , p_to ) :
self . _edges [ p_from ] . remove ( p_to )
try :
del self . _edge_numbers [ ( p_from , p_to ) ]
except KeyError :
return None
if p_remove_unconnected_nodes :
if self . is_isolated ( p_from ) :
self . remove_node ( p_from )
if self . is_isolated ( p_to )... |
def get_batch_children ( self ) :
"""Retrieves batch child tasks for this task if its a batch task .
: return : Collection instance .
: raises SbError if task is not a batch task .""" | if not self . batch :
raise SbgError ( "This task is not a batch task." )
return self . query ( parent = self . id , api = self . _api ) |
def get_ephemerides ( self , observatory_code , airmass_lessthan = 99 , solar_elongation = ( 0 , 180 ) , skip_daylight = False ) :
"""Call JPL HORIZONS website to obtain ephemerides based on the
provided targetname , epochs , and observatory _ code . For a list
of valid observatory codes , refer to
http : / /... | # queried fields ( see HORIZONS website for details )
# if fields are added here , also update the field identification below
quantities = '1,3,4,8,9,10,18,19,20,21,23,24,27,31,33,36'
# encode objectname for use in URL
objectname = urllib . quote ( self . targetname . encode ( "utf8" ) )
# construct URL for HORIZONS qu... |
def _get_point_rates ( self , source , mmin , mmax = np . inf ) :
"""Adds the rates for a point source
: param source :
Point source as instance of : class :
openquake . hazardlib . source . point . PointSource
: param float mmin :
Minimum Magnitude
: param float mmax :
Maximum Magnitude""" | src_mesh = Mesh . from_points_list ( [ source . location ] )
in_poly = self . limits . intersects ( src_mesh ) [ 0 ]
if not in_poly :
return
else :
for ( mag , rate ) in source . get_annual_occurrence_rates ( ) :
if ( mag < mmin ) or ( mag > mmax ) :
return
else :
for ( p... |
def _authenticate_websocket ( self , websocket , event_handler ) :
"""Sends a authentication challenge over a websocket .
This is not needed when we just send the cookie we got on login
when connecting to the websocket .""" | log . debug ( 'Authenticating websocket' )
json_data = json . dumps ( { "seq" : 1 , "action" : "authentication_challenge" , "data" : { "token" : self . _token } } ) . encode ( 'utf8' )
yield from websocket . send ( json_data )
while True :
message = yield from websocket . recv ( )
status = json . loads ( messag... |
def prepare ( self ) :
"""Prepare the session , setting up the session object and loading in
the values , assigning the IP address to the session if it ' s an new one .""" | super ( SessionRequestHandler , self ) . prepare ( )
result = yield gen . Task ( self . start_session )
LOGGER . debug ( 'Exiting SessionRequestHandler.prepare: %r' , result ) |
def calc_qv_v1 ( self ) :
"""Calculate the discharge of both forelands after Manning - Strickler .
Required control parameters :
| EKV |
| SKV |
| Gef |
Required flux sequence :
| AV |
| UV |
Calculated flux sequence :
| lstream _ fluxes . QV |
Examples :
For appropriate strictly positive valu... | con = self . parameters . control . fastaccess
flu = self . sequences . fluxes . fastaccess
for i in range ( 2 ) :
if ( flu . av [ i ] > 0. ) and ( flu . uv [ i ] > 0. ) :
flu . qv [ i ] = ( con . ekv [ i ] * con . skv [ i ] * flu . av [ i ] ** ( 5. / 3. ) / flu . uv [ i ] ** ( 2. / 3. ) * con . gef ** .5 )... |
def _update_roster ( self ) :
'''Update default flat roster with the passed in information .
: return :''' | roster_file = self . _get_roster ( )
if os . access ( roster_file , os . W_OK ) :
if self . __parsed_rosters [ self . ROSTER_UPDATE_FLAG ] :
with salt . utils . files . fopen ( roster_file , 'a' ) as roster_fp :
roster_fp . write ( '# Automatically added by "{s_user}" at {s_time}\n{hostname}:\n ... |
def validate_overlap ( comp1 , comp2 , force ) :
"""Validate the overlap between the wavelength sets
of the two given components .
Parameters
comp1 , comp2 : ` ~ pysynphot . spectrum . SourceSpectrum ` or ` ~ pysynphot . spectrum . SpectralElement `
Source spectrum and bandpass of an observation .
force :... | warnings = dict ( )
if force is None :
stat = comp2 . check_overlap ( comp1 )
if stat == 'full' :
pass
elif stat == 'partial' :
raise ( exceptions . PartialOverlap ( 'Spectrum and bandpass do not fully overlap. You may use force=[extrap|taper] to force this Observation anyway.' ) )
elif ... |
def samples_to_batches ( samples : Iterable , batch_size : int ) :
"""Chunk a series of network inputs and outputs into larger batches""" | it = iter ( samples )
while True :
with suppress ( StopIteration ) :
batch_in , batch_out = [ ] , [ ]
for i in range ( batch_size ) :
sample_in , sample_out = next ( it )
batch_in . append ( sample_in )
batch_out . append ( sample_out )
if not batch_in :
... |
def decode_unicode_obj ( obj ) :
"""Decode unicoded dict / list / tuple encoded by ` unicode _ obj `""" | if isinstance ( obj , dict ) :
r = { }
for k , v in iteritems ( obj ) :
r [ decode_unicode_string ( k ) ] = decode_unicode_obj ( v )
return r
elif isinstance ( obj , six . string_types ) :
return decode_unicode_string ( obj )
elif isinstance ( obj , ( list , tuple ) ) :
return [ decode_unico... |
async def close_async ( self ) :
"""Close the client asynchronously . This includes closing the Session
and CBS authentication layer as well as the Connection .
If the client was opened using an external Connection ,
this will be left intact .""" | if self . message_handler :
await self . message_handler . destroy_async ( )
self . message_handler = None
self . _shutdown = True
if self . _keep_alive_thread :
await self . _keep_alive_thread
self . _keep_alive_thread = None
if not self . _session :
return
# already closed .
if not self . _con... |
def _handle_offset_error ( self , failure ) :
"""Retry the offset fetch request if appropriate .
Once the : attr : ` . retry _ delay ` reaches our : attr : ` . retry _ max _ delay ` , we
log a warning . This should perhaps be extended to abort sooner on
certain errors .""" | # outstanding request got errback ' d , clear it
self . _request_d = None
if self . _stopping and failure . check ( CancelledError ) : # Not really an error
return
# Do we need to abort ?
if ( self . request_retry_max_attempts != 0 and self . _fetch_attempt_count >= self . request_retry_max_attempts ) :
log . d... |
def run ( bam_file , data , fastqc_out ) :
"""Run fastqc , generating report in specified directory and parsing metrics .
Downsamples to 10 million reads to avoid excessive processing times with large
files , unless we ' re running a Standard / smallRNA - seq / QC pipeline .
Handles fastqc 0.11 + , which use ... | sentry_file = os . path . join ( fastqc_out , "fastqc_report.html" )
if not os . path . exists ( sentry_file ) :
work_dir = os . path . dirname ( fastqc_out )
utils . safe_makedir ( work_dir )
ds_file = ( bam . downsample ( bam_file , data , 1e7 , work_dir = work_dir ) if data . get ( "analysis" , "" ) . lo... |
def transfer_learning_tuner ( self , additional_parents = None , estimator = None ) :
"""Creates a new ` ` HyperparameterTuner ` ` by copying the request fields from the provided parent to the new
instance of ` ` HyperparameterTuner ` ` . Followed by addition of warm start configuration with the type as
" Trans... | return self . _create_warm_start_tuner ( additional_parents = additional_parents , warm_start_type = WarmStartTypes . TRANSFER_LEARNING , estimator = estimator ) |
def from_cli ( opt , dyn_range_fac = 1 , precision = 'single' , inj_filter_rejector = None ) :
"""Parses the CLI options related to strain data reading and conditioning .
Parameters
opt : object
Result of parsing the CLI with OptionParser , or any object with the
required attributes ( gps - start - time , g... | gating_info = { }
if opt . frame_cache or opt . frame_files or opt . frame_type :
if opt . frame_cache :
frame_source = opt . frame_cache
if opt . frame_files :
frame_source = opt . frame_files
logging . info ( "Reading Frames" )
if hasattr ( opt , 'frame_sieve' ) and opt . frame_sieve :... |
def get_catalogs ( portal ) :
"""Returns the catalogs from the site""" | res = [ ]
for object in portal . objectValues ( ) :
if ICatalogTool . providedBy ( object ) :
res . append ( object )
elif IZCatalog . providedBy ( object ) :
res . append ( object )
res . sort ( )
return res |
def find_children ( self , linespec ) :
"""Find lines and immediate children that match the linespec regex .
: param linespec : regular expression of line to match
: returns : list of lines . These correspond to the lines that were
matched and their immediate children""" | res = [ ]
for parent in self . find_objects ( linespec ) :
res . append ( parent . line )
res . extend ( [ child . line for child in parent . children ] )
return res |
def projected_gradient_descent ( model_fn , x , eps , eps_iter , nb_iter , ord , clip_min = None , clip_max = None , y = None , targeted = False , rand_init = None , rand_minmax = 0.3 , sanity_checks = True ) :
"""This class implements either the Basic Iterative Method
( Kurakin et al . 2016 ) when rand _ init is... | assert eps_iter <= eps , ( eps_iter , eps )
if ord == 1 :
raise NotImplementedError ( "It's not clear that FGM is a good inner loop" " step for PGD when ord=1, because ord=1 FGM " " changes only one pixel at a time. We need " " to rigorously test a strong ord=1 PGD " "before enabling this feature." )
if ord not in ... |
def _terminate ( self , level : int ) -> bool :
"""Returns : succeeded in * attempting * a kill ?""" | if not self . running :
return True
# Already closed by itself ?
try :
self . wait ( 0 )
return True
except subprocess . TimeoutExpired : # failed to close
pass
# SEE NOTES ABOVE . This is tricky under Windows .
suffix = " [to child process {}]" . format ( self . process . pid )
if level == self . KILL_... |
def post_order ( parent ) :
"""Post order a forest .""" | n = len ( parent )
k = 0
p = matrix ( 0 , ( n , 1 ) )
head = matrix ( - 1 , ( n , 1 ) )
next = matrix ( 0 , ( n , 1 ) )
stack = matrix ( 0 , ( n , 1 ) )
for j in range ( n - 1 , - 1 , - 1 ) :
if ( parent [ j ] == j ) :
continue
next [ j ] = head [ parent [ j ] ]
head [ parent [ j ] ] = j
for j in ra... |
def decorate_disabled ( self ) :
"""Return True if this decoration must be omitted , otherwise - False .
This class searches for tags values in environment variable
( : attr : ` . Verifier . _ _ environment _ var _ _ ` ) , Derived class can implement any logic
: return : bool""" | if len ( self . _tags ) == 0 :
return False
if self . _env_var not in os . environ :
return True
env_tags = os . environ [ self . _env_var ] . split ( self . __class__ . __tags_delimiter__ )
if '*' in env_tags :
return False
for tag in self . _tags :
if tag in env_tags :
return False
return True |
def _import_parsers ( ) :
"""Lazy imports to prevent circular dependencies between this module and utils""" | global ARCGIS_NODES
global ARCGIS_ROOTS
global ArcGISParser
global FGDC_ROOT
global FgdcParser
global ISO_ROOTS
global IsoParser
global VALID_ROOTS
if ARCGIS_NODES is None or ARCGIS_ROOTS is None or ArcGISParser is None :
from gis_metadata . arcgis_metadata_parser import ARCGIS_NODES
from gis_metadata . arcgis_... |
def get_content_models ( self ) :
"""Return all subclasses that are admin registered .""" | models = [ ]
for model in self . concrete_model . get_content_models ( ) :
try :
admin_url ( model , "add" )
except NoReverseMatch :
continue
else :
setattr ( model , "meta_verbose_name" , model . _meta . verbose_name )
setattr ( model , "add_url" , admin_url ( model , "add" ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.