signature stringlengths 29 44.1k | implementation stringlengths 0 85.2k |
|---|---|
def attach ( self , remote_entry ) :
"""Attach a remote entry to a local entry""" | self . name = remote_entry . name
self . sha = remote_entry . sha
self . url = remote_entry . url
self . author = remote_entry . author
return self |
def icon_resource ( name , package = None ) :
"""Returns the absolute URI path to an image . If a package is not explicitly specified then the calling package name is
used .
: param name : path relative to package path of the image resource .
: param package : package name in dotted format .
: return : the ... | if not package :
package = '%s.resources.images' % calling_package ( )
name = resource_filename ( package , name )
if not name . startswith ( '/' ) :
return 'file://%s' % abspath ( name )
return 'file://%s' % name |
def _members_changed ( sender , instance , action , reverse , model , pk_set , ** kwargs ) :
"""Hook that executes whenever the group members are changed .""" | if action == "post_remove" :
if not reverse :
group = instance
for person in model . objects . filter ( pk__in = pk_set ) :
_remove_group ( group , person )
else :
person = instance
for group in model . objects . filter ( pk__in = pk_set ) :
_remove_group ... |
def _get_file_md5 ( filename ) :
"""Compute the md5 checksum of a file""" | md5_data = md5 ( )
with open ( filename , 'rb' ) as f :
for chunk in iter ( lambda : f . read ( 128 * md5_data . block_size ) , b'' ) :
md5_data . update ( chunk )
return md5_data . hexdigest ( ) |
def rescale ( self , fun ) :
"""perform raster computations with custom functions and assign them to the existing raster object in memory
Parameters
fun : function
the custom function to compute on the data
Examples
> > > with Raster ( ' filename ' ) as ras :
> > > ras . rescale ( lambda x : 10 * x )""" | if self . bands != 1 :
raise ValueError ( 'only single band images are currently supported' )
# load array
mat = self . matrix ( )
# scale values
scaled = fun ( mat )
# assign newly computed array to raster object
self . assign ( scaled , band = 0 ) |
def datasets ( data = 'all' , type = None , uuid = None , query = None , id = None , limit = 100 , offset = None , ** kwargs ) :
'''Search for datasets and dataset metadata .
: param data : [ str ] The type of data to get . Default : ` ` all ` `
: param type : [ str ] Type of dataset , options include ` ` OCCUR... | args = { 'q' : query , 'type' : type , 'limit' : limit , 'offset' : offset }
data_choices = [ 'all' , 'organization' , 'contact' , 'endpoint' , 'identifier' , 'tag' , 'machinetag' , 'comment' , 'constituents' , 'document' , 'metadata' , 'deleted' , 'duplicate' , 'subDataset' , 'withNoEndpoint' ]
check_data ( data , dat... |
def on_uninstall ( self ) :
"""Uninstalls the editor extension from the editor .""" | self . _on_close = True
self . enabled = False
self . _editor = None |
def stackexchange_request ( self , path , callback , access_token = None , post_args = None , ** kwargs ) :
"""Make a request to the StackExchange API , passing in the path , a
callback , the access token , optional post arguments and keyword
arguments to be added as values in the request body or URI""" | url = self . _API_URL + path
all_args = { }
if access_token :
all_args [ "access_token" ] = access_token
all_args . update ( kwargs )
if all_args :
url += "?" + auth . urllib_parse . urlencode ( all_args )
callback = self . async_callback ( self . _on_stackexchange_request , callback )
http = self . _get_au... |
def create_textfile_with_contents ( filename , contents , encoding = 'utf-8' ) :
"""Creates a textual file with the provided contents in the workdir .
Overwrites an existing file .""" | ensure_directory_exists ( os . path . dirname ( filename ) )
if os . path . exists ( filename ) :
os . remove ( filename )
outstream = codecs . open ( filename , "w" , encoding )
outstream . write ( contents )
if contents and not contents . endswith ( "\n" ) :
outstream . write ( "\n" )
outstream . flush ( )
ou... |
def set_backgroundcolor ( self , color ) :
'''Sets the background color of the current axes ( and legend ) .
Use ' None ' ( with quotes ) for transparent . To get transparent
background on saved figures , use :
pp . savefig ( " fig1 . svg " , transparent = True )''' | ax = self . ax
ax . patch . set_facecolor ( color )
lh = ax . get_legend ( )
if lh != None :
lh . legendPatch . set_facecolor ( color )
plt . draw ( ) |
def convex_comb_agg_log ( model , a , b ) :
"""convex _ comb _ agg _ log - - add piecewise relation with a logarithmic number of binary variables
using the convex combination formulation - - non - disaggregated .
Parameters :
- model : a model where to include the piecewise linear relation
- a [ k ] : x - c... | K = len ( a ) - 1
G = int ( math . ceil ( ( math . log ( K ) / math . log ( 2 ) ) ) )
# number of required bits
w , g = { } , { }
for k in range ( K + 1 ) :
w [ k ] = model . addVar ( lb = 0 , ub = 1 , vtype = "C" )
for j in range ( G ) :
g [ j ] = model . addVar ( vtype = "B" )
X = model . addVar ( lb = a [ 0 ... |
def partition ( cls , iterable , pred ) :
"""Use a predicate to partition items into false and true entries .""" | t1 , t2 = itertools . tee ( iterable )
return cls ( itertools . filterfalse ( pred , t1 ) , filter ( pred , t2 ) ) |
async def process_update ( self , update : types . Update ) :
"""Process single update object
: param update :
: return :""" | types . Update . set_current ( update )
try :
if update . message :
types . User . set_current ( update . message . from_user )
types . Chat . set_current ( update . message . chat )
return await self . message_handlers . notify ( update . message )
if update . edited_message :
t... |
def fix_lib64 ( lib_dir , symlink = True ) :
"""Some platforms ( particularly Gentoo on x64 ) put things in lib64 / pythonX . Y
instead of lib / pythonX . Y . If this is such a platform we ' ll just create a
symlink so lib64 points to lib""" | # PyPy ' s library path scheme is not affected by this .
# Return early or we will die on the following assert .
if is_pypy :
logger . debug ( 'PyPy detected, skipping lib64 symlinking' )
return
# Check we have a lib64 library path
if not [ p for p in distutils . sysconfig . get_config_vars ( ) . values ( ) if ... |
def lookup_field_help ( self , field , default = None ) :
"""Looks up the help text for the passed in field .
This is overloaded so that we can check whether our form has help text set
explicitely . If so , we will pass this as the default to our parent function .""" | default = None
for form_field in self . form :
if form_field . name == field :
default = form_field . help_text
break
return super ( SmartFormMixin , self ) . lookup_field_help ( field , default = default ) |
def clear_license ( self ) :
"""Removes the license .
raise : NoAccess - ` ` Metadata . isRequired ( ) ` ` is ` ` true ` ` or
` ` Metadata . isReadOnly ( ) ` ` is ` ` true ` `
* compliance : mandatory - - This method must be implemented . *""" | if ( self . get_license_metadata ( ) . is_read_only ( ) or self . get_license_metadata ( ) . is_required ( ) ) :
raise errors . NoAccess ( )
self . _my_map [ 'license' ] = dict ( self . _license_default ) |
def _read_centroid_from_ndk_string ( self , ndk_string , hypocentre ) :
"""Reads the centroid data from the ndk string to return an
instance of the GCMTCentroid class
: param str ndk _ string :
String of data ( line 3 of ndk format )
: param hypocentre :
Instance of the GCMTHypocentre class""" | centroid = GCMTCentroid ( hypocentre . date , hypocentre . time )
data = ndk_string [ : 58 ] . split ( )
centroid . centroid_type = data [ 0 ] . rstrip ( ':' )
data = [ float ( x ) for x in data [ 1 : ] ]
time_diff = data [ 0 ]
if fabs ( time_diff ) > 1E-6 :
centroid . _get_centroid_time ( time_diff )
centroid . ti... |
def handler ( event , context ) : # pylint : disable = W0613
"""Historical S3 event differ .
Listens to the Historical current table and determines if there are differences that need to be persisted in the
historical record .""" | # De - serialize the records :
records = deserialize_records ( event [ 'Records' ] )
for record in records :
process_dynamodb_differ_record ( record , CurrentS3Model , DurableS3Model ) |
def fromfd ( fd , family , type , proto = 0 ) :
"""fromfd ( fd , family , type [ , proto ] ) - > socket object
Create a socket object from a duplicate of the given file
descriptor . The remaining arguments are the same as for socket ( ) .""" | nfd = dup ( fd )
return socket ( family , type , proto , nfd ) |
def commit ( self , message , author = None ) :
"""Commit changes to tracked files in the working tree .
: param message : The commit message ( a string ) .
: param author : Override : attr : ` author ` ( refer to
: func : ` coerce _ author ( ) ` for details
on argument handling ) .""" | # Make sure the local repository exists and supports a working tree .
self . ensure_exists ( )
self . ensure_working_tree ( )
logger . info ( "Committing changes in %s: %s" , format_path ( self . local ) , message )
author = coerce_author ( author ) if author else self . author
self . context . execute ( * self . get_c... |
def _check_valid_data ( self , data ) :
"""Checks that the incoming data is a 3 x # elements ndarray of normal
vectors .
Parameters
data : : obj : ` numpy . ndarray `
The data to verify .
Raises
ValueError
If the data is not of the correct shape or type , or if the vectors
therein are not normalized... | if data . dtype . type != np . float32 and data . dtype . type != np . float64 :
raise ValueError ( 'Must initialize normals clouds with a numpy float ndarray' )
if data . shape [ 0 ] != 3 :
raise ValueError ( 'Illegal data array passed to normal cloud. Must have 3 coordinates' )
if len ( data . shape ) > 2 :
... |
def _object_contents ( obj ) :
"""Return the signature contents of any Python object .
We have to handle the case where object contains a code object
since it can be pickled directly .""" | try : # Test if obj is a method .
return _function_contents ( obj . __func__ )
except AttributeError :
try : # Test if obj is a callable object .
return _function_contents ( obj . __call__ . __func__ )
except AttributeError :
try : # Test if obj is a code object .
return _code_co... |
def identity_gate ( qubits : Union [ int , Qubits ] ) -> Gate :
"""Returns the K - qubit identity gate""" | _ , qubits = qubits_count_tuple ( qubits )
return I ( * qubits ) |
def updateSiteName ( self , block_name , origin_site_name ) :
"""Update the origin _ site _ name for a given block name""" | if not origin_site_name :
dbsExceptionHandler ( 'dbsException-invalid-input' , "DBSBlock/updateSiteName. origin_site_name is mandatory." )
conn = self . dbi . connection ( )
trans = conn . begin ( )
try :
self . updatesitename . execute ( conn , block_name , origin_site_name )
except :
if trans :
tr... |
def _addToPoolingActivation ( self , activeCells , overlaps ) :
"""Adds overlaps from specified active cells to cells ' pooling
activation .
@ param activeCells : Indices of those cells winning the inhibition step
@ param overlaps : A current set of overlap values for each cell
@ return current pooling acti... | self . _poolingActivation [ activeCells ] = self . _exciteFunction . excite ( self . _poolingActivation [ activeCells ] , overlaps [ activeCells ] )
# increase pooling timers for all cells
self . _poolingTimer [ self . _poolingTimer >= 0 ] += 1
# reset pooling timer for active cells
self . _poolingTimer [ activeCells ]... |
def _parse_the_ned_list_results ( self ) :
"""* parse the ned results *
* * Key Arguments : * *
* * Return : * *
- None
. . todo : :
- @ review : when complete , clean _ parse _ the _ ned _ results method
- @ review : when complete add logging""" | self . log . info ( 'starting the ``_parse_the_ned_list_results`` method' )
results = [ ]
# CHOOSE VALUES TO RETURN
allHeaders = [ "searchIndex" , "searchRa" , "searchDec" , "row_number" , "input_note" , "input_name" , "ned_notes" , "ned_name" , "ra" , "dec" , "eb-v" , "object_type" , "redshift" , "redshift_err" , "red... |
def elbv2_load_balancer_hosted_zone ( self , lookup , default = None ) :
"""Args :
lookup : the friendly name of the V2 elb to look up
default : value to return in case of no match
Returns :
The hosted zone ID of the ELB found with a name matching ' lookup ' .""" | try :
elb = self . _elbv2_load_balancer ( lookup )
return elb [ 'CanonicalHostedZoneId' ]
except ClientError :
return default |
async def append ( self , reply : Reply ) -> None :
"""Add the given Reply to this transaction store ' s list of responses .
Also add to processedRequests if not added previously .""" | result = reply . result
identifier = result . get ( f . IDENTIFIER . nm )
txnId = result . get ( TXN_ID )
logger . debug ( "Reply being sent {}" . format ( reply ) )
if self . _isNewTxn ( identifier , reply , txnId ) :
self . addToProcessedTxns ( identifier , txnId , reply )
if identifier not in self . responses :
... |
def get_cash_balance ( self ) :
"""Returns the account cash balance available for investing
Returns
float
The cash balance in your account .""" | cash = False
try :
response = self . session . get ( '/browse/cashBalanceAj.action' )
json_response = response . json ( )
if self . session . json_success ( json_response ) :
self . __log ( 'Cash available: {0}' . format ( json_response [ 'cashBalance' ] ) )
cash_value = json_response [ 'cas... |
def main ( self ) :
"""This is the main entry point of the ElastiCluster CLI .
First the central configuration is created , which can be altered
through the command line interface . Then the given command from
the command line interface is called .""" | assert self . params . func , "No subcommand defined in `ElastiCluster.main()"
try :
return self . params . func ( )
except Exception as err :
log . error ( "Error: %s" , err )
if self . params . verbose > 2 :
import traceback
traceback . print_exc ( )
print ( "Aborting because of errors... |
def tmpdir ( prefix = 'npythy_tempdir_' , delete = True ) :
'''tmpdir ( ) creates a temporary directory and yields its path . At python exit , the directory and
all of its contents are recursively deleted ( so long as the the normal python exit process is
allowed to call the atexit handlers ) .
tmpdir ( prefi... | path = tempfile . mkdtemp ( prefix = prefix )
if not os . path . isdir ( path ) :
raise ValueError ( 'Could not find or create temp directory' )
if delete :
atexit . register ( shutil . rmtree , path )
return path |
def fit_arrays ( uv , xy ) :
"""Performs a generalized fit between matched lists of positions
given by the 2 column arrays xy and uv .
This function fits for translation , rotation , and scale changes
between ' xy ' and ' uv ' , allowing for different scales and
orientations for X and Y axes .
DEVELOPMENT... | if not isinstance ( xy , np . ndarray ) : # cast input list as numpy ndarray for fitting
xy = np . array ( xy )
if not isinstance ( uv , np . ndarray ) : # cast input list as numpy ndarray for fitting
uv = np . array ( uv )
# Set up products used for computing the fit
Sx = xy [ : , 0 ] . sum ( )
Sy = xy [ : , 1... |
def init_signals ( self ) :
"""Connect signals""" | self . widget . activated . connect ( self . on_item_activated )
self . widget . clicked . connect ( self . on_item_clicked )
self . widget . doubleClicked . connect ( self . on_item_double_clicked )
self . widget . entered . connect ( self . on_item_entered )
self . widget . pressed . connect ( self . on_item_pressed ... |
def norm_nuclear ( X ) :
r"""Compute the nuclear norm
. . math : :
\ | X \ | _ * = \ sum _ i \ sigma _ i
where : math : ` \ sigma _ i ` are the singular values of matrix : math : ` X ` .
Parameters
X : array _ like
Input array : math : ` X `
Returns
nncl : float
Nuclear norm of ` X `""" | return np . sum ( np . linalg . svd ( sl . promote16 ( X ) , compute_uv = False ) ) |
def previous ( self ) :
"""Return a copy of this object as was at its previous state in
history .
Returns None if this object is new ( and therefore has no history ) .
The returned object is always " disconnected " , i . e . does not receive
live updates .""" | return self . model . state . get_entity ( self . entity_type , self . entity_id , self . _history_index - 1 , connected = False ) |
def create_page_blob_service ( self ) :
'''Creates a PageBlobService object with the settings specified in the
CloudStorageAccount .
: return : A service object .
: rtype : : class : ` ~ azure . storage . blob . pageblobservice . PageBlobService `''' | try :
from azure . storage . blob . pageblobservice import PageBlobService
return PageBlobService ( self . account_name , self . account_key , sas_token = self . sas_token , is_emulated = self . is_emulated )
except ImportError :
raise Exception ( 'The package azure-storage-blob is required. ' + 'Please ins... |
def values ( self ) :
"""list of _ ColumnPairwiseSignificance tests .
Result has as many elements as there are coliumns in the slice . Each
significance test contains ` p _ vals ` and ` t _ stats ` significance tests .""" | # TODO : Figure out how to intersperse pairwise objects for columns
# that represent H & S
return [ _ColumnPairwiseSignificance ( self . _slice , col_idx , self . _axis , self . _weighted , self . _alpha , self . _only_larger , self . _hs_dims , ) for col_idx in range ( self . _slice . get_shape ( hs_dims = self . _hs_... |
def _construct_email ( self , email , ** extra ) :
"""Converts incoming data to properly structured dictionary .""" | if isinstance ( email , dict ) :
email = Email ( manager = self . _manager , ** email )
elif isinstance ( email , ( MIMEText , MIMEMultipart ) ) :
email = Email . from_mime ( email , self . _manager )
elif not isinstance ( email , Email ) :
raise ValueError
email . _update ( extra )
return email . as_dict (... |
def p_function_declaration_statement ( p ) :
'function _ declaration _ statement : FUNCTION is _ reference STRING LPAREN parameter _ list RPAREN LBRACE inner _ statement _ list RBRACE' | p [ 0 ] = ast . Function ( p [ 3 ] , p [ 5 ] , p [ 8 ] , p [ 2 ] , lineno = p . lineno ( 1 ) ) |
def plot_phase_plane ( self , indices = None , ** kwargs ) :
"""Plots a phase portrait from last integration .
This method will be deprecated . Please use : meth : ` Result . plot _ phase _ plane ` .
See : func : ` pyodesys . plotting . plot _ phase _ plane `""" | return self . _plot ( plot_phase_plane , indices = indices , ** kwargs ) |
def GetString ( self ) :
"""Retrieves a string representation of the report .
Returns :
str : string representation of the report .""" | string_list = [ ]
string_list . append ( 'Report generated from: {0:s}' . format ( self . plugin_name ) )
time_compiled = getattr ( self , 'time_compiled' , 0 )
if time_compiled :
time_compiled = timelib . Timestamp . CopyToIsoFormat ( time_compiled )
string_list . append ( 'Generated on: {0:s}' . format ( time... |
def crossplat_loop_run ( coro ) -> Any :
"""Cross - platform method for running a subprocess - spawning coroutine .""" | if sys . platform == 'win32' :
signal . signal ( signal . SIGINT , signal . SIG_DFL )
loop = asyncio . ProactorEventLoop ( )
else :
loop = asyncio . new_event_loop ( )
asyncio . set_event_loop ( loop )
with contextlib . closing ( loop ) :
return loop . run_until_complete ( coro ) |
def evict ( self , key ) :
"""Evicts the specified key from this map .
* * Warning : This method uses _ _ hash _ _ and _ _ eq _ _ methods of binary form of the key , not the actual implementations
of _ _ hash _ _ and _ _ eq _ _ defined in key ' s class . * *
: param key : ( object ) , key to evict .
: retur... | check_not_none ( key , "key can't be None" )
key_data = self . _to_data ( key )
return self . _evict_internal ( key_data ) |
def is_2d_regular_grid ( nc , variable ) :
'''Returns True if the variable is a 2D Regular grid .
: param netCDF4 . Dataset nc : An open netCDF dataset
: param str variable : name of the variable to check''' | # x ( x ) , y ( y ) , t ( t )
# X ( t , y , x )
dims = nc . variables [ variable ] . dimensions
cmatrix = coordinate_dimension_matrix ( nc )
for req in ( 'x' , 'y' , 't' ) :
if req not in cmatrix :
return False
x = get_lon_variable ( nc )
y = get_lat_variable ( nc )
t = get_time_variable ( nc )
if cmatrix [... |
def addConstraint ( self , login , tableName , constraintClassName ) :
"""Parameters :
- login
- tableName
- constraintClassName""" | self . send_addConstraint ( login , tableName , constraintClassName )
return self . recv_addConstraint ( ) |
def remove_child_bank ( self , bank_id , child_id ) :
"""Removes a child from a bank .
arg : bank _ id ( osid . id . Id ) : the ` ` Id ` ` of a bank
arg : child _ id ( osid . id . Id ) : the ` ` Id ` ` of the new child
raise : NotFound - ` ` bank _ id ` ` not parent of ` ` child _ id ` `
raise : NullArgumen... | # Implemented from template for
# osid . resource . BinHierarchyDesignSession . remove _ child _ bin _ template
if self . _catalog_session is not None :
return self . _catalog_session . remove_child_catalog ( catalog_id = bank_id , child_id = child_id )
return self . _hierarchy_session . remove_child ( id_ = bank_i... |
def _GetStatus ( self ) :
"""Retrieves status information .
Returns :
dict [ str , object ] : status attributes , indexed by name .""" | if self . _analysis_mediator :
number_of_produced_event_tags = ( self . _analysis_mediator . number_of_produced_event_tags )
number_of_produced_reports = ( self . _analysis_mediator . number_of_produced_analysis_reports )
else :
number_of_produced_event_tags = None
number_of_produced_reports = None
if s... |
def all_instruments ( type = None , date = None ) :
"""获取某个国家市场的所有合约信息 。 使用者可以通过这一方法很快地对合约信息有一个快速了解 , 目前仅支持中国市场 。
: param str type : 需要查询合约类型 , 例如 : type = ' CS ' 代表股票 。 默认是所有类型
: param date : 查询时间点
: type date : ` str ` | ` datetime ` | ` date `
: return : ` pandas DataFrame ` 所有合约的基本信息 。
其中type参数传入的合约类型... | env = Environment . get_instance ( )
if date is None :
dt = env . trading_dt
else :
dt = pd . Timestamp ( date ) . to_pydatetime ( )
dt = min ( dt , env . trading_dt )
if type is not None :
if isinstance ( type , six . string_types ) :
type = [ type ]
types = set ( )
for t in type :
... |
def custom_repository ( self ) :
"""Return dictionary with repo name and url ( used external )""" | custom_dict_repo = { }
for line in self . custom_repositories_list . splitlines ( ) :
line = line . lstrip ( )
if not line . startswith ( "#" ) :
custom_dict_repo [ line . split ( ) [ 0 ] ] = line . split ( ) [ 1 ]
return custom_dict_repo |
def contains_interval ( self , other ) :
"""Whether other is contained in this Interval .
: param other : Interval
: return : True or False
: rtype : bool""" | return ( self . begin <= other . begin and self . end >= other . end ) |
def create ( ** data ) :
"""Create a Payment request .
: param data : data required to create the payment
: return : The payment resource
: rtype resources . Payment""" | http_client = HttpClient ( )
response , _ = http_client . post ( routes . url ( routes . PAYMENT_RESOURCE ) , data )
return resources . Payment ( ** response ) |
def calc_lfp_layer ( self ) :
"""Calculate the LFP from concatenated subpopulations residing in a
certain layer , e . g all L4E pops are summed , according to the ` mapping _ Yy `
attribute of the ` hybridLFPy . Population ` objects .""" | LFPdict = { }
lastY = None
for Y , y in self . mapping_Yy :
if lastY != Y :
try :
LFPdict . update ( { Y : self . LFPdict [ y ] } )
except KeyError :
pass
else :
try :
LFPdict [ Y ] += self . LFPdict [ y ]
except KeyError :
pass
... |
def file_sha1 ( path ) :
"""Compute SHA1 hash of a file .""" | sha1 = hashlib . sha1 ( )
with open ( path , "rb" ) as f :
while True :
block = f . read ( 2 ** 10 )
if not block :
break
sha1 . update ( block )
return sha1 . hexdigest ( ) |
def _joint_likelihood ( self , logits : torch . Tensor , tags : torch . Tensor , mask : torch . LongTensor ) -> torch . Tensor :
"""Computes the numerator term for the log - likelihood , which is just score ( inputs , tags )""" | batch_size , sequence_length , _ = logits . data . shape
# Transpose batch size and sequence dimensions :
logits = logits . transpose ( 0 , 1 ) . contiguous ( )
mask = mask . float ( ) . transpose ( 0 , 1 ) . contiguous ( )
tags = tags . transpose ( 0 , 1 ) . contiguous ( )
# Start with the transition scores from start... |
def sample_wr ( lst ) :
"""Sample from lst , with replacement""" | arr = np . array ( lst )
indices = np . random . randint ( len ( lst ) , size = len ( lst ) )
sample = np . empty ( arr . shape , dtype = arr . dtype )
for i , ix in enumerate ( indices ) :
sample [ i ] = arr [ ix ]
return list ( sample ) |
def parse_ini_file ( self , path ) :
"""Parse ini file at ` ` path ` ` and return dict .""" | cfgobj = ConfigObj ( path , list_values = False )
def extract_section ( namespace , d ) :
cfg = { }
for key , val in d . items ( ) :
if isinstance ( d [ key ] , dict ) :
cfg . update ( extract_section ( namespace + [ key ] , d [ key ] ) )
else :
cfg [ '_' . join ( namespa... |
async def tcp_echo_client ( message , loop , host , port ) :
"""Generic python tcp echo client""" | print ( "Connecting to server at %s:%d" % ( host , port ) )
reader , writer = await asyncio . open_connection ( host , port , loop = loop )
writer . write ( message . encode ( ) )
print ( 'Sent: %r' % message )
data = await reader . read ( 100 )
print ( 'Received: %r' % data . decode ( ) )
writer . close ( ) |
def split_obj ( obj , prefix = None ) :
'''Split the object , returning a 3 - tuple with the flat object , optionally
followed by the key for the subobjects and a list of those subobjects .''' | # copy the object , optionally add the prefix before each key
new = obj . copy ( ) if prefix is None else { '{}_{}' . format ( prefix , k ) : v for k , v in obj . items ( ) }
# try to find the key holding the subobject or a list of subobjects
for k , v in new . items ( ) : # list of subobjects
if isinstance ( v , l... |
def extractVersion ( string , default = '?' ) :
"""Extracts a three digit standard format version number""" | return extract ( VERSION_PATTERN , string , condense = True , default = default , one = True ) |
def _update_asset_content_filename_on_disk_to_match_id ( self , ac ) :
"""Because we want the asset content filename to match the ac . ident ,
here we manipulate the saved file on disk after creating the
asset content""" | def has_secondary_storage ( ) :
return 'secondary_data_store_path' in self . _config_map
datastore_path = ''
secondary_data_store_path = ''
if 'data_store_full_path' in self . _config_map :
datastore_path = self . _config_map [ 'data_store_full_path' ]
if has_secondary_storage ( ) :
secondary_data_store_pat... |
def print_table ( column_names : IterableOfStrings , rows : IterableOfTuples , column_alignments : Optional [ IterableOfStrings ] = None , primary_column_idx : int = 0 , ) -> None :
"""Prints a table of information to the console . Automatically determines if the
console is wide enough , and if not , displays the... | header_template = ''
row_template = ''
table_width = 0
type_formatters = { int : 'd' , float : 'f' , str : 's' }
types = [ type_formatters . get ( type ( x ) , 'r' ) for x in rows [ 0 ] ]
alignments = { int : '>' , float : '>' }
column_alignments = ( column_alignments or [ alignments . get ( type ( x ) , '<' ) for x in... |
def register ( self , new_outputs , * args , ** kwargs ) :
"""Register outputs and metadata .
* ` ` initial _ value ` ` - used in dynamic calculations
* ` ` size ` ` - number of elements per timestep
* ` ` uncertainty ` ` - in percent of nominal value
* ` ` variance ` ` - dictionary of covariances , diagona... | kwargs . update ( zip ( self . meta_names , args ) )
# call super method
super ( OutputRegistry , self ) . register ( new_outputs , ** kwargs ) |
def update ( self , ipv6s ) :
"""Method to update ipv6 ' s
: param ipv6s : List containing ipv6 ' s desired to updated
: return : None""" | data = { 'ips' : ipv6s }
ipv6s_ids = [ str ( ipv6 . get ( 'id' ) ) for ipv6 in ipv6s ]
return super ( ApiIPv6 , self ) . put ( 'api/v3/ipv6/%s/' % ';' . join ( ipv6s_ids ) , data ) |
def schema ( ) :
"""All tables , columns , steps , injectables and broadcasts registered with
Orca . Includes local columns on tables .""" | tables = orca . list_tables ( )
cols = { t : orca . get_table ( t ) . columns for t in tables }
steps = orca . list_steps ( )
injectables = orca . list_injectables ( )
broadcasts = orca . list_broadcasts ( )
return jsonify ( tables = tables , columns = cols , steps = steps , injectables = injectables , broadcasts = bro... |
def get ( self , remote , local = None , preserve_mode = True ) :
"""Download a file from the current connection to the local filesystem .
: param str remote :
Remote file to download .
May be absolute , or relative to the remote working directory .
. . note : :
Most SFTP servers set the remote working di... | # TODO : how does this API change if we want to implement
# remote - to - remote file transfer ? ( Is that even realistic ? )
# TODO : handle v1 ' s string interpolation bits , especially the default
# one , or at least think about how that would work re : split between
# single and multiple server targets .
# TODO : c... |
def save_process ( MAVExpLastGraph , child_pipe_console_input , child_pipe_graph_input , statusMsgs ) :
'''process for saving a graph''' | from MAVProxy . modules . lib import wx_processguard
from MAVProxy . modules . lib . wx_loader import wx
from MAVProxy . modules . lib . wxgrapheditor import GraphDialog
# This pipe is used to send text to the console
global pipe_console_input
pipe_console_input = child_pipe_console_input
# This pipe is used to send gr... |
def prepare_create_transaction ( * , signers , recipients = None , asset = None , metadata = None ) :
"""Prepares a ` ` " CREATE " ` ` transaction payload , ready to be
fulfilled .
Args :
signers ( : obj : ` list ` | : obj : ` tuple ` | : obj : ` str ` ) : One
or more public keys representing the issuer ( s... | if not isinstance ( signers , ( list , tuple ) ) :
signers = [ signers ]
# NOTE : Needed for the time being . See
# https : / / github . com / bigchaindb / bigchaindb / issues / 797
elif isinstance ( signers , tuple ) :
signers = list ( signers )
if not recipients :
recipients = [ ( signers , 1 ) ]
elif not... |
def modify_storage ( self , storage , size , title , backup_rule = { } ) :
"""Modify a Storage object . Returns an object based on the API ' s response .""" | res = self . _modify_storage ( str ( storage ) , size , title , backup_rule )
return Storage ( cloud_manager = self , ** res [ 'storage' ] ) |
def create_deep_linking_urls ( self , url_params ) :
"""Bulk Creates Deep Linking URLs
See the URL https : / / dev . branch . io / references / http _ api / # bulk - creating - deep - linking - urls
: param url _ params : Array of values returned from " create _ deep _ link _ url ( . . . , skip _ api _ call = T... | url = "/v1/url/bulk/%s" % self . branch_key
method = "POST"
# Checks params
self . _check_param ( value = url_params , type = list , sub_type = dict , optional = False )
return self . make_api_call ( method , url , json_params = url_params ) |
def write_to_logfile ( out , err , logfile , samplelog = None , sampleerr = None , analysislog = None , analysiserr = None ) :
"""Writes out and err ( both should be strings ) to logfile .""" | # Run log
with open ( logfile + '_out.txt' , 'a+' ) as outfile :
outfile . write ( out + '\n' )
with open ( logfile + '_err.txt' , 'a+' ) as outfile :
outfile . write ( err + '\n' )
# Sample log
if samplelog :
with open ( samplelog , 'a+' ) as outfile :
outfile . write ( out + '\n' )
with open (... |
def chaincode_query ( self , chaincode_name , type = CHAINCODE_LANG_GO , function = "query" , args = [ "a" ] , id = 1 , secure_context = None , confidentiality_level = CHAINCODE_CONFIDENTIAL_PUB , metadata = None ) :
"""" jsonrpc " : " 2.0 " ,
" method " : " query " ,
" params " : {
" type " : 1,
" chaincod... | return self . _exec_action ( method = "query" , type = type , chaincodeID = { "name" : chaincode_name } , function = function , args = args , id = id , secure_context = secure_context , confidentiality_level = confidentiality_level , metadata = metadata ) |
def check_in_lambda ( ) :
"""Return None if SDK is not loaded in AWS Lambda worker .
Otherwise drop a touch file and return a lambda context .""" | if not os . getenv ( LAMBDA_TASK_ROOT_KEY ) :
return None
try :
os . mkdir ( TOUCH_FILE_DIR )
except OSError :
log . debug ( 'directory %s already exists' , TOUCH_FILE_DIR )
try :
f = open ( TOUCH_FILE_PATH , 'w+' )
f . close ( )
# utime force second parameter in python2.7
os . utime ( TOUCH... |
def reduced_chi_squareds ( self , p = None ) :
"""Returns the reduced chi squared for each massaged data set .
p = None means use the fit results .""" | if len ( self . _set_xdata ) == 0 or len ( self . _set_ydata ) == 0 :
return None
if p is None :
p = self . results [ 0 ]
r = self . studentized_residuals ( p )
# In case it ' s not possible to calculate
if r is None :
return
# calculate the number of points
N = 0
for i in range ( len ( r ) ) :
N += len... |
def sql_select ( self , fields , * args , ** kwargs ) :
"""Execute a simple SQL ` ` SELECT ` ` statement and returns values as new numpy rec array .
The arguments * fields * and the additional optional arguments
are simply concatenated with additional SQL statements
according to the template : :
SELECT < fi... | SQL = "SELECT " + str ( fields ) + " FROM __self__ " + " " . join ( args )
return self . sql ( SQL , ** kwargs ) |
def getEdges ( self , fromVol ) :
"""Return the edges available from fromVol .""" | return [ self . toDict . diff ( d ) for d in self . butterStore . getEdges ( self . toObj . vol ( fromVol ) ) ] |
def build_columns ( self , X , verbose = False ) :
"""construct the model matrix columns for the term
Parameters
X : array - like
Input dataset with n rows
verbose : bool
whether to show warnings
Returns
scipy sparse array with n rows""" | X [ : , self . feature ] [ : , np . newaxis ]
splines = b_spline_basis ( X [ : , self . feature ] , edge_knots = self . edge_knots_ , spline_order = self . spline_order , n_splines = self . n_splines , sparse = True , periodic = self . basis in [ 'cp' ] , verbose = verbose )
if self . by is not None :
splines = spl... |
def convert_requirement ( req ) :
"""Converts a pkg _ resources . Requirement object into a list of Rez package
request strings .""" | pkg_name = convert_name ( req . project_name )
if not req . specs :
return [ pkg_name ]
req_strs = [ ]
for spec in req . specs :
op , ver = spec
ver = convert_version ( ver )
if op == "<" :
r = "%s-0+<%s" % ( pkg_name , ver )
req_strs . append ( r )
elif op == "<=" :
r = "%s-... |
def service_list ( ) :
'''List " services " on the REST server''' | r = salt . utils . http . query ( DETAILS [ 'url' ] + 'service/list' , decode_type = 'json' , decode = True )
return r [ 'dict' ] |
def chmod ( self , mode ) :
"""Set the mode . May be the new mode ( os . chmod behavior ) or a ` symbolic
mode < http : / / en . wikipedia . org / wiki / Chmod # Symbolic _ modes > ` _ .
. . seealso : : : func : ` os . chmod `""" | if isinstance ( mode , str ) :
mask = _multi_permission_mask ( mode )
mode = mask ( self . stat ( ) . st_mode )
os . chmod ( self , mode )
return self |
def supports_kwargs ( module_or_fn , kwargs_list ) :
"""Determines whether the provided callable supports all the kwargs .
This is useful when you have a module that might or might not support a
kwarg such as ` is _ training ` . Rather than calling the module and catching the
error , risking the potential mod... | if isinstance ( kwargs_list , six . string_types ) :
kwargs_list = [ kwargs_list ]
# If it ' s not a function or method , then assume it ' s a module , so introspect
# the _ _ call _ _ method . wrapt ensures that for Sonnet modules the _ build
# signature is available here .
if not ( inspect . isfunction ( module_o... |
def windowed_run_count ( da , window , dim = 'time' ) :
"""Return the number of consecutive true values in array for runs at least as long as given duration .
Parameters
da : N - dimensional Xarray data array ( boolean )
Input data array
window : int
Minimum run length .
dim : Xarray dimension ( default... | d = rle ( da , dim = dim )
out = d . where ( d >= window , 0 ) . sum ( dim = dim )
return out |
def update_meta_data_for_port ( graphical_editor_view , item , handle ) :
"""This method updates the meta data of the states ports if they changed .
: param graphical _ editor _ view : Graphical Editor the change occurred in
: param item : State the port was moved in
: param handle : Handle of moved port or N... | from rafcon . gui . mygaphas . items . ports import IncomeView , OutcomeView , InputPortView , OutputPortView , ScopedVariablePortView
for port in item . get_all_ports ( ) :
if not handle or handle is port . handle :
rel_pos = ( port . handle . pos . x . value , port . handle . pos . y . value )
if ... |
async def _load_container ( self , reader , container_type , params = None , container = None ) :
"""Loads container of elements from the reader . Supports the container ref .
Returns loaded container .
: param reader :
: param container _ type :
: param params :
: param container :
: return :""" | c_len = ( container_type . SIZE if container_type . FIX_SIZE else await load_uvarint ( reader ) )
if container and get_elem ( container ) and c_len != len ( container ) :
raise ValueError ( "Size mismatch" )
elem_type = container_elem_type ( container_type , params )
res = container if container else [ ]
for i in r... |
def choices ( cls , blank = False ) :
"""Choices for Enum
: return : List of tuples ( < value > , < human - readable value > )
: rtype : list""" | choices = sorted ( [ ( key , value ) for key , value in cls . values . items ( ) ] , key = lambda x : x [ 0 ] )
if blank :
choices . insert ( 0 , ( '' , Enum . Value ( '' , None , '' , cls ) ) )
return choices |
def get_load ( jid ) :
'''Return the load from a specified jid''' | log . debug ( 'sqlite3 returner <get_load> called jid: %s' , jid )
conn = _get_conn ( ret = None )
cur = conn . cursor ( )
sql = '''SELECT load FROM jids WHERE jid = :jid'''
cur . execute ( sql , { 'jid' : jid } )
data = cur . fetchone ( )
if data :
return salt . utils . json . loads ( data [ 0 ] . encode ( ) )
_cl... |
def z__update ( self ) :
"""Triple quoted baseline representation .
Return string with multiple triple quoted baseline strings when
baseline had been compared multiple times against varying strings .
: returns : source file baseline replacement text
: rtype : str""" | updates = [ ]
for text in self . _updates :
if self . _AVOID_RAW_FORM :
text_repr = multiline_repr ( text )
raw_char = ''
else :
text_repr = multiline_repr ( text , RAW_MULTILINE_CHARS )
if len ( text_repr ) == len ( text ) :
raw_char = 'r' if '\\' in text_repr else '... |
def _set_md5_auth ( self , v , load = False ) :
"""Setter method for md5 _ auth , mapped from YANG variable / routing _ system / interface / ve / ipv6 / ipv6 _ vrrp _ extended / auth _ type / md5 _ auth ( container )
If this variable is read - only ( config : false ) in the
source YANG file , then _ set _ md5 _... | if hasattr ( v , "_utype" ) :
v = v . _utype ( v )
try :
t = YANGDynClass ( v , base = md5_auth . md5_auth , is_container = 'container' , presence = False , yang_name = "md5-auth" , rest_name = "md5-auth" , parent = self , path_helper = self . _path_helper , extmethods = self . _extmethods , register_paths = Tr... |
def _get_class ( self , classname , namespace , local_only = None , include_qualifiers = None , include_classorigin = None , property_list = None ) : # pylint : disable = invalid - name
"""Get class from repository . Gets the class defined by classname
from the repository , creates a copy , expands the copied cla... | class_repo = self . _get_class_repo ( namespace )
# try to get the target class and create a copy for response
try :
c = class_repo [ classname ]
except KeyError :
raise CIMError ( CIM_ERR_NOT_FOUND , _format ( "Class {0!A} not found in namespace {1!A}." , classname , namespace ) )
cc = deepcopy ( c )
if local_... |
def parse_options ( arguments = None ) :
"""Reads command - line arguments
> > > parse _ options ( ' - - indent - comments ' )""" | if arguments is None :
arguments = sys . argv [ 1 : ]
if isinstance ( arguments , str ) :
arguments = arguments . split ( )
if isinstance ( arguments , argparse . Namespace ) :
return arguments
parser = create_args_parser ( )
args = parser . parse_args ( arguments )
# pprint ( args . _ _ dict _ _ )
args . d... |
def _skip_file ( self , d , files ) :
'''The function passed into shutil . copytree to ignore certain patterns and filetypes
Currently Skipped
Directories - handled by copytree
Symlinks - handled by copytree
Write - only files ( stuff in / proc )
Binaries ( can ' t scan them )''' | skip_list = [ ]
for f in files :
f_full = os . path . join ( d , f )
if not os . path . isdir ( f_full ) :
if not os . path . islink ( f_full ) : # mode = oct ( os . stat ( f _ full ) . st _ mode ) [ - 3 : ]
# executing as root makes this first if clause useless .
# i thought i ' d alrea... |
def _validate_required_settings ( self , application_id , application_config , required_settings ) :
"""All required keys must be present""" | for setting_key in required_settings :
if setting_key not in application_config . keys ( ) :
raise ImproperlyConfigured ( MISSING_SETTING . format ( application_id = application_id , setting = setting_key ) ) |
def _launch_instance ( self ) :
"""Create new test instance in a resource group with the same name .""" | self . running_instance_id = ipa_utils . generate_instance_name ( 'azure-ipa-test' )
self . logger . debug ( 'ID of instance: %s' % self . running_instance_id )
self . _set_default_resource_names ( )
try : # Try block acts as a transaction . If an exception is raised
# attempt to cleanup the resource group and all crea... |
def get_asset_repository_session ( self ) :
"""Gets the session for retrieving asset to repository mappings .
return : ( osid . repository . AssetRepositorySession ) - an
` ` AssetRepositorySession ` `
raise : OperationFailed - unable to complete request
raise : Unimplemented - ` ` supports _ asset _ reposi... | if not self . supports_asset_repository ( ) :
raise errors . Unimplemented ( )
# pylint : disable = no - member
return sessions . AssetRepositorySession ( runtime = self . _runtime ) |
def get_inheritors ( cls ) :
"""Get a set of all classes that inherit from the given class .""" | subclasses = set ( )
work = [ cls ]
while work :
parent = work . pop ( )
for child in parent . __subclasses__ ( ) :
if child not in subclasses :
subclasses . add ( child )
work . append ( child )
return subclasses |
def add_atr ( self , periods = 14 , str = None , name = '' , ** kwargs ) :
"""Add Average True Range ( ATR ) study to QuantFigure . studies
Parameters :
periods : int or list ( int )
Number of periods
name : string
Name given to the study
str : string
Label factory for studies
The following wildcard... | study = { 'kind' : 'atr' , 'name' : name , 'params' : { 'periods' : periods , 'high' : self . _d [ 'high' ] , 'low' : self . _d [ 'low' ] , 'close' : self . _d [ 'close' ] , 'str' : str } , 'display' : utils . merge_dict ( { 'legendgroup' : False } , kwargs ) }
self . _add_study ( study ) |
def __GetServiceVersionDescription ( protocol , server , port , path , sslContext ) :
"""Private method that returns a root from an ElementTree describing the API versions
supported by the specified server . The result will be vimServiceVersions . xml
if it exists , otherwise vimService . wsdl if it exists , ot... | tree = __GetElementTree ( protocol , server , port , path + "/vimServiceVersions.xml" , sslContext )
if tree is not None :
return tree
tree = __GetElementTree ( protocol , server , port , path + "/vimService.wsdl" , sslContext )
return tree |
def post_user_bookmarks_save ( self , id , ** data ) :
"""POST / users / : id / bookmarks / save /
Adds a new bookmark for the user . Returns ` ` { " created " : true } ` ` .
A user is only authorized to save his / her own events .""" | return self . post ( "/users/{0}/bookmarks/save/" . format ( id ) , data = data ) |
def nvmlSystemGetTopologyGpuSet ( cpuNumber ) :
r"""* Retrieve the set of GPUs that have a CPU affinity with the given CPU number
* For all products .
* Supported on Linux only .
* @ param cpuNumber The CPU number
* @ param count When zero , is set to the number of matching GPUs such that \ a deviceArray
... | c_count = c_uint ( 0 )
fn = _nvmlGetFunctionPointer ( "nvmlSystemGetTopologyGpuSet" )
# First call will get the size
ret = fn ( cpuNumber , byref ( c_count ) , None )
if ret != NVML_SUCCESS :
raise NVMLError ( ret )
print ( c_count . value )
# call again with a buffer
device_array = c_nvmlDevice_t * c_count . value... |
def update ( self , event = None , force = False ) :
"""highlight the current line""" | line_no = self . text . index ( tkinter . INSERT ) . split ( "." ) [ 0 ]
# if not force :
# if line _ no = = self . current _ line :
# log . critical ( " no highlight line needed . " )
# return
# log . critical ( " highlight line : % s " % line _ no )
# self . current _ line = line _ no
self . text . tag_remove ( self ... |
def content ( self ) :
"""Content of the response , in bytes or unicode
( if available ) .""" | if self . _content is not None :
return self . _content
if self . _content_consumed :
raise RuntimeError ( 'The content for this response was ' 'already consumed' )
# Read the contents .
try :
self . _content = self . raw . read ( )
except AttributeError :
return None
# Decode GZip ' d content .
if 'gzi... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.