signature stringlengths 29 44.1k | implementation stringlengths 0 85.2k |
|---|---|
def emit ( self , value ) :
"""Emits a value to output writer .
Args :
value : a value of type expected by the output writer .""" | if not self . _tstate . output_writer :
logging . error ( "emit is called, but no output writer is set." )
return
self . _tstate . output_writer . write ( value ) |
def get_prefixes ( self , ns_uri ) :
"""Gets ( a copy of ) the prefix set for the given namespace .""" | ni = self . __lookup_uri ( ns_uri )
return ni . prefixes . copy ( ) |
def get_user ( self , user_id ) :
"""Details for a specific user .
Will pull from cached users first , or get and add to cached users .
: param username : the username or userId of the user
: return : VoicebaseUser""" | if user_id in self . _users :
return self . _users . get ( user_id )
else : # Load user
# Save user in cache
return |
def write ( self , basename = "/tmp/resynclist.xml" ) :
"""Write a single sitemap or sitemapindex XML document .
Must be overridden to support multi - file lists .""" | self . default_capability ( )
fh = open ( basename , 'w' )
s = self . new_sitemap ( )
s . resources_as_xml ( self , fh = fh , sitemapindex = self . sitemapindex )
fh . close ( ) |
def _create_p ( s , h ) :
"""Parabolic derivative""" | p = np . zeros_like ( s )
p [ 1 : ] = ( s [ : - 1 ] * h [ 1 : ] + s [ 1 : ] * h [ : - 1 ] ) / ( h [ 1 : ] + h [ : - 1 ] )
return p |
def list ( self , sort = False ) :
""": param sort : Result will be sorted if it ' s True
: return : A list of : class : ` Processor ` or its children classes""" | prs = self . _processors . values ( )
if sort :
return sorted ( prs , key = operator . methodcaller ( "cid" ) )
return prs |
def set_vertex_colors ( self , colors , indexed = None ) :
"""Set the vertex color array
Parameters
colors : array
Array of colors . Must have shape ( Nv , 4 ) ( indexing by vertex )
or shape ( Nf , 3 , 4 ) ( vertices indexed by face ) .
indexed : str | None
Should be ' faces ' if colors are indexed by ... | colors = _fix_colors ( np . asarray ( colors ) )
if indexed is None :
if colors . ndim != 2 :
raise ValueError ( 'colors must be 2D if indexed is None' )
if colors . shape [ 0 ] != self . n_vertices :
raise ValueError ( 'incorrect number of colors %s, expected %s' % ( colors . shape [ 0 ] , self... |
def filter_counter ( self , counter , min = 2 , max = 100000000 ) :
"""Filter the counted records .
Returns : List with record numbers .""" | records_filterd = { }
counter_all_records = 0
for item in counter :
counter_all_records += 1
if max > counter [ item ] >= min :
records_filterd [ item ] = counter [ item ]
self . stat [ 'user_record_events' ] = counter_all_records
self . stat [ 'records_filtered' ] = len ( records_filterd )
return recor... |
def _solve_scipy ( self , intern_x0 , tol = 1e-8 , method = None , ** kwargs ) :
"""Uses ` ` scipy . optimize . root ` `
See : http : / / docs . scipy . org / doc / scipy / reference / generated / scipy . optimize . root . html
Parameters
intern _ x0 : array _ like
initial guess
tol : float
Tolerance
... | from scipy . optimize import root
if method is None :
if self . nf > self . nx :
method = 'lm'
elif self . nf == self . nx :
method = 'hybr'
else :
raise ValueError ( 'Underdetermined problem' )
if 'band' in kwargs :
raise ValueError ( "Set 'band' at initialization instead." )
if... |
def describe_reserved_instances_offerings ( DryRun = None , ReservedInstancesOfferingIds = None , InstanceType = None , AvailabilityZone = None , ProductDescription = None , Filters = None , InstanceTenancy = None , OfferingType = None , NextToken = None , MaxResults = None , IncludeMarketplace = None , MinDuration = N... | pass |
def wv45 ( msg ) :
"""Wake vortex .
Args :
msg ( String ) : 28 bytes hexadecimal message string
Returns :
int : Wake vortex level . 0 = NIL , 1 = Light , 2 = Moderate , 3 = Severe""" | d = hex2bin ( data ( msg ) )
if d [ 12 ] == '0' :
return None
ws = bin2int ( d [ 13 : 15 ] )
return ws |
def _get_magnitude_term ( self , C , mag ) :
"""Returns the magnitude scaling term provided in Equation ( 5)""" | dmag = mag - 8.0
return C [ "c0" ] + C [ "c3" ] * dmag + C [ "c4" ] * ( dmag ** 2. ) |
def find_videos_by_playlist ( self , playlist_id , page = 1 , count = 20 ) :
"""doc : http : / / open . youku . com / docs / doc ? id = 71""" | url = 'https://openapi.youku.com/v2/playlists/videos.json'
params = { 'client_id' : self . client_id , 'playlist_id' : playlist_id , 'page' : page , 'count' : count }
r = requests . get ( url , params = params )
check_error ( r )
return r . json ( ) |
def auto_migrate_storage_system ( * , persistent_storage_system = None , new_persistent_storage_system = None , data_item_uuids = None , deletions : typing . List [ uuid . UUID ] = None , utilized_deletions : typing . Set [ uuid . UUID ] = None , ignore_older_files : bool = True ) :
"""Migrate items from the storag... | storage_handlers = persistent_storage_system . find_data_items ( )
ReaderInfo = collections . namedtuple ( "ReaderInfo" , [ "properties" , "changed_ref" , "large_format" , "storage_handler" , "identifier" ] )
reader_info_list = list ( )
for storage_handler in storage_handlers :
try :
large_format = isinstan... |
def find_contiguous_packing_segments ( polypeptide , residues , max_dist = 10.0 ) :
"""Assembly containing segments of polypeptide , divided according to separation of contiguous residues .
Parameters
polypeptide : Polypeptide
residues : iterable containing Residues
max _ dist : float
Separation beyond wh... | segments = Assembly ( assembly_id = polypeptide . ampal_parent . id )
residues_in_polypeptide = list ( sorted ( residues . intersection ( set ( polypeptide . get_monomers ( ) ) ) , key = lambda x : int ( x . id ) ) )
if not residues_in_polypeptide :
return segments
# residue _ pots contains separate pots of residue... |
def read_memory_block32 ( self , addr , size ) :
"""read a block of aligned words in memory . Returns
an array of word values""" | data = self . ap . read_memory_block32 ( addr , size )
return self . bp_manager . filter_memory_aligned_32 ( addr , size , data ) |
def add_records ( self , domain , records ) :
"""Adds the records to this domain . Each record should be a dict with the
following keys :
- type ( required )
- name ( required )
- data ( required )
- ttl ( optional )
- comment ( optional )
- priority ( required for MX and SRV records ; forbidden other... | if isinstance ( records , dict ) : # Single record passed
records = [ records ]
dom_id = utils . get_id ( domain )
uri = "/domains/%s/records" % dom_id
body = { "records" : records }
resp , resp_body = self . _async_call ( uri , method = "POST" , body = body , error_class = exc . DomainRecordAdditionFailed , has_re... |
def create_argparser ( self ) :
"""Factory for arg parser . Can be overridden as long as it returns
an ArgParser compatible instance .""" | if self . desc :
if self . title :
fulldesc = '%s\n\n%s' % ( self . title , self . desc )
else :
fulldesc = self . desc
else :
fulldesc = self . title
return self . ArgumentParser ( command = self , prog = self . name , description = fulldesc ) |
def add_classification_events ( obj , events , labels , signal_label = None , weights = None , test = False ) :
"""Add classification events to a TMVA : : Factory or TMVA : : DataLoader from NumPy arrays .
Parameters
obj : TMVA : : Factory or TMVA : : DataLoader
A TMVA : : Factory or TMVA : : DataLoader ( TMV... | if NEW_TMVA_API : # pragma : no cover
if not isinstance ( obj , TMVA . DataLoader ) :
raise TypeError ( "obj must be a TMVA.DataLoader " "instance for ROOT >= 6.07/04" )
else : # pragma : no cover
if not isinstance ( obj , TMVA . Factory ) :
raise TypeError ( "obj must be a TMVA.Factory instance... |
def default_security_rule_get ( name , security_group , resource_group , ** kwargs ) :
'''. . versionadded : : 2019.2.0
Get details about a default security rule within a security group .
: param name : The name of the security rule to query .
: param security _ group : The network security group containing t... | result = { }
default_rules = default_security_rules_list ( security_group = security_group , resource_group = resource_group , ** kwargs )
if isinstance ( default_rules , dict ) and 'error' in default_rules :
return default_rules
try :
for default_rule in default_rules :
if default_rule [ 'name' ] == na... |
def parse_names_and_default ( self ) :
"""parse for ` parse _ content `
{ title : [ ( ' - a , - - all = STH ' , ' default ' ) , . . . ] }""" | result = { }
for title , text in self . formal_content . items ( ) :
if not text :
result [ title ] = [ ]
continue
logger . debug ( '\n' + text )
collect = [ ]
to_list = text . splitlines ( )
# parse first line . Should NEVER failed .
# this will ensure in ` [ default : xxx ] ` ,... |
def remove ( key , val , delimiter = DEFAULT_TARGET_DELIM ) :
'''. . versionadded : : 0.17.0
Remove a value from a list in the grains config file
key
The grain key to remove .
val
The value to remove .
delimiter
The key can be a nested dict key . Use this parameter to
specify the delimiter you use ,... | grains = get ( key , [ ] , delimiter )
if not isinstance ( grains , list ) :
return 'The key {0} is not a valid list' . format ( key )
if val not in grains :
return 'The val {0} was not in the list {1}' . format ( val , key )
grains . remove ( val )
while delimiter in key :
key , rest = key . rsplit ( delim... |
def tags ( self ) :
"""The image ' s tags .""" | tags = self . attrs . get ( 'RepoTags' )
if tags is None :
tags = [ ]
return [ tag for tag in tags if tag != '<none>:<none>' ] |
def c_filler ( self , frequency ) :
'''Capacitance of an electrode covered in filler media ( e . g . , air or oil ) ,
normalized per unit area ( i . e . , units are F / mm ^ 2 ) .''' | try :
return np . interp ( frequency , self . _c_filler [ 'frequency' ] , self . _c_filler [ 'capacitance' ] )
except :
pass
return self . _c_filler |
def period ( self , value : float ) :
"""Set the period .
Args :
value ( float ) : seconds""" | if value < 0 :
raise ValueError ( "Period must be greater or equal than zero." )
self . _period = timedelta ( seconds = value ) |
def hasDefault ( self , param ) :
"""Checks whether a param has a default value .""" | param = self . _resolveParam ( param )
return param in self . _defaultParamMap |
def _parse_json ( self , response , exactly_one = True ) :
"""Parse responses as JSON objects .""" | if not len ( response ) :
return None
if exactly_one :
return self . _format_structured_address ( response [ 0 ] )
else :
return [ self . _format_structured_address ( c ) for c in response ] |
def _handle_load_unknown ( self , data , original ) :
"""Preserve unknown keys during deserialization .""" | for key , val in original . items ( ) :
if key not in self . fields :
data [ key ] = val
return data |
def transformer_base_vq1_16_nb1_packed_nda_b01_scales_dialog ( ) :
"""Set of hyperparameters .""" | hparams = transformer_base_vq1_16_nb1_packed_nda_b01_scales ( )
hparams . batch_size = 2048
hparams . max_length = 1024
hparams . filter_size = 3072
return hparams |
def find_first_available_template ( self , template_name_list ) :
"""Given a list of template names , find the first one that actually exists
and is available .""" | if isinstance ( template_name_list , six . string_types ) :
return template_name_list
else : # Take advantage of fluent _ pages ' internal implementation
return _select_template_name ( template_name_list ) |
def epsilon_crit ( self ) :
"""returns the critical projected mass density in units of M _ sun / Mpc ^ 2 ( physical units )""" | const_SI = const . c ** 2 / ( 4 * np . pi * const . G )
# c ^ 2 / ( 4 * pi * G ) in units of [ kg / m ]
conversion = const . Mpc / const . M_sun
# converts [ kg / m ] to [ M _ sun / Mpc ]
pre_const = const_SI * conversion
# c ^ 2 / ( 4 * pi * G ) in units of [ M _ sun / Mpc ]
Epsilon_Crit = self . D_s / ( self . D_d * ... |
def new_from_url ( cls , url , verify = True ) :
"""Constructs a new WebPage object for the URL ,
using the ` requests ` module to fetch the HTML .
Parameters
url : str
verify : bool""" | response = requests . get ( url , verify = verify , timeout = 2.5 )
return cls . new_from_response ( response ) |
def add_default_options ( self , optprs ) :
"""Adds the default reference viewer startup options to an
OptionParser instance ` optprs ` .""" | optprs . add_option ( "--bufsize" , dest = "bufsize" , metavar = "NUM" , type = "int" , default = 10 , help = "Buffer length to NUM" )
optprs . add_option ( '-c' , "--channels" , dest = "channels" , help = "Specify list of channels to create" )
optprs . add_option ( "--debug" , dest = "debug" , default = False , action... |
def getchar ( echo = False ) :
"""Fetches a single character from the terminal and returns it . This
will always return a unicode character and under certain rare
circumstances this might return more than one character . The
situations which more than one character is returned is when for
whatever reason mu... | f = _getchar
if f is None :
from . _termui_impl import getchar as f
return f ( echo ) |
def create_header_from_parent ( self , parent_header : BlockHeader , ** header_params : HeaderParams ) -> BlockHeader :
"""Passthrough helper to the VM class of the block descending from the
given header .""" | return self . get_vm_class_for_block_number ( block_number = parent_header . block_number + 1 , ) . create_header_from_parent ( parent_header , ** header_params ) |
def set_debug_mode ( debug = True ) :
"""Set the global debug mode .""" | global debug_mode
global _setting_keep_wirevector_call_stack
global _setting_slower_but_more_descriptive_tmps
debug_mode = debug
_setting_keep_wirevector_call_stack = debug
_setting_slower_but_more_descriptive_tmps = debug |
def get_plc_datetime ( self ) :
"""Get date and time from PLC .
: return : date and time as datetime""" | type_ = c_int32
buffer = ( type_ * 9 ) ( )
result = self . library . Cli_GetPlcDateTime ( self . pointer , byref ( buffer ) )
check_error ( result , context = "client" )
return datetime ( year = buffer [ 5 ] + 1900 , month = buffer [ 4 ] + 1 , day = buffer [ 3 ] , hour = buffer [ 2 ] , minute = buffer [ 1 ] , second = ... |
def get_storage_conn ( storage_account = None , storage_key = None , conn_kwargs = None ) :
'''. . versionadded : : 2015.8.0
Return a storage _ conn object for the storage account''' | if conn_kwargs is None :
conn_kwargs = { }
if not storage_account :
storage_account = config . get_cloud_config_value ( 'storage_account' , get_configured_provider ( ) , __opts__ , search_global = False , default = conn_kwargs . get ( 'storage_account' , None ) )
if not storage_key :
storage_key = config . ... |
def feed ( self , weights , data ) :
"""Evaluate the network with alternative weights on the input data and
return the output activation .""" | assert len ( data ) == self . layers [ 0 ] . size
self . layers [ 0 ] . apply ( data )
# Propagate trough the remaining layers .
connections = zip ( self . layers [ : - 1 ] , weights , self . layers [ 1 : ] )
for previous , weight , current in connections :
incoming = self . forward ( weight , previous . outgoing )... |
def batch ( self , reqs ) :
"""send batch request using jsonrpc 2.0""" | batch_data = [ ]
for req_id , req in enumerate ( reqs ) :
batch_data . append ( { "method" : req [ 0 ] , "params" : req [ 1 ] , "jsonrpc" : "2.0" , "id" : req_id } )
data = json . dumps ( batch_data )
response = self . session . post ( self . url , data = data ) . json ( )
return response |
def getGolangPackages ( self ) :
"""Get a list of all golang packages for all available branches""" | packages = { }
# get all packages
url = "%s/packages" % self . base_url
params = { "pattern" : "golang-*" , "limit" : 200 }
response = requests . get ( url , params = params )
if response . status_code != requests . codes . ok :
return { }
data = response . json ( )
for package in data [ "packages" ] :
packages... |
def ready ( self ) :
"""Called once per Django process instance .
If the filesystem setup fails or if an error is found in settings . py ,
django . core . exceptions . ImproperlyConfigured is raised , causing Django not to
launch the main GMN app .""" | # Stop the startup code from running automatically from pytest unit tests .
# When running tests in parallel with xdist , an instance of GMN is launched
# before thread specific settings have been applied .
# if hasattr ( sys , ' _ launched _ by _ pytest ' ) :
# return
self . _assert_readable_file_if_set ( 'CLIENT_CERT... |
def _get_library_metadata ( self , date_range ) :
"""Retrieve the libraries for the given date range , the assumption is that the date ranges do not overlap and
they are CLOSED _ CLOSED .
At the moment the date range is mandatory""" | if date_range is None :
raise Exception ( "A date range must be provided" )
if not ( date_range . start and date_range . end ) :
raise Exception ( "The date range {0} must contain a start and end date" . format ( date_range ) )
start = date_range . start if date_range . start . tzinfo is not None else date_rang... |
def interface_direct_csvpath ( csvpath ) :
"""help to direct to the correct interface interacting with DB by csvfile path""" | with open ( csvpath ) as csvfile :
reader = csv . DictReader ( csvfile )
for row in reader :
data_class = row . pop ( 'amaasclass' , '' )
return interface_direct_class ( data_class ) |
def __on_presence ( self , data ) :
"""Got a presence stanza""" | room_jid = data [ 'from' ] . bare
muc_presence = data [ 'muc' ]
room = muc_presence [ 'room' ]
nick = muc_presence [ 'nick' ]
with self . __lock :
try : # Get room state machine
room_data = self . __rooms [ room ]
if room_data . nick != nick : # Not about the room creator
return
exce... |
def set ( self , value ) :
"""Sets the value of the object
: param value :
An integer or a tuple of integers 0 and 1
: raises :
ValueError - when an invalid value is passed""" | if isinstance ( value , set ) :
if self . _map is None :
raise ValueError ( unwrap ( '''
%s._map has not been defined
''' , type_name ( self ) ) )
bits = [ 0 ] * self . _size
self . _native = value
for index in range ( 0 , self . _size ) :
key = se... |
def check_dependee_order ( depender , dependee , dependee_id ) :
"""Checks whether run orders are in the appropriate order .""" | # If it depends on a module id , then the module id should be higher up
# in the run order .
shutit_global . shutit_global_object . yield_to_draw ( )
if dependee . run_order > depender . run_order :
return 'depender module id:\n\n' + depender . module_id + '\n\n(run order: ' + str ( depender . run_order ) + ') ' + ... |
def grants ( self ) :
"""Retrieves the grants for this user . If the user is unrestricted , this
will result in an ApiError . This is smart , and will only fetch from the
api once unless the object is invalidated .
: returns : The grants for this user .
: rtype : linode . objects . account . UserGrants""" | from linode_api4 . objects . account import UserGrants
if not hasattr ( self , '_grants' ) :
resp = self . _client . get ( UserGrants . api_endpoint . format ( username = self . username ) )
grants = UserGrants ( self . _client , self . username , resp )
self . _set ( '_grants' , grants )
return self . _gra... |
def _compare ( self , other , method ) :
"""see https : / / regebro . wordpress . com / 2010/12/13 / python - implementing - rich - comparison - the - correct - way /""" | # This needs to be updated to take uncertainty into account :
if isinstance ( other , abc_mapping_primitives . Coordinate ) :
if self . get_dimensions ( ) != other . get_dimensions ( ) :
return False
other_values = other . get_values ( )
for index in range ( self . _dimensions ) :
if not met... |
def parse_params ( self , nb_candidate = 10 , overshoot = 0.02 , max_iter = 50 , clip_min = 0. , clip_max = 1. , ** kwargs ) :
""": param nb _ candidate : The number of classes to test against , i . e . ,
deepfool only consider nb _ candidate classes when
attacking ( thus accelerate speed ) . The nb _ candidate... | self . nb_candidate = nb_candidate
self . overshoot = overshoot
self . max_iter = max_iter
self . clip_min = clip_min
self . clip_max = clip_max
if len ( kwargs . keys ( ) ) > 0 :
warnings . warn ( "kwargs is unused and will be removed on or after " "2019-04-26." )
return True |
def do_add_signature ( input_file , output_file , signature_file ) :
"""Add a signature to the MAR file .""" | signature = open ( signature_file , 'rb' ) . read ( )
if len ( signature ) == 256 :
hash_algo = 'sha1'
elif len ( signature ) == 512 :
hash_algo = 'sha384'
else :
raise ValueError ( )
with open ( output_file , 'w+b' ) as dst :
with open ( input_file , 'rb' ) as src :
add_signature_block ( src , ... |
def read ( self , uri ) :
"""Method takes uri and creates a RDF graph from Fedora Repository
Args :
uri ( str ) : URI of Fedora URI
Returns :
rdflib . Graph""" | read_response = self . connect ( uri )
fedora_graph = rdflib . Graph ( ) . parse ( data = read_response . read ( ) , format = 'turtle' )
return fedora_graph |
def add_query ( self , sql , auto_begin = True , bindings = None , abridge_sql_log = False ) :
"""Add a query to the current transaction . A thin wrapper around
ConnectionManager . add _ query .
: param str sql : The SQL query to add
: param bool auto _ begin : If set and there is no transaction in progress ,... | return self . connections . add_query ( sql , auto_begin , bindings , abridge_sql_log ) |
def load ( self ) :
"""Load the definition of the rule , searching in the specified rule dirs first , then in the built - in definitions
: return : None""" | file_name_valid = False
rule_type_valid = False
# Look for a locally - defined rule
for rule_dir in self . rule_dirs :
file_path = os . path . join ( rule_dir , self . file_name ) if rule_dir else self . file_name
if os . path . isfile ( file_path ) :
self . file_path = file_path
file_name_valid... |
def write_index ( fn , index ) :
"""Writes the index to file .
Args :
fn ( str ) : the name of the file that will contain the index .
index ( pandas . DataFrame ) : the index .""" | with open ( fn , "wb" ) as o_file :
o_file . write ( _CHECK_STRING )
o_file . write ( zlib . compress ( bytes ( index . to_csv ( None , index = False , encoding = "utf-8" ) , encoding = "utf-8" , ) ) ) |
def set_mode ( filename , flags ) :
"""Set mode flags for given filename if not already set .""" | try :
mode = os . lstat ( filename ) . st_mode
except OSError : # ignore
return
if not ( mode & flags ) :
try :
os . chmod ( filename , flags | mode )
except OSError as msg :
log_error ( "could not set mode flags for `%s': %s" % ( filename , msg ) ) |
def _buildFromPerPartition ( self , item , partition ) :
"""This function will get the partition info and then it ' ll write the container and preservation data
to the dictionary ' item '
: param item : a dict which contains the ARTeplate data columns
: param partition : a dict with some partition info
: re... | uc = getToolByName ( self , 'uid_catalog' )
container = uc ( UID = partition . get ( 'container_uid' , '' ) )
preservation = uc ( UID = partition . get ( 'preservation_uid' , '' ) )
if container :
container = container [ 0 ] . getObject ( )
item [ 'ContainerTitle' ] = container . title
item [ 'replace' ] [ ... |
def _get_file_size ( self ) :
"""Fetches file size by reading the Content - Length header
for the resource .
: return : File size .""" | file_size = retry ( self . _retry_count ) ( _get_content_length ) ( self . _session , self . url , self . _timeout )
file_size = int ( file_size )
if file_size == 0 :
with io . open ( self . _file_path , 'a' , encoding = 'utf-8' ) :
pass
return file_size |
def _PrintExtractionStatusUpdateWindow ( self , processing_status ) :
"""Prints an extraction status update in window mode .
Args :
processing _ status ( ProcessingStatus ) : processing status .""" | if self . _stdout_output_writer :
self . _ClearScreen ( )
output_text = 'plaso - {0:s} version {1:s}\n\n' . format ( self . _tool_name , plaso . __version__ )
self . _output_writer . Write ( output_text )
self . PrintExtractionStatusHeader ( processing_status )
table_view = views . CLITabularTableView ( column_name... |
def openOrder ( self , orderId , contract , order , orderState ) :
"""This wrapper is called to :
* feed in open orders at startup ;
* feed in open orders or order updates from other clients and TWS
if clientId = master id ;
* feed in manual orders and order updates from TWS if clientId = 0;
* handle open... | if order . whatIf : # response to whatIfOrder
self . _endReq ( order . orderId , orderState )
else :
key = self . orderKey ( order . clientId , order . orderId , order . permId )
trade = self . trades . get ( key )
# ignore ' ? ' values in the order
d = { k : v for k , v in order . dict ( ) . items ... |
def calculate_subscription_lifecycle ( subscription_id ) :
"""Calculates the expected lifecycle position the subscription in
subscription _ ids , and creates a BehindSubscription entry for them .
Args :
subscription _ id ( str ) : ID of subscription to calculate lifecycle for""" | subscription = Subscription . objects . select_related ( "messageset" , "schedule" ) . get ( id = subscription_id )
behind = subscription . messages_behind ( )
if behind == 0 :
return
current_messageset = subscription . messageset
current_sequence_number = subscription . next_sequence_number
end_subscription = Subs... |
def put_observation_field_values ( observation_id : int , observation_field_id : int , value : Any , access_token : str ) -> Dict [ str , Any ] : # TODO : Also implement a put _ or _ update _ observation _ field _ values ( ) that deletes then recreates the field _ value ?
# TODO : Write example use in docstring .
# TOD... | payload = { 'observation_field_value' : { 'observation_id' : observation_id , 'observation_field_id' : observation_field_id , 'value' : value } }
response = requests . put ( "{base_url}/observation_field_values/{id}" . format ( base_url = INAT_BASE_URL , id = observation_field_id ) , headers = _build_auth_header ( acce... |
def cleanup_subprocesses ( ) :
"""On python exit : find possibly running subprocesses and kill them .""" | # pylint : disable = redefined - outer - name , reimported
# atexit functions tends to loose global imports sometimes so reimport
# everything what is needed again here :
import os
import errno
from mirakuru . base_env import processes_with_env
from mirakuru . compat import SIGKILL
pids = processes_with_env ( ENV_UUID ... |
def fit ( self , P ) :
"""Fit the diagonal matrices in Sinkhorn Knopp ' s algorithm
Parameters
P : 2d array - like
Must be a square non - negative 2d array - like object , that
is convertible to a numpy array . The matrix must not be
equal to 0 and it must have total support for the algorithm
to converg... | P = np . asarray ( P )
assert np . all ( P >= 0 )
assert P . ndim == 2
assert P . shape [ 0 ] == P . shape [ 1 ]
N = P . shape [ 0 ]
max_thresh = 1 + self . _epsilon
min_thresh = 1 - self . _epsilon
# Initialize r and c , the diagonals of D1 and D2
# and warn if the matrix does not have support .
r = np . ones ( ( N , ... |
def _to_dict ( self ) :
"""Return a json dictionary representing this model .""" | _dict = { }
if hasattr ( self , 'field_name' ) and self . field_name is not None :
_dict [ 'field' ] = self . field_name
if hasattr ( self , 'field_type' ) and self . field_type is not None :
_dict [ 'type' ] = self . field_type
return _dict |
def create_event_object ( self , event_type , code , value , timeval = None ) :
"""Create an evdev style object .""" | if not timeval :
timeval = self . __get_timeval ( )
try :
event_code = self . manager . codes [ 'type_codes' ] [ event_type ]
except KeyError :
raise UnknownEventType ( "We don't know what kind of event a %s is." % event_type )
event = struct . pack ( EVENT_FORMAT , timeval [ 0 ] , timeval [ 1 ] , event_cod... |
def export ( self ) :
"""Returns a dictionary with all song information .
Use the : meth : ` from _ export ` method to recreate the
: class : ` Song ` object .""" | return { 'artists' : self . _artists , 'radio' : self . _radio , 'recent_artists' : self . _recent_artists , 'songs_already_seen' : self . _songs_already_seen } |
def is_group ( value ) :
"""Check whether groupname or gid as argument exists .
if this function recieved groupname , convert gid and exec validation .""" | if type ( value ) == str :
try :
entry = grp . getgrnam ( value )
value = entry . gr_gid
except KeyError :
err_message = ( '{0}: No such group.' . format ( value ) )
raise validate . VdtValueError ( err_message )
return value
elif type ( value ) == int :
try :
grp... |
def mbar_W_nk ( u_kn , N_k , f_k ) :
"""Calculate the weight matrix .
Parameters
u _ kn : np . ndarray , shape = ( n _ states , n _ samples ) , dtype = ' float '
The reduced potential energies , i . e . - log unnormalized probabilities
N _ k : np . ndarray , shape = ( n _ states ) , dtype = ' int '
The nu... | return np . exp ( mbar_log_W_nk ( u_kn , N_k , f_k ) ) |
def Append ( self , ** kw ) :
"""Append values to existing construction variables
in an Environment .""" | kw = copy_non_reserved_keywords ( kw )
for key , val in kw . items ( ) : # It would be easier on the eyes to write this using
# " continue " statements whenever we finish processing an item ,
# but Python 1.5.2 apparently doesn ' t let you use " continue "
# within try : - except : blocks , so we have to nest our code ... |
def ignore_reports ( self ) :
"""Ignore future reports on this object .
This prevents future reports from causing notifications or appearing
in the various moderation listing . The report count will still
increment .""" | url = self . reddit_session . config [ 'ignore_reports' ]
data = { 'id' : self . fullname }
return self . reddit_session . request_json ( url , data = data ) |
def associate_dhcp_options_to_vpc ( dhcp_options_id , vpc_id = None , vpc_name = None , region = None , key = None , keyid = None , profile = None ) :
'''Given valid DHCP options id and a valid VPC id , associate the DHCP options record with the VPC .
Returns True if the DHCP options record were associated and re... | try :
vpc_id = check_vpc ( vpc_id , vpc_name , region , key , keyid , profile )
if not vpc_id :
return { 'associated' : False , 'error' : { 'message' : 'VPC {0} does not exist.' . format ( vpc_name or vpc_id ) } }
conn = _get_conn ( region = region , key = key , keyid = keyid , profile = profile )
... |
def organize_objects ( self ) :
"""Organize objects and namespaces""" | def _render_children ( obj ) :
for child in obj . children_strings :
child_object = self . objects . get ( child )
if child_object :
obj . item_map [ child_object . plural ] . append ( child_object )
obj . children . append ( child_object )
for key in obj . item_map :
... |
def add_arguments ( self , parser ) :
"""Add arguments to the command parser .
Uses argparse syntax . See documentation at
https : / / docs . python . org / 3 / library / argparse . html .""" | parser . add_argument ( '--start' , '-s' , default = 0 , type = int , help = u"The Submission.id at which to begin updating rows. 0 by default." )
parser . add_argument ( '--chunk' , '-c' , default = 1000 , type = int , help = u"Batch size, how many rows to update in a given transaction. Default 1000." , )
parser . add... |
def image_predict ( self , X ) :
"""Predicts class label for the entire image .
Parameters :
X : array , shape = [ n _ samples , n _ pixels _ y , n _ pixels _ x , n _ bands ]
Array of training images
y : array , shape = [ n _ samples ] or [ n _ samples , n _ pixels _ y , n _ pixels _ x ]
Target labels or ... | self . _check_image ( X )
patches , patches_shape = self . _to_patches ( X )
predictions = self . classifier . predict ( self . _transform_input ( patches ) )
image_predictions = predictions . reshape ( patches_shape [ 0 : 3 ] )
image_results = np . zeros ( ( self . _samples , ) + self . _image_size )
nx , ny = self . ... |
def roots ( g ) :
"Get nodes from graph G with indegree 0" | return set ( n for n , d in iteritems ( g . in_degree ( ) ) if d == 0 ) |
def _connect ( self ) :
"""Connect to our domain""" | if not self . _db :
import boto
sdb = boto . connect_sdb ( )
if not self . domain_name :
self . domain_name = boto . config . get ( "DB" , "sequence_db" , boto . config . get ( "DB" , "db_name" , "default" ) )
try :
self . _db = sdb . get_domain ( self . domain_name )
except SDBRespo... |
def add ( self , element ) :
"""Add an element to this set .""" | key = self . _transform ( element )
if key not in self . _elements :
self . _elements [ key ] = element |
def promptyn ( msg , default = None ) :
"""Display a blocking prompt until the user confirms""" | while True :
yes = "Y" if default else "y"
if default or default is None :
no = "n"
else :
no = "N"
confirm = prompt ( "%s [%s/%s]" % ( msg , yes , no ) , "" ) . lower ( )
if confirm in ( "y" , "yes" ) :
return True
elif confirm in ( "n" , "no" ) :
return False
... |
def _get_balance ( self ) :
"""Get to know how much you totally have and how much you get today .""" | response = self . session . get ( self . balance_url , verify = False )
soup = BeautifulSoup ( response . text , 'html.parser' )
first_line = soup . select ( "table.data tr:nth-of-type(2)" ) [ 0 ] . text . strip ( ) . split ( '\n' )
total , today = first_line [ - 2 : ]
logging . info ( '%-26sTotal:%-8s' , today , total... |
def _render_log ( ) :
"""Totally tap into Towncrier internals to get an in - memory result .""" | config = load_config ( ROOT )
definitions = config [ 'types' ]
fragments , fragment_filenames = find_fragments ( pathlib . Path ( config [ 'directory' ] ) . absolute ( ) , config [ 'sections' ] , None , definitions , )
rendered = render_fragments ( pathlib . Path ( config [ 'template' ] ) . read_text ( encoding = 'utf-... |
def set_state ( self , state ) :
"""Switches state of the TDS session .
It also does state transitions checks .
: param state : New state , one of TDS _ PENDING / TDS _ READING / TDS _ IDLE / TDS _ DEAD / TDS _ QUERING""" | prior_state = self . state
if state == prior_state :
return state
if state == tds_base . TDS_PENDING :
if prior_state in ( tds_base . TDS_READING , tds_base . TDS_QUERYING ) :
self . state = tds_base . TDS_PENDING
else :
raise tds_base . InterfaceError ( 'logic error: cannot chage query stat... |
def show_message ( self , text_string , scroll_speed = .1 , text_colour = [ 255 , 255 , 255 ] , back_colour = [ 0 , 0 , 0 ] ) :
"""Scrolls a string of text across the LED matrix using the specified
speed and colours""" | # We must rotate the pixel map left through 90 degrees when drawing
# text , see _ load _ text _ assets
previous_rotation = self . _rotation
self . _rotation -= 90
if self . _rotation < 0 :
self . _rotation = 270
dummy_colour = [ None , None , None ]
string_padding = [ dummy_colour ] * 64
letter_padding = [ dummy_c... |
def find_enclosing_bracket_right ( self , left_ch , right_ch , end_pos = None ) :
"""Find the right bracket enclosing current position . Return the relative
position to the cursor position .
When ` end _ pos ` is given , don ' t look past the position .""" | if self . current_char == right_ch :
return 0
if end_pos is None :
end_pos = len ( self . text )
else :
end_pos = min ( len ( self . text ) , end_pos )
stack = 1
# Look forward .
for i in range ( self . cursor_position + 1 , end_pos ) :
c = self . text [ i ]
if c == left_ch :
stack += 1
... |
def get_recent_mtime ( t ) :
'''获取更精简的时间 .
如果是当天的 , 就返回时间 ; 如果是当年的 , 就近回月份和日期 ; 否则返回完整的时间''' | if isinstance ( t , int ) : # ignore micro seconds
if len ( str ( t ) ) == 13 :
t = t // 1000
t = datetime . datetime . fromtimestamp ( t )
now = datetime . datetime . now ( )
delta = now - t
if delta . days == 0 :
return datetime . datetime . strftime ( t , '%H:%M:%S' )
elif now . year == t . year ... |
def _metaconfigure ( self , argv = None ) :
"""Initialize metaconfig for provisioning self .""" | metaconfig = self . _get_metaconfig_class ( )
if not metaconfig :
return
if self . __class__ is metaconfig : # don ' t get too meta
return
override = { 'conflict_handler' : 'resolve' , 'add_help' : False , 'prog' : self . _parser_kwargs . get ( 'prog' ) , }
self . _metaconf = metaconfig ( ** override )
metapars... |
def _init ( self , * args , ** kwargs ) :
"""_ deps is used for common dependencies .
When a expr depend on other exprs , and the expr is not calculated from the others ,
the _ deps are specified to identify the dependencies .""" | self . _init_attr ( '_deps' , None )
self . _init_attr ( '_ban_optimize' , False )
self . _init_attr ( '_engine' , None )
self . _init_attr ( '_Expr__execution' , None )
self . _init_attr ( '_need_cache' , False )
self . _init_attr ( '_mem_cache' , False )
if '_id' not in kwargs :
kwargs [ '_id' ] = new_id ( )
supe... |
def columns ( self ) :
"""Returns the list of selected column names .""" | fields = [ f . label for f in self . form_fields if self . cleaned_data [ "field_%s_export" % f . id ] ]
if self . cleaned_data [ "field_0_export" ] :
fields . append ( self . entry_time_name )
return fields |
def media_new ( self , mrl , * options ) :
"""Create a new Media instance .
If mrl contains a colon ( : ) preceded by more than 1 letter , it
will be treated as a URL . Else , it will be considered as a
local path . If you need more control , directly use
media _ new _ location / media _ new _ path methods ... | if ':' in mrl and mrl . index ( ':' ) > 1 : # Assume it is a URL
m = libvlc_media_new_location ( self , str_to_bytes ( mrl ) )
else : # Else it should be a local path .
m = libvlc_media_new_path ( self , str_to_bytes ( os . path . normpath ( mrl ) ) )
for o in options :
libvlc_media_add_option ( m , str_to_... |
def bna_config_cmd_output_status_string ( self , ** kwargs ) :
"""Auto Generated Code""" | config = ET . Element ( "config" )
bna_config_cmd = ET . Element ( "bna_config_cmd" )
config = bna_config_cmd
output = ET . SubElement ( bna_config_cmd , "output" )
status_string = ET . SubElement ( output , "status-string" )
status_string . text = kwargs . pop ( 'status_string' )
callback = kwargs . pop ( 'callback' ,... |
def contains_index ( self ) :
"""Returns the * line number * that has the CONTAINS keyword separating the
member and type definitions from the subroutines and functions .""" | if self . _contains_index is None :
max_t = 0
for tkey in self . types :
if self . types [ tkey ] . end > max_t and not self . types [ tkey ] . embedded :
max_t = self . types [ tkey ] . end
# Now we have a good first guess . Continue to iterate the next few lines
# of the the refstr... |
def build_request_include ( include , params ) :
"""Augment request parameters with includes .
When one or all resources are requested an additional set of
resources can be requested as part of the request . This function
extends the given parameters for a request with a list of resource
types passed in as ... | params = params or OrderedDict ( )
if include is not None :
params [ 'include' ] = ',' . join ( [ cls . _resource_type ( ) for cls in include ] )
return params |
def start_discovery ( self , service_uuids = [ ] ) :
"""Starts a discovery for BLE devices with given service UUIDs .
: param service _ uuids : Filters the search to only return devices with given UUIDs .""" | discovery_filter = { 'Transport' : 'le' }
if service_uuids : # D - Bus doesn ' t like empty lists , it needs to guess the type
discovery_filter [ 'UUIDs' ] = service_uuids
try :
self . _adapter . SetDiscoveryFilter ( discovery_filter )
self . _adapter . StartDiscovery ( )
except dbus . exceptions . DBusExce... |
def _clone ( self ) :
'''Must clone additional fields to those cloned by elasticsearch - dsl - py .''' | instance = super ( Bungiesearch , self ) . _clone ( )
instance . _raw_results_only = self . _raw_results_only
return instance |
def queryset ( self , request ) :
"""Returns a Queryset of all model instances that can be edited by the
admin site . This is used by changelist _ view .""" | query_set = self . model . _default_manager . all_with_deleted ( )
ordering = self . ordering or ( )
if ordering :
query_set = query_set . order_by ( * ordering )
return query_set |
def _sanitize_dates ( start , end ) :
"""Return ( datetime _ start , datetime _ end ) tuple
if start is None - default is 2015/01/01
if end is None - default is today""" | if isinstance ( start , int ) : # regard int as year
start = datetime ( start , 1 , 1 )
start = to_datetime ( start )
if isinstance ( end , int ) :
end = datetime ( end , 1 , 1 )
end = to_datetime ( end )
if start is None :
start = datetime ( 2015 , 1 , 1 )
if end is None :
end = datetime . today ( )
if... |
def get_rollback_status_reason ( self , stack_name ) :
"""Process events and returns latest roll back reason""" | event = next ( ( item for item in self . get_events ( stack_name , False ) if item [ "ResourceStatus" ] == "UPDATE_ROLLBACK_IN_PROGRESS" ) , None )
if event :
reason = event [ "ResourceStatusReason" ]
return reason
else :
event = next ( ( item for item in self . get_events ( stack_name ) if item [ "Resource... |
def user_parse ( data ) :
"""Parse information from provider .""" | id_ = data . get ( 'id' )
yield 'id' , id_
yield 'email' , data . get ( 'email' )
yield 'first_name' , data . get ( 'first_name' )
yield 'last_name' , data . get ( 'last_name' )
yield 'username' , data . get ( 'name' )
yield 'picture' , 'http://graph.facebook.com/{0}/picture?' 'type=large' . format ( id_ )
yield 'link'... |
def version ( app , appbuilder ) :
"""Flask - AppBuilder package version""" | _appbuilder = import_application ( app , appbuilder )
click . echo ( click . style ( "F.A.B Version: {0}." . format ( _appbuilder . version ) , bg = "blue" , fg = "white" ) ) |
def reorder ( self , fields_in_new_order ) :
"""Pass in field names in the order you wish them to be swapped .""" | if not len ( fields_in_new_order ) == len ( self . fields ) :
raise Exception ( "Fields to reorder with are not the same length " "(%s) as the original fields (%s)" % ( len ( fields_in_new_order ) , len ( self . fields ) ) )
if not set ( fields_in_new_order ) == set ( self . fields ) :
raise Exception ( "Fields... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.