signature stringlengths 29 44.1k | implementation stringlengths 0 85.2k |
|---|---|
def deliver_dashboard ( schedule ) :
"""Given a schedule , delivery the dashboard as an email report""" | dashboard = schedule . dashboard
dashboard_url = _get_url_path ( 'Superset.dashboard' , dashboard_id = dashboard . id , )
# Create a driver , fetch the page , wait for the page to render
driver = create_webdriver ( )
window = config . get ( 'WEBDRIVER_WINDOW' ) [ 'dashboard' ]
driver . set_window_size ( * window )
driv... |
def get_parent_page ( self ) :
"""For ' parent ' in cms . api . create _ page ( )""" | if self . current_level == 1 : # ' root ' page
return None
else :
return self . page_data [ ( self . current_level - 1 , self . current_count ) ] |
def from_xxx ( cls , xxx ) :
"""Create a new Language instance from a LanguageID string
: param xxx : LanguageID as string
: return : Language instance with instance . xxx ( ) = = xxx if xxx is valid else instance of UnknownLanguage""" | xxx = str ( xxx ) . lower ( )
if xxx is 'unknown' :
return UnknownLanguage ( xxx )
try :
return cls . _from_xyz ( 'LanguageID' , xxx )
except NotALanguageException :
log . warning ( 'Unknown LanguageId: {}' . format ( xxx ) )
return UnknownLanguage ( xxx ) |
def logger ( message , level = 10 ) :
"""Handle logging .""" | logging . getLogger ( __name__ ) . log ( level , str ( message ) ) |
def send_errors_to_logging ( ) :
"""Send all VTK error / warning messages to Python ' s logging module""" | error_output = vtk . vtkStringOutputWindow ( )
error_win = vtk . vtkOutputWindow ( )
error_win . SetInstance ( error_output )
obs = Observer ( )
return obs . observe ( error_output ) |
def normalize_strategy_parameters ( params ) :
"""Normalize strategy parameters to be a list of strings .
Parameters
params : ( space - delimited ) string or sequence of strings / numbers Parameters
expected by : class : ` SampleStrategy ` object , in various forms , where the first
parameter is the name of... | def fixup_numbers ( val ) :
try : # See if it is a number
return str ( float ( val ) )
except ValueError : # ok , it is not a number we know of , perhaps a string
return str ( val )
if isinstance ( params , basestring ) :
params = params . split ( ' ' )
# No number
return tuple ( fixup_numbe... |
def _make_new_contig_from_nucmer_and_spades ( self , original_contig , hits , circular_spades , log_fh = None , log_outprefix = None ) :
'''Tries to make new circularised contig from contig called original _ contig . hits = list of nucmer hits , all with ref = original contg . circular _ spades = set of query conti... | writing_log_file = None not in [ log_fh , log_outprefix ]
hits_to_circular_contigs = [ x for x in hits if x . qry_name in circular_spades ]
if len ( hits_to_circular_contigs ) == 0 :
if writing_log_file :
print ( log_outprefix , original_contig , 'No matches to SPAdes circular contigs' , sep = '\t' , file =... |
def engine_list ( self ) :
""": returns : Return list of engines supported by GNS3 for the GNS3VM""" | download_url = "https://github.com/GNS3/gns3-gui/releases/download/v{version}/GNS3.VM.VMware.Workstation.{version}.zip" . format ( version = __version__ )
vmware_informations = { "engine_id" : "vmware" , "description" : 'VMware is the recommended choice for best performances.<br>The GNS3 VM can be <a href="{}">download... |
def set_organization ( self , organization ) : # type : ( Union [ hdx . data . organization . Organization , Dict , str ] ) - > None
"""Set the dataset ' s organization .
Args :
organization ( Union [ Organization , Dict , str ] ) : Either an Organization id or Organization metadata from an Organization object ... | if isinstance ( organization , hdx . data . organization . Organization ) or isinstance ( organization , dict ) :
if 'id' not in organization :
organization = hdx . data . organization . Organization . read_from_hdx ( organization [ 'name' ] , configuration = self . configuration )
organization = organi... |
def to_python ( self ) -> typing . Dict :
"""Get object as JSON serializable
: return :""" | self . clean ( )
result = { }
for name , value in self . values . items ( ) :
if name in self . props :
value = self . props [ name ] . export ( self )
if isinstance ( value , TelegramObject ) :
value = value . to_python ( )
if isinstance ( value , LazyProxy ) :
value = str ( value )... |
def comments_between_tokens ( token1 , token2 ) :
"""Find all comments between two tokens""" | if token2 is None :
buf = token1 . end_mark . buffer [ token1 . end_mark . pointer : ]
elif ( token1 . end_mark . line == token2 . start_mark . line and not isinstance ( token1 , yaml . StreamStartToken ) and not isinstance ( token2 , yaml . StreamEndToken ) ) :
return
else :
buf = token1 . end_mark . buffe... |
def get ( self , reference , country , target = datetime . date . today ( ) ) :
"""Get the inflation / deflation value change for the target date based
on the reference date . Target defaults to today and the instance ' s
reference and country will be used if they are not provided as
parameters""" | # Set country & reference to object ' s country & reference respectively
reference = self . reference if reference is None else reference
# Get the reference and target indices ( values ) from the source
reference_value = self . data . get ( reference , country ) . value
target_value = self . data . get ( target , coun... |
def _plot_neuron3d ( neuron , inline , ** kwargs ) :
'''Generates a figure of the neuron ,
that contains a soma and a list of trees .''' | return _plotly ( neuron , plane = '3d' , title = 'neuron-3D' , inline = inline , ** kwargs ) |
def set_led ( self , led , value ) :
"""Sets specified LED ( value of 0 to 127 ) to the specified value , 0 / False
for off and 1 ( or any True / non - zero value ) for on .""" | if led < 0 or led > 127 :
raise ValueError ( 'LED must be value of 0 to 127.' )
# Calculate position in byte buffer and bit offset of desired LED .
pos = led // 8
offset = led % 8
if not value : # Turn off the specified LED ( set bit to zero ) .
self . buffer [ pos ] &= ~ ( 1 << offset )
else : # Turn on the sp... |
def version ( ) :
"""Flask - AppBuilder package version""" | click . echo ( click . style ( "F.A.B Version: {0}." . format ( current_app . appbuilder . version ) , bg = "blue" , fg = "white" ) ) |
def retrieve ( self , id ) :
"""Retrieve a single source
Returns a single source available to the user by the provided id
If a source with the supplied unique identifier does not exist it returns an error
: calls : ` ` get / sources / { id } ` `
: param int id : Unique identifier of a Source .
: return : ... | _ , _ , source = self . http_client . get ( "/sources/{id}" . format ( id = id ) )
return source |
def siblings ( self , as_resources = False ) :
'''method to return hierarchical siblings of this resource .
Args :
as _ resources ( bool ) : if True , opens each as appropriate resource type instead of return URI only
Returns :
( list ) : list of resources''' | siblings = set ( )
# loop through parents and get children
for parent in self . parents ( as_resources = True ) :
for sibling in parent . children ( as_resources = as_resources ) :
siblings . add ( sibling )
# remove self
if as_resources :
siblings . remove ( self )
if not as_resources :
siblings . ... |
def computeMatchProbabilityOmega ( k , bMax , theta , nTrials = 100 ) :
"""The Omega match probability estimates the probability of matching when
both vectors have exactly b components in common . This function computes
this probability for b = 1 to bMax .
For each value of b this function :
1 ) Creates nTr... | omegaProb = np . zeros ( bMax + 1 )
for b in range ( 1 , bMax + 1 ) :
xwb = getSparseTensor ( b , b , nTrials , fixedRange = 1.0 / k )
xib = getSparseTensor ( b , b , nTrials , onlyPositive = True , fixedRange = 2.0 / k )
r = xwb . matmul ( xib . t ( ) )
numMatches = ( ( r >= theta ) . sum ( ) ) . item ... |
def get_server_type ( ) :
"""Checks server . ini for server type .""" | server_location_file = os . path . expanduser ( SERVER_LOCATION_FILE )
if not os . path . exists ( server_location_file ) :
raise Exception ( "%s not found. Please run 'loom server set " "<servertype>' first." % server_location_file )
config = ConfigParser . SafeConfigParser ( )
config . read ( server_location_file... |
def get_config_template ( namespace , method , version ) :
"""Get the configuration template for a method .
The method should exist in the methods repository .
Args :
namespace ( str ) : Method ' s namespace
method ( str ) : method name
version ( int ) : snapshot _ id of the method
Swagger :
https : /... | body = { "methodNamespace" : namespace , "methodName" : method , "methodVersion" : int ( version ) }
return __post ( "template" , json = body ) |
def parse_streams ( self ) :
"""Try to parse all input streams from file""" | logger . debug ( "Parsing streams of {}" . format ( self . input_file ) )
cmd = [ self . ffmpeg_normalize . ffmpeg_exe , '-i' , self . input_file , '-c' , 'copy' , '-t' , '0' , '-map' , '0' , '-f' , 'null' , NUL ]
cmd_runner = CommandRunner ( cmd )
cmd_runner . run_command ( )
output = cmd_runner . get_output ( )
logge... |
def context_exists ( self , name ) :
"""Check if a given context exists .""" | contexts = self . data [ 'contexts' ]
for context in contexts :
if context [ 'name' ] == name :
return True
return False |
def KMA ( inputfile_1 , gene_list , kma_db , out_path , sample_name , min_cov , mapping_path ) :
"""This function is called when KMA is the method of choice . The
function calls kma externally and waits for it to finish .
The kma output files with the prefixes . res and . aln are parsed
throught to obtain the... | # Get full path to input of output files
inputfile_1 = os . path . abspath ( inputfile_1 )
kma_outfile = os . path . abspath ( out_path + "/kma_out_" + sample_name )
kma_cmd = "%s -i %s -t_db %s -o %s -1t1 -gapopen -5 -gapextend -2 -penalty -3 -reward 1" % ( mapping_path , inputfile_1 , kma_db , kma_outfile )
# - ID 90... |
def _open_repo ( args , path_key = '<path>' ) :
"""Open and return the repository containing the specified file .
The file is specified by looking up ` path _ key ` in ` args ` . This value or
` None ` is passed to ` open _ repository ` .
Returns : A ` Repository ` instance .
Raises :
ExitError : If there... | path = pathlib . Path ( args [ path_key ] ) if args [ path_key ] else None
try :
repo = open_repository ( path )
except ValueError as exc :
raise ExitError ( ExitCode . DATA_ERR , str ( exc ) )
return repo |
def a2b_hashed_base58 ( s ) :
"""If the passed string is hashed _ base58 , return the binary data .
Otherwise raises an EncodingError .""" | data = a2b_base58 ( s )
data , the_hash = data [ : - 4 ] , data [ - 4 : ]
if double_sha256 ( data ) [ : 4 ] == the_hash :
return data
raise EncodingError ( "hashed base58 has bad checksum %s" % s ) |
def agenerator ( ) :
"""Arandom number generator""" | free_mem = psutil . virtual_memory ( ) . available
mem_24 = 0.24 * free_mem
mem_26 = 0.26 * free_mem
a = MemEater ( int ( mem_24 ) )
b = MemEater ( int ( mem_26 ) )
sleep ( 5 )
return free_mem / 1000 / 1000 , psutil . virtual_memory ( ) . available / 1000 / 1000 |
def __uncache ( self , file ) :
"""Uncaches given file .
: param file : File to uncache .
: type file : unicode""" | if file in self . __files_cache :
self . __files_cache . remove_content ( file ) |
def get_construction_table ( self , fragment_list = None , use_lookup = None , perform_checks = True ) :
"""Create a construction table for a Zmatrix .
A construction table is basically a Zmatrix without the values
for the bond lengths , angles and dihedrals .
It contains the whole information about which ref... | if use_lookup is None :
use_lookup = settings [ 'defaults' ] [ 'use_lookup' ]
if fragment_list is None :
self . get_bonds ( use_lookup = use_lookup )
self . _give_val_sorted_bond_dict ( use_lookup = use_lookup )
fragments = sorted ( self . fragmentate ( use_lookup = use_lookup ) , key = len , reverse = ... |
def geocode ( query ) :
"""Geocode a query string to ( lat , lon ) with the Nominatim geocoder .
Parameters
query : string
the query string to geocode
Returns
point : tuple
the ( lat , lon ) coordinates returned by the geocoder""" | # send the query to the nominatim geocoder and parse the json response
url_template = 'https://nominatim.openstreetmap.org/search?format=json&limit=1&q={}'
url = url_template . format ( query )
response = requests . get ( url , timeout = 60 )
results = response . json ( )
# if results were returned , parse lat and long... |
def interfaces ( self ) :
"""list [ dict ] : A list of dictionary items describing the operational
state of interfaces .
This method currently only lists the Physical Interfaces (
Gigabitethernet , tengigabitethernet , fortygigabitethernet ,
hundredgigabitethernet ) and Loopback interfaces . It currently
... | urn = "{urn:brocade.com:mgmt:brocade-interface-ext}"
int_ns = 'urn:brocade.com:mgmt:brocade-interface-ext'
result = [ ]
has_more = ''
last_interface_name = ''
last_interface_type = ''
while ( has_more == '' ) or ( has_more == 'true' ) :
request_interface = self . get_interface_detail_request ( last_interface_name ,... |
def etag ( self , etag ) :
"""Sets the etag of this BulkResponse .
etag
: param etag : The etag of this BulkResponse .
: type : str""" | if etag is None :
raise ValueError ( "Invalid value for `etag`, must not be `None`" )
if etag is not None and not re . search ( '[A-Za-z0-9]{0,256}' , etag ) :
raise ValueError ( "Invalid value for `etag`, must be a follow pattern or equal to `/[A-Za-z0-9]{0,256}/`" )
self . _etag = etag |
def _determine_slot ( self , * args ) :
"""figure out what slot based on command and args""" | if len ( args ) <= 1 :
raise RedisClusterException ( "No way to dispatch this command to Redis Cluster. Missing key." )
command = args [ 0 ]
if command in [ 'EVAL' , 'EVALSHA' ] :
numkeys = args [ 2 ]
keys = args [ 3 : 3 + numkeys ]
slots = { self . connection_pool . nodes . keyslot ( key ) for key in k... |
def addEvent ( self , event , fd , action ) :
"""Add a new win32 event to the event loop .""" | self . _events [ event ] = ( fd , action ) |
def updateData ( self , exten , data ) :
"""Write out updated data and header to
the original input file for this object .""" | _extnum = self . _interpretExten ( exten )
fimg = fileutil . openImage ( self . _filename , mode = 'update' , memmap = False )
fimg [ _extnum ] . data = data
fimg [ _extnum ] . header = self . _image [ _extnum ] . header
fimg . close ( ) |
def _get_vsan_eligible_disks ( service_instance , host , host_names ) :
'''Helper function that returns a dictionary of host _ name keys with either a list of eligible
disks that can be added to VSAN or either an ' Error ' message or a message saying no
eligible disks were found . Possible keys / values look li... | ret = { }
for host_name in host_names : # Get VSAN System Config Manager , if available .
host_ref = _get_host_ref ( service_instance , host , host_name = host_name )
vsan_system = host_ref . configManager . vsanSystem
if vsan_system is None :
msg = 'VSAN System Config Manager is unset for host \'{0... |
def table_from_root ( source , treename = None , columns = None , ** kwargs ) :
"""Read a Table from a ROOT tree""" | import root_numpy
# parse column filters into tree2array ` ` selection ` ` keyword
# NOTE : not all filters can be passed directly to root _ numpy , so we store
# those separately and apply them after - the - fact before returning
try :
selection = kwargs . pop ( 'selection' )
except KeyError : # no filters
fil... |
def prepare_native_return_state ( native_state ) :
"""Hook target for native function call returns .
Recovers and stores the return value from native memory and toggles the
state , s . t . execution continues in the Soot engine .""" | javavm_simos = native_state . project . simos
ret_state = native_state . copy ( )
# set successor flags
ret_state . regs . _ip = ret_state . callstack . ret_addr
ret_state . scratch . guard = ret_state . solver . true
ret_state . history . jumpkind = 'Ijk_Ret'
# if available , lookup the return value in native memory
r... |
def eval_in_system_namespace ( self , exec_str ) :
"""Get Callable for specified string ( for GUI - based editing )""" | ns = self . cmd_namespace
try :
return eval ( exec_str , ns )
except Exception as e :
self . logger . warning ( 'Could not execute %s, gave error %s' , exec_str , e )
return None |
def update ( self , ip_address = values . unset , friendly_name = values . unset , cidr_prefix_length = values . unset ) :
"""Update the IpAddressInstance
: param unicode ip _ address : An IP address in dotted decimal notation from which you want to accept traffic . Any SIP requests from this IP address will be a... | return self . _proxy . update ( ip_address = ip_address , friendly_name = friendly_name , cidr_prefix_length = cidr_prefix_length , ) |
def extract_headers ( lines , max_wrap_lines ) :
"""Extracts email headers from the given lines . Returns a dict with the
detected headers and the amount of lines that were processed .""" | hdrs = { }
header_name = None
# Track overlong headers that extend over multiple lines
extend_lines = 0
lines_processed = 0
for n , line in enumerate ( lines ) :
if not line . strip ( ) :
header_name = None
continue
match = HEADER_RE . match ( line )
if match :
header_name , header_v... |
def readline ( self , fmt = None ) :
"""Return next unformatted " line " . If format is given , unpack content ,
otherwise return byte string .""" | prefix_size = self . _fix ( )
if fmt is None :
content = self . read ( prefix_size )
else :
fmt = self . endian + fmt
fmt = _replace_star ( fmt , prefix_size )
content = struct . unpack ( fmt , self . read ( prefix_size ) )
try :
suffix_size = self . _fix ( )
except EOFError : # when endian is inval... |
def execute ( self ) :
"""Run all child tasks concurrently in separate threads .
Return last result after all child tasks have completed execution .""" | with self . _lock_c :
self . count = 0
self . numtasks = 0
self . taskset = [ ]
self . results = { }
self . totaltime = time . time ( )
# Start all tasks
for task in self . taskseq :
self . taskset . append ( task )
self . numtasks += 1
task . init_and_start ( self )
... |
def _validateIterCommonParams ( MaxObjectCount , OperationTimeout ) :
"""Validate common parameters for an iter . . . operation .
MaxObjectCount must be a positive non - zero integer or None .
OperationTimeout must be positive integer or zero
Raises :
ValueError : if these parameters are invalid""" | if MaxObjectCount is None or MaxObjectCount <= 0 :
raise ValueError ( _format ( "MaxObjectCount must be > 0 but is {0}" , MaxObjectCount ) )
if OperationTimeout is not None and OperationTimeout < 0 :
raise ValueError ( _format ( "OperationTimeout must be >= 0 but is {0}" , OperationTimeout ) ) |
def has_same_sumformula ( self , other ) :
"""Determines if ` ` other ` ` has the same sumformula
Args :
other ( molecule ) :
Returns :
bool :""" | same_atoms = True
for atom in set ( self [ 'atom' ] ) :
own_atom_number = len ( self [ self [ 'atom' ] == atom ] )
other_atom_number = len ( other [ other [ 'atom' ] == atom ] )
same_atoms = ( own_atom_number == other_atom_number )
if not same_atoms :
break
return same_atoms |
def top_stories ( self , raw = False , limit = None ) :
"""Returns list of item ids of current top stories
Args :
limit ( int ) : specifies the number of stories to be returned .
raw ( bool ) : Flag to indicate whether to represent all
objects in raw json .
Returns :
` list ` object containing ids of to... | top_stories = self . _get_stories ( 'topstories' , limit )
if raw :
top_stories = [ story . raw for story in top_stories ]
return top_stories |
def _get_stories ( self , page , limit ) :
"""Hacker News has different categories ( i . e . stories ) like
' topstories ' , ' newstories ' , ' askstories ' , ' showstories ' , ' jobstories ' .
This method , first fetches the relevant story ids of that category
The URL is : https : / / hacker - news . firebas... | url = urljoin ( self . base_url , f"{page}.json" )
story_ids = self . _get_sync ( url ) [ : limit ]
return self . get_items_by_ids ( item_ids = story_ids ) |
def encode_timeseries_put ( self , tsobj ) :
'''Returns an Erlang - TTB encoded tuple with the appropriate data and
metadata from a TsObject .
: param tsobj : a TsObject
: type tsobj : TsObject
: rtype : term - to - binary encoded object''' | if tsobj . columns :
raise NotImplementedError ( 'columns are not used' )
if tsobj . rows and isinstance ( tsobj . rows , list ) :
req_rows = [ ]
for row in tsobj . rows :
req_r = [ ]
for cell in row :
req_r . append ( self . encode_to_ts_cell ( cell ) )
req_rows . append... |
def add_multi_sign_transaction ( self , m : int , pub_keys : List [ bytes ] or List [ str ] , signer : Account ) :
"""This interface is used to generate an Transaction object which has multi signature .
: param tx : a Transaction object which will be signed .
: param m : the amount of signer .
: param pub _ k... | for index , pk in enumerate ( pub_keys ) :
if isinstance ( pk , str ) :
pub_keys [ index ] = pk . encode ( 'ascii' )
pub_keys = ProgramBuilder . sort_public_keys ( pub_keys )
tx_hash = self . hash256 ( )
sig_data = signer . generate_signature ( tx_hash )
if self . sig_list is None or len ( self . sig_list )... |
def colors ( palette ) :
"""Example endpoint return a list of colors by palette
This is using docstring for specifications
tags :
- colors
parameters :
- name : palette
in : path
type : string
enum : [ ' all ' , ' rgb ' , ' cmyk ' ]
required : true
default : all
description : Which palette to ... | all_colors = { 'cmyk' : [ 'cian' , 'magenta' , 'yellow' , 'black' ] , 'rgb' : [ 'red' , 'green' , 'blue' ] }
if palette == 'all' :
result = all_colors
else :
result = { palette : all_colors . get ( palette ) }
return jsonify ( result ) |
def map ( self , func , value_shape = None , dtype = None ) :
"""Apply an array - > array function to each block""" | mapped = self . values . map ( func , value_shape = value_shape , dtype = dtype )
return self . _constructor ( mapped ) . __finalize__ ( self , noprop = ( 'dtype' , ) ) |
def batch_means ( x , f = lambda y : y , theta = .5 , q = .95 , burn = 0 ) :
"""TODO : Use Bayesian CI .
Returns the half - width of the frequentist confidence interval
( q ' th quantile ) of the Monte Carlo estimate of E [ f ( x ) ] .
: Parameters :
x : sequence
Sampled series . Must be a one - dimension... | try :
import scipy
from scipy import stats
except ImportError :
raise ImportError ( 'SciPy must be installed to use batch_means.' )
x = x [ burn : ]
n = len ( x )
b = np . int ( n ** theta )
a = n / b
t_quant = stats . t . isf ( 1 - q , a - 1 )
Y = np . array ( [ np . mean ( f ( x [ i * b : ( i + 1 ) * b ] ... |
def safe_extract_proto_from_ipfs ( ipfs_client , ipfs_hash , protodir ) :
"""Tar files might be dangerous ( see https : / / bugs . python . org / issue21109,
and https : / / docs . python . org / 3 / library / tarfile . html , TarFile . extractall warning )
we extract only simple files""" | spec_tar = get_from_ipfs_and_checkhash ( ipfs_client , ipfs_hash )
with tarfile . open ( fileobj = io . BytesIO ( spec_tar ) ) as f :
for m in f . getmembers ( ) :
if ( os . path . dirname ( m . name ) != "" ) :
raise Exception ( "tarball has directories. We do not support it." )
if ( no... |
def create_api ( self ) :
"""Create the REST API .""" | created_api = self . client . create_rest_api ( name = self . trigger_settings . get ( 'api_name' , self . app_name ) )
api_id = created_api [ 'id' ]
self . log . info ( "Successfully created API" )
return api_id |
def export_plotter_vtkjs ( plotter , filename , compress_arrays = False ) :
"""Export a plotter ' s rendering window to the VTKjs format .""" | sceneName = os . path . split ( filename ) [ 1 ]
doCompressArrays = compress_arrays
# Generate timestamp and use it to make subdirectory within the top level output dir
timeStamp = time . strftime ( "%a-%d-%b-%Y-%H-%M-%S" )
root_output_directory = os . path . split ( filename ) [ 0 ]
output_dir = os . path . join ( roo... |
def parse_view ( query ) :
"""Parses asql query to view object .
Args :
query ( str ) : asql query
Returns :
View instance : parsed view .""" | try :
idx = query . lower ( ) . index ( 'where' )
query = query [ : idx ]
except ValueError :
pass
if not query . endswith ( ';' ) :
query = query . strip ( )
query += ';'
result = _view_stmt . parseString ( query )
return View ( result ) |
def clone ( self , choices ) :
"""Make a copy of this parameter , supply different choices .
@ param choices : A sequence of L { Option } instances .
@ type choices : C { list }
@ rtype : L { ChoiceParameter }""" | return self . __class__ ( self . name , choices , self . label , self . description , self . multiple , self . viewFactory ) |
def _set_show_firmware_option ( self , v , load = False ) :
"""Setter method for show _ firmware _ option , mapped from YANG variable / show / show _ firmware _ dummy / show _ firmware _ option ( container )
If this variable is read - only ( config : false ) in the
source YANG file , then _ set _ show _ firmwar... | if hasattr ( v , "_utype" ) :
v = v . _utype ( v )
try :
t = YANGDynClass ( v , base = show_firmware_option . show_firmware_option , is_container = 'container' , presence = False , yang_name = "show-firmware-option" , rest_name = "firmware" , parent = self , path_helper = self . _path_helper , extmethods = self... |
def graph_structure ( self , x1x2 ) :
"""Architecture of FlowNetCorr in Figure 2 of FlowNet 1.0.
Args :
x : 2CHW .""" | with argscope ( [ tf . layers . conv2d ] , activation = lambda x : tf . nn . leaky_relu ( x , 0.1 ) , padding = 'valid' , strides = 2 , kernel_size = 3 , data_format = 'channels_first' ) , argscope ( [ tf . layers . conv2d_transpose ] , padding = 'same' , activation = tf . identity , data_format = 'channels_first' , st... |
def show ( self , bAsync = True ) :
"""Make the window visible .
@ see : L { hide }
@ type bAsync : bool
@ param bAsync : Perform the request asynchronously .
@ raise WindowsError : An error occured while processing this request .""" | if bAsync :
win32 . ShowWindowAsync ( self . get_handle ( ) , win32 . SW_SHOW )
else :
win32 . ShowWindow ( self . get_handle ( ) , win32 . SW_SHOW ) |
def gt ( self , event_property , value ) :
"""A greater - than filter chain .
> > > request _ time = EventExpression ( ' request ' , ' elapsed _ ms ' )
> > > filtered = request _ time . gt ( ' elapsed _ ms ' , 500)
> > > print ( filtered )
request ( elapsed _ ms ) . gt ( elapsed _ ms , 500)""" | c = self . copy ( )
c . filters . append ( filters . GT ( event_property , value ) )
return c |
def retrieve ( cat_name , mw_instance = 'https://en.wikipedia.org' , types = [ 'page' , 'subcat' , 'file' ] , clean_subcat_names = False ) :
"""Retrieve pages that belong to a given category .
Args :
cat _ name : Category name e . g . ' Category : Presidents _ of _ the _ United _ States ' .
mw _ instance : Wh... | cmtype = f'&cmtype={"|".join(types)}'
base_url = f'{mw_instance}/w/api.php?action=query&format=json&list=categorymembers&cmtitle={cat_name}&cmlimit=500{cmtype}'
cont = ''
result = [ ]
while True :
url = f'{base_url}&cmcontinue={cont}'
r = requests . get ( url , timeout = 30 )
r . raise_for_status ( )
r_... |
def formatSI ( n ) -> str :
"""Format the integer or float n to 3 significant digits + SI prefix .""" | s = ''
if n < 0 :
n = - n
s += '-'
if type ( n ) is int and n < 1000 :
s = str ( n ) + ' '
elif n < 1e-22 :
s = '0.00 '
else :
assert n < 9.99e26
log = int ( math . floor ( math . log10 ( n ) ) )
i , j = divmod ( log , 3 )
for _try in range ( 2 ) :
templ = '%.{}f' . format ( 2 - ... |
def build_api_struct ( self ) :
"""Calls the clean method of the class and returns the info in a
structure that Atlas API is accepting .""" | self . clean ( )
data = { "type" : self . measurement_type }
# add all options
for option in self . used_options :
option_key , option_value = self . v2_translator ( option )
data . update ( { option_key : option_value } )
return data |
def _compute_term_r ( self , C , mag , rrup ) :
"""Compute distance term
d = log10 ( max ( R , rmin ) ) ;""" | if mag > self . M1 :
rrup_min = 0.55
elif mag > self . M2 :
rrup_min = - 2.80 * mag + 14.55
else :
rrup_min = - 0.295 * mag + 2.65
R = np . maximum ( rrup , rrup_min )
return np . log10 ( R ) |
def modify_request ( self , http_request = None ) :
"""Sets HTTP request components based on the URI .""" | if http_request is None :
http_request = HttpRequest ( )
if http_request . uri is None :
http_request . uri = Uri ( )
# Determine the correct scheme .
if self . scheme :
http_request . uri . scheme = self . scheme
if self . port :
http_request . uri . port = self . port
if self . host :
http_request... |
def gen_pdf ( rst_content , style_text , header = None , footer = FOOTER ) :
"""Create PDF file from ` rst _ content ` using ` style _ text ` as style .
Optinally , add ` header ` or ` footer ` .
Args :
rst _ content ( str ) : Content of the PDF file in restructured text markup .
style _ text ( str ) : Styl... | out_file_obj = StringIO ( )
with NamedTemporaryFile ( ) as f :
f . write ( style_text )
f . flush ( )
pdf = _init_pdf ( f . name , header , footer )
# create PDF
pdf . createPdf ( text = rst_content , output = out_file_obj , compressed = True )
# rewind file pointer to begin
out_file_obj . seek ( 0 )
return... |
def get_times ( ) :
"""Produce a deepcopy of the current timing data ( no risk of interference
with active timing or other operaitons ) .
Returns :
Times : gtimer timing data structure object .""" | if f . root . stopped :
return copy . deepcopy ( f . root . times )
else :
t = timer ( )
times = collapse . collapse_times ( )
f . root . self_cut += timer ( ) - t
return times |
def parse_xml_node ( self , node ) :
'''Parse an xml . dom Node object representing a message sending object
into this object .''' | self . _targets = [ ]
for c in node . getElementsByTagNameNS ( RTS_NS , 'targets' ) :
if c . getElementsByTagNameNS ( RTS_NS , 'WaitTime' ) :
new_target = WaitTime ( )
elif c . getElementsByTagNameNS ( RTS_NS , 'Preceding' ) :
new_target = Preceding ( )
else :
new_target = Condition ... |
def argsort2 ( indexable , key = None , reverse = False ) :
"""Returns the indices that would sort a indexable object .
This is similar to np . argsort , but it is written in pure python and works
on both lists and dictionaries .
Args :
indexable ( list or dict ) : indexable to sort by
Returns :
list : ... | # Create an iterator of value / key pairs
if isinstance ( indexable , dict ) :
vk_iter = ( ( v , k ) for k , v in indexable . items ( ) )
else :
vk_iter = ( ( v , k ) for k , v in enumerate ( indexable ) )
# Sort by values and extract the keys
if key is None :
indices = [ k for v , k in sorted ( vk_iter , r... |
def export ( self ) :
"""See DiskExportManager . export""" | with LogTask ( 'Exporting disk {} to {}' . format ( self . name , self . dst ) ) :
with utils . RollbackContext ( ) as rollback :
rollback . prependDefer ( shutil . rmtree , self . dst , ignore_errors = True )
self . copy ( )
if not self . disk [ 'format' ] == 'iso' :
self . spar... |
def neverCalledWith ( cls , spy , * args , ** kwargs ) : # pylint : disable = invalid - name
"""Checking the inspector is never called with partial args / kwargs
Args : SinonSpy , args / kwargs""" | cls . __is_spy ( spy )
if not ( spy . neverCalledWith ( * args , ** kwargs ) ) :
raise cls . failException ( cls . message ) |
def release_filename ( self , id_ ) :
"""Release a file name .""" | entry = self . __entries . get ( id_ )
if entry is None :
raise ValueError ( "Invalid filename id (%d)" % id_ )
# Decrease reference count and check if the entry has to be removed . . .
if entry . dec_ref_count ( ) == 0 :
del self . __entries [ id_ ]
del self . __id_lut [ entry . filename ] |
def _maybe_run_matchers ( self , text , run_matchers ) :
"""OverlayedText should be smart enough to not run twice the same
matchers but this is an extra handle of control over that .""" | if run_matchers is True or ( run_matchers is not False and text not in self . _overlayed_already ) :
text . overlay ( self . matchers )
self . _overlayed_already . append ( text ) |
def _find_family_class ( dev ) :
"""! @ brief Search the families list for matching entry .""" | for familyInfo in FAMILIES : # Skip if wrong vendor .
if dev . vendor != familyInfo . vendor :
continue
# Scan each level of families
for familyName in dev . families :
for regex in familyInfo . matches : # Require the regex to match the entire family name .
match = regex . match... |
def files_set_public_or_private ( self , request , set_public , files_queryset , folders_queryset ) :
"""Action which enables or disables permissions for selected files and files in selected folders to clipboard ( set them private or public ) .""" | if not self . has_change_permission ( request ) :
raise PermissionDenied
if request . method != 'POST' :
return None
check_files_edit_permissions ( request , files_queryset )
check_folder_edit_permissions ( request , folders_queryset )
# We define it like that so that we can modify it inside the set _ files
# f... |
def normpath ( path ) :
"""Normalize ` ` path ` ` , collapsing redundant separators and up - level refs .""" | scheme , netloc , path_ = parse ( path )
return unparse ( scheme , netloc , os . path . normpath ( path_ ) ) |
def _proxy ( self ) :
"""Generate an instance context for the instance , the context is capable of
performing various actions . All instance actions are proxied to the context
: returns : CredentialContext for this CredentialInstance
: rtype : twilio . rest . notify . v1 . credential . CredentialContext""" | if self . _context is None :
self . _context = CredentialContext ( self . _version , sid = self . _solution [ 'sid' ] , )
return self . _context |
def get_perm_codename ( perm , fail_silently = True ) :
"""Get permission codename from permission - string .
Examples
> > > get _ perm _ codename ( ' app _ label . codename _ model ' )
' codename _ model '
> > > get _ perm _ codename ( ' app _ label . codename ' )
' codename '
> > > get _ perm _ codena... | try :
perm = perm . split ( '.' , 1 ) [ 1 ]
except IndexError as e :
if not fail_silently :
raise e
return perm |
def _to_temperature ( self , temperature ) :
"""Step to a given temperature .
: param temperature : Get to this temperature .""" | self . _to_value ( self . _temperature , temperature , self . command_set . temperature_steps , self . _warmer , self . _cooler ) |
def _maybe_numeric_slice ( df , slice_ , include_bool = False ) :
"""want nice defaults for background _ gradient that don ' t break
with non - numeric data . But if slice _ is passed go with that .""" | if slice_ is None :
dtypes = [ np . number ]
if include_bool :
dtypes . append ( bool )
slice_ = IndexSlice [ : , df . select_dtypes ( include = dtypes ) . columns ]
return slice_ |
def tween2 ( self , val , frm , to ) :
"""linearly maps val between frm and to to a number between 0 and 1""" | return self . tween ( Mapping . linlin ( val , frm , to , 0 , 1 ) ) |
def _lt_from_gt ( self , other ) :
"""Return a < b . Computed by @ total _ ordering from ( not a > b ) and ( a ! = b ) .""" | op_result = self . __gt__ ( other )
if op_result is NotImplemented :
return NotImplemented
return not op_result and self != other |
def validate_keys ( self , * keys ) :
"""Validation helper to ensure that keys are present in data
This method makes sure that all of keys received here are
present in the data received from the caller .
It is better to call this method in the ` validate ( ) ` method of
your event . Not in the ` clean ( ) `... | current_keys = set ( self . data . keys ( ) )
needed_keys = set ( keys )
if not needed_keys . issubset ( current_keys ) :
raise ValidationError ( 'One of the following keys are missing from the ' 'event\'s data: {}' . format ( ', ' . join ( needed_keys . difference ( current_keys ) ) ) )
return True |
def limit_chord_unlock_tasks ( app ) :
"""Set max _ retries for chord . unlock tasks to avoid infinitely looping
tasks . ( see celery / celery # 1700 or celery / celery # 2725)""" | task = app . tasks [ 'celery.chord_unlock' ]
if task . max_retries is None :
retries = getattr ( app . conf , 'CHORD_UNLOCK_MAX_RETRIES' , None )
task . max_retries = retries |
def timedelta_to_duration ( dt ) :
"""Return a string according to the DURATION property format
from a timedelta object""" | days , secs = dt . days , dt . seconds
res = 'P'
if days // 7 :
res += str ( days // 7 ) + 'W'
days %= 7
if days :
res += str ( days ) + 'D'
if secs :
res += 'T'
if secs // 3600 :
res += str ( secs // 3600 ) + 'H'
secs %= 3600
if secs // 60 :
res += str ( secs // 60 ) + '... |
def _init_map ( self ) :
"""stub""" | SimpleDifficultyItemFormRecord . _init_map ( self )
SourceItemFormRecord . _init_map ( self )
PDFPreviewFormRecord . _init_map ( self )
PublishedFormRecord . _init_map ( self )
ProvenanceFormRecord . _init_map ( self )
super ( MecQBankBaseMixin , self ) . _init_map ( ) |
def _actionsFreqs ( self , * args , ** kwargs ) :
"""NAME :
actionsFreqs ( _ actionsFreqs )
PURPOSE :
evaluate the actions and frequencies ( jr , lz , jz , Omegar , Omegaphi , Omegaz )
INPUT :
Either :
a ) R , vR , vT , z , vz [ , phi ] :
1 ) floats : phase - space value for single object ( phi is opt... | fixed_quad = kwargs . pop ( 'fixed_quad' , False )
if len ( args ) == 5 : # R , vR . vT , z , vz
R , vR , vT , z , vz = args
elif len ( args ) == 6 : # R , vR . vT , z , vz , phi
R , vR , vT , z , vz , phi = args
else :
self . _parse_eval_args ( * args )
R = self . _eval_R
vR = self . _eval_vR
v... |
def get_securitygroup ( self , group_id , ** kwargs ) :
"""Returns the information about the given security group .
: param string id : The ID for the security group
: returns : A diction of information about the security group""" | if 'mask' not in kwargs :
kwargs [ 'mask' ] = ( 'id,' 'name,' 'description,' '''rules[id, remoteIp, remoteGroupId,
direction, ethertype, portRangeMin,
portRangeMax, protocol, createDate, modifyDate],''' '''networkComponentBindings[
networkCompone... |
def add_singles ( self , results ) :
"""Add singles to the bacckground estimate and find candidates
Parameters
results : dict of arrays
Dictionary of dictionaries indexed by ifo and keys such as ' snr ' ,
' chisq ' , etc . The specific format it determined by the
LiveBatchMatchedFilter class .
Returns
... | # Let ' s see how large everything is
logging . info ( 'BKG Coincs %s stored %s bytes' , len ( self . coincs ) , self . coincs . nbytes )
# If there are no results just return
valid_ifos = [ k for k in results . keys ( ) if results [ k ] and k in self . ifos ]
if len ( valid_ifos ) == 0 :
return { }
# Add single tr... |
def get_release_component ( comp ) :
"""Split the argument passed on the command line into a component name and expected version""" | name , vers = comp . split ( "-" )
if name not in comp_names :
print ( "Known components:" )
for comp in comp_names :
print ( "- %s" % comp )
raise EnvironmentError ( "Unknown release component name '%s'" % name )
return name , vers |
def connect ( cls , host , public_key , private_key , verbose = 0 , use_cache = True ) :
"""Connect the client with the given host and the provided credentials .
Parameters
host : str
The Cytomine host ( without protocol ) .
public _ key : str
The Cytomine public key .
private _ key : str
The Cytomine... | return cls ( host , public_key , private_key , verbose , use_cache ) |
def left_button_down ( self , obj , event_type ) :
"""Register the event for a left button down click""" | # Get 2D click location on window
click_pos = self . iren . GetEventPosition ( )
# Get corresponding click location in the 3D plot
picker = vtk . vtkWorldPointPicker ( )
picker . Pick ( click_pos [ 0 ] , click_pos [ 1 ] , 0 , self . renderer )
self . pickpoint = np . asarray ( picker . GetPickPosition ( ) ) . reshape (... |
def renamed_tree ( self , source , dest ) :
"""Directory was renamed in file explorer or in project explorer .""" | dirname = osp . abspath ( to_text_string ( source ) )
tofile = to_text_string ( dest )
for fname in self . get_filenames ( ) :
if osp . abspath ( fname ) . startswith ( dirname ) :
new_filename = fname . replace ( dirname , tofile )
self . renamed ( source = fname , dest = new_filename ) |
def vor_to_am ( vor ) :
r"""Given a Voronoi tessellation object from Scipy ' s ` ` spatial ` ` module ,
converts to a sparse adjacency matrix network representation in COO format .
Parameters
vor : Voronoi Tessellation object
This object is produced by ` ` scipy . spatial . Voronoi ` `
Returns
A sparse ... | # Create adjacency matrix in lil format for quick matrix construction
N = vor . vertices . shape [ 0 ]
rc = [ [ ] , [ ] ]
for ij in vor . ridge_dict . keys ( ) :
row = vor . ridge_dict [ ij ] . copy ( )
# Make sure voronoi cell closes upon itself
row . append ( row [ 0 ] )
# Add connections to rc list
... |
def heatmap_seaborn ( dfr , outfilename = None , title = None , params = None ) :
"""Returns seaborn heatmap with cluster dendrograms .
- dfr - pandas DataFrame with relevant data
- outfilename - path to output file ( indicates output format )""" | # Decide on figure layout size : a minimum size is required for
# aesthetics , and a maximum to avoid core dumps on rendering .
# If we hit the maximum size , we should modify font size .
maxfigsize = 120
calcfigsize = dfr . shape [ 0 ] * 1.1
figsize = min ( max ( 8 , calcfigsize ) , maxfigsize )
if figsize == maxfigsi... |
def job_path ( cls , project , location , job ) :
"""Return a fully - qualified job string .""" | return google . api_core . path_template . expand ( "projects/{project}/locations/{location}/jobs/{job}" , project = project , location = location , job = job , ) |
def template2features ( sent , i , token_syntax , debug = True ) :
""": type token : object""" | columns = [ ]
for j in range ( len ( sent [ 0 ] ) ) :
columns . append ( [ t [ j ] for t in sent ] )
matched = re . match ( "T\[(?P<index1>\-?\d+)(\,(?P<index2>\-?\d+))?\](\[(?P<column>.*)\])?(\.(?P<function>.*))?" , token_syntax )
column = matched . group ( "column" )
column = int ( column ) if column else 0
index... |
def neg_loglik ( self , beta ) :
"""Creates the negative log - likelihood of the model
Parameters
beta : np . array
Contains untransformed starting values for latent variables
Returns
The negative logliklihood of the model""" | lmda , Y , ___ , theta = self . _model ( beta )
return - np . sum ( logpdf ( Y , self . latent_variables . z_list [ - 3 ] . prior . transform ( beta [ - 3 ] ) , loc = theta , scale = np . exp ( lmda / 2.0 ) , skewness = self . latent_variables . z_list [ - 4 ] . prior . transform ( beta [ - 4 ] ) ) ) |
def weighted_random_choice ( items ) :
"""Returns a weighted random choice from a list of items .
: param items : A list of tuples ( object , weight )
: return : A random object , whose likelihood is proportional to its weight .""" | l = list ( items )
r = random . random ( ) * sum ( [ i [ 1 ] for i in l ] )
for x , p in l :
if p > r :
return x
r -= p
return None |
def find_shape ( self , canvas_x , canvas_y ) :
'''Look up shape based on canvas coordinates .''' | shape_x , shape_y , w = self . canvas_to_shapes_transform . dot ( [ canvas_x , canvas_y , 1 ] )
if hasattr ( self . space , 'point_query_first' ) : # Assume ` pymunk < 5.0 ` .
shape = self . space . point_query_first ( ( shape_x , shape_y ) )
else : # Assume ` pymunk > = 5.0 ` , where ` point _ query _ first ` meth... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.