signature stringlengths 29 44.1k | implementation stringlengths 0 85.2k |
|---|---|
def TaubinSVD ( XY ) :
"""algebraic circle fit
input : list [ [ x _ 1 , y _ 1 ] , [ x _ 2 , y _ 2 ] , . . . . ]
output : a , b , r . a and b are the center of the fitting circle , and r is the radius
Algebraic circle fit by Taubin
G . Taubin , " Estimation Of Planar Curves , Surfaces And Nonplanar
Space C... | XY = numpy . array ( XY )
X = XY [ : , 0 ] - numpy . mean ( XY [ : , 0 ] )
# norming points by x avg
Y = XY [ : , 1 ] - numpy . mean ( XY [ : , 1 ] )
# norming points by y avg
centroid = [ numpy . mean ( XY [ : , 0 ] ) , numpy . mean ( XY [ : , 1 ] ) ]
Z = X * X + Y * Y
Zmean = numpy . mean ( Z )
Z0 = old_div ( ( Z - Z... |
def get_current_and_head_revision ( database_url : str , alembic_config_filename : str , alembic_base_dir : str = None , version_table : str = DEFAULT_ALEMBIC_VERSION_TABLE ) -> Tuple [ str , str ] :
"""Returns a tuple of ` ` ( current _ revision , head _ revision ) ` ` ; see
: func : ` get _ current _ revision `... | # Where we are
head_revision = get_head_revision_from_alembic ( alembic_config_filename = alembic_config_filename , alembic_base_dir = alembic_base_dir , version_table = version_table )
log . info ( "Intended database version: {}" , head_revision )
# Where we want to be
current_revision = get_current_revision ( databas... |
def list_installed_genomes ( genome_dir = None ) :
"""List all available genomes .
Parameters
genome _ dir : str
Directory with installed genomes .
Returns
list with genome names""" | if not genome_dir :
genome_dir = config . get ( "genome_dir" , None )
if not genome_dir :
raise norns . exceptions . ConfigError ( "Please provide or configure a genome_dir" )
return [ f for f in os . listdir ( genome_dir ) if _is_genome_dir ( genome_dir + "/" + f ) ] |
def _RepackTemplates ( self ) :
"""Repack templates with a dummy config .""" | dummy_config = os . path . join ( args . grr_src , "grr/test/grr_response_test/test_data/dummyconfig.yaml" )
if args . build_32 :
template_i386 = glob . glob ( os . path . join ( args . output_dir , "*_i386*.zip" ) ) . pop ( )
template_amd64 = glob . glob ( os . path . join ( args . output_dir , "*_amd64*.zip" ) ) ... |
def visit_FunctionDef ( self , node ) :
"""Determine this function definition can be inlined .""" | if ( len ( node . body ) == 1 and isinstance ( node . body [ 0 ] , ( ast . Call , ast . Return ) ) ) :
ids = self . gather ( Identifiers , node . body [ 0 ] )
# FIXME : It mark " not inlinable " def foo ( foo ) : return foo
if node . name not in ids :
self . result [ node . name ] = copy . deepcopy ... |
def duplicated ( values , keep = 'first' ) :
"""Return boolean ndarray denoting duplicate values .
. . versionadded : : 0.19.0
Parameters
values : ndarray - like
Array over which to check for duplicate values .
keep : { ' first ' , ' last ' , False } , default ' first '
- ` ` first ` ` : Mark duplicates... | values , dtype , ndtype = _ensure_data ( values )
f = getattr ( htable , "duplicated_{dtype}" . format ( dtype = ndtype ) )
return f ( values , keep = keep ) |
def _context_defaults ( self , context , conf ) :
"""Apply any defaults and role _ defaults from the current config .
The config might be at the task level or the global ( top ) level .
The order is such that a role _ defaults value will be applied before
a normal defaults value so if present , the role _ def... | if hasattr ( self , '_legion' ) :
roles = self . _legion . get_roles ( )
else :
roles = self . get_roles ( )
if conf and roles and 'role_defaults' in conf and isinstance ( conf [ 'role_defaults' ] , dict ) :
for role in conf [ 'role_defaults' ] :
if role in roles :
for tag , val in conf ... |
def init_config ( policy_config ) :
"""Get policy lambda execution configuration .
cli parameters are serialized into the policy lambda config ,
we merge those with any policy specific execution options .
- - assume role and - s output directory get special handling , as
to disambiguate any cli context .
... | global account_id
exec_options = policy_config . get ( 'execution-options' , { } )
# Remove some configuration options that don ' t make sense to translate from
# cli to lambda automatically .
# - assume role on cli doesn ' t translate , it is the default lambda role and
# used to provision the lambda .
# - profile doe... |
def build ( pattern = None , path = '.' ) :
"""Generates a static copy of the sources""" | path = abspath ( path )
c = Clay ( path )
c . build ( pattern ) |
def upload ( self , filename , number_of_hosts ) :
"""Upload the given file to the specified number of hosts .
: param filename : The filename of the file to upload .
: type filename : str
: param number _ of _ hosts : The number of hosts to connect to .
: type number _ of _ hosts : int
: returns : A list... | return self . multiupload ( filename , self . random_hosts ( number_of_hosts ) ) |
def run_blot ( imageObjectList , output_wcs , paramDict , wcsmap = wcs_functions . WCSMap ) :
"""run _ blot ( imageObjectList , output _ wcs , paramDict , wcsmap = wcs _ functions . WCSMap )
Perform the blot operation on the list of images .""" | # Insure that input imageObject is a list
if not isinstance ( imageObjectList , list ) :
imageObjectList = [ imageObjectList ]
# Setup the versions info dictionary for output to PRIMARY header
# The keys will be used as the name reported in the header , as - is
_versions = { 'AstroDrizzle' : __version__ , 'PyFITS' ... |
def add_function ( self , function_id = None , function = None , inputs = None , outputs = None , input_domain = None , weight = None , inp_weight = None , out_weight = None , description = None , filters = None , await_domain = None , await_result = None , ** kwargs ) :
"""Add a single function node to dispatcher ... | from . utils . blue import _init
function = _init ( function )
if inputs is None : # Set a dummy input .
if START not in self . nodes :
self . add_data ( START )
inputs = [ START ]
# Update inputs .
if outputs is None : # Set a dummy output .
if SINK not in self . nodes :
self . add_data ( S... |
def flush_ct_inventory ( self ) :
"""internal method used only if ct _ inventory is enabled""" | if hasattr ( self , '_ct_inventory' ) : # skip self from update
self . _ct_inventory = None
self . update_view = False
self . save ( ) |
def get_overridden_calculated_entry ( self ) :
"""Gets the calculated entry this entry overrides .
return : ( osid . grading . GradeEntry ) - the calculated entry
raise : IllegalState - ` ` overrides _ calculated _ entry ( ) ` ` is
` ` false ` `
raise : OperationFailed - unable to complete request
* compl... | # Implemented from template for osid . resource . Resource . get _ avatar _ template
if not bool ( self . _my_map [ 'overriddenCalculatedEntryId' ] ) :
raise errors . IllegalState ( 'this GradeEntry has no overridden_calculated_entry' )
mgr = self . _get_provider_manager ( 'GRADING' )
if not mgr . supports_grade_en... |
def changed ( self , name ) :
"""Returns true if the parameter with the specified name has its value changed by
the * first * module procedure in the interface .
: arg name : the name of the parameter to check changed status for .""" | if self . first :
return self . first . changed ( name )
else :
return False |
def _check_valid_udunits ( self , ds , variable_name ) :
'''Checks that the variable ' s units are contained in UDUnits
: param netCDF4 . Dataset ds : An open netCDF dataset
: param str variable _ name : Name of the variable to be checked''' | variable = ds . variables [ variable_name ]
units = getattr ( variable , 'units' , None )
standard_name = getattr ( variable , 'standard_name' , None )
standard_name , standard_name_modifier = self . _split_standard_name ( standard_name )
std_name_units_dimensionless = cfutil . is_dimensionless_standard_name ( self . _... |
def delete_grade ( self , grade_id ) :
"""Deletes a ` ` Grade ` ` .
arg : grade _ id ( osid . id . Id ) : the ` ` Id ` ` of the ` ` Grade ` ` to
remove
raise : NotFound - ` ` grade _ id ` ` not found
raise : NullArgument - ` ` grade _ id ` ` is ` ` null ` `
raise : OperationFailed - unable to complete req... | # Implemented from template for
# osid . repository . AssetAdminSession . delete _ asset _ content _ template
from dlkit . abstract_osid . id . primitives import Id as ABCId
from . objects import Grade
collection = JSONClientValidated ( 'grading' , collection = 'GradeSystem' , runtime = self . _runtime )
if not isinsta... |
def main_pred_type ( self , value ) :
"""set main predicate combination type
: param value : ( character ) One of ` ` equals ` ` ( ` ` = ` ` ) , ` ` and ` ` ( ` ` & ` ` ) , ` ` or ` ` ( ` ` | ` ` ) ,
` ` lessThan ` ` ( ` ` < ` ` ) , ` ` lessThanOrEquals ` ` ( ` ` < = ` ` ) , ` ` greaterThan ` ` ( ` ` > ` ` ) , ... | if value not in operators :
value = operator_lkup . get ( value )
if value :
self . _main_pred_type = value
self . payload [ 'predicate' ] [ 'type' ] = self . _main_pred_type
else :
raise Exception ( "main predicate combiner not a valid operator" ) |
def get_user ( self , username = "" , ext_collections = False , ext_galleries = False ) :
"""Get user profile information
: param username : username to lookup profile of
: param ext _ collections : Include collection folder info
: param ext _ galleries : Include gallery folder info""" | if not username and self . standard_grant_type == "authorization_code" :
response = self . _req ( '/user/whoami' )
u = User ( )
u . from_dict ( response )
else :
if not username :
raise DeviantartError ( "No username defined." )
else :
response = self . _req ( '/user/profile/{}' . fo... |
def vel_inlet_man_max ( sed_inputs = sed_dict ) :
"""Return the maximum velocity through the manifold .
Parameters
sed _ inputs : dict
A dictionary of all of the constant inputs needed for sedimentation tank
calculations can be found in sed . yaml
Returns
float
Maximum velocity through the manifold . ... | vel_manifold_max = ( sed_inputs [ 'diffuser' ] [ 'vel_max' ] . to ( u . m / u . s ) . magnitude * sqrt ( 2 * ( ( 1 - ( sed_inputs [ 'manifold' ] [ 'ratio_Q_man_orifice' ] ) ** 2 ) ) / ( ( ( sed_inputs [ 'manifold' ] [ 'ratio_Q_man_orifice' ] ) ** 2 ) + 1 ) ) )
return vel_manifold_max |
def action_object ( self , obj , ** kwargs ) :
"""Stream of most recent actions where obj is the action _ object .
Keyword arguments will be passed to Action . objects . filter""" | check ( obj )
return obj . action_object_actions . public ( ** kwargs ) |
def near_to_position ( self , position , max_distance ) :
'''Returns true iff the record is within max _ distance of the given position .
Note : chromosome name not checked , so that ' s up to you to do first .''' | end = self . ref_end_pos ( )
return self . POS <= position <= end or abs ( position - self . POS ) <= max_distance or abs ( position - end ) <= max_distance |
def column_width ( tokens ) :
"""Return a suitable column width to display one or more strings .""" | get_len = tools . display_len if PY3 else len
lens = sorted ( map ( get_len , tokens or [ ] ) ) or [ 0 ]
width = lens [ - 1 ]
# adjust for disproportionately long strings
if width >= 18 :
most = lens [ int ( len ( lens ) * 0.9 ) ]
if most < width + 6 :
return most
return width |
def calc_et0_v1 ( self ) :
"""Calculate reference evapotranspiration after Turc - Wendling .
Required control parameters :
| NHRU |
| KE |
| KF |
| HNN |
Required input sequence :
| Glob |
Required flux sequence :
| TKor |
Calculated flux sequence :
| ET0 |
Basic equation :
: math : ` ET0 ... | con = self . parameters . control . fastaccess
inp = self . sequences . inputs . fastaccess
flu = self . sequences . fluxes . fastaccess
for k in range ( con . nhru ) :
flu . et0 [ k ] = ( con . ke [ k ] * ( ( ( 8.64 * inp . glob + 93. * con . kf [ k ] ) * ( flu . tkor [ k ] + 22. ) ) / ( 165. * ( flu . tkor [ k ] ... |
def backprop ( self , ** args ) :
"""Computes error and wed for back propagation of error .""" | retval = self . compute_error ( ** args )
if self . learning :
self . compute_wed ( )
return retval |
def finish ( self ) :
"""Wait for GL commands to to finish
This creates a GLIR command for glFinish and then processes the
GLIR commands . If the GLIR interpreter is remote ( e . g . WebGL ) , this
function will return before GL has finished processing the commands .""" | if hasattr ( self , 'flush_commands' ) :
context = self
else :
context = get_current_canvas ( ) . context
context . glir . command ( 'FUNC' , 'glFinish' )
context . flush_commands ( ) |
def _write_metrics ( self , iteration : int , last_metrics : MetricsList , start_idx : int = 2 ) -> None :
"Writes training metrics to Tensorboard ." | recorder = self . learn . recorder
for i , name in enumerate ( recorder . names [ start_idx : ] ) :
if last_metrics is None or len ( last_metrics ) < i + 1 :
return
scalar_value = last_metrics [ i ]
self . _write_scalar ( name = name , scalar_value = scalar_value , iteration = iteration ) |
def splitlines ( self , keepends = False ) :
"""B . splitlines ( [ keepends ] ) - > list of lines
Return a list of the lines in B , breaking at line boundaries .
Line breaks are not included in the resulting list unless keepends
is given and true .""" | # Py2 str . splitlines ( ) takes keepends as an optional parameter ,
# not as a keyword argument as in Python 3 bytes .
parts = super ( newbytes , self ) . splitlines ( keepends )
return [ newbytes ( part ) for part in parts ] |
def make_model ( num_layers : int = 6 , input_size : int = 512 , # Attention size
hidden_size : int = 2048 , # FF layer size
heads : int = 8 , dropout : float = 0.1 , return_all_layers : bool = False ) -> TransformerEncoder :
"""Helper : Construct a model from hyperparameters .""" | attn = MultiHeadedAttention ( heads , input_size , dropout )
ff = PositionwiseFeedForward ( input_size , hidden_size , dropout )
model = TransformerEncoder ( EncoderLayer ( input_size , attn , ff , dropout ) , num_layers , return_all_layers = return_all_layers )
# Initialize parameters with Glorot / fan _ avg .
for p i... |
def p_var_decl ( p ) :
"""var _ decl : DIM idlist typedef""" | for vardata in p [ 2 ] :
SYMBOL_TABLE . declare_variable ( vardata [ 0 ] , vardata [ 1 ] , p [ 3 ] )
p [ 0 ] = None |
def needle_msa ( reference , results , gap_open = - 15 , gap_extend = 0 , matrix = submat . DNA_SIMPLE ) :
'''Create a multiple sequence alignment based on aligning every result
sequence against the reference , then inserting gaps until every aligned
reference is identical''' | gap = '-'
# Convert alignments to list of strings
alignments = [ ]
for result in results :
ref_dna , res_dna , score = needle ( reference , result , gap_open = gap_open , gap_extend = gap_extend , matrix = matrix )
alignments . append ( [ str ( ref_dna ) , str ( res_dna ) , score ] )
def insert_gap ( sequence ,... |
def xche4_teff ( self , ifig = None , lims = [ 1. , 0. , 3.4 , 4.7 ] , label = None , colour = None , s2ms = True , dashes = None ) :
"""Plot effective temperature against central helium abundance .
Parameters
ifig : integer or string
Figure label , if None the current figure is used
The default value is No... | fsize = 18
params = { 'axes.labelsize' : fsize , # ' font . family ' : ' serif ' ,
'font.family' : 'Times New Roman' , 'figure.facecolor' : 'white' , 'text.fontsize' : fsize , 'legend.fontsize' : fsize , 'xtick.labelsize' : fsize * 0.8 , 'ytick.labelsize' : fsize * 0.8 , 'text.usetex' : False }
try :
pl . rcParams ... |
def confd_state_rest_listen_tcp_ip ( self , ** kwargs ) :
"""Auto Generated Code""" | config = ET . Element ( "config" )
confd_state = ET . SubElement ( config , "confd-state" , xmlns = "http://tail-f.com/yang/confd-monitoring" )
rest = ET . SubElement ( confd_state , "rest" )
listen = ET . SubElement ( rest , "listen" )
tcp = ET . SubElement ( listen , "tcp" )
ip = ET . SubElement ( tcp , "ip" )
ip . t... |
def protected_operation_with_request ( fn ) :
"""Use this decorator to prevent an operation from being executed
when the related uri resource is still in use .
The request must contain a registry . queryUtility ( IReferencer )
: raises pyramid . httpexceptions . HTTPConflict : Signals that we don ' t want to ... | @ functools . wraps ( fn )
def wrapped ( request , * args , ** kwargs ) :
response = _advice ( request )
if response is not None :
return response
else :
return fn ( request , * args , ** kwargs )
return wrapped |
def finished ( self ) :
"""Mark the activity as finished""" | self . data_service . update_activity ( self . id , self . name , self . desc , started_on = self . started , ended_on = self . _current_timestamp_str ( ) ) |
def from_json_file ( cls , json_file ) :
"""Constructs a ` GPT2Config ` from a json file of parameters .""" | with open ( json_file , "r" , encoding = "utf-8" ) as reader :
text = reader . read ( )
return cls . from_dict ( json . loads ( text ) ) |
def send_keys ( self , keysToSend ) :
"""Send Keys to the Alert .
: Args :
- keysToSend : The text to be sent to Alert .""" | if self . driver . w3c :
self . driver . execute ( Command . W3C_SET_ALERT_VALUE , { 'value' : keys_to_typing ( keysToSend ) , 'text' : keysToSend } )
else :
self . driver . execute ( Command . SET_ALERT_VALUE , { 'text' : keysToSend } ) |
def _get_renamed_deleted_sourcesapp ( self ) :
"""Get renamed and deleted sources lists from receiver .
Internal method which queries device via HTTP to get names of renamed
input sources . In this method AppCommand . xml is used .""" | # renamed _ sources and deleted _ sources are dicts with " source " as key
# and " renamed _ source " or deletion flag as value .
renamed_sources = { }
deleted_sources = { }
# Collect tags for AppCommand . xml call
tags = [ "GetRenameSource" , "GetDeletedSource" ]
# Execute call
root = self . exec_appcommand_post ( tag... |
def train ( self , data , vars , idx ) :
"""Train the scales on the data .
The scales should be for the same aesthetic
e . g . x scales , y scales , color scales , . . .
Parameters
data : dataframe
data to use for training
vars : list | tuple
columns in data to use for training .
These should be all... | idx = np . asarray ( idx )
for col in vars :
for i , sc in enumerate ( self , start = 1 ) :
bool_idx = ( i == idx )
sc . train ( data . loc [ bool_idx , col ] ) |
def _year_expand ( s ) :
"""Parses a year or dash - delimeted year range""" | regex = r"^((?:19|20)\d{2})?(\s*-\s*)?((?:19|20)\d{2})?$"
try :
start , dash , end = match ( regex , ustr ( s ) ) . groups ( )
start = start or 1900
end = end or 2099
except AttributeError :
return 1900 , 2099
return ( int ( start ) , int ( end ) ) if dash else ( int ( start ) , int ( start ) ) |
def get ( self , dev_id ) :
"""Retrieve the information for a device entity .""" | path = '/' . join ( [ 'device' , dev_id ] )
return self . rachio . get ( path ) |
def quality_to_bitmap ( quality ) :
"""Return the bitmap for a given quality .
Parameters
quality : str
Chord quality name .
Returns
bitmap : np . ndarray
Bitmap representation of this quality ( 12 - dim ) .""" | if quality not in QUALITIES :
raise InvalidChordException ( "Unsupported chord quality shorthand: '%s' " "Did you mean to reduce extended chords?" % quality )
return np . array ( QUALITIES [ quality ] ) |
def flattened2str ( flattened , missing = False , extra = False ) :
"""Return a pretty - printed multi - line string version of the output of
flatten _ errors . Know that flattened comes in the form of a list
of keys that failed . Each member of the list is a tuple : :
( [ list of sections . . . ] , key , res... | if flattened is None or len ( flattened ) < 1 :
return ''
retval = ''
for sections , key , result in flattened : # Name the section and item , to start the message line
if sections is None or len ( sections ) == 0 :
retval += '\t"' + key + '"'
elif len ( sections ) == 1 :
if key is None : # ... |
def _dimension_keys ( self ) :
"""Helper for _ _ mul _ _ that returns the list of keys together with
the dimension labels .""" | return [ tuple ( zip ( [ d . name for d in self . kdims ] , [ k ] if self . ndims == 1 else k ) ) for k in self . keys ( ) ] |
def get ( self , path , query , ** options ) :
"""Parses GET request options and dispatches a request .""" | api_options = self . _parse_api_options ( options , query_string = True )
query_options = self . _parse_query_options ( options )
parameter_options = self . _parse_parameter_options ( options )
# options in the query takes precendence
query = _merge ( query_options , api_options , parameter_options , query )
return sel... |
def list_to_alpha3 ( languages , synonyms = True ) :
"""Parse all the language codes in a given list into ISO 639 Part 2 codes
and optionally expand them with synonyms ( i . e . other names for the same
language ) .""" | codes = set ( [ ] )
for language in ensure_list ( languages ) :
code = iso_639_alpha3 ( language )
if code is None :
continue
codes . add ( code )
if synonyms :
codes . update ( expand_synonyms ( code ) )
return codes |
def draw_to_screen ( self , screen_id , address , x , y , width , height ) :
"""Draws a 32 - bpp image of the specified size from the given buffer
to the given point on the VM display .
in screen _ id of type int
Monitor to take the screenshot from .
in address of type str
Address to store the screenshot ... | if not isinstance ( screen_id , baseinteger ) :
raise TypeError ( "screen_id can only be an instance of type baseinteger" )
if not isinstance ( address , basestring ) :
raise TypeError ( "address can only be an instance of type basestring" )
if not isinstance ( x , baseinteger ) :
raise TypeError ( "x can o... |
def update ( self , entity ) :
"""Executes collection ' s update method based on keyword args .
Example : :
manager = EntityManager ( Product )
p = Product ( )
p . name = ' new name '
p . description = ' new description '
p . price = 300.0
yield manager . update ( p )""" | assert isinstance ( entity , Entity ) , "Error: entity must have an instance of Entity"
return self . __collection . update ( { '_id' : entity . _id } , { '$set' : entity . as_dict ( ) } ) |
def generate ( self , * args , ** kwargs ) :
"""Generates and prints the console report , which consists of a table of test cases ran as
well as a summary table with passrate , number of test cases and statistics on
passed / failed / inconclusive / skipped cases .
: param args : arguments , not used
: param... | # Generate TC result table
table = PrettyTable ( [ "Testcase" , "Verdict" , "Fail Reason" , "Skip Reason" , "platforms" , "duration" , "Retried" ] )
for result in self . results :
table . add_row ( [ result . get_tc_name ( ) , result . get_verdict ( ) , hex_escape_str ( result . fail_reason ) [ : 60 ] , str ( resul... |
def proceedings ( self , key , value ) :
"""Populate the ` ` proceedings ` ` key .
Also populates the ` ` refereed ` ` key through side effects .""" | proceedings = self . get ( 'proceedings' )
refereed = self . get ( 'refereed' )
if not proceedings :
normalized_a_values = [ el . upper ( ) for el in force_list ( value . get ( 'a' ) ) ]
if 'PROCEEDINGS' in normalized_a_values :
proceedings = True
if not refereed :
normalized_a_values = [ el . upper... |
def write_long ( self , n , pack = Struct ( '>I' ) . pack ) :
"""Write an integer as an unsigned 32 - bit value .""" | if 0 <= n <= 0xFFFFFFFF :
self . _output_buffer . extend ( pack ( n ) )
else :
raise ValueError ( 'Long %d out of range 0..0xFFFFFFFF' , n )
return self |
def _translate_response ( self , response , state ) :
"""Translates a saml authorization response to an internal response
: type response : saml2 . response . AuthnResponse
: rtype : satosa . internal . InternalData
: param response : The saml authorization response
: return : A translated internal response... | # The response may have been encrypted by the IdP so if we have an
# encryption key , try it .
if self . encryption_keys :
response . parse_assertion ( self . encryption_keys )
authn_info = response . authn_info ( ) [ 0 ]
auth_class_ref = authn_info [ 0 ]
timestamp = response . assertion . authn_statement [ 0 ] . a... |
def parse ( self , values ) :
"""Override existing hyperparameter values , parsing new values from a string .
See parse _ values for more detail on the allowed format for values .
Args :
values : String . Comma separated list of ` name = value ` pairs where ' value '
must follow the syntax described above .... | type_map = { }
for name , t in self . _hparam_types . items ( ) :
param_type , _ = t
type_map [ name ] = param_type
values_map = parse_values ( values , type_map )
return self . override_from_dict ( values_map ) |
def update_state ( self ) :
"""Update state with latest info from Wink API .""" | response = self . api_interface . get_device_state ( self , type_override = "button" )
return self . _update_state_from_response ( response ) |
def get_objective_banks_by_activity ( self , * args , ** kwargs ) :
"""Pass through to provider ActivityObjectiveBankSession . get _ objective _ banks _ by _ activity""" | # Implemented from kitosid template for -
# osid . resource . ResourceBinSession . get _ bins _ by _ resource
catalogs = self . _get_provider_session ( 'activity_objective_bank_session' ) . get_objective_banks_by_activity ( * args , ** kwargs )
cat_list = [ ]
for cat in catalogs :
cat_list . append ( ObjectiveBank ... |
def _monitoring_groups_list ( args , _ ) :
"""Lists the groups in the project .""" | project_id = args [ 'project' ]
pattern = args [ 'name' ] or '*'
groups = gcm . Groups ( context = _make_context ( project_id ) )
dataframe = groups . as_dataframe ( pattern = pattern )
return _render_dataframe ( dataframe ) |
def gnmt_print ( * args , ** kwargs ) :
"""Wrapper for MLPerf compliance logging calls .
All arguments but ' sync ' are passed to mlperf _ log . gnmt _ print function .
If ' sync ' is set to True then the wrapper will synchronize all distributed
workers . ' sync ' should be set to True for all compliance tags... | if kwargs . pop ( 'sync' ) :
barrier ( )
if get_rank ( ) == 0 :
kwargs [ 'stack_offset' ] = 2
mlperf_log . gnmt_print ( * args , ** kwargs ) |
def parse_iso8601 ( text ) :
"""ISO 8601 compliant parser .
: param text : The string to parse
: type text : str
: rtype : datetime . datetime or datetime . time or datetime . date""" | parsed = _parse_iso8601_duration ( text )
if parsed is not None :
return parsed
m = ISO8601_DT . match ( text )
if not m :
raise ParserError ( "Invalid ISO 8601 string" )
ambiguous_date = False
is_date = False
is_time = False
year = 0
month = 1
day = 1
minute = 0
second = 0
microsecond = 0
tzinfo = None
if m :
... |
def clear_cached ( self ) :
"""Remove cached results from this table ' s computed columns .""" | _TABLE_CACHE . pop ( self . name , None )
for col in _columns_for_table ( self . name ) . values ( ) :
col . clear_cached ( )
logger . debug ( 'cleared cached columns for table {!r}' . format ( self . name ) ) |
def xor_bytes ( b1 : bytes , b2 : bytes ) -> bytearray :
"""Apply XOR operation on two bytes arguments
: param b1 : First bytes argument
: param b2 : Second bytes argument
: rtype bytearray :""" | result = bytearray ( )
for i1 , i2 in zip ( b1 , b2 ) :
result . append ( i1 ^ i2 )
return result |
def ones_like ( array , dtype = None , keepmeta = True ) :
"""Create an array of ones with the same shape and type as the input array .
Args :
array ( xarray . DataArray ) : The shape and data - type of it define
these same attributes of the output array .
dtype ( data - type , optional ) : If spacified , t... | if keepmeta :
return xr . ones_like ( array , dtype )
else :
return dc . ones ( array . shape , dtype ) |
def contained ( self , key , include_self = True , exclusive = False , biggest_first = True , only = None ) :
"""Get all locations that are completely within this location .
If the ` ` resolved _ row ` ` context manager is not used , ` ` RoW ` ` doesn ' t have a spatial definition . Therefore , ` ` . contained ( ... | if 'RoW' not in self :
if key == 'RoW' :
return [ 'RoW' ] if 'RoW' in ( only or [ ] ) else [ ]
elif only and 'RoW' in only :
only . pop ( only . index ( 'RoW' ) )
possibles = self . topology if only is None else { k : self [ k ] for k in only }
faces = self [ key ]
lst = [ ( k , len ( v ) ) for ... |
def first_solar_spectral_loss ( self , pw , airmass_absolute ) :
"""Use the : py : func : ` first _ solar _ spectral _ correction ` function to
calculate the spectral loss modifier . The model coefficients are
specific to the module ' s cell type , and are determined by searching
for one of the following keys... | if 'first_solar_spectral_coefficients' in self . module_parameters . keys ( ) :
coefficients = self . module_parameters [ 'first_solar_spectral_coefficients' ]
module_type = None
else :
module_type = self . _infer_cell_type ( )
coefficients = None
return atmosphere . first_solar_spectral_correction ( pw... |
def get_template_name ( self , template_name_suffix = None ) :
"""Generates a template path name based on model and app .
: param template _ name _ suffix : pass a custom suffix or leave empty for default
: return : template path""" | if hasattr ( self . object_list , 'model' ) :
meta = self . object_list . model . _meta
return self . get_template_path ( meta , app_label = meta . app_label , object_name = meta . object_name , template_name_suffix = template_name_suffix ) |
def check_arrays_survival ( X , y , ** kwargs ) :
"""Check that all arrays have consistent first dimensions .
Parameters
X : array - like
Data matrix containing feature vectors .
y : structured array with two fields
A structured array containing the binary event indicator
as first field , and time of ev... | event , time = check_y_survival ( y )
kwargs . setdefault ( "dtype" , numpy . float64 )
X = check_array ( X , ensure_min_samples = 2 , ** kwargs )
check_consistent_length ( X , event , time )
return X , event , time |
def absent ( name , profile = 'grafana' ) :
'''Ensure that a data source is present .
name
Name of the data source to remove .''' | if isinstance ( profile , string_types ) :
profile = __salt__ [ 'config.option' ] ( profile )
ret = { 'result' : None , 'comment' : None , 'changes' : { } }
datasource = _get_datasource ( profile , name )
if not datasource :
ret [ 'result' ] = True
ret [ 'comment' ] = 'Data source {0} already absent' . form... |
def sort ( self , columnId , order = Qt . AscendingOrder ) :
"""Sorts the model column
After sorting the data in ascending or descending order , a signal
` layoutChanged ` is emitted .
: param : columnId ( int )
the index of the column to sort on .
: param : order ( Qt : : SortOrder , optional )
descend... | self . layoutAboutToBeChanged . emit ( )
self . sortingAboutToStart . emit ( )
column = self . _dataFrame . columns [ columnId ]
self . _dataFrame . sort_values ( column , ascending = not bool ( order ) , inplace = True )
self . layoutChanged . emit ( )
self . sortingFinished . emit ( ) |
def _initialize ( self ) :
"""Read the SharQ configuration and set appropriate
variables . Open a redis connection pool and load all
the Lua scripts .""" | self . _key_prefix = self . _config . get ( 'redis' , 'key_prefix' )
self . _job_expire_interval = int ( self . _config . get ( 'sharq' , 'job_expire_interval' ) )
self . _default_job_requeue_limit = int ( self . _config . get ( 'sharq' , 'default_job_requeue_limit' ) )
# initalize redis
redis_connection_type = self . ... |
def removed ( name , updates = None ) :
'''Ensure Microsoft Updates are uninstalled .
Args :
name ( str ) :
The identifier of a single update to uninstall .
updates ( list ) :
A list of identifiers for updates to be removed . Overrides ` ` name ` ` .
Default is None .
. . note : : Identifiers can be t... | if isinstance ( updates , six . string_types ) :
updates = [ updates ]
if not updates :
updates = name
ret = { 'name' : name , 'changes' : { } , 'result' : True , 'comment' : '' }
wua = salt . utils . win_update . WindowsUpdateAgent ( )
# Search for updates
updates = wua . search ( updates )
# No updates found
... |
def put_keys ( self , press_keys = None , hold_keys = None , press_delay = 50 ) :
"""Put scancodes that represent keys defined in the sequences provided .
Arguments :
press _ keys : Press a sequence of keys
hold _ keys : While pressing the sequence of keys , hold down the keys
defined in hold _ keys .
pre... | if press_keys is None :
press_keys = [ ]
if hold_keys is None :
hold_keys = [ ]
release_codes = set ( )
put_codes = set ( )
try : # hold the keys
for k in hold_keys :
put , release = self . SCANCODES [ k ]
# Avoid putting codes over and over
put = set ( put ) - put_codes
self... |
def calc_r_sm_v1 ( self ) :
"""Calculate effective precipitation and update soil moisture .
Required control parameters :
| NmbZones |
| ZoneType |
| FC |
| Beta |
Required fluxes sequence :
| In _ |
Calculated flux sequence :
Updated state sequence :
| SM |
Basic equations :
: math : ` \\ f... | con = self . parameters . control . fastaccess
flu = self . sequences . fluxes . fastaccess
sta = self . sequences . states . fastaccess
for k in range ( con . nmbzones ) :
if con . zonetype [ k ] in ( FIELD , FOREST ) :
if con . fc [ k ] > 0. :
flu . r [ k ] = flu . in_ [ k ] * ( sta . sm [ k ]... |
def GetMethodConfig ( self , method ) :
"""Returns service cached method config for given method .""" | method_config = self . _method_configs . get ( method )
if method_config :
return method_config
func = getattr ( self , method , None )
if func is None :
raise KeyError ( method )
method_config = getattr ( func , 'method_config' , None )
if method_config is None :
raise KeyError ( method )
self . _method_co... |
def set_manage_params ( self , chunked_input = None , chunked_output = None , gzip = None , websockets = None , source_method = None , rtsp = None , proxy_protocol = None ) :
"""Allows enabling various automatic management mechanics .
* http : / / uwsgi . readthedocs . io / en / latest / Changelog - 1.9 . html # ... | self . _set_aliased ( 'chunked-input' , chunked_input , cast = bool )
self . _set_aliased ( 'auto-chunked' , chunked_output , cast = bool )
self . _set_aliased ( 'auto-gzip' , gzip , cast = bool )
self . _set_aliased ( 'websockets' , websockets , cast = bool )
self . _set_aliased ( 'manage-source' , source_method , cas... |
def addAttachment ( self , title , attachment ) :
"""Adds an attachment to this comment .
: param title | < str >
attachment | < variant >""" | self . _attachments [ title ] = attachment
self . resizeToContents ( ) |
def ActivateCard ( self , card ) :
"""Activate a card .""" | if not hasattr ( card , 'connection' ) :
card . connection = card . createConnection ( )
if None != self . parent . apdutracerpanel :
card . connection . addObserver ( self . parent . apdutracerpanel )
card . connection . connect ( )
self . dialogpanel . OnActivateCard ( card ) |
def getTypeByPosition ( self , idx ) :
"""Return ASN . 1 type object by its position in fields set .
Parameters
idx : : py : class : ` int `
Field index
Returns
ASN . 1 type
Raises
: : class : ` ~ pyasn1 . error . PyAsn1Error `
If given position is out of fields range""" | try :
return self . __namedTypes [ idx ] . asn1Object
except IndexError :
raise error . PyAsn1Error ( 'Type position out of range' ) |
def full_zone_set ( self , user_key , zone_name ) :
"""Create new zone and all subdomains for user associated with this
user _ key .
: param user _ key : The unique 3auth string , identifying the user ' s
CloudFlare Account . Generated from a user _ create or user _ auth
: type user _ key : str
: param zo... | params = { 'act' : 'full_zone_set' , 'user_key' : user_key , 'zone_name' : zone_name , }
return self . _request ( params ) |
def phone_num_lists ( ) :
"""Gets a dictionary of 0-9 integer values ( as Strings ) mapped to their potential Backpage ad manifestations , such as " zer0 " or " seven " .
Returns :
dictionary of 0-9 integer values mapped to a list of strings containing the key ' s possible manifestations""" | all_nums = { }
all_nums [ '2' ] = [ '2' , 'two' ]
all_nums [ '3' ] = [ '3' , 'three' ]
all_nums [ '4' ] = [ '4' , 'four' , 'fuor' ]
all_nums [ '5' ] = [ '5' , 'five' , 'fith' ]
all_nums [ '6' ] = [ '6' , 'six' ]
all_nums [ '7' ] = [ '7' , 'seven' , 'sven' ]
all_nums [ '8' ] = [ '8' , 'eight' ]
all_nums [ '9' ] = [ '9' ... |
def isfile ( self , str_path ) :
"""A convenience function , returns bool if < str _ path > is
a " file " in the tree space""" | b_isFile = False
if self . isdir ( str_path ) :
b_isFile = False
else :
str_parentDir = '/' . join ( str_path . split ( '/' ) [ 0 : - 1 ] )
str_fileName = str_path . split ( '/' ) [ - 1 ]
if self . cd ( str_parentDir ) [ 'status' ] :
l_files = self . lsf ( str_parentDir )
if any ( str_fi... |
def visitShapeOrRef ( self , ctx : ShExDocParser . ShapeOrRefContext ) :
"""shapeOrRef : shapeDefinition | shapeRef""" | if ctx . shapeDefinition ( ) :
from pyshexc . parser_impl . shex_shape_definition_parser import ShexShapeDefinitionParser
shdef_parser = ShexShapeDefinitionParser ( self . context , self . label )
shdef_parser . visitChildren ( ctx )
self . expr = shdef_parser . shape
else :
self . expr = self . con... |
def compute_Pi_V_insVJ_given_J ( self , CDR3_seq , Pi_V_given_J , max_V_align ) :
"""Compute Pi _ V _ insVJ conditioned on J .
This function returns the Pi array from the model factors of the V genomic
contributions , P ( V , J ) * P ( delV | V ) , and the VJ ( N ) insertions ,
first _ nt _ bias _ insVJ ( m _... | # max _ insertions = 30 # len ( PinsVJ ) - 1 should zeropad the last few spots
max_insertions = len ( self . PinsVJ ) - 1
Pi_V_insVJ_given_J = [ np . zeros ( ( 4 , len ( CDR3_seq ) * 3 ) ) for i in range ( len ( Pi_V_given_J ) ) ]
for j in range ( len ( Pi_V_given_J ) ) : # start position is first nt in a codon
for... |
def get_signin_vcode ( cookie , codeString ) :
'''获取登录时的验证码图片 .
codeString - 调用check _ login ( ) 时返回的codeString .''' | url = '' . join ( [ const . PASSPORT_BASE , 'cgi-bin/genimage?' , codeString , ] )
headers = { 'Cookie' : cookie . header_output ( ) , 'Referer' : const . REFERER , }
req = net . urlopen ( url , headers = headers )
if req :
return req . data
else :
return None |
def addLogHandler ( func ) :
"""Add a custom log handler .
@ param func : a function object with prototype ( level , object , category ,
message ) where level is either ERROR , WARN , INFO , DEBUG , or
LOG , and the rest of the arguments are strings or None . Use
getLevelName ( level ) to get a printable na... | if not callable ( func ) :
raise TypeError ( "func must be callable" )
if func not in _log_handlers :
_log_handlers . append ( func ) |
def go_online ( self , comment = None ) :
"""Executes a Go - Online operation on the specified node
typically done when the node has already been forced offline
via : func : ` go _ offline `
: param str comment : ( optional ) comment to audit
: raises NodeCommandFailed : online not available
: return : No... | self . make_request ( NodeCommandFailed , method = 'update' , resource = 'go_online' , params = { 'comment' : comment } ) |
def from_sample_rate ( sample_rate , n_bands , always_even = False ) :
"""Return a : class : ` ~ zounds . spectral . LinearScale ` instance whose upper
frequency bound is informed by the nyquist frequency of the sample rate .
Args :
sample _ rate ( SamplingRate ) : the sample rate whose nyquist frequency
wi... | fb = FrequencyBand ( 0 , sample_rate . nyquist )
return LinearScale ( fb , n_bands , always_even = always_even ) |
def startReceivingBoxes ( self , sender ) :
"""Start observing log events for stat events to send .""" | AMP . startReceivingBoxes ( self , sender )
log . addObserver ( self . _emit ) |
def _getCellsWithFewestSegments ( self , columns ) :
"""For each column , get the cell that has the fewest total segments ( basal or
apical ) . Break ties randomly .
@ param columns ( numpy array )
Columns to check
@ return ( numpy array )
One cell for each of the provided columns""" | candidateCells = np2 . getAllCellsInColumns ( columns , self . cellsPerColumn )
# Arrange the segment counts into one row per minicolumn .
segmentCounts = np . reshape ( self . basalConnections . getSegmentCounts ( candidateCells ) + self . apicalConnections . getSegmentCounts ( candidateCells ) , newshape = ( len ( co... |
def everythingbut ( self ) :
'''Return a finite state machine which will accept any string NOT
accepted by self , and will not accept any string accepted by self .
This is more complicated if there are missing transitions , because the
missing " dead " state must now be reified .''' | alphabet = self . alphabet
initial = { 0 : self . initial }
def follow ( current , symbol ) :
next = { }
if 0 in current and current [ 0 ] in self . map and symbol in self . map [ current [ 0 ] ] :
next [ 0 ] = self . map [ current [ 0 ] ] [ symbol ]
return next
# state is final unless the original ... |
def strerror ( errno ) :
"""Translate an error code to a message string .""" | from pypy . module . _codecs . locale import str_decode_locale_surrogateescape
return str_decode_locale_surrogateescape ( os . strerror ( errno ) ) |
def emit ( self , signal , * args ) :
"""Emits the given signal with the inputted args . This will go through
its list of connected callback slots and call them .
: param signal | < variant >
* args | variables""" | callbacks = self . _callbacks . get ( signal , [ ] )
new_callbacks = [ ]
for callback in callbacks : # clear out deleted pointers
if not callback . isValid ( ) :
continue
new_callbacks . append ( callback )
try :
callback ( * args )
except StandardError :
logger . exception ( 'Er... |
def filter_rows ( filters , rows ) :
"""Yield rows matching all applicable filters .
Filter functions have binary arity ( e . g . ` filter ( row , col ) ` ) where
the first parameter is the dictionary of row data , and the second
parameter is the data at one particular column .
Args :
filters : a tuple of... | for row in rows :
if all ( condition ( row , row . get ( col ) ) for ( cols , condition ) in filters for col in cols if col is None or col in row ) :
yield row |
def scope2lat ( telescope ) :
"""Convert a telescope name into a latitude
returns None when the telescope is unknown .
Parameters
telescope : str
Acronym ( name ) of telescope , eg MWA .
Returns
lat : float
The latitude of the telescope .
Notes
These values were taken from wikipedia so have varyin... | scopes = { 'MWA' : - 26.703319 , "ATCA" : - 30.3128 , "VLA" : 34.0790 , "LOFAR" : 52.9088 , "KAT7" : - 30.721 , "MEERKAT" : - 30.721 , "PAPER" : - 30.7224 , "GMRT" : 19.096516666667 , "OOTY" : 11.383404 , "ASKAP" : - 26.7 , "MOST" : - 35.3707 , "PARKES" : - 32.999944 , "WSRT" : 52.914722 , "AMILA" : 52.16977 , "AMISA" ... |
def combine ( self , pattern , variable ) :
"""Combine a pattern and variable parts to be a line string again .""" | inter_zip = izip_longest ( variable , pattern , fillvalue = '' )
interleaved = [ elt for pair in inter_zip for elt in pair ]
return '' . join ( interleaved ) |
def _list_syntax_error ( ) :
"""If we ' re going through a syntax error , add the directory of the error to
the watchlist .""" | _ , e , _ = sys . exc_info ( )
if isinstance ( e , SyntaxError ) and hasattr ( e , 'filename' ) :
yield path . dirname ( e . filename ) |
def binormal ( obj , params , ** kwargs ) :
"""Evaluates the binormal vector of the curves or surfaces at the input parameter values .
This function is designed to evaluate binormal vectors of the B - Spline and NURBS shapes at single or
multiple parameter positions .
: param obj : input shape
: type obj : ... | normalize = kwargs . get ( 'normalize' , True )
if isinstance ( obj , abstract . Curve ) :
if isinstance ( params , ( list , tuple ) ) :
return ops . binormal_curve_single_list ( obj , params , normalize )
else :
return ops . binormal_curve_single ( obj , params , normalize )
if isinstance ( obj... |
def unicode_to_hex ( unicode_string ) :
"""Return a string containing the Unicode hexadecimal codepoint
of each Unicode character in the given Unicode string .
Return ` ` None ` ` if ` ` unicode _ string ` ` is ` ` None ` ` .
Example : :
a = > U + 0061
ab = > U + 0061 U + 0062
: param str unicode _ stri... | if unicode_string is None :
return None
acc = [ ]
for c in unicode_string :
s = hex ( ord ( c ) ) . replace ( "0x" , "" ) . upper ( )
acc . append ( "U+" + ( "0" * ( 4 - len ( s ) ) ) + s )
return u" " . join ( acc ) |
def list_images ( call = None , kwargs = None ) :
'''List all the images with alias by location
CLI Example :
. . code - block : : bash
salt - cloud - f list _ images my - profitbricks - config location = us / las''' | if call != 'function' :
raise SaltCloudSystemExit ( 'The list_images function must be called with ' '-f or --function.' )
if not version_compatible ( '4.0' ) :
raise SaltCloudNotFound ( "The 'image_alias' feature requires the profitbricks " "SDK v4.0.0 or greater." )
ret = { }
conn = get_conn ( )
if kwargs . ge... |
def _deserialize_dict ( data , boxed_type ) :
"""Deserializes a dict and its elements .
: param data : dict to deserialize .
: type data : dict
: param boxed _ type : class literal .
: return : deserialized dict .
: rtype : dict""" | return { k : _deserialize ( v , boxed_type ) for k , v in six . iteritems ( data ) } |
def unregister ( self , name ) :
"""Unregister function by name .""" | try :
name = name . name
except AttributeError :
pass
return self . pop ( name , None ) |
def dns_meta_data ( self ) :
"""Pull out the dns metadata for packet / transport in the input _ stream""" | # For each packet process the contents
for packet in self . input_stream : # Skip packets without transport info ( ARP / ICMP / IGMP / whatever )
if 'transport' not in packet :
continue
try :
dns_meta = dpkt . dns . DNS ( packet [ 'transport' ] [ 'data' ] )
_raw_info = data_utils . make_... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.