signature stringlengths 29 44.1k | implementation stringlengths 0 85.2k |
|---|---|
def autostrip ( cls ) :
"""strip text fields before validation
example :
@ autostrip
class PersonForm ( forms . Form ) :
name = forms . CharField ( min _ length = 2 , max _ length = 10)
email = forms . EmailField ( )
Author : nail . xx""" | warnings . warn ( "django-annoying autostrip is deprecated and will be removed in a " "future version. Django now has native support for stripping form " "fields. " "https://docs.djangoproject.com/en/stable/ref/forms/fields/#django.forms.CharField.strip" , DeprecationWarning , stacklevel = 2 , )
fields = [ ( key , valu... |
def charts_slug_get ( self , slug , ** kwargs ) :
"""Chart
A Chart is chosen by Pollster editors . One example is \" Obama job approval - Democrats \" . It is always based upon a single Question . Users should strongly consider basing their analysis on Questions instead . Charts are derived data ; Pollster editor... | kwargs [ '_return_http_data_only' ] = True
if kwargs . get ( 'callback' ) :
return self . charts_slug_get_with_http_info ( slug , ** kwargs )
else :
( data ) = self . charts_slug_get_with_http_info ( slug , ** kwargs )
return data |
def secgroup_delete ( self , name ) :
'''Delete a security group''' | nt_ks = self . compute_conn
for item in nt_ks . security_groups . list ( ) :
if item . name == name :
nt_ks . security_groups . delete ( item . id )
return { name : 'Deleted security group: {0}' . format ( name ) }
return 'Security group not found: {0}' . format ( name ) |
def terminate ( self ) :
"""Properly terminates this player instance . Preferably use this instead of relying on python ' s garbage
collector to cause this to be called from the object ' s destructor .""" | self . handle , handle = None , self . handle
if threading . current_thread ( ) is self . _event_thread : # Handle special case to allow event handle to be detached .
# This is necessary since otherwise the event thread would deadlock itself .
grim_reaper = threading . Thread ( target = lambda : _mpv_terminate_dest... |
def applyUserPars_steps ( configObj , input_dict , step = '3a' ) :
"""Apply logic to turn on use of user - specified output WCS if user provides
any parameter on command - line regardless of how final _ wcs was set .""" | step_kws = { '7a' : 'final_wcs' , '3a' : 'driz_sep_wcs' }
stepname = getSectionName ( configObj , step )
finalParDict = configObj [ stepname ] . copy ( )
del finalParDict [ step_kws [ step ] ]
# interpret input _ dict to find any parameters for this step specified by the user
user_pars = { }
for kw in finalParDict :
... |
def decodeGsm7 ( encodedText ) :
"""GSM - 7 text decoding algorithm
Decodes the specified GSM - 7 - encoded string into a plaintext string .
: param encodedText : the text string to encode
: type encodedText : bytearray or str
: return : A string containing the decoded text
: rtype : str""" | result = [ ]
if type ( encodedText ) == str :
encodedText = rawStrToByteArray ( encodedText )
# bytearray ( encodedText )
iterEncoded = iter ( encodedText )
for b in iterEncoded :
if b == 0x1B : # ESC - switch to extended table
c = chr ( next ( iterEncoded ) )
for char , value in dictItemsIt... |
def find_references_origin ( irs ) :
"""Make lvalue of each Index , Member operation
points to the left variable""" | for ir in irs :
if isinstance ( ir , ( Index , Member ) ) :
ir . lvalue . points_to = ir . variable_left |
def rename ( self , new_relation ) :
"""Rename this cached relation to new _ relation .
Note that this will change the output of key ( ) , all refs must be
updated !
: param _ CachedRelation new _ relation : The new name to apply to the
relation""" | # Relations store this stuff inside their ` path ` dict . But they
# also store a table _ name , and usually use it in their . render ( ) ,
# so we need to update that as well . It doesn ' t appear that
# table _ name is ever anything but the identifier ( via . create ( ) )
self . inner = self . inner . incorporate ( p... |
def disallow ( ctx , foreign_account , permission , threshold , account ) :
"""Remove a key / account from an account ' s permission""" | print_tx ( ctx . bitshares . disallow ( foreign_account , account = account , permission = permission , threshold = threshold ) ) |
def createAndCleanTPED ( tped , tfam , snps , prefix , chosenSNPs , completion , concordance , snpsToComplete , tfamFileName , completionT , concordanceT ) :
"""Complete a TPED for duplicated SNPs .
: param tped : a representation of the ` ` tped ` ` of duplicated markers .
: param tfam : a representation of th... | zeroedOutFile = None
try :
zeroedOutFile = open ( prefix + ".zeroed_out" , "w" )
except IOError :
msg = "%(prefix).zeroed_out: can't write file" % locals ( )
raise ProgramError ( msg )
print >> zeroedOutFile , "\t" . join ( [ "famID" , "indID" , "snpID" ] )
notGoodEnoughFile = None
try :
notGoodEnoughFi... |
def dense_output ( t_current , t_old , h_current , rcont ) :
"""Dense output function , basically extrapolatin""" | # initialization
s = ( t_current - t_old ) / h_current
s1 = 1.0 - s
return rcont [ 0 ] + s * ( rcont [ 1 ] + s1 * ( rcont [ 2 ] + s * ( rcont [ 3 ] + s1 * ( rcont [ 4 ] + s * ( rcont [ 5 ] + s1 * ( rcont [ 6 ] + s * rcont [ 7 ] ) ) ) ) ) ) |
def create_time_labels ( self ) :
"""Create the time labels , but don ' t plot them yet .
Notes
It ' s necessary to have the height of the time labels , so that we can
adjust the main scene .
Not very robust , because it uses seconds as integers .""" | min_time = int ( floor ( min ( self . data . axis [ 'time' ] [ 0 ] ) ) )
max_time = int ( ceil ( max ( self . data . axis [ 'time' ] [ 0 ] ) ) )
n_time_labels = self . parent . value ( 'n_time_labels' )
self . idx_time = [ ]
self . time_pos = [ ]
for one_time in linspace ( min_time , max_time , n_time_labels ) :
x_... |
def response_continue ( self ) :
"""Signals that a partial reception of data has occurred and that the exporter should continue to send data for
this entity . This should also be used if import - side caching has missed , in which case the response will direct
the exporter to re - send the full data for the ent... | if self . entity is not None :
ImportRequest . logger . debug ( "Sending: continue" )
return jsonify ( { 'state' : 'continue' } )
else :
ImportRequest . logger . debug ( "Sending: continue-nocache" )
return jsonify ( { 'state' : 'continue-nocache' } ) |
def SayString ( self , text , delay = 0 ) :
"""Enter some text .
: param text : the text you want to enter .""" | self . _delay ( delay )
cmd = Command ( "SayString" , 'SayString "%s"' % text )
self . add ( cmd ) |
def write_unitary_matrix_to_hdf5 ( temperature , mesh , unitary_matrix = None , sigma = None , sigma_cutoff = None , solver = None , filename = None , verbose = False ) :
"""Write eigenvectors of collision matrices at temperatures .
Depending on the choice of the solver , eigenvectors are sotred in
either colum... | suffix = _get_filename_suffix ( mesh , sigma = sigma , sigma_cutoff = sigma_cutoff , filename = filename )
hdf5_filename = "unitary" + suffix + ".hdf5"
with h5py . File ( hdf5_filename , 'w' ) as w :
w . create_dataset ( 'temperature' , data = temperature )
if unitary_matrix is not None :
w . create_dat... |
def buffer_leave ( self , filename ) :
"""User is changing of buffer .""" | self . log . debug ( 'buffer_leave: %s' , filename )
# TODO : This is questionable , and we should use location list for
# single - file errors .
self . editor . clean_errors ( ) |
def write_manifest ( self ) :
"""Write the file list in ' self . filelist ' to the manifest file
named by ' self . manifest ' .""" | self . filelist . _repair ( )
# Now _ repairs should encodability , but not unicode
files = [ self . _manifest_normalize ( f ) for f in self . filelist . files ]
msg = "writing manifest file '%s'" % self . manifest
self . execute ( write_file , ( self . manifest , files ) , msg ) |
def list_nodes ( full = False , call = None ) :
'''List of nodes , keeping only a brief listing
CLI Example :
. . code - block : : bash
salt - cloud - Q''' | if call == 'action' :
raise SaltCloudSystemExit ( 'The list_nodes function must be called with -f or --function.' )
ret = { }
nodes = list_nodes_full ( 'function' )
if full :
return nodes
for node in nodes :
ret [ node ] = { }
for item in ( 'id' , 'image' , 'size' , 'public_ips' , 'private_ips' , 'state... |
def run ( self , grid = None , num_of_paths = 2000 , seed = 0 , num_of_workers = CPU_COUNT , profiling = False ) :
"""implements simulation
: param list ( date ) grid : list of Monte Carlo grid dates
: param int num _ of _ paths : number of Monte Carlo paths
: param hashable seed : seed used for rnds initiali... | self . grid = sorted ( set ( grid ) )
self . num_of_paths = num_of_paths
self . num_of_workers = num_of_workers
self . seed = seed
# pre processing
self . producer . initialize ( self . grid , self . num_of_paths , self . seed )
self . consumer . initialize ( self . grid , self . num_of_paths , self . seed )
if num_of_... |
def get_mods ( package ) :
"""List all loadable python modules in a directory
This function looks inside the specified directory for all files that look
like Python modules with a numeric prefix and returns them . It will omit
any duplicates and return file names without extension .
: param package : packag... | pkgdir = package . __path__ [ 0 ]
matches = filter ( None , [ PYMOD_RE . match ( f ) for f in os . listdir ( pkgdir ) ] )
parse_match = lambda groups : ( groups [ 0 ] , int ( groups [ 1 ] ) , int ( groups [ 2 ] ) )
return sorted ( list ( set ( [ parse_match ( m . groups ( ) ) for m in matches ] ) ) , key = lambda x : (... |
def reentrancies ( self ) :
"""Return a mapping of variables to their re - entrancy count .
A re - entrancy is when more than one edge selects a node as its
target . These graphs are rooted , so the top node always has an
implicit entrancy . Only nodes with re - entrancies are reported ,
and the count is on... | entrancies = defaultdict ( int )
entrancies [ self . top ] += 1
# implicit entrancy to top
for t in self . edges ( ) :
entrancies [ t . target ] += 1
return dict ( ( v , cnt - 1 ) for v , cnt in entrancies . items ( ) if cnt >= 2 ) |
def libvlc_media_player_has_vout ( p_mi ) :
'''How many video outputs does this media player have ?
@ param p _ mi : the media player .
@ return : the number of video outputs .''' | f = _Cfunctions . get ( 'libvlc_media_player_has_vout' , None ) or _Cfunction ( 'libvlc_media_player_has_vout' , ( ( 1 , ) , ) , None , ctypes . c_uint , MediaPlayer )
return f ( p_mi ) |
def wait_for_successful_query ( url , wait_for = 300 , ** kwargs ) :
'''Query a resource until a successful response , and decode the return data
CLI Example :
. . code - block : : bash
salt ' * ' http . wait _ for _ successful _ query http : / / somelink . com / wait _ for = 160''' | starttime = time . time ( )
while True :
caught_exception = None
result = None
try :
result = query ( url = url , ** kwargs )
if not result . get ( 'Error' ) and not result . get ( 'error' ) :
return result
except Exception as exc :
caught_exception = exc
if time ... |
def _default_error_handler ( msg , _ ) :
"""Default error handler callback for libopenjp2.""" | msg = "OpenJPEG library error: {0}" . format ( msg . decode ( 'utf-8' ) . rstrip ( ) )
opj2 . set_error_message ( msg ) |
def preprocess ( self ) :
"""Preprocessing .
Each active custom field is given a ' name ' key that holds the field
name , and for each keyed name , the value of the custom field is
assigned .
Notes on the group get some html tags removed .""" | super ( MambuLoan , self ) . preprocess ( )
try :
self [ 'notes' ] = strip_tags ( self [ 'notes' ] )
except KeyError :
pass |
def lee_yeast_ChIP ( data_set = 'lee_yeast_ChIP' ) :
"""Yeast ChIP data from Lee et al .""" | if not data_available ( data_set ) :
download_data ( data_set )
from pandas import read_csv
dir_path = os . path . join ( data_path , data_set )
filename = os . path . join ( dir_path , 'binding_by_gene.tsv' )
S = read_csv ( filename , header = 1 , index_col = 0 , sep = '\t' )
transcription_factors = [ col for col ... |
def validate_hex ( value ) :
"""Validate that value has hex format .""" | try :
binascii . unhexlify ( value )
except Exception :
raise vol . Invalid ( '{} is not of hex format' . format ( value ) )
return value |
def legend ( self ) :
'''Splattable list of : class : ` ~ bokeh . models . annotations . Legend ` objects .''' | panels = self . above + self . below + self . left + self . right + self . center
legends = [ obj for obj in panels if isinstance ( obj , Legend ) ]
return _legend_attr_splat ( legends ) |
def enabled_service_owners ( ) :
'''Return which packages own each of the services that are currently enabled .
CLI Example :
salt myminion introspect . enabled _ service _ owners''' | error = { }
if 'pkg.owner' not in __salt__ :
error [ 'Unsupported Package Manager' ] = ( 'The module for the package manager on this system does not ' 'support looking up which package(s) owns which file(s)' )
if 'service.show' not in __salt__ :
error [ 'Unsupported Service Manager' ] = ( 'The module for the se... |
def callback_oauth2 ( self , request ) :
"""Process for oAuth 2
: param request : contains the current session
: return :""" | callback_url = self . callback_url ( request )
oauth = OAuth2Session ( client_id = self . consumer_key , redirect_uri = callback_url , scope = self . scope )
request_token = oauth . fetch_token ( self . REQ_TOKEN , code = request . GET . get ( 'code' , '' ) , authorization_response = callback_url , client_secret = self... |
def _makeExtraWidgets ( self ) :
"""Makes a text widget .""" | self . textWidget = urwid . Text ( self . text )
return [ self . textWidget ] |
def getVersion ( ) :
"""Returns underlying libusb ' s version information as a 6 - namedtuple ( or
6 - tuple if namedtuples are not avaiable ) :
- major
- minor
- micro
- nano
- rc
- describe
Returns ( 0 , 0 , 0 , 0 , ' ' , ' ' ) if libusb doesn ' t have required entry point .""" | version = libusb1 . libusb_get_version ( ) . contents
return Version ( version . major , version . minor , version . micro , version . nano , version . rc , version . describe , ) |
def initializable ( self ) :
"""True if the Slot is initializable .""" | return bool ( lib . EnvSlotInitableP ( self . _env , self . _cls , self . _name ) ) |
def atualizar_software_sat ( self ) :
"""Sobrepõe : meth : ` ~ satcfe . base . FuncoesSAT . atualizar _ software _ sat ` .
: return : Uma resposta SAT padrão .
: rtype : satcfe . resposta . padrao . RespostaSAT""" | resp = self . _http_post ( 'atualizarsoftwaresat' )
conteudo = resp . json ( )
return RespostaSAT . atualizar_software_sat ( conteudo . get ( 'retorno' ) ) |
def select ( i ) :
"""Input : {
dict - dict with values being dicts with ' name ' as string to display and ' sort ' as int ( for ordering )
( title ) - print title
( error _ if _ empty ) - if ' yes ' and Enter , make error
( skip _ sort ) - if ' yes ' , do not sort array
Output : {
return - return code ... | s = ''
title = i . get ( 'title' , '' )
if title != '' :
out ( title )
out ( '' )
d = i [ 'dict' ]
if i . get ( 'skip_sort' , '' ) != 'yes' :
kd = sorted ( d , key = lambda v : d [ v ] . get ( 'sort' , 0 ) )
else :
kd = d
j = 0
ks = { }
for k in kd :
q = d [ k ]
sj = str ( j )
ks [ sj ] = k
... |
def get_disks ( vm_ ) :
'''Return the disks of a named vm
CLI Example :
. . code - block : : bash
salt ' * ' virt . get _ disks < vm name >''' | with _get_xapi_session ( ) as xapi :
disk = { }
vm_uuid = _get_label_uuid ( xapi , 'VM' , vm_ )
if vm_uuid is False :
return False
for vbd in xapi . VM . get_VBDs ( vm_uuid ) :
dev = xapi . VBD . get_device ( vbd )
if not dev :
continue
prop = xapi . VBD . get... |
def sheets ( self , index = None ) :
"""Return either a list of all sheets if index is None , or the sheet at the given index .""" | if self . _sheets is None :
self . _sheets = [ self . get_worksheet ( s , i ) for i , s in enumerate ( self . iterate_sheets ( ) ) ]
if index is None :
return self . _sheets
else :
return self . _sheets [ index ] |
def get_root ( self ) :
""": returns : the root node for the current node object .""" | return get_result_class ( self . __class__ ) . objects . get ( path = self . path [ 0 : self . steplen ] ) |
def process_beads_table ( beads_table , instruments_table , base_dir = "." , verbose = False , plot = False , plot_dir = None , full_output = False , get_transform_fxn_kwargs = { } ) :
"""Process calibration bead samples , as specified by an input table .
This function processes the entries in ` beads _ table ` .... | # Initialize output variables
beads_samples = [ ]
mef_transform_fxns = collections . OrderedDict ( )
mef_outputs = [ ]
# Return empty structures if beads table is empty
if beads_table . empty :
if full_output :
return beads_samples , mef_transform_fxns , mef_outputs
else :
return beads_samples ,... |
def auth ( self ) :
"""Auth is used to call the AUTH API of CricketAPI .
Access token required for every request call to CricketAPI .
Auth functional will post user Cricket API app details to server
and return the access token .
Return :
Access token""" | if not self . store_handler . has_value ( 'access_token' ) :
params = { }
params [ "access_key" ] = self . access_key
params [ "secret_key" ] = self . secret_key
params [ "app_id" ] = self . app_id
params [ "device_id" ] = self . device_id
auth_url = self . api_path + "auth/"
response = self... |
def timeinfo ( self ) :
"""Time series data of the time step .
Set to None if no time series data is available for this time step .""" | if self . istep not in self . sdat . tseries . index :
return None
return self . sdat . tseries . loc [ self . istep ] |
def hs_mux ( sel , ls_hsi , hso ) :
"""[ Many - to - one ] Multiplexes a list of input handshake interfaces
sel - ( i ) selects an input handshake interface to be connected to the output
ls _ hsi - ( i ) list of input handshake tuples ( ready , valid )
hso - ( o ) output handshake tuple ( ready , valid )""" | N = len ( ls_hsi )
ls_hsi_rdy , ls_hsi_vld = zip ( * ls_hsi )
ls_hsi_rdy , ls_hsi_vld = list ( ls_hsi_rdy ) , list ( ls_hsi_vld )
hso_rdy , hso_vld = hso
@ always_comb
def _hsmux ( ) :
hso_vld . next = 0
for i in range ( N ) :
ls_hsi_rdy [ i ] . next = 0
if i == sel :
hso_vld . next ... |
def map_or_apply ( function , param ) :
"""Map the function on ` ` param ` ` , or apply it , depending whether ` ` param ` ` is a list or an item .
: param function : The function to apply .
: param param : The parameter to feed the function with ( list or item ) .
: returns : The computed value or ` ` None `... | try :
if isinstance ( param , list ) :
return [ next ( iter ( function ( i ) ) ) for i in param ]
else :
return next ( iter ( function ( param ) ) )
except StopIteration :
return None |
def _write_method ( schema ) :
"""Add a write method for named schema to a class .""" | def method ( self , filename = None , schema = schema , id_col = 'uid' , sequence_col = 'sequence' , extra_data = None , alphabet = None , ** kwargs ) : # Use generic write class to write data .
return _write ( self . _data , filename = filename , schema = schema , id_col = id_col , sequence_col = sequence_col , ex... |
def scatter ( * args , ** kwargs ) :
"""This function creates a scatter chart . Specifcally it creates an
: py : class : ` . AxisChart ` and then adds a : py : class : ` . ScatterSeries ` to it .
: param \ * data : The data for the scatter series as either ( x , y ) values or two big tuples / lists of x and y v... | scatter_series_kwargs = { }
for kwarg in ( "name" , "color" , "size" , "linewidth" ) :
if kwarg in kwargs :
scatter_series_kwargs [ kwarg ] = kwargs [ kwarg ]
del kwargs [ kwarg ]
if "color" not in scatter_series_kwargs :
scatter_series_kwargs [ "color" ] = colors [ 0 ]
series = ScatterSeries ( ... |
def display ( component , ** kwargs ) :
"""Display the given component based on the environment it ' s run from .
See : class : ` DisplayEnvironment < cqparts . display . environment . DisplayEnvironment > `
documentation for more details .
: param component : component to display
: type component : : class... | disp_env = get_display_environment ( )
if disp_env is None :
raise LookupError ( 'valid display environment could not be found' )
disp_env . display ( component , ** kwargs ) |
def _get_reference_namespace ( self , name ) :
"""Return namespace where reference name is defined
It returns the globals ( ) if reference has not yet been defined""" | glbs = self . _mglobals ( )
if self . _pdb_frame is None :
return glbs
else :
lcls = self . _pdb_locals
if name in lcls :
return lcls
else :
return glbs |
def _get_bandgap_eigenval ( eigenval_fname , outcar_fname ) :
"""Get the bandgap from the EIGENVAL file""" | with open ( outcar_fname , "r" ) as f :
parser = OutcarParser ( )
nelec = next ( iter ( filter ( lambda x : "number of electrons" in x , parser . parse ( f . readlines ( ) ) ) ) ) [ "number of electrons" ]
with open ( eigenval_fname , "r" ) as f :
eigenval_info = list ( EigenvalParser ( ) . parse ( f . read... |
def _render_select ( selections ) :
"""Render the selection part of a query .
Parameters
selections : dict
Selections for a table
Returns
str
A string for the " select " part of a query
See Also
render _ query : Further clarification of ` selections ` dict formatting""" | if not selections :
return 'SELECT *'
rendered_selections = [ ]
for name , options in selections . items ( ) :
if not isinstance ( options , list ) :
options = [ options ]
original_name = name
for options_dict in options :
name = original_name
alias = options_dict . get ( 'alias'... |
def get_type ( var ) :
"""Gets types accounting for numpy
Ignore :
import utool as ut
import pandas as pd
var = np . array ( [ ' a ' , ' b ' , ' c ' ] )
ut . get _ type ( var )
var = pd . Index ( [ ' a ' , ' b ' , ' c ' ] )
ut . get _ type ( var )""" | if HAVE_NUMPY and isinstance ( var , np . ndarray ) :
if _WIN32 : # This is a weird system specific error
# https : / / github . com / numpy / numpy / issues / 3667
type_ = var . dtype
else :
type_ = var . dtype . type
elif HAVE_PANDAS and isinstance ( var , pd . Index ) :
if _WIN32 :
... |
def iter_filths ( ) :
"""Iterate over all instances of filth""" | for filth_cls in iter_filth_clss ( ) :
if issubclass ( filth_cls , RegexFilth ) :
m = next ( re . finditer ( r"\s+" , "fake pattern string" ) )
yield filth_cls ( m )
else :
yield filth_cls ( ) |
def _task_table ( self , task_id ) :
"""Fetch and parse the task table information for a single task ID .
Args :
task _ id : A task ID to get information about .
Returns :
A dictionary with information about the task ID in question .""" | assert isinstance ( task_id , ray . TaskID )
message = self . _execute_command ( task_id , "RAY.TABLE_LOOKUP" , ray . gcs_utils . TablePrefix . RAYLET_TASK , "" , task_id . binary ( ) )
if message is None :
return { }
gcs_entries = ray . gcs_utils . GcsTableEntry . GetRootAsGcsTableEntry ( message , 0 )
assert gcs_... |
def fit_points_in_bounding_box_params ( df_points , bounding_box , padding_fraction = 0 ) :
'''Return offset and scale factor to scale ` ` x ` ` , ` ` y ` ` columns of
: data : ` df _ points ` to fill : data : ` bounding _ box ` while maintaining aspect
ratio .
Arguments
df _ points : pandas . DataFrame
A... | width = df_points . x . max ( )
height = df_points . y . max ( )
points_bbox = pd . Series ( [ width , height ] , index = [ 'width' , 'height' ] )
fill_scale = 1 - 2 * padding_fraction
assert ( fill_scale > 0 )
scale = scale_to_fit_a_in_b ( points_bbox , bounding_box )
padded_scale = scale * fill_scale
offset = .5 * ( ... |
def update_existing ( self , * args , ** kwargs ) :
"""Update already existing properties of this CIM instance .
Existing properties will be updated , and new properties will be
ignored without further notice .
Parameters :
* args ( list ) :
Properties for updating the properties of the instance , specifi... | for mapping in args :
if hasattr ( mapping , 'items' ) :
for key , value in mapping . items ( ) :
try :
prop = self . properties [ key ]
except KeyError :
continue
prop . value = value
else :
for ( key , value ) in mapping :
... |
def resolve_configuration ( self , configuration ) :
"""Resolve requirements from given JSON encoded data .
The JSON should follow the testcase meta - data requirements field format . This function
will resolve requirements for each individual DUT and create a DUT requirements list
that contains the configura... | configuration = configuration if configuration else self . json_config
self . _resolve_requirements ( configuration [ "requirements" ] )
self . _resolve_dut_count ( ) |
def randomize_molecule_low ( molecule , manipulations ) :
"""Return a randomized copy of the molecule , without the nonbond check .""" | manipulations = copy . copy ( manipulations )
shuffle ( manipulations )
coordinates = molecule . coordinates . copy ( )
for manipulation in manipulations :
manipulation . apply ( coordinates )
return molecule . copy_with ( coordinates = coordinates ) |
def find ( decl_matcher , decls , recursive = True ) :
"""Returns a list of declarations that match ` decl _ matcher ` defined
criteria or None
: param decl _ matcher : Python callable object , that takes one argument -
reference to a declaration
: param decls : the search scope , : class : declaration _ t ... | where = [ ]
if isinstance ( decls , list ) :
where . extend ( decls )
else :
where . append ( decls )
if recursive :
where = make_flatten ( where )
return list ( filter ( decl_matcher , where ) ) |
def setText ( self , text ) :
"""Sets the text for this widget to the inputed text , converting it based \
on the current input format if necessary .
: param text | < str >""" | if text is None :
text = ''
super ( XLineEdit , self ) . setText ( projex . text . encoded ( self . formatText ( text ) , self . encoding ( ) ) ) |
def format ( table , field , fmt , ** kwargs ) :
"""Convenience function to format all values in the given ` field ` using the
` fmt ` format string .
The ` ` where ` ` keyword argument can be given with a callable or expression
which is evaluated on each row and which should return True if the
conversion s... | conv = lambda v : fmt . format ( v )
return convert ( table , field , conv , ** kwargs ) |
def int_to_alpha ( n , upper = True ) :
"Generates alphanumeric labels of form A - Z , AA - ZZ etc ." | casenum = 65 if upper else 97
label = ''
count = 0
if n == 0 :
return str ( chr ( n + casenum ) )
while n >= 0 :
mod , div = n % 26 , n
for _ in range ( count ) :
div //= 26
div %= 26
if count == 0 :
val = mod
else :
val = div
label += str ( chr ( val + casenum ) )
... |
def ei ( cn , ns = None , lo = None , di = None , iq = None , ico = None , pl = None ) : # pylint : disable = redefined - outer - name , too - many - arguments
"""This function is a wrapper for
: meth : ` ~ pywbem . WBEMConnection . EnumerateInstances ` .
Enumerate the instances of a class ( including instances... | return CONN . EnumerateInstances ( cn , ns , LocalOnly = lo , DeepInheritance = di , IncludeQualifiers = iq , IncludeClassOrigin = ico , PropertyList = pl ) |
def get_json_log_data ( data ) :
"""Returns a new ` data ` dictionary with hidden params
for log purpose .""" | log_data = data
for param in LOG_HIDDEN_JSON_PARAMS :
if param in data [ 'params' ] :
if log_data is data :
log_data = copy . deepcopy ( data )
log_data [ 'params' ] [ param ] = "**********"
return log_data |
def find_interfaces ( device , ** kwargs ) :
""": param device :
: return :""" | interfaces = [ ]
try :
for cfg in device :
try :
interfaces . extend ( usb_find_desc ( cfg , find_all = True , ** kwargs ) )
except :
pass
except :
pass
return interfaces |
def send_single_file ( self , sender , receiver , media_id ) :
"""发送单聊文件消息
: param sender : 发送人
: param receiver : 接收人成员 ID
: param media _ id : 文件id , 可以调用上传素材文件接口获取 , 文件须大于4字节
: return : 返回的 JSON 数据包""" | return self . send_file ( sender , 'single' , receiver , media_id ) |
def from_array ( array ) :
"""Deserialize a new ChatActionMessage from a given dictionary .
: return : new ChatActionMessage instance .
: rtype : ChatActionMessage""" | if array is None or not array :
return None
# end if
assert_type_or_raise ( array , dict , parameter_name = "array" )
data = { }
data [ 'action' ] = u ( array . get ( 'action' ) )
if array . get ( 'chat_id' ) is None :
data [ 'receiver' ] = None
elif isinstance ( array . get ( 'chat_id' ) , None ) :
data [ ... |
def _photometricErrors ( self , n_per_bin = 100 , plot = False ) :
"""Realistic photometric errors estimated from catalog objects and mask .
Extend below the magnitude threshold with a flat extrapolation .""" | self . catalog . spatialBin ( self . roi )
if len ( self . catalog . mag_1 ) < n_per_bin :
logger . warning ( "Catalog contains fewer objects than requested to calculate errors." )
n_per_bin = int ( len ( self . catalog . mag_1 ) / 3 )
# Band 1
mag_1_thresh = self . mask . mask_1 . mask_roi_sparse [ self . cata... |
def get_active_token ( self ) :
"""Getting the valid access token .
Access token expires every 24 hours , It will expires then it will
generate a new token .
Return :
active access token""" | expire_time = self . store_handler . has_value ( "expires" )
access_token = self . store_handler . has_value ( "access_token" )
if expire_time and access_token :
expire_time = self . store_handler . get_value ( "expires" )
if not datetime . now ( ) < datetime . fromtimestamp ( float ( expire_time ) ) :
... |
def _validate_schema ( schema , body ) :
"""Validate data against a schema""" | # Note
# Schema validation is currently the major CPU bottleneck of
# BigchainDB . the ` jsonschema ` library validates python data structures
# directly and produces nice error messages , but validation takes 4 + ms
# per transaction which is pretty slow . The rapidjson library validates
# much faster at 1.5ms , howev... |
def check ( self , diff ) :
r"""Check that the new file introduced has a valid name
The module can either be an _ _ init _ _ . py file or must
match ` ` feature _ [ a - zA - Z0-9 _ ] + \ . \ w + ` ` .""" | filename = pathlib . Path ( diff . b_path ) . parts [ - 1 ]
is_valid_feature_module_name = re_test ( FEATURE_MODULE_NAME_REGEX , filename )
is_valid_init_module_name = filename == '__init__.py'
assert is_valid_feature_module_name or is_valid_init_module_name |
def unflatten2 ( flat_list , cumlen_list ) :
"""Rebuilds unflat list from invertible _ flatten1
Args :
flat _ list ( list ) : the flattened list
cumlen _ list ( list ) : the list which undoes flattenting
Returns :
unflat _ list2 : original nested list
SeeAlso :
invertible _ flatten1
invertible _ fla... | unflat_list2 = [ flat_list [ low : high ] for low , high in zip ( itertools . chain ( [ 0 ] , cumlen_list ) , cumlen_list ) ]
return unflat_list2 |
def gcd ( * numbers ) :
"""Returns the greatest common divisor for a sequence of numbers .
Args :
\*numbers: Sequence of numbers.
Returns :
( int ) Greatest common divisor of numbers .""" | n = numbers [ 0 ]
for i in numbers :
n = pygcd ( n , i )
return n |
def send_data ( data ) :
"""Send data to herkulex
Paketize & write the packet to serial port
Args :
data ( list ) : the data to be sent
Raises :
SerialException : Error occured while opening serial port""" | datalength = len ( data )
csm1 = checksum1 ( data , datalength )
csm2 = checksum2 ( csm1 )
data . insert ( 0 , 0xFF )
data . insert ( 1 , 0xFF )
data . insert ( 5 , csm1 )
data . insert ( 6 , csm2 )
stringtosend = ""
for i in range ( len ( data ) ) :
byteformat = '%02X' % data [ i ]
stringtosend = stringtosend ... |
def authenticate ( self , request ) :
"""Attempt to authenticate the request .
: param request : django . http . Request instance
: return bool : True if success else raises HTTP _ 401""" | authenticators = self . _meta . authenticators
if request . method == 'OPTIONS' and ADREST_ALLOW_OPTIONS :
self . auth = AnonimousAuthenticator ( self )
return True
error_message = "Authorization required."
for authenticator in authenticators :
auth = authenticator ( self )
try :
if not auth . a... |
def parse ( self , what ) :
""": param what :
can be ' rlz - 1 / ref - asset1 ' , ' rlz - 2 / sid - 1 ' , . . .""" | if '/' not in what :
key , spec = what , ''
else :
key , spec = what . split ( '/' )
if spec and not spec . startswith ( ( 'ref-' , 'sid-' ) ) :
raise ValueError ( 'Wrong specification in %s' % what )
elif spec == '' : # export losses for all assets
aids = [ ]
arefs = [ ]
for aid , rec in enumer... |
def prepare_headers ( self , headers , metadata , queue_derive = True ) :
"""Convert a dictionary of metadata into S3 compatible HTTP
headers , and append headers to ` ` headers ` ` .
: type metadata : dict
: param metadata : Metadata to be converted into S3 HTTP Headers
and appended to ` ` headers ` ` .
... | if not metadata . get ( 'scanner' ) :
scanner = 'Internet Archive Python library {0}' . format ( __version__ )
metadata [ 'scanner' ] = scanner
prepared_metadata = prepare_metadata ( metadata )
headers [ 'x-archive-auto-make-bucket' ] = '1'
if queue_derive is False :
headers [ 'x-archive-queue-derive' ] = '... |
def generate_pydenticon ( identifier , size ) :
'''Use pydenticon to generate an identicon image .
All parameters are extracted from configuration .''' | blocks_size = get_internal_config ( 'size' )
foreground = get_internal_config ( 'foreground' )
background = get_internal_config ( 'background' )
generator = pydenticon . Generator ( blocks_size , blocks_size , digest = hashlib . sha1 , foreground = foreground , background = background )
# Pydenticon adds padding to the... |
def forward_iter ( self , X , training = False , device = 'cpu' ) :
"""Yield outputs of module forward calls on each batch of data .
The storage device of the yielded tensors is determined
by the ` ` device ` ` parameter .
Parameters
X : input data , compatible with skorch . dataset . Dataset
By default ,... | dataset = self . get_dataset ( X )
iterator = self . get_iterator ( dataset , training = training )
for data in iterator :
Xi = unpack_data ( data ) [ 0 ]
yp = self . evaluation_step ( Xi , training = training )
if isinstance ( yp , tuple ) :
yield tuple ( n . to ( device ) for n in yp )
else :
... |
def _get_distance_scaling ( self , C , mag , rhypo ) :
"""Returns the distance scalig term""" | return ( C [ "a3" ] * np . log ( rhypo ) ) + ( C [ "a4" ] + C [ "a5" ] * mag ) * rhypo |
def convolutional_layer_series ( initial_size , layer_sequence ) :
"""Execute a series of convolutional layer transformations to the size number""" | size = initial_size
for filter_size , padding , stride in layer_sequence :
size = convolution_size_equation ( size , filter_size , padding , stride )
return size |
def readCol ( self , col , startRow = 0 , endRow = - 1 ) :
'''read col''' | return self . __operation . readCol ( col , startRow , endRow ) |
def _merge_before_set ( self , key , existing , value , is_secret ) :
"""Merge the new value being set with the existing value before set""" | def _log_before_merging ( _value ) :
self . logger . debug ( "Merging existing %s: %s with new: %s" , key , existing , _value )
def _log_after_merge ( _value ) :
self . logger . debug ( "%s merged to %s" , key , _value )
global_merge = getattr ( self , "MERGE_ENABLED_FOR_DYNACONF" , False )
if isinstance ( valu... |
def keys_to_typing ( value ) :
"""Processes the values that will be typed in the element .""" | typing = [ ]
for val in value :
if isinstance ( val , Keys ) :
typing . append ( val )
elif isinstance ( val , int ) :
val = str ( val )
for i in range ( len ( val ) ) :
typing . append ( val [ i ] )
else :
for i in range ( len ( val ) ) :
typing . app... |
def values ( self ) :
"""Return all values as numpy - array ( mean , var , min , max , num ) .""" | return np . array ( [ self . mean , self . var , self . min , self . max , self . num ] ) |
def get_core_source_partial ( ) :
"""_ get _ core _ source ( ) is expensive , even with @ lru _ cache in minify . py , threads
can enter it simultaneously causing severe slowdowns .""" | global _core_source_partial
if _core_source_partial is None :
_core_source_lock . acquire ( )
try :
if _core_source_partial is None :
_core_source_partial = PartialZlib ( _get_core_source ( ) . encode ( 'utf-8' ) )
finally :
_core_source_lock . release ( )
return _core_source_par... |
def copy_file ( stream , target , maxread = - 1 , buffer_size = 2 * 16 ) :
'''Read from : stream and write to : target until : maxread or EOF .''' | size , read = 0 , stream . read
while 1 :
to_read = buffer_size if maxread < 0 else min ( buffer_size , maxread - size )
part = read ( to_read )
if not part :
return size
target . write ( part )
size += len ( part ) |
def process_runway_configs ( runway_dir = '' ) :
"""Read the _ application . json _ files .
Args :
runway _ dir ( str ) : Name of runway directory with app . json files .
Returns :
collections . defaultdict : Configurations stored for each environment
found .""" | LOG . info ( 'Processing application.json files from local directory "%s".' , runway_dir )
file_lookup = FileLookup ( runway_dir = runway_dir )
app_configs = process_configs ( file_lookup , 'application-master-{env}.json' , 'pipeline.json' )
return app_configs |
def compile ( self , db ) :
"""Building the sql expression
: param db : the database instance""" | sql = self . expression
if self . alias :
sql += ( ' AS ' + db . quote_column ( self . alias ) )
return sql |
def _bytes_to_values ( self , bs , width = None ) :
"""Convert a packed row of bytes into a row of values .
Result will be a freshly allocated object ,
not shared with the argument .""" | if self . bitdepth == 8 :
return bytearray ( bs )
if self . bitdepth == 16 :
return array ( 'H' , struct . unpack ( '!%dH' % ( len ( bs ) // 2 ) , bs ) )
assert self . bitdepth < 8
if width is None :
width = self . width
# Samples per byte
spb = 8 // self . bitdepth
out = bytearray ( )
mask = 2 ** self . bi... |
def start_head_processes ( self ) :
"""Start head processes on the node .""" | logger . info ( "Process STDOUT and STDERR is being redirected to {}." . format ( self . _logs_dir ) )
assert self . _redis_address is None
# If this is the head node , start the relevant head node processes .
self . start_redis ( )
self . start_monitor ( )
self . start_raylet_monitor ( )
# The dashboard is Python3 . x... |
def require ( obj , caller_args = [ ] ) :
"""Primary method for test assertions in Specter
: param obj : The evaluated target object
: param caller _ args : Is only used when using expecting a raised Exception""" | line , module = get_module_and_line ( '__spec__' )
src_params = ExpectParams ( line , module )
require_obj = RequireAssert ( obj , src_params = src_params , caller_args = caller_args )
_add_expect_to_wrapper ( require_obj )
return require_obj |
def get_version ( module_name_or_file = None ) :
"""Return the current version as defined by the given module / file .""" | if module_name_or_file is None :
parts = base_module . split ( '.' )
module_name_or_file = parts [ 0 ] if len ( parts ) > 1 else find_packages ( exclude = [ 'test' , 'test.*' ] ) [ 0 ]
if os . path . isdir ( module_name_or_file ) :
module_name_or_file = os . path . join ( module_name_or_file , '__init__.py'... |
def simulate ( self , l , noisefunc = None , random_state = None ) :
"""Simulate vector autoregressive ( VAR ) model .
This function generates data from the VAR model .
Parameters
l : int or [ int , int ]
Number of samples to generate . Can be a tuple or list , where l [ 0]
is the number of samples and l ... | m , n = np . shape ( self . coef )
p = n // m
try :
l , t = l
except TypeError :
t = 1
if noisefunc is None :
rng = check_random_state ( random_state )
noisefunc = lambda : rng . normal ( size = ( 1 , m ) )
n = l + 10 * p
y = np . zeros ( ( n , m , t ) )
res = np . zeros ( ( n , m , t ) )
for s in range... |
def package ( self , vm_name = None , base = None , output = None , vagrantfile = None ) :
'''Packages a running vagrant environment into a box .
vm _ name = None : name of VM .
base = None : name of a VM in virtualbox to package as a base box
output = None : name of the file to output
vagrantfile = None : ... | cmd = [ 'package' , vm_name ]
if output is not None :
cmd += [ '--output' , output ]
if vagrantfile is not None :
cmd += [ '--vagrantfile' , vagrantfile ]
self . _call_vagrant_command ( cmd ) |
def output_shape ( self ) :
"""Returns the output shape .""" | if self . _output_shape is None :
self . _ensure_is_connected ( )
if callable ( self . _output_shape ) :
self . _output_shape = tuple ( self . _output_shape ( ) )
return self . _output_shape |
def get_k8s_metadata ( ) :
"""Get kubernetes container metadata , as on GCP GKE .""" | k8s_metadata = { }
gcp_cluster = ( gcp_metadata_config . GcpMetadataConfig . get_attribute ( gcp_metadata_config . CLUSTER_NAME_KEY ) )
if gcp_cluster is not None :
k8s_metadata [ CLUSTER_NAME_KEY ] = gcp_cluster
for attribute_key , attribute_env in _K8S_ENV_ATTRIBUTES . items ( ) :
attribute_value = os . envir... |
def _searchservices ( device , name = None , uuid = None , uuidbad = None ) :
"""Searches the given IOBluetoothDevice using the specified parameters .
Returns an empty list if the device has no services .
uuid should be IOBluetoothSDPUUID object .""" | if not isinstance ( device , _IOBluetooth . IOBluetoothDevice ) :
raise ValueError ( "device must be IOBluetoothDevice, was %s" % type ( device ) )
services = [ ]
allservices = device . getServices ( )
if uuid :
gooduuids = ( uuid , )
else :
gooduuids = ( )
if uuidbad :
baduuids = ( uuidbad , )
else :
... |
def view_history_source ( name , gitref = None ) :
"""Serve a page name from git repo ( an old version of a page ) .
then return the reST source code
This function does not use any template it returns only plain text
. . note : : this is a bottle view
* this is a GET only method : you can not change a commi... | response . set_header ( 'Cache-control' , 'no-cache' )
response . set_header ( 'Pragma' , 'no-cache' )
response . set_header ( 'Content-Type' , 'text/html; charset=utf-8' )
if gitref is None :
files = glob . glob ( "{0}.rst" . format ( name ) )
if len ( files ) > 0 :
file_handle = open ( files [ 0 ] , '... |
def _post ( self , * args , ** kwargs ) :
"""Wrapper around Requests for POST requests
Returns :
Response :
A Requests Response object""" | if 'timeout' not in kwargs :
kwargs [ 'timeout' ] = self . timeout
req = self . session . post ( * args , ** kwargs )
return req |
def remove_ipv4addr ( self , ipv4addr ) :
"""Remove an IPv4 address from the host .
: param str ipv4addr : The IP address to remove""" | for addr in self . ipv4addrs :
if ( ( isinstance ( addr , dict ) and addr [ 'ipv4addr' ] == ipv4addr ) or ( isinstance ( addr , HostIPv4 ) and addr . ipv4addr == ipv4addr ) ) :
self . ipv4addrs . remove ( addr )
break |
def validate ( self , grid ) :
"""Using the MagIC data model , generate validation errors on a MagicGrid .
Parameters
grid : dialogs . magic _ grid3 . MagicGrid
The MagicGrid to be validated
Returns
warnings : dict
Empty dict if no warnings , otherwise a dict with format { name of problem : [ problem _ ... | grid_name = str ( grid . GetName ( ) )
dmodel = self . contribution . dmodel
reqd_headers = dmodel . get_reqd_headers ( grid_name )
df = self . contribution . tables [ grid_name ] . df
df = df . replace ( '' , np . nan )
# python does not view empty strings as null
if df . empty :
return { }
col_names = set ( df . ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.