signature stringlengths 29 44.1k | implementation stringlengths 0 85.2k |
|---|---|
def start ( self , xmlstream ) :
"""Start or resume the stanza stream on the given
: class : ` aioxmpp . protocol . XMLStream ` ` xmlstream ` .
This starts the main broker task , registers stanza classes at the
` xmlstream ` .""" | if self . running :
raise RuntimeError ( "already started" )
self . _start_prepare ( xmlstream , self . recv_stanza )
self . _closed = False
self . _start_commit ( xmlstream ) |
def _collapse_device ( self , node , flat ) :
"""Collapse device hierarchy into a flat folder .""" | items = [ item for branch in node . branches for item in self . _collapse_device ( branch , flat ) if item ]
show_all = not flat or self . _quickmenu_actions == 'all'
methods = node . methods if show_all else [ method for method in node . methods if method . method in self . _quickmenu_actions ]
if flat :
items . e... |
def headers_as_list ( self ) :
"""Does the same as ' headers ' except it is returned as a list .""" | headers = self . headers
headers_list = [ '{}: {}' . format ( key , value ) for key , value in iteritems ( headers ) ]
return headers_list |
def _sequence ( self , i ) :
"""Handle character group .""" | c = next ( i )
if c == '!' :
c = next ( i )
if c in ( '^' , '-' , '[' ) :
c = next ( i )
while c != ']' :
if c == '\\' : # Handle escapes
subindex = i . index
try :
self . _references ( i , True )
except PathNameException :
raise StopIteration
except S... |
def depth ( self , * args ) :
"""Get / set the depth""" | if len ( args ) :
self . _depth = args [ 0 ]
else :
return self . _depth |
def loads ( data , use_datetime = 0 ) :
"""data - > unmarshalled data , method name
Convert an XML - RPC packet to unmarshalled data plus a method
name ( None if not present ) .
If the XML - RPC packet represents a fault condition , this function
raises a Fault exception .""" | p , u = getparser ( use_datetime = use_datetime )
p . feed ( data )
p . close ( )
return u . close ( ) , u . getmethodname ( ) |
def find_column ( selectable , name ) :
"""Find a column named ` name ` in selectable
: param selectable :
: param name :
: return : A column object""" | from recipe import Recipe
if isinstance ( selectable , Recipe ) :
selectable = selectable . subquery ( )
# Selectable is a table
if isinstance ( selectable , DeclarativeMeta ) :
col = getattr ( selectable , name , None )
if col is not None :
return col
col = _find_in_columncollection ( selectabl... |
def exclude ( source , keys , * , transform = None ) :
"""Returns a dictionary excluding keys from a source dictionary .
: source : a dictionary
: keys : a set of keys , or a predicate function that accepting a key
: transform : a function that transforms the values""" | check = keys if callable ( keys ) else lambda key : key in keys
return { key : transform ( source [ key ] ) if transform else source [ key ] for key in source if not check ( key ) } |
def format_label ( sl , fmt = None ) :
"""Combine a list of strings to a single str , joined by sep .
Passes through single strings .
: param sl :
: return :""" | if isinstance ( sl , str ) : # Already is a string .
return sl
if fmt :
return fmt . format ( * sl )
return ' ' . join ( str ( s ) for s in sl ) |
def get_server_capabilities ( self ) :
"""Returns the server capabilities
raises : IloError on an error from iLO .""" | capabilities = { }
sushy_system = self . _get_sushy_system ( PROLIANT_SYSTEM_ID )
sushy_manager = self . _get_sushy_manager ( PROLIANT_MANAGER_ID )
try :
count = len ( sushy_system . pci_devices . gpu_devices )
boot_mode = rf_utils . get_supported_boot_mode ( sushy_system . supported_boot_mode )
capabilitie... |
def get_bank_ids_by_assessment_offered ( self , assessment_offered_id ) :
"""Gets the list of ` ` Bank ` ` ` ` Ids ` ` mapped to an ` ` AssessmentOffered ` ` .
arg : assessment _ offered _ id ( osid . id . Id ) : ` ` Id ` ` of an
` ` AssessmentOffered ` `
return : ( osid . id . IdList ) - list of bank ` ` Ids... | # Implemented from template for
# osid . resource . ResourceBinSession . get _ bin _ ids _ by _ resource
mgr = self . _get_provider_manager ( 'ASSESSMENT' , local = True )
lookup_session = mgr . get_assessment_offered_lookup_session ( proxy = self . _proxy )
lookup_session . use_federated_bank_view ( )
assessment_offer... |
def loadlist ( self , playlist , mode = 'replace' ) :
"""Mapped mpv loadlist command , see man mpv ( 1 ) .""" | self . command ( 'loadlist' , playlist . encode ( fs_enc ) , mode ) |
def _wait_non_ressources ( self , callback ) :
"""This get started as a thread , and waits for the data lock to be freed then advertise itself to the SelectableSelector using the callback""" | # noqa : E501
self . trigger = threading . Lock ( )
self . was_ended = False
self . trigger . acquire ( )
self . trigger . acquire ( )
if not self . was_ended :
callback ( self ) |
def to_dict ( self ) :
"""Convert current Task into a dictionary
: return : python dictionary""" | task_desc_as_dict = { 'uid' : self . _uid , 'name' : self . _name , 'state' : self . _state , 'state_history' : self . _state_history , 'pre_exec' : self . _pre_exec , 'executable' : self . _executable , 'arguments' : self . _arguments , 'post_exec' : self . _post_exec , 'cpu_reqs' : self . _cpu_reqs , 'gpu_reqs' : sel... |
def set ( path , value , version = - 1 , profile = None , hosts = None , scheme = None , username = None , password = None , default_acl = None ) :
'''Update znode with new value
path
znode to update
value
value to set in znode
version
only update znode if version matches ( Default : - 1 ( always matche... | conn = _get_zk_conn ( profile = profile , hosts = hosts , scheme = scheme , username = username , password = password , default_acl = default_acl )
return conn . set ( path , salt . utils . stringutils . to_bytes ( value ) , version = version ) |
def send ( self , event ) :
"""Convert a high - level event into bytes that can be sent to the peer ,
while updating our internal state machine .
Args :
event : The : ref : ` event < events > ` to send .
Returns :
If ` ` type ( event ) is ConnectionClosed ` ` , then returns
` ` None ` ` . Otherwise , re... | data_list = self . send_with_data_passthrough ( event )
if data_list is None :
return None
else :
return b"" . join ( data_list ) |
def add_directory ( self , directory : PathLike ) -> None :
"""Adds * . gtb . cp4 * tables from a directory . The relevant files are lazily
opened when the tablebase is actually probed .""" | directory = os . path . abspath ( directory )
if not os . path . isdir ( directory ) :
raise IOError ( "not a directory: {!r}" . format ( directory ) )
for tbfile in fnmatch . filter ( os . listdir ( directory ) , "*.gtb.cp4" ) :
self . available_tables [ os . path . basename ( tbfile ) . replace ( ".gtb.cp4" ,... |
def async_login ( self ) :
"""Login to Alarm . com .""" | _LOGGER . debug ( 'Attempting to log into Alarm.com...' )
# Get the session key for future logins .
response = None
try :
with async_timeout . timeout ( 10 , loop = self . _loop ) :
response = yield from self . _websession . get ( self . ALARMDOTCOM_URL + '/default.aspx' , headers = { 'User-Agent' : 'Mozill... |
def hierarchyLookup ( self , record ) :
"""Looks up additional hierarchy information for the inputed record .
: param record | < orb . Table >
: return ( < subclass of orb . Table > | | None , < str > column )""" | def _get_lookup ( cls ) :
if cls in self . _hierarchyLookup :
return self . _hierarchyLookup [ cls ]
for base in cls . __bases__ :
results = _get_lookup ( base )
if results :
return results
return ( None , None )
tableType , column = _get_lookup ( type ( record ) )
if tab... |
def find_geometry ( self , physics ) :
r"""Find the Geometry associated with a given Physics
Parameters
physics : OpenPNM Physics Object
Must be a Physics object
Returns
An OpenPNM Geometry object
Raises
If no Geometry object can be found , then an Exception is raised .""" | # If geometry happens to be in settings , look it up directly
if 'geometry' in physics . settings . keys ( ) :
geom = self . geometries ( ) [ physics . settings [ 'geometry' ] ]
return geom
# Otherwise , use the bottom - up approach
for geo in self . geometries ( ) . values ( ) :
if physics in self . find_p... |
def is_element_in_database ( element = '' , database = 'ENDF_VII' ) :
"""will try to find the element in the folder ( database ) specified
Parameters :
element : string . Name of the element . Not case sensitive
database : string ( default is ' ENDF _ VII ' ) . Name of folder that has the list of elements
R... | if element == '' :
return False
list_entry_from_database = get_list_element_from_database ( database = database )
if element in list_entry_from_database :
return True
return False |
def patch ( patchfile , options = '' , saltenv = 'base' , source_hash = None , show_changes = True , source = 'running' , path = None , test = False , commit = True , debug = False , replace = True ) :
'''. . versionadded : : 2019.2.0
Apply a patch to the configuration source , and load the result into the
runn... | config_saved = save_config ( source = source , path = path )
if not config_saved or not config_saved [ 'result' ] :
return config_saved
path = config_saved [ 'out' ]
patchfile_cache = __salt__ [ 'cp.cache_file' ] ( patchfile )
if patchfile_cache is False :
return { 'out' : None , 'result' : False , 'comment' : ... |
def nr_cases ( self , snv_cases = None , sv_cases = None ) :
"""Return the number of cases in the database
Args :
snv _ cases ( bool ) : If only snv cases should be searched
sv _ cases ( bool ) : If only snv cases should be searched
Returns :
cases ( Iterable ( Case ) ) : A iterable with mongo cases""" | query = { }
if snv_cases :
query = { 'vcf_path' : { '$exists' : True } }
if sv_cases :
query = { 'vcf_sv_path' : { '$exists' : True } }
if snv_cases and sv_cases :
query = None
return self . db . case . count_documents ( query ) |
def calc_qar_v1 ( self ) :
"""Calculate the discharge responses of the different AR processes .
Required derived parameters :
| Nmb |
| AR _ Order |
| AR _ Coefs |
Required log sequence :
| LogOut |
Calculated flux sequence :
| QAR |
Examples :
Assume there are four response functions , involvin... | der = self . parameters . derived . fastaccess
flu = self . sequences . fluxes . fastaccess
log = self . sequences . logs . fastaccess
for idx in range ( der . nmb ) :
flu . qar [ idx ] = 0.
for jdx in range ( der . ar_order [ idx ] ) :
flu . qar [ idx ] += der . ar_coefs [ idx , jdx ] * log . logout [ ... |
def spectrodir ( self , filetype , ** kwargs ) :
"""Returns : envvar : ` SPECTRO _ REDUX ` or : envvar : ` BOSS _ SPECTRO _ REDUX `
depending on the value of ` run2d ` .
Parameters
filetype : str
File type parameter .
run2d : int or str
2D Reduction ID .
Returns
spectrodir : str
Value of the appro... | if str ( kwargs [ 'run2d' ] ) in ( '26' , '103' , '104' ) :
return os . environ [ 'SPECTRO_REDUX' ]
else :
return os . environ [ 'BOSS_SPECTRO_REDUX' ] |
def upload ( self , wg_uuid , file_path , description = None , parent = None ) :
"""Upload a file to LinShare using its rest api .
The uploaded document uuid will be returned""" | url = "%(base)s/%(wg_uuid)s/nodes" % { 'base' : self . local_base_url , 'wg_uuid' : wg_uuid }
param = { }
if parent : # I use only the last folder uuid , the first ones are not really useful
if isinstance ( parent , ( list , ) ) :
if len ( parent ) >= 1 :
parent = parent [ - 1 ]
param [ 'par... |
def get_all_longest_col_lengths ( self ) :
"""iterate over all columns and get their longest values
: return : dict , { " column _ name " : 132}""" | response = { }
for col in self . col_list :
response [ col ] = self . _longest_val_in_column ( col )
return response |
def activate ( request , activation_key , template_name = 'accounts/activate_fail.html' , success_url = None , extra_context = None ) :
"""Activate a user with an activation key .
The key is a SHA1 string . When the SHA1 is found with an
: class : ` AccountsSignup ` , the : class : ` User ` of that account will... | user = AccountsSignup . objects . activate_user ( activation_key )
if user : # Sign the user in .
auth_user = authenticate ( identification = user . email , check_password = False )
login ( request , auth_user )
if accounts_settings . ACCOUNTS_USE_MESSAGES :
messages . success ( request , _ ( 'Your ... |
def kappa_analysis_koch ( kappa ) :
"""Analysis kappa number with Landis - Koch benchmark .
: param kappa : kappa number
: type kappa : float
: return : strength of agreement as str""" | try :
if kappa < 0 :
return "Poor"
if kappa >= 0 and kappa < 0.2 :
return "Slight"
if kappa >= 0.20 and kappa < 0.4 :
return "Fair"
if kappa >= 0.40 and kappa < 0.6 :
return "Moderate"
if kappa >= 0.60 and kappa < 0.8 :
return "Substantial"
if kappa >= 0.8... |
def sigFromPy ( pobj ) :
"""Returns the DBus signature type for the argument . If the argument is an
instance of one of the type wrapper classes , the exact type signature
corresponding to the wrapper class will be used . If the object has a
variable named ' dbusSignature ' , the value of that variable will b... | sig = getattr ( pobj , 'dbusSignature' , None )
if sig is not None :
return sig
elif isinstance ( pobj , int ) :
return 'i'
elif isinstance ( pobj , six . integer_types ) :
return 'x'
elif isinstance ( pobj , float ) :
return 'd'
elif isinstance ( pobj , six . string_types ) :
return 's'
elif isinst... |
def close_positions_order ( self ) :
"""平仓单
Raises :
RuntimeError - - if ACCOUNT . RUNNING _ ENVIRONMENT is NOT TZERO
Returns :
list - - list with order""" | order_list = [ ]
time = '{} 15:00:00' . format ( self . date )
if self . running_environment == RUNNING_ENVIRONMENT . TZERO :
for code , amount in self . hold_available . iteritems ( ) :
order = False
if amount < 0 : # 先卖出的单子 买平
order = self . send_order ( code = code , price = 0 , amoun... |
def all ( self ) :
"""Get all ssh keys associated with your account .""" | url = self . bitbucket . url ( 'GET_SSH_KEYS' )
return self . bitbucket . dispatch ( 'GET' , url , auth = self . bitbucket . auth ) |
def extract_subset ( self , subset , contract = True ) :
"""Return all nodes in a subset .
We assume the oboInOwl encoding of subsets , and subset IDs are IRIs , or IR fragments""" | return [ n for n in self . nodes ( ) if subset in self . subsets ( n , contract = contract ) ] |
def hil_rc_inputs_raw_encode ( self , time_usec , chan1_raw , chan2_raw , chan3_raw , chan4_raw , chan5_raw , chan6_raw , chan7_raw , chan8_raw , chan9_raw , chan10_raw , chan11_raw , chan12_raw , rssi ) :
'''Sent from simulation to autopilot . The RAW values of the RC channels
received . The standard PPM modulat... | return MAVLink_hil_rc_inputs_raw_message ( time_usec , chan1_raw , chan2_raw , chan3_raw , chan4_raw , chan5_raw , chan6_raw , chan7_raw , chan8_raw , chan9_raw , chan10_raw , chan11_raw , chan12_raw , rssi ) |
def resolve_links ( self , link_resolver ) :
"""Banana banana""" | self . type_link = None
self . type_tokens = [ ]
for child in self . get_children_symbols ( ) :
child . resolve_links ( link_resolver )
for tok in self . input_tokens :
if isinstance ( tok , Link ) :
self . type_link = link_resolver . upsert_link ( tok )
self . type_tokens . append ( self . type... |
def _hash ( x , elementType , relicHashFunc ) :
"""Hash an array of bytes , @ x , using @ relicHashFunc and returns the result
of @ elementType .""" | # Combine all inputs into a single bytearray
barray = bytearray ( )
map ( barray . extend , bytes ( x ) )
# Create an element of the correct type to hold the hash result
result = elementType ( )
# Convert barray into a modifiable ctypes buffer , hash using the provided
# function , and return the result .
buf = getBuff... |
def to_string ( self , other ) :
"""String representation with addtional information""" | arg = "%s/%s,%s" % ( self . ttl , self . get_remaining_ttl ( current_time_millis ( ) ) , other )
return DNSEntry . to_string ( self , "record" , arg ) |
def reverb ( self , reverberance = 50 , hf_damping = 50 , room_scale = 100 , stereo_depth = 100 , pre_delay = 20 , wet_gain = 0 , wet_only = False ) :
"""reverb takes 7 parameters : reverberance , high - freqnency damping ,
room scale , stereo depth , pre - delay , wet gain and wet only ( Truce or
False )""" | self . command . append ( 'reverb' )
if wet_only :
self . command . append ( '-w' )
self . command . append ( reverberance )
self . command . append ( hf_damping )
self . command . append ( room_scale )
self . command . append ( stereo_depth )
self . command . append ( pre_delay )
self . command . append ( wet_gain... |
def signin ( request , auth_form = AuthenticationForm , template_name = 'userena/signin_form.html' , redirect_field_name = REDIRECT_FIELD_NAME , redirect_signin_function = signin_redirect , extra_context = None ) :
"""Signin using email or username with password .
Signs a user in by combining email / username wit... | form = auth_form ( )
if request . method == 'POST' :
form = auth_form ( request . POST , request . FILES )
if form . is_valid ( ) :
identification , password , remember_me = ( form . cleaned_data [ 'identification' ] , form . cleaned_data [ 'password' ] , form . cleaned_data [ 'remember_me' ] )
... |
def start ( self , container , ** kwargs ) :
"""Identical to : meth : ` docker . api . container . ContainerApiMixin . start ` with additional logging .""" | self . push_log ( "Starting container '{0}'." . format ( container ) )
super ( DockerFabricClient , self ) . start ( container , ** kwargs ) |
def ensure_int_vector_or_None ( F , require_order = False ) :
"""Ensures that F is either None , or a numpy array of floats
If F is already either None or a numpy array of floats , F is returned ( no copied ! )
Otherwise , checks if the argument can be converted to an array of floats and does that .
Parameter... | if F is None :
return F
else :
return ensure_int_vector ( F , require_order = require_order ) |
def get_automation ( self , automation_id , refresh = False ) :
"""Get a single automation .""" | if self . _automations is None :
self . get_automations ( )
refresh = False
automation = self . _automations . get ( str ( automation_id ) )
if automation and refresh :
automation . refresh ( )
return automation |
def execute ( self , method , args , ref ) :
"""Execute the method with args""" | response = { 'result' : None , 'error' : None , 'ref' : ref }
fun = self . methods . get ( method )
if not fun :
response [ 'error' ] = 'Method `{}` not found' . format ( method )
else :
try :
response [ 'result' ] = fun ( * args )
except Exception as exception :
logging . error ( exception ... |
def parse_result ( cls , result ) :
"""Parse an items + count tuple result .
May either be three item tuple containing items , count , and a context dictionary ( see : relation convention )
or a two item tuple containing only items and count .""" | if len ( result ) == 3 :
items , count , context = result
else :
context = { }
items , count = result
return items , count , context |
def list_passwords ( kwargs = None , call = None ) :
'''List all password on the account
. . versionadded : : 2015.8.0''' | response = _query ( 'support' , 'password/list' )
ret = { }
for item in response [ 'list' ] :
if 'server' in item :
server = item [ 'server' ] [ 'name' ]
if server not in ret :
ret [ server ] = [ ]
ret [ server ] . append ( item )
return ret |
def dimension ( self ) :
"""Compute the dimension of the sampling space and identify the slices
belonging to each stochastic .""" | self . dim = 0
self . _slices = { }
for stochastic in self . stochastics :
if isinstance ( stochastic . value , np . matrix ) :
p_len = len ( stochastic . value . A . ravel ( ) )
elif isinstance ( stochastic . value , np . ndarray ) :
p_len = len ( stochastic . value . ravel ( ) )
else :
... |
def _make_2d_array ( self , data ) :
"""Convert a 1D array of mesh values to a masked 2D mesh array
given the 1D mesh indices ` ` mesh _ idx ` ` .
Parameters
data : 1D ` ~ numpy . ndarray `
A 1D array of mesh values .
Returns
result : 2D ` ~ numpy . ma . MaskedArray `
A 2D masked array . Pixels not de... | if data . shape != self . mesh_idx . shape :
raise ValueError ( 'data and mesh_idx must have the same shape' )
if np . ma . is_masked ( data ) :
raise ValueError ( 'data must not be a masked array' )
data2d = np . zeros ( self . _mesh_shape ) . astype ( data . dtype )
data2d [ self . mesh_yidx , self . mesh_xid... |
def _maybe_flush_gcs ( self ) :
"""Experimental : issue a flush request to the GCS .
The purpose of this feature is to control GCS memory usage .
To activate this feature , Ray must be compiled with the flag
RAY _ USE _ NEW _ GCS set , and Ray must be started at run time with the flag
as well .""" | if not self . issue_gcs_flushes :
return
if self . gcs_flush_policy is None :
serialized = self . redis . get ( "gcs_flushing_policy" )
if serialized is None : # Client has not set any policy ; by default flushing is off .
return
self . gcs_flush_policy = pickle . loads ( serialized )
if not sel... |
def export ( self , name , columns , points ) :
"""Write the points to the Cassandra cluster .""" | logger . debug ( "Export {} stats to Cassandra" . format ( name ) )
# Remove non number stats and convert all to float ( for Boolean )
data = { k : float ( v ) for ( k , v ) in dict ( zip ( columns , points ) ) . iteritems ( ) if isinstance ( v , Number ) }
# Write input to the Cassandra table
try :
stmt = "INSERT ... |
def is_entailed_by ( self , other ) :
"""Returns True iff the values in this list can be entailed by the other
list ( ie , this list is a prefix of the other )""" | other = ListCell . coerce ( other )
if other . size ( ) < self . size ( ) : # other is bigger , can ' t be entailed
return False
if self . value is None : # list is empty
return True
# see if any values in the shorter list are contradictory or
# unequal
for i , oval in enumerate ( other . value ) :
if i == ... |
def delete_audit_sink ( self , name , ** kwargs ) :
"""delete an AuditSink
This method makes a synchronous HTTP request by default . To make an
asynchronous HTTP request , please pass async _ req = True
> > > thread = api . delete _ audit _ sink ( name , async _ req = True )
> > > result = thread . get ( ) ... | kwargs [ '_return_http_data_only' ] = True
if kwargs . get ( 'async_req' ) :
return self . delete_audit_sink_with_http_info ( name , ** kwargs )
else :
( data ) = self . delete_audit_sink_with_http_info ( name , ** kwargs )
return data |
def disconnect ( self , id ) : # pylint : disable = invalid - name , redefined - builtin
"""Close proxy connection to a device ' s management interface .
: param id : Device ID as an int .""" | return self . service . post ( self . base + str ( id ) + '/disconnect/' ) |
def restart ( self , start_from = 1 , occupied = [ ] ) :
"""Restart the manager from scratch . The arguments replicate those of
the constructor of : class : ` IDPool ` .""" | # initial ID
self . top = start_from - 1
# occupied IDs
self . _occupied = sorted ( occupied , key = lambda x : x [ 0 ] )
# main dictionary storing the mapping from objects to variable IDs
self . obj2id = collections . defaultdict ( lambda : self . _next ( ) )
# mapping back from variable IDs to objects
# ( if for what... |
def total_variation ( arr ) :
'''If arr is a 2D array ( N X M ) , assumes that arr is a spectrogram with time along axis = 0.
Calculates the 1D total variation in time for each frequency and returns an array
of size M .
If arr is a 1D array , calculates total variation and returns a scalar .
Sum ( Abs ( arr... | return np . sum ( np . abs ( np . diff ( arr , axis = 0 ) ) , axis = 0 ) |
def get_vnetwork_dvs_output_vnetwork_dvs_pnic ( self , ** kwargs ) :
"""Auto Generated Code""" | config = ET . Element ( "config" )
get_vnetwork_dvs = ET . Element ( "get_vnetwork_dvs" )
config = get_vnetwork_dvs
output = ET . SubElement ( get_vnetwork_dvs , "output" )
vnetwork_dvs = ET . SubElement ( output , "vnetwork-dvs" )
pnic = ET . SubElement ( vnetwork_dvs , "pnic" )
pnic . text = kwargs . pop ( 'pnic' )
c... |
def relocate ( self , lon ) :
"""Relocates this object to a new longitude .""" | self . lon = angle . norm ( lon )
self . signlon = self . lon % 30
self . sign = const . LIST_SIGNS [ int ( self . lon / 30.0 ) ] |
def loadBrowsers ( ) :
"""Loads all installed and supported browsers into BrowserCookies . browsers
Loops through all classes that subclass BrowserCookies and checks the installed
attribute . If the browser is installed , it ' s instance is loaded into
BrowserCookies . browsers in the format of browsers [ bro... | for browser in BrowserCookies . __subclasses__ ( ) :
if browser . installed :
BrowserCookies . browsers [ browser . name ] = browser |
def get_handler ( self , * args , ** options ) :
"""Returns the static files serving handler wrapping the default handler ,
if static files should be served . Otherwise just returns the default
handler .""" | handler = super ( Command , self ) . get_handler ( * args , ** options )
insecure_serving = options . get ( 'insecure_serving' , False )
if self . should_use_static_handler ( options ) :
return StaticFilesHandler ( handler )
return handler |
def expand_url ( url , protocol ) :
"""Expands the given URL to a full URL by adding
the magento soap / wsdl parts
: param url : URL to be expanded
: param service : ' xmlrpc ' or ' soap '""" | if protocol == 'soap' :
ws_part = 'api/?wsdl'
elif protocol == 'xmlrpc' :
ws_part = 'index.php/api/xmlrpc'
else :
ws_part = 'index.php/rest/V1'
return url . endswith ( '/' ) and url + ws_part or url + '/' + ws_part |
def get_catalog ( self , query ) :
"""Fetch a parsed THREDDS catalog from the radar server .
Requests a catalog of radar data files data from the radar server given the
parameters in ` query ` and returns a : class : ` ~ siphon . catalog . TDSCatalog ` instance .
Parameters
query : RadarQuery
The paramete... | # TODO : Refactor TDSCatalog so we don ' t need two requests , or to do URL munging
try :
url = self . _base [ : - 1 ] if self . _base [ - 1 ] == '/' else self . _base
url += '?' + str ( query )
return TDSCatalog ( url )
except ET . ParseError :
raise BadQueryError ( self . get_catalog_raw ( query ) ) |
def put ( self , x ) :
"""Assign input ` x ` to an available worker and invoke
` parallizable . forward _ backward ` with x .""" | if self . _num_serial > 0 or len ( self . _threads ) == 0 :
self . _num_serial -= 1
out = self . _parallizable . forward_backward ( x )
self . _out_queue . put ( out )
else :
self . _in_queue . put ( x ) |
def color_str ( self ) :
"Return an escape - coded string to write to the terminal ." | s = self . s
for k , v in sorted ( self . atts . items ( ) ) : # ( self . atts sorted for the sake of always acting the same . )
if k not in xforms : # Unsupported SGR code
continue
elif v is False :
continue
elif v is True :
s = xforms [ k ] ( s )
else :
s = xforms [ k ]... |
def _sync_etc ( self , headless = False ) : # Ignore SIGQUIT ( ctrl - \ ) . The child process will handle it , and we ' ll
# exit when the child process does .
# We disable these signals after running the process so the child doesn ' t
# inherit this behaviour .
try :
signal . signal ( signal . SIGQUIT , si... | if exitcode is None :
exitcode = 254
wandb . termlog ( 'Killing program failed; syncing files anyway. Press ctrl-c to abort syncing.' )
else :
if exitcode == 0 :
wandb . termlog ( 'Program ended successfully.' )
resume_path = os . path . join ( wandb . wandb_dir ( ) , wandb_run . RESUME_FNAM... |
def _match_batches ( tumor , normal ) :
"""Fix batch names for shared tumor / normals to ensure matching""" | def _get_batch ( x ) :
b = dd . get_batch ( x )
return [ b ] if not isinstance ( b , ( list , tuple ) ) else b
if normal :
tumor = copy . deepcopy ( tumor )
normal = copy . deepcopy ( normal )
cur_batch = list ( set ( _get_batch ( tumor ) ) & set ( _get_batch ( normal ) ) )
assert len ( cur_batc... |
def delete ( self , qname ) :
'''Delete an existings RackSpace Queue .''' | try :
q = self . exists ( qname )
if not q :
return False
queue = self . show ( qname )
if queue :
queue . delete ( )
except pyrax . exceptions as err_msg :
log . error ( 'RackSpace API got some problems during deletion: %s' , err_msg )
return False
return True |
def _date_time_match ( cron , ** kwargs ) :
'''Returns true if the minute , hour , etc . params match their counterparts from
the dict returned from list _ tab ( ) .''' | return all ( [ kwargs . get ( x ) is None or cron [ x ] == six . text_type ( kwargs [ x ] ) or ( six . text_type ( kwargs [ x ] ) . lower ( ) == 'random' and cron [ x ] != '*' ) for x in ( 'minute' , 'hour' , 'daymonth' , 'month' , 'dayweek' ) ] ) |
def predict ( self , X ) :
"""Predict values using the model
Parameters
X : { array - like , sparse matrix } of shape [ n _ samples , n _ features ]
Returns
C : numpy array of shape [ n _ samples , n _ outputs ]
Predicted values .""" | if not self . fitted_ :
raise ValueError ( "ELMRegressor not fitted" )
# compute hidden layer activations
self . hidden_activations_ = self . hidden_layer . transform ( X )
# compute output predictions for new hidden activations
predictions = self . _get_predictions ( )
return predictions |
def table_type ( table_name ) :
"""Returns the type of a registered table .
The type can be either " dataframe " or " function " .
Parameters
table _ name : str
Returns
table _ type : { ' dataframe ' , ' function ' }""" | table = get_raw_table ( table_name )
if isinstance ( table , DataFrameWrapper ) :
return 'dataframe'
elif isinstance ( table , TableFuncWrapper ) :
return 'function' |
def get_raw_request_token ( self , method = 'GET' , ** kwargs ) :
'''Returns a Requests ' response over the
: attr : ` rauth . OAuth1Service . request _ token _ url ` .
Use this if your endpoint if you need the full ` Response ` object .
: param method : A string representation of the HTTP method to be used ,... | # ensure we ' ve set the request _ token _ url
if self . request_token_url is None :
raise TypeError ( 'request_token_url must not be None' )
session = self . get_session ( )
self . request_token_response = session . request ( method , self . request_token_url , ** kwargs )
return self . request_token_response |
def remove_images ( self , images ) :
"""Remove images from the album .
: param images : A list of the images we want to remove from the album .
Can be Image objects , ids or a combination of the two . Images that
you cannot remove ( non - existing , not owned by you or not part of
album ) will not cause ex... | url = ( self . _imgur . _base_url + "/3/album/{0}/" "remove_images" . format ( self . _delete_or_id_hash ) )
# NOTE : Returns True and everything seem to be as it should in testing .
# Seems most likely to be upstream bug .
params = { 'ids' : images }
return self . _imgur . _send_request ( url , params = params , metho... |
def table_top_abs ( self ) :
"""Returns the absolute position of table top""" | table_height = np . array ( [ 0 , 0 , self . table_full_size [ 2 ] ] )
return string_to_array ( self . floor . get ( "pos" ) ) + table_height |
def QA_SU_save_deal ( dealist , client = DATABASE ) :
"""存储order _ handler的deal _ status
Arguments :
dealist { [ dataframe ] } - - [ description ]
Keyword Arguments :
client { [ type ] } - - [ description ] ( default : { DATABASE } )""" | if isinstance ( dealist , pd . DataFrame ) :
collection = client . deal
collection . create_index ( [ ( 'account_cookie' , ASCENDING ) , ( 'trade_id' , ASCENDING ) ] , unique = True )
try :
dealist = QA_util_to_json_from_pandas ( dealist . reset_index ( ) )
collection . insert_many ( dealist... |
def register_socket ( self , socket ) :
"""Registers the given socket ( s ) for further use .
: param Socket | list [ Socket ] socket : Socket type object . See ` ` . sockets ` ` .""" | sockets = self . _sockets
for socket in listify ( socket ) :
uses_shared = isinstance ( socket . address , SocketShared )
if uses_shared : # Handling shared sockets involves socket index resolution .
shared_socket = socket . address
# type : SocketShared
if shared_socket not in sockets :... |
def _get_file_index_str ( self ) :
"""Create a string out of the current file _ index""" | file_index = str ( self . file_index )
if self . n_digits is not None :
file_index = file_index . zfill ( self . n_digits )
return file_index |
def copy_spline_array ( a ) :
"""This returns an instance of a new spline _ array with all the fixins , and the data from a .""" | b = spline_array ( )
b . x_splines = a . x_splines
b . y_splines = a . y_splines
b . max_y_splines = a . max_y_splines
b . xmin = a . xmin
b . xmax = a . xmax
b . ymin = a . ymin
b . ymax = a . ymax
b . xlabel = a . xlabel
b . ylabel = a . ylabel
b . zlabel = a . zlabel
b . simple = a . simple
b . generate_y_values ( )... |
def calc_outflow_v1 ( self ) :
"""Calculate the total outflow of the dam .
Note that the maximum function is used to prevent from negative outflow
values , which could otherwise occur within the required level of
numerical accuracy .
Required flux sequences :
| ActualRelease |
| FloodDischarge |
Calcu... | flu = self . sequences . fluxes . fastaccess
flu . outflow = max ( flu . actualrelease + flu . flooddischarge , 0. ) |
def get_wave_form ( self ) :
'''getter''' | if isinstance ( self . __wave_form , WaveFormInterface ) is False :
raise TypeError ( )
return self . __wave_form |
def rotate_left ( self ) :
"""Rotate the node to the left .""" | right = self . right
new = self . _replace ( right = self . right . left , red = True )
top = right . _replace ( left = new , red = self . red )
return top |
def process_request ( self , request ) :
"""Ignore unnecessary actions for static file requests , posts , or ajax
requests . We ' re only interested in redirecting following a ' natural '
request redirection to the ` wagtailadmin _ explore _ root ` or
` wagtailadmin _ explore ` views .""" | referer_url = request . META . get ( 'HTTP_REFERER' )
return_to_index_url = request . session . get ( 'return_to_index_url' )
try :
if all ( ( return_to_index_url , referer_url , request . method == 'GET' , not request . is_ajax ( ) , resolve ( request . path ) . url_name in ( 'wagtailadmin_explore_root' , 'wagtail... |
def remove_indices ( self , indices ) :
"""Remove rows by which have the given indices .
Parameters
indices : list
Returns
filtered _ list : EList""" | new_list = [ ]
for index , element in enumerate ( self ) :
if index not in indices :
new_list . append ( element )
return EList ( new_list ) |
def depends ( self , d ) :
"""Adds additional instances of ' VirtualTarget ' that this
one depends on .""" | self . dependencies_ = unique ( self . dependencies_ + d ) . sort ( ) |
def remove ( self , widget ) :
"""Remove a widget from the window .""" | for i , ( wid , _ ) in enumerate ( self . _widgets ) :
if widget is wid :
del self . _widgets [ i ]
return True
raise ValueError ( 'Widget not in list' ) |
def create_prefix_dir ( nb_file , fmt ) :
"""Create directory if fmt has a prefix""" | if 'prefix' in fmt :
nb_dir = os . path . dirname ( nb_file ) + os . path . sep
if not os . path . isdir ( nb_dir ) :
logging . log ( logging . WARNING , "[jupytext] creating missing directory %s" , nb_dir )
os . makedirs ( nb_dir ) |
def get_formset ( self ) :
"""Provide the formset corresponding to this DataTable .
Use this to validate the formset and to get the submitted data back .""" | if self . _formset is None :
self . _formset = self . formset_class ( self . request . POST or None , initial = self . _get_formset_data ( ) , prefix = self . _meta . name )
return self . _formset |
def on_click_search_widget ( self , event ) :
"""When the search control is toggled , set visibility and hand down cats""" | self . search . cats = self . cats
self . search . visible = event . new
if self . search . visible :
self . search . watchers . append ( self . select . widget . link ( self . search , value = 'cats' ) ) |
def host_get ( host = None , name = None , hostids = None , ** kwargs ) :
'''. . versionadded : : 2016.3.0
Retrieve hosts according to the given parameters
. . note : :
This function accepts all optional host . get parameters : keyword
argument names differ depending on your zabbix version , see here _ _ . ... | conn_args = _login ( ** kwargs )
ret = { }
try :
if conn_args :
method = 'host.get'
params = { "output" : "extend" , "filter" : { } }
if not name and not hostids and not host :
return False
if name :
params [ 'filter' ] . setdefault ( 'name' , name )
i... |
def in_function_call ( self ) :
"""This function is called whenever the cursor / buffer goes idle for
a second . The real workhorse of the intellisense . Decides what kind
of intellisense is needed and returns the relevant response .""" | # See if we are calling a function inside a module or other function .
result = [ ]
if ( self . context . el_section == "body" and self . context . el_call in [ "sub" , "fun" ] ) : # Do a signature completion for the function / subroutine call .
result = self . signature ( )
if result == [ ] :
return self . com... |
def ExportInstance ( r , instance , mode , destination , shutdown = None , remove_instance = None , x509_key_name = None , destination_x509_ca = None ) :
"""Exports an instance .
@ type instance : string
@ param instance : Instance name
@ type mode : string
@ param mode : Export mode
@ rtype : string
@ ... | body = { "destination" : destination , "mode" : mode , }
if shutdown is not None :
body [ "shutdown" ] = shutdown
if remove_instance is not None :
body [ "remove_instance" ] = remove_instance
if x509_key_name is not None :
body [ "x509_key_name" ] = x509_key_name
if destination_x509_ca is not None :
bod... |
def valueAt ( self , point ) :
"""Returns the X , Y value for the given point .
: param point | < QPoint >
: return ( < variant > x , < variant > y )""" | x = point . x ( )
y = point . y ( )
hruler = self . horizontalRuler ( )
vruler = self . verticalRuler ( )
grid = self . _buildData . get ( 'grid_rect' )
if ( not grid ) :
return ( None , None )
x_perc = 1 - ( ( grid . right ( ) - x ) / grid . width ( ) )
y_perc = ( ( grid . bottom ( ) - y ) / grid . height ( ) )
re... |
def _format_arguments ( ctx ) :
"""Format all ` click . Argument ` for a ` click . Command ` .""" | params = [ x for x in ctx . command . params if isinstance ( x , click . Argument ) ]
for param in params :
for line in _format_argument ( param ) :
yield line
yield '' |
def write_slide_list ( self , logname , slides ) :
"""Write list of slides to logfile""" | # Write slides . txt with list of slides
with open ( '%s/%s' % ( self . cache , logname ) , 'w' ) as logfile :
for slide in slides :
heading = slide [ 'heading' ] [ 'text' ]
filename = self . get_image_name ( heading )
print ( '%s,%d' % ( filename , slide . get ( 'time' , 0 ) ) , file = logf... |
def install_package_requirements ( self , psrc , stream_output = None ) :
"""Install from requirements . txt file found in psrc
: param psrc : name of directory in environment directory""" | package = self . target + '/' + psrc
assert isdir ( package ) , package
reqname = '/requirements.txt'
if not exists ( package + reqname ) :
reqname = '/pip-requirements.txt'
if not exists ( package + reqname ) :
return
return self . user_run_script ( script = scripts . get_script_path ( 'install_reqs.sh... |
def is_type_II_branch ( u , v , dfs_data ) :
"""Determines whether a branch uv is a type II branch .""" | if u != a ( v , dfs_data ) :
return False
if u < L2 ( v , dfs_data ) :
return True
return False |
def cancel_job ( self , job_resource_name : str ) :
"""Cancels the given job .
See also the cancel method on EngineJob .
Params :
job _ resource _ name : A string of the form
` projects / project _ id / programs / program _ id / jobs / job _ id ` .""" | self . service . projects ( ) . programs ( ) . jobs ( ) . cancel ( name = job_resource_name , body = { } ) . execute ( ) |
def configure_app ( config_path = None , project = None , default_config_path = None , default_settings = None , settings_initializer = None , settings_envvar = None , initializer = None , allow_extras = True , config_module_name = None , runner_name = None , on_configure = None ) :
""": param project : should repr... | global __configured
project_filename = sanitize_name ( project )
if default_config_path is None :
default_config_path = '~/%s/%s.conf.py' % ( project_filename , project_filename )
if settings_envvar is None :
settings_envvar = project_filename . upper ( ) + '_CONF'
if config_module_name is None :
config_mod... |
def persist ( self , ttl = None , ** kwargs ) :
"""Save data from this source to local persistent storage""" | from . . container import container_map
from . . container . persist import PersistStore
import time
if 'original_tok' in self . metadata :
raise ValueError ( 'Cannot persist a source taken from the persist ' 'store' )
method = container_map [ self . container ] . _persist
store = PersistStore ( )
out = method ( se... |
def match_template_opencv ( template , image , options ) :
"""Match template using OpenCV template matching implementation .
Limited by number of channels as maximum of 3.
Suitable for direct RGB or Gray - scale matching
: param options : Other options :
- distance : Distance measure to use . ( euclidean | ... | # if image has more than 3 channels , use own implementation
if len ( image . shape ) > 3 :
return match_template ( template , image , options )
op = _DEF_TM_OPT . copy ( )
if options is not None :
op . update ( options )
method = cv . TM_CCORR_NORMED
if op [ 'normalize' ] and op [ 'distance' ] == 'euclidean' :... |
def transformer ( grid ) :
"""Choose transformer and add to grid ' s station
Parameters
grid : LVGridDing0
LV grid data""" | # choose size and amount of transformers
transformer , transformer_cnt = select_transformers ( grid )
# create transformers and add them to station of LVGD
for t in range ( 0 , transformer_cnt ) :
lv_transformer = TransformerDing0 ( grid = grid , id_db = id , v_level = 0.4 , s_max_longterm = transformer [ 'S_nom' ]... |
def module_name ( self ) :
"""The module where this route ' s view function was defined .""" | if not self . view_func :
return None
elif self . _controller_cls :
rv = inspect . getmodule ( self . _controller_cls ) . __name__
return rv
return inspect . getmodule ( self . view_func ) . __name__ |
def until_state ( self , state , timeout = None ) :
"""Future that resolves when a certain client state is attained
Parameters
state : str
Desired state , one of ( " disconnected " , " syncing " , " synced " )
timeout : float
Timeout for operation in seconds .""" | return self . _state . until_state ( state , timeout = timeout ) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.