signature stringlengths 29 44.1k | implementation stringlengths 0 85.2k |
|---|---|
def _plot_rprof_list ( sdat , lovs , rprofs , metas , stepstr , rads = None ) :
"""Plot requested profiles""" | if rads is None :
rads = { }
for vfig in lovs :
fig , axes = plt . subplots ( ncols = len ( vfig ) , sharey = True )
axes = [ axes ] if len ( vfig ) == 1 else axes
fname = 'rprof_'
for iplt , vplt in enumerate ( vfig ) :
xlabel = None
for ivar , rvar in enumerate ( vplt ) :
... |
def _get_comparison_strings ( self , s ) :
"""Find all similar strings""" | str_len = len ( s )
comparison_idxs = make_unique_ngrams ( s , self . idx_size )
min_len = len ( s ) - self . plus_minus
if min_len < 0 :
min_len = 0
if self . _els_idxed is None :
raise UnintitializedError ( 'Database not created' )
all_sets = set ( )
for idx in comparison_idxs :
found_idx = self . _els_id... |
def sort ( self , column , order = Qt . AscendingOrder ) :
"""Overriding sort method""" | reverse = ( order == Qt . DescendingOrder )
if column == 0 :
self . sizes = sort_against ( self . sizes , self . keys , reverse )
self . types = sort_against ( self . types , self . keys , reverse )
try :
self . keys . sort ( reverse = reverse )
except :
pass
elif column == 1 :
self ... |
def reload_scoped_variables_list_store ( self ) :
"""Reloads the scoped variable list store from the data port models""" | if isinstance ( self . model , ContainerStateModel ) :
tmp = self . get_new_list_store ( )
for sv_model in self . model . scoped_variables :
data_type = sv_model . scoped_variable . data_type
# get name of type ( e . g . ndarray )
data_type_name = data_type . __name__
# get modul... |
def reverse ( self , query , exactly_one = DEFAULT_SENTINEL , timeout = DEFAULT_SENTINEL , feature_code = None , lang = None , find_nearby_type = 'findNearbyPlaceName' , ) :
"""Return an address by location point .
. . versionadded : : 1.2.0
: param query : The coordinates for which you wish to obtain the
clo... | if exactly_one is DEFAULT_SENTINEL :
warnings . warn ( '%s.reverse: default value for `exactly_one` ' 'argument will become True in geopy 2.0. ' 'Specify `exactly_one=False` as the argument ' 'explicitly to get rid of this warning.' % type ( self ) . __name__ , DeprecationWarning , stacklevel = 2 )
exactly_one ... |
def result_code ( self , value ) :
"""The result _ code property .
Args :
value ( string ) . the property value .""" | if value == self . _defaults [ 'resultCode' ] and 'resultCode' in self . _values :
del self . _values [ 'resultCode' ]
else :
self . _values [ 'resultCode' ] = value |
async def sound ( dev : Device , target , value ) :
"""Get or set sound settings .""" | if target and value :
click . echo ( "Setting %s to %s" % ( target , value ) )
click . echo ( await dev . set_sound_settings ( target , value ) )
print_settings ( await dev . get_sound_settings ( ) ) |
def confd_state_cli_listen_ssh_ip ( self , ** kwargs ) :
"""Auto Generated Code""" | config = ET . Element ( "config" )
confd_state = ET . SubElement ( config , "confd-state" , xmlns = "http://tail-f.com/yang/confd-monitoring" )
cli = ET . SubElement ( confd_state , "cli" )
listen = ET . SubElement ( cli , "listen" )
ssh = ET . SubElement ( listen , "ssh" )
ip = ET . SubElement ( ssh , "ip" )
ip . text... |
def _get_site_amplification ( self , C_AMP , vs30 , pga_rock ) :
"""Gets the site amplification term based on equations 7 and 8 of
Atkinson & Boore ( 2006)""" | # Get nonlinear term
bnl = self . _get_bnl ( C_AMP , vs30 )
f_nl_coeff = np . log ( 60.0 / 100.0 ) * np . ones_like ( vs30 )
idx = pga_rock > 60.0
f_nl_coeff [ idx ] = np . log ( pga_rock [ idx ] / 100.0 )
return np . log ( np . exp ( C_AMP [ "blin" ] * np . log ( vs30 / self . CONSTS [ "Vref" ] ) + bnl * f_nl_coeff ) ... |
def _scanDataFiles ( self , dataDir , patterns ) :
"""Scans the specified directory for files with the specified globbing
pattern and calls self . _ addDataFile for each . Raises an
EmptyDirException if no data files are found .""" | numDataFiles = 0
for pattern in patterns :
scanPath = os . path . join ( dataDir , pattern )
for filename in glob . glob ( scanPath ) :
self . _addDataFile ( filename )
numDataFiles += 1
if numDataFiles == 0 :
raise exceptions . EmptyDirException ( dataDir , patterns ) |
def fit ( self , X , y = None , ** kwargs ) :
"""Determine transformation parameters from data in X .
Subsequent calls to ` transform ( Y ) ` compute the pairwise
distance to ` X ` .
Parameters of the clinical kernel are only updated
if ` fit _ once ` is ` False ` , otherwise you have to
explicitly call `... | if X . ndim != 2 :
raise ValueError ( "expected 2d array, but got %d" % X . ndim )
if self . fit_once :
self . X_fit_ = X
else :
self . _prepare_by_column_dtype ( X )
return self |
def verify ( conf , input_requirements_filename ) :
"""Verifying that given requirements file is not missing any pins
args :
input _ requirements _ filename : requriements file to verify""" | exit_if_file_not_exists ( input_requirements_filename , conf )
cireqs . check_if_requirements_are_up_to_date ( requirements_filename = input_requirements_filename , ** conf . _asdict ( ) )
click . echo ( click . style ( '✓' , fg = 'green' ) + " {} has been verified" . format ( input_requirements_filename ) ) |
def close ( self ) :
"""Closes the stream .""" | if self . call is None :
return
self . _request_queue . put ( None )
self . call . cancel ( )
self . _request_generator = None |
def create_col_nums ( ) :
"""Return column numbers and letters that repeat up to NUM _ REPEATS .
I . e . , NUM _ REPEATS = 2 would return a list of 26 * 26 = 676 2 - tuples .""" | NUM_REPEATS = 2
column_letters = list ( string . ascii_uppercase ) + map ( '' . join , itertools . product ( string . ascii_uppercase , repeat = NUM_REPEATS ) )
letter_numbers = [ ]
count = 1
for letter in column_letters :
letter_numbers . append ( ( count , str ( count ) + ' (' + letter + ')' ) )
count += 1
re... |
def main ( ) :
"""NAME
plot _ magmap . py
DESCRIPTION
makes a color contour map of desired field model
SYNTAX
plot _ magmap . py [ command line options ]
OPTIONS
- h prints help and quits
- f FILE specify field model file with format : l m g h
- fmt [ pdf , eps , svg , png ] specify format for out... | cmap = 'RdYlBu'
date = 2016.
if not Basemap :
print ( "-W- Cannot access the Basemap module, which is required to run plot_magmap.py" )
sys . exit ( )
dir_path = '.'
lincr = 1
# level increment for contours
if '-WD' in sys . argv :
ind = sys . argv . index ( '-WD' )
dir_path = sys . argv [ ind + 1 ]
if ... |
def __read_developer_settings ( self ) :
"""Читает конфигурации разработчика с локальной машины или из переменных окружения
При этом переменная окружения приоритетнее
: return :""" | self . developer_settings = read_developer_settings ( )
if not self . developer_settings :
self . log . warning ( "НЕ УСТАНОВЛЕНЫ настройки разработчика, это может приводить к проблемам в дальнейшей работе!" ) |
def parse_stack ( self , global_params , region , stack ) :
"""Parse a single stack and fetch additional attributes
: param global _ params : Parameters shared for all regions
: param region : Name of the AWS region
: param stack _ url : URL of the AWS stack""" | stack [ 'id' ] = stack . pop ( 'StackId' )
stack [ 'name' ] = stack . pop ( 'StackName' )
stack_policy = api_clients [ region ] . get_stack_policy ( StackName = stack [ 'name' ] )
if 'StackPolicyBody' in stack_policy :
stack [ 'policy' ] = json . loads ( stack_policy [ 'StackPolicyBody' ] )
self . stacks [ stack [ ... |
def reorient_z ( structure ) :
"""reorients a structure such that the z axis is concurrent with the
normal to the A - B plane""" | struct = structure . copy ( )
sop = get_rot ( struct )
struct . apply_operation ( sop )
return struct |
def _process_change ( self , payload , user , repo , repo_url , event , codebase = None ) :
"""Consumes the JSON as a python object and actually starts the build .
: arguments :
payload
Python Object that represents the JSON sent by GitLab Service
Hook .""" | changes = [ ]
refname = payload [ 'ref' ]
# project name from http headers is empty for me , so get it from repository / name
project = payload [ 'repository' ] [ 'name' ]
# We only care about regular heads or tags
match = re . match ( r"^refs/(heads|tags)/(.+)$" , refname )
if not match :
log . msg ( "Ignoring ref... |
def has_access ( self , permission_name , view_name ) :
"""Check if current user or public has access to view or menu""" | if current_user . is_authenticated :
return self . _has_view_access ( g . user , permission_name , view_name )
elif current_user_jwt :
return self . _has_view_access ( current_user_jwt , permission_name , view_name )
else :
return self . is_item_public ( permission_name , view_name ) |
def _raise_for_status ( response ) :
"""Raises stored : class : ` HTTPError ` , if one occurred .
This is the : meth : ` requests . models . Response . raise _ for _ status ` method ,
modified to add the response from Space - Track , if given .""" | http_error_msg = ''
if 400 <= response . status_code < 500 :
http_error_msg = '%s Client Error: %s for url: %s' % ( response . status_code , response . reason , response . url )
elif 500 <= response . status_code < 600 :
http_error_msg = '%s Server Error: %s for url: %s' % ( response . status_code , response . ... |
def show_report ( self ) :
"""Show report .""" | self . action_show_report . setEnabled ( False )
self . action_show_log . setEnabled ( True )
self . load_html_file ( self . report_path ) |
def to_before_pedalboard ( self ) :
"""Change the current : class : ` . Pedalboard ` for the previous pedalboard .
If the current pedalboard is the first in the current : class : ` Bank ` ,
the current pedalboard is will be the * * last of the current Bank * * .
. . warning : :
If the current : attr : ` . p... | if self . pedalboard is None :
raise CurrentPedalboardError ( 'The current pedalboard is None' )
before_index = self . pedalboard . index - 1
if before_index == - 1 :
before_index = len ( self . bank . pedalboards ) - 1
self . set_pedalboard ( self . bank . pedalboards [ before_index ] ) |
async def do_cmd ( self , * args , success = None ) :
"""Sends the given command to the server .
Args :
* args : Command and arguments to be sent to the server .
Raises :
ConnectionResetError : If the connection with the server is
unexpectedely lost .
SMTPCommandFailedError : If the command fails .
Re... | if success is None :
success = ( 250 , )
cmd = " " . join ( args )
await self . writer . send_command ( cmd )
code , message = await self . reader . read_reply ( )
if code not in success :
raise SMTPCommandFailedError ( code , message , cmd )
return code , message |
def solveAgents ( self ) :
'''Solves the microeconomic problem for all AgentTypes in this market .
Parameters
None
Returns
None''' | # for this _ type in self . agents :
# this _ type . solve ( )
try :
multiThreadCommands ( self . agents , [ 'solve()' ] )
except Exception as err :
if self . print_parallel_error_once : # Set flag to False so this is only printed once .
self . print_parallel_error_once = False
print ( "**** WAR... |
def property_value ( self , io_handler , name ) :
"""Prints the value of the given property , looking into
framework properties then environment variables .""" | value = self . _context . get_property ( name )
if value is None : # Avoid printing " None "
value = ""
io_handler . write_line ( str ( value ) ) |
def is_avro ( path_or_buffer ) :
"""Return True if path ( or buffer ) points to an Avro file .
Parameters
path _ or _ buffer : path to file or file - like object
Path to file""" | if is_str ( path_or_buffer ) :
fp = open ( path_or_buffer , 'rb' )
close = True
else :
fp = path_or_buffer
close = False
try :
header = fp . read ( len ( MAGIC ) )
return header == MAGIC
finally :
if close :
fp . close ( ) |
def sample_to ( self , count , skip_header_rows , strategy , target ) :
"""Sample rows from GCS or local file and save results to target file .
Args :
count : number of rows to sample . If strategy is " BIGQUERY " , it is used as approximate number .
skip _ header _ rows : whether to skip first row when readi... | # TODO ( qimingj ) Add unit test
# Read data from source into DataFrame .
if sys . version_info . major > 2 :
xrange = range
# for python 3 compatibility
if strategy == 'BIGQUERY' :
import datalab . bigquery as bq
if not self . path . startswith ( 'gs://' ) :
raise Exception ( 'Cannot use BIGQUERY i... |
def _get_sector ( self , channel , nlines , ncols ) :
"""Determine which sector was scanned""" | if self . _is_vis ( channel ) :
margin = 100
sectors_ref = self . vis_sectors
else :
margin = 50
sectors_ref = self . ir_sectors
for ( nlines_ref , ncols_ref ) , sector in sectors_ref . items ( ) :
if np . fabs ( ncols - ncols_ref ) < margin and np . fabs ( nlines - nlines_ref ) < margin :
r... |
def remover ( self , id_script_type ) :
"""Remove Script Type from by the identifier .
: param id _ script _ type : Identifier of the Script Type . Integer value and greater than zero .
: return : None
: raise InvalidParameterError : The identifier of Script Type is null and invalid .
: raise TipoRoteiroNao... | if not is_valid_int_param ( id_script_type ) :
raise InvalidParameterError ( u'The identifier of Script Type is invalid or was not informed.' )
url = 'scripttype/' + str ( id_script_type ) + '/'
code , xml = self . submit ( None , 'DELETE' , url )
return self . response ( code , xml ) |
def vcf_line ( input_data , reference ) :
"""Convert the var files information into VCF format .
This is nontrivial because the var file can contain zero - length variants ,
which is not allowed by VCF . To handle these cases , we " move backwards "
by one position , look up the reference sequence , and add t... | vcf_data = VCF_DATA_TEMPLATE . copy ( )
start = int ( input_data [ 'start' ] )
dbsnp_data = input_data [ 'dbsnp_data' ]
ref_allele = input_data [ 'ref_seq' ]
genome_alleles = input_data [ 'alleles' ]
# Get dbSNP IDs .
dbsnp_cleaned = [ ]
for dbsnp in dbsnp_data :
if dbsnp not in dbsnp_cleaned :
dbsnp_cleane... |
def set ( self , attribute , specification , exact = False ) :
"""Set the named attribute from the specification given by the user .
The value actually set may be different .""" | assert isinstance ( attribute , basestring )
assert isinstance ( exact , ( int , bool ) )
if __debug__ and not exact :
if attribute == 'requirements' :
assert ( isinstance ( specification , property_set . PropertySet ) or all ( isinstance ( s , basestring ) for s in specification ) )
elif attribute in (... |
def date_range_builder ( self , start = '2013-02-11' , end = None ) :
"""Builds date range query .
: param start :
Date string . format : YYYY - MM - DD
: type start :
String
: param end :
date string . format : YYYY - MM - DD
: type end :
String
: returns :
String""" | if not end :
end = time . strftime ( '%Y-%m-%d' )
return 'acquisitionDate:[%s+TO+%s]' % ( start , end ) |
def _escape_regexp ( s ) :
"""escape characters with specific regexp use""" | return ( str ( s ) . replace ( '|' , '\\|' ) . replace ( '.' , '\.' ) # ` . ` has to be replaced before ` * `
. replace ( '*' , '.*' ) . replace ( '+' , '\+' ) . replace ( '(' , '\(' ) . replace ( ')' , '\)' ) . replace ( '$' , '\\$' ) ) |
def receive_message ( self , operation , request_id ) :
"""Receive a raw BSON message or raise ConnectionFailure .
If any exception is raised , the socket is closed .""" | try :
return receive_message ( self . sock , operation , request_id , self . max_message_size )
except BaseException as error :
self . _raise_connection_failure ( error ) |
def nltk_tokenize_words ( string , attached_period = False , language = None ) :
"""Wrap NLTK ' s tokenizer PunktLanguageVars ( ) , but make final period
its own token .
> > > nltk _ tokenize _ words ( " Sentence 1 . Sentence 2 . " )
[ ' Sentence ' , ' 1 ' , ' . ' , ' Sentence ' , ' 2 ' , ' . ' ]
> > > # Op... | assert isinstance ( string , str ) , "Incoming string must be type str."
if language == 'sanskrit' :
periods = [ '.' , '।' , '॥' ]
else :
periods = [ '.' ]
punkt = PunktLanguageVars ( )
tokens = punkt . word_tokenize ( string )
if attached_period :
return tokens
new_tokens = [ ]
for word in tokens :
for... |
def get_random_areanote ( zone ) :
"""省份行政区划代码 , 返回下辖的随机地区名称
: param :
* zone : ( string ) 省份行政区划代码 比如 ' 310000'
: returns :
* random _ areanote : ( string ) 省份下辖随机地区名称
举例如下 : :
print ( ' - - - fish _ data get _ random _ areanote demo - - - ' )
print ( cardbin _ get _ bank _ by _ name ( 310000 ) )
p... | # 获取省份下的地区信息
province = str ( zone ) [ : 2 ]
areanote_list = IdCard . get_areanote_info ( province )
# 选出省份名称
province_name_list = [ item for item in areanote_list if item [ 0 ] == str ( zone ) ]
if not ( areanote_list and province_name_list ) :
raise ValueError ( 'zone error, please check and try again' )
# 只选取下辖区... |
def func_quantiles ( node , qlist = ( .025 , .25 , .5 , .75 , .975 ) ) :
"""Returns an array whose ith row is the q [ i ] th quantile of the
function .
: Arguments :
func _ stacks : The samples of the function . func _ stacks [ i , : ]
gives sample i .
qlist : A list or array of the quantiles you would li... | # For very large objects , this will be rather long .
# Too get the length of the table , use obj . trace . length ( )
if isinstance ( node , Variable ) :
func_stacks = node . trace ( )
else :
func_stacks = node
if any ( qlist < 0. ) or any ( qlist > 1. ) :
raise TypeError ( 'The elements of qlist must be b... |
def triplifyGML ( dpath = "../data/fb/" , fname = "foo.gdf" , fnamei = "foo_interaction.gdf" , fpath = "./fb/" , scriptpath = None , uid = None , sid = None , fb_link = None , ego = True , umbrella_dir = None ) :
"""Produce a linked data publication tree from a standard GML file .
INPUTS :
= > the data director... | c ( "iniciado tripgml" )
if sum ( c . isdigit ( ) for c in fname ) == 4 :
year = re . findall ( r".*(\d\d\d\d).gml" , fname ) [ 0 ] [ 0 ]
B . datetime_snapshot = datetime . date ( * [ int ( i ) for i in ( year ) ] )
if sum ( c . isdigit ( ) for c in fname ) == 12 :
day , month , year , hour , minute = re . ... |
def jacobi_prolongation_smoother ( S , T , C , B , omega = 4.0 / 3.0 , degree = 1 , filter = False , weighting = 'diagonal' ) :
"""Jacobi prolongation smoother .
Parameters
S : csr _ matrix , bsr _ matrix
Sparse NxN matrix used for smoothing . Typically , A .
T : csr _ matrix , bsr _ matrix
Tentative prol... | # preprocess weighting
if weighting == 'block' :
if sparse . isspmatrix_csr ( S ) :
weighting = 'diagonal'
elif sparse . isspmatrix_bsr ( S ) :
if S . blocksize [ 0 ] == 1 :
weighting = 'diagonal'
if filter : # Implement filtered prolongation smoothing for the general case by
# utili... |
def is_str ( arg ) :
'''is _ str ( x ) yields True if x is a string object or a 0 - dim numpy array of a string and yields
False otherwise .''' | return ( isinstance ( arg , six . string_types ) or is_npscalar ( arg , 'string' ) or is_npvalue ( arg , 'string' ) ) |
def dict_to_body ( star_dict ) :
"""Converts a dictionary of variable star data to a ` Body ` instance .
Requires ` PyEphem < http : / / rhodesmill . org / pyephem / > ` _ to be installed .""" | if ephem is None : # pragma : no cover
raise NotImplementedError ( "Please install PyEphem in order to use dict_to_body." )
body = ephem . FixedBody ( )
body . name = star_dict [ 'name' ]
body . _ra = ephem . hours ( str ( star_dict [ 'ra' ] ) )
body . _dec = ephem . degrees ( str ( star_dict [ 'dec' ] ) )
body . _... |
def handle_response ( self , ts , resp ) :
"""Passes a response message to the corresponding event handler , and also
takes care of handling errors raised by the _ raise _ error handler .
: param ts : timestamp , declares when data was received by the client
: param resp : dict , containing info or error keys... | log . info ( "handle_response: Handling response %s" , resp )
event = resp [ 'event' ]
try :
self . _event_handlers [ event ] ( ts , ** resp )
# Handle Non - Critical Errors
except ( InvalidChannelError , InvalidPairError , InvalidBookLengthError , InvalidBookPrecisionError ) as e :
log . exception ( e )
pr... |
def obj_with_unit ( obj , unit ) :
"""Returns a ` FloatWithUnit ` instance if obj is scalar , a dictionary of
objects with units if obj is a dict , else an instance of
` ArrayWithFloatWithUnit ` .
Args :
unit : Specific units ( eV , Ha , m , ang , etc . ) .""" | unit_type = _UNAME2UTYPE [ unit ]
if isinstance ( obj , numbers . Number ) :
return FloatWithUnit ( obj , unit = unit , unit_type = unit_type )
elif isinstance ( obj , collections . Mapping ) :
return { k : obj_with_unit ( v , unit ) for k , v in obj . items ( ) }
else :
return ArrayWithUnit ( obj , unit = ... |
def bytes ( self ) :
"""Returns a t - uple with instruction bytes ( integers )""" | result = [ ]
op = self . opcode . split ( ' ' )
argi = 0
while op :
q = op . pop ( 0 )
if q == 'XX' :
for k in range ( self . argbytes [ argi ] - 1 ) :
op . pop ( 0 )
result . extend ( num2bytes ( self . argval ( ) [ argi ] , self . argbytes [ argi ] ) )
argi += 1
else :
... |
def timing ( function ) :
'''Decorator wrapper to log execution time , for profiling purposes''' | @ wraps ( function )
def wrapped ( * args , ** kwargs ) :
start_time = time . time ( )
ret = function ( * args , ** salt . utils . args . clean_kwargs ( ** kwargs ) )
end_time = time . time ( )
if function . __module__ . startswith ( 'salt.loaded.int.' ) :
mod_name = function . __module__ [ 16 :... |
def searchAccession ( acc ) :
"""attempt to use NCBI Entrez to get
BioSample ID""" | # try genbank file
# genome database
out , error = entrez ( 'genome' , acc )
for line in out . splitlines ( ) :
line = line . decode ( 'ascii' ) . strip ( )
if 'Assembly_Accession' in line or 'BioSample' in line :
newAcc = line . split ( '>' ) [ 1 ] . split ( '<' ) [ 0 ] . split ( '.' ) [ 0 ] . split ( ... |
def attach_model ( subscription , rgname , vmssvm_model , diskname , lun ) :
'''Attach a data disk to a VMSS VM model''' | disk_id = '/subscriptions/' + subscription + '/resourceGroups/' + rgname + '/providers/Microsoft.Compute/disks/' + diskname
disk_model = { 'lun' : lun , 'createOption' : 'Attach' , 'caching' : 'None' , 'managedDisk' : { 'storageAccountType' : 'Standard_LRS' , 'id' : disk_id } }
vmssvm_model [ 'properties' ] [ 'storageP... |
def console_save_xp ( con : tcod . console . Console , filename : str , compress_level : int = 9 ) -> bool :
"""Save a console to a REXPaint ` . xp ` file .""" | return bool ( lib . TCOD_console_save_xp ( _console ( con ) , filename . encode ( "utf-8" ) , compress_level ) ) |
def run_nb ( config , path = None ) :
"""Run a notebook file .
Runs the one specified by the config file , or the one at
the location specificed by ' path ' .""" | if path is None :
path = os . getcwd ( )
root = config . get ( 'root' , 'path' )
root = os . path . join ( path , root )
nb_name = config . get ( 'misc' , 'nb-name' )
nb_path = os . path . join ( root , '%s.ipynb' % nb_name )
if not os . path . exists ( nb_path ) :
print ( ( "No notebook found at %s. " "Create ... |
def error ( self , msgid , error ) :
"""Handle a error message .""" | self . requests [ msgid ] . errback ( error )
del self . requests [ msgid ] |
def GET_prices_name ( self , path_info , name ) :
"""Get the price for a name in a namespace
Reply the price as { ' name _ price ' : { ' amount ' : str ( . . . ) , ' units ' : str ( . . . ) } } ( also , ' satoshis ' : . . . if the name is in BT )
Reply 404 if the namespace doesn ' t exist
Reply 502 if we can ... | if not check_name ( name ) :
return self . _reply_json ( { 'error' : 'Invalid name' } , status_code = 400 )
blockstackd_url = get_blockstackd_url ( )
price_info = blockstackd_client . get_name_cost ( name , hostport = blockstackd_url )
if json_is_error ( price_info ) : # error
status_code = price_info . get ( '... |
def _apk_analysis ( self ) :
"""Run analysis on the APK file .
This method is usually called by _ _ init _ _ except if skip _ analysis is False .
It will then parse the AndroidManifest . xml and set all fields in the APK class which can be
extracted from the Manifest .""" | i = "AndroidManifest.xml"
try :
manifest_data = self . zip . read ( i )
except KeyError :
log . warning ( "Missing AndroidManifest.xml. Is this an APK file?" )
else :
ap = AXMLPrinter ( manifest_data )
if not ap . is_valid ( ) :
log . error ( "Error while parsing AndroidManifest.xml - is the fil... |
def replaceint ( fname , replacewith = '%s' ) :
"""replace int in lst""" | words = fname . split ( )
for i , word in enumerate ( words ) :
try :
word = int ( word )
words [ i ] = replacewith
except ValueError :
pass
return ' ' . join ( words ) |
def delete ( self ) :
"""Explicit destructor of the internal SAT oracle and all the
totalizer objects creating during the solving process .""" | if self . oracle :
self . oracle . delete ( )
self . oracle = None
if self . solver != 'mc' : # for minicard , there is nothing to free
for t in six . itervalues ( self . tobj ) :
t . delete ( ) |
def stem ( self , word ) :
"""Stem the word if it has more than two characters ,
otherwise return it as is .""" | if len ( word ) <= 2 :
return word
else :
word = self . remove_initial_apostrophe ( word )
word = self . set_ys ( word )
self . find_regions ( word )
word = self . strip_possessives ( word )
word = self . replace_suffixes_1 ( word )
word = self . replace_suffixes_2 ( word )
word = self .... |
def generate_data ( self , data_dir , tmp_dir , task_id = - 1 ) :
"""The function generating the data .""" | filepath_fns = { problem . DatasetSplit . TRAIN : self . training_filepaths , problem . DatasetSplit . EVAL : self . dev_filepaths , problem . DatasetSplit . TEST : self . test_filepaths , }
# We set shuffled = True as we don ' t want to shuffle on disk later .
split_paths = [ ( split [ "split" ] , filepath_fns [ split... |
def set_state ( self , vid , value = None , default = False , disable = False ) :
"""Configures the VLAN state
EosVersion :
4.13.7M
Args :
vid ( str ) : The VLAN ID to configure
value ( str ) : The value to set the vlan state to
default ( bool ) : Configures the vlan state to its default value
disable... | cmds = self . command_builder ( 'state' , value = value , default = default , disable = disable )
return self . configure_vlan ( vid , cmds ) |
def river_sources ( world , water_flow , water_path ) :
"""Find places on map where sources of river can be found""" | river_source_list = [ ]
# Using the wind and rainfall data , create river ' seeds ' by
# flowing rainfall along paths until a ' flow ' threshold is reached
# and we have a beginning of a river . . . trickle - > stream - > river - > sea
# step one : Using flow direction , follow the path for each cell
# adding the previ... |
def grouped ( self ) :
"""Yield the matches grouped by their final state in the automaton , i . e . structurally identical patterns
only differing in constraints will be yielded together . Each group is yielded as a list of tuples consisting of
a pattern and a match substitution .
Yields :
The grouped match... | for _ in self . _match ( self . matcher . root ) :
yield list ( self . _internal_iter ( ) ) |
def within ( self , version ) :
"""A single version can also be interpreted as an open range ( i . e . no
maximum version )""" | if not isinstance ( version , Version ) :
version = type ( self . _min_ver ) ( self . _req , version )
return version >= self |
def _reduce ( self ) :
"""Reduce data from multiple context to cpu .""" | ctx = context . cpu ( )
if self . _stype == 'default' :
block = self . list_data ( )
data = ndarray . add_n ( * ( w . copyto ( ctx ) for w in block ) ) / len ( block )
else : # fetch all rows for ' row _ sparse ' param
all_row_ids = ndarray . arange ( 0 , self . shape [ 0 ] , dtype = 'int64' , ctx = ctx )
... |
def ensure_dir ( d ) :
"""Check to make sure the supplied directory path does not exist , if so , create it . The
method catches OSError exceptions and returns a descriptive message instead of
re - raising the error .
: type d : str
: param d : It is the full path to a directory .
: return : Does not retu... | if not os . path . exists ( d ) :
try :
os . makedirs ( d )
except OSError as oe : # should not happen with os . makedirs
# ENOENT : No such file or directory
if os . errno == errno . ENOENT :
msg = twdd ( """One or more directories in the path ({}) do not exist. If
... |
def access_id ( self , id_ , lineno , scope = None , default_type = None , default_class = CLASS . unknown ) :
"""Access a symbol by its identifier and checks if it exists .
If not , it ' s supposed to be an implicit declared variable .
default _ class is the class to use in case of an undeclared - implicit - a... | if isinstance ( default_type , symbols . BASICTYPE ) :
default_type = symbols . TYPEREF ( default_type , lineno , implicit = False )
assert default_type is None or isinstance ( default_type , symbols . TYPEREF )
if not check_is_declared_explicit ( lineno , id_ ) :
return None
result = self . get_entry ( id_ , s... |
def thumbnails_for_file ( relative_source_path , root = None , basedir = None , subdir = None , prefix = None ) :
"""Return a list of dictionaries , one for each thumbnail belonging to the
source image .
The following list explains each key of the dictionary :
` filename ` - - absolute thumbnail path
` x ` ... | if root is None :
root = settings . MEDIA_ROOT
if prefix is None :
prefix = settings . THUMBNAIL_PREFIX
if subdir is None :
subdir = settings . THUMBNAIL_SUBDIR
if basedir is None :
basedir = settings . THUMBNAIL_BASEDIR
source_dir , filename = os . path . split ( relative_source_path )
thumbs_path = os... |
def merge_files ( configuration , locale , fail_if_missing = True ) :
"""Merge all the files in ` locale ` , as specified in config . yaml .""" | for target , sources in configuration . generate_merge . items ( ) :
merge ( configuration , locale , target , sources , fail_if_missing ) |
def format_obj_name ( obj , delim = "<>" ) :
"""Formats the object name in a pretty way
@ obj : any python object
@ delim : the characters to wrap a parent object name in
- > # str formatted name
from vital . debug import format _ obj _ name
format _ obj _ name ( vital . debug . Timer )
# - > ' Timer < ... | pname = ""
parent_name = get_parent_name ( obj )
if parent_name :
pname = "{}{}{}" . format ( delim [ 0 ] , get_parent_name ( obj ) , delim [ 1 ] )
return "{}{}" . format ( get_obj_name ( obj ) , pname ) |
def construct ( arg ) :
'''Shortcut syntax to define trafarets .
- int , str , float and bool will return t . Int , t . String , t . Float and t . Bool
- one element list will return t . List
- tuple or list with several args will return t . Tuple
- dict will return t . Dict . If key has ' ? ' at the and it... | if isinstance ( arg , t . Trafaret ) :
return arg
elif isinstance ( arg , tuple ) or ( isinstance ( arg , list ) and len ( arg ) > 1 ) :
return t . Tuple ( * ( construct ( a ) for a in arg ) )
elif isinstance ( arg , list ) : # if len ( arg ) = = 1
return t . List ( construct ( arg [ 0 ] ) )
elif isinstance... |
def f1_with_flattening ( estimator , X , y ) :
"""Calculate F1 score by flattening the predictions of the
estimator across all sequences . For example , given the following
address sequences as input
[ ' 1 My str ' , ' 2 Your blvd ' ] ,
the predictions of the model will be flattened like so :
[ ' AddressN... | predicted = estimator . predict ( X )
flat_pred , flat_gold = [ ] , [ ]
for a , b in zip ( predicted , y ) :
if len ( a ) == len ( b ) :
flat_pred . extend ( a )
flat_gold . extend ( b )
return f1_score ( flat_gold , flat_pred ) |
import math
def compute_tetrahedron_area ( edge_length ) :
"""Function to calculate the surface area of a tetrahedron .
Examples :
compute _ tetrahedron _ area ( 3 ) - > 15.588457268119894
compute _ tetrahedron _ area ( 20 ) - > 692.8203230275509
compute _ tetrahedron _ area ( 10 ) - > 173.20508075688772
... | surface_area = math . sqrt ( 3 ) * ( edge_length ** 2 )
return surface_area |
def handle_signature ( self , sig , signode ) :
"""Create a signature for this thing .""" | if sig != 'Configuration' :
signode . clear ( )
# Add " component " which is the type of this thing
signode += addnodes . desc_annotation ( 'component ' , 'component ' )
if '.' in sig :
modname , clsname = sig . rsplit ( '.' , 1 )
else :
modname , clsname = '' , sig
# If there ' ... |
def get_last_scene_time ( self , refresh = False ) :
"""Get last scene time .
Refresh data from Vera if refresh is True , otherwise use local cache .
Refresh is only needed if you ' re not using subscriptions .""" | if refresh :
self . refresh_complex_value ( 'LastSceneTime' )
val = self . get_complex_value ( 'LastSceneTime' )
return val |
def __makeattr ( self , name ) :
"""lazily compute value for name or raise AttributeError if unknown .""" | # print " makeattr " , self . _ _ name _ _ , name
target = None
if '__onfirstaccess__' in self . __map__ :
target = self . __map__ . pop ( '__onfirstaccess__' )
importobj ( * target ) ( )
try :
modpath , attrname = self . __map__ [ name ]
except KeyError :
if target is not None and name != '__onfirstacc... |
def get_meta_fields ( self , fields , kwargs = { } ) :
'''Return a dictionary of metadata fields''' | fields = to_list ( fields )
meta = self . get_meta ( )
return { field : meta . get ( field ) for field in fields } |
def simxGetIntegerSignal ( clientID , signalName , operationMode ) :
'''Please have a look at the function description / documentation in the V - REP user manual''' | signalValue = ct . c_int ( )
if ( sys . version_info [ 0 ] == 3 ) and ( type ( signalName ) is str ) :
signalName = signalName . encode ( 'utf-8' )
return c_GetIntegerSignal ( clientID , signalName , ct . byref ( signalValue ) , operationMode ) , signalValue . value |
def read_file ( cls , filepath ) :
"""Decodes bencoded data of a given file .
Returns decoded structure ( s ) .
: param str filepath :
: rtype : list""" | with open ( filepath , mode = 'rb' ) as f :
contents = f . read ( )
return cls . decode ( contents ) |
def laser_mirrors ( rows , cols , mir ) :
"""Orienting mirrors to allow reachability by laser beam
: param int rows :
: param int cols : rows and cols are the dimension of the grid
: param mir : list of mirror coordinates , except
mir [ 0 ] = laser entrance ,
mir [ - 1 ] = laser exit .
: complexity : : ... | # build structures
n = len ( mir )
orien = [ None ] * ( n + 2 )
orien [ n ] = 0
# arbitrary orientations
orien [ n + 1 ] = 0
succ = [ [ None for direc in range ( 4 ) ] for i in range ( n + 2 ) ]
L = [ ( mir [ i ] [ 0 ] , mir [ i ] [ 1 ] , i ) for i in range ( n ) ]
L . append ( ( 0 , - 1 , n ) )
# enter
L . append ( ( ... |
def drop_capabilities ( keep = [ ] ) :
"""Drop all capabilities this process has .
@ param keep : list of capabilities to not drop""" | capdata = ( libc . CapData * 2 ) ( )
for cap in keep :
capdata [ 0 ] . effective |= ( 1 << cap )
capdata [ 0 ] . permitted |= ( 1 << cap )
libc . capset ( ctypes . byref ( libc . CapHeader ( version = libc . LINUX_CAPABILITY_VERSION_3 , pid = 0 ) ) , ctypes . byref ( capdata ) ) |
def lvscan ( self ) :
"""Probes the volume group for logical volumes and returns a list of
LogicalVolume instances : :
from lvm2py import *
lvm = LVM ( )
vg = lvm . get _ vg ( " myvg " )
lvs = vg . lvscan ( )
* Raises : *
* HandleError""" | self . open ( )
lv_list = [ ]
lv_handles = lvm_vg_list_lvs ( self . handle )
if not bool ( lv_handles ) :
return lv_list
lvh = dm_list_first ( lv_handles )
while lvh :
c = cast ( lvh , POINTER ( lvm_lv_list ) )
lv = LogicalVolume ( self , lvh = c . contents . lv )
lv_list . append ( lv )
if dm_list_... |
def _process ( self , startblock ) :
"""Processesing method .""" | log . debug ( "Processing blocks %d to %d" % ( startblock , startblock + BATCH_SIZE ) )
addresses = [ ]
for blockNum in range ( startblock , startblock + BATCH_SIZE ) :
block_hash = self . db . reader . _get_block_hash ( blockNum )
if block_hash is not None :
receipts = self . db . reader . _get_block_r... |
def matches ( self , filter , layer = Layer . NETWORK ) :
"""Evaluates the packet against the given packet filter string .
The remapped function is : :
BOOL WinDivertHelperEvalFilter (
_ _ in const char * filter ,
_ _ in WINDIVERT _ LAYER layer ,
_ _ in PVOID pPacket ,
_ _ in UINT packetLen ,
_ _ in P... | buff , buff_ = self . __to_buffers ( )
return windivert_dll . WinDivertHelperEvalFilter ( filter . encode ( ) , layer , ctypes . byref ( buff_ ) , len ( self . raw ) , ctypes . byref ( self . wd_addr ) ) |
def blame ( channel , rest , nick ) :
"Pass the buck !" | if rest :
blamee = rest
else :
blamee = channel
karma . Karma . store . change ( nick , - 1 )
if random . randint ( 1 , 10 ) == 1 :
yield "/me jumps atop the chair and points back at %s." % nick
yield ( "stop blaming the world for your problems, you bitter, " "two-faced sissified monkey!" )
else :
y... |
def add_to_submenu ( self , submenu_path , item ) :
'''add an item to a submenu using a menu path array''' | if len ( submenu_path ) == 0 :
self . add ( item )
return
for m in self . items :
if isinstance ( m , MPMenuSubMenu ) and submenu_path [ 0 ] == m . name :
m . add_to_submenu ( submenu_path [ 1 : ] , item )
return
self . add ( MPMenuSubMenu ( submenu_path [ 0 ] , [ ] ) )
self . add_to_submenu... |
def data ( self ) :
"""Get parsed DATA segment of the FCS file .""" | if self . _data is None :
with open ( self . path , 'rb' ) as f :
self . read_data ( f )
return self . _data |
def sse ( mean , estimator ) :
"""Description :
Calculates the Sum of Squared Errors ( SSE ) of
an estimation on flat numpy ndarrays .
Parameters :
mean : actual value ( numpy ndarray )
estimator : estimated value of the mean ( numpy ndarray )""" | return np . sum ( ( np . asarray ( estimator ) - np . asarray ( mean ) ) ** 2 , axis = 0 ) |
def load_data ( self , filename , * args , ** kwargs ) :
"""Load parameters from Excel spreadsheet .
: param filename : Name of Excel workbook with data .
: type filename : str
: returns : Data read from Excel workbook .
: rtype : dict""" | # workbook read from file
workbook = open_workbook ( filename , verbosity = True )
data = { }
# an empty dictionary to store data
# iterate through sheets in parameters
# iterate through the parameters on each sheet
for param , pval in self . parameters . iteritems ( ) :
sheet = pval [ 'extras' ] [ 'sheet' ]
# ... |
def annotation_rows ( prefix , annotations ) :
"""Helper function to extract N : and C : rows from annotations and pad their values""" | ncol = len ( annotations [ 'Column Name' ] )
return { name . replace ( prefix , '' , 1 ) : values + [ '' ] * ( ncol - len ( values ) ) for name , values in annotations . items ( ) if name . startswith ( prefix ) } |
def prog_callback ( prog , msg ) :
"""Program callback , calls prog with message in stdin""" | pipe = Popen ( prog , stdin = PIPE )
data = json . dumps ( msg )
pipe . stdin . write ( data . encode ( 'utf-8' ) )
pipe . stdin . close ( ) |
def updatej9DB ( dbname = abrevDBname , saveRawHTML = False ) :
"""Updates the database of Journal Title Abbreviations . Requires an internet connection . The data base is saved relative to the source file not the working directory .
# Parameters
_ dbname _ : ` optional [ str ] `
> The name of the database fi... | if saveRawHTML :
rawDir = '{}/j9Raws' . format ( os . path . dirname ( __file__ ) )
if not os . path . isdir ( rawDir ) :
os . mkdir ( rawDir )
_j9SaveCurrent ( sDir = rawDir )
dbLoc = os . path . join ( os . path . normpath ( os . path . dirname ( __file__ ) ) , dbname )
try :
with dbm . dumb .... |
def parse_args ( ) :
"""Parses command line arguments .""" | parser = argparse . ArgumentParser ( description = 'Tool to download dataset images.' )
parser . add_argument ( '--input_file' , required = True , help = 'Location of dataset.csv' )
parser . add_argument ( '--output_dir' , required = True , help = 'Output path to download images' )
parser . add_argument ( '--threads' ,... |
def _coords2index ( im , x , y , inverted = False ) :
"""Converts data coordinates to index coordinates of the array .
Parameters
im : An AxesImage instance
The image artist to operation on
x : number
The x - coordinate in data coordinates .
y : number
The y - coordinate in data coordinates .
invert... | xmin , xmax , ymin , ymax = im . get_extent ( )
if im . origin == 'upper' :
ymin , ymax = ymax , ymin
data_extent = mtransforms . Bbox ( [ [ ymin , xmin ] , [ ymax , xmax ] ] )
array_extent = mtransforms . Bbox ( [ [ 0 , 0 ] , im . get_array ( ) . shape [ : 2 ] ] )
trans = mtransforms . BboxTransformFrom ( data_ext... |
def status_line ( self ) :
"""Returns a status line for an item .
Only really interesting when called for a draft
item as it can tell you if the draft is the same as
another version .""" | date = self . date_published
status = self . state . title ( )
if self . state == self . DRAFT : # Check if this item has changed since
# our last publish
status = "Draft saved"
date = self . last_save
if date and self . last_save == self . last_scheduled : # We need to figure out if the item it is based on... |
def write_config ( cfg ) :
'''try writing config file to a default directory''' | cfg_path = '/usr/local/etc/freelan'
cfg_file = 'freelan_TEST.cfg'
cfg_lines = [ ]
if not isinstance ( cfg , FreelanCFG ) :
if not isinstance ( cfg , ( list , tuple ) ) :
print ( "Freelan write input can not be processed." )
return
cfg_lines = cfg
else :
cfg_lines = cfg . build ( )
if not os ... |
def active_repositories ( doc ) :
"""View for getting active repositories""" | if doc . get ( 'state' ) != 'deactivated' :
for repository_id , repo in doc . get ( 'repositories' , { } ) . items ( ) :
if repo . get ( 'state' ) != 'deactivated' :
repo [ 'id' ] = repository_id
repo [ 'organisation_id' ] = doc [ '_id' ]
yield repository_id , repo |
def umount ( self , forced = True ) :
"""Try to unmount our mount point .
Defaults to using forced method . If OS is Linux , it will not
delete the mount point .
Args :
forced : Bool whether to force the unmount . Default is True .""" | if self . is_mounted ( ) :
if is_osx ( ) :
cmd = [ "/usr/sbin/diskutil" , "unmount" , self . connection [ "mount_point" ] ]
if forced :
cmd . insert ( 2 , "force" )
subprocess . check_call ( cmd )
else :
cmd = [ "umount" , self . connection [ "mount_point" ] ]
... |
def queries_start_with ( queries , prefixes ) :
"""Check if any queries start with any item from * prefixes * .""" | for query in sqlparse . split ( queries ) :
if query and query_starts_with ( query , prefixes ) is True :
return True
return False |
def run_program ( program , args = None , ** subprocess_kwargs ) :
"""Run program in a separate process .
NOTE : returns the process object created by
` subprocess . Popen ( ) ` . This can be used with
` proc . communicate ( ) ` for example .
If ' shell ' appears in the kwargs , it must be False ,
otherwi... | if 'shell' in subprocess_kwargs and subprocess_kwargs [ 'shell' ] :
raise ProgramError ( "This function is only for non-shell programs, " "use run_shell_command() instead." )
fullcmd = find_program ( program )
if not fullcmd :
raise ProgramError ( "Program %s was not found" % program )
# As per subprocess , we ... |
def prep_jid ( nocache = False , passed_jid = None ) :
'''Call both with prep _ jid on all returners in multi _ returner
TODO : finish this , what do do when you get different jids from 2 returners . . .
since our jids are time based , this make this problem hard , because they
aren ' t unique , meaning that ... | jid = passed_jid
for returner_ in __opts__ [ CONFIG_KEY ] :
if jid is None :
jid = _mminion ( ) . returners [ '{0}.prep_jid' . format ( returner_ ) ] ( nocache = nocache )
else :
r_jid = _mminion ( ) . returners [ '{0}.prep_jid' . format ( returner_ ) ] ( nocache = nocache )
if r_jid != ... |
def lines ( self , encoding = None , errors = 'strict' , retain = True ) :
r"""Open this file , read all lines , return them in a list .
Optional arguments :
` encoding ` - The Unicode encoding ( or character set ) of
the file . The default is ` ` None ` ` , meaning the content
of the file is read as 8 - bi... | return self . text ( encoding , errors ) . splitlines ( retain ) |
def bounce_cluster ( name ) :
'''Bounce all Traffic Server nodes in the cluster . Bouncing Traffic Server
shuts down and immediately restarts Traffic Server , node - by - node .
. . code - block : : yaml
bounce _ ats _ cluster :
trafficserver . bounce _ cluster''' | ret = { 'name' : name , 'changes' : { } , 'result' : None , 'comment' : '' }
if __opts__ [ 'test' ] :
ret [ 'comment' ] = 'Bouncing cluster'
return ret
__salt__ [ 'trafficserver.bounce_cluster' ] ( )
ret [ 'result' ] = True
ret [ 'comment' ] = 'Bounced cluster'
return ret |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.