signature stringlengths 29 44.1k | implementation stringlengths 0 85.2k |
|---|---|
def get_body_from_message ( message , maintype , subtype ) :
"""Fetchs the body message matching main / sub content type .""" | body = six . text_type ( '' )
for part in message . walk ( ) :
if part . get ( 'content-disposition' , '' ) . startswith ( 'attachment;' ) :
continue
if part . get_content_maintype ( ) == maintype and part . get_content_subtype ( ) == subtype :
charset = part . get_content_charset ( )
th... |
def vector_analysis ( vector , coordinates , elements_vdw , increment = 1.0 ) :
"""Analyse a sampling vector ' s path for window analysis purpose .""" | # Calculate number of chunks if vector length is divided by increment .
chunks = int ( np . linalg . norm ( vector ) // increment )
# Create a single chunk .
chunk = vector / chunks
# Calculate set of points on vector ' s path every increment .
vector_pathway = np . array ( [ chunk * i for i in range ( chunks + 1 ) ] )... |
def to_transformation_matrix ( translation , orientation_matrix = np . zeros ( ( 3 , 3 ) ) ) :
"""Converts a tuple ( translation _ vector , orientation _ matrix ) to a transformation matrix
Parameters
translation : numpy . array
The translation of your frame presented as a 3D vector .
orientation _ matrix :... | matrix = np . eye ( 4 )
matrix [ : - 1 , : - 1 ] = orientation_matrix
matrix [ : - 1 , - 1 ] = translation
return matrix |
def _is_kvm_hyper ( ) :
'''Returns a bool whether or not this node is a KVM hypervisor''' | try :
with salt . utils . files . fopen ( '/proc/modules' ) as fp_ :
if 'kvm_' not in salt . utils . stringutils . to_unicode ( fp_ . read ( ) ) :
return False
except IOError : # No / proc / modules ? Are we on Windows ? Or Solaris ?
return False
return 'libvirtd' in __salt__ [ 'cmd.run' ] (... |
def setCurrentRule ( self , rule ) :
"""Sets the current query rule for this widget , updating its widget editor if the types do not match .
: param rule | < QueryRule > | | None""" | curr_rule = self . currentRule ( )
if ( curr_rule == rule ) :
return
self . _currentRule = rule
curr_op = self . uiOperatorDDL . currentText ( )
self . uiOperatorDDL . blockSignals ( True )
self . uiOperatorDDL . clear ( )
if ( rule ) :
self . uiOperatorDDL . addItems ( rule . operators ( ) )
index = self .... |
def _get_struct_string ( self ) :
"""Get the STRING structure .""" | data = [ ]
while True :
t = self . _src . read ( 1 )
if t == b'\x00' :
break
data . append ( t )
val = b'' . join ( data )
return val . decode ( "utf8" ) |
def yn ( n , x , context = None ) :
"""Return the value of the second kind Bessel function of order ` ` n ` ` at
` ` n ` ` should be a Python integer .""" | return _apply_function_in_current_context ( BigFloat , mpfr . mpfr_yn , ( n , BigFloat . _implicit_convert ( x ) ) , context , ) |
def update_status_with_media ( self , ** params ) : # pragma : no cover
"""Updates the authenticating user ' s current status and attaches media
for upload . In other words , it creates a Tweet with a picture attached .
Docs :
https : / / developer . twitter . com / en / docs / tweets / post - and - engage / ... | warnings . warn ( 'This method is deprecated. You should use Twython.upload_media instead.' , TwythonDeprecationWarning , stacklevel = 2 )
return self . post ( 'statuses/update_with_media' , params = params ) |
def set_volume ( self , volume ) :
"""Set receiver volume via HTTP get command .
Volume is send in a format like - 50.0.
Minimum is - 80.0 , maximum at 18.0""" | if volume < - 80 or volume > 18 :
raise ValueError ( "Invalid volume" )
try :
return bool ( self . send_get_command ( self . _urls . command_set_volume % volume ) )
except requests . exceptions . RequestException :
_LOGGER . error ( "Connection error: set volume command not sent." )
return False |
def create_table ( self , table_name , primary_id = None , primary_type = None ) :
"""Create a new table .
Either loads a table or creates it if it doesn ' t exist yet . You can
define the name and type of the primary key field , if a new table is to
be created . The default is to create an auto - incrementin... | assert not isinstance ( primary_type , six . string_types ) , 'Text-based primary_type support is dropped, use db.types.'
table_name = normalize_table_name ( table_name )
with self . lock :
if table_name not in self . _tables :
self . _tables [ table_name ] = Table ( self , table_name , primary_id = primary... |
def authenticate ( self , request : AxesHttpRequest , username : str = None , password : str = None , ** kwargs : dict ) :
"""Checks user lockout status and raise a PermissionDenied if user is not allowed to log in .
This method interrupts the login flow and inserts error message directly to the
` ` response _ ... | if request is None :
raise AxesBackendRequestParameterRequired ( 'AxesBackend requires a request as an argument to authenticate' )
credentials = get_credentials ( username = username , password = password , ** kwargs )
if AxesProxyHandler . is_allowed ( request , credentials ) :
return
# Locked out , don ' t tr... |
def get_environ ( self , key , default = None , cast = None ) :
"""Get value from environment variable using os . environ . get
: param key : The name of the setting value , will always be upper case
: param default : In case of not found it will be returned
: param cast : Should cast in to @ int , @ float , ... | key = key . upper ( )
data = self . environ . get ( key , default )
if data :
if cast in converters :
data = converters . get ( cast ) ( data )
if cast is True :
data = parse_conf_data ( data , tomlfy = True )
return data |
def parse ( cls , on_str , force_type = None ) : # @ ReservedAssignment
"""Parse a string into one of the object number classes .""" | on_str_orig = on_str
if on_str is None :
return None
if not on_str :
raise NotObjectNumberError ( "Got null input" )
if not isinstance ( on_str , string_types ) :
raise NotObjectNumberError ( "Must be a string. Got a {} " . format ( type ( on_str ) ) )
# if isinstance ( on _ str , unicode ) :
# dataset = on... |
def create_decision_tree ( data , attributes , class_attr , fitness_func , wrapper , ** kwargs ) :
"""Returns a new decision tree based on the examples given .""" | split_attr = kwargs . get ( 'split_attr' , None )
split_val = kwargs . get ( 'split_val' , None )
assert class_attr not in attributes
node = None
data = list ( data ) if isinstance ( data , Data ) else data
if wrapper . is_continuous_class :
stop_value = CDist ( seq = [ r [ class_attr ] for r in data ] )
# For ... |
def __accept_reject ( self , prompt , accepted_text , rejected_text , display_rejected ) :
"""Return a boolean value for accept / reject .""" | accept_event = threading . Event ( )
result_ref = [ False ]
def perform ( ) :
def accepted ( ) :
result_ref [ 0 ] = True
accept_event . set ( )
def rejected ( ) :
result_ref [ 0 ] = False
accept_event . set ( )
self . __message_column . remove_all ( )
pose_confirmation_me... |
def est_credible_region ( self , level = 0.95 , return_outside = False , modelparam_slice = None ) :
"""Returns an array containing particles inside a credible region of a
given level , such that the described region has probability mass
no less than the desired level .
Particles in the returned region are se... | # which slice of modelparams to take
s_ = np . s_ [ modelparam_slice ] if modelparam_slice is not None else np . s_ [ : ]
mps = self . particle_locations [ : , s_ ]
# Start by sorting the particles by weight .
# We do so by obtaining an array of indices ` id _ sort ` such that
# ` particle _ weights [ id _ sort ] ` is ... |
def folder_path ( preferred_mode , check_other_mode , key ) :
'''This function implements all heuristics and workarounds for messed up
KNOWNFOLDERID registry values . It ' s also verbose ( OutputDebugStringW )
about whether fallbacks worked or whether they would have worked if
check _ other _ mode had been al... | other_mode = 'system' if preferred_mode == 'user' else 'user'
path , exception = dirs_src [ preferred_mode ] [ key ]
if not exception :
return path
logger . info ( "WARNING: menuinst key: '%s'\n" " path: '%s'\n" " .. excepted with: '%s' in knownfolders.py, implementing workarounds .." % ( key , ... |
def posterior_to_xarray ( self ) :
"""Convert posterior samples to xarray .""" | data = self . posterior
if not isinstance ( data , dict ) :
raise TypeError ( "DictConverter.posterior is not a dictionary" )
if "log_likelihood" in data :
warnings . warn ( "log_likelihood found in posterior." " For stats functions log_likelihood needs to be in sample_stats." , SyntaxWarning , )
return dict_to... |
def _get_sections ( request ) :
"""Returns list of sections ( horizontal cut , base level ) .""" | sections = [ ]
for section_url in SECTIONS :
crumb = find_crumb ( request , section_url )
if crumb :
if section_url == '/' :
if request . path == section_url :
crumb . is_current = True
else :
if request . path . startswith ( section_url ) :
... |
def convert_ram_sp_wf ( ADDR_WIDTH = 8 , DATA_WIDTH = 8 ) :
'''Convert RAM : Single - Port , Write - First''' | clk = Signal ( bool ( 0 ) )
we = Signal ( bool ( 0 ) )
addr = Signal ( intbv ( 0 ) [ ADDR_WIDTH : ] )
di = Signal ( intbv ( 0 ) [ DATA_WIDTH : ] )
do = Signal ( intbv ( 0 ) [ DATA_WIDTH : ] )
toVerilog ( ram_sp_wf , clk , we , addr , di , do ) |
def unmount ( self , force = None , auth_no_user_interaction = None ) :
"""Unmount filesystem .""" | return self . _M . Filesystem . Unmount ( '(a{sv})' , filter_opt ( { 'force' : ( 'b' , force ) , 'auth.no_user_interaction' : ( 'b' , auth_no_user_interaction ) , } ) ) |
def PopEvent ( self ) :
"""Pops an event from the heap .
Returns :
tuple : containing :
str : identifier of the event MACB group or None if the event cannot
be grouped .
str : identifier of the event content .
EventObject : event .""" | try :
macb_group_identifier , content_identifier , event = heapq . heappop ( self . _heap )
if macb_group_identifier == '' :
macb_group_identifier = None
return macb_group_identifier , content_identifier , event
except IndexError :
return None |
def timeout ( seconds , error_message = None ) :
"""Timeout checking just for Linux - like platform , not working in Windows platform .""" | def decorated ( func ) :
result = ""
def _handle_timeout ( signum , frame ) :
errmsg = error_message or 'Timeout: The action <%s> is timeout!' % func . __name__
global result
result = None
import inspect
stack_frame = inspect . stack ( ) [ 4 ]
file_name = os . pat... |
def find_lt ( array , x ) :
"""Find rightmost value less than x .
: type array : list
: param array : an iterable object that support inex
: param x : a comparable value
Example : :
> > > find _ lt ( [ 0 , 1 , 2 , 3 ] , 2.5)
* * 中文文档 * *
寻找最大的小于x的数 。""" | i = bisect . bisect_left ( array , x )
if i :
return array [ i - 1 ]
raise ValueError |
def get_assigned_value ( self , name ) :
"""Get the assigned value of an attribute .
Get the underlying value of an attribute . If value has not
been set , will not return the default for the field .
Args :
name : Name of attribute to get .
Returns :
Value of attribute , None if it has not been set .""" | message_type = type ( self )
try :
field = message_type . field_by_name ( name )
except KeyError :
raise AttributeError ( 'Message %s has no field %s' % ( message_type . __name__ , name ) )
return self . __tags . get ( field . number ) |
def _finalize_axis ( self , key , ** kwargs ) :
"""Extends the ElementPlot _ finalize _ axis method to set appropriate
labels , and axes options for 3D Plots .""" | axis = self . handles [ 'axis' ]
self . handles [ 'fig' ] . set_frameon ( False )
axis . grid ( self . show_grid )
axis . view_init ( elev = self . elevation , azim = self . azimuth )
axis . dist = self . distance
if self . xaxis is None :
axis . w_xaxis . line . set_lw ( 0. )
axis . w_xaxis . label . set_text ... |
async def do_upload ( context , files ) :
"""Upload artifacts and return status .
Returns the integer status of the upload .
args :
context ( scriptworker . context . Context ) : the scriptworker context .
files ( list of str ) : list of files to be uploaded as artifacts
Raises :
Exception : on unexpect... | status = 0
try :
await upload_artifacts ( context , files )
except ScriptWorkerException as e :
status = worst_level ( status , e . exit_code )
log . error ( "Hit ScriptWorkerException: {}" . format ( e ) )
except aiohttp . ClientError as e :
status = worst_level ( status , STATUSES [ 'intermittent-task... |
def get_variant_id ( variant_dict = None , variant_line = None ) :
"""Build a variant id
The variant id is a string made of CHROM _ POS _ REF _ ALT
Args :
variant _ dict ( dict ) : A variant dictionary
Returns :
variant _ id ( str )""" | if variant_dict :
chrom = variant_dict [ 'CHROM' ]
position = variant_dict [ 'POS' ]
ref = variant_dict [ 'REF' ]
alt = variant_dict [ 'ALT' ]
elif variant_line :
splitted_line = variant_line . rstrip ( ) . split ( '\t' )
chrom = splitted_line [ 0 ]
position = splitted_line [ 1 ]
ref = s... |
def adaptive ( u_kn , N_k , f_k , tol = 1.0e-12 , options = None ) :
"""Determine dimensionless free energies by a combination of Newton - Raphson iteration and self - consistent iteration .
Picks whichever method gives the lowest gradient .
Is slower than NR since it calculates the log norms twice each iterati... | # put the defaults here in case we get passed an ' options ' dictionary that is only partial
options . setdefault ( 'verbose' , False )
options . setdefault ( 'maximum_iterations' , 250 )
options . setdefault ( 'print_warning' , False )
options . setdefault ( 'gamma' , 1.0 )
gamma = options [ 'gamma' ]
doneIterating = ... |
def get ( self , section , val ) :
"""Get a setting or the default
` Returns ` The current value of the setting ` val ` or the default , or ` None ` if not found
` section ` ( mandatory ) ( string ) the section name in the config E . g . ` " agent " `
` val ` ( mandatory ) ( string ) the section name in the c... | val = val . lower ( )
if section in self . __config :
if val in self . __config [ section ] : # logger . debug ( ' get config % s % s = % s ' , section , val , self . _ _ config [ section ] [ val ] )
return self . __config [ section ] [ val ]
if section in self . __defaults :
if val in self . __defaults... |
def append ( name , value , convert = False , delimiter = DEFAULT_TARGET_DELIM ) :
'''. . versionadded : : 2014.7.0
Append a value to a list in the grains config file . The grain that is being
appended to ( name ) must exist before the new value can be added .
name
The grain name
value
The value to appe... | name = re . sub ( delimiter , DEFAULT_TARGET_DELIM , name )
ret = { 'name' : name , 'changes' : { } , 'result' : True , 'comment' : '' }
grain = __salt__ [ 'grains.get' ] ( name , None )
# Check if bool ( grain ) is False or if the grain is specified in the minions
# grains . Grains can be set to a None value by omitti... |
def remove_duplicate_sg ( security_groups ) :
"""Removes duplicate Security Groups that share a same name alias
Args :
security _ groups ( list ) : A list of security group id to compare against SECURITYGROUP _ REPLACEMENTS
Returns :
security _ groups ( list ) : A list of security groups with duplicate alia... | for each_sg , duplicate_sg_name in SECURITYGROUP_REPLACEMENTS . items ( ) :
if each_sg in security_groups and duplicate_sg_name in security_groups :
LOG . info ( 'Duplicate SG found. Removing %s in favor of %s.' , duplicate_sg_name , each_sg )
security_groups . remove ( duplicate_sg_name )
return se... |
def _setSerialTimeout ( self , timeout , device , message ) :
"""Set the serial timeout on the hardware device .
: Parameters :
timeout : ` float ` or ` int `
The timeout value as defined by the hardware manual .
device : ` int `
The device is the integer number of the hardware devices ID and
is only us... | timeout = min ( self . _timeoutKeys , key = lambda x : abs ( x - timeout ) )
value = self . _timeoutToValue . get ( timeout , 0 )
self . _deviceConfig [ device ] [ 'timeout' ] = timeout
return self . _setConfig ( self . SERIAL_TIMEOUT , value , device , message ) |
def asm ( code , addr = 0 , syntax = None , target = None , gnu_binutils_prefix = None ) :
"""Assemble statements into machine readable code .
Args :
code ( str ) : The statements to assemble .
addr ( int ) : The memory address where the code will run .
syntax ( AsmSyntax ) : The input assembler syntax for ... | if target is None :
target = pwnypack . target . target
if syntax is None and target . arch is pwnypack . target . Target . Arch . x86 :
syntax = AsmSyntax . nasm
if HAVE_KEYSTONE and WANT_KEYSTONE :
ks_mode = 0
ks_syntax = None
if target . arch is pwnypack . target . Target . Arch . x86 :
k... |
def qualify ( self ) :
"""Convert attribute values , that are references to other
objects , into I { qref } . Qualfied using default document namespace .
Since many wsdls are written improperly : when the document does
not define a default namespace , the schema target namespace is used
to qualify reference... | defns = self . root . defaultNamespace ( )
if Namespace . none ( defns ) :
defns = self . schema . tns
for a in self . autoqualified ( ) :
ref = getattr ( self , a )
if ref is None :
continue
if isqref ( ref ) :
continue
qref = qualify ( ref , self . root , defns )
log . debug ( ... |
def with_json_path ( self , path , field = None ) :
"""Annotate Storage objects with a specific JSON path .
: param path : Path to get inside the stored object , which can be
either a list of path components or a comma - separated
string
: param field : Optional output field name""" | if field is None :
field = '_' . join ( [ 'json' ] + json_path_components ( path ) )
kwargs = { field : JsonGetPath ( 'json' , path ) }
return self . defer ( 'json' ) . annotate ( ** kwargs ) |
def unmarshall ( values ) :
"""Transform a response payload from DynamoDB to a native dict
: param dict values : The response payload from DynamoDB
: rtype : dict
: raises ValueError : if an unsupported type code is encountered""" | unmarshalled = { }
for key in values :
unmarshalled [ key ] = _unmarshall_dict ( values [ key ] )
return unmarshalled |
def sudo_remove_dirtree ( dir_name ) :
"""Removes directory tree as a superuser .
Args :
dir _ name : name of the directory to remove .
This function is necessary to cleanup directories created from inside a
Docker , since they usually written as a root , thus have to be removed as a
root .""" | try :
subprocess . check_output ( [ 'sudo' , 'rm' , '-rf' , dir_name ] )
except subprocess . CalledProcessError as e :
raise WorkerError ( 'Can' 't remove directory {0}' . format ( dir_name ) , e ) |
def hmget ( self , name , keys , * args ) :
"""Returns the values stored in the fields .
: param name : str the name of the redis key
: param fields :
: return : Future ( )""" | member_encode = self . memberparse . encode
keys = [ k for k in self . _parse_values ( keys , args ) ]
with self . pipe as pipe :
f = Future ( )
res = pipe . hmget ( self . redis_key ( name ) , [ member_encode ( k ) for k in keys ] )
def cb ( ) :
f . set ( [ self . _value_decode ( keys [ i ] , v ) f... |
def all_languages ( ) :
"""Compile a list of all available language translations""" | rv = [ ]
for lang in os . listdir ( localedir ) :
base = lang . split ( '_' ) [ 0 ] . split ( '.' ) [ 0 ] . split ( '@' ) [ 0 ]
if 2 <= len ( base ) <= 3 and all ( c . islower ( ) for c in base ) :
if base != 'all' :
rv . append ( lang )
rv . sort ( )
rv . append ( 'en' )
l10n_log ( 'Registe... |
def _rewrite_interpreter ( self , path ) :
"""Given the original interpreter binary extracted from the script ' s
interpreter line , look up the associated ` ansible _ * _ interpreter `
variable , render it and return it .
: param str path :
Absolute UNIX path to original interpreter .
: returns :
Shell... | key = u'ansible_%s_interpreter' % os . path . basename ( path ) . strip ( )
try :
template = self . _inv . task_vars [ key ]
except KeyError :
return path
return mitogen . utils . cast ( self . _inv . templar . template ( template ) ) |
def command ( cls , name = None ) :
"""A decorator to convert a function to a command .
A command ' s docstring must be a docopt usage string .
See docopt . org for what it supports .
Commands receive three arguments :
* opts : a dictionary output by docopt
* bot : the Bot instance handling the command ( ... | # adapted from https : / / github . com / docopt / docopt / blob / master / examples / interactive _ example . py
def decorator ( func ) :
@ functools . wraps ( func )
def _cmd_wrapper ( rest , * args , ** kwargs ) :
try :
usage = _cmd_wrapper . __doc__ . partition ( '\n' ) [ 0 ]
... |
def get_instance ( self , payload ) :
"""Build an instance of AssistantInitiationActionsInstance
: param dict payload : Payload response from the API
: returns : twilio . rest . preview . understand . assistant . assistant _ initiation _ actions . AssistantInitiationActionsInstance
: rtype : twilio . rest . p... | return AssistantInitiationActionsInstance ( self . _version , payload , assistant_sid = self . _solution [ 'assistant_sid' ] , ) |
def get_phase ( self ) :
"""get phase of the pod
: return : PodPhase enum""" | if self . phase != PodPhase . TERMINATING :
self . phase = PodPhase . get_from_string ( self . get_status ( ) . phase )
return self . phase |
def recover ( options ) :
"""recover from an existing export run . We do this by
finding the last time change between events , truncate the file
and restart from there""" | event_format = options . kwargs [ 'omode' ]
buffer_size = 64 * 1024
fpd = open ( options . kwargs [ 'output' ] , "r+" )
fpd . seek ( 0 , 2 )
# seek to end
fptr = max ( fpd . tell ( ) - buffer_size , 0 )
fptr_eof = 0
while ( fptr > 0 ) :
fpd . seek ( fptr )
event_buffer = fpd . read ( buffer_size )
( event_s... |
def rectangles_from_points ( S ) :
"""How many rectangles can be formed from a set of points
: param S : list of points , as coordinate pairs
: returns : the number of rectangles
: complexity : : math : ` O ( n ^ 2 ) `""" | answ = 0
pairs = { }
for j in range ( len ( S ) ) :
for i in range ( j ) :
px , py = S [ i ]
qx , qy = S [ j ]
center = ( px + qx , py + qy )
dist = ( px - qx ) ** 2 + ( py - qy ) ** 2
sign = ( center , dist )
if sign in pairs :
answ += len ( pairs [ sign ... |
def extract_name_max_chars ( name , max_chars = 64 , blank = " " ) :
"""Extracts max chars in name truncated to nearest word
: param name : path to edit
: param max _ chars : max chars of new name
: param blank : char that represents the blank between words
: return : Name edited to contain at most max _ ch... | new_name = name . strip ( )
if len ( new_name ) > max_chars :
new_name = new_name [ : max_chars ]
# get at most 64 chars
if new_name . rfind ( blank ) > 0 :
new_name = new_name [ : new_name . rfind ( blank ) ]
# nearest word
return new_name |
def create_processing_context ( feedback ) :
"""Creates a default processing context
: param feedback : Linked processing feedback object
: type feedback : QgsProcessingFeedback
: return : Processing context
: rtype : QgsProcessingContext""" | context = QgsProcessingContext ( )
context . setFeedback ( feedback )
context . setProject ( QgsProject . instance ( ) )
# skip Processing geometry checks - Inasafe has its own geometry validation
# routines which have already been used
context . setInvalidGeometryCheck ( QgsFeatureRequest . GeometryNoCheck )
return co... |
def new_message ( self , message ) :
""": return : None""" | self . logger . info ( "New message: " + str ( message ) )
if isinstance ( message , velbus . BusActiveMessage ) :
self . logger . info ( "Velbus active message received" )
if isinstance ( message , velbus . ReceiveReadyMessage ) :
self . logger . info ( "Velbus receive ready message received" )
if isinstance (... |
def execute ( self ) :
"""Execute this generator regarding its current configuration .""" | if self . direct :
if self . file_type == 'pdf' :
raise IOError ( u"Direct output mode is not available for PDF " "export" )
else :
print ( self . render ( ) . encode ( self . encoding ) )
else :
self . write_and_log ( )
if self . watch :
from landslide . watcher import watch
... |
def _is_plugin_disabled ( plugin ) :
"""Determines if provided plugin is disabled from running for the
active task .""" | item = _registered . get ( plugin . name )
if not item :
return False
_ , props = item
return bool ( props . get ( 'disabled' ) ) |
def list ( cls , ** kwargs ) :
"""List a command by issuing a GET request to the / command endpoint
Args :
` * * kwargs ` : Various parameters can be used to filter the commands such as :
* command _ type - HiveQuery , PrestoQuery , etc . The types should be in title case .
* status - failed , success , etc... | conn = Qubole . agent ( )
params = { }
for k in kwargs :
if kwargs [ k ] :
params [ k ] = kwargs [ k ]
params = None if not params else params
return conn . get ( cls . rest_entity_path , params = params ) |
def get_all_hosts ( resource_root , view = None ) :
"""Get all hosts
@ param resource _ root : The root Resource object .
@ return : A list of ApiHost objects .""" | return call ( resource_root . get , HOSTS_PATH , ApiHost , True , params = view and dict ( view = view ) or None ) |
def pid_max ( self ) :
"""Get the maximum PID value .
On Linux , the value is read from the ` / proc / sys / kernel / pid _ max ` file .
From ` man 5 proc ` :
The default value for this file , 32768 , results in the same range of
PIDs as on earlier kernels . On 32 - bit platfroms , 32768 is the maximum
va... | if LINUX : # XXX : waiting for https : / / github . com / giampaolo / psutil / issues / 720
try :
with open ( '/proc/sys/kernel/pid_max' , 'rb' ) as f :
return int ( f . read ( ) )
except ( OSError , IOError ) :
return None
else :
return None |
def write_memory ( self , * , region_name : str , offset : int = 0 , value = None ) :
"""Writes a value into a memory region on the QAM at a specified offset .
: param region _ name : Name of the declared memory region on the QAM .
: param offset : Integer offset into the memory region to write to .
: param v... | assert self . status in [ 'loaded' , 'done' ]
aref = ParameterAref ( name = region_name , index = offset )
self . _variables_shim [ aref ] = value
return self |
def revoke_all ( cls , cur , schema_name , roles ) :
"""Revoke all privileges from schema , tables , sequences and functions for a specific role""" | cur . execute ( 'REVOKE ALL ON SCHEMA {0} FROM {1};' 'REVOKE ALL ON ALL TABLES IN SCHEMA {0} FROM {1};' 'REVOKE ALL ON ALL SEQUENCES IN SCHEMA {0} FROM {1};' 'REVOKE ALL ON ALL FUNCTIONS IN SCHEMA {0} FROM {1};' . format ( schema_name , roles ) ) |
def update_domain ( self , service_id , version_number , name_key , ** kwargs ) :
"""Update the domain for a particular service and version .""" | body = self . _formdata ( kwargs , FastlyDomain . FIELDS )
content = self . _fetch ( "/service/%s/version/%d/domain/%s" % ( service_id , version_number , name_key ) , method = "PUT" , body = body )
return FastlyDomain ( self , content ) |
def load ( stream , overrides = None , ** kwargs ) :
"""Loads a YAML configuration from a string or file - like object .
Parameters
stream : str or object
Either a string containing valid YAML or a file - like object
supporting the . read ( ) interface .
overrides : dict , optional
A dictionary containi... | global is_initialized
if not is_initialized :
initialize ( )
if isinstance ( stream , basestring ) :
string = stream
else :
string = '\n' . join ( stream . readlines ( ) )
# processed _ string = preprocess ( string )
proxy_graph = yaml . load ( string , ** kwargs )
from . import init
init_dict = proxy_graph... |
def validate ( self , data ) :
"""Validate data using defined sub schema / expressions ensuring all
values are valid .
: param data : to be validated with sub defined schemas .
: return : returns validated data""" | for s in [ self . _schema ( s , error = self . _error , ignore_extra_keys = self . _ignore_extra_keys ) for s in self . _args ] :
data = s . validate ( data )
return data |
def prune_old ( self ) :
"""Removes the directories that are older than a certain date .""" | path = self . pubdir
dirmask = self . dirmask
expire = self . expire
expire_limit = int ( time . time ( ) ) - ( 86400 * expire )
logger . info ( 'Pruning directories older than %d days' , expire )
if not os . path . isdir ( path ) :
logger . warning ( 'Dir %r not found -- skipping pruning' , path )
return
for e... |
def check_running ( self ) :
'''Check if a pid file exists and if it is associated with
a running process .''' | if self . check_pidfile ( ) :
pid = self . get_pidfile ( )
if not salt . utils . platform . is_windows ( ) :
if self . check_pidfile ( ) and self . is_daemonized ( pid ) and os . getppid ( ) != pid :
return True
else : # We have no os . getppid ( ) on Windows . Use salt . utils . win _ f... |
def parse_prompts ( etc_folder ) :
"""Read prompts and prompts - orignal and return as dictionary ( id as key ) .""" | prompts_path = os . path . join ( etc_folder , 'PROMPTS' )
prompts_orig_path = os . path . join ( etc_folder , 'prompts-original' )
prompts = textfile . read_key_value_lines ( prompts_path , separator = ' ' )
prompts_orig = textfile . read_key_value_lines ( prompts_orig_path , separator = ' ' )
prompts_key_fixed = { }
... |
def getTransitionActor ( obj , action_id ) :
"""Returns the actor that performed a given transition . If transition has
not been perormed , or current user has no privileges , returns None
: return : the username of the user that performed the transition passed - in
: type : string""" | review_history = getReviewHistory ( obj )
for event in review_history :
if event . get ( 'action' ) == action_id :
return event . get ( 'actor' )
return None |
def readpipe ( self , chunk = None ) :
"""Return iterator that iterates over STDIN line by line
If ` ` chunk ` ` is set to a positive non - zero integer value , then the
reads are performed in chunks of that many lines , and returned as a
list . Otherwise the lines are returned one by one .""" | read = [ ]
while True :
l = sys . stdin . readline ( )
if not l :
if read :
yield read
return
return
if not chunk :
yield l
else :
read . append ( l )
if len ( read ) == chunk :
yield read |
def upgrade_plugin ( self , name , remote , privileges ) :
"""Upgrade an installed plugin .
Args :
name ( string ) : Name of the plugin to upgrade . The ` ` : latest ` `
tag is optional and is the default if omitted .
remote ( string ) : Remote reference to upgrade to . The
` ` : latest ` ` tag is optiona... | url = self . _url ( '/plugins/{0}/upgrade' , name )
params = { 'remote' : remote , }
headers = { }
registry , repo_name = auth . resolve_repository_name ( remote )
header = auth . get_config_header ( self , registry )
if header :
headers [ 'X-Registry-Auth' ] = header
response = self . _post_json ( url , params = p... |
def _pick_cluster_host ( self , value ) :
"""Selects the Redis cluster host for the specified value .
: param mixed value : The value to use when looking for the host
: rtype : tredis . client . _ Connection""" | crc = crc16 . crc16 ( self . _encode_resp ( value [ 1 ] ) ) % HASH_SLOTS
for host in self . _cluster . keys ( ) :
for slot in self . _cluster [ host ] . slots :
if slot [ 0 ] <= crc <= slot [ 1 ] :
return self . _cluster [ host ]
LOGGER . debug ( 'Host not found for %r, returning first connectio... |
def commit ( self , force = False , partial = False , device_and_network = False , policy_and_objects = False , vsys = "" , no_vsys = False , delay_factor = 0.1 , ) :
"""Commit the candidate configuration .
Commit the entered configuration . Raise an error and return the failure
if the commit fails .
Automati... | delay_factor = self . select_delay_factor ( delay_factor )
if ( device_and_network or policy_and_objects or vsys or no_vsys ) and not partial :
raise ValueError ( "'partial' must be True when using " "device_and_network or policy_and_objects " "or vsys or no_vsys." )
# Select proper command string based on argument... |
def get_mesos_task ( task_name ) :
"""Get a mesos task with a specific task name""" | tasks = get_mesos_tasks ( )
if tasks is not None :
for task in tasks :
if task [ 'name' ] == task_name :
return task
return None |
def create_group ( self , group_name , path = '/' ) :
"""Create a group .
: type group _ name : string
: param group _ name : The name of the new group
: type path : string
: param path : The path to the group ( Optional ) . Defaults to / .""" | params = { 'GroupName' : group_name , 'Path' : path }
return self . get_response ( 'CreateGroup' , params ) |
def _copy_id_str_old ( self ) :
'''Return the string to execute ssh - copy - id''' | if self . passwd : # Using single quotes prevents shell expansion and
# passwords containing ' $ '
return "{0} {1} '{2} -p {3} {4} {5}@{6}'" . format ( 'ssh-copy-id' , '-i {0}.pub' . format ( self . priv ) , self . _passwd_opts ( ) , self . port , self . _ssh_opts ( ) , self . user , self . host )
return None |
def compute_collections ( self ) :
"""Finds the collections ( clusters , chains ) that exist in parsed _ response .
Modified :
- self . collection _ sizes : populated with a list of integers indicating
the number of units belonging to each collection
- self . collection _ indices : populated with a list of ... | if self . custom_threshold :
self . similarity_threshold = self . custom_threshold
elif self . type == "PHONETIC" :
if self . current_similarity_measure == "phone" :
phonetic_similarity_thresholds = { 'a' : 0.222222222222 , 'b' : 0.3 , 'c' : 0.2857142857134 , 'd' : 0.3 , 'e' : 0.25 , 'f' : 0.33333333333... |
def get_parent ( brain_or_object , catalog_search = False ) :
"""Locate the parent object of the content / catalog brain
The ` catalog _ search ` switch uses the ` portal _ catalog ` to do a search return
a brain instead of the full parent object . However , if the search returned
no results , it falls back t... | if is_portal ( brain_or_object ) :
return get_portal ( )
# Do a catalog search and return the brain
if catalog_search :
parent_path = get_parent_path ( brain_or_object )
# parent is the portal object
if parent_path == get_path ( get_portal ( ) ) :
return get_portal ( )
# get the catalog tool... |
def get ( self , path = None , url_kwargs = None , ** kwargs ) :
"""Sends a GET request .
: param path :
The HTTP path ( either absolute or relative ) .
: param url _ kwargs :
Parameters to override in the generated URL . See ` ~ hyperlink . URL ` .
: param * * kwargs :
Optional arguments that ` ` reque... | return self . _session . get ( self . _url ( path , url_kwargs ) , ** kwargs ) |
def select_configuration ( self , obresult ) :
"""Select instrument configuration based on OB""" | logger = logging . getLogger ( __name__ )
logger . debug ( 'calling default configuration selector' )
# get first possible image
ref = obresult . get_sample_frame ( )
extr = self . datamodel . extractor_map [ 'fits' ]
if ref : # get INSCONF configuration
result = extr . extract ( 'insconf' , ref )
if result : #... |
def add_sink ( self , sink ) :
"""Add a vehicle data sink to the instance . ` ` sink ` ` should be a
sub - class of ` ` DataSink ` ` or at least have a ` ` receive ( message ,
* * kwargs ) ` ` method .
The sink will be started if it is startable . ( i . e . it has a ` ` start ( ) ` `
method ) .""" | if sink is not None :
self . sinks . add ( sink )
if hasattr ( sink , 'start' ) :
sink . start ( ) |
def do_folder_update_metadata ( client , args ) :
"""Update file metadata""" | client . update_folder_metadata ( args . uri , foldername = args . foldername , description = args . description , mtime = args . mtime , privacy = args . privacy , privacy_recursive = args . recursive )
return True |
def dumps ( obj , pretty = False , escaped = True ) :
"""Serialize ` ` obj ` ` to a VDF formatted ` ` str ` ` .""" | if not isinstance ( obj , dict ) :
raise TypeError ( "Expected data to be an instance of``dict``" )
if not isinstance ( pretty , bool ) :
raise TypeError ( "Expected pretty to be of type bool" )
if not isinstance ( escaped , bool ) :
raise TypeError ( "Expected escaped to be of type bool" )
return '' . join... |
def get_removed_obs_importance ( self , obslist_dict = None , reset_zero_weight = False ) :
"""get a dataframe the posterior uncertainty
as a result of losing some observations
Parameters
obslist _ dict : dict
dictionary of groups of observations
that are to be treated as lost . key values become
row la... | if obslist_dict is not None :
if type ( obslist_dict ) == list :
obslist_dict = dict ( zip ( obslist_dict , obslist_dict ) )
elif reset_zero_weight is False and self . pst . nnz_obs == 0 :
raise Exception ( "not resetting weights and there are no non-zero weight obs to remove" )
reset = False
if reset_z... |
def gammaRDD ( sc , shape , scale , size , numPartitions = None , seed = None ) :
"""Generates an RDD comprised of i . i . d . samples from the Gamma
distribution with the input shape and scale .
: param sc : SparkContext used to create the RDD .
: param shape : shape ( > 0 ) parameter for the Gamma distribut... | return callMLlibFunc ( "gammaRDD" , sc . _jsc , float ( shape ) , float ( scale ) , size , numPartitions , seed ) |
def str2date ( self , datestr ) :
"""Try parse date from string . If None template matching this datestr ,
raise Error .
: param datestr : a string represent a date
: type datestr : str
: return : a datetime . date object
Usage : :
> > > from weatherlab . lib . timelib . timewrapper import timewrapper
... | try :
return datetime . strptime ( datestr , self . default_date_template ) . date ( )
except : # 如果默认的模板不匹配 , 则重新尝试所有的模板
pass
# try all date _ templates
# 对每个template进行尝试 , 如果都不成功 , 抛出异常
for template in self . date_templates :
try :
a_datetime = datetime . strptime ( datestr , template )
# ... |
def clear_trash ( cookie , tokens ) :
'''清空回收站 , 将里面的所有文件都删除 .''' | url = '' . join ( [ const . PAN_API_URL , 'recycle/clear?channel=chunlei&clienttype=0&web=1' , '&t=' , util . timestamp ( ) , '&bdstoken=' , tokens [ 'bdstoken' ] , ] )
# 使用POST方式发送命令 , 但data为空 .
req = net . urlopen ( url , headers = { 'Cookie' : cookie . header_output ( ) , } , data = '' . encode ( ) )
if req :
co... |
def _validate_image_datatype ( self , img_array ) :
"""Only uint8 and uint16 images are currently supported .""" | if img_array . dtype != np . uint8 and img_array . dtype != np . uint16 :
msg = ( "Only uint8 and uint16 datatypes are currently supported " "when writing." )
raise RuntimeError ( msg ) |
def list_all_refund_operations ( cls , ** kwargs ) :
"""List RefundOperations
Return a list of RefundOperations
This method makes a synchronous HTTP request by default . To make an
asynchronous HTTP request , please pass async = True
> > > thread = api . list _ all _ refund _ operations ( async = True )
>... | kwargs [ '_return_http_data_only' ] = True
if kwargs . get ( 'async' ) :
return cls . _list_all_refund_operations_with_http_info ( ** kwargs )
else :
( data ) = cls . _list_all_refund_operations_with_http_info ( ** kwargs )
return data |
def creation_time ( self ) :
"""dfdatetime . DateTimeValues : creation time or None if not available .""" | timestamp = self . _fsapfs_file_entry . get_creation_time_as_integer ( )
return dfdatetime_apfs_time . APFSTime ( timestamp = timestamp ) |
def version ( self ) :
"""What ' s the version of this database ? Found in metadata attached
by datacache when creating this database .""" | query = "SELECT version FROM %s" % METADATA_TABLE_NAME
cursor = self . connection . execute ( query )
version = cursor . fetchone ( )
if not version :
return 0
else :
return int ( version [ 0 ] ) |
def load_chk ( filename ) :
'''Load a checkpoint file
Argument :
| filename - - the file to load from
The return value is a dictionary whose keys are field labels and the
values can be None , string , integer , float , boolean or an array of
strings , integers , booleans or floats .
The file format is s... | with open ( filename ) as f :
result = { }
while True :
line = f . readline ( )
if line == '' :
break
if len ( line ) < 54 :
raise IOError ( 'Header lines must be at least 54 characters long.' )
key = line [ : 40 ] . strip ( )
kind = line [ 47 : 52... |
def predict ( parameters , X ) :
"""Using the learned parameters , predicts a class for each example in X
Arguments :
parameters - - python dictionary containing your parameters
X - - input data of size ( n _ x , m )
Returns
predictions - - vector of predictions of our model ( red : 0 / blue : 1)""" | # Computes probabilities using forward propagation ,
# and classifies to 0/1 using 0.5 as the threshold .
A2 , cache = forward_propagation ( X , parameters )
predictions = np . array ( [ 1 if ( i > 0.5 ) else 0 for i in A2 [ 0 ] ] )
return predictions |
def beacon ( config ) :
'''Check on different service status reported by the django - server - status
library .
. . code - block : : yaml
beacons :
http _ status :
- sites :
example - site - 1:
url : " https : / / example . com / status "
timeout : 30
content - type : json
status :
- value : 4... | ret = [ ]
_config = { }
list ( map ( _config . update , config ) )
for site , site_config in _config . get ( 'sites' , { } ) . items ( ) :
url = site_config . pop ( 'url' )
content_type = site_config . pop ( 'content_type' , 'json' )
try :
r = requests . get ( url , timeout = site_config . pop ( 'ti... |
def add_cmdline_arg ( args , arg , * values ) :
"""Adds a command line argument * arg * to a list of argument * args * , e . g . as returned from
: py : func : ` global _ cmdline _ args ` . When * arg * exists , * args * is returned unchanged . Otherwise ,
* arg * is appended to the end with optional argument *... | if arg not in args :
args = list ( args ) + [ arg ] + list ( values )
return args |
def make_tornado_app ( self ) :
"""Creates a : py : class ` tornado . web . Application ` instance that respect the
JSON RPC 2.0 specs and exposes the designated methods . Can be used
in tests to obtain the Tornado application .
: return : a : py : class : ` tornado . web . Application ` instance""" | handlers = [ ( self . endpoint , TornadoJsonRpcHandler , { "microservice" : self } ) ]
self . _add_extra_handlers ( handlers )
self . _add_static_handlers ( handlers )
return Application ( handlers , template_path = self . template_dir ) |
def url_to_filename ( url , index = 'index.html' , alt_char = False ) :
'''Return a filename from a URL .
Args :
url ( str ) : The URL .
index ( str ) : If a filename could not be derived from the URL path ,
use index instead . For example , ` ` / images / ` ` will return
` ` index . html ` ` .
alt _ ch... | assert isinstance ( url , str ) , 'Expect str. Got {}.' . format ( type ( url ) )
url_split_result = urllib . parse . urlsplit ( url )
filename = url_split_result . path . split ( '/' ) [ - 1 ]
if not filename :
filename = index
if url_split_result . query :
if alt_char :
query_delim = '@'
else :
... |
def _set_digraph_a ( self , char ) :
'''Sets the currently active character , in case it is ( potentially )
the first part of a digraph .''' | self . _set_char ( char , CV )
self . active_dgr_a_info = di_a_lt [ char ] |
def add_page ( self , orientation = '' ) :
"Start a new page" | if ( self . state == 0 ) :
self . open ( )
family = self . font_family
if self . underline :
style = self . font_style + 'U'
else :
style = self . font_style
size = self . font_size_pt
lw = self . line_width
dc = self . draw_color
fc = self . fill_color
tc = self . text_color
cf = self . color_flag
if ( sel... |
def list_billing ( region , filter_by_kwargs ) :
"""List available billing metrics""" | conn = boto . ec2 . cloudwatch . connect_to_region ( region )
metrics = conn . list_metrics ( metric_name = 'EstimatedCharges' )
# Filtering is based on metric Dimensions . Only really valuable one is
# ServiceName .
if filter_by_kwargs :
filter_key = filter_by_kwargs . keys ( ) [ 0 ]
filter_value = filter_by_k... |
def get_version ( db , name ) :
"""Query database and return migration version . WARNING : side effecting
function ! if no version information can be found , any existing database
matching the passed one ' s name will be deleted and recreated .
: param db : connetion object
: param name : associated name
... | try :
result = db . fetchone ( GET_VERSION_SQL , dict ( name = name ) )
except psycopg2 . ProgrammingError as exc :
if 'does not exist' in str ( exc ) :
return recreate ( db , name )
raise
else :
if result is None :
set_version ( db , name , 0 , 0 )
return ( 0 , 0 )
version =... |
def write_mount_cache ( real_name , device , mkmnt , fstype , mount_opts ) :
'''. . versionadded : : 2018.3.0
Provide information if the path is mounted
: param real _ name : The real name of the mount point where the device is mounted .
: param device : The device that is being mounted .
: param mkmnt : Wh... | cache = salt . utils . mount . read_cache ( __opts__ )
if not cache :
cache = { }
cache [ 'mounts' ] = { }
else :
if 'mounts' not in cache :
cache [ 'mounts' ] = { }
cache [ 'mounts' ] [ real_name ] = { 'device' : device , 'fstype' : fstype , 'mkmnt' : mkmnt , 'opts' : mount_opts }
cache_write = sal... |
def from_summary_line ( cls , summaryLine , version = 4 , existing_object = None ) :
'''Summary format :
object mag stdev dist . . E nobs time av _ xres av _ yres max _ x max _ y
a . . E e . . E i . . E node . . E argperi . . E M . . E ra _ dis dec _ dis''' | if not summaryLine :
raise ValueError ( 'No summary line given' )
if version == 4 :
params = summaryLine . split ( )
if len ( params ) != 25 :
print params
raise TypeError ( 'Expected 25 columns, {0} given' . format ( len ( params ) ) )
input_params = params [ 0 : 1 ] + params [ 3 : 23 ]... |
def restore_state ( self ) :
"""Read last state of GUI from configuration file .""" | last_path = setting ( 'directory' , '' , expected_type = str )
self . output_directory . setText ( last_path ) |
def component ( self , * components ) :
r"""When search ( ) is called it will limit results to items in a component .
: param component : items passed in will be turned into a list
: returns : : class : ` Search `""" | for component in components :
self . _component . append ( component )
return self |
def scale ( val , src , dst ) :
"""Scale value from src range to dst range .
If value outside bounds , it is clipped and set to
the low or high bound of dst .
Ex :
scale ( 0 , ( 0.0 , 99.0 ) , ( - 1.0 , 1.0 ) ) = = - 1.0
scale ( - 5 , ( 0.0 , 99.0 ) , ( - 1.0 , 1.0 ) ) = = - 1.0""" | if val < src [ 0 ] :
return dst [ 0 ]
if val > src [ 1 ] :
return dst [ 1 ]
return ( ( val - src [ 0 ] ) / ( src [ 1 ] - src [ 0 ] ) ) * ( dst [ 1 ] - dst [ 0 ] ) + dst [ 0 ] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.