signature stringlengths 29 44.1k | implementation stringlengths 0 85.2k |
|---|---|
def namespaces ( ** kwargs ) :
'''Return the names of the available namespaces
CLI Examples : :
salt ' * ' kubernetes . namespaces
salt ' * ' kubernetes . namespaces kubeconfig = / etc / salt / k8s / kubeconfig context = minikube''' | cfg = _setup_conn ( ** kwargs )
try :
api_instance = kubernetes . client . CoreV1Api ( )
api_response = api_instance . list_namespace ( )
return [ nms [ 'metadata' ] [ 'name' ] for nms in api_response . to_dict ( ) . get ( 'items' ) ]
except ( ApiException , HTTPError ) as exc :
if isinstance ( exc , Ap... |
def _to_dict ( self ) :
"""Return a json dictionary representing this model .""" | _dict = { }
if hasattr ( self , 'configuration_id' ) and self . configuration_id is not None :
_dict [ 'configuration_id' ] = self . configuration_id
if hasattr ( self , 'status' ) and self . status is not None :
_dict [ 'status' ] = self . status
if hasattr ( self , 'notices' ) and self . notices is not None :... |
def set_metadata_index_and_column_names ( dim , meta_df ) :
"""Sets index and column names to GCTX convention .
Input :
- dim ( str ) : Dimension of metadata to read . Must be either " row " or " col "
- meta _ df ( pandas . DataFrame ) : data frame corresponding to metadata fields
of dimension specified . ... | if dim == "row" :
meta_df . index . name = "rid"
meta_df . columns . name = "rhd"
elif dim == "col" :
meta_df . index . name = "cid"
meta_df . columns . name = "chd" |
def send_message ( msg : 'EFBMsg' ) -> Optional [ 'EFBMsg' ] :
"""Deliver a message to the destination channel .
Args :
msg ( EFBMsg ) : The message
Returns :
The message sent by the destination channel ,
includes the updated message ID from there .
Returns ` ` None ` ` if the message is not sent .""" | global middlewares , master , slaves
if msg is None :
return
# Go through middlewares
for i in middlewares :
m = i . process_message ( msg )
if m is None :
return None
# for mypy type check
assert m is not None
msg = m
msg . verify ( )
if msg . deliver_to . channel_id == master . channel... |
def label ( self , input_grid ) :
"""Labels input grid using enhanced watershed algorithm .
Args :
input _ grid ( numpy . ndarray ) : Grid to be labeled .
Returns :
Array of labeled pixels""" | marked = self . find_local_maxima ( input_grid )
marked = np . where ( marked >= 0 , 1 , 0 )
# splabel returns two things in a tuple : an array and an integer
# assign the first thing ( array ) to markers
markers = splabel ( marked ) [ 0 ]
return markers |
def _ExtractGMailSearchQuery ( self , url ) :
"""Extracts a search query from a GMail search URL .
GMail : https : / / mail . google . com / mail / u / 0 / # search / query [ / ? ]
Args :
url ( str ) : URL .
Returns :
str : search query or None if no query was found .""" | if 'search/' not in url :
return None
_ , _ , line = url . partition ( 'search/' )
line , _ , _ = line . partition ( '/' )
line , _ , _ = line . partition ( '?' )
return line . replace ( '+' , ' ' ) |
def get_unpack_filter ( cls , unpackable_target ) :
"""Calculate a filter function from the include / exclude patterns of a Target .
: param ImportRemoteSourcesMixin unpackable _ target : A target with include _ patterns and
exclude _ patterns attributes .""" | # TODO : we may be able to make use of glob matching in the engine to avoid doing this filtering .
return cls . _calculate_unpack_filter ( includes = unpackable_target . payload . include_patterns , excludes = unpackable_target . payload . exclude_patterns , spec = unpackable_target . address . spec ) |
def select_grid_model_residential ( lvgd ) :
"""Selects typified model grid based on population
Parameters
lvgd : LVGridDistrictDing0
Low - voltage grid district object
Returns
: pandas : ` pandas . DataFrame < dataframe > `
Selected string of typified model grid
: pandas : ` pandas . DataFrame < data... | # Load properties of LV typified model grids
string_properties = lvgd . lv_grid . network . static_data [ 'LV_model_grids_strings' ]
# Load relational table of apartment count and strings of model grid
apartment_string = lvgd . lv_grid . network . static_data [ 'LV_model_grids_strings_per_grid' ]
# load assumtions
apar... |
def mtz2tw ( n , c , e , l ) :
"""mtz : model for the traveling salesman problem with time windows
( based on Miller - Tucker - Zemlin ' s one - index potential formulation , stronger constraints )
Parameters :
- n : number of nodes
- c [ i , j ] : cost for traversing arc ( i , j )
- e [ i ] : earliest da... | model = Model ( "tsptw - mtz-strong" )
x , u = { } , { }
for i in range ( 1 , n + 1 ) :
u [ i ] = model . addVar ( lb = e [ i ] , ub = l [ i ] , vtype = "C" , name = "u(%s)" % i )
for j in range ( 1 , n + 1 ) :
if i != j :
x [ i , j ] = model . addVar ( vtype = "B" , name = "x(%s,%s)" % ( i ... |
def refactor_dir ( self , dir_name , write = False , doctests_only = False ) :
"""Descends down a directory and refactor every Python file found .
Python files are assumed to have a . py extension .
Files and subdirectories starting with ' . ' are skipped .""" | py_ext = os . extsep + "py"
for dirpath , dirnames , filenames in os . walk ( dir_name ) :
self . log_debug ( "Descending into %s" , dirpath )
dirnames . sort ( )
filenames . sort ( )
for name in filenames :
if ( not name . startswith ( "." ) and os . path . splitext ( name ) [ 1 ] == py_ext ) :... |
def mergeGraphs ( targetGraph , addedGraph , incrementedNodeVal = 'count' , incrementedEdgeVal = 'weight' ) :
"""A quick way of merging graphs , this is meant to be quick and is only intended for graphs generated by metaknowledge . This does not check anything and as such may cause unexpected results if the source ... | for addedNode , attribs in addedGraph . nodes ( data = True ) :
if incrementedNodeVal :
try :
targetGraph . node [ addedNode ] [ incrementedNodeVal ] += attribs [ incrementedNodeVal ]
except KeyError :
targetGraph . add_node ( addedNode , ** attribs )
else :
if no... |
def _read_23andme ( file ) :
"""Read and parse 23andMe file .
https : / / www . 23andme . com
Parameters
file : str
path to file
Returns
pandas . DataFrame
individual ' s genetic data normalized for use with ` lineage `
str
name of data source""" | df = pd . read_csv ( file , comment = "#" , sep = "\t" , na_values = "--" , names = [ "rsid" , "chrom" , "pos" , "genotype" ] , index_col = 0 , dtype = { "chrom" : object } , )
return sort_snps ( df ) , "23andMe" |
def SelectComponent ( ds , idxs ) :
"""Select / reorder components from datapoints .
Args :
ds ( DataFlow ) : input DataFlow .
idxs ( list [ int ] ) : a list of component indices .
Example :
. . code - block : : none
original df produces : [ c1 , c2 , c3]
idxs : [ 2,1]
this df : [ c3 , c2]""" | return MapData ( ds , lambda dp : [ dp [ i ] for i in idxs ] ) |
def instruction_BSR_JSR ( self , opcode , ea ) :
"""Program control is transferred to the effective address after storing
the return address on the hardware stack .
A return from subroutine ( RTS ) instruction is used to reverse this
process and must be the last instruction executed in a subroutine .
source... | # log . info ( " % x | \ tJSR / BSR to $ % x \ t | % s " % (
# self . last _ op _ address ,
# ea , self . cfg . mem _ info . get _ shortest ( ea )
self . push_word ( self . system_stack_pointer , self . program_counter . value )
self . program_counter . set ( ea ) |
def dumps ( self , format = "local" ) :
"""Dumps the content in standard metadata format or the pysaml2 metadata
format
: param format : Which format to dump in
: return : a string""" | if format == "local" :
res = EntitiesDescriptor ( )
for _md in self . metadata . values ( ) :
try :
res . entity_descriptor . extend ( _md . entities_descr . entity_descriptor )
except AttributeError :
res . entity_descriptor . append ( _md . entity_descr )
return "%s... |
def predict ( self , dataset , output_type = 'cluster_id' , verbose = True ) :
"""Return predicted cluster label for instances in the new ' dataset ' .
K - means predictions are made by assigning each new instance to the
closest cluster center .
Parameters
dataset : SFrame
Dataset of new observations . Mu... | # # Validate the input dataset .
_tkutl . _raise_error_if_not_sframe ( dataset , "dataset" )
_tkutl . _raise_error_if_sframe_empty ( dataset , "dataset" )
# # Validate the output type .
if not isinstance ( output_type , str ) :
raise TypeError ( "The 'output_type' parameter must be a string." )
if not output_type i... |
def create_config_tree ( config , modules , prefix = '' ) :
'''Cause every possible configuration sub - dictionary to exist .
This is intended to be called very early in the configuration
sequence . For each module , it checks that the corresponding
configuration item exists in ` config ` and creates it as an... | def work_in ( parent_config , config_name , prefix , module ) :
if config_name not in parent_config : # this is the usual , expected case
parent_config [ config_name ] = { }
elif not isinstance ( parent_config [ config_name ] , collections . Mapping ) :
raise ConfigurationError ( '{0} must be an... |
def _jsonify ( x ) :
"""Use most compact form of JSON""" | if isinstance ( x , dict_class ) :
return json . dumps ( x . _d , separators = ( ',' , ':' ) )
return json . dumps ( x , separators = ( ',' , ':' ) ) |
def list ( self ) :
"""Lists already deployed lambdas""" | for function in self . client . list_functions ( ) . get ( 'Functions' , [ ] ) :
lines = json . dumps ( function , indent = 4 , sort_keys = True ) . split ( '\n' )
for line in lines :
logger . info ( line ) |
def setVisible ( self , state ) :
"""Handles the visibility operation for this dialog .
: param state | < bool >""" | super ( XViewProfileDialog , self ) . setVisible ( state )
if ( state ) :
self . activateWindow ( )
self . uiNameTXT . setFocus ( )
self . uiNameTXT . selectAll ( ) |
def print_result_from_timeit ( stmt = 'pass' , setup = 'pass' , number = 1000000 ) :
"""Clean function to know how much time took the execution of one statement""" | units = [ "s" , "ms" , "us" , "ns" ]
duration = timeit ( stmt , setup , number = int ( number ) )
avg_duration = duration / float ( number )
thousands = int ( math . floor ( math . log ( avg_duration , 1000 ) ) )
print ( "Total time: %fs. Average run: %.3f%s." % ( duration , avg_duration * ( 1000 ** - thousands ) , uni... |
def normalize_node ( node , headers = None ) :
"""Normalizes given node as str or dict with headers""" | headers = { } if headers is None else headers
if isinstance ( node , str ) :
url = normalize_url ( node )
return { 'endpoint' : url , 'headers' : headers }
url = normalize_url ( node [ 'endpoint' ] )
node_headers = node . get ( 'headers' , { } )
return { 'endpoint' : url , 'headers' : { ** headers , ** node_hea... |
def send_email ( self ) :
"""send email notification according to user settings""" | # send only if user notification setting is set to true
if self . check_user_settings ( ) :
send_mail ( _ ( self . type ) , self . email_message , settings . DEFAULT_FROM_EMAIL , [ self . to_user . email ] )
return True
else : # return false otherwise
return False |
def _linux_gpu_data ( ) :
'''num _ gpus : int
gpus :
- vendor : nvidia | amd | ati | . . .
model : string''' | if __opts__ . get ( 'enable_lspci' , True ) is False :
return { }
if __opts__ . get ( 'enable_gpu_grains' , True ) is False :
return { }
lspci = salt . utils . path . which ( 'lspci' )
if not lspci :
log . debug ( 'The `lspci` binary is not available on the system. GPU grains ' 'will not be available.' )
... |
def argsort ( self , axis = - 1 , kind = "quicksort" , order = None ) :
"""Returns the indices that would sort the array .
See the documentation of ndarray . argsort for details about the keyword
arguments .
Example
> > > from unyt import km
> > > data = [ 3 , 8 , 7 ] * km
> > > print ( np . argsort ( d... | return self . view ( np . ndarray ) . argsort ( axis , kind , order ) |
def runner ( self ) :
"""Run the necessary methods in the correct order""" | logging . info ( 'Starting {} analysis pipeline' . format ( self . analysistype ) )
if not self . pipeline :
general = None
for sample in self . runmetadata . samples :
general = getattr ( sample , 'general' )
if general is None : # Create the objects to be used in the analyses
objects = Obj... |
def jquery_js ( version = None , migrate = False ) :
'''A shortcut to render a ` ` script ` ` tag for the packaged jQuery''' | version = version or settings . JQUERY_VERSION
suffix = '.min' if not settings . DEBUG else ''
libs = [ js_lib ( 'jquery-%s%s.js' % ( version , suffix ) ) ]
if _boolean ( migrate ) :
libs . append ( js_lib ( 'jquery-migrate-%s%s.js' % ( JQUERY_MIGRATE_VERSION , suffix ) ) )
return '\n' . join ( libs ) |
def resetToDefault ( self , resetChildren = True ) :
"""Resets the data to the default data . By default the children will be reset as well""" | self . data = self . defaultData
if resetChildren :
for child in self . childItems :
child . resetToDefault ( resetChildren = True ) |
def overwhitened_data ( self , delta_f ) :
"""Return overwhitened data
Parameters
delta _ f : float
The sample step to generate overwhitened frequency domain data for
Returns
htilde : FrequencySeries
Overwhited strain data""" | # we haven ' t already computed htilde for this delta _ f
if delta_f not in self . segments :
buffer_length = int ( 1.0 / delta_f )
e = len ( self . strain )
s = int ( e - buffer_length * self . sample_rate - self . reduced_pad * 2 )
fseries = make_frequency_series ( self . strain [ s : e ] )
# we h... |
def to_gzipped_file ( data , out = None ) :
"""Pack ` data ` to GZIP and write them to ` out ` . If ` out ` is not defined ,
: mod : ` stringio ` is used .
Args :
data ( obj ) : Any packable data ( str / unicode / whatever ) .
out ( file , default None ) : Optional opened file handler .
Returns :
obj : ... | if not out :
out = StringIO . StringIO ( )
with gzip . GzipFile ( fileobj = out , mode = "w" ) as f :
f . write ( data )
out . seek ( 0 )
return out |
def write_discrete_trajectory ( filename , dtraj ) :
r"""Write discrete trajectory to ascii file .
The discrete trajectory is written to a
single column ascii file with integer entries
Parameters
filename : str
The filename of the discrete state trajectory file .
The filename can either contain the full... | dtraj = np . asarray ( dtraj )
with open ( filename , 'w' ) as f :
dtraj . tofile ( f , sep = '\n' , format = '%d' ) |
def Parse ( self , stat , file_object , knowledge_base ) :
"""Parse the netgroup file and return User objects .
Lines are of the form :
group1 ( - , user1 , ) ( - , user2 , ) ( - , user3 , )
Groups are ignored , we return users in lines that match the filter regexes ,
or all users in the file if no filters ... | _ , _ = stat , knowledge_base
lines = [ l . strip ( ) for l in utils . ReadFileBytesAsUnicode ( file_object ) . splitlines ( ) ]
return self . ParseLines ( lines ) |
def _compute_asset_ids ( cls , inputs , marker_output_index , outputs , asset_quantities ) :
"""Computes the asset IDs of every output in a transaction .
: param list [ TransactionOutput ] inputs : The outputs referenced by the inputs of the transaction .
: param int marker _ output _ index : The position of th... | # If there are more items in the asset quantities list than outputs in the transaction ( excluding the
# marker output ) , the marker output is deemed invalid
if len ( asset_quantities ) > len ( outputs ) - 1 :
return None
# If there is no input in the transaction , the marker output is always invalid
if len ( inpu... |
def keys ( self , prefix = None , delimiter = None ) :
""": param prefix : NOT A STRING PREFIX , RATHER PATH ID PREFIX ( MUST MATCH TO NEXT " . " OR " : " )
: param delimiter : TO GET Prefix OBJECTS , RATHER THAN WHOLE KEYS
: return : SET OF KEYS IN BUCKET , OR""" | if delimiter : # WE REALLY DO NOT GET KEYS , BUT RATHER Prefix OBJECTS
# AT LEAST THEY ARE UNIQUE
candidates = [ k . name . rstrip ( delimiter ) for k in self . bucket . list ( prefix = prefix , delimiter = delimiter ) ]
else :
candidates = [ strip_extension ( k . key ) for k in self . bucket . list ( prefix = ... |
def within_hull ( point , hull ) :
'''Return true if the point is within the convex hull''' | h_prev_pt = hull [ - 1 , : ]
for h_pt in hull :
if np . cross ( h_pt - h_prev_pt , point - h_pt ) >= 0 :
return False
h_prev_pt = h_pt
return True |
def group_associations_types ( self , main_type , sub_type , unique_id , target , api_branch = None , api_entity = None , owner = None , params = None , ) :
"""Args :
owner :
main _ type :
sub _ type :
unique _ id :
target :
api _ branch :
api _ entity :
params :
Return :""" | params = params or { }
if owner :
params [ 'owner' ] = owner
api_branch = api_branch or target . api_sub_type
api_entity = api_entity or target . api_entity
if not sub_type :
url = '/v2/{}/{}/groups/{}' . format ( main_type , unique_id , api_branch )
else :
url = '/v2/{}/{}/{}/groups/{}' . format ( main_typ... |
def with_connection ( func , self , * args , ** argd ) :
"""with _ connection : decorator ; make sure that there is a connection available
for action . Set the connections ' last _ used ' attribute to current timestamp .
We always get a fresh connection from the CONNECTION REGISTRY since the
' extras ' could ... | self . connection = self . get_connection ( )
self . connection . last_used = time . time ( )
self . connection . pre_call_hook ( self , func )
return func ( self , * args , ** argd ) |
def libs ( args ) :
"""% prog libs libfile
Get list of lib _ ids to be run by pull ( ) . The SQL commands :
select library . lib _ id , library . name from library join bac on
library . bac _ id = bac . id where bac . lib _ name = " Medicago " ;
select seq _ name from sequence where seq _ name like ' MBE % ... | p = OptionParser ( libs . __doc__ )
p . set_db_opts ( dbname = "track" , credentials = None )
opts , args = p . parse_args ( args )
if len ( args ) != 1 :
sys . exit ( not p . print_help ( ) )
libfile , = args
sqlcmd = "select library.lib_id, library.name, bac.gb# from library join bac on " + "library.bac_id=bac.id... |
def render ( self , text , ** overrides ) :
"""It delegates to the : func : ` markdown ` function , passing any default
options or renderer set in the : meth : ` _ _ init _ _ ` method .
The ` ` markdown ` ` template filter calls this method .
: param text : Markdown - formatted text to be rendered to HTML
:... | options = self . defaults
if overrides :
options = copy ( options )
options . update ( overrides )
return markdown ( text , self . renderer , ** options ) |
def itable ( * args , ** kwargs ) :
'''itable ( . . . ) yields a new immutable table object from the given set of arguments . The arguments
may be any number of maps or itables followed by any number of keyword arguments . All the
entries from the arguments and keywords are collapsed left - to - right ( respect... | # a couple things we want to check first . . . does our argument list reduce to just an empty
# itable or just a single itable ?
if len ( args ) == 0 and len ( kwargs ) == 0 :
return ITable ( { } , n = 0 )
elif len ( args ) == 1 and len ( kwargs ) == 0 and isinstance ( args [ 0 ] , ITable ) :
return args [ 0 ]
... |
def arcsin_sqrt ( biom_tbl ) :
"""Applies the arcsine square root transform to the
given BIOM - format table""" | arcsint = lambda data , id_ , md : np . arcsin ( np . sqrt ( data ) )
tbl_relabd = relative_abd ( biom_tbl )
tbl_asin = tbl_relabd . transform ( arcsint , inplace = False )
return tbl_asin |
def is_dicom_file ( filename ) :
"""Util function to check if file is a dicom file
the first 128 bytes are preamble
the next 4 bytes should contain DICM otherwise it is not a dicom
: param filename : file to check for the DICM header block
: type filename : six . string _ types
: returns : True if it is a... | file_stream = open ( filename , 'rb' )
file_stream . seek ( 128 )
data = file_stream . read ( 4 )
file_stream . close ( )
if data == b'DICM' :
return True
if settings . pydicom_read_force :
try :
dicom_headers = pydicom . read_file ( filename , defer_size = "1 KB" , stop_before_pixels = True , force = T... |
def _saturation ( self , T ) :
"""Saturation calculation for two phase search""" | rhoc = self . _constants . get ( "rhoref" , self . rhoc )
Tc = self . _constants . get ( "Tref" , self . Tc )
if T > Tc :
T = Tc
tau = Tc / T
rhoLo = self . _Liquid_Density ( T )
rhoGo = self . _Vapor_Density ( T )
def f ( parr ) :
rhol , rhog = parr
deltaL = rhol / rhoc
deltaG = rhog / rhoc
phirL =... |
def account_application ( self , customer_ip , first_name , last_name , tax_id , date_of_birth , address_line_1 , city_name , state_code , postal_code , phone_number , email_address , citizenship_country , employment_status , product_id , funding_amount , account_number , routing_number , backup_withholding = False , p... | title = '%s.account_application' % self . __class__ . __name__
from copy import deepcopy
# validate general inputs
input_fields = { 'customer_ip' : customer_ip , 'product_id' : product_id , 'cd_term' : cd_term , 'funding_type' : funding_type , 'funding_amount' : funding_amount , 'account_number' : account_number , 'rou... |
def fetch_logs_from_host ( hostname , install_path , prefix , logs , directory , pattern ) :
"""Static method Copies logs from specified host on the specified install path
: Parameter hostname the remote host from where we need to fetch the logs
: Parameter install _ path path where the app is installed
: Par... | if hostname is not None :
with get_sftp_client ( hostname , username = runtime . get_username ( ) , password = runtime . get_password ( ) ) as ftp :
for f in logs :
try :
mode = ftp . stat ( f ) . st_mode
except IOError , e :
if e . errno == errno . EN... |
def _convert ( frame ) :
"""Helper funcation to build a parameterized url .""" | frame = frame . convert_objects ( convert_numeric = True )
for column in frame :
if column in c . dates :
frame [ column ] = frame [ column ] . astype ( 'datetime64' )
return frame |
def fw_rule_delete ( self , data , fw_name = None ) :
"""Top level rule delete function .""" | LOG . debug ( "FW Rule delete %s" , data )
self . _fw_rule_delete ( fw_name , data ) |
def _import_data ( self , import_header_only = False ) :
"""Import data from an epw file .
Hourly data will be saved in self . data and the various header data
will be saved in the properties above .""" | # perform checks on the file before opening it .
assert os . path . isfile ( self . _file_path ) , 'Cannot find an epw file at {}' . format ( self . _file_path )
assert self . _file_path . lower ( ) . endswith ( 'epw' ) , '{} is not an .epw file. \n' 'It does not possess the .epw file extension.' . format ( self . _fil... |
def get_swagger_objects ( settings , route_info , registry ) :
"""Returns appropriate swagger handler and swagger spec schema .
Swagger Handler contains callables that isolate implementation differences
in the tween to handle both Swagger 1.2 and Swagger 2.0.
Exception is made when ` settings . prefer _ 20 _ ... | enabled_swagger_versions = get_swagger_versions ( registry . settings )
schema12 = registry . settings [ 'pyramid_swagger.schema12' ]
schema20 = registry . settings [ 'pyramid_swagger.schema20' ]
fallback_to_swagger12_route = ( SWAGGER_20 in enabled_swagger_versions and SWAGGER_12 in enabled_swagger_versions and settin... |
def checkempty ( self ) :
"""Determine whether the dataset is empty .
Args : :
no argument
Returns : :
True ( 1 ) if dataset is empty , False ( 0 ) if not
C library equivalent : SDcheckempty""" | status , emptySDS = _C . SDcheckempty ( self . _id )
_checkErr ( 'checkempty' , status , 'invalid SDS identifier' )
return emptySDS |
def sum_odd_length_subarrays ( array : list ) -> int :
"""A Python function that calculates the sum of all subarrays with odd length .
> > > sum _ odd _ length _ subarrays ( [ 1 , 2 , 4 ] )
14
> > > sum _ odd _ length _ subarrays ( [ 1 , 2 , 1 , 2 ] )
15
> > > sum _ odd _ length _ subarrays ( [ 1 , 7 ] ) ... | total_sum = 0
array_length = len ( array )
for index in range ( array_length ) :
total_sum += ( ( ( index + 1 ) * ( array_length - index ) + 1 ) // 2 ) * array [ index ]
return total_sum |
def add_envelope ( self , component = None , ** kwargs ) :
"""[ NOT SUPPORTED ]
Shortcut to : meth : ` add _ component ` but with kind = ' envelope '""" | kwargs . setdefault ( 'component' , component )
return self . add_component ( 'envelope' , ** kwargs ) |
def update ( self ) :
'''Called at regular intervals to poll the mouse position to send continuous commands .''' | if self . action_space == 'continuous' : # mouse movement only used for continuous action space
if self . world_state and self . world_state . is_mission_running :
if self . mouse_event and self . prev_mouse_event :
rotation_speed = 0.1
turn_speed = ( self . mouse_event . x - self . ... |
def add_parameter ( self , field_name , param_name , param_value ) :
"""Add a parameter to a field into script _ fields
The ScriptFields object will be returned , so calls to this can be chained .""" | try :
self . fields [ field_name ] [ 'params' ] [ param_name ] = param_value
except Exception as ex :
raise ScriptFieldsError ( "Error adding parameter %s with value %s :%s" % ( param_name , param_value , ex ) )
return self |
def extract_ZXY_motion ( self , ApproxZXYFreqs , uncertaintyInFreqs , ZXYPeakWidths , subSampleFraction = 1 , NPerSegmentPSD = 1000000 , MakeFig = True , show_fig = True ) :
"""Extracts the x , y and z signals ( in volts ) from the voltage signal . Does this by finding the highest peaks in the signal about the appr... | [ zf , xf , yf ] = ApproxZXYFreqs
zf , xf , yf = get_ZXY_freqs ( self , zf , xf , yf , bandwidth = uncertaintyInFreqs )
[ zwidth , xwidth , ywidth ] = ZXYPeakWidths
self . zVolts , self . xVolts , self . yVolts , time , fig , ax = get_ZXY_data ( self , zf , xf , yf , subSampleFraction , zwidth , xwidth , ywidth , MakeF... |
def _start_instance ( self ) :
"""Start the instance .""" | instance = self . _get_instance ( )
self . compute_driver . ex_start_node ( instance )
self . compute_driver . wait_until_running ( [ instance ] , timeout = self . timeout ) |
def qnwequi ( n , a , b , kind = "N" , equidist_pp = None , random_state = None ) :
"""Generates equidistributed sequences with property that averages
value of integrable function evaluated over the sequence converges
to the integral as n goes to infinity .
Parameters
n : int
Number of sequence points
a... | random_state = check_random_state ( random_state )
if equidist_pp is None :
import sympy as sym
equidist_pp = np . sqrt ( np . array ( list ( sym . primerange ( 0 , 7920 ) ) ) )
n , a , b = list ( map ( np . atleast_1d , list ( map ( np . asarray , [ n , a , b ] ) ) ) )
d = max ( list ( map ( len , [ n , a , b ... |
def activate ( self , engine ) :
"""Activates the Component .
: param engine : Engine to attach the Component to .
: type engine : QObject
: return : Method success .
: rtype : bool""" | LOGGER . debug ( "> Activating '{0}' Component." . format ( self . __class__ . __name__ ) )
self . __engine = engine
self . __settings = self . __engine . settings
self . __settings_section = self . name
self . activated = True
return True |
def populator ( self , sample ) :
"""Populates objects with the necessary attributes
: param sample : sample object""" | from accessoryFunctions . accessoryFunctions import GenObject
if sample . general . bestassemblyfile != 'NA' :
profile = ''
setattr ( sample , self . analysistype , GenObject ( ) )
sample [ self . analysistype ] . analyse = True
if self . analysistype . lower ( ) == 'rmlst' : # Run the allele updater me... |
def set_params ( self , targets = None ) :
'''Set the values of the parameters to the given target values .
Parameters
targets : sequence of ndarray , optional
Arrays for setting the parameters of our model . If this is not
provided , the current best parameters for this optimizer will be
used .''' | if not isinstance ( targets , ( list , tuple ) ) :
targets = self . _best_params
for param , target in zip ( self . _params , targets ) :
param . set_value ( target ) |
def get ( self , dataset_name ) :
"""Fetch a single Cached Dataset for a Project . Read key must be set .
: param dataset _ name : Name of Cached Dataset ( not ` display _ name ` )""" | url = "{0}/{1}" . format ( self . _cached_datasets_url , dataset_name )
return self . _get_json ( HTTPMethods . GET , url , self . _get_read_key ( ) ) |
def ci_macos ( ) :
"""Setup Travis - CI macOS for wheel building""" | run_command ( "brew install $PYTHON pipenv || echo \"Installed PipEnv\"" )
command_string = "sudo -H $PIP install "
for element in DEPENDENCIES + REQUIREMENTS + [ "-U" ] :
command_string += element + " "
run_command ( command_string )
# Build a wheel
run_command ( "sudo -H $PYTHON setup.py bdist_wheel" )
assert che... |
def get_public_keys_der_v2 ( self ) :
"""Return a list of DER coded X . 509 public keys from the v3 signature block""" | if self . _v2_signing_data == None :
self . parse_v2_signing_block ( )
public_keys = [ ]
for signer in self . _v2_signing_data :
public_keys . append ( signer . public_key )
return public_keys |
def init_app ( self , app ) :
"""Flask application initialization .""" | self . init_config ( app )
app . cli . add_command ( classifier_cmd )
app . extensions [ 'invenio-classifier' ] = self |
def append ( self , data , size ) :
"""Append user - supplied data to chunk , return resulting chunk size . If the
data would exceeded the available space , it is truncated . If you want to
grow the chunk to accommodate new data , use the zchunk _ extend method .""" | return lib . zchunk_append ( self . _as_parameter_ , data , size ) |
def two_pointers ( self ) :
"""Returns an ` ` int ` ` of the total number of two point field goals the
player made .""" | if self . field_goals and self . three_pointers :
return int ( self . field_goals - self . three_pointers )
# Occurs when the player didn ' t make any three pointers , so the number
# of two pointers the player made is equal to the total number of field
# goals the player made .
if self . field_goals :
return i... |
def make_instance ( cls , data ) :
"""Validate the data and create a model instance from the data .
Args :
data ( dict ) : The unserialized data to insert into the new model
instance through it ' s constructor .
Returns :
peewee . Model | sqlalchemy . Model : The model instance with it ' s data
inserted... | schema = cls ( )
if not hasattr ( schema . Meta , 'model' ) :
raise AttributeError ( "In order to make an instance, a model for " "the schema must be defined in the Meta " "class." )
serialized_data = schema . load ( data ) . data
return cls . Meta . model ( ** serialized_data ) |
def to_json ( self , pretty : bool = False , sastag : bool = False , ** kwargs ) -> str :
"""Export this SAS Data Set to a JSON Object
PROC JSON documentation : http : / / go . documentation . sas . com / ? docsetId = proc & docsetVersion = 9.4 & docsetTarget = p06hstivs0b3hsn1cb4zclxukkut . htm & locale = en
:... | code = "filename file1 temp;"
code += "proc json out=file1"
if pretty :
code += " pretty "
if not sastag :
code += " nosastags "
code += ";\n export %s.%s %s;\n run;" % ( self . libref , self . table , self . _dsopts ( ) )
if self . sas . nosub :
print ( code )
return None
ll = self . _is_valid ( )
runc... |
def add_node ( self , n , layers = None , attr_dict = None , ** attr ) :
"""Add a single node n and update node attributes .
Parameters
n : node
A node can be any hashable Python object except None .
layers : set of str or None
the set of layers the node belongs to ,
e . g . { ' tiger : token ' , ' anap... | if not layers :
layers = { self . ns }
assert isinstance ( layers , set ) , "'layers' parameter must be given as a set of strings."
assert all ( ( isinstance ( layer , str ) for layer in layers ) ) , "All elements of the 'layers' set must be strings."
# add layers to keyword arguments dict
attr . update ( { 'layers... |
def fielddefsql_from_fieldspec ( fieldspec : FIELDSPEC_TYPE ) -> str :
"""Returns SQL fragment to define a field .""" | sql = fieldspec [ "name" ] + " " + fieldspec [ "sqltype" ]
if "notnull" in fieldspec and fieldspec [ "notnull" ] :
sql += " NOT NULL"
if "autoincrement" in fieldspec and fieldspec [ "autoincrement" ] :
sql += " AUTO_INCREMENT"
if "pk" in fieldspec and fieldspec [ "pk" ] :
sql += " PRIMARY KEY"
else :
if... |
def mui ( x , y ) :
"""MUtial Information""" | assert len ( x ) == len ( y )
l = len ( x )
p_x = Counter ( x )
p_y = Counter ( y )
p_xy = Counter ( zip ( x , y ) )
return sum ( p_xy [ ( x , y ) ] * math . log ( ( p_xy [ ( x , y ) ] * l ) / float ( p_x [ x ] * p_y [ y ] ) , 2 ) / l for x , y in p_xy ) |
def p_break_statement_2 ( self , p ) :
"""break _ statement : BREAK identifier SEMI
| BREAK identifier AUTOSEMI""" | p [ 0 ] = self . asttypes . Break ( p [ 2 ] )
p [ 0 ] . setpos ( p ) |
def yule_walker ( acf , orden ) :
"""Program to solve Yule - Walker equations for AutoRegressive Models
: author : XAVI LLORT ( llort ( at ) grahi . upc . edu )
: created : MAY 2007
: changes : adapted to python by R . Dussurget
: parameter acf : AutoCorrelation Function
: parameter orden : Order of the A... | if len ( acf ) + 1 <= orden :
raise Exception ( 'ACF too short for the solicited order!' )
bb = acf [ 1 : orden + 1 ]
aa = np . zeros ( ( orden , orden ) )
for ii in np . arange ( 0 , orden ) :
for jj in np . arange ( 0 , orden ) :
aa [ ii , jj ] = acf [ np . int ( np . abs ( ii - jj ) ) ]
aa_1 = np . l... |
def file_build ( self , path , modname = None ) :
"""Build astroid from a source code file ( i . e . from an ast )
* path * is expected to be a python source file""" | try :
stream , encoding , data = open_source_file ( path )
except IOError as exc :
raise exceptions . AstroidBuildingError ( "Unable to load file {path}:\n{error}" , modname = modname , path = path , error = exc , ) from exc
except ( SyntaxError , LookupError ) as exc :
raise exceptions . AstroidSyntaxError... |
def capture_exception ( fn ) :
"""decorator that catches and returns an exception from wrapped function""" | def wrapped ( * args ) :
try :
return fn ( * args )
except Exception as e :
return e
return wrapped |
def tokenize ( text , to_lower = False , delimiters = DEFAULT_DELIMITERS ) :
"""Tokenize the input SArray of text strings and return the list of tokens .
Parameters
text : SArray [ str ]
Input data of strings representing English text . This tokenizer is not
intended to process XML , HTML , or other structu... | _raise_error_if_not_sarray ( text , "text" )
# # Compute word counts
sf = _turicreate . SFrame ( { 'docs' : text } )
fe = _feature_engineering . Tokenizer ( features = 'docs' , to_lower = to_lower , delimiters = delimiters , output_column_prefix = None )
tokens = fe . fit_transform ( sf )
return tokens [ 'docs' ] |
def powerDown ( self , powerup , interface = None ) :
"""Remove a powerup .
If no interface is specified , and the type of the object being
installed has a " powerupInterfaces " attribute ( containing
either a sequence of interfaces , or a sequence of ( interface ,
priority ) tuples ) , the target will be p... | if interface is None :
for interface , priority in powerup . _getPowerupInterfaces ( ) :
self . powerDown ( powerup , interface )
else :
for cable in self . store . query ( _PowerupConnector , AND ( _PowerupConnector . item == self , _PowerupConnector . interface == unicode ( qual ( interface ) ) , _Pow... |
def list_values ( hive , key = None , use_32bit_registry = False , include_default = True ) :
'''Enumerates the values in a registry key or hive .
Args :
hive ( str ) :
The name of the hive . Can be one of the following :
- HKEY _ LOCAL _ MACHINE or HKLM
- HKEY _ CURRENT _ USER or HKCU
- HKEY _ USER or ... | local_hive = _to_unicode ( hive )
local_key = _to_unicode ( key )
registry = Registry ( )
try :
hkey = registry . hkeys [ local_hive ]
except KeyError :
raise CommandExecutionError ( 'Invalid Hive: {0}' . format ( local_hive ) )
access_mask = registry . registry_32 [ use_32bit_registry ]
handle = None
values = ... |
def fragment ( pkt , fragsize = 1480 ) :
"""Fragment a big IP datagram""" | fragsize = ( fragsize + 7 ) // 8 * 8
lst = [ ]
for p in pkt :
s = bytes ( p [ IP ] . payload )
nb = ( len ( s ) + fragsize - 1 ) // fragsize
for i in range ( nb ) :
q = p . copy ( )
del q [ IP ] . payload
del q [ IP ] . chksum
del q [ IP ] . len
if i == nb - 1 :
... |
def p_declaration_3 ( t ) :
"""declaration : type _ specifier STAR ID""" | # encode this as the equivalent ' type _ specifier ID LT 1 GT '
if not isinstance ( t [ 1 ] , type_info ) :
t [ 1 ] = type_info ( t [ 1 ] , t . lineno ( 1 ) )
t [ 1 ] . id = t [ 3 ]
t [ 1 ] . array = True
t [ 1 ] . fixed = False
t [ 1 ] . len = '1'
t [ 0 ] = t [ 1 ] |
def download_signed_document ( self , signature_id , document_id ) :
"""Get the audit trail of concrete document
@ signature _ id : Id of signature
@ document _ id : Id of document""" | connection = Connection ( self . token )
connection . set_url ( self . production , self . SIGNS_DOCUMENTS_SIGNED_URL % ( signature_id , document_id ) )
response , headers = connection . file_request ( )
if headers [ 'content-type' ] == 'application/json' :
return response
return response |
def create_dataset ( group , name , data , units = '' , datatype = DataTypes . UNDEFINED , chunks = True , maxshape = None , compression = None , ** attributes ) :
"""Create an ARF dataset under group , setting required attributes
Required arguments :
name - - the name of dataset in which to store the data
da... | from numpy import asarray
srate = attributes . get ( 'sampling_rate' , None )
# check data validity before doing anything
if not hasattr ( data , 'dtype' ) :
data = asarray ( data )
if data . dtype . kind in ( 'S' , 'O' , 'U' ) :
raise ValueError ( "data must be in array with numeric or compound type" )... |
def assert_wildtype_matches ( self , mutation ) :
'''Check that the wildtype of the Mutation object matches the PDB sequence .''' | readwt = self . getAminoAcid ( self . getAtomLine ( mutation . Chain , mutation . ResidueID ) )
assert ( mutation . WildTypeAA == residue_type_3to1_map [ readwt ] ) |
def walk ( self , work , predicate = None ) :
"""Walk of this target ' s dependency graph , DFS preorder traversal , visiting each node exactly
once .
If a predicate is supplied it will be used to test each target before handing the target to
work and descending . Work can return targets in which case these w... | if not callable ( work ) :
raise ValueError ( 'work must be callable but was {}' . format ( work ) )
if predicate and not callable ( predicate ) :
raise ValueError ( 'predicate must be callable but was {}' . format ( predicate ) )
self . _build_graph . walk_transitive_dependency_graph ( [ self . address ] , wor... |
def mixture_channel ( val : Any , default : Any = RaiseTypeErrorIfNotProvided ) -> Sequence [ Tuple [ float , np . ndarray ] ] :
"""Return a sequence of tuples for a channel that is a mixture of unitaries .
In contrast to ` mixture ` this method falls back to ` unitary ` if ` _ mixture _ `
is not implemented . ... | mixture_getter = getattr ( val , '_mixture_' , None )
result = NotImplemented if mixture_getter is None else mixture_getter ( )
if result is not NotImplemented :
return result
unitary_getter = getattr ( val , '_unitary_' , None )
result = NotImplemented if unitary_getter is None else unitary_getter ( )
if result is... |
def pushd ( cls , new_dir ) :
"""Change directory , and back to previous directory .
It behaves like " pushd directory ; something ; popd " .""" | previous_dir = os . getcwd ( )
try :
new_ab_dir = None
if os . path . isabs ( new_dir ) :
new_ab_dir = new_dir
else :
new_ab_dir = os . path . join ( previous_dir , new_dir )
# Use absolute path to show it on FileNotFoundError message .
cls . cd ( new_ab_dir )
yield
finally :
... |
def startup ( self ) :
"""This will launch and configure the virtual box machine""" | # Do not launch the virtual machine
if not self . browser_config . get ( 'launch' , False ) :
return True
self . info_log ( "Starting up..." )
try :
vm_already_running_cmd = [ "VBoxManage" , "showvminfo" , self . browser_config . get ( 'vbname' ) , "--machinereadable" , "|" , "grep" , "VMState=" , "|" , "cut" ,... |
def version ( ) :
'''Shows installed version of dnsmasq .
CLI Example :
. . code - block : : bash
salt ' * ' dnsmasq . version''' | cmd = 'dnsmasq -v'
out = __salt__ [ 'cmd.run' ] ( cmd ) . splitlines ( )
comps = out [ 0 ] . split ( )
return comps [ 2 ] |
def op_get_opcode_name ( op_string ) :
"""Get the name of an opcode , given the ' op ' byte sequence of the operation .""" | global OPCODE_NAMES
# special case . . .
if op_string == '{}:' . format ( NAME_REGISTRATION ) :
return 'NAME_RENEWAL'
op = op_string [ 0 ]
if op not in OPCODE_NAMES :
raise Exception ( 'No such operation "{}"' . format ( op ) )
return OPCODE_NAMES [ op ] |
def find_value_in_object ( attr , obj ) :
"""Return values for any key coincidence with attr in obj or any other
nested dict .""" | # Carry on inspecting inside the list or tuple
if isinstance ( obj , ( collections . Iterator , list ) ) :
for item in obj :
yield from find_value_in_object ( attr , item )
# Final object ( dict or entity ) inspect inside
elif isinstance ( obj , collections . Mapping ) : # If result is found , inspect insid... |
def exists ( self ) :
"""Performs an existence check on the remote database .
: returns : Boolean True if the database exists , False otherwise""" | resp = self . r_session . head ( self . database_url )
if resp . status_code not in [ 200 , 404 ] :
resp . raise_for_status ( )
return resp . status_code == 200 |
def make_mid_color ( self , color1 , color2 , distance , long_route = False ) :
"""Generate a mid color between color1 and color2.
Colors should be a tuple ( hue , saturation , value ) .
distance is a float between 0.0 and 1.0 describing how far between
color1 and color2 we want to return the color . 0.0 woul... | def fade ( a , b ) :
x = b * distance
x += a * ( 1 - distance )
return x
h1 , s1 , v1 = color1
h2 , s2 , v2 = color2
hue_diff = h1 - h2
if long_route :
if hue_diff < 0.5 and hue_diff > - 0.5 :
h1 += 1
else :
if hue_diff > 0.5 :
h2 += 1
elif hue_diff < - 0.5 :
h1 += 1
retu... |
def n_lfom_rows ( FLOW , HL_LFOM ) :
"""This equation states that the open area corresponding to one row can be
set equal to two orifices of diameter = row height . If there are more than
two orifices per row at the top of the LFOM then there are more orifices
than are convenient to drill and more than necess... | N_estimated = ( HL_LFOM * np . pi / ( 2 * width_stout ( HL_LFOM , HL_LFOM ) * FLOW ) )
variablerow = min ( 10 , max ( 4 , math . trunc ( N_estimated . magnitude ) ) )
# Forcing the LFOM to either have 4 or 8 rows , for design purposes
# If the hydraulic calculation finds that there should be 4 rows , then there
# will ... |
def add_function_signature_help ( spec_dict : dict ) -> dict :
"""Add function signature help
Simplify the function signatures for presentation to BEL Editor users""" | for f in spec_dict [ "functions" ] [ "signatures" ] :
for argset_idx , argset in enumerate ( spec_dict [ "functions" ] [ "signatures" ] [ f ] [ "signatures" ] ) :
args_summary = ""
args_list = [ ]
arg_idx = 0
for arg_idx , arg in enumerate ( spec_dict [ "functions" ] [ "signatures" ]... |
def singularize ( word , pos = NOUN , gender = MALE , role = SUBJECT , custom = { } ) :
"""Returns the singular of a given word .
The inflection is based on probability rather than gender and role .""" | w = word . lower ( ) . capitalize ( )
if word in custom :
return custom [ word ]
if word in singular :
return singular [ word ]
if pos == NOUN :
for a , b in singular_inflections :
if w . endswith ( a ) :
return w [ : - len ( a ) ] + b
# Default rule : strip known plural suffixes ( b... |
def set_value ( self , section , variable , value ) :
"""Set config input value directly ,
see : mod : ` pyhector . emissions ` for possible values .
Parameters
section : str
Component in Hector config .
variable : str
Name of emissions variable .
value : pandas . Series , list , tuple , float , or st... | if isinstance ( value , pd . Series ) : # values with time as Series
values = list ( zip ( value . index , value ) )
for v in values :
self . _set_timed_double ( section , variable , v [ 0 ] , v [ 1 ] )
elif isinstance ( value , list ) : # values with time
for v in value :
if len ( v ) == 3 ... |
def get_generalised_coordinates ( self , lons , lats ) :
"""Transforms the site positions into the generalised coordinate form
described by Spudich and Chiou ( 2015 ) for the multi - rupture and / or
discordant case
Spudich , Paul and Chiou , Brian ( 2015 ) Strike - parallel and strike - normal
coordinate s... | # If the GC2 configuration has not been setup already - do it !
if not self . gc2_config :
self . _setup_gc2_framework ( )
# Initially the weights are set to zero
sx , sy = self . proj ( lons , lats )
sum_w_i = numpy . zeros_like ( lons )
sum_w_i_t_i = numpy . zeros_like ( lons )
sum_wi_ui_si = numpy . zeros_like (... |
def _warn_key_unknown ( cls , cls_context , key ) :
""": type cls _ context : type
: type key : str
: rtype : None""" | context_name = cls_context . __name__
warnings . warn ( cls . _WARNING_KEY_UNKNOWN . format ( key , context_name ) ) |
def handle_finish ( queue_name ) :
"""Marks a task on a queue as finished .""" | task_id = request . form . get ( 'task_id' , type = str )
owner = request . form . get ( 'owner' , request . remote_addr , type = str )
error = request . form . get ( 'error' , type = str ) is not None
try :
work_queue . finish ( queue_name , task_id , owner , error = error )
except work_queue . Error , e :
ret... |
def set_settings ( self , settings ) :
"""Set every given settings as object attributes .
Args :
settings ( dict ) : Dictionnary of settings .""" | for k , v in settings . items ( ) :
setattr ( self , k , v ) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.