signature stringlengths 29 44.1k | implementation stringlengths 0 85.2k |
|---|---|
def updating ( name , jail = None , chroot = None , root = None , filedate = None , filename = None ) :
'''Displays UPDATING entries of software packages
CLI Example :
. . code - block : : bash
salt ' * ' pkg . updating foo
jail
Perform the action in the specified jail
CLI Example :
. . code - block :... | opts = ''
if filedate :
opts += 'd {0}' . format ( filedate )
if filename :
opts += 'f {0}' . format ( filename )
cmd = _pkg ( jail , chroot , root )
cmd . append ( 'updating' )
if opts :
cmd . append ( '-' + opts )
cmd . append ( name )
return __salt__ [ 'cmd.run' ] ( cmd , output_loglevel = 'trace' , pyth... |
def write_file ( self , html , outfile ) :
"""Write an HTML string to a file .""" | try :
with open ( outfile , 'wt' ) as file :
file . write ( html )
except ( IOError , OSError ) as e :
err_exit ( 'Error writing %s: %s' % ( outfile , e . strerror or e ) ) |
def _execute_request ( self , request ) :
"""Helper method to execute a request , since a lock should be used
to not fire up multiple requests at the same time .
: return : Result of ` request . execute `""" | with GoogleCloudProvider . __gce_lock :
return request . execute ( http = self . _auth_http ) |
def quoted_tweet ( self ) :
"""The quoted Tweet as a Tweet object
If the Tweet is not a quote Tweet , return None
If the quoted Tweet payload cannot be loaded as a Tweet , this will
raise a " NotATweetError "
Returns :
Tweet : A Tweet representing the quoted status ( or None )
( see tweet _ embeds . get... | quote_tweet = tweet_embeds . get_quoted_tweet ( self )
if quote_tweet is not None :
try :
return Tweet ( quote_tweet )
except NotATweetError as nate :
raise ( NotATweetError ( "The quote-tweet payload appears malformed." + " Failed with '{}'" . format ( nate ) ) )
else :
return None |
def slurpLines ( file , expand = False ) :
r"""Read in a complete file ( specified by a file handler or a filename
string / unicode string ) as list of lines""" | file = _normalizeToFile ( file , "r" , expand )
try :
return file . readlines ( )
finally :
file . close ( ) |
def decode_cf_variables ( variables , attributes , concat_characters = True , mask_and_scale = True , decode_times = True , decode_coords = True , drop_variables = None , use_cftime = None ) :
"""Decode several CF encoded variables .
See : decode _ cf _ variable""" | dimensions_used_by = defaultdict ( list )
for v in variables . values ( ) :
for d in v . dims :
dimensions_used_by [ d ] . append ( v )
def stackable ( dim ) : # figure out if a dimension can be concatenated over
if dim in variables :
return False
for v in dimensions_used_by [ dim ] :
... |
async def handle_agent_hello ( self , agent_addr , message : AgentHello ) :
"""Handle an AgentAvailable message . Add agent _ addr to the list of available agents""" | self . _logger . info ( "Agent %s (%s) said hello" , agent_addr , message . friendly_name )
if agent_addr in self . _registered_agents : # Delete previous instance of this agent , if any
await self . _delete_agent ( agent_addr )
self . _registered_agents [ agent_addr ] = message . friendly_name
self . _available_ag... |
def delete_ssh_template ( auth , url , template_name = None , template_id = None ) :
"""Takes template _ name as input to issue RESTUL call to HP IMC which will delete the specific
ssh template from the IMC system
: param auth : requests auth object # usually auth . creds from auth pyhpeimc . auth . class
: p... | try :
if template_id is None :
ssh_templates = get_ssh_template ( auth , url )
if template_name is None :
template_name = ssh_template [ 'name' ]
template_id = None
for template in ssh_templates :
if template [ 'name' ] == template_name :
templ... |
def expose ( * methods ) :
"""A decorator for exposing the methods of a class .
Parameters
* methods : str
A str representation of the methods that should be exposed to callbacks .
Returns
decorator : function
A function accepting one argument - the class whose methods will be
exposed - and which retu... | def setup ( base ) :
return expose_as ( base . __name__ , base , * methods )
return setup |
def check ( self , request , user ) :
"""check if the service is well configured
: return : Boolean""" | redirect_uris = '%s://%s%s' % ( request . scheme , request . get_host ( ) , reverse ( 'mastodon_callback' ) )
us = UserService . objects . get ( user = user , name = 'ServiceMastodon' )
client_id , client_secret = MastodonAPI . create_app ( client_name = "TriggerHappy" , api_base_url = us . host , redirect_uris = redir... |
def re_line_and_indentation ( base_indentation , modifiers = ( True , True ) ) :
"""Returns a re matching newline + base _ indentation .
modifiers is a tuple , ( include _ first , include _ final ) .
If include _ first , matches indentation at the beginning of the string .
If include _ final , matches indenta... | cache = re_line_and_indentation . cache [ modifiers ]
compiled = cache . get ( base_indentation , None )
if compiled is None :
[ prefix , suffix ] = re_line_and_indentation . tuple [ modifiers ]
compiled = cache [ modifiers ] = _re . compile ( prefix + base_indentation + suffix )
return compiled |
def __get_segmentation_path ( self , path ) :
"""Create path with " _ segmentation " suffix and keep extension .
: param path :
: return :""" | startpath , ext = os . path . splitext ( path )
segmentation_path = startpath + "_segmentation" + ext
return segmentation_path |
def artifact_bundles ( self ) :
"""Gets the Artifact Bundles API client .
Returns :
ArtifactBundles :""" | if not self . __artifact_bundles :
self . __artifact_bundles = ArtifactBundles ( self . __connection )
return self . __artifact_bundles |
def _ctxs ( self ) :
""": rtype : list of SliceViewContext""" | return [ self . _tab_widget . widget ( index ) . context for index in range ( 0 , self . _tab_widget . count ( ) ) ] |
def check_garner ( text ) :
"""Suggest the preferred forms .
source : Garner ' s Modern American Usage
source _ url : http : / / bit . ly / 1T4alrY""" | err = "redundancy.garner"
msg = "Redundancy. Use '{}' instead of '{}'."
redundancies = [ [ "adequate" , [ "adequate enough" ] ] , [ "admitted" , [ "self-admitted" ] ] , [ "affidavit" , [ "sworn affidavit" ] ] , [ "agreement" , [ "mutual agreement" ] ] , [ "alumnus" , [ "former alumnus" ] ] , [ "antithetical" , [ "direc... |
def load_pyproject_toml ( use_pep517 , # type : Optional [ bool ]
pyproject_toml , # type : str
setup_py , # type : str
req_name # type : str
) : # type : ( . . . ) - > Optional [ Tuple [ List [ str ] , str , List [ str ] ] ]
"""Load the pyproject . toml file .
Parameters :
use _ pep517 - Has the user requested... | has_pyproject = os . path . isfile ( pyproject_toml )
has_setup = os . path . isfile ( setup_py )
if has_pyproject :
with io . open ( pyproject_toml , encoding = "utf-8" ) as f :
pp_toml = pytoml . load ( f )
build_system = pp_toml . get ( "build-system" )
else :
build_system = None
# The following ... |
def split ( args ) :
"""% prog split file outdir N
Split file into N records . This allows splitting FASTA / FASTQ / TXT file
properly at boundary of records . Split is useful for parallelization
on input chunks .
Option - - mode is useful on how to break into chunks .
1 . chunk - chunk records sequential... | p = OptionParser ( split . __doc__ )
mode_choices = ( "batch" , "cycle" , "optimal" )
p . add_option ( "--all" , default = False , action = "store_true" , help = "split all records [default: %default]" )
p . add_option ( "--mode" , default = "optimal" , choices = mode_choices , help = "Mode when splitting records [defa... |
def showDraw ( self , fignum = 1 ) :
"""show the element drawing
: param fignum : define figure number to show element drawing""" | if self . _patches == [ ] :
print ( "Please setDraw() before showDraw(), then try again." )
return
else :
fig = plt . figure ( fignum )
fig . clear ( )
ax = fig . add_subplot ( 111 , aspect = 'equal' )
[ ax . add_patch ( i ) for i in self . _patches ]
bbox = self . _patches [ 0 ] . get_path ... |
def _unpack_oxm_field ( self ) :
"""Unpack oxm _ field from oxm _ field _ and _ mask .
Returns :
: class : ` OxmOfbMatchField ` , int : oxm _ field from oxm _ field _ and _ mask .
Raises :
ValueError : If oxm _ class is OFPXMC _ OPENFLOW _ BASIC but
: class : ` OxmOfbMatchField ` has no such integer value... | field_int = self . oxm_field_and_mask >> 1
# We know that the class below requires a subset of the ofb enum
if self . oxm_class == OxmClass . OFPXMC_OPENFLOW_BASIC :
return OxmOfbMatchField ( field_int )
return field_int |
def assignrepr ( self , prefix , style = None , utcoffset = None ) :
"""Return a | repr | string with an prefixed assignement .
Without option arguments given , printing the returned string
looks like :
> > > from hydpy import Timegrid
> > > timegrid = Timegrid ( ' 1996-11-01 00:00:00 ' ,
. . . ' 1997-11-... | skip = len ( prefix ) + 9
blanks = ' ' * skip
return ( f"{prefix}Timegrid('" f"{self.firstdate.to_string(style, utcoffset)}',\n" f"{blanks}'{self.lastdate.to_string(style, utcoffset)}',\n" f"{blanks}'{str(self.stepsize)}')" ) |
def remove_widget ( self ) :
"""Removes the Component Widget from the engine .
: return : Method success .
: rtype : bool""" | LOGGER . debug ( "> Removing '{0}' Component Widget." . format ( self . __class__ . __name__ ) )
self . __preferences_manager . findChild ( QGridLayout , "Others_Preferences_gridLayout" ) . removeWidget ( self )
self . TCP_Client_Ui_groupBox . setParent ( None )
return True |
def get_or_create_time_series ( self , label_values ) :
"""Get a mutable measurement for the given set of label values .
: type label _ values : list ( : class : ` LabelValue ` )
: param label _ values : The measurement ' s label values .
: rtype : : class : ` GaugePointLong ` , : class : ` GaugePointDouble `... | if label_values is None :
raise ValueError
if any ( lv is None for lv in label_values ) :
raise ValueError
if len ( label_values ) != self . _len_label_keys :
raise ValueError
return self . _get_or_create_time_series ( label_values ) |
def nvmlDeviceGetMemoryInfo ( handle ) :
r"""* Retrieves the amount of used , free and total memory available on the device , in bytes .
* For all products .
* Enabling ECC reduces the amount of total available memory , due to the extra required parity bits .
* Under WDDM most device memory is allocated and m... | c_memory = c_nvmlMemory_t ( )
fn = _nvmlGetFunctionPointer ( "nvmlDeviceGetMemoryInfo" )
ret = fn ( handle , byref ( c_memory ) )
_nvmlCheckReturn ( ret )
return bytes_to_str ( c_memory ) |
def main ( set_to = None , set_patch_count = None , release = None , bump = None , lock = None , file_triggers = None , config_path = None , ** extra_updates ) :
"""Main workflow .
Load config from cli and file
Detect " bump triggers " - things that cause a version increment
Find the current version
Create ... | updates = { }
if config_path :
get_or_create_config ( config_path , config )
for k , v in config . regexers . items ( ) :
config . regexers [ k ] = re . compile ( v )
# a forward - mapping of the configured aliases
# giving < our config param > : < the configured value >
# if a value occurs multiple times , we ... |
def to_compressed ( self ) :
"""Compress an IP address to its shortest possible compressed form .
> > > print ( IP ( ' 127.0.0.1 ' ) . to _ compressed ( ) )
127.1
> > > print ( IP ( ' 127.1.0.1 ' ) . to _ compressed ( ) )
127.1.1
> > > print ( IP ( ' 127.0.1.1 ' ) . to _ compressed ( ) )
127.0.1.1
> >... | if self . v == 4 :
quads = self . dq . split ( '.' )
try :
zero = quads . index ( '0' )
if zero == 1 and quads . index ( '0' , zero + 1 ) :
quads . pop ( zero )
quads . pop ( zero )
return '.' . join ( quads )
elif zero == 2 :
quads . pop (... |
def metadata ( self , run_id = None ) :
"""Provide metadata on a Ding0 run
Parameters
run _ id : str , ( defaults to current date )
Distinguish multiple versions of Ding0 data by a ` run _ id ` . If not
set it defaults to current date in the format YYYYMMDDhhmmss
Returns
dict
Metadata""" | # Get latest version and / or git commit hash
try :
version = subprocess . check_output ( [ "git" , "describe" , "--tags" , "--always" ] ) . decode ( 'utf8' )
except :
version = None
# Collect names of database table used to run Ding0 and data version
if self . config [ 'input_data_source' ] [ 'input_data' ] ==... |
def waliki_box ( context , slug , show_edit = True , * args , ** kwargs ) :
"""A templatetag to render a wiki page content as a box in any webpage ,
and allow rapid edition if you have permission .
It ' s inspired in ` django - boxes ` _
. . _ django - boxes : https : / / github . com / eldarion / django - bo... | request = context [ "request" ]
try :
page = Page . objects . get ( slug = slug )
except Page . DoesNotExist :
page = None
if ( page and check_perms_helper ( 'change_page' , request . user , slug ) or ( not page and check_perms_helper ( 'add_page' , request . user , slug ) ) ) :
form = PageForm ( instance =... |
def safe_run ( coro , return_exceptions = False ) :
"""Executes a given coroutine and optionally catches exceptions , returning
them as value . This function is intended to be used internally .""" | try :
result = yield from coro
except Exception as err :
if return_exceptions :
result = err
else :
raise err
return result |
def stop ( self , timeout = None ) :
"""Stops the task thread . Synchronous !""" | with self . _lock :
if self . _thread :
self . _queue . put_nowait ( self . _terminator )
self . _thread . join ( timeout = timeout )
self . _thread = None
self . _thread_for_pid = None |
def get_signatures_from_script ( script ) :
"""Returns a list of signatures retrieved from the provided ( partially )
signed multisig scriptSig .
: param script : The partially - signed multisig scriptSig .
: type script : ` ` bytes ` `
: returns : A list of retrieved signature from the provided scriptSig .... | script = script [ 1 : ]
# remove the first OP _ 0
sigs = [ ]
while len ( script ) > 0 : # Consume script while extracting possible signatures :
val , script = read_var_int ( script )
potential_sig , script = read_bytes ( script , val )
try : # Raises ValueError if argument to ` der _ to _ cdata ` is not a
... |
def display_output ( arguments ) :
'''Display the ASCII art from the image .''' | global _ASCII
if arguments [ '--alt-chars' ] :
_ASCII = _ASCII_2
try :
im = Image . open ( arguments [ 'FILE' ] )
except :
raise IOError ( 'Unable to open the file.' )
im = im . convert ( "RGBA" )
aspect_ratio = float ( im . size [ 0 ] ) / im . size [ 1 ]
scaled_height = _WIDTH / aspect_ratio
scaled_width =... |
def threshold ( self , n = None ) :
"""Returns the threshold number of tasks that need to be complete in order to consider the
workflow as being complete itself . This takes into account the
: py : attr : ` law . BaseWorkflow . acceptance ` parameter of the workflow . The threshold is passed
to the : py : cla... | if n is None :
n = len ( self . task . branch_map ( ) )
acceptance = self . task . acceptance
return ( acceptance * n ) if acceptance <= 1 else acceptance |
def use ( data , attrs ) :
"""Return the values of the attributes for the given data
: param data : the data
: param attrs : strings
: returns : a list
With a dict : :
> > > band = { ' name ' : ' Metallica ' , ' singer ' : ' James Hetfield ' , ' guitarist ' : ' Kirk Hammet ' }
> > > use ( band , ( ' nam... | if isinstance ( data , dict ) :
if not isiterable ( attrs ) :
attrs = [ attrs ]
coll = map ( data . get , attrs )
else :
coll = map ( lambda x : getattr ( data , x ) , attrs )
return coll |
def __find_handles ( self , model , ** spec ) :
"""find model instances based on given filter ( spec )
The filter is based on available server - calls , so some values might not be available for filtering .
Multiple filter - values is going to do multiple server - calls .
For complex filters in small datasets... | server_calls = [ ]
filter_names = dict ( [ ( f [ 'name' ] , f [ 'method' ] , ) for f in model . get_filters ( ) ] )
if not spec :
server_calls . append ( { 'method' : "%s_GetAll" % model . __name__ , 'args' : [ ] } )
else :
for key , value in spec . items ( ) :
if not key in filter_names :
r... |
def getAnalystName ( self ) :
"""Returns the name of the currently assigned analyst""" | analyst = self . getAnalyst ( )
if not analyst :
return ""
user = api . get_user ( analyst . strip ( ) )
return user and user . getProperty ( "fullname" ) or analyst |
def diff_compute ( self , text1 , text2 , checklines , deadline ) :
"""Find the differences between two texts . Assumes that the texts do not
have any common prefix or suffix .
Args :
text1 : Old string to be diffed .
text2 : New string to be diffed .
checklines : Speedup flag . If false , then don ' t ru... | if not text1 : # Just add some text ( speedup ) .
return [ ( self . DIFF_INSERT , text2 ) ]
if not text2 : # Just delete some text ( speedup ) .
return [ ( self . DIFF_DELETE , text1 ) ]
if len ( text1 ) > len ( text2 ) :
( longtext , shorttext ) = ( text1 , text2 )
else :
( shorttext , longtext ) = ( t... |
def name ( self , name ) :
"""Sets the name of this FileCreateOrUpdateRequest .
File name . Should include type extension always when possible . Must not include slashes .
: param name : The name of this FileCreateOrUpdateRequest .
: type : str""" | if name is None :
raise ValueError ( "Invalid value for `name`, must not be `None`" )
if name is not None and len ( name ) > 128 :
raise ValueError ( "Invalid value for `name`, length must be less than or equal to `128`" )
if name is not None and len ( name ) < 1 :
raise ValueError ( "Invalid value for `nam... |
def _validate_granttype ( self , path , obj , _ ) :
"""make sure either implicit or authorization _ code is defined""" | errs = [ ]
if not obj . implicit and not obj . authorization_code :
errs . append ( 'Either implicit or authorization_code should be defined.' )
return path , obj . __class__ . __name__ , errs |
def unflat_unique_rowid_map ( func , unflat_rowids , ** kwargs ) :
"""performs only one call to the underlying func with unique rowids the func
must be some lookup function
TODO : move this to a better place .
CommandLine :
python - m utool . util _ list - - test - unflat _ unique _ rowid _ map : 0
python... | import utool as ut
# First flatten the list , and remember the original dimensions
flat_rowids , reverse_list = ut . invertible_flatten2 ( unflat_rowids )
# Then make the input unique
flat_rowids_arr = np . array ( flat_rowids )
unique_flat_rowids , inverse_unique = np . unique ( flat_rowids_arr , return_inverse = True... |
def split ( df ) :
"""Returns a tuple with down / up - cast .""" | idx = df . index . argmax ( ) + 1
down = df . iloc [ : idx ]
# Reverse index to orient it as a CTD cast .
up = df . iloc [ idx : ] [ : : - 1 ]
return down , up |
def remove ( self , name ) :
"""Remove all attributes with the given * name * .
Raises : exc : ` ValueError ` if none were found .""" | attrs = [ attr for attr in self . attributes if attr . name == name . strip ( ) ]
if not attrs :
raise ValueError ( name )
for attr in attrs :
self . attributes . remove ( attr ) |
def expand_single_values ( var , scans ) :
"""Expand single valued variable to full scan lengths .""" | if scans . size == 1 :
return var
else :
expanded = np . repeat ( var , scans )
expanded . attrs = var . attrs
expanded . rename ( { expanded . dims [ 0 ] : 'y' } )
return expanded |
def _get_next_time ( lines : [ dict ] , target : str ) -> str : # type : ignore
"""Returns the next FROM target value or empty""" | for line in lines :
if line [ target ] and not _is_tempo_or_prob ( line [ 'type' ] ) :
return line [ target ]
return '' |
def none ( self ) :
"""Returns an empty QuerySet .""" | return EmptyQuerySet ( model = self . model , using = self . _using , connection = self . _connection ) |
def urls ( self , key , value ) :
"""Populate the ` ` url ` ` key .
Also populates the ` ` ids ` ` key through side effects .""" | description = force_single_element ( value . get ( 'y' ) )
url = value . get ( 'u' )
linkedin_match = LINKEDIN_URL . match ( url )
twitter_match = TWITTER_URL . match ( url )
wikipedia_match = WIKIPEDIA_URL . match ( url )
if linkedin_match :
self . setdefault ( 'ids' , [ ] ) . append ( { 'schema' : 'LINKEDIN' , 'v... |
def _to_dict ( self ) :
"""Return a json dictionary representing this model .""" | _dict = { }
if hasattr ( self , 'sentiment' ) and self . sentiment is not None :
_dict [ 'sentiment' ] = self . sentiment
if hasattr ( self , 'emotion' ) and self . emotion is not None :
_dict [ 'emotion' ] = self . emotion
if hasattr ( self , 'limit' ) and self . limit is not None :
_dict [ 'limit' ] = sel... |
def init_instance ( self , key ) :
"""Create an empty instance if it doesn ' t exist .
If the instance already exists , this is a noop .""" | with self . _lock :
if key not in self . _metadata :
self . _metadata [ key ] = { }
self . _metric_ids [ key ] = [ ] |
def _add_filename_details ( full_f ) :
"""Add variant callers and germline information standard CWL filenames .
This is an ugly way of working around not having metadata with calls .""" | out = { "vrn_file" : full_f }
f = os . path . basename ( full_f )
for vc in list ( genotype . get_variantcallers ( ) . keys ( ) ) + [ "ensemble" ] :
if f . find ( "-%s.vcf" % vc ) > 0 :
out [ "variantcaller" ] = vc
if f . find ( "-germline-" ) >= 0 :
out [ "germline" ] = full_f
return out |
def embed ( self , width = 600 , height = 650 ) :
"""Embed a viewer into a Jupyter notebook .""" | from IPython . display import IFrame
return IFrame ( self . url , width , height ) |
def topic_present ( name , subscriptions = None , attributes = None , region = None , key = None , keyid = None , profile = None ) :
'''Ensure the SNS topic exists .
name
Name of the SNS topic .
subscriptions
List of SNS subscriptions .
Each subscription is a dictionary with a protocol and endpoint key : ... | ret = { 'name' : name , 'result' : True , 'comment' : '' , 'changes' : { } }
something_changed = False
current = __salt__ [ 'boto3_sns.describe_topic' ] ( name , region , key , keyid , profile )
if current :
ret [ 'comment' ] = 'AWS SNS topic {0} present.' . format ( name )
TopicArn = current [ 'TopicArn' ]
els... |
def remove_docstrings ( tokens ) :
"""Removes docstrings from * tokens * which is expected to be a list equivalent
of ` tokenize . generate _ tokens ( ) ` ( so we can update in - place ) .""" | prev_tok_type = None
for index , tok in enumerate ( tokens ) :
token_type = tok [ 0 ]
if token_type == tokenize . STRING :
if prev_tok_type == tokenize . INDENT : # Definitely a docstring
tokens [ index ] [ 1 ] = ''
# Remove it
# Remove the leftover indentation and ne... |
def _parse_gene_anatomy ( self , fh , limit ) :
"""Process anat _ entity files with columns :
Ensembl gene ID , gene name , anatomical entity ID ,
anatomical entity name , rank score , XRefs to BTO
: param fh : filehandle
: param limit : int , limit per group
: return : None""" | dataframe = pd . read_csv ( fh , sep = '\t' )
col = self . files [ 'anat_entity' ] [ 'columns' ]
if list ( dataframe ) != col :
LOG . warning ( '\nExpected headers: %s\nRecived headers: %s' , col , list ( dataframe ) )
gene_groups = dataframe . sort_values ( 'rank score' , ascending = False ) . groupby ( 'Ensembl... |
def image ( self , render_mode ) :
"""Return an image generated with a particular render mode .
Parameters
render _ mode : : obj : ` RenderMode `
The type of image we want .
Returns
: obj : ` Image `
The color , depth , or binary image if render _ mode is
COLOR , DEPTH , or SEGMASK respectively .""" | if render_mode == RenderMode . COLOR :
return self . color_im
elif render_mode == RenderMode . DEPTH :
return self . depth_im
elif render_mode == RenderMode . SEGMASK :
return self . binary_im
else :
return None |
def advise ( self , name , f , * a , ** kw ) :
"""Add an advice that will be handled later by the handle method .
Arguments :
name
The name of the advice group
A callable method or function .
The rest of the arguments will be passed as arguments and
keyword arguments to f when it ' s invoked .""" | if name is None :
return
advice = ( f , a , kw )
debug = self . get ( DEBUG )
frame = currentframe ( )
if frame is None :
logger . debug ( 'currentframe() failed to return frame' )
else :
if name in self . _called :
self . __advice_stack_frame_protection ( frame )
if debug :
logger . deb... |
async def _check_latch_data ( self , key , data ) :
"""This is a private utility method .
When a data change message is received this method checks to see if
latching needs to be processed
: param key : encoded pin number
: param data : data change
: returns : None""" | process = False
latching_entry = self . latch_map . get ( key )
if latching_entry [ Constants . LATCH_STATE ] == Constants . LATCH_ARMED : # Has the latching criteria been met
if latching_entry [ Constants . LATCHED_THRESHOLD_TYPE ] == Constants . LATCH_EQ :
if data == latching_entry [ Constants . LATCH_DAT... |
def get_third_party ( self , third_party ) :
"""Return the account for the given third - party . Raise < something > if the third party doesn ' t belong to this bookset .""" | actual_account = third_party . get_account ( )
assert actual_account . get_bookset ( ) == self . get_bookset ( )
return ProjectAccount ( actual_account , project = self , third_party = third_party ) |
def reference ( self , refobj , taskfileinfo ) :
"""Reference the given taskfileinfo into the scene and return the created reference node
The created reference node will be used on : meth : ` RefobjInterface . set _ reference ` to
set the reference on a reftrack node .
Do not call : meth : ` RefobjInterface .... | # work in root namespace
with common . preserve_namespace ( ":" ) :
jbfile = JB_File ( taskfileinfo )
filepath = jbfile . get_fullpath ( )
ns_suggestion = reftrack . get_namespace ( taskfileinfo )
newnodes = cmds . file ( filepath , reference = True , namespace = ns_suggestion , returnNewNodes = True )
... |
def expire ( self , key , timeout ) :
"""Set a timeout on key . After the timeout has expired , the key will
automatically be deleted . A key with an associated timeout is often
said to be volatile in Redis terminology .
The timeout is cleared only when the key is removed using the
: meth : ` ~ tredis . Red... | return self . _execute ( [ b'EXPIRE' , key , ascii ( timeout ) . encode ( 'ascii' ) ] , 1 ) |
def static_fit_result ( fit_result , v_residual = None , v_label = 'Unit-cell volume $(\mathrm{\AA}^3)$' , figsize = ( 5 , 5 ) , height_ratios = ( 3 , 1 ) , ms_data = 8 , p_err = None , v_err = None , pdf_filen = None , title = 'Fit result' ) :
"""plot static compressional curve fitting result
: param fit _ resul... | # basic figure setup
f , ax = plt . subplots ( 2 , 1 , sharex = True , figsize = figsize , gridspec_kw = { 'height_ratios' : height_ratios } )
for ax_i in ax :
ax_i . tick_params ( direction = 'in' )
# read data to plot
v_data = fit_result . userkws [ 'v' ]
p_data = fit_result . data
p_datafit = fit_result . best_f... |
def add_phrase ( self , phrase : List [ int ] ) -> None :
"""Recursively adds a phrase to this trie node .
: param phrase : A list of word IDs to add to this trie node .""" | if len ( phrase ) == 1 :
self . final_ids . add ( phrase [ 0 ] )
else :
next_word = phrase [ 0 ]
if next_word not in self . children :
self . children [ next_word ] = AvoidTrie ( )
self . step ( next_word ) . add_phrase ( phrase [ 1 : ] ) |
def create ( model_config , reinforcer , optimizer , storage , total_frames , batches_per_epoch , callbacks = None , scheduler = None , openai_logging = False ) :
"""Vel factory function""" | from vel . openai . baselines import logger
logger . configure ( dir = model_config . openai_dir ( ) )
return RlTrainCommand ( model_config = model_config , reinforcer = reinforcer , optimizer_factory = optimizer , scheduler_factory = scheduler , storage = storage , callbacks = callbacks , total_frames = int ( float ( ... |
def generate_specifications ( self , count = 1 ) :
"""Returns a mapping of count - > specification""" | out = { }
# mapping of UID index to AR objects { 1 : < AR1 > , 2 : < AR2 > . . . }
copy_from = self . get_copy_from ( )
for arnum in range ( count ) : # get the source object
source = copy_from . get ( arnum )
if source is None :
out [ arnum ] = { }
continue
# get the results range from the ... |
def get_order_book ( self , code ) :
"""获取实时摆盘数据
: param code : 股票代码
: return : ( ret , data )
ret = = RET _ OK 返回字典 , 数据格式如下
ret ! = RET _ OK 返回错误字符串
{ ‘ code ’ : 股票代码
‘ Ask ’ : [ ( ask _ price1 , ask _ volume1 , order _ num ) , ( ask _ price2 , ask _ volume2 , order _ num ) , . . . ]
‘ Bid ’ : [ ( b... | if code is None or is_str ( code ) is False :
error_str = ERROR_STR_PREFIX + "the type of code param is wrong"
return RET_ERROR , error_str
query_processor = self . _get_sync_query_processor ( OrderBookQuery . pack_req , OrderBookQuery . unpack_rsp , )
kargs = { "code" : code , "conn_id" : self . get_sync_conn_... |
def make_application_private ( application_id , sar_client = None ) :
"""Set the application to be private .
: param application _ id : The Amazon Resource Name ( ARN ) of the application
: type application _ id : str
: param sar _ client : The boto3 client used to access SAR
: type sar _ client : boto3 . c... | if not application_id :
raise ValueError ( 'Require application id to make the app private' )
if not sar_client :
sar_client = boto3 . client ( 'serverlessrepo' )
sar_client . put_application_policy ( ApplicationId = application_id , Statements = [ ] ) |
def fetch_data_table ( api_key , show_progress , retries ) :
"""Fetch WIKI Prices data table from Quandl""" | for _ in range ( retries ) :
try :
if show_progress :
log . info ( 'Downloading WIKI metadata.' )
metadata = pd . read_csv ( format_metadata_url ( api_key ) )
# Extract link from metadata and download zip file .
table_url = metadata . loc [ 0 , 'file.link' ]
if sh... |
def revoke ( self , cidr_ip = None , ec2_group = None ) :
"""Revoke access to a CIDR range or EC2 SecurityGroup .
You need to pass in either a CIDR block or
an EC2 SecurityGroup from which to revoke access .
@ type cidr _ ip : string
@ param cidr _ ip : A valid CIDR IP range to revoke
@ type ec2 _ group :... | if isinstance ( ec2_group , SecurityGroup ) :
group_name = ec2_group . name
group_owner_id = ec2_group . owner_id
return self . connection . revoke_dbsecurity_group ( self . name , ec2_security_group_name = group_name , ec2_security_group_owner_id = group_owner_id )
# Revoking by CIDR IP range
return self .... |
def _tag_and_field_maker ( self , event ) :
'''> > > idbf = InfluxDBForwarder ( ' no _ host ' , ' 8086 ' , ' deadpool ' ,
. . . ' chimichanga ' , ' logs ' , ' collection ' )
> > > log = { u ' data ' : { u ' _ ' : { u ' file ' : u ' log . py ' ,
. . . u ' fn ' : u ' start ' ,
. . . u ' ln ' : 8,
. . . u ' ... | data = event . pop ( 'data' )
data = flatten_dict ( { 'data' : data } )
t = dict ( ( k , event [ k ] ) for k in event if k not in self . EXCLUDE_TAGS )
f = dict ( )
for k in data :
v = data [ k ]
if is_number ( v ) or isinstance ( v , MarkValue ) :
f [ k ] = v
else : # if v . startswith ( ' _ ' ) : ... |
def compute_edges ( edges ) :
"""Computes edges as midpoints of the bin centers . The first and
last boundaries are equidistant from the first and last midpoints
respectively .""" | edges = np . asarray ( edges )
if edges . dtype . kind == 'i' :
edges = edges . astype ( 'f' )
midpoints = ( edges [ : - 1 ] + edges [ 1 : ] ) / 2.0
boundaries = ( 2 * edges [ 0 ] - midpoints [ 0 ] , 2 * edges [ - 1 ] - midpoints [ - 1 ] )
return np . concatenate ( [ boundaries [ : 1 ] , midpoints , boundaries [ - ... |
def check_settings ( self , settings ) :
"""Checks the settings info .
: param settings : Dict with settings data
: type settings : dict
: returns : Errors found on the settings data
: rtype : list""" | assert isinstance ( settings , dict )
errors = [ ]
if not isinstance ( settings , dict ) or len ( settings ) == 0 :
errors . append ( 'invalid_syntax' )
else :
if not self . __sp_validation_only :
errors += self . check_idp_settings ( settings )
sp_errors = self . check_sp_settings ( settings )
... |
def isreal ( obj ) :
"""Test if the argument is a real number ( float or integer ) .
: param obj : Object
: type obj : any
: rtype : boolean""" | return ( ( obj is not None ) and ( not isinstance ( obj , bool ) ) and isinstance ( obj , ( int , float ) ) ) |
def _parse ( encoded_data , data_len , pointer = 0 , lengths_only = False ) :
"""Parses a byte string into component parts
: param encoded _ data :
A byte string that contains BER - encoded data
: param data _ len :
The integer length of the encoded data
: param pointer :
The index in the byte string to... | if data_len < pointer + 2 :
raise ValueError ( _INSUFFICIENT_DATA_MESSAGE % ( 2 , data_len - pointer ) )
start = pointer
first_octet = ord ( encoded_data [ pointer ] ) if _PY2 else encoded_data [ pointer ]
pointer += 1
tag = first_octet & 31
# Base 128 length using 8th bit as continuation indicator
if tag == 31 :
... |
def submit_mult_calcs ( calc_suite_specs , exec_options = None ) :
"""Generate and execute all specified computations .
Once the calculations are prepped and submitted for execution , any
calculation that triggers any exception or error is skipped , and the rest
of the calculations proceed unaffected . This p... | if exec_options is None :
exec_options = dict ( )
if exec_options . pop ( 'prompt_verify' , False ) :
print ( _print_suite_summary ( calc_suite_specs ) )
_user_verify ( )
calc_suite = CalcSuite ( calc_suite_specs )
calcs = calc_suite . create_calcs ( )
if not calcs :
raise AospyException ( "The specifie... |
def from_description ( cls , description , attrs ) :
"""Create an object from a dynamo3 response""" | hash_key = None
range_key = None
index_type = description [ "Projection" ] [ "ProjectionType" ]
includes = description [ "Projection" ] . get ( "NonKeyAttributes" )
for data in description [ "KeySchema" ] :
name = data [ "AttributeName" ]
if name not in attrs :
continue
key_type = data [ "KeyType" ]... |
def handle_real_loop_comparison ( self , args , target , upper_bound ) :
"""Handle comparison for real loops .
Add the correct comparison operator if possible .""" | # order is 1 for increasing loop , - 1 for decreasing loop and 0 if it is
# not known at compile time
if len ( args ) <= 2 :
order = 1
elif isinstance ( args [ 2 ] , ast . Num ) :
order = - 1 + 2 * ( int ( args [ 2 ] . n ) > 0 )
elif isinstance ( args [ 1 ] , ast . Num ) and isinstance ( args [ 0 ] , ast . Num ... |
def path ( self , which = None ) :
"""Extend ` ` nailgun . entity _ mixins . Entity . path ` ` .
The format of the returned path depends on the value of ` ` which ` ` :
clone
/ api / roles / : role _ id / clone
Otherwise , call ` ` super ` ` .""" | if which == 'clone' :
return '{0}/{1}' . format ( super ( Role , self ) . path ( which = 'self' ) , which )
return super ( Role , self ) . path ( which ) |
def _write_frame ( self , data ) :
"""Write a frame to the PN532 with the specified data bytearray .""" | assert data is not None and 0 < len ( data ) < 255 , 'Data must be array of 1 to 255 bytes.'
# Build frame to send as :
# - SPI data write ( 0x01)
# - Preamble ( 0x00)
# - Start code ( 0x00 , 0xFF )
# - Command length ( 1 byte )
# - Command length checksum
# - Command bytes
# - Checksum
# - Postamble ( 0x00)
length = l... |
def pil_image ( self , fill_value = None , compute = True ) :
"""Return a PIL image from the current image .
Args :
fill _ value ( int or float ) : Value to use for NaN null values .
See : meth : ` ~ trollimage . xrimage . XRImage . finalize ` for more
info .
compute ( bool ) : Whether to return a fully c... | channels , mode = self . finalize ( fill_value )
res = channels . transpose ( 'y' , 'x' , 'bands' )
img = dask . delayed ( PILImage . fromarray ) ( np . squeeze ( res . data ) , mode )
if compute :
img = img . compute ( )
return img |
def AgregarRomaneo ( self , nro_romaneo , fecha_romaneo , ** kwargs ) :
"Agrego uno o más romaneos a la liq ." | romaneo = dict ( nroRomaneo = nro_romaneo , fechaRomaneo = fecha_romaneo , fardo = [ ] )
self . solicitud [ 'romaneo' ] . append ( romaneo )
return True |
def display_name ( self , display_name ) :
"""Sets the display _ name of this OrderFulfillmentRecipient .
The display name of the fulfillment recipient . If provided , overrides the value from customer profile indicated by customer _ id .
: param display _ name : The display _ name of this OrderFulfillmentRecip... | if display_name is None :
raise ValueError ( "Invalid value for `display_name`, must not be `None`" )
if len ( display_name ) > 255 :
raise ValueError ( "Invalid value for `display_name`, length must be less than `255`" )
self . _display_name = display_name |
def set_many ( self , block , update_dict ) :
"""Update many fields on an XBlock simultaneously .
: param block : the block to update
: type block : : class : ` ~ xblock . core . XBlock `
: param update _ dict : A map of field names to their new values
: type update _ dict : dict""" | for key , value in six . iteritems ( update_dict ) :
self . set ( block , key , value ) |
def get_logger ( name ) :
"""Helper function to get a logger""" | if name in loggers :
return loggers [ name ]
logger = logging . getLogger ( name )
logger . propagate = False
pre1 , suf1 = hash_coloured_escapes ( name ) if supports_color ( ) else ( '' , '' )
pre2 , suf2 = hash_coloured_escapes ( name + 'salt' ) if supports_color ( ) else ( '' , '' )
formatter = logging . Formatt... |
def export ( self , storage_client , overwrite = True ) :
'''a method to export all the records in collection to another platform
: param storage _ client : class object with storage client methods
: return : string with exit message''' | title = '%s.export' % self . __class__ . __name__
# validate storage client
method_list = [ 'save' , 'load' , 'list' , 'export' , 'delete' , 'remove' , '_import' , 'collection_name' ]
for method in method_list :
if not getattr ( storage_client , method , None ) :
from labpack . parsing . grammar import join... |
def delete_file ( self , sass_filename , sass_fileurl ) :
"""Delete a * . css file , but only if it has been generated through a SASS / SCSS file .""" | if self . use_static_root :
destpath = os . path . join ( self . static_root , os . path . splitext ( sass_fileurl ) [ 0 ] + '.css' )
else :
destpath = os . path . splitext ( sass_filename ) [ 0 ] + '.css'
if os . path . isfile ( destpath ) :
os . remove ( destpath )
self . processed_files . append ( sa... |
async def list ( cls , fields : Iterable [ str ] = None ) -> Sequence [ dict ] :
'''Lists the keypair resource policies .
You need an admin privilege for this operation .''' | if fields is None :
fields = ( 'name' , 'created_at' , 'total_resource_slots' , 'max_concurrent_sessions' , 'max_vfolder_count' , 'max_vfolder_size' , 'idle_timeout' , )
q = 'query {' ' keypair_resource_policies {' ' $fields' ' }' '}'
q = q . replace ( '$fields' , ' ' . join ( fields ) )
rqst = Request ( cls .... |
def with_cardinality ( cls , cardinality , converter , pattern = None , listsep = ',' ) :
"""Creates a type converter for the specified cardinality
by using the type converter for T .
: param cardinality : Cardinality to use ( 0 . . 1 , 0 . . * , 1 . . * ) .
: param converter : Type converter ( function ) for... | if cardinality is Cardinality . one :
return converter
# - - NORMAL - CASE
builder_func = getattr ( cls , "with_%s" % cardinality . name )
if cardinality is Cardinality . zero_or_one :
return builder_func ( converter , pattern )
else : # - - MANY CASE : 0 . . * , 1 . . *
return builder_func ( converter , pa... |
def query ( self , ns , selector = '*' ) :
"""Query the label store for labels
: param ns : Label namespace ( ` bind _ pwd ` for example )
: type ns : str
: param selector : Target selector ( ` test ` or ` test . guest ` for example )
: type selector : str""" | q , r = HicaLabelStore . PREFIX + '.' + ns , [ ]
for ( key , value ) in self . items :
if not selector and key == q :
r . append ( ( key , value ) )
if key . startswith ( q ) and key != q :
sub = key [ len ( q ) : ]
m = re . match ( '.' + selector , sub )
if m :
r . a... |
def is_format_selected ( image_format , formats , progs ) :
"""Determine if the image format is selected by command line arguments .""" | intersection = formats & Settings . formats
mode = _is_program_selected ( progs )
result = ( image_format in intersection ) and mode
return result |
async def open_async ( self ) :
"""Open the Sender using the supplied conneciton .
If the handler has previously been redirected , the redirect
context will be used to create a new handler before opening it .
: param connection : The underlying client shared connection .
: type : connection : ~ uamqp . asyn... | self . running = True
if self . redirected :
self . target = self . redirected . address
self . _handler = SendClientAsync ( self . target , auth = self . client . get_auth ( ) , debug = self . client . debug , msg_timeout = self . timeout , error_policy = self . retry_policy , keep_alive_interval = self . keep... |
def hexdump ( src , length = 16 , sep = '.' ) :
"""Hexdump function by sbz and 7h3rAm on Github :
( https : / / gist . github . com / 7h3rAm / 5603718 ) .
: param src : Source , the string to be shown in hexadecimal format
: param length : Number of hex characters to print in one row
: param sep : Unprintab... | filtr = '' . join ( [ ( len ( repr ( chr ( x ) ) ) == 3 ) and chr ( x ) or sep for x in range ( 256 ) ] )
lines = [ ]
for c in xrange ( 0 , len ( src ) , length ) :
chars = src [ c : c + length ]
hexstring = ' ' . join ( [ "%02x" % ord ( x ) for x in chars ] )
if len ( hexstring ) > 24 :
hexstring =... |
def resizeEvent ( self , event ) :
"""Updates the position of the additional buttons when this widget \
resizes .
: param event | < QResizeEvet >""" | super ( XTabWidget , self ) . resizeEvent ( event )
self . adjustButtons ( ) |
def get_usage ( self ) :
"""Get fitness locations and their current usage .""" | resp = requests . get ( FITNESS_URL , timeout = 30 )
resp . raise_for_status ( )
soup = BeautifulSoup ( resp . text , "html5lib" )
eastern = pytz . timezone ( 'US/Eastern' )
output = [ ]
for item in soup . findAll ( "div" , { "class" : "barChart" } ) :
data = [ x . strip ( ) for x in item . get_text ( "\n" ) . stri... |
def validate_deserialize ( rawmsg , requrl = None , check_expiration = True , decode_payload = True , algorithm_name = DEFAULT_ALGO ) :
"""Validate a JWT compact serialization and return the header and
payload if the signature is good .
If check _ expiration is False , the payload will be accepted even if
exp... | assert algorithm_name in ALGORITHM_AVAILABLE
algo = ALGORITHM_AVAILABLE [ algorithm_name ]
segments = rawmsg . split ( '.' )
if len ( segments ) != 3 or not all ( segments ) :
raise InvalidMessage ( 'must contain 3 non-empty segments' )
header64 , payload64 , cryptoseg64 = segments
try :
signature = base64url_d... |
def read ( self , size = None ) :
"""Reads a byte string from the file - like object at the current offset .
The function will read a byte string of the specified size or
all of the remaining data if no size was specified .
Args :
size ( Optional [ int ] ) : number of bytes to read , where None is all
rem... | if not self . _is_open :
raise IOError ( 'Not opened.' )
if self . _current_offset < 0 :
raise IOError ( 'Invalid current offset value less than zero.' )
# The SleuthKit is not POSIX compliant in its read behavior . Therefore
# pytsk3 will raise an IOError if the read offset is beyond the data size .
if self . ... |
def get_conn ( opts , profile ) :
'''Return a client object for accessing consul''' | opts_pillar = opts . get ( 'pillar' , { } )
opts_master = opts_pillar . get ( 'master' , { } )
opts_merged = { }
opts_merged . update ( opts_master )
opts_merged . update ( opts_pillar )
opts_merged . update ( opts )
if profile :
conf = opts_merged . get ( profile , { } )
else :
conf = opts_merged
params = { }
... |
def comment_form ( context , object ) :
"""Usage :
{ % comment _ form obj as comment _ form % }
Will read the ` user ` var out of the contex to know if the form should be
form an auth ' d user or not .""" | user = context . get ( "user" )
form_class = context . get ( "form" , CommentForm )
form = form_class ( obj = object , user = user )
return form |
def lunch ( rest ) :
"Pick where to go to lunch" | rs = rest . strip ( )
if not rs :
return "Give me an area and I'll pick a place: (%s)" % ( ', ' . join ( list ( pmxbot . config . lunch_choices ) ) )
if rs not in pmxbot . config . lunch_choices :
return "I didn't recognize that area; here's what i have: (%s)" % ( ', ' . join ( list ( pmxbot . config . lunch_ch... |
def add_parens ( line , maxline , indent , statements = statements , count = count ) :
"""Attempt to add parentheses around the line
in order to make it splittable .""" | if line [ 0 ] in statements :
index = 1
if not line [ 0 ] . endswith ( ' ' ) :
index = 2
assert line [ 1 ] == ' '
line . insert ( index , '(' )
if line [ - 1 ] == ':' :
line . insert ( - 1 , ')' )
else :
line . append ( ')' )
# That was the easy stuff . Now for assign... |
def gunzip ( input_gzip_file , block_size = 1024 ) :
"""Gunzips the input file to the same directory
: param input _ gzip _ file : File to be gunzipped
: return : path to the gunzipped file
: rtype : str""" | assert os . path . splitext ( input_gzip_file ) [ 1 ] == '.gz'
assert is_gzipfile ( input_gzip_file )
with gzip . open ( input_gzip_file ) as infile :
with open ( os . path . splitext ( input_gzip_file ) [ 0 ] , 'w' ) as outfile :
while True :
block = infile . read ( block_size )
if ... |
def restore ( self , state ) :
"""Restore the contents of this virtual stream walker .
Args :
state ( dict ) : The previously serialized state .
Raises :
ArgumentError : If the serialized state does not have
a matching selector .""" | selector = DataStreamSelector . FromString ( state . get ( u'selector' ) )
if self . selector != selector :
raise ArgumentError ( "Attempted to restore an InvalidStreamWalker with a different selector" , selector = self . selector , serialized_data = state )
if state . get ( u'type' ) != u'invalid' :
raise Argu... |
def _cursor_pb ( cursor_pair ) :
"""Convert a cursor pair to a protobuf .
If ` ` cursor _ pair ` ` is : data : ` None ` , just returns : data : ` None ` .
Args :
cursor _ pair ( Optional [ Tuple [ list , bool ] ] ) : Two - tuple of
* a list of field values .
* a ` ` before ` ` flag
Returns :
Optional ... | if cursor_pair is not None :
data , before = cursor_pair
value_pbs = [ _helpers . encode_value ( value ) for value in data ]
return query_pb2 . Cursor ( values = value_pbs , before = before ) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.