signature stringlengths 29 44.1k | implementation stringlengths 0 85.2k |
|---|---|
def smart_search_vrf ( self , auth , query_str , search_options = None , extra_query = None ) :
"""Perform a smart search on VRF list .
* ` auth ` [ BaseAuth ]
AAA options .
* ` query _ str ` [ string ]
Search string
* ` search _ options ` [ options _ dict ]
Search options . See : func : ` search _ vrf ... | if search_options is None :
search_options = { }
self . _logger . debug ( "smart_search_vrf query string: %s" % query_str )
success , query = self . _parse_vrf_query ( query_str )
if not success :
return { 'interpretation' : query , 'search_options' : search_options , 'result' : [ ] , 'error' : True , 'error_me... |
def moments_match_ep ( self , obs , tau , v , Y_metadata_i = None ) :
"""Calculation of moments using quadrature
: param obs : observed output
: param tau : cavity distribution 1st natural parameter ( precision )
: param v : cavity distribution 2nd natural paramenter ( mu * precision )""" | # Compute first integral for zeroth moment .
# NOTE constant np . sqrt ( 2 * pi / tau ) added at the end of the function
mu = v / tau
sigma2 = 1. / tau
# Lets do these for now based on the same idea as Gaussian quadrature
# i . e . multiply anything by close to zero , and its zero .
f_min = mu - 20 * np . sqrt ( sigma2... |
def format_time ( time ) :
"""Formats the given time into HH : MM : SS""" | h , r = divmod ( time / 1000 , 3600 )
m , s = divmod ( r , 60 )
return "%02d:%02d:%02d" % ( h , m , s ) |
def package ( options ) :
"""Creates a tarball to use for building the system elsewhere""" | import pkg_resources
import tarfile
import geonode
version = geonode . get_version ( )
# Use GeoNode ' s version for the package name .
pkgname = 'GeoNode-%s-all' % version
# Create the output directory .
out_pkg = path ( pkgname )
out_pkg_tar = path ( "%s.tar.gz" % pkgname )
# Create a distribution in zip format for t... |
def insert ( self , packet , time = None , ** kwargs ) :
'''Insert a packet into the database
Arguments
packet
The : class : ` ait . core . tlm . Packet ` instance to insert into
the database
time
Optional parameter specifying the time value to use when inserting
the record into the database . Default... | fields = { }
pd = packet . _defn
for defn in pd . fields :
val = getattr ( packet . raw , defn . name )
if pd . history and defn . name in pd . history :
val = getattr ( packet . history , defn . name )
if val is not None and not ( isinstance ( val , float ) and math . isnan ( val ) ) :
fiel... |
def iterchildren ( self ) :
"""Iterates the subkeys for this Registry key .
@ rtype : iter of L { RegistryKey }
@ return : Iterator of subkeys .""" | handle = self . handle
index = 0
while 1 :
subkey = win32 . RegEnumKey ( handle , index )
if subkey is None :
break
yield self . child ( subkey )
index += 1 |
def match ( self , files ) :
"""Matches this pattern against the specified files .
* files * ( : class : ` ~ collections . abc . Iterable ` of : class : ` str ` ) contains
each file relative to the root directory ( e . g . , ` ` " relative / path / to / file " ` ` ) .
Returns an : class : ` ~ collections . ab... | raise NotImplementedError ( "{}.{} must override match()." . format ( self . __class__ . __module__ , self . __class__ . __name__ ) ) |
def write ( self , frame ) :
"""Write frame to Bus .""" | if not isinstance ( frame , FrameBase ) :
raise PyVLXException ( "Frame not of type FrameBase" , frame_type = type ( frame ) )
PYVLXLOG . debug ( "SEND: %s" , frame )
self . transport . write ( slip_pack ( bytes ( frame ) ) ) |
def __init_keystone_session ( self ) :
"""Create and return a Keystone session object .""" | api = self . _identity_api_version
# for readability
tried = [ ]
if api in [ '3' , None ] :
sess = self . __init_keystone_session_v3 ( check = ( api is None ) )
tried . append ( 'v3' )
if sess :
return sess
if api in [ '2' , None ] :
sess = self . __init_keystone_session_v2 ( check = ( api is No... |
def a2bits_list ( chars : str , encoding : str = "UTF-8" ) -> List [ str ] :
"""Convert a string to its bits representation as a list of 0 ' s and 1 ' s .
> > > a2bits _ list ( " Hello World ! " )
[ ' 01001000 ' ,
'01100101 ' ,
'01101100 ' ,
'01101100 ' ,
'01101111 ' ,
'00100000 ' ,
'01010111 ' ,
... | return [ bin ( ord ( x ) ) [ 2 : ] . rjust ( ENCODINGS [ encoding ] , "0" ) for x in chars ] |
def style_classpath ( self , products , scheduler ) :
"""Returns classpath as paths for scalastyle .""" | classpath_entries = self . _tool_classpath ( 'scalastyle' , products , scheduler )
return [ classpath_entry . path for classpath_entry in classpath_entries ] |
def get_ht_mcs ( mcs ) :
"""http : / / git . kernel . org / cgit / linux / kernel / git / jberg / iw . git / tree / util . c ? id = v3.17 # n591.
Positional arguments :
mcs - - bytearray .
Returns :
Dict .""" | answers = dict ( )
max_rx_supp_data_rate = ( mcs [ 10 ] & ( ( mcs [ 11 ] & 0x3 ) << 8 ) )
tx_mcs_set_defined = not not ( mcs [ 12 ] & ( 1 << 0 ) )
tx_mcs_set_equal = not ( mcs [ 12 ] & ( 1 << 1 ) )
tx_max_num_spatial_streams = ( ( mcs [ 12 ] >> 2 ) & 3 ) + 1
tx_unequal_modulation = not not ( mcs [ 12 ] & ( 1 << 4 ) )
i... |
def pdf ( self , x , e = 0. , w = 1. , a = 0. ) :
"""probability density function
see : https : / / en . wikipedia . org / wiki / Skew _ normal _ distribution
: param x : input value
: param e :
: param w :
: param a :
: return :""" | t = ( x - e ) / w
return 2. / w * stats . norm . pdf ( t ) * stats . norm . cdf ( a * t ) |
def indent ( lines , spaces = 4 ) :
"""Indent ` lines ` by ` spaces ` spaces .
Parameters
lines : Union [ str , List [ str ] ]
A string or list of strings to indent
spaces : int
The number of spaces to indent ` lines `
Returns
indented _ lines : str""" | if isinstance ( lines , str ) :
text = [ lines ]
text = '\n' . join ( lines )
return textwrap . indent ( text , ' ' * spaces ) |
def prop_set ( prop , value , extra_args = None , cibfile = None ) :
'''Set the value of a cluster property
prop
name of the property
value
value of the property prop
extra _ args
additional options for the pcs property command
cibfile
use cibfile instead of the live CIB
CLI Example :
. . code -... | return item_create ( item = 'property' , item_id = '{0}={1}' . format ( prop , value ) , item_type = None , create = 'set' , extra_args = extra_args , cibfile = cibfile ) |
def request ( self ) :
"""Returns an OAuth2 Session to be used to make requests .
Returns None if a token hasn ' t yet been received .""" | headers = { 'Accept' : 'application/json' }
# Use API Key if possible
if self . api_key :
headers [ 'X-API-KEY' ] = self . api_key
return requests , headers
else : # Try to use OAuth
if self . token :
return OAuth2Session ( self . client_id , token = self . token ) , headers
else :
raise... |
def process_rule ( self , m , dct , tpe ) :
"""uses the MapRule ' m ' to run through the ' dict '
and extract data based on the rule""" | print ( 'TODO - ' + tpe + ' + applying rule ' + str ( m ) . replace ( '\n' , '' ) ) |
def iterRun ( self , sqlTail = '' , raw = False ) :
"""Compile filters and run the query and returns an iterator . This much more efficient for large data sets but
you get the results one element at a time . One thing to keep in mind is that this function keeps the cursor open , that means that the sqlite databae... | sql , sqlValues = self . getSQLQuery ( )
cur = self . con . execute ( '%s %s' % ( sql , sqlTail ) , sqlValues )
for v in cur :
if not raw :
yield RabaPupa ( self . rabaClass , v [ 0 ] )
else :
yield v |
def get_instance ( self , payload ) :
"""Build an instance of UserBindingInstance
: param dict payload : Payload response from the API
: returns : twilio . rest . chat . v2 . service . user . user _ binding . UserBindingInstance
: rtype : twilio . rest . chat . v2 . service . user . user _ binding . UserBindi... | return UserBindingInstance ( self . _version , payload , service_sid = self . _solution [ 'service_sid' ] , user_sid = self . _solution [ 'user_sid' ] , ) |
def get_authorizations ( self ) :
"""Gets the authorization list resulting from the search .
return : ( osid . authorization . AuthorizationList ) - the
authorization list
raise : IllegalState - list has already been retrieved
* compliance : mandatory - - This method must be implemented . *""" | if self . retrieved :
raise errors . IllegalState ( 'List has already been retrieved.' )
self . retrieved = True
return objects . AuthorizationList ( self . _results , runtime = self . _runtime ) |
def argmin ( self , axis = None , skipna = True ) :
"""Return a ndarray of the minimum argument indexer .
Parameters
axis : { None }
Dummy argument for consistency with Series
skipna : bool , default True
Returns
numpy . ndarray
See Also
numpy . ndarray . argmin""" | nv . validate_minmax_axis ( axis )
return nanops . nanargmin ( self . _values , skipna = skipna ) |
def reloadGraphs ( self ) :
"reloads the graph list" | r = self . connection . session . get ( self . graphsURL )
data = r . json ( )
if r . status_code == 200 :
self . graphs = { }
for graphData in data [ "graphs" ] :
try :
self . graphs [ graphData [ "_key" ] ] = GR . getGraphClass ( graphData [ "_key" ] ) ( self , graphData )
except K... |
def install ( self , package : str , option : str = '-r' ) -> None :
'''Push package to the device and install it .
Args :
option :
- l : forward lock application
- r : replace existing application
- t : allow test packages
- s : install application on sdcard
- d : allow version code downgrade ( debug... | if not os . path . isfile ( package ) :
raise FileNotFoundError ( f'{package!r} does not exist.' )
for i in option :
if i not in '-lrtsdg' :
raise ValueError ( f'There is no option named: {option!r}.' )
self . _execute ( '-s' , self . device_sn , 'install' , option , package ) |
def mnl_estimate ( data , chosen , numalts , GPU = False , coeffrange = ( - 3 , 3 ) , weights = None , lcgrad = False , beta = None ) :
"""Calculate coefficients of the MNL model .
Parameters
data : 2D array
The data are expected to be in " long " form where each row is for
one alternative . Alternatives ar... | logger . debug ( 'start: MNL fit with len(data)={} and numalts={}' . format ( len ( data ) , numalts ) )
atype = 'numpy' if not GPU else 'cuda'
numvars = data . shape [ 1 ]
numobs = data . shape [ 0 ] // numalts
if chosen is None :
chosen = np . ones ( ( numobs , numalts ) )
# used for latent classes
data = np . tr... |
def prepare_venn_axes ( ax , centers , radii ) :
'''Sets properties of the axis object to suit venn plotting . I . e . hides ticks , makes proper xlim / ylim .''' | ax . set_aspect ( 'equal' )
ax . set_xticks ( [ ] )
ax . set_yticks ( [ ] )
min_x = min ( [ centers [ i ] [ 0 ] - radii [ i ] for i in range ( len ( radii ) ) ] )
max_x = max ( [ centers [ i ] [ 0 ] + radii [ i ] for i in range ( len ( radii ) ) ] )
min_y = min ( [ centers [ i ] [ 1 ] - radii [ i ] for i in range ( len... |
def get_likes ( self ) -> Iterator [ 'Profile' ] :
"""Iterate over all likes of the post . A : class : ` Profile ` instance of each likee is yielded .""" | if self . likes == 0 : # Avoid doing additional requests if there are no comments
return
likes_edges = self . _field ( 'edge_media_preview_like' , 'edges' )
if self . likes == len ( likes_edges ) : # If the Post ' s metadata already contains all likes , don ' t do GraphQL requests to obtain them
yield from ( Pr... |
def normalized ( vector ) :
"""Get unit vector for a given one .
: param vector :
Numpy vector as coordinates in Cartesian space , or an array of such .
: returns :
Numpy array of the same shape and structure where all vectors are
normalized . That is , each coordinate component is divided by its
vector... | length = numpy . sum ( vector * vector , axis = - 1 )
length = numpy . sqrt ( length . reshape ( length . shape + ( 1 , ) ) )
return vector / length |
def tree_to_file ( tree : 'BubbleTree' , outfile : str ) :
"""Compute the gexf representation of given power graph ,
and push it into given file .""" | with open ( outfile , 'w' ) as fd :
fd . write ( tree_to_gexf ( tree ) ) |
def set_article_url ( self , resolve_doi = True ) :
"""If record has a DOI , set article URL based on where the DOI points .""" | if 'DOI' in self . record :
doi_url = "/" . join ( [ 'http://dx.doi.org' , self . record [ 'DOI' ] ] )
if resolve_doi :
try :
response = urlopen ( doi_url )
except URLError :
self . url = ''
else :
self . url = response . geturl ( )
else :
... |
def _shutdown_transport ( self ) :
"""Unwrap a Python 2.6 SSL socket , so we can call shutdown ( )""" | if HAVE_PY26_SSL and ( self . sslobj is not None ) :
self . sock = self . sslobj . unwrap ( )
self . sslobj = None |
def doctype_matches ( text , regex ) :
"""Check if the doctype matches a regular expression ( if present ) .
Note that this method only checks the first part of a DOCTYPE .
eg : ' html PUBLIC " - / / W3C / / DTD XHTML 1.0 Strict / / EN " '""" | m = doctype_lookup_re . match ( text )
if m is None :
return False
doctype = m . group ( 2 )
return re . compile ( regex , re . I ) . match ( doctype . strip ( ) ) is not None |
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 : StepContextContext for this StepContextInstance
: rtype : twilio . rest . studio . v1 . flow . engagement . step . step _ ... | if self . _context is None :
self . _context = StepContextContext ( self . _version , flow_sid = self . _solution [ 'flow_sid' ] , engagement_sid = self . _solution [ 'engagement_sid' ] , step_sid = self . _solution [ 'step_sid' ] , )
return self . _context |
def omit_deep ( omit_props , dct ) :
"""Implementation of omit that recurses . This tests the same keys at every level of dict and in lists
: param omit _ props :
: param dct :
: return :""" | omit_partial = omit_deep ( omit_props )
if isinstance ( dict , dct ) : # Filter out keys and then recurse on each value that wasn ' t filtered out
return map_dict ( omit_partial , compact_dict ( omit ( omit_props , dct ) ) )
if isinstance ( ( list , tuple ) , dct ) : # run omit _ deep on each value
return map (... |
def getAttachments ( self ) :
"""Get all : class : ` rtcclient . models . Attachment ` objects of
this workitem
: return : a : class : ` list ` contains all the
: class : ` rtcclient . models . Attachment ` objects
: rtype : list""" | attachment_tag = ( "rtc_cm:com.ibm.team.workitem.linktype." "attachment.attachment" )
return ( self . rtc_obj . _get_paged_resources ( "Attachment" , workitem_id = self . identifier , customized_attr = attachment_tag , page_size = "10" ) ) |
def prepare_dax ( self , grid_site = None , tmp_exec_dir = '.' , peg_frame_cache = None ) :
"""Sets up a pegasus script for the given dag""" | dag = self
log_path = self . __log_file_path
# this function creates the following three files needed by pegasus
peg_fh = open ( "pegasus_submit_dax" , "w" )
pegprop_fh = open ( "pegasus.properties" , "w" )
sitefile = open ( 'sites.xml' , 'w' )
# write the default properties
print >> pegprop_fh , PEGASUS_PROPERTIES % (... |
def store ( self , database , validate = True , role = None ) :
"""Store the document in the given database .
: param database : the ` Database ` object source for storing the document .
: return : an updated instance of ` Document ` / self .""" | if validate :
self . validate ( )
self . _id , self . _rev = database . save ( self . to_primitive ( role = role ) )
return self |
def _create_update_expression ( ) :
"""Create the grammar for an update expression""" | ine = ( Word ( "if_not_exists" ) + Suppress ( "(" ) + var + Suppress ( "," ) + var_val + Suppress ( ")" ) )
list_append = ( Word ( "list_append" ) + Suppress ( "(" ) + var_val + Suppress ( "," ) + var_val + Suppress ( ")" ) )
fxn = Group ( ine | list_append ) . setResultsName ( "set_function" )
# value has to come befo... |
def _add_g2p_assoc ( self , graph , strain_id , sex , assay_id , phenotypes , comment ) :
"""Create an association between a sex - specific strain id
and each of the phenotypes .
Here , we create a genotype from the strain ,
and a sex - specific genotype .
Each of those genotypes are created as anonymous no... | geno = Genotype ( graph )
model = Model ( graph )
eco_id = self . globaltt [ 'experimental phenotypic evidence' ]
strain_label = self . idlabel_hash . get ( strain_id )
# strain genotype
genotype_id = '_:' + '-' . join ( ( re . sub ( r':' , '' , strain_id ) , 'genotype' ) )
genotype_label = '[' + strain_label + ']'
sex... |
def covariance_mtx_to_superop ( self , mtx ) :
"""Converts a covariance matrix to the corresponding
superoperator , represented as a QuTiP Qobj
with ` ` type = " super " ` ` .""" | M = self . flat ( )
return qt . Qobj ( np . dot ( np . dot ( M . conj ( ) . T , mtx ) , M ) , dims = [ [ self . dims ] * 2 ] * 2 ) |
def clone ( self ) :
"""Returns a deep copy of self
Function clones :
* allocation
* nodes
Returns
type
Deep copy of self""" | new_route = self . __class__ ( self . _problem )
for node in self . nodes ( ) : # Insere new node on new route
new_node = node . __class__ ( node . _name , node . _demand )
new_route . allocate ( [ new_node ] )
return new_route |
def bovy_plot ( * args , ** kwargs ) :
"""NAME :
bovy _ plot
PURPOSE :
wrapper around matplotlib ' s plot function
INPUT :
see http : / / matplotlib . sourceforge . net / api / pyplot _ api . html # matplotlib . pyplot . plot
xlabel - ( raw string ! ) x - axis label , LaTeX math mode , no $ s needed
y... | overplot = kwargs . pop ( 'overplot' , False )
gcf = kwargs . pop ( 'gcf' , False )
onedhists = kwargs . pop ( 'onedhists' , False )
scatter = kwargs . pop ( 'scatter' , False )
loglog = kwargs . pop ( 'loglog' , False )
semilogx = kwargs . pop ( 'semilogx' , False )
semilogy = kwargs . pop ( 'semilogy' , False )
color... |
def transliterate ( self , word ) :
"""Transliterate the word from its source language to the target one .
The method works by encoding the word into English then decoding the new
Enlgish word to the target language .""" | encoded_word = self . encoder ( word )
decoded_word = self . decoder ( encoded_word )
return decoded_word |
def source_add ( source , source_type = 'imgapi' ) :
'''Add a new source
source : string
source url to add
source _ trype : string ( imgapi )
source type , either imgapi or docker
. . versionadded : : 2019.2.0
CLI Example :
. . code - block : : bash
salt ' * ' imgadm . source _ add https : / / updat... | ret = { }
# NOTE : there are some undocumented deprecated source types
# so we just warn instead of error on those
if source_type not in [ 'imgapi' , 'docker' ] :
log . warning ( 'Possible unsupported imgage source type specified!' )
cmd = 'imgadm sources -a {0} -t {1}' . format ( source , source_type )
res = __sal... |
def update_hostname ( self , prompt ) :
"""Update the hostname based on the prompt analysis .""" | result = re . search ( self . prompt_re , prompt )
if result :
hostname = result . group ( 'hostname' )
self . log ( "Hostname detected: {}" . format ( hostname ) )
else :
hostname = self . device . hostname
self . log ( "Hostname not set: {}" . format ( prompt ) )
return hostname |
async def container_load ( self , container_type , params = None , container = None , obj = None ) :
"""Loads container of elements from the reader . Supports the container ref .
Returns loaded container .
: param container _ type :
: param params :
: param container :
: param obj :
: return :""" | if isinstance ( obj , IModel ) :
obj = obj . val
if obj is None :
return NoSetSentinel ( )
c_len = len ( obj )
elem_type = params [ 0 ] if params else None
if elem_type is None :
elem_type = container_type . ELEM_TYPE
res = container if container else [ ]
for i in range ( c_len ) :
try :
self . ... |
def build_conflict_dict ( key_list , val_list ) :
"""Builds dict where a list of values is associated with more than one key
Args :
key _ list ( list ) :
val _ list ( list ) :
Returns :
dict : key _ to _ vals
CommandLine :
python - m utool . util _ dict - - test - build _ conflict _ dict
Example :
... | key_to_vals = defaultdict ( list )
for key , val in zip ( key_list , val_list ) :
key_to_vals [ key ] . append ( val )
return key_to_vals |
def clone_environment ( self , clone , name = None , prefix = None , ** kwargs ) :
"""Clone the environment ` clone ` into ` name ` or ` prefix ` .""" | cmd_list = [ 'create' , '--json' ]
if ( name and prefix ) or not ( name or prefix ) :
raise TypeError ( "conda clone_environment: exactly one of `name` " "or `path` required" )
if name :
cmd_list . extend ( [ '--name' , name ] )
if prefix :
cmd_list . extend ( [ '--prefix' , prefix ] )
cmd_list . extend ( [... |
def _load ( self , filename = None ) :
"""Read the SEVIRI rsr data""" | if not filename :
filename = self . seviri_path
wb_ = open_workbook ( filename )
self . rsr = { }
sheet_names = [ ]
for sheet in wb_ . sheets ( ) :
if sheet . name in [ 'Info' , 'Requirements' ] :
continue
ch_name = sheet . name . strip ( )
sheet_names . append ( sheet . name . strip ( ) )
s... |
def from_config ( cls , cp , model , nprocesses = 1 , use_mpi = False ) :
"""Loads the sampler from the given config file .
For generating the temperature ladder to be used by emcee _ pt , either
the number of temperatures ( provided by the option ' ntemps ' ) ,
or the path to a file storing inverse temperatu... | section = "sampler"
# check name
assert cp . get ( section , "name" ) == cls . name , ( "name in section [sampler] must match mine" )
# get the number of walkers to use
nwalkers = int ( cp . get ( section , "nwalkers" ) )
if cp . has_option ( section , "ntemps" ) and cp . has_option ( section , "inverse-temperatures-fi... |
def get_app_perms ( model_or_app_label ) :
"""Get permission - string list of the specified django application .
Parameters
model _ or _ app _ label : model class or string
A model class or app _ label string to specify the particular django
application .
Returns
set
A set of perms of the specified dj... | from django . contrib . auth . models import Permission
if isinstance ( model_or_app_label , string_types ) :
app_label = model_or_app_label
else : # assume model _ or _ app _ label is model class
app_label = model_or_app_label . _meta . app_label
qs = Permission . objects . filter ( content_type__app_label = a... |
def get_select_sql ( self ) :
"""Gets the SELECT field portion for the field without the alias . If the field
has a table , it will be included here like table . field
: return : Gets the SELECT field portion for the field without the alias
: rtype : str""" | if self . table :
return '{0}.{1}' . format ( self . table . get_identifier ( ) , self . name )
return '{0}' . format ( self . name ) |
def removeChild ( self , child ) :
"""Remove a child from this element . The child element is
returned , and it ' s parentNode element is reset .""" | super ( Table , self ) . removeChild ( child )
if child . tagName == ligolw . Column . tagName :
self . _update_column_info ( )
return child |
def upload ( df , gfile = "/New Spreadsheet" , wks_name = None , col_names = True , row_names = True , clean = True , credentials = None , start_cell = 'A1' , df_size = False , new_sheet_dimensions = ( 1000 , 100 ) ) :
'''Upload given Pandas DataFrame to Google Drive and returns
gspread Worksheet object
: param... | # access credentials
credentials = get_credentials ( credentials )
# auth for gspread
gc = gspread . authorize ( credentials )
try :
gc . open_by_key ( gfile ) . __repr__ ( )
gfile_id = gfile
except :
gfile_id = get_file_id ( credentials , gfile , write_access = True )
# Tuple of rows , cols in the datafram... |
def print_result ( self , audio_len , start , end ) :
"""Print result of SD .
: param audio _ len : the length of the entire audio file , in seconds
: type audio _ len : float
: param start : the start position of the spoken text
: type start : float
: param end : the end position of the spoken text
: t... | msg = [ ]
zero = 0
head_len = start
text_len = end - start
tail_len = audio_len - end
msg . append ( u"" )
msg . append ( u"Head: %.3f %.3f (%.3f)" % ( zero , start , head_len ) )
msg . append ( u"Text: %.3f %.3f (%.3f)" % ( start , end , text_len ) )
msg . append ( u"Tail: %.3f %.3f (%.3f)" % ( end , audio_len , tail_... |
def handle ( self , handler_name , request , suffix = '' ) :
"""Handle ` request ` with this block ' s runtime .""" | return self . runtime . handle ( self , handler_name , request , suffix ) |
def get_notebook ( note_store , my_notebook ) :
"""get the notebook from its name""" | notebook_id = 0
notebooks = note_store . listNotebooks ( )
# get the notebookGUID . . .
for notebook in notebooks :
if notebook . name . lower ( ) == my_notebook . lower ( ) :
notebook_id = notebook . guid
break
return notebook_id |
def plot ( self ) :
"""Plot basis functions over full range of knots .
Convenience function . Requires matplotlib .""" | try :
import matplotlib . pyplot as plt
except ImportError :
from sys import stderr
print ( "ERROR: matplotlib.pyplot not found, matplotlib must be installed to use this function" , file = stderr )
raise
x_min = np . min ( self . knot_vector )
x_max = np . max ( self . knot_vector )
x = np . linspace ( ... |
def run ( analysis , path = None , name = None , info = None , ** kwargs ) :
"""Run a single analysis .
: param Analysis analysis : Analysis class to run .
: param str path : Path of analysis . Can be ` _ _ file _ _ ` .
: param str name : Name of the analysis .
: param dict info : Optional entries are ` ` v... | kwargs . update ( { 'analysis' : analysis , 'path' : path , 'name' : name , 'info' : info , } )
main ( ** kwargs ) |
def as_processed_list ( func ) :
"""A decorator used to return a JSON response of a list of model
objects . It differs from ` as _ list ` in that it accepts a variety
of querying parameters and can use them to filter and modify the
results . It expects the decorated function to return either Model Class
to ... | @ wraps ( func )
def wrapper ( * args , ** kwargs ) :
func_argspec = inspect . getargspec ( func )
func_args = func_argspec . args
for kw in request . args :
if ( kw in func_args and kw not in RESTRICTED and not any ( request . args . get ( kw ) . startswith ( op ) for op in OPERATORS ) and not any ... |
def delete_row ( self , key , value ) :
"""Deletes the rows where key = value .""" | self . rows = filter ( lambda x : x . get ( key ) != value , self . rows ) |
def make_map ( ) :
"""Create , configure and return the routes Mapper""" | map = Mapper ( directory = config [ 'pylons.paths' ] [ 'controllers' ] , always_scan = config [ 'debug' ] )
# The ErrorController route ( handles 404/500 error pages ) ; it should
# likely stay at the top , ensuring it can always be resolved
map . connect ( 'error/:action/:id' , controller = 'error' )
# CUSTOM ROUTES H... |
def available ( name ) :
'''Check if a service is available on the system .
Args :
name ( str ) : The name of the service to check
Returns :
bool : ` ` True ` ` if the service is available , ` ` False ` ` otherwise
CLI Example :
. . code - block : : bash
salt ' * ' service . available < service name >... | for service in get_all ( ) :
if name . lower ( ) == service . lower ( ) :
return True
return False |
def vpn_sites ( self ) :
"""Instance depends on the API version :
* 2018-04-01 : : class : ` VpnSitesOperations < azure . mgmt . network . v2018_04_01 . operations . VpnSitesOperations > `""" | api_version = self . _get_api_version ( 'vpn_sites' )
if api_version == '2018-04-01' :
from . v2018_04_01 . operations import VpnSitesOperations as OperationClass
else :
raise NotImplementedError ( "APIVersion {} is not available" . format ( api_version ) )
return OperationClass ( self . _client , self . config... |
def Beta ( alpha : vertex_constructor_param_types , beta : vertex_constructor_param_types , label : Optional [ str ] = None ) -> Vertex :
"""One to one constructor for mapping some tensorShape of alpha and beta to
a matching tensorShaped Beta .
: param alpha : the alpha of the Beta with either the same tensorSh... | return Double ( context . jvm_view ( ) . BetaVertex , label , cast_to_double_vertex ( alpha ) , cast_to_double_vertex ( beta ) ) |
def wait_for_task ( upid , timeout = 300 ) :
'''Wait until a the task has been finished successfully''' | start_time = time . time ( )
info = _lookup_proxmox_task ( upid )
if not info :
log . error ( 'wait_for_task: No task information ' 'retrieved based on given criteria.' )
raise SaltCloudExecutionFailure
while True :
if 'status' in info and info [ 'status' ] == 'OK' :
log . debug ( 'Task has been fin... |
def filterAcceptsRow ( self , source_row , source_parent ) :
"""Exclude items in ` self . excludes `""" | model = self . sourceModel ( )
item = model . items [ source_row ]
key = getattr ( item , "filter" , None )
if key is not None :
regex = self . filterRegExp ( )
if regex . pattern ( ) :
match = regex . indexIn ( key )
return False if match == - 1 else True
# - - - Check if any family assigned to... |
def jdbc_datasource_absent ( name , both = True , server = None ) :
'''Ensures the JDBC Datasource doesn ' t exists
name
Name of the datasource
both
Delete both the pool and the resource , defaults to ` ` true ` `''' | ret = { 'name' : name , 'result' : None , 'comment' : None , 'changes' : { } }
pool_ret = _do_element_absent ( name , 'jdbc_connection_pool' , { 'cascade' : both } , server )
if not pool_ret [ 'error' ] :
if __opts__ [ 'test' ] and pool_ret [ 'delete' ] :
ret [ 'comment' ] = 'JDBC Datasource set to be delet... |
def chunkiter ( objs , n = 100 ) :
"""Chunk an iterator of unknown size . The optional
keyword ' n ' sets the chunk size ( default 100 ) .""" | objs = iter ( objs )
try :
while ( 1 ) :
chunk = [ ]
while len ( chunk ) < n :
chunk . append ( six . next ( objs ) )
yield chunk
except StopIteration :
pass
if len ( chunk ) :
yield chunk |
def get_chassis_name ( host = None , admin_username = None , admin_password = None ) :
'''Get the name of a chassis .
host
The chassis host .
admin _ username
The username used to access the chassis .
admin _ password
The password used to access the chassis .
CLI Example :
. . code - block : : bash ... | return bare_rac_cmd ( 'getchassisname' , host = host , admin_username = admin_username , admin_password = admin_password ) |
def is_redirect ( self ) :
'''Return whether the response contains a redirect code .''' | if self . _response :
status_code = self . _response . status_code
return status_code in self . _codes or status_code in self . _repeat_codes |
def imsurfit ( data , order , output_fit = False ) :
"""Fit a bidimensional polynomial to an image .
: param data : a bidimensional array
: param integer order : order of the polynomial
: param bool output _ fit : return the fitted image
: returns : a tuple with an array with the coefficients of the polynom... | # we create a grid with the same number of points
# between - 1 and 1
c0 = complex ( 0 , data . shape [ 0 ] )
c1 = complex ( 0 , data . shape [ 1 ] )
xx , yy = numpy . ogrid [ - 1 : 1 : c0 , - 1 : 1 : c1 ]
ncoeff = ( order + 1 ) * ( order + 2 ) // 2
powerlist = list ( _powers ( order ) )
# Array with ncoff x , y moment... |
def logpdf_link ( self , link_f , y , Y_metadata = None ) :
"""Log Likelihood Function given link ( f )
. . math : :
\\ ln p ( y _ { i } | \ lambda ( f _ { i } ) ) = \\ alpha _ { i } \\ log \\ beta - \\ log \\ Gamma ( \\ alpha _ { i } ) + ( \\ alpha _ { i } - 1) \\ log y _ { i } - \\ beta y _ { i } \\ \ \\ alph... | # alpha = self . gp _ link . transf ( gp ) * self . beta
# return ( 1 . - alpha ) * np . log ( obs ) + self . beta * obs - alpha * np . log ( self . beta ) + np . log ( special . gamma ( alpha ) )
alpha = link_f * self . beta
log_objective = alpha * np . log ( self . beta ) - np . log ( special . gamma ( alpha ) ) + ( ... |
def shutdown ( name ) :
'''Shut down Traffic Server on the local node .
. . code - block : : yaml
shutdown _ ats :
trafficserver . shutdown''' | ret = { 'name' : name , 'changes' : { } , 'result' : None , 'comment' : '' }
if __opts__ [ 'test' ] :
ret [ 'comment' ] = 'Shutting down local node'
return ret
__salt__ [ 'trafficserver.shutdown' ] ( )
ret [ 'result' ] = True
ret [ 'comment' ] = 'Shutdown local node'
return ret |
def build_by_builder ( self , builder : Builder , stats : BuildProcessStats ) :
"""run one builder , return statistics about the run""" | logger = logging . getLogger ( __name__ )
target_signature = builder . get_signature ( )
assert target_signature is not None , "builder signature is None"
if self . cache . list_sig_ok ( target_signature ) :
logger . info ( "verifying [{}]" . format ( builder . get_name ( ) ) )
file_bad = 0
file_correct = 0... |
def load_creditscoring2 ( cost_mat_parameters = None ) :
"""Load and return the credit scoring PAKDD 2009 competition dataset ( classification ) .
The credit scoring is a easily transformable example - dependent cost - sensitive classification dataset .
Parameters
cost _ mat _ parameters : Dictionary - like o... | module_path = dirname ( __file__ )
raw_data = pd . read_csv ( join ( module_path , 'data' , 'creditscoring2.csv.gz' ) , delimiter = '\t' , compression = 'gzip' )
descr = open ( join ( module_path , 'descr' , 'creditscoring2.rst' ) ) . read ( )
# Exclude TARGET _ LABEL _ BAD = 1 = = ' N '
raw_data = raw_data . loc [ raw... |
def list ( self , walkTrace = tuple ( ) , case = None , element = None ) :
"""List section titles .""" | if case == 'sectionmain' :
print ( walkTrace , self . title ) |
def transform ( self , flip_x , flip_y , swap_xy ) :
"""Transform view of the image .
. . note : :
Transforming the image is generally faster than rotating ,
if rotating in 90 degree increments . Also see : meth : ` rotate ` .
Parameters
flipx , flipy : bool
If ` True ` , flip the image in the X and Y a... | self . logger . debug ( "flip_x=%s flip_y=%s swap_xy=%s" % ( flip_x , flip_y , swap_xy ) )
with self . suppress_redraw :
self . t_ . set ( flip_x = flip_x , flip_y = flip_y , swap_xy = swap_xy ) |
def findAnyBracketBackward ( self , block , column ) :
"""Search for a needle and return ( block , column )
Raise ValueError , if not found
NOTE this methods ignores strings and comments""" | depth = { '()' : 1 , '[]' : 1 , '{}' : 1 }
for foundBlock , foundColumn , char in self . iterateCharsBackwardFrom ( block , column ) :
if self . _qpart . isCode ( foundBlock . blockNumber ( ) , foundColumn ) :
for brackets in depth . keys ( ) :
opening , closing = brackets
if char ==... |
def close ( self ) :
"""Disable al operations and close the underlying file - like object , if any""" | if callable ( getattr ( self . _file , 'close' , None ) ) :
self . _iterator . close ( )
self . _iterator = None
self . _unconsumed = None
self . closed = True |
def get_tool_variants ( self , tool_name ) :
"""Get the variant ( s ) that provide the named tool .
If there are more than one variants , the tool is in conflict , and Rez
does not know which variant ' s tool is actually exposed .
Args :
tool _ name ( str ) : Name of the tool to search for .
Returns :
S... | variants = set ( )
tools_dict = self . get_tools ( request_only = False )
for variant , tools in tools_dict . itervalues ( ) :
if tool_name in tools :
variants . add ( variant )
return variants |
def wait_until_page_does_not_contain ( self , text , timeout = None , error = None ) :
"""Waits until ` text ` disappears from current page .
Fails if ` timeout ` expires before the ` text ` disappears . See
` introduction ` for more information about ` timeout ` and its
default value .
` error ` can be use... | def check_present ( ) :
present = self . _is_text_present ( text )
if not present :
return
else :
return error or "Text '%s' did not disappear in %s" % ( text , self . _format_timeout ( timeout ) )
self . _wait_until_no_error ( timeout , check_present ) |
def name ( random = random , * args , ** kwargs ) :
"""Return someone ' s name
> > > mock _ random . seed ( 0)
> > > name ( random = mock _ random )
' carl poopbritches '
> > > mock _ random . seed ( 7)
> > > name ( random = mock _ random , capitalize = True )
' Duke Testy Wonderful '""" | if random . choice ( [ True , True , True , False ] ) :
return firstname ( random = random ) + " " + lastname ( random = random )
elif random . choice ( [ True , False ] ) :
return title ( random = random ) + " " + firstname ( random = random ) + " " + lastname ( random = random )
else :
return title ( rand... |
def get_raw_fixed_block ( self , unbuffered = False ) :
"""Get the raw " fixed block " of settings and min / max data .""" | if unbuffered or not self . _fixed_block :
self . _fixed_block = self . _read_fixed_block ( )
return self . _fixed_block |
def getModelSummaryAsGeoJson ( self , session , withStreamNetwork = True , withNodes = False ) :
"""Retrieve a GeoJSON representation of the model . Includes vectorized mask map and stream network .
Args :
session ( : mod : ` sqlalchemy . orm . session . Session ` ) : SQLAlchemy session object bound to PostGIS ... | # Get mask map
watershedMaskCard = self . getCard ( 'WATERSHED_MASK' )
maskFilename = watershedMaskCard . value
maskExtension = maskFilename . strip ( '"' ) . split ( '.' ) [ 1 ]
maskMap = session . query ( RasterMapFile ) . filter ( RasterMapFile . projectFile == self ) . filter ( RasterMapFile . fileExtension == mask... |
def encoding_chars ( self ) :
"""A ` ` dict ` ` with the encoding chars of the : class : ` Element < hl7apy . core . Element > ` .
If the : class : ` Element < hl7apy . core . Element > ` has a parent it is the parent ' s
` ` encoding _ chars ` ` otherwise the ones returned by
: func : ` get _ default _ encod... | if self . parent is not None :
return self . parent . encoding_chars
return get_default_encoding_chars ( self . version ) |
def generate_graph ( self ) :
"""Generate the graph ; return a 2 - tuple of strings , script to place in the
head of the HTML document and div content for the graph itself .
: return : 2 - tuple ( script , div )
: rtype : tuple""" | logger . debug ( 'Generating graph for %s' , self . _graph_id )
# tools to use
tools = [ PanTool ( ) , BoxZoomTool ( ) , WheelZoomTool ( ) , SaveTool ( ) , ResetTool ( ) , ResizeTool ( ) ]
# generate the stacked area graph
try :
g = Area ( self . _data , x = 'Date' , y = self . _y_series_names , title = self . _tit... |
def create_database ( dbpath , schema = '' , overwrite = True ) :
"""Create a new database at the given dbpath
Parameters
dbpath : str
The full path for the new database , including the filename and . db file extension .
schema : str
The path to the . sql schema for the database
overwrite : bool
Overw... | if dbpath . endswith ( '.db' ) :
if os . path . isfile ( dbpath ) and overwrite :
os . system ( 'rm {}' . format ( dbpath ) )
# Load the schema if given
if schema :
os . system ( "cat {} | sqlite3 {}" . format ( schema , dbpath ) )
# Otherwise just make an empty SOURCES table
else :
... |
def incver ( o , prop_names ) :
"""Increment the version numbers of a set of properties and return a new object""" | from ambry . identity import ObjectNumber
d = { }
for p in o . __mapper__ . attrs :
v = getattr ( o , p . key )
if v is None :
d [ p . key ] = None
elif p . key in prop_names :
d [ p . key ] = str ( ObjectNumber . increment ( v ) )
else :
if not hasattr ( v , '__mapper__' ) : # O... |
def get_lock_amount_after_fees ( lock : HashTimeLockState , payee_channel : NettingChannelState , ) -> PaymentWithFeeAmount :
"""Return the lock . amount after fees are taken .
Fees are taken only for the outgoing channel , which is the one with
collateral locked from this node .""" | return PaymentWithFeeAmount ( lock . amount - payee_channel . mediation_fee ) |
def plot_ps_extra ( dataobj , key , ** kwargs ) :
"""Create grouped pseudoplots for one or more time steps
Parameters
dataobj : : class : ` reda . containers . ERT `
An ERT container with loaded data
key : string
The column name to plot
subquery : string , optional
cbmin : float , optional
cbmax : f... | if isinstance ( dataobj , pd . DataFrame ) :
df_raw = dataobj
else :
df_raw = dataobj . data
if kwargs . get ( 'subquery' , False ) :
df = df_raw . query ( kwargs . get ( 'subquery' ) )
else :
df = df_raw
def fancyfy ( axes , N ) :
for ax in axes [ 0 : - 1 , : ] . flat :
ax . set_xlabel ( ''... |
def update ( self , * others ) :
"""Update the set , adding elements from all others .""" | self . db . sunionstore ( self . key , [ self . key ] + [ o . key for o in others ] ) |
def combine ( word_list , window = 2 ) :
"""构造在window下的单词组合 , 用来构造单词之间的边 。
Keyword arguments :
word _ list - - list of str , 由单词组成的列表 。
windows - - int , 窗口大小 。""" | if window < 2 :
window = 2
for x in range ( 1 , window ) :
if x >= len ( word_list ) :
break
word_list2 = word_list [ x : ]
res = zip ( word_list , word_list2 )
for r in res :
yield r |
def check ( ) :
"""Sanity check api deployment""" | t = time . time ( )
results = Client ( BASE_URL ) . version ( )
print ( "Endpoint" , BASE_URL )
print ( "Response Time %0.2f" % ( time . time ( ) - t ) )
print ( "Headers" )
for k , v in results . headers . items ( ) :
print ( " %s: %s" % ( k , v ) )
print ( "Body" )
print ( results . text ) |
def _process_pubmed_ids ( pubmed_ids ) :
"""Take a list of pubmed IDs and add PMID prefix
Args :
: param pubmed _ ids - string representing publication
ids seperated by a | symbol
Returns :
: return list : Pubmed curies""" | if pubmed_ids . strip ( ) == '' :
id_list = [ ]
else :
id_list = pubmed_ids . split ( '|' )
for ( i , val ) in enumerate ( id_list ) :
id_list [ i ] = 'PMID:' + val
return id_list |
def get_top_level_forum_url ( self ) :
"""Returns the parent forum from which forums are marked as read .""" | return ( reverse ( 'forum:index' ) if self . top_level_forum is None else reverse ( 'forum:forum' , kwargs = { 'slug' : self . top_level_forum . slug , 'pk' : self . kwargs [ 'pk' ] } , ) ) |
def complexidade ( obj ) :
"""Returns a value that indicates project health , currently FinancialIndicator
is used as this value , but it can be a result of calculation with other
indicators in future""" | indicators = obj . indicator_set . all ( )
if not indicators :
value = 0.0
else :
value = indicators . first ( ) . value
return value |
def apply_annotation ( self , annotation ) :
"""Apply a new annotation onto self , and return a new ValueSet object .
: param RegionAnnotation annotation : The annotation to apply .
: return : A new ValueSet object
: rtype : ValueSet""" | vs = self . copy ( )
vs . _merge_si ( annotation . region_id , annotation . region_base_addr , annotation . offset )
return vs |
def flatten ( inputs , scope = None ) :
"""Flattens the input while maintaining the batch _ size .
Assumes that the first dimension represents the batch .
Args :
inputs : a tensor of size [ batch _ size , . . . ] .
scope : Optional scope for name _ scope .
Returns :
a flattened tensor with shape [ batch... | if len ( inputs . get_shape ( ) ) < 2 :
raise ValueError ( 'Inputs must be have a least 2 dimensions' )
dims = inputs . get_shape ( ) [ 1 : ]
k = dims . num_elements ( )
with tf . name_scope ( scope , 'Flatten' , [ inputs ] ) :
return tf . reshape ( inputs , [ - 1 , k ] ) |
def threshold ( args ) :
"""Calculate motif score threshold for a given FPR .""" | if args . fpr < 0 or args . fpr > 1 :
print ( "Please specify a FPR between 0 and 1" )
sys . exit ( 1 )
motifs = read_motifs ( args . pwmfile )
s = Scanner ( )
s . set_motifs ( args . pwmfile )
s . set_threshold ( args . fpr , filename = args . inputfile )
print ( "Motif\tScore\tCutoff" )
for motif in motifs :
... |
def DataIterator ( data , checklines = 10 , transform = None , force_dialect_check = False , from_string = False , ** kwargs ) :
"""Iterate over features , no matter how they are provided .
Parameters
data : str , iterable of Feature objs , FeatureDB
` data ` can be a string ( filename , URL , or contents of ... | _kwargs = dict ( data = data , checklines = checklines , transform = transform , force_dialect_check = force_dialect_check , ** kwargs )
if isinstance ( data , six . string_types ) :
if from_string :
return _StringIterator ( ** _kwargs )
else :
if os . path . exists ( data ) :
return... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.