signature stringlengths 29 44.1k | implementation stringlengths 0 85.2k |
|---|---|
def args_wrapper ( * args ) :
"""Generates callback arguments for model . fit ( )
for a set of callback objects .
Callback objects like PandasLogger ( ) , LiveLearningCurve ( )
get passed in . This assembles all their callback arguments .""" | out = defaultdict ( list )
for callback in args :
callback_args = callback . callback_args ( )
for k , v in callback_args . items ( ) :
out [ k ] . append ( v )
return dict ( out ) |
def five_prime ( self , upstream = 1 , downstream = 0 ) :
"""Creates a BED / GFF file of the 5 ' end of each feature represented in the
table and returns the resulting pybedtools . BedTool object . Needs an
attached database .
Parameters
upstream , downstream : int
Number of basepairs up and downstream to... | return pybedtools . BedTool ( self . features ( ) ) . each ( featurefuncs . five_prime , upstream , downstream ) . saveas ( ) |
def downgrade ( ) :
"""Downgrade database .""" | if op . _proxy . migration_context . dialect . name == 'postgresql' :
op . alter_column ( 'records_metadata' , 'json' , type_ = sa . dialects . postgresql . JSON , postgresql_using = 'json::text::json' ) |
def exists ( self , ** kwargs ) :
"""Providing a partition is not necessary on topology ; causes errors""" | kwargs . pop ( 'partition' , None )
kwargs [ 'transform_name' ] = True
return self . _exists ( ** kwargs ) |
def info ( self ) :
"""Retrieve info about the attribute : name , data type and
number of values .
Args : :
no argument
Returns : :
3 - element tuple holding :
- attribute name
- attribute data type ( see constants SDC . xxx )
- number of values in the attribute ; for a string - valued
attribute (... | if self . _index is None :
try :
self . _index = self . _obj . findattr ( self . _name )
except HDF4Error :
raise HDF4Error ( "info: cannot convert name to index" )
status , self . _name , data_type , n_values = _C . SDattrinfo ( self . _obj . _id , self . _index )
_checkErr ( 'info' , status , ... |
def calculate_bin_centers ( edges ) :
"""Calculate the centers of wavelengths bins given their edges .
Parameters
edges : array _ like
Sequence of bin edges . Must be 1D and have at least two values .
Returns
centers : ndarray
Array of bin centers . Will be 1D and have one less value than ` ` edges ` ` ... | edges = np . asanyarray ( edges , dtype = np . float )
if edges . ndim != 1 :
raise ValueError ( 'edges input array must be 1D.' )
if edges . size < 2 :
raise ValueError ( 'edges input must have at least two values.' )
centers = np . empty ( edges . size - 1 , dtype = np . float )
centers [ 0 ] = edges [ : 2 ] ... |
def jaccard ( seq1 , seq2 ) :
"""Compute the Jaccard distance between the two sequences ` seq1 ` and ` seq2 ` .
They should contain hashable items .
The return value is a float between 0 and 1 , where 0 means equal , and 1 totally different .""" | set1 , set2 = set ( seq1 ) , set ( seq2 )
return 1 - len ( set1 & set2 ) / float ( len ( set1 | set2 ) ) |
def _CallEventHandler ( self , Event , * Args , ** KwArgs ) :
"""Calls all event handlers defined for given Event , additional parameters
will be passed unchanged to event handlers , all event handlers are fired on
separate threads .
: Parameters :
Event : str
Name of the event .
Args
Positional argum... | if Event not in self . _EventHandlers :
raise ValueError ( '%s is not a valid %s event name' % ( Event , self . __class__ . __name__ ) )
args = map ( repr , Args ) + [ '%s=%s' % ( key , repr ( value ) ) for key , value in KwArgs . items ( ) ]
self . __Logger . debug ( 'calling %s: %s' , Event , ', ' . join ( args )... |
def _setup_task_manager ( self ) :
"""instantiate the threaded task manager to run the producer / consumer
queue that is the heart of the processor .""" | self . config . logger . info ( 'installing signal handers' )
# set up the signal handler for dealing with SIGTERM . the target should
# be this app instance so the signal handler can reach in and set the
# quit flag to be True . See the ' respond _ to _ SIGTERM ' method for the
# more information
respond_to_SIGTERM_wi... |
def _proxy ( self ) :
"""Generate an instance context for the instance , the context is capable of
performing various actions . All instance actions are proxied to the context
: returns : SyncListPermissionContext for this SyncListPermissionInstance
: rtype : twilio . rest . sync . v1 . service . sync _ list ... | if self . _context is None :
self . _context = SyncListPermissionContext ( self . _version , service_sid = self . _solution [ 'service_sid' ] , list_sid = self . _solution [ 'list_sid' ] , identity = self . _solution [ 'identity' ] , )
return self . _context |
def parse_mime_type ( mime_type ) :
"""Carves up a mime - type and returns a tuple of the ( type , subtype , params ) where
' params ' is a dictionary of all the parameters for the media range . For example , the
media range ' application / xhtml ; q = 0.5 ' would get parsed into :
( ' application ' , ' xhtml... | parts = mime_type . split ( ";" )
params = dict ( [ tuple ( [ s . strip ( ) for s in param . split ( "=" ) ] ) for param in parts [ 1 : ] ] )
full_type = parts [ 0 ] . strip ( )
# Java URLConnection class sends an Accept header that includes a single " * "
# Turn it into a legal wildcard .
if full_type == '*' :
ful... |
def run ( configObj = None , input_dict = { } , loadOnly = False ) :
"""Build DQ masks from all input images , then apply static mask ( s ) .""" | # If called from interactive user - interface , configObj will not be
# defined yet , so get defaults using EPAR / TEAL .
# Also insure that the input _ dict ( user - specified values ) are folded in
# with a fully populated configObj instance .
configObj = util . getDefaultConfigObj ( __taskname__ , configObj , input_... |
def _prepare_bam ( bam_file , bed_file , config ) :
"""Remove regions from bed files""" | if not bam_file or not bed_file :
return bam_file
out_file = utils . append_stem ( bam_file , '_filter' )
bedtools = config_utils . get_program ( "bedtools" , config )
if not utils . file_exists ( out_file ) :
with file_transaction ( out_file ) as tx_out :
cmd = "{bedtools} subtract -nonamecheck -A -a {... |
def replace_launch_config ( self , scaling_group , launch_config_type , server_name , image , flavor , disk_config = None , metadata = None , personality = None , networks = None , load_balancers = None , key_name = None , config_drive = False , user_data = None ) :
"""Replace an existing launch configuration . All... | group_id = utils . get_id ( scaling_group )
uri = "/%s/%s/launch" % ( self . uri_base , group_id )
body = self . _create_launch_config_body ( launch_config_type = launch_config_type , server_name = server_name , image = image , flavor = flavor , disk_config = disk_config , metadata = metadata , personality = personalit... |
def encode_multipart_formdata ( fields , boundary = None ) :
"""Encode a dictionary of ` ` fields ` ` using the multipart / form - data mime format .
: param fields :
Dictionary of fields . The key is treated as the field name , and the
value as the body of the form - data . If the value is a tuple of two
e... | body = StringIO ( )
if boundary is None :
boundary = mimetools . choose_boundary ( )
for fieldname , value in fields . iteritems ( ) :
body . write ( '--%s\r\n' % ( boundary ) )
if isinstance ( value , tuple ) :
filename , data = value
writer ( body ) . write ( 'Content-Disposition: form-dat... |
def _clean_text ( self , text ) :
"""Performs invalid character removal and whitespace cleanup on text .""" | output = [ ]
for char in text :
cp = ord ( char )
if cp in ( 0 , 0xfffd ) or self . _is_control ( char ) :
continue
if self . _is_whitespace ( char ) :
output . append ( ' ' )
else :
output . append ( char )
return '' . join ( output ) |
def get_service_definitions ( self , service_type = None ) :
"""GetServiceDefinitions .
[ Preview API ]
: param str service _ type :
: rtype : [ ServiceDefinition ]""" | route_values = { }
if service_type is not None :
route_values [ 'serviceType' ] = self . _serialize . url ( 'service_type' , service_type , 'str' )
response = self . _send ( http_method = 'GET' , location_id = 'd810a47d-f4f4-4a62-a03f-fa1860585c4c' , version = '5.0-preview.1' , route_values = route_values )
return ... |
def variance_inflation_factors ( df ) :
'''Computes the variance inflation factor ( VIF ) for each column in the df .
Returns a pandas Series of VIFs
Args :
df : pandas DataFrame with columns to run diagnostics on''' | corr = np . corrcoef ( df , rowvar = 0 )
corr_inv = np . linalg . inv ( corr )
vifs = np . diagonal ( corr_inv )
return pd . Series ( vifs , df . columns , name = 'VIF' ) |
def get_called_sequence ( self , section = None , fastq = False ) :
"""Return either the called sequence data , if present .
: param section : [ ' template ' , ' complement ' or ' 2D ' ]
: param fastq : If True , return a single , multiline fastq string . If
False , return a tuple of ( name , sequence , qstri... | if section != "2D" :
warnings . warn ( "Basecall2DTools.get_called_sequence() should specify section='2D'" , DeprecationWarning )
# Backwards compatibilty to 0.3.3 , if no " 2D " section , bump args by 1 and pass to super
if section == None : # We assume that a named arg or no - arg was given
return... |
def retrieve_matching_jwk ( self , token ) :
"""Get the signing key by exploring the JWKS endpoint of the OP .""" | response_jwks = requests . get ( self . OIDC_OP_JWKS_ENDPOINT , verify = self . get_settings ( 'OIDC_VERIFY_SSL' , True ) )
response_jwks . raise_for_status ( )
jwks = response_jwks . json ( )
# Compute the current header from the given token to find a match
jws = JWS . from_compact ( token )
json_header = jws . signat... |
def parse_color ( color ) :
"""Parses color into a vtk friendly rgb list""" | if color is None :
color = rcParams [ 'color' ]
if isinstance ( color , str ) :
return vtki . string_to_rgb ( color )
elif len ( color ) == 3 :
return color
else :
raise Exception ( """
Invalid color input
Must ba string, rgb list, or hex color string. For example:
color='white'
... |
def getCalculationDependants ( self , deps = None ) :
"""Return a flat list of services who depend on this calculation .
This refers only to services who ' s Calculation UIDReferenceField have
the value set to point to this calculation .
It has nothing to do with the services referenced in the calculation ' s... | if deps is None :
deps = [ ]
backrefs = get_backreferences ( self , 'AnalysisServiceCalculation' )
services = map ( get_object_by_uid , backrefs )
for service in services :
calc = service . getCalculation ( )
if calc and calc . UID ( ) != self . UID ( ) :
calc . getCalculationDependants ( deps )
... |
def to_representation ( self , value ) :
"""Serialize translated fields .
Simply iterate over available translations and , for each language ,
delegate serialization logic to the translation model serializer .
Output languages can be selected by passing a list of language codes ,
` languages ` , within the ... | if value is None :
return
# Only need one serializer to create the native objects
serializer = self . serializer_class ( instance = self . parent . instance , # Typically None
context = self . context , partial = self . parent . partial )
# Don ' t need to have a ' language _ code ' , it will be split up already ,
... |
def adjoint ( self ) :
"""Adjoint of this operator .
For example , if A and B are operators : :
[ [ A , 0 ] ,
[0 , B ] ]
The adjoint is given by : :
[ [ A ^ * , 0 ] ,
[0 , B ^ * ] ]
This is only well defined if each sub - operator has an adjoint
Returns
adjoint : ` DiagonalOperator `
The adjoint... | adjoints = [ op . adjoint for op in self . operators ]
return DiagonalOperator ( * adjoints , domain = self . range , range = self . domain ) |
def _code ( self ) :
"""( internal ) generates imports , code and runtime calls to save a pipeline .""" | icode , tcode = '' , ''
# imports , task code
icall , pcall = '' , ''
# imap calls , piper calls
tdone , idone = [ ] , [ ]
# task done , imap done
for piper in self :
p = piper
w = piper . worker
i = piper . imap
in_ = i . name if hasattr ( i , 'name' ) else False
if in_ and in_ not in idone :
... |
def fmt_num ( num , zero_num = None ) :
"""humanize number ( 9000 to 9,000)""" | if zero_num is not None :
num = floatformat ( num , zero_num )
return intcomma ( num , False ) |
def get_surname_initial_author_pattern ( incl_numeration = False ) :
"""Match an author name of the form : ' surname initial ( s ) '
This is sometimes the represention of the first author found inside an author group .
This author pattern is only used to find a maximum of ONE author inside an author group .
A... | # Possible inclusion of superscript numeration at the end of author names
# Will match the empty string
if incl_numeration :
append_num_re = get_author_affiliation_numeration_str ( ) + '?'
else :
append_num_re = ""
return ur"""
(?:
(?:
(?!%(invalid_prefixes)s) ... |
def read ( self , want = 0 ) :
'''Read method , gets data from internal buffer while releasing
: meth : ` write ` locks when needed .
The lock usage means it must ran on a different thread than
: meth : ` fill ` , ie . the main thread , otherwise will deadlock .
The combination of both write and this method... | if self . _finished :
if self . _finished == 1 :
self . _finished += 1
return ""
return EOFError ( "EOF reached" )
# Thread communication
self . _want = want
self . _add . set ( )
self . _result . wait ( )
self . _result . clear ( )
if want :
data = self . _data [ : want ]
self . _data =... |
def _to_dict ( self ) :
'''Returns a dictionary representation of this object''' | return dict ( latitude = self . latitude , longitude = self . longitude , depth = self . depth ) |
def del_watch ( self , wd ) :
"""Remove watch entry associated to watch descriptor wd .
@ param wd : Watch descriptor .
@ type wd : int""" | try :
del self . _wmd [ wd ]
except KeyError as err :
log . error ( 'Cannot delete unknown watch descriptor %s' % str ( err ) ) |
def usable_id ( cls , id ) :
"""Retrieve id from input which can be hostname , vhost , id .""" | try : # id is maybe a hostname
qry_id = cls . from_name ( id )
if not qry_id : # id is maybe an ip
qry_id = cls . from_ip ( id )
if not qry_id :
qry_id = cls . from_vhost ( id )
except Exception :
qry_id = None
if not qry_id :
msg = 'unknown identifier %s' % id
cls . error ( msg ... |
def reload_using_spawn_exit ( self ) :
"""Spawn a subprocess and exit the current process .
: return :
None .""" | # Create command parts
cmd_parts = [ sys . executable ] + sys . argv
# Get env dict copy
env_copy = os . environ . copy ( )
# Spawn subprocess
subprocess . Popen ( cmd_parts , env = env_copy , close_fds = True )
# If need force exit
if self . _force_exit : # Force exit
os . _exit ( 0 )
# pylint : disable = protecte... |
def _CreateFeedMapping ( client , feed_details ) :
"""Creates the feed mapping for DSA page feeds .
Args :
client : an AdWordsClient instance .
feed _ details : a _ DSAFeedDetails instance .""" | # Get the FeedMappingService .
feed_mapping_service = client . GetService ( 'FeedMappingService' , version = 'v201809' )
# Create the operation .
operation = { # Create the feed mapping .
'operand' : { 'criterionType' : DSA_PAGE_FEED_CRITERION_TYPE , 'feedId' : feed_details . feed_id , # Map the feedAttributeIds to the... |
def check_datafile_present_and_download ( path , backup_url = None ) :
"""Check whether the file is present , otherwise download .""" | path = Path ( path )
if path . is_file ( ) :
return True
if backup_url is None :
return False
logg . info ( 'try downloading from url\n' + backup_url + '\n' + '... this may take a while but only happens once' )
if not path . parent . is_dir ( ) :
logg . info ( 'creating directory' , str ( path . parent ) + ... |
def zoom_out_pixel ( self , curr_pixel ) :
"""return the curr _ frag at a lower resolution""" | low_frag = curr_pixel [ 0 ]
high_frag = curr_pixel [ 1 ]
level = curr_pixel [ 2 ]
str_level = str ( level )
if level < self . n_level - 1 :
low_super = self . spec_level [ str_level ] [ "fragments_dict" ] [ low_frag ] [ "super_index" ]
high_super = self . spec_level [ str_level ] [ "fragments_dict" ] [ high_fra... |
def receive_message ( self , message , data ) :
"""Called when a receiver - message has been received .""" | if data [ MESSAGE_TYPE ] == TYPE_RECEIVER_STATUS :
self . _process_get_status ( data )
return True
elif data [ MESSAGE_TYPE ] == TYPE_LAUNCH_ERROR :
self . _process_launch_error ( data )
return True
return False |
def bbox ( ctx , tile ) :
"""Print Tile bounding box as geometry .""" | geom = TilePyramid ( ctx . obj [ 'grid' ] , tile_size = ctx . obj [ 'tile_size' ] , metatiling = ctx . obj [ 'metatiling' ] ) . tile ( * tile ) . bbox ( pixelbuffer = ctx . obj [ 'pixelbuffer' ] )
if ctx . obj [ 'output_format' ] in [ 'WKT' , 'Tile' ] :
click . echo ( geom )
elif ctx . obj [ 'output_format' ] == 'G... |
def rand_hexstr ( length , lower = True ) :
"""Gererate fixed - length random hexstring , usually for md5.
: param length : total length of this string .
: param lower : use lower case or upper case .""" | if lower :
return rand_str ( length , allowed = CHARSET_HEXSTR_LOWER )
else :
return rand_str ( length , allowed = CHARSET_HEXSTR_UPPER ) |
def set_pair ( self , term1 , term2 , value , ** kwargs ) :
"""Set the value for a pair of terms .
Args :
term1 ( str )
term2 ( str )
value ( mixed )""" | key = self . key ( term1 , term2 )
self . keys . update ( [ term1 , term2 ] )
self . pairs [ key ] = value |
def synthesize ( lemma , form , partofspeech = '' , hint = '' , guess = True , phonetic = False ) :
"""Synthesize a single word based on given morphological attributes .
Note that spellchecker does not respect pre - tokenized words and concatenates
token sequences such as " New York " .
Parameters
lemma : s... | return Vabamorf . instance ( ) . synthesize ( lemma , form , partofspeech , hint , guess , phonetic ) |
def bio_EventRelated ( epoch , event_length , window_post_ecg = 0 , window_post_rsp = 4 , window_post_eda = 4 , ecg_features = [ "Heart_Rate" , "Cardiac_Phase" , "RR_Interval" , "RSA" , "HRV" ] ) :
"""Extract event - related bio ( EDA , ECG and RSP ) changes .
Parameters
epoch : pandas . DataFrame
An epoch co... | bio_response = { }
ECG_Response = ecg_EventRelated ( epoch , event_length , window_post = window_post_ecg , features = ecg_features )
bio_response . update ( ECG_Response )
RSP_Response = rsp_EventRelated ( epoch , event_length , window_post = window_post_rsp )
bio_response . update ( RSP_Response )
EDA_Response = eda_... |
def shift_list_to_right ( lst : list , count1 : int , count2 : int ) -> list :
"""Function to modify provided list by rotating it to the right by a specific number of elements .
Args :
lst ( list ) : Original list to rotate .
count1 ( int ) : Number of elements to take from the end of a list .
count2 ( int ... | output_list = lst [ - count1 : ] + lst [ : - count2 ]
return output_list |
def _get_schedule ( self , include_opts = True , include_pillar = True , remove_hidden = False ) :
'''Return the schedule data structure''' | schedule = { }
if include_pillar :
pillar_schedule = self . opts . get ( 'pillar' , { } ) . get ( 'schedule' , { } )
if not isinstance ( pillar_schedule , dict ) :
raise ValueError ( 'Schedule must be of type dict.' )
schedule . update ( pillar_schedule )
if include_opts :
opts_schedule = self .... |
def set_file_system ( self , source_url = False , build_url = False ) :
"""Set the source file filesystem and / or build file system""" | assert isinstance ( source_url , string_types ) or source_url is None or source_url is False
assert isinstance ( build_url , string_types ) or build_url is False
if source_url :
self . _source_url = source_url
self . dataset . config . library . source . url = self . _source_url
self . _source_fs = None
eli... |
def get_raw_path ( self ) :
"""Returns the raw path to the mounted disk image , i . e . the raw : file : ` . dd ` , : file : ` . raw ` or : file : ` ewf1 `
file .
: rtype : str""" | if self . disk_mounter == 'dummy' :
return self . paths [ 0 ]
else :
if self . disk_mounter == 'avfs' and os . path . isdir ( os . path . join ( self . mountpoint , 'avfs' ) ) :
logger . debug ( "AVFS mounted as a directory, will look in directory for (random) file." )
# there is no support for ... |
def _validate_isvalid_orcid ( self , isvalid_orcid , field , value ) :
"""Checks for valid ORCID if given .
Args :
isvalid _ orcid ( ` bool ` ) : flag from schema indicating ORCID to be checked .
field ( ` str ` ) : ' author '
value ( ` dict ` ) : dictionary of author metadata .
The rule ' s arguments are... | if isvalid_orcid and 'ORCID' in value :
try :
res = search_orcid ( value [ 'ORCID' ] )
except ConnectionError :
warn ( 'network not available, ORCID not validated.' )
return
except HTTPError :
self . _error ( field , 'ORCID incorrect or invalid for ' + value [ 'name' ] )
... |
def merge_bins ( self , amount : Optional [ int ] = None , * , min_frequency : Optional [ float ] = None , axis : Optional [ AxisIdentifier ] = None , inplace : bool = False ) -> 'HistogramBase' :
"""Reduce the number of bins and add their content :
Parameters
amount : How many adjacent bins to join together . ... | if not inplace :
histogram = self . copy ( )
histogram . merge_bins ( amount , min_frequency = min_frequency , axis = axis , inplace = True )
return histogram
elif axis is None :
for i in range ( self . ndim ) :
self . merge_bins ( amount = amount , min_frequency = min_frequency , axis = i , inp... |
def sample_cov ( prices , frequency = 252 ) :
"""Calculate the annualised sample covariance matrix of ( daily ) asset returns .
: param prices : adjusted closing prices of the asset , each row is a date
and each column is a ticker / id .
: type prices : pd . DataFrame
: param frequency : number of time peri... | if not isinstance ( prices , pd . DataFrame ) :
warnings . warn ( "prices are not in a dataframe" , RuntimeWarning )
prices = pd . DataFrame ( prices )
daily_returns = daily_price_returns ( prices )
return daily_returns . cov ( ) * frequency |
def normalize_options ( options ) :
"""Turns a mapping of ' option : arg ' to a list and prefix the options .
arg can be a list of arguments .
for example :
dict = {
o1 : a1,
o2 : ,
o3 : [ a31 , a32]
o4 : [ ]
will be transformed to :
prefix _ option ( o1 ) , a1 , prefix _ option ( o2 ) ,
prefix ... | normalized_options = [ ]
def _add ( option , arg = None ) :
normalized_options . append ( option )
arg and normalized_options . append ( arg )
for option , arg in options . viewitems ( ) :
prefixed_option = Build . prefix_option ( option )
if isinstance ( arg , list ) and arg :
for a in arg :
... |
def _submit ( self , pool , args , callback ) :
"""If the caller has passed the magic ' single - threaded ' flag , call the
function directly instead of pool . apply _ async . The single - threaded flag
is intended for gathering more useful performance information about
what appens beneath ` call _ runner ` ,... | if self . config . args . single_threaded :
callback ( self . call_runner ( * args ) )
else :
pool . apply_async ( self . call_runner , args = args , callback = callback ) |
def add_field ( self , field_instance ) :
"""Appends a field .""" | if isinstance ( field_instance , BaseScriptField ) :
field_instance = field_instance
else :
raise ValueError ( 'Expected a basetring or Field instance' )
self . fields . append ( field_instance )
return self |
def predict_density ( self , Fmu , Fvar , Y ) :
r"""Given a Normal distribution for the latent function , and a datum Y ,
compute the log predictive density of Y .
i . e . if
q ( f ) = N ( Fmu , Fvar )
and this object represents
p ( y | f )
then this method computes the predictive density
\ log \ int ... | return ndiagquad ( self . logp , self . num_gauss_hermite_points , Fmu , Fvar , logspace = True , Y = Y ) |
def get_arg_name ( self , param ) :
"""gets the argument name used in the command table for a parameter""" | if self . current_command in self . cmdtab :
for arg in self . cmdtab [ self . current_command ] . arguments :
for name in self . cmdtab [ self . current_command ] . arguments [ arg ] . options_list :
if name == param :
return arg
return None |
def lookup_extrapolation ( x , xs , ys ) :
"""Intermediate values are calculated with linear interpolation between the intermediate points .
Out - of - range values are calculated with linear extrapolation from the last two values at either end .""" | length = len ( xs )
if x < xs [ 0 ] :
dx = xs [ 1 ] - xs [ 0 ]
dy = ys [ 1 ] - ys [ 0 ]
k = dy / dx
return ys [ 0 ] + ( x - xs [ 0 ] ) * k
if x > xs [ length - 1 ] :
dx = xs [ length - 1 ] - xs [ length - 2 ]
dy = ys [ length - 1 ] - ys [ length - 2 ]
k = dy / dx
return ys [ length - 1 ]... |
def Akers_Deans_Crosser ( m , rhog , rhol , kl , mul , Cpl , D , x ) :
r'''Calculates heat transfer coefficient for condensation
of a pure chemical inside a vertical tube or tube bundle , as presented in
[2 ] _ according to [ 1 ] _ .
. . math : :
Nu = \ frac { hD _ i } { k _ l } = C Re _ e ^ n Pr _ l ^ { 1/... | G = m / ( pi / 4 * D ** 2 )
Ge = G * ( ( 1 - x ) + x * ( rhol / rhog ) ** 0.5 )
Ree = D * Ge / mul
Prl = mul * Cpl / kl
if Ree > 5E4 :
C , n = 0.0265 , 0.8
else :
C , n = 5.03 , 1 / 3.
Nu = C * Ree ** n * Prl ** ( 1 / 3. )
return Nu * kl / D |
def thing_type_absent ( name , thingTypeName , region = None , key = None , keyid = None , profile = None ) :
'''Ensure thing type with passed properties is absent .
. . versionadded : : 2016.11.0
name
The name of the state definition .
thingTypeName
Name of the thing type .
region
Region to connect t... | ret = { 'name' : thingTypeName , 'result' : True , 'comment' : '' , 'changes' : { } }
_describe = __salt__ [ 'boto_iot.describe_thing_type' ] ( thingTypeName = thingTypeName , region = region , key = key , keyid = keyid , profile = profile )
if 'error' in _describe :
ret [ 'result' ] = False
ret [ 'comment' ] =... |
def print_projects ( self , projects ) :
"""Print method for projects .""" | for project in projects :
print ( '{}: {}' . format ( project . name , project . id ) ) |
def serialize_list ( self , tag ) :
"""Return the literal representation of a list tag .""" | separator , fmt = self . comma , '[{}]'
with self . depth ( ) :
if self . should_expand ( tag ) :
separator , fmt = self . expand ( separator , fmt )
return fmt . format ( separator . join ( map ( self . serialize , tag ) ) ) |
def get_store_credit_transaction_by_id ( cls , store_credit_transaction_id , ** kwargs ) :
"""Find StoreCreditTransaction
Return single instance of StoreCreditTransaction by its ID .
This method makes a synchronous HTTP request by default . To make an
asynchronous HTTP request , please pass async = True
> >... | kwargs [ '_return_http_data_only' ] = True
if kwargs . get ( 'async' ) :
return cls . _get_store_credit_transaction_by_id_with_http_info ( store_credit_transaction_id , ** kwargs )
else :
( data ) = cls . _get_store_credit_transaction_by_id_with_http_info ( store_credit_transaction_id , ** kwargs )
return d... |
def get_commensurate_points ( supercell_matrix ) : # wrt primitive cell
"""Commensurate q - points are returned .
Parameters
supercell _ matrix : array _ like
Supercell matrix with respect to primitive cell basis vectors .
shape = ( 3 , 3)
dtype = intc""" | smat = np . array ( supercell_matrix , dtype = int )
rec_primitive = PhonopyAtoms ( numbers = [ 1 ] , scaled_positions = [ [ 0 , 0 , 0 ] ] , cell = np . diag ( [ 1 , 1 , 1 ] ) , pbc = True )
rec_supercell = get_supercell ( rec_primitive , smat . T )
q_pos = rec_supercell . get_scaled_positions ( )
return np . array ( n... |
def deserialize_iter ( self , attr , iter_type ) :
"""Deserialize an iterable .
: param list attr : Iterable to be deserialized .
: param str iter _ type : The type of object in the iterable .
: rtype : list""" | if attr is None :
return None
if isinstance ( attr , ET . Element ) : # If I receive an element here , get the children
attr = list ( attr )
if not isinstance ( attr , ( list , set ) ) :
raise DeserializationError ( "Cannot deserialize as [{}] an object of type {}" . format ( iter_type , type ( attr ) ) )
r... |
def resource_group_check_existence ( name , ** kwargs ) :
'''. . versionadded : : 2019.2.0
Check for the existence of a named resource group in the current subscription .
: param name : The resource group name to check .
CLI Example :
. . code - block : : bash
salt - call azurearm _ resource . resource _ ... | result = False
resconn = __utils__ [ 'azurearm.get_client' ] ( 'resource' , ** kwargs )
try :
result = resconn . resource_groups . check_existence ( name )
except CloudError as exc :
__utils__ [ 'azurearm.log_cloud_error' ] ( 'resource' , str ( exc ) , ** kwargs )
return result |
def predictive_mean ( self , mu , variance , Y_metadata = None ) :
"""Quadrature calculation of the predictive mean : E ( Y _ star | Y ) = E ( E ( Y _ star | f _ star , Y ) )
: param mu : mean of posterior
: param sigma : standard deviation of posterior""" | # conditional _ mean : the edpected value of y given some f , under this likelihood
fmin = - np . inf
fmax = np . inf
def int_mean ( f , m , v ) :
exponent = - ( 0.5 / v ) * np . square ( f - m )
# If exponent is under - 30 then exp ( exponent ) will be very small , so don ' t exp it ! )
# If p is zero then... |
def make_nd_vec ( v , nd = None , t = None , norm = False ) :
"""Coerce input to np . array ( ) and validate dimensionality .
Ensure dimensionality ' n ' if passed .
Cast to type ' t ' if passed
Normalize output if norm = True
. . todo : : Complete make _ nd _ vec docstring""" | # Imports
import numpy as np
from scipy import linalg as spla
# Reduce the input to the extent possible
out_v = np . array ( v , dtype = t ) . squeeze ( )
# Confirm vector form
if not len ( out_v . shape ) == 1 :
raise ValueError ( "'v' is not reducible to a vector." )
# # end if
# If indicated , confirm dimensiona... |
def plot_skipped_corr ( x , y , xlabel = None , ylabel = None , n_boot = 2000 , seed = None ) :
"""Plot the bootstrapped 95 % confidence intervals and distribution
of a robust Skipped correlation .
Parameters
x , y : 1D - arrays or list
Samples
xlabel , ylabel : str
Axes labels
n _ boot : int
Number... | from pingouin . correlation import skipped
from scipy . stats import pearsonr
from pingouin . effsize import compute_bootci
# Safety check
x = np . asarray ( x )
y = np . asarray ( y )
assert x . size == y . size
# Skipped Spearman / Pearson correlations
r , p , outliers = skipped ( x , y , method = 'spearman' )
r_pear... |
def who ( self , target ) :
"""Runs a WHO on a target
Required arguments :
* target - / WHO < target >
Returns a dictionary , with a nick as the key and -
the value is a list in the form of ;
[0 ] - Username
[1 ] - Priv level
[2 ] - Real name
[3 ] - Hostname""" | with self . lock :
self . send ( 'WHO %s' % target )
who_lst = { }
while self . readable ( ) :
msg = self . _recv ( expected_replies = ( '352' , '315' ) )
if msg [ 0 ] == '352' :
raw_who = msg [ 2 ] . split ( None , 7 )
prefix = raw_who [ 5 ] . replace ( 'H' , '' , 1 ... |
def _mask_cov_func ( self , * args ) :
"""Masks the covariance function into a form usable by : py : func : ` mpmath . diff ` .
Parameters
* args : ` num _ dim ` * 2 floats
The individual elements of Xi and Xj to be passed to : py : attr : ` cov _ func ` .""" | # Have to do it in two cases to get the 1d unwrapped properly :
if self . num_dim == 1 :
return self . cov_func ( args [ 0 ] , args [ 1 ] , * self . params )
else :
return self . cov_func ( args [ : self . num_dim ] , args [ self . num_dim : ] , * self . params ) |
def probe ( gandi , resource , enable , disable , test , host , interval , http_method , http_response , threshold , timeout , url , window ) :
"""Manage a probe for a webaccelerator""" | result = gandi . webacc . probe ( resource , enable , disable , test , host , interval , http_method , http_response , threshold , timeout , url , window )
output_keys = [ 'status' , 'timeout' ]
output_generic ( gandi , result , output_keys , justify = 14 )
return result |
def queryBuilderWidget ( self ) :
"""Returns the query builder widget instance that this widget is associated with .
: return < XQueryBuilderWidget >""" | from projexui . widgets . xquerybuilderwidget import XQueryBuilderWidget
builder = self . parent ( )
while ( builder and not isinstance ( builder , XQueryBuilderWidget ) ) :
builder = builder . parent ( )
return builder |
def sunion ( self , * other_sets ) :
"""Union between Sets .
Returns a set of common members . Uses Redis . sunion .""" | return self . db . sunion ( [ self . key ] + [ s . key for s in other_sets ] ) |
def _make_signature ( self ) :
"""Create a signature for ` execute ` based on the minimizers this
` ChainedMinimizer ` was initiated with . For the format , see the docstring
of : meth : ` ChainedMinimizer . execute ` .
: return : : class : ` inspect . Signature ` instance .""" | # Create KEYWORD _ ONLY arguments with the names of the minimizers .
name = lambda x : x . __class__ . __name__
count = Counter ( [ name ( minimizer ) for minimizer in self . minimizers ] )
# Count the number of each minimizer , they don ' t have to be unique
# Note that these are inspect _ sig . Parameter ' s , not sy... |
def assert_hashable ( * args , ** kw ) :
"""Verify that each argument is hashable .
Passes silently if successful . Raises descriptive TypeError otherwise .
Example : :
> > > assert _ hashable ( 1 , ' foo ' , bar = ' baz ' )
> > > assert _ hashable ( 1 , [ ] , baz = ' baz ' )
Traceback ( most recent call ... | try :
for i , arg in enumerate ( args ) :
hash ( arg )
except TypeError :
raise TypeError ( 'Argument in position %d is not hashable: %r' % ( i , arg ) )
try :
for key , val in iterate_items ( kw ) :
hash ( val )
except TypeError :
raise TypeError ( 'Keyword argument %r is not hashable: ... |
def showDiffResults ( self ) :
"""Show results when diff option on .""" | try :
oldWarnings = self . parseWarnings ( self . _readDiffFile ( ) )
except :
sys . stderr . write ( self . errorResultRead % self . diffOption )
return 1
newWarnings = self . parseWarnings ( self . streamForDiff . getvalue ( ) )
diffWarnings = self . generateDiff ( oldWarnings , newWarnings )
if diffWarni... |
def ext_pillar ( minion_id , pillar , # pylint : disable = W0613
** kwargs ) :
'''Check vmware / vcenter for all data''' | vmware_pillar = { }
host = None
username = None
password = None
property_types = [ ]
property_name = 'name'
protocol = None
port = None
pillar_key = 'vmware'
replace_default_attributes = False
type_specific_pillar_attributes = { 'VirtualMachine' : [ { 'config' : [ 'version' , 'guestId' , 'files' , 'tools' , 'flags' , '... |
def get_page_access_token ( self , app_id , app_secret , user_token ) :
"""Returns a dictionary of never expired page token indexed by page names .
: param str app _ id : Application ID
: param str app _ secret : Application secret
: param str user _ token : User short - lived token
: rtype : dict""" | url_extend = ( self . _url_base + '/oauth/access_token?grant_type=fb_exchange_token&' 'client_id=%(app_id)s&client_secret=%(app_secret)s&fb_exchange_token=%(user_token)s' )
response = self . lib . get ( url_extend % { 'app_id' : app_id , 'app_secret' : app_secret , 'user_token' : user_token } )
user_token_long_lived = ... |
def run ( name , location = '\\' ) :
r'''Run a scheduled task manually .
: param str name : The name of the task to run .
: param str location : A string value representing the location of the task .
Default is ' \ \ ' which is the root for the task scheduler
( C : \ Windows \ System32 \ tasks ) .
: retur... | # Check for existing folder
if name not in list_tasks ( location ) :
return '{0} not found in {1}' . format ( name , location )
# connect to the task scheduler
with salt . utils . winapi . Com ( ) :
task_service = win32com . client . Dispatch ( "Schedule.Service" )
task_service . Connect ( )
# get the folder to... |
def inst_matches ( self , start , end , instr , target = None , include_beyond_target = False ) :
"""Find all ` instr ` in the block from start to end .
` instr ` is a Python opcode or a list of opcodes
If ` instr ` is an opcode with a target ( like a jump ) , a target
destination can be specified which must ... | try :
None in instr
except :
instr = [ instr ]
first = self . offset2inst_index [ start ]
result = [ ]
for inst in self . insts [ first : ] :
if inst . opcode in instr :
if target is None :
result . append ( inst . offset )
else :
t = self . get_target ( inst . offset... |
def parse_value_objectwithlocalpath ( self , tup_tree ) :
"""< ! ELEMENT VALUE . OBJECTWITHLOCALPATH ( ( LOCALCLASSPATH , CLASS ) |
( LOCALINSTANCEPATH , INSTANCE ) ) >
Returns :
tupletree with child item that is :
- for class - level use : a tuple ( CIMClassName , CIMClass ) where the
path of the CIMClas... | self . check_node ( tup_tree , 'VALUE.OBJECTWITHLOCALPATH' )
k = kids ( tup_tree )
if len ( k ) != 2 :
raise CIMXMLParseError ( _format ( "Element {0!A} has invalid number of child elements " "{1!A} (expecting two child elements " "((LOCALCLASSPATH, CLASS) | (LOCALINSTANCEPATH, " "INSTANCE)))" , name ( tup_tree ) ,... |
def coords_string_parser ( self , coords ) :
"""Pareses the address string into coordinates to match address _ to _ coords return object""" | lat , lon = coords . split ( ',' )
return { "lat" : lat . strip ( ) , "lon" : lon . strip ( ) , "bounds" : { } } |
def str_to_v1_str ( xml_str ) :
"""Convert a API v2 XML doc to v1 XML doc .
Removes elements that are only valid for v2 and changes namespace to v1.
If doc is already v1 , it is returned unchanged .
Args :
xml _ str : str
API v2 XML doc . E . g . : ` ` SystemMetadata v2 ` ` .
Returns :
str : API v1 XM... | if str_is_v1 ( xml_str ) :
return xml_str
etree_obj = str_to_etree ( xml_str )
strip_v2_elements ( etree_obj )
etree_replace_namespace ( etree_obj , d1_common . types . dataoneTypes_v1 . Namespace )
return etree_to_str ( etree_obj ) |
def get_auth_info ( self , ** params ) :
"""https : / / developers . coinbase . com / api / v2 # show - authorization - information""" | response = self . _get ( 'v2' , 'user' , 'auth' , params = params )
return self . _make_api_object ( response , APIObject ) |
def commit ( ) :
"""Commit changes and release the write lock""" | session_token = request . headers [ 'session_token' ]
repository = request . headers [ 'repository' ]
current_user = have_authenticated_user ( request . environ [ 'REMOTE_ADDR' ] , repository , session_token )
if current_user is False :
return fail ( user_auth_fail_msg )
repository_path = config [ 'repositories' ] ... |
def to_array ( self ) :
"""Serializes this PassportFile to a dictionary .
: return : dictionary representation of this object .
: rtype : dict""" | array = super ( PassportFile , self ) . to_array ( )
array [ 'file_id' ] = u ( self . file_id )
# py2 : type unicode , py3 : type str
array [ 'file_size' ] = int ( self . file_size )
# type int
array [ 'file_date' ] = int ( self . file_date )
# type int
return array |
def access_add ( name , event , cid , uid , ** kwargs ) :
"""Creates a new record with specified cid / uid in the event authorization .
Requests with token that contains such cid / uid will have access to the specified event of a
service .""" | ctx = Context ( ** kwargs )
ctx . execute_action ( 'access:add' , ** { 'unicorn' : ctx . repo . create_secure_service ( 'unicorn' ) , 'service' : name , 'event' : event , 'cids' : cid , 'uids' : uid , } ) |
def to_expression ( self , lhs , rhs , op ) :
"""Builds a binary sql expression .
At its most basic , returns ' lhs op rhs ' such as ' 5 + 3 ' . However , it also specially handles the
' in ' and ' between ' operators . For each of these operators it is expected that rhs will be
iterable .
If the comparison... | if op == "raw" : # TODO : This is not documented
return lhs
elif op == "between" :
return "{0} between {1} and {2}" . format ( lhs , * rhs )
elif op == "in" :
return "{0} in {1}" . format ( lhs , self . to_tuple ( rhs ) )
elif op . startswith ( "not(" ) and op . endswith ( ")" ) :
return "not ({0} {1} {... |
def monkeypatch_method ( cls , patch_name ) : # This function ' s code was inspired from the following thread :
# " [ Python - Dev ] Monkeypatching idioms - - elegant or ugly ? "
# by Robert Brewer < fumanchu at aminus . org >
# ( Tue Jan 15 19:13:25 CET 2008)
"""Add the decorated method to the given class ; replac... | def decorator ( func ) :
fname = func . __name__
old_func = getattr ( cls , fname , None )
if old_func is not None : # Add the old func to a list of old funcs .
old_ref = "_old_%s_%s" % ( patch_name , fname )
old_attr = getattr ( cls , old_ref , None )
if old_attr is None :
... |
def remove ( self , * args ) :
"""Remove object ( s ) from the Conf .
: param * args : Any objects to remove from the Conf .
: returns : full list of Conf ' s child objects""" | for x in args :
self . children . remove ( x )
return self . children |
def learn ( self , spiro , iterations = 1 ) :
'''Train short term memory with given spirograph .
: param spiro :
: py : class : ` SpiroArtifact ` object''' | for i in range ( iterations ) :
self . stmem . train_cycle ( spiro . obj . flatten ( ) ) |
def set_n_gram ( self , value ) :
'''setter''' | if isinstance ( value , Ngram ) :
self . __n_gram = value
else :
raise TypeError ( "The type of n_gram must be Ngram." ) |
def get_version ( ) :
"""Retrieves package version from the file .""" | with open ( 'fades/_version.py' ) as fh :
m = re . search ( "\(([^']*)\)" , fh . read ( ) )
if m is None :
raise ValueError ( "Unrecognized version in 'fades/_version.py'" )
return m . groups ( ) [ 0 ] . replace ( ', ' , '.' ) |
def is_duplicate_of ( self , other ) :
"""Check if spectrum is duplicate of another .""" | if super ( Spectrum , self ) . is_duplicate_of ( other ) :
return True
row_matches = 0
for ri , row in enumerate ( self . get ( self . _KEYS . DATA , [ ] ) ) :
lambda1 , flux1 = tuple ( row [ 0 : 2 ] )
if ( self . _KEYS . DATA not in other or ri > len ( other [ self . _KEYS . DATA ] ) ) :
break
... |
def getAllRegexp ( ) :
'''Method that recovers ALL the list of < RegexpObject > classes to be processed . . . .
: return : Returns a list [ ] of < RegexpObject > classes .''' | logger = logging . getLogger ( "entify" )
logger . debug ( "Recovering all the available <RegexpObject> classes." )
listAll = [ ]
# For demo only
# listAll . append ( Demo ( ) )
listAll . append ( BitcoinAddress ( ) )
listAll . append ( DNI ( ) )
listAll . append ( DogecoinAddress ( ) )
listAll . append ( Email ( ) )
l... |
def get_segment_leaderboard ( self , segment_id , gender = None , age_group = None , weight_class = None , following = None , club_id = None , timeframe = None , top_results_limit = None , page = None , context_entries = None ) :
"""Gets the leaderboard for a segment .
http : / / strava . github . io / api / v3 /... | params = { }
if gender is not None :
if gender . upper ( ) not in ( 'M' , 'F' ) :
raise ValueError ( "Invalid gender: {0}. Possible values: 'M' or 'F'" . format ( gender ) )
params [ 'gender' ] = gender
valid_age_groups = ( '0_24' , '25_34' , '35_44' , '45_54' , '55_64' , '65_plus' )
if age_group is not... |
def _set_bucket_dns ( self ) :
"""Create CNAME for S3 endpoint .""" | # Different regions have different s3 endpoint formats
dotformat_regions = [ "eu-west-2" , "eu-central-1" , "ap-northeast-2" , "ap-south-1" , "ca-central-1" , "us-east-2" ]
if self . region in dotformat_regions :
s3_endpoint = "{0}.s3-website.{1}.amazonaws.com" . format ( self . bucket , self . region )
else :
... |
def get ( self , url , params = None ) :
'Make a GET request for url and return the response content as a generic lxml . objectify object' | url = self . escapeUrl ( url )
content = six . BytesIO ( self . raw ( url , params = params ) )
# We need to make sure that the xml fits in available memory before we parse
# with lxml . objectify . fromstring ( ) , or else it will bomb out .
# If it is too big , we need to buffer it to disk before we run it through ob... |
def new ( ) -> ulid . ULID :
"""Create a new : class : ` ~ ulid . ulid . ULID ` instance .
The timestamp is created from : func : ` ~ time . time ` .
The randomness is created from : func : ` ~ os . urandom ` .
: return : ULID from current timestamp
: rtype : : class : ` ~ ulid . ulid . ULID `""" | timestamp = int ( time . time ( ) * 1000 ) . to_bytes ( 6 , byteorder = 'big' )
randomness = os . urandom ( 10 )
return ulid . ULID ( timestamp + randomness ) |
def parse_fileshare_or_file_snapshot_parameter ( url ) : # type : ( str ) - > Tuple [ str , str ]
"""Checks if the fileshare or file is a snapshot
: param url str : file url
: rtype : tuple
: return : ( url , snapshot )""" | if is_not_empty ( url ) :
if '?sharesnapshot=' in url :
try :
tmp = url . split ( '?sharesnapshot=' )
if len ( tmp ) == 2 :
dateutil . parser . parse ( tmp [ 1 ] )
return tmp [ 0 ] , tmp [ 1 ]
except ( ValueError , OverflowError ) :
... |
def label ( self , name , color , update = True ) :
"""Create or update a label""" | url = '%s/labels' % self
data = dict ( name = name , color = color )
response = self . http . post ( url , json = data , auth = self . auth , headers = self . headers )
if response . status_code == 201 :
return True
elif response . status_code == 422 and update :
url = '%s/%s' % ( url , name )
response = se... |
def StartupInstance ( r , instance , dry_run = False , no_remember = False ) :
"""Starts up an instance .
@ type instance : str
@ param instance : the instance to start up
@ type dry _ run : bool
@ param dry _ run : whether to perform a dry run
@ type no _ remember : bool
@ param no _ remember : if true... | query = { "dry-run" : dry_run , "no-remember" : no_remember , }
return r . request ( "put" , "/2/instances/%s/startup" % instance , query = query ) |
def release ( self , on_element = None ) :
"""Releasing a held mouse button on an element .
: Args :
- on _ element : The element to mouse up .
If None , releases on current mouse position .""" | if on_element :
self . move_to_element ( on_element )
if self . _driver . w3c :
self . w3c_actions . pointer_action . release ( )
self . w3c_actions . key_action . pause ( )
else :
self . _actions . append ( lambda : self . _driver . execute ( Command . MOUSE_UP , { } ) )
return self |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.