signature stringlengths 29 44.1k | implementation stringlengths 0 85.2k |
|---|---|
def no_proxy ( self , value ) :
"""Sets noproxy setting .
: Args :
- value : The noproxy value .""" | self . _verify_proxy_type_compatibility ( ProxyType . MANUAL )
self . proxyType = ProxyType . MANUAL
self . noProxy = value |
def ipv6_range_to_list ( start_packed , end_packed ) :
"""Return a list of IPv6 entries from start _ packed to end _ packed .""" | new_list = list ( )
start = int ( binascii . hexlify ( start_packed ) , 16 )
end = int ( binascii . hexlify ( end_packed ) , 16 )
for value in range ( start , end + 1 ) :
high = value >> 64
low = value & ( ( 1 << 64 ) - 1 )
new_ip = inet_ntop ( socket . AF_INET6 , struct . pack ( '!2Q' , high , low ) )
... |
def ExpandWindowsEnvironmentVariables ( data_string , knowledge_base ) :
r"""Take a string and expand any windows environment variables .
Args :
data _ string : A string , e . g . " % SystemRoot % \ \ LogFiles "
knowledge _ base : A knowledgebase object .
Returns :
A string with available environment vari... | win_environ_regex = re . compile ( r"%([^%]+?)%" )
components = [ ]
offset = 0
for match in win_environ_regex . finditer ( data_string ) :
components . append ( data_string [ offset : match . start ( ) ] )
# KB environment variables are prefixed with environ _ .
kb_value = getattr ( knowledge_base , "enviro... |
def _breakRemNewlines ( tag ) :
"""non - recursively break spaces and remove newlines in the tag""" | for i , c in enumerate ( tag . contents ) :
if type ( c ) != bs4 . element . NavigableString :
continue
c . replace_with ( re . sub ( r' {2,}' , ' ' , c ) . replace ( '\n' , '' ) ) |
def append_pre_auth_tx_signer ( self , pre_auth_tx , signer_weight , source = None ) :
"""Add a PreAuthTx signer to an account .
Add a PreAuthTx signer to an account via a : class : ` SetOptions
< stellar _ base . operation . SetOptions ` operation . This is a helper
function for : meth : ` append _ set _ opt... | return self . append_set_options_op ( signer_address = pre_auth_tx , signer_type = 'preAuthTx' , signer_weight = signer_weight , source = source ) |
def _set_env ( self , env ) :
"""Set environment for each callback in callbackList""" | for callback in self . callbacks :
if callable ( getattr ( callback , '_set_env' , None ) ) :
callback . _set_env ( env ) |
def p_param_def_type ( p ) :
"""param _ def : ID typedef""" | if p [ 2 ] is not None :
api . check . check_type_is_explicit ( p . lineno ( 1 ) , p [ 1 ] , p [ 2 ] )
p [ 0 ] = make_param_decl ( p [ 1 ] , p . lineno ( 1 ) , p [ 2 ] ) |
def encode ( self , formatter = None ) :
"""Return a representation of the cart as a JSON - response .
Parameters
formatter : func , optional
A function that accepts the cart representation and returns
its formatted version .
Returns
django . http . JsonResponse
Examples
Assume that items with prima... | items = { }
# The prices are converted to strings , because they may have a
# type that can ' t be serialized to JSON ( e . g . Decimal ) .
for item in self . items . values ( ) :
pk = str ( item . obj . pk )
items [ pk ] = { 'price' : str ( item . price ) , 'quantity' : item . quantity , 'total' : item . total... |
def _process_docstrings ( self , doc , members , add = True ) :
"""Adds the docstrings from the list of DocElements to their
respective members .
Returns true if the doc element belonged to a member .""" | if ( ( doc . doctype == "member" or doc . doctype == "local" ) and doc . pointsto is not None and doc . pointsto in members ) :
if add :
members [ doc . pointsto ] . docstring . append ( doc )
else :
members [ doc . pointsto ] . overwrite_docs ( doc )
return True
else :
return False |
def readinto ( self , b ) :
"""Read bytes into a pre - allocated , writable bytes - like object b ,
and return the number of bytes read .
Args :
b ( bytes - like object ) : buffer .
Returns :
int : number of bytes read""" | if not self . _readable :
raise UnsupportedOperation ( 'read' )
# Get and update stream positions
size = len ( b )
with self . _seek_lock :
start = self . _seek
end = start + size
self . _seek = end
# Read data range
with handle_os_exceptions ( ) :
read_data = self . _read_range ( start , end )
# Co... |
def repo_values ( self ) :
"""Set the appropriate repo dir and get the branches and commits of it""" | branches = [ ]
commits = { }
m_helper = Tools ( )
status = m_helper . repo_branches ( self . parentApp . repo_value [ 'repo' ] )
# branches and commits must both be retrieved successfully
if status [ 0 ] :
branches = status [ 1 ]
status = m_helper . repo_commits ( self . parentApp . repo_value [ 'repo' ] )
... |
def remove_negativescores_nodes ( self ) :
"""if there are elements inside our top node
that have a negative gravity score ,
let ' s give em the boot""" | gravity_items = self . parser . css_select ( self . top_node , "*[gravityScore]" )
for item in gravity_items :
score = self . parser . getAttribute ( item , 'gravityScore' )
score = int ( score , 0 )
if score < 1 :
item . getparent ( ) . remove ( item ) |
def refresh ( cls ) :
"""This gets called by the refresh function ( see the top level
_ _ init _ _ ) .""" | # clear the old values in _ flag _ map
try :
del cls . _flag_map [ "t" ]
except KeyError :
pass
try :
del cls . _flag_map [ "-" ]
except KeyError :
pass
# set the value given the git version
if Git ( ) . version_info [ : 2 ] >= ( 2 , 10 ) :
cls . _flag_map [ "t" ] = cls . TAG_UPDATE
else :
cls .... |
def run ( ) :
"""Module level test .""" | logging . basicConfig ( level = logging . DEBUG )
load_config . ConfigLoader ( ) . load ( )
config . debug = True
print ( repr ( config . engine . item ( sys . argv [ 1 ] ) ) ) |
def snr ( * args , ** kwargs ) :
"""Compute the SNR of binaries .
snr is a function that takes binary parameters and sensitivity curves as inputs ,
and returns snr for chosen phases .
Warning : All binary parameters must be either scalar , len - 1 arrays ,
or arrays of the same length . All of these can be ... | squeeze = False
max_length = 0
for arg in args :
try :
length = len ( arg )
if length > max_length :
max_length = length
except TypeError :
pass
if max_length == 0 :
squeeze = True
kwargs [ 'length' ] = max_length
snr_main = SNR ( ** kwargs )
if squeeze :
snr_out = sn... |
def process ( fn , bound_names ) :
"""process automatic context variable capturing .
return the transformed function and its ast .""" | if isinstance ( fn , _AutoContext ) :
fn = fn . fn
# noinspection PyArgumentList , PyArgumentList
if isinstance ( fn , _FnCodeStr ) :
if bound_names :
assign_code_str = '{syms} = map(state.ctx.get, {names})' . format ( syms = ', ' . join ( bound_names ) + ',' , names = repr ( bound_names ) )
else :
... |
def declare_label ( self , id_ , lineno ) :
"""Declares a label ( line numbers are also labels ) .
Unlike variables , labels are always global .""" | # TODO : consider to make labels private
id1 = id_
id_ = str ( id_ )
if not self . check_is_undeclared ( id_ , lineno , 'label' ) :
entry = self . get_entry ( id_ )
syntax_error ( lineno , "Label '%s' already used at %s:%i" % ( id_ , entry . filename , entry . lineno ) )
return entry
entry = self . get_entr... |
def __unionfs_set_up ( ro_dir , rw_dir , mount_dir ) :
"""Setup a unionfs via unionfs - fuse .
Args :
ro _ base : base _ directory of the project
rw _ image : virtual image of actual file system
mountpoint : location where ro _ base and rw _ image merge""" | mount_dir . mkdir ( )
rw_dir . mkdir ( )
if not ro_dir . exists ( ) :
LOG . error ( "Base dir does not exist: '%s'" , ro_dir )
raise ValueError ( "Base directory does not exist" )
from benchbuild . utils . cmd import unionfs as unionfs_cmd
LOG . debug ( "Mounting UnionFS on %s with RO:%s RW:%s" , mount_dir , ro... |
def run ( self ) :
"""The run loop . Returns self . destroy ( )""" | while self . running :
self . update ( )
self . render ( )
self . update_screen ( )
return self . destroy ( ) |
def update ( self , ip_address = values . unset , friendly_name = values . unset , cidr_prefix_length = values . unset ) :
"""Update the IpAddressInstance
: param unicode ip _ address : An IP address in dotted decimal notation from which you want to accept traffic . Any SIP requests from this IP address will be a... | data = values . of ( { 'IpAddress' : ip_address , 'FriendlyName' : friendly_name , 'CidrPrefixLength' : cidr_prefix_length , } )
payload = self . _version . update ( 'POST' , self . _uri , data = data , )
return IpAddressInstance ( self . _version , payload , account_sid = self . _solution [ 'account_sid' ] , ip_access... |
def auth_expired ( self ) :
"""Compare the expiration value of our current token including a CLOCK _ SKEW .
: return : true if the token has expired""" | if self . _auth and self . _expires :
now_with_skew = time . time ( ) + AUTH_TOKEN_CLOCK_SKEW_MAX
return now_with_skew > self . _expires
return True |
def load_wineind ( as_series = False ) :
"""Australian total wine sales by wine makers in bottles < = 1 litre .
This time - series records wine sales by Australian wine makers between
Jan 1980 - - Aug 1994 . This dataset is found in the R ` ` forecast ` ` package .
Parameters
as _ series : bool , optional (... | rslt = np . array ( [ 15136 , 16733 , 20016 , 17708 , 18019 , 19227 , 22893 , 23739 , 21133 , 22591 , 26786 , 29740 , 15028 , 17977 , 20008 , 21354 , 19498 , 22125 , 25817 , 28779 , 20960 , 22254 , 27392 , 29945 , 16933 , 17892 , 20533 , 23569 , 22417 , 22084 , 26580 , 27454 , 24081 , 23451 , 28991 , 31386 , 16896 , 20... |
def init_publisher ( app ) :
"""Calling this with your flask app as argument is required for the
publisher decorator to work .""" | @ app . context_processor
def inject_links ( ) :
return { 'websub_self_url' : stack . top . websub_self_url , 'websub_hub_url' : stack . top . websub_hub_url , 'websub_self_link' : stack . top . websub_self_link , 'websub_hub_link' : stack . top . websub_hub_link , } |
def path_to_text ( self , path ) :
'''Transform local PDF file to string .
Args :
path : path to PDF file .
Returns :
string .''' | rsrcmgr = PDFResourceManager ( )
retstr = StringIO ( )
codec = 'utf-8'
laparams = LAParams ( )
device = TextConverter ( rsrcmgr , retstr , codec = codec , laparams = laparams )
fp = open ( path , 'rb' )
interpreter = PDFPageInterpreter ( rsrcmgr , device )
password = ""
maxpages = 0
caching = True
pagenos = set ( )
pag... |
def run_tree ( tree , g , l ) :
"""Main entry point for remote ( ) .""" | runner = Ayrton ( g = g , l = l )
return runner . run_tree ( tree , 'unknown_tree' ) |
def import_participant_element ( diagram_graph , participants_dictionary , participant_element ) :
"""Adds ' participant ' element to the collaboration dictionary .
: param diagram _ graph : NetworkX graph representing a BPMN process diagram ,
: param participants _ dictionary : dictionary with participant elem... | participant_id = participant_element . getAttribute ( consts . Consts . id )
name = participant_element . getAttribute ( consts . Consts . name )
process_ref = participant_element . getAttribute ( consts . Consts . process_ref )
if participant_element . getAttribute ( consts . Consts . process_ref ) == '' :
diagram... |
def _subfield_conflicts ( conflicts , # type : List [ Tuple [ Tuple [ str , str ] , List [ Node ] , List [ Node ] ] ]
response_name , # type : str
ast1 , # type : Node
ast2 , # type : Node
) : # type : ( . . . ) - > Optional [ Tuple [ Tuple [ str , str ] , List [ Node ] , List [ Node ] ] ]
"""Given a series of Conf... | if conflicts :
return ( # type : ignore
( response_name , [ conflict [ 0 ] for conflict in conflicts ] ) , tuple ( itertools . chain ( [ ast1 ] , * [ conflict [ 1 ] for conflict in conflicts ] ) ) , tuple ( itertools . chain ( [ ast2 ] , * [ conflict [ 2 ] for conflict in conflicts ] ) ) , )
return None |
def name_variants ( self ) :
"""List of named tuples containing variants of the author name with
number of documents published with that variant .""" | fields = 'indexed_name initials surname given_name doc_count'
variant = namedtuple ( 'Variant' , fields )
path = [ 'author-profile' , 'name-variant' ]
out = [ variant ( indexed_name = var [ 'indexed-name' ] , surname = var [ 'surname' ] , doc_count = var . get ( '@doc-count' ) , initials = var [ 'initials' ] , given_na... |
def label ( self ) -> str :
"""A latex formatted label representing constant expression and united value .""" | label = self . expression . replace ( "_" , "\\;" )
if self . units_kind :
symbol = wt_units . get_symbol ( self . units )
for v in self . variables :
vl = "%s_{%s}" % ( symbol , v . label )
vl = vl . replace ( "_{}" , "" )
# label can be empty , no empty subscripts
label = label... |
def _get_module_folders ( self , temp_repo ) :
"""Get a list of module paths contained in a temp directory .
: param string temp _ repo : the folder containing the modules .""" | paths = ( os . path . join ( temp_repo , path ) for path in os . listdir ( temp_repo ) if self . _is_module_included ( path ) )
return ( path for path in paths if os . path . isdir ( path ) ) |
def convert_to_international_phonetic_alphabet ( self , arpabet ) :
'''转换成国际音标
: param arpabet :
: return :''' | word = self . _convert_to_word ( arpabet = arpabet )
if not word :
return None
return word . translate_to_international_phonetic_alphabet ( ) |
async def deserialize ( self , data : dict , silent = True ) :
'''Deserializes a Python ` ` dict ` ` into the model by assigning values to their respective fields .
Ignores data attributes that do not match one of the Model ' s fields .
Ignores data attributes who ' s matching fields are declared with the ` ` r... | self . import_data ( self . _deserialize ( data ) )
self . validate ( ) |
def write_membership ( filename , config , srcfile , section = None ) :
"""Top level interface to write the membership from a config and source model .""" | source = Source ( )
source . load ( srcfile , section = section )
loglike = createLoglike ( config , source )
loglike . write_membership ( filename ) |
def _endProductionCrewNode ( self , name , content ) :
"""Process the end of a node under xtvd / productionCrew""" | if name == 'role' :
self . _role = content
elif name == 'givenname' :
self . _givenname = content
elif name == 'surname' :
self . _surname = content
elif name == 'member' :
if not self . _error :
if self . _givenname :
name = '%s %s' % ( self . _givenname , self . _surname )
... |
def gen_source_models ( self , gsim_lt ) :
"""Yield empty LtSourceModel instances ( one per effective realization )""" | samples_by_lt_path = self . samples_by_lt_path ( )
for i , rlz in enumerate ( get_effective_rlzs ( self ) ) :
smpath = rlz . lt_path
num_samples = samples_by_lt_path [ smpath ]
num_gsim_paths = ( num_samples if self . num_samples else gsim_lt . get_num_paths ( ) )
yield LtSourceModel ( rlz . value , rlz... |
def init ( version = None , command = None , options = None ) :
"""Initializes the gcc toolset for the given version . If necessary , command may
be used to specify where the compiler is located . The parameter ' options ' is a
space - delimited list of options , each one specified as
< option - name > option... | options = to_seq ( options )
command = to_seq ( command )
# Information about the gcc command . . .
# The command .
command = to_seq ( common . get_invocation_command ( 'gcc' , 'g++' , command ) )
# The root directory of the tool install .
root = feature . get_values ( '<root>' , options )
root = root [ 0 ] if root els... |
def nscannedObjects ( self ) :
"""Extract counters if available ( lazy ) .
Looks for nscannedObjects or docsExamined .""" | if not self . _counters_calculated :
self . _counters_calculated = True
self . _extract_counters ( )
return self . _nscannedObjects |
def add_child ( self , parent_slug = None , title = "" , level = "" , start_date = None , end_date = None , date_expression = None , notes = [ ] , ) :
"""Adds a new resource component parented within ` parent ` .
: param str parent _ slug : The parent ' s slug .
: param str title : A title for the record .
: ... | new_object = { "title" : title , "level_of_description" : level }
if parent_slug is not None :
new_object [ "parent_slug" ] = parent_slug
# Optionally add date specification
new_date = { }
if start_date is not None :
new_date [ "start_date" ] = start_date
if end_date is not None :
new_date [ "end_date" ] = ... |
def stop ( name , kill = False , path = None , use_vt = None ) :
'''Stop the named container
path
path to the container parent directory
default : / var / lib / lxc ( system )
. . versionadded : : 2015.8.0
kill : False
Do not wait for the container to stop , kill all tasks in the container .
Older LXC... | _ensure_exists ( name , path = path )
orig_state = state ( name , path = path )
if orig_state == 'frozen' and not kill : # Gracefully stopping a frozen container is slower than unfreezing and
# then stopping it ( at least in my testing ) , so if we ' re not
# force - stopping the container , unfreeze it first .
unf... |
def fuller_scaling ( target , DABo , To , Po , temperature = 'pore.temperature' , pressure = 'pore.pressure' ) :
r"""Uses Fuller model to adjust a diffusion coefficient for gases from
reference conditions to conditions of interest
Parameters
target : OpenPNM Object
The object for which these values are bein... | Ti = target [ temperature ]
Pi = target [ pressure ]
value = DABo * ( Ti / To ) ** 1.75 * ( Po / Pi )
return value |
def config_logger ( name = 'andes' , log_file = 'andes.log' , log_path = '' , stream = True , stream_level = logging . INFO ) :
"""Configure a logger for the andes package with options for a ` FileHandler `
and a ` StreamHandler ` . This function is called at the beginning of
` ` andes . main . main ( ) ` ` .
... | logger = logging . getLogger ( name )
logger . setLevel ( logging . DEBUG )
# file handler for level DEBUG and up
if log_file is not None :
log_full_path = os . path . join ( log_path , log_file )
fh_formatter = logging . Formatter ( '%(asctime)s - %(name)s - %(levelname)s - %(message)s' )
fh = logging . Fi... |
def GetOptionString ( self , section , option ) :
"""Get the value of an option in the config file .
Args :
section : string , the section of the config file to check .
option : string , the option to retrieve the value of .
Returns :
string , the value of the option or None if the option doesn ' t exist ... | if self . config . has_option ( section , option ) :
return self . config . get ( section , option )
else :
return None |
def save ( self , vpk_output_path ) :
"""Saves the VPK at the given path""" | with fopen ( vpk_output_path , 'wb' ) as f : # write VPK1 header
f . write ( struct . pack ( "3I" , self . signature , self . version , self . tree_length ) )
self . header_length = f . tell ( )
data_offset = self . header_length + self . tree_length
# write file tree
for ext in self . tree :
... |
def save_to_eitdir ( self , directory ) :
"""Save the eit data into a eit / sip directory structure
Parameters
directory : string | path
output directory""" | if os . path . isdir ( directory ) :
raise Exception ( 'output directory already exists' )
os . makedirs ( directory )
np . savetxt ( directory + os . sep + 'frequencies.dat' , self . frequencies )
invmod_dir = directory + os . sep + 'invmod'
os . makedirs ( invmod_dir )
for nr , key in enumerate ( sorted ( self . ... |
def parse ( self , argument ) :
"""See base class .""" | if isinstance ( argument , list ) :
return argument
elif not argument :
return [ ]
else :
return [ s . strip ( ) for s in argument . split ( self . _token ) ] |
def time ( self , t = None ) :
"""Set / get actor ' s absolute time .""" | if t is None :
return self . _time
self . _time = t
return self |
def autodecode ( self , a_bytes ) :
"""Automatically detect encoding , and decode bytes .""" | try : # 如果装了chardet
analysis = chardet . detect ( a_bytes )
if analysis [ "confidence" ] >= 0.75 : # 如果可信
return ( self . decode ( a_bytes , analysis [ "encoding" ] ) [ 0 ] , analysis [ "encoding" ] )
else : # 如果不可信 , 打印异常
raise Exception ( "Failed to detect encoding. (%s, %s)" % ( analysis ... |
def symmetry_average ( image , symmetry ) :
"""symmetry averaged image
: param image :
: param symmetry :
: return :""" | img_sym = np . zeros_like ( image )
angle = 360. / symmetry
for i in range ( symmetry ) :
img_sym += rotateImage ( image , angle * i )
img_sym /= symmetry
return img_sym |
def getVariable ( self , name ) :
"""Get the variable with the corresponding name .
Args :
name : Name of the variable to be found .
Raises :
TypeError : if the specified variable does not exist .""" | return lock_and_call ( lambda : Variable ( self . _impl . getVariable ( name ) ) , self . _lock ) |
def losc_frame_json ( ifo , start_time , end_time ) :
"""Get the information about the public data files in a duration of time
Parameters
ifo : str
The name of the IFO to find the information about .
start _ time : int
The gps time in GPS seconds
end _ time : int
The end time in GPS seconds
Returns ... | import urllib , json
run = get_run ( start_time )
run2 = get_run ( end_time )
if run != run2 :
raise ValueError ( 'Spanning multiple runs is not currently supported.' 'You have requested data that uses ' 'both %s and %s' % ( run , run2 ) )
url = _losc_url % ( run , ifo , int ( start_time ) , int ( end_time ) )
try ... |
def firmware_version ( self ) :
"""Provides information on the connected Pebble , including its firmware version , language , capabilities , etc .
. . note :
This is a blocking call if : meth : ` fetch _ watch _ info ` has not yet been called , which could lead to deadlock
if called in an endpoint callback . ... | version = self . watch_info . running . version_tag [ 1 : ]
parts = version . split ( '-' , 1 )
points = [ int ( x ) for x in parts [ 0 ] . split ( '.' ) ]
while len ( points ) < 3 :
points . append ( 0 )
if len ( parts ) == 2 :
suffix = parts [ 1 ]
else :
suffix = ''
return FirmwareVersion ( * ( points + [... |
def nom_diam_pipe ( self ) :
"""The nominal diameter of the LFOM pipe""" | ID = pc . diam_circle ( self . area_pipe_min )
return pipe . ND_SDR_available ( ID , self . sdr ) |
def handle_aladin_event ( self , _ , content , buffers ) :
"""used to collect json objects that are sent by the js - side of the application by using the send ( ) method""" | if content . get ( 'event' , '' ) . startswith ( 'callback' ) :
if content . get ( 'type' ) == 'objectHovered' :
result = self . listener_callback_source_hover ( content . get ( 'data' ) )
elif content . get ( 'type' ) == 'objectClicked' :
result = self . listener_callback_source_click ( content... |
def connected ( self ) :
"""A property that returns the : class : ` list ` of : class : ` User ` that are currently in this call .""" | ret = [ u for u in self . channel . recipients if self . voice_state_for ( u ) is not None ]
me = self . channel . me
if self . voice_state_for ( me ) is not None :
ret . append ( me )
return ret |
def list ( self , subid , params = None ) :
'''/ v1 / server / list _ ipv4
GET - account
List the IPv4 information of a virtual machine . IP information is only
available for virtual machines in the " active " state .
Link : https : / / www . vultr . com / api / # server _ list _ ipv4''' | params = update_params ( params , { 'SUBID' : subid } )
return self . request ( '/v1/server/list_ipv4' , params , 'GET' ) |
def do_serialize ( self , line ) :
"""Serialize an entity into an RDF flavour""" | opts = self . SERIALIZE_OPTS
if not self . current :
self . _help_noontology ( )
return
line = line . split ( )
g = self . current [ 'graph' ]
if not line :
line = [ 'turtle' ]
if line [ 0 ] not in opts :
self . help_serialize ( )
return
elif self . currentEntity :
self . currentEntity [ 'object... |
def emitMany ( * args , ** kwargs ) :
"""A more efficient way to emit a number of tuples at once .""" | global MODE
if MODE == Bolt :
emitManyBolt ( * args , ** kwargs )
elif MODE == Spout :
emitManySpout ( * args , ** kwargs ) |
def _get_first_all_link_record ( self ) :
"""Request first ALL - Link record .""" | _LOGGER . debug ( "Starting: _get_first_all_link_record" )
_LOGGER . info ( 'Requesting ALL-Link Records' )
if self . aldb . status == ALDBStatus . LOADED :
self . _next_all_link_rec_nak_retries = 3
self . _handle_get_next_all_link_record_nak ( None )
return
self . aldb . clear ( )
self . _next_all_link_rec... |
def migrate_v0_rules ( self ) :
'''Remove any v0 ( i . e . pre - 010 ) rules from storage and replace them with v1 rules .
Notes :
v0 had two differences user was a username . Replaced with iden of user as ' iden ' field .
Also ' iden ' was storage as binary . Now it is stored as hex string .''' | for iden , valu in self . core . slab . scanByFull ( db = self . trigdb ) :
ruledict = s_msgpack . un ( valu )
ver = ruledict . get ( 'ver' )
if ver != 0 :
continue
user = ruledict . pop ( 'user' )
if user is None :
logger . warning ( 'Username missing in stored trigger rule %r' , id... |
def available ( software = True , drivers = True , summary = False , skip_installed = True , skip_hidden = True , skip_mandatory = False , skip_reboot = False , categories = None , severities = None , ) :
'''. . versionadded : : 2017.7.0
List updates that match the passed criteria . This allows for more filter
... | # Create a Windows Update Agent instance
wua = salt . utils . win_update . WindowsUpdateAgent ( )
# Look for available
updates = wua . available ( skip_hidden = skip_hidden , skip_installed = skip_installed , skip_mandatory = skip_mandatory , skip_reboot = skip_reboot , software = software , drivers = drivers , categor... |
def create_issue ( self , request , group , form_data , ** kwargs ) :
"""Creates the issue on the remote service and returns an issue ID .""" | instance = self . get_option ( 'instance' , group . project )
project = ( form_data . get ( 'project' ) or self . get_option ( 'default_project' , group . project ) )
client = self . get_client ( request . user )
title = form_data [ 'title' ]
description = form_data [ 'description' ]
link = absolute_uri ( group . get_a... |
def _ParseLogFileOptions ( self , options ) :
"""Parses the log file options .
Args :
options ( argparse . Namespace ) : command line arguments .""" | self . _log_file = self . ParseStringOption ( options , 'log_file' )
if not self . _log_file :
local_date_time = datetime . datetime . now ( )
self . _log_file = ( '{0:s}-{1:04d}{2:02d}{3:02d}T{4:02d}{5:02d}{6:02d}.log.gz' ) . format ( self . NAME , local_date_time . year , local_date_time . month , local_date_... |
def _at ( self , idx ) :
"""Returns a view of the array sliced at ` idx ` in the first dim .
This is called through ` ` x [ idx ] ` ` .
Parameters
idx : int
index for slicing the ` NDArray ` in the first dim .
Returns
NDArray
` NDArray ` sharing the memory with the current one sliced at ` idx ` in the... | handle = NDArrayHandle ( )
if idx < 0 :
length = self . shape [ 0 ]
idx += length
if idx < 0 :
raise IndexError ( 'index %d is out of bounds for axis 0 with size %d' % ( idx - length , length ) )
check_call ( _LIB . MXNDArrayAt ( self . handle , mx_uint ( idx ) , ctypes . byref ( handle ) ) )
return... |
def cut_setting ( self , cut ) :
'''Set cut setting for printer .
Args :
cut : The type of cut setting we want . Choices are ' full ' , ' half ' , ' chain ' , and ' special ' .
Returns :
None
Raises :
RuntimeError : Invalid cut type .''' | cut_settings = { 'full' : 0b00000001 , 'half' : 0b00000010 , 'chain' : 0b00000100 , 'special' : 0b00001000 }
if cut in cut_settings :
self . send ( chr ( 27 ) + 'iC' + chr ( cut_settings [ cut ] ) )
else :
raise RuntimeError ( 'Invalid cut type.' ) |
def set_params ( self , ** params ) :
"""Set parameters on this object
Safe setter method - attributes should not be modified directly as some
changes are not valid .
Valid parameters :
- n _ jobs
- random _ state
- verbose
Invalid parameters : ( these would require modifying the kernel matrix )
- k... | # mnn specific arguments
if 'beta' in params and params [ 'beta' ] != self . beta :
raise ValueError ( "Cannot update beta. Please create a new graph" )
# knn arguments
knn_kernel_args = [ 'knn' , 'decay' , 'distance' , 'thresh' , 'bandwidth' ]
knn_other_args = [ 'n_jobs' , 'random_state' , 'verbose' ]
for arg in k... |
def _draw_title ( self ) :
"""Draw title onto the figure""" | # This is very laboured . Should be changed when MPL
# finally has a constraint based layout manager .
figure = self . figure
title = self . labels . get ( 'title' , '' )
rcParams = self . theme . rcParams
get_property = self . theme . themeables . property
# Pick suitable values in inches and convert them to
# transFi... |
def from_json ( cls , json ) :
"""Deserialize from json .
Args :
json : a dict of json compatible fields .
Returns :
a KeyRanges object .
Raises :
ValueError : if the json is invalid .""" | if json [ "name" ] in _KEYRANGES_CLASSES :
return _KEYRANGES_CLASSES [ json [ "name" ] ] . from_json ( json )
raise ValueError ( "Invalid json %s" , json ) |
def free ( self ) :
"""Free the parameters with the coordinates ( either ra , dec or l , b depending on how the class
has been instanced )""" | if self . _coord_type == 'equatorial' :
self . ra . fix = False
self . dec . fix = False
else :
self . l . fix = False
self . b . fix = False |
def _validate_buckets ( categorical , k , scheme ) :
"""This method validates that the hue parameter is correctly specified . Valid inputs are :
1 . Both k and scheme are specified . In that case the user wants us to handle binning the data into k buckets
ourselves , using the stated algorithm . We issue a warn... | if categorical and ( k != 5 or scheme ) :
raise ValueError ( "Invalid input: categorical cannot be specified as True simultaneously with scheme or k " "parameters" )
if k > 10 :
warnings . warn ( "Generating a choropleth using a categorical column with over 10 individual categories. " "This is not recommended!"... |
def engine_schema ( engine , out_names = None , filename = None , format = "pdf" ) :
"""Build a graphviz schema of a reliure : class : ` . Engine ` .
It depends on ` graphviz < https : / / pypi . python . org / pypi / graphviz > ` _ .
: param engine : reliure engine to graph
: type engine : : class : ` . Engi... | import graphviz as pgv
# engine . validate ( )
dg = pgv . Digraph ( format = format )
input_node_name = "in"
output_node_name = "out"
dg . node ( input_node_name , label = input_node_name , shape = "ellipse" )
block_source = { }
# witch block is the source for witch data
for e_in_name in engine . in_name :
block_so... |
def strip_prompt ( self , a_string ) :
"""Strip the trailing router prompt from the output .""" | expect_string = r"^(OK|ERROR|Command not recognized\.)$"
response_list = a_string . split ( self . RESPONSE_RETURN )
last_line = response_list [ - 1 ]
if re . search ( expect_string , last_line ) :
return self . RESPONSE_RETURN . join ( response_list [ : - 1 ] )
else :
return a_string |
def _get_merge_rules ( properties , path = None ) :
"""Yields merge rules as key - value pairs , in which the first element is a JSON path as a tuple , and the second element
is a list of merge properties whose values are ` true ` .""" | if path is None :
path = ( )
for key , value in properties . items ( ) :
new_path = path + ( key , )
types = _get_types ( value )
# ` omitWhenMerged ` supersedes all other rules .
# See http : / / standard . open - contracting . org / 1.1 - dev / en / schema / merging / # omit - when - merged
if... |
def cleanBlockQuotedText ( text , joiner = b' ' ) :
"""This is an internal utility which takes triple -
quoted text form within the document and returns
( hopefully ) the paragraph the user intended originally .""" | L = filter ( truth , map ( _lineClean , split ( text , '\n' ) ) )
return joiner . join ( L ) |
def export_into_python ( self ) :
"""Write the model into a pickle and create a module that loads it .
The model basically exports itself as a pickle file and a Python
file is then written which loads the pickle file . This allows importing
the model in the simulation workflow .""" | pkl_path = self . model . name + '.pkl'
with open ( pkl_path , 'wb' ) as fh :
pickle . dump ( self , fh , protocol = 2 )
py_str = """
import pickle
with open('%s', 'rb') as fh:
model_class = pickle.load(fh)
""" % os . path . abspath ( pkl_path )
py_str = textwrap . dedent ( py_st... |
def has_namespace ( self , namespace : str ) -> bool :
"""Check that the namespace has either been defined by an enumeration or a regular expression .""" | return self . has_enumerated_namespace ( namespace ) or self . has_regex_namespace ( namespace ) |
def next_pos_with_sort_not_in ( self , address , sorts , max_distance = None ) :
"""Returns the address of the next occupied block whose sort is not one of the specified ones .
: param int address : The address to begin the search with ( including itself ) .
: param sorts : A collection of sort strings .
: pa... | list_length = len ( self . _list )
idx = self . _search ( address )
if idx < list_length : # Occupied
block = self . _list [ idx ]
if max_distance is not None and address + max_distance < block . start :
return None
if block . start <= address < block . end : # the address is inside the current bloc... |
def create ( ctx , name , description ) :
"""Create a new dataset .
Prints a JSON object containing the attributes
of the new dataset .
$ mapbox datasets create
All endpoints require authentication . An access token with
` datasets : write ` scope is required , see ` mapbox - - help ` .""" | service = ctx . obj . get ( 'service' )
res = service . create ( name , description )
if res . status_code == 200 :
click . echo ( res . text )
else :
raise MapboxCLIException ( res . text . strip ( ) ) |
def _lookup ( cls : str ) -> LdapObjectClass :
"""Lookup module . class .""" | if isinstance ( cls , str ) :
module_name , _ , name = cls . rpartition ( "." )
module = importlib . import_module ( module_name )
try :
cls = getattr ( module , name )
except AttributeError :
raise AttributeError ( "%s reference cannot be found" % cls )
return cls |
def satellite ( self , stellar_mass , distance_modulus , mc_source_id = 1 , seed = None , ** kwargs ) :
"""Create a simulated satellite . Returns a catalog object .""" | if seed is not None :
np . random . seed ( seed )
isochrone = kwargs . pop ( 'isochrone' , self . isochrone )
kernel = kwargs . pop ( 'kernel' , self . kernel )
for k , v in kwargs . items ( ) :
if k in kernel . params . keys ( ) :
setattr ( kernel , k , v )
mag_1 , mag_2 = isochrone . simulate ( stella... |
def writeInteger ( self , n ) :
"""Writes an integer to the stream .
@ type n : integer data
@ param n : The integer data to be encoded to the AMF3 data stream .""" | if n < MIN_29B_INT or n > MAX_29B_INT :
self . writeNumber ( float ( n ) )
return
self . stream . write ( TYPE_INTEGER )
self . stream . write ( encode_int ( n ) ) |
def _get_class ( self , superclass , namespace = None , local_only = False , include_qualifiers = True , include_classorigin = True ) :
"""This method is just rename of GetClass to support same method
with both MOFWBEMConnection and FakedWBEMConnection""" | return self . GetClass ( superclass , namespace = namespace , local_only = local_only , include_qualifiers = include_qualifiers , include_classorigin = include_classorigin ) |
def change_svc_modattr ( self , service , value ) :
"""Change service modified attributes
Format of the line that triggers function call : :
CHANGE _ SVC _ MODATTR ; < host _ name > ; < service _ description > ; < value >
For boolean attributes , toggles the service attribute state ( enable / disable )
For ... | # todo : deprecate this
# We need to change each of the needed attributes .
previous_value = service . modified_attributes
changes = int ( value )
# For all boolean and non boolean attributes
for modattr in [ "MODATTR_NOTIFICATIONS_ENABLED" , "MODATTR_ACTIVE_CHECKS_ENABLED" , "MODATTR_PASSIVE_CHECKS_ENABLED" , "MODATTR... |
def validate ( config , log ) :
"""Validate config values .
: raise HandledError : On invalid config values .
: param dict config : Dictionary from get _ arguments ( ) .
: param logging . Logger log : Logger for this function . Populated by with _ log ( ) decorator .""" | if config [ 'always_job_dirs' ] and config [ 'no_job_dirs' ] :
log . error ( 'Contradiction: --always-job-dirs and --no-job-dirs used.' )
raise HandledError
if config [ 'commit' ] and not REGEX_COMMIT . match ( config [ 'commit' ] ) :
log . error ( 'No or invalid git commit obtained.' )
raise HandledErr... |
def delete_table ( self , table_name ) :
"""Deletes the table and all of it ' s data . After this request
the table will be in the DELETING state until DynamoDB
completes the delete operation .
: type table _ name : str
: param table _ name : The name of the table to delete .""" | data = { 'TableName' : table_name }
json_input = json . dumps ( data )
return self . make_request ( 'DeleteTable' , json_input ) |
def get_pre_compute ( self , s ) :
''': param s : [ src _ sequence , batch _ size , src _ dim ]
: return : [ src _ sequence , batch _ size . hidden _ dim ]''' | hidden_dim = self . hidden_dim
src_dim = s . get_shape ( ) . as_list ( ) [ - 1 ]
assert src_dim is not None , 'src dim must be defined'
W = self . _get_var ( 'W' , shape = [ src_dim , hidden_dim ] )
b = self . _get_var ( 'b' , shape = [ 1 , hidden_dim ] )
return tf . tensordot ( s , W , [ [ 2 ] , [ 0 ] ] ) + b |
def get_available_detectors ( ) :
"""Return list of detectors known in the currently sourced lalsuite .
This function will query lalsuite about which detectors are known to
lalsuite . Detectors are identified by a two character string e . g . ' K1 ' ,
but also by a longer , and clearer name , e . g . KAGRA . ... | ld = lal . __dict__
known_lal_names = [ j for j in ld . keys ( ) if "DETECTOR_PREFIX" in j ]
known_prefixes = [ ld [ k ] for k in known_lal_names ]
known_names = [ ld [ k . replace ( 'PREFIX' , 'NAME' ) ] for k in known_lal_names ]
return zip ( known_prefixes , known_names ) |
def visit_Assign ( self , node ) :
"""Visit assignment statement .""" | if len ( node . targets ) != 1 :
raise ValueError ( 'no support for chained assignment' )
# Before the node gets modified , get a source code representation
# to add as a comment later on
if anno . hasanno ( node , 'pre_anf' ) :
orig_src = anno . getanno ( node , 'pre_anf' )
else :
orig_src = quoting . unqu... |
def enable_compression ( self , force : Optional [ Union [ bool , ContentCoding ] ] = None ) -> None :
"""Enables response compression encoding .""" | # Backwards compatibility for when force was a bool < 0.17.
if type ( force ) == bool :
force = ContentCoding . deflate if force else ContentCoding . identity
warnings . warn ( "Using boolean for force is deprecated #3318" , DeprecationWarning )
elif force is not None :
assert isinstance ( force , ContentCo... |
def template_files ( path , exts = None ) :
"""Return a list of filenames found at @ path .
The list of filenames can be filtered by extensions .
Arguments :
path : Existing filepath we want to list .
exts : List of extensions to filter by .
Returns :
A list of filenames found in the path .""" | if not os . path . isabs ( path ) :
_path = os . path . join ( determine_path ( ) , path )
if not ( os . path . exists ( _path ) and os . path . isdir ( _path ) ) :
return [ ]
if not exts :
exts = [ ]
files = os . listdir ( _path )
files = [ f for f in files if os . path . splitext ( f ) [ - 1 ] in exts ]
f... |
def ddk_filepath ( self ) :
"""Returns ( at runtime ) the absolute path of the input DKK file .""" | if self . ddk_node is None :
return "DDK_FILE_DOES_NOT_EXIST"
if isinstance ( self . ddk_node , FileNode ) :
return self . ddk_node . filepath
path = self . ddk_node . outdir . has_abiext ( "DDK" )
return path if path else "DDK_FILE_DOES_NOT_EXIST" |
def trace_dependencies ( req , requirement_set , dependencies , _visited = None ) :
"""Trace all dependency relationship
@ param req : requirements to trace
@ param requirement _ set : RequirementSet
@ param dependencies : list for storing dependencies relationships
@ param _ visited : visited requirement s... | _visited = _visited or set ( )
if req in _visited :
return
_visited . add ( req )
for reqName in req . requirements ( ) :
try :
name = pkg_resources . Requirement . parse ( reqName ) . project_name
except ValueError , e :
logger . error ( 'Invalid requirement: %r (%s) in requirement %s' % ( ... |
def signUserCsr ( self , xcsr , signas , outp = None ) :
'''Signs a user CSR with a CA keypair .
Args :
cert ( OpenSSL . crypto . X509Req ) : The certificate signing request .
signas ( str ) : The CA keypair name to sign the CSR with .
outp ( synapse . lib . output . Output ) : The output buffer .
Example... | pkey = xcsr . get_pubkey ( )
name = xcsr . get_subject ( ) . CN
return self . genUserCert ( name , csr = pkey , signas = signas , outp = outp ) |
def grid_visual ( * args , ** kwargs ) :
"""Deprecation wrapper""" | warnings . warn ( "`grid_visual` has moved to `cleverhans.plot.pyplot_image`. " "cleverhans.utils.grid_visual may be removed on or after " "2019-04-24." )
from cleverhans . plot . pyplot_image import grid_visual as new_grid_visual
return new_grid_visual ( * args , ** kwargs ) |
def update_credentials ( self , password ) :
"""Update credentials of a redfish system
: param password : password to be updated""" | data = { 'Password' : password , }
self . _conn . patch ( self . path , data = data ) |
def get_nac_frequencies_along_dir ( self , direction ) :
"""Returns the nac _ frequencies for the given direction ( not necessarily a versor ) .
None if the direction is not present or nac _ frequencies has not been calculated .
Args :
direction : the direction as a list of 3 elements
Returns :
the freque... | versor = [ i / np . linalg . norm ( direction ) for i in direction ]
for d , f in self . nac_frequencies :
if np . allclose ( versor , d ) :
return f
return None |
def img_url ( obj , profile_app_name , profile_model_name ) :
"""returns url of profile image of a user""" | try :
content_type = ContentType . objects . get ( app_label = profile_app_name , model = profile_model_name . lower ( ) )
except ContentType . DoesNotExist :
return ""
except AttributeError :
return ""
Profile = content_type . model_class ( )
fields = Profile . _meta . get_fields ( )
profile = content_type... |
def p_try_statement_3 ( self , p ) :
"""try _ statement : TRY block catch finally""" | p [ 0 ] = self . asttypes . Try ( statements = p [ 2 ] , catch = p [ 3 ] , fin = p [ 4 ] )
p [ 0 ] . setpos ( p ) |
def _group_edges ( self ) :
"""Group all edges that are topologically identical .
This means that ( i , source , target , polarity ) are the same , then sets
edges on parent ( i . e . - group ) nodes to ' Virtual ' and creates a new
edge to represent all of them .""" | # edit edges on parent nodes and make new edges for them
edges_to_add = [ [ ] , [ ] ]
# [ group _ edges , uuid _ lists ]
for e in self . _edges :
new_edge = deepcopy ( e )
new_edge [ 'data' ] . pop ( 'id' , None )
uuid_list = new_edge [ 'data' ] . pop ( 'uuid_list' , [ ] )
# Check if edge source or targ... |
def instance ( ) :
"""Singleton accessor for NotificationDB
Returns :
NotificationDB : The current instance of the NotificationDB""" | if not NotificationDB . __instance :
if settings . NOTIFICATION_DB_PATH :
NotificationDB . __instance = NotificationDB ( settings . notification_leveldb_path )
else :
logger . info ( "Notification DB Path not configured in settings" )
return NotificationDB . __instance |
def FromString ( val ) :
"""Create a ContractParameterType object from a str
Args :
val ( str ) : the value to be converted to a ContractParameterType .
val can be hex encoded ( b ' 07 ' ) , int ( 7 ) , string int ( " 7 " ) , or string literal ( " String " )
Returns :
ContractParameterType""" | # first , check if the value supplied is the string literal of the enum ( e . g . " String " )
if isinstance ( val , bytes ) :
val = val . decode ( 'utf-8' )
try :
return ContractParameterType [ val ]
except Exception as e : # ignore a KeyError if the val isn ' t found in the Enum
pass
# second , check if t... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.