signature stringlengths 29 44.1k | implementation stringlengths 0 85.2k |
|---|---|
def _get_local_dirs ( sub ) :
"""Get all the directories""" | path = os . environ . get ( "SPARK_LOCAL_DIRS" , "/tmp" )
dirs = path . split ( "," )
if len ( dirs ) > 1 : # different order in different processes and instances
rnd = random . Random ( os . getpid ( ) + id ( dirs ) )
random . shuffle ( dirs , rnd . random )
return [ os . path . join ( d , "python" , str ( os ... |
def ihfft ( a , n = None , axis = - 1 , norm = None ) :
"""Compute the inverse FFT of a signal which has Hermitian symmetry .
Parameters
a : array _ like
Input array .
n : int , optional
Length of the inverse FFT .
Number of points along transformation axis in the input to use .
If ` n ` is smaller th... | # The copy may be required for multithreading .
a = array ( a , copy = True , dtype = float )
if n is None :
n = a . shape [ axis ]
unitary = _unitary ( norm )
output = conjugate ( rfft ( a , n , axis ) )
return output * ( 1 / ( sqrt ( n ) if unitary else n ) ) |
def hex ( self ) :
"""Hexideciaml representation of the message in bytes .""" | props = self . _message_properties ( )
msg = bytearray ( [ MESSAGE_START_CODE_0X02 , self . _code ] )
for prop in props : # pylint : disable = unused - variable
for key , val in prop . items ( ) :
if val is None :
pass
elif isinstance ( val , int ) :
msg . append ( val )
... |
def probe_plate ( self ) -> str :
'''Probes for the deck plate and calculates the plate distance
from home .
To be used for calibrating MagDeck''' | self . run_flag . wait ( )
try :
self . _send_command ( GCODES [ 'PROBE_PLATE' ] )
except ( MagDeckError , SerialException , SerialNoResponse ) as e :
return str ( e )
return '' |
def _generate ( self , func ) :
"""Generate a population of : math : ` \ lambda ` individuals .
Notes
Individuals are of type * ind _ init * from the current strategy .
Parameters
ind _ init :
A function object that is able to initialize an
individual from a list .""" | arz = numpy . random . standard_normal ( ( self . lambda_ , self . dim ) )
arz = self . centroid + self . sigma * numpy . dot ( arz , self . BD . T )
self . population = list ( map ( func , arz ) )
return |
def get_header_by_name ( self , hdrname ) :
'''Return the header object that has the given ( string ) header
class name . Returns None if no such header exists .''' | for hdr in self . _headers :
if hdr . __class__ . __name__ == hdrname :
return hdr
return None |
def get_minkowski_red ( structure ) :
"""Get a minkowski reduced structure""" | output = run_aconvasp_command ( [ "aconvasp" , "--kpath" ] , structure )
started = False
poscar_string = ""
if "ERROR" in output [ 1 ] :
raise AconvaspError ( output [ 1 ] )
for line in output [ 0 ] . split ( "\n" ) :
if started or line . find ( "KPOINTS TO RUN" ) != - 1 :
poscar_string = poscar_string ... |
def get_gradebook_column_lookup_session ( self , proxy ) :
"""Gets the ` ` OsidSession ` ` associated with the gradebook column lookup service .
arg : proxy ( osid . proxy . Proxy ) : a proxy
return : ( osid . grading . GradebookColumnLookupSession ) - a
` ` GradebookColumnLookupSession ` `
raise : NullArgu... | if not self . supports_gradebook_column_lookup ( ) :
raise errors . Unimplemented ( )
# pylint : disable = no - member
return sessions . GradebookColumnLookupSession ( proxy = proxy , runtime = self . _runtime ) |
def getpLvlPcvd ( self ) :
'''Finds the representative agent ' s ( average ) perceived productivity level .
Average perception of productivity gets UpdatePrb weight on the true level ,
for those that update , and ( 1 - UpdatePrb ) weight on the previous average
perception times expected aggregate growth , for... | pLvlPcvd = self . UpdatePrb * self . pLvlTrue + ( 1.0 - self . UpdatePrb ) * ( self . pLvlNow * self . PermGroFac [ self . t_cycle [ 0 ] - 1 ] )
return pLvlPcvd |
def _find_utmp ( ) :
'''Figure out which utmp file to use when determining runlevel .
Sometimes / var / run / utmp doesn ' t exist , / run / utmp is the new hotness .''' | result = { }
# These are the likely locations for the file on Ubuntu
for utmp in '/var/run/utmp' , '/run/utmp' :
try :
result [ os . stat ( utmp ) . st_mtime ] = utmp
except Exception :
pass
if result :
return result [ sorted ( result ) . pop ( ) ]
else :
return False |
def getGenoID ( self , i0 = None , i1 = None , pos0 = None , pos1 = None , chrom = None , pos_cum0 = None , pos_cum1 = None ) :
"""get genotype IDs .
Optionally the indices for loading subgroups the genotype IDs for all people
can be given in one out of three ways :
- 0 - based indexing ( i0 - i1)
- positio... | # position based matching ?
if ( i0 is None ) and ( i1 is None ) and ( ( pos0 is not None ) & ( pos1 is not None ) & ( chrom is not None ) ) or ( ( pos_cum0 is not None ) & ( pos_cum1 is not None ) ) :
i0 , i1 = self . getGenoIndex ( pos0 = pos0 , pos1 = pos1 , chrom = chrom , pos_cum0 = pos_cum0 , pos_cum1 = pose_... |
def build_compounds_dict ( compounds ) :
"""Take a list with annotated compound variants for each family and
returns a dictionary with family _ id as key and a list of dictionarys
that holds the information about the compounds .
Args :
compounds : A list that can be either on the form
'1:1_23 _ A _ C | 1_... | logger = getLogger ( __name__ )
logger . debug ( "Parsing compounds: {0}" . format ( compounds ) )
parsed_compounds = { }
for family_info in compounds :
logger . debug ( "Parsing entry {0}" . format ( family_info ) )
splitted_family_info = family_info . split ( ':' )
family_id = splitted_family_info [ 0 ]
... |
def import_new_atlas_pointings ( self , recent = False ) :
"""* Import any new ATLAS pointings from the atlas3 / atlas4 databases into the ` ` atlas _ exposures ` ` table of the Atlas Movers database *
* * Key Arguments : * *
- ` ` recent ` ` - - only sync the most recent 2 weeks of data ( speeds things up )
... | self . log . info ( 'starting the ``import_new_atlas_pointings`` method' )
if recent :
mjd = mjdnow ( log = self . log ) . get_mjd ( )
recent = mjd - 14
recent = " mjd_obs > %(recent)s " % locals ( )
else :
recent = "1=1"
# SELECT ALL OF THE POINTING INFO REQUIRED FROM THE ATLAS3 DATABASE
sqlQuery = u""... |
def get_release_id ( version = None ) :
"""Get a unique , time - based identifier for a deployment
that optionally , also includes some sort of version number
or release .
If a version is supplied , the release ID will be of the form
' $ timestamp - $ version ' . For example :
> > > get _ release _ id ( v... | # pylint : disable = invalid - name
ts = datetime . utcnow ( ) . strftime ( RELEASE_DATE_FMT )
if version is None :
return ts
return '{0}-{1}' . format ( ts , version ) |
def read_nwchem ( basis_lines , fname ) :
'''Reads NWChem - formatted file data and converts it to a dictionary with the
usual BSE fields
Note that the nwchem format does not store all the fields we
have , so some fields are left blank''' | skipchars = '#'
basis_lines = [ l for l in basis_lines if l and not l [ 0 ] in skipchars ]
bs_data = create_skel ( 'component' )
i = 0
while i < len ( basis_lines ) :
line = basis_lines [ i ]
if line . lower ( ) . startswith ( 'basis' ) :
i += 1
# NWChem doesn ' t seem to really block by element... |
def tracker_print ( msg ) :
"""Print message to the tracker .
This function can be used to communicate the information of
the progress to the tracker
Parameters
msg : str
The message to be printed to tracker .""" | if not isinstance ( msg , STRING_TYPES ) :
msg = str ( msg )
is_dist = _LIB . RabitIsDistributed ( )
if is_dist != 0 :
_LIB . RabitTrackerPrint ( c_str ( msg ) )
else :
sys . stdout . write ( msg )
sys . stdout . flush ( ) |
def search ( geo_coords , mode = 2 , verbose = True ) :
"""Function to query for a list of coordinates""" | if not isinstance ( geo_coords , tuple ) and not isinstance ( geo_coords , list ) :
raise TypeError ( 'Expecting a tuple or a tuple/list of tuples' )
elif not isinstance ( geo_coords [ 0 ] , tuple ) :
geo_coords = [ geo_coords ]
_rg = RGeocoder ( mode = mode , verbose = verbose )
return _rg . query ( geo_coords... |
def pipfaster_download_cacher ( index_urls ) :
"""vanilla pip stores a cache of the http session in its cache and not the
wheel files . We intercept the download and save those files into our
cache""" | from pip . _internal import download
orig = download . _download_http_url
patched_fn = get_patched_download_http_url ( orig , index_urls )
return patched ( vars ( download ) , { '_download_http_url' : patched_fn } ) |
def convert ( self , image , output = None ) :
"""Convert an image to a PDF .
: param image : Image file path
: param output : Output name , same as image name with . pdf extension by default
: return : PDF file path""" | return self . _convert ( image , image . replace ( Path ( image ) . suffix , '.pdf' ) if not output else output ) |
def actions ( self ) :
"""List of : class : ` TableAction ` elements defined for this table""" | actions = [ ]
for a in dir ( self ) :
a = getattr ( self , a )
if isinstance ( a , TableAction ) :
actions . append ( a )
# We are not caching this because array len should be low enough
actions . sort ( key = lambda action : action . creation_counter )
return actions |
def app_assets ( request , ** kwargs ) :
'Return a local dash app asset , served up through the Django static framework' | get_params = request . GET . urlencode ( )
extra_part = ""
if get_params :
redone_url = "/static/dash/assets/%s?%s" % ( extra_part , get_params )
else :
redone_url = "/static/dash/assets/%s" % extra_part
return HttpResponseRedirect ( redirect_to = redone_url ) |
def create ( self ) :
"""Create a new ConfigurationInstance
: returns : Newly created ConfigurationInstance
: rtype : twilio . rest . flex _ api . v1 . configuration . ConfigurationInstance""" | data = values . of ( { } )
payload = self . _version . create ( 'POST' , self . _uri , data = data , )
return ConfigurationInstance ( self . _version , payload , ) |
def lpad ( s , N , char = '\0' ) :
"""pads a string to the left with null - bytes or any other given character .
. . note : : This is used by the : py : func : ` xor ` function .
: param s : the string
: param N : an integer of how much padding should be done
: returns : the original bytes""" | assert isinstance ( char , bytes ) and len ( char ) == 1 , 'char should be a string with length 1'
return s . rjust ( N , char ) |
def _parse_bare_key ( self ) : # type : ( ) - > Key
"""Parses a bare key .""" | key_type = None
dotted = False
self . mark ( )
while self . _current . is_bare_key_char ( ) and self . inc ( ) :
pass
key = self . extract ( )
if self . _current == "." :
self . inc ( )
dotted = True
key += "." + self . _parse_key ( ) . as_string ( )
key_type = KeyType . Bare
return Key ( key , key_... |
def _compile_vts ( self , vts , ctx , upstream_analysis , dependency_classpath , progress_message , settings , compiler_option_sets , zinc_file_manager , counter ) :
"""Compiles sources for the given vts into the given output dir .
: param vts : VersionedTargetSet with one entry for the target .
: param ctx : -... | if not ctx . sources :
self . context . log . warn ( 'Skipping {} compile for targets with no sources:\n {}' . format ( self . name ( ) , vts . targets ) )
else :
counter_val = str ( counter ( ) ) . rjust ( counter . format_length ( ) , ' ' )
counter_str = '[{}/{}] ' . format ( counter_val , counter . size... |
def _get_lp_matrix ( spin_states , nodes , edges , offset_weight , gap_weight ) :
"""Creates an linear programming matrix based on the spin states , graph , and scalars provided .
LP matrix :
[ spin _ states , corresponding states of edges , offset _ weight , gap _ weight ]
Args :
spin _ states : Numpy arra... | if len ( spin_states ) == 0 :
return None
# Set up an empty matrix
n_states = len ( spin_states )
m_linear = len ( nodes )
m_quadratic = len ( edges )
matrix = np . empty ( ( n_states , m_linear + m_quadratic + 2 ) )
# + 2 columns for offset and gap
# Populate linear terms ( i . e . spin states )
if spin_states . n... |
def uptime ( ut , facter ) :
"""Check uptime and facts to get the uptime information .
Prefer uptime to facts .
Returns :
insights . combiners . uptime . Uptime : A named tuple with ` currtime ` ,
` updays ` , ` uphhmm ` , ` users ` , ` loadavg ` and ` uptime ` components .
Raises :
Exception : If no da... | ut = ut
if ut and ut . loadavg :
return Uptime ( ut . currtime , ut . updays , ut . uphhmm , ut . users , ut . loadavg , ut . uptime )
ft = facter
if ft and hasattr ( ft , 'uptime_seconds' ) :
import datetime
secs = int ( ft . uptime_seconds )
up_dd = secs // ( 3600 * 24 )
up_hh = ( secs % ( 3600 * ... |
def to_json ( self ) :
""": return : str""" | json_dict = self . to_json_basic ( )
json_dict [ 'channel' ] = self . channel
json_dict [ 'timeout' ] = self . timeout
json_dict [ 'status' ] = self . status
json_dict [ 'led_status' ] = self . led_status
json_dict [ 'blind_position' ] = self . blind_position
json_dict [ 'locked_inhibit_forced' ] = self . locked_inhibi... |
def fill_slot ( self , filler_pipeline_key , slot , value ) :
"""Fills a slot , enqueueing a task to trigger pending barriers .
Args :
filler _ pipeline _ key : db . Key or stringified key of the _ PipelineRecord
that filled this slot .
slot : The Slot instance to fill .
value : The serializable value to ... | if not isinstance ( filler_pipeline_key , db . Key ) :
filler_pipeline_key = db . Key ( filler_pipeline_key )
if _TEST_MODE :
slot . _set_value_test ( filler_pipeline_key , value )
else :
encoded_value = json . dumps ( value , sort_keys = True , cls = mr_util . JsonEncoder )
value_text = None
value_... |
def get_implicit_deps ( self , env , initial_scanner , path_func , kw = { } ) :
"""Return a list of implicit dependencies for this node .
This method exists to handle recursive invocation of the scanner
on the implicit dependencies returned by the scanner , if the
scanner ' s recursive flag says that we shoul... | nodes = [ self ]
seen = set ( nodes )
dependencies = [ ]
path_memo = { }
root_node_scanner = self . _get_scanner ( env , initial_scanner , None , kw )
while nodes :
node = nodes . pop ( 0 )
scanner = node . _get_scanner ( env , initial_scanner , root_node_scanner , kw )
if not scanner :
continue
... |
def _add_text ( self , text ) :
"""If ` ` text ` ` is not empty , append a new Text node to the most recent
pending node , if there is any , or to the new nodes , if there are no
pending nodes .""" | if text :
if self . pending_nodes :
self . pending_nodes [ - 1 ] . append ( nodes . Text ( text ) )
else :
self . new_nodes . append ( nodes . Text ( text ) ) |
def get_id ( id_or_obj ) :
"""Returns the ' id ' attribute of ' id _ or _ obj ' if present ; if not ,
returns ' id _ or _ obj ' .""" | if isinstance ( id_or_obj , six . string_types + ( int , ) ) : # It ' s an ID
return id_or_obj
try :
return id_or_obj . id
except AttributeError :
return id_or_obj |
def percentage ( value , decimal_places = 1 , multiply = True , failure_string = 'N/A' ) :
"""Converts a floating point value into a percentage value .
Number of decimal places set by the ` decimal _ places ` kwarg . Default is one .
By default the number is multiplied by 100 . You can prevent it from doing
t... | try :
value = float ( value )
except ValueError :
return failure_string
if multiply :
value = value * 100
return _saferound ( value , decimal_places ) + '%' |
def getFeatureID ( self , location ) :
"""Returns the feature index associated with the provided location .
In the case of a sphere , it is always the same if the location is valid .""" | if not self . contains ( location ) :
return self . EMPTY_FEATURE
return self . SPHERICAL_SURFACE |
def _learnTransition ( self , prevActiveCells , deltaLocation , newLocation ) :
"""For each cell in the newLocation SDR , learn the transition of prevLocation
( i . e . prevActiveCells ) + deltaLocation .
The transition might be already known . In that case , just reinforce the
existing segments .""" | prevLocationPotentialOverlaps = self . internalConnections . computeActivity ( prevActiveCells )
deltaPotentialOverlaps = self . deltaConnections . computeActivity ( deltaLocation )
matchingDeltaSegments = np . where ( ( prevLocationPotentialOverlaps >= self . learningThreshold ) & ( deltaPotentialOverlaps >= self . le... |
def load_balancer_get ( name , resource_group , ** kwargs ) :
'''. . versionadded : : 2019.2.0
Get details about a specific load balancer .
: param name : The name of the load balancer to query .
: param resource _ group : The resource group name assigned to the
load balancer .
CLI Example :
. . code - ... | netconn = __utils__ [ 'azurearm.get_client' ] ( 'network' , ** kwargs )
try :
load_balancer = netconn . load_balancers . get ( load_balancer_name = name , resource_group_name = resource_group )
result = load_balancer . as_dict ( )
except CloudError as exc :
__utils__ [ 'azurearm.log_cloud_error' ] ( 'networ... |
def AgregarOpcional ( self , codigo = None , descripcion = None , ** kwargs ) :
"Agrega la información referente a los opcionales de la liq . seq ." | self . opcionales . append ( dict ( opcional = dict ( codigo = codigo , descripcion = descripcion , ) ) )
return True |
def header_without_lines ( header , remove ) :
"""Return : py : class : ` Header ` without lines given in ` ` remove ` `
` ` remove ` ` is an iterable of pairs ` ` key ` ` / ` ` ID ` ` with the VCF header key
and ` ` ID ` ` of entry to remove . In the case that a line does not have
a ` ` mapping ` ` entry , y... | remove = set ( remove )
# Copy over lines that are not removed
lines = [ ]
for line in header . lines :
if hasattr ( line , "mapping" ) :
if ( line . key , line . mapping . get ( "ID" , None ) ) in remove :
continue
# filter out
else :
if ( line . key , line . value ) in ... |
def get_symmetric_image ( self ) :
"""Creates a new DirectedHypergraph object that is the symmetric
image of this hypergraph ( i . e . , identical hypergraph with all
edge directions reversed ) .
Copies of each of the nodes ' and hyperedges ' attributes are stored
and used in the new hypergraph .
: return... | new_H = self . copy ( )
# No change to _ node _ attributes necessary , as nodes remain the same
# Reverse the tail and head ( and _ _ frozen _ tail and _ _ frozen _ head ) for
# every hyperedge
for hyperedge_id in self . get_hyperedge_id_set ( ) :
attr_dict = new_H . _hyperedge_attributes [ hyperedge_id ]
attr_... |
def num_leaves ( tree ) :
"""Determine the number of leaves in a tree""" | if tree . is_leaf :
return 1
else :
return num_leaves ( tree . left_child ) + num_leaves ( tree . right_child ) |
def sle ( self , other ) :
"""Compares two equal - sized BinWords , treating them as signed
integers , and returning True if the first is smaller or equal .""" | self . _check_match ( other )
return self . to_sint ( ) <= other . to_sint ( ) |
def do_execute_direct ( self , code : str , silent : bool = False ) -> [ str , dict ] :
"""This is the main method that takes code from the Jupyter cell and submits it to the SAS server
: param code : code from the cell
: param silent :
: return : str with either the log or list""" | if not code . strip ( ) :
return { 'status' : 'ok' , 'execution_count' : self . execution_count , 'payload' : [ ] , 'user_expressions' : { } }
if self . mva is None :
self . _allow_stdin = True
self . _start_sas ( )
if self . lst_len < 0 :
self . _get_lst_len ( )
if code . startswith ( 'Obfuscated SAS C... |
def control_group ( self , control_group_id , ctrl , shift , alt ) :
"""Act on a control group , selecting , setting , etc .""" | action = sc_pb . Action ( )
select = action . action_ui . control_group
mod = sc_ui . ActionControlGroup
if not ctrl and not shift and not alt :
select . action = mod . Recall
elif ctrl and not shift and not alt :
select . action = mod . Set
elif not ctrl and shift and not alt :
select . action = mod . Appe... |
def get_page_template ( self , ** kwargs ) :
"""Return the template name used for this request .
Only called if * page _ template * is not given as a kwarg of
* self . as _ view * .""" | opts = self . object_list . model . _meta
return '{0}/{1}{2}{3}.html' . format ( opts . app_label , opts . object_name . lower ( ) , self . template_name_suffix , self . page_template_suffix , ) |
def exists ( self , ** kwargs ) :
"""Check for the existence of the named object on the BigIP
Sends an HTTP GET to the URI of the named object and if it fails with
a : exc : ~ requests . HTTPError ` exception it checks the exception for
status code of 404 and returns : obj : ` False ` in that case .
If the ... | requests_params = self . _handle_requests_params ( kwargs )
self . _check_load_parameters ( ** kwargs )
kwargs [ 'uri_as_parts' ] = True
session = self . _meta_data [ 'bigip' ] . _meta_data [ 'icr_session' ]
base_uri = self . _meta_data [ 'container' ] . _meta_data [ 'uri' ]
kwargs . update ( requests_params )
try :
... |
def visualize_conv_weights ( filters , name ) :
"""Visualize use weights in convolution filters .
Args :
filters : tensor containing the weights [ H , W , Cin , Cout ]
name : label for tensorboard
Returns :
image of all weight""" | with tf . name_scope ( 'visualize_w_' + name ) :
filters = tf . transpose ( filters , ( 3 , 2 , 0 , 1 ) )
# [ h , w , cin , cout ] - > [ cout , cin , h , w ]
filters = tf . unstack ( filters )
# - - > cout * [ cin , h , w ]
filters = tf . concat ( filters , 1 )
# - - > [ cin , cout * h , w ]
... |
def validate_orientation ( dicoms ) :
"""Validate that all dicoms have the same orientation
: param dicoms : list of dicoms""" | first_image_orient1 = numpy . array ( dicoms [ 0 ] . ImageOrientationPatient ) [ 0 : 3 ]
first_image_orient2 = numpy . array ( dicoms [ 0 ] . ImageOrientationPatient ) [ 3 : 6 ]
for dicom_ in dicoms : # Create affine matrix ( http : / / nipy . sourceforge . net / nibabel / dicom / dicom _ orientation . html # dicom - s... |
def _find_usage_certs ( self ) :
"""Find usage on Client Certificates . Update ` self . limits ` .""" | logger . debug ( 'Finding usage for Client Certificates' )
cert_count = 0
paginator = self . conn . get_paginator ( 'get_client_certificates' )
for resp in paginator . paginate ( ) :
cert_count += len ( resp [ 'items' ] )
self . limits [ 'Client certificates per account' ] . _add_current_usage ( cert_count , aws_ty... |
def _get_java_env ( self ) :
"Pass the VCAP through the environment to the java submission" | env = super ( _StreamingAnalyticsSubmitter , self ) . _get_java_env ( )
vcap = streamsx . rest . _get_vcap_services ( self . _vcap_services )
env [ 'VCAP_SERVICES' ] = json . dumps ( vcap )
return env |
def get_all_subscriptions_by_topic ( name , region = None , key = None , keyid = None , profile = None ) :
'''Get list of all subscriptions to a specific topic .
CLI example to delete a topic : :
salt myminion boto _ sns . get _ all _ subscriptions _ by _ topic mytopic region = us - east - 1''' | cache_key = _subscriptions_cache_key ( name )
try :
return __context__ [ cache_key ]
except KeyError :
pass
conn = _get_conn ( region = region , key = key , keyid = keyid , profile = profile )
ret = conn . get_all_subscriptions_by_topic ( get_arn ( name , region , key , keyid , profile ) )
__context__ [ cache_k... |
async def get_top_clans ( self ) :
'''Get a list of top clans , info is only brief ,
call get _ clan ( ) on each of the ClanInfo objects
to get full clan info''' | url = self . BASE + '/top/clans'
data = await self . request ( url )
return [ ClanInfo ( self , c ) for c in data . get ( 'clans' ) ] |
def get_file_volume_details ( self , volume_id , ** kwargs ) :
"""Returns details about the specified volume .
: param volume _ id : ID of volume .
: param kwargs :
: return : Returns details about the specified volume .""" | if 'mask' not in kwargs :
items = [ 'id' , 'username' , 'password' , 'capacityGb' , 'bytesUsed' , 'snapshotCapacityGb' , 'parentVolume.snapshotSizeBytes' , 'storageType.keyName' , 'serviceResource.datacenter[name]' , 'serviceResourceBackendIpAddress' , 'fileNetworkMountAddress' , 'storageTierLevel' , 'provisionedIo... |
def full_file_list ( scan_path ) :
"""Returns a list of all files in a folder and its subfolders ( only files ) .""" | file_list = [ ]
path = os . path . abspath ( scan_path )
for root , dirs , files in os . walk ( path ) :
if len ( files ) != 0 and not '.svn' in root and not '.git' in root :
for f in files :
file_list . append ( os . path . join ( root , f ) )
return file_list |
def randomize_molecule ( molecule , manipulations , nonbond_thresholds , max_tries = 1000 ) :
"""Return a randomized copy of the molecule .
If no randomized molecule can be generated that survives the nonbond
check after max _ tries repetitions , None is returned . In case of success ,
the randomized molecule... | for m in range ( max_tries ) :
random_molecule = randomize_molecule_low ( molecule , manipulations )
if check_nonbond ( random_molecule , nonbond_thresholds ) :
return random_molecule |
def add_resolved_requirements ( self , reqs , platforms = None ) :
"""Multi - platform dependency resolution for PEX files .
: param builder : Dump the requirements into this builder .
: param interpreter : The : class : ` PythonInterpreter ` to resolve requirements for .
: param reqs : A list of : class : ` ... | distributions = self . _resolve_distributions_by_platform ( reqs , platforms = platforms )
locations = set ( )
for platform , dists in distributions . items ( ) :
for dist in dists :
if dist . location not in locations :
self . _log . debug ( ' Dumping distribution: .../{}' . format ( os . path... |
def _create_filter_by ( self ) :
"""Transform the json - server filter arguments to model - resource ones .""" | filter_by = [ ]
for name , values in request . args . copy ( ) . lists ( ) : # copy . lists works in py2 and py3
if name not in _SKIPPED_ARGUMENTS :
column = _re_column_name . search ( name ) . group ( 1 )
if column not in self . _model_columns :
continue
for value in values :
... |
def summary ( self , featuresCol , weightCol = None ) :
"""Returns an aggregate object that contains the summary of the column with the requested
metrics .
: param featuresCol :
a column that contains features Vector object .
: param weightCol :
a column that contains weight value . Default weight is 1.0.... | featuresCol , weightCol = Summarizer . _check_param ( featuresCol , weightCol )
return Column ( self . _java_obj . summary ( featuresCol . _jc , weightCol . _jc ) ) |
def export ( self , file_to_export , xformat = 'csv' ) :
"""Export epochwise annotations to csv file .
Parameters
file _ to _ export : path to file
file to write to""" | if 'csv' == xformat :
with open ( file_to_export , 'w' , newline = '' ) as f :
csv_file = writer ( f )
csv_file . writerow ( [ 'Wonambi v{}' . format ( __version__ ) ] )
csv_file . writerow ( ( 'clock start time' , 'start' , 'end' , 'stage' ) )
for epoch in self . epochs :
... |
def _heapreplace_max ( heap , item ) :
"""Maxheap version of a heappop followed by a heappush .""" | returnitem = heap [ 0 ]
# raises appropriate IndexError if heap is empty
heap [ 0 ] = item
_siftup_max ( heap , 0 )
return returnitem |
def delete_async ( self , ** ctx_options ) :
"""Schedule deletion of the entity for this Key .
This returns a Future , whose result becomes available once the
deletion is complete . If no such entity exists , a Future is still
returned . In all cases the Future ' s result is None ( i . e . there is
no way t... | from . import tasklets , model
ctx = tasklets . get_context ( )
cls = model . Model . _kind_map . get ( self . kind ( ) )
if cls :
cls . _pre_delete_hook ( self )
fut = ctx . delete ( self , ** ctx_options )
if cls :
post_hook = cls . _post_delete_hook
if not cls . _is_default_hook ( model . Model . _defaul... |
def do_attr_any ( self , element , decl , pseudo ) :
"""Implement generic attribute setting .""" | step = self . state [ self . state [ 'current_step' ] ]
actions = step [ 'actions' ]
strval = self . eval_string_value ( element , decl . value )
actions . append ( ( 'attrib' , ( decl . name [ 5 : ] , strval ) ) ) |
def parse_schema_extension ( lexer : Lexer ) -> SchemaExtensionNode :
"""SchemaExtension""" | start = lexer . token
expect_keyword ( lexer , "extend" )
expect_keyword ( lexer , "schema" )
directives = parse_directives ( lexer , True )
operation_types = ( many_nodes ( lexer , TokenKind . BRACE_L , parse_operation_type_definition , TokenKind . BRACE_R ) if peek ( lexer , TokenKind . BRACE_L ) else [ ] )
if not di... |
def move_selection ( reverse = False ) :
"""Goes through the list of gunicorns , setting the selected as the one after
the currently selected .""" | global selected_pid
if selected_pid not in gunicorns :
selected_pid = None
found = False
pids = sorted ( gunicorns . keys ( ) , reverse = reverse )
# Iterate items twice to enable wrapping .
for pid in pids + pids :
if selected_pid is None or found :
selected_pid = pid
return
found = pid == ... |
def atlas_zonefile_push_dequeue ( zonefile_queue = None ) :
"""Dequeue a zonefile ' s information to replicate
Return None if there are none queued""" | ret = None
with AtlasZonefileQueueLocked ( zonefile_queue ) as zfq :
if len ( zfq ) > 0 :
ret = zfq . pop ( 0 )
return ret |
def assertTimeZoneNotEqual ( self , dt , tz , msg = None ) :
'''Fail if ` ` dt ` ` ' s ` ` tzinfo ` ` attribute equals ` ` tz ` ` as
determined by the ' ! = ' operator .
Parameters
dt : datetime
tz : timezone
msg : str
If not provided , the : mod : ` marbles . mixins ` or
: mod : ` unittest ` standard... | if not isinstance ( dt , datetime ) :
raise TypeError ( 'First argument is not a datetime object' )
if not isinstance ( tz , timezone ) :
raise TypeError ( 'Second argument is not a timezone object' )
self . assertNotEqual ( dt . tzinfo , tz , msg = msg ) |
def persist ( self , storageLevel = StorageLevel . MEMORY_AND_DISK ) :
"""Sets the storage level to persist the contents of the : class : ` DataFrame ` across
operations after the first time it is computed . This can only be used to assign
a new storage level if the : class : ` DataFrame ` does not have a stora... | self . is_cached = True
javaStorageLevel = self . _sc . _getJavaStorageLevel ( storageLevel )
self . _jdf . persist ( javaStorageLevel )
return self |
def register_wcs ( name , wrapper_class , coord_types ) :
"""Register a custom WCS wrapper .
Parameters
name : str
The name of the custom WCS wrapper
wrapper _ class : subclass of ` ~ ginga . util . wcsmod . BaseWCS `
The class implementing the WCS wrapper
coord _ types : list of str
List of names of ... | global custom_wcs
custom_wcs [ name ] = Bunch . Bunch ( name = name , wrapper_class = wrapper_class , coord_types = coord_types ) |
def _advance_window ( self ) :
"""Update values in current window and the current window means and variances .""" | x_to_remove , y_to_remove = self . _x_in_window [ 0 ] , self . _y_in_window [ 0 ]
self . _window_bound_lower += 1
self . _update_values_in_window ( )
x_to_add , y_to_add = self . _x_in_window [ - 1 ] , self . _y_in_window [ - 1 ]
self . _remove_observation ( x_to_remove , y_to_remove )
self . _add_observation ( x_to_ad... |
def push_async_exit ( self , exit ) :
"""Registers a coroutine function with the standard _ _ aexit _ _ method
signature .
Can suppress exceptions the same way _ _ aexit _ _ method can .
Also accepts any object with an _ _ aexit _ _ method ( registering a call
to the method instead of the object itself ) ."... | _cb_type = type ( exit )
try :
exit_method = _cb_type . __aexit__
except AttributeError : # Not an async context manager , so assume it ' s a coroutine function
self . _push_exit_callback ( exit , False )
else :
self . _push_async_cm_exit ( exit , exit_method )
return exit |
async def set_codec ( self , codectype = 0x0040 , bitrate = 0x0003 ) :
"""Set codec settings .""" | act = self . service . action ( "X_SetCodec" )
res = await act . async_call ( CodecType = codectype , CodecBitrate = bitrate )
return res |
def get_source ( self , name ) :
"""Concrete implementation of InspectLoader . get _ source .""" | path = self . get_filename ( name )
try :
source_bytes = self . get_data ( path )
except OSError as exc :
e = _ImportError ( 'source not available through get_data()' , name = name )
e . __cause__ = exc
raise e
return decode_source ( source_bytes ) |
def remove_root_bin ( self , bin_id ) :
"""Removes a root bin .
arg : bin _ id ( osid . id . Id ) : the ` ` Id ` ` of a bin
raise : NotFound - ` ` bin _ id ` ` not a root
raise : NullArgument - ` ` bin _ id ` ` is ` ` null ` `
raise : OperationFailed - unable to complete request
raise : PermissionDenied -... | # Implemented from template for
# osid . resource . BinHierarchyDesignSession . remove _ root _ bin _ template
if self . _catalog_session is not None :
return self . _catalog_session . remove_root_catalog ( catalog_id = bin_id )
return self . _hierarchy_session . remove_root ( id_ = bin_id ) |
def process ( self , envelope , session , mode = None , composer_factory = None , ** kwargs ) :
""": meth : ` . WMessengerOnionLayerProto . process ` implementation""" | if mode == WMessengerComposerLayer . Mode . compose :
return self . compose ( envelope , session , composer_factory , ** kwargs )
elif mode == WMessengerComposerLayer . Mode . decompose :
return self . decompose ( envelope , session , composer_factory , ** kwargs )
raise RuntimeError ( 'Invalid mode was specifi... |
def get_argument ( self , name ) :
"""Return single argument by name""" | val = self . arguments . get ( name )
if val :
return val [ 0 ]
return None |
def _update_job_info ( cls , job_dir ) :
"""Update information for given job .
Meta file will be loaded if exists , and the job information in
in db backend will be updated .
Args :
job _ dir ( str ) : Directory path of the job .
Return :
Updated dict of job meta info""" | meta_file = os . path . join ( job_dir , JOB_META_FILE )
meta = parse_json ( meta_file )
if meta :
logging . debug ( "Update job info for %s" % meta [ "job_id" ] )
JobRecord . objects . filter ( job_id = meta [ "job_id" ] ) . update ( end_time = timestamp2date ( meta [ "end_time" ] ) ) |
def concat ( self , operand , start = 0 , end = 0 , offset = 0 ) :
"""Concat a map . You can also optionally slice the operand map
and apply an offset to each position before concatting""" | if not Gauged . map_concat ( self . ptr , operand . ptr , start , end , offset ) :
raise MemoryError |
def get_dir ( path , dest , saltenv = 'base' , template = None , gzip = None , ** kwargs ) :
'''Used to recursively copy a directory from the salt master
CLI Example :
. . code - block : : bash
salt ' * ' cp . get _ dir salt : / / path / to / dir / / minion / dest
get _ dir supports the same template and gz... | ( path , dest ) = _render_filenames ( path , dest , saltenv , template , ** kwargs )
return _client ( ) . get_dir ( path , dest , saltenv , gzip ) |
def derived_sequence ( graph ) :
"""Compute the derived sequence of the graph G
The intervals of G are collapsed into nodes , intervals of these nodes are
built , and the process is repeated iteratively until we obtain a single
node ( if the graph is not irreducible )""" | deriv_seq = [ graph ]
deriv_interv = [ ]
single_node = False
while not single_node :
interv_graph , interv_heads = intervals ( graph )
deriv_interv . append ( interv_heads )
single_node = len ( interv_graph ) == 1
if not single_node :
deriv_seq . append ( interv_graph )
graph = interv_graph
... |
def unlock_swarm ( self , key ) :
"""Unlock a locked swarm .
Args :
key ( string ) : The unlock key as provided by
: py : meth : ` get _ unlock _ key `
Raises :
: py : class : ` docker . errors . InvalidArgument `
If the key argument is in an incompatible format
: py : class : ` docker . errors . APIE... | if isinstance ( key , dict ) :
if 'UnlockKey' not in key :
raise errors . InvalidArgument ( 'Invalid unlock key format' )
else :
key = { 'UnlockKey' : key }
url = self . _url ( '/swarm/unlock' )
res = self . _post_json ( url , data = key )
self . _raise_for_status ( res )
return True |
def set_indexing ( working_dir , flag ) :
"""Set a flag in the filesystem as to whether or not we ' re indexing .""" | indexing_path = get_indexing_lockfile ( working_dir )
if flag :
try :
fd = open ( indexing_path , "w+" )
fd . close ( )
return True
except :
return False
else :
try :
os . unlink ( indexing_path )
return True
except :
return False |
def start ( context : typing . Optional [ typing . Mapping ] = None , banner : typing . Optional [ str ] = None , shell : typing . Type [ Shell ] = AutoShell , prompt : typing . Optional [ str ] = None , output : typing . Optional [ str ] = None , context_format : str = "full" , ** kwargs : typing . Any , ) -> None :
... | logger . debug ( f"Using shell: {shell!r}" )
if banner is None :
banner = speak ( )
# Default to global config
context_ = context or _cfg [ "context" ]
banner_ = banner or _cfg [ "banner" ]
if isinstance ( shell , type ) and issubclass ( shell , Shell ) :
shell_ = shell
else :
shell_ = SHELL_MAP . get ( she... |
def hmean_int ( a , a_min = 5778 , a_max = 1149851 ) :
"""Harmonic mean of an array , returns the closest int""" | from scipy . stats import hmean
return int ( round ( hmean ( np . clip ( a , a_min , a_max ) ) ) ) |
def trace_requirements ( requirements ) :
"""given an iterable of pip InstallRequirements ,
return the set of required packages , given their transitive requirements .""" | requirements = tuple ( pretty_req ( r ) for r in requirements )
working_set = fresh_working_set ( )
# breadth - first traversal :
from collections import deque
queue = deque ( requirements )
queued = { _package_req_to_pkg_resources_req ( req . req ) for req in queue }
errors = [ ]
result = [ ]
while queue :
req = q... |
def set_probe_position ( self , new_probe_position ) :
"""Set the probe position , in normalized coordinates with origin at top left .""" | if new_probe_position is not None : # convert the probe position to a FloatPoint and limit it to the 0.0 to 1.0 range in both axes .
new_probe_position = Geometry . FloatPoint . make ( new_probe_position )
new_probe_position = Geometry . FloatPoint ( y = max ( min ( new_probe_position . y , 1.0 ) , 0.0 ) , x = ... |
def _do_sse_request ( self , path , params = None ) :
"""Query Marathon server for events .""" | urls = [ '' . join ( [ server . rstrip ( '/' ) , path ] ) for server in self . servers ]
while urls :
url = urls . pop ( )
try : # Requests does not set the original Authorization header on cross origin
# redirects . If set allow _ redirects = True we may get a 401 response .
response = self . sse_s... |
def get_ccle_mutations ( gene_list , cell_lines , mutation_type = None ) :
"""Return a dict of mutations in given genes and cell lines from CCLE .
This is a specialized call to get _ mutations tailored to CCLE cell lines .
Parameters
gene _ list : list [ str ]
A list of HGNC gene symbols to get mutations in... | mutations = { cl : { g : [ ] for g in gene_list } for cl in cell_lines }
for cell_line in cell_lines :
mutations_cl = get_mutations ( ccle_study , gene_list , mutation_type = mutation_type , case_id = cell_line )
for gene , aa_change in zip ( mutations_cl [ 'gene_symbol' ] , mutations_cl [ 'amino_acid_change' ]... |
def _normalizeCursor ( self , x , y ) :
"""return the normalized the cursor position .""" | width , height = self . get_size ( )
assert width != 0 and height != 0 , 'can not print on a console with a width or height of zero'
while x >= width :
x -= width
y += 1
while y >= height :
if self . _scrollMode == 'scroll' :
y -= 1
self . scroll ( 0 , - 1 )
elif self . _scrollMode == 'e... |
def makefile ( self , mode = 'r' , bufsize = - 1 ) :
"""create a file - like object that wraps the socket
: param mode :
like the ` ` mode ` ` argument for other files , indicates read ` ` ' r ' ` ` ,
write ` ` ' w ' ` ` , or both ` ` ' r + ' ` ` ( default ` ` ' r ' ` ` )
: type mode : str
: param bufsize... | f = SocketFile ( self . _sock , mode )
f . _sock . settimeout ( self . gettimeout ( ) )
return f |
def get_type ( self ) :
"""Get the type name of key""" | for typechar , typename in self . KEY_TYPE_CHOICES :
if typechar == self . key_type :
return typename |
def _quantityToReal ( self , quantity ) :
"""Convert a quantity , either spelled - out or numeric , to a float
@ type quantity : string
@ param quantity : quantity to parse to float
@ rtype : int
@ return : the quantity as an float , defaulting to 0.0""" | if not quantity :
return 1.0
try :
return float ( quantity . replace ( ',' , '.' ) )
except ValueError :
pass
try :
return float ( self . ptc . numbers [ quantity ] )
except KeyError :
pass
return 0.0 |
def on_btn_convert_3 ( self , event ) :
"""Open dialog for rough conversion of
2.5 files to 3.0 files .
Offer link to earthref for proper upgrade .""" | dia = pw . UpgradeDialog ( None )
dia . Center ( )
res = dia . ShowModal ( )
if res == wx . ID_CANCEL :
webbrowser . open ( "https://www2.earthref.org/MagIC/upgrade" , new = 2 )
return
# # more nicely styled way , but doesn ' t link to earthref
# msg = " This tool is meant for relatively simple upgrades ( for i... |
def instruction_BNE ( self , opcode , ea ) :
"""Tests the state of the Z ( zero ) bit and causes a branch if it is clear .
When used after a subtract or compare operation on any binary values ,
this instruction will branch if the register is , or would be , not equal
to the memory register .
source code for... | if self . Z == 0 : # log . info ( " $ % x BNE branch to $ % x , because Z = = 0 \ t | % s " % (
# self . program _ counter , ea , self . cfg . mem _ info . get _ shortest ( ea )
self . program_counter . set ( ea ) |
def remove_package ( self , team , user , package ) :
"""Removes a package ( all instances ) from this store .""" | self . check_name ( team , user , package )
path = self . package_path ( team , user , package )
remove_objs = set ( )
# TODO : do we really want to delete invisible dirs ?
if os . path . isdir ( path ) : # Collect objects from all instances for potential cleanup
contents_path = os . path . join ( path , PackageSto... |
def extract ( repository , destination , version , debug = False ) :
"""Extract the specified repository / version into the given directory and
return None .
: param repository : A string containing the path to the repository to be
extracted .
: param destination : A string containing the directory to clone... | with util . saved_cwd ( ) :
if os . path . isdir ( destination ) :
shutil . rmtree ( destination )
os . chdir ( repository )
_get_version ( version , debug )
cmd = sh . git . bake ( 'checkout-index' , force = True , all = True , prefix = destination )
util . run_command ( cmd , debug = debug... |
def make_slot_check ( wanted ) :
"""Creates and returns a function that takes a slot
and checks if it matches the wanted item .
Args :
wanted : function ( Slot ) or Slot or itemID or ( itemID , metadata )""" | if isinstance ( wanted , types . FunctionType ) :
return wanted
# just forward the slot check function
if isinstance ( wanted , int ) :
item , meta = wanted , None
elif isinstance ( wanted , Slot ) :
item , meta = wanted . item_id , wanted . damage
# TODO compare NBT
elif isinstance ( wanted , ( Item , ... |
def paginate ( data : typing . Iterable , page : int = 0 , limit : int = 10 ) -> typing . Iterable :
"""Slice data over pages
: param data : any iterable object
: type data : : obj : ` typing . Iterable `
: param page : number of page
: type page : : obj : ` int `
: param limit : items per page
: type l... | return data [ page * limit : page * limit + limit ] |
def write_ulong ( self , l ) :
"""Writes a 4 byte unsigned integer to the stream .
@ param l : 4 byte unsigned integer
@ type l : C { int }
@ raise TypeError : Unexpected type for int C { l } .
@ raise OverflowError : Not in range .""" | if type ( l ) not in python . int_types :
raise TypeError ( 'expected an int (got:%r)' % ( type ( l ) , ) )
if not 0 <= l <= 4294967295 :
raise OverflowError ( "Not in range, %d" % l )
self . write ( struct . pack ( "%sL" % self . endian , l ) ) |
def subset_bed_by_chrom ( in_file , chrom , data , out_dir = None ) :
"""Subset a BED file to only have items from the specified chromosome .""" | if out_dir is None :
out_dir = os . path . dirname ( in_file )
base , ext = os . path . splitext ( os . path . basename ( in_file ) )
out_file = os . path . join ( out_dir , "%s-%s%s" % ( base , chrom , ext ) )
if not utils . file_uptodate ( out_file , in_file ) :
with file_transaction ( data , out_file ) as tx... |
def getPart ( ID , chart ) :
"""Returns an Arabic Part .""" | obj = GenericObject ( )
obj . id = ID
obj . type = const . OBJ_ARABIC_PART
obj . relocate ( partLon ( ID , chart ) )
return obj |
def k_array_rank ( a ) :
"""Given an array ` a ` of k distinct nonnegative integers , sorted in
ascending order , return its ranking in the lexicographic ordering of
the descending sequences of the elements [ 1 ] _ .
Parameters
a : ndarray ( int , ndim = 1)
Array of length k .
Returns
idx : scalar ( i... | k = len ( a )
idx = int ( a [ 0 ] )
# Convert to Python int
for i in range ( 1 , k ) :
idx += comb ( a [ i ] , i + 1 , exact = True )
return idx |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.