signature stringlengths 29 44.1k | implementation stringlengths 0 85.2k |
|---|---|
def get_value ( cls , group , key = None ) :
"""get value""" | return cls . query . get_value ( group = group , key = key ) |
def _check_data ( data ) :
"""Check whether ` data ` is a valid input / output for libsamplerate .
Returns
num _ frames
Number of frames in ` data ` .
channels
Number of channels in ` data ` .
Raises
ValueError : If invalid data is supplied .""" | if not ( data . dtype == _np . float32 and data . flags . c_contiguous ) :
raise ValueError ( 'supplied data must be float32 and C contiguous' )
if data . ndim == 2 :
num_frames , channels = data . shape
elif data . ndim == 1 :
num_frames , channels = data . size , 1
else :
raise ValueError ( 'rank > 2 ... |
def maps_get_default_rules_output_rules_value ( self , ** kwargs ) :
"""Auto Generated Code""" | config = ET . Element ( "config" )
maps_get_default_rules = ET . Element ( "maps_get_default_rules" )
config = maps_get_default_rules
output = ET . SubElement ( maps_get_default_rules , "output" )
rules = ET . SubElement ( output , "rules" )
value = ET . SubElement ( rules , "value" )
value . text = kwargs . pop ( 'val... |
def list_metrics ( self , entity , check , limit = None , marker = None , return_next = False ) :
"""Returns a list of all the metrics associated with the specified check .""" | return entity . list_metrics ( check , limit = limit , marker = marker , return_next = return_next ) |
def get_nets_arin ( self , response ) :
"""The function for parsing network blocks from ARIN whois data .
Args :
response ( : obj : ` str ` ) : The response from the ARIN whois server .
Returns :
list of dict : Mapping of networks with start and end positions .
' cidr ' ( str ) - The network routing block... | nets = [ ]
# Find the first NetRange value .
pattern = re . compile ( r'^NetRange:[^\S\n]+(.+)$' , re . MULTILINE )
temp = pattern . search ( response )
net_range = None
net_range_start = None
if temp is not None :
net_range = temp . group ( 1 ) . strip ( )
net_range_start = temp . start ( )
# Iterate through a... |
def svd_entropy ( X , Tau , DE , W = None ) :
"""Compute SVD Entropy from either two cases below :
1 . a time series X , with lag tau and embedding dimension dE ( default )
2 . a list , W , of normalized singular values of a matrix ( if W is provided ,
recommend to speed up . )
If W is None , the function w... | if W is None :
Y = embed_seq ( X , Tau , DE )
W = numpy . linalg . svd ( Y , compute_uv = 0 )
W /= sum ( W )
# normalize singular values
return - 1 * sum ( W * numpy . log ( W ) ) |
def diff ( self , a_ref , target = None , b_ref = None ) :
"""Gerenates diff message string output
Args :
target ( str ) - file / directory to check diff of
a _ ref ( str ) - first tag
( optional ) b _ ref ( str ) - second git tag
Returns :
string : string of output message with diff info""" | result = { }
diff_dct = self . scm . get_diff_trees ( a_ref , b_ref = b_ref )
result [ DIFF_A_REF ] = diff_dct [ DIFF_A_REF ]
result [ DIFF_B_REF ] = diff_dct [ DIFF_B_REF ]
if diff_dct [ DIFF_EQUAL ] :
result [ DIFF_EQUAL ] = True
return result
result [ DIFF_LIST ] = [ ]
diff_outs = _get_diff_outs ( self , dif... |
def _get_command ( classes ) :
"""Associates each command class with command depending on setup . cfg""" | commands = { }
setup_file = os . path . join ( os . path . abspath ( os . path . join ( os . path . dirname ( __file__ ) , '../..' ) ) , 'setup.cfg' )
for line in open ( setup_file , 'r' ) :
for cl in classes :
if cl in line :
commands [ cl ] = line . split ( ' = ' ) [ 0 ] . strip ( ) . replace ... |
def mcp_als ( X , rank , mask , random_state = None , init = 'randn' , ** options ) :
"""Fits CP Decomposition with missing data using Alternating Least Squares ( ALS ) .
Parameters
X : ( I _ 1 , . . . , I _ N ) array _ like
A tensor with ` ` X . ndim > = 3 ` ` .
rank : integer
The ` rank ` sets the numbe... | # Check inputs .
optim_utils . _check_cpd_inputs ( X , rank )
# Initialize problem .
U , _ = optim_utils . _get_initial_ktensor ( init , X , rank , random_state , scale_norm = False )
result = FitResult ( U , 'MCP_ALS' , ** options )
normX = np . linalg . norm ( ( X * mask ) )
# Main optimization loop .
while result . ... |
def select ( self , selector ) :
'''Transforms each element of a sequence into a new form .
Each element is transformed through a selector function to produce a
value for each value in the source sequence . The generated sequence is
lazily evaluated .
Args :
selector : A unary function mapping a value in ... | return self . _create ( self . _pool . imap_unordered ( selector , iter ( self ) , self . _chunksize ) ) |
def storeSenderKey ( self , senderKeyName , senderKeyRecord ) :
""": type senderKeyName : SenderKeName
: type senderKeyRecord : SenderKeyRecord""" | q = "INSERT INTO sender_keys (group_id, sender_id, record) VALUES(?,?, ?)"
cursor = self . dbConn . cursor ( )
serialized = senderKeyRecord . serialize ( )
if sys . version_info < ( 2 , 7 ) :
serialized = buffer ( serialized )
try :
cursor . execute ( q , ( senderKeyName . getGroupId ( ) , senderKeyName . getSe... |
def get_user ( self , user_name = None ) :
"""Retrieve information about the specified user .
If the user _ name is not specified , the user _ name is determined
implicitly based on the AWS Access Key ID used to sign the request .
: type user _ name : string
: param user _ name : The name of the user to del... | params = { }
if user_name :
params [ 'UserName' ] = user_name
return self . get_response ( 'GetUser' , params ) |
def during ( rrule , duration = None , timestamp = None , ** kwargs ) :
"""Check if input timestamp is in rrule + duration period
: param rrule : rrule to check
: type rrule : str or dict
( freq , dtstart , interval , count , wkst , until , bymonth , byminute , etc . )
: param dict duration : time duration ... | result = False
# if rrule is a string expression
if isinstance ( rrule , string_types ) :
rrule_object = rrule_class . rrulestr ( rrule )
else :
rrule_object = rrule_class ( ** rrule )
# if timestamp is None , use now
if timestamp is None :
timestamp = time ( )
# get now object
now = datetime . fromtimestam... |
def _prepare_for_training ( self , job_name = None ) :
"""Set hyperparameters needed for training . This method will also validate ` ` source _ dir ` ` .
Args :
* job _ name ( str ) : Name of the training job to be created . If not specified , one is generated ,
using the base name given to the constructor if... | super ( Framework , self ) . _prepare_for_training ( job_name = job_name )
# validate source dir will raise a ValueError if there is something wrong with the
# source directory . We are intentionally not handling it because this is a critical error .
if self . source_dir and not self . source_dir . lower ( ) . startswi... |
def append ( self , list_name , value ) :
"""Appends : attr : ` value ` to the list named : attr : ` list _ name ` .""" | with self . lock :
l = self . lists . get ( list_name )
if l :
l . append ( value )
else :
l = [ value ]
self . lists [ list_name ] = l |
def record_download_archive ( track ) :
"""Write the track _ id in the download archive""" | global arguments
if not arguments [ '--download-archive' ] :
return
archive_filename = arguments . get ( '--download-archive' )
try :
with open ( archive_filename , 'a' , encoding = 'utf-8' ) as file :
file . write ( '{0}' . format ( track [ 'id' ] ) + '\n' )
except IOError as ioe :
logger . error (... |
def get_google_auth_password ( self , totp_key = None ) :
"""Returns a time - based one - time password based on the
Google Authenticator password algorithm . Works with Authy .
If " totp _ key " is not specified , defaults to using the one
provided in seleniumbase / config / settings . py
Google Auth passw... | import pyotp
if not totp_key :
totp_key = settings . TOTP_KEY
epoch_interval = time . time ( ) / 30.0
cycle_lifespan = float ( epoch_interval ) - int ( epoch_interval )
if float ( cycle_lifespan ) > 0.95 : # Password expires in the next 1.5 seconds . Wait for a new one .
for i in range ( 30 ) :
time . s... |
def _load_lexers ( module_name ) :
"""Load a lexer ( and all others in the module too ) .""" | mod = __import__ ( module_name , None , None , [ '__all__' ] )
for lexer_name in mod . __all__ :
cls = getattr ( mod , lexer_name )
_lexer_cache [ cls . name ] = cls |
def writeImageToFile ( self , filename , _format = "PNG" ) :
'''Write the View image to the specified filename in the specified format .
@ type filename : str
@ param filename : Absolute path and optional filename receiving the image . If this points to
a directory , then the filename is determined by this Vi... | filename = self . device . substituteDeviceTemplate ( filename )
if not os . path . isabs ( filename ) :
raise ValueError ( "writeImageToFile expects an absolute path (fielname='%s')" % filename )
if os . path . isdir ( filename ) :
filename = os . path . join ( filename , self . variableNameFromId ( ) + '.' + ... |
def all_minutes ( self ) :
"""Returns a DatetimeIndex representing all the minutes in this calendar .""" | opens_in_ns = self . _opens . values . astype ( 'datetime64[ns]' , ) . view ( 'int64' )
closes_in_ns = self . _closes . values . astype ( 'datetime64[ns]' , ) . view ( 'int64' )
return DatetimeIndex ( compute_all_minutes ( opens_in_ns , closes_in_ns ) , tz = UTC , ) |
def get_parsed_sked ( self , skedname ) :
"""Returns an array because multiple sked K ' s are allowed""" | if not self . processed :
raise Exception ( "Filing must be processed to return parsed sked" )
if skedname in self . schedules :
matching_skeds = [ ]
for sked in self . result :
if sked [ 'schedule_name' ] == skedname :
matching_skeds . append ( sked )
return matching_skeds
else :
... |
def _partition_index_names ( provisioned_index_names , index_names ) :
'''Returns 3 disjoint sets of indexes : existing , to be created , and to be deleted .''' | existing_index_names = set ( )
new_index_names = set ( )
for name in index_names :
if name in provisioned_index_names :
existing_index_names . add ( name )
else :
new_index_names . add ( name )
index_names_to_be_deleted = provisioned_index_names - existing_index_names
return existing_index_names... |
def _desy_bookkeeping2marc ( self , key , value ) :
"""Populate the ` ` 595 _ D ` ` MARC field .
Also populates the ` ` 035 ` ` MARC field through side effects .""" | if 'identifier' not in value :
return { 'a' : value . get ( 'expert' ) , 'd' : value . get ( 'date' ) , 's' : value . get ( 'status' ) , }
self . setdefault ( '035' , [ ] ) . append ( { '9' : 'DESY' , 'z' : value [ 'identifier' ] } ) |
def delete_user ( self , user ) :
"""Delete user and all data""" | assert self . user == 'catroot' or self . user == 'postgres'
assert not user == 'public'
con = self . connection or self . _connect ( )
cur = con . cursor ( )
cur . execute ( 'DROP SCHEMA {user} CASCADE;' . format ( user = user ) )
cur . execute ( 'REVOKE USAGE ON SCHEMA public FROM {user};' . format ( user = user ) )
... |
def role_create ( auth = None , ** kwargs ) :
'''Create a role
CLI Example :
. . code - block : : bash
salt ' * ' keystoneng . role _ create name = role1
salt ' * ' keystoneng . role _ create name = role1 domain _ id = b62e76fbeeff4e8fb77073f591cf211e''' | cloud = get_operator_cloud ( auth )
kwargs = _clean_kwargs ( keep_name = True , ** kwargs )
return cloud . create_role ( ** kwargs ) |
def from_client_secrets_file ( cls , client_secrets_file , scopes , ** kwargs ) :
"""Creates a : class : ` Flow ` instance from a Google client secrets file .
Args :
client _ secrets _ file ( str ) : The path to the client secrets . json
file .
scopes ( Sequence [ str ] ) : The list of scopes to request dur... | with open ( client_secrets_file , 'r' ) as json_file :
client_config = json . load ( json_file )
return cls . from_client_config ( client_config , scopes = scopes , ** kwargs ) |
def hsvToRGB ( h , s , v ) :
"""Convert HSV ( hue , saturation , value ) color space to RGB ( red , green blue )
color space .
* * Parameters * *
* * h * * : float
Hue , a number in [ 0 , 360 ] .
* * s * * : float
Saturation , a number in [ 0 , 1 ] .
* * v * * : float
Value , a number in [ 0 , 1 ] .... | hi = math . floor ( h / 60.0 ) % 6
f = ( h / 60.0 ) - math . floor ( h / 60.0 )
p = v * ( 1.0 - s )
q = v * ( 1.0 - ( f * s ) )
t = v * ( 1.0 - ( ( 1.0 - f ) * s ) )
D = { 0 : ( v , t , p ) , 1 : ( q , v , p ) , 2 : ( p , v , t ) , 3 : ( p , q , v ) , 4 : ( t , p , v ) , 5 : ( v , p , q ) }
return D [ hi ] |
def disco ( version , co , out = None , is_pypy = False ) :
"""diassembles and deparses a given code block ' co '""" | assert iscode ( co )
# store final output stream for case of error
real_out = out or sys . stdout
print ( '# Python %s' % version , file = real_out )
if co . co_filename :
print ( '# Embedded file name: %s' % co . co_filename , file = real_out )
scanner = get_scanner ( version , is_pypy = is_pypy )
queue = deque ( ... |
def _connect_mitogen_su ( spec ) :
"""Return ContextService arguments for su as a first class connection .""" | return { 'method' : 'su' , 'kwargs' : { 'username' : spec . remote_user ( ) , 'password' : spec . password ( ) , 'python_path' : spec . python_path ( ) , 'su_path' : spec . become_exe ( ) , 'connect_timeout' : spec . timeout ( ) , 'remote_name' : get_remote_name ( spec ) , } } |
def tag_id ( self , name ) :
"""Get the unique tag identifier for a given tag .
: param name : The tag
: type name : str
: rtype : str""" | return self . _store . get ( self . tag_key ( name ) ) or self . reset_tag ( name ) |
def compute_csets_TRAM ( connectivity , state_counts , count_matrices , equilibrium_state_counts = None , ttrajs = None , dtrajs = None , bias_trajs = None , nn = None , factor = 1.0 , callback = None ) :
r"""Computes the largest connected sets in the produce space of Markov state and
thermodynamic states for TRA... | return _compute_csets ( connectivity , state_counts , count_matrices , ttrajs , dtrajs , bias_trajs , nn = nn , equilibrium_state_counts = equilibrium_state_counts , factor = factor , callback = callback ) |
def Verify ( self , mempool ) :
"""Verify the transaction .
Args :
mempool :
Returns :
bool : True if verified . False otherwise .""" | if self . Gas . value % 100000000 != 0 :
return False
return super ( InvocationTransaction , self ) . Verify ( mempool ) |
def _sim_colour ( r1 , r2 ) :
"""calculate the sum of histogram intersection of colour""" | return sum ( [ min ( a , b ) for a , b in zip ( r1 [ "hist_c" ] , r2 [ "hist_c" ] ) ] ) |
def options ( self , parser , env ) :
"""Configure with command line option ' - - filetype ' .""" | Plugin . options ( self , parser , env )
parser . add_option ( '--filetype' , action = 'append' , help = 'Specify additional filetypes to monitor.' ) |
def _diff_replication_group ( current , desired ) :
'''If you need to enhance what modify _ replication _ group ( ) considers when deciding what is to be
( or can be ) updated , add it to ' modifiable ' below . It ' s a dict mapping the param as used
in modify _ replication _ group ( ) to that in describe _ rep... | if current . get ( 'AutomaticFailover' ) is not None :
current [ 'AutomaticFailoverEnabled' ] = True if current [ 'AutomaticFailover' ] in ( 'enabled' , 'enabling' ) else False
modifiable = { # Amazingly , the AWS API provides NO WAY to query the current state of most repl group
# settings ! All we can do is send a... |
def get_readable_time_string ( seconds ) :
"""Returns human readable string from number of seconds""" | seconds = int ( seconds )
minutes = seconds // 60
seconds = seconds % 60
hours = minutes // 60
minutes = minutes % 60
days = hours // 24
hours = hours % 24
result = ""
if days > 0 :
result += "%d %s " % ( days , "Day" if ( days == 1 ) else "Days" )
if hours > 0 :
result += "%d %s " % ( hours , "Hour" if ( hours... |
def do_purge ( bare = False , downloads = False , allow_global = False ) :
"""Executes the purge functionality .""" | if downloads :
if not bare :
click . echo ( crayons . normal ( fix_utf8 ( "Clearing out downloads directory…" ) , bold = True ) )
vistir . path . rmtree ( project . download_location )
return
# Remove comments from the output , if any .
installed = set ( [ pep423_name ( pkg . project_name ) for pkg ... |
def asdict ( inst , recurse = True , filter = None , dict_factory = dict , retain_collection_types = False , ) :
"""Return the ` ` attrs ` ` attribute values of * inst * as a dict .
Optionally recurse into other ` ` attrs ` ` - decorated classes .
: param inst : Instance of an ` ` attrs ` ` - decorated class . ... | attrs = fields ( inst . __class__ )
rv = dict_factory ( )
for a in attrs :
v = getattr ( inst , a . name )
if filter is not None and not filter ( a , v ) :
continue
if recurse is True :
if has ( v . __class__ ) :
rv [ a . name ] = asdict ( v , True , filter , dict_factory , retai... |
def _contains_policies ( self , resource_properties ) :
"""Is there policies data in this resource ?
: param dict resource _ properties : Properties of the resource
: return : True if we can process this resource . False , otherwise""" | return resource_properties is not None and isinstance ( resource_properties , dict ) and self . POLICIES_PROPERTY_NAME in resource_properties |
def emitDataChanged ( self , regItem ) :
"""Emits the dataChagned signal for the regItem""" | leftIndex = self . indexFromItem ( regItem , col = 0 )
rightIndex = self . indexFromItem ( regItem , col = - 1 )
logger . debug ( "Data changed: {} ...{}" . format ( self . data ( leftIndex ) , self . data ( rightIndex ) ) )
self . dataChanged . emit ( leftIndex , rightIndex ) |
def astype ( self , dtype ) :
"""Cast & clone an ANTsImage to a given numpy datatype .
Map :
uint8 : unsigned char
uint32 : unsigned int
float32 : float
float64 : double""" | if dtype not in _supported_dtypes :
raise ValueError ( 'Datatype %s not supported. Supported types are %s' % ( dtype , _supported_dtypes ) )
pixeltype = _npy_to_itk_map [ dtype ]
return self . clone ( pixeltype ) |
def asJSON ( self ) :
"""returns the data source as JSON""" | self . _json = json . dumps ( self . asDictionary )
return self . _json |
def add_flag ( self , flag ) :
"""Add flag to the flags and memorize this attribute has changed so we can
regenerate it when outputting text .""" | super ( Entry , self ) . add_flag ( flag )
self . _changed_attrs . add ( 'flags' ) |
def launch_simulation ( self , parameter ) :
"""Launch a single simulation , using SimulationRunner ' s facilities .
This function is used by ParallelRunner ' s run _ simulations to map
simulation running over the parameter list .
Args :
parameter ( dict ) : the parameter combination to simulate .""" | return next ( SimulationRunner . run_simulations ( self , [ parameter ] , self . data_folder ) ) |
def getPrioritySortkey ( self ) :
"""Returns the key that will be used to sort the current Analysis , from
most prioritary to less prioritary .
: return : string used for sorting""" | analysis_request = self . getRequest ( )
if analysis_request is None :
return None
ar_sort_key = analysis_request . getPrioritySortkey ( )
ar_id = analysis_request . getId ( ) . lower ( )
title = sortable_title ( self )
if callable ( title ) :
title = title ( )
return '{}.{}.{}' . format ( ar_sort_key , ar_id ,... |
def main ( ) :
"""NAME
plotXY . py
DESCRIPTION
Makes simple X , Y plots
INPUT FORMAT
X , Y data in columns
SYNTAX
plotxy . py [ command line options ]
OPTIONS
- h prints this help message
- f FILE to set file name on command line
- c col1 col2 specify columns to plot
- xsig col3 specify xsig... | fmt , plot = 'svg' , 0
col1 , col2 = 0 , 1
sym , size = 'ro' , 50
xlab , ylab = '' , ''
lines = 0
if '-h' in sys . argv :
print ( main . __doc__ )
sys . exit ( )
if '-f' in sys . argv :
ind = sys . argv . index ( '-f' )
file = sys . argv [ ind + 1 ]
if '-fmt' in sys . argv :
ind = sys . argv . index... |
def get_operation_device ( self , operation_name ) :
"""The device of an operation .
Note that only tf operations have device assignments .
Args :
operation _ name : a string , name of an operation in the graph .
Returns :
a string or None , representing the device name .""" | operation = self . _name_to_operation ( operation_name )
if isinstance ( operation , tf . Operation ) :
return operation . device
else : # mtf . Operation
return None |
def _is_bright ( rgb ) :
"""Return whether a RGB color is bright or not .""" | r , g , b = rgb
gray = 0.299 * r + 0.587 * g + 0.114 * b
return gray >= .5 |
def find_hwpack_dir ( root ) :
"""search for hwpack dir under root .""" | root = path ( root )
log . debug ( 'files in dir: %s' , root )
for x in root . walkfiles ( ) :
log . debug ( ' %s' , x )
hwpack_dir = None
for h in ( root . walkfiles ( 'boards.txt' ) ) :
assert not hwpack_dir
hwpack_dir = h . parent
log . debug ( 'found hwpack: %s' , hwpack_dir )
assert hwpack_dir
ret... |
def addNode ( self , node ) :
"""Add a node to the graph referenced by the root""" | self . msg ( 4 , "addNode" , node )
try :
self . graph . restore_node ( node . graphident )
except GraphError :
self . graph . add_node ( node . graphident , node ) |
def to_json ( self ) :
"""Serialize object to json dict
: return : dict""" | res = dict ( )
res [ 'Count' ] = self . count
res [ 'Messages' ] = self . messages
res [ 'ForcedState' ] = self . forced
res [ 'ForcedKeyboard' ] = self . keyboard
res [ 'Entities' ] = list ( )
for item in self . entities :
res [ 'Entities' ] . append ( item . to_json ( ) )
res [ 'ForcedMessage' ] = self . forced_m... |
def string_to_integer ( value , strict = False ) :
"""Return an integer corresponding to the string representation of a
number .
@ param value : a string representation of an integer number .
@ param strict : indicate whether the specified string MUST be of a
valid integer number representation .
@ return... | if is_undefined ( value ) :
if strict :
raise ValueError ( 'The value cannot be null' )
return None
try :
return int ( value )
except ValueError :
raise ValueError ( 'The specified string "%s" does not represent an integer' % value ) |
def urljoin ( parent , url ) :
"""If url is relative , join parent and url . Else leave url as - is .
@ return joined url""" | if urlutil . url_is_absolute ( url ) :
return url
return urlparse . urljoin ( parent , url ) |
async def city ( self , city : str , state : str , country : str ) -> dict :
"""Return data for the specified city .""" | data = await self . _request ( 'get' , 'city' , params = { 'city' : city , 'state' : state , 'country' : country } )
return data [ 'data' ] |
def migrate ( belstr : str ) -> str :
"""Migrate BEL 1 to 2.0.0
Args :
bel : BEL 1
Returns :
bel : BEL 2""" | bo . ast = bel . lang . partialparse . get_ast_obj ( belstr , "2.0.0" )
return migrate_ast ( bo . ast ) . to_string ( ) |
def maybe_download_from_drive ( directory , filename , url ) :
"""Download filename from Google drive unless it ' s already in directory .
Args :
directory : path to the directory that will be used .
filename : name of the file to download to ( do nothing if it already exists ) .
url : URL to download from ... | if not tf . gfile . Exists ( directory ) :
tf . logging . info ( "Creating directory %s" % directory )
tf . gfile . MakeDirs ( directory )
filepath = os . path . join ( directory , filename )
confirm_token = None
if tf . gfile . Exists ( filepath ) :
tf . logging . info ( "Not downloading, file already foun... |
def delete_webhook ( self , id , ** data ) :
"""DELETE / webhooks / : id /
Deletes the specified : format : ` webhook ` object .""" | return self . delete ( "/webhooks/{0}/" . format ( id ) , data = data ) |
def face_midpoints ( self , simplices = None ) :
"""Identify the centroid of every simplex in the triangulation . If an array of
simplices is given then the centroids of only those simplices is returned .""" | if type ( simplices ) == type ( None ) :
simplices = self . simplices
mids = self . points [ simplices ] . mean ( axis = 1 )
mid_xpt , mid_ypt = mids [ : , 0 ] , mids [ : , 1 ]
return mid_xpt , mid_ypt |
def _get_components ( self , * component_types : Type ) -> Iterable [ Tuple [ int , ... ] ] :
"""Get an iterator for Entity and multiple Component sets .
: param component _ types : Two or more Component types .
: return : An iterator for Entity , ( Component1 , Component2 , etc )
tuples .""" | entity_db = self . _entities
comp_db = self . _components
try :
for entity in set . intersection ( * [ comp_db [ ct ] for ct in component_types ] ) :
yield entity , [ entity_db [ entity ] [ ct ] for ct in component_types ]
except KeyError :
pass |
def load_params ( self , params ) :
"""Load parameters from main configuration file
: param params : parameters list ( converted right at the beginning )
: type params :
: return : None""" | logger . debug ( "Alignak parameters:" )
for key , value in sorted ( self . clean_params ( params ) . items ( ) ) :
update_attribute = None
# Maybe it ' s a variable as $ USER $ or $ ANOTHERVARIABLE $
# so look at the first character . If it ' s a $ , it is a macro variable
# if it ends with $ too
i... |
def start ( opts , bot , event ) :
"""Usage : start [ - - name = < name > ]
Start a timer .
Without _ name _ , start the default timer .
To run more than one timer at once , pass _ name _ to start and stop .""" | name = opts [ '--name' ]
now = datetime . datetime . now ( )
bot . timers [ name ] = now
return bot . start_fmt . format ( now ) |
def fht ( zsrc , zrec , lsrc , lrec , off , factAng , depth , ab , etaH , etaV , zetaH , zetaV , xdirect , fhtarg , use_ne_eval , msrc , mrec ) :
r"""Hankel Transform using the Digital Linear Filter method .
The * Digital Linear Filter * method was introduced to geophysics by
[ Ghos70 ] _ , and made popular and... | # 1 . Get fhtargs
fhtfilt = fhtarg [ 0 ]
pts_per_dec = fhtarg [ 1 ]
lambd = fhtarg [ 2 ]
int_pts = fhtarg [ 3 ]
# 2 . Call the kernel
PJ = kernel . wavenumber ( zsrc , zrec , lsrc , lrec , depth , etaH , etaV , zetaH , zetaV , lambd , ab , xdirect , msrc , mrec , use_ne_eval )
# 3 . Carry out the dlf
fEM = dlf ( PJ , l... |
def write_result ( self , url_data ) :
"""Write url _ data . result .""" | if url_data . valid :
self . write ( u'<tr><td class="valid">' )
self . write ( self . part ( "result" ) )
self . write ( u'</td><td class="valid">' )
self . write ( cgi . escape ( _ ( "Valid" ) ) )
else :
self . write ( u'<tr><td class="error">' )
self . write ( self . part ( "result" ) )
s... |
def to_frame ( self , columns = None ) :
"""Make a DataFrame with the given columns .
Will always return a copy of the underlying table .
Parameters
columns : sequence or string , optional
Sequence of the column names desired in the DataFrame . A string
can also be passed if only one column is desired .
... | extra_cols = _columns_for_table ( self . name )
if columns is not None :
columns = [ columns ] if isinstance ( columns , str ) else columns
columns = set ( columns )
set_extra_cols = set ( extra_cols )
local_cols = set ( self . local . columns ) & columns - set_extra_cols
df = self . local [ list ( ... |
def katex_rendering_options ( app ) :
"""Strip katex _ options from enclosing { } and append ,""" | options = trim ( app . config . katex_options )
# Remove surrounding { }
if options . startswith ( '{' ) and options . endswith ( '}' ) :
options = trim ( options [ 1 : - 1 ] )
# If options is not empty , ensure it ends with ' , '
if options and not options . endswith ( ',' ) :
options += ','
return options |
def count_error_types ( graph : BELGraph ) -> Counter :
"""Count the occurrence of each type of error in a graph .
: return : A Counter of { error type : frequency }""" | return Counter ( exc . __class__ . __name__ for _ , exc , _ in graph . warnings ) |
def component ( self , ** kwargs ) :
"""Return a key that specifies data the sub - selection""" | kwargs_copy = self . base_dict . copy ( )
kwargs_copy . update ( ** kwargs )
self . _replace_none ( kwargs_copy )
try :
return NameFactory . component_format . format ( ** kwargs_copy )
except KeyError :
return None |
def _clean_tag ( name ) :
"""Cleans a tag . Removes illegal characters for instance .
Adapted from the TensorFlow function ` clean _ tag ( ) ` at
https : / / github . com / tensorflow / tensorflow / blob / master / tensorflow / python / ops / summary _ op _ util . py
Parameters
name : str
The original tag... | # In the past , the first argument to summary ops was a tag , which allowed
# arbitrary characters . Now we are changing the first argument to be the node
# name . This has a number of advantages ( users of summary ops now can
# take advantage of the tf name scope system ) but risks breaking existing
# usage , because ... |
def delete_router_by_name ( self , rtr_name , tenant_id ) :
"""Delete the openstack router and its interfaces given its name .
The interfaces should be already removed prior to calling this
function .""" | try :
routers = self . neutronclient . list_routers ( )
rtr_list = routers . get ( 'routers' )
for rtr in rtr_list :
if rtr_name == rtr [ 'name' ] :
self . neutronclient . delete_router ( rtr [ 'id' ] )
except Exception as exc :
LOG . error ( "Failed to get and delete router by name ... |
def guess_type_tag ( self , input_bytes , filename ) :
"""Try to guess the type _ tag for this sample""" | mime_to_type = { 'application/jar' : 'jar' , 'application/java-archive' : 'jar' , 'application/octet-stream' : 'data' , 'application/pdf' : 'pdf' , 'application/vnd.ms-cab-compressed' : 'cab' , 'application/vnd.ms-fontobject' : 'ms_font' , 'application/vnd.tcpdump.pcap' : 'pcap' , 'application/x-dosexec' : 'exe' , 'app... |
def autocomplete ( self ) :
"""Execute solr query for autocomplete""" | params = self . set_lay_params ( )
logging . info ( "PARAMS=" + str ( params ) )
results = self . solr . search ( ** params )
logging . info ( "Docs found: {}" . format ( results . hits ) )
return self . _process_layperson_results ( results ) |
def hkeys ( self , name , key_start , key_end , limit = 10 ) :
"""Return a list of the top ` ` limit ` ` keys between ` ` key _ start ` ` and
` ` key _ end ` ` in hash ` ` name ` `
Similiar with * * Redis . HKEYS * *
. . note : : The range is ( ` ` key _ start ` ` , ` ` key _ end ` ` ] . The ` ` key _ start `... | limit = get_positive_integer ( 'limit' , limit )
return self . execute_command ( 'hkeys' , name , key_start , key_end , limit ) |
def attach_service ( cls , service ) :
"""Allows you to attach one TCP and one HTTP service
deprecated : : 2.1.73 use http and tcp specific methods
: param service : A vyked TCP or HTTP service that needs to be hosted""" | invalid_service = True
_service_classes = { '_tcp_service' : TCPService , '_http_service' : HTTPService }
for key , value in _service_classes . items ( ) :
if isinstance ( service , value ) :
cls . _services [ key ] = service
invalid_service = False
break
if invalid_service :
cls . _logg... |
def Command ( self , target , source , action , ** kw ) :
"""Builds the supplied target files from the supplied
source files using the supplied action . Action may
be any type that the Builder constructor will accept
for an action .""" | bkw = { 'action' : action , 'target_factory' : self . fs . Entry , 'source_factory' : self . fs . Entry , }
try :
bkw [ 'source_scanner' ] = kw [ 'source_scanner' ]
except KeyError :
pass
else :
del kw [ 'source_scanner' ]
bld = SCons . Builder . Builder ( ** bkw )
return bld ( self , target , source , ** k... |
def k_array_rank_jit ( a ) :
"""Numba jit version of ` k _ array _ rank ` .
Notes
An incorrect value will be returned without warning or error if
overflow occurs during the computation . It is the user ' s
responsibility to ensure that the rank of the input array fits
within the range of possible values o... | k = len ( a )
idx = a [ 0 ]
for i in range ( 1 , k ) :
idx += comb_jit ( a [ i ] , i + 1 )
return idx |
def make ( self ) :
"""Instantiates an instance of the environment with appropriate kwargs""" | if self . _entry_point is None :
raise error . Error ( 'Attempting to make deprecated env {}. (HINT: is there a newer registered version of this env?)' . format ( self . id ) )
cls = load ( self . _entry_point )
env = cls ( ** self . _kwargs )
# Make the enviroment aware of which spec it came from .
env . spec = se... |
def parse_msg ( self , datafeed ) :
'''parse messages''' | message_parsed = [ ]
for message in datafeed :
mid = message [ 'id' ]
streamId = message [ 'streamId' ]
mstring = message [ 'message' ]
fromuser = message [ 'fromUserId' ]
timestamp = message [ 'timestamp' ]
timestamp_c = date . fromtimestamp ( int ( timestamp ) / 1000.0 )
hashes , mentions ... |
def _format_years ( years ) :
"""Format a list of ints into a string including ranges
Source : https : / / stackoverflow . com / a / 9471386/1307974""" | def sub ( x ) :
return x [ 1 ] - x [ 0 ]
ranges = [ ]
for k , iterable in groupby ( enumerate ( sorted ( years ) ) , sub ) :
rng = list ( iterable )
if len ( rng ) == 1 :
s = str ( rng [ 0 ] [ 1 ] )
else :
s = "{}-{}" . format ( rng [ 0 ] [ 1 ] , rng [ - 1 ] [ 1 ] )
ranges . append (... |
def split_text ( text_to_split ) :
"""Split text
Splits the debug text into its different parts : ' Time ' , ' LogLevel + Module Name ' , ' Debug message '
: param text _ to _ split : Text to split
: return : List containing the content of text _ to _ split split up""" | assert isinstance ( text_to_split , string_types )
try :
time , rest = text_to_split . split ( ': ' , 1 )
source , message = rest . split ( ':' , 1 )
except ValueError :
time = source = ""
message = text_to_split
return time . strip ( ) , source . strip ( ) , message . strip ( ) |
def get_parse ( self , uri , params = { } ) :
'''Convenience method to call get ( ) on an arbitrary URI and parse the response
into a JSON object . Raises an error on non - 200 response status .''' | return self . _request_parse ( self . get , uri , params ) |
def run_jobs ( delete_completed = False , ignore_errors = False , now = None ) :
"""Run scheduled jobs .
You may specify a date to be treated as the current time .""" | if ScheduledJob . objects . filter ( status = 'running' ) :
raise ValueError ( 'jobs in progress found; aborting' )
if now is None :
now = datetime . datetime . now ( )
expire_jobs ( now )
schedule_sticky_jobs ( )
start_scheduled_jobs ( now , delete_completed , ignore_errors ) |
def upload_napp ( self , metadata , package ) :
"""Upload the napp from the current directory to the napps server .""" | endpoint = os . path . join ( self . _config . get ( 'napps' , 'api' ) , 'napps' , '' )
metadata [ 'token' ] = self . _config . get ( 'auth' , 'token' )
request = self . make_request ( endpoint , json = metadata , package = package , method = "POST" )
if request . status_code != 201 :
KytosConfig ( ) . clear_token ... |
def execute ( self , eopatch ) :
"""Execute method that processes EOPatch and returns EOPatch""" | # pylint : disable = too - many - locals
feature_type , feature_name , new_feature_name = next ( self . feature ( eopatch ) )
# Make a copy not to change original numpy array
feature_data = eopatch [ feature_type ] [ feature_name ] . copy ( )
time_num , height , width , band_num = feature_data . shape
if time_num <= 1 ... |
def read_24bit_uint ( self ) :
"""Reads a 24 bit unsigned integer from the stream .
@ since : 0.4""" | order = None
if not self . _is_big_endian ( ) :
order = [ 0 , 8 , 16 ]
else :
order = [ 16 , 8 , 0 ]
n = 0
for x in order :
n += ( self . read_uchar ( ) << x )
return n |
def thumbUrl ( self ) :
"""Return url to for the thumbnail image .""" | key = self . firstAttr ( 'thumb' , 'parentThumb' , 'granparentThumb' )
return self . _server . url ( key , includeToken = True ) if key else None |
def load_config ( path = None , config = None , context = None ) :
"""Returns a dict with configuration details which is loaded from ( in this order ) :
- config
- can . rc
- Environment variables CAN _ INTERFACE , CAN _ CHANNEL , CAN _ BITRATE
- Config files ` ` / etc / can . conf ` ` or ` ` ~ / . can ` ` ... | # start with an empty dict to apply filtering to all sources
given_config = config or { }
config = { }
# use the given dict for default values
config_sources = [ given_config , can . rc , lambda _context : load_environment_config ( ) , # context is not supported
lambda _context : load_file_config ( path , _context ) ]
... |
def create ( self , name = None , ** kwargs ) :
"""Create a new project .
: param name : The name of the project .
: returns : An instance of the newly create project .
: rtype : renku . models . projects . Project""" | data = self . _client . api . create_project ( { 'name' : name } )
return self . Meta . model ( data , client = self . _client , collection = self ) |
def execute_substep ( stmt , global_def , global_vars , task = '' , task_params = '' , proc_vars = { } , shared_vars = [ ] , config = { } ) :
'''Execute a substep with specific input etc
Substep executed by this function should be self - contained . It can contain
tasks ( which will be sent to the master proces... | assert not env . zmq_context . closed
assert 'workflow_id' in proc_vars
assert 'step_id' in proc_vars
assert '_input' in proc_vars
assert '_output' in proc_vars
assert '_depends' in proc_vars
assert 'step_output' in proc_vars
assert '_index' in proc_vars
assert 'result_push_socket' in config [ "sockets" ]
# this should... |
def uri ( self ) :
"""Connection string to pass to ` ~ pymongo . mongo _ client . MongoClient ` .""" | if self . _uds_path :
uri = 'mongodb://%s' % ( quote_plus ( self . _uds_path ) , )
else :
uri = 'mongodb://%s' % ( format_addr ( self . _address ) , )
return uri + '/?ssl=true' if self . _ssl else uri |
def can_update_topics_to_sticky_topics ( self , forum , user ) :
"""Given a forum , checks whether the user can change its topic types to sticky topics .""" | return ( self . _perform_basic_permission_check ( forum , user , 'can_edit_posts' ) and self . _perform_basic_permission_check ( forum , user , 'can_post_stickies' ) ) |
def readkmz ( self , filename ) :
'''reads in a kmz file and returns xml nodes''' | # Strip quotation marks if neccessary
filename . strip ( '"' )
# Open the zip file ( as applicable )
if filename [ - 4 : ] == '.kml' :
fo = open ( filename , "r" )
fstring = fo . read ( )
fo . close ( )
elif filename [ - 4 : ] == '.kmz' :
zip = ZipFile ( filename )
for z in zip . filelist :
... |
def _populate_alternate_kwargs ( kwargs ) :
"""Translates the parsed arguments into a format used by generic ARM commands
such as the resource and lock commands .""" | resource_namespace = kwargs [ 'namespace' ]
resource_type = kwargs . get ( 'child_type_{}' . format ( kwargs [ 'last_child_num' ] ) ) or kwargs [ 'type' ]
resource_name = kwargs . get ( 'child_name_{}' . format ( kwargs [ 'last_child_num' ] ) ) or kwargs [ 'name' ]
_get_parents_from_parts ( kwargs )
kwargs [ 'resource_... |
def empty_topic ( self , topic ) :
"""Empty all the queued messages for an existing topic .""" | nsq . assert_valid_topic_name ( topic )
return self . _request ( 'POST' , '/topic/empty' , fields = { 'topic' : topic } ) |
def has_header_value ( headers , name , value ) :
"""Look in headers for a specific header name and value .
Both name and value are case insensitive .
@ return : True if header name and value are found
@ rtype : bool""" | name = name . lower ( )
value = value . lower ( )
for hname , hvalue in headers :
if hname . lower ( ) == name and hvalue . lower ( ) == value :
return True
return False |
def update_payload ( self , fields = None ) :
"""Wrap submitted data within an extra dict .""" | payload = super ( ConfigTemplate , self ) . update_payload ( fields )
if 'template_combinations' in payload :
payload [ 'template_combinations_attributes' ] = payload . pop ( 'template_combinations' )
return { u'config_template' : payload } |
def settrace ( host = None , stdoutToServer = False , stderrToServer = False , port = 5678 , suspend = True , trace_only_current_thread = False , overwrite_prev_trace = False , patch_multiprocessing = False , stop_at_frame = None , ) :
'''Sets the tracing function with the pydev debug function and initializes neede... | _set_trace_lock . acquire ( )
try :
_locked_settrace ( host , stdoutToServer , stderrToServer , port , suspend , trace_only_current_thread , patch_multiprocessing , stop_at_frame , )
finally :
_set_trace_lock . release ( ) |
def get_prefix_stripper ( strip_prefix ) :
"""Return function to strip ` strip _ prefix ` prefix from string if present
Parameters
prefix : str
Prefix to strip from the beginning of string if present
Returns
stripper : func
function such that ` ` stripper ( a _ string ) ` ` will strip ` prefix ` from
... | n = len ( strip_prefix )
def stripper ( path ) :
return path if not path . startswith ( strip_prefix ) else path [ n : ]
return stripper |
def bg_thread ( func ) :
"""A threading decorator
: param func :
: return :""" | @ functools . wraps ( func )
def wrapper ( * args , ** kwargs ) :
p = threading . Thread ( target = func , args = args , kwargs = kwargs )
p . start ( )
return wrapper |
def parse_inline ( text ) :
"""Takes a string of text from a text inline and returns a 3 tuple of
( name , value , * * kwargs ) .""" | m = INLINE_SPLITTER . match ( text )
if not m :
raise InlineUnparsableError
args = m . group ( 'args' )
name = m . group ( 'name' )
value = ""
kwtxt = ""
kwargs = { }
if args :
kwtxt = INLINE_KWARG_PARSER . search ( args ) . group ( 'kwargs' )
value = re . sub ( "%s\Z" % kwtxt , "" , args )
value = valu... |
def json_2_container ( json_obj ) :
"""transform json from Ariane server to local object
: param json _ obj : json from Ariane Server
: return : transformed container""" | LOGGER . debug ( "Container.json_2_container" )
if MappingService . driver_type != DriverFactory . DRIVER_REST :
if 'containerProperties' in json_obj :
properties = DriverTools . json2properties ( json_obj [ 'containerProperties' ] )
else :
properties = None
else :
properties = json_obj [ 'c... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.