signature stringlengths 29 44.1k | implementation stringlengths 0 85.2k |
|---|---|
def _validate_information ( self ) :
"""Validate that all information has been filled in""" | needed_variables = [ "ModuleName" , "ModuleVersion" , "APIVersion" ]
for var in needed_variables :
if var not in self . variables :
raise DataError ( "Needed variable was not defined in mib file." , variable = var )
# Make sure ModuleName is < = 6 characters
if len ( self . variables [ "ModuleName" ] ) > 6 ... |
def visit_Call ( self , node ) :
"""Call visitor - used for finding setup ( ) call .""" | self . generic_visit ( node )
# Setup ( ) is a keywords - only function .
if node . args :
return
keywords = set ( )
for k in node . keywords :
if k . arg is not None :
keywords . add ( k . arg )
# Simple case for dictionary expansion for Python > = 3.5.
if k . arg is None and isinstance ( k . v... |
def settings ( ** kwargs ) :
"""Generally , this will automatically be added to a newly initialized
: class : ` phoebe . frontend . bundle . Bundle `
: parameter * * kwargs : defaults for the values of any of the parameters
: return : a : class : ` phoebe . parameters . parameters . ParameterSet ` of all newl... | params = [ ]
params += [ StringParameter ( qualifier = 'phoebe_version' , value = kwargs . get ( 'phoebe_version' , __version__ ) , description = 'Version of PHOEBE - change with caution' ) ]
params += [ BoolParameter ( qualifier = 'log_history' , value = kwargs . get ( 'log_history' , False ) , description = 'Whether ... |
def show ( config_file = False ) :
'''Return a list of sysctl parameters for this minion
CLI Example :
. . code - block : : bash
salt ' * ' sysctl . show''' | roots = ( 'compat' , 'debug' , 'dev' , 'hptmv' , 'hw' , 'kern' , 'machdep' , 'net' , 'p1003_1b' , 'security' , 'user' , 'vfs' , 'vm' )
cmd = 'sysctl -ae'
ret = { }
comps = [ '' ]
if config_file : # If the file doesn ' t exist , return an empty list
if not os . path . exists ( config_file ) :
return [ ]
... |
def _get_device_names_in_group ( self ) :
'''_ get _ device _ names _ in _ group
: returns : list - - list of device names in group''' | device_names = [ ]
dg = pollster ( self . _get_device_group ) ( self . devices [ 0 ] )
members = dg . devices_s . get_collection ( )
for member in members :
member_name = member . name . replace ( '/%s/' % self . partition , '' )
device_names . append ( member_name )
return device_names |
def _open_archive ( path ) :
""": param path :
A unicode string of the filesystem path to the archive
: return :
An archive object""" | if path . endswith ( '.zip' ) :
return zipfile . ZipFile ( path , 'r' )
return tarfile . open ( path , 'r' ) |
def _refresh_url ( self ) :
"""刷新获取 url , 失败的时候返回空而不是 None""" | songs = self . _api . weapi_songs_url ( [ int ( self . identifier ) ] )
if songs and songs [ 0 ] [ 'url' ] :
self . url = songs [ 0 ] [ 'url' ]
else :
self . url = '' |
def tospark ( self , engine = None ) :
"""Convert to spark mode .""" | from thunder . series . readers import fromarray
if self . mode == 'spark' :
logging . getLogger ( 'thunder' ) . warn ( 'images already in local mode' )
pass
if engine is None :
raise ValueError ( 'Must provide SparkContext' )
return fromarray ( self . toarray ( ) , index = self . index , labels = self . la... |
def get_tag ( self , el ) :
"""Get tag .""" | name = self . get_tag_name ( el )
return util . lower ( name ) if name is not None and not self . is_xml else name |
async def listHooks ( self , * args , ** kwargs ) :
"""List hooks in a given group
This endpoint will return a list of all the hook definitions within a
given hook group .
This method gives output : ` ` v1 / list - hooks - response . json # ` `
This method is ` ` stable ` `""" | return await self . _makeApiCall ( self . funcinfo [ "listHooks" ] , * args , ** kwargs ) |
def smart_initialize ( self ) :
'''Use k - means + + to initialize a good set of centroids''' | if self . seed is not None : # useful for obtaining consistent results
np . random . seed ( self . seed )
centroids = np . zeros ( ( self . k , self . data . shape [ 1 ] ) )
# Randomly choose the first centroid .
# Since we have no prior knowledge , choose uniformly at random
idx = np . random . randint ( self . da... |
def _mirror_groups ( self ) :
"""Mirrors the user ' s LDAP groups in the Django database and updates the
user ' s membership .""" | target_group_names = frozenset ( self . _get_groups ( ) . get_group_names ( ) )
current_group_names = frozenset ( self . _user . groups . values_list ( "name" , flat = True ) . iterator ( ) )
# These were normalized to sets above .
MIRROR_GROUPS_EXCEPT = self . settings . MIRROR_GROUPS_EXCEPT
MIRROR_GROUPS = self . set... |
def _is_vis ( channel ) :
"""Determine whether the given channel is a visible channel""" | if isinstance ( channel , str ) :
return channel == '00_7'
elif isinstance ( channel , int ) :
return channel == 1
else :
raise ValueError ( 'Invalid channel' ) |
def insert ( key , value ) :
"""Store a value with a key .
If the key is already present in the database , this does nothing .""" | # Pickle the value .
value = pickle . dumps ( value , protocol = constants . PICKLE_PROTOCOL )
# Store the value as binary data in a document .
doc = { KEY_FIELD : key , VALUE_FIELD : Binary ( value ) }
# Pickle and store the value with its key . If the key already exists , we
# don ' t insert ( since the key is a uniq... |
def cli_verify_jar_signature ( argument_list ) :
"""Command - line wrapper around verify ( )
TODO : use trusted keystore ;""" | usage_message = "jarutil v file.jar trusted_certificate.pem [SF_NAME.SF]"
if len ( argument_list ) < 2 or len ( argument_list ) > 3 :
print ( usage_message )
return 1
jar_file , certificate , sf_name = ( argument_list + [ None ] ) [ : 3 ]
try :
verify ( certificate , jar_file , sf_name )
except Verification... |
def _set_description ( self , schema ) :
"""Set description from schema .
: type schema : Sequence [ google . cloud . bigquery . schema . SchemaField ]
: param schema : A description of fields in the schema .""" | if schema is None :
self . description = None
return
self . description = tuple ( [ Column ( name = field . name , type_code = field . field_type , display_size = None , internal_size = None , precision = None , scale = None , null_ok = field . is_nullable , ) for field in schema ] ) |
def append_line ( self , new_line ) :
"""Appends the new _ line to the LS340 program .""" | # TODO : The user still has to write the raw line , this is error prone .
self . _write ( ( 'PGM' , [ Integer , String ] ) , self . idx , new_line ) |
def resolve_reference ( target_reference , project ) :
"""Given a target _ reference , made in context of ' project ' ,
returns the AbstractTarget instance that is referred to , as well
as properties explicitly specified for this reference .""" | # Separate target name from properties override
assert isinstance ( target_reference , basestring )
assert isinstance ( project , ProjectTarget )
split = _re_separate_target_from_properties . match ( target_reference )
if not split :
raise BaseException ( "Invalid reference: '%s'" % target_reference )
id = split . ... |
def add_comment ( self , app_id , record_id , field_id , message ) :
"""Directly add a comment to a record without retrieving the app or record first
Warnings :
Does not perform any app , record , or field ID validation
Args :
app _ id ( str ) : Full App ID string
record _ id ( str ) : Full parent Record ... | self . _swimlane . request ( 'post' , 'app/{0}/record/{1}/{2}/comment' . format ( app_id , record_id , field_id ) , json = { 'message' : message , 'createdDate' : pendulum . now ( ) . to_rfc3339_string ( ) } ) |
def _set_people ( self , people ) :
"""Sets who the object is sent to""" | if hasattr ( people , "object_type" ) :
people = [ people ]
elif hasattr ( people , "__iter__" ) :
people = list ( people )
return people |
def convert_time_string ( date_str ) :
"""Change a date string from the format 2018-08-15T23:55:17 into a datetime object""" | dt , _ , _ = date_str . partition ( "." )
dt = datetime . strptime ( dt , "%Y-%m-%dT%H:%M:%S" )
return dt |
def phi4 ( gold_clustering , predicted_clustering ) :
"""Subroutine for ceafe . Computes the mention F measure between gold and
predicted mentions in a cluster .""" | return 2 * len ( [ mention for mention in gold_clustering if mention in predicted_clustering ] ) / float ( len ( gold_clustering ) + len ( predicted_clustering ) ) |
def _build_likelihood ( self ) :
"""Construct a tensorflow function to compute the bound on the marginal
likelihood .""" | pX = DiagonalGaussian ( self . X_mean , self . X_var )
num_inducing = len ( self . feature )
psi0 = tf . reduce_sum ( expectation ( pX , self . kern ) )
psi1 = expectation ( pX , ( self . kern , self . feature ) )
psi2 = tf . reduce_sum ( expectation ( pX , ( self . kern , self . feature ) , ( self . kern , self . feat... |
def add_sparql_line_nums ( sparql ) :
"""Returns a sparql query with line numbers prepended""" | lines = sparql . split ( "\n" )
return "\n" . join ( [ "%s %s" % ( i + 1 , line ) for i , line in enumerate ( lines ) ] ) |
def _augmenting_row_reduction ( self ) :
"""Augmenting row reduction step from LAPJV algorithm""" | unassigned = np . where ( self . _x == - 1 ) [ 0 ]
for i in unassigned :
for _ in range ( self . c . size ) : # Time in this loop can be proportional to 1 / epsilon
# This step is not strictly necessary , so cutoff early
# to avoid near - infinite loops
# find smallest 2 values and indices
temp ... |
def new ( self , time_flags ) : # type : ( int ) - > None
'''Create a new Rock Ridge Time Stamp record .
Parameters :
time _ flags - The flags to use for this time stamp record .
Returns :
Nothing .''' | if self . _initialized :
raise pycdlibexception . PyCdlibInternalError ( 'TF record already initialized!' )
self . time_flags = time_flags
tflen = 7
if self . time_flags & ( 1 << 7 ) :
tflen = 17
for index , fieldname in enumerate ( self . FIELDNAMES ) :
if self . time_flags & ( 1 << index ) :
if tf... |
def show_download_links ( self ) :
"""Query PyPI for pkg download URI for a packge
@ returns : 0""" | # In case they specify version as ' dev ' instead of using - T svn ,
# don ' t show three svn URI ' s
if self . options . file_type == "all" and self . version == "dev" :
self . options . file_type = "svn"
if self . options . file_type == "svn" :
version = "dev"
else :
if self . version :
version = ... |
def is_none ( string_ , default = 'raise' ) :
"""Check if a string is equivalent to None .
Parameters
string _ : str
default : { ' raise ' , False }
Default behaviour if none of the " None " strings is detected .
Returns
is _ none : bool
Examples
> > > is _ none ( ' 2 ' , default = False )
False
... | none = [ 'none' , 'undefined' , 'unknown' , 'null' , '' ]
if string_ . lower ( ) in none :
return True
elif not default :
return False
else :
raise ValueError ( 'The value \'{}\' cannot be mapped to none.' . format ( string_ ) ) |
def _setSpeed ( self , speed , motor , device ) :
"""Set motor speed . This method takes into consideration the PWM frequency
that the hardware is currently running at and limits the values passed
to the hardware accordingly .
: Parameters :
speed : ` int `
Motor speed as an integer . Negative numbers ind... | reverse = False
if speed < 0 :
speed = - speed
reverse = True
# 0 and 2 for Qik 2s9v1 , 0 , 2 , and 4 for 2s12v10
if self . _deviceConfig [ device ] [ 'pwm' ] in ( 0 , 2 , 4 , ) and speed > 127 :
speed = 127
if speed > 127 :
if speed > 255 :
speed = 255
if reverse :
cmd = self . _COM... |
def local_to_global ( self , index ) :
"""Calculate local index from global index
: param index : input index
: return : local index for data""" | if ( type ( index ) is int ) or ( type ( index ) is slice ) :
if len ( self . __mask ) > 1 :
raise IndexError ( 'check length of parameter index' )
# 1D array
if type ( index ) is int :
return self . int_local_to_global ( index )
elif type ( index ) is slice :
return self . slice... |
def plot_gos ( fout_img , goids , go2obj , ** kws ) :
"""Given GO ids and the obo _ dag , create a plot of paths from GO ids .""" | gosubdag = GoSubDag ( goids , go2obj , rcntobj = True )
godagplot = GoSubDagPlot ( gosubdag , ** kws )
godagplot . plt_dag ( fout_img ) |
def run ( self ) :
'''Spin up the multiprocess event returner''' | salt . utils . process . appendproctitle ( self . __class__ . __name__ )
self . event = get_event ( 'master' , opts = self . opts , listen = True )
events = self . event . iter_events ( full = True )
self . event . fire_event ( { } , 'salt/event_listen/start' )
try :
for event in events :
if event [ 'tag' ]... |
def make_ica_funs ( observed_dimension , latent_dimension ) :
"""These functions implement independent component analysis .
The model is :
latents are drawn i . i . d . for each data point from a product of student - ts .
weights are the same across all datapoints .
each data = latents * weghts + noise .""" | def sample ( weights , n_samples , noise_std , rs ) :
latents = rs . randn ( latent_dimension , n_samples )
latents = np . array ( sorted ( latents . T , key = lambda a_entry : a_entry [ 0 ] ) ) . T
noise = rs . randn ( n_samples , observed_dimension ) * noise_std
observed = predict ( weights , latents ... |
def create ( self , name , backend_router_id , flavor , instances , test = False ) :
"""Orders a Virtual _ ReservedCapacityGroup
: param string name : Name for the new reserved capacity
: param int backend _ router _ id : This selects the pod . See create _ options for a list
: param string flavor : Capacity ... | # Since orderManger needs a DC id , just send in 0 , the API will ignore it
args = ( self . capacity_package , 0 , [ flavor ] )
extras = { "backendRouterId" : backend_router_id , "name" : name }
kwargs = { 'extras' : extras , 'quantity' : instances , 'complex_type' : 'SoftLayer_Container_Product_Order_Virtual_ReservedC... |
def change_tunnel_ad_url ( self ) :
'''Change tunnel ad url .''' | if self . is_open :
self . close ( )
req = requests . delete ( 'https://api.psiturk.org/api/tunnel/' , auth = ( self . access_key , self . secret_key ) )
# the request content here actually will include the tunnel _ hostname
# if needed or wanted .
if req . status_code in [ 401 , 403 , 500 ] :
print ( req . con... |
def analyze ( self , filename ) :
"""Reimplement analyze method""" | if self . dockwidget and not self . ismaximized :
self . dockwidget . setVisible ( True )
self . dockwidget . setFocus ( )
self . dockwidget . raise_ ( )
self . pylint . analyze ( filename ) |
def command ( self , function = None , prefix = None , unobserved = False ) :
"""Decorator to define a new command for this Ingredient or Experiment .
The name of the command will be the name of the function . It can be
called from the command - line or by using the run _ command function .
Commands are autom... | captured_f = self . capture ( function , prefix = prefix )
captured_f . unobserved = unobserved
self . commands [ function . __name__ ] = captured_f
return captured_f |
def serialize_wrapped_key ( key_provider , wrapping_algorithm , wrapping_key_id , encrypted_wrapped_key ) :
"""Serializes EncryptedData into a Wrapped EncryptedDataKey .
: param key _ provider : Info for Wrapping MasterKey
: type key _ provider : aws _ encryption _ sdk . structures . MasterKeyInfo
: param wra... | if encrypted_wrapped_key . iv is None :
key_info = wrapping_key_id
key_ciphertext = encrypted_wrapped_key . ciphertext
else :
key_info = struct . pack ( ">{key_id_len}sII{iv_len}s" . format ( key_id_len = len ( wrapping_key_id ) , iv_len = wrapping_algorithm . algorithm . iv_len ) , to_bytes ( wrapping_key_... |
def valid_config_exists ( config_path = CONFIG_PATH ) :
"""Verify that a valid config file exists .
Args :
config _ path ( str ) : Path to the config file .
Returns :
boolean : True if there is a valid config file , false if not .""" | if os . path . isfile ( config_path ) :
try :
config = read_config ( config_path )
check_config ( config )
except ( ConfigurationError , IOError ) :
return False
else :
return False
return True |
def _delete ( self , tree ) :
"""Run a DELETE statement""" | tablename = tree . table
table = self . describe ( tablename , require = True )
kwargs = { }
visitor = Visitor ( self . reserved_words )
if tree . where :
constraints = ConstraintExpression . from_where ( tree . where )
kwargs [ "condition" ] = constraints . build ( visitor )
kwargs [ "expr_values" ] = visitor ... |
def _get_end_time ( self , start_time : datetime ) -> datetime :
"""Generates the end time to be used for the store range query .
: param start _ time : Start time to use as an offset to calculate the end time
based on the window type in the schema .
: return :""" | if Type . is_type_equal ( self . _schema . window_type , Type . DAY ) :
return start_time + timedelta ( days = self . _schema . window_value )
elif Type . is_type_equal ( self . _schema . window_type , Type . HOUR ) :
return start_time + timedelta ( hours = self . _schema . window_value ) |
def tarbell_switch ( command , args ) :
"""Switch to a project .""" | with ensure_settings ( command , args ) as settings :
projects_path = settings . config . get ( "projects_path" )
if not projects_path :
show_error ( "{0} does not exist" . format ( projects_path ) )
sys . exit ( )
project = args . get ( 0 )
args . remove ( project )
project_path = o... |
def init ( opts ) :
'''Open the connection to the Junos device , login , and bind to the
Resource class''' | opts [ 'multiprocessing' ] = False
log . debug ( 'Opening connection to junos' )
args = { "host" : opts [ 'proxy' ] [ 'host' ] }
optional_args = [ 'user' , 'username' , 'password' , 'passwd' , 'port' , 'gather_facts' , 'mode' , 'baud' , 'attempts' , 'auto_probe' , 'ssh_private_key_file' , 'ssh_config' , 'normalize' ]
i... |
def _check_error ( response ) :
"""Checks for JSON error messages and raises Python exception""" | if 'error' in response :
raise InfluxDBError ( response [ 'error' ] )
elif 'results' in response :
for statement in response [ 'results' ] :
if 'error' in statement :
msg = '{d[error]} (statement {d[statement_id]})'
raise InfluxDBError ( msg . format ( d = statement ) ) |
def mb_neg_logposterior ( self , beta , mini_batch ) :
"""Returns negative log posterior
Parameters
beta : np . array
Contains untransformed starting values for latent variables
mini _ batch : int
Batch size for the data
Returns
Negative log posterior""" | post = ( self . data . shape [ 0 ] / mini_batch ) * self . mb_neg_loglik ( beta , mini_batch )
for k in range ( 0 , self . z_no ) :
post += - self . latent_variables . z_list [ k ] . prior . logpdf ( beta [ k ] )
return post |
def remove_quotes ( self , value ) :
"""Remove any surrounding quotes from a value and unescape any contained
quotes of that type .""" | # beware the empty string
if not value :
return value
if value [ 0 ] == value [ - 1 ] == '"' :
return value [ 1 : - 1 ] . replace ( '\\"' , '"' )
if value [ 0 ] == value [ - 1 ] == "'" :
return value [ 1 : - 1 ] . replace ( "\\'" , "'" )
return value |
def remove ( local_file_name ) :
"""Function attempts to remove file , if failure occures - > print exception
: param local _ file _ name : name of file to remove""" | try :
os . remove ( local_file_name )
except Exception as e :
print ( "Cannot remove file '" + local_file_name + "'. Please remove it manually." )
print ( e ) |
def opponent_rank ( self ) :
"""Returns a ` ` string ` ` of the opponent ' s rank when the game was played
and None if the team was unranked .""" | rank = re . findall ( r'\d+' , self . _opponent_name )
if len ( rank ) > 0 :
return int ( rank [ 0 ] )
return None |
def set_line_width ( self , width ) :
"""Sets the current line width within the cairo context .
The line width value specifies the diameter of a pen
that is circular in user space ,
( though device - space pen may be an ellipse in general
due to scaling / shear / rotation of the CTM ) .
. . note : :
Whe... | cairo . cairo_set_line_width ( self . _pointer , width )
self . _check_status ( ) |
def get_appointment_groups ( self , ** kwargs ) :
"""List appointment groups .
: calls : ` GET / api / v1 / appointment _ groups < https : / / canvas . instructure . com / doc / api / appointment _ groups . html # method . appointment _ groups . index > ` _
: rtype : : class : ` canvasapi . paginated _ list . P... | from canvasapi . appointment_group import AppointmentGroup
return PaginatedList ( AppointmentGroup , self . __requester , 'GET' , 'appointment_groups' , _kwargs = combine_kwargs ( ** kwargs ) ) |
def get_next_departures ( stop , filter_line = None , num_line_groups = 1 , verbose = False ) :
"""Get all real - time departure times for given stop and return as filtered table .
Terminate if we can assume there is no connection to the internet .""" | # Get departures table from online service
# ( great : we don ' t have to iterate over multiple pages ) .
url = BVG_URL_PAT % stop
if verbose :
print ( '- Fetching table for URL "%s".' % url )
try :
tables = pd . read_html ( url . encode ( 'utf-8' ) )
except urllib . error . URLError :
msg = 'Not connected ... |
def extract_fields ( lines , delim , searches , match_lineno = 1 , ** kwargs ) :
"""Return generator of fields matching ` searches ` .
Parameters
lines : iterable
Provides line number ( 1 - based ) and line ( str )
delim : str
Delimiter to split line by to produce fields
searches : iterable
Returns se... | keep_idx = [ ]
for lineno , line in lines :
if lineno < match_lineno or delim not in line :
if lineno == match_lineno :
raise WcutError ( 'Delimter not found in line {}' . format ( match_lineno ) )
yield [ line ]
continue
fields = line . split ( delim )
if lineno == match... |
def sanitize_op ( self , op_data ) :
"""Remove unnecessary fields for an operation , i . e . prior to committing it .
This includes any invariant tags we ' ve added with our invariant decorators
( such as @ state _ create or @ state _ transition ) .
TODO : less ad - hoc way to do this""" | op_data = super ( BlockstackDB , self ) . sanitize_op ( op_data )
# remove invariant tags ( i . e . added by our invariant state _ * decorators )
to_remove = get_state_invariant_tags ( )
for tag in to_remove :
if tag in op_data . keys ( ) :
del op_data [ tag ]
# NOTE : this is called the opcode family , bec... |
def _expire_data ( self ) :
"""Remove all expired entries .""" | expire_time_stamp = time . time ( ) - self . expire_time
self . timed_data = { d : t for d , t in self . timed_data . items ( ) if t > expire_time_stamp } |
def format ( self , message_format ) :
"""Set the message format
: param message _ format : The format to set
: type message _ format : str""" | if message_format not in self . formats :
self . _log . error ( 'Invalid Message format specified: {format}' . format ( format = message_format ) )
return
self . _log . debug ( 'Setting message format to {format}' . format ( format = message_format ) )
self . _format = message_format |
def _collect_placeholders_required ( self ) :
"""* collect placeholders required from filename etc *""" | self . log . info ( 'starting the ``_collect_placeholders_required`` method' )
phs = self . settings [ "frankenstein" ] [ "placeholder delimiters" ]
phsString = "|" . join ( phs )
matchObject = re . finditer ( r'(%(phsString)s)([^\s]*?)\1' % locals ( ) , string = self . contentString , flags = re . S # re . S
)
phDict ... |
def set_current_operation_progress ( self , percent ) :
"""Internal method , not to be called externally .
in percent of type int""" | if not isinstance ( percent , baseinteger ) :
raise TypeError ( "percent can only be an instance of type baseinteger" )
self . _call ( "setCurrentOperationProgress" , in_p = [ percent ] ) |
def inserir ( self , name ) :
"""Inserts a new Group L3 and returns its identifier .
: param name : Group L3 name . String with a minimum 2 and maximum of 80 characters
: return : Dictionary with the following structure :
{ ' group _ l3 ' : { ' id ' : < id _ group _ l3 > } }
: raise InvalidParameterError : ... | group_l3_map = dict ( )
group_l3_map [ 'name' ] = name
code , xml = self . submit ( { 'group_l3' : group_l3_map } , 'POST' , 'groupl3/' )
return self . response ( code , xml ) |
def write ( self , data , ** keys ) :
"""Write data into this HDU
parameters
data : ndarray or list of ndarray
A numerical python array . Should be an ordinary array for image
HDUs , should have fields for tables . To write an ordinary array to
a column in a table HDU , use write _ column . If data alread... | slow = keys . get ( 'slow' , False )
isrec = False
if isinstance ( data , ( list , dict ) ) :
if isinstance ( data , list ) :
data_list = data
columns_all = keys . get ( 'columns' , None )
if columns_all is None :
columns_all = keys . get ( 'names' , None )
if columns... |
def generate_mfa_token ( self , user_id , expires_in = 259200 , reusable = False ) :
"""Use to generate a temporary MFA token that can be used in place of other MFA tokens for a set time period .
For example , use this token for account recovery .
: param user _ id : Id of the user
: type user _ id : int
: ... | self . clean_error ( )
try :
url = self . get_url ( Constants . GENERATE_MFA_TOKEN_URL , user_id )
data = { 'expires_in' : expires_in , 'reusable' : reusable }
response = self . execute_call ( 'post' , url , json = data )
if response . status_code == 201 :
json_data = response . json ( )
... |
async def status ( request : web . Request ) -> web . Response :
"""Get request will return the status of the machine ' s connection to the
internet as well as the status of its network interfaces .
The body of the response is a json dict containing
' status ' : internet connectivity status , where the option... | connectivity = { 'status' : 'none' , 'interfaces' : { } }
try :
connectivity [ 'status' ] = await nmcli . is_connected ( )
connectivity [ 'interfaces' ] = { i . value : await nmcli . iface_info ( i ) for i in nmcli . NETWORK_IFACES }
log . debug ( "Connectivity: {}" . format ( connectivity [ 'status' ] ) )
... |
def exerciseOptions ( self , tickerId , contract , exerciseAction , exerciseQuantity , account , override ) :
"""exerciseOptions ( EClientSocketBase self , TickerId tickerId , Contract contract , int exerciseAction , int exerciseQuantity , IBString const & account , int override )""" | return _swigibpy . EClientSocketBase_exerciseOptions ( self , tickerId , contract , exerciseAction , exerciseQuantity , account , override ) |
def rdb_repository ( _context , name = None , make_default = False , aggregate_class = None , repository_class = None , db_string = None , metadata_factory = None ) :
"""Directive for registering a RDBM based repository .""" | cnf = { }
if not db_string is None :
cnf [ 'db_string' ] = db_string
if not metadata_factory is None :
cnf [ 'metadata_factory' ] = metadata_factory
_repository ( _context , name , make_default , aggregate_class , repository_class , REPOSITORY_TYPES . RDB , 'add_rdb_repository' , cnf ) |
async def AddMetricBatches ( self , batches ) :
'''batches : typing . Sequence [ ~ MetricBatchParam ]
Returns - > typing . Sequence [ ~ ErrorResult ]''' | # map input types to rpc msg
_params = dict ( )
msg = dict ( type = 'MetricsAdder' , request = 'AddMetricBatches' , version = 2 , params = _params )
_params [ 'batches' ] = batches
reply = await self . rpc ( msg )
return reply |
def set_reverb ( self , roomsize = - 1.0 , damping = - 1.0 , width = - 1.0 , level = - 1.0 ) :
"""roomsize Reverb room size value ( 0.0-1.2)
damping Reverb damping value ( 0.0-1.0)
width Reverb width value ( 0.0-100.0)
level Reverb level value ( 0.0-1.0)""" | set = 0
if roomsize >= 0 :
set += 0b0001
if damping >= 0 :
set += 0b0010
if width >= 0 :
set += 0b0100
if level >= 0 :
set += 0b1000
return fluid_synth_set_reverb_full ( self . synth , set , roomsize , damping , width , level ) |
def load_from_sens_file ( self , filename ) :
"""Load real and imaginary parts from a sens . dat file generated by
CRMod
Parameters
filename : string
filename of sensitivity file
Returns
nid _ re : int
ID of real part of sensitivities
nid _ im : int
ID of imaginary part of sensitivities""" | sens_data = np . loadtxt ( filename , skiprows = 1 )
nid_re = self . add_data ( sens_data [ : , 2 ] )
nid_im = self . add_data ( sens_data [ : , 3 ] )
return nid_re , nid_im |
def make_format ( self , fmt , width ) :
"""Make subreport text in a specified format""" | if not self . report_data :
return
for data_item in self . report_data :
if data_item . results :
if fmt is None or fmt == 'text' :
data_item . make_text ( width )
elif fmt == 'html' :
data_item . make_html ( )
elif fmt == 'csv' :
data_item . make_csv ... |
def download_subtitle ( self , subtitle ) :
"""Download ` subtitle ` ' s : attr : ` ~ subliminal . subtitle . Subtitle . content ` .
: param subtitle : subtitle to download .
: type subtitle : : class : ` ~ subliminal . subtitle . Subtitle `
: return : ` True ` if the subtitle has been successfully downloaded... | # check discarded providers
if subtitle . provider_name in self . discarded_providers :
logger . warning ( 'Provider %r is discarded' , subtitle . provider_name )
return False
logger . info ( 'Downloading subtitle %r' , subtitle )
try :
self [ subtitle . provider_name ] . download_subtitle ( subtitle )
exce... |
def get_svc_stats ( self , svcs ) :
"""Get statistics for Services , resp . Service entities""" | stats = { "services.total" : 0 , "services.ok" : 0 , "services.warning" : 0 , "services.critical" : 0 , "services.unknown" : 0 , "services.flapping" : 0 , "services.in_downtime" : 0 , "services.checked" : 0 , "services.scheduled" : 0 , "services.active_checks" : 0 , "services.passive_checks" : 0 , }
for svc in svcs :
... |
def plot_contours ( self , grid , filled = True , ax = None , labels = None , subplots_kw = dict ( ) , ** kwargs ) :
"""Plot equipotentials contours . Computes the potential energy on a grid
( specified by the array ` grid ` ) .
. . warning : : Right now the grid input must be arrays and must already
be in th... | import matplotlib . pyplot as plt
from matplotlib import cm
# figure out which elements are iterable , which are numeric
_grids = [ ]
_slices = [ ]
for ii , g in enumerate ( grid ) :
if isiterable ( g ) :
_grids . append ( ( ii , g ) )
else :
_slices . append ( ( ii , g ) )
# figure out the dime... |
def summary ( app ) :
"""Print a summary of a deployed app ' s status .""" | r = requests . get ( 'https://{}.herokuapp.com/summary' . format ( app ) )
summary = r . json ( ) [ 'summary' ]
click . echo ( "\nstatus \t| count" )
click . echo ( "----------------" )
for s in summary :
click . echo ( "{}\t| {}" . format ( s [ 0 ] , s [ 1 ] ) )
num_101s = sum ( [ s [ 1 ] for s in summary if s [ 0... |
def _request_callback ( self , request_id ) :
"""Construct a request callback for the given request ID .""" | def callback ( future ) : # Remove the future from the client requests map
self . _client_request_futures . pop ( request_id , None )
if future . cancelled ( ) :
future . set_exception ( JsonRpcRequestCancelled ( ) )
message = { 'jsonrpc' : JSONRPC_VERSION , 'id' : request_id , }
try :
m... |
def curve_spline ( x , y = None , weights = None , order = 1 , even_out = True , smoothing = None , periodic = False , meta_data = None ) :
'''curve _ spline ( coords ) yields a bicubic spline function through
the points in the given coordinate matrix .
curve _ spline ( x , y ) uses the coordinate matrix [ x , ... | curv = CurveSpline ( x , y , weights = weights , order = order , smoothing = smoothing , periodic = periodic , meta_data = meta_data )
if even_out :
curv = curv . even_out ( )
return curv |
def now ( self ) :
"""Return a : py : class : ` datetime . datetime ` instance representing the current time .
: rtype : : py : class : ` datetime . datetime `""" | if self . use_utc :
return datetime . datetime . utcnow ( )
else :
return datetime . datetime . now ( ) |
def unlink ( self , node , hyperedge ) :
"""Unlink given node and hyperedge .
@ type node : node
@ param node : Node .
@ type hyperedge : hyperedge
@ param hyperedge : Hyperedge .""" | self . node_links [ node ] . remove ( hyperedge )
self . edge_links [ hyperedge ] . remove ( node )
self . graph . del_edge ( ( ( node , 'n' ) , ( hyperedge , 'h' ) ) ) |
def disable_token ( platform , user_id , token , on_error = None , on_success = None ) :
"""Disable a device token for a user .
: param str platform The platform which to disable token on . One of either
Google Cloud Messaging ( outbound . GCM ) or Apple Push Notification Service
( outbound . APNS ) .
: par... | __device_token ( platform , False , user_id , token = token , on_error = on_error , on_success = on_success ) |
def stored_bind ( self , instance ) :
"""Bind an instance to this Pangler , using the bound Pangler store .
This method functions identically to ` bind ` , except that it might
return a Pangler which was previously bound to the provided instance .""" | if self . id is None :
return self . bind ( instance )
store = self . _bound_pangler_store . setdefault ( instance , { } )
p = store . get ( self . id )
if p is None :
p = store [ self . id ] = self . bind ( instance )
return p |
def _notify_remove ( self , slice_ ) :
"""Notify about a RemoveChange .""" | change = RemoveChange ( self , slice_ )
self . notify_observers ( change ) |
def clear_screen ( ) :
import os , platform
"""http : / / stackoverflow . com / questions / 18937058 / python - clear - screen - in - shell""" | if platform . system ( ) == "Windows" :
tmp = os . system ( 'cls' )
# for window
else :
tmp = os . system ( 'clear' )
# for Linux
return True |
def get ( self , _create = False , ** ctx_options ) :
"""NOTE : ` ctx _ options ` are ignored""" | if _create :
return self . _kind_factory . create ( key = self )
else :
return self . _kind_factory ( key = self ) |
def tempo_account_delete_account_by_id ( self , account_id ) :
"""Delete an Account by id . Caller must have the Manage Account Permission for the Account .
The Account can not be deleted if it has an AccountLinkBean .
: param account _ id : the id of the Account to be deleted .
: return :""" | url = 'rest/tempo-accounts/1/account/{id}/' . format ( id = account_id )
return self . delete ( url ) |
def load ( self ) :
"""Get load time series ( only active power )
Returns
dict or : pandas : ` pandas . DataFrame < dataframe > `
See class definition for details .""" | try :
return self . _load . loc [ [ self . timeindex ] , : ]
except :
return self . _load . loc [ self . timeindex , : ] |
def _sampleRange ( rng , start , end , step , k ) :
"""Equivalent to :
random . sample ( xrange ( start , end , step ) , k )
except it uses our random number generator .
This wouldn ' t need to create the arange if it were implemented in C .""" | array = numpy . empty ( k , dtype = "uint32" )
rng . sample ( numpy . arange ( start , end , step , dtype = "uint32" ) , array )
return array |
def read_config ( file_name ) :
"""Read YAML file with configuration and pointers to example data .
Args :
file _ name ( str ) : Name of the file , where the configuration is stored .
Returns :
dict : Parsed and processed data ( see : func : ` _ process _ config _ item ` ) .
Example YAML file : :
html :... | dirname = os . path . dirname ( os . path . abspath ( file_name ) )
dirname = os . path . relpath ( dirname )
# create utf - 8 strings , not unicode
def custom_str_constructor ( loader , node ) :
return loader . construct_scalar ( node ) . encode ( 'utf-8' )
yaml . add_constructor ( u'tag:yaml.org,2002:str' , custo... |
def gen_front_term ( self , x , dmp_num ) :
"""Generates the front term on the forcing term .
For rhythmic DMPs it ' s non - diminishing , so this
function is just a placeholder to return 1.
x float : the current value of the canonical system
dmp _ num int : the index of the current dmp""" | if isinstance ( x , np . ndarray ) :
return np . ones ( x . shape )
return 1 |
def find_all_mappings ( self , other_lattice : "Lattice" , ltol : float = 1e-5 , atol : float = 1 , skip_rotation_matrix : bool = False , ) -> Iterator [ Tuple [ "Lattice" , Optional [ np . ndarray ] , np . ndarray ] ] :
"""Finds all mappings between current lattice and another lattice .
Args :
other _ lattice ... | ( lengths , angles ) = other_lattice . lengths_and_angles
( alpha , beta , gamma ) = angles
frac , dist , _ , _ = self . get_points_in_sphere ( [ [ 0 , 0 , 0 ] ] , [ 0 , 0 , 0 ] , max ( lengths ) * ( 1 + ltol ) , zip_results = False )
cart = self . get_cartesian_coords ( frac )
# this can ' t be broadcast because they ... |
def main ( args , stop = False ) :
"""Arguments parsing , etc . .""" | daemon = AMQPDaemon ( con_param = getConParams ( settings . RABBITMQ_MX2MODS_VIRTUALHOST ) , queue = settings . RABBITMQ_MX2MODS_INPUT_QUEUE , out_exch = settings . RABBITMQ_MX2MODS_EXCHANGE , out_key = settings . RABBITMQ_MX2MODS_OUTPUT_KEY , react_fn = reactToAMQPMessage , glob = globals ( ) # used in deserializer
)
... |
def update_lipd_v1_1 ( d ) :
"""Update LiPD v1.0 to v1.1
- chronData entry is a list that allows multiple tables
- paleoData entry is a list that allows multiple tables
- chronData now allows measurement , model , summary , modelTable , ensemble , calibratedAges tables
- Added ' lipdVersion ' key
: param ... | logger_versions . info ( "enter update_lipd_v1_1" )
tmp_all = [ ]
try : # ChronData is the only structure update
if "chronData" in d : # As of v1.1 , ChronData should have an extra level of abstraction .
# No longer shares the same structure of paleoData
# If no measurement table , then make a measurement t... |
def update_steadystate ( x , z , K , H = None ) :
"""Add a new measurement ( z ) to the Kalman filter . If z is None , nothing
is changed .
Parameters
x : numpy . array ( dim _ x , 1 ) , or float
State estimate vector
z : ( dim _ z , 1 ) : array _ like
measurement for this update . z can be a scalar if ... | if z is None :
return x
if H is None :
H = np . array ( [ 1 ] )
if np . isscalar ( H ) :
H = np . array ( [ H ] )
Hx = np . atleast_1d ( dot ( H , x ) )
z = reshape_z ( z , Hx . shape [ 0 ] , x . ndim )
# error ( residual ) between measurement and prediction
y = z - Hx
# estimate new x with residual scaled ... |
def _group_detect ( templates , stream , threshold , threshold_type , trig_int , plotvar , group_size = None , pre_processed = False , daylong = False , parallel_process = True , xcorr_func = None , concurrency = None , cores = None , ignore_length = False , overlap = "calculate" , debug = 0 , full_peaks = False , proc... | master = templates [ 0 ]
# Check that they are all processed the same .
lap = 0.0
for template in templates :
starts = [ t . stats . starttime for t in template . st . sort ( [ 'starttime' ] ) ]
if starts [ - 1 ] - starts [ 0 ] > lap :
lap = starts [ - 1 ] - starts [ 0 ]
if not template . same_proce... |
def perms_check ( perms , prefix , ambiguous = False ) :
"""Return the user ' s perms for the specified prefix
perms < dict > permissions dict
prefix < string > namespace to check for perms
ambiguous < bool = False > if True reverse wildcard matching is active and a perm check for a . b . * will
be matched ... | try :
token = prefix . split ( "." )
i = 1
l = len ( token )
r = 0
# collect permission rules with a wildcard in them , so we dont do unecessary
# regex searches later on
perms_wc = { }
for ns , p in perms . items ( ) :
if ns . find ( "*" ) > - 1 :
perms_wc [ re . esc... |
def _contains_cftime_datetimes ( array ) -> bool :
"""Check if an array contains cftime . datetime objects""" | try :
from cftime import datetime as cftime_datetime
except ImportError :
return False
else :
if array . dtype == np . dtype ( 'O' ) and array . size > 0 :
sample = array . ravel ( ) [ 0 ]
if isinstance ( sample , dask_array_type ) :
sample = sample . compute ( )
if i... |
def _create_variables ( self , n_features ) :
"""Create the TensorFlow variables for the model .
: param n _ features : number of features
: return : self""" | w_name = 'weights'
self . W = tf . Variable ( tf . truncated_normal ( shape = [ n_features , self . num_hidden ] , stddev = 0.1 ) , name = w_name )
tf . summary . histogram ( w_name , self . W )
bh_name = 'hidden-bias'
self . bh_ = tf . Variable ( tf . constant ( 0.1 , shape = [ self . num_hidden ] ) , name = bh_name )... |
def _extract_service_catalog ( self , body ) :
"""Set the client ' s service catalog from the response data .""" | self . auth_ref = access . create ( body = body )
self . service_catalog = self . auth_ref . service_catalog
self . auth_token = self . auth_ref . auth_token
self . auth_tenant_id = self . auth_ref . tenant_id
self . auth_user_id = self . auth_ref . user_id
if not self . endpoint_url :
self . endpoint_url = self . ... |
def on_linkType_changed ( self , evt ) :
"""User changed link kind , so prepare available fields .""" | if self . current_idx < 0 :
evt . Skip ( )
return
n = self . linkType . GetSelection ( )
lt_str = self . linkType . GetString ( n )
lt = self . link_code [ lt_str ]
self . prep_link_details ( lt )
lnk = self . page_links [ self . current_idx ]
lnk [ "update" ] = True
lnk [ "kind" ] = lt
self . enable_update ( )... |
def _handle_location ( self , location ) :
"""Return an element located at location with flexible args .
Args :
location : String xpath to use in an Element . find search OR
an Element ( which is simply returned ) .
Returns :
The found Element .
Raises :
ValueError if the location is a string that res... | if not isinstance ( location , ElementTree . Element ) :
element = self . find ( location )
if element is None :
raise ValueError ( "Invalid path!" )
else :
element = location
return element |
def load_obj_from_path ( import_path , prefix = None , ld = dict ( ) ) :
"""import a python object from an import path
` import _ path ` - a python import path . For instance :
mypackage . module . func
or
mypackage . module . class
` prefix ` ( str ) - a value to prepend to the import path
if it isn ' ... | if prefix and not import_path . startswith ( prefix ) :
import_path = '.' . join ( [ prefix , import_path ] )
log . debug ( 'attempting to load a python object from an import path' , extra = dict ( import_path = import_path , ** ld ) )
try :
mod = importlib . import_module ( import_path )
return mod
# y... |
def read_firmware_file ( file_path ) :
"""Reads a firmware file into a dequeue for processing .
: param file _ path : Path to the firmware file
: type file _ path : string
: returns : deque""" | data_queue = deque ( )
with open ( file_path ) as firmware_handle :
for line in firmware_handle :
line = line . rstrip ( )
if line != '' and line [ 0 ] == ':' :
data_queue . append ( line + "\r" )
return data_queue |
def get_bool ( self , name , default = None ) :
"""Retrieves an environment variable value as ` ` bool ` ` .
Integer values are converted as expected : zero evaluates to
` ` False ` ` , and non - zero to ` ` True ` ` . String values of ` ` ' true ' ` `
and ` ` ' false ' ` ` are evaluated case insensitive .
... | if name not in self :
if default is not None :
return default
raise EnvironmentError . not_found ( self . _prefix , name )
return bool ( self . get_int ( name ) ) |
def _end_of_decade ( self ) :
"""Reset the date to the last day of the decade .
: rtype : Date""" | year = self . year - self . year % YEARS_PER_DECADE + YEARS_PER_DECADE - 1
return self . set ( year , 12 , 31 ) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.