signature stringlengths 29 44.1k | implementation stringlengths 0 85.2k |
|---|---|
def get_asset_classes_for_security ( self , namespace : str , symbol : str ) -> List [ AssetClass ] :
"""Find all asset classes ( should be only one at the moment , though ! ) to which the symbol belongs""" | full_symbol = symbol
if namespace :
full_symbol = f"{namespace}:{symbol}"
result = ( self . session . query ( AssetClassStock ) . filter ( AssetClassStock . symbol == full_symbol ) . all ( ) )
return result |
def create_session ( self , lock_type = library . LockType . shared , session = None ) :
"""Lock this machine
Arguments :
lock _ type - see IMachine . lock _ machine for details
session - optionally define a session object to lock this machine
against . If not defined , a new ISession object is
created to... | if session is None :
session = library . ISession ( )
# NOTE : The following hack handles the issue of unknown machine state .
# This occurs most frequently when a machine is powered off and
# in spite waiting for the completion event to end , the state of
# machine still raises the following Error :
# virtualbox .... |
def _do_resumable_upload ( self , stream , metadata , num_retries ) :
"""Perform a resumable upload .
: type stream : IO [ bytes ]
: param stream : A bytes IO object open for reading .
: type metadata : dict
: param metadata : The metadata associated with the upload .
: type num _ retries : int
: param ... | upload , transport = self . _initiate_resumable_upload ( stream , metadata , num_retries )
while not upload . finished :
response = upload . transmit_next_chunk ( transport )
return response |
def methods ( * meth ) :
"""To explicitely set the methods to use without using @ route
This can only be applied of methods . Not class .
: param meth : tuple of available method
: return :""" | def decorator ( f ) :
if not hasattr ( f , '_methods_cache' ) :
f . _methods_cache = [ m . upper ( ) for m in meth ]
return f
return decorator |
def _get_response ( self , params ) :
"""wrap the call to the requests package""" | return self . _session . get ( self . _api_url , params = params , timeout = self . _timeout ) . json ( encoding = "utf8" ) |
def getfo ( self , remotepath , fl , callback = None ) :
"""Copy a remote file ( ` ` remotepath ` ` ) from the SFTP server and write to
an open file or file - like object , ` ` fl ` ` . Any exception raised by
operations will be passed through . This method is primarily provided
as a convenience .
: param o... | file_size = self . stat ( remotepath ) . st_size
with self . open ( remotepath , "rb" ) as fr :
fr . prefetch ( file_size )
return self . _transfer_with_callback ( reader = fr , writer = fl , file_size = file_size , callback = callback ) |
def from_array ( self , coeffs , r0 , errors = None , normalization = 'schmidt' , csphase = 1 , lmax = None , copy = True ) :
"""Initialize the class with spherical harmonic coefficients from an input
array .
Usage
x = SHMagCoeffs . from _ array ( array , r0 , [ errors , normalization , csphase ,
lmax , cop... | if _np . iscomplexobj ( coeffs ) :
raise TypeError ( 'The input array must be real.' )
if type ( normalization ) != str :
raise ValueError ( 'normalization must be a string. ' 'Input type was {:s}' . format ( str ( type ( normalization ) ) ) )
if normalization . lower ( ) not in ( '4pi' , 'ortho' , 'schmidt' , ... |
def solve_sort ( expr , vars ) :
"""Sort values on the LHS by the value they yield when passed to RHS .""" | lhs_values = repeated . getvalues ( __solve_for_repeated ( expr . lhs , vars ) [ 0 ] )
sort_expression = expr . rhs
def _key_func ( x ) :
return solve ( sort_expression , __nest_scope ( expr . lhs , vars , x ) ) . value
results = ordered . ordered ( lhs_values , key_func = _key_func )
return Result ( repeated . mel... |
def verify_selenium_server_is_running ( self ) :
"""Start the Selenium standalone server , if it isn ' t already running .
Returns a tuple of two elements :
* A boolean which is True if the server is now running
* The Popen object representing the process so it can be terminated
later ; if the server was al... | selenium_jar = settings . SELENIUM_JAR_PATH
if len ( selenium_jar ) < 5 :
self . stdout . write ( 'You need to configure SELENIUM_JAR_PATH' )
return False , None
_jar_dir , jar_name = os . path . split ( selenium_jar )
# Is it already running ?
process = Popen ( [ 'ps -e | grep "%s"' % jar_name [ : - 4 ] ] , sh... |
def plot_acquisition ( bounds , input_dim , model , Xdata , Ydata , acquisition_function , suggested_sample , filename = None ) :
'''Plots of the model and the acquisition function in 1D and 2D examples .''' | # Plots in dimension 1
if input_dim == 1 : # X = np . arange ( bounds [ 0 ] [ 0 ] , bounds [ 0 ] [ 1 ] , 0.001)
# X = X . reshape ( len ( X ) , 1)
# acqu = acquisition _ function ( X )
# acqu _ normalized = ( - acqu - min ( - acqu ) ) / ( max ( - acqu - min ( - acqu ) ) ) # normalize acquisition
# m , v = model . predi... |
def create_links ( self ) :
"""Create links to installed scripts in the virtualenv ' s
bin directory to our bin directory .""" | for link in self . list_exes ( ) :
print_pretty ( "<FG_BLUE>Creating link for {}...<END>" . format ( link ) )
os . symlink ( link , path . join ( ENV_BIN , path . basename ( link ) ) ) |
def get_permission ( self , service , func ) :
"""Build permission required to access function " func " """ | if self . permission :
perm = self . permission
elif self . prefix is False : # No permission will be checked
perm = False
elif self . prefix :
perm = build_permission_name ( service . model_class , self . prefix )
else :
name = func . __name__
# check if there is a translation between default permi... |
def request_add_sensor ( self , sock , msg ) :
"""add a sensor""" | self . add_sensor ( Sensor ( int , 'int_sensor%d' % len ( self . _sensors ) , 'descr' , 'unit' , params = [ - 10 , 10 ] ) )
return Message . reply ( 'add-sensor' , 'ok' ) |
def get_schema ( schema_type ) :
'''Get a schema that can validate BSE JSON files
The schema _ type represents the type of BSE JSON file to be validated ,
and can be ' component ' , ' element ' , ' table ' , ' metadata ' , or ' references ' .''' | schema_file = "{}-schema.json" . format ( schema_type )
file_path = os . path . join ( _default_schema_dir , schema_file )
if not os . path . isfile ( file_path ) :
raise RuntimeError ( 'Schema file \'{}\' does not exist, is not readable, or is not a file' . format ( file_path ) )
return fileio . read_schema ( file... |
def match ( self , path : str ) -> Tuple [ Optional [ Dict [ str , Any ] ] , bool ] :
"""Check if the path matches this Rule .
If it does it returns a dict of matched and converted values ,
otherwise None is returned .""" | match = self . _pattern . match ( path )
if match is not None : # If the route is a branch ( not leaf ) and the path is
# missing a trailing slash then it needs one to be
# considered a match in the strict slashes mode .
needs_slash = ( self . strict_slashes and not self . is_leaf and match . groupdict ( ) [ '__sla... |
def _event_to_pb ( event ) :
"""Supports converting internal TaskData and WorkerData , as well as
celery Task and Worker to proto buffers messages .
Args :
event ( Union [ TaskData | Task | WorkerData | Worker ] ) :
Returns :
ProtoBuf object""" | if isinstance ( event , ( TaskData , Task ) ) :
key , klass = 'task' , clearly_pb2 . TaskMessage
elif isinstance ( event , ( WorkerData , Worker ) ) :
key , klass = 'worker' , clearly_pb2 . WorkerMessage
else :
raise ValueError ( 'unknown event' )
keys = klass . DESCRIPTOR . fields_by_name . keys ( )
# noin... |
def sendcommand ( self , cmd , opt = None ) :
"Send a telnet command ( IAC )" | if cmd in [ DO , DONT ] :
if not self . DOOPTS . has_key ( opt ) :
self . DOOPTS [ opt ] = None
if ( ( ( cmd == DO ) and ( self . DOOPTS [ opt ] != True ) ) or ( ( cmd == DONT ) and ( self . DOOPTS [ opt ] != False ) ) ) :
self . DOOPTS [ opt ] = ( cmd == DO )
self . writecooked ( IAC + ... |
def _merge_many_to_one_field ( self , main_infos , prop , result ) :
"""* Find the foreignkey associated to the current relationship
* Get its title
* Remove this fkey field from the export
: param dict main _ infos : The datas collected about the relationship
: param obj prop : The property mapper of the r... | title = None
# We first find the related foreignkey to get the good title
rel_base = list ( prop . local_columns ) [ 0 ]
related_fkey_name = rel_base . name
if not main_infos . get ( 'keep_key' , False ) :
for val in result :
if val [ 'name' ] == related_fkey_name :
title = val [ 'label' ]
... |
def sync_type ( ks_name , type_model , connection = None ) :
"""Inspects the type _ model and creates / updates the corresponding type .
Note that the attributes removed from the type _ model are not deleted on the database ( this operation is not supported ) .
They become effectively ignored by ( will not show... | if not _allow_schema_modification ( ) :
return
if not issubclass ( type_model , UserType ) :
raise CQLEngineException ( "Types must be derived from base UserType." )
_sync_type ( ks_name , type_model , connection = connection ) |
def _GetArgsFromRequest ( self , request , method_metadata , route_args ) :
"""Builds args struct out of HTTP request .""" | format_mode = GetRequestFormatMode ( request , method_metadata )
if request . method in [ "GET" , "HEAD" ] :
if method_metadata . args_type :
unprocessed_request = request . args
if hasattr ( unprocessed_request , "dict" ) :
unprocessed_request = unprocessed_request . dict ( )
ar... |
def draw ( self ) :
"""Draw guide
Returns
out : matplotlib . offsetbox . Offsetbox
A drawing of this legend""" | obverse = slice ( 0 , None )
reverse = slice ( None , None , - 1 )
nbreak = len ( self . key )
themeable = self . theme . figure . _themeable
# When there is more than one guide , we keep
# record of all of them using lists
if 'legend_title' not in themeable :
themeable [ 'legend_title' ] = [ ]
if 'legend_text_lege... |
def wait_socket ( host , port , timeout = 120 ) :
'''Wait for socket opened on remote side . Return False after timeout''' | return wait_result ( lambda : check_socket ( host , port ) , True , timeout ) |
def merge_scores ( self , df_addition , reference_markers = 'all' , addition_markers = 'all' , on = [ 'project_name' , 'sample_name' , 'frame_name' , 'cell_index' ] ) :
"""Combine CellDataFrames that differ by score composition
Args :
df _ addition ( CellDataFrame ) : The CellDataFrame to merge scores in from
... | if isinstance ( reference_markers , str ) :
reference_markers = self . scored_names
elif reference_markers is None :
reference_markers = [ ]
if isinstance ( addition_markers , str ) :
addition_markers = df_addition . scored_names
elif addition_markers is None :
addition_markers = [ ]
df_addition = df_ad... |
def parents ( self , p_todo , p_only_direct = False ) :
"""Returns a list of parent todos that ( in ) directly depend on the
given todo .""" | parents = self . _depgraph . incoming_neighbors ( hash ( p_todo ) , not p_only_direct )
return [ self . _tododict [ parent ] for parent in parents ] |
def get_overlay_data_start_offset ( self ) :
"""Get the offset of data appended to the file and not contained within
the area described in the headers .""" | largest_offset_and_size = ( 0 , 0 )
def update_if_sum_is_larger_and_within_file ( offset_and_size , file_size = len ( self . __data__ ) ) :
if sum ( offset_and_size ) <= file_size and sum ( offset_and_size ) > sum ( largest_offset_and_size ) :
return offset_and_size
return largest_offset_and_size
if has... |
async def list ( self , * args , ** kwargs ) :
'''Corresponds to GET request without a resource identifier , fetching documents from the database''' | limit = int ( kwargs . pop ( 'limit' , self . limit ) )
limit = 1000 if limit == 0 else limit
# lets not go crazy here
offset = int ( kwargs . pop ( 'offset' , self . offset ) )
projection = None
# perform full text search or standard filtering
if self . _meta . fts_operator in kwargs . keys ( ) :
filters = { '$tex... |
def add_contact ( self , segment_id , contact_id ) :
"""Add a contact to the segment
: param segment _ id : int Segment ID
: param contact _ id : int Contact ID
: return : dict | str""" | response = self . _client . session . post ( '{url}/{segment_id}/contact/add/{contact_id}' . format ( url = self . endpoint_url , segment_id = segment_id , contact_id = contact_id ) )
return self . process_response ( response ) |
def m2eul ( r , axis3 , axis2 , axis1 ) :
"""Factor a rotation matrix as a product of three rotations
about specified coordinate axes .
http : / / naif . jpl . nasa . gov / pub / naif / toolkit _ docs / C / cspice / m2eul _ c . html
: param r : A rotation matrix to be factored
: type r : 3x3 - Element Array... | r = stypes . toDoubleMatrix ( r )
axis3 = ctypes . c_int ( axis3 )
axis2 = ctypes . c_int ( axis2 )
axis1 = ctypes . c_int ( axis1 )
angle3 = ctypes . c_double ( )
angle2 = ctypes . c_double ( )
angle1 = ctypes . c_double ( )
libspice . m2eul_c ( r , axis3 , axis2 , axis1 , ctypes . byref ( angle3 ) , ctypes . byref ( ... |
def parse_args ( self , args = None , namespace = None , config_file_contents = None , env_vars = os . environ ) :
"""Supports all the same args as the ArgumentParser . parse _ args ( . . ) ,
as well as the following additional args .
Additional Args :
args : a list of args as in argparse , or a string ( eg .... | args , argv = self . parse_known_args ( args = args , namespace = namespace , config_file_contents = config_file_contents , env_vars = env_vars )
if argv :
self . error ( 'unrecognized arguments: %s' % ' ' . join ( argv ) )
return args |
def insert ( self , i , tab_index ) :
"""Insert the widget ( at tab index ) in the position i ( index ) .""" | _id = id ( self . editor . tabs . widget ( tab_index ) )
self . history . insert ( i , _id ) |
def corr_dim ( data , emb_dim , rvals = None , dist = rowwise_euclidean , fit = "RANSAC" , debug_plot = False , debug_data = False , plot_file = None ) :
"""Calculates the correlation dimension with the Grassberger - Procaccia algorithm
Explanation of correlation dimension :
The correlation dimension is a chara... | data = np . asarray ( data )
# TODO what are good values for r ?
# TODO do this for multiple values of emb _ dim ?
if rvals is None :
sd = np . std ( data )
rvals = logarithmic_r ( 0.1 * sd , 0.5 * sd , 1.03 )
n = len ( data )
orbit = delay_embedding ( data , emb_dim , lag = 1 )
dists = np . array ( [ dist ( or... |
def breakpoint ( args ) :
"""% prog breakpoint mstmap . input > breakpoints . bed
Find scaffold breakpoints using genetic map . Use variation . vcf . mstmap ( ) to
generate the input for this routine .""" | from jcvi . utils . iter import pairwise
p = OptionParser ( breakpoint . __doc__ )
p . add_option ( "--diff" , default = .1 , type = "float" , help = "Maximum ratio of differences allowed [default: %default]" )
opts , args = p . parse_args ( args )
if len ( args ) != 1 :
sys . exit ( not p . print_help ( ) )
mstmap... |
def ip_hide_as_path_holder_as_path_access_list_seq_keyword ( self , ** kwargs ) :
"""Auto Generated Code""" | config = ET . Element ( "config" )
ip = ET . SubElement ( config , "ip" , xmlns = "urn:brocade.com:mgmt:brocade-common-def" )
hide_as_path_holder = ET . SubElement ( ip , "hide-as-path-holder" , xmlns = "urn:brocade.com:mgmt:brocade-ip-policy" )
as_path = ET . SubElement ( hide_as_path_holder , "as-path" )
access_list ... |
def validate_enum_attribute ( self , attribute : str , candidates : Set [ Union [ str , int , float ] ] ) -> None :
"""Validates that the attribute value is among the candidates""" | self . add_errors ( validate_enum_attribute ( self . fully_qualified_name , self . _spec , attribute , candidates ) ) |
def check_time_param ( t ) :
"""Check whether a string sent in matches the ISO8601 format . If a
Datetime object is passed instead , it will be converted into an ISO8601
compliant string .
: param t : the datetime to check
: type t : string or Datetime
: rtype : string""" | if type ( t ) is str :
if not ISO . match ( t ) :
raise ValueError ( 'Date string "%s" does not match ISO8601 format' % ( t ) )
return t
else :
return t . isoformat ( ) |
def create ( self , bundle , container_id = None , empty_process = False , log_path = None , pid_file = None , sync_socket = None , log_format = "kubernetes" ) :
'''use the client to create a container from a bundle directory . The bundle
directory should have a config . json . You must be the root user to
crea... | return self . _run ( bundle , container_id = container_id , empty_process = empty_process , log_path = log_path , pid_file = pid_file , sync_socket = sync_socket , command = "create" , log_format = log_format ) |
def quick_mapper ( table : Table ) -> Type [ DeclarativeMeta ] :
"""Makes a new SQLAlchemy mapper for an existing table .
See
http : / / www . tylerlesmann . com / 2009 / apr / 27 / copying - databases - across - platforms - sqlalchemy /
Args :
table : SQLAlchemy : class : ` Table ` object
Returns :
a :... | # noqa
# noinspection PyPep8Naming
Base = declarative_base ( )
class GenericMapper ( Base ) :
__table__ = table
# noinspection PyTypeChecker
return GenericMapper |
def Parse ( self , stat , unused_knowledge_base ) :
"""Parse the key currentcontrolset output .""" | value = stat . registry_data . GetValue ( )
if not str ( value ) . isdigit ( ) or int ( value ) > 999 or int ( value ) < 0 :
raise parser . ParseError ( "Invalid value for CurrentControlSet key %s" % value )
yield rdfvalue . RDFString ( "HKEY_LOCAL_MACHINE\\SYSTEM\\ControlSet%03d" % int ( value ) ) |
def eeg_name_frequencies ( freqs ) :
"""Name frequencies according to standart classifications .
Parameters
freqs : list or numpy . array
list of floats containing frequencies to classify .
Returns
freqs _ names : list
Named frequencies
Example
> > > import neurokit as nk
> > > nk . eeg _ name _ f... | freqs = list ( freqs )
freqs_names = [ ]
for freq in freqs :
if freq < 1 :
freqs_names . append ( "UltraLow" )
elif freq <= 3 :
freqs_names . append ( "Delta" )
elif freq <= 7 :
freqs_names . append ( "Theta" )
elif freq <= 9 :
freqs_names . append ( "Alpha1/Mu" )
eli... |
def double_ell_distance ( mjr0 , mnr0 , pa0 , mjr1 , mnr1 , pa1 , dx , dy ) :
"""Given two ellipses separated by * dx * and * dy * , compute their separation in
terms of σ . Based on Pineau et al ( 2011A & A . . . 527A . 126P ) .
The " 0 " ellipse is taken to be centered at ( 0 , 0 ) , while the " 1"
ellipse ... | # 1 . We need to rotate the frame so that ellipse 1 lies on the X axis .
theta = - np . arctan2 ( dy , dx )
# 2 . We also need to express these rotated ellipses in " biv " format .
sx0 , sy0 , cxy0 = ellbiv ( mjr0 , mnr0 , pa0 + theta )
sx1 , sy1 , cxy1 = ellbiv ( mjr1 , mnr1 , pa1 + theta )
# 3 . Their convolution is ... |
def log_filenos ( log , cloexec = True ) :
"""Identify the filenos ( unix file descriptors ) of a logging object .
This is most commonly used to avoid closing the log file descriptors
after a fork so information can be logged before an exec ( ) .
To prevent conficts and potential hangs , the default is to set... | filenos = [ ]
try :
for handler in log . handlers :
for name in dir ( handler ) :
attr = getattr ( handler , name , None )
if attr and hasattr ( attr , 'fileno' ) and callable ( attr . fileno ) :
filenos . append ( attr . fileno ( ) )
for fd in filenos :
f... |
def compute ( self , config , budget , working_directory , * args , ** kwargs ) :
"""Simple example for a compute function using a feed forward network .
It is trained on the MNIST dataset .
The input parameter " config " ( dictionary ) contains the sampled configurations passed by the bohb optimizer""" | model = Sequential ( )
model . add ( Conv2D ( config [ 'num_filters_1' ] , kernel_size = ( 3 , 3 ) , activation = 'relu' , input_shape = self . input_shape ) )
model . add ( MaxPooling2D ( pool_size = ( 2 , 2 ) ) )
if config [ 'num_conv_layers' ] > 1 :
model . add ( Conv2D ( config [ 'num_filters_2' ] , kernel_size... |
def read ( self , path ) :
"""Read EPW weather data from path .
Args :
path ( str ) : path to read weather data from""" | with open ( path , "r" ) as f :
for line in f :
line = line . strip ( )
match_obj_name = re . search ( r"^([A-Z][A-Z/ \d]+)," , line )
if match_obj_name is not None :
internal_name = match_obj_name . group ( 1 )
if internal_name in self . _data :
self ... |
def LaplaceCentreWeight ( self ) :
"""Centre weighting matrix for TV Laplacian .""" | sz = [ 1 , ] * self . S . ndim
for ax in self . axes :
sz [ ax ] = self . S . shape [ ax ]
lcw = 2 * len ( self . axes ) * np . ones ( sz , dtype = self . dtype )
for ax in self . axes :
lcw [ ( slice ( None ) , ) * ax + ( [ 0 , - 1 ] , ) ] -= 1.0
return lcw |
def add_context ( self , name , cluster_name = None , user_name = None , namespace_name = None , ** attrs ) :
"""Add a context to config .""" | if self . context_exists ( name ) :
raise KubeConfError ( "context with the given name already exists." )
contexts = self . get_contexts ( )
# Add parameters .
new_context = { 'name' : name , 'context' : { } }
# Add attributes
attrs_ = new_context [ 'context' ]
if cluster_name is not None :
attrs_ [ 'cluster' ]... |
def Read ( self , timeout = None ) :
'''Reads the context menu
: param timeout : Optional . Any value other than None indicates a non - blocking read
: return :''' | if not self . Shown :
self . Shown = True
self . TrayIcon . show ( )
if timeout is None :
self . App . exec_ ( )
elif timeout == 0 :
self . App . processEvents ( )
else :
self . timer = start_systray_read_timer ( self , timeout )
self . App . exec_ ( )
if self . timer :
stop_timer ( ... |
def index ( ) :
"""Display list of the user ' s repositories .""" | github = GitHubAPI ( user_id = current_user . id )
token = github . session_token
ctx = dict ( connected = False )
if token : # The user is authenticated and the token we have is still valid .
if github . account . extra_data . get ( 'login' ) is None :
github . init_account ( )
db . session . commi... |
def coords_by_dimension ( self , dimensions = 3 ) :
"""Returns fitted coordinates in specified number of dimensions , and
the amount of variance explained )""" | coords_matrix = self . vecs [ : , : dimensions ]
varexp = self . cve [ dimensions - 1 ]
return coords_matrix , varexp |
def emit ( self , action , payload ) :
"""Emit action with payload via ` requests . post ` .""" | url = self . get_emit_api ( action )
headers = { 'User-Agent' : 'rio/%s' % VERSION , 'X-Rio-Protocol' : '1' , }
args = dict ( url = url , json = payload , headers = headers , timeout = self . timeout , )
resp = requests . post ( ** args )
data = resp . json ( )
is_success = resp . status_code == 200
result = dict ( is_... |
def carve ( self , freespace = True ) :
"""Call this method to carve the free space of the volume for ( deleted ) files . Note that photorec has its
own interface that temporarily takes over the shell .
: param freespace : indicates whether the entire volume should be carved ( False ) or only the free space ( T... | self . _make_mountpoint ( var_name = 'carve' , suffix = "carve" , in_paths = True )
# if no slot , we need to make a loopback that we can use to carve the volume
loopback_was_created_for_carving = False
if not self . slot :
if not self . loopback :
self . _find_loopback ( )
# Can ' t carve if volume... |
def serial_udb_extra_f8_encode ( self , sue_HEIGHT_TARGET_MAX , sue_HEIGHT_TARGET_MIN , sue_ALT_HOLD_THROTTLE_MIN , sue_ALT_HOLD_THROTTLE_MAX , sue_ALT_HOLD_PITCH_MIN , sue_ALT_HOLD_PITCH_MAX , sue_ALT_HOLD_PITCH_HIGH ) :
'''Backwards compatible version of SERIAL _ UDB _ EXTRA F8 : format
sue _ HEIGHT _ TARGET _ ... | return MAVLink_serial_udb_extra_f8_message ( sue_HEIGHT_TARGET_MAX , sue_HEIGHT_TARGET_MIN , sue_ALT_HOLD_THROTTLE_MIN , sue_ALT_HOLD_THROTTLE_MAX , sue_ALT_HOLD_PITCH_MIN , sue_ALT_HOLD_PITCH_MAX , sue_ALT_HOLD_PITCH_HIGH ) |
def get_provider_name ( driver ) :
"""Return the provider name from the driver class
: param driver : obj
: return : str""" | kls = driver . __class__ . __name__
for d , prop in DRIVERS . items ( ) :
if prop [ 1 ] == kls :
return d
return None |
def bivnorm ( sx , sy , cxy ) :
"""Given the parameters of a Gaussian bivariate distribution , compute the
correct normalization for the equivalent 2D Gaussian . It ' s 1 / ( 2 pi sqrt
( sx * * 2 sy * * 2 - cxy * * 2 ) . This function adds a lot of sanity checking .
Inputs :
* sx : standard deviation ( not ... | _bivcheck ( sx , sy , cxy )
from numpy import pi , sqrt
t = ( sx * sy ) ** 2 - cxy ** 2
if t <= 0 :
raise ValueError ( 'covariance just barely out of bounds ' '(sx=%.10e, sy=%.10e, cxy=%.10e, cxy/sxsy=%.16f)' % ( sx , sy , cxy , cxy / ( sx * sy ) ) )
return ( 2 * pi * sqrt ( t ) ) ** - 1 |
def _get_dense_tensor ( self , inputs , weight_collections = None , trainable = None ) :
"""Returns a ` Tensor ` .""" | del weight_collections
text_batch = tf . reshape ( inputs . get ( self ) , shape = [ - 1 ] )
m = module . Module ( self . module_spec , trainable = self . trainable and trainable )
return m ( text_batch ) |
def index_exists ( self , table : str , indexname : str ) -> bool :
"""Does an index exist ? ( Specific to MySQL . )""" | # MySQL :
sql = ( "SELECT COUNT(*) FROM information_schema.statistics" " WHERE table_name=? AND index_name=?" )
row = self . fetchone ( sql , table , indexname )
return True if row [ 0 ] >= 1 else False |
def parse ( self , rrstr ) : # type : ( bytes ) - > None
'''Parse a Rock Ridge Continuation Entry record out of a string .
Parameters :
rrstr - The string to parse the record out of .
Returns :
Nothing .''' | if self . _initialized :
raise pycdlibexception . PyCdlibInternalError ( 'CE record already initialized!' )
( su_len , su_entry_version_unused , bl_cont_area_le , bl_cont_area_be , offset_cont_area_le , offset_cont_area_be , len_cont_area_le , len_cont_area_be ) = struct . unpack_from ( '=BBLLLLLL' , rrstr [ : 28 ]... |
def _set_ecmp ( self , v , load = False ) :
"""Setter method for ecmp , mapped from YANG variable / rbridge _ id / fabric / ecmp ( container )
If this variable is read - only ( config : false ) in the
source YANG file , then _ set _ ecmp is considered as a private
method . Backends looking to populate this va... | if hasattr ( v , "_utype" ) :
v = v . _utype ( v )
try :
t = YANGDynClass ( v , base = ecmp . ecmp , is_container = 'container' , presence = False , yang_name = "ecmp" , rest_name = "ecmp" , parent = self , path_helper = self . _path_helper , extmethods = self . _extmethods , register_paths = True , extensions ... |
def _parse_symbol ( self , sym ) :
"""Parse a string with a symbol to extract a string representing an element .
Args :
sym ( str ) : A symbol to be parsed .
Returns :
A string with the parsed symbol . None if no parsing was possible .""" | # Common representations for elements / water in cif files
# TODO : fix inconsistent handling of water
special = { "Hw" : "H" , "Ow" : "O" , "Wat" : "O" , "wat" : "O" , "OH" : "" , "OH2" : "" , "NO3" : "N" }
parsed_sym = None
# try with special symbols , otherwise check the first two letters ,
# then the first letter a... |
def case_insensitive_update ( dct1 , dct2 ) :
"""Given two dicts , updates the first one with the second , but considers keys
that are identical except for case to be the same .
No return value ; this function modified dct1 similar to the update ( ) method .""" | lowkeys = dict ( [ ( key . lower ( ) , key ) for key in dct1 ] )
for key , val in dct2 . items ( ) :
d1_key = lowkeys . get ( key . lower ( ) , key )
dct1 [ d1_key ] = val |
def jsonify_assert ( asserted , message , status_code = 400 ) :
"""Asserts something is true , aborts the request if not .""" | if asserted :
return
try :
raise AssertionError ( message )
except AssertionError , e :
stack = traceback . extract_stack ( )
stack . pop ( )
logging . error ( 'Assertion failed: %s\n%s' , str ( e ) , '' . join ( traceback . format_list ( stack ) ) )
abort ( jsonify_error ( e , status_code = sta... |
def loadVectorsFromFile ( self , filename , cols = None , everyNrows = 1 , delim = ' ' , checkEven = 1 , patterned = 0 ) :
"""Deprecated .""" | fp = open ( filename , "r" )
line = fp . readline ( )
lineno = 0
lastLength = None
data = [ ]
while line :
if lineno % everyNrows == 0 :
if patterned :
linedata1 = [ x for x in line . strip ( ) . split ( delim ) ]
else :
linedata1 = [ float ( x ) for x in line . strip ( ) . s... |
def create_log_entry ( self , log_entry_form ) :
"""Creates a new ` ` LogEntry ` ` .
arg : log _ entry _ form ( osid . logging . LogEntryForm ) : the form for
this ` ` LogEntry ` `
return : ( osid . logging . LogEntry ) - the new ` ` LogEntry ` `
raise : IllegalState - ` ` log _ entry _ form ` ` already use... | collection = JSONClientValidated ( 'logging' , collection = 'LogEntry' , runtime = self . _runtime )
if not isinstance ( log_entry_form , ABCLogEntryForm ) :
raise errors . InvalidArgument ( 'argument type is not an LogEntryForm' )
if log_entry_form . is_for_update ( ) :
raise errors . InvalidArgument ( 'the Lo... |
def get_calendar ( self , calendar_id = None , calendar_name = None ) :
"""Returns a calendar by it ' s id or name
: param str calendar _ id : the calendar id to be retrieved .
: param str calendar _ name : the calendar name to be retrieved .
: return : calendar for the given info
: rtype : Calendar""" | if calendar_id and calendar_name :
raise RuntimeError ( 'Provide only one of the options' )
if not calendar_id and not calendar_name :
raise RuntimeError ( 'Provide one of the options' )
if calendar_id : # get calendar by it ' s id
url = self . build_url ( self . _endpoints . get ( 'get_calendar' ) . format... |
def oauth_logout_handler ( sender_app , user = None ) :
"""Remove all access tokens from session on logout .""" | oauth = current_app . extensions [ 'oauthlib.client' ]
for remote in oauth . remote_apps . values ( ) :
token_delete ( remote )
db . session . commit ( ) |
def get_language ( ) :
"""Return an active language code that is guaranteed to be in
settings . LANGUAGES ( Django does not seem to guarantee this for us ) .""" | lang = _get_language ( )
if lang is None : # Django > = 1.8
return settings . DEFAULT_LANGUAGE
if lang not in settings . AVAILABLE_LANGUAGES and '-' in lang :
lang = lang . split ( '-' ) [ 0 ]
if lang in settings . AVAILABLE_LANGUAGES :
return lang
return settings . DEFAULT_LANGUAGE |
def _cache ( self , key , val ) :
"""Request that a key / value pair be considered for caching .""" | cache_size = ( 1 if util . dimensionless_contents ( self . streams , self . kdims ) else self . cache_size )
if len ( self ) >= cache_size :
first_key = next ( k for k in self . data )
self . data . pop ( first_key )
self [ key ] = val |
def _parse_splits ( patch , splits ) :
"""Parse splits string to get list of all associated subset strings .
Parameters
patch : obj
Patch object containing data to subset
splits : str
Specifies how a column of a dataset should be split . See Notes .
Returns
list
List of subset strings derived from s... | split_list = splits . replace ( ' ' , '' ) . split ( ';' )
subset_list = [ ]
# List of all subset strings
for split in split_list :
col , val = split . split ( ':' )
if val == 'split' :
uniques = [ ]
for level in patch . table [ col ] :
if level not in uniques :
uniqu... |
def set_cloexec ( fd ) :
"""Set the file descriptor ` fd ` to automatically close on
: func : ` os . execve ` . This has no effect on file descriptors inherited across
: func : ` os . fork ` , they must be explicitly closed through some other means ,
such as : func : ` mitogen . fork . on _ fork ` .""" | flags = fcntl . fcntl ( fd , fcntl . F_GETFD )
assert fd > 2
fcntl . fcntl ( fd , fcntl . F_SETFD , flags | fcntl . FD_CLOEXEC ) |
def get_composite_field_value ( self , name ) :
"""Return the form / formset instance for the given field name .""" | field = self . composite_fields [ name ]
if hasattr ( field , 'get_form' ) :
return self . forms [ name ]
if hasattr ( field , 'get_formset' ) :
return self . formsets [ name ] |
def xpath ( self , query ) :
"""Run Xpath expression and parse the resulting elements . Don ' t forget to use the FoLiA namesapace in your expressions , using folia : or the short form f :""" | for result in self . tree . xpath ( query , namespaces = { 'f' : 'http://ilk.uvt.nl/folia' , 'folia' : 'http://ilk.uvt.nl/folia' } ) :
yield self . parsexml ( result ) |
def get_connection_id ( self , conn_or_int_id ) :
"""Get the connection id .
Args :
conn _ or _ int _ id ( int , string ) : The external integer connection id or
and internal string connection id
Returns :
dict : The context data associated with that connection or None if it cannot
be found .
Raises :... | key = conn_or_int_id
if isinstance ( key , str ) :
table = self . _int_connections
elif isinstance ( key , int ) :
table = self . _connections
else :
raise ArgumentError ( "You must supply either an int connection id or a string internal id to _get_connection_state" , id = key )
try :
data = table [ key... |
def generate_report ( self , components , output_folder = None , iface = None , ordered_layers_uri = None , legend_layers_uri = None , use_template_extent = False ) :
"""Generate Impact Report independently by the Impact Function .
: param components : Report components to be generated .
: type components : lis... | # iface set up , in case IF run from test
if not iface :
iface = IFACE
error_code = None
message = None
population_found = False
population_impact_function = None
for impact_function in self . impact_functions :
exposure_keywords = impact_function . provenance [ 'exposure_keywords' ]
exposure_type = definit... |
def validCtxtNormalizeAttributeValue ( self , doc , elem , name , value ) :
"""Does the validation related extra step of the normalization
of attribute values : If the declared value is not CDATA ,
then the XML processor must further process the normalized
attribute value by discarding any leading and trailin... | if doc is None :
doc__o = None
else :
doc__o = doc . _o
if elem is None :
elem__o = None
else :
elem__o = elem . _o
ret = libxml2mod . xmlValidCtxtNormalizeAttributeValue ( self . _o , doc__o , elem__o , name , value )
return ret |
def _add_vertex_attributes_by_genes ( self , genes : List [ Gene ] ) -> None :
"""Assign values to attributes on vertices .
: param genes : A list of Gene objects from which values will be extracted .""" | for gene in genes :
try :
vertex = self . graph . vs . find ( name = str ( gene . entrez_id ) ) . index
self . graph . vs [ vertex ] [ 'l2fc' ] = gene . log2_fold_change
self . graph . vs [ vertex ] [ 'symbol' ] = gene . symbol
self . graph . vs [ vertex ] [ 'padj' ] = gene . padj
... |
def _fetchAllChildren ( self ) :
"""Fetches all sub groups and variables that this group contains .""" | assert self . _ncGroup is not None , "dataset undefined (file not opened?)"
assert self . canFetchChildren ( ) , "canFetchChildren must be True"
childItems = [ ]
# Add dimensions
for dimName , ncDim in self . _ncGroup . dimensions . items ( ) :
childItems . append ( NcdfDimensionRti ( ncDim , nodeName = dimName , f... |
def sort ( self ) :
"""Consolidate adjacent lines , if same commit ID .
Will modify line number to be a range , when two or more lines with the
same commit ID .""" | self . sorted_commits = [ ]
if not self . commits :
return self . sorted_commits
prev_commit = self . commits . pop ( 0 )
prev_line = prev_commit . line_number
prev_uuid = prev_commit . uuid
for commit in self . commits :
if ( commit . uuid != prev_uuid or commit . line_number != ( prev_line + 1 ) ) :
p... |
def unpack ( regex ) :
"""Remove the outermost parens , keep the ( ? P . . . ) one
> > > unpack ( r ' ( abc ) ' )
' abc '
> > > unpack ( r ' ( ? : abc ) ' )
' abc '
> > > unpack ( r ' ( ? P < xyz > abc ) ' )
' ( ? P < xyz > abc ) '
> > > unpack ( r ' [ abc ] ' )
' [ abc ] '""" | if is_packed ( regex ) and not regex . startswith ( '(?P<' ) :
return re . sub ( r'^\((\?:)?(?P<content>.*?)\)$' , r'\g<content>' , regex )
else :
return regex |
def remove_bond ( self , particle_pair ) :
"""Deletes a bond between a pair of Particles
Parameters
particle _ pair : indexable object , length = 2 , dtype = mb . Compound
The pair of Particles to remove the bond between""" | from mbuild . port import Port
if self . root . bond_graph is None or not self . root . bond_graph . has_edge ( * particle_pair ) :
warn ( "Bond between {} and {} doesn't exist!" . format ( * particle_pair ) )
return
self . root . bond_graph . remove_edge ( * particle_pair )
bond_vector = particle_pair [ 0 ] . ... |
def create_jinja_environment ( self ) :
"""Creates the Jinja2 environment based on : attr : ` jinja _ options `
and : meth : ` select _ jinja _ autoescape ` . Since 0.7 this also adds
the Jinja2 globals and filters after initialization . Override
this function to customize the behavior .""" | options = dict ( self . jinja_options )
if 'autoescape' not in options :
options [ 'autoescape' ] = self . select_jinja_autoescape
rv = SandboxedEnvironment ( self , ** options )
rv . globals . update ( url_for = url_for , get_flashed_messages = get_flashed_messages , config = self . config , # FIXME : Sandboxed te... |
def _check_preferences ( prefs , pref_type = None ) :
"""Check cipher , digest , and compression preference settings .
MD5 is not allowed . This is ` not 1994 ` _ _ . SHA1 is allowed _ grudgingly _ .
_ _ http : / / www . cs . colorado . edu / ~ jrblack / papers / md5e - full . pdf
. . _ allowed : http : / / e... | if prefs is None :
return
cipher = frozenset ( [ 'AES256' , 'AES192' , 'AES128' , 'CAMELLIA256' , 'CAMELLIA192' , 'TWOFISH' , '3DES' ] )
digest = frozenset ( [ 'SHA512' , 'SHA384' , 'SHA256' , 'SHA224' , 'RMD160' , 'SHA1' ] )
compress = frozenset ( [ 'BZIP2' , 'ZLIB' , 'ZIP' , 'Uncompressed' ] )
trust = frozenset (... |
async def change_mode ( self , area , new_mode ) :
"""Set / unset / part set an area .""" | if not isinstance ( new_mode , AreaMode ) :
raise TypeError ( "new_mode must be an AreaMode" )
AREA_MODE_COMMAND_MAP = { AreaMode . UNSET : 'unset' , AreaMode . PART_SET_A : 'set_a' , AreaMode . PART_SET_B : 'set_b' , AreaMode . FULL_SET : 'set' }
if isinstance ( area , Area ) :
area_id = area . id
else :
a... |
def _submit ( self ) :
'''submit a uservoice ticket . When we get here we should have :
{ ' user _ prompt _ issue ' : ' I want to do the thing . ' ,
' record _ asciinema ' : ' / tmp / helpme . 93o _ _ nt5 . json ' ,
' record _ environment ' : ( ( 1,1 ) , ( 2,2 ) . . . ( N , N ) ) }
Required Client Variables... | # Step 0 : Authenticate with uservoice API
self . authenticate ( )
title = "HelpMe UserVoice Ticket: %s" % ( self . run_id )
body = self . data [ 'user_prompt_issue' ]
# Step 1 : Environment
envars = self . data . get ( 'record_environment' )
if envars not in [ None , '' , [ ] ] :
body += '\n\nEnvironment:\n'
f... |
def subprogram_signature ( vo , fullname = None ) :
'''Generate a signature string
Args :
vo ( VhdlFunction , VhdlProcedure ) : Subprogram object
Returns :
Signature string .''' | if fullname is None :
fullname = vo . name
if isinstance ( vo , VhdlFunction ) :
plist = ',' . join ( p . data_type for p in vo . parameters )
sig = '{}[{} return {}]' . format ( fullname , plist , vo . return_type )
else : # procedure
plist = ',' . join ( p . data_type for p in vo . parameters )
si... |
def set_probe_file_name ( self , checked ) :
"""sets the filename to which the probe logging function will write
Args :
checked : boolean ( True : opens file ) ( False : closes file )""" | if checked :
file_name = os . path . join ( self . gui_settings [ 'probes_log_folder' ] , '{:s}_probes.csv' . format ( datetime . datetime . now ( ) . strftime ( '%y%m%d-%H_%M_%S' ) ) )
if os . path . isfile ( file_name ) == False :
self . probe_file = open ( file_name , 'a' )
new_values = self ... |
def initialize ( self ) :
"""Initializes important node values to zero for each node in the
layer ( target , error , activation , dbias , delta , netinput , bed ) .""" | self . randomize ( )
self . dweight = Numeric . zeros ( self . size , 'f' )
self . delta = Numeric . zeros ( self . size , 'f' )
self . wed = Numeric . zeros ( self . size , 'f' )
self . wedLast = Numeric . zeros ( self . size , 'f' )
self . target = Numeric . zeros ( self . size , 'f' )
self . error = Numeric . zeros ... |
def make_tarball ( tarball_fname , directory , cwd = None ) :
"create a tarball from a directory" | if tarball_fname . endswith ( '.gz' ) :
opts = 'czf'
else :
opts = 'cf'
args = [ '/bin/tar' , opts , tarball_fname , directory ]
process_command ( args , cwd = cwd ) |
def setiddname ( cls , iddname , testing = False ) :
"""Set the path to the EnergyPlus IDD for the version of EnergyPlus which
is to be used by eppy .
Parameters
iddname : str
Path to the IDD file .
testing : bool
Flag to use if running tests since we may want to ignore the
` IDDAlreadySetError ` .
... | if cls . iddname == None :
cls . iddname = iddname
cls . idd_info = None
cls . block = None
elif cls . iddname == iddname :
pass
else :
if testing == False :
errortxt = "IDD file is set to: %s" % ( cls . iddname , )
raise IDDAlreadySetError ( errortxt ) |
def _infer_binary_operation ( left , right , binary_opnode , context , flow_factory ) :
"""Infer a binary operation between a left operand and a right operand
This is used by both normal binary operations and augmented binary
operations , the only difference is the flow factory used .""" | context , reverse_context = _get_binop_contexts ( context , left , right )
left_type = helpers . object_type ( left )
right_type = helpers . object_type ( right )
methods = flow_factory ( left , left_type , binary_opnode , right , right_type , context , reverse_context )
for method in methods :
try :
result... |
def _check_outcome_validity ( self , check_outcome ) :
"""Checks the validity of an outcome
Checks whether the id or the name of the outcome is already used by another outcome within the state .
: param rafcon . core . logical _ port . Outcome check _ outcome : The outcome to be checked
: return bool validity... | for outcome_id , outcome in self . outcomes . items ( ) : # Do not compare outcome with itself when checking for existing name / id
if check_outcome is not outcome :
if check_outcome . outcome_id == outcome_id :
return False , "outcome id '{0}' existing in state" . format ( check_outcome . outco... |
def add ( self , dimlist , dimvalues ) :
'''add dimensions
: parameter dimlist : list of dimensions
: parameter dimvalues : list of values for dimlist''' | for i , d in enumerate ( dimlist ) :
self [ d ] = dimvalues [ i ]
self . set_ndims ( ) |
def join_configs ( configs ) :
"""Join all config files into one config .""" | joined_config = { }
for config in configs :
joined_config . update ( yaml . load ( config ) )
return joined_config |
def is_same_host ( self , url ) :
"""Check if the given ` ` url ` ` is a member of the same host as this
connection pool .""" | if url . startswith ( '/' ) :
return True
# TODO : Add optional support for socket . gethostbyname checking .
scheme , host , port = get_host ( url )
host = _ipv6_host ( host ) . lower ( )
# Use explicit default port for comparison when none is given
if self . port and not port :
port = port_by_scheme . get ( s... |
def create_storage_container ( kwargs = None , storage_conn = None , call = None ) :
'''. . versionadded : : 2015.8.0
Create a storage container
CLI Example :
. . code - block : : bash
salt - cloud - f create _ storage _ container my - azure name = mycontainer
name :
Name of container to create .
meta... | if call != 'function' :
raise SaltCloudSystemExit ( 'The create_storage_container function must be called with -f or --function.' )
if not storage_conn :
storage_conn = get_storage_conn ( conn_kwargs = kwargs )
try :
storage_conn . create_container ( container_name = kwargs [ 'name' ] , x_ms_meta_name_value... |
def buff_internal_eval ( params ) :
"""Builds and evaluates BUFF internal energy of a model in parallelization
Parameters
params : list
Tuple containing the specification to be built , the sequence
and the parameters for model building .
Returns
model . bude _ score : float
BUFF internal energy score ... | specification , sequence , parsed_ind = params
model = specification ( * parsed_ind )
model . build ( )
model . pack_new_sequences ( sequence )
return model . buff_internal_energy . total_energy |
async def fromURL ( cls , url , * , credentials = None , insecure = False ) :
"""Return a ` SessionAPI ` for a given MAAS instance .""" | try :
description = await helpers . fetch_api_description ( url , insecure = insecure )
except helpers . RemoteError as error : # For now just re - raise as SessionError .
raise SessionError ( str ( error ) )
else :
session = cls ( description , credentials )
session . insecure = insecure
return ses... |
def assure_check ( fnc ) :
"""Converts an checkID passed as the check to a CloudMonitorCheck object .""" | @ wraps ( fnc )
def _wrapped ( self , check , * args , ** kwargs ) :
if not isinstance ( check , CloudMonitorCheck ) : # Must be the ID
check = self . _check_manager . get ( check )
return fnc ( self , check , * args , ** kwargs )
return _wrapped |
def _preprocess_movie_lens ( ratings_df ) :
"""Separate the rating datafram into train and test sets .
Filters out users with less than two distinct timestamps . Creates train set
and test set . The test set contains all the last interactions of users with
more than two distinct timestamps .
Args :
rating... | ratings_df [ "data" ] = 1.0
num_timestamps = ratings_df [ [ "userId" , "timestamp" ] ] . groupby ( "userId" ) . nunique ( )
last_user_timestamp = ratings_df [ [ "userId" , "timestamp" ] ] . groupby ( "userId" ) . max ( )
ratings_df [ "numberOfTimestamps" ] = ratings_df [ "userId" ] . apply ( lambda x : num_timestamps [... |
def getargs ( ) :
"""Return a list of valid arguments .""" | parser = argparse . ArgumentParser ( description = 'Python Disk Usage Calculator.' )
parser . add_argument ( "path" , type = chkpath , nargs = '?' , default = "." , help = "A valid path." )
return parser . parse_args ( ) |
def getCitations ( self , field = None , values = None , pandasFriendly = True , counts = True ) :
"""Creates a pandas ready dict with each row a different citation the contained Records and columns containing the original string , year , journal , author ' s name and the number of times it occured .
There are al... | retCites = [ ]
if values is not None :
if isinstance ( values , ( str , int , float ) ) or not isinstance ( values , collections . abc . Container ) :
values = [ values ]
for R in self :
retCites += R . getCitations ( field = field , values = values , pandasFriendly = False )
if pandasFriendly :
ret... |
def headerData ( self , section , orientation , role ) :
"""Returns the header for a section ( row or column depending on orientation ) .
Reimplemented from QAbstractTableModel to make the headers start at 0.""" | if role == QtCore . Qt . DisplayRole :
if orientation == Qt . Horizontal :
return self . attrNames [ section ]
else :
return str ( section )
else :
return None |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.