signature stringlengths 29 44.1k | implementation stringlengths 0 85.2k |
|---|---|
def markdown_to_html ( text , options = 0 ) :
"""Render the given text to Markdown .
This is a direct interface to ` ` cmark _ markdown _ to _ html ` ` .
Args :
text ( str ) : The text to render to Markdown .
options ( int ) : The cmark options .
Returns :
str : The rendered markdown .""" | encoded_text = text . encode ( 'utf-8' )
raw_result = _cmark . lib . cmark_markdown_to_html ( encoded_text , len ( encoded_text ) , options )
return _cmark . ffi . string ( raw_result ) . decode ( 'utf-8' ) |
def discover ( self ) :
"""Open resource and populate the source attributes .""" | self . _load_metadata ( )
return dict ( datashape = self . datashape , dtype = self . dtype , shape = self . shape , npartitions = self . npartitions , metadata = self . metadata ) |
def from_sample ( sample ) :
"""Upload results of processing from an analysis pipeline sample .""" | upload_config = sample . get ( "upload" )
if upload_config :
approach = _approaches [ upload_config . get ( "method" , "filesystem" ) ]
for finfo in _get_files ( sample ) :
approach . update_file ( finfo , sample , upload_config )
return [ [ sample ] ] |
def extent ( self ) -> Optional [ Interval ] :
"""Returns an : class : ` Interval ` running from the earliest start of an
interval in this list to the latest end . Returns ` ` None ` ` if we are
empty .""" | if not self . intervals :
return None
return Interval ( self . start_datetime ( ) , self . end_datetime ( ) ) |
def label_from_df ( self , cols : IntsOrStrs = 1 , label_cls : Callable = None , ** kwargs ) :
"Label ` self . items ` from the values in ` cols ` in ` self . inner _ df ` ." | labels = self . inner_df . iloc [ : , df_names_to_idx ( cols , self . inner_df ) ]
assert labels . isna ( ) . sum ( ) . sum ( ) == 0 , f"You have NaN values in column(s) {cols} of your dataframe, please fix it."
if is_listy ( cols ) and len ( cols ) > 1 and ( label_cls is None or label_cls == MultiCategoryList ) :
... |
def is_ljoodhhaattr ( text : str ) :
"""Basic check , only the number of lines matters : 6 for ljóðaháttr
> > > text1 = " Hljóðs bið ek allar \\ nhelgar kindir , \\ nmeiri ok minni \\ nmögu Heimdallar ; \\ nviltu at ek , Valföðr , \\ nvel fyr telja \\ nforn spjöll fira , \\ nþau er fremst of man . "
> > >... | lines = [ line for line in text . split ( "\n" ) if line ]
return len ( lines ) == 6 |
def with_sql_context ( application_name , conf = None ) :
"""Context manager for a spark context
Returns
sc : SparkContext
sql _ context : SQLContext
Examples
Used within a context manager
> > > with with _ sql _ context ( " MyApplication " ) as ( sc , sql _ context ) :
. . . import pyspark
. . . # ... | if conf is None :
conf = default_configuration
assert isinstance ( conf , SparkConfiguration )
sc = conf . spark_context ( application_name )
import pyspark . sql
try :
yield sc , pyspark . sql . SQLContext ( sc )
finally :
sc . stop ( ) |
def save ( self , path ) :
"""Save a binary copy of this report
Args :
path ( string ) : The path where we should save the binary copy of the report""" | data = self . encode ( )
with open ( path , "wb" ) as out :
out . write ( data ) |
def _configure_tls_parameters ( parameters ) :
"""Configure the pika connection parameters for TLS based on the configuration .
This modifies the object provided to it . This accounts for whether or not
the new API based on the standard library ' s SSLContext is available for
pika .
Args :
parameters ( pi... | cert = config . conf [ "tls" ] [ "certfile" ]
key = config . conf [ "tls" ] [ "keyfile" ]
if cert and key :
_log . info ( "Authenticating with server using x509 (certfile: %s, keyfile: %s)" , cert , key , )
parameters . credentials = pika . credentials . ExternalCredentials ( )
else :
cert , key = None , No... |
def time_pipeline ( iterable , * steps ) :
'''This times the steps in a pipeline . Give it an iterable to test against
followed by the steps of the pipeline seperated in individual functions .
Example Usage :
from random import choice , randint
l = [ randint ( 0,50 ) for i in range ( 100 ) ]
step1 = lambd... | if callable ( iterable ) :
try :
iter ( iterable ( ) )
callable_base = True
except :
raise TypeError ( 'time_pipeline needs the first argument to be an iterable or a function that produces an iterable.' )
else :
try :
iter ( iterable )
callable_base = False
except... |
def greater_value ( num1 , num2 ) :
"""Function to determine and return the larger of two numbers .
Examples :
> > > greater _ value ( 10 , 20)
20
> > > greater _ value ( 19 , 15)
19
> > > greater _ value ( ( - 10 ) , ( - 20 ) )
-10
Args :
num1 : The first number .
num2 : The second number .
R... | return num1 if num1 > num2 else num2 |
def tile_height ( self , zoom ) :
"""Tile height in pixel .
- zoom : zoom level""" | warnings . warn ( DeprecationWarning ( "tile_height is deprecated" ) )
validate_zoom ( zoom )
matrix_pixel = 2 ** ( zoom ) * self . tile_size * self . grid . shape . height
tile_pixel = self . tile_size * self . metatiling
return matrix_pixel if tile_pixel > matrix_pixel else tile_pixel |
def extract ( d , whichtables , mode , time ) :
"""LiPD Version 1.3
Main function to initiate LiPD to TSOs conversion .
Each object has a
" paleoNumber " or " chronNumber "
" tableNumber "
" modelNumber "
" time _ id "
" mode " - chronData or paleoData
" tableType " - " meas " " ens " " summ "
: p... | logger_ts . info ( "enter extract_main" )
_root = { }
_ts = { }
# _ switch = { " paleoData " : " chronData " , " chronData " : " paleoData " }
_pc = "paleoData"
if mode == "chron" :
_pc = "chronData"
_root [ "mode" ] = _pc
_root [ "time_id" ] = time
try : # Build the root level data .
# This will serve as the templ... |
def _remove_vlan_from_all_service_profiles ( self , handle , vlan_id , ucsm_ip ) :
"""Deletes VLAN Profile config from server ' s ethernet ports .""" | service_profile_list = [ ]
for key , value in six . iteritems ( self . ucsm_sp_dict ) :
if ( ucsm_ip in key ) and value :
service_profile_list . append ( value )
if not service_profile_list : # Nothing to do
return
try :
handle . StartTransaction ( )
for service_profile in service_profile_list :... |
def create_certificate ( path = None , text = False , overwrite = True , ca_server = None , ** kwargs ) :
'''Create an X509 certificate .
path :
Path to write the certificate to .
text :
If ` ` True ` ` , return the PEM text without writing to a file .
Default ` ` False ` ` .
overwrite :
If True ( def... | if not path and not text and ( 'testrun' not in kwargs or kwargs [ 'testrun' ] is False ) :
raise salt . exceptions . SaltInvocationError ( 'Either path or text must be specified.' )
if path and text :
raise salt . exceptions . SaltInvocationError ( 'Either path or text must be specified, not both.' )
if 'publi... |
def _read_range ( self , start , end = 0 ) :
"""Read a range of bytes in stream .
Args :
start ( int ) : Start stream position .
end ( int ) : End stream position .
0 To not specify end .
Returns :
bytes : number of bytes read""" | try :
with _handle_client_exception ( ) :
return self . _client . get_object ( * self . _client_args , headers = dict ( Range = self . _http_range ( start , end ) ) ) [ 1 ]
except _ClientException as exception :
if exception . http_status == 416 : # EOF
return b''
raise |
def permutation_to_block_permutations ( permutation ) :
"""If possible , decompose a permutation into a sequence of permutations
each acting on individual ranges of the full range of indices .
E . g .
` ` ( 1,2,0,3,5,4 ) - - > ( 1,2,0 ) [ + ] ( 0,2,1 ) ` `
: param permutation : A valid permutation image tup... | if len ( permutation ) == 0 or not check_permutation ( permutation ) :
raise BadPermutationError ( )
cycles = permutation_to_disjoint_cycles ( permutation )
if len ( cycles ) == 1 :
return ( permutation , )
current_block_start = cycles [ 0 ] [ 0 ]
current_block_end = max ( cycles [ 0 ] )
current_block_cycles = ... |
def geo_location ( ip_address ) :
"""Get the Geolocation of an IP address .""" | try :
type ( ipaddress . ip_address ( ip_address ) )
except ValueError :
return { }
data = requests . get ( 'https://ipapi.co/{}/json/' . format ( ip_address ) , timeout = 5 ) . json ( )
return data |
def create_session ( user ) :
"""Create the login session
: param user : UserModel
: return :""" | def cb ( ) :
if user :
if __options__ . get ( "require_email_verification" ) and not user . email_verified :
raise exceptions . VerifyEmailError ( )
if flask_login . login_user ( user ) :
user . update ( last_login_at = utc_now ( ) )
return user
return None
re... |
def open_ns ( symbol ) :
'''generates a open namespace from symbol namespace x { y { z {''' | blocks = [ 'namespace {0} {{' . format ( x ) for x in symbol . module . name_parts ]
return ' ' . join ( blocks ) |
def eventFilter ( self , object , event ) :
"""Processes when the window is moving to update the position for the
popup if in popup mode .
: param object | < QObject >
event | < QEvent >""" | if not self . isVisible ( ) :
return False
links = self . positionLinkedTo ( )
is_dialog = self . currentMode ( ) == self . Mode . Dialog
if object not in links :
return False
if event . type ( ) == event . Close :
self . close ( )
return False
if event . type ( ) == event . Hide and not is_dialog :
... |
def append_flipped_images ( self ) :
"""Only flip boxes coordinates , images will be flipped when loading into network""" | logger . info ( '%s append flipped images to roidb' % self . _name )
roidb_flipped = [ ]
for roi_rec in self . _roidb :
boxes = roi_rec [ 'boxes' ] . copy ( )
oldx1 = boxes [ : , 0 ] . copy ( )
oldx2 = boxes [ : , 2 ] . copy ( )
boxes [ : , 0 ] = roi_rec [ 'width' ] - oldx2 - 1
boxes [ : , 2 ] = roi... |
def counter ( self , ch , part = None ) :
"""Return a counter on the channel ch .
ch : string or integer .
The channel index number or channel name .
part : int or None
The 0 - based enumeration of a True part to return . This
has an effect whether or not the mask or filter is turned
on . Raise IndexErr... | return Counter ( self ( self . _key ( ch ) , part = part ) ) |
def associate ( self , et_id , id_filter ) :
"""Create a relationship between Filter and TipoEquipamento .
: param et _ id : Identifier of TipoEquipamento . Integer value and greater than zero .
: param id _ filter : Identifier of Filter . Integer value and greater than zero .
: return : Following dictionary ... | if not is_valid_int_param ( et_id ) :
raise InvalidParameterError ( u'The identifier of TipoEquipamento is invalid or was not informed.' )
if not is_valid_int_param ( id_filter ) :
raise InvalidParameterError ( u'The identifier of Filter is invalid or was not informed.' )
url = 'filter/' + str ( id_filter ) + '... |
def language_selector ( context ) :
"""displays a language selector dropdown in the admin , based on Django " LANGUAGES " context .
requires :
* USE _ I18N = True / settings . py
* LANGUAGES specified / settings . py ( otherwise all Django locales will be displayed )
* " set _ language " url configured ( se... | output = ""
i18 = getattr ( settings , 'USE_I18N' , False )
if i18 :
template = "admin/language_selector.html"
context [ 'i18n_is_set' ] = True
try :
output = render_to_string ( template , context )
except :
pass
return output |
def to_dict ( self ) :
"""Returns a dictionary with all of the information
about the entity .""" | return { 'type' : self . __class__ . __name__ , 'points' : self . points . tolist ( ) , 'knots' : self . knots . tolist ( ) , 'closed' : self . closed } |
def first ( self , limit = 1 , columns = None ) :
"""Execute the query and get the first results
: param limit : The number of results to get
: type limit : int
: param columns : The columns to get
: type columns : list
: return : The result
: rtype : mixed""" | if not columns :
columns = [ "*" ]
return self . take ( limit ) . get ( columns ) . first ( ) |
def _get_applicable_options ( self , options : Dict [ str , Dict [ str , Any ] ] ) :
"""Returns the options that are applicable to this particular parser , from the full map of options .
It first uses ' get _ id _ for _ options ( ) ' to know the id of this parser , and then simply extracts the contents of
the o... | return get_options_for_id ( options , self . get_id_for_options ( ) ) |
def retention_policy_get ( database , name , user = None , password = None , host = None , port = None ) :
'''Get an existing retention policy .
database
The database to operate on .
name
Name of the policy to modify .
CLI Example :
. . code - block : : bash
salt ' * ' influxdb08 . retention _ policy ... | client = _client ( user = user , password = password , host = host , port = port )
for policy in client . get_list_retention_policies ( database ) :
if policy [ 'name' ] == name :
return policy
return None |
def offset ( self , offset ) :
"""Offset a number of rows before returning rows from the database .
: param offset : The number of rows to offset in the recipe . 0 will
return from the first available row
: type offset : int""" | if self . _offset != offset :
self . dirty = True
self . _offset = offset
return self |
def _encode_multipart_formdata ( fields , files ) :
"""Create a multipart encoded form for use in PUTing and POSTing .
fields is a sequence of ( name , value ) elements for regular form fields .
files is a sequence of ( name , filename , value ) elements for data to be uploaded as files
Return ( content _ typ... | BOUNDARY = '----------A_vEry_UnlikelY_bouNdary_$'
CRLF = '\r\n'
L = [ ]
for ( key , value ) in fields :
L . append ( '--' + BOUNDARY )
L . append ( str ( 'Content-Disposition: form-data; name="%s"' % key ) )
L . append ( '' )
L . append ( value )
for ( key , filename , value ) in files :
L . append ... |
def fix_e712 ( self , result ) :
"""Fix ( trivial case of ) comparison with boolean .""" | ( line_index , offset , target ) = get_index_offset_contents ( result , self . source )
# Handle very easy " not " special cases .
if re . match ( r'^\s*if [\w.]+ == False:$' , target ) :
self . source [ line_index ] = re . sub ( r'if ([\w.]+) == False:' , r'if not \1:' , target , count = 1 )
elif re . match ( r'^\... |
def update ( self , id , data ) :
"""Update a component""" | id = self . as_id ( id )
response = self . http . patch ( '%s/%s' % ( self , id ) , json = data , auth = self . auth )
response . raise_for_status ( )
return response . json ( ) |
def cookies ( self , url ) :
"""Return cookies that are matching the path and are still valid
: param url :
: return :""" | part = urlparse ( url )
# if part . port :
# _ domain = " % s : % s " % ( part . hostname , part . port )
# else :
_domain = part . hostname
cookie_dict = { }
now = utc_now ( )
for _ , a in list ( self . cookiejar . _cookies . items ( ) ) :
for _ , b in a . items ( ) :
for cookie in list ( b . values ( ) ) ... |
def get_parquet_lib ( cls ) :
"""Find / choose a library to read and write Parquet files
based on installed options .""" | if cls . __parquet_lib is None :
parq_env = os . environ . get ( 'QUILT_PARQUET_LIBRARY' , ParquetLib . ARROW . value )
cls . __parquet_lib = ParquetLib ( parq_env )
return cls . __parquet_lib |
def temporary_file ( root_dir = None , cleanup = True , suffix = '' , permissions = None , binary_mode = True ) :
"""A with - context that creates a temporary file and returns a writeable file descriptor to it .
You may specify the following keyword args :
: param str root _ dir : The parent directory to create... | mode = 'w+b' if binary_mode else 'w+'
# tempfile ' s default is ' w + b '
with tempfile . NamedTemporaryFile ( suffix = suffix , dir = root_dir , delete = False , mode = mode ) as fd :
try :
if permissions is not None :
os . chmod ( fd . name , permissions )
yield fd
finally :
... |
def all ( cls , name , hash_key , range_key = None , throughput = None ) :
"""Create an index that projects all attributes""" | return cls ( cls . ALL , name , hash_key , range_key , throughput = throughput ) |
def create ( self , name , command_to_run , description = "" , environment_variables = None , required_arguments = None , required_arguments_default_values = None , json_file_option = None , extra_data_to_post = None , ) :
"""Create a container task type .
Args :
name ( str ) : The name of the task .
command ... | # Add in extra data specific to container task types
if extra_data_to_post is None :
extra_data_to_post = { }
extra_data_to_post . update ( { "json_file_option" : json_file_option } )
# Call the parent create function
return super ( ExecutableTaskTypeManager , self ) . create ( name = name , command_to_run = comman... |
def finish_parse ( self , last_lineno_seen ) :
"""Clean - up / summary tasks run at the end of parsing .""" | if self . state == self . STATES [ 'step_in_progress' ] : # We ' ve reached the end of the log without seeing the final " step finish "
# marker , which would normally have triggered updating the step . As such we
# must manually close out the current step , so things like result , finish
# time are set for it . This e... |
def _get_link ( self , cobj ) :
"""Get a valid link , False if not found""" | fullname = cobj [ 'module_short' ] + '.' + cobj [ 'name' ]
try :
value = self . _searchindex [ 'objects' ] [ cobj [ 'module_short' ] ]
match = value [ cobj [ 'name' ] ]
except KeyError :
link = False
else :
fname_idx = match [ 0 ]
objname_idx = str ( match [ 1 ] )
anchor = match [ 3 ]
fname ... |
def list_docs ( self , options = None ) :
"""Return list of previously created documents .""" | if options is None :
raise ValueError ( "Please pass in an options dict" )
default_options = { "page" : 1 , "per_page" : 100 , "raise_exception_on_failure" : False , "user_credentials" : self . api_key , }
options = dict ( list ( default_options . items ( ) ) + list ( options . items ( ) ) )
raise_exception_on_fail... |
def _submit_result ( self ) :
"""Adding current values as a Raw Result and Resetting everything .
Notice that we are not calculating final result of assay . We just set
NP and GP values and in Bika , AS will have a Calculation to generate
final result based on NP and GP values .""" | if self . _cur_res_id and self . _cur_values : # Setting DefaultResult just because it is obligatory . However ,
# it won ' t be used because AS must have a Calculation based on
# GP and NP results .
self . _cur_values [ self . _keyword ] [ 'DefaultResult' ] = 'DefResult'
self . _cur_values [ self . _keyword ] ... |
def _walk_tree ( self , data , scheme , ancestors = None , property_name = None , prefix = None ) :
"""This function takes configuration data and a validation scheme
then walk the configuration tree validating the configuraton data agenst
the scheme provided . Will raise error on failure otherwise return None .... | if property_name is None :
property_name = 'root'
# hack until i add this to references
# reorder validates putting required first . If the data doesn ' t exist there is no need to continue .
order = [ 'registries' ] + [ key for key in scheme . keys ( ) if key not in ( 'registries' , ) ]
scheme = Or... |
def dist_mat_km ( catalog ) :
"""Compute the distance matrix for all a catalog using epicentral separation .
Will give physical distance in kilometers .
: type catalog : obspy . core . event . Catalog
: param catalog : Catalog for which to compute the distance matrix
: returns : distance matrix
: rtype : ... | # Initialize square matrix
dist_mat = np . array ( [ np . array ( [ 0.0 ] * len ( catalog ) ) ] * len ( catalog ) )
# Calculate distance vector for each event
for i , master in enumerate ( catalog ) :
mast_list = [ ]
if master . preferred_origin ( ) :
master_ori = master . preferred_origin ( )
else ... |
def exclude ( self , ** kwargs ) :
"""Generates a QueryList containing the subset of objects from
this QueryList that do * * not * * match the provided field lookups .
The following example returns the subset of a QueryList named
` ` site _ list ` ` where the id is greather than 1000.
> > > site _ list . ex... | return QueryList ( data = ( x for x in self if not self . _check_element ( kwargs , x ) ) , wrapper = self . _wrapper , wrap = False ) |
def parse ( self ) :
"""Produce a ` TxtFile ` object from the . TXT file""" | log . debug ( 'Parsing PocketTopo .TXT file %s ...' , self . txtfilename )
SurveyClass = MergingSurvey if self . merge_duplicate_shots else Survey
txtobj = None
with codecs . open ( self . txtfilename , 'rb' , self . encoding ) as txtfile :
lines = txtfile . read ( ) . splitlines ( )
# first line is cave name a... |
def action ( self , event_type , when , ** kwargs ) :
"""Called from within SimuVEX when events happens . This function checks all breakpoints registered for that event
and fires the ones whose conditions match .""" | l . debug ( "Event %s (%s) firing..." , event_type , when )
for k , v in kwargs . items ( ) :
if k not in inspect_attributes :
raise ValueError ( "Invalid inspect attribute %s passed in. Should be one of: %s" % ( k , inspect_attributes ) )
# l . debug ( " . . . % s = % r " , k , v )
l . debug ( "...... |
def contains ( value : Union [ str , 'Type' ] ) -> bool :
"""Checks if a type is defined""" | if isinstance ( value , str ) :
return any ( value . lower ( ) == i . value for i in Type )
return any ( value == i for i in Type ) |
def process_rename ( self , client , tag_value , resource_set ) :
"""Move source tag value to destination tag value
- Collect value from old tag
- Delete old tag
- Create new tag & assign stored value""" | self . log . info ( "Renaming tag on %s instances" % ( len ( resource_set ) ) )
old_key = self . data . get ( 'old_key' )
new_key = self . data . get ( 'new_key' )
# We have a preference to creating the new tag when possible first
resource_ids = [ r [ self . id_key ] for r in resource_set if len ( r . get ( 'Tags' , [ ... |
def savefig ( filename , width = None , height = None , fig = None , timeout_seconds = 10 , output_widget = None , headless = False , devmode = False ) :
"""Save the figure to an image file .
: param str filename : must have extension . png , . jpeg or . svg
: param int width : the width of the image in pixels ... | __ , ext = os . path . splitext ( filename )
format = ext [ 1 : ]
assert format in [ 'png' , 'jpeg' , 'svg' ] , "image format must be png, jpeg or svg"
with open ( filename , "wb" ) as f :
f . write ( _screenshot_data ( timeout_seconds = timeout_seconds , output_widget = output_widget , format = format , width = wi... |
def expect ( self , pattern , timeout = - 1 ) :
"""Waits on the given pattern to appear in std _ out""" | if self . blocking :
raise RuntimeError ( 'expect can only be used on non-blocking commands.' )
self . subprocess . expect ( pattern = pattern , timeout = timeout ) |
def dist_string ( self , val_meters ) :
'''return a distance as a string''' | if self . settings . dist_unit == 'nm' :
return "%.1fnm" % ( val_meters * 0.000539957 )
if self . settings . dist_unit == 'miles' :
return "%.1fmiles" % ( val_meters * 0.000621371 )
return "%um" % val_meters |
def multiple_domains ( self ) :
"""Returns True if there are multiple domains in the jar .
Returns False otherwise .
: rtype : bool""" | domains = [ ]
for cookie in iter ( self ) :
if cookie . domain is not None and cookie . domain in domains :
return True
domains . append ( cookie . domain )
return False |
def hardmax ( attrs , inputs , proto_obj ) :
"""Returns batched one - hot vectors .""" | input_tensor_data = proto_obj . model_metadata . get ( 'input_tensor_data' ) [ 0 ]
input_shape = input_tensor_data [ 1 ]
axis = int ( attrs . get ( 'axis' , 1 ) )
axis = axis if axis >= 0 else len ( input_shape ) + axis
if axis == len ( input_shape ) - 1 :
amax = symbol . argmax ( inputs [ 0 ] , axis = - 1 )
on... |
def update_rotation ( self , dt , buttons ) :
"""Updates rotation and impulse direction""" | assert isinstance ( buttons , dict )
ma = buttons [ 'right' ] - buttons [ 'left' ]
if ma != 0 :
self . stats [ 'battery' ] -= self . battery_use [ 'angular' ]
self . rotation += ma * dt * self . angular_velocity
# Redirect velocity in new direction
a = math . radians ( self . rotation )
self . impulse_dir = eu ... |
def join_all ( domain , * parts ) :
"""Join all url components .
Example : :
> > > join _ all ( " https : / / www . apple . com " , " iphone " )
https : / / www . apple . com / iphone
: param domain : Domain parts , example : https : / / www . python . org
: param parts : Other parts , example : " / doc "... | l = list ( )
if domain . endswith ( "/" ) :
domain = domain [ : - 1 ]
l . append ( domain )
for part in parts :
for i in part . split ( "/" ) :
if i . strip ( ) :
l . append ( i )
url = "/" . join ( l )
return url |
async def _do_tp ( self , pip , mount ) -> top_types . Point :
"""Execute the work of tip probe .
This is a separate function so that it can be encapsulated in
a context manager that ensures the state of the pipette tip tracking
is reset properly . It should not be called outside of
: py : meth : ` locate _... | # Clear the old offset during calibration
pip . update_instrument_offset ( top_types . Point ( ) )
# Hotspots based on our expectation of tip length and config
hotspots = robot_configs . calculate_tip_probe_hotspots ( pip . current_tip_length , self . _config . tip_probe )
new_pos : Dict [ Axis , List [ float ] ] = { a... |
def matches_at_fpr ( fg_vals , bg_vals , fpr = 0.01 ) :
"""Computes the hypergeometric p - value at a specific FPR ( default 1 % ) .
Parameters
fg _ vals : array _ like
The list of values for the positive set .
bg _ vals : array _ like
The list of values for the negative set .
fpr : float , optional
T... | fg_vals = np . array ( fg_vals )
s = scoreatpercentile ( bg_vals , 100 - fpr * 100 )
return [ sum ( fg_vals >= s ) , sum ( bg_vals >= s ) ] |
def v_from_i ( resistance_shunt , resistance_series , nNsVth , current , saturation_current , photocurrent , method = 'lambertw' ) :
'''Device voltage at the given device current for the single diode model .
Uses the single diode model ( SDM ) as described in , e . g . ,
Jain and Kapoor 2004 [ 1 ] .
The solut... | if method . lower ( ) == 'lambertw' :
return _singlediode . _lambertw_v_from_i ( resistance_shunt , resistance_series , nNsVth , current , saturation_current , photocurrent )
else : # Calculate points on the IV curve using either ' newton ' or ' brentq '
# methods . Voltages are determined by first solving the sing... |
def defragment ( self ) :
"""Defragment a member ' s backend database to recover storage space .""" | defrag_request = etcdrpc . DefragmentRequest ( )
self . maintenancestub . Defragment ( defrag_request , self . timeout , credentials = self . call_credentials , metadata = self . metadata ) |
def find_executable ( name ) :
"""Returns the path of an executable file .
Searches for an executable with the given name , first in the ` PATH ` ,
then in the current directory ( recursively ) . Upon finding the file ,
returns the full filepath of it .
Parameters
name : str
The name of the executable .... | if sys . platform . startswith ( 'win' ) or os . name . startswith ( 'os2' ) :
name = name + '.exe'
executable_path = find_file ( name , deep = True )
return executable_path |
def tag ( self ) :
"""Return a ( deferred ) cached Koji tag name for this change .""" | name_or_id = self . task . tag
if name_or_id is None :
return defer . succeed ( None )
if isinstance ( name_or_id , StringType ) :
return defer . succeed ( name_or_id )
if isinstance ( name_or_id , int ) :
return self . task . connection . cache . tag_name ( name_or_id )
return defer . fail ( ) |
def get_full_archive_path ( self , path ) :
"""Returns the full archive path""" | return os . path . join ( self . archive_dir , path . lstrip ( '/' ) ) |
def create_address ( kwargs = None , call = None ) :
'''Create a static address in a region .
CLI Example :
. . code - block : : bash
salt - cloud - f create _ address gce name = my - ip region = us - central1 address = IP''' | if call != 'function' :
raise SaltCloudSystemExit ( 'The create_address function must be called with -f or --function.' )
if not kwargs or 'name' not in kwargs :
log . error ( 'A name must be specified when creating an address.' )
return False
if 'region' not in kwargs :
log . error ( 'A region must be ... |
def categorize ( func : Union [ Callable , Iterable ] , category : str ) -> None :
"""Categorize a function .
The help command output will group this function under the specified category heading
: param func : function to categorize
: param category : category to put it in""" | if isinstance ( func , Iterable ) :
for item in func :
setattr ( item , HELP_CATEGORY , category )
else :
setattr ( func , HELP_CATEGORY , category ) |
def quote_identifier_if_required ( cls , identifier : str , debug_force_quote : bool = False ) -> str :
"""Transforms a SQL identifier ( such as a column name ) into a version
that is quoted if required ( or , with ` ` debug _ force _ quote = True ` ` , is
quoted regardless ) .""" | if debug_force_quote :
return cls . quote_identifier ( identifier )
if cls . is_quoted ( identifier ) :
return identifier
if cls . requires_quoting ( identifier ) :
return cls . quote_identifier ( identifier )
return identifier |
def name ( self ) -> str :
"""Friendly name for the stop place or platform""" | if self . is_platform :
if self . _data [ "publicCode" ] :
return self . _data [ 'name' ] + " Platform " + self . _data [ "publicCode" ]
else :
return self . _data [ 'name' ] + " Platform " + self . place_id . split ( ':' ) [ - 1 ]
else :
return self . _data [ 'name' ] |
def fit_two_lorentzian ( spectra , f_ppm , lb = 2.6 , ub = 3.6 ) :
"""Fit a lorentzian function to the sum spectra to be used for estimation of
the creatine and choline peaks .
Parameters
spectra : array of shape ( n _ transients , n _ points )
Typically the sum of the on / off spectra in each transient .
... | # We are only going to look at the interval between lb and ub
idx = ut . make_idx ( f_ppm , lb , ub )
n_points = np . abs ( idx . stop - idx . start )
n_params = 10
# Lotsa params !
# Set the bounds for the optimization
bounds = [ ( lb , ub ) , # peak1
( lb , ub ) , # peak2
( 0 , None ) , # area1
( 0 , None ) , # area2... |
def _get_fix_my_django_submission_url ( self , tb_info , sanitized_tb ) :
"""Links to the error submission url with pre filled fields""" | err_post_create_path = '/create/'
url = '{0}{1}' . format ( base_url , err_post_create_path )
return '{url}?{query}' . format ( url = url , query = urlencode ( { 'exception_type' : clean_exception_type ( tb_info [ 'parsed_traceback' ] [ 'exc_type' ] ) , 'error_message' : tb_info [ 'parsed_traceback' ] [ 'exc_msg' ] , '... |
def run ( self , applet_input , * args , ** kwargs ) :
"""Creates a new job that executes the function " main " of this applet with
the given input * applet _ input * .
See : meth : ` dxpy . bindings . dxapplet . DXExecutable . run ` for the available
args .""" | # Rename applet _ input arg to preserve API compatibility when calling
# DXApplet . run ( applet _ input = . . . )
return super ( DXApplet , self ) . run ( applet_input , * args , ** kwargs ) |
def extract_from_html ( msg_body ) :
"""Extract not quoted message from provided html message body
using tags and plain text algorithm .
Cut out the ' blockquote ' , ' gmail _ quote ' tags .
Cut Microsoft quotations .
Then use plain text algorithm to cut out splitter or
leftover quotation .
This works b... | if isinstance ( msg_body , six . text_type ) :
msg_body = msg_body . encode ( 'utf8' )
elif not isinstance ( msg_body , bytes ) :
msg_body = msg_body . encode ( 'ascii' )
result = _extract_from_html ( msg_body )
if isinstance ( result , bytes ) :
result = result . decode ( 'utf8' )
return result |
def update_positions ( self , time , xs , ys , zs , vxs , vys , vzs , ethetas , elongans , eincls , ds = None , Fs = None , ignore_effects = False ) :
"""TODO : add documentation
all arrays should be for the current time , but iterable over all bodies""" | self . xs = np . array ( _value ( xs ) )
self . ys = np . array ( _value ( ys ) )
self . zs = np . array ( _value ( zs ) )
for starref , body in self . items ( ) :
body . update_position ( time , xs , ys , zs , vxs , vys , vzs , ethetas , elongans , eincls , ds = ds , Fs = Fs , ignore_effects = ignore_effects ) |
def sent_tokenize ( text , tokenizer = None ) :
"""Convenience function for tokenizing sentences ( not iterable ) .
If tokenizer is not specified , the default tokenizer NLTKPunktTokenizer ( )
is used ( same behaviour as in the main ` TextBlob ` _ library ) .
This function returns the sentences as a generator... | _tokenizer = tokenizer if tokenizer is not None else NLTKPunktTokenizer ( )
return SentenceTokenizer ( tokenizer = _tokenizer ) . itokenize ( text ) |
def fetch ( self , filter = None , order_by = None , group_by = [ ] , page = None , page_size = None , query_parameters = None , commit = True , async = False , callback = None ) :
"""Fetch objects according to given filter and page .
Note :
This method fetches all managed class objects and store them
in loca... | request = NURESTRequest ( method = HTTP_METHOD_GET , url = self . _prepare_url ( ) , params = query_parameters )
self . _prepare_headers ( request = request , filter = filter , order_by = order_by , group_by = group_by , page = page , page_size = page_size )
if async :
return self . parent_object . send_request ( r... |
def _glob_to_sql ( self , string ) :
"""Convert glob - like wildcards to SQL wildcards
* becomes %
? becomes _
% becomes \ %
\\ remains \ \ * remains \ *
\? remains \?
This also adds a leading and trailing % , unless the pattern begins with
^ or ends with $""" | # What ' s with the chr ( 1 ) and chr ( 2 ) nonsense ? It ' s a trick to
# hide \ * and \ ? from the * and ? substitutions . This trick
# depends on the substitutiones being done in order . chr ( 1)
# and chr ( 2 ) were picked because I know those characters
# almost certainly won ' t be in the input string
table = ( (... |
def waypoint_current ( self ) :
'''return current waypoint''' | if self . mavlink10 ( ) :
m = self . recv_match ( type = 'MISSION_CURRENT' , blocking = True )
else :
m = self . recv_match ( type = 'WAYPOINT_CURRENT' , blocking = True )
return m . seq |
def serialize_dtype ( o ) :
"""Serializes a : obj : ` numpy . dtype ` .
Args :
o ( : obj : ` numpy . dtype ` ) : : obj : ` dtype ` to be serialized .
Returns :
A dictionary that can be passed to : obj : ` json . dumps ` .""" | if len ( o ) == 0 :
return dict ( _type = 'np.dtype' , descr = str ( o ) )
return dict ( _type = 'np.dtype' , descr = o . descr ) |
def iter_forks ( self , sort = '' , number = - 1 , etag = None ) :
"""Iterate over forks of this repository .
: param str sort : ( optional ) , accepted values :
( ' newest ' , ' oldest ' , ' watchers ' ) , API default : ' newest '
: param int number : ( optional ) , number of forks to return . Default : - 1 ... | url = self . _build_url ( 'forks' , base_url = self . _api )
params = { }
if sort in ( 'newest' , 'oldest' , 'watchers' ) :
params = { 'sort' : sort }
return self . _iter ( int ( number ) , url , Repository , params , etag ) |
def _fill_function ( * args ) :
"""Fills in the rest of function data into the skeleton function object
The skeleton itself is create by _ make _ skel _ func ( ) .""" | if len ( args ) == 2 :
func = args [ 0 ]
state = args [ 1 ]
elif len ( args ) == 5 : # Backwards compat for cloudpickle v0.4.0 , after which the ` module `
# argument was introduced
func = args [ 0 ]
keys = [ 'globals' , 'defaults' , 'dict' , 'closure_values' ]
state = dict ( zip ( keys , args [ 1 :... |
def _disable ( self ) :
"""The configuration containing this function has been disabled by host .
Endpoint do not work anymore , so cancel AIO operation blocks .""" | if self . _enabled :
self . _real_onCannotSend ( )
has_cancelled = 0
for block in self . _aio_recv_block_list + self . _aio_send_block_list :
try :
self . _aio_context . cancel ( block )
except OSError as exc :
trace ( 'cancelling %r raised: %s' % ( block , exc ) , )
... |
def update_dependency ( self , tile , depinfo , destdir = None ) :
"""Attempt to install or update a dependency to the latest version .
Args :
tile ( IOTile ) : An IOTile object describing the tile that has the dependency
depinfo ( dict ) : a dictionary from tile . dependencies specifying the dependency
des... | if destdir is None :
destdir = os . path . join ( tile . folder , 'build' , 'deps' , depinfo [ 'unique_id' ] )
has_version = False
had_version = False
if os . path . exists ( destdir ) :
has_version = True
had_version = True
for priority , rule in self . rules :
if not self . _check_rule ( rule , depinf... |
def extract_asset_tags ( dstore , tagname ) :
"""Extract an array of asset tags for the given tagname . Use it as
/ extract / asset _ tags or / extract / asset _ tags / taxonomy""" | tagcol = dstore [ 'assetcol/tagcol' ]
if tagname :
yield tagname , barray ( tagcol . gen_tags ( tagname ) )
for tagname in tagcol . tagnames :
yield tagname , barray ( tagcol . gen_tags ( tagname ) ) |
def absent ( name , auth = None , ** kwargs ) :
'''Ensure role does not exist
name
Name of the role''' | ret = { 'name' : name , 'changes' : { } , 'result' : True , 'comment' : '' }
__salt__ [ 'keystoneng.setup_clouds' ] ( auth )
kwargs [ 'name' ] = name
role = __salt__ [ 'keystoneng.role_get' ] ( ** kwargs )
if role :
if __opts__ [ 'test' ] is True :
ret [ 'result' ] = None
ret [ 'changes' ] = { 'id' ... |
def p_expr_plus_expr ( p ) :
"""expr : expr PLUS expr""" | p [ 0 ] = make_binary ( p . lineno ( 2 ) , 'PLUS' , p [ 1 ] , p [ 3 ] , lambda x , y : x + y ) |
def clear ( self ) :
'''Clear a chessboard''' | self . pos = [ [ 0 for _ in range ( self . board_size ) ] for _ in range ( self . board_size ) ]
self . graph = copy . deepcopy ( self . pos )
self . _game_round = 1 |
def produce ( cls , mapped_props , aggregated , value_type , visitor ) :
"""Like : py : meth : ` normalize . visitor . VisitorPattern . reduce ` , but
constructs instances rather than returning plain dicts .""" | kwargs = { } if not mapped_props else dict ( ( k . name , v ) for k , v in mapped_props )
if issubclass ( value_type , Collection ) :
kwargs [ 'values' ] = aggregated
return value_type ( ** kwargs ) |
def is_on ( self ) :
"""Get sensor state .
Assume offline or open ( worst case ) .""" | return self . status not in ( CONST . STATUS_OFF , CONST . STATUS_OFFLINE , CONST . STATUS_CLOSED , CONST . STATUS_OPEN ) |
def decode_time ( self , value ) :
"""converts strings in the form of HH : MM : SS . mmmmm
( created by datetime . time . isoformat ( ) ) to
datetime . time objects .
Timzone - aware strings ( " HH : MM : SS . mmmmm + HH : MM " ) won ' t
be handled right now and will raise TimeDecodeError .""" | if '-' in value or '+' in value : # TODO : Handle tzinfo
raise TimeDecodeError ( "Can't handle timezone aware objects: %r" % value )
tmp = value . split ( '.' )
arg = map ( int , tmp [ 0 ] . split ( ':' ) )
if len ( tmp ) == 2 :
arg . append ( int ( tmp [ 1 ] ) )
return time ( * arg ) |
def _add_raster_layer ( self , raster_layer , layer_name , save_style = False ) :
"""Add a raster layer to the folder .
: param raster _ layer : The layer to add .
: type raster _ layer : QgsRasterLayer
: param layer _ name : The name of the layer in the datastore .
: type layer _ name : str
: param save ... | if not self . is_writable ( ) :
return False , 'The destination is not writable.'
output = QFileInfo ( self . uri . filePath ( layer_name + '.tif' ) )
source = QFileInfo ( raster_layer . source ( ) )
if source . exists ( ) and source . suffix ( ) in [ 'tiff' , 'tif' ] : # If it ' s tiff file based .
QFile . cop... |
def getclient ( ) :
'''return settings dictionnary''' | if not Configuration . client_initialized :
Configuration . _initconf ( )
Configuration . client_settings = Configuration . settings [ 'client' ]
Configuration . client_initialized = True
return Configuration . client_settings |
def connect_cancel ( self , functions ) :
'''Run given functions when a run is cancelled .''' | self . _cancel_functions = [ ]
for func in functions :
if isinstance ( func , basestring ) and hasattr ( self , func ) and callable ( getattr ( self , func ) ) :
self . _cancel_functions . append ( getattr ( self , func ) )
elif callable ( func ) :
self . _cancel_functions . append ( func )
... |
def get_or_create ( self , ** kwargs ) :
"""Allows to override population mode with a ` ` populate ` ` method .""" | with auto_populate ( self . _populate_mode ) :
return super ( MultilingualQuerySet , self ) . get_or_create ( ** kwargs ) |
def get_file ( cls , path ) :
"""Retrieves a file by storage name and fileid in the form of a path
Path is expected to be ` ` storage _ name / fileid ` ` .""" | depot_name , file_id = path . split ( '/' , 1 )
depot = cls . get ( depot_name )
return depot . get ( file_id ) |
def types ( self ) :
"""A tuple containing the value types for this Slot .
The Python equivalent of the CLIPS deftemplate - slot - types function .""" | data = clips . data . DataObject ( self . _env )
lib . EnvDeftemplateSlotTypes ( self . _env , self . _tpl , self . _name , data . byref )
return tuple ( data . value ) if isinstance ( data . value , list ) else ( ) |
def effective_max_ar_order ( self ) :
"""The maximum number of AR coefficients that shall or can be
determined .
It is the minimum of | ARMA . max _ ar _ order | and the number of
coefficients of the pure | MA | after their turning point .""" | return min ( self . max_ar_order , self . ma . order - self . ma . turningpoint [ 0 ] - 1 ) |
def create_director ( self , service_id , version_number , name , quorum = 75 , _type = FastlyDirectorType . RANDOM , retries = 5 , shield = None ) :
"""Create a director for a particular service and version .""" | body = self . _formdata ( { "name" : name , "quorum" : quorum , "type" : _type , "retries" : retries , "shield" : shield , } , FastlyDirector . FIELDS )
content = self . _fetch ( "/service/%s/version/%d/director" % ( service_id , version_number ) , method = "POST" , body = body )
return FastlyDirector ( self , content ... |
def _add_section_default ( self , section , parameters ) :
'''Add the given section with the given paramters to the config . The
parameters must be a dictionary with all the keys to add . Each key
must be specified as an other dictionary with the following
parameters : default , description , type
@ param s... | section = section . lower ( )
if not self . has_section ( section ) :
self . add_section ( section )
if not section in self . config_description :
self . config_description [ section ] = { }
for key , value in parameters . items ( ) :
key = key . lower ( )
if not ( 'default' in value and 'type' in value... |
def get_all ( self , cat ) :
"""if data can ' t found in cache then it will be fetched from db ,
parsed and stored to cache for each lang _ code .
: param cat : cat of catalog data
: return :""" | return self . _get_from_local_cache ( cat ) or self . _get_from_cache ( cat ) or self . _get_from_db ( cat ) |
def fn_floor ( self , value ) :
"""Return the floor of a number . For negative numbers , floor returns a lower value . E . g . , ` floor ( - 2.5 ) = = - 3 `
: param value : The number .
: return : The floor of the number .""" | if is_ndarray ( value ) or isinstance ( value , ( list , tuple ) ) :
return numpy . floor ( self . _to_ndarray ( value ) )
else :
return math . floor ( value ) |
def _to_ned ( self ) :
"""Switches the reference frame to NED""" | if self . ref_frame is 'USE' : # Rotate
return utils . use_to_ned ( self . tensor ) , utils . use_to_ned ( self . tensor_sigma )
elif self . ref_frame is 'NED' : # Alreadt NED
return self . tensor , self . tensor_sigma
else :
raise ValueError ( 'Reference frame %s not recognised - cannot ' 'transform to NED... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.