signature stringlengths 29 44.1k | implementation stringlengths 0 85.2k |
|---|---|
def _get_flatchoices ( self ) :
"""Redefine standard method .
Return constants themselves instead of their names for right rendering
in admin ' s ' change _ list ' view , if field is present in ' list _ display '
attribute of model ' s admin .""" | return [ ( self . to_python ( choice ) , value ) for choice , value in self . _choices ] |
def globalsfilter ( input_dict , check_all = False , filters = None , exclude_private = None , exclude_capitalized = None , exclude_uppercase = None , exclude_unsupported = None , excluded_names = None ) :
"""Keep only objects that can be pickled""" | output_dict = { }
for key , value in list ( input_dict . items ( ) ) :
excluded = ( exclude_private and key . startswith ( '_' ) ) or ( exclude_capitalized and key [ 0 ] . isupper ( ) ) or ( exclude_uppercase and key . isupper ( ) and len ( key ) > 1 and not key [ 1 : ] . isdigit ( ) ) or ( key in excluded_names ) ... |
def assure_cache ( project_path = None ) :
"""Assure that a project directory has a cache folder .
If not , it will create it .""" | project_path = path ( project_path , ISDIR )
cache_path = os . path . join ( project_path , CACHE_NAME )
if not os . path . isdir ( cache_path ) :
os . mkdir ( cache_path ) |
def index_of_coincidence ( * texts ) :
"""Calculate the index of coincidence for one or more ` ` texts ` ` .
The results are averaged over multiple texts to return the delta index of coincidence .
Examples :
> > > index _ of _ coincidence ( " aabbc " )
0.2
> > > index _ of _ coincidence ( " aabbc " , " ab... | if not texts :
raise ValueError ( "texts must not be empty" )
return statistics . mean ( _calculate_index_of_coincidence ( frequency_analyze ( text ) , len ( text ) ) for text in texts ) |
def transaction_insert_dict_auto_inc ( self , transaction_cursor , tblname , d , unique_id_fields = [ ] , fields = None , check_existing = False , id_field = 'ID' ) :
'''A transaction wrapper for inserting dicts into fields with an autoincrementing ID . Insert the record and return the associated ID ( long ) .''' | sql , params , record_exists = self . create_insert_dict_string ( tblname , d , PKfields = unique_id_fields , fields = fields , check_existing = check_existing )
if not record_exists :
transaction_cursor . execute ( sql , params )
id = transaction_cursor . lastrowid
if id == None :
id = self . get_unique_record... |
def optimise_xy ( xy , * args ) :
"""Return negative pore diameter for x and y coordinates optimisation .""" | z , elements , coordinates = args
window_com = np . array ( [ xy [ 0 ] , xy [ 1 ] , z ] )
return - pore_diameter ( elements , coordinates , com = window_com ) [ 0 ] |
def send_message_event ( self , room_id , event_type , content , txn_id = None , timestamp = None ) :
"""Perform PUT / rooms / $ room _ id / send / $ event _ type
Args :
room _ id ( str ) : The room ID to send the message event in .
event _ type ( str ) : The event type to send .
content ( dict ) : The JSON... | if not txn_id :
txn_id = self . _make_txn_id ( )
path = "/rooms/%s/send/%s/%s" % ( quote ( room_id ) , quote ( event_type ) , quote ( str ( txn_id ) ) , )
params = { }
if timestamp :
params [ "ts" ] = timestamp
return self . _send ( "PUT" , path , content , query_params = params ) |
def to_python ( self , value ) :
"""Return a str representation of the hexadecimal""" | if isinstance ( value , six . string_types ) :
return value
if value is None :
return value
return _unsigned_integer_to_hex_string ( value ) |
def primaryName ( self , value : Optional [ str ] ) -> None :
"""Set the value of isPrimary .
: param value : the value to set isPrimary to""" | if value is not None :
self . warned_no_primary = False
self . primaryNames [ self . viewNo ] = value
self . compact_primary_names ( )
if value != self . _primaryName :
self . _primaryName = value
self . logger . info ( "{} setting primaryName for view no {} to: {}" . format ( self , self . viewNo , value )... |
def create_menu ( self ) :
"""Create the MenuBar for the GUI current structure is :
File : Change Working Directory , Import Interpretations from LSQ
file , Import interpretations from a redo file , Save interpretations
to a redo file , Save MagIC tables , Save Plots
Edit : New Interpretation , Delete Inter... | self . menubar = wx . MenuBar ( )
# File Menu
menu_file = wx . Menu ( )
m_change_WD = menu_file . Append ( - 1 , "Change Working Directory\tCtrl-W" , "" )
self . Bind ( wx . EVT_MENU , self . on_menu_change_working_directory , m_change_WD )
m_import_meas_file = menu_file . Append ( - 1 , "Change measurements file" , ""... |
def do_genesis ( args , data_dir = None ) :
"""Given the command args , take an series of input files containing
GenesisData , combine all the batches into one GenesisData , and output the
result into a new file .""" | if data_dir is None :
data_dir = get_data_dir ( )
if not os . path . exists ( data_dir ) :
raise CliException ( "Data directory does not exist: {}" . format ( data_dir ) )
genesis_batches = [ ]
for input_file in args . input_file :
print ( 'Processing {}...' . format ( input_file ) )
input_data = BatchL... |
def get_avatar_metadata ( self ) :
"""Gets the metadata for an asset .
return : ( osid . Metadata ) - metadata for the asset
* compliance : mandatory - - This method must be implemented . *""" | # Implemented from template for osid . resource . ResourceForm . get _ group _ metadata _ template
metadata = dict ( self . _mdata [ 'avatar' ] )
metadata . update ( { 'existing_id_values' : self . _my_map [ 'avatarId' ] } )
return Metadata ( ** metadata ) |
def parallel_loop ( func , n_jobs = 1 , verbose = 1 ) :
"""run loops in parallel , if joblib is available .
Parameters
func : function
function to be executed in parallel
n _ jobs : int | None
Number of jobs . If set to None , do not attempt to use joblib .
verbose : int
verbosity level
Notes
Exec... | if n_jobs :
try :
from joblib import Parallel , delayed
except ImportError :
try :
from sklearn . externals . joblib import Parallel , delayed
except ImportError :
n_jobs = None
if not n_jobs :
if verbose :
print ( 'running ' , func , ' serially' )
... |
def process_tag ( self , tag ) :
"""Processes tag and detects which function to use""" | try :
if not self . _is_function ( tag ) :
self . _tag_type_processor [ tag . data_type ] ( tag )
except KeyError as ex :
raise Exception ( 'Tag type {0} not recognized for tag {1}' . format ( tag . data_type , tag . name ) , ex ) |
def _prepare_summary ( evolve_file , ssm_file , cnv_file , work_dir , somatic_info ) :
"""Prepare a summary with gene - labelled heterogeneity from PhyloWGS predictions .""" | out_file = os . path . join ( work_dir , "%s-phylowgs.txt" % somatic_info . tumor_name )
if not utils . file_uptodate ( out_file , evolve_file ) :
with file_transaction ( somatic_info . tumor_data , out_file ) as tx_out_file :
with open ( tx_out_file , "w" ) as out_handle :
ssm_locs = _read_ssm_... |
def hash_starts_numeric ( records ) :
"""Very useful function that only accepts records with a numeric start to
their sha - 1 hash .""" | for record in records :
seq_hash = hashlib . sha1 ( str ( record . seq ) ) . hexdigest ( )
if seq_hash [ 0 ] . isdigit ( ) :
yield record |
def gaussApprox ( self , xy , ** kwargs ) :
"""NAME :
gaussApprox
PURPOSE :
return the mean and variance of a Gaussian approximation to the stream DF at a given phase - space point in Galactocentric rectangular coordinates ( distribution is over missing directions )
INPUT :
xy - phase - space point [ X , ... | interp = kwargs . get ( 'interp' , self . _useInterp )
lb = kwargs . get ( 'lb' , False )
# What are we looking for
coordGiven = numpy . array ( [ not x is None for x in xy ] , dtype = 'bool' )
nGiven = numpy . sum ( coordGiven )
# First find the nearest track point
if not 'cindx' in kwargs and lb :
cindx = self . ... |
def mxmg ( m1 , m2 , nrow1 , ncol1 , ncol2 ) :
"""Multiply two double precision matrices of arbitrary size .
http : / / naif . jpl . nasa . gov / pub / naif / toolkit _ docs / C / cspice / mxmg _ c . html
: param m1 : nrow1 X ncol1 double precision matrix .
: type m1 : NxM - Element Array of floats
: param ... | m1 = stypes . toDoubleMatrix ( m1 )
m2 = stypes . toDoubleMatrix ( m2 )
mout = stypes . emptyDoubleMatrix ( x = ncol2 , y = nrow1 )
nrow1 = ctypes . c_int ( nrow1 )
ncol1 = ctypes . c_int ( ncol1 )
ncol2 = ctypes . c_int ( ncol2 )
libspice . mxmg_c ( m1 , m2 , nrow1 , ncol1 , ncol2 , mout )
return stypes . cMatrixToNum... |
def cart2sph ( x , y , z ) :
"""Converts cartesian coordinates ` x ` , ` y ` , ` z ` into a longitude and latitude .
x = 0 , y = 0 , z = 0 is assumed to correspond to the center of the globe .
Returns lon and lat in radians .
Parameters
` x ` , ` y ` , ` z ` : Arrays of cartesian coordinates
Returns
lon... | r = np . sqrt ( x ** 2 + y ** 2 + z ** 2 )
lat = np . arcsin ( z / r )
lon = np . arctan2 ( y , x )
return lon , lat |
def ping ( ) :
'''Check to see if the host is responding . Returns False if the host didn ' t
respond , True otherwise .
CLI Example :
. . code - block : : bash
salt cisco - nso test . ping''' | try :
client = _get_client ( )
client . info ( )
except SaltSystemExit as err :
log . warning ( err )
return False
return True |
def _objective_function ( X , W , R , S , gamma ) :
"""Evaluate the objective function .
. . math : : \\ sum _ { i = 1 } ^ { N } 1/2 \\ | X _ i - W _ i R - S _ i \\ | _ F ^ 2
. . math : : + / \\ gamma * \\ | S _ i \\ | _ 1
Parameters
X : list of array , element i has shape = [ voxels _ i , timepoints ]
Ea... | subjs = len ( X )
func = .0
for i in range ( subjs ) :
func += 0.5 * np . sum ( ( X [ i ] - W [ i ] . dot ( R ) - S [ i ] ) ** 2 ) + gamma * np . sum ( np . abs ( S [ i ] ) )
return func |
def str_kwargs ( self ) :
"""Generator that yields a dict of values corresponding to the
calendar date and time for the internal JD values .""" | iys , ims , ids , ihmsfs = d2dtf ( self . scale . upper ( ) . encode ( 'utf8' ) , 6 , self . jd1 , self . jd2 )
# Get the str _ fmt element of the first allowed output subformat
_ , _ , str_fmt = self . _select_subfmts ( self . out_subfmt ) [ 0 ]
yday = None
has_yday = '{yday:' in str_fmt or False
ihrs = ihmsfs [ ... ,... |
def get_record ( self , name , record_id ) :
"""Retrieve a record with a given type name and record id .
Args :
name ( string ) : The name which the record is stored under .
record _ id ( int ) : The id of the record requested .
Returns :
: class : ` cinder _ data . model . CinderModel ` : The cached mode... | if name in self . _cache :
if record_id in self . _cache [ name ] :
return self . _cache [ name ] [ record_id ] |
def get_project_config ( self , * args , ** kwargs ) :
"""Returns a ProjectConfig for the given project""" | warnings . warn ( "BaseGlobalConfig.get_project_config is pending deprecation" , DeprecationWarning , )
return self . project_config_class ( self , * args , ** kwargs ) |
def subscribe_to_quorum_channel ( self ) :
"""In case the experiment enforces a quorum , listen for notifications
before creating Partipant objects .""" | from dallinger . experiment_server . sockets import chat_backend
self . log ( "Bot subscribing to quorum channel." )
chat_backend . subscribe ( self , "quorum" ) |
def addBaseType ( self , item ) :
'''Add a Type instance to the data model .''' | ctor = '.' . join ( [ item . __class__ . __module__ , item . __class__ . __qualname__ ] )
self . _modeldef [ 'ctors' ] . append ( ( ( item . name , ctor , dict ( item . opts ) , dict ( item . info ) ) ) )
self . types [ item . name ] = item |
def superuser_only ( view_func ) :
"""Limit a view to superuser only .""" | def _inner ( request , * args , ** kwargs ) :
if not request . user . is_superuser :
raise PermissionDenied
return view_func ( request , * args , ** kwargs )
return _inner |
def process_request ( self , request , response ) :
"""Logs the basic endpoint requested""" | self . logger . info ( 'Requested: {0} {1} {2}' . format ( request . method , request . relative_uri , request . content_type ) ) |
def bbox_vert_aligned_right ( box1 , box2 ) :
"""Returns true if the right boundary of both boxes is within 2 pts""" | if not ( box1 and box2 ) :
return False
return abs ( box1 . right - box2 . right ) <= 2 |
def compact ( self , term_doc_matrix ) :
'''Parameters
term _ doc _ matrix : TermDocMatrix
Term document matrix object to compact
Returns
TermDocMatrix''' | rank_df = self . scorer . get_rank_df ( term_doc_matrix )
return self . _prune_higher_ranked_terms ( term_doc_matrix , rank_df , self . rank ) |
def _Soundex ( self ) :
"""The Soundex phonetic indexing algorithm adapted to ME phonology .
Algorithm :
Let w the original word and W the resulting one
1 ) Capitalize the first letter of w and append it to W
2 ) Apply the following replacement rules
p , b , f , v , gh ( non - nasal fricatives ) - > 1
t... | word = self . word [ 1 : ]
for w , val in zip ( dict_SE . keys ( ) , dict_SE . values ( ) ) :
word = word . replace ( w , val )
# Remove multiple adjacent occurences of digit
word = re . sub ( r"(\d)\1+" , r"\1" , word )
# Strip remaining letters
word = re . sub ( r"[a-zðþƿ]+" , "" , word )
# Add trailing zeroes an... |
def return_hdr ( self ) :
"""Return the header for further use .
Returns
subj _ id : str
subject identification code
start _ time : datetime
start time of the dataset
s _ freq : float
sampling frequency
chan _ name : list of str
list of all the channels
n _ samples : int
number of samples in t... | subj_id = self . task . subject
sampling_freq = set ( self . task . channels . get ( map_lambda = lambda x : x [ 'sampling_frequency' ] ) )
if len ( sampling_freq ) > 1 :
raise ValueError ( 'Multiple sampling frequencies not supported' )
s_freq = float ( next ( iter ( sampling_freq ) ) )
chan_name = self . task . c... |
def server_bind ( self ) :
"""Override to enable IPV4 mapping for IPV6 sockets when desired .
The main use case for this is so that when no host is specified , TensorBoard
can listen on all interfaces for both IPv4 and IPv6 connections , rather than
having to choose v4 or v6 and hope the browser didn ' t choo... | socket_is_v6 = ( hasattr ( socket , 'AF_INET6' ) and self . socket . family == socket . AF_INET6 )
has_v6only_option = ( hasattr ( socket , 'IPPROTO_IPV6' ) and hasattr ( socket , 'IPV6_V6ONLY' ) )
if self . _auto_wildcard and socket_is_v6 and has_v6only_option :
try :
self . socket . setsockopt ( socket . ... |
def log_download ( self , log_num , filename ) :
'''download a log file''' | print ( "Downloading log %u as %s" % ( log_num , filename ) )
self . download_lognum = log_num
self . download_file = open ( filename , "wb" )
self . master . mav . log_request_data_send ( self . target_system , self . target_component , log_num , 0 , 0xFFFFFFFF )
self . download_filename = filename
self . download_set... |
def private_dir_path ( app_name ) :
"""Returns the private directory path
: param str app _ name : the name of the app
: rtype : str
: returns : directory path""" | _private_dir_path = os . path . expanduser ( click . get_app_dir ( app_name , force_posix = True , # forces to ~ / . tigerhost on Mac and Unix
) )
return _private_dir_path |
def mediate_transfer ( state : MediatorTransferState , possible_routes : List [ 'RouteState' ] , payer_channel : NettingChannelState , channelidentifiers_to_channels : ChannelMap , nodeaddresses_to_networkstates : NodeNetworkStateMap , pseudo_random_generator : random . Random , payer_transfer : LockedTransferSignedSta... | reachable_routes = filter_reachable_routes ( possible_routes , nodeaddresses_to_networkstates , )
available_routes = filter_used_routes ( state . transfers_pair , reachable_routes , )
assert payer_channel . partner_state . address == payer_transfer . balance_proof . sender
transfer_pair , mediated_events = forward_tran... |
def cli ( env , identifier ) :
"""Delete an image .""" | image_mgr = SoftLayer . ImageManager ( env . client )
image_id = helpers . resolve_id ( image_mgr . resolve_ids , identifier , 'image' )
image_mgr . delete_image ( image_id ) |
def bvlpdu_contents ( self , use_dict = None , as_class = dict ) :
"""Return the contents of an object as a dict .""" | # make / extend the dictionary of content
if use_dict is None :
use_dict = as_class ( )
# save the content
use_dict . __setitem__ ( 'address' , str ( self . fdAddress ) )
use_dict . __setitem__ ( 'ttl' , self . fdTTL )
use_dict . __setitem__ ( 'remaining' , self . fdRemain )
# return what we built / updated
return ... |
def _update_repo ( ret , name , target , clean , user , identity , rev , opts , update_head ) :
'''Update the repo to a given revision . Using clean passes - C to the hg up''' | log . debug ( 'target %s is found, "hg pull && hg up is probably required"' , target )
current_rev = __salt__ [ 'hg.revision' ] ( target , user = user , rev = '.' )
if not current_rev :
return _fail ( ret , 'Seems that {0} is not a valid hg repo' . format ( target ) )
if __opts__ [ 'test' ] :
test_result = ( 'R... |
def split_s3_path ( url : str ) -> Tuple [ str , str ] :
"""Split a full s3 path into the bucket name and path .""" | parsed = urlparse ( url )
if not parsed . netloc or not parsed . path :
raise ValueError ( "bad s3 path {}" . format ( url ) )
bucket_name = parsed . netloc
s3_path = parsed . path
# Remove ' / ' at beginning of path .
if s3_path . startswith ( "/" ) :
s3_path = s3_path [ 1 : ]
return bucket_name , s3_path |
def _filter_subgraph ( self , subgraph , predicate ) :
"""Given a subgraph of the manifest , and a predicate , filter
the subgraph using that predicate . Generates a list of nodes .""" | to_return = [ ]
for unique_id , item in subgraph . items ( ) :
if predicate ( item ) :
to_return . append ( item )
return to_return |
def _gen_cache_key_for_slice ( url_dict , start_int , total_int , authn_subj_list ) :
"""Generate cache key for the REST URL the client is currently accessing or is
expected to access in order to get the slice starting at the given ` ` start _ int ` ` of
a multi - slice result set .
When used for finding the ... | # logging . debug ( ' Gen key . result _ record _ count = { } ' . format ( result _ record _ count ) )
key_url_dict = copy . deepcopy ( url_dict )
key_url_dict [ 'query' ] . pop ( 'start' , None )
key_url_dict [ 'query' ] . pop ( 'count' , None )
key_json = d1_common . util . serialize_to_normalized_compact_json ( { 'u... |
def validate_unit_process_ids ( self , expected , actual ) :
"""Validate process id quantities for services on units .""" | self . log . debug ( 'Checking units for running processes...' )
self . log . debug ( 'Expected PIDs: {}' . format ( expected ) )
self . log . debug ( 'Actual PIDs: {}' . format ( actual ) )
if len ( actual ) != len ( expected ) :
return ( 'Unit count mismatch. expected, actual: {}, ' '{} ' . format ( len ( expect... |
def arguments ( ) :
"""Pulls in command line arguments .""" | DESCRIPTION = """\
"""
parser = argparse . ArgumentParser ( description = DESCRIPTION , formatter_class = Raw )
parser . add_argument ( "--email" , dest = "email" , action = 'store' , required = False , default = False , help = "An email address is required for querying Entrez databases." )
parser . add_argument ( ... |
def get_doc_entries ( target : typing . Callable ) -> list :
"""Gets the lines of documentation from the given target , which are formatted
so that each line is a documentation entry .
: param target :
: return :
A list of strings containing the documentation block entries""" | raw = get_docstring ( target )
if not raw :
return [ ]
raw_lines = [ line . strip ( ) for line in raw . replace ( '\r' , '' ) . split ( '\n' ) ]
def compactify ( compacted : list , entry : str ) -> list :
chars = entry . strip ( )
if not chars :
return compacted
if len ( compacted ) < 1 or chars... |
def _extract_value ( self , value ) :
"""If the value is true / false / null replace with Python equivalent .""" | return ModelEndpoint . _value_map . get ( smart_str ( value ) . lower ( ) , value ) |
def _update_case ( self , bs , ln , gn , base_mva , Yf , Yt , Va , Vm , Pg , Qg , lmbda ) :
"""Calculates the result attribute values .""" | V = Vm * exp ( 1j * Va )
# Va _ var = self . om . get _ var ( " Va " )
Vm_var = self . _Vm
Pmis = self . om . get_nln_constraint ( "Pmis" )
Qmis = self . om . get_nln_constraint ( "Qmis" )
Pg_var = self . _Pg
Qg_var = self . _Qg
# mu _ l = lmbda [ " mu _ l " ]
# mu _ u = lmbda [ " mu _ u " ]
lower = lmbda [ "lower" ]
u... |
def encode ( self , obj ) :
"""Returns ` ` obj ` ` serialized as a pickle binary string .
Raises
~ ipfsapi . exceptions . EncodingError
Parameters
obj : object
Serializable Python object
Returns
bytes""" | try :
return pickle . dumps ( obj )
except pickle . PicklingError as error :
raise exceptions . EncodingError ( 'pickle' , error ) |
def get_default_config ( self ) :
"""Return the default config for the handler""" | config = super ( MultiGraphitePickleHandler , self ) . get_default_config ( )
config . update ( { 'host' : [ 'localhost' ] , 'port' : 2003 , 'proto' : 'tcp' , 'timeout' : 15 , 'batch' : 1 , 'max_backlog_multiplier' : 5 , 'trim_backlog_multiplier' : 4 , } )
return config |
def get_template ( self , template_id ) :
"""Get a particular lightcurve template
Parameters
template _ id : str
id of desired template
Returns
phase : ndarray
array of phases
mag : ndarray
array of normalized magnitudes""" | try :
data = np . loadtxt ( self . data . extractfile ( template_id + '.dat' ) )
except KeyError :
raise ValueError ( "invalid star id: {0}" . format ( template_id ) )
return data [ : , 0 ] , data [ : , 1 ] |
def _verify_configs ( configs ) :
"""Verify a Molecule config was found and returns None .
: param configs : A list containing absolute paths to Molecule config files .
: return : None""" | if configs :
scenario_names = [ c . scenario . name for c in configs ]
for scenario_name , n in collections . Counter ( scenario_names ) . items ( ) :
if n > 1 :
msg = ( "Duplicate scenario name '{}' found. " 'Exiting.' ) . format ( scenario_name )
util . sysexit_with_message ( ... |
def decode_dict ( data ) :
"""解析json字典 , 转换成utf - 8""" | if six . PY3 :
return data
rv = { }
for key , value in iteritems ( data ) :
if isinstance ( key , text_type ) :
key = key . encode ( 'utf-8' )
if isinstance ( value , text_type ) :
value = value . encode ( 'utf-8' )
elif isinstance ( value , list ) :
value = _decode_list ( value ... |
def _copy_stream_position ( position ) :
"""Copy a StreamPosition .
Args :
position ( Union [ dict , ~ google . cloud . bigquery _ storage _ v1beta1 . types . StreamPosition ] ) :
StreamPostion ( or dictionary in StreamPosition format ) to copy .
Returns :
~ google . cloud . bigquery _ storage _ v1beta1 .... | if isinstance ( position , types . StreamPosition ) :
output = types . StreamPosition ( )
output . CopyFrom ( position )
return output
return types . StreamPosition ( ** position ) |
def extract_relationtypes ( urml_xml_tree ) :
"""extracts the allowed RST relation names and relation types from
an URML XML file .
Parameters
urml _ xml _ tree : lxml . etree . _ ElementTree
lxml ElementTree representation of an URML XML file
Returns
relations : dict of ( str , str )
Returns a dictio... | return { rel . attrib [ 'name' ] : rel . attrib [ 'type' ] for rel in urml_xml_tree . iterfind ( '//header/reltypes/rel' ) if 'type' in rel . attrib } |
def histogram_cover ( self , minAcc , maxAcc , groupBy = None , new_reg_fields = None ) :
"""* Wrapper of * ` ` COVER ` `
Variant of the function : meth : ` ~ . cover ` that returns all regions contributing to
the COVER divided in different ( contiguous ) parts according to their accumulation
index value ( on... | return self . cover ( minAcc , maxAcc , groupBy , new_reg_fields , cover_type = "histogram" ) |
def on_pubmsg ( self , connection , event ) :
"""Messages received in the channel - send them to the WebSocket .""" | for message in event . arguments ( ) :
nickname = self . get_nickname ( event )
nickname_color = self . nicknames [ nickname ]
self . namespace . emit ( "message" , nickname , message , nickname_color ) |
def bucket_type ( self , name ) :
"""Gets the bucket - type by the specified name . Bucket - types do
not always exist ( unlike buckets ) , but this will always return
a : class : ` BucketType < riak . bucket . BucketType > ` object .
: param name : the bucket - type name
: type name : str
: rtype : : cla... | if not isinstance ( name , string_types ) :
raise TypeError ( 'BucketType name must be a string' )
btype = BucketType ( self , name )
return self . _setdefault_handle_none ( self . _bucket_types , name , btype ) |
def _set_snmp ( self , v , load = False ) :
"""Setter method for snmp , mapped from YANG variable / interface / tengigabitethernet / snmp ( container )
If this variable is read - only ( config : false ) in the
source YANG file , then _ set _ snmp is considered as a private
method . Backends looking to populat... | if hasattr ( v , "_utype" ) :
v = v . _utype ( v )
try :
t = YANGDynClass ( v , base = snmp . snmp , is_container = 'container' , presence = False , yang_name = "snmp" , rest_name = "snmp" , parent = self , path_helper = self . _path_helper , extmethods = self . _extmethods , register_paths = True , extensions ... |
def sudoku ( G ) :
"""Solving Sudoku
: param G : integer matrix with 0 at empty cells
: returns bool : True if grid could be solved
: modifies : G will contain the solution
: complexity : huge , but linear for usual published 9x9 grids""" | global N , N2 , N4
if len ( G ) == 16 : # for a 16 x 16 sudoku grid
N , N2 , N4 = 4 , 16 , 256
e = 4 * N4
universe = e + 1
S = [ [ rc ( a ) , rv ( a ) , cv ( a ) , bv ( a ) ] for a in range ( N4 * N2 ) ]
A = [ e ]
for r in range ( N2 ) :
for c in range ( N2 ) :
if G [ r ] [ c ] != 0 :
a = as... |
def get_column ( matrix : list , col_index : int ) -> list :
"""This function retrieves the specified column from the provided nested list ( matrix ) .
Args :
matrix ( list ) : The nested list from which we need to extract the column .
col _ index ( int ) : The index of the column to be extracted .
Returns ... | return [ row [ col_index ] for row in matrix ] |
def _validate_nested_list_type ( self , name , obj , nested_level , * args ) :
"""Helper function that checks the input object as a list then recursively until nested _ level is 1.
: param name : Name of the object .
: param obj : Object to check the type of .
: param nested _ level : Integer with the current... | if nested_level <= 1 :
self . _validate_list_type ( name , obj , * args )
else :
if obj is None :
return
if not isinstance ( obj , list ) :
raise TypeError ( self . __class__ . __name__ + '.' + name + ' contains value of type ' + type ( obj ) . __name__ + ' where a list is expected' )
fo... |
def create ( gandi , domain , zone_id , name , type , value , ttl ) :
"""Create new DNS zone record entry for a domain .""" | if not zone_id :
result = gandi . domain . info ( domain )
zone_id = result [ 'zone_id' ]
if not zone_id :
gandi . echo ( 'No zone records found, domain %s doesn\'t seems to be ' 'managed at Gandi.' % domain )
return
record = { 'type' : type , 'name' : name , 'value' : value }
if ttl :
record [ 'ttl... |
def _get_attributes ( self , path ) :
""": param path : filepath within fast5
: return : dictionary of attributes found at ` ` path ` `
: rtype dict""" | path_grp = self . handle [ path ]
path_attr = path_grp . attrs
return dict ( path_attr ) |
def set_from_json ( self , obj , json , models = None , setter = None ) :
'''Sets the value of this property from a JSON value .
This method first
Args :
obj ( HasProps ) :
json ( JSON - dict ) :
models ( seq [ Model ] , optional ) :
setter ( ClientSession or ServerSession or None , optional ) :
This ... | if isinstance ( json , dict ) : # we want to try to keep the " format " of the data spec as string , dict , or number ,
# assuming the serialized dict is compatible with that .
old = getattr ( obj , self . name )
if old is not None :
try :
self . property . _type . validate ( old , False )
... |
def parseURIReference ( self , str ) :
"""Parse an URI reference string based on RFC 3986 and fills
in the appropriate fields of the @ uri structure
URI - reference = URI / relative - ref""" | ret = libxml2mod . xmlParseURIReference ( self . _o , str )
return ret |
def to_internal_value_single ( self , data , serializer ) :
"""Return the underlying object , given the serialized form .""" | related_model = serializer . Meta . model
if isinstance ( data , related_model ) :
return data
try :
instance = related_model . objects . get ( pk = data )
except related_model . DoesNotExist :
raise ValidationError ( "Invalid value for '%s': %s object with ID=%s not found" % ( self . field_name , related_m... |
def workerScript ( jobStore , config , jobName , jobStoreID , redirectOutputToLogFile = True ) :
"""Worker process script , runs a job .
: param str jobName : The " job name " ( a user friendly name ) of the job to be run
: param str jobStoreLocator : Specifies the job store to use
: param str jobStoreID : Th... | logging . basicConfig ( )
setLogLevel ( config . logLevel )
# Create the worker killer , if requested
logFileByteReportLimit = config . maxLogFileSize
if config . badWorker > 0 and random . random ( ) < config . badWorker : # We need to kill the process we are currently in , to simulate worker
# failure . We don ' t wa... |
def raw_update ( self , attributes = None ) :
"""Run a raw update against the base query .
: type attributes : dict
: rtype : int""" | if attributes is None :
attributes = { }
if self . _query is not None :
return self . _query . update ( attributes ) |
def _handle_remark_msg ( self , msg ) :
"""Try to parse the message provided with the remark tag or element .
: param str msg : The message
: raises overpy . exception . OverpassRuntimeError : If message starts with ' runtime error : '
: raises overpy . exception . OverpassRuntimeRemark : If message starts wi... | msg = msg . strip ( )
if msg . startswith ( "runtime error:" ) :
raise exception . OverpassRuntimeError ( msg = msg )
elif msg . startswith ( "runtime remark:" ) :
raise exception . OverpassRuntimeRemark ( msg = msg )
raise exception . OverpassUnknownError ( msg = msg ) |
def write_handle ( self , handle : int , value : bytes ) :
"""Write a handle to the device .""" | if not self . is_connected ( ) :
raise BluetoothBackendException ( 'Not connected to device!' )
self . _device . char_write_handle ( handle , value , True )
return True |
def parse ( self , s ) :
"""Parse reaction string .""" | global_comp = None
if self . _parse_global : # Split by colon for global compartment information
m = re . match ( r'^\s*\[(\w+)\]\s*:\s*(.*)' , s )
if m is not None :
global_comp = m . group ( 1 )
s = m . group ( 2 )
expect_operator = False
direction = None
left = [ ]
right = [ ]
current_side = ... |
def play ( self ) :
"""Change state to playing .""" | if self . state == STATE_PAUSED :
self . _player . set_state ( Gst . State . PLAYING )
self . state = STATE_PLAYING |
def _read_header ( self ) :
"""Reads the message header from the input stream .
: returns : tuple containing deserialized header and header _ auth objects
: rtype : tuple of aws _ encryption _ sdk . structures . MessageHeader
and aws _ encryption _ sdk . internal . structures . MessageHeaderAuthentication
:... | header , raw_header = deserialize_header ( self . source_stream )
self . __unframed_bytes_read += len ( raw_header )
if ( self . config . max_body_length is not None and header . content_type == ContentType . FRAMED_DATA and header . frame_length > self . config . max_body_length ) :
raise CustomMaximumValueExceede... |
def new ( self , name ) :
"""Build a stub migration with name + auto - id in config [ ' migration _ home ' ]
There is no guarantee this id will be unique for all remote migration
configurations . Conflicts will require manual management .""" | # XXX : dc : assert that the name is somewhat sane and follows python
# naming conventions
next_id = 0
cls_name = '_' . join ( ( name , next_id ) )
with open ( pjoin ( self . migration_home , name ) , "w+" ) as new_migration :
print >> new_migration , migration_tmpl . format ( cls_name = cls_name , migration_name =... |
def plot_grid ( images , slices = None , axes = 2 , # general figure arguments
figsize = 1. , rpad = 0 , cpad = 0 , # title arguments
title = None , tfontsize = 20 , title_dx = 0 , title_dy = 0 , # row arguments
rlabels = None , rfontsize = 14 , rfontcolor = 'white' , rfacecolor = 'black' , # column arguments
clabels =... | def mirror_matrix ( x ) :
return x [ : : - 1 , : ]
def rotate270_matrix ( x ) :
return mirror_matrix ( x . T )
def rotate180_matrix ( x ) :
return x [ : : - 1 , : ]
def rotate90_matrix ( x ) :
return mirror_matrix ( x ) . T
def flip_matrix ( x ) :
return mirror_matrix ( rotate180_matrix ( x ) )
def ... |
def _endless_page ( self , number , label = None ) :
"""Factory function that returns a * EndlessPage * instance .
This method works just like a partial constructor .""" | return EndlessPage ( self . _request , number , self . _page . number , len ( self ) , self . _querystring_key , label = label , default_number = self . _default_number , override_path = self . _override_path , ) |
def rate_url ( obj , score = 1 ) :
"""Generates a link to " rate " the given object with the provided score - this
can be used as a form target or for POSTing via Ajax .""" | return reverse ( 'ratings_rate_object' , args = ( ContentType . objects . get_for_model ( obj ) . pk , obj . pk , score , ) ) |
def get_validators_description ( view ) :
"""Returns validators description in format :
# # # Validators :
* validator1 name
* validator1 docstring
* validator2 name
* validator2 docstring""" | action = getattr ( view , 'action' , None )
if action is None :
return ''
description = ''
validators = getattr ( view , action + '_validators' , [ ] )
for validator in validators :
validator_description = get_entity_description ( validator )
description += '\n' + validator_description if description else v... |
def render_to_string ( self , template_file , context ) :
"""Render given template to string and add object to context""" | context = context if context else { }
if self . object :
context [ 'object' ] = self . object
context [ self . object . __class__ . __name__ . lower ( ) ] = self . object
return render_to_string ( template_file , context , self . request ) |
def set_current_language ( self , language_code , initialize = False ) :
"""Switch the currently activate language of the object .""" | self . _current_language = normalize_language_code ( language_code or get_language ( ) )
# Ensure the translation is present for _ _ get _ _ queries .
if initialize :
self . _get_translated_model ( use_fallback = False , auto_create = True ) |
def uncertainty_timescales ( self ) :
"""Estimate of the element - wise asymptotic standard deviation
in the model relaxation timescales .""" | if self . information_ is None :
self . _build_information ( )
sigma_timescales = _ratematrix . sigma_timescales ( self . information_ , theta = self . theta_ , n = self . n_states_ )
if self . n_timescales is None :
return sigma_timescales
return sigma_timescales [ : self . n_timescales ] |
def submit_and_connect ( self , spec ) :
"""Submit a new skein application , and wait to connect to it .
If an error occurs before the application connects , the application is
killed .
Parameters
spec : ApplicationSpec , str , or dict
A description of the application to run . Can be an
` ` ApplicationS... | spec = ApplicationSpec . _from_any ( spec )
app_id = self . submit ( spec )
try :
return self . connect ( app_id , security = spec . master . security )
except BaseException :
self . kill_application ( app_id )
raise |
def write_cache_decorator ( self , node_or_pagetag , name , args , buffered , identifiers , inline = False , toplevel = False ) :
"""write a post - function decorator to replace a rendering
callable with a cached version of itself .""" | self . printer . writeline ( "__M_%s = %s" % ( name , name ) )
cachekey = node_or_pagetag . parsed_attributes . get ( 'cache_key' , repr ( name ) )
cache_args = { }
if self . compiler . pagetag is not None :
cache_args . update ( ( pa [ 6 : ] , self . compiler . pagetag . parsed_attributes [ pa ] ) for pa in self .... |
def from_string ( cls , public_key ) :
"""Construct an Verifier instance from a public key or public
certificate string .
Args :
public _ key ( Union [ str , bytes ] ) : The public key in PEM format or the
x509 public key certificate .
Returns :
Verifier : The constructed verifier .
Raises :
ValueEr... | public_key_data = _helpers . to_bytes ( public_key )
if _CERTIFICATE_MARKER in public_key_data :
cert = cryptography . x509 . load_pem_x509_certificate ( public_key_data , _BACKEND )
pubkey = cert . public_key ( )
else :
pubkey = serialization . load_pem_public_key ( public_key_data , _BACKEND )
return cls ... |
def load_building_sample_data ( bd ) :
"""Sample data for the Building object
: param bd :
: return :""" | number_of_storeys = 6
interstorey_height = 3.4
masses = 40.0e3
# kg
bd . interstorey_heights = interstorey_height * np . ones ( number_of_storeys )
bd . floor_length = 18.0
bd . floor_width = 16.0
bd . storey_masses = masses * np . ones ( number_of_storeys ) |
def parse_event_xml ( self , event_data ) -> dict :
"""Parse metadata xml .""" | event = { }
event_xml = event_data . decode ( )
message = MESSAGE . search ( event_xml )
if not message :
return { }
event [ EVENT_OPERATION ] = message . group ( EVENT_OPERATION )
topic = TOPIC . search ( event_xml )
if topic :
event [ EVENT_TOPIC ] = topic . group ( EVENT_TOPIC )
source = SOURCE . search ( ev... |
def findAll ( self , tag_name , params = None , fn = None , case_sensitive = False ) :
"""Search for elements by their parameters using ` Depth - first algorithm
< http : / / en . wikipedia . org / wiki / Depth - first _ search > ` _ .
Args :
tag _ name ( str ) : Name of the tag you are looking for . Set to "... | output = [ ]
if self . isAlmostEqual ( tag_name , params , fn , case_sensitive ) :
output . append ( self )
tmp = [ ]
for el in self . childs :
tmp = el . findAll ( tag_name , params , fn , case_sensitive )
if tmp :
output . extend ( tmp )
return output |
def randbelow ( num : int ) -> int :
"""Return a random int in the range [ 0 , num ) .
Raises ValueError if num < = 0 , and TypeError if it ' s not an integer .
> > > randbelow ( 16 ) # doctest : + SKIP
13""" | if not isinstance ( num , int ) :
raise TypeError ( 'number must be an integer' )
if num <= 0 :
raise ValueError ( 'number must be greater than zero' )
if num == 1 :
return 0
# https : / / github . com / python / cpython / blob / 3.6 / Lib / random . py # L223
nbits = num . bit_length ( )
# don ' t use ( n ... |
def complete_use ( self , text , * _ ) :
"""Autocomplete for use""" | return [ t + " " for t in REGIONS if t . startswith ( text ) ] |
def clean_process_tree ( * signal_handler_args ) :
"""Stop all Processes in the current Process tree , recursively .""" | parent = psutil . Process ( )
procs = parent . children ( recursive = True )
if procs :
print ( f"[ZProc] Cleaning up {parent.name()!r} ({os.getpid()})..." )
for p in procs :
with suppress ( psutil . NoSuchProcess ) :
p . terminate ( )
_ , alive = psutil . wait_procs ( procs , timeout = 0.5 )
# 0.5 seem... |
def stop ( self ) :
"""Stops a paused pipeline . This will a trigger a ` ` StopIteration ` ` in the
inputs of the pipeline . And retrieve the buffered results . This will
stop all ` ` Pipers ` ` and ` ` NuMaps ` ` . Python will not terminate cleanly
if a pipeline is running or paused .""" | if self . _started . isSet ( ) and not self . _running . isSet ( ) and not self . _pausing . isSet ( ) : # stops the dagger
super ( Plumber , self ) . stop ( )
# disconnects all pipers
self . disconnect ( )
self . stats [ 'run_time' ] = time ( ) - self . stats [ 'start_time' ]
self . _started . clea... |
def _sign_threshold_signature_fulfillment ( cls , input_ , message , key_pairs ) :
"""Signs a ThresholdSha256.
Args :
input _ ( : class : ` ~ bigchaindb . common . transaction .
Input ` ) The Input to be signed .
message ( str ) : The message to be signed
key _ pairs ( dict ) : The keys to sign the Transa... | input_ = deepcopy ( input_ )
message = sha3_256 ( message . encode ( ) )
if input_ . fulfills :
message . update ( '{}{}' . format ( input_ . fulfills . txid , input_ . fulfills . output ) . encode ( ) )
for owner_before in set ( input_ . owners_before ) : # TODO : CC should throw a KeypairMismatchException , inste... |
def appliance_time_and_locale_configuration ( self ) :
"""Gets the ApplianceTimeAndLocaleConfiguration API client .
Returns :
ApplianceTimeAndLocaleConfiguration :""" | if not self . __appliance_time_and_locale_configuration :
self . __appliance_time_and_locale_configuration = ApplianceTimeAndLocaleConfiguration ( self . __connection )
return self . __appliance_time_and_locale_configuration |
def _prepend_name ( self , prefix , dict_ ) :
'''changes the keys of the dictionary prepending them with " name . "''' | return dict ( [ '.' . join ( [ prefix , name ] ) , msg ] for name , msg in dict_ . iteritems ( ) ) |
def on_connect ( self , client , userdata , flags , result_code ) :
"""Callback when the MQTT client is connected .
: param client : the client being connected .
: param userdata : unused .
: param flags : unused .
: param result _ code : result code .""" | self . log_info ( "Connected with result code {}" . format ( result_code ) )
self . state_handler . set_state ( State . welcome ) |
def parse ( cls , msg ) :
"""Parse message string to request object .""" | lines = msg . splitlines ( )
method , uri , version = lines [ 0 ] . split ( )
headers = cls . parse_headers ( '\r\n' . join ( lines [ 1 : ] ) )
return cls ( version = version , uri = uri , method = method , headers = headers ) |
import math
def min_steps_to_equate_numbers ( num1 , num2 ) :
"""Python function to determine the minimum number of operations required
to make two numbers equal .
Examples :
> > > min _ steps _ to _ equate _ numbers ( 2 , 4)
> > > min _ steps _ to _ equate _ numbers ( 4 , 10)
> > > min _ steps _ to _ equ... | if ( num1 > num2 ) :
num1 , num2 = num2 , num1
num2 = num2 // math . gcd ( num1 , num2 )
return num2 - 1 |
def _assume2point ( ) :
"""Convert global assumptions to a point .""" | point = dict ( )
for lit in _ASSUMPTIONS :
if isinstance ( lit , Complement ) :
point [ ~ lit ] = 0
elif isinstance ( lit , Variable ) :
point [ lit ] = 1
return point |
def add_request_handler ( self , request_handler ) : # type : ( AbstractRequestHandler ) - > None
"""Register input to the request handlers list .
: param request _ handler : Request Handler instance to be
registered .
: type request _ handler : AbstractRequestHandler
: return : None""" | if request_handler is None :
raise RuntimeConfigException ( "Valid Request Handler instance to be provided" )
if not isinstance ( request_handler , AbstractRequestHandler ) :
raise RuntimeConfigException ( "Input should be a RequestHandler instance" )
self . request_handler_chains . append ( GenericRequestHandl... |
def spawn ( self , command ) :
"""Spawns a new process and adds it to the pool""" | # process _ name
# output
# time before starting ( wait for port ? )
# start _ new _ session = True : avoid sending parent signals to child
env = dict ( os . environ )
env [ "MRQ_IS_SUBPROCESS" ] = "1"
env . update ( self . extra_env or { } )
# Extract env variables from shell commands .
parts = shlex . split ( command... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.