signature stringlengths 29 44.1k | implementation stringlengths 0 85.2k |
|---|---|
def show ( destination , protocol = None , ** kwargs ) : # pylint : disable = unused - argument
'''Displays all details for a certain route learned via a specific protocol .
If the protocol is not specified , will return all possible routes .
. . note : :
This function return the routes from the RIB .
In ca... | return salt . utils . napalm . call ( napalm_device , # pylint : disable = undefined - variable
'get_route_to' , ** { 'destination' : destination , 'protocol' : protocol } ) |
def _job_done_callback ( self , submissionid , task , result , grade , problems , tests , custom , state , archive , stdout , stderr , newsub = True ) :
"""Callback called by Client when a job is done . Updates the submission in the database with the data returned after the completion of the
job""" | submission = self . get_submission ( submissionid , False )
submission = self . get_input_from_submission ( submission )
data = { "status" : ( "done" if result [ 0 ] == "success" or result [ 0 ] == "failed" else "error" ) , # error only if error was made by INGInious
"result" : result [ 0 ] , "grade" : grade , "text" :... |
def get_one_ping_per_client ( pings ) :
"""Returns a single ping for each client in the RDD .
THIS METHOD IS NOT RECOMMENDED : The ping to be returned is essentially
selected at random . It is also expensive as it requires data to be
shuffled around . It should be run only after extracting a subset with
get... | if isinstance ( pings . first ( ) , binary_type ) :
pings = pings . map ( lambda p : json . loads ( p . decode ( 'utf-8' ) ) )
filtered = pings . filter ( lambda p : "clientID" in p or "clientId" in p )
if not filtered :
raise ValueError ( "Missing clientID/clientId attribute." )
if "clientID" in filtered . fir... |
def visit_Call_35 ( self , call ) :
"""visit ` ast . Call ` nodes on Python3.5 and after""" | new_func , func_expl = self . visit ( call . func )
arg_expls = [ ]
new_args = [ ]
new_kwargs = [ ]
for arg in call . args :
res , expl = self . visit ( arg )
arg_expls . append ( expl )
new_args . append ( res )
for keyword in call . keywords :
res , expl = self . visit ( keyword . value )
new_kwar... |
def get_headers_global ( ) :
"""Defines the so - called global column headings for Arbin . res - files""" | headers = dict ( )
# - global column headings ( specific for Arbin )
headers [ "applications_path_txt" ] = 'Applications_Path'
headers [ "channel_index_txt" ] = 'Channel_Index'
headers [ "channel_number_txt" ] = 'Channel_Number'
headers [ "channel_type_txt" ] = 'Channel_Type'
headers [ "comments_txt" ] = 'Comments'
hea... |
def ProcessHuntFlowDone ( flow_obj , status_msg = None ) :
"""Notifis hunt about a given hunt - induced flow completion .""" | if not hunt . IsLegacyHunt ( flow_obj . parent_hunt_id ) :
hunt_obj = hunt . StopHuntIfCPUOrNetworkLimitsExceeded ( flow_obj . parent_hunt_id )
hunt . CompleteHuntIfExpirationTimeReached ( hunt_obj )
return
hunt_urn = rdfvalue . RDFURN ( "hunts" ) . Add ( flow_obj . parent_hunt_id )
client_urn = rdf_client ... |
def count ( self ) :
"""Count the number of distinct results of the wrapped query .
@ return : an L { int } representing the number of distinct results .""" | if not self . query . store . autocommit :
self . query . store . checkpoint ( )
target = ', ' . join ( [ tableClass . storeID . getColumnName ( self . query . store ) for tableClass in self . query . tableClass ] )
sql , args = self . query . _sqlAndArgs ( 'SELECT DISTINCT' , target )
sql = 'SELECT COUNT(*) FROM (... |
def human_id ( self ) :
"""Subclasses may override this to provide a pretty ID which can be used
for bash completion .""" | if self . NAME_ATTR in self . __dict__ and self . HUMAN_ID :
return utils . to_slug ( getattr ( self , self . NAME_ATTR ) )
return None |
def legend_aesthetics ( self , layer , plot ) :
"""Return the aesthetics that contribute to the legend
Parameters
layer : Layer
Layer whose legend is to be drawn
plot : ggplot
Plot object
Returns
matched : list
List of the names of the aethetics that contribute
to the legend .""" | l = layer
legend_ae = set ( self . key . columns ) - { 'label' }
all_ae = ( l . mapping . keys ( ) | ( plot . mapping if l . inherit_aes else set ( ) ) | l . stat . DEFAULT_AES . keys ( ) )
geom_ae = l . geom . REQUIRED_AES | l . geom . DEFAULT_AES . keys ( )
matched = all_ae & geom_ae & legend_ae
matched = list ( matc... |
def get_json_report_object ( self , key ) :
"""Retrieve a JSON report object of the report .
: param key : The key of the report object
: return : The deserialized JSON report object .""" | con = ConnectionManager ( ) . get_connection ( self . _connection_alias )
return con . get_json ( self . json_report_objects [ key ] , append_base_url = False ) |
def get ( self : 'Option[Mapping[K,V]]' , key : K , default = None ) -> 'Option[V]' :
"""Gets a mapping value by key in the contained value or returns
` ` default ` ` if the key doesn ' t exist .
Args :
key : The mapping key .
default : The defauilt value .
Returns :
* ` ` Some ` ` variant of the mappin... | if self . _is_some :
return self . _type . maybe ( self . _val . get ( key , default ) )
return self . _type . maybe ( default ) |
def get_activities_by_ids ( self , activity_ids ) :
"""Gets an ` ` ActivityList ` ` corresponding to the given ` ` IdList ` ` .
In plenary mode , the returned list contains all of the
activities specified in the ` ` Id ` ` list , in the order of the
list , including duplicates , or an error results if an ` ` ... | # Implemented from template for
# osid . resource . ResourceLookupSession . get _ resources _ by _ ids
# NOTE : This implementation currently ignores plenary view
collection = JSONClientValidated ( 'learning' , collection = 'Activity' , runtime = self . _runtime )
object_id_list = [ ]
for i in activity_ids :
object... |
def register ( self ) :
"""Proxy method to register the device with the parent .""" | if not self . registered :
self . registered = True
if self . parent :
self . parent . register ( self ) |
def replace_persistent_volume_status ( self , name , body , ** kwargs ) : # noqa : E501
"""replace _ persistent _ volume _ status # noqa : E501
replace status of the specified PersistentVolume # noqa : E501
This method makes a synchronous HTTP request by default . To make an
asynchronous HTTP request , please... | kwargs [ '_return_http_data_only' ] = True
if kwargs . get ( 'async_req' ) :
return self . replace_persistent_volume_status_with_http_info ( name , body , ** kwargs )
# noqa : E501
else :
( data ) = self . replace_persistent_volume_status_with_http_info ( name , body , ** kwargs )
# noqa : E501
retu... |
def install_packages ( packages , what_for = 'for a complete setup to work properly' ) :
'''Try to install . deb packages given by list .
Return True , if packages could be installed or are installed already , or if
they cannot be installed but the user gives feedback to continue .
Else return False .''' | res = True
non_installed_packages = _non_installed ( packages )
packages_str = ' ' . join ( non_installed_packages )
if non_installed_packages :
with quiet ( ) :
dpkg = _has_dpkg ( )
hint = ' (You may have to install them manually)'
do_install = False
go_on = True
if dpkg :
if _is_... |
def nl_msg_in_handler_debug ( msg , arg ) :
"""https : / / github . com / thom311 / libnl / blob / libnl3_2_25 / lib / handlers . c # L114.""" | ofd = arg or _LOGGER . debug
ofd ( '-- Debug: Received Message:' )
nl_msg_dump ( msg , ofd )
return NL_OK |
def set_color_zones ( self , start_index , end_index , color , duration = 0 , apply = 1 , callb = None , rapid = False ) :
"""Convenience method to set the colour status zone of the device
This method will send a MultiZoneSetColorZones message to the device , and request callb be executed
when an ACK is receive... | if len ( color ) == 4 :
args = { "start_index" : start_index , "end_index" : end_index , "color" : color , "duration" : duration , "apply" : apply , }
mypartial = partial ( self . resp_set_multizonemultizone , args = args )
if callb :
mycallb = lambda x , y : ( mypartial ( y ) , callb ( x , y ) )
... |
def merge ( move , output_dir , sources ) :
"""Merge multiple results folder into one , by copying the results over to a new folder .
For a faster operation ( which on the other hand destroys the campaign data
if interrupted ) , the move option can be used to directly move results to
the new folder .""" | # Get paths for all campaign JSONS
jsons = [ ]
for s in sources :
filename = "%s.json" % os . path . split ( s ) [ 1 ]
jsons += [ os . path . join ( s , filename ) ]
# Check that the configuration for all campaigns is the same
reference_config = TinyDB ( jsons [ 0 ] ) . table ( 'config' )
for j in jsons [ 1 : ]... |
def sort_matches ( matches ) :
'''Sorts a ` ` list ` ` of matches best to worst''' | multipliers = { 'exact' : 10 ** 5 , 'fname' : 10 ** 4 , 'fuzzy' : 10 ** 2 , 'fuzzy_fragment' : 1 }
matches = [ ( multipliers [ x . type ] * ( x . amount if x . amount else 1 ) , x ) for x in matches ]
return [ x [ 1 ] for x in sorted ( matches , reverse = True ) ] |
def set_footer ( self , * , text = EmptyEmbed , icon_url = EmptyEmbed ) :
"""Sets the footer for the embed content .
This function returns the class instance to allow for fluent - style
chaining .
Parameters
text : : class : ` str `
The footer text .
icon _ url : : class : ` str `
The URL of the foote... | self . _footer = { }
if text is not EmptyEmbed :
self . _footer [ 'text' ] = str ( text )
if icon_url is not EmptyEmbed :
self . _footer [ 'icon_url' ] = str ( icon_url )
return self |
def django_main ( server_getter ) :
"""Call this within ` _ _ main _ _ ` to start the service as a standalone server with Django support . Your server should have
` use _ django = True ` . If it does not , see ` simple _ main ` , instead .
: param server _ getter : A callable that returns the service ' s ` Serv... | import os
# noinspection PyUnresolvedReferences , PyPackageRequirements
import django
parser = _get_arg_parser ( )
parser . add_argument ( '-s' , '--settings' , help = 'The settings module to use (must be importable)' , required = 'DJANGO_SETTINGS_MODULE' not in os . environ , # if env var does not exist , this argumen... |
def _connect ( self , target , listen , udp , ipv6 , retry ) :
"""Takes target / listen / udp / ipv6 and sets self . sock and self . peer""" | ty = socket . SOCK_DGRAM if udp else socket . SOCK_STREAM
fam = socket . AF_INET6 if ipv6 else socket . AF_INET
self . sock = socket . socket ( fam , ty )
if listen :
self . sock . setsockopt ( socket . SOL_SOCKET , socket . SO_REUSEADDR , 1 )
self . sock . bind ( target )
if not udp :
self . sock .... |
def findAndHandleDeadJobs ( cls , nodeInfo , batchSystemShutdown = False ) :
"""Look at the state of all jobs registered in the individual job state files , and handle them
( clean up the disk , and run any registered defer functions )
: param str nodeInfo : The location of the workflow directory on the node . ... | # A list of tuples of ( job name , pid or process running job , registered defer functions )
for jobState in cls . _getAllJobStates ( nodeInfo ) :
if not cls . _pidExists ( jobState [ 'jobPID' ] ) : # using same logic to prevent races as CachingFileStore . _ setupCache
myPID = str ( os . getpid ( ) )
... |
def get_stats ( self ) :
"""Get received / dropped statistics""" | try :
ret = fcntl . ioctl ( self . ins , BIOCGSTATS , struct . pack ( "2I" , 0 , 0 ) )
return struct . unpack ( "2I" , ret )
except IOError :
warning ( "Unable to get stats from BPF !" )
return ( None , None ) |
def BinarySigmoid ( self , func ) :
'''Currently , caffe2 does not support this function .''' | n = onnx . helper . make_node ( 'HardSigmoid' , func . input , func . output , alpha = 1.0 , beta = 0.0 )
return [ n ] |
def list_pkgs ( * packages , ** kwargs ) :
'''List the packages currently installed in a dict : :
{ ' < package _ name > ' : ' < version > ' }
External dependencies : :
Virtual package resolution requires aptitude . Because this function
uses dpkg , virtual packages will be reported as not installed .
CLI... | pkgs = { }
cmd = 'dpkg -l {0}' . format ( ' ' . join ( packages ) )
out = __salt__ [ 'cmd.run_all' ] ( cmd , python_shell = False )
if out [ 'retcode' ] != 0 :
msg = 'Error: ' + out [ 'stderr' ]
log . error ( msg )
return msg
out = out [ 'stdout' ]
for line in out . splitlines ( ) :
if line . startswit... |
def hash_file ( filepath : str ) -> str :
"""Return the hexdigest MD5 hash of content of file at ` filepath ` .""" | md5 = hashlib . md5 ( )
acc_hash ( filepath , md5 )
return md5 . hexdigest ( ) |
def entrez_sets_of_results ( url , retstart = False , retmax = False , count = False ) -> Optional [ List [ requests . Response ] ] :
"""Gets sets of results back from Entrez .
Entrez can only return 500 results at a time . This creates a generator that gets results by incrementing
retstart and retmax .
Param... | if not retstart :
retstart = 0
if not retmax :
retmax = 500
if not count :
count = retmax
retmax = 500
# Entrez can return a max of 500
while retstart < count :
diff = count - retstart
if diff < 500 :
retmax = diff
_url = url + f'&retstart={retstart}&retmax={retmax}'
resp = entrez_tr... |
def get_count ( self , instance ) :
"""Haystack facets are returned as a two - tuple ( value , count ) .
The count field should contain the faceted count .""" | instance = instance [ 1 ]
return serializers . IntegerField ( read_only = True ) . to_representation ( instance ) |
def listens_to ( name , sender = None , weak = True ) :
"""Listens to a named signal""" | def decorator ( f ) :
if sender :
return signal ( name ) . connect ( f , sender = sender , weak = weak )
return signal ( name ) . connect ( f , weak = weak )
return decorator |
def encrypt_password ( self ) :
"""encrypt password if not already encrypted""" | if self . password and not self . password . startswith ( '$pbkdf2' ) :
self . set_password ( self . password ) |
def load_yaml ( filepath ) :
"""Convenience function for loading yaml - encoded data from disk .""" | with open ( filepath ) as f :
txt = f . read ( )
return yaml . load ( txt ) |
def stop ( self , failover = False ) :
"""Stops the scheduler driver .
If the ' failover ' flag is set to False then it is expected that this
framework will never reconnect to Mesos and all of its executors and
tasks can be terminated . Otherwise , all executors and tasks will
remain running ( for some fram... | logging . info ( 'Stops Scheduler Driver' )
return self . driver . stop ( failover ) |
def iteration ( self , node_status = True ) :
"""Execute a single model iteration
: return : Iteration _ id , Incremental node status ( dictionary node - > status )""" | self . clean_initial_status ( self . available_statuses . values ( ) )
actual_status = { node : nstatus for node , nstatus in future . utils . iteritems ( self . status ) }
# streaming
if self . stream_execution :
raise ValueError ( "Streaming network not allowed." )
# snapshot
else :
if self . actual_iteration... |
def make_list ( obj , cast = True ) :
"""Converts an object * obj * to a list and returns it . Objects of types * tuple * and * set * are
converted if * cast * is * True * . Otherwise , and for all other types , * obj * is put in a new list .""" | if isinstance ( obj , list ) :
return list ( obj )
elif is_lazy_iterable ( obj ) :
return list ( obj )
elif isinstance ( obj , ( tuple , set ) ) and cast :
return list ( obj )
else :
return [ obj ] |
def weight_list_to_tuple ( data , attr_name ) :
'''Converts a list of values and corresponding weights to a tuple of values''' | if len ( data [ 'Value' ] ) != len ( data [ 'Weight' ] ) :
raise ValueError ( 'Number of weights do not correspond to number of ' 'attributes in %s' % attr_name )
weight = np . array ( data [ 'Weight' ] )
if fabs ( np . sum ( weight ) - 1. ) > 1E-7 :
raise ValueError ( 'Weights do not sum to 1.0 in %s' % attr_n... |
def _get_funcs ( self ) :
"""Returns a 32 - bit value stating supported I2C functions .
: rtype : int""" | f = c_uint32 ( )
ioctl ( self . fd , I2C_FUNCS , f )
return f . value |
def get_authuser_by_userid ( cls , request ) :
"""Get user by ID .
Used by Ticket - based auth . Is added as request method to populate
` request . user ` .""" | userid = authenticated_userid ( request )
if userid :
cache_request_user ( cls , request , userid )
return request . _user |
def normalize ( self , inplace = True ) :
"""Normalizes the pdf of the continuous factor so that it integrates to
1 over all the variables .
Parameters
inplace : boolean
If inplace = True it will modify the factor itself , else would return
a new factor .
Returns
ContinuousFactor or None :
if inplac... | phi = self if inplace else self . copy ( )
phi . distriution = phi . distribution . normalize ( inplace = False )
if not inplace :
return phi |
def get_repository_hierarchy_design_session ( self , proxy ) :
"""Gets the repository hierarchy design session .
arg proxy ( osid . proxy . Proxy ) : a proxy
return : ( osid . repository . RepositoryHierarchyDesignSession ) - a
RepostoryHierarchyDesignSession
raise : OperationFailed - unable to complete req... | if not self . supports_repository_hierarchy_design ( ) :
raise Unimplemented ( )
try :
from . import sessions
except ImportError :
raise
# OperationFailed ( )
proxy = self . _convert_proxy ( proxy )
try :
session = sessions . RepositoryHierarchyDesignSession ( proxy , runtime = self . _runtime )
exc... |
def draw_capitan_score_bitmap ( self , export_path : ExportPath ) -> None :
"""Draws the 30x30 symbol into the given file
: param export _ path : The path , where the symbols should be created on disk""" | with Image . fromarray ( self . image_data , mode = 'L' ) as image :
image . save ( export_path . get_full_path ( ) ) |
def _ParseRecord ( self , parser_mediator , page_data , record_offset ) :
"""Parses a record from the page data .
Args :
parser _ mediator ( ParserMediator ) : parser mediator .
page _ data ( bytes ) : page data .
record _ offset ( int ) : offset of the record relative to the start
of the page .
Raises ... | record_header_map = self . _GetDataTypeMap ( 'binarycookies_record_header' )
try :
record_header = self . _ReadStructureFromByteStream ( page_data [ record_offset : ] , record_offset , record_header_map )
except ( ValueError , errors . ParseError ) as exception :
raise errors . ParseError ( ( 'Unable to map rec... |
def users_set_preferences ( self , user_id , data , ** kwargs ) :
"""Set user ’ s preferences .""" | return self . __call_api_post ( 'users.setPreferences' , userId = user_id , data = data , kwargs = kwargs ) |
def _write_comid_lat_lon_z ( self ) :
"""Add latitude , longitude , and z values for each netCDF feature
Remarks :
Lookup table is a CSV file with COMID , Lat , Lon ,
and Elev _ m columns .
Columns must be in that order and these must be the first
four columns .""" | # only add if user adds
if self . comid_lat_lon_z_file and os . path . exists ( self . comid_lat_lon_z_file ) : # get list of COMIDS
lookup_table = csv_to_list ( self . comid_lat_lon_z_file )
lookup_comids = np . array ( [ int ( float ( row [ 0 ] ) ) for row in lookup_table [ 1 : ] ] )
# Get relevant arrays... |
def copy_meta_from ( self , ido ) :
"""Copies vtki meta data onto this object from another object""" | self . _active_scalar_info = ido . active_scalar_info
self . _active_vectors_info = ido . active_vectors_info
if hasattr ( ido , '_textures' ) :
self . _textures = ido . _textures |
def _get_attribute_value_of ( resource , attribute_name , default = None ) :
"""Gets the value of attribute _ name from the resource
It catches the exception , if any , while retrieving the
value of attribute _ name from resource and returns default .
: param resource : The resource object
: attribute _ nam... | try :
return getattr ( resource , attribute_name )
except ( sushy . exceptions . SushyError , exception . MissingAttributeError ) as e :
msg = ( ( 'The Redfish controller failed to get the ' 'attribute %(attribute)s from resource %(resource)s. ' 'Error %(error)s' ) % { 'error' : str ( e ) , 'attribute' : attrib... |
def mutualReceptions ( self , idA , idB ) :
"""Returns all pairs of dignities in mutual reception .""" | AB = self . receives ( idA , idB )
BA = self . receives ( idB , idA )
# Returns a product of both lists
return [ ( a , b ) for a in AB for b in BA ] |
def parents ( self , node ) :
"""Determine all parents of node in our tree""" | return [ parent for parent in getattr ( node , 'parents' , [ ] ) if getattr ( parent , 'tree' , self . TREE ) == self . TREE ] |
def apply ( self , function ) :
"""Applies a function on the value , the actual stored value will not change .
: param function : ( Function ) , A stateful serializable object which represents the Function defined on
server side .
This object must have a serializable Function counter part registered on server... | check_not_none ( function , "function can't be None" )
return self . _encode_invoke ( atomic_reference_apply_codec , function = self . _to_data ( function ) ) |
def __log_density_single ( x , mean , covar ) :
"""This is just a test function to calculate
the normal density at x given mean and covariance matrix .
Note : this function is not efficient , so
_ log _ multivariate _ density is recommended for use .""" | n_dim = mean . shape [ 0 ]
dx = x - mean
covar_inv = scipy . linalg . inv ( covar )
covar_det = scipy . linalg . det ( covar )
den = np . dot ( np . dot ( dx . T , covar_inv ) , dx ) + n_dim * np . log ( 2 * np . pi ) + np . log ( covar_det )
return ( - 1 / 2 * den ) |
def _get_request_content ( self , message = None ) :
'''Updates all messages in message with default message
parameters .
: param message : A collection of Postmark message data
: type message : a collection of message ` dict ` s
: rtype : JSON encoded ` str `''' | if not message :
raise MessageError ( 'No messages to send.' )
if len ( message ) > MAX_BATCH_MESSAGES :
err = 'Maximum {0} messages allowed in batch'
raise MessageError ( err . format ( MAX_BATCH_MESSAGES ) )
message = [ self . _cast_message ( message = msg ) for msg in message ]
message = [ msg . data ( )... |
def future_request ( self , msg , timeout = None , use_mid = None ) :
"""Send a request messsage , with future replies .
Parameters
msg : Message object
The request Message to send .
timeout : float in seconds
How long to wait for a reply . The default is the
the timeout set when creating the AsyncClien... | mid = self . _get_mid_and_update_msg ( msg , use_mid )
if msg . name in self . request_handlers :
req = FakeClientRequestConnection ( self . client_connection , msg )
reply_msg = yield tornado . gen . maybe_future ( self . request_handlers [ msg . name ] ( req , msg ) )
reply_informs = req . informs_sent
el... |
def _outer_to_numpy_indexer ( key , shape ) :
"""Convert an OuterIndexer into an indexer for NumPy .
Parameters
key : Basic / OuterIndexer
An indexer to convert .
shape : tuple
Shape of the array subject to the indexing .
Returns
tuple
Tuple suitable for use to index a NumPy array .""" | if len ( [ k for k in key . tuple if not isinstance ( k , slice ) ] ) <= 1 : # If there is only one vector and all others are slice ,
# it can be safely used in mixed basic / advanced indexing .
# Boolean index should already be converted to integer array .
return key . tuple
else :
return _outer_to_vectorized_... |
def set_security_zones_activation ( self , internal = True , external = True ) :
"""this function will set the alarm system to armed or disable it
Args :
internal ( bool ) : activates / deactivates the internal zone
external ( bool ) : activates / deactivates the external zone
Examples :
arming while bein... | data = { "zonesActivation" : { "EXTERNAL" : external , "INTERNAL" : internal } }
return self . _restCall ( "home/security/setZonesActivation" , json . dumps ( data ) ) |
def _make_absolute ( self , link ) :
"""Makes a given link absolute .""" | # Parse the link with stdlib .
parsed = urlparse ( link ) . _asdict ( )
# If link is relative , then join it with base _ url .
if not parsed [ 'netloc' ] :
return urljoin ( self . base_url , link )
# Link is absolute ; if it lacks a scheme , add one from base _ url .
if not parsed [ 'scheme' ] :
parsed [ 'schem... |
def glob ( self , pathname , ondisk = True , source = False , strings = False , exclude = None ) :
"""Returns a list of Nodes ( or strings ) matching a specified
pathname pattern .
Pathname patterns follow UNIX shell semantics : * matches
any - length strings of any characters , ? matches any character ,
an... | dirname , basename = os . path . split ( pathname )
if not dirname :
result = self . _glob1 ( basename , ondisk , source , strings )
else :
if has_glob_magic ( dirname ) :
list = self . glob ( dirname , ondisk , source , False , exclude )
else :
list = [ self . Dir ( dirname , create = True ... |
def _walk ( recursion ) :
"""Returns a recursive or non - recursive directory walker""" | try :
from scandir import walk as walk_function
except ImportError :
from os import walk as walk_function
if recursion :
walk = partial ( walk_function )
else :
def walk ( path ) : # pylint : disable = C0111
try :
yield next ( walk_function ( path ) )
except NameError :
... |
def calc_cost ( self , node_a , node_b ) :
"""get the distance between current node and the neighbor ( cost )""" | if node_b . x - node_a . x == 0 or node_b . y - node_a . y == 0 : # direct neighbor - distance is 1
ng = 1
else : # not a direct neighbor - diagonal movement
ng = SQRT2
# weight for weighted algorithms
if self . weighted :
ng *= node_b . weight
return node_a . g + ng |
def get_db_uri ( config , output_dir ) :
"""Process results _ database parameters in config to format them for
set database function
: param dict config : project configuration dict
: param str output _ dir : output directory for results
: return : string for db uri""" | db_config = config . get ( "results_database" , { "db_uri" : "default" } )
if db_config [ 'db_uri' ] == 'default' :
return os . path . join ( output_dir , "results.sqlite" )
return db_config [ 'db_uri' ] |
def cons ( f , mindepth ) :
"""Makes a list of lists of reads at each site""" | C = ClustFile ( f )
for data in C :
names , seqs , nreps = zip ( * data )
total_nreps = sum ( nreps )
# Depth filter
if total_nreps < mindepth :
continue
S = [ ]
for name , seq , nrep in data : # Append sequence * number of dereps
S . append ( [ seq , nrep ] )
# Make list for... |
def _getOpenChoices ( self ) :
"""Go through all possible sites to find applicable . cfg files .
Return as an iterable .""" | tsk = self . _taskParsObj . getName ( )
taskFiles = set ( )
dirsSoFar = [ ]
# this helps speed this up ( skip unneeded globs )
# last dir
aDir = os . path . dirname ( self . _taskParsObj . filename )
if len ( aDir ) < 1 :
aDir = os . curdir
dirsSoFar . append ( aDir )
taskFiles . update ( cfgpars . getCfgFilesInDir... |
def get_sidecar_nodes ( self ) -> Iterator [ PostSidecarNode ] :
"""Sidecar nodes of a Post with typename = = GraphSidecar .""" | if self . typename == 'GraphSidecar' :
for edge in self . _field ( 'edge_sidecar_to_children' , 'edges' ) :
node = edge [ 'node' ]
is_video = node [ 'is_video' ]
yield PostSidecarNode ( is_video = is_video , display_url = node [ 'display_url' ] , video_url = node [ 'video_url' ] if is_video ... |
def scrape ( self , selector , cleaner = None , processor = None ) :
"""Scrape the value for this field from the selector .""" | # Apply CSS or XPath expression to the selector
selected = selector . xpath ( self . selection ) if self . xpath else selector . css ( self . selection )
# Extract the value and apply regular expression if specified
value = selected . re ( self . re ) if self . re else selected . extract ( raw = self . raw , cleaner = ... |
def _gatherUpdatedJobs ( self , updatedJobTuple ) :
"""Gather any new , updated jobGraph from the batch system""" | jobID , result , wallTime = updatedJobTuple
# easy , track different state
try :
updatedJob = self . jobBatchSystemIDToIssuedJob [ jobID ]
except KeyError :
logger . warn ( "A result seems to already have been processed " "for job %s" , jobID )
else :
if result == 0 :
cur_logger = ( logger . debug i... |
def unsubscribe ( self , message , handler ) :
'''Removes handler from message listeners .
: param str message :
Name of message to unsubscribe handler from .
: param callable handler :
Callable that should be removed as handler for ` message ` .''' | with self . _lock :
self . _subscribers [ message ] . remove ( WeakCallable ( handler ) ) |
def all_finite ( self , X ) :
"""returns true if X is finite , false , otherwise""" | # Adapted from sklearn utils : _ assert _ all _ finite ( X )
# First try an O ( n ) time , O ( 1 ) space solution for the common case that
# everything is finite ; fall back to O ( n ) space np . isfinite to prevent
# false positives from overflow in sum method .
# Note : this is basically here because sklearn tree . p... |
def construct_getatt ( node ) :
"""Reconstruct ! GetAtt into a list""" | if isinstance ( node . value , six . text_type ) :
return node . value . split ( "." , 1 )
elif isinstance ( node . value , list ) :
return [ s . value for s in node . value ]
else :
raise ValueError ( "Unexpected node type: {}" . format ( type ( node . value ) ) ) |
def get_request_token ( self ) :
"""Return the request token for this API . If we ' ve not fetched it yet ,
go out , request and memoize it .""" | if self . _request_token is None :
self . _request_token = self . _get_request_token ( )
return self . _request_token |
def NewFromHtml ( html , alpha = 1.0 , wref = _DEFAULT_WREF ) :
'''Create a new instance based on the specifed HTML color definition .
Parameters :
: html :
The HTML definition of the color ( # RRGGBB or # RGB or a color name ) .
: alpha :
The color transparency [ 0 . . . 1 ] , default is opaque .
: wre... | return Color ( Color . HtmlToRgb ( html ) , 'rgb' , alpha , wref ) |
def open_remote_url ( urls , ** kwargs ) :
"""Open the url and check that it stores a file .
Args :
: urls : Endpoint to take the file""" | if isinstance ( urls , str ) :
urls = [ urls ]
for url in urls :
try :
web_file = requests . get ( url , stream = True , ** kwargs )
if 'html' in web_file . headers [ 'content-type' ] :
raise ValueError ( "HTML source file retrieved." )
return web_file
except Exception as... |
async def _connect_sentinel ( self , address , timeout , pools ) :
"""Try to connect to specified Sentinel returning either
connections pool or exception .""" | try :
with async_timeout ( timeout , loop = self . _loop ) :
pool = await create_pool ( address , minsize = 1 , maxsize = 2 , parser = self . _parser_class , loop = self . _loop )
pools . append ( pool )
return pool
except asyncio . TimeoutError as err :
sentinel_logger . debug ( "Failed to conn... |
def show ( self , viewer = None , ** kwargs ) :
"""Display the current scene .
Parameters
viewer : str ' gl ' : open a pyglet window
str , ' notebook ' : return ipython . display . HTML
None : automatically pick based on whether or not
we are in an ipython notebook
smooth : bool
Turn on or off automat... | if viewer is None : # check to see if we are in a notebook or not
from . . viewer import in_notebook
viewer = [ 'gl' , 'notebook' ] [ int ( in_notebook ( ) ) ]
if viewer == 'gl' : # this imports pyglet , and will raise an ImportError
# if pyglet is not available
from . . viewer import SceneViewer
return... |
def getWorkingCollisionBoundsInfo ( self ) :
"""Returns the number of Quads if the buffer points to null . Otherwise it returns Quads
into the buffer up to the max specified from the working copy .""" | fn = self . function_table . getWorkingCollisionBoundsInfo
pQuadsBuffer = HmdQuad_t ( )
punQuadsCount = c_uint32 ( )
result = fn ( byref ( pQuadsBuffer ) , byref ( punQuadsCount ) )
return result , pQuadsBuffer , punQuadsCount . value |
def setStyle ( self , styleName , styleValue ) :
'''setStyle - Sets a style param . Example : " display " , " block "
If you need to set many styles on an element , use setStyles instead .
It takes a dictionary of attribute , value pairs and applies it all in one go ( faster )
To remove a style , set its valu... | myAttributes = self . _attributes
if 'style' not in myAttributes :
myAttributes [ 'style' ] = "%s: %s" % ( styleName , styleValue )
else :
setattr ( myAttributes [ 'style' ] , styleName , styleValue ) |
def target_internal_dependencies ( target ) :
"""Returns internal Jarable dependencies that were " directly " declared .
Directly declared deps are those that are explicitly listed in the definition of a
target , rather than being depended on transitively . But in order to walk through
aggregator targets such... | for dep in target . dependencies :
if isinstance ( dep , Jarable ) :
yield dep
else :
for childdep in target_internal_dependencies ( dep ) :
yield childdep |
def unescape_single_character ( match ) :
"""Unescape a single escape sequence found from a MySQL string literal ,
according to the rules defined at :
https : / / dev . mysql . com / doc / refman / 5.6 / en / string - literals . html # character - escape - sequences
: param match : Regular expression match ob... | value = match . group ( 0 )
assert value . startswith ( "\\" )
return MYSQL_STRING_ESCAPE_SEQUENCE_MAPPING . get ( value ) or value [ 1 : ] |
def set_default_region ( self , region ) :
"""This sets the default region for detecting license plates . For example ,
setting region to " md " for Maryland or " fr " for France .
: param region : A unicode / ascii string ( Python 2/3 ) or bytes array ( Python 3)
: return : None""" | region = _convert_to_charp ( region )
self . _set_default_region_func ( self . alpr_pointer , region ) |
def prepare_destruction ( self ) :
"""Get rid of circular references""" | self . _tool = None
self . _painter = None
self . relieve_model ( self . _selection )
self . _selection = None
# clear observer class attributes , also see ExtendenController . destroy ( )
self . _Observer__PROP_TO_METHS . clear ( )
self . _Observer__METH_TO_PROPS . clear ( )
self . _Observer__PAT_TO_METHS . clear ( )
... |
def draw ( self ) :
"""Draws the image at the given location .""" | if not self . visible :
return
self . window . blit ( self . image , self . loc ) |
def _maxscore ( self ) :
"""m . _ maxscore ( ) - - Sets self . maxscore and self . minscore""" | total = 0
lowtot = 0
for lli in self . ll :
total = total + max ( lli . values ( ) )
lowtot = lowtot + min ( lli . values ( ) )
self . maxscore = total
self . minscore = lowtot |
def save_model ( ) :
"""Save cnn model
Returns
callback : A callback function that can be passed as epoch _ end _ callback to fit""" | if not os . path . exists ( "checkpoint" ) :
os . mkdir ( "checkpoint" )
return mx . callback . do_checkpoint ( "checkpoint/checkpoint" , args . save_period ) |
def cells ( self ) :
'''Returns an interator of all cells in the table .''' | for line in self . text . splitlines ( ) :
for cell in self . getcells ( line ) :
yield cell |
def universal_extract_paragraphs ( xml ) :
"""Extract paragraphs from xml that could be from different sources
First try to parse the xml as if it came from elsevier . if we do not
have valid elsevier xml this will throw an exception . the text extraction
function in the pmc client may not throw an exception ... | try :
paragraphs = elsevier_client . extract_paragraphs ( xml )
except Exception :
paragraphs = None
if paragraphs is None :
try :
paragraphs = pmc_client . extract_paragraphs ( xml )
except Exception :
paragraphs = [ xml ]
return paragraphs |
def on_backward_end ( self , ** kwargs : Any ) -> None :
"Convert the gradients back to FP32 and divide them by the scale ." | if self . dynamic and grad_overflow ( self . model_params ) and self . loss_scale > 1 :
self . loss_scale /= 2
self . noskip = 0
# The step will be skipped since we don ' t update the master grads so they are all None or zero
else :
model_g2master_g ( self . model_params , self . master_params , self . ... |
def upload_plugin ( self , plugin_path ) :
"""Provide plugin path for upload into Jira e . g . useful for auto deploy
: param plugin _ path :
: return :""" | files = { 'plugin' : open ( plugin_path , 'rb' ) }
headers = { 'X-Atlassian-Token' : 'nocheck' }
upm_token = self . request ( method = 'GET' , path = 'rest/plugins/1.0/' , headers = headers , trailing = True ) . headers [ 'upm-token' ]
url = 'rest/plugins/1.0/?token={upm_token}' . format ( upm_token = upm_token )
retur... |
def UV_B ( self ) :
"""returns UV = all respected U - > Ux in ternary coding ( 1 = V , 2 = U )""" | h = reduce ( lambda x , y : x & y , ( B ( g , self . width - 1 ) for g in self ) )
return UV_B ( h , self . width ) |
def get_elections ( self , obj ) :
"""All elections on an election day .""" | election_day = ElectionDay . objects . get ( date = self . context [ 'election_date' ] )
elections = Election . objects . filter ( race__office = obj , election_day = election_day )
return ElectionSerializer ( elections , many = True ) . data |
def struct ( self ) :
"""XML - RPC - friendly representation of the current object state""" | data = { }
for var , fmap in self . _def . items ( ) :
if hasattr ( self , var ) :
data . update ( fmap . get_outputs ( getattr ( self , var ) ) )
return data |
def load ( hdf5_file_name , data , minPts , eps = None , quantile = 50 , subsamples_matrix = None , samples_weights = None , metric = 'minkowski' , p = 2 , verbose = True ) :
"""Determines the radius ' eps ' for DBSCAN clustering of ' data ' in an adaptive , data - dependent way .
Parameters
hdf5 _ file _ name ... | data = np . array ( data , copy = False )
if data . ndim > 2 :
raise ValueError ( "\nERROR: DBSCAN_multiplex @ load:\n" "the data array is of dimension %d. Please provide a two-dimensional " "array instead.\n" % data . ndim )
if subsamples_matrix is None :
subsamples_matrix = np . arange ( data . shape [ 0 ] , ... |
def get_group ( self , uuid = None ) :
"""Get group data based on uuid .
Args :
uuid ( str ) : optional uuid . defaults to self . cuuid
Raises :
PyLmodUnexpectedData : No data was returned .
requests . RequestException : Exception connection error
Returns :
dict : group json""" | if uuid is None :
uuid = self . uuid
group_data = self . get ( 'group' , params = { 'uuid' : uuid } )
return group_data |
def contains ( bank , key ) :
'''Checks if the specified bank contains the specified key .''' | if key is None :
return True
# any key could be a branch and a leaf at the same time in Consul
else :
try :
c_key = '{0}/{1}' . format ( bank , key )
_ , value = api . kv . get ( c_key )
except Exception as exc :
raise SaltCacheError ( 'There was an error getting the key, {0}: {1... |
def get ( path ) :
'''Get the content of the docker - compose file into a directory
path
Path where the docker - compose file is stored on the server
CLI Example :
. . code - block : : bash
salt myminion dockercompose . get / path / where / docker - compose / stored''' | file_path = __get_docker_file_path ( path )
if file_path is None :
return __standardize_result ( False , 'Path {} is not present' . format ( path ) , None , None )
salt_result = __read_docker_compose_file ( file_path )
if not salt_result [ 'status' ] :
return salt_result
project = __load_project ( path )
if isi... |
def extensions ( ) :
"""How do we handle cython :
1 . when on git , require cython during setup time ( do not distribute
generated . c files via git )
a ) cython present - > fine
b ) no cython present - > install it on the fly . Extensions have to have . pyx suffix
This is solved via a lazy evaluation of ... | USE_CYTHON = False
try :
from Cython . Build import cythonize
USE_CYTHON = True
except ImportError :
warnings . warn ( 'Cython not found. Using pre cythonized files.' )
import mdtraj
# Note , that we add numpy include to every extension after declaration .
from numpy import get_include as _np_inc
np_inc = _... |
def _get_config_file_path ( xdg_config_dir , xdg_config_file ) :
"""Search ` ` XDG _ CONFIG _ DIRS ` ` for a config file and return the first found .
Search each of the standard XDG configuration directories for a
configuration file . Return as soon as a configuration file is found . Beware
that by the time c... | for config_dir in BaseDirectory . load_config_paths ( xdg_config_dir ) :
path = join ( config_dir , xdg_config_file )
if isfile ( path ) :
return path
raise ConfigFileError ( 'No configuration files could be located after searching for a file ' 'named "{0}" in the standard XDG configuration paths, such ... |
def download_file_job ( entry , directory , checksums , filetype = 'genbank' , symlink_path = None ) :
"""Generate a DownloadJob that actually triggers a file download .""" | pattern = NgdConfig . get_fileending ( filetype )
filename , expected_checksum = get_name_and_checksum ( checksums , pattern )
base_url = convert_ftp_url ( entry [ 'ftp_path' ] )
full_url = '{}/{}' . format ( base_url , filename )
local_file = os . path . join ( directory , filename )
full_symlink = None
if symlink_pat... |
def _get_masses ( fitnesses ) :
"""Convert fitnesses into masses , as given by GSA algorithm .""" | # Obtain constants
best_fitness = max ( fitnesses )
worst_fitness = min ( fitnesses )
fitness_range = best_fitness - worst_fitness
# Calculate raw masses for each solution
raw_masses = [ ]
for fitness in fitnesses : # Epsilon is added to prevent divide by zero errors
raw_masses . append ( ( fitness - worst_fitness ... |
def get_command ( self , pure = False ) :
"""Get command from message
: return :""" | command = self . get_full_command ( )
if command :
command = command [ 0 ]
if pure :
command , _ , _ = command [ 1 : ] . partition ( '@' )
return command |
def setup ( addr , user , remote_path , local_key = None ) :
"""Setup the tunnel""" | port = find_port ( addr , user )
if not port or not is_alive ( addr , user ) :
port = new_port ( )
scp ( addr , user , __file__ , '~/unixpipe' , local_key )
ssh_call = [ 'ssh' , '-fL%d:127.0.0.1:12042' % port , '-o' , 'ExitOnForwardFailure=yes' , '-o' , 'ControlPath=~/.ssh/unixpipe_%%r@%%h_%d' % port , '-o'... |
def autoLayoutSelected ( self , padX = None , padY = None , direction = Qt . Horizontal , layout = 'Layered' , animate = 0 , centerOn = None , center = None ) :
"""Automatically lays out all the selected nodes in the scene using the autoLayoutNodes method .
: param padX | < int > | | None | default is 2 * cell wi... | nodes = self . selectedNodes ( )
return self . autoLayoutNodes ( nodes , padX , padY , direction , layout , animate , centerOn , center ) |
def is_compatible ( self ) :
'''Is the wheel is compatible with the current platform ?''' | supported_tags = pep425tags . get_supported ( )
return next ( ( True for t in self . tags ( ) if t in supported_tags ) , False ) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.