signature stringlengths 29 44.1k | implementation stringlengths 0 85.2k |
|---|---|
def implement ( cls , implementations , for_type = None , for_types = None ) :
"""Provide protocol implementation for a type .
Register all implementations of multimethod functions in this
protocol and add the type into the abstract base class of the
protocol .
Arguments :
implementations : A dict of ( fu... | for type_ in cls . __get_type_args ( for_type , for_types ) :
cls . _implement_for_type ( for_type = type_ , implementations = implementations ) |
def get_signature_request_list ( self , page = 1 , ux_version = None ) :
'''Get a list of SignatureRequest that you can access
This includes SignatureRequests you have sent as well as received , but
not ones that you have been CCed on .
Args :
page ( int , optional ) : Which page number of the SignatureRequ... | request = self . _get_request ( )
parameters = { "page" : page }
if ux_version is not None :
parameters [ 'ux_version' ] = ux_version
return request . get ( self . SIGNATURE_REQUEST_LIST_URL , parameters = parameters ) |
def MaxSpeed ( self , speed ) :
'Setup of maximum speed' | spi . SPI_write ( self . CS , [ 0x07 , 0x07 ] )
# Max Speed setup
spi . SPI_write ( self . CS , [ 0x00 , 0x00 ] )
spi . SPI_write ( self . CS , [ speed , speed ] ) |
def create_tag ( version : Union [ Version , str ] , tag_format : Optional [ str ] = None ) :
"""The tag and the software version might be different .
That ' s why this function exists .
Example :
| tag | version ( PEP 0440 ) |
| v0.9.0 | 0.9.0 |
| ver1.0.0 | 1.0.0 |
| ver1.0.0 . a0 | 1.0.0a0 |""" | if isinstance ( version , str ) :
version = Version ( version )
if not tag_format :
return version . public
major , minor , patch = version . release
prerelease = ""
if version . is_prerelease :
prerelease = f"{version.pre[0]}{version.pre[1]}"
t = Template ( tag_format )
return t . safe_substitute ( version... |
def _find_reader_dataset ( self , dataset_key , ** dfilter ) :
"""Attempt to find a ` DatasetID ` in the available readers .
Args :
dataset _ key ( str , float , DatasetID ) :
Dataset name , wavelength , or a combination of ` DatasetID `
parameters to use in searching for the dataset from the
available re... | too_many = False
for reader_name , reader_instance in self . readers . items ( ) :
try :
ds_id = reader_instance . get_dataset_key ( dataset_key , ** dfilter )
except TooManyResults :
LOG . trace ( "Too many datasets matching key {} in reader {}" . format ( dataset_key , reader_name ) )
... |
async def download ( resource_url ) :
'''Download given resource _ url''' | scheme = resource_url . parsed . scheme
if scheme in ( 'http' , 'https' ) :
await download_http ( resource_url )
elif scheme in ( 'git' , 'git+https' , 'git+http' ) :
await download_git ( resource_url )
else :
raise ValueError ( 'Unknown URL scheme: "%s"' % scheme ) |
def ruge_stuben_solver ( A , strength = ( 'classical' , { 'theta' : 0.25 } ) , CF = 'RS' , presmoother = ( 'gauss_seidel' , { 'sweep' : 'symmetric' } ) , postsmoother = ( 'gauss_seidel' , { 'sweep' : 'symmetric' } ) , max_levels = 10 , max_coarse = 10 , keep = False , ** kwargs ) :
"""Create a multilevel solver usi... | levels = [ multilevel_solver . level ( ) ]
# convert A to csr
if not isspmatrix_csr ( A ) :
try :
A = csr_matrix ( A )
warn ( "Implicit conversion of A to CSR" , SparseEfficiencyWarning )
except BaseException :
raise TypeError ( 'Argument A must have type csr_matrix, \
... |
def delete ( cls , schedule_id , schedule_instance_id , note_attachment_schedule_instance_id , monetary_account_id = None , custom_headers = None ) :
""": type user _ id : int
: type monetary _ account _ id : int
: type schedule _ id : int
: type schedule _ instance _ id : int
: type note _ attachment _ sch... | if custom_headers is None :
custom_headers = { }
api_client = client . ApiClient ( cls . _get_api_context ( ) )
endpoint_url = cls . _ENDPOINT_URL_DELETE . format ( cls . _determine_user_id ( ) , cls . _determine_monetary_account_id ( monetary_account_id ) , schedule_id , schedule_instance_id , note_attachment_sche... |
def parse_cli_args_into ( ) :
"""Creates the cli argparser for application specifics and AWS credentials .
: return : A dict of values from the cli arguments
: rtype : TemplaterCommand""" | cli_arg_parser = argparse . ArgumentParser ( parents = [ AWSArgumentParser ( default_role_session_name = 'aws-autodiscovery-templater' ) ] )
main_parser = cli_arg_parser . add_argument_group ( 'AWS Autodiscovery Templater' )
# template _ location = main _ parser . add _ mutually _ exclusive _ group ( required = True )
... |
def save_positions ( post_data , queryset = None ) :
"""Function to update a queryset of position objects with a post data dict .
: post _ data : Typical post data dictionary like ` ` request . POST ` ` , which
contains the keys of the position inputs .
: queryset : Queryset of the model ` ` ObjectPosition ` ... | if not queryset :
queryset = ObjectPosition . objects . all ( )
for key in post_data :
if key . startswith ( 'position-' ) :
try :
obj_id = int ( key . replace ( 'position-' , '' ) )
except ValueError :
continue
queryset . filter ( pk = obj_id ) . update ( positio... |
def delete_collection_api_service ( self , ** kwargs ) :
"""delete collection of APIService
This method makes a synchronous HTTP request by default . To make an
asynchronous HTTP request , please pass async _ req = True
> > > thread = api . delete _ collection _ api _ service ( async _ req = True )
> > > re... | kwargs [ '_return_http_data_only' ] = True
if kwargs . get ( 'async_req' ) :
return self . delete_collection_api_service_with_http_info ( ** kwargs )
else :
( data ) = self . delete_collection_api_service_with_http_info ( ** kwargs )
return data |
def hours_estimate ( self , branch = 'master' , grouping_window = 0.5 , single_commit_hours = 0.5 , limit = None , days = None , committer = True , ignore_globs = None , include_globs = None ) :
"""inspired by : https : / / github . com / kimmobrunfeldt / git - hours / blob / 8aaeee237cb9d9028e7a2592a25ad8468b1f45e... | max_diff_in_minutes = grouping_window * 60.0
first_commit_addition_in_minutes = single_commit_hours * 60.0
# First get the commit history
ch = self . commit_history ( branch = branch , limit = limit , days = days , ignore_globs = ignore_globs , include_globs = include_globs )
# split by committer | author
if committer ... |
def python_cardinality ( self , subject : str , all_are_optional : bool = False ) -> str :
"""Add the appropriate python typing to subject ( e . g . Optional , List , . . . )
: param subject : Subject to be decorated
: param all _ are _ optional : Force everything to be optional
: return : Typed subject""" | if self . multiple_elements :
rval = f"typing.List[{subject}]"
elif self . one_optional_element :
rval = subject if subject . startswith ( "typing.Optional[" ) else f"typing.Optional[{subject}]"
elif self . max == 0 :
rval = "type(None)"
else :
rval = subject
if all_are_optional and not self . one_optio... |
def fill_pager ( self , page ) :
"""Fix pager spaces""" | tty_size = os . popen ( "stty size" , "r" ) . read ( ) . split ( )
rows = int ( tty_size [ 0 ] ) - 1
lines = sum ( 1 for line in page . splitlines ( ) )
diff = rows - lines
fill = "\n" * diff
if diff > 0 :
return fill
else :
return "" |
def getOpenIDStore ( filestore_path , table_prefix ) :
"""Returns an OpenID association store object based on the database
engine chosen for this Django application .
* If no database engine is chosen , a filesystem - based store will
be used whose path is filestore _ path .
* If a database engine is chosen... | db_engine = settings . DATABASES [ 'default' ] [ 'ENGINE' ]
if not db_engine :
return FileOpenIDStore ( filestore_path )
# Possible side - effect : create a database connection if one isn ' t
# already open .
connection . cursor ( )
# Create table names to specify for SQL - backed stores .
tablenames = { 'associati... |
def send_json_message ( address , message , ** kwargs ) :
"""a shortcut for message sending""" | data = { 'message' : message , }
if not kwargs . get ( 'subject_id' ) :
data [ 'subject_id' ] = address
data . update ( kwargs )
hxdispatcher . send ( address , data ) |
def min_eta_for_em_bright ( bh_spin_z , ns_g_mass , mNS_pts , sBH_pts , eta_mins ) :
"""Function that uses the end product of generate _ em _ constraint _ data
to swipe over a set of NS - BH binaries and determine the minimum
symmetric mass ratio required by each binary to yield a remnant
disk mass that excee... | f = scipy . interpolate . RectBivariateSpline ( mNS_pts , sBH_pts , eta_mins , kx = 1 , ky = 1 )
# If bh _ spin _ z is a numpy array ( assuming ns _ g _ mass has the same size )
if isinstance ( bh_spin_z , np . ndarray ) :
eta_min = np . empty ( len ( bh_spin_z ) )
for i in range ( len ( bh_spin_z ) ) :
... |
def p_integerdecl_signed ( self , p ) :
'integerdecl : INTEGER SIGNED integernamelist SEMICOLON' | intlist = [ Integer ( r , Width ( msb = IntConst ( '31' , lineno = p . lineno ( 3 ) ) , lsb = IntConst ( '0' , lineno = p . lineno ( 3 ) ) , lineno = p . lineno ( 3 ) ) , signed = True , lineno = p . lineno ( 3 ) ) for r in p [ 2 ] ]
p [ 0 ] = Decl ( tuple ( intlist ) , lineno = p . lineno ( 1 ) )
p . set_lineno ( 0 , ... |
def get_projection ( self , axis ) :
"""Return the projection of this vector onto the given axis . The
axis does not need to be normalized .""" | scale = axis . dot ( self ) / axis . dot ( axis )
return axis * scale |
def add ( self , chassis ) :
"""add chassis .
: param chassis : chassis IP address .""" | self . chassis_chain [ chassis ] = IxeChassis ( self . session , chassis , len ( self . chassis_chain ) + 1 )
self . chassis_chain [ chassis ] . connect ( ) |
def synchronizeReplica ( self , replicaID , transportType = "esriTransportTypeUrl" , replicaServerGen = None , returnIdsForAdds = False , edits = None , returnAttachmentDatabyURL = False , async = False , syncDirection = "snapshot" , syncLayers = "perReplica" , editsUploadID = None , editsUploadFormat = None , dataForm... | params = { "f" : "json" , "replicaID" : replicaID , "transportType" : transportType , "dataFormat" : dataFormat , "rollbackOnFailure" : rollbackOnFailure , "async" : async , "returnIdsForAdds" : returnIdsForAdds , "syncDirection" : syncDirection , "returnAttachmentDatabyURL" : returnAttachmentDatabyURL }
return |
def render ( raw_config , environment = None ) :
"""Renders a config , using it as a template with the environment .
Args :
raw _ config ( str ) : the raw stacker configuration string .
environment ( dict , optional ) : any environment values that should be
passed to the config
Returns :
str : the stack... | t = Template ( raw_config )
buff = StringIO ( )
if not environment :
environment = { }
try :
substituted = t . substitute ( environment )
except KeyError as e :
raise exceptions . MissingEnvironment ( e . args [ 0 ] )
except ValueError : # Support " invalid " placeholders for lookup placeholders .
subst... |
def get ( self , request , bot_id , id , format = None ) :
"""Get state by id
serializer : StateSerializer
responseMessages :
- code : 401
message : Not authenticated""" | return super ( StateDetail , self ) . get ( request , bot_id , id , format ) |
def save_hdf5 ( X , y , path ) :
"""Save data as a HDF5 file .
Args :
X ( numpy or scipy sparse matrix ) : Data matrix
y ( numpy array ) : Target vector .
path ( str ) : Path to the HDF5 file to save data .""" | with h5py . File ( path , 'w' ) as f :
is_sparse = 1 if sparse . issparse ( X ) else 0
f [ 'issparse' ] = is_sparse
f [ 'target' ] = y
if is_sparse :
if not sparse . isspmatrix_csr ( X ) :
X = X . tocsr ( )
f [ 'shape' ] = np . array ( X . shape )
f [ 'data' ] = X . d... |
def density_separation ( X , labels , cluster_id1 , cluster_id2 , internal_nodes1 , internal_nodes2 , core_distances1 , core_distances2 , metric = 'euclidean' , ** kwd_args ) :
"""Compute the density separation between two clusters . This is the minimum
all - points mutual reachability distance between pairs of p... | if metric == 'precomputed' :
sub_select = X [ labels == cluster_id1 , : ] [ : , labels == cluster_id2 ]
distance_matrix = sub_select [ internal_nodes1 , : ] [ : , internal_nodes2 ]
else :
cluster1 = X [ labels == cluster_id1 ] [ internal_nodes1 ]
cluster2 = X [ labels == cluster_id2 ] [ internal_nodes2 ... |
def run ( cls , return_results = False ) :
"""Iterates through all associated Fields and applies all attached Rules . Depending on ' return _ collated _ results ' ,
this method will either return True ( all rules successful ) , False ( all , or some , rules failed )
or a dictionary list
containing the collate... | cls . result = [ ]
passed = True
for field in cls . fields :
result , errors = field . run ( )
results = { 'field' : field . name , 'value' : field . value , 'passed' : result , 'errors' : None }
if errors :
passed = False
results [ 'errors' ] = errors
cls . result . append ( results )
i... |
def sudo ( orig ) : # pragma : no cover
"""a nicer version of sudo that uses getpass to ask for a password , or
allows the first argument to be a string password""" | prompt = "[sudo] password for %s: " % getpass . getuser ( )
def stdin ( ) :
pw = getpass . getpass ( prompt = prompt ) + "\n"
yield pw
def process ( args , kwargs ) :
password = kwargs . pop ( "password" , None )
if password is None :
pass_getter = stdin ( )
else :
pass_getter = pass... |
def get_samp_con ( ) :
"""get sample naming convention""" | samp_con , Z = "" , ""
while samp_con == "" :
samp_con = input ( """
Sample naming convention:
[1] XXXXY: where XXXX is an arbitrary length site designation and Y
is the single character sample designation. e.g., TG001a is the
first sample from site TG001. [de... |
def __interact_copy ( self , escape_character = None , input_filter = None , output_filter = None ) :
'''This is used by the interact ( ) method .''' | while self . isalive ( ) :
if self . use_poll :
r = poll_ignore_interrupts ( [ self . child_fd , self . STDIN_FILENO ] )
else :
r , w , e = select_ignore_interrupts ( [ self . child_fd , self . STDIN_FILENO ] , [ ] , [ ] )
if self . child_fd in r :
try :
data = self . __i... |
def get_mainmarket_ip ( ip , port ) :
"""[ summary ]
Arguments :
ip { [ type ] } - - [ description ]
port { [ type ] } - - [ description ]
Returns :
[ type ] - - [ description ]""" | global best_ip
if ip is None and port is None and best_ip [ 'stock' ] [ 'ip' ] is None and best_ip [ 'stock' ] [ 'port' ] is None :
best_ip = select_best_ip ( )
ip = best_ip [ 'stock' ] [ 'ip' ]
port = best_ip [ 'stock' ] [ 'port' ]
elif ip is None and port is None and best_ip [ 'stock' ] [ 'ip' ] is not No... |
def gev_expval ( xi , mu = 0 , sigma = 1 ) :
"""Expected value of generalized extreme value distribution .""" | return mu - ( sigma / xi ) + ( sigma / xi ) * flib . gamfun ( 1 - xi ) |
def ddot ( L , R , left = None , out = None ) :
r"""Dot product of a matrix and a diagonal one .
Args :
L ( array _ like ) : Left matrix .
R ( array _ like ) : Right matrix .
out ( : class : ` numpy . ndarray ` , optional ) : copy result to .
Returns :
: class : ` numpy . ndarray ` : Resulting matrix ."... | L = asarray ( L , float )
R = asarray ( R , float )
if left is None :
ok = min ( L . ndim , R . ndim ) == 1 and max ( L . ndim , R . ndim ) == 2
if not ok :
msg = "Wrong array layout. One array should have"
msg += " ndim=1 and the other one ndim=2."
raise ValueError ( msg )
left = L ... |
def molecule ( lines ) :
"""Parse molfile part into molecule object
Args :
lines ( list ) : lines of molfile part
Raises :
ValueError : Symbol not defined in periodictable . yaml
( Polymer expression not supported yet )""" | count_line = lines [ 3 ]
num_atoms = int ( count_line [ 0 : 3 ] )
num_bonds = int ( count_line [ 3 : 6 ] )
# chiral _ flag = int ( count _ line [ 12:15 ] ) # Not used
# num _ prop = int ( count _ line [ 30:33 ] ) # " No longer supported "
compound = Compound ( )
compound . graph . _node = atoms ( lines [ 4 : num_atoms ... |
def get ( self , names_to_get , convert_to_numpy = True ) :
"""Loads the requested variables from the matlab com client .
names _ to _ get can be either a variable name or a list of variable names .
If it is a variable name , the values is returned .
If it is a list , a dictionary of variable _ name - > value... | self . _check_open ( )
single_itme = isinstance ( names_to_get , ( unicode , str ) )
if single_itme :
names_to_get = [ names_to_get ]
ret = { }
for name in names_to_get :
ret [ name ] = self . client . GetWorkspaceData ( name , 'base' )
# TODO ( daniv ) : Do we really want to reduce dimensions like that ? w... |
def main ( ) :
"""This is a Toil pipeline to transfer TCGA data into an S3 Bucket
Data is pulled down with Genetorrent and transferred to S3 via S3AM .""" | # Define Parser object and add to toil
parser = build_parser ( )
Job . Runner . addToilOptions ( parser )
args = parser . parse_args ( )
# Store inputs from argparse
inputs = { 'genetorrent' : args . genetorrent , 'genetorrent_key' : args . genetorrent_key , 'ssec' : args . ssec , 's3_dir' : args . s3_dir }
# Sanity ch... |
def send ( self , to , amount , from_address = None , fee = None ) :
"""Send bitcoin from your wallet to a single address .
: param str to : recipient bitcoin address
: param int amount : amount to send ( in satoshi )
: param str from _ address : specific address to send from ( optional )
: param int fee : ... | recipient = { to : amount }
return self . send_many ( recipient , from_address , fee ) |
def _series_col_letter ( self , series ) :
"""The letter of the Excel worksheet column in which the data for a
series appears .""" | column_number = 1 + series . categories . depth + series . index
return self . _column_reference ( column_number ) |
def _apply_concretization_strategies ( self , addr , strategies , action ) :
"""Applies concretization strategies on the address until one of them succeeds .""" | # we try all the strategies in order
for s in strategies : # first , we trigger the SimInspect breakpoint and give it a chance to intervene
e = addr
self . state . _inspect ( 'address_concretization' , BP_BEFORE , address_concretization_strategy = s , address_concretization_action = action , address_concretizat... |
def _pickle_to_temp_location_or_memory ( obj ) :
'''If obj can be serialized directly into memory ( via cloudpickle ) this
will return the serialized bytes .
Otherwise , gl _ pickle is attempted and it will then
generates a temporary directory serializes an object into it , returning
the directory name . Th... | from . import _cloudpickle as cloudpickle
try : # try cloudpickle first and see if that works
lambda_str = cloudpickle . dumps ( obj )
return lambda_str
except :
pass
# nope . that does not work ! lets try again with gl pickle
filename = _make_temp_filename ( 'pickle' )
from . . import _gl_pickle
pickler = ... |
def ffmpeg_version ( ) :
"""Returns the available ffmpeg version
Returns
version : str
version number as string""" | cmd = [ 'ffmpeg' , '-version' ]
output = sp . check_output ( cmd )
aac_codecs = [ x for x in output . splitlines ( ) if "ffmpeg version " in str ( x ) ] [ 0 ]
hay = aac_codecs . decode ( 'ascii' )
match = re . findall ( r'ffmpeg version (\d+\.)?(\d+\.)?(\*|\d+)' , hay )
if match :
return "" . join ( match [ 0 ] )
e... |
def pyprf ( strCsvCnfg , lgcTest = False , varRat = None , strPathHrf = None ) :
"""Main function for pRF mapping .
Parameters
strCsvCnfg : str
Absolute file path of config file .
lgcTest : Boolean
Whether this is a test ( pytest ) . If yes , absolute path of pyprf libary
will be prepended to config fil... | # * * * Check time
print ( '---pRF analysis' )
varTme01 = time . time ( )
# * * * Preparations
# Load config parameters from csv file into dictionary :
dicCnfg = load_config ( strCsvCnfg , lgcTest = lgcTest )
# Load config parameters from dictionary into namespace :
cfg = cls_set_config ( dicCnfg )
# Conditional import... |
def _gen_toc ( self , idx ) :
"""生成目录html
: return :
: rtype :""" | if not self . _chapterization :
return ''
start , end = self . _start_end_of_index ( idx )
chap_infos = '\n' . join ( [ " <li><a href=\"#ch{}\">{}</a></li>" . format ( chap . _idx , chap . _title ) for chap in self . _chapters [ start : end ] ] )
toc = """
<div id="toc">
<h2>
目录<b... |
def load_migration_file ( self , filename ) :
"""Load migration file as module .""" | path = os . path . join ( self . directory , filename )
# spec = spec _ from _ file _ location ( " migration " , path )
# module = module _ from _ spec ( spec )
# spec . loader . exec _ module ( module )
module = imp . load_source ( "migration" , path )
return module |
def get_scope ( self , which , labels ) :
""": param which : str , description of the image this belongs to
: param labels : dict , labels on the image""" | try :
scope_choice = labels [ self . SCOPE_LABEL ]
except ( KeyError , TypeError ) :
self . log . debug ( "no distribution scope set for %s image" , which )
raise NothingToCheck
try :
scope = self . SCOPE_NAME . index ( scope_choice )
except ValueError :
self . log . warning ( "invalid label %s=%s f... |
def cli ( ) :
"""Entry point for the application script""" | parser = get_argparser ( )
args = parser . parse_args ( )
check_args ( args )
if args . v :
print ( 'ERAlchemy version {}.' . format ( __version__ ) )
exit ( 0 )
render_er ( args . i , args . o , include_tables = args . include_tables , include_columns = args . include_columns , exclude_tables = args . exclude_... |
def show_member ( self , member , ** _params ) :
"""Fetches information of a certain load balancer member .""" | return self . get ( self . member_path % ( member ) , params = _params ) |
def ToURN ( self ) :
"""Converts a reference into an URN .""" | if self . path_type in [ PathInfo . PathType . OS , PathInfo . PathType . TSK ] :
return rdfvalue . RDFURN ( self . client_id ) . Add ( "fs" ) . Add ( self . path_type . name . lower ( ) ) . Add ( "/" . join ( self . path_components ) )
elif self . path_type == PathInfo . PathType . REGISTRY :
return rdfvalue .... |
def get_table_description ( self , cursor , table_name , identity_check = True ) :
"""Returns a description of the table , with DB - API cursor . description interface .
The ' auto _ check ' parameter has been added to the function argspec .
If set to True , the function will check each of the table ' s fields ... | # map pyodbc ' s cursor . columns to db - api cursor description
columns = [ [ c [ 3 ] , c [ 4 ] , None , c [ 6 ] , c [ 6 ] , c [ 8 ] , c [ 10 ] ] for c in cursor . columns ( table = table_name ) ]
items = [ ]
for column in columns :
if identity_check and self . _is_auto_field ( cursor , table_name , column [ 0 ] )... |
def collect_members ( module_to_name ) :
"""Collect all symbols from a list of modules .
Args :
module _ to _ name : Dictionary mapping modules to short names .
Returns :
Dictionary mapping name to ( fullname , member ) pairs .""" | members = { }
for module , module_name in module_to_name . items ( ) :
all_names = getattr ( module , "__all__" , None )
for name , member in inspect . getmembers ( module ) :
if ( ( inspect . isfunction ( member ) or inspect . isclass ( member ) ) and not _always_drop_symbol_re . match ( name ) and ( a... |
def transform ( self , y , exogenous = None , ** _ ) :
"""Transform the new array
Apply the Box - Cox transformation to the array after learning the
lambda parameter .
Parameters
y : array - like or None , shape = ( n _ samples , )
The endogenous ( time - series ) array .
exogenous : array - like or Non... | check_is_fitted ( self , "lam1_" )
lam1 = self . lam1_
lam2 = self . lam2_
y , exog = self . _check_y_exog ( y , exogenous )
y += lam2
neg_mask = y <= 0.
if neg_mask . any ( ) :
action = self . neg_action
msg = "Negative or zero values present in y"
if action == "raise" :
raise ValueError ( msg )
... |
def _copyValues ( self , to , extra = None ) :
"""Copies param values from this instance to another instance for
params shared by them .
: param to : the target instance
: param extra : extra params to be copied
: return : the target instance with param values copied""" | paramMap = self . _paramMap . copy ( )
if extra is not None :
paramMap . update ( extra )
for param in self . params : # copy default params
if param in self . _defaultParamMap and to . hasParam ( param . name ) :
to . _defaultParamMap [ to . getParam ( param . name ) ] = self . _defaultParamMap [ param... |
def remove ( self , key , column_path , timestamp , consistency_level ) :
"""Remove data from the row specified by key at the granularity specified by column _ path , and the given timestamp . Note
that all the values in column _ path besides column _ path . column _ family are truly optional : you can remove the... | self . _seqid += 1
d = self . _reqs [ self . _seqid ] = defer . Deferred ( )
self . send_remove ( key , column_path , timestamp , consistency_level )
return d |
def join_channel ( self , channel ) :
"""Join a different chat channel on Twitch .
Note , this function returns immediately , but the switch might
take a moment
: param channel : name of the channel ( without # )""" | self . s . send ( ( 'JOIN #%s\r\n' % channel ) . encode ( 'utf-8' ) )
if self . verbose :
print ( 'JOIN #%s\r\n' % channel ) |
def prune_directory ( self ) :
"""Delete any objects that can be loaded and are expired according to
the current lifetime setting .
A file will be deleted if the following conditions are met :
- The file extension matches : py : meth : ` bucketcache . backends . Backend . file _ extension `
- The object can... | glob = '*.{ext}' . format ( ext = self . backend . file_extension )
totalsize = 0
totalnum = 0
for f in self . _path . glob ( glob ) :
filesize = f . stat ( ) . st_size
key_hash = f . stem
in_cache = key_hash in self . _cache
try :
self . _get_obj_from_hash ( key_hash )
except KeyExpirationE... |
def _get ( self , locator , expected_condition , params = None , timeout = None , error_msg = "" , driver = None , ** kwargs ) :
"""Get elements based on locator with optional parameters .
Uses selenium . webdriver . support . expected _ conditions to determine the state of the element ( s ) .
: param locator :... | from selenium . webdriver . support . ui import WebDriverWait
if not isinstance ( locator , WebElement ) :
error_msg += "\nLocator of type <{}> with selector <{}> with params <{params}>" . format ( * locator , params = params )
locator = self . __class__ . get_compliant_locator ( * locator , params = params )
_... |
def create_from_pointer ( cls , pointer ) :
""": type pointer : Pointer""" | instance = cls . __new__ ( cls )
instance . pointer = pointer
instance . label_monetary_account = LabelMonetaryAccount ( )
instance . label_monetary_account . _iban = pointer . value
instance . label_monetary_account . _display_name = pointer . name
return instance |
def close ( self ) :
"""Close the client . This includes closing the Session
and CBS authentication layer as well as the Connection .
If the client was opened using an external Connection ,
this will be left intact .
No further messages can be sent or received and the client
cannot be re - opened .
All ... | if self . message_handler :
self . message_handler . destroy ( )
self . message_handler = None
self . _shutdown = True
if self . _keep_alive_thread :
self . _keep_alive_thread . join ( )
self . _keep_alive_thread = None
if not self . _session :
return
# already closed .
if not self . _connection... |
def load_func ( serializer_type ) :
"""A decorator for ` ` _ load ( loader _ func = loader _ func , * * kwargs ) ` `""" | def outer_wrapper ( loader_func ) :
def wrapper ( * args , ** kwargs ) :
return _load ( * args , loader_func = loader_func , serializer_type = serializer_type , ** kwargs )
return wrapper
return outer_wrapper |
def create_api_pool_deploy ( self ) :
"""Get an instance of Api Pool Deploy services facade .""" | return ApiPoolDeploy ( self . networkapi_url , self . user , self . password , self . user_ldap ) |
def run_breiman85 ( ) :
"""Run Breiman 85 sample .""" | x , y = build_sample_ace_problem_breiman85 ( 200 )
ace_solver = ace . ACESolver ( )
ace_solver . specify_data_set ( x , y )
ace_solver . solve ( )
try :
ace . plot_transforms ( ace_solver , 'sample_ace_breiman85.png' )
except ImportError :
pass
return ace_solver |
def buildEXPmask ( self , chip , dqarr ) :
"""Builds a weight mask from an input DQ array and the exposure time
per pixel for this chip .""" | log . info ( "Applying EXPTIME weighting to DQ mask for chip %s" % chip )
# exparr = self . getexptimeimg ( chip )
exparr = self . _image [ self . scienceExt , chip ] . _exptime
expmask = exparr * dqarr
return expmask . astype ( np . float32 ) |
def check_allowed_letters ( seq , allowed_letters_as_set ) :
"""Validate sequence : Rise an error if sequence contains undesirable letters .""" | # set of unique letters in sequence
seq_set = set ( seq )
not_allowed_letters_in_seq = [ x for x in seq_set if str ( x ) . upper ( ) not in allowed_letters_as_set ]
if len ( not_allowed_letters_in_seq ) > 0 :
raise forms . ValidationError ( "This sequence type cannot contain letters: " + ", " . join ( not_allowed_l... |
def _groupname ( ) :
'''Grain for the minion groupname''' | if grp :
try :
groupname = grp . getgrgid ( os . getgid ( ) ) . gr_name
except KeyError :
groupname = ''
else :
groupname = ''
return groupname |
def checkPrediction2 ( self , patternNZs , output = None , confidence = None , details = False ) :
"""This function will replace checkPrediction .
This function produces goodness - of - match scores for a set of input patterns , by
checking for their presense in the current and predicted output of the TP .
Re... | # Get the non - zeros in each pattern
numPatterns = len ( patternNZs )
# Compute the union of all the expected patterns
orAll = set ( )
orAll = orAll . union ( * patternNZs )
# Get the list of active columns in the output
if output is None :
assert self . currentOutput is not None
output = self . currentOutput
... |
def decrypt_element ( encrypted_data , key , debug = False , inplace = False ) :
"""Decrypts an encrypted element .
: param encrypted _ data : The encrypted data .
: type : lxml . etree . Element | DOMElement | basestring
: param key : The key .
: type : string
: param debug : Activate the xmlsec debug
... | if isinstance ( encrypted_data , Element ) :
encrypted_data = OneLogin_Saml2_XML . to_etree ( str ( encrypted_data . toxml ( ) ) )
if not inplace and isinstance ( encrypted_data , OneLogin_Saml2_XML . _element_class ) :
encrypted_data = deepcopy ( encrypted_data )
elif isinstance ( encrypted_data , OneLogin_Sam... |
def get_tr ( self ) :
"""Returns the top right border of the cell""" | cell_above = CellBorders ( self . cell_attributes , * self . cell . get_above_key_rect ( ) )
return cell_above . get_r ( ) |
def delete ( name , remove = False , force = False , root = None ) :
'''Remove a user from the minion
name
Username to delete
remove
Remove home directory and mail spool
force
Force some actions that would fail otherwise
root
Directory to chroot into
CLI Example :
. . code - block : : bash
sal... | cmd = [ 'userdel' ]
if remove :
cmd . append ( '-r' )
if force and __grains__ [ 'kernel' ] != 'OpenBSD' and __grains__ [ 'kernel' ] != 'AIX' :
cmd . append ( '-f' )
cmd . append ( name )
if root is not None and __grains__ [ 'kernel' ] != 'AIX' :
cmd . extend ( ( '-R' , root ) )
ret = __salt__ [ 'cmd.run_all... |
def make_template_paths ( template_file , paths = None ) :
"""Make up a list of template search paths from given ' template _ file '
( absolute or relative path to the template file ) and / or ' paths ' ( a list of
template search paths given by user ) .
NOTE : User - given ' paths ' will take higher priority... | tmpldir = os . path . abspath ( os . path . dirname ( template_file ) )
return [ tmpldir ] if paths is None else paths + [ tmpldir ] |
def _create_base_ensemble ( self , out , n_estimators , n_folds ) :
"""For each base estimator collect models trained on each fold""" | ensemble_scores = numpy . empty ( ( n_estimators , n_folds ) )
base_ensemble = numpy . empty_like ( ensemble_scores , dtype = numpy . object )
for model , fold , score , est in out :
ensemble_scores [ model , fold ] = score
base_ensemble [ model , fold ] = est
return ensemble_scores , base_ensemble |
def dump_graph ( self ) :
"""Dump a key - only representation of the schema to a dictionary . Every
known relation is a key with a value of a list of keys it is referenced
by .""" | # we have to hold the lock for the entire dump , if other threads modify
# self . relations or any cache entry ' s referenced _ by during iteration
# it ' s a runtime error !
with self . lock :
return { dot_separated ( k ) : v . dump_graph_entry ( ) for k , v in self . relations . items ( ) } |
def lock ( func ) :
"""互斥锁""" | @ functools . wraps ( func )
def _func ( * args , ** kwargs ) :
mutex . acquire ( )
try :
return func ( * args , ** kwargs )
finally :
mutex . release ( )
return _func |
def nested_insert ( self , item_list ) :
"""Create a series of nested LIVVDicts given a list""" | if len ( item_list ) == 1 :
self [ item_list [ 0 ] ] = LIVVDict ( )
elif len ( item_list ) > 1 :
if item_list [ 0 ] not in self :
self [ item_list [ 0 ] ] = LIVVDict ( )
self [ item_list [ 0 ] ] . nested_insert ( item_list [ 1 : ] ) |
def home ( self , n = 1 , interval = 0 , pre_dl = None , post_dl = None ) :
"""Pres home key n times .
* * 中文文档 * *
按 home 键n次 。""" | self . delay ( pre_dl )
self . k . tap_key ( self . k . home_key , n , interval )
self . delay ( post_dl ) |
def is_allowed ( self , user_agent , url , syntax = GYM2008 ) :
"""True if the user agent is permitted to visit the URL . The syntax
parameter can be GYM2008 ( the default ) or MK1996 for strict adherence
to the traditional standard .""" | if PY_MAJOR_VERSION < 3 : # The robot rules are stored internally as Unicode . The two lines
# below ensure that the parameters passed to this function are
# also Unicode . If those lines were not present and the caller
# passed a non - Unicode user agent or URL string to this function ,
# Python would silently convert... |
def if_then ( self , classical_reg , if_program , else_program = None ) :
"""If the classical register at index classical reg is 1 , run if _ program , else run
else _ program .
Equivalent to the following construction :
. . code : :
IF [ c ] :
instrA . . .
ELSE :
instrB . . .
JUMP - WHEN @ THEN [ c... | else_program = else_program if else_program is not None else Program ( )
label_then = LabelPlaceholder ( "THEN" )
label_end = LabelPlaceholder ( "END" )
self . inst ( JumpWhen ( target = label_then , condition = unpack_classical_reg ( classical_reg ) ) )
self . inst ( else_program )
self . inst ( Jump ( label_end ) )
s... |
def global_to_local ( self , index ) :
"""Calculate local index from global index
: param index : input index
: return : local index for data""" | if ( type ( index ) is int ) or ( type ( index ) is slice ) :
if len ( self . __mask ) > 1 :
raise IndexError ( 'check length of parameter index' )
# 1D array
if type ( index ) is int :
return self . int_global_to_local ( index )
elif type ( index ) is slice :
return self . slice... |
def _keygen ( self , event , ts = None ) :
"""Generate redis key for event at timestamp .
: param event : event name
: param ts : timestamp , default to current timestamp if left as None""" | return "%s:%s" % ( self . namespace ( ts or time . time ( ) ) , event ) |
def init ( name , cpu , mem , image , hypervisor = 'kvm' , host = None , seed = True , nic = 'default' , install = True , start = True , disk = 'default' , saltenv = 'base' , enable_vnc = False , seed_cmd = 'seed.apply' , enable_qcow = False , serial_type = 'None' ) :
'''This routine is used to create a new virtual... | __jid_event__ . fire_event ( { 'message' : 'Searching for hosts' } , 'progress' )
data = query ( host , quiet = True )
# Check if the name is already deployed
for node in data :
if 'vm_info' in data [ node ] :
if name in data [ node ] [ 'vm_info' ] :
__jid_event__ . fire_event ( { 'message' : 'V... |
def _parse_tree_dump ( text_dump ) : # type : ( str ) - > Optional [ Dict [ str , Any ] ]
"""Parse text tree dump ( one item of a list returned by Booster . get _ dump ( ) )
into json format that will be used by next XGBoost release .""" | result = None
stack = [ ]
# type : List [ Dict ]
for line in text_dump . split ( '\n' ) :
if line :
depth , node = _parse_dump_line ( line )
if depth == 0 :
assert not stack
result = node
stack . append ( node )
elif depth > len ( stack ) :
rai... |
def QA_util_time_gap ( time , gap , methods , type_ ) :
'分钟线回测的时候的gap' | min_len = int ( 240 / int ( str ( type_ ) . split ( 'min' ) [ 0 ] ) )
day_gap = math . ceil ( gap / min_len )
if methods in [ '>' , 'gt' ] :
data = pd . concat ( [ pd . DataFrame ( QA_util_make_min_index ( day , type_ ) ) for day in trade_date_sse [ trade_date_sse . index ( str ( datetime . datetime . strptime ( ti... |
def findlast ( * args , ** kwargs ) :
"""Find the last matching element in a list and return it .
Usage : :
findlast ( element , list _ )
findlast ( of = element , in _ = list _ )
findlast ( where = predicate , in _ = list _ )
: param element , of : Element to search for ( by equality comparison )
: par... | list_ , idx = _index ( * args , start = sys . maxsize , step = - 1 , ** kwargs )
if idx < 0 :
raise IndexError ( "element not found" )
return list_ [ idx ] |
def conpair_general_stats_table ( self ) :
"""Take the parsed stats from the Conpair report and add it to the
basic stats table at the top of the report""" | headers = { }
headers [ 'concordance_concordance' ] = { 'title' : 'Concordance' , 'max' : 100 , 'min' : 0 , 'suffix' : '%' , 'format' : '{:,.2f}' , 'scale' : 'RdYlGn' }
headers [ 'contamination_normal' ] = { 'title' : 'N Contamination' , 'description' : 'Normal sample contamination level' , 'max' : 100 , 'min' : 0 , 's... |
def delete_post ( self , blogname , id ) :
"""Deletes a post with the given id
: param blogname : a string , the url of the blog you want to delete from
: param id : an int , the post id that you want to delete
: returns : a dict created from the JSON response""" | url = "/v2/blog/{}/post/delete" . format ( blogname )
return self . send_api_request ( 'post' , url , { 'id' : id } , [ 'id' ] ) |
def copy_tree ( src , dst , symlinks = False , ignore = [ ] ) :
"""Copy a full directory structure .
: param src : Source path
: param dst : Destination path
: param symlinks : Copy symlinks
: param ignore : Subdirs / filenames to ignore""" | names = os . listdir ( src )
if not os . path . exists ( dst ) :
os . makedirs ( dst )
errors = [ ]
for name in names :
if name in ignore :
continue
srcname = os . path . join ( src , name )
dstname = os . path . join ( dst , name )
try :
if symlinks and os . path . islink ( srcname ... |
def on_next_request ( self , py_db , request ) :
''': param NextRequest request :''' | arguments = request . arguments
# : : type arguments : NextArguments
thread_id = arguments . threadId
if py_db . get_use_libraries_filter ( ) :
step_cmd_id = CMD_STEP_OVER_MY_CODE
else :
step_cmd_id = CMD_STEP_OVER
self . api . request_step ( py_db , thread_id , step_cmd_id )
response = pydevd_base_schema . bui... |
def _build_document_converter ( cls , session : AppSession ) :
'''Build the Document Converter .''' | if not session . args . convert_links :
return
converter = session . factory . new ( 'BatchDocumentConverter' , session . factory [ 'HTMLParser' ] , session . factory [ 'ElementWalker' ] , session . factory [ 'URLTable' ] , backup = session . args . backup_converted )
return converter |
def waiver2mef ( sciname , newname = None , convert_dq = True , writefits = True ) :
"""Converts a GEIS science file and its corresponding
data quality file ( if present ) to MEF format
Writes out both files to disk .
Returns the new name of the science image .""" | if isinstance ( sciname , fits . HDUList ) :
filename = sciname . filename ( )
else :
filename = sciname
try :
clobber = True
fimg = convertwaiveredfits . convertwaiveredfits ( filename )
# check for the existence of a data quality file
_dqname = fileutil . buildNewRootname ( filename , extn = '... |
def get_json_or_yaml ( file_path , content ) :
"""Generate JSON or YAML depending on the file extension .""" | if os . path . splitext ( file_path ) [ 1 ] == ".json" :
return json . dumps ( content , sort_keys = False , indent = 4 , separators = ( ',' , ': ' ) )
else :
return inginious . common . custom_yaml . dump ( content ) |
def matched ( self , other ) :
"""Returns True if the two ValueElement instances differ only by name ,
default value or some other inconsequential modifier .""" | mods = [ "allocatable" , "pointer" ]
return ( self . kind . lower ( ) == other . kind . lower ( ) and self . dtype . lower ( ) == other . dtype . lower ( ) and self . D == other . D and all ( [ m in other . modifiers for m in self . modifiers if m in mods ] ) ) |
def dispatch_command ( self , command , stage ) :
"""Given a command to execute and stage ,
execute that command .""" | self . api_stage = stage
if command not in [ 'status' , 'manage' ] :
if not self . vargs . get ( 'json' , None ) :
click . echo ( "Calling " + click . style ( command , fg = "green" , bold = True ) + " for stage " + click . style ( self . api_stage , bold = True ) + ".." )
# Explicitly define the app functi... |
def has_permission ( obj_name , principal , permission , access_mode = 'grant' , obj_type = 'file' , exact = True ) :
r'''Check if the object has a permission
Args :
obj _ name ( str ) :
The name of or path to the object .
principal ( str ) :
The name of the user or group for which to get permissions . Ca... | # Validate access _ mode
if access_mode . lower ( ) not in [ 'grant' , 'deny' ] :
raise SaltInvocationError ( 'Invalid "access_mode" passed: {0}' . format ( access_mode ) )
access_mode = access_mode . lower ( )
# Get the DACL
obj_dacl = dacl ( obj_name , obj_type )
obj_type = obj_type . lower ( )
# Get a PySID obje... |
def search_stack_for_var ( varname , verbose = util_arg . NOT_QUIET ) :
"""Finds a varable ( local or global ) somewhere in the stack and returns the value
Args :
varname ( str ) : variable name
Returns :
None if varname is not found else its value""" | curr_frame = inspect . currentframe ( )
if verbose :
print ( ' * Searching parent frames for: ' + six . text_type ( varname ) )
frame_no = 0
while curr_frame . f_back is not None :
if varname in curr_frame . f_locals . keys ( ) :
if verbose :
print ( ' * Found local in frame: ' + six . text_... |
def enable ( self , license_key , license_token , sandbox_type = 'cloud_sandbox' , service = 'Automatic' , http_proxy = None , sandbox_data_center = 'Automatic' ) :
"""Enable sandbox on this engine . Provide a valid license key
and license token obtained from your engine licensing .
Requires SMC version > = 6.3... | service = element_resolver ( SandboxService ( service ) , do_raise = False ) or element_resolver ( SandboxService . create ( name = service , sandbox_data_center = SandboxDataCenter ( sandbox_data_center ) ) )
self . update ( sandbox_license_key = license_key , sandbox_license_token = license_token , sandbox_service = ... |
def can_overlap ( self , contig , strand = None ) :
"""Is this locus on the same contig and ( optionally ) on the same strand ?""" | return ( self . on_contig ( contig ) and ( strand is None or self . on_strand ( strand ) ) ) |
def insert ( self , key ) :
"""Insert new key into node""" | # Create new node
n = TreeNode ( key )
if not self . node :
self . node = n
self . node . left = AvlTree ( )
self . node . right = AvlTree ( )
elif key < self . node . val :
self . node . left . insert ( key )
elif key > self . node . val :
self . node . right . insert ( key )
self . re_balance ( ) |
def hyphenation ( phrase , format = 'json' ) :
"""Returns back the stress points in the " phrase " passed
: param phrase : word for which hyphenation is to be found
: param format : response structure type . Defaults to : " json "
: returns : returns a json object as str , False if invalid phrase""" | base_url = Vocabulary . __get_api_link ( "wordnik" )
url = base_url . format ( word = phrase . lower ( ) , action = "hyphenation" )
json_obj = Vocabulary . __return_json ( url )
if json_obj : # return json . dumps ( json _ obj )
# return json _ obj
return Response ( ) . respond ( json_obj , format )
else :
retu... |
def _get_qvm_qc ( name : str , qvm_type : str , device : AbstractDevice , noise_model : NoiseModel = None , requires_executable : bool = False , connection : ForestConnection = None ) -> QuantumComputer :
"""Construct a QuantumComputer backed by a QVM .
This is a minimal wrapper over the QuantumComputer , QVM , a... | if connection is None :
connection = ForestConnection ( )
return QuantumComputer ( name = name , qam = _get_qvm_or_pyqvm ( qvm_type = qvm_type , connection = connection , noise_model = noise_model , device = device , requires_executable = requires_executable ) , device = device , compiler = QVMCompiler ( device = d... |
def loadSignalFromWav ( inputSignalFile , calibrationRealWorldValue = None , calibrationSignalFile = None , start = None , end = None ) -> Signal :
"""reads a wav file into a Signal and scales the input so that the sample are expressed in real world values
( as defined by the calibration signal ) .
: param inpu... | inputSignal = readWav ( inputSignalFile , start = start , end = end )
if calibrationSignalFile is not None :
calibrationSignal = readWav ( calibrationSignalFile )
scalingFactor = calibrationRealWorldValue / np . max ( calibrationSignal . samples )
return Signal ( inputSignal . samples * scalingFactor , inpu... |
def get_minimal_syspath ( self , absolute_paths = True ) :
"""Provide a list of directories that , when added to sys . path , would enable
any of the discovered python modules to be found""" | # firstly , gather a list of the minimum path to each package
package_list = set ( )
packages = [ p [ 0 ] for p in self . _packages if not p [ 1 ] ]
for package in sorted ( packages , key = len ) :
parent = os . path . split ( package ) [ 0 ]
if parent not in packages and parent not in package_list :
pa... |
def _PrintCheckDependencyStatus ( self , dependency , result , status_message , verbose_output = True ) :
"""Prints the check dependency status .
Args :
dependency ( DependencyDefinition ) : dependency definition .
result ( bool ) : True if the Python module is available and conforms to
the minimum required... | if not result or dependency . is_optional :
if dependency . is_optional :
status_indicator = '[OPTIONAL]'
else :
status_indicator = '[FAILURE]'
print ( '{0:s}\t{1:s}' . format ( status_indicator , status_message ) )
elif verbose_output :
print ( '[OK]\t\t{0:s}' . format ( status_message ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.