signature stringlengths 29 44.1k | implementation stringlengths 0 85.2k |
|---|---|
def is_true ( value = None ) :
'''Returns a boolean value representing the " truth " of the value passed . The
rules for what is a " True " value are :
1 . Integer / float values greater than 0
2 . The string values " True " and " true "
3 . Any object for which bool ( obj ) returns True''' | # First , try int / float conversion
try :
value = int ( value )
except ( ValueError , TypeError ) :
pass
try :
value = float ( value )
except ( ValueError , TypeError ) :
pass
# Now check for truthiness
if isinstance ( value , ( six . integer_types , float ) ) :
return value > 0
elif isinstance ( v... |
def bna_config_cmd_input_dest ( self , ** kwargs ) :
"""Auto Generated Code""" | config = ET . Element ( "config" )
bna_config_cmd = ET . Element ( "bna_config_cmd" )
config = bna_config_cmd
input = ET . SubElement ( bna_config_cmd , "input" )
dest = ET . SubElement ( input , "dest" )
dest . text = kwargs . pop ( 'dest' )
callback = kwargs . pop ( 'callback' , self . _callback )
return callback ( c... |
def get_byte ( self , i ) :
"""Get byte .""" | value = [ ]
for x in range ( 2 ) :
c = next ( i )
if c . lower ( ) in _HEX :
value . append ( c )
else : # pragma : no cover
raise SyntaxError ( 'Invalid byte character at %d!' % ( i . index - 1 ) )
return '' . join ( value ) |
def newpin ( digits = 4 ) :
"""Return a random numeric string with the specified number of digits ,
default 4.
> > > len ( newpin ( ) )
> > > len ( newpin ( 5 ) )
> > > newpin ( ) . isdigit ( )
True""" | randnum = randint ( 0 , 10 ** digits )
while len ( str ( randnum ) ) > digits :
randnum = randint ( 0 , 10 ** digits )
return ( u'%%0%dd' % digits ) % randnum |
def _calculate_weights ( self , this_samples , N ) :
"""Calculate and save the weights of a run .""" | this_weights = self . weights . append ( N ) [ : , 0 ]
if self . target_values is None :
for i in range ( N ) :
tmp = self . target ( this_samples [ i ] ) - self . proposal . evaluate ( this_samples [ i ] )
this_weights [ i ] = _exp ( tmp )
else :
this_target_values = self . target_values . appe... |
def condition_indices ( df ) :
'''Returns a pandas Series with condition indices of the df columns .
Args :
df : pandas DataFrame with columns to run diagnostics on''' | eigvals = eigenvalues ( df )
cond_idx = np . sqrt ( eigvals . max ( ) / eigvals )
return pd . Series ( cond_idx , df . columns , name = 'Condition index' ) |
def add_cmd_handler ( self , handler_obj ) :
"""Registers a new command handler object .
All methods on ` handler _ obj ` whose name starts with " cmd _ " are
registered as a GTP command . For example , the method cmd _ genmove will
be invoked when the engine receives a genmove command .
Args :
handler _ ... | for field in dir ( handler_obj ) :
if field . startswith ( "cmd_" ) :
cmd = field [ 4 : ]
fn = getattr ( handler_obj , field )
if cmd in self . cmds :
print ( 'Replacing {} with {}' . format ( _handler_name ( self . cmds [ cmd ] ) , _handler_name ( fn ) ) , file = sys . stderr )
... |
def get_job_input ( self , job_id ) :
"""GetJobInput
https : / / apidocs . joyent . com / manta / api . html # GetJobInput
with the added sugar that it will retrieve the archived job if it has
been archived , per :
https : / / apidocs . joyent . com / manta / jobs - reference . html # job - completion - and... | try :
return RawMantaClient . get_job_input ( self , job_id )
except errors . MantaAPIError as ex :
if ex . res . status != 404 :
raise
# Job was archived , try to retrieve the archived data .
mpath = "/%s/jobs/%s/in.txt" % ( self . account , job_id )
content = self . get_object ( mpath )
... |
def export_glb ( scene , extras = None , include_normals = False ) :
"""Export a scene as a binary GLTF ( GLB ) file .
Parameters
scene : trimesh . Scene
Input geometry
extras : JSON serializable
Will be stored in the extras field
include _ normals : bool
Include vertex normals in output file ?
Retu... | # if we were passed a bare Trimesh or Path3D object
if not util . is_instance_named ( scene , "Scene" ) and hasattr ( scene , "scene" ) : # generate a scene with just that mesh in it
scene = scene . scene ( )
tree , buffer_items = _create_gltf_structure ( scene = scene , extras = extras , include_normals = include_... |
def percentile ( self , percentile ) :
"""Calculate a given spectral percentile for this ` Spectrogram ` .
Parameters
percentile : ` float `
percentile ( 0 - 100 ) of the bins to compute
Returns
spectrum : ` ~ gwpy . frequencyseries . FrequencySeries `
the given percentile ` FrequencySeries ` calculated... | out = scipy . percentile ( self . value , percentile , axis = 0 )
if self . name is not None :
name = '{}: {} percentile' . format ( self . name , _ordinal ( percentile ) )
else :
name = None
return FrequencySeries ( out , epoch = self . epoch , channel = self . channel , name = name , f0 = self . f0 , df = sel... |
def set_scene_name ( self , scene_id , name ) :
"""rename a scene by scene ID""" | if not scene_id in self . state . scenes : # does that scene _ id exist ?
err_msg = "Requested to rename scene {sceneNum}, which does not exist" . format ( sceneNum = scene_id )
logging . info ( err_msg )
return ( False , 0 , err_msg )
self . state . scenes [ scene_id ] = self . state . scenes [ scene_id ] ... |
def import_laid_out_tensor ( mesh , laid_out_tensor , shape , name = None ) :
"""Import a laid _ out _ tensor .
For expert users .
The input must be laid out appropriately given the eventual MeshImpl ,
and layout .
Args :
mesh : a Mesh
laid _ out _ tensor : a LaidOutTensor
shape : a mtf . Shape
name... | return ImportLaidOutTensorOperation ( mesh , laid_out_tensor , convert_to_shape ( shape ) , name = name ) . outputs [ 0 ] |
def _parse_textgroup ( self , cts_file ) :
"""Parses a textgroup from a cts file
: param cts _ file : Path to the CTS File
: type cts _ file : str
: return : CtsTextgroupMetadata and Current file""" | with io . open ( cts_file ) as __xml__ :
return self . classes [ "textgroup" ] . parse ( resource = __xml__ ) , cts_file |
def psql ( self , * psqlargs ) :
"""Run a psql command""" | db , env = self . get_db_args_env ( )
args = [ '-v' , 'ON_ERROR_STOP=on' , '-d' , db [ 'name' ] , '-h' , db [ 'host' ] , '-U' , db [ 'user' ] , '-w' , '-A' , '-t' ] + list ( psqlargs )
stdout , stderr = External . run ( 'psql' , args , capturestd = True , env = env )
if stderr :
log . warn ( 'stderr: %s' , stderr )... |
def migrate_secret_key ( old_key ) :
"""Call entry points exposed for the SECRET _ KEY change .""" | if 'SECRET_KEY' not in current_app . config or current_app . config [ 'SECRET_KEY' ] is None :
raise click . ClickException ( 'SECRET_KEY is not set in the configuration.' )
for ep in iter_entry_points ( 'invenio_base.secret_key' ) :
try :
ep . load ( ) ( old_key = old_key )
except Exception :
... |
def modify_identity ( self , identity , ** kwargs ) :
"""Modify some attributes of an identity or its name .
: param : identity a zobjects . Identity with ` id ` set ( mandatory ) . Also
set items you want to modify / set and / or the ` name ` attribute to
rename the identity .
Can also take the name in str... | if isinstance ( identity , zobjects . Identity ) :
self . request ( 'ModifyIdentity' , { 'identity' : identity . _full_data } )
return self . get_identities ( identity = identity . name ) [ 0 ]
else :
attrs = [ ]
for attr , value in kwargs . items ( ) :
attrs . append ( { 'name' : attr , '_conte... |
def Jacobian_re_im ( self , pars ) :
r""": math : ` J `
> > > import sip _ models . res . cc as cc
> > > import numpy as np
> > > f = np . logspace ( - 3 , 3 , 20)
> > > pars = [ 100 , 0.1 , 0.04 , 0.8]
> > > obj = cc . cc ( f )
> > > J = obj . Jacobian _ re _ im ( pars )""" | partials = [ ]
# partials . append ( self . dre _ dlog10rho0 ( pars ) [ : , np . newaxis , : ] )
partials . append ( self . dre_drho0 ( pars ) [ : , np . newaxis ] )
partials . append ( self . dre_dm ( pars ) )
# partials . append ( self . dre _ dlog10tau ( pars ) )
partials . append ( self . dre_dtau ( pars ) )
partia... |
def DEFINE_flag ( flag , flag_values = _flagvalues . FLAGS , module_name = None ) : # pylint : disable = invalid - name
"""Registers a ' Flag ' object with a ' FlagValues ' object .
By default , the global FLAGS ' FlagValue ' object is used .
Typical users will use one of the more specialized DEFINE _ xxx
fun... | # Copying the reference to flag _ values prevents pychecker warnings .
fv = flag_values
fv [ flag . name ] = flag
# Tell flag _ values who ' s defining the flag .
if module_name :
module = sys . modules . get ( module_name )
else :
module , module_name = _helpers . get_calling_module_object_and_name ( )
flag_va... |
def main ( ) :
"""Command line entry point .""" | def help_exit ( ) :
raise SystemExit ( "usage: ddate [day] [month] [year]" )
if "--help" in sys . argv or "-h" in sys . argv :
help_exit ( )
if len ( sys . argv ) == 2 : # allow for 23-2-2014 style , be lazy / sloppy with it
for split_char in ".-/`,:;" : # who knows what the human will use . . .
if ... |
def _map_content_types ( archetype_tool , catalogs_definition ) :
"""Updates the mapping for content _ types against catalogs
: archetype _ tool : an archetype _ tool object
: catalogs _ definition : a dictionary like
CATALOG _ ID : {
' types ' : [ ' ContentType ' , . . . ] ,
' indexes ' : {
' UID ' : '... | # This will be a dictionari like { ' content _ type ' : [ ' catalog _ id ' , . . . ] }
ct_map = { }
# This list will contain the atalog ids to be rebuild
to_reindex = [ ]
# getting the dictionary of mapped content _ types in the catalog
map_types = archetype_tool . catalog_map
for catalog_id in catalogs_definition . ke... |
def _filter_seqs ( fn ) :
"""Convert names of sequences to unique ids""" | out_file = op . splitext ( fn ) [ 0 ] + "_unique.fa"
idx = 0
if not file_exists ( out_file ) :
with open ( out_file , 'w' ) as out_handle :
with open ( fn ) as in_handle :
for line in in_handle :
if line . startswith ( "@" ) or line . startswith ( ">" ) :
fixe... |
def modify ( self , sort = None , purge = False , done = None , undone = None ) :
"""Handles the ' m ' command .
: sort : Sort pattern .
: purge : Whether to purge items marked as ' done ' .
: done : Done pattern .
: undone : Not done pattern .""" | self . model . modifyInPlace ( sort = self . _getPattern ( sort ) , purge = purge , done = self . _getDone ( done , undone ) ) |
def isPositiveMap ( self ) :
"""Returns true if increasing ra increases pix in skyToPix ( )""" | x0 , y0 = self . skyToPix ( self . ra0_deg , self . dec0_deg )
x1 , y1 = self . skyToPix ( self . ra0_deg + 1 / 3600. , self . dec0_deg )
if x1 > x0 :
return True
return False |
def new_topic ( self , title , content ) :
"""小组发贴
: return : 帖子 id 或 ` ` None ` `""" | data = { 'title' : title , 'body' : content , 'csrfmiddlewaretoken' : self . _request . cookies . get ( 'csrftoken' ) }
url = 'http://www.shanbay.com/api/v1/forum/%s/thread/' % self . forum_id ( )
r = self . request ( url , 'post' , data = data )
j = r . json ( )
if j [ 'status_code' ] == 0 :
return j [ 'data' ] [ ... |
def clearkml ( self ) :
'''Clear the kmls from the map''' | # go through all the current layers and remove them
for layer in self . curlayers :
self . mpstate . map . remove_object ( layer )
for layer in self . curtextlayers :
self . mpstate . map . remove_object ( layer )
self . allayers = [ ]
self . curlayers = [ ]
self . alltextlayers = [ ]
self . curtextlayers = [ ]... |
def url_tibiadata ( self ) :
""": class : ` str ` : The URL to the highscores page on TibiaData . com containing the results .""" | return self . get_url_tibiadata ( self . world , self . category , self . vocation ) |
def get_prior_alignment ( self ) :
"""Return the prior alignment that was used for 2D basecalling .
: return : Alignment data table .""" | data_group = '{}/HairpinAlign' . format ( self . group_name )
data = self . handle . get_analysis_dataset ( data_group , 'Alignment' )
return data |
def check_file_exists ( self , remote_cmd = "" ) :
"""Check if the dest _ file already exists on the file system ( return boolean ) .""" | if self . direction == "put" :
if not remote_cmd :
remote_cmd = "dir {}{}" . format ( self . file_system , self . dest_file )
remote_out = self . ssh_ctl_chan . send_command_expect ( remote_cmd )
search_string = r"{}.*Usage for" . format ( self . dest_file )
if "No such file or directory" in rem... |
def h_function ( self , x , xsquare ) :
"""Computes the h - function as defined in Paillier ' s paper page 12,
' Decryption using Chinese - remaindering ' .""" | return invert ( self . l_function ( powmod ( self . public_key . g , x - 1 , xsquare ) , x ) , x ) |
def _todict ( cls ) :
"""generate a dict keyed by value""" | return dict ( ( getattr ( cls , attr ) , attr ) for attr in dir ( cls ) if not attr . startswith ( '_' ) ) |
def idle_task ( self ) :
'''called rapidly by mavproxy''' | if self . downloaders_lock . acquire ( False ) :
removed_one = False
for url in self . downloaders . keys ( ) :
if not self . downloaders [ url ] . is_alive ( ) :
print ( "fw: Download thread for (%s) done" % url )
del self . downloaders [ url ]
removed_one = True
... |
def get_number ( self ) :
'''. . versionchanged : : 0.9.2
Add support for float exponent strings ( e . g . , ` ` 3.435e - 7 ` ` ) .
Fixes ` issue # 4 < https : / / github . com / wheeler - microfluidics / svg - model / issues / 4 > ` .''' | number = None
start = self . get_char ( '0123456789.-' )
if start :
number = start
finish = self . get_chars ( '-e0123456789.' )
if finish :
number += finish
if any ( c in number for c in '.e' ) :
return float ( number )
else :
return int ( number ) |
def total_length ( self ) :
"""Returns the total length of the captions .""" | if not self . _captions :
return 0
return int ( self . _captions [ - 1 ] . end_in_seconds ) - int ( self . _captions [ 0 ] . start_in_seconds ) |
def worker ( f ) :
"""Generic wrapper to log uncaught exceptions in a function .
When we cross concurrent . futures executor boundaries we lose our
traceback information , and when doing bulk operations we may tolerate
transient failures on a partial subset . However we still want to have
full accounting of... | def _f ( * args , ** kw ) :
try :
return f ( * args , ** kw )
except Exception :
worker_log . exception ( 'Error invoking %s' , "%s.%s" % ( f . __module__ , f . __name__ ) )
raise
functools . update_wrapper ( _f , f )
return _f |
def sg_max ( tensor , opt ) :
r"""Computes the maximum of elements across axis of a tensor .
See ` tf . reduce _ max ( ) ` in tensorflow .
Args :
tensor : A ` Tensor ` ( automatically given by chain ) .
opt :
axis : A tuple / list of integers or an integer . The axis to reduce .
keep _ dims : If true , ... | return tf . reduce_max ( tensor , axis = opt . axis , keep_dims = opt . keep_dims , name = opt . name ) |
def _process_stream_delta ( self , delta_stream ) :
"""Bookkeeping on internal data structures while iterating a stream .""" | for pchange in delta_stream :
if pchange . kind == ChangeType . ADD :
self . policy_files . setdefault ( pchange . file_path , PolicyCollection ( ) ) . add ( pchange . policy )
elif pchange . kind == ChangeType . REMOVE :
self . policy_files [ pchange . file_path ] . remove ( pchange . policy )
... |
def _open_icmp_socket ( self , family ) :
"""Opens a socket suitable for sending / receiving ICMP echo
requests / responses .""" | try :
proto = socket . IPPROTO_ICMP if family == socket . AF_INET else _IPPROTO_ICMPV6
return socket . socket ( family , socket . SOCK_RAW , proto )
except socket . error as e :
if e . errno == 1 :
raise MultiPingError ( "Root privileges required for sending " "ICMP" )
# Re - raise any other err... |
def search ( self , text , limit = 1000 , order_by = None , sort_order = None , filter = None ) :
"""Do a fulltext search for series in the Fred dataset . Returns information about matching series in a DataFrame .
Parameters
text : str
text to do fulltext search on , e . g . , ' Real GDP '
limit : int , opt... | url = "%s/series/search?search_text=%s&" % ( self . root_url , quote_plus ( text ) )
info = self . __get_search_results ( url , limit , order_by , sort_order , filter )
return info |
def user_present ( name , uid , password , channel = 14 , callback = False , link_auth = True , ipmi_msg = True , privilege_level = 'administrator' , ** kwargs ) :
'''Ensure IPMI user and user privileges .
name
name of user ( limit 16 bytes )
uid
user id number ( 1 to 7)
password
user password ( limit 1... | ret = { 'name' : name , 'result' : False , 'comment' : '' , 'changes' : { } }
org_user = __salt__ [ 'ipmi.get_user' ] ( uid = uid , channel = channel , ** kwargs )
change = False
if org_user [ 'access' ] [ 'callback' ] != callback :
change = True
if org_user [ 'access' ] [ 'link_auth' ] != link_auth :
change = ... |
def end_headers ( self ) :
"""Send the blank line ending the MIME headers .""" | if self . request_version != 'HTTP/0.9' :
self . _headers_buffer . append ( b"\r\n" )
self . flush_headers ( ) |
def get_unique_scan_parameter_combinations ( meta_data_array , scan_parameters = None , scan_parameter_columns_only = False ) :
'''Takes the numpy meta data array and returns the first rows with unique combinations of different scan parameter values for selected scan parameters .
If selected columns only is true ... | try :
last_not_parameter_column = meta_data_array . dtype . names . index ( 'error_code' )
# for interpreted meta _ data
except ValueError :
last_not_parameter_column = meta_data_array . dtype . names . index ( 'error' )
# for raw data file meta _ data
if last_not_parameter_column == len ( meta_data_arr... |
def random ( self ) :
"""Returns a random value that fits this column ' s parameters .
: return : < variant >""" | minimum = self . minimum ( ) or 0
maximum = self . maximum ( ) or 100
return random . randint ( minimum , maximum ) |
def to_csv ( self , path , mode = WRITE_MODE , dialect = 'excel' , compression = None , newline = '' , ** fmtparams ) :
"""Saves the sequence to a csv file . Each element should be an iterable which will be expanded
to the elements of each row .
: param path : path to write file
: param mode : file open mode ... | if 'b' in mode :
newline = None
with universal_write_open ( path , mode = mode , compression = compression , newline = newline ) as output :
csv_writer = csv . writer ( output , dialect = dialect , ** fmtparams )
for row in self :
csv_writer . writerow ( [ six . u ( str ( element ) ) for element in ... |
def plot_ARD ( kernel , filtering = None , legend = False , canvas = None , ** kwargs ) :
"""If an ARD kernel is present , plot a bar representation using matplotlib
: param fignum : figure number of the plot
: param filtering : list of names , which to use for plotting ARD parameters .
Only kernels which mat... | Tango . reset ( )
ard_params = np . atleast_2d ( kernel . input_sensitivity ( summarize = False ) )
bottom = 0
last_bottom = bottom
x = np . arange ( kernel . _effective_input_dim )
parts = [ ]
def visit ( x ) :
if ( not isinstance ( x , CombinationKernel ) ) and isinstance ( x , Kern ) :
parts . append ( x... |
def send_location ( self , number , name , url , latitude , longitude ) :
"""Send location message
: param str number : phone number with cc ( country code )
: param str name : indentifier for the location
: param str url : location url
: param str longitude : location longitude
: param str latitude : loc... | location_message = LocationMediaMessageProtocolEntity ( latitude , longitude , name , url , encoding = "raw" , to = self . normalize_jid ( number ) )
self . toLower ( location_message )
return location_message |
def _load_certificate ( location ) :
"""Load a certificate from the given location .
Args :
location ( str ) : The location to load . This can either be an HTTPS URL or an absolute file
path . This is intended to be used with PEM - encoded certificates and therefore assumes
ASCII encoding .
Returns :
st... | if location . startswith ( 'https://' ) :
_log . info ( 'Downloading x509 certificate from %s' , location )
with requests . Session ( ) as session :
session . mount ( 'https://' , requests . adapters . HTTPAdapter ( max_retries = 3 ) )
response = session . get ( location , timeout = 30 )
... |
def UpgradeReferenceFields ( ) :
"""Convert all ReferenceField ' s values into UIDReferenceFields .
These are not touched : HistoryAware to be removed :
- Analysis . Calculation : HistoryAwareReferenceField ( rel =
AnalysisCalculation )
- DuplicateAnalysis . Calculation : HistoryAwareReferenceField ( rel = ... | # Change these carefully
# they were made slowly with love
# still they may be wrong .
for portal_type , fields in [ # portal _ type
[ 'ARReport' , [ ( 'AnalysisRequest' , 'ARReportAnalysisRequest' ) ] ] , [ 'Analysis' , [ # AbstractBaseAnalysis
( 'Category' , 'AnalysisCategory' ) , ( 'Department' , 'AnalysisDepartment... |
def get_value ( self , sid , dt , field ) :
"""Retrieve the value at the given coordinates .
Parameters
sid : int
The asset identifier .
dt : pd . Timestamp
The timestamp for the desired data point .
field : string
The OHLVC name for the desired data point .
Returns
value : float | int
The value... | try :
country_code = self . _country_code_for_assets ( [ sid ] )
except ValueError as exc :
raise_from ( NoDataForSid ( 'Asset not contained in daily pricing file: {}' . format ( sid ) ) , exc )
return self . _readers [ country_code ] . get_value ( sid , dt , field ) |
def get_container_data ( self ) :
"""Returns a list of Container data""" | for obj in self . get_containers ( ) :
info = self . get_base_info ( obj )
yield info |
def decode_data ( response_content , data_type , entire_response = None ) :
"""Interprets downloaded data and returns it .
: param response _ content : downloaded data ( i . e . json , png , tiff , xml , zip , . . . file )
: type response _ content : bytes
: param data _ type : expected downloaded data type
... | LOGGER . debug ( 'data_type=%s' , data_type )
if data_type is MimeType . JSON :
if isinstance ( entire_response , requests . Response ) :
return entire_response . json ( )
return json . loads ( response_content . decode ( 'utf-8' ) )
if MimeType . is_image_format ( data_type ) :
return decode_image ... |
def insertDict ( self , tblname , d , fields = None ) :
'''Simple function for inserting a dictionary whose keys match the fieldnames of tblname .''' | if fields == None :
fields = sorted ( d . keys ( ) )
values = None
try :
SQL = 'INSERT INTO %s (%s) VALUES (%s)' % ( tblname , join ( fields , ", " ) , join ( [ '%s' for x in range ( len ( fields ) ) ] , ',' ) )
values = tuple ( [ d [ k ] for k in fields ] )
self . locked_execute ( SQL , parameters = va... |
def _find_or_create_version ( self , product ) :
"""Create a Version in MetaDeploy if it doesn ' t already exist""" | tag = self . options [ "tag" ]
label = self . project_config . get_version_for_tag ( tag )
result = self . _call_api ( "GET" , "/versions" , params = { "product" : product [ "id" ] , "label" : label } )
if len ( result [ "data" ] ) == 0 :
version = self . _call_api ( "POST" , "/versions" , json = { "product" : prod... |
def real_main ( start_url = None , ignore_prefixes = None , upload_build_id = None , upload_release_name = None ) :
"""Runs the site _ diff .""" | coordinator = workers . get_coordinator ( )
fetch_worker . register ( coordinator )
coordinator . start ( )
item = SiteDiff ( start_url = start_url , ignore_prefixes = ignore_prefixes , upload_build_id = upload_build_id , upload_release_name = upload_release_name , heartbeat = workers . PrintWorkflow )
item . root = Tr... |
def do_thaw ( client , args ) :
"""Execute the thaw operation , pulling in an actual Vault
client if neccesary""" | vault_client = None
if args . gpg_pass_path :
vault_client = client . connect ( args )
aomi . filez . thaw ( vault_client , args . icefile , args )
sys . exit ( 0 ) |
def file_handles ( self ) -> Iterable [ IO [ str ] ] :
"""Generates all file handles represented by the analysis .
Callee owns file handle and closes it when the next is yielded or the
generator ends .""" | if self . file_handle :
yield self . file_handle
self . file_handle . close ( )
self . file_handle = None
else :
for name in self . file_names ( ) :
with open ( name , "r" ) as f :
yield f |
def build_query_string ( self , data ) :
"""This method occurs after dumping the data into the class .
Args :
data ( dict ) : dictionary of all the query values
Returns :
data ( dict ) : ordered dict of all the values""" | query = [ ]
keys_to_be_removed = [ ]
for key , value in data . items ( ) :
if key not in [ 'version' , 'restApi' , 'resourcePath' ] :
if not key == 'method' :
if key == 'points' :
value = ',' . join ( str ( val ) for val in value )
keys_to_be_removed . append ( ke... |
def reinit_on_backend_changes ( tf_bin , # pylint : disable = too - many - arguments
module_path , backend_options , env_name , env_region , env_vars ) :
"""Clean terraform directory and run init if necessary .
If deploying a TF module to multiple regions ( or any scenario requiring
multiple backend configs ) ,... | terraform_dir = os . path . join ( module_path , '.terraform' )
local_tfstate_path = os . path . join ( terraform_dir , 'terraform.tfstate' )
current_backend_config = { }
desired_backend_config = { }
LOGGER . debug ( 'Comparing previous & desired Terraform backend configs' )
if os . path . isfile ( local_tfstate_path )... |
def cdata ( self , data ) :
"""Print HTML cdata .
@ param data : the character data
@ type data : string
@ return : None""" | data = data . encode ( self . encoding , "ignore" )
self . fd . write ( "<![CDATA[%s]]>" % data ) |
def ExportClientsByKeywords ( keywords , filename , token = None ) :
r"""A script to export clients summaries selected by a keyword search .
This script does a client search for machines matching all of keywords and
writes a . csv summary of the results to filename . Multi - value fields are ' \ n '
separated... | index = client_index . CreateClientIndex ( token = token )
client_list = index . LookupClients ( keywords )
logging . info ( "found %d clients" , len ( client_list ) )
if not client_list :
return
writer = csv . DictWriter ( [ u"client_id" , u"hostname" , u"last_seen" , u"os" , u"os_release" , u"os_version" , u"user... |
def activatePdpContextRequest ( AccessPointName_presence = 0 , ProtocolConfigurationOptions_presence = 0 ) :
"""ACTIVATE PDP CONTEXT REQUEST Section 9.5.1""" | a = TpPd ( pd = 0x8 )
b = MessageType ( mesType = 0x41 )
# 01000001
c = NetworkServiceAccessPointIdentifier ( )
d = LlcServiceAccessPointIdentifier ( )
e = QualityOfService ( )
f = PacketDataProtocolAddress ( )
packet = a / b / c / d / e / f
if AccessPointName_presence is 1 :
g = AccessPointName ( ieiAPN = 0x28 )
... |
def addStep ( self , key ) :
"""Add information about a new step to the dict of steps
The value ' ptime ' is the output from ' _ ptime ( ) ' containing
both the formatted and unformatted time for the start of the
step .""" | ptime = _ptime ( )
print ( '==== Processing Step ' , key , ' started at ' , ptime [ 0 ] )
self . steps [ key ] = { 'start' : ptime }
self . order . append ( key ) |
def try_printout ( data , out , opts , ** kwargs ) :
'''Safely get the string to print out , try the configured outputter , then
fall back to nested and then to raw''' | try :
printout = get_printout ( out , opts ) ( data , ** kwargs )
if printout is not None :
return printout . rstrip ( )
except ( KeyError , AttributeError , TypeError ) :
log . debug ( traceback . format_exc ( ) )
try :
printout = get_printout ( 'nested' , opts ) ( data , ** kwargs )
... |
def _get_db_password ( dbSystem , db , user ) :
"""Read through the users . dbrc file to get password for the db / user
combination suplied . If no password is found then prompt for one""" | import string , getpass , os
dbrc = os . environ [ 'HOME' ] + "/.dbrc"
password = { }
if os . access ( dbrc , os . R_OK ) :
fd = open ( dbrc )
lines = fd . readlines ( )
for line in lines :
entry = line . split ( )
if entry [ 0 ] == dbSystem and entry [ 1 ] == db and entry [ 2 ] == user :
... |
def find ( self , _limit = None , _offset = 0 , _step = 5000 , order_by = "id" , return_count = False , ** _filter ) :
"""Performs a simple search on the table . Simply pass keyword arguments as ` ` filter ` ` .
results = table . find ( country = ' France ' )
results = table . find ( country = ' France ' , year... | self . _check_dropped ( )
if not isinstance ( order_by , ( list , tuple ) ) :
order_by = [ order_by ]
order_by = [ o for o in order_by if ( o . startswith ( "-" ) and o [ 1 : ] or o ) in self . table . columns ]
order_by = [ self . _args_to_order_by ( o ) for o in order_by ]
args = self . _args_to_clause ( _filter ... |
def casefold ( s , fullcasefold = True , useturkicmapping = False ) :
"""Function for performing case folding . This function will take the input
string s and return a copy of the string suitable for caseless comparisons .
The input string must be of type ' unicode ' , otherwise a TypeError will be
raised .
... | if not isinstance ( s , six . text_type ) :
raise TypeError ( u"String to casefold must be of type 'unicode'!" )
lookup_order = "CF"
if not fullcasefold :
lookup_order = "CS"
if useturkicmapping :
lookup_order = "T" + lookup_order
return u"" . join ( [ casefold_map . lookup ( c , lookup_order = lookup_order... |
def open ( cls , path ) :
"""Load an image file into a PIX object .
Leptonica can load TIFF , PNM ( PBM , PGM , PPM ) , PNG , and JPEG . If
loading fails then the object will wrap a C null pointer .""" | filename = fspath ( path )
with _LeptonicaErrorTrap ( ) :
return cls ( lept . pixRead ( os . fsencode ( filename ) ) ) |
def pandoc ( script = None , input = None , output = None , args = '{input:q} --output {output:q}' , ** kwargs ) :
'''Convert input file to output using pandoc
The input can be specified in three ways :
1 . instant script , which is assumed to be in md format
pandoc : output = ' report . html '
script
2 .... | # # this is output format
# pandoc [ OPTIONS ] [ FILES ]
# Input formats : commonmark , docbook , docx , epub , haddock , html , json * , latex ,
# markdown , markdown _ github , markdown _ mmd , markdown _ phpextra ,
# markdown _ strict , mediawiki , native , odt , opml , org , rst , t2t ,
# textile , twiki
# [ * only... |
def write ( self ) :
"""Write csv file of resolved names and txt file of unresolved names .""" | csv_file = os . path . join ( self . outdir , 'search_results.csv' )
txt_file = os . path . join ( self . outdir , 'unresolved.txt' )
headers = self . key_terms
unresolved = [ ]
with open ( csv_file , 'w' ) as file :
writer = csv . writer ( file )
writer . writerow ( headers )
for key in list ( self . _stor... |
def whitespace_around_operator ( logical_line ) :
r"""Avoid extraneous whitespace around an operator .
Okay : a = 12 + 3
E221 : a = 4 + 5
E222 : a = 4 + 5
E223 : a = 4 \ t + 5
E224 : a = 4 + \ t5""" | for match in OPERATOR_REGEX . finditer ( logical_line ) :
before , after = match . groups ( )
if '\t' in before :
yield match . start ( 1 ) , "E223 tab before operator"
elif len ( before ) > 1 :
yield match . start ( 1 ) , "E221 multiple spaces before operator"
if '\t' in after :
... |
def open ( self , data_source , * args , ** kwargs ) :
"""Open filename to get data for data _ source .
: param data _ source : Data source for which the file contains data .
: type data _ source : str
Positional and keyword arguments can contain either the data to use for
the data source or the full path o... | if self . sources [ data_source ] . _meta . data_reader . is_file_reader :
filename = kwargs . get ( 'filename' )
path = kwargs . get ( 'path' , '' )
rel_path = kwargs . get ( 'rel_path' , '' )
if len ( args ) > 0 :
filename = args [ 0 ]
if len ( args ) > 1 :
path = args [ 1 ]
if... |
def queue_context_entry ( exchange , queue_name , routing = None ) :
"""forms queue ' s context entry""" | if routing is None :
routing = queue_name
queue_entry = QueueContextEntry ( mq_queue = queue_name , mq_exchange = exchange , mq_routing_key = routing )
return queue_entry |
def basis_functions ( degree , knot_vector , spans , knots ) :
"""Computes the non - vanishing basis functions for a list of parameters .
: param degree : degree , : math : ` p `
: type degree : int
: param knot _ vector : knot vector , : math : ` U `
: type knot _ vector : list , tuple
: param spans : li... | basis = [ ]
for span , knot in zip ( spans , knots ) :
basis . append ( basis_function ( degree , knot_vector , span , knot ) )
return basis |
def syllabify ( word ) :
'''Syllabify the given word , whether simplex or complex .''' | compound = not word . isalpha ( )
syllabify = _syllabify_complex if compound else _syllabify_simplex
syllabifications = list ( syllabify ( word ) )
# if variation , order variants from most preferred to least preferred
if len ( syllabifications ) > 1 :
syllabifications = rank ( syllabifications )
for word , rules i... |
def extract_function_metadata ( wrapped , instance , args , kwargs , return_value ) :
"""Stash the ` args ` and ` kwargs ` into the metadata of the subsegment .""" | LOGGER . debug ( 'Extracting function call metadata' , args = args , kwargs = kwargs , )
return { 'metadata' : { 'args' : args , 'kwargs' : kwargs , } , } |
def index_layer ( self , layer_id , use_cache = False ) :
"""Index a layer in the search backend .
If cache is set , append it to the list , if it isn ' t send the transaction right away .
cache needs memcached to be available .""" | from hypermap . aggregator . models import Layer
layer = Layer . objects . get ( id = layer_id )
if not layer . is_valid :
LOGGER . debug ( 'Not indexing or removing layer with id %s in search engine as it is not valid' % layer . id )
unindex_layer ( layer . id , use_cache )
return
if layer . was_deleted :
... |
def log_to_file ( logdir , mode = 'a' , delete = False , clearmem = True ) :
"""Like : class : ` log _ to ( ) ` , but automatically creates a new FileLogger
instead of having one passed .
Note that the logger stays alive ( in memory ) forever . If you need
to control the lifetime of a logger , use : class : `... | logger = FileLogger ( logdir , mode , delete , clearmem )
_loggers . append ( logger )
return log_to ( logger ) |
def get_track_info ( track_id ) :
"""Fetches track info from Soundcloud , given a track _ id""" | logger . info ( 'Retrieving more info on the track' )
info_url = url [ "trackinfo" ] . format ( track_id )
r = requests . get ( info_url , params = { 'client_id' : CLIENT_ID } , stream = True )
item = r . json ( )
logger . debug ( item )
return item |
def _set_ipv6_routes ( self , v , load = False ) :
"""Setter method for ipv6 _ routes , mapped from YANG variable / isis _ state / ipv6 _ routes ( container )
If this variable is read - only ( config : false ) in the
source YANG file , then _ set _ ipv6 _ routes is considered as a private
method . Backends lo... | if hasattr ( v , "_utype" ) :
v = v . _utype ( v )
try :
t = YANGDynClass ( v , base = ipv6_routes . ipv6_routes , is_container = 'container' , presence = False , yang_name = "ipv6-routes" , rest_name = "ipv6-routes" , parent = self , path_helper = self . _path_helper , extmethods = self . _extmethods , registe... |
def get_appapi_params ( self , prepay_id , timestamp = None , nonce_str = None ) :
"""获取 APP 支付参数
: param prepay _ id : 统一下单接口返回的 prepay _ id 参数值
: param timestamp : 可选 , 时间戳 , 默认为当前时间戳
: param nonce _ str : 可选 , 随机字符串 , 默认自动生成
: return : 签名""" | data = { 'appid' : self . appid , 'partnerid' : self . mch_id , 'prepayid' : prepay_id , 'package' : 'Sign=WXPay' , 'timestamp' : timestamp or to_text ( int ( time . time ( ) ) ) , 'noncestr' : nonce_str or random_string ( 32 ) }
sign = calculate_signature ( data , self . _client . api_key )
data [ 'sign' ] = sign
retu... |
def find_column ( t ) :
"""Get cursor position , based on previous newline""" | pos = t . lexer . lexpos
data = t . lexer . lexdata
last_cr = data . rfind ( '\n' , 0 , pos )
if last_cr < 0 :
last_cr = - 1
column = pos - last_cr
return column |
def AddPerformanceOptions ( self , argument_group ) :
"""Adds the performance options to the argument group .
Args :
argument _ group ( argparse . _ ArgumentGroup ) : argparse argument group .""" | argument_group . add_argument ( '--buffer_size' , '--buffer-size' , '--bs' , dest = 'buffer_size' , action = 'store' , default = 0 , help = ( 'The buffer size for the output (defaults to 196MiB).' ) )
argument_group . add_argument ( '--queue_size' , '--queue-size' , dest = 'queue_size' , action = 'store' , default = 0 ... |
def get_mutation ( self , stage , data ) :
'''Get the next mutation , if in the correct stage
: param stage : current stage of the stack
: param data : a dictionary of items to pass to the model
: return : mutated payload if in apropriate stage , None otherwise''' | payload = None
# Commented out for now : we want to return the same
# payload - while inside the same test
# if self . _ keep _ running ( ) and self . _ do _ fuzz . is _ set ( ) :
if self . _keep_running ( ) :
fuzz_node = self . _fuzz_path [ self . _index_in_path ] . dst
if self . _should_fuzz_node ( fuzz_node ... |
def dvnorm ( state ) :
"""Function to calculate the derivative of the norm of a 3 - vector .
http : / / naif . jpl . nasa . gov / pub / naif / toolkit _ docs / C / cspice / dvnorm _ c . html
: param state :
A 6 - vector composed of three coordinates and their derivatives .
: type state : 6 - Element Array o... | assert len ( state ) is 6
state = stypes . toDoubleVector ( state )
return libspice . dvnorm_c ( state ) |
def _do_customer_service ( self ) :
"""This method is called before the shutdown of the scheduler .
If customer _ service is on and the flow didn ' t completed successfully ,
a lightweight tarball file with inputs and the most important output files
is created in customer _ servide _ dir .""" | if self . customer_service_dir is None :
return
doit = self . exceptions or not self . flow . all_ok
doit = True
if not doit :
return
prefix = os . path . basename ( self . flow . workdir ) + "_"
import tempfile , datetime
suffix = str ( datetime . datetime . now ( ) ) . replace ( " " , "-" )
# Remove milliseco... |
def almost_identity ( gate : Gate ) -> bool :
"""Return true if gate tensor is ( almost ) the identity""" | N = gate . qubit_nb
return np . allclose ( asarray ( gate . asoperator ( ) ) , np . eye ( 2 ** N ) ) |
def sort_dict_by_key ( obj ) :
"""Sort dict by its keys
> > > sort _ dict _ by _ key ( dict ( c = 1 , b = 2 , a = 3 , d = 4 ) )
OrderedDict ( [ ( ' a ' , 3 ) , ( ' b ' , 2 ) , ( ' c ' , 1 ) , ( ' d ' , 4 ) ] )""" | sort_func = lambda x : x [ 0 ]
return OrderedDict ( sorted ( obj . items ( ) , key = sort_func ) ) |
def load_dataset ( dataset_key , force_update = False , auto_update = False , profile = 'default' , ** kwargs ) :
"""Load a dataset from the local filesystem , downloading it from data . world
first , if necessary .
This function returns an object of type ` LocalDataset ` . The object
allows access to metedat... | return _get_instance ( profile , ** kwargs ) . load_dataset ( dataset_key , force_update = force_update , auto_update = auto_update ) |
def get_by_name ( self , name : str ) -> List [ Account ] :
"""Searches accounts by name""" | # return self . query . filter ( Account . name = = name ) . all ( )
return self . get_by_name_from ( self . book . root , name ) |
def add_batch_parser ( subparsers , parent_parser ) :
"""Adds arguments parsers for the batch list , batch show and batch status
commands
Args :
subparsers : Add parsers to this subparser object
parent _ parser : The parent argparse . ArgumentParser object""" | parser = subparsers . add_parser ( 'batch' , help = 'Displays information about batches and submit new batches' , description = 'Provides subcommands to display Batch information and ' 'submit Batches to the validator via the REST API.' )
grand_parsers = parser . add_subparsers ( title = 'subcommands' , dest = 'subcomm... |
def getCachedDataKey ( engineVersionHash , key ) :
"""Retrieves the cached data value for the specified engine version hash and dictionary key""" | cacheFile = CachedDataManager . _cacheFileForHash ( engineVersionHash )
return JsonDataManager ( cacheFile ) . getKey ( key ) |
def send_email ( sender , receivers , subject , text = None , html = None , charset = 'utf-8' , config = Injected ) :
"""Sends an email .
: param sender : Sender as string or None for default got from config .
: param receivers : String or array of recipients .
: param subject : Subject .
: param text : Pla... | smtp_config = config [ 'SMTP' ]
# Receivers must be an array .
if not isinstance ( receivers , list ) and not isinstance ( receivers , tuple ) :
receivers = [ receivers ]
# Create the messages
msgs = [ ]
if text is not None :
msgs . append ( MIMEText ( text , 'plain' , charset ) )
if html is not None :
msgs... |
def search_reference_sets ( self , accession = None , md5checksum = None , assembly_id = None ) :
"""Returns an iterator over the ReferenceSets fulfilling the specified
conditions .
: param str accession : If not null , return the reference sets for which
the ` accession ` matches this string ( case - sensiti... | request = protocol . SearchReferenceSetsRequest ( )
request . accession = pb . string ( accession )
request . md5checksum = pb . string ( md5checksum )
request . assembly_id = pb . string ( assembly_id )
request . page_size = pb . int ( self . _page_size )
return self . _run_search_request ( request , "referencesets" ,... |
def render_impl ( template_file , ctx = None , paths = None , filters = None ) :
""": param template _ file : Absolute or relative path to the template file
: param ctx : Context dict needed to instantiate templates
: param filters : Custom filters to add into template engine
: return : Compiled result ( str ... | env = tmpl_env ( make_template_paths ( template_file , paths ) )
if env is None :
return copen ( template_file ) . read ( )
if filters is not None :
env . filters . update ( filters )
if ctx is None :
ctx = { }
return env . get_template ( os . path . basename ( template_file ) ) . render ( ** ctx ) |
def producer ( id , message_count = 16 ) :
"""Spam the bus with messages including the data id .
: param int id : the id of the thread / process""" | with can . Bus ( bustype = 'socketcan' , channel = 'vcan0' ) as bus :
for i in range ( message_count ) :
msg = can . Message ( arbitration_id = 0x0cf02200 + id , data = [ id , i , 0 , 1 , 3 , 1 , 4 , 1 ] )
bus . send ( msg )
sleep ( 1.0 )
print ( "Producer #{} finished sending {} messages" . for... |
def get_first_row ( dbconn , tablename , n = 1 , uuid = None ) :
"""Returns the first ` n ` rows in the table""" | return fetch ( dbconn , tablename , n , uuid , end = False ) |
def _set_prefixes ( self , conf ) :
"""Set the graphite key prefixes
: param dict conf : The configuration data""" | if conf . get ( 'legacy_namespace' , 'y' ) in self . TRUE_VALUES :
self . count_prefix = 'stats_counts'
self . count_suffix = ''
self . gauge_prefix = 'stats.gauges'
self . timer_prefix = 'stats.timers'
self . rate_prefix = 'stats'
self . rate_suffix = ''
else :
global_prefix = conf . get ( ... |
def upload ( self , bug : Bug ) -> bool :
"""Attempts to upload the Docker image for a given bug to
` DockerHub < https : / / hub . docker . com > ` _ .""" | return self . __installation . build . upload ( bug . image ) |
def woa_profile_from_dap ( var , d , lat , lon , depth , cfg ) :
"""Monthly Climatologic Mean and Standard Deviation from WOA ,
used either for temperature or salinity .
INPUTS
time : [ day of the year ]
lat : [ - 90 < lat < 90]
lon : [ - 180 < lon < 180]
depth : [ meters ]
Reads the WOA Monthly Clima... | if lon < 0 :
lon = lon + 360
url = cfg [ 'url' ]
doy = int ( d . strftime ( '%j' ) )
dataset = open_url ( url )
dn = ( np . abs ( doy - dataset [ 'time' ] [ : ] ) ) . argmin ( )
xn = ( np . abs ( lon - dataset [ 'lon' ] [ : ] ) ) . argmin ( )
yn = ( np . abs ( lat - dataset [ 'lat' ] [ : ] ) ) . argmin ( )
if re . ... |
def fold_xor ( bloomfilter , # type : bitarray
folds # type : int
) : # type : ( . . . ) - > bitarray
"""Performs XOR folding on a Bloom filter .
If the length of the original Bloom filter is n and we perform
r folds , then the length of the resulting filter is n / 2 * * r .
: param bloomfilter : Bloom filter... | if len ( bloomfilter ) % 2 ** folds != 0 :
msg = ( 'The length of the bloom filter is {length}. It is not ' 'divisible by 2 ** {folds}, so it cannot be folded {folds} ' 'times.' . format ( length = len ( bloomfilter ) , folds = folds ) )
raise ValueError ( msg )
for _ in range ( folds ) :
bf1 = bloomfilter ... |
def _ask_to_confirm ( self , ui , pac_man , * to_install ) :
"""Return True if user wants to install packages , False otherwise""" | ret = DialogHelper . ask_for_package_list_confirm ( ui , prompt = pac_man . get_perm_prompt ( to_install ) , package_list = to_install , )
return bool ( ret ) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.