signature stringlengths 29 44.1k | implementation stringlengths 0 85.2k |
|---|---|
def visit_addresses ( frame , return_addresses ) :
"""Visits all of the addresses , returns a new dict
which contains just the addressed elements
Parameters
frame
return _ addresses : a dictionary ,
keys will be column names of the resulting dataframe , and are what the
user passed in as ' return _ colu... | outdict = dict ( )
for real_name , ( pyname , address ) in return_addresses . items ( ) :
if address :
xrval = frame [ pyname ] . loc [ address ]
if xrval . size > 1 :
outdict [ real_name ] = xrval
else :
outdict [ real_name ] = float ( np . squeeze ( xrval . values )... |
def interruptWrite ( self , endpoint , buffer , timeout = 100 ) :
r"""Perform a interrupt write request to the endpoint specified .
Arguments :
endpoint : endpoint number .
buffer : sequence data buffer to write .
This parameter can be any sequence type .
timeout : operation timeout in milliseconds . ( de... | return self . dev . write ( endpoint , buffer , timeout ) |
def favorite_dashboard ( self , id , ** kwargs ) : # noqa : E501
"""Mark a dashboard as favorite # noqa : E501
# noqa : E501
This method makes a synchronous HTTP request by default . To make an
asynchronous HTTP request , please pass async _ req = True
> > > thread = api . favorite _ dashboard ( id , async ... | kwargs [ '_return_http_data_only' ] = True
if kwargs . get ( 'async_req' ) :
return self . favorite_dashboard_with_http_info ( id , ** kwargs )
# noqa : E501
else :
( data ) = self . favorite_dashboard_with_http_info ( id , ** kwargs )
# noqa : E501
return data |
def set_sns ( style = "white" , context = "paper" , font_scale = 1.5 , color_codes = True , rc = { } ) :
"""Set default plot style using seaborn .
Font size is set to match the size of the tick labels , rather than the axes
labels .""" | rcd = { "lines.markersize" : 8 , "lines.markeredgewidth" : 1.25 , "legend.fontsize" : "small" , "font.size" : 12 / 1.5 * font_scale , "legend.frameon" : True , "axes.formatter.limits" : ( - 5 , 5 ) , "axes.grid" : True }
rcd . update ( rc )
import seaborn as sns
sns . set ( style = style , context = context , font_scal... |
def unpack_frame ( message ) :
"""Called to unpack a STOMP message into a dictionary .
returned = {
# STOMP Command :
' cmd ' : ' . . . ' ,
# Headers e . g .
' headers ' : {
' destination ' : ' xyz ' ,
' message - id ' : ' some event ' ,
etc ,
# Body :
' body ' : ' . . . 1234 . . . \x00 ' ,""" | body = [ ]
returned = dict ( cmd = '' , headers = { } , body = '' )
breakdown = message . split ( '\n' )
# Get the message command :
returned [ 'cmd' ] = breakdown [ 0 ]
breakdown = breakdown [ 1 : ]
def headD ( field ) : # find the first ' : ' everything to the left of this is a
# header , everything to the right is d... |
def getcellslice ( self , columnname , rownr , blc , trc , inc = [ ] ) :
"""Get a slice from a column cell holding an array .
The columnname and ( 0 - relative ) rownr indicate the table cell .
The slice to get is defined by the blc , trc , and optional inc arguments
( blc = bottom - left corner , trc = top -... | return self . _getcellslice ( columnname , rownr , blc , trc , inc ) |
def badEntries ( self ) :
"""Creates a new collection of the same type with only the bad entries
# Returns
` CollectionWithIDs `
> A collection of only the bad entries""" | badEntries = set ( )
for i in self :
if i . bad :
badEntries . add ( i )
return type ( self ) ( badEntries , quietStart = True ) |
def evaluate ( self , env ) :
"""Evaluate the entire expression in the environment , returning
a Unicode string .""" | out = [ ]
for part in self . parts :
if isinstance ( part , str ) :
out . append ( part )
else :
out . append ( part . evaluate ( env ) )
return u'' . join ( map ( str , out ) ) |
def wait_for_next_completion ( self , runtime_context ) : # type : ( RuntimeContext ) - > None
"""Wait for jobs to finish .""" | if runtime_context . workflow_eval_lock is not None :
runtime_context . workflow_eval_lock . wait ( )
if self . exceptions :
raise self . exceptions [ 0 ] |
def allowed_values ( self ) :
"""A tuple containing the allowed values for this Slot .
The Python equivalent of the CLIPS slot - allowed - values function .""" | data = clips . data . DataObject ( self . _env )
lib . EnvDeftemplateSlotAllowedValues ( self . _env , self . _tpl , self . _name , data . byref )
return tuple ( data . value ) if isinstance ( data . value , list ) else ( ) |
def run ( self ) :
"""Run consumer""" | if KSER_METRICS_ENABLED == "yes" :
from prometheus_client import start_http_server
logger . info ( "Metric.Starting..." )
start_http_server ( os . getenv ( "KSER_METRICS_PORT" , 8888 ) , os . getenv ( "KSER_METRICS_ADDRESS" , "0.0.0.0" ) )
logger . info ( "{}.Starting..." . format ( self . __class__ . __nam... |
def eff_request_host ( request ) :
"""Return a tuple ( request - host , effective request - host name ) .
As defined by RFC 2965 , except both are lowercased .""" | erhn = req_host = request_host ( request )
if req_host . find ( "." ) == - 1 and not IPV4_RE . search ( req_host ) :
erhn = req_host + ".local"
return req_host , erhn |
def get_tables ( self , models ) :
'''Extract all peewee models from the passed in module''' | return { obj . _meta . db_table : obj for obj in models . __dict__ . itervalues ( ) if isinstance ( obj , peewee . BaseModel ) and len ( obj . _meta . fields ) > 1 } |
def _init_transforms ( self , subjs , voxels , features , random_state ) :
"""Initialize the mappings ( Wi ) with random orthogonal matrices .
Parameters
subjs : int
The number of subjects .
voxels : list of int
A list with the number of voxels per subject .
features : int
The number of features in th... | # Init the Random seed generator
np . random . seed ( self . rand_seed )
# Draw a random W for each subject
W = [ random_state . random_sample ( ( voxels [ i ] , features ) ) for i in range ( subjs ) ]
# Make it orthogonal it with QR decomposition
for i in range ( subjs ) :
W [ i ] , _ = np . linalg . qr ( W [ i ] ... |
def folder2db ( folder_name , debug , energy_limit , skip_folders , goto_reaction ) :
"""Read folder and collect data in local sqlite3 database""" | folder_name = folder_name . rstrip ( '/' )
skip = [ ]
for s in skip_folders . split ( ', ' ) :
for sk in s . split ( ',' ) :
skip . append ( sk )
pub_id = _folder2db . main ( folder_name , debug , energy_limit , skip , goto_reaction )
if pub_id :
print ( '' )
print ( '' )
print ( 'Ready to relea... |
def get_asm_uids ( taxon_uid ) :
"""Returns a set of NCBI UIDs associated with the passed taxon .
This query at NCBI returns all assemblies for the taxon subtree
rooted at the passed taxon _ uid .""" | query = "txid%s[Organism:exp]" % taxon_uid
logger . info ( "Entrez ESearch with query: %s" , query )
# Perform initial search for assembly UIDs with taxon ID as query .
# Use NCBI history for the search .
handle = entrez_retry ( Entrez . esearch , db = "assembly" , term = query , format = "xml" , usehistory = "y" )
rec... |
def find_item ( self , fq_name ) :
"""Find an item in the specification by fully qualified name .
Args :
fq _ name ( str ) : Fully - qualified name of the item .
Returns :
The item if it is in the specification . None otherwise""" | names = fq_name . split ( self . _separator )
current = self . _yapconf_items
for name in names :
if isinstance ( current , ( YapconfDictItem , YapconfListItem ) ) :
current = current . children
if name not in current :
return None
current = current [ name ]
return current |
def _get_delta ( self , now , then ) :
"""Internal helper which will return a ` ` datetime . timedelta ` `
representing the time between ` ` now ` ` and ` ` then ` ` . Assumes
` ` now ` ` is a ` ` datetime . date ` ` or ` ` datetime . datetime ` ` later
than ` ` then ` ` .
If ` ` now ` ` and ` ` then ` ` ar... | if now . __class__ is not then . __class__ :
now = datetime . date ( now . year , now . month , now . day )
then = datetime . date ( then . year , then . month , then . day )
if now < then :
raise ValueError ( "Cannot determine moderation rules because date field is set to a value in the future" )
return no... |
def get ( self , name : str ) -> Union [ None , str , List [ str ] ] :
"""获取 header""" | name = name . casefold ( )
if name == "referer" or name == "referrer" :
if "referrer" in self . _headers :
return self . _headers [ "referrer" ]
elif "referer" in self . _headers :
return self . _headers [ "referer" ]
else :
return None
elif name in self . _headers :
return self ... |
def unassign ( pid_type , pid_value ) :
"""Unassign persistent identifier .""" | from . models import PersistentIdentifier
obj = PersistentIdentifier . get ( pid_type , pid_value )
obj . unassign ( )
db . session . commit ( )
click . echo ( obj . status ) |
def reverse_cipher ( message ) :
"""反转加密法
: param message : 待加密字符串
: return : 被加密字符串""" | translated = ''
i = len ( message ) - 1
while i >= 0 :
translated = translated + message [ i ]
i = i - 1
return translated |
def from_css ( Class , csstext , encoding = None , href = None , media = None , title = None , validate = None ) :
"""parse CSS text into a Styles object , using cssutils""" | styles = Class ( )
cssStyleSheet = cssutils . parseString ( csstext , encoding = encoding , href = href , media = media , title = title , validate = validate )
for rule in cssStyleSheet . cssRules :
if rule . type == cssutils . css . CSSRule . FONT_FACE_RULE :
if styles . get ( '@font-face' ) is None :
... |
def get_data ( latitude = 52.091579 , longitude = 5.119734 , usexml = False ) :
"""Get buienradar xml data and return results .""" | if usexml :
log . info ( "Getting buienradar XML data for latitude=%s, longitude=%s" , latitude , longitude )
return get_xml_data ( latitude , longitude )
else :
log . info ( "Getting buienradar JSON data for latitude=%s, longitude=%s" , latitude , longitude )
return get_json_data ( latitude , longitude... |
def parse_cache ( self , full_df ) :
"""Format the cached data model into a dictionary of DataFrames
and a criteria map DataFrame .
Parameters
full _ df : DataFrame
result of self . get _ dm _ offline ( )
Returns
data _ model : dictionary of DataFrames
crit _ map : DataFrame""" | data_model = { }
levels = [ 'specimens' , 'samples' , 'sites' , 'locations' , 'ages' , 'measurements' , 'criteria' , 'contribution' , 'images' ]
criteria_map = pd . DataFrame ( full_df [ 'criteria_map' ] )
for level in levels :
df = pd . DataFrame ( full_df [ 'tables' ] [ level ] [ 'columns' ] )
data_model [ le... |
def send_raw_packet ( self , packet : str ) :
"""Encode and put packet string onto write buffer .""" | data = packet + '\r\n'
log . debug ( 'writing data: %s' , repr ( data ) )
self . transport . write ( data . encode ( ) ) |
def variant ( case_id , variant_id ) :
"""Show a single variant .""" | case_obj = app . db . case ( case_id )
variant = app . db . variant ( case_id , variant_id )
if variant is None :
return abort ( 404 , "variant not found" )
comments = app . db . comments ( variant_id = variant . md5 )
template = 'sv_variant.html' if app . db . variant_type == 'sv' else 'variant.html'
return render... |
def rank ( self , item ) :
'''Return the rank ( index ) of ` ` item ` ` in this : class : ` zset ` .''' | score = self . _dict . get ( item )
if score is not None :
return self . _sl . rank ( score ) |
def _get_free_words ( self , blockAllowed , isRead ) :
"""Return the number of words free in the transmit packet""" | if blockAllowed : # DAP _ TransferBlock request packet :
# BYTE | BYTE * * * * * | SHORT * * * * * | BYTE * * * * * | WORD * * * * * |
# > 0x06 | DAP Index | Transfer Count | Transfer Request | Transfer Data |
send = self . _size - 5 - 4 * self . _write_count
# DAP _ TransferBlock response packet :
# BYTE |... |
def _mutate ( self ) :
'''Mutate enclosed fields''' | for i in range ( self . _field_idx , len ( self . _fields ) ) :
self . _field_idx = i
if self . _current_field ( ) . mutate ( ) :
return True
self . _current_field ( ) . reset ( )
return False |
def _relativePath ( self , fullPath ) :
"""Return fullPath relative to Store directory .
Return fullPath if fullPath is not inside directory .
Return None if fullPath is outside our scope .""" | if fullPath is None :
return None
assert fullPath . startswith ( "/" ) , fullPath
path = os . path . relpath ( fullPath , self . userPath )
if not path . startswith ( "../" ) :
return path
elif self . ignoreExtraVolumes :
return None
else :
return fullPath |
def handle_prepared_selection_of_core_class_elements ( self , core_class , models ) :
"""Handles the selection for TreeStore widgets maintaining lists of a specific ` core _ class ` elements
If widgets hold a TreeStore with elements of a specific ` core _ class ` , the local selection of that element
type is ha... | if extend_selection ( ) :
self . _selected . difference_update ( self . get_selected_elements_of_core_class ( core_class ) )
else :
self . _selected . clear ( )
models = self . _check_model_types ( models )
if len ( models ) > 1 :
models = reduce_to_parent_states ( models )
self . _selected . update ( model... |
def extend ( self , http_api , route = "" , base_url = "" , ** kwargs ) :
"""Adds handlers from a different Hug API to this one - to create a single API""" | self . versions . update ( http_api . versions )
base_url = base_url or self . base_url
for router_base_url , routes in http_api . routes . items ( ) :
self . routes . setdefault ( base_url , OrderedDict ( ) )
for item_route , handler in routes . items ( ) :
for method , versions in handler . items ( ) ... |
def derivative ( self , z , x , y , fase ) :
"""Wrapper derivative for custom derived properties
where x , y , z can be : P , T , v , rho , u , h , s , g , a""" | return deriv_H ( self , z , x , y , fase ) |
def smooth_gaps ( self , min_intron ) :
"""any gaps smaller than min _ intron are joined , andreturns a new mapping with gaps smoothed
: param min _ intron : the smallest an intron can be , smaller gaps will be sealed
: type min _ intron : int
: return : a mapping with small gaps closed
: rtype : MappingGen... | rngs = [ self . _rngs [ 0 ] . copy ( ) ]
for i in range ( len ( self . _rngs ) - 1 ) :
dist = - 1
if self . _rngs [ i + 1 ] . chr == rngs [ - 1 ] . chr :
dist = self . _rngs [ i + 1 ] . start - rngs [ - 1 ] . end - 1
if dist >= min_intron or dist < 0 :
rngs . append ( self . _rngs [ i + 1 ] ... |
def _log_control ( self , s ) :
"""Write control characters to the appropriate log files""" | if self . encoding is not None :
s = s . decode ( self . encoding , 'replace' )
self . _log ( s , 'send' ) |
def slackbuild ( self , name , sbo_file ) :
"""Read SlackBuild file""" | return URL ( self . sbo_url + name + sbo_file ) . reading ( ) |
def _RunUserDefinedFunctions_ ( config , data , histObj , position , namespace = __name__ ) :
"""Return a single updated data record and history object after running user - defined functions
: param dict config : DWM configuration ( see DataDictionary )
: param dict data : single record ( dictionary ) to which ... | udfConfig = config [ 'userDefinedFunctions' ]
if position in udfConfig :
posConfig = udfConfig [ position ]
for udf in posConfig . keys ( ) :
posConfigUDF = posConfig [ udf ]
data , histObj = getattr ( sys . modules [ namespace ] , posConfigUDF ) ( data = data , histObj = histObj )
return data ,... |
def _send_paginated_message ( self , endpoint , params = None ) :
"""Send API message that results in a paginated response .
The paginated responses are abstracted away by making API requests on
demand as the response is iterated over .
Paginated API messages support 3 additional parameters : ` before ` ,
`... | if params is None :
params = dict ( )
url = self . url + endpoint
while True :
r = self . session . get ( url , params = params , auth = self . auth , timeout = 30 )
results = r . json ( )
for result in results :
yield result
# If there are no more pages , we ' re done . Otherwise update ` a... |
def list_files ( tag = None , sat_id = None , data_path = None , format_str = None ) :
"""Return a Pandas Series of every file for chosen satellite data
Parameters
tag : ( string or NoneType )
Denotes type of file to load . Accepted types are ' ' and ' ascii ' .
If ' ' is specified , the primary data type (... | import sys
# if tag = = ' ionprf ' :
# # from _ os constructor currently doesn ' t work because of the variable
# # filename components at the end of each string . . . . .
# ion _ fmt = ' * / ionPrf _ * . { year : 04d } . { day : 03d } . { hour : 02d } . { min : 02d } * _ nc '
# return pysat . Files . from _ os ( dir _... |
def close ( self ) :
"""Close connection to an MS SQL Server .
This function tries to close the connection and free all memory used .
It can be called more than once in a row . No exception is raised in
this case .""" | if self . _conn :
if self . _pooling :
_connection_pool . add ( self . _key , ( self . _conn , self . _main_cursor . _session ) )
else :
self . _conn . close ( )
self . _active_cursor = None
self . _main_cursor = None
self . _conn = None
self . _closed = True |
def get_penalty_model ( specification ) :
"""Factory function for penaltymodel _ maxgap .
Args :
specification ( penaltymodel . Specification ) : The specification
for the desired penalty model .
Returns :
: class : ` penaltymodel . PenaltyModel ` : Penalty model with the given specification .
Raises : ... | # check that the feasible _ configurations are spin
feasible_configurations = specification . feasible_configurations
if specification . vartype is dimod . BINARY :
feasible_configurations = { tuple ( 2 * v - 1 for v in config ) : en for config , en in feasible_configurations . items ( ) }
# convert ising _ quadrat... |
def queryURL ( self , xri , service_type = None ) :
"""Build a URL to query the proxy resolver .
@ param xri : An XRI to resolve .
@ type xri : unicode
@ param service _ type : The service type to resolve , if you desire
service endpoint selection . A service type is a URI .
@ type service _ type : str
... | # Trim off the xri : / / prefix . The proxy resolver didn ' t accept it
# when this code was written , but that may ( or may not ) change for
# XRI Resolution 2.0 Working Draft 11.
qxri = toURINormal ( xri ) [ 6 : ]
hxri = self . proxy_url + qxri
args = { # XXX : If the proxy resolver will ensure that it doesn ' t retu... |
def from_file ( cls , fname , form = None ) :
"""Read an orthography profile from a metadata file or a default tab - separated profile file .""" | try :
tg = TableGroup . from_file ( fname )
opfname = None
except JSONDecodeError :
tg = TableGroup . fromvalue ( cls . MD )
opfname = fname
if len ( tg . tables ) != 1 :
raise ValueError ( 'profile description must contain exactly one table' )
metadata = tg . common_props
metadata . update ( fname ... |
def get ( self , key ) :
"""get a set of keys from redis""" | res = self . connection . get ( key )
print ( res )
return res |
def initialize_segment_register_x64 ( self , state , concrete_target ) :
"""Set the gs register in the angr to the value of the fs register in the concrete process
: param state : state which will be modified
: param concrete _ target : concrete target that will be used to read the fs register
: return : None... | _l . debug ( "Synchronizing gs segment register" )
state . regs . gs = self . _read_gs_register_x64 ( concrete_target ) |
def decode ( self ) :
"""Decode this report from a msgpack encoded binary blob .""" | report_dict = msgpack . unpackb ( self . raw_report , raw = False )
events = [ IOTileEvent . FromDict ( x ) for x in report_dict . get ( 'events' , [ ] ) ]
readings = [ IOTileReading . FromDict ( x ) for x in report_dict . get ( 'data' , [ ] ) ]
if 'device' not in report_dict :
raise DataError ( "Invalid encoded Fl... |
def connection_factory_absent ( name , both = True , server = None ) :
'''Ensures the transaction factory is absent .
name
Name of the connection factory
both
Delete both the pool and the resource , defaults to ` ` true ` `''' | ret = { 'name' : name , 'result' : None , 'comment' : None , 'changes' : { } }
pool_name = '{0}-Connection-Pool' . format ( name )
pool_ret = _do_element_absent ( pool_name , 'connector_c_pool' , { 'cascade' : both } , server )
if not pool_ret [ 'error' ] :
if __opts__ [ 'test' ] and pool_ret [ 'delete' ] :
... |
def request_url ( self , request , proxies ) :
"""Obtain the url to use when making the final request .
If the message is being sent through a HTTP proxy , the full URL has to
be used . Otherwise , we should only use the path portion of the URL .
This should not be called from user code , and is only exposed ... | proxies = proxies or { }
scheme = urlparse ( request . url ) . scheme
proxy = proxies . get ( scheme )
if proxy and scheme != 'https' :
url = urldefragauth ( request . url )
else :
url = request . path_url
return url |
def get_max_val_indices ( input_list ) :
"""This function determines all indices of the maximum values in the supplied list .
Examples :
> > > get _ max _ val _ indices ( [ 12 , 33 , 23 , 10 , 67 , 89 , 45 , 667 , 23 , 12 , 11 , 10 , 54 ] )
> > > get _ max _ val _ indices ( [ 1 , 2 , 2 , 2 , 4 , 4 , 4 , 5 , 5... | max_value = max ( input_list )
indices = [ index for index , value in enumerate ( input_list ) if value == max_value ]
return indices |
def load_completions ( self ) :
"""Load completions from the completion index .
Updates the following attributes :
* commands
* subcommands
* global _ opts
* args _ opts""" | try :
index_str = self . load_index ( utils . AWSCLI_VERSION )
except IndexLoadError :
return
index_str = self . load_index ( utils . AWSCLI_VERSION )
index_data = json . loads ( index_str )
index_root = index_data [ 'aws' ]
# ec2 , s3 , elb . . .
self . commands = index_root [ 'commands' ]
# - - profile , - - ... |
def _parse_family_pb ( family_pb ) :
"""Parses a Family protobuf into a dictionary .
: type family _ pb : : class : ` . _ generated . data _ pb2 . Family `
: param family _ pb : A protobuf
: rtype : tuple
: returns : A string and dictionary . The string is the name of the
column family and the dictionary ... | result = { }
for column in family_pb . columns :
result [ column . qualifier ] = cells = [ ]
for cell in column . cells :
val_pair = ( cell . value , _datetime_from_microseconds ( cell . timestamp_micros ) )
cells . append ( val_pair )
return family_pb . name , result |
def switch_showfilter_icon ( self , toggled ) :
"""Switch the icon on the showfilter _ tb
: param toggled : the state of the button
: type toggled : : class : ` bool `
: returns : None
: rtype : None
: raises : None""" | at = QtCore . Qt . DownArrow if toggled else QtCore . Qt . RightArrow
self . showfilter_tb . setArrowType ( at ) |
def _make_verb_helper ( verb_func , add_groups = False ) :
"""Create function that prepares verb for the verb function
The functions created add expressions to be evaluated to
the verb , then call the core verb function
Parameters
verb _ func : function
Core verb function . This is the function called aft... | @ wraps ( verb_func )
def _verb_func ( verb ) :
verb . expressions , new_columns = build_expressions ( verb )
if add_groups :
verb . groups = new_columns
return verb_func ( verb )
return _verb_func |
def mock_stream ( hamiltonian , prog_orbit , prog_mass , k_mean , k_disp , release_every = 1 , Integrator = DOPRI853Integrator , Integrator_kwargs = dict ( ) , snapshot_filename = None , output_every = 1 , seed = None ) :
"""Generate a mock stellar stream in the specified potential with a
progenitor system that e... | if isinstance ( hamiltonian , CPotentialBase ) :
warnings . warn ( "This function now expects a `Hamiltonian` instance " "instead of a `PotentialBase` subclass instance. If you " "are using a static reference frame, you just need to " "pass your potential object in to the Hamiltonian " "constructor to use, e.g., Ha... |
def select_between_exonic_splice_site_and_alternate_effect ( effect ) :
"""If the given effect is an ExonicSpliceSite then it might contain
an alternate effect of higher priority . In that case , return the
alternate effect . Otherwise , this acts as an identity function .""" | if effect . __class__ is not ExonicSpliceSite :
return effect
if effect . alternate_effect is None :
return effect
splice_priority = effect_priority ( effect )
alternate_priority = effect_priority ( effect . alternate_effect )
if splice_priority > alternate_priority :
return effect
else :
return effect ... |
def _chglog ( amend : bool = False , stage : bool = False , next_version : str = None , auto_next_version : bool = False ) :
"""Writes the changelog
Args :
amend : amend last commit with changes
stage : stage changes""" | if config . CHANGELOG_DISABLE ( ) :
LOGGER . info ( 'skipping changelog update as per config' )
else :
epab . utils . ensure_exe ( 'git' )
epab . utils . ensure_exe ( 'gitchangelog' )
LOGGER . info ( 'writing changelog' )
if auto_next_version :
next_version = epab . utils . get_next_version ... |
def has_true ( self , e , extra_constraints = ( ) , solver = None , model_callback = None ) : # pylint : disable = unused - argument
"""Should return True if ` e ` can possible be True .
: param e : The AST .
: param extra _ constraints : Extra constraints ( as ASTs ) to add to the solver for this solve .
: p... | # if self . _ solver _ required and solver is None :
# raise BackendError ( " % s requires a solver for evaluation " % self . _ _ class _ _ . _ _ name _ _ )
return self . _has_true ( self . convert ( e ) , extra_constraints = extra_constraints , solver = solver , model_callback = model_callback ) |
def _call ( self , x , out = None ) :
"""Implement ` ` self ( x [ , out ] ) ` ` .""" | if out is None :
return self . vector * self . functional ( x )
else :
scalar = self . functional ( x )
out . lincomb ( scalar , self . vector ) |
def read_csv_with_different_type ( csv_name , column_types_dict , usecols = None ) :
"""Returns a DataFrame from a . csv file stored in / data / raw / .
Reads the CSV as string .""" | csv_path = os . path . join ( DATA_FOLDER , csv_name )
csv = pd . read_csv ( csv_path , usecols = usecols , encoding = "utf-8" , dtype = column_types_dict , engine = "python" , )
for key_column , val_type in column_types_dict . items ( ) :
if val_type == str :
csv [ key_column ] = csv [ key_column ] . str .... |
def get_apex ( self , lat , height = None ) :
"""Calculate apex height
Parameters
lat : ( float )
Latitude in degrees
height : ( float or NoneType )
Height above the surface of the earth in km or NoneType to use
reference height ( default = None )
Returns
apex _ height : ( float )
Height of the fi... | lat = helpers . checklat ( lat , name = 'alat' )
if height is None :
height = self . refh
cos_lat_squared = np . cos ( np . radians ( lat ) ) ** 2
apex_height = ( self . RE + height ) / cos_lat_squared - self . RE
return apex_height |
def setFixedHeight ( self , height ) :
"""Sets the maximum height value to the inputed height and emits the sizeConstraintChanged signal .
: param height | < int >""" | super ( XView , self ) . setFixedHeight ( height )
if ( not self . signalsBlocked ( ) ) :
self . sizeConstraintChanged . emit ( ) |
def one ( self ) :
"""Return a single row of the results or None if empty . This is basically
a shortcut to ` result _ set . current _ rows [ 0 ] ` and should only be used when
you know a query returns a single row . Consider using an iterator if the
ResultSet contains more than one row .""" | row = None
if self . _current_rows :
try :
row = self . _current_rows [ 0 ]
except TypeError : # generator object is not subscriptable , PYTHON - 1026
row = next ( iter ( self . _current_rows ) )
return row |
def make_header ( self , locale , catalog ) :
"""Populate header with correct data from top - most locale file .""" | return { "po-revision-date" : self . get_catalogue_header_value ( catalog , 'PO-Revision-Date' ) , "mime-version" : self . get_catalogue_header_value ( catalog , 'MIME-Version' ) , "last-translator" : 'Automatic <hi@thorgate.eu>' , "x-generator" : "Python" , "language" : self . get_catalogue_header_value ( catalog , 'L... |
def estimateBackgroundLevel ( img , image_is_artefact_free = False , min_rel_size = 0.05 , max_abs_size = 11 ) :
'''estimate background level through finding the most homogeneous area
and take its average
min _ size - relative size of the examined area''' | s0 , s1 = img . shape [ : 2 ]
s = min ( max_abs_size , int ( max ( s0 , s1 ) * min_rel_size ) )
arr = np . zeros ( shape = ( s0 - 2 * s , s1 - 2 * s ) , dtype = img . dtype )
# fill arr :
_spatialStd ( img , arr , s )
# most homogeneous area :
i , j = np . unravel_index ( arr . argmin ( ) , arr . shape )
sub = img [ in... |
def registered ( self , driver , frameworkId , masterInfo ) :
"""Invoked when the scheduler successfully registers with a Mesos master""" | log . debug ( "Registered with framework ID %s" , frameworkId . value )
# Save the framework ID
self . frameworkId = frameworkId . value |
def find ( self , path , resolved = True ) :
"""Get the definition object for the schema type located at the specified
path .
The path may contain ( . ) dot notation to specify nested types .
Actually , the path separator is usually a ( . ) but can be redefined
during contruction .
@ param path : A ( . ) ... | result = None
parts = self . split ( path )
try :
result = self . root ( parts )
if len ( parts ) > 1 :
result = result . resolve ( nobuiltin = True )
result = self . branch ( result , parts )
result = self . leaf ( result , parts )
if resolved :
result = result . resolve ( n... |
def read_file ( filename ) :
"""Read contents of the specified file .
Parameters :
filename : str
The name of the file to be read
Returns :
lines : list of str
The contents of the file , split by line""" | infile = open ( filename , 'r' )
lines = infile . readlines ( )
infile . close ( )
return lines |
def hooks ( ctx ) :
"""List registered hooks ( in the order they run ) .""" | from . . hooks . run_hooks_hook import RunHooksHook
bundles = _get_bundles ( ctx . obj . data [ 'env' ] )
hooks = RunHooksHook ( None ) . collect_from_bundles ( bundles )
print_table ( ( 'Hook Name' , 'Default Bundle Module' , 'Bundle Module Override Attr' , 'Description' ) , [ ( hook . name , hook . bundle_module_name... |
def import_string ( import_name , silent = False ) :
"""Imports an object based on a string . This is useful if you want to
use import paths as endpoints or something similar . An import path can
be specified either in dotted notation ( ` ` xml . sax . saxutils . escape ` ` )
or with a colon as object delimit... | # XXX : py3 review needed
assert isinstance ( import_name , string_types )
# force the import name to automatically convert to strings
import_name = str ( import_name )
try :
if ':' in import_name :
module , obj = import_name . split ( ':' , 1 )
elif '.' in import_name :
module , obj = import_na... |
def download_page ( url , data = None ) :
'''Returns the response for the given url . The optional data argument is
passed directly to urlopen .''' | conn = urllib2 . urlopen ( url , data )
resp = conn . read ( )
conn . close ( )
return resp |
def recursive_copy ( source , destination ) :
"""A wrapper around distutils . dir _ util . copy _ tree but won ' t throw any exception when the source
directory does not exist .
Args :
source ( str ) : source path
destination ( str ) : destination path""" | if os . path . isdir ( source ) :
copy_tree ( source , destination ) |
def encrypt_state_m ( self , plaintext_in , key_in , reset ) :
"""Builds a multiple cycle AES Encryption state machine circuit
: param reset : a one bit signal telling the state machine
to reset and accept the current plaintext and key
: return ready , cipher _ text : ready is a one bit signal showing
that ... | if len ( key_in ) != len ( plaintext_in ) :
raise pyrtl . PyrtlError ( "AES key and plaintext should be the same length" )
plain_text , key = ( pyrtl . Register ( len ( plaintext_in ) ) for i in range ( 2 ) )
key_exp_in , add_round_in = ( pyrtl . WireVector ( len ( plaintext_in ) ) for i in range ( 2 ) )
counter = ... |
def gcp ( main = False ) :
"""Get the current project
Parameters
main : bool
If True , the current main project is returned , otherwise the current
subproject is returned .
See Also
scp : Sets the current project
project : Creates a new project""" | if main :
return project ( ) if _current_project is None else _current_project
else :
return gcp ( True ) if _current_subproject is None else _current_subproject |
def cmd_devop ( self , args ) :
'''device operations''' | usage = "Usage: devop <read|write> <spi|i2c> name bus address"
if len ( args ) < 5 :
print ( usage )
return
if args [ 1 ] == 'spi' :
bustype = mavutil . mavlink . DEVICE_OP_BUSTYPE_SPI
elif args [ 1 ] == 'i2c' :
bustype = mavutil . mavlink . DEVICE_OP_BUSTYPE_I2C
else :
print ( usage )
if args [ 0 ]... |
def complete_invoice ( self , invoice_id , complete_dict ) :
"""Completes an invoice
: param complete _ dict : the complete dict with the template id
: param invoice _ id : the invoice id
: return : Response""" | return self . _create_put_request ( resource = INVOICES , billomat_id = invoice_id , command = COMPLETE , send_data = complete_dict ) |
def _get_run_input_fields_for_applet ( executable_input , ** kwargs ) :
'''Takes the same arguments as the run method . Creates an input
hash for the / applet - xxxx / run method .''' | # Although it says " for _ applet " , this is factored out of
# DXApplet because apps currently use the same mechanism
for unsupported_arg in [ 'stage_instance_types' , 'stage_folders' , 'rerun_stages' , 'ignore_reuse_stages' ] :
if kwargs . get ( unsupported_arg ) :
raise DXError ( unsupported_arg + ' is n... |
def cbpdnmd_ystep ( k ) :
"""Do the Y step of the cbpdn stage . The only parameter is the slice
index ` k ` and there are no return values ; all inputs and outputs are
from and to global variables .""" | if mp_W . shape [ 0 ] > 1 :
W = mp_W [ k ]
else :
W = mp_W
AXU0 = mp_DX [ k ] - mp_S [ k ] + mp_Z_U0 [ k ]
AXU1 = mp_Z_X [ k ] + mp_Z_U1 [ k ]
mp_Z_Y0 [ k ] = mp_xrho * AXU0 / ( W ** 2 + mp_xrho )
mp_Z_Y1 [ k ] = sp . prox_l1 ( AXU1 , ( mp_lmbda / mp_xrho ) ) |
def grouper_dict ( d , n ) :
"""Evenly divide dictionary into fixed - length piece , no filled value if
chunk size smaller than fixed - length .
Usage : :
> > > list ( grouper _ dict ( { 1 : ' A ' , 2 : ' B ' , 3 : ' C ' , 4 : ' D ' , 5 : ' E ' ,
6 : ' F ' , 7 : ' G ' , 8 : ' H ' , 9 : ' I ' , 10 : ' J ' } ... | chunk = dict ( )
counter = 0
for k , v in d . items ( ) :
counter += 1
chunk [ k ] = v
print ( counter , chunk )
if counter == n :
yield chunk
chunk = dict ( )
counter = 0
if len ( chunk ) > 0 :
yield chunk |
def size ( ctx , dataset , kwargs ) :
"Show dataset size" | kwargs = parse_kwargs ( kwargs )
( print ) ( data ( dataset , ** ctx . obj ) . get ( ** kwargs ) . complete_set . size ) |
def get_last_weekday_in_month ( year , month , weekday ) :
"""Get the last weekday in a given month . e . g :
> > > # the last monday in Jan 2013
> > > Calendar . get _ last _ weekday _ in _ month ( 2013 , 1 , MON )
datetime . date ( 2013 , 1 , 28)""" | day = date ( year , month , monthrange ( year , month ) [ 1 ] )
while True :
if day . weekday ( ) == weekday :
break
day = day - timedelta ( days = 1 )
return day |
def get_upload_content ( pmid , force_fulltext_lookup = False ) :
"""Get full text and / or abstract for paper and upload to S3.""" | # Make sure that the PMID doesn ' t start with PMID so that it doesn ' t
# screw up the literature clients
if pmid . startswith ( 'PMID' ) :
pmid = pmid [ 4 : ]
# First , check S3:
( ft_content_s3 , ft_content_type_s3 ) = get_full_text ( pmid )
# The abstract is on S3 but there is no full text ; if we ' re not forc... |
def iter_sources ( self ) :
"""Iterates over all source names and IDs .""" | for src_id in xrange ( self . get_source_count ( ) ) :
yield src_id , self . get_source_name ( src_id ) |
def items ( self ) :
"""Get all list items""" | query = self . get_queryset ( )
fields = self . get_model_config ( ) . get_list_fields ( )
for item in query . iterator ( ) :
row = OrderedDict ( )
for field_name in self . get_current_fields ( ) :
field = fields . get ( field_name )
if not field_name :
row [ field_name ] = ''
... |
def inet_ntoa ( address ) :
"""Convert a network format IPv6 address into text .
@ param address : the binary address
@ type address : string
@ rtype : string
@ raises ValueError : the address isn ' t 16 bytes long""" | if len ( address ) != 16 :
raise ValueError ( "IPv6 addresses are 16 bytes long" )
hex = address . encode ( 'hex_codec' )
chunks = [ ]
i = 0
l = len ( hex )
while i < l :
chunk = hex [ i : i + 4 ]
# strip leading zeros . we do this with an re instead of
# with lstrip ( ) because lstrip ( ) didn ' t supp... |
def parameters ( self , value ) :
"""Used to set all of the model ' s parameters to new values .
* * Parameters : * *
value : array _ like
New values for the model parameters . Must be of length
` ` self . n _ parameters ` ` .""" | if len ( value ) != self . n_parameters :
raise ValueError ( "Incorrect length of parameter vector. " "Model has %d parameters, but got %d" % ( self . n_parameters , len ( value ) ) )
i = 0
for hl in self . hidden_layers :
hl . parameters = value [ i : i + hl . n_parameters ]
i += hl . n_parameters
self . t... |
def inverse_transform ( t ) :
"""Return the inverse transformation of t
: param t : A transform [ [ x , y , z ] , [ x , y , z , w ] ]
: return : t2 such as multiply _ transform _ ( t , t2 ) = [ [ 0 , 0 , 0 ] , [ 0 , 0 , 0 , 1 ] ]""" | return [ quat_rotate ( tf . transformations . quaternion_inverse ( t [ 1 ] ) , [ - t [ 0 ] [ 0 ] , - t [ 0 ] [ 1 ] , - t [ 0 ] [ 2 ] ] ) , tf . transformations . quaternion_inverse ( t [ 1 ] ) ] |
def delete_all ( self , * args , ** kwargs ) :
"""Deletes objects that match a set of conditions supplied .
This method forwards filters directly to the repository . It does not instantiate entities and
it does not trigger Entity callbacks or validations .
Returns the number of objects matched and deleted .""... | deleted_item_count = 0
repository = repo_factory . get_repository ( self . _entity_cls )
try :
deleted_item_count = repository . delete_all ( self . _criteria )
except Exception : # FIXME Log Exception
raise
return deleted_item_count |
def _assert_is_dictlike ( maybe_dictlike , valid_keys ) :
"""Raises a TypeError iff ` maybe _ dictlike ` is not a dictlike object .""" | # This covers a common mistake when people use incorrect dictionary nesting
# for initializers / partitioners etc . The previous error message was quite
# opaque , this should be much clearer .
if not hasattr ( maybe_dictlike , "__getitem__" ) :
raise TypeError ( "Expected a dict-like object with possible keys %s, ... |
def _gwf_channel_segments ( path , channel , warn = True ) :
"""Yields the segments containing data for ` ` channel ` ` in this GWF path""" | stream = open_gwf ( path )
# get segments for frames
toc = stream . GetTOC ( )
secs = toc . GetGTimeS ( )
nano = toc . GetGTimeN ( )
dur = toc . GetDt ( )
readers = [ getattr ( stream , 'ReadFr{0}Data' . format ( type_ . title ( ) ) ) for type_ in ( "proc" , "sim" , "adc" ) ]
# for each segment , try and read the data ... |
def tx_extract ( payload , senders , inputs , outputs , block_id , vtxindex , txid ) :
"""Extract and return a dict of fields from the underlying blockchain transaction data
that are useful to this operation .
structure :
inputs | outputs
sender scriptsig + scriptPubkey | OP _ RETURN with token transfer pay... | sender_script = None
sender_address = None
recipient_script = None
recipient_address = None
try : # first two outputs matter to us
assert check_tx_output_types ( outputs [ : 2 ] , block_id )
assert len ( senders ) > 0
assert 'script_pubkey' in senders [ 0 ] . keys ( )
assert 'addresses' in senders [ 0 ]... |
async def _flowupdater ( self ) :
"""Coroutine calling ` updateflow ( ) `""" | lastresult = set ( v for v in self . _savedresult if v is not None and not v . isdeleted ( ) )
flowupdate = FlowUpdaterNotification . createMatcher ( self , FlowUpdaterNotification . FLOWUPDATE )
while True :
currentresult = [ v for v in self . _savedresult if v is not None and not v . isdeleted ( ) ]
# Calcula... |
def cmd ( send , msg , args ) :
"""Translate something .
Syntax : { command } [ - - from < language code > ] [ - - to < language code > ] < text >
See https : / / cloud . google . com / translate / v2 / translate - reference # supported _ languages for a list of valid language codes""" | parser = arguments . ArgParser ( args [ 'config' ] )
parser . add_argument ( '--lang' , '--from' , default = None )
parser . add_argument ( '--to' , default = 'en' )
parser . add_argument ( 'msg' , nargs = '+' )
try :
cmdargs = parser . parse_args ( msg )
except arguments . ArgumentException as e :
send ( str (... |
async def complete ( self , code : str , opts : dict = None ) -> Iterable [ str ] :
'''Gets the auto - completion candidates from the given code string ,
as if a user has pressed the tab key just after the code in
IDEs .
Depending on the language of the compute session , this feature
may not be supported . ... | opts = { } if opts is None else opts
params = { }
if self . owner_access_key :
params [ 'owner_access_key' ] = self . owner_access_key
rqst = Request ( self . session , 'POST' , '/kernel/{}/complete' . format ( self . kernel_id ) , params = params )
rqst . set_json ( { 'code' : code , 'options' : { 'row' : int ( op... |
def evaluate ( self , x ) :
'''Evaluate this polynomial at value x , returning the result ( which is the sum of all evaluations at each term ) .''' | # Holds the sum over each term in the polynomial
# c = 0
# Holds the current power of x . This is multiplied by x after each term
# in the polynomial is added up . Initialized to x ^ 0 = 1
# p = 1
# for term in self . coefficients [ : : - 1 ] :
# c = c + term * p
# p = p * x
# return c
# Faster alternative using Horner... |
def _right_zero_blocks ( self , r ) :
"""Number of blocks with zeros from the right in block row ` r ` .""" | if not self . _include_off_diagonal :
return self . _block_rows - r - 1
elif self . _upper :
return 0
elif self . _include_diagonal :
return self . _block_rows - r - 1
else :
return self . _block_rows - r |
def sent_folder ( self ) :
"""Shortcut to get SentItems Folder instance
: rtype : mailbox . Folder""" | return self . folder_constructor ( parent = self , name = 'SentItems' , folder_id = OutlookWellKnowFolderNames . SENT . value ) |
def SLICE_0 ( self , instr ) :
'obj [ : ]' | value = self . ast_stack . pop ( )
kw = dict ( lineno = instr . lineno , col_offset = 0 )
slice = _ast . Slice ( lower = None , step = None , upper = None , ** kw )
subscr = _ast . Subscript ( value = value , slice = slice , ctx = _ast . Load ( ) , ** kw )
self . ast_stack . append ( subscr ) |
def parse ( self , line ) :
"""Parse a line of the Nginx error log""" | csv_list = line . split ( "," )
date_time_message = csv_list . pop ( 0 ) . split ( " " , 2 )
otherinfo = dict ( )
for item in csv_list :
key_value_pair = item . split ( ":" , 1 )
key = key_value_pair [ 0 ] . strip ( )
if len ( key_value_pair ) > 1 :
value = key_value_pair [ 1 ] . strip ( )
i... |
def shutdown ( self ) :
"""Shutdown the application and exit
: returns : No return value""" | task = asyncio . ensure_future ( self . core . shutdown ( ) )
self . loop . run_until_complete ( task ) |
def infer_object_subtype ( self , api , pid = None , create = False , default_pidspace = None ) :
"""Construct a DigitalObject or appropriate subclass , inferring the
appropriate subtype using : meth : ` best _ subtype _ for _ object ` . Note that
this method signature has been selected to match the
: class :... | obj = DigitalObject ( api , pid , create , default_pidspace )
if create :
return obj
if not obj . exists :
return obj
match_type = self . best_subtype_for_object ( obj )
return match_type ( api , pid ) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.