signature stringlengths 29 44.1k | implementation stringlengths 0 85.2k |
|---|---|
def copy ( self , contents = True ) :
'''Create a copy of this model , optionally without contents ( i . e . just configuration )''' | cp = connection ( self . _baseiri , self . _attr_cls , self . _logger )
if contents :
cp . add_many ( self . _relationships )
return cp |
def _build_url ( self ) :
"""Build the URL string to mount this file share .""" | if self . connection . get ( "username" ) and self . connection . get ( "password" ) :
auth = "%s:%s@" % ( self . connection [ "username" ] , self . _encoded_password )
else :
auth = ""
# Optional port number
port = self . connection . get ( "port" )
port = ":" + port if port else ""
self . connection [ "mount_... |
def get_or_create_analysis_system_instance ( instance_uuid = '' , identifier = '' , verbose_name = '' , tag_filter_exp = '' , uuid_file = 'uuid.txt' ) :
"""Get or create an analysis system instance for the analysis system with the respective identifier .
This is a function for solving a common problem with implem... | if instance_uuid :
return resources . AnalysisSystemInstance . get ( instance_uuid )
try :
with open ( uuid_file , 'r' ) as uuid_fp :
instance_uuid = uuid_fp . read ( ) . strip ( )
return resources . AnalysisSystemInstance . get ( instance_uuid )
except IOError :
logging . debug ( 'UUID file... |
def more_master_mem_overhead ( self , mem_increase_mb = 1000 ) :
"""Method to increase the amount of memory overheaded asked for the master node .
Return : new master memory overhead if success , 0 if it cannot be increased .""" | old_master_mem_overhead = self . master_mem_overhead
new_master_mem_overhead = old_master_mem_overhead + mem_increase_mb
if new_master_mem_overhead + self . mem_per_proc < self . hw . mem_per_node :
self . set_master_mem_overhead ( new_master_mem_overhead )
return new_master_mem_overhead
raise self . Error ( 'c... |
def _get_action_from_method_and_request_uri ( self , method , request_uri ) :
"""basically used for ` rest - json ` APIs
You can refer to example from link below
https : / / github . com / boto / botocore / blob / develop / botocore / data / iot / 2015-05-28 / service - 2 . json""" | # service response class should have ' SERVICE _ NAME ' class member ,
# if you want to get action from method and url
if not hasattr ( self , 'SERVICE_NAME' ) :
return None
service = self . SERVICE_NAME
conn = boto3 . client ( service , region_name = self . region )
# make cache if it does not exist yet
if not has... |
def pyang_plugin_init ( ) :
"""Called by pyang plugin framework at to initialize the plugin .""" | # Register the plugin
plugin . register_plugin ( SMIPlugin ( ) )
# Add our special argument syntax checkers
syntax . add_arg_type ( 'smi-oid' , _chk_smi_oid )
syntax . add_arg_type ( 'smi-max-access' , _chk_smi_max_access )
# Register that we handle extensions from the YANG module ' ietf - yang - smiv2'
grammar . regis... |
def pending_exists ( self , hash ) :
"""Check whether block is pending by * * hash * *
. . version 8.0 required
: param hash : Hash of block to check if pending
: type hash : str
: raises : : py : exc : ` nano . rpc . RPCException `
> > > rpc . pending _ exists (
hash = " 000D1BAEC8EC208142C99059B393051... | hash = self . _process_value ( hash , 'block' )
payload = { "hash" : hash }
resp = self . call ( 'pending_exists' , payload )
return resp [ 'exists' ] == '1' |
def evaluate_inline ( self , groups ) :
"""Evaluate inline comments on their own lines .""" | # Consecutive lines with only comments with same leading whitespace
# will be captured as a single block .
if self . lines :
if ( self . group_comments and self . line_num == self . prev_line + 1 and groups [ 'leading_space' ] == self . leading ) :
self . line_comments [ - 1 ] [ 0 ] += '\n' + groups [ 'line... |
def get_objective_admin_session ( self ) :
"""Gets the ` ` OsidSession ` ` associated with the objective administration service .
return : ( osid . learning . ObjectiveAdminSession ) - an
` ` ObjectiveAdminSession ` `
raise : OperationFailed - unable to complete request
raise : Unimplemented - ` ` supports ... | if not self . supports_objective_admin ( ) :
raise errors . Unimplemented ( )
# pylint : disable = no - member
return sessions . ObjectiveAdminSession ( runtime = self . _runtime ) |
def _remove_accents ( filename ) :
"""Function that will try to remove accents from a unicode string to be used in a filename .
input filename should be either an ascii or unicode string""" | # noinspection PyBroadException
try :
filename = filename . replace ( " " , "_" )
if isinstance ( filename , type ( six . u ( '' ) ) ) :
unicode_filename = filename
else :
unicode_filename = six . u ( filename )
cleaned_filename = unicodedata . normalize ( 'NFKD' , unicode_filename ) . e... |
def main ( arguments = None ) :
"""The main function used when ` ` yaml _ to _ database . py ` ` when installed as a cl tool""" | # setup the command - line util settings
su = tools ( arguments = arguments , docString = __doc__ , logLevel = "WARNING" , options_first = False , projectName = False )
arguments , settings , log , dbConn = su . setup ( )
# unpack remaining cl arguments using ` exec ` to setup the variable names
# automatically
for arg... |
def UpdateManifestResourcesFromXMLFile ( dstpath , srcpath , names = None , languages = None ) :
"""Update or add manifest XML from srcpath as resource in dstpath""" | logger . info ( "Updating manifest from %s in %s" , srcpath , dstpath )
if dstpath . lower ( ) . endswith ( ".exe" ) :
name = 1
else :
name = 2
winresource . UpdateResourcesFromDataFile ( dstpath , srcpath , RT_MANIFEST , names or [ name ] , languages or [ 0 , "*" ] ) |
def metrics ( prices , fudge = False , sharpe_days = 252. , baseline = '$SPX' ) :
"""Calculate the volatiliy , average daily return , Sharpe ratio , and cumulative return
Arguments :
prices ( file or basestring or iterable ) : path to file or file pointer or sequence of prices / values of a portfolio or equity ... | if isinstance ( prices , basestring ) and os . path . isfile ( prices ) :
prices = open ( prices , 'rU' )
if isinstance ( prices , file ) :
values = { }
csvreader = csv . reader ( prices , dialect = 'excel' , quoting = csv . QUOTE_MINIMAL )
for row in csvreader : # print row
values [ tuple ( int... |
def check_basic_battery_status ( the_session , the_helper , the_snmp_value ) :
"""OID . 1.3.6.1.4.1.318.1.1.1.2.1.1.0
MIB Excerpt
The status of the UPS batteries . A batteryLow ( 3)
value indicates the UPS will be unable to sustain the
current load , and its services will be lost if power is
not restored ... | apc_battery_states = { '1' : 'unknown' , '2' : 'batteryNormal' , '3' : 'batteryLow' , '4' : 'batteryInFaultCondition' }
a_state = apc_battery_states . get ( the_snmp_value , 'unknown' )
if the_snmp_value == '2' :
the_helper . add_status ( pynag . Plugins . ok )
elif the_snmp_value == '3' :
the_helper . add_stat... |
def _post_process_successors ( self , input_state , sim_successors , successors ) :
"""Filter the list of successors
: param SimState input _ state : Input state .
: param SimSuccessors sim _ successors : The SimSuccessors instance .
: param list successors : A list of successors generated after processing th... | if sim_successors . sort == 'IRSB' and input_state . thumb :
successors = self . _arm_thumb_filter_jump_successors ( sim_successors . addr , sim_successors . artifacts [ 'irsb' ] . size , successors , lambda state : state . scratch . ins_addr , lambda state : state . scratch . exit_stmt_idx )
# If there is a call e... |
def modify_content ( file , old , new ) :
"""替换文件中的指定内容 , 逐行进行""" | try :
lines = open ( file , 'r' ) . readlines ( )
f_len = len ( lines ) - 1
for i in range ( f_len ) :
if old in lines [ i ] :
lines [ i ] = lines [ i ] . replace ( old , new )
open ( file , 'w' ) . writelines ( lines )
except Exception as e :
print ( e ) |
def run_tsne ( self , X = None , metric = 'correlation' , ** kwargs ) :
"""Wrapper for sklearn ' s t - SNE implementation .
See sklearn for the t - SNE documentation . All arguments are the same
with the exception that ' metric ' is set to ' precomputed ' by default ,
implying that this function expects a dis... | if ( X is not None ) :
dt = man . TSNE ( metric = metric , ** kwargs ) . fit_transform ( X )
return dt
else :
dt = man . TSNE ( metric = self . distance , ** kwargs ) . fit_transform ( self . adata . obsm [ 'X_pca' ] )
tsne2d = dt
self . adata . obsm [ 'X_tsne' ] = tsne2d |
def lsdb ( self , lsdb = None , url = None , hgnc_symbol = None , hgnc_identifier = None , limit = None , as_df = False ) :
"""Method to query : class : ` . models . LSDB ` objects in database
: param lsdb : name ( s ) of the Locus Specific Mutation Database
: type lsdb : str or tuple ( str ) or None
: param ... | q = self . session . query ( models . LSDB )
model_queries_config = ( ( lsdb , models . LSDB . lsdb ) , ( url , models . LSDB . url ) , )
q = self . get_model_queries ( q , model_queries_config )
one_to_many_queries_config = ( ( hgnc_symbol , models . HGNC . symbol ) , ( hgnc_identifier , models . HGNC . identifier ) )... |
def promote ( self , cls , update = False , preserve = True ) :
"""Transform this record into an instance of a more specialized subclass .""" | if not issubclass ( cls , self . __class__ ) :
raise TypeError ( "Must promote to a subclass of " + self . __class__ . __name__ )
return self . _as ( cls , update , preserve ) |
def parse ( self , color ) :
"""parse string or a color tuple into color usable for cairo ( all values
in the normalized ( 0 . . 1 ) range""" | assert color is not None
# parse color into rgb values
if isinstance ( color , str ) :
match = self . hex_color_long . match ( color )
if match :
color = [ int ( color , 16 ) / 65535.0 for color in match . groups ( ) ]
else :
match = self . hex_color_normal . match ( color )
if match... |
def diff ( models , filename , pytest_args , exclusive , skip , solver , experimental , custom_tests , custom_config ) :
"""Take a snapshot of all the supplied models and generate a diff report .
MODELS : List of paths to two or more model files .""" | if not any ( a . startswith ( "--tb" ) for a in pytest_args ) :
pytest_args = [ "--tb" , "no" ] + pytest_args
# Add further directories to search for tests .
pytest_args . extend ( custom_tests )
config = ReportConfiguration . load ( )
# Update the default test configuration with custom ones ( if any ) .
for custom... |
def unarchive ( filename , output_dir = '.' ) :
'''unpacks the given archive into ` ` output _ dir ` `''' | if not os . path . exists ( output_dir ) :
os . makedirs ( output_dir )
for archive in archive_formats :
if filename . endswith ( archive_formats [ archive ] [ 'suffix' ] ) :
return subprocess . call ( archive_formats [ archive ] [ 'command' ] ( output_dir , filename ) ) == 0
return False |
def callgrind ( self , out , filename = None , commandline = None , relative_path = False ) :
"""Dump statistics in callgrind format .
Contains :
- per - line hit count , time and time - per - hit
- call associations ( call tree )
Note : hit count is not inclusive , in that it is not the sum of all
hits i... | print >> out , 'version: 1'
if commandline is not None :
print >> out , 'cmd:' , commandline
print >> out , 'creator: pprofile'
print >> out , 'event: usphit :us/hit'
print >> out , 'events: hits us usphit'
file_dict = self . file_dict
if relative_path :
convertPath = _relpath
else :
convertPath = lambda x ... |
async def pipeline ( self , transaction = None , shard_hint = None , watches = None ) :
"""Cluster impl :
Pipelines do not work in cluster mode the same way they do in normal mode .
Create a clone of this object so that simulating pipelines will work correctly .
Each command will be called directly when used ... | await self . connection_pool . initialize ( )
if shard_hint :
raise RedisClusterException ( "shard_hint is deprecated in cluster mode" )
from aredis . pipeline import StrictClusterPipeline
return StrictClusterPipeline ( connection_pool = self . connection_pool , startup_nodes = self . connection_pool . nodes . star... |
def getRootJobs ( self ) :
""": return : The roots of the connected component of jobs that contains this job . A root is a job with no predecessors .
: rtype : set of toil . job . Job instances""" | roots = set ( )
visited = set ( )
# Function to get the roots of a job
def getRoots ( job ) :
if job not in visited :
visited . add ( job )
if len ( job . _directPredecessors ) > 0 :
list ( map ( lambda p : getRoots ( p ) , job . _directPredecessors ) )
else :
roots .... |
def enrich_by_predicate ( request , json , fun , predicate , skip_nested = False , ** kwargs ) :
"""Take the JSON , find all its subparts satisfying the given condition and
them by the given function . Other key - word arguments are passed to the function .
. . testsetup : :
from pprint import pprint
from p... | time_start = time ( )
collected = [ ]
memory = { 'nested' : False }
def _collect ( json_inner , nested ) :
if nested and skip_nested :
return
if isinstance ( json_inner , list ) :
list ( map ( lambda x : _collect ( x , nested ) , json_inner ) )
elif isinstance ( json_inner , dict ) :
... |
def collect_user_info ( endpoint_context , session , userinfo_claims = None ) :
"""Collect information about a user .
This can happen in two cases , either when constructing an IdToken or
when returning user info through the UserInfo endpoint
: param session : Session information
: param userinfo _ claims :... | authn_req = session [ 'authn_req' ]
if userinfo_claims is None :
uic = scope2claims ( authn_req [ "scope" ] )
# Get only keys allowed by user and update the dict if such info
# is stored in session
perm_set = session . get ( 'permission' )
if perm_set :
uic = { key : uic [ key ] for key in u... |
def application_properties ( self , key = None ) :
"""Return the mutable server application properties .
: param key : the single property to return a value for
: type key : Optional [ str ]
: rtype : Union [ Dict [ str , str ] , List [ Dict [ str , str ] ] ]""" | params = { }
if key is not None :
params [ 'key' ] = key
return self . _get_json ( 'application-properties' , params = params ) |
def draw_best_fit ( X , y , ax , estimator = 'linear' , ** kwargs ) :
"""Uses Scikit - Learn to fit a model to X and y then uses the resulting model
to predict the curve based on the X values . This curve is drawn to the ax
( matplotlib axis ) which must be passed as the third variable .
The estimator functio... | # Estimators are the types of best fit lines that can be drawn .
estimators = { LINEAR : fit_linear , # Uses OLS to fit the regression
QUADRATIC : fit_quadratic , # Uses OLS with Polynomial order 2
EXPONENTIAL : fit_exponential , # Not implemented yet
LOG : fit_log , # Not implemented yet
SELECT_BEST : fit_select_best ... |
def extract_pixels ( X ) :
"""Extract pixels from array X
: param X : Array of images to be classified .
: type X : numpy array , shape = [ n _ images , n _ pixels _ y , n _ pixels _ x , n _ bands ]
: return : Reshaped 2D array
: rtype : numpy array , [ n _ samples * n _ pixels _ y * n _ pixels _ x , n _ ba... | if len ( X . shape ) != 4 :
raise ValueError ( 'Array of input images has to be a 4-dimensional array of shape' '[n_images, n_pixels_y, n_pixels_x, n_bands]' )
new_shape = ( X . shape [ 0 ] * X . shape [ 1 ] * X . shape [ 2 ] , X . shape [ 3 ] , )
pixels = X . reshape ( new_shape )
return pixels |
def update ( self ) :
"""Wrapper method to update the stats .""" | # For standalone and server modes
# For each plugins , call the update method
for p in self . _plugins :
if self . _plugins [ p ] . is_disable ( ) : # If current plugin is disable
# then continue to next plugin
continue
# Update the stats . . .
self . _plugins [ p ] . update ( )
# . . . the ... |
def help_dataframe_pe ( self ) :
"""Help for making a DataFrame with Workbench CLI""" | help = '%sMaking a DataFrame: %s how to make a dataframe from pe files' % ( color . Yellow , color . Green )
help += '\n\n%sPE Files Example (loading a directory):' % ( color . Green )
help += '\n\t%s> load_sample /path/to/pe/bad [\'bad\', \'case_69\']' % ( color . LightBlue )
help += '\n\n\t%sSearch for all samples in... |
def lsb_release ( ) :
"""Return / etc / lsb - release in a dict""" | d = { }
with open ( '/etc/lsb-release' , 'r' ) as lsb :
for l in lsb :
k , v = l . split ( '=' )
d [ k . strip ( ) ] = v . strip ( )
return d |
def of_project ( project : 'projects.Project' ) -> dict :
"""Returns the file status information for every file within the project
source directory and its shared library folders .
: param project :
The project for which the status information should be generated
: return :
A dictionary containing :
- p... | source_directory = project . source_directory
libraries_status = [ { } if d . startswith ( source_directory ) else of_directory ( d ) for d in project . library_directories ]
return dict ( project = of_directory ( source_directory ) , libraries = libraries_status ) |
def _nbytes ( self , deep = False ) :
"""return the number of bytes in the underlying data
deeply introspect the level data if deep = True
include the engine hashtable
* this is in internal routine *""" | # for implementations with no useful getsizeof ( PyPy )
objsize = 24
level_nbytes = sum ( i . memory_usage ( deep = deep ) for i in self . levels )
label_nbytes = sum ( i . nbytes for i in self . codes )
names_nbytes = sum ( getsizeof ( i , objsize ) for i in self . names )
result = level_nbytes + label_nbytes + names_... |
def setup_logdir ( self ) : # todo : locking on logdir creation
"""Create logdir for task / job / run . No - op if the task is not chief ( 0 ' th task of 0 ' th job of run )""" | run_name = ncluster_globals . get_run_for_task ( self )
self . log ( "Creating logdir for run " + run_name )
logdir_root = ncluster_globals . LOGDIR_ROOT
assert logdir_root
self . run ( f'mkdir -p {logdir_root}' )
find_command = f'find {logdir_root} -maxdepth 1 -type d'
stdout , stderr = self . run_with_output ( find_c... |
def setShowMinutes ( self , state = True ) :
"""Sets whether or not to display the minutes combo box for this widget .
: param state | < bool >""" | self . _showMinutes = state
if state :
self . _minuteCombo . show ( )
else :
self . _minuteCombo . hide ( ) |
def DownloadReportToFile ( self , report_job_id , export_format , outfile , include_report_properties = False , include_totals_row = None , use_gzip_compression = True ) :
"""Downloads report data and writes it to a file .
The report job must be completed before calling this function .
Args :
report _ job _ i... | service = self . _GetReportService ( )
if include_totals_row is None : # True unless CSV export if not specified
include_totals_row = True if export_format != 'CSV_DUMP' else False
opts = { 'exportFormat' : export_format , 'includeReportProperties' : include_report_properties , 'includeTotalsRow' : include_totals_r... |
def joined_seq ( seq , sep = None ) :
r"""Join a sequence into a tuple or a concatenated string
> > > joined _ seq ( range ( 3 ) , ' , ' )
'0 , 1 , 2'
> > > joined _ seq ( [ 1 , 2 , 3 ] )
(1 , 2 , 3)""" | joined_seq = tuple ( seq )
if isinstance ( sep , basestring ) :
joined_seq = sep . join ( str ( item ) for item in joined_seq )
return joined_seq |
def ResolveForCreate ( self , document ) :
"""Resolves the collection for creating the document based on the partition key .
: param dict document :
The document to be created .
: return :
Collection Self link or Name based link which should handle the Create operation .
: rtype :
str""" | if document is None :
raise ValueError ( "document is None." )
partition_key = self . partition_key_extractor ( document )
return self . consistent_hash_ring . GetCollectionNode ( partition_key ) |
def union ( self , * queries ) :
'''Return a new : class : ` Query ` obtained form the union of this
: class : ` Query ` with one or more * queries * .
For example , lets say we want to have the union
of two queries obtained from the : meth : ` filter ` method : :
query = session . query ( MyModel )
qs = ... | q = self . _clone ( )
q . unions += queries
return q |
def get_signature_params ( func ) :
"""Get signature parameters
Support Cython functions by grabbing relevant attributes from the Cython
function and attaching to a no - op function . This is somewhat brittle , since
funcsigs may change , but given that funcsigs is written to a PEP , we hope
it is relativel... | # The first condition for Cython functions , the latter for Cython instance
# methods
if is_cython ( func ) :
attrs = [ "__code__" , "__annotations__" , "__defaults__" , "__kwdefaults__" ]
if all ( hasattr ( func , attr ) for attr in attrs ) :
original_func = func
def func ( ) :
retu... |
def _read_data_handler ( whence , ctx , complete , can_flush ) :
"""Creates a co - routine for retrieving data up to a requested size .
Args :
whence ( Coroutine ) : The co - routine to return to after the data is satisfied .
ctx ( _ HandlerContext ) : The context for the read .
complete ( True | False ) : ... | trans = None
queue = ctx . queue
while True :
data_event , self = ( yield trans )
if data_event is not None :
if data_event . data is not None :
data = data_event . data
data_len = len ( data )
if data_len > 0 :
queue . extend ( data )
... |
def _discretize_check ( self , table , att , col ) :
'''Replaces the value with an appropriate interval symbol , if available .''' | label = "'%s'" % col
if table in self . discr_intervals and att in self . discr_intervals [ table ] :
intervals = self . discr_intervals [ table ] [ att ]
n_intervals = len ( intervals )
prev_value = None
for i , value in enumerate ( intervals ) :
if i > 0 :
prev_value = intervals [ ... |
def _get_state ( inspect_results ) :
'''Helper for deriving the current state of the container from the inspect
results .''' | if inspect_results . get ( 'State' , { } ) . get ( 'Paused' , False ) :
return 'paused'
elif inspect_results . get ( 'State' , { } ) . get ( 'Running' , False ) :
return 'running'
else :
return 'stopped' |
def show_in_view ( self , sourceview , matches , targetname = None ) :
"""Show search result in ncurses view .""" | append = self . options . append_view or self . options . alter_view == 'append'
remove = self . options . alter_view == 'remove'
action_name = ', appending to' if append else ', removing from' if remove else ' into'
targetname = config . engine . show ( matches , targetname or self . options . to_view or "rtcontrol" ,... |
def cache ( self ) :
"""Get the Django cache interface .
This allows disabling the cache with
settings . USE _ DRF _ INSTANCE _ CACHE = False . It also delays import so that
Django Debug Toolbar will record cache requests .""" | if not self . _cache :
use_cache = getattr ( settings , 'USE_DRF_INSTANCE_CACHE' , True )
if use_cache :
from django . core . cache import cache
self . _cache = cache
return self . _cache |
def sci ( self ) :
"""Property providing access to the : class : ` . ServerCommandInterfaceAPI `""" | if self . _sci_api is None :
self . _sci_api = self . get_sci_api ( )
return self . _sci_api |
def startService ( self ) :
"""Start calling persistent timed events whose time has come .""" | super ( _SiteScheduler , self ) . startService ( )
self . _transientSchedule ( self . now ( ) , self . now ( ) ) |
def ib_group_member_add ( self , group_id , userids ) :
'''ib group member add''' | req_hook = 'pod/v1/admin/group/' + group_id + '/membership/add'
req_args = { 'usersListId' : userids }
req_args = json . dumps ( req_args )
status_code , response = self . __rest__ . POST_query ( req_hook , req_args )
self . logger . debug ( '%s: %s' % ( status_code , response ) )
return status_code , response |
def _gripper_visualization ( self ) :
"""Do any needed visualization here . Overrides superclass implementations .""" | # color the gripper site appropriately based on distance to cube
if self . gripper_visualization : # get distance to cube
cube_site_id = self . sim . model . site_name2id ( "cube" )
dist = np . sum ( np . square ( self . sim . data . site_xpos [ cube_site_id ] - self . sim . data . get_site_xpos ( "grip_site" )... |
def __initialize_snapshot ( self ) :
"""Private method to automatically initialize the snapshot
when you try to use it without calling any of the scan _ *
methods first . You don ' t need to call this yourself .""" | if not self . __processDict :
try :
self . scan_processes ( )
# remote desktop api ( relative fn )
except Exception :
self . scan_processes_fast ( )
# psapi ( no filenames )
self . scan_process_filenames ( ) |
def _CurrentAuditLog ( ) :
"""Get the rdfurn of the current audit log .""" | now_sec = rdfvalue . RDFDatetime . Now ( ) . AsSecondsSinceEpoch ( )
rollover_seconds = AUDIT_ROLLOVER_TIME . seconds
# This gives us a filename that only changes every
# AUDIT _ ROLLOVER _ TIfilME seconds , but is still a valid timestamp .
current_log = ( now_sec // rollover_seconds ) * rollover_seconds
return _AuditL... |
def __public_objs ( self ) :
"""Returns a dictionary mapping a public identifier name to a
Python object . This counts the ` _ _ init _ _ ` method as being
public .""" | _budoc = getattr ( self . module . module , '__budoc__' , { } )
def forced_out ( name ) :
return _budoc . get ( '%s.%s' % ( self . name , name ) , False ) is None
def exported ( name ) :
exported = name == '__init__' or _is_exported ( name )
return not forced_out ( name ) and exported
idents = dict ( inspec... |
def from_cli ( opt ) :
"""Parses the command line options and returns a precessing scheme .
Parameters
opt : object
Result of parsing the CLI with OptionParser , or any object with
the required attributes .
Returns
ctx : Scheme
Returns the requested processing scheme .""" | scheme_str = opt . processing_scheme . split ( ':' )
name = scheme_str [ 0 ]
if name == "cuda" :
logging . info ( "Running with CUDA support" )
ctx = CUDAScheme ( opt . processing_device_id )
elif name == "mkl" :
if len ( scheme_str ) > 1 :
numt = scheme_str [ 1 ]
if numt . isdigit ( ) :
... |
def cached_object ( self , path , compute_fn ) :
"""If ` cached _ object ` has already been called for a value of ` path ` in this
running Python instance , then it should have a cached value in the
_ memory _ cache ; return that value .
If this function was never called before with a particular value of
` ... | if path in self . _memory_cache :
return self . _memory_cache [ path ]
if exists ( path ) and not self . is_empty ( path ) :
obj = load_pickle ( path )
else :
obj = compute_fn ( )
dump_pickle ( obj , path )
self . _memory_cache [ path ] = obj
return obj |
def append ( self , message_level , message_text ) :
"""Adds a message level / text pair to this MessagesHeader""" | if not message_level in MessagesHeader . _message_levels :
raise ValueError ( 'message_level="%s"' % message_level )
self . _messages . append ( ( message_level , message_text ) ) |
def _merge_list_of_keys_into_dict ( cls , data , keys , value , index = 0 ) :
"""Recursively merge list of keys that points to the given value into data .
Will override a primitive value with another primitive value , but will not
override a primitive with a dictionary .
For example :
Given the dictionary {... | if len ( keys ) == 0 or index < 0 or index >= len ( keys ) :
raise ValueError ( 'Keys must contain at least one key and index must be' 'an integer greater than 0 and less than the number of keys.' )
if len ( keys ) < 2 or not data :
new_data_to_add = cls . _create_dict_with_nested_keys_and_val ( keys , value )
... |
def schema_cmd ( options ) :
"""Print info about the resources , actions and filters available .""" | from c7n import schema
if options . json :
schema . json_dump ( options . resource )
return
load_resources ( )
resource_mapping = schema . resource_vocabulary ( )
if options . summary :
schema . summary ( resource_mapping )
return
# Here are the formats for what we accept :
# - No argument
# - List all ... |
def stats ( self , columns ) :
"""Compute the stats for each column provided in columns .
Parameters
columns : list of str , contains all columns to compute stats on .""" | assert ( not isinstance ( columns , basestring ) ) , "columns should be a " "list of strs, " "not a str!"
assert isinstance ( columns , list ) , "columns should be a list!"
from pyspark . sql import functions as F
functions = [ F . min , F . max , F . avg , F . count ]
aggs = list ( self . _flatmap ( lambda column : m... |
def runSearchContinuousSets ( self , request ) :
"""Returns a SearchContinuousSetsResponse for the specified
SearchContinuousSetsRequest object .""" | return self . runSearchRequest ( request , protocol . SearchContinuousSetsRequest , protocol . SearchContinuousSetsResponse , self . continuousSetsGenerator ) |
async def get_response ( self , message = None , * , timeout = None ) :
"""Returns a coroutine that will resolve once a response arrives .
Args :
message ( ` Message < telethon . tl . custom . message . Message > ` | ` int ` , optional ) :
The message ( or the message ID ) for which a response
is expected .... | return await self . _get_message ( message , self . _response_indices , self . _pending_responses , timeout , lambda x , y : True ) |
def info ( ) :
"""make Texinfo files and run them through makeinfo""" | rc = texinfo ( )
print ( 'Running Texinfo files through makeinfo...' )
builddir = os . path . join ( BUILDDIR , 'texinfo' )
subprocess . call ( [ 'make' , '-C' , builddir , 'info' ] )
print ( 'makeinfo finished; the Info files are in {}.' . format ( builddir ) ) |
def get_next_section_start_line ( self , data ) :
"""Get the starting line number of next section .
It will return - 1 if no section was found .
The section is a section key ( e . g . ' Parameters : ' )
then the content
: param data : a list of strings containing the docstring ' s lines
: returns : the in... | start = - 1
for i , line in enumerate ( data ) :
if isin_alone ( [ k + ":" for k in self . opt . values ( ) ] , line ) :
start = i
break
return start |
def _levenshtein_compute ( source , target , rd_flag ) :
"""Computes the Levenshtein
( https : / / en . wikipedia . org / wiki / Levenshtein _ distance )
and restricted Damerau - Levenshtein
( https : / / en . wikipedia . org / wiki / Damerau % E2%80%93Levenshtein _ distance )
distances between two Unicode ... | # Create matrix of correct size ( this is s _ len + 1 * t _ len + 1 so that the
# empty prefixes " " can also be included ) . The leftmost column represents
# transforming various source prefixes into an empty string , which can
# always be done by deleting all characters in the respective prefix , and
# the top row re... |
def pop ( self , key ) :
"""Pops dict _ grid with undo and redo support
Parameters
key : 3 - tuple of Integer
\t Cell key that shall be popped""" | try :
self . result_cache . pop ( repr ( key ) )
except KeyError :
pass
return DataArray . pop ( self , key ) |
def run_impl ( self , change , entry , out ) :
"""sets up the report directory for an HTML report . Obtains the
top - level Cheetah template that is appropriate for the change
instance , and runs it .
The cheetah templates are supplied the following values :
* change - the Change instance to report on
* e... | options = self . options
# translate relative paths if necessary
javascripts = self . _relative_uris ( options . html_javascripts )
stylesheets = self . _relative_uris ( options . html_stylesheets )
# map the class of the change to a template class
template_class = resolve_cheetah_template ( type ( change ) )
# instant... |
def show_fabric_trunk_info_output_show_trunk_list_trunk_list_groups_trunk_list_member_trunk_list_nbr_interface_type ( self , ** kwargs ) :
"""Auto Generated Code""" | config = ET . Element ( "config" )
show_fabric_trunk_info = ET . Element ( "show_fabric_trunk_info" )
config = show_fabric_trunk_info
output = ET . SubElement ( show_fabric_trunk_info , "output" )
show_trunk_list = ET . SubElement ( output , "show-trunk-list" )
trunk_list_groups = ET . SubElement ( show_trunk_list , "t... |
def byte_to_unitcode ( bytecode ) :
"""Return an X10 unitcode value from a byte value .""" | return list ( UC_LOOKUP . keys ( ) ) [ list ( UC_LOOKUP . values ( ) ) . index ( bytecode ) ] |
def parse_datetime ( time_str ) :
"""Wraps dateutil ' s parser function to set an explicit UTC timezone , and
to make sure microseconds are 0 . Unified Uploader format and EMK format
bother don ' t use microseconds at all .
: param str time _ str : The date / time str to parse .
: rtype : datetime . datetim... | try :
return dateutil . parser . parse ( time_str ) . replace ( microsecond = 0 ) . astimezone ( UTC_TZINFO )
except ValueError : # This was some kind of unrecognizable time string .
raise ParseError ( "Invalid time string: %s" % time_str ) |
def ds_cT ( ds , x , y , xy_srs = wgs_srs ) :
"""Convert input point coordinates to map coordinates that match input dataset""" | # Convert lat / lon to projected srs
ds_srs = get_ds_srs ( ds )
# If xy _ srs is undefined , assume it is the same as ds _ srs
mX = x
mY = y
if xy_srs is not None :
if not ds_srs . IsSame ( xy_srs ) :
mX , mY , mZ = cT_helper ( x , y , 0 , xy_srs , ds_srs )
return mX , mY |
def get_coordinates ( self , i , end = False ) :
"""Returns the starting coordinates of node i as a pair ,
or the end coordinates iff end is True .""" | if end :
endpoint = self . endpoints [ i ] [ 1 ]
else :
endpoint = self . endpoints [ i ] [ 0 ]
return ( endpoint . real , endpoint . imag ) |
def remove_cookie_by_name ( cookiejar , name , domain = None , path = None ) :
"""Unsets a cookie by name , by default over all domains and paths .
Wraps CookieJar . clear ( ) , is O ( n ) .""" | clearables = [ ]
for cookie in cookiejar :
if cookie . name != name :
continue
if domain is not None and domain != cookie . domain :
continue
if path is not None and path != cookie . path :
continue
clearables . append ( ( cookie . domain , cookie . path , cookie . name ) )
for d... |
def _getCommonStart ( self , left , right ) :
"""Return the common prefix of the 2 strings .
@ param left : one string
@ param right : another string""" | prefix = [ ]
for a , b in zip ( left , right ) :
if a == b :
prefix . append ( a )
else :
break
return '' . join ( prefix ) |
def cov_params ( self , r_matrix = None , column = None , scale = None , cov_p = None , other = None ) :
"""Returns the variance / covariance matrix .
The variance / covariance matrix can be of a linear contrast
of the estimates of params or all params multiplied by scale which
will usually be an estimate of ... | if ( hasattr ( self , 'mle_settings' ) and self . mle_settings [ 'optimizer' ] in [ 'l1' , 'l1_cvxopt_cp' ] ) :
dot_fun = nan_dot
else :
dot_fun = np . dot
if ( cov_p is None and self . normalized_cov_params is None and not hasattr ( self , 'cov_params_default' ) ) :
raise ValueError ( 'need covariance of p... |
def get_hyperparameter_configurations ( self , num , r , searchspace_json , random_state ) : # pylint : disable = invalid - name
"""Randomly generate num hyperparameter configurations from search space
Parameters
num : int
the number of hyperparameter configurations
Returns
list
a list of hyperparameter... | global _KEY
# pylint : disable = global - statement
assert self . i == 0
hyperparameter_configs = dict ( )
for _ in range ( num ) :
params_id = create_bracket_parameter_id ( self . bracket_id , self . i )
params = json2paramater ( searchspace_json , random_state )
params [ _KEY ] = r
hyperparameter_conf... |
def validate_spec ( spec ) :
"""Validate the output of an : class : ` APISpec ` object against the
OpenAPI specification .
Note : Requires installing apispec with the ` ` [ validation ] ` ` extras .
pip install ' apispec [ validation ] '
: raise : apispec . exceptions . OpenAPIError if validation fails .""" | try :
import prance
except ImportError as error : # re - raise with a more verbose message
exc_class = type ( error )
raise exc_class ( "validate_spec requires prance to be installed. " "You can install all validation requirements using:\n" " pip install 'apispec[validation]'" )
parser_kwargs = { }
if sp... |
def read ( self ) :
"""Read object from artifactory . Fill object if exist
: return :
True if object exist ,
False else""" | logging . debug ( 'Read {x.__class__.__name__} [{x.name}]' . format ( x = self ) )
request_url = self . _artifactory . drive + '/api/{uri}/{x.name}' . format ( uri = self . _uri , x = self )
r = self . _session . get ( request_url , auth = self . _auth , )
if 404 == r . status_code or 400 == r . status_code :
loggi... |
def _update_servers ( self ) :
"""Sync our Servers from TopologyDescription . server _ descriptions .
Hold the lock while calling this .""" | for address , sd in self . _description . server_descriptions ( ) . items ( ) :
if address not in self . _servers :
monitor = self . _settings . monitor_class ( server_description = sd , topology = self , pool = self . _create_pool_for_monitor ( address ) , topology_settings = self . _settings )
wea... |
def with_options ( self , codec_options = None , read_preference = None , write_concern = None , read_concern = None ) :
"""Get a clone of this database changing the specified settings .
> > > db1 . read _ preference
Primary ( )
> > > from pymongo import ReadPreference
> > > db2 = db1 . with _ options ( rea... | return Database ( self . client , self . __name , codec_options or self . codec_options , read_preference or self . read_preference , write_concern or self . write_concern , read_concern or self . read_concern ) |
def mod_bufsize ( iface , * args , ** kwargs ) :
'''Modify network interface buffers ( currently linux only )
CLI Example :
. . code - block : : bash
salt ' * ' network . mod _ bufsize tx = < val > rx = < val > rx - mini = < val > rx - jumbo = < val >''' | if __grains__ [ 'kernel' ] == 'Linux' :
if os . path . exists ( '/sbin/ethtool' ) :
return _mod_bufsize_linux ( iface , * args , ** kwargs )
return False |
def defragment6 ( packets ) :
"""Performs defragmentation of a list of IPv6 packets . Packets are reordered .
Crap is dropped . What lacks is completed by ' X ' characters .""" | # Remove non fragments
lst = [ x for x in packets if IPv6ExtHdrFragment in x ]
if not lst :
return [ ]
id = lst [ 0 ] [ IPv6ExtHdrFragment ] . id
llen = len ( lst )
lst = [ x for x in lst if x [ IPv6ExtHdrFragment ] . id == id ]
if len ( lst ) != llen :
warning ( "defragment6: some fragmented packets have been ... |
def make_supercell ( system , matrix , supercell = [ 1 , 1 , 1 ] ) :
"""Return a supercell .
This functions takes the input unitcell and creates a supercell of it that
is returned as a new : class : ` pywindow . molecular . MolecularSystem ` .
Parameters
system : : attr : ` pywindow . molecular . MolecularS... | user_supercell = [ [ 1 , supercell [ 0 ] ] , [ 1 , supercell [ 1 ] ] , [ 1 , supercell [ 1 ] ] ]
system = create_supercell ( system , matrix , supercell = user_supercell )
return MolecularSystem . load_system ( system ) |
def list_catalog ( self , kind ) :
'''listing the category .''' | kwd = { 'pager' : '' , 'title' : '最近文档' , 'kind' : kind , 'router' : config . router_post [ kind ] }
self . render ( 'admin/{0}/category_list.html' . format ( self . tmpl_router ) , kwd = kwd , view = MCategory . query_all ( kind , by_order = True ) , format_date = tools . format_date , userinfo = self . userinfo , cfg... |
def _handle_result_by_index ( self , idx ) :
"""Handle processing when the result argument provided is an integer .""" | if idx < 0 :
return None
opts = dict ( self . options )
skip = opts . pop ( 'skip' , 0 )
limit = opts . pop ( 'limit' , None )
py_to_couch_validate ( 'skip' , skip )
py_to_couch_validate ( 'limit' , limit )
if limit is not None and idx >= limit : # Result is out of range
return dict ( )
return self . _ref ( ski... |
def build ( self ) :
"""Build package from source and create log
file in path / var / log / slpkg / sbo / build _ logs / .
Also check md5sum calculates .""" | try :
self . _delete_dir ( )
try :
tar = tarfile . open ( self . script )
except Exception as err :
print err
raise SystemExit ( )
tar . extractall ( )
tar . close ( )
self . _makeflags ( )
self . _delete_sbo_tar_gz ( )
self . _create_md5_dict ( )
if not self ... |
def _save_single_attr ( self , entity , value = None , schema = None , create_nulls = False , extra = { } ) :
"""Creates or updates an EAV attribute for given entity with given value .
: param schema : schema for attribute . Default it current schema instance .
: param create _ nulls : boolean : if True , even ... | # If schema is not many - to - one , the value is saved to the corresponding
# Attr instance ( which is created or updated ) .
schema = schema or self
lookups = dict ( get_entity_lookups ( entity ) , schema = schema , ** extra )
try :
attr = self . attrs . get ( ** lookups )
except self . attrs . model . DoesNotExi... |
def write ( self , group_id , handle ) :
'''Write this parameter group , with parameters , to a file handle .
Parameters
group _ id : int
The numerical ID of the group .
handle : file handle
An open , writable , binary file handle .''' | name = self . name . encode ( 'utf-8' )
desc = self . desc . encode ( 'utf-8' )
handle . write ( struct . pack ( 'bb' , len ( name ) , - group_id ) )
handle . write ( name )
handle . write ( struct . pack ( '<h' , 3 + len ( desc ) ) )
handle . write ( struct . pack ( 'B' , len ( desc ) ) )
handle . write ( desc )
for p... |
def _to_dict ( xmltree ) :
'''Converts an XML ElementTree to a dictionary that only contains items .
This is the default behavior in version 2017.7 . This will default to prevent
unexpected parsing issues on modules dependant on this .''' | # If this object has no children , the for . . loop below will return nothing
# for it , so just return a single dict representing it .
if not xmltree . getchildren ( ) :
name = _conv_name ( xmltree . tag )
return { name : xmltree . text }
xmldict = { }
for item in xmltree :
name = _conv_name ( item . tag )... |
def clone ( self , url , update_after_clone = True , bare = False ) :
"""Tries to clone changes from external location .
: param update _ after _ clone : If set to ` ` False ` ` , git won ' t checkout
working directory
: param bare : If set to ` ` True ` ` , repository would be cloned into
* bare * git repo... | url = self . _get_url ( url )
cmd = [ 'clone' ]
if bare :
cmd . append ( '--bare' )
elif not update_after_clone :
cmd . append ( '--no-checkout' )
cmd += [ '--' , '"%s"' % url , '"%s"' % self . path ]
cmd = ' ' . join ( cmd )
# If error occurs run _ git _ command raises RepositoryError already
self . run_git_co... |
def authenticate ( self , request ) :
"""Authenticate request using HTTP Basic authentication protocl .
If the user is successfully identified , the corresponding user
object is stored in ` request . user ` . If the request has already
been authenticated ( i . e . ` request . user ` has authenticated user
o... | # todo : can we trust that request . user variable is even defined ?
if request . user and request . user . is_authenticated ( ) :
return request . user
if 'HTTP_AUTHORIZATION' in request . META :
auth = request . META [ 'HTTP_AUTHORIZATION' ] . split ( )
if len ( auth ) == 2 :
if auth [ 0 ] . lower... |
def handle_request ( self ) :
"""Handles an HTTP request . The actual HTTP request is handled using a
different thread .""" | timeout = self . socket . gettimeout ( )
if timeout is None :
timeout = self . timeout
elif self . timeout is not None :
timeout = min ( timeout , self . timeout )
ctime = get_time ( )
done_req = False
shutdown_latency = self . shutdown_latency
if timeout is not None :
shutdown_latency = min ( shutdown_late... |
def set_max_workers ( self , nb ) :
"""Set the maximum workers to create .""" | self . count_lock . acquire ( )
self . shared [ 'max_workers' ] = nb
if self . shared [ 'workers' ] > self . shared [ 'max_workers' ] :
self . kill ( self . shared [ 'workers' ] - self . shared [ 'max_workers' ] )
self . count_lock . release ( ) |
def _migrate_subresources ( parent , migrations ) :
"""Migrate a resource ' s subresources
: param parent : the parent perch . Document instance
: param migrations : the migrations for a resource""" | for subresource , resource_migrations in migrations . items ( ) :
parent = _migrate_subresource ( subresource , parent , resource_migrations )
return parent |
def setData ( self , index , value , role = QtCore . Qt . UserRole ) :
"""Sets the component at * index * to * value *""" | # item must already exist at provided index
self . _stim . overwriteComponent ( value , index . row ( ) , index . column ( ) )
self . samplerateChanged . emit ( self . samplerate ( ) ) |
def diagnose_repo_nexml2json ( shard ) :
"""Optimistic test for Nexson version in a shard ( tests first study found )""" | with shard . _index_lock :
fp = next ( iter ( shard . study_index . values ( ) ) ) [ 2 ]
with codecs . open ( fp , mode = 'r' , encoding = 'utf-8' ) as fo :
fj = json . load ( fo )
from peyotl . nexson_syntax import detect_nexson_version
return detect_nexson_version ( fj ) |
def write ( self , pkt ) :
"""accepts a either a single packet or a list of packets
to be written to the dumpfile""" | if not self . header_present :
self . _write_header ( pkt )
if isinstance ( pkt , BasePacket ) :
self . _write_packet ( pkt )
else :
for p in pkt :
self . _write_packet ( p ) |
def dump_rexobj_results ( rexobj , options = None ) :
'''print all the results .''' | print ( "-" * 60 )
print ( "Match count: " , rexobj . res_count )
matches = rexobj . matches
for match in matches :
print ( "Loc:" , match . loc , ":: " )
for key in match . named_groups . keys ( ) :
print ( "%s: %s" % ( key , match . named_groups [ key ] ) )
print ( "" ) |
def _prodterm_prime ( lexer ) :
"""Return a product term ' expression , eliminates left recursion .""" | tok = next ( lexer )
# ' & ' FACTOR PRODTERM '
if isinstance ( tok , OP_and ) :
factor = _factor ( lexer )
prodterm_prime = _prodterm_prime ( lexer )
if prodterm_prime is None :
return factor
else :
return ( 'and' , factor , prodterm_prime )
# null
else :
lexer . unpop_token ( tok )
... |
def get_model ( self ) :
"""Get a model if the formula was previously satisfied .""" | if self . minisat and self . status == True :
model = pysolvers . minisat22_model ( self . minisat )
return model if model != None else [ ] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.