signature stringlengths 29 44.1k | implementation stringlengths 0 85.2k |
|---|---|
def get_sn ( unit ) :
"""获取文本行的句子数量
Keyword arguments :
unit - - 文本行
Return :
sn - - 句数""" | sn = 0
match_re = re . findall ( str ( sentence_delimiters ) , unit )
if match_re :
string = '' . join ( match_re )
sn = len ( string )
return int ( sn ) |
def _nutation ( date , eop_correction = True , terms = 106 ) :
"""Model 1980 of nutation as described in Vallado p . 224
Args :
date ( beyond . utils . date . Date )
eop _ correction ( bool ) : set to ` ` True ` ` to include model correction
from ' finals ' files .
terms ( int )
Return :
tuple : 3 - e... | ttt = date . change_scale ( 'TT' ) . julian_century
r = 360.
# in arcsecond
epsilon_bar = 84381.448 - 46.8150 * ttt - 5.9e-4 * ttt ** 2 + 1.813e-3 * ttt ** 3
# Conversion to degrees
epsilon_bar /= 3600.
# mean anomaly of the moon
m_m = 134.96298139 + ( 1325 * r + 198.8673981 ) * ttt + 0.0086972 * ttt ** 2 + 1.78e-5 * t... |
def _get_assistive_access ( ) :
'''Get a list of all of the assistive access applications installed ,
returns as a ternary showing whether each app is enabled or not .''' | cmd = 'sqlite3 "/Library/Application Support/com.apple.TCC/TCC.db" "SELECT * FROM access"'
call = __salt__ [ 'cmd.run_all' ] ( cmd , output_loglevel = 'debug' , python_shell = False )
if call [ 'retcode' ] != 0 :
comment = ''
if 'stderr' in call :
comment += call [ 'stderr' ]
if 'stdout' in call :
... |
def get_mark_css ( aes_name , css_value ) :
"""Generate CSS class for < mark > tag .
Parameters
aes _ name : str
The name of the class .
css _ value : str
The value for the CSS property defined by aes _ name .
Returns
list of str
The CSS codeblocks""" | css_prop = AES_CSS_MAP [ aes_name ]
if isinstance ( css_value , list ) :
return get_mark_css_for_rules ( aes_name , css_prop , css_value )
else :
return get_mark_simple_css ( aes_name , css_prop , css_value ) |
def find_by_external_tracker ( self , url , id_ ) :
"""Find a list of bugs by searching an external tracker URL and ID .
param url : ` ` str ` ` , the external ticket URL , eg
" http : / / tracker . ceph . com " . ( Note this is the base URL . )
param id _ : ` ` str ` ` , the external ticket ID , eg " 18812 "... | payload = { 'include_fields' : [ 'id' , 'summary' , 'status' ] , 'f1' : 'external_bugzilla.url' , 'o1' : 'substring' , 'v1' : url , 'f2' : 'ext_bz_bug_map.ext_bz_bug_id' , 'o2' : 'equals' , 'v2' : id_ , }
d = self . call ( 'Bug.search' , payload )
d . addCallback ( self . _parse_bugs_callback )
return d |
def lonlat_to_laea ( lon , lat , lon0 , lat0 , f_e = 0.0 , f_n = 0.0 ) :
"""Converts vectors of longitude and latitude into Lambert Azimuthal
Equal Area projection ( km ) , with respect to an origin point
: param numpy . ndarray lon :
Longitudes
: param numpy . ndarray lat :
Latitude
: param float lon0:... | lon = np . radians ( lon )
lat = np . radians ( lat )
lon0 = np . radians ( lon0 )
lat0 = np . radians ( lat0 )
q_0 = TO_Q ( lat0 )
q_p = TO_Q ( np . pi / 2. )
q_val = TO_Q ( lat )
beta = np . arcsin ( q_val / q_p )
beta0 = np . arcsin ( q_0 / q_p )
r_q = WGS84 [ "a" ] * np . sqrt ( q_p / 2. )
dval = WGS84 [ "a" ] * ( ... |
def _validate_anyof ( self , definitions , field , value ) :
"""{ ' type ' : ' list ' , ' logical ' : ' anyof ' }""" | valids , _errors = self . __validate_logical ( 'anyof' , definitions , field , value )
if valids < 1 :
self . _error ( field , errors . ANYOF , _errors , valids , len ( definitions ) ) |
def list ( self , prefix = '' , delimiter = '' , filter_function = None , max_results = 1 , previous_key = '' ) :
'''a method to list keys in the google drive collection
: param prefix : string with prefix value to filter results
: param delimiter : string with value which results must not contain ( after prefi... | title = '%s.list' % self . __class__ . __name__
# validate input
input_fields = { 'prefix' : prefix , 'delimiter' : delimiter , 'max_results' : max_results , 'previous_key' : previous_key }
for key , value in input_fields . items ( ) :
if value :
object_title = '%s(%s=%s)' % ( title , key , str ( value ) )
... |
def tag ( context : click . Context , file_id : int , tags : List [ str ] ) :
"""Add tags to an existing file .""" | file_obj = context . obj [ 'db' ] . file_ ( file_id )
if file_obj is None :
print ( click . style ( 'unable to find file' , fg = 'red' ) )
context . abort ( )
for tag_name in tags :
tag_obj = context . obj [ 'db' ] . tag ( tag_name )
if tag_obj is None :
tag_obj = context . obj [ 'db' ] . new_ta... |
def _set_datapath ( self , datapath ) :
"""Set a datapath .""" | if datapath :
self . _datapath = datapath . rstrip ( os . sep )
self . _fifo = int ( stat . S_ISFIFO ( os . stat ( self . datapath ) . st_mode ) )
else :
self . _datapath = None
self . _fifo = False |
def segment_from_cnr ( cnr_file , data , out_base ) :
"""Provide segmentation on a cnr file , used in external PureCN integration .""" | cns_file = _cnvkit_segment ( cnr_file , dd . get_coverage_interval ( data ) , data , [ data ] , out_file = "%s.cns" % out_base , detailed = True )
out = _add_seg_to_output ( { "cns" : cns_file } , data , enumerate_chroms = False )
return out [ "seg" ] |
def next ( self , timeout = None ) :
"""Return the next result value in the sequence . Raise
StopIteration at the end . Can raise the exception raised by
the Job""" | try :
apply_result = self . _collector . _get_result ( self . _idx , timeout )
except IndexError : # Reset for next time
self . _idx = 0
raise StopIteration
except :
self . _idx = 0
raise
self . _idx += 1
assert apply_result . ready ( )
return apply_result . get ( 0 ) |
def filter_belief ( stmts_in , belief_cutoff , ** kwargs ) :
"""Filter to statements with belief above a given cutoff .
Parameters
stmts _ in : list [ indra . statements . Statement ]
A list of statements to filter .
belief _ cutoff : float
Only statements with belief above the belief _ cutoff will be ret... | dump_pkl = kwargs . get ( 'save' )
logger . info ( 'Filtering %d statements to above %f belief' % ( len ( stmts_in ) , belief_cutoff ) )
# The first round of filtering is in the top - level list
stmts_out = [ ]
# Now we eliminate supports / supported - by
for stmt in stmts_in :
if stmt . belief < belief_cutoff :
... |
def get_resource_class_collection_attribute_iterator ( rc ) :
"""Returns an iterator over all terminal attributes in the given registered
resource .""" | for attr in itervalues_ ( rc . __everest_attributes__ ) :
if attr . kind == RESOURCE_ATTRIBUTE_KINDS . COLLECTION :
yield attr |
def _get_template_list ( self ) :
"Get the hierarchy of templates belonging to the object / box _ type given ." | t_list = [ ]
if hasattr ( self . obj , 'category_id' ) and self . obj . category_id :
cat = self . obj . category
base_path = 'box/category/%s/content_type/%s/' % ( cat . path , self . name )
if hasattr ( self . obj , 'slug' ) :
t_list . append ( base_path + '%s/%s.html' % ( self . obj . slug , self... |
def get_authorize_url ( self , redirect_uri = None , ** kw ) :
'''return the authorization url that the user should be redirected to .''' | redirect = redirect_uri if redirect_uri else self . redirect_uri
if not redirect :
raise APIError ( '21305' , 'Parameter absent: redirect_uri' , 'OAuth2 request' )
response_type = kw . pop ( 'response_type' , 'code' )
return '%s%s?%s' % ( self . auth_url , 'authorize' , _encode_params ( client_id = self . client_id... |
def trips_process_text ( ) :
"""Process text with TRIPS and return INDRA Statements .""" | if request . method == 'OPTIONS' :
return { }
response = request . body . read ( ) . decode ( 'utf-8' )
body = json . loads ( response )
text = body . get ( 'text' )
tp = trips . process_text ( text )
return _stmts_from_proc ( tp ) |
def _read ( self , directory , filename , session , path , name , extension , spatial = None , spatialReferenceID = None , replaceParamFile = None ) :
"""ProjectFileEvent Read from File Method""" | yml_events = [ ]
with open ( path ) as fo :
yml_events = yaml . load ( fo )
for yml_event in yml_events :
if os . path . exists ( os . path . join ( directory , yml_event . subfolder ) ) :
orm_event = yml_event . as_orm ( )
if not self . _similar_event_exists ( orm_event . subfolder ) :
... |
def recommend_delete ( self , num_iid , session ) :
'''taobao . item . recommend . delete 取消橱窗推荐一个商品
取消当前用户指定商品的橱窗推荐状态 这个Item所属卖家从传入的session中获取 , 需要session绑定''' | request = TOPRequest ( 'taobao.item.recommend.delete' )
request [ 'num_iid' ] = num_iid
self . create ( self . execute ( request , session ) [ 'item' ] )
return self |
def should_show_thanks_page_to ( participant ) :
"""In the context of the / ad route , should the participant be shown
the thanks . html page instead of ad . html ?""" | if participant is None :
return False
status = participant . status
marked_done = participant . end_time is not None
ready_for_external_submission = ( status in ( "overrecruited" , "working" ) and marked_done )
assignment_complete = status in ( "submitted" , "approved" )
return assignment_complete or ready_for_exte... |
def decryption ( self , ciphertext , key ) :
"""Builds a single cycle AES Decryption circuit
: param WireVector ciphertext : data to decrypt
: param WireVector key : AES key to use to encrypt ( AES is symmetric )
: return : a WireVector containing the plaintext""" | if len ( ciphertext ) != self . _key_len :
raise pyrtl . PyrtlError ( "Ciphertext length is invalid" )
if len ( key ) != self . _key_len :
raise pyrtl . PyrtlError ( "key length is invalid" )
key_list = self . _key_gen ( key )
t = self . _add_round_key ( ciphertext , key_list [ 10 ] )
for round in range ( 1 , 1... |
def _combine_msd_quan ( msd , quan ) :
"""Combine msd and quantiles in chain summary
Parameters
msd : array of shape ( num _ params , 2 , num _ chains )
mean and sd for chains
cquan : array of shape ( num _ params , num _ quan , num _ chains )
quantiles for chains
Returns
msdquan : array of shape ( nu... | dim1 = msd . shape
n_par , _ , n_chains = dim1
ll = [ ]
for i in range ( n_chains ) :
a1 = msd [ : , : , i ]
a2 = quan [ : , : , i ]
ll . append ( np . column_stack ( [ a1 , a2 ] ) )
msdquan = np . dstack ( ll )
return msdquan |
def split_url ( self , url ) :
"""Parse an IIIF API URL path into components .
Will parse a URL or URL path that accords with either the
parametrized or info API forms . Will raise an IIIFRequestError on
failure .
If self . identifier is set then url is assumed not to include the
identifier .""" | # clear data first
identifier = self . identifier
self . clear ( )
# url must start with baseurl if set ( including slash )
if ( self . baseurl is not None ) :
( path , num ) = re . subn ( '^' + self . baseurl , '' , url , 1 )
if ( num != 1 ) :
raise IIIFRequestError ( text = "Request URL does not start... |
def args_match ( m_args , m_kwargs , default , * args , ** kwargs ) :
""": param m _ args : values to match args against
: param m _ kwargs : values to match kwargs against
: param arg : args to match
: param arg : kwargs to match""" | if len ( m_args ) > len ( args ) :
return False
for m_arg , arg in zip ( m_args , args ) :
matches = arg_match ( m_arg , arg , eq )
if not matches or matches is InvalidArg :
return False
# bail out
if m_kwargs :
for name , m_arg in m_kwargs . items ( ) :
name , comparator = arg_comparito... |
def list_sensors ( self , filter = "" , strategy = False , status = "" , use_python_identifiers = True , tuple = False , refresh = False ) :
"""List sensors available on this resource matching certain criteria .
Parameters
filter : string , optional
Filter each returned sensor ' s name against this regexp if ... | |
def save ( self , * args , ** kwargs ) :
"""Extends save ( ) method of Django models to check that the database name
is not left blank .
Note : ' blank = False ' is only checked at a form - validation - stage . A test
using Fixtureless that tries to randomly create a CrossRefDB with an
empty string name wou... | if self . name == '' :
raise FieldError
else :
return super ( CrossRefDB , self ) . save ( * args , ** kwargs ) |
def render_button ( content , button_type = None , icon = None , button_class = "btn-default" , size = "" , href = "" , name = None , value = None , title = None , extra_classes = "" , id = "" , ) :
"""Render a button with content""" | attrs = { }
classes = add_css_class ( "btn" , button_class )
size = text_value ( size ) . lower ( ) . strip ( )
if size == "xs" :
classes = add_css_class ( classes , "btn-xs" )
elif size == "sm" or size == "small" :
classes = add_css_class ( classes , "btn-sm" )
elif size == "lg" or size == "large" :
classe... |
def output_to_fd ( self , fd ) :
"""Outputs the results of the scanner to a file descriptor ( stdout counts : )
: param fd : file
: return : void""" | for library in self . libraries_found :
fd . write ( "%s==%s\n" % ( library . key , library . version ) ) |
def line_is_continuation ( line : str ) -> bool :
"""Args :
line
Returns :
True iff line is a continuation line , else False .""" | llstr = line . lstrip ( )
return len ( llstr ) > 0 and llstr [ 0 ] == "&" |
def attr ( ** context ) :
"""Decorator that add attributes into func .
Added attributes can be access outside via function ' s ` func _ dict ` property .""" | # TODO ( Jim Zhan ) FIXME
def decorator ( func ) :
def wrapped_func ( * args , ** kwargs ) :
for key , value in context . items ( ) :
print key , value
return func ( * args , ** kwargs )
return wraps ( func ) ( decorator )
return decorator |
def update_order_by_id ( cls , order_id , order , ** kwargs ) :
"""Update Order
Update attributes of Order
This method makes a synchronous HTTP request by default . To make an
asynchronous HTTP request , please pass async = True
> > > thread = api . update _ order _ by _ id ( order _ id , order , async = Tr... | kwargs [ '_return_http_data_only' ] = True
if kwargs . get ( 'async' ) :
return cls . _update_order_by_id_with_http_info ( order_id , order , ** kwargs )
else :
( data ) = cls . _update_order_by_id_with_http_info ( order_id , order , ** kwargs )
return data |
def make_contiguous ( im , keep_zeros = True ) :
r"""Take an image with arbitrary greyscale values and adjust them to ensure
all values fall in a contiguous range starting at 0.
This function will handle negative numbers such that most negative number
will become 0 , * unless * ` ` keep _ zeros ` ` is ` ` Tru... | im = sp . copy ( im )
if keep_zeros :
mask = ( im == 0 )
im [ mask ] = im . min ( ) - 1
im = im - im . min ( )
im_flat = im . flatten ( )
im_vals = sp . unique ( im_flat )
im_map = sp . zeros ( shape = sp . amax ( im_flat ) + 1 )
im_map [ im_vals ] = sp . arange ( 0 , sp . size ( sp . unique ( im_flat ) ) )
im_... |
def minute_his ( self , symbol = '' , datetime = '20161209' ) :
'''分时历史数据
: param market :
: param symbol :
: param datetime :
: return : pd . dataFrame or None''' | market = get_stock_market ( symbol )
with self . client . connect ( * self . bestip ) :
data = self . client . get_history_minute_time_data ( int ( market ) , symbol , datetime )
return self . client . to_df ( data ) |
def set_status ( self , status ) :
"""Updates the status text
Args :
status ( int ) : The offline / starting / online status of Modis
0 : offline , 1 : starting , 2 : online""" | text = ""
colour = "#FFFFFF"
if status == 0 :
text = "OFFLINE"
colour = "#EF9A9A"
elif status == 1 :
text = "STARTING"
colour = "#FFE082"
elif status == 2 :
text = "ONLINE"
colour = "#A5D6A7"
self . status . set ( text )
self . statusbar . config ( background = colour ) |
def _createFilenames ( self , pixels = None ) :
"""Create a masked records array of all filenames for the given set of
pixels and store the existence of those files in the mask values .
Examples :
f = getFilenames ( [ 1,2,3 ] )
# All possible catalog files
f [ ' catalog ' ] . data
# All existing catalog... | nside_catalog = self [ 'coords' ] [ 'nside_catalog' ]
# Deprecated : ADW 2018-06-17
# if nside _ catalog is None :
# pixels = [ None ]
if pixels is not None :
pixels = [ pixels ] if np . isscalar ( pixels ) else pixels
else :
pixels = np . arange ( hp . nside2npix ( nside_catalog ) )
npix = len ( pixels )
catal... |
def process ( source , target , rdfsonly , base = None , logger = logging ) :
'''Prepare a statement into a triple ready for rdflib graph''' | for link in source . match ( ) :
s , p , o = link [ : 3 ]
# SKip docheader statements
if s == ( base or '' ) + '@docheader' :
continue
if p in RESOURCE_MAPPING :
p = RESOURCE_MAPPING [ p ]
if o in RESOURCE_MAPPING :
o = RESOURCE_MAPPING [ o ]
if p == VERSA_BASEIRI + 'refi... |
def get_from_sources ( self , index , doc_type , document_id ) :
"""Get source stored locally""" | return self . sources . get ( index , { } ) . get ( doc_type , { } ) . get ( document_id , { } ) |
def linkify ( self , hosts , timeperiods ) :
"""Create link between objects : :
* hostdependency - > host
* hostdependency - > timeperiods
: param hosts : hosts to link
: type hosts : alignak . objects . host . Hosts
: param timeperiods : timeperiods to link
: type timeperiods : alignak . objects . time... | self . linkify_hd_by_h ( hosts )
self . linkify_hd_by_tp ( timeperiods )
self . linkify_h_by_hd ( hosts ) |
def save_to_rst ( prefix , data ) :
"""Saves a RST file with the given prefix into the script file location .""" | with open ( find_full_name ( prefix ) , "w" ) as rst_file :
rst_file . write ( full_gpl_for_rst )
rst_file . write ( data ) |
def close ( self ) :
'''Save the cookie jar if needed .''' | if self . _save_filename :
self . _cookie_jar . save ( self . _save_filename , ignore_discard = self . _keep_session_cookies ) |
def delete_dscp_marking_rule ( self , rule , policy ) :
"""Deletes a DSCP marking rule .""" | return self . delete ( self . qos_dscp_marking_rule_path % ( policy , rule ) ) |
def get_friends ( self , ** params ) :
"""Return a UserList of Redditors with whom the user is friends .""" | url = self . config [ 'friends' ]
return self . request_json ( url , params = params ) [ 0 ] |
def notify_workers ( self , worker_ids , subject , message_text ) :
"""Send a text message to workers .""" | params = { 'Subject' : subject , 'MessageText' : message_text }
self . build_list_params ( params , worker_ids , 'WorkerId' )
return self . _process_request ( 'NotifyWorkers' , params ) |
def prefix ( self , keys ) :
"""Set a new prefix key .""" | assert isinstance ( keys , tuple )
self . _prefix = keys
self . _load_prefix_binding ( ) |
def _query_api ( self , method , url , fields = None , extra_headers = None , req_body = None ) :
"""Abstracts http queries to the API""" | with self . auth . authenticate ( ) as token :
logging . debug ( 'PA Authentication returned token %s' , token )
headers = { 'Authorization' : 'Bearer %s' % ( token , ) , 'Realm' : self . auth_realm }
if extra_headers is not None :
headers . update ( extra_headers )
logging . info ( '[%s] %s' , ... |
def alias_tool ( self , context_name , tool_name , tool_alias ) :
"""Register an alias for a specific tool .
Note that a tool alias takes precedence over a context prefix / suffix .
Args :
context _ name ( str ) : Context containing the tool .
tool _ name ( str ) : Name of tool to alias .
tool _ alias ( s... | data = self . _context ( context_name )
aliases = data [ "tool_aliases" ]
if tool_name in aliases :
raise SuiteError ( "Tool %r in context %r is already aliased to %r" % ( tool_name , context_name , aliases [ tool_name ] ) )
self . _validate_tool ( context_name , tool_name )
aliases [ tool_name ] = tool_alias
self ... |
def get_instance_attribute ( self , instance_id , attribute ) :
"""Gets an attribute from an instance .
: type instance _ id : string
: param instance _ id : The Amazon id of the instance
: type attribute : string
: param attribute : The attribute you need information about
Valid choices are :
* instanc... | params = { 'InstanceId' : instance_id }
if attribute :
params [ 'Attribute' ] = attribute
return self . get_object ( 'DescribeInstanceAttribute' , params , InstanceAttribute , verb = 'POST' ) |
def is_valid ( cls , arg ) :
"""Return True if arg is valid value for the class . If the string
value is wrong for the enumeration , the encoding will fail .""" | return ( isinstance ( arg , ( int , long ) ) and ( arg >= 0 ) ) or isinstance ( arg , basestring ) |
def get_or_create_modification ( self , graph : BELGraph , node : BaseEntity ) -> Optional [ List [ Modification ] ] :
"""Create a list of node modification objects that belong to the node described by node _ data .
Return ` ` None ` ` if the list can not be constructed , and the node should also be skipped .
:... | modification_list = [ ]
if FUSION in node :
mod_type = FUSION
node = node [ FUSION ]
p3_namespace_url = graph . namespace_url [ node [ PARTNER_3P ] [ NAMESPACE ] ]
if p3_namespace_url in graph . uncached_namespaces :
log . warning ( 'uncached namespace %s in fusion()' , p3_namespace_url )
... |
def start_event ( self ) :
"""Called by the event loop when it is started .
Creates the output frame pools ( if used ) then calls
: py : meth : ` on _ start ` . Creating the output frame pools now allows
their size to be configured before starting the component .""" | # create object pool for each output
if self . with_outframe_pool :
self . update_config ( )
for name in self . outputs :
self . outframe_pool [ name ] = ObjectPool ( Frame , self . new_frame , self . config [ 'outframe_pool_len' ] )
try :
self . on_start ( )
except Exception as ex :
self . logg... |
def _parse_arguments ( ) :
"""Constructs and parses the command line arguments for eg . Returns an args
object as returned by parser . parse _ args ( ) .""" | parser = argparse . ArgumentParser ( description = 'eg provides examples of common command usage.' )
parser . add_argument ( '-v' , '--version' , action = 'store_true' , help = 'Display version information about eg' )
parser . add_argument ( '-f' , '--config-file' , help = 'Path to the .egrc file, if it is not in the d... |
def p_binary_operators ( self , p ) :
"""conditional : conditional AND condition
| conditional OR condition
condition : condition LTE expression
| condition GTE expression
| condition LT expression
| condition GT expression
| condition EQ expression
expression : expression ADD term
| expression SUB ... | p [ 0 ] = Instruction ( "op(left, right)" , context = { 'op' : self . binary_operators [ p [ 2 ] ] , 'left' : p [ 1 ] , 'right' : p [ 3 ] } ) |
def get_modifications_indirect ( self ) :
"""Extract indirect Modification INDRA Statements .""" | # Get all the specific mod types
mod_event_types = list ( ont_to_mod_type . keys ( ) )
# Add ONT : : PTMs as a special case
mod_event_types += [ 'ONT::PTM' ]
def get_increase_events ( mod_event_types ) :
mod_events = [ ]
events = self . tree . findall ( "EVENT/[type='ONT::INCREASE']" )
for event in events :... |
def shutdown ( self ) :
"""Send shutdown command and wait for the process to exit .""" | # Return early if this server has already exited .
if not process . proc_alive ( self . proc ) :
return
logger . info ( "Attempting to connect to %s" , self . hostname )
client = self . connection
# Attempt the shutdown command twice , the first attempt might fail due
# to an election .
attempts = 2
for i in range ... |
def pr ( self , script = False , expanded = False , verbose = False ) -> str :
"""Represent a HistoryItem in a pretty fashion suitable for printing .
If you pass verbose = True , script and expanded will be ignored
: return : pretty print string version of a HistoryItem""" | if verbose :
ret_str = self . listformat . format ( self . idx , str ( self ) . rstrip ( ) )
if self != self . expanded :
ret_str += self . ex_listformat . format ( self . idx , self . expanded . rstrip ( ) )
else :
if script : # display without entry numbers
if expanded or self . statement ... |
def xmlrpc_method ( ** kwargs ) :
"""Support multiple endpoints serving the same views by chaining calls to
xmlrpc _ method""" | # Add some default arguments
kwargs . update ( require_csrf = False , require_methods = [ "POST" ] , decorator = ( submit_xmlrpc_metrics ( method = kwargs [ "method" ] ) , ) , mapper = TypedMapplyViewMapper , )
def decorator ( f ) :
rpc2 = _xmlrpc_method ( endpoint = "RPC2" , ** kwargs )
pypi = _xmlrpc_method (... |
def in_notebook ( ) :
"""Check to see if we are in an IPython or Jypyter notebook .
Returns
in _ notebook : bool
Returns True if we are in a notebook""" | try : # function returns IPython context , but only in IPython
ipy = get_ipython ( )
# NOQA
# we only want to render rich output in notebooks
# in terminals we definitely do not want to output HTML
name = str ( ipy . __class__ ) . lower ( )
terminal = 'terminal' in name
# spyder uses ZMQshel... |
def _cast_to ( e , solution , cast_to ) :
"""Casts a solution for the given expression to type ` cast _ to ` .
: param e : The expression ` value ` is a solution for
: param value : The solution to be cast
: param cast _ to : The type ` value ` should be cast to . Must be one of the currently supported types ... | if cast_to is None :
return solution
if type ( solution ) is bool :
if cast_to is bytes :
return bytes ( [ int ( solution ) ] )
elif cast_to is int :
return int ( solution )
elif type ( solution ) is float :
solution = _concrete_value ( claripy . FPV ( solution , claripy . fp . FSort . f... |
def fovray ( inst , raydir , rframe , abcorr , observer , et ) :
"""Determine if a specified ray is within the field - of - view ( FOV ) of a
specified instrument at a given time .
http : / / naif . jpl . nasa . gov / pub / naif / toolkit _ docs / C / cspice / fovray _ c . html
: param inst : Name or ID code ... | inst = stypes . stringToCharP ( inst )
raydir = stypes . toDoubleVector ( raydir )
rframe = stypes . stringToCharP ( rframe )
abcorr = stypes . stringToCharP ( abcorr )
observer = stypes . stringToCharP ( observer )
et = ctypes . c_double ( et )
visible = ctypes . c_int ( )
libspice . fovray_c ( inst , raydir , rframe ... |
def _get_pltdotstrs ( self , hdrgos_usr , ** kws ) :
"""Plot GO DAGs for each group found under a specfied header GO .""" | import datetime
import timeit
dotstrs_all = [ ]
tic = timeit . default_timer ( )
# Loop through GO groups . Each group of GOs is formed under a single " header GO "
hdrgo2usrgos , go2obj = self . _get_plt_data ( hdrgos_usr )
# get dot strings with _ get _ dotstrs _ curs
for hdrgo , usrgos in hdrgo2usrgos . items ( ) :
... |
def analyze ( fqdn , result , argl , argd ) :
"""Analyzes the result from calling the method with the specified FQDN .
Args :
fqdn ( str ) : full - qualified name of the method that was called .
result : result of calling the method with ` fqdn ` .
argl ( tuple ) : positional arguments passed to the method ... | package = fqdn . split ( '.' ) [ 0 ]
if package not in _methods :
_load_methods ( package )
if _methods [ package ] is not None and fqdn in _methods [ package ] :
return _methods [ package ] [ fqdn ] ( fqdn , result , * argl , ** argd ) |
def seek ( self , offset , from_what = os . SEEK_SET ) :
''': param offset : Position in the file to seek to
: type offset : integer
Seeks to * offset * bytes from the beginning of the file . This is a no - op if the file is open for writing .
The position is computed from adding * offset * to a reference poi... | if from_what == os . SEEK_SET :
reference_pos = 0
elif from_what == os . SEEK_CUR :
reference_pos = self . _pos
elif from_what == os . SEEK_END :
if self . _file_length == None :
desc = self . describe ( )
self . _file_length = int ( desc [ "size" ] )
reference_pos = self . _file_length
... |
def warn ( self , cmd , desc = '' ) :
'''Style for warning message .''' | return self . _label_desc ( cmd , desc , self . warn_color ) |
def load_related_model ( self , name , load_only = None , dont_load = None ) :
'''Load a the : class : ` ForeignKey ` field ` ` name ` ` if this is part of the
fields of this model and if the related object is not already loaded .
It is used by the lazy loading mechanism of : ref : ` one - to - many < one - to ... | field = self . _meta . dfields . get ( name )
if not field :
raise ValueError ( 'Field "%s" not available' % name )
elif not field . type == 'related object' :
raise ValueError ( 'Field "%s" not a foreign key' % name )
return self . _load_related_model ( field , load_only , dont_load ) |
def expect_column_values_to_match_regex ( self , column , regex , mostly = None , result_format = None , include_config = False , catch_exceptions = None , meta = None ) :
"""Expect column entries to be strings that match a given regular expression . Valid matches can be found anywhere in the string , for example "... | raise NotImplementedError |
def train ( ds , ii ) :
"""Run the training step , given a dataset object .""" | print ( "Loading model" )
m = model . CannonModel ( 2 )
print ( "Training..." )
m . fit ( ds )
np . savez ( "./ex%s_coeffs.npz" % ii , m . coeffs )
np . savez ( "./ex%s_scatters.npz" % ii , m . scatters )
np . savez ( "./ex%s_chisqs.npz" % ii , m . chisqs )
np . savez ( "./ex%s_pivots.npz" % ii , m . pivots )
fig = m .... |
def getSpec ( cls ) :
"""Return base spec for this region . See base class method for more info .""" | spec = { "description" : CoordinateSensorRegion . __doc__ , "singleNodeOnly" : True , "inputs" : { } , # input data is added to queue via " addDataToQueue " command
"outputs" : { "dataOut" : { "description" : "Encoded coordinate SDR." , "dataType" : "Real32" , "count" : 0 , "regionLevel" : True , "isDefaultOutput" : Tr... |
def _try_convert_data ( self , name , data , use_dtypes = True , convert_dates = True ) :
"""try to parse a ndarray like into a column by inferring dtype""" | # don ' t try to coerce , unless a force conversion
if use_dtypes :
if self . dtype is False :
return data , False
elif self . dtype is True :
pass
else : # dtype to force
dtype = ( self . dtype . get ( name ) if isinstance ( self . dtype , dict ) else self . dtype )
if dtype... |
def _get_csr_extensions ( csr ) :
'''Returns a list of dicts containing the name , value and critical value of
any extension contained in a csr object .''' | ret = OrderedDict ( )
csrtempfile = tempfile . NamedTemporaryFile ( )
csrtempfile . write ( csr . as_pem ( ) )
csrtempfile . flush ( )
csryaml = _parse_openssl_req ( csrtempfile . name )
csrtempfile . close ( )
if csryaml and 'Requested Extensions' in csryaml [ 'Certificate Request' ] [ 'Data' ] :
csrexts = csryaml... |
def send_emote ( self , room_id , text_content , timestamp = None ) :
"""Perform PUT / rooms / $ room _ id / send / m . room . message with m . emote msgtype
Args :
room _ id ( str ) : The room ID to send the event in .
text _ content ( str ) : The m . emote body to send .
timestamp ( int ) : Set origin _ s... | return self . send_message_event ( room_id , "m.room.message" , self . get_emote_body ( text_content ) , timestamp = timestamp ) |
def load_lang_conf ( ) :
"""Load language setting from language config file if it exists , otherwise
try to use the local settings if Spyder provides a translation , or
return the default if no translation provided .""" | if osp . isfile ( LANG_FILE ) :
with open ( LANG_FILE , 'r' ) as f :
lang = f . read ( )
else :
lang = get_interface_language ( )
save_lang_conf ( lang )
# Save language again if it ' s been disabled
if lang . strip ( '\n' ) in DISABLED_LANGUAGES :
lang = DEFAULT_LANGUAGE
save_lang_conf ( la... |
def union ( self , x , y ) :
"""Merges part that contain x and part containing y
: returns : False if x , y are already in same part
: complexity : O ( inverse _ ackerman ( n ) )""" | repr_x = self . find ( x )
repr_y = self . find ( y )
if repr_x == repr_y : # already in the same component
return False
if self . rank [ repr_x ] == self . rank [ repr_y ] :
self . rank [ repr_x ] += 1
self . up [ repr_y ] = repr_x
elif self . rank [ repr_x ] > self . rank [ repr_y ] :
self . up [ repr... |
def calculate_dates ( self , dt ) :
"""Given a dt , find that day ' s close and period start ( close - offset ) .""" | period_end = self . cal . open_and_close_for_session ( self . cal . minute_to_session_label ( dt ) , ) [ 1 ]
# Align the market close time here with the execution time used by the
# simulation clock . This ensures that scheduled functions trigger at
# the correct times .
self . _period_end = self . cal . execution_time... |
def check_permission ( permission , hidden = True ) :
"""Check if permission is allowed .
If permission fails then the connection is aborted .
: param permission : The permission to check .
: param hidden : Determine if a 404 error ( ` ` True ` ` ) or 401/403 error
( ` ` False ` ` ) should be returned if th... | if permission is not None and not permission . can ( ) :
if hidden :
abort ( 404 )
else :
if current_user . is_authenticated :
abort ( 403 , 'You do not have a permission for this action' )
abort ( 401 ) |
async def prompt ( self , text = None ) :
'''Prompt for user input from stdin .''' | if self . sess is None :
hist = FileHistory ( s_common . getSynPath ( 'cmdr_history' ) )
self . sess = PromptSession ( history = hist )
if text is None :
text = self . cmdprompt
with patch_stdout ( ) :
retn = await self . sess . prompt ( text , async_ = True , vi_mode = self . vi_mode , enable_open_in_e... |
def visitName ( self , ctx : jsgParser . NameContext ) :
"""name : ID | STRING""" | rtkn = get_terminal ( ctx )
tkn = esc_kw ( rtkn )
self . _names [ rtkn ] = tkn |
def lookup ( self , key ) :
"""Look up the given ` node ` URL using the given ` hash _ ` first in the
database and then by waiting on the futures created with
: meth : ` create _ query _ future ` for that node URL and hash .
If the hash is not in the database , : meth : ` lookup ` iterates as long as
there ... | try :
result = self . lookup_in_database ( key )
except KeyError :
pass
else :
return result
while True :
fut = self . _lookup_cache [ key ]
try :
result = yield from fut
except ValueError :
continue
else :
return result |
def home_page ( self , tld_type : Optional [ TLDType ] = None ) -> str :
"""Generate a random home page .
: param tld _ type : TLD type .
: return : Random home page .
: Example :
http : / / www . fontir . info""" | resource = self . random . choice ( USERNAMES )
domain = self . top_level_domain ( tld_type = tld_type , )
return 'http://www.{}{}' . format ( resource , domain ) |
def generateViewHierarchies ( self ) :
'''Wrapper method to create the view hierarchies . Currently it just calls
: func : ` ~ exhale . graph . ExhaleRoot . generateClassView ` and
: func : ` ~ exhale . graph . ExhaleRoot . generateDirectoryView ` - - - if you want to implement
additional hierarchies , implem... | # gather the class hierarchy data and write it out
class_view_data = self . generateClassView ( )
self . writeOutHierarchy ( True , class_view_data )
# gather the file hierarchy data and write it out
file_view_data = self . generateDirectoryView ( )
self . writeOutHierarchy ( False , file_view_data ) |
def load_conf ( cfg_path ) :
"""Try to load the given conf file .""" | global config
try :
cfg = open ( cfg_path , 'r' )
except Exception as ex :
if verbose :
print ( "Unable to open {0}" . format ( cfg_path ) )
print ( str ( ex ) )
return False
# Read the entire contents of the conf file
cfg_json = cfg . read ( )
cfg . close ( )
# print ( cfg _ json )
# Try to... |
def rpm_qf_args ( tags = None , separator = ';' ) :
"""Return the arguments to pass to rpm to list RPMs in the format expected
by parse _ rpm _ output .""" | if tags is None :
tags = image_component_rpm_tags
fmt = separator . join ( [ "%%{%s}" % tag for tag in tags ] )
return r"-qa --qf '{0}\n'" . format ( fmt ) |
def set_default ( feature , value ) :
"""Sets the default value of the given feature , overriding any previous default .
feature : the name of the feature
value : the default value to assign""" | f = __all_features [ feature ]
bad_attribute = None
if f . free :
bad_attribute = "free"
elif f . optional :
bad_attribute = "optional"
if bad_attribute :
raise InvalidValue ( "%s property %s cannot have a default" % ( bad_attribute , f . name ) )
if value not in f . values :
raise InvalidValue ( "The s... |
def exception_uuid ( exc_type , exc_value , exc_traceback ) :
"""Calculate a 32 - bit UUID for a given exception .
Useful for looking for an existing ticket coresponding to a given exception .
Takes into account the type of exception , and the name of every file and
function in the traceback , along with the ... | hasher = hashlib . sha256 ( str ( exc_type ) )
for file_name , line_no , func_name , source in traceback . extract_tb ( exc_traceback ) :
hasher . update ( '\n' + file_name + ':' + func_name + ':' + ( source or '' ) )
return hasher . hexdigest ( ) [ : 8 ] |
def user_delete ( self , id , ** kwargs ) :
"https : / / developer . zendesk . com / rest _ api / docs / core / users # delete - user" | api_path = "/api/v2/users/{id}.json"
api_path = api_path . format ( id = id )
return self . call ( api_path , method = "DELETE" , ** kwargs ) |
def get_default_config_help ( self ) :
"""Returns the help text for the configuration options for this handler""" | config = super ( InfluxdbHandler , self ) . get_default_config_help ( )
config . update ( { 'hostname' : 'Hostname' , 'port' : 'Port' , 'ssl' : 'set to True to use HTTPS instead of http' , 'batch_size' : 'How many metrics to store before sending to the' ' influxdb server' , 'cache_size' : 'How many values to store in c... |
def from_euler ( self , roll , pitch , yaw ) :
'''fill the matrix from Euler angles in radians''' | cp = cos ( pitch )
sp = sin ( pitch )
sr = sin ( roll )
cr = cos ( roll )
sy = sin ( yaw )
cy = cos ( yaw )
self . a . x = cp * cy
self . a . y = ( sr * sp * cy ) - ( cr * sy )
self . a . z = ( cr * sp * cy ) + ( sr * sy )
self . b . x = cp * sy
self . b . y = ( sr * sp * sy ) + ( cr * cy )
self . b . z = ( cr * sp * s... |
def buy_avg_holding_price ( self ) :
"""[ float ] 买方向持仓均价""" | return 0 if self . buy_quantity == 0 else self . _buy_holding_cost / self . buy_quantity / self . contract_multiplier |
def write_catalog ( detections , fname , format = "QUAKEML" ) :
"""Write events contained within detections to a catalog file .
: type detections : list
: param detections : list of eqcorrscan . core . match _ filter . Detection
: type fname : str
: param fname : Name of the file to write to
: type format... | catalog = get_catalog ( detections )
catalog . write ( filename = fname , format = format ) |
def domains ( self ) :
"""This method returns all of your current domains .""" | json = self . request ( '/domains' , method = 'GET' )
status = json . get ( 'status' )
if status == 'OK' :
domains_json = json . get ( 'domains' , [ ] )
domains = [ Domain . from_json ( domain ) for domain in domains_json ]
return domains
else :
message = json . get ( 'message' )
raise DOPException ... |
def _event_for ( self , elts ) :
"""Creates an Event that is set when the bundle with elts is sent .""" | event = Event ( )
event . canceller = self . _canceller_for ( elts , event )
return event |
def deactivate_in_ec ( self , ec_index ) :
'''Deactivate this component in an execution context .
@ param ec _ index The index of the execution context to deactivate in .
This index is into the total array of contexts , that
is both owned and participating contexts . If the value
of ec _ index is greater th... | with self . _mutex :
if ec_index >= len ( self . owned_ecs ) :
ec_index -= len ( self . owned_ecs )
if ec_index >= len ( self . participating_ecs ) :
raise exceptions . BadECIndexError ( ec_index )
ec = self . participating_ecs [ ec_index ]
else :
ec = self . owned_ec... |
def control_force ( self , c ) :
'''represents physical limitation of the control''' | # bring instance variables into local scope
g = self . g
s = self . s
return g * ( 2 / π ) * arctan ( ( s / g ) * c ) |
def incr ( self , name , amount = 1 ) :
"""Increase the value at key ` ` name ` ` by ` ` amount ` ` . If no key exists , the value
will be initialized as ` ` amount ` ` .
Like * * Redis . INCR * *
: param string name : the key name
: param int amount : increments
: return : the integer value at key ` ` na... | amount = get_integer ( 'amount' , amount )
return self . execute_command ( 'incr' , name , amount ) |
def with_timeout ( timeout , d , reactor = reactor ) :
"""Returns a ` Deferred ` that is in all respects equivalent to ` d ` , e . g . when ` cancel ( ) ` is called on it ` Deferred ` ,
the wrapped ` Deferred ` will also be cancelled ; however , a ` Timeout ` will be fired after the ` timeout ` number of
second... | if timeout is None or not isinstance ( d , Deferred ) :
return d
ret = Deferred ( canceller = lambda _ : ( d . cancel ( ) , timeout_d . cancel ( ) , ) )
timeout_d = sleep ( timeout , reactor )
timeout_d . addCallback ( lambda _ : ( d . cancel ( ) , ret . errback ( Failure ( Timeout ( ) ) ) if not ret . called else ... |
def process_attrib ( element , msg ) :
'''process _ attrib
High - level api : Delete four attributes from an ElementTree node if they
exist : operation , insert , value and key . Then a new attribute ' diff ' is
added .
Parameters
element : ` Element `
A node needs to be looked at .
msg : ` str `
Me... | attrib_required = [ 'type' , 'access' , 'mandatory' ]
for node in element . iter ( ) :
for attrib in node . attrib . keys ( ) :
if attrib not in attrib_required :
del node . attrib [ attrib ]
if msg :
node . attrib [ 'diff' ] = msg
return element |
def get_fmt_results ( results , limit = 5 , sep = '::' , fmt = None ) :
"""Return a list of formatted strings representation on a result dictionary .
The elements of the key are divided by a separator string . The result is
appended after the key between parentheses . Apply a format transformation
to odd elem... | result_list = [ ]
for key in sorted ( results , key = lambda x : results [ x ] , reverse = True ) :
if len ( result_list ) >= limit and results [ key ] <= 1 :
break
if fmt is not None :
fmtkey = [ ]
for i in range ( len ( key ) ) :
if i % 2 == 1 :
fmtkey . app... |
def in_git_clone ( ) :
"""Returns ` True ` if the current directory is a git repository
Logic is ' borrowed ' from : func : ` git . repo . fun . is _ git _ dir `""" | gitdir = '.git'
return os . path . isdir ( gitdir ) and ( os . path . isdir ( os . path . join ( gitdir , 'objects' ) ) and os . path . isdir ( os . path . join ( gitdir , 'refs' ) ) and os . path . exists ( os . path . join ( gitdir , 'HEAD' ) ) ) |
def build_attrs ( self , * args , ** kwargs ) :
"""Disable automatic corrections and completions .""" | attrs = super ( CaptchaAnswerInput , self ) . build_attrs ( * args , ** kwargs )
attrs [ 'autocapitalize' ] = 'off'
attrs [ 'autocomplete' ] = 'off'
attrs [ 'autocorrect' ] = 'off'
attrs [ 'spellcheck' ] = 'false'
return attrs |
def get_default_config ( self ) :
"""Returns the default collector settings""" | config = super ( EximCollector , self ) . get_default_config ( )
config . update ( { 'path' : 'exim' , 'bin' : '/usr/sbin/exim' , 'use_sudo' : False , 'sudo_cmd' : '/usr/bin/sudo' , 'sudo_user' : 'root' , } )
return config |
def _fw_delete ( self , drvr_name , data ) :
"""Firewall Delete routine .
This function calls routines to remove FW from fabric and device .
It also updates its local cache .""" | fw_id = data . get ( 'firewall_id' )
tenant_id = self . tenant_db . get_fw_tenant ( fw_id )
if tenant_id not in self . fwid_attr :
LOG . error ( "Invalid tenant id for FW delete %s" , tenant_id )
return
tenant_obj = self . fwid_attr [ tenant_id ]
ret = self . _check_delete_fw ( tenant_id , drvr_name )
if ret :
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.