signature stringlengths 29 44.1k | implementation stringlengths 0 85.2k |
|---|---|
def serve ( self , port = None , address = None ) :
"""Serves the SMTP server on the given port and address .""" | port = port or self . port
address = address or self . address
log . info ( 'Starting SMTP server at {0}:{1}' . format ( address , port ) )
server = InboxServer ( self . collator , ( address , port ) , None )
try :
asyncore . loop ( )
except KeyboardInterrupt :
log . info ( 'Cleaning up' ) |
def _BuildAuthenticatorResponse ( self , app_id , client_data , plugin_response ) :
"""Builds the response to return to the caller .""" | encoded_client_data = self . _Base64Encode ( client_data )
signature_data = str ( plugin_response [ 'signatureData' ] )
key_handle = str ( plugin_response [ 'keyHandle' ] )
response = { 'clientData' : encoded_client_data , 'signatureData' : signature_data , 'applicationId' : app_id , 'keyHandle' : key_handle , }
return... |
def _create_ansi_color_dict ( color_cls ) :
"Create a table that maps the 16 named ansi colors to their Windows code ." | return { 'ansidefault' : color_cls . BLACK , 'ansiblack' : color_cls . BLACK , 'ansidarkgray' : color_cls . BLACK | color_cls . INTENSITY , 'ansilightgray' : color_cls . GRAY , 'ansiwhite' : color_cls . GRAY | color_cls . INTENSITY , # Low intensity .
'ansidarkred' : color_cls . RED , 'ansidarkgreen' : color_cls . GREE... |
def got_a ( self , _type ) :
"""Returns whether there is an instance implementing < _ type >""" | if _type not in self . modules :
raise ValueError ( "No such module, %s" % _type )
return ( _type in self . insts_implementing and self . insts_implementing [ _type ] ) |
def report ( self , name , ** kwargs ) :
"""Add Report data to Batch object .
Args :
name ( str ) : The name for this Group .
file _ name ( str ) : The name for the attached file for this Group .
date _ added ( str , kwargs ) : The date timestamp the Indicator was created .
file _ content ( str ; method ,... | group_obj = Report ( name , ** kwargs )
return self . _group ( group_obj ) |
def post_event_discount ( self , event_id , discount_code , discount_amount_off = None , discount_percent_off = None , discount_ticket_ids = None , discount_quantity_available = None , discount_start_date = None , discount_end_date = None ) :
"""POST / events / : id / discounts /
discount _ code string required C... | data = construct_namespaced_dict ( "discount" , locals ( ) )
return self . post ( "/events/{0}/discounts/" . format ( event_id ) , data = data ) |
def streamlines ( dataset , vectors = None , source_center = None , source_radius = None , n_points = 100 , integrator_type = 45 , integration_direction = 'both' , surface_streamlines = False , initial_step_length = 0.5 , step_unit = 'cl' , min_step_length = 0.01 , max_step_length = 1.0 , max_steps = 2000 , terminal_sp... | integration_direction = str ( integration_direction ) . strip ( ) . lower ( )
if integration_direction not in [ 'both' , 'back' , 'backward' , 'forward' ] :
raise RuntimeError ( "integration direction must be one of: 'backward', 'forward', or 'both' - not '{}'." . format ( integration_direction ) )
if integrator_ty... |
def filter_transition_coefs ( transition_coef , indices ) :
"""> > > coef = np . array ( [ [ 0 , 1 , 2 ] , [ 3 , 4 , 5 ] , [ 6 , 7 , 8 ] ] )
> > > filter _ transition _ coefs ( coef , [ 0 ] )
array ( [ [ 0 ] ] )
> > > filter _ transition _ coefs ( coef , [ 1 , 2 ] )
array ( [ [ 4 , 5 ] ,
[7 , 8 ] ] )
> ... | indices = np . array ( indices )
rows = transition_coef [ indices ]
return rows [ : , indices ] |
def gen_passwd ( self ) :
'''reseting password''' | post_data = self . get_post_data ( )
userinfo = MUser . get_by_name ( post_data [ 'u' ] )
sub_timestamp = int ( post_data [ 't' ] )
cur_timestamp = tools . timestamp ( )
if cur_timestamp - sub_timestamp < 600 and cur_timestamp > sub_timestamp :
pass
else :
kwd = { 'info' : '密码重置已超时!' , 'link' : '/user/reset-pas... |
def match_not_exists ( self , field , new_group = False ) :
"""Require a field to not exist in the results .
Matches will not have ` ` field ` ` present .
Arguments :
field ( str ) : The field to check .
The field must be namespaced according to Elasticsearch rules
using the dot syntax .
For example , `... | return self . exclude_field ( field , "*" , new_group = new_group ) |
def _vector_layers ( self ) :
"""Return a list of vector layers available .
: return : List of vector layers available in the geopackage .
: rtype : list
. . versionadded : : 4.0""" | layers = [ ]
vector_datasource = self . vector_driver . Open ( self . uri . absoluteFilePath ( ) )
if vector_datasource :
for i in range ( vector_datasource . GetLayerCount ( ) ) :
layers . append ( vector_datasource . GetLayer ( i ) . GetName ( ) )
return layers |
def highcharts_linegraph ( plotdata , pconfig = None ) :
"""Build the HTML needed for a HighCharts line graph . Should be
called by linegraph . plot ( ) , which properly formats input data .""" | if pconfig is None :
pconfig = { }
# Get the plot ID
if pconfig . get ( 'id' ) is None :
pconfig [ 'id' ] = 'mqc_hcplot_' + '' . join ( random . sample ( letters , 10 ) )
# Sanitise plot ID and check for duplicates
pconfig [ 'id' ] = report . save_htmlid ( pconfig [ 'id' ] )
# Build the HTML for the page
html =... |
def _mine_get ( self , load ) :
'''Gathers the data from the specified minions ' mine
: param dict load : A payload received from a minion
: rtype : dict
: return : Mine data from the specified minions''' | load = self . __verify_load ( load , ( 'id' , 'tgt' , 'fun' , 'tok' ) )
if load is False :
return { }
else :
return self . masterapi . _mine_get ( load , skip_verify = True ) |
def print_progress_bar ( done : int , total : int , prefix : str = '' , suffix : str = '' ) -> None :
"""Print a progressbar with the given prefix and suffix , without newline at the end .
param done : current step in computation
param total : total count of steps in computation
param prefix : info text displ... | percent = '{0:.1f}' . format ( 100 * ( done / float ( total ) ) )
base_len = shutil . get_terminal_size ( ) . columns - 7 - len ( prefix ) - len ( suffix )
base_len = min ( [ base_len , 50 ] )
min_length = base_len - 1 - len ( '{}/{}={}' . format ( total , total , '100.0' ) )
length = base_len - len ( '{}/{}={}' . form... |
def _parse_bug ( self , data ) :
"""param data : dict of data from XML - RPC server , representing a bug .
returns : AttrDict""" | if 'id' in data :
data [ 'weburl' ] = self . url . replace ( 'xmlrpc.cgi' , str ( data [ 'id' ] ) )
bug = AttrDict ( data )
return bug |
def extract ( self , archive_path , output_package_path , ** kwargs ) :
'''Extract an archived GraftM package .
Parameters
archive _ path : str
path to archive
output _ package _ path : str
path to where to put the extracted file
kwargs :
force : bool
overwrite an existing directory''' | force = kwargs . pop ( 'force' , ArchiveDefaultOptions . force )
if len ( kwargs ) > 0 :
raise Exception ( "Unexpected arguments detected: %s" % kwargs )
logging . info ( "Un-archiving GraftM package '%s' from '%s'" % ( output_package_path , archive_path ) )
archive = os . path . abspath ( archive_path )
output = o... |
def _get_formset_data ( self ) :
"""Formats the self . filtered _ data in a way suitable for a formset .""" | data = [ ]
for datum in self . filtered_data :
form_data = { }
for column in self . columns . values ( ) :
value = column . get_data ( datum )
form_data [ column . name ] = value
form_data [ 'id' ] = self . get_object_id ( datum )
data . append ( form_data )
return data |
def unregister_callback ( self , type_ , from_ , * , wildcard_resource = True ) :
"""Unregister a callback function .
: param type _ : Stanza type to listen for , or : data : ` None ` for a
wildcard match .
: param from _ : Sender to listen for , or : data : ` None ` for a full wildcard
match .
: type fro... | if from_ is None or not from_ . is_bare :
wildcard_resource = False
self . _map . pop ( ( type_ , from_ , wildcard_resource ) ) |
def filter_skiplines ( code , errors ) :
"""Filter lines by ` noqa ` .
: return list : A filtered errors""" | if not errors :
return errors
enums = set ( er . lnum for er in errors )
removed = set ( [ num for num , l in enumerate ( code . split ( '\n' ) , 1 ) if num in enums and SKIP_PATTERN ( l ) ] )
if removed :
errors = [ er for er in errors if er . lnum not in removed ]
return errors |
def get_octahedra ( self , atoms , periodicity = 3 ) :
'''Extract octahedra as lists of sequence numbers of corner atoms''' | octahedra = [ ]
for n , i in enumerate ( atoms ) :
found = [ ]
if i . symbol in Perovskite_Structure . B :
for m , j in enumerate ( self . virtual_atoms ) :
if j . symbol in Perovskite_Structure . C and self . virtual_atoms . get_distance ( n , m ) <= self . OCTAHEDRON_BOND_LENGTH_LIMIT :
... |
def all ( self , query = None , ** kwargs ) :
"""Gets all spaces .""" | return super ( SpacesProxy , self ) . all ( query = query ) |
def duplicate ( self ) :
'''Returns a copy of the current contact element .
@ returns : Contact''' | return self . __class__ ( name = self . name , identifier = self . identifier , phone = self . phone , require_id = self . __require_id , address = self . address . duplicate ( ) ) |
def get_file_behaviour ( self , resources ) :
"""Retrieves a report about the behaviour of a md5 , sha1 , and / or sha2 hash of
a file when executed in a sandboxed environment ( Cuckoo sandbox ) .
Args :
resources : list of string hashes .""" | api_name = 'virustotal-file-behaviour'
api_endpoint = 'file/behaviour'
return self . _extract_all_responses ( resources , api_endpoint , api_name ) |
def bbox2array ( vol , bbox , order = 'F' , readonly = False , lock = None , location = None ) :
"""Convenince method for creating a
shared memory numpy array based on a CloudVolume
and Bbox . c . f . sharedmemory . ndarray for information
on the optional lock parameter .""" | location = location or vol . shared_memory_id
shape = list ( bbox . size3 ( ) ) + [ vol . num_channels ]
return ndarray ( shape = shape , dtype = vol . dtype , location = location , readonly = readonly , lock = lock , order = order ) |
def _newton_refine ( nodes , point , s ) :
r"""Refine a solution to : math : ` B ( s ) = p ` using Newton ' s method .
Computes updates via
. . math : :
\ mathbf { 0 } \ approx
\ left ( B \ left ( s _ { \ ast } \ right ) - p \ right ) +
B ' \ left ( s _ { \ ast } \ right ) \ Delta s
For example , consid... | pt_delta = point - evaluate_multi ( nodes , np . asfortranarray ( [ s ] ) )
derivative = evaluate_hodograph ( s , nodes )
# Each array is 2 x 1 ( i . e . a column vector ) , we want the vector
# dot product .
delta_s = np . vdot ( pt_delta [ : , 0 ] , derivative [ : , 0 ] ) / np . vdot ( derivative [ : , 0 ] , derivati... |
def get_notifications ( self , ** params ) :
"""https : / / developers . coinbase . com / api / v2 # list - notifications""" | response = self . _get ( 'v2' , 'notifications' , params = params )
return self . _make_api_object ( response , Notification ) |
def _print_task_data ( self , task ) :
"""Pretty - prints task data .
Args :
task : Task dict generated by Turbinia .""" | print ( ' {0:s} ({1:s})' . format ( task [ 'name' ] , task [ 'id' ] ) )
paths = task . get ( 'saved_paths' , [ ] )
if not paths :
return
for path in paths :
if path . endswith ( 'worker-log.txt' ) :
continue
if path . endswith ( '{0:s}.log' . format ( task . get ( 'id' ) ) ) :
continue
i... |
def as_set ( self , preserve_casing = False ) :
"""Return the set as real python set type . When calling this , all
the items are converted to lowercase and the ordering is lost .
: param preserve _ casing : if set to ` True ` the items in the set returned
will have the original case like in the
: class : `... | if preserve_casing :
return set ( self . _headers )
return set ( self . _set ) |
def gradient_log_likelihood_css_arma ( self , diffedy ) :
"""Calculates the gradient for the log likelihood function using CSS
Derivation :
L ( y | \t heta ) = - \f rac { n } { 2 } log ( 2 \ pi \ sigma ^ 2 ) - \f rac { 1 } { 2 \ pi } \ sum _ { i = 1 } ^ n \ epsilon _ t ^ 2 \ \ sigma ^ 2 = \f rac { \ sum _ { i =... | # need to copy diffedy to a double [ ] for Java
result = self . _jmodel . gradientlogLikelihoodCSSARMA ( _py2java_double_array ( self . _ctx , diffedy ) )
return _java2py ( self . _ctx , result ) |
def render ( self , template = None ) :
"""Render the plot using a template .
Once the plot is complete , it needs to be rendered . Artist uses
the Jinja2 templating engine . The default template results in a
LaTeX file which can be included in your document .
: param template : a user - supplied template o... | if not template :
template = self . template
for subplot in self . subplots :
subplot . _prepare_data ( )
response = template . render ( rows = self . rows , columns = self . columns , xmode = self . xmode , ymode = self . ymode , width = self . width , height = self . height , xlabel = self . xlabel , ylabel =... |
def foreign_links ( network ) :
"""Change transmission technology of foreign lines from AC to DC ( links ) .
Parameters
network : : class : ` pypsa . Network
Overall container of PyPSA
Returns
network : : class : ` pypsa . Network
Overall container of PyPSA""" | foreign_buses = network . buses [ network . buses . country_code != 'DE' ]
foreign_lines = network . lines [ network . lines . bus0 . astype ( str ) . isin ( foreign_buses . index ) | network . lines . bus1 . astype ( str ) . isin ( foreign_buses . index ) ]
foreign_links = network . links [ network . links . bus0 . as... |
def initdict ( self , fname ) :
"""create a blank dictionary""" | if isinstance ( fname , Idd ) :
self . dt , self . dtls = fname . dt , fname . dtls
return self . dt , self . dtls
astr = mylib2 . readfile ( fname )
nocom = removecomment ( astr , '!' )
idfst = nocom
alist = idfst . split ( ';' )
lss = [ ]
for element in alist :
lst = element . split ( ',' )
lss . appe... |
def bind_key ( pymux , variables ) :
"""Bind a key sequence .
- n : Not necessary to use the prefix .""" | key = variables [ '<key>' ]
command = variables [ '<command>' ]
arguments = variables [ '<arguments>' ]
needs_prefix = not variables [ '-n' ]
try :
pymux . key_bindings_manager . add_custom_binding ( key , command , arguments , needs_prefix = needs_prefix )
except ValueError :
raise CommandException ( 'Invalid ... |
def requirements ( collector ) :
"""Just print out the requirements""" | out = sys . stdout
artifact = collector . configuration [ 'dashmat' ] . artifact
if artifact not in ( None , "" , NotSpecified ) :
if isinstance ( artifact , six . string_types ) :
out = open ( artifact , 'w' )
else :
out = artifact
for active in collector . configuration [ '__imported__' ] . va... |
def some ( args ) :
"""% prog some bedfile idsfile > newbedfile
Retrieve a subset of bed features given a list of ids .""" | from jcvi . formats . base import SetFile
from jcvi . utils . cbook import gene_name
p = OptionParser ( some . __doc__ )
p . add_option ( "-v" , dest = "inverse" , default = False , action = "store_true" , help = "Get the inverse, like grep -v [default: %default]" )
p . set_outfile ( )
p . set_stripnames ( )
opts , arg... |
def rules ( self , word ) :
"""Function to tokenize input string and return output of str with ortho rules
applied .
Parameters
word : str
The input string to be tokenized .
Returns
result : str
Result of the orthography rules applied to the input str .""" | return self . _rules . apply ( word ) if self . _rules else word |
def bagToXML ( bagPath , ark_naan = None ) :
"""Given a path to a bag , read stuff about it and make an XML file""" | # This is so . DEFAULT _ ARK _ NAAN can be modified
# at runtime .
if ark_naan is None :
ark_naan = DEFAULT_ARK_NAAN
bagInfoPath = os . path . join ( bagPath , "bag-info.txt" )
bagTags = getBagTags ( bagInfoPath )
if 'Payload-Oxum' not in bagTags :
bagTags [ 'Payload-Oxum' ] = getOxum ( os . path . join ( bagPa... |
def bootstrap_resample_run ( ns_run , threads = None , ninit_sep = False , random_seed = False ) :
"""Bootstrap resamples threads of nested sampling run , returning a new
( resampled ) nested sampling run .
Get the individual threads for a nested sampling run .
Parameters
ns _ run : dict
Nested sampling r... | if random_seed is not False : # save the random state so we don ' t affect other bits of the code
state = np . random . get_state ( )
np . random . seed ( random_seed )
if threads is None :
threads = nestcheck . ns_run_utils . get_run_threads ( ns_run )
n_threads = len ( threads )
if ninit_sep :
try :
... |
def parse_dot_data ( s ) :
"""Parse DOT description in ( unicode ) string ` s ` .
@ return : Graphs that result from parsing .
@ rtype : ` list ` of ` pydot . Dot `""" | global top_graphs
top_graphs = list ( )
try :
graphparser = graph_definition ( )
graphparser . parseWithTabs ( )
tokens = graphparser . parseString ( s )
return list ( tokens )
except ParseException as err :
print ( err . line + " " * ( err . column - 1 ) + "^" + err )
return None |
def verify_file_private ( filename ) :
"""Raises ValueError the file permissions allow group / other
On windows this never raises due to the implementation of stat .""" | if platform . system ( ) . upper ( ) != 'WINDOWS' :
filename = os . path . expanduser ( filename )
if os . path . exists ( filename ) :
file_stat = os . stat ( filename )
if mode_allows_group_or_other ( file_stat . st_mode ) :
raise ValueError ( CONFIG_FILE_PERMISSIONS_ERROR ) |
def _u_distance_correlation_sqr_naive ( x , y , exponent = 1 ) :
"""Bias - corrected distance correlation estimator between two matrices .""" | return _distance_sqr_stats_naive_generic ( x , y , matrix_centered = _u_distance_matrix , product = u_product , exponent = exponent ) . correlation_xy |
def receiver ( signal , ** kwargs ) :
"""A decorator for connecting receivers to signals . Used by passing in the
signal ( or list of signals ) and keyword arguments to connect : :
@ receiver ( post _ save , sender = MyModel )
def signal _ receiver ( sender , * * kwargs ) :
@ receiver ( [ post _ save , post... | def _decorator ( func ) :
if isinstance ( signal , ( list , tuple ) ) :
for s in signal :
s . connect ( func , ** kwargs )
else :
signal . connect ( func , ** kwargs )
return func
return _decorator |
def all_keys ( self , uppercase_keys = False ) :
"""Return all keys regardless where they are set .""" | d = { }
for k in self . _override . keys ( ) :
d [ k . upper ( ) if uppercase_keys else k . lower ( ) ] = { }
for k in self . _args . keys ( ) :
d [ k . upper ( ) if uppercase_keys else k . lower ( ) ] = { }
for k in self . _env . keys ( ) :
d [ k . upper ( ) if uppercase_keys else k . lower ( ) ] = { }
for... |
def for_version ( self , version_guid ) :
"""Return a UsageLocator for the same block in a different version of the library .""" | return self . replace ( library_key = self . library_key . for_version ( version_guid ) ) |
def object_id_doi ( tag , parent_tag_name = None ) :
"""DOI in an object - id tag found inside the tag""" | doi = None
object_id = None
object_ids = raw_parser . object_id ( tag , "doi" )
if object_ids :
object_id = first ( [ id_ for id_ in object_ids ] )
if parent_tag_name and object_id and object_id . parent . name != parent_tag_name :
object_id = None
if object_id :
doi = node_contents_str ( object_id )
return... |
def to_dict ( self ) :
"""A wrapper for to _ dict the makes sure that all the private information
as well as extra arguments are included . This method should * not * be
used for exporting information about the key .
: return : A dictionary representation of the JSON Web key""" | res = self . serialize ( private = True )
res . update ( self . extra_args )
return res |
def insert_device_filter ( self , position , filter_p ) :
"""Inserts the given USB device to the specified position
in the list of filters .
Positions are numbered starting from 0 . If the specified
position is equal to or greater than the number of elements in
the list , the filter is added to the end of t... | if not isinstance ( position , baseinteger ) :
raise TypeError ( "position can only be an instance of type baseinteger" )
if not isinstance ( filter_p , IUSBDeviceFilter ) :
raise TypeError ( "filter_p can only be an instance of type IUSBDeviceFilter" )
self . _call ( "insertDeviceFilter" , in_p = [ position , ... |
def set_label ( self , row , column , text , location = 'upper right' , style = None ) :
"""Set a label for the subplot .
: param row , column : specify the subplot .
: param text : the label text .
: param location : the location of the label inside the plot . May
be one of ' center ' , ' upper right ' , '... | subplot = self . get_subplot_at ( row , column )
subplot . set_label ( text , location , style ) |
def fill_zeros ( result , x , y , name , fill ) :
"""If this is a reversed op , then flip x , y
If we have an integer value ( or array in y )
and we have 0 ' s , fill them with the fill ,
return the result .
Mask the nan ' s from x .""" | if fill is None or is_float_dtype ( result ) :
return result
if name . startswith ( ( 'r' , '__r' ) ) :
x , y = y , x
is_variable_type = ( hasattr ( y , 'dtype' ) or hasattr ( y , 'type' ) )
is_scalar_type = is_scalar ( y )
if not is_variable_type and not is_scalar_type :
return result
if is_scalar_type :
... |
def log_to_file ( self , message ) :
"""Write a log message only to the file""" | with self . build_fs . open ( self . log_file , 'a+' ) as f :
f . write ( unicode ( message + '\n' ) ) |
def job_success ( self , job , queue , job_result ) :
"""Called just after an execute call was successful .
job _ result is the value returned by the callback , if any .""" | job . queued . delete ( )
job . hmset ( end = str ( datetime . utcnow ( ) ) , status = STATUSES . SUCCESS )
queue . success . rpush ( job . ident )
self . log ( self . job_success_message ( job , queue , job_result ) )
if hasattr ( job , 'on_success' ) :
job . on_success ( queue , job_result ) |
def update_hparams_for_tpu ( hparams ) :
"""Change hparams to be compatible with TPU training .""" | # Adafactor uses less memory than Adam .
# switch to Adafactor with its recommended learning rate scheme .
hparams . optimizer = "Adafactor"
hparams . learning_rate_schedule = "rsqrt_decay"
hparams . learning_rate_warmup_steps = 10000
# Avoid an expensive concat on TPU .
# > 1 shards helps with faster parameter distrib... |
def local_variable_action ( self , text , loc , var ) :
"""Code executed after recognising a local variable""" | exshared . setpos ( loc , text )
if DEBUG > 0 :
print ( "LOCAL_VAR:" , var , var . name , var . type )
if DEBUG == 2 :
self . symtab . display ( )
if DEBUG > 2 :
return
index = self . symtab . insert_local_var ( var . name , var . type , self . shared . function_vars )
self . shared . functi... |
def _is_in_comment_type ( token_type ) :
"""Return true if this kind of token can be inside a comment .""" | return token_type in [ TokenType . Comment , TokenType . Newline , TokenType . Whitespace , TokenType . RST , TokenType . BeginRSTComment , TokenType . BeginInlineRST , TokenType . EndInlineRST ] |
def __calculate_current_value ( self , asset_class : AssetClass ) :
"""Calculate totals for asset class by adding all the children values""" | # Is this the final asset class , the one with stocks ?
if asset_class . stocks : # add all the stocks
stocks_sum = Decimal ( 0 )
for stock in asset_class . stocks : # recalculate into base currency !
stocks_sum += stock . value_in_base_currency
asset_class . curr_value = stocks_sum
if asset_class .... |
def _parse_config_file ( job , config_file , max_cores = None ) :
"""Parse the input yaml config file and download all tool inputs into the file store .
: param str config _ file : Path to the input config file
: param int max _ cores : The maximum cores to use for any single high - compute job .
: return : t... | job . fileStore . logToMaster ( 'Parsing config file' )
config_file = os . path . abspath ( config_file )
if not os . path . exists ( config_file ) :
raise ParameterError ( 'The config file was not found at specified location. Please verify ' + 'and retry.' )
# Initialize variables to hold the sample sets , the uni... |
def _normalize_group_attrs ( self , attrs ) :
"""Normalize the attributes used to set groups
If it ' s a list of one element , it just become this
element .
It raises an error if the attribute doesn ' t exist
or if it ' s multivaluated .""" | for key in self . group_attrs_keys :
if key not in attrs :
raise MissingGroupAttr ( key )
if type ( attrs [ key ] ) is list and len ( attrs [ key ] ) == 1 :
attrs [ key ] = attrs [ key ] [ 0 ]
if type ( attrs [ key ] ) is list and len ( attrs [ key ] ) != 1 :
raise MultivaluedGroupAt... |
def grouper ( num , iterable , fillvalue = None ) :
"Collect data into fixed - length chunks or blocks" | # grouper ( 3 , ' ABCDEFG ' , ' x ' ) - - > ABC DEF Gxx
args = [ iter ( iterable ) ] * num
return zip_longest ( fillvalue = fillvalue , * args ) |
def default_value ( self ) :
"""The default category when making a query""" | if not hasattr ( self , "_default_value" ) :
if self . elem_type == "select" :
try : # Get option marked " selected "
def_value = get_option_value ( self . elem . select_one ( "[selected]" ) )
except AttributeError : # . . . or if that one doesen ' t exist get the first option
... |
def create_or_update ( cls , course_video , file_name = None , image_data = None , generated_images = None ) :
"""Create a VideoImage object for a CourseVideo .
NOTE : If ` image _ data ` is None then ` file _ name ` value will be used as it is , otherwise
a new file name is constructed based on uuid and extens... | video_image , created = cls . objects . get_or_create ( course_video = course_video )
if image_data : # Delete the existing image only if this image is not used by anyone else . This is necessary because
# after a course re - run , a video in original course and the new course points to same image , So when
# we update... |
def reg2mim ( regfile , mimfile , maxdepth ) :
"""Parse a DS9 region file and write a MIMAS region ( . mim ) file .
Parameters
regfile : str
DS9 region ( . reg ) file .
mimfile : str
MIMAS region ( . mim ) file .
maxdepth : str
Depth / resolution of the region file .""" | logging . info ( "Reading regions from {0}" . format ( regfile ) )
lines = ( l for l in open ( regfile , 'r' ) if not l . startswith ( '#' ) )
poly = [ ]
circles = [ ]
for line in lines :
if line . startswith ( 'box' ) :
poly . append ( box2poly ( line ) )
elif line . startswith ( 'circle' ) :
c... |
def regions ( ) :
"""Get all available regions for the SQS service .
: rtype : list
: return : A list of : class : ` boto . ec2 . regioninfo . RegionInfo `""" | return [ SQSRegionInfo ( name = 'us-east-1' , endpoint = 'sqs.us-east-1.amazonaws.com' ) , SQSRegionInfo ( name = 'eu-west-1' , endpoint = 'sqs.eu-west-1.amazonaws.com' ) , SQSRegionInfo ( name = 'us-west-1' , endpoint = 'sqs.us-west-1.amazonaws.com' ) , SQSRegionInfo ( name = 'us-west-2' , endpoint = 'sqs.us-west-2.am... |
def parse_cell ( self , cell ) :
"""Process cell field , the field format just like { { field } }
: param cell :
: return : value , field""" | field = ''
if ( isinstance ( cell . value , ( str , unicode ) ) and cell . value . startswith ( '{{' ) and cell . value . endswith ( '}}' ) ) :
field = cell . value [ 2 : - 2 ] . strip ( )
value = ''
else :
value = cell . value
return value , field |
def _construct_approximation ( self , basis_kwargs , coefs_list ) :
"""Construct a collection of derivatives and functions that approximate
the solution to the boundary value problem .
Parameters
basis _ kwargs : dict ( str : )
coefs _ list : list ( numpy . ndarray )
Returns
basis _ derivs : list ( func... | derivs = self . _construct_derivatives ( coefs_list , ** basis_kwargs )
funcs = self . _construct_functions ( coefs_list , ** basis_kwargs )
return derivs , funcs |
def create_logstash ( self , ** kwargs ) :
"""Creates an instance of the Logging Service .""" | logstash = predix . admin . logstash . Logging ( ** kwargs )
logstash . create ( )
logstash . add_to_manifest ( self )
logging . info ( 'Install Kibana-Me-Logs application by following GitHub instructions' )
logging . info ( 'git clone https://github.com/cloudfoundry-community/kibana-me-logs.git' )
return logstash |
def merge_data ( * data_frames , ** kwargs ) :
"""Merge DataFrames by column . Number of rows in tables must be the same .
This method can be called both outside and as a DataFrame method .
: param list [ DataFrame ] data _ frames : DataFrames to be merged .
: param bool auto _ rename : if True , fields in so... | from . specialized import build_merge_expr
from . . utils import ML_ARG_PREFIX
if len ( data_frames ) <= 1 :
raise ValueError ( 'Count of DataFrames should be at least 2.' )
norm_data_pairs = [ ]
df_tuple = collections . namedtuple ( 'MergeTuple' , 'df cols exclude' )
for pair in data_frames :
if isinstance ( p... |
def nvlist_to_dict ( nvlist ) :
'''Convert a CORBA namevalue list into a dictionary .''' | result = { }
for item in nvlist :
result [ item . name ] = item . value . value ( )
return result |
def sids ( self ) :
"""Requires an extra request . Result is cached .""" | if self . cid :
results = get_json ( self . cid , operation = 'sids' )
return results [ 'InformationList' ] [ 'Information' ] [ 0 ] [ 'SID' ] if results else [ ] |
def get_occupation ( self ) :
"""Returns the occupation as was last recorded .""" | ret = { }
self . l . info ( "Reading occupation from database..." )
with self . lock :
for pc_name , pc_id in self . pc2id_lut . iteritems ( ) :
self . c . execute ( """ SELECT occupation FROM occupationUpdates
WHERE pc=? ORDER BY datetime DESC
... |
def deserialize ( type_ , value = None , ** kwargs ) :
'''Get an object from a text representation''' | if not isinstance ( type_ , str ) :
return type_
des = deserializer ( type_ , ** kwargs )
if value is None :
return des
return des ( value ) |
def parse_comments_for_file ( filename ) :
"""Return a list of all parsed comments in a file . Mostly for testing &
interactive use .""" | return [ parse_comment ( strip_stars ( comment ) , next_line ) for comment , next_line in get_doc_comments ( read_file ( filename ) ) ] |
def _parse_date ( self , cell_value ) :
"""Attempts to parse a cell _ value as a date .""" | date_tuple = xlrd . xldate_as_tuple ( cell_value , self . raw_sheet . book . datemode )
return self . tuple_to_datetime ( date_tuple ) |
def _create_analysis_wizard_action ( self ) :
"""Create action for IF - centric wizard .""" | icon = resources_path ( 'img' , 'icons' , 'show-wizard.svg' )
self . action_function_centric_wizard = QAction ( QIcon ( icon ) , self . tr ( 'Impact Function Centric Wizard' ) , self . iface . mainWindow ( ) )
self . action_function_centric_wizard . setStatusTip ( self . tr ( 'Open InaSAFE impact function centric wizar... |
def _splice ( value , n ) :
"""Splice ` value ` at its center , retaining a total of ` n ` characters .
Parameters
value : str
n : int
The total length of the returned ends will not be greater than this
value . Characters will be dropped from the center to reach this limit .
Returns
A tuple of str : (... | if n <= 0 :
raise ValueError ( "n must be positive" )
value_len = len ( value )
center = value_len // 2
left , right = value [ : center ] , value [ center : ]
if n >= value_len :
return left , right
n_todrop = value_len - n
right_idx = n_todrop // 2
left_idx = right_idx + n_todrop % 2
return left [ : - left_idx... |
def create_timeline ( self , timeline , scope_identifier , hub_name , plan_id ) :
"""CreateTimeline .
: param : class : ` < Timeline > < azure . devops . v5_0 . task . models . Timeline > ` timeline :
: param str scope _ identifier : The project GUID to scope the request
: param str hub _ name : The name of t... | route_values = { }
if scope_identifier is not None :
route_values [ 'scopeIdentifier' ] = self . _serialize . url ( 'scope_identifier' , scope_identifier , 'str' )
if hub_name is not None :
route_values [ 'hubName' ] = self . _serialize . url ( 'hub_name' , hub_name , 'str' )
if plan_id is not None :
route_... |
def content_val ( self , ymldata = None , messages = None ) :
"""Validates the Telemetry Dictionary to ensure the contents for each of the fields
meets specific criteria regarding the expected types , byte ranges , etc .""" | # Turn off the YAML Processor
log . debug ( "BEGIN: Content-based validation of Telemetry dictionary" )
if ymldata is not None :
tlmdict = ymldata
else :
tlmdict = tlm . TlmDict ( self . _ymlfile )
try : # instantiate the document number . this will increment in order to
# track the line numbers and section whe... |
def validate ( mets_doc , xmlschema = METS_XSD_PATH , schematron = AM_SCT_PATH ) :
"""Validate a METS file using both an XMLSchema ( . xsd ) schema and a
schematron schema , the latter of which typically places additional
constraints on what a METS file can look like .""" | is_xsd_valid , xsd_error_log = xsd_validate ( mets_doc , xmlschema = xmlschema )
is_sct_valid , sct_report = schematron_validate ( mets_doc , schematron = schematron )
valid = is_xsd_valid and is_sct_valid
report = { "is_xsd_valid" : is_xsd_valid , "is_sct_valid" : is_sct_valid , "xsd_error_log" : xsd_error_log , "sct_... |
def remove_notes ( data ) :
"""Omit notes from a DataFrame object , where notes are identified as rows with non - numerical entries in the first column .
: param data : DataFrame object to remove notes from
: type data : Pandas . DataFrame
: return : DataFrame object with no notes
: rtype : Pandas . DataFra... | has_text = data . iloc [ : , 0 ] . astype ( str ) . str . contains ( '(?!e-)[a-zA-Z]' )
text_rows = list ( has_text . index [ has_text ] )
return data . drop ( text_rows ) |
def _sge_info ( queue ) :
"""Returns machine information for an sge job scheduler .""" | qhost_out = subprocess . check_output ( [ "qhost" , "-q" , "-xml" ] ) . decode ( )
qstat_queue = [ "-q" , queue ] if queue and "," not in queue else [ ]
qstat_out = subprocess . check_output ( [ "qstat" , "-f" , "-xml" ] + qstat_queue ) . decode ( )
slot_info = _sge_get_slots ( qstat_out )
mem_info = _sge_get_mem ( qho... |
def to_etree ( self ) :
"""creates an etree element of a ` ` SaltNode ` ` that mimicks a SaltXMI
< nodes > element""" | layers_attrib_val = ' ' . join ( '//@layers.{}' . format ( layer_id ) for layer_id in self . layers )
attribs = { '{{{pre}}}type' . format ( pre = NAMESPACES [ 'xsi' ] ) : self . xsi_type , 'layers' : layers_attrib_val }
E = ElementMaker ( )
node = E ( 'nodes' , attribs )
label_elements = ( label . to_etree ( ) for lab... |
def kebab_case ( string ) :
"""Converts a string to kebab case . For example : :
kebab _ case ( ' one _ two _ three ' ) - > ' one - two - three '
NOTE : To generate valid slugs , use : meth : ` slugify `""" | if not string :
return string
string = string . replace ( '_' , '-' ) . replace ( ' ' , '-' )
return de_camel ( string , '-' ) |
def toplevelTryFunc ( func , * args , ** kwargs ) :
'Thread entry - point for ` func ( * args , * * kwargs ) ` with try / except wrapper' | t = threading . current_thread ( )
t . name = func . __name__
ret = None
try :
ret = func ( * args , ** kwargs )
except EscapeException as e : # user aborted
t . status += 'aborted by user'
status ( '%s aborted' % t . name , priority = 2 )
except Exception as e :
t . exception = e
exceptionCaught ( ... |
def migrate_cluster ( cluster ) :
"""Called when loading a cluster when it comes from an older version
of elasticluster""" | for old , new in [ ( '_user_key_public' , 'user_key_public' ) , ( '_user_key_private' , 'user_key_private' ) , ( '_user_key_name' , 'user_key_name' ) , ] :
if hasattr ( cluster , old ) :
setattr ( cluster , new , getattr ( cluster , old ) )
delattr ( cluster , old )
for kind , nodes in cluster . nod... |
def newline_text ( self , text , indent = False ) :
"""Inserts a newline and text , optionally with indentation ( helper function )""" | self . newline ( indent )
self . text ( text ) |
def id ( self ) :
"""Return the distro ID of the OS distribution , as a string .
For details , see : func : ` distro . id ` .""" | def normalize ( distro_id , table ) :
distro_id = distro_id . lower ( ) . replace ( ' ' , '_' )
return table . get ( distro_id , distro_id )
distro_id = self . os_release_attr ( 'id' )
if distro_id :
return normalize ( distro_id , NORMALIZED_OS_ID )
distro_id = self . lsb_release_attr ( 'distributor_id' )
i... |
async def container_size ( self , container_len = None , container_type = None , params = None ) :
"""Container size
: param container _ len :
: param container _ type :
: param params :
: return :""" | if hasattr ( container_type , "serialize_archive" ) :
raise ValueError ( "not supported" )
if self . writing :
return await self . _dump_container_size ( self . iobj , container_len , container_type , params )
else :
raise ValueError ( "Not supported" ) |
def normalize_with_model ( vector , model ) :
r"""Normalize as with ` normalize ` , but not based on the data of the passed feature
vector , but rather on a learned model created with ` normalize ` . Thus formerly
unseen query data can be normalized according to the training data .
Parameters
vector : seque... | vector = numpy . array ( vector , dtype = numpy . float )
# unpack model
minp , maxp , minv , maxv = model
# add a singleton dimension if required
if 1 == vector . ndim :
vector = vector [ : , None ]
# shift outliers to fit range
for i in range ( vector . shape [ 1 ] ) :
vector [ : , i ] [ vector [ : , i ] < mi... |
def local_2d_halo_exchange ( k , v , num_h_blocks , h_dim , num_w_blocks , w_dim , mask_right ) :
"""Halo exchange for keys and values for Local 2D attention .""" | for blocks_dim , block_size_dim , halo_size in [ ( num_h_blocks , h_dim , h_dim . size ) , ( num_w_blocks , w_dim , w_dim . size ) ] : # shape of k is [ num _ h _ blocks , num _ w _ blocks , h _ dim , w _ dim , kv _ channels ]
if halo_size > 0 :
if blocks_dim is not None :
if mask_right :
... |
def predict_variant_effects ( variant , raise_on_error = False ) :
"""Determine the effects of a variant on any transcripts it overlaps .
Returns an EffectCollection object .
Parameters
variant : Variant
raise _ on _ error : bool
Raise an exception if we encounter an error while trying to
determine the ... | # if this variant isn ' t overlapping any genes , return a
# Intergenic effect
# TODO : look for nearby genes and mark those as Upstream and Downstream
# effects
if len ( variant . gene_ids ) == 0 :
effects = [ Intergenic ( variant ) ]
else : # list of all MutationEffects for all genes & transcripts
effects = [... |
def create_table_from_csv ( self , csv_source , table_name = "" , attr_names = ( ) , delimiter = "," , quotechar = '"' , encoding = "utf-8" , primary_key = None , add_primary_key_column = False , index_attrs = None , ) :
"""Create a table from a CSV file / text .
: param str csv _ source : Path to the CSV file or... | import pytablereader as ptr
loader = ptr . CsvTableFileLoader ( csv_source )
if typepy . is_not_null_string ( table_name ) :
loader . table_name = table_name
loader . headers = attr_names
loader . delimiter = delimiter
loader . quotechar = quotechar
loader . encoding = encoding
try :
for table_data in loader . ... |
def _dispense_plunger_position ( self , ul ) :
"""Calculate axis position for a given liquid volume .
Translates the passed liquid volume to absolute coordinates
on the axis associated with this pipette .
Calibration of the pipette motor ' s ul - to - mm conversion is required""" | millimeters = ul / self . _ul_per_mm ( ul , 'dispense' )
destination_mm = self . _get_plunger_position ( 'bottom' ) + millimeters
return round ( destination_mm , 6 ) |
def fetch_by_code ( self , code ) :
"""Retrieves an auth code by its code .
: param code : The code of an auth code .
: return : An instance of : class : ` oauth2 . datatype . AuthorizationCode ` .
: raises : : class : ` oauth2 . error . AuthCodeNotFound ` if no auth code could
be retrieved .""" | auth_code_data = self . fetchone ( self . fetch_code_query , code )
if auth_code_data is None :
raise AuthCodeNotFound
data = dict ( )
data_result = self . fetchall ( self . fetch_data_query , auth_code_data [ 0 ] )
if data_result is not None :
for dataset in data_result :
data [ dataset [ 0 ] ] = datas... |
def init_ui ( self ) :
"""Init game interface .""" | board_width = self . ms_game . board_width
board_height = self . ms_game . board_height
self . create_grid ( board_width , board_height )
self . time = 0
self . timer = QtCore . QTimer ( )
self . timer . timeout . connect ( self . timing_game )
self . timer . start ( 1000 ) |
def _remove_root_tag_prefix ( v ) :
"""Removes ' voe ' namespace prefix from root tag .
When we load in a VOEvent , the root element has a tag prefixed by
the VOE namespace , e . g . { http : / / www . ivoa . net / xml / VOEvent / v2.0 } VOEvent
Because objectify expects child elements to have the same namesp... | if v . prefix : # Create subelement without a prefix via etree . SubElement
etree . SubElement ( v , 'original_prefix' )
# Now carefully access said named subelement ( without prefix cascade )
# and alter the first value in the list of children with this name . . .
# LXML syntax is a minefield !
v [... |
def approx_equals ( self , other , atol ) :
"""Return ` ` True ` ` in case of approximate equality .
Returns
approx _ eq : bool
` ` True ` ` if ` ` other ` ` is a ` RectPartition ` instance with
` ` self . set = = other . set ` ` up to ` ` atol ` ` and
` ` self . grid = = other . other ` ` up to ` ` atol ... | if other is self :
return True
elif not isinstance ( other , RectPartition ) :
return False
else :
return ( self . set . approx_equals ( other . set , atol = atol ) and self . grid . approx_equals ( other . grid , atol = atol ) ) |
def add_const_spec ( self , const_spec ) :
"""Adds a ConstSpec to the compliation scope .
If the ConstSpec ' s ` ` save ` ` attribute is True , the constant will be
added to the module at the top - level .""" | if const_spec . name in self . const_specs :
raise ThriftCompilerError ( 'Cannot define constant "%s". That name is already taken.' % const_spec . name )
self . const_specs [ const_spec . name ] = const_spec |
def convert_line_endings ( filename : str , to_unix : bool = False , to_windows : bool = False ) -> None :
"""Converts a file ( in place ) from UNIX to Windows line endings , or the
reverse .
Args :
filename : filename to modify ( in place )
to _ unix : convert Windows ( CR LF ) to UNIX ( LF )
to _ window... | assert to_unix != to_windows
with open ( filename , "rb" ) as f :
contents = f . read ( )
windows_eol = b"\r\n"
# CR LF
unix_eol = b"\n"
# LF
if to_unix :
log . info ( "Converting from Windows to UNIX line endings: {!r}" , filename )
src = windows_eol
dst = unix_eol
else : # to _ windows
log . info ... |
def compact ( self , term_doc_matrix ) :
'''Parameters
term _ doc _ matrix : TermDocMatrix
Returns
New term doc matrix''' | tdf = self . term_ranker ( term_doc_matrix ) . get_ranks ( )
tdf_sum = tdf . sum ( axis = 0 )
tdf_portions = tdf / tdf_sum
threshold = np . max ( self . term_count / tdf_sum )
terms_to_remove = tdf_portions [ ~ ( tdf_portions > threshold ) . any ( axis = 1 ) ] . index
return term_doc_matrix . remove_terms ( terms_to_re... |
def mouseDoubleClickEvent ( self , event ) :
"""Override Qt method to trigger the tab name editor .""" | if self . rename_tabs is True and event . buttons ( ) == Qt . MouseButtons ( Qt . LeftButton ) : # Tab index
index = self . tabAt ( event . pos ( ) )
if index >= 0 : # Tab is valid , call tab name editor
self . tab_name_editor . edit_tab ( index )
else : # Event is not interesting , raise to parent
... |
def loader_for_type ( self , ctype ) :
"""Gets a function ref to deserialize content
for a certain mimetype .""" | for loadee , mimes in Mimer . TYPES . iteritems ( ) :
for mime in mimes :
if ctype . startswith ( mime ) :
return loadee |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.