signature stringlengths 29 44.1k | implementation stringlengths 0 85.2k |
|---|---|
def next_tzolkin ( tzolkin , jd ) :
'''For a given tzolk ' in day , and a julian day count , find the next occurrance of that tzolk ' in after the date''' | if jd < EPOCH :
raise IndexError ( "Input day is before Mayan epoch." )
count1 = _tzolkin_count ( * to_tzolkin ( jd ) )
count2 = _tzolkin_count ( * tzolkin )
add_days = ( count2 - count1 ) % 260
return jd + add_days |
def rbridge_id ( self , ** kwargs ) :
"""Configures device ' s rbridge ID . Setting this property will need
a switch reboot
Args :
rbridge _ id ( str ) : The rbridge ID of the device on which BGP will be
configured in a VCS fabric .
get ( bool ) : Get config instead of editing config . ( True , False )
... | is_get_config = kwargs . pop ( 'get' , False )
if not is_get_config :
rbridge_id = kwargs . pop ( 'rbridge_id' )
else :
rbridge_id = ''
callback = kwargs . pop ( 'callback' , self . _callback )
rid_args = dict ( rbridge_id = rbridge_id )
rid = getattr ( self . _rbridge , 'rbridge_id_rbridge_id' )
config = rid (... |
def do ( self , x_orig ) :
"""Transform the unknowns to preconditioned coordinates
This method also transforms the gradient to original coordinates""" | if self . scales is None :
return x_orig
else :
return np . dot ( self . rotation . transpose ( ) , x_orig ) * self . scales |
def GET_names_owned_by_address ( self , path_info , blockchain , address ) :
"""Get all names owned by an address
Returns the list on success
Return 404 on unsupported blockchain
Return 502 on failure to get names for any non - specified reason""" | if not check_address ( address ) :
return self . _reply_json ( { 'error' : 'Invalid address' } , status_code = 400 )
if blockchain != 'bitcoin' :
return self . _reply_json ( { 'error' : 'Unsupported blockchain' } , status_code = 404 )
blockstackd_url = get_blockstackd_url ( )
address = str ( address )
subdomain... |
def some ( args ) :
"""% prog some fastafile listfile outfastafile
generate a subset of fastafile , based on a list""" | p = OptionParser ( some . __doc__ )
p . add_option ( "--exclude" , default = False , action = "store_true" , help = "Output sequences not in the list file [default: %default]" )
p . add_option ( "--uniprot" , default = False , action = "store_true" , help = "Header is from uniprot [default: %default]" )
opts , args = p... |
def WMITimeStrToRDFDatetime ( self , timestr ) :
"""Return RDFDatetime from string like 20140825162259.00000-420.
Args :
timestr : WMI time string
Returns :
rdfvalue . RDFDatetime
We have some timezone manipulation work to do here because the UTC offset is
in minutes rather than + - HHMM""" | # We use manual parsing here because the time functions provided ( datetime ,
# dateutil ) do not properly deal with timezone information .
offset_minutes = timestr [ 21 : ]
year = timestr [ : 4 ]
month = timestr [ 4 : 6 ]
day = timestr [ 6 : 8 ]
hours = timestr [ 8 : 10 ]
minutes = timestr [ 10 : 12 ]
seconds = timest... |
def _from_dict ( cls , _dict ) :
"""Initialize a ListCollectionFieldsResponse object from a json dictionary .""" | args = { }
if 'fields' in _dict :
args [ 'fields' ] = [ Field . _from_dict ( x ) for x in ( _dict . get ( 'fields' ) ) ]
return cls ( ** args ) |
def map_overlay_forecast ( self ) :
"""Returns capabilities data for forecast map overlays .""" | return json . loads ( self . _query ( LAYER , FORECAST , ALL , CAPABILITIES , "" ) . decode ( errors = "replace" ) ) |
def get_security_attributes_for_user ( user = None ) :
"""Return a SECURITY _ ATTRIBUTES structure with the SID set to the
specified user ( uses current user if none is specified ) .""" | if user is None :
user = get_current_user ( )
assert isinstance ( user , security . TOKEN_USER ) , ( "user must be TOKEN_USER instance" )
SD = security . SECURITY_DESCRIPTOR ( )
SA = security . SECURITY_ATTRIBUTES ( )
# by attaching the actual security descriptor , it will be garbage -
# collected with the security... |
def get_widget ( name ) :
"""Give back a widget class according to his name .""" | for widget in registry :
if widget . __name__ == name :
return widget
raise WidgetNotFound ( _ ( 'The widget %s has not been registered.' ) % name ) |
def get ( self ) :
"""Return form result""" | # It is import to avoid accessing Qt C + + object as it has probably
# already been destroyed , due to the Qt . WA _ DeleteOnClose attribute
if self . outfile :
if self . result in [ 'list' , 'dict' , 'OrderedDict' ] :
fd = open ( self . outfile + '.py' , 'w' )
fd . write ( str ( self . data ) )
... |
def bar ( it , label = '' , width = 32 , hide = None , empty_char = ' ' , filled_char = None , expected_size = None , every = 1 ) :
"""Progress iterator . Wrap your iterables with it .
@ type it : iterator
@ type label : str
@ type width : int
@ type hide : str , None
@ type empty _ char : float
@ type ... | if filled_char is None :
filled_char_tmp = b'\xe2\x96\x88' . decode ( )
filled_char = "\033[0;37m" + filled_char_tmp + "\033[0m"
count = len ( it ) if expected_size is None else expected_size
with Bar ( label = label , width = width , hide = hide , expected_size = count , every = every , empty_char = empty_char... |
def _compute_pga_rock ( self , C_PGA , mag , rjb ) :
"""Returns the PGA ( g ) on rock , as defined in equation 15""" | return np . exp ( self . _compute_linear_magnitude_term ( C_PGA , mag ) + self . _compute_simple_distance_term ( C_PGA , rjb ) ) |
def unmarshall_key ( self , key ) :
"""Unmarshalls a Crash key read from the database .
@ type key : str or buffer
@ param key : Key to convert .
@ rtype : L { Crash } key .
@ return : Converted key .""" | key = str ( key )
if self . escapeKeys :
key = key . decode ( 'hex' )
if self . compressKeys :
key = zlib . decompress ( key )
key = pickle . loads ( key )
return key |
def top ( ** kwargs ) :
'''Compile tops''' | # Node definitions path will be retrieved from args ( or set to default ) ,
# then added to ' salt _ data ' dict that is passed to the ' get _ pillars '
# function . The dictionary contains :
# - _ _ opts _ _
# - _ _ salt _ _
# - _ _ grains _ _
# - _ _ pillar _ _
# - minion _ id
# - path
# If successful , the function ... |
def btc_get_privkey_address ( privkey_info , ** blockchain_opts ) :
"""Get the address for a given private key info bundle
( be it multisig or singlesig )
Return the address on success
Raise exception on error""" | from . multisig import make_multisig_segwit_address_from_witness_script
if btc_is_singlesig ( privkey_info ) :
return btc_address_reencode ( ecdsalib . ecdsa_private_key ( privkey_info ) . public_key ( ) . address ( ) )
if btc_is_multisig ( privkey_info ) or btc_is_singlesig_segwit ( privkey_info ) :
redeem_scr... |
def resolve_exported_function ( self , pid , modName , procName ) :
"""Resolves the exported DLL function for the given process .
@ type pid : int
@ param pid : Process global ID .
@ type modName : str
@ param modName : Name of the module that exports the function .
@ type procName : str
@ param procNam... | aProcess = self . system . get_process ( pid )
aModule = aProcess . get_module_by_name ( modName )
if not aModule :
aProcess . scan_modules ( )
aModule = aProcess . get_module_by_name ( modName )
if aModule :
address = aModule . resolve ( procName )
return address
return None |
def login ( self ) :
"""Gets and stores an OAUTH token from Rightscale .""" | log . debug ( 'Logging into RightScale...' )
login_data = { 'grant_type' : 'refresh_token' , 'refresh_token' : self . refresh_token , }
response = self . _request ( 'post' , self . oauth_path , data = login_data )
raw_token = response . json ( )
auth_token = "Bearer %s" % raw_token [ 'access_token' ]
self . s . headers... |
def load_if_not_loaded ( widget , filenames , verbose = False , delay = 0.1 , force = False , local = True , evaluator = None ) :
"""Load a javascript file to the Jupyter notebook context ,
unless it was already loaded .""" | if evaluator is None :
evaluator = EVALUATOR
# default if not specified .
for filename in filenames :
loaded = False
if force or not filename in LOADED_JAVASCRIPT :
js_text = get_text_from_file_name ( filename , local )
if verbose :
print ( "loading javascript file" , filenam... |
def integers ( start , count ) :
'''Generates in sequence the integral numbers within a range .
Note : This method uses deferred execution .
Args :
start : The first integer in the sequence .
count : The number of sequential integers to generate .
Returns :
A Queryable over the specified range of intege... | if count < 0 :
raise ValueError ( "integers() count cannot be negative" )
return query ( irange ( start , start + count ) ) |
def search_meta ( self , attr , value = None , stronly = False ) :
"""Get a list of Symbols by searching a specific meta
attribute , and optionally the value .
Parameters
attr : str
The meta attribute to query .
value : None , str or list
The meta attribute to query . If you pass a float , or an int ,
... | if stronly :
qry = self . ses . query ( Symbol . name ) . join ( SymbolMeta )
else :
qry = self . ses . query ( Symbol ) . join ( SymbolMeta )
crits = [ ]
if value is None :
crits . append ( SymbolMeta . attr == attr )
else :
if isinstance ( value , str ) :
values = [ value ]
elif isinstance... |
def show_channel ( self , channel , owner ) :
'''List the channels for owner
If owner is none , the currently logged in user is used''' | url = '%s/channels/%s/%s' % ( self . domain , owner , channel )
res = self . session . get ( url )
self . _check_response ( res , [ 200 ] )
return res . json ( ) |
def node_application ( self , application_id ) :
"""An application resource contains information about a particular
application that was run or is running on this NodeManager .
: param str application _ id : The application id
: returns : API response object with JSON data
: rtype : : py : class : ` yarn _ ... | path = '/ws/v1/node/apps/{appid}' . format ( appid = application_id )
return self . request ( path ) |
def QA_fetch_get_stock_info ( code , ip = None , port = None ) :
'股票基本信息' | ip , port = get_mainmarket_ip ( ip , port )
api = TdxHq_API ( )
market_code = _select_market_code ( code )
with api . connect ( ip , port ) :
return api . to_df ( api . get_finance_info ( market_code , code ) ) |
def repeat_expt ( smplr , n_expts , n_labels , output_file = None ) :
"""Parameters
smplr : sub - class of PassiveSampler
sampler must have a sample _ distinct method , reset method and . . .
n _ expts : int
number of expts to run
n _ labels : int
number of labels to query from the oracle in each expt""... | FILTERS = tables . Filters ( complib = 'zlib' , complevel = 5 )
max_iter = smplr . _max_iter
n_class = smplr . _n_class
if max_iter < n_labels :
raise ValueError ( "Cannot query {} labels. Sampler " . format ( n_labels ) + "instance supports only {} iterations" . format ( max_iter ) )
if output_file is None : # Use... |
def delete_file ( self , name ) :
"""Deletes the file identified by ` ` name ` ` along with its metadata .
The file is removed from both the local store and the remote store .""" | if self . local_store :
lock = self . lock_manager . lock_for ( name )
lock . lock_exclusive ( )
try :
self . local_store . delete_file ( name )
finally :
lock . close ( )
if self . remote_store :
self . remote_store . delete_file ( name ) |
def train ( cls , rdd , k = 10 , maxIterations = 20 , docConcentration = - 1.0 , topicConcentration = - 1.0 , seed = None , checkpointInterval = 10 , optimizer = "em" ) :
"""Train a LDA model .
: param rdd :
RDD of documents , which are tuples of document IDs and term
( word ) count vectors . The term count v... | model = callMLlibFunc ( "trainLDAModel" , rdd , k , maxIterations , docConcentration , topicConcentration , seed , checkpointInterval , optimizer )
return LDAModel ( model ) |
def _start_server ( self , * args ) :
"""Run the node local server""" | self . log ( "Starting server" , args )
secure = self . certificate is not None
if secure :
self . log ( "Running SSL server with cert:" , self . certificate )
else :
self . log ( "Running insecure server without SSL. Do not use without SSL proxy in production!" , lvl = warn )
try :
self . server = Server (... |
def get_counter ( data , base ) :
"""See setCounters ( ) / getCounters ( ) methods in IJ source , ij / gui / PointRoi . java .""" | b0 = data [ base ]
b1 = data [ base + 1 ]
b2 = data [ base + 2 ]
b3 = data [ base + 3 ]
counter = b3
position = ( b1 << 8 ) + b2
return counter , position |
def get_homecall ( callsign ) :
"""Strips off country prefixes ( HC2 / DH1TW ) and activity suffixes ( DH1TW / P ) .
Args :
callsign ( str ) : Amateur Radio callsign
Returns :
str : callsign without country / activity pre / suffixes
Raises :
ValueError : No callsign found in string
Example :
The fol... | callsign = callsign . upper ( )
homecall = re . search ( '[\d]{0,1}[A-Z]{1,2}\d([A-Z]{1,4}|\d{3,3}|\d{1,3}[A-Z])[A-Z]{0,5}' , callsign )
if homecall :
homecall = homecall . group ( 0 )
return homecall
else :
raise ValueError |
def cli ( ctx , config_file = None , requirements = None , profile = None ) :
'''An abstraction layer for data storage systems
DataFS is a package manager for data . It manages file versions ,
dependencies , and metadata for individual use or large organizations .
For more information , see the docs at https ... | ctx . obj = _DataFSInterface ( )
ctx . obj . config_file = config_file
ctx . obj . requirements = requirements
ctx . obj . profile = profile
def teardown ( ) :
if hasattr ( ctx . obj , 'api' ) :
ctx . obj . api . close ( )
ctx . call_on_close ( teardown ) |
def auto_detect_adjacent_shapes ( svg_source , shape_i_attr = 'id' , layer_name = 'Connections' , shapes_xpath = '//svg:path | //svg:polygon' , extend = 1.5 ) :
'''Attempt to automatically find " adjacent " shapes in a SVG layer .
In a layer within a new SVG document , draw each detected connection between
the ... | # Read SVG polygons into dataframe , one row per polygon vertex .
df_shapes = svg_shapes_to_df ( svg_source , xpath = shapes_xpath )
df_shapes = compute_shape_centers ( df_shapes , shape_i_attr )
df_shape_connections = extract_adjacent_shapes ( df_shapes , shape_i_attr , extend = extend )
# Parse input file .
xml_root ... |
def _set_clear_mpls_auto_bandwidth_sample_history_lsp ( self , v , load = False ) :
"""Setter method for clear _ mpls _ auto _ bandwidth _ sample _ history _ lsp , mapped from YANG variable / brocade _ mpls _ rpc / clear _ mpls _ auto _ bandwidth _ sample _ history _ lsp ( rpc )
If this variable is read - only ( ... | if hasattr ( v , "_utype" ) :
v = v . _utype ( v )
try :
t = YANGDynClass ( v , base = clear_mpls_auto_bandwidth_sample_history_lsp . clear_mpls_auto_bandwidth_sample_history_lsp , is_leaf = True , yang_name = "clear-mpls-auto-bandwidth-sample-history-lsp" , rest_name = "clear-mpls-auto-bandwidth-sample-history... |
def minion_runner ( self , clear_load ) :
'''Execute a runner from a minion , return the runner ' s function data
: param dict clear _ load : The minion payload
: rtype : dict
: return : The runner function data''' | load = self . __verify_load ( clear_load , ( 'fun' , 'arg' , 'id' , 'tok' ) )
if load is False :
return { }
else :
return self . masterapi . minion_runner ( clear_load ) |
def and_ ( cls , obj , ** kwargs ) :
"""Query an object
: param obj :
object to test
: param kwargs : query specified in kwargssql
: return :
` True ` if all ` kwargs ` expression are ` True ` , ` False ` otherwise .
: rtype : bool""" | return cls . __eval_seqexp ( obj , operator . and_ , ** kwargs ) |
def check_sorting_order ( numbers_list ) :
'''Checks if the list of integers is sorted in ascending order .
Returns False , if same number appears more than twice . Considers
only positive numbers .
Usage :
check _ sorting _ order ( [ 5 ] ) ➞ True
check _ sorting _ order ( [ 1 , 2 , 3 , 4 , 5 ] ) ➞ True
... | num_counter = dict ( [ ( num , 0 ) for num in numbers_list ] )
for num in numbers_list :
num_counter [ num ] += 1
if any ( num_counter [ num ] > 2 for num in numbers_list ) :
return False
else :
if numbers_list == sorted ( numbers_list ) :
return True
else :
return False |
def _offset_from_spaces ( dom , ran ) :
"""Return index offset corresponding to given spaces .""" | affected = np . not_equal ( dom . shape , ran . shape )
diff_l = np . abs ( ran . grid . min ( ) - dom . grid . min ( ) )
offset_float = diff_l / dom . cell_sides
offset = np . around ( offset_float ) . astype ( int )
for i in range ( dom . ndim ) :
if affected [ i ] and not np . isclose ( offset [ i ] , offset_flo... |
def format_diff_xml ( a_xml , b_xml ) :
"""Create a diff between two XML documents .
Args :
a _ xml : str
b _ xml : str
Returns :
str : ` Differ ` - style delta""" | return '\n' . join ( difflib . ndiff ( reformat_to_pretty_xml ( a_xml ) . splitlines ( ) , reformat_to_pretty_xml ( b_xml ) . splitlines ( ) , ) ) |
def setup_forward_or_backward_execution ( self ) :
"""Sets up the execution of the concurrency states dependent on if the state is executed forward of backward .
: return :""" | if self . backward_execution : # pop the return item of this concurrency state to get the correct scoped data
last_history_item = self . execution_history . pop_last_item ( )
assert isinstance ( last_history_item , ReturnItem )
self . scoped_data = last_history_item . scoped_data
# get the concurrency i... |
def rel_curve_to ( self , dx1 , dy1 , dx2 , dy2 , dx3 , dy3 ) :
"""Relative - coordinate version of : meth : ` curve _ to ` .
All offsets are relative to the current point .
Adds a cubic Bézier spline to the path from the current point
to a point offset from the current point by ` ` ( dx3 , dy3 ) ` ` ,
usi... | cairo . cairo_rel_curve_to ( self . _pointer , dx1 , dy1 , dx2 , dy2 , dx3 , dy3 )
self . _check_status ( ) |
def export ( self , fn : PathOrStr , ** kwargs ) :
"Export the minimal state and save it in ` fn ` to load an empty version for inference ." | pickle . dump ( self . get_state ( ** kwargs ) , open ( fn , 'wb' ) ) |
def randhex ( ndigits : int ) -> str :
"""Return a random text string of hexadecimal characters .
The string has * ndigits * random digits .
Raises ValueError if ndigits < = 0 , and TypeError if it ' s not an integer .
> > > randhex ( 16 ) # doctest : + SKIP
'56054d728fc56f63'""" | if not isinstance ( ndigits , int ) :
raise TypeError ( 'number of digits must be an integer' )
if ndigits <= 0 :
raise ValueError ( 'number of digits must be greater than zero' )
nbytes = ceil ( ndigits / 2 )
rbytes = random_randbytes ( nbytes )
hexstr = rbytes . hex ( ) [ : ndigits ]
return hexstr |
def get_node ( self , obj , cls = type ( None ) , hist = { } ) :
"""Returns the node corresponding to obj . If does not already exist
then it will create it .""" | # ~ ident = getattr ( obj , ' ident ' , obj )
if obj in self . modules and is_module ( obj , cls ) :
return self . modules [ obj ]
elif obj in self . submodules and is_submodule ( obj , cls ) :
return self . submodules [ obj ]
elif obj in self . types and is_type ( obj , cls ) :
return self . types [ obj ]
... |
def find_nested ( self ) :
"""Returns a dictionary mapping parent intervals to sets of
intervals overlapped by and contained in the parent .
Completes in O ( n ^ 2 ) time .
: rtype : dict of [ Interval , set of Interval ]""" | result = { }
def add_if_nested ( ) :
if parent . contains_interval ( child ) :
if parent not in result :
result [ parent ] = set ( )
result [ parent ] . add ( child )
long_ivs = sorted ( self . all_intervals , key = Interval . length , reverse = True )
for i , parent in enumerate ( long_... |
def debug_sleep ( self , timeout ) :
"""Suspend connection for timeout seconds .""" | fut = self . execute ( b'DEBUG' , b'SLEEP' , timeout )
return wait_ok ( fut ) |
def convert ( self , layer = 2 , split_sign = '_' , * args , ** kwargs ) :
"""convert data to DataFrame""" | return series2df ( self . series , * args , ** kwargs ) |
def _to_dict ( self ) :
"""Return a json dictionary representing this model .""" | _dict = { }
if hasattr ( self , 'name' ) and self . name is not None :
_dict [ 'name' ] = self . name
if hasattr ( self , 'dbpedia_resource' ) and self . dbpedia_resource is not None :
_dict [ 'dbpedia_resource' ] = self . dbpedia_resource
if hasattr ( self , 'subtype' ) and self . subtype is not None :
_di... |
def _show_message ( self , text ) :
"""Show message on splash screen .""" | self . splash . showMessage ( text , Qt . AlignBottom | Qt . AlignCenter | Qt . AlignAbsolute , QColor ( Qt . white ) ) |
def rollback ( self ) :
"""Rolls back pending mutations .
Keep in mind that NoTransactionBatch splits all mutations into smaller
batches and commit them as soon as mutation buffer reaches maximum length .
That ' s why rollback method will only roll back pending mutations from the
buffer , but won ' t be abl... | try :
if self . _cur_batch :
self . _cur_batch . rollback ( )
except ValueError : # ignore " Batch must be in progress to rollback " error
pass
self . _cur_batch = None
self . _num_mutations = 0 |
def iter_encode ( input , encoding = UTF8 , errors = 'strict' ) :
"""“ Pull ” - based encoder .
: param input : An iterable of Unicode strings .
: param encoding : An : class : ` Encoding ` object or a label string .
: param errors : Type of error handling . See : func : ` codecs . register ` .
: raises : :... | # Fail early if ` encoding ` is an invalid label .
encode = IncrementalEncoder ( encoding , errors ) . encode
return _iter_encode_generator ( input , encode ) |
def display_items ( self ) -> typing . List [ Display ] :
"""Return the list of display items .
: return : The list of : py : class : ` nion . swift . Facade . Display ` objects .
. . versionadded : : 1.0
Scriptable : Yes""" | return [ Display ( display_item ) for display_item in self . __document_model . display_items ] |
def start ( self ) :
"""Start worker processes and a control loop""" | setproctitle ( 'oq-zworkerpool %s' % self . ctrl_url [ 6 : ] )
# strip tcp : / /
# start workers
self . workers = [ ]
for _ in range ( self . num_workers ) :
sock = z . Socket ( self . task_out_port , z . zmq . PULL , 'connect' )
proc = multiprocessing . Process ( target = self . worker , args = ( sock , ) )
... |
def get_atoms ( structure , ** kwargs ) :
"""Returns ASE Atoms object from pymatgen structure .
Args :
structure : pymatgen . core . structure . Structure
* * kwargs : other keyword args to pass into the ASE Atoms constructor
Returns :
ASE Atoms object""" | if not structure . is_ordered :
raise ValueError ( "ASE Atoms only supports ordered structures" )
symbols = [ str ( site . specie . symbol ) for site in structure ]
positions = [ site . coords for site in structure ]
cell = structure . lattice . matrix
return Atoms ( symbols = symbols , positions = positions , pbc ... |
def keepalive ( self ) :
"""启动保持在线的进程""" | if self . heart_thread . is_alive ( ) :
self . heart_active = True
else :
self . heart_thread . start ( ) |
def __get_base_path ( self ) :
"""Return the file ' s directory and file name , with the
suffix stripped .""" | entry = self . get ( )
return SCons . Subst . SpecialAttrWrapper ( SCons . Util . splitext ( entry . get_path ( ) ) [ 0 ] , entry . name + "_base" ) |
def _fit_overlay_lists ( self , text , start , matchers , ** kw ) :
"""Return a list of overlays that start at start .""" | if matchers :
for o in matchers [ 0 ] . fit_overlays ( text , start ) :
for rest in self . _fit_overlay_lists ( text , o . end , matchers [ 1 : ] ) :
yield [ o ] + rest
else :
yield [ ] |
def set_properties ( self , properties , recursive = True ) :
"""Adds new or modifies existing properties listed in properties
properties - is a dict which contains the property names and values to set .
Property values can be a list or tuple to set multiple values
for a key .
recursive - on folders propert... | if not properties :
return
return self . _accessor . set_properties ( self , properties , recursive ) |
def get_output_jsonpath_with_name ( self , sub_output = None ) :
"""If ExtractorProcessor has a name defined , return
a JSONPath that has a filter on that name""" | if self . name is None :
return None
output_jsonpath_field = self . get_output_jsonpath_field ( sub_output )
extractor_filter = "name='{}'" . format ( self . name )
output_jsonpath = "{}[?{}].(result[*][value])" . format ( output_jsonpath_field , extractor_filter )
return output_jsonpath |
def prepare_outdir ( outdir ) :
"""Creates the output directory if not existing .
If outdir is None or if no output _ files are provided nothing happens .
: param outdir : The output directory to create .""" | if outdir :
outdir = os . path . expanduser ( outdir )
if not os . path . isdir ( outdir ) :
try :
os . makedirs ( outdir )
except os . error as e :
raise JobExecutionError ( 'Failed to create outdir "{}".\n{}' . format ( outdir , str ( e ) ) ) |
def solve_resolve ( expr , vars ) :
"""Use IStructured . resolve to get member ( rhs ) from the object ( lhs ) .
This operation supports both scalars and repeated values on the LHS -
resolving from a repeated value implies a map - like operation and returns a
new repeated values .""" | objs , _ = __solve_for_repeated ( expr . lhs , vars )
member = solve ( expr . rhs , vars ) . value
try :
results = [ structured . resolve ( o , member ) for o in repeated . getvalues ( objs ) ]
except ( KeyError , AttributeError ) : # Raise a better exception for the non - existent member .
raise errors . Efilt... |
def put_if_not_exists ( self , key , value , lease = None ) :
"""Atomically puts a value only if the key previously had no value .
This is the etcdv3 equivalent to setting a key with the etcdv2
parameter prevExist = false .
: param key : key in etcd to put
: param value : value to be written to key
: type... | status , _ = self . transaction ( compare = [ self . transactions . create ( key ) == '0' ] , success = [ self . transactions . put ( key , value , lease = lease ) ] , failure = [ ] , )
return status |
def log ( self , facility , level , text , pid = False ) :
"""Send the message text to all registered hosts .
The facility and level will be used to create the packet ' s PRI
part . The HEADER will be automatically determined from the
current time and hostname . The MSG will be set from the
running program ... | pri = PRI ( facility , level )
header = HEADER ( )
if pid :
msg = MSG ( content = text , pid = os . getpid ( ) )
else :
msg = MSG ( content = text )
packet = Packet ( pri , header , msg )
self . _send_packet_to_hosts ( packet ) |
def get_itemstr_list ( list_ , ** listkw ) :
"""TODO : have this replace dict _ itemstr list or at least most functionality in
it . have it make two itemstr lists over keys and values and then combine
them .""" | import utool as ut
_valstr = _make_valstr ( ** listkw )
def make_item_str ( item ) :
item_str = _valstr ( item )
return item_str
items = list ( list_ )
itemstr_list = [ make_item_str ( item ) for item in items ]
dosort = listkw . get ( 'sorted_' , None )
if dosort is None : # Force orderings on sets .
dosor... |
def send_by_packet ( self , data ) :
"""Send data by packet on socket""" | total_sent = 0
while total_sent < PACKET_SIZE :
sent = self . sock . send ( data [ total_sent : ] )
if sent == 0 :
raise RuntimeError ( "socket connection broken" )
total_sent += sent
return total_sent |
def uid ( self , p_todo ) :
"""Returns the unique text - based ID for a todo item .""" | try :
return self . _todo_id_map [ p_todo ]
except KeyError as ex :
raise InvalidTodoException from ex |
def do_execute ( self ) :
"""The actual execution of the actor .
: return : None if successful , otherwise error message
: rtype : str""" | if isinstance ( self . input . payload , Instances ) :
inst = None
data = self . input . payload
else :
inst = self . input . payload
data = inst . dataset
retrain = False
if ( self . _header is None ) or ( self . _header . equal_headers ( data ) is not None ) or ( inst is None ) :
retrain = True
... |
def _rename ( self ) :
"""Called during a PUT request where the action specifies
a rename operation . Returns resource URI of the renamed file .""" | newname = self . action [ 'newname' ]
try :
newpath = self . fs . rename ( self . fp , newname )
except OSError :
raise tornado . web . HTTPError ( 400 )
return newpath |
def differing_blocks ( self ) :
""": returns : A list of block matches which appear to differ""" | differing_blocks = [ ]
for ( block_a , block_b ) in self . _block_matches :
if not self . blocks_probably_identical ( block_a , block_b ) :
differing_blocks . append ( ( block_a , block_b ) )
return differing_blocks |
def spawn_daemon ( self , pgrpfile = None , outfile = "out.txt" ) :
'''Causes this arbiters run ( ) function to be executed in a newly spawned
daemon process .
Parameters
pgrpfile : str , optional
Path at which to write a pgrpfile ( file containing the process
group id of the daemon process and its childr... | if spawn_daemon ( self . fork , pgrpfile , outfile ) :
return
signal . signal ( signal . SIGTERM , lambda signal , frame : self . stop ( ) )
self . run ( False ) |
def resolved_row ( objs , geomatcher ) :
"""Temporarily insert ` ` RoW ` ` into ` ` geomatcher . topology ` ` , defined by the topo faces not used in ` ` objs ` ` .
Will overwrite any existing ` ` RoW ` ` .
On exiting the context manager , ` ` RoW ` ` is deleted .""" | def get_locations ( lst ) :
for elem in lst :
try :
yield elem [ 'location' ]
except TypeError :
yield elem
geomatcher [ 'RoW' ] = geomatcher . faces . difference ( reduce ( set . union , [ geomatcher [ obj ] for obj in get_locations ( objs ) ] ) )
yield geomatcher
del geomat... |
def registerAugmentation ( self , * names ) :
"""Register table extension .
SNMP SMI provides a way to extend already existing SMI table with
another table . This method registers dependent ( extending ) table
( or type : py : class : ` MibTableRow ` ) to already existing table .
Whenever a row of the paren... | for name in names :
if name in self . _augmentingRows :
raise error . SmiError ( 'Row %s already augmented by %s::%s' % ( self . name , name [ 0 ] , name [ 1 ] ) )
self . _augmentingRows . add ( name )
return self |
def unwrap ( self , message , signature ) :
"""NTLM GSSUnwrap ( )
: param message : The message to be decrypted
: return : The decrypted message""" | plain_text = _Ntlm2Session . decrypt ( self , message )
_Ntlm2Session . verify ( self , plain_text , signature )
return plain_text |
def MapEncoder ( field_descriptor ) :
"""Encoder for extensions of MessageSet .
Maps always have a wire format like this :
message MapEntry {
key _ type key = 1;
value _ type value = 2;
repeated MapEntry map = N ;""" | # Can ' t look at field _ descriptor . message _ type . _ concrete _ class because it may
# not have been initialized yet .
message_type = field_descriptor . message_type
encode_message = MessageEncoder ( field_descriptor . number , False , False )
def EncodeField ( write , value ) :
for key in value :
entr... |
def setup_coords ( arr_names = None , sort = [ ] , dims = { } , ** kwargs ) :
"""Sets up the arr _ names dictionary for the plot
Parameters
arr _ names : string , list of strings or dictionary
Set the unique array names of the resulting arrays and ( optionally )
dimensions .
- if string : same as list of ... | try :
return OrderedDict ( arr_names )
except ( ValueError , TypeError ) : # ValueError for cyordereddict , TypeError for collections . OrderedDict
pass
if arr_names is None :
arr_names = repeat ( 'arr{0}' )
elif isstring ( arr_names ) :
arr_names = repeat ( arr_names )
dims = OrderedDict ( dims )
for k... |
def list_upgrades ( refresh = True , ** kwargs ) : # pylint : disable = W0613
'''List all available package upgrades on this system
CLI Example :
. . code - block : : bash
salt ' * ' pkgutil . list _ upgrades''' | if salt . utils . data . is_true ( refresh ) :
refresh_db ( )
upgrades = { }
lines = __salt__ [ 'cmd.run_stdout' ] ( '/opt/csw/bin/pkgutil -A --parse' ) . splitlines ( )
for line in lines :
comps = line . split ( '\t' )
if comps [ 2 ] == "SAME" :
continue
if comps [ 2 ] == "not installed" :
... |
def warn_with_traceback ( message , category , filename , lineno , file = None , line = None ) :
"""Get full tracebacks when warning is raised by setting
warnings . showwarning = warn _ with _ traceback
See also
http : / / stackoverflow . com / questions / 22373927 / get - traceback - of - warnings""" | import traceback
traceback . print_stack ( )
log = file if hasattr ( file , 'write' ) else sys . stderr
settings . write ( warnings . formatwarning ( message , category , filename , lineno , line ) ) |
def find_referenced_templates ( template , search_path ) :
"""Returns a list of files which can be either { % imported % } ,
{ % extended % } or { % included % } within a template .""" | from jinja2 import Environment , meta
env = Environment ( )
ast = env . parse ( template . read ( ) )
referenced_templates = list ( meta . find_referenced_templates ( ast ) )
def realpath ( tpl ) :
for path in search_path :
t = os . path . realpath ( os . path . join ( path , tpl ) )
if os . path . ... |
def computeContribs ( urls , rank ) :
"""Calculates URL contributions to the rank of other URLs .""" | num_urls = len ( urls )
for url in urls :
yield ( url , rank / num_urls ) |
def values ( self ) :
"""Return the ` list representation ` _ of the binary tree .
. . _ list representation :
https : / / en . wikipedia . org / wiki / Binary _ tree # Arrays
: return : List representation of the binary tree , which is a list of
node values in breadth - first order starting from the root (... | current_nodes = [ self ]
has_more_nodes = True
values = [ ]
while has_more_nodes :
has_more_nodes = False
next_nodes = [ ]
for node in current_nodes :
if node is None :
values . append ( None )
next_nodes . extend ( ( None , None ) )
continue
if node . lef... |
def probability_of_n_purchases_up_to_time ( self , t , n ) :
r"""Compute the probability of n purchases .
. . math : : P ( N ( t ) = n | \ text { model } )
where N ( t ) is the number of repeat purchases a customer makes in t
units of time .
Parameters
t : float
number units of time
n : int
number o... | r , alpha , a , b = self . _unload_params ( "r" , "alpha" , "a" , "b" )
first_term = ( beta ( a , b + n ) / beta ( a , b ) * gamma ( r + n ) / gamma ( r ) / gamma ( n + 1 ) * ( alpha / ( alpha + t ) ) ** r * ( t / ( alpha + t ) ) ** n )
if n > 0 :
j = np . arange ( 0 , n )
finite_sum = ( gamma ( r + j ) / gamma... |
def checkout ( cwd , remote , target = None , user = None , username = None , password = None , * opts ) :
'''Download a working copy of the remote Subversion repository
directory or file
cwd
The path to the Subversion repository
remote : None
URL to checkout
target : None
The name to give the file or... | opts += ( remote , )
if target :
opts += ( target , )
return _run_svn ( 'checkout' , cwd , user , username , password , opts ) |
def render_customizations ( self ) :
"""Customize template for site user specified customizations""" | disable_plugins = self . pt . customize_conf . get ( 'disable_plugins' , [ ] )
if not disable_plugins :
logger . debug ( 'No site-user specified plugins to disable' )
else :
for plugin in disable_plugins :
try :
self . pt . remove_plugin ( plugin [ 'plugin_type' ] , plugin [ 'plugin_name' ] ... |
def _setup_metric_group_definitions ( self ) :
"""Return the dict of MetricGroupDefinition objects for this metrics
context , by processing its ' metric - group - infos ' property .""" | # Dictionary of MetricGroupDefinition objects , by metric group name
metric_group_definitions = dict ( )
for mg_info in self . properties [ 'metric-group-infos' ] :
mg_name = mg_info [ 'group-name' ]
mg_def = MetricGroupDefinition ( name = mg_name , resource_class = _resource_class_from_group ( mg_name ) , metr... |
def components ( self ) :
"""Returns full : class : ` dict ` of : class : ` Component ` instances , after
a successful : meth : ` build `
: return : dict of named : class : ` Component ` instances
: rtype : : class : ` dict `
For more information read about the : ref : ` parts _ assembly - build - cycle ` .... | if self . _components is None :
self . build ( recursive = False )
return self . _components |
def eliminate_sequential_children ( paths ) :
"helper for infer _ columns . removes paths that are direct children of the n - 1 or n - 2 path" | return [ p for i , p in enumerate ( paths ) if not ( ( i > 0 and paths [ i - 1 ] == p [ : - 1 ] ) or ( i > 1 and paths [ i - 2 ] == p [ : - 1 ] ) ) ] |
def _unescape ( self , msg ) :
"""Removes double quotes that were used to escape double quotes . Expects
a string without its delimiting quotes , or a number . Returns a new
unescaped string .""" | if isinstance ( msg , ( int , float , long ) ) :
return msg
unescaped = ''
i = 0
while i < len ( msg ) :
unescaped += msg [ i ]
if msg [ i ] == '"' :
i += 1
i += 1
return unescaped |
def get_dweets_for ( thing_name , key = None , session = None ) :
"""Read all the dweets for a dweeter""" | if key is not None :
params = { 'key' : key }
else :
params = None
return _request ( 'get' , '/get/dweets/for/{0}' . format ( thing_name ) , params = params , session = None ) |
def text_to_bool ( value : str ) -> bool :
"""Tries to convert a text value to a bool . If unsuccessful returns if value is None or not
: param value : Value to check""" | try :
return bool ( strtobool ( value ) )
except ( ValueError , AttributeError ) :
return value is not None |
def show_letter ( self , s , text_colour = [ 255 , 255 , 255 ] , back_colour = [ 0 , 0 , 0 ] ) :
"""Displays a single text character on the LED matrix using the specified
colours""" | if len ( s ) > 1 :
raise ValueError ( 'Only one character may be passed into this method' )
# We must rotate the pixel map left through 90 degrees when drawing
# text , see _ load _ text _ assets
previous_rotation = self . _rotation
self . _rotation -= 90
if self . _rotation < 0 :
self . _rotation = 270
dummy_c... |
def create_link ( self , blogname , ** kwargs ) :
"""Create a link post on a blog
: param blogname : a string , the url of the blog you want to post to .
: param state : a string , The state of the post .
: param tags : a list of tags that you want applied to the post
: param tweet : a string , the customiz... | kwargs . update ( { "type" : "link" } )
return self . _send_post ( blogname , kwargs ) |
def main ( ylib : str = None , path : str = None , scope : ValidationScope = ValidationScope . all , ctype : ContentType = ContentType . config , set_id : bool = False , tree : bool = False , no_types : bool = False , digest : bool = False , validate : str = None ) -> int :
"""Entry - point for a validation script ... | if ylib is None :
parser = argparse . ArgumentParser ( prog = "yangson" , description = "Validate JSON data against a YANG data model." )
parser . add_argument ( "-V" , "--version" , action = "version" , version = f"%(prog)s {pkg_resources.get_distribution('yangson').version}" )
parser . add_argument ( "yli... |
def strip_line_magic_v2 ( cls , line ) :
"""strip _ line _ magic ( ) implementation for Python 2""" | matches = re . findall ( "magic\(([^]]+)" , line )
if matches and matches [ 0 ] : # This line contains the pattern
match = matches [ 0 ]
if match [ - 1 ] == ')' :
match = match [ : - 1 ]
# Just because the re way is hard
stripped = eval ( match )
magic_kind = stripped . split ( ' ' ) [ 0... |
def update_pmag_tables ( self ) :
"""Reads pmag tables from data model 2.5 and updates them with updates
their data""" | pmag_specimens , pmag_samples , pmag_sites = [ ] , [ ] , [ ]
print ( "-I- Reading previous interpretations from specimen/sample/site tables" )
try :
pmag_specimens , file_type = pmag . magic_read ( os . path . join ( self . WD , "pmag_specimens.txt" ) )
except :
print ( "-I- Can't read pmag_specimens.txt" )
try... |
def take_nd ( self , indexer , axis , new_mgr_locs = None , fill_tuple = None ) :
"""Take values according to indexer and return them as a block . bb""" | # algos . take _ nd dispatches for DatetimeTZBlock , CategoricalBlock
# so need to preserve types
# sparse is treated like an ndarray , but needs . get _ values ( ) shaping
values = self . values
if self . is_sparse :
values = self . get_values ( )
if fill_tuple is None :
fill_value = self . fill_value
new_... |
def pluralize ( word ) :
"""Return the plural form of a word .
Examples : :
> > > pluralize ( " post " )
" posts "
> > > pluralize ( " octopus " )
" octopi "
> > > pluralize ( " sheep " )
" sheep "
> > > pluralize ( " CamelOctopus " )
" CamelOctopi " """ | if not word or word . lower ( ) in UNCOUNTABLES :
return word
else :
for rule , replacement in PLURALS :
if re . search ( rule , word ) :
return re . sub ( rule , replacement , word )
return word |
async def list_mailboxes ( self , ref_name : str , filter_ : str , subscribed : bool = False , selected : SelectedMailbox = None ) -> Tuple [ Iterable [ Tuple [ str , Optional [ str ] , Sequence [ bytes ] ] ] , Optional [ SelectedMailbox ] ] :
"""List the mailboxes owned by the user .
See Also :
` RFC 3501 6.3.... | ... |
def setup_mflist_budget_obs ( list_filename , flx_filename = "flux.dat" , vol_filename = "vol.dat" , start_datetime = "1-1'1970" , prefix = '' , save_setup_file = False ) :
"""setup observations of budget volume and flux from modflow list file . writes
an instruction file and also a _ setup _ . csv to use when co... | flx , vol = apply_mflist_budget_obs ( list_filename , flx_filename , vol_filename , start_datetime )
_write_mflist_ins ( flx_filename + ".ins" , flx , prefix + "flx" )
_write_mflist_ins ( vol_filename + ".ins" , vol , prefix + "vol" )
# run ( " inschek { 0 } . ins { 0 } " . format ( flx _ filename ) )
# run ( " inschek... |
def amazon_elb_trace_id ( ) :
"""Get the amazon ELB trace id from current Flask request context
: return : The found Trace - ID or None if not found
: rtype : str | None""" | amazon_request_id = request . headers . get ( 'X-Amzn-Trace-Id' , '' )
trace_id_params = dict ( x . split ( '=' ) if '=' in x else ( x , None ) for x in amazon_request_id . split ( ';' ) )
if 'Self' in trace_id_params :
return trace_id_params [ 'Self' ]
if 'Root' in trace_id_params :
return trace_id_params [ 'R... |
def _utime ( self , path , modified , accessed ) :
"""Set the * accessed * and * modified * times of a resource .""" | if accessed is not None or modified is not None :
accessed = int ( modified if accessed is None else accessed )
modified = int ( accessed if modified is None else modified )
self . _sftp . utime ( path , ( accessed , modified ) )
else :
self . _sftp . utime ( path , None ) |
def word ( self , _id , padding = 75 ) :
"""Get words""" | word = self . words [ _id ] [ 2 ]
vec = word_to_vector ( word )
vec += [ - 1 ] * ( padding - len ( vec ) )
return np . array ( vec , dtype = np . int32 ) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.