signature stringlengths 29 44.1k | implementation stringlengths 0 85.2k |
|---|---|
def set_register ( self , addr , data ) :
"""Sets an arbitrary register at @ addr and subsequent registers depending
on how much data you decide to write . It will automatically fill extra
bytes with zeros . You cannot write more than 14 bytes at a time .
@ addr should be a static constant from the Addr class... | assert len ( data ) <= 14 , "Cannot write more than 14 bytes at a time"
cmd = chr ( addr ) + chr ( len ( data ) | 0x80 )
for byte in data :
cmd += chr ( cast_to_byte ( byte ) )
cmd += ( 16 - len ( cmd ) ) * chr ( 0 )
self . _dev . send_bytes ( cmd ) |
def unroll ( self , length , inputs , begin_state = None , layout = 'NTC' , merge_outputs = None , valid_length = None ) :
"""Unrolls an RNN cell across time steps .
Parameters
length : int
Number of steps to unroll .
inputs : Symbol , list of Symbol , or None
If ` inputs ` is a single Symbol ( usually th... | # pylint : disable = too - many - locals
self . reset ( )
inputs , axis , F , batch_size = _format_sequence ( length , inputs , layout , False )
begin_state = _get_begin_state ( self , F , begin_state , inputs , batch_size )
states = begin_state
outputs = [ ]
all_states = [ ]
for i in range ( length ) :
output , st... |
def is_known_scalar ( value ) :
"""Return True if value is a type we expect in a dataframe""" | def _is_datetime_or_timedelta ( value ) : # Using pandas . Series helps catch python , numpy and pandas
# versions of these types
return pd . Series ( value ) . dtype . kind in ( 'M' , 'm' )
return not np . iterable ( value ) and ( isinstance ( value , numbers . Number ) or _is_datetime_or_timedelta ( value ) ) |
def date_time_this_month ( ) :
"""获取当前月的随机时间
: return :
* date _ this _ month : ( datetime ) 当前月份的随机时间
举例如下 : :
print ( ' - - - GetRandomTime . date _ time _ this _ month demo - - - ' )
print ( GetRandomTime . date _ time _ this _ month ( ) )
print ( ' - - - ' )
执行结果 : :
- - - GetRandomTime . date _... | now = datetime . now ( )
this_month_start = now . replace ( day = 1 , hour = 0 , minute = 0 , second = 0 , microsecond = 0 )
this_month_days = calendar . monthrange ( now . year , now . month )
random_seconds = random . randint ( 0 , this_month_days [ 1 ] * A_DAY_SECONDS )
return this_month_start + timedelta ( seconds ... |
def _apply_subtotals ( self , res , include_transforms_for_dims ) :
"""* Insert subtotals ( and perhaps other insertions later ) for
dimensions having their apparent dimension - idx in
* include _ transforms _ for _ dims * .""" | if not include_transforms_for_dims :
return res
suppressed_dim_count = 0
for ( dim_idx , dim ) in enumerate ( self . _all_dimensions ) :
if dim . dimension_type == DT . MR_CAT :
suppressed_dim_count += 1
# - - - only marginable dimensions can be subtotaled - - -
if not dim . is_marginable :
... |
def read_tsv ( cls , file_path : str , gene_table : ExpGeneTable = None , encoding : str = 'UTF-8' , sep : str = '\t' ) :
"""Read expression matrix from a tab - delimited text file .
Parameters
file _ path : str
The path of the text file .
gene _ table : ` ExpGeneTable ` object , optional
The set of valid... | # use pd . read _ csv to parse the tsv file into a DataFrame
matrix = cls ( pd . read_csv ( file_path , sep = sep , index_col = 0 , header = 0 , encoding = encoding ) )
# parse index column separately
# ( this seems to be the only way we can prevent pandas from converting
# " nan " or " NaN " to floats in the index ) [... |
def get_html ( self ) :
"""Generates if need be and returns a simpler html document with text""" | if self . __htmltree is not None :
return self . __htmltree
else :
self . __make_tree ( )
return self . __htmltree |
def wait_for_processes ( die_on_failure : bool = True , timeout_sec : float = 1 ) -> None :
"""Wait for child processes ( catalogued in : data : ` processes ` ) to finish .
If ` ` die _ on _ failure ` ` is ` ` True ` ` , then whenever a subprocess returns
failure , all are killed .
If ` ` timeout _ sec ` ` is... | global processes
global proc_args_list
n = len ( processes )
Pool ( n ) . map ( print_lines , processes )
# in case of PIPE
something_running = True
while something_running :
something_running = False
for i , p in enumerate ( processes ) :
try :
retcode = p . wait ( timeout = timeout_sec )
... |
def WriteSessionCompletion ( self , aborted = False ) :
"""Writes session completion information .
Args :
aborted ( Optional [ bool ] ) : True if the session was aborted .
Raises :
IOError : if the storage type is not supported or
when the storage writer is closed .
OSError : if the storage type is not ... | self . _RaiseIfNotWritable ( )
if self . _storage_type != definitions . STORAGE_TYPE_SESSION :
raise IOError ( 'Unsupported storage type.' )
self . _session . aborted = aborted
session_completion = self . _session . CreateSessionCompletion ( )
self . _storage_file . WriteSessionCompletion ( session_completion ) |
def get_package_hashes ( filename ) :
"""Provides hash of given filename .
Args :
filename ( str ) : Name of file to hash
Returns :
( str ) : sha256 hash""" | log . debug ( 'Getting package hashes' )
filename = os . path . abspath ( filename )
with open ( filename , 'rb' ) as f :
data = f . read ( )
_hash = hashlib . sha256 ( data ) . hexdigest ( )
log . debug ( 'Hash for file %s: %s' , filename , _hash )
return _hash |
def packexe ( exefile , srcdir ) :
"""Pack the files in srcdir into exefile using 7z .
Requires that stub files are available in checkouts / stubs""" | exefile = cygpath ( os . path . abspath ( exefile ) )
appbundle = exefile + ".app.7z"
# Make sure that appbundle doesn ' t already exist
# We don ' t want to risk appending to an existing file
if os . path . exists ( appbundle ) :
raise OSError ( "%s already exists" % appbundle )
files = os . listdir ( srcdir )
SEV... |
def _ssweek_to_gregorian ( ssweek_year , ssweek_week , ssweek_day ) :
"Gregorian calendar date for the given Sundaystarting - week year , week and day" | year_start = _ssweek_year_start ( ssweek_year )
return year_start + dt . timedelta ( days = ssweek_day - 1 , weeks = ssweek_week - 1 ) |
def _read_returned_msg ( self , method_frame ) :
'''Support method to read a returned ( basic . return ) Message from the
current frame buffer . Will return a Message with return _ info , or
re - queue current frames and raise a FrameUnderflow .
: returns : Message with the return _ info attribute set , where... | header_frame , body = self . _reap_msg_frames ( method_frame )
return_info = { 'channel' : self . channel , 'reply_code' : method_frame . args . read_short ( ) , 'reply_text' : method_frame . args . read_shortstr ( ) , 'exchange' : method_frame . args . read_shortstr ( ) , 'routing_key' : method_frame . args . read_sho... |
def get_wallet_transactions ( wallet_name , api_key , coin_symbol = 'btc' , before_bh = None , after_bh = None , txn_limit = None , omit_addresses = False , unspent_only = False , show_confidence = False , confirmations = 0 ) :
'''Takes a wallet , api _ key , coin _ symbol and returns the wallet ' s details
Optio... | assert len ( wallet_name ) <= 25 , wallet_name
assert api_key
assert is_valid_coin_symbol ( coin_symbol = coin_symbol )
assert isinstance ( show_confidence , bool ) , show_confidence
assert isinstance ( omit_addresses , bool ) , omit_addresses
url = make_url ( coin_symbol , ** dict ( addrs = wallet_name ) )
params = { ... |
def get_ticks ( self ) :
"""Get all ticks and labels for a band structure plot .
Returns :
A dict with ' distance ' : a list of distance at which ticks should
be set and ' label ' : a list of label for each of those ticks .""" | tick_distance = [ ]
tick_labels = [ ]
previous_label = self . _bs . qpoints [ 0 ] . label
previous_branch = self . _bs . branches [ 0 ] [ 'name' ]
for i , c in enumerate ( self . _bs . qpoints ) :
if c . label is not None :
tick_distance . append ( self . _bs . distance [ i ] )
this_branch = None
... |
def update_webhook ( self , url , headers = None ) :
"""Register new webhook for incoming subscriptions .
If a webhook is already set , this will do an overwrite .
: param str url : the URL with listening webhook ( Required )
: param dict headers : K / V dict with additional headers to send with request
: r... | headers = headers or { }
api = self . _get_api ( mds . NotificationsApi )
# Delete notifications channel
api . delete_long_poll_channel ( )
# Send the request to register the webhook
webhook_obj = WebhookData ( url = url , headers = headers )
api . register_webhook ( webhook_obj )
return |
def get_family ( self , family_id = None ) :
"""Gets the ` ` Family ` ` specified by its ` ` Id ` ` .
In plenary mode , the exact ` ` Id ` ` is found or a ` ` NotFound ` `
results . Otherwise , the returned ` ` Family ` ` may have a different
` ` Id ` ` than requested , such as the case where a duplicate ` ` ... | if family_id is None :
raise NullArgument ( )
url_path = '/handcar/services/relationship/families/' + str ( family_id )
return objects . Family ( self . _get_request ( url_path ) ) |
def _strip_dollars_fast ( text ) :
"""Replace ` $ $ ` with ` $ ` . raise immediately
if ` $ ` starting an interpolated expression is found .
@ param text : the source text
@ return : the text with dollars replaced , or raise
HasExprException if there are interpolated expressions""" | def _sub ( m ) :
if m . group ( 0 ) == '$$' :
return '$'
raise HasExprException ( )
return _dollar_strip_re . sub ( _sub , text ) |
def flight_modes ( logfile ) :
'''show flight modes for a log file''' | print ( "Processing log %s" % filename )
mlog = mavutil . mavlink_connection ( filename )
mode = ""
previous_mode = ""
mode_start_timestamp = - 1
time_in_mode = { }
previous_percent = - 1
seconds_per_percent = - 1
filesize = os . path . getsize ( filename )
while True :
m = mlog . recv_match ( type = [ 'SYS_STATUS'... |
def check ( self , item_id ) :
"""Check if an analysis is complete .
: type item _ id : str
: param item _ id : File ID to check .
: rtype : bool
: return : Boolean indicating if a report is done or not .""" | response = self . _request ( "/submission/sample/{sample_id}" . format ( sample_id = item_id ) , headers = self . headers )
if response . status_code == 404 : # unknown id
return False
try :
finished = False
for submission in response . json ( ) [ 'data' ] :
finished = finished or submission [ 'subm... |
def create_filehandlers ( self , filenames , fh_kwargs = None ) :
"""Organize the filenames into file types and create file handlers .""" | filenames = list ( OrderedDict . fromkeys ( filenames ) )
logger . debug ( "Assigning to %s: %s" , self . info [ 'name' ] , filenames )
self . info . setdefault ( 'filenames' , [ ] ) . extend ( filenames )
filename_set = set ( filenames )
created_fhs = { }
# load files that we know about by creating the file handlers
f... |
def _xdate_setter ( self , xdate_format = '%Y-%m-%d' ) :
"""Makes x axis a date axis with auto format
Parameters
xdate _ format : String
\t Sets date formatting""" | if xdate_format : # We have to validate xdate _ format . If wrong then bail out .
try :
self . autofmt_xdate ( )
datetime . date ( 2000 , 1 , 1 ) . strftime ( xdate_format )
except ValueError :
self . autofmt_xdate ( )
return
self . __axes . xaxis_date ( )
formatter = dat... |
def run_c_extension_with_fallback ( log_function , extension , c_function , py_function , args , rconf ) :
"""Run a function calling a C extension , falling back
to a pure Python function if the former does not succeed .
: param function log _ function : a logger function
: param string extension : the name o... | computed = False
if not rconf [ u"c_extensions" ] :
log_function ( u"C extensions disabled" )
elif extension not in rconf :
log_function ( [ u"C extension '%s' not recognized" , extension ] )
elif not rconf [ extension ] :
log_function ( [ u"C extension '%s' disabled" , extension ] )
else :
log_function... |
def serialize ( self , items ) :
"""Does the inverse of config parsing by taking parsed values and
converting them back to a string representing config file contents .""" | r = StringIO ( )
for key , value in items . items ( ) :
if isinstance ( value , list ) : # handle special case of lists
value = "[" + ", " . join ( map ( str , value ) ) + "]"
r . write ( "%s = %s\n" % ( key , value ) )
return r . getvalue ( ) |
def unfollow ( user , obj , send_action = False , flag = '' ) :
"""Removes a " follow " relationship .
Set ` ` send _ action ` ` to ` ` True ` ` ( ` ` False is default ) to also send a
` ` < user > stopped following < object > ` ` action signal .
Pass a string value to ` ` flag ` ` to determine which type of ... | check ( obj )
qs = apps . get_model ( 'actstream' , 'follow' ) . objects . filter ( user = user , object_id = obj . pk , content_type = ContentType . objects . get_for_model ( obj ) )
if flag :
qs = qs . filter ( flag = flag )
qs . delete ( )
if send_action :
if not flag :
action . send ( user , verb = ... |
def remove_properties ( self ) :
"""Removes the property layer , if exists""" | node_prop = self . node . find ( 'properties' )
if node_prop is not None :
self . node . remove ( node_prop ) |
def domain_create ( self , domain , master = True , ** kwargs ) :
"""Registers a new Domain on the acting user ' s account . Make sure to point
your registrar to Linode ' s nameservers so that Linode ' s DNS manager will
correctly serve your domain .
: param domain : The domain to register to Linode ' s DNS m... | params = { 'domain' : domain , 'type' : 'master' if master else 'slave' , }
params . update ( kwargs )
result = self . post ( '/domains' , data = params )
if not 'id' in result :
raise UnexpectedResponseError ( 'Unexpected response when creating Domain!' , json = result )
d = Domain ( self , result [ 'id' ] , resul... |
def categories ( self , value ) :
"""Setter for * * self . _ _ categories * * attribute .
: param value : Attribute value .
: type value : dict""" | if value is not None :
assert type ( value ) is dict , "'{0}' attribute: '{1}' type is not 'dict'!" . format ( "categories" , value )
for key in value :
assert type ( key ) is unicode , "'{0}' attribute: '{1}' type is not 'unicode'!" . format ( "categories" , key )
self . __categories = value |
def square_count ( x : int , y : int ) -> int :
"""This python function calculates the total number of squares within a rectangular area .
Args :
x : The length of the rectangle
y : The width of the rectangle
Returns :
An integer count of the total number of squares within the rectangular grid .
Example... | if y < x :
x , y = y , x
return int ( ( ( ( x * ( x + 1 ) ) * ( ( 2 * x ) + 1 ) ) / 6 ) + ( ( ( ( y - x ) * x ) * ( x + 1 ) ) / 2 ) ) |
def create_datastore_write_config ( mapreduce_spec ) :
"""Creates datastore config to use in write operations .
Args :
mapreduce _ spec : current mapreduce specification as MapreduceSpec .
Returns :
an instance of datastore _ rpc . Configuration to use for all write
operations in the mapreduce .""" | force_writes = parse_bool ( mapreduce_spec . params . get ( "force_writes" , "false" ) )
if force_writes :
return datastore_rpc . Configuration ( force_writes = force_writes )
else : # dev server doesn ' t support force _ writes .
return datastore_rpc . Configuration ( ) |
def wait_for ( self , wait_for , timeout_ms ) :
"""Waits for one or more events to happen .
in wait _ for of type int
Specifies what to wait for ;
see : py : class : ` ProcessWaitForFlag ` for more information .
in timeout _ ms of type int
Timeout ( in ms ) to wait for the operation to complete .
Pass 0... | if not isinstance ( wait_for , baseinteger ) :
raise TypeError ( "wait_for can only be an instance of type baseinteger" )
if not isinstance ( timeout_ms , baseinteger ) :
raise TypeError ( "timeout_ms can only be an instance of type baseinteger" )
reason = self . _call ( "waitFor" , in_p = [ wait_for , timeout_... |
def _normalize ( self , tokens ) :
"""Normalization transform to apply to both dictionary words and input tokens .""" | if self . case_sensitive :
return ' ' . join ( self . lexicon [ t ] . normalized for t in tokens )
else :
return ' ' . join ( self . lexicon [ t ] . lower for t in tokens ) |
def create_multi_output_factor ( self , tool , source , splitting_node , sink ) :
"""Creates a multi - output factor .
This takes a single node , applies a MultiOutputTool to create multiple nodes on a new plate
Instantiates a single tool for all of the input plate values ,
and connects the source and sink no... | if source and not isinstance ( source , Node ) :
raise ValueError ( "Expected Node, got {}" . format ( type ( source ) ) )
if not isinstance ( sink , Node ) :
raise ValueError ( "Expected Node, got {}" . format ( type ( sink ) ) )
# if isinstance ( tool , dict ) :
# tool = self . channels . get _ tool ( * * too... |
def _handle ( self , event_handler , event_name , user_args , event_timeout , cond , cond_timeout ) :
"""Pop an event of specified type and calls its handler on it . If
condition is not None , block until condition is met or timeout .""" | if cond :
cond . wait ( cond_timeout )
event = self . pop_event ( event_name , event_timeout )
return event_handler ( event , * user_args ) |
def cli ( obj , alert , severity , timeout , purge ) :
"""List heartbeats .""" | client = obj [ 'client' ]
if obj [ 'output' ] == 'json' :
r = client . http . get ( '/heartbeats' )
click . echo ( json . dumps ( r [ 'heartbeats' ] , sort_keys = True , indent = 4 , ensure_ascii = False ) )
else :
timezone = obj [ 'timezone' ]
headers = { 'id' : 'ID' , 'origin' : 'ORIGIN' , 'customer' ... |
def get_biased_correlations ( data , threshold = 10 ) :
"""Gets the highest few correlations for each bit , across the entirety of the
data . Meant to provide a comparison point for the pairwise correlations
reported in the literature , which are typically between neighboring neurons
tuned to the same inputs ... | data = data . toDense ( )
correlations = numpy . corrcoef ( data , rowvar = False )
highest_correlations = [ ]
for row in correlations :
highest_correlations += sorted ( row , reverse = True ) [ 1 : threshold + 1 ]
return numpy . mean ( highest_correlations ) |
def write_tensorboard_text ( self , key , input_dict ) :
"""Saves text to Tensorboard .
Note : Only works on tensorflow r1.2 or above .
: param key : The name of the text .
: param input _ dict : A dictionary that will be displayed in a table on Tensorboard .""" | try :
with tf . Session ( ) as sess :
s_op = tf . summary . text ( key , tf . convert_to_tensor ( ( [ [ str ( x ) , str ( input_dict [ x ] ) ] for x in input_dict ] ) ) )
s = sess . run ( s_op )
self . summary_writer . add_summary ( s , self . get_step )
except :
LOGGER . info ( "Cannot ... |
def funk ( p , x , y ) :
"""Function misfit evaluation for best - fit tanh curve
f ( x [ : ] ) = alpha * tanh ( beta * x [ : ] )
alpha = params [ 0]
beta = params [ 1]
funk ( params ) = sqrt ( sum ( ( y [ : ] - f ( x [ : ] ) ) * * 2 ) / len ( y [ : ] ) )
Output is RMS misfit
x = xx [ 0 ] [ : ]
y = xx ... | alpha = p [ 0 ]
beta = p [ 1 ]
dev = 0
for i in range ( len ( x ) ) :
dev = dev + ( ( y [ i ] - ( alpha * math . tanh ( beta * x [ i ] ) ) ) ** 2 )
rms = math . sqrt ( old_div ( dev , float ( len ( y ) ) ) )
return rms |
def prepare_string ( partname , thread , maxw ) :
"""extract a content string for part ' partname ' from ' thread ' of maximal
length ' maxw ' .""" | # map part names to function extracting content string and custom shortener
prep = { 'mailcount' : ( prepare_mailcount_string , None ) , 'date' : ( prepare_date_string , None ) , 'authors' : ( prepare_authors_string , shorten_author_string ) , 'subject' : ( prepare_subject_string , None ) , 'content' : ( prepare_conten... |
def replace ( self , nodes , node ) :
"""Replace nodes with node . Edges incoming to nodes [ 0 ] are connected to
the new node , and nodes outgoing from nodes [ - 1 ] become outgoing from
the new node .""" | nodes = nodes if isinstance ( nodes , list ) else [ nodes ]
# Is the new node part of the replace nodes ( i . e . want to collapse
# a group of nodes into one of them ) ?
collapse = self . id ( node ) in self . nodes
# Add new node and edges
if not collapse :
self . add_node ( node )
for in_node in self . incoming ... |
def p_redirection_heredoc ( p ) :
'''redirection : LESS _ LESS WORD
| NUMBER LESS _ LESS WORD
| REDIR _ WORD LESS _ LESS WORD
| LESS _ LESS _ MINUS WORD
| NUMBER LESS _ LESS _ MINUS WORD
| REDIR _ WORD LESS _ LESS _ MINUS WORD''' | parserobj = p . context
assert isinstance ( parserobj , _parser )
output = ast . node ( kind = 'word' , word = p [ len ( p ) - 1 ] , parts = [ ] , pos = p . lexspan ( len ( p ) - 1 ) )
if len ( p ) == 3 :
p [ 0 ] = ast . node ( kind = 'redirect' , input = None , type = p [ 1 ] , heredoc = None , output = output , p... |
def from_record ( self , record ) :
"""Constructs and returns a sequenced item object , from given ORM object .""" | kwargs = self . get_field_kwargs ( record )
return self . sequenced_item_class ( ** kwargs ) |
def p_ExtendedAttributeNoArgs ( p ) :
"""ExtendedAttributeNoArgs : IDENTIFIER""" | p [ 0 ] = model . ExtendedAttribute ( value = model . ExtendedAttributeValue ( name = p [ 1 ] ) ) |
def _connect ( self ) :
"""Connects to the cloud web services . If this is the first
authentication , a web browser will be started to authenticate
against google and provide access to elasticluster .
: return : A Resource object with methods for interacting with the
service .""" | # check for existing connection
with GoogleCloudProvider . __gce_lock :
if self . _gce :
return self . _gce
flow = OAuth2WebServerFlow ( self . _client_id , self . _client_secret , GCE_SCOPE )
# The ` Storage ` object holds the credentials that your
# application needs to authorize access to the... |
def plot_circ ( fignum , pole , ang , col ) :
"""function to put a small circle on an equal area projection plot , fig , fignum
Parameters
_ _ _ _ _
fignum : matplotlib figure number
pole : dec , inc of center of circle
ang : angle of circle
col :""" | plt . figure ( num = fignum )
D_c , I_c = pmag . circ ( pole [ 0 ] , pole [ 1 ] , ang )
X_c_up , Y_c_up = [ ] , [ ]
X_c_d , Y_c_d = [ ] , [ ]
for k in range ( len ( D_c ) ) :
XY = pmag . dimap ( D_c [ k ] , I_c [ k ] )
if I_c [ k ] < 0 :
X_c_up . append ( XY [ 0 ] )
Y_c_up . append ( XY [ 1 ] )
... |
def is_bad_headers ( self ) :
"""Checks for bad headers i . e . newlines in subject , sender or recipients .""" | headers = [ self . subject , self . sender ]
headers += list ( self . send_to )
headers += dict ( self . extra_headers ) . values ( )
for val in headers :
for c in '\r\n' :
if c in val :
return True
return False |
def report_on_jobs ( self ) :
"""Gathers information about jobs such as its child jobs and status .
: returns jobStats : Pairings of a useful category and a list of jobs which fall into it .
: rtype dict :""" | hasChildren = [ ]
readyToRun = [ ]
zombies = [ ]
hasLogFile = [ ]
hasServices = [ ]
services = [ ]
properties = set ( )
for job in self . jobsToReport :
if job . logJobStoreFileID is not None :
hasLogFile . append ( job )
childNumber = reduce ( lambda x , y : x + y , map ( len , job . stack ) + [ 0 ] )
... |
def ensure_routing_table_is_fresh ( self , access_mode ) :
"""Update the routing table if stale .
This method performs two freshness checks , before and after acquiring
the refresh lock . If the routing table is already fresh on entry , the
method exits immediately ; otherwise , the refresh lock is acquired a... | if self . routing_table . is_fresh ( access_mode ) :
return False
with self . refresh_lock :
if self . routing_table . is_fresh ( access_mode ) :
if access_mode == READ_ACCESS : # if reader is fresh but writers is not fresh , then we are reading in absence of writer
self . missing_writer = n... |
def _validate_missing ( self , value ) :
"""Validate missing values . Raise a : exc : ` ValidationError ` if
` value ` should be considered missing .""" | if value is missing_ :
if hasattr ( self , 'required' ) and self . required :
self . fail ( 'required' )
if value is None :
if hasattr ( self , 'allow_none' ) and self . allow_none is not True :
self . fail ( 'null' ) |
def transaction_retry ( max_retries = 1 ) :
"""Decorator for methods doing database operations .
If the database operation fails , it will retry the operation
at most ` ` max _ retries ` ` times .""" | def _outer ( fun ) :
@ wraps ( fun )
def _inner ( * args , ** kwargs ) :
_max_retries = kwargs . pop ( 'exception_retry_count' , max_retries )
for retries in count ( 0 ) :
try :
return fun ( * args , ** kwargs )
except Exception : # pragma : no cover
... |
def mu ( X , Z , A ) :
'''mean molecular weight assuming full ionisation .
( Kippenhahn & Weigert , Ch 13.1 , Eq . 13.6)
Parameters
X : float
Mass fraction vector .
Z : float
Charge number vector .
A : float
Mass number vector .''' | if not isinstance ( Z , np . ndarray ) :
Z = np . array ( Z )
if not isinstance ( A , np . ndarray ) :
A = np . array ( A )
if not isinstance ( X , np . ndarray ) :
X = np . array ( X )
try :
mu = old_div ( 1. , sum ( X * ( 1. + Z ) / A ) )
except TypeError :
X = np . array ( [ X ] )
A = np . ar... |
def format_param_list ( listed_params , output_name ) :
'''Utility method for formatting lists of parameters for api consumption
Useful for email address lists , etc
Args :
listed _ params ( list of values ) - the list to format
output _ name ( str ) - the parameter name to prepend to each key''' | output_payload = { }
if listed_params :
for index , item in enumerate ( listed_params ) :
output_payload [ str ( output_name ) + "[" + str ( index ) + "]" ] = item
return output_payload |
def _resolved_type ( self ) :
"""Return the type for the columns , and a flag to indicate that the
column has codes .""" | import datetime
self . type_ratios = { test : ( float ( self . type_counts [ test ] ) / float ( self . count ) ) if self . count else None for test , testf in tests + [ ( None , None ) ] }
# If it is more than 5 % str , it ' s a str
try :
if self . type_ratios . get ( text_type , 0 ) + self . type_ratios . get ( bi... |
def types ( self ) :
"""Tuple containing types transformed by this transformer .""" | out = [ ]
if self . _transform_bytes :
out . append ( bytes )
if self . _transform_str :
out . append ( str )
return tuple ( out ) |
def check_compression_gathering ( self , ds ) :
"""At the current time the netCDF interface does not provide for packing
data . However a simple packing may be achieved through the use of the
optional NUG defined attributes scale _ factor and add _ offset . After the
data values of a variable have been read ,... | ret_val = [ ]
for compress_var in ds . get_variables_by_attributes ( compress = lambda s : s is not None ) :
valid = True
reasoning = [ ]
# puts the referenced variable being compressed into a set
compress_set = set ( compress_var . compress . split ( ' ' ) )
if compress_var . ndim != 1 :
va... |
def _zoom_labels ( self , zoom ) :
"""Adjust grid label font to zoom factor""" | labelfont = self . grid . GetLabelFont ( )
default_fontsize = get_default_font ( ) . GetPointSize ( )
labelfont . SetPointSize ( max ( 1 , int ( round ( default_fontsize * zoom ) ) ) )
self . grid . SetLabelFont ( labelfont ) |
def recv_msg ( self ) :
"""Receive a single message from the stream .
: return : A SLIP - decoded message
: rtype : bytes
: raises ProtocolError : when a SLIP protocol error has been encountered .
A subsequent call to : meth : ` recv _ msg ` ( after handling the exception )
will return the message from th... | # First check if there are any pending messages
if self . _messages :
return self . _messages . popleft ( )
# No pending messages left . If a ProtocolError has occurred
# it must be re - raised here :
if self . _protocol_error :
self . _handle_pending_protocol_error ( )
while not self . _messages and not self .... |
def _as_json ( self , response ) :
"""Assuming this is not empty , return the content as JSON .
Result / exceptions is not determined if you call this method without testing _ is _ empty .
: raises : DeserializationError if response body contains invalid json data .""" | # Assume ClientResponse has " body " , and otherwise it ' s a requests . Response
content = response . text ( ) if hasattr ( response , "body" ) else response . text
try :
return json . loads ( content )
except ValueError :
raise DeserializationError ( "Error occurred in deserializing the response body." ) |
def raises ( self ) :
"""Return list of : raises meta .""" | return [ DocstringRaises . from_meta ( meta ) for meta in self . meta if meta . args [ 0 ] in { 'raises' , 'raise' , 'except' , 'exception' } ] |
def distinct ( ) :
"""Validates that all items in the given field list value are distinct ,
i . e . that the list contains no duplicates .""" | def validate ( value ) :
for i , item in enumerate ( value ) :
if item in value [ i + 1 : ] :
return e ( "{} is not a distinct set of values" , value )
return validate |
def _JMS_to_Bern_II ( C , udlnu ) :
"""From JMS to BernII basis for charged current process semileptonic
operators . ` udlnu ` should be of the form ' udl _ enu _ tau ' , ' cbl _ munu _ e ' etc .""" | u = uflav [ udlnu [ 0 ] ]
d = dflav [ udlnu [ 1 ] ]
l = lflav [ udlnu [ 4 : udlnu . find ( 'n' ) ] ]
lp = lflav [ udlnu [ udlnu . find ( '_' , 5 ) + 1 : len ( udlnu ) ] ]
ind = udlnu [ 0 ] + udlnu [ 1 ] + udlnu [ 4 : udlnu . find ( 'n' ) ] + udlnu [ udlnu . find ( '_' , 5 ) + 1 : len ( udlnu ) ]
return { '1' + ind : C ... |
async def move_to ( self , mount : top_types . Mount , abs_position : top_types . Point , speed : float = None , critical_point : CriticalPoint = None ) :
"""Move the critical point of the specified mount to a location
relative to the deck , at the specified speed . ' speed ' sets the speed
of all robot axes to... | if not self . _current_position :
raise MustHomeError
await self . _cache_and_maybe_retract_mount ( mount )
z_axis = Axis . by_mount ( mount )
if mount == top_types . Mount . LEFT :
offset = top_types . Point ( * self . config . mount_offset )
else :
offset = top_types . Point ( 0 , 0 , 0 )
cp = self . _cri... |
def from_mongo ( cls , doc ) :
"""Convert data coming in from the MongoDB wire driver into a Document instance .""" | if doc is None : # To support simplified iterative use , None should return None .
return None
if isinstance ( doc , Document ) : # No need to perform processing on existing Document instances .
return doc
if cls . __type_store__ and cls . __type_store__ in doc : # Instantiate specific class mentioned in the da... |
def _filter_scanline ( self , filter_type , line , result ) :
"""Apply a scanline filter to a scanline .
` filter _ type ` specifies the filter type ( 0 to 4)
' line ` specifies the current ( unfiltered ) scanline as a sequence
of bytes ;""" | assert 0 <= filter_type < 5
if self . prev is None : # We ' re on the first line . Some of the filters can be reduced
# to simpler cases which makes handling the line " off the top "
# of the image simpler . " up " becomes " none " ; " paeth " becomes
# " left " ( non - trivial , but true ) . " average " needs to be ha... |
def get_collection ( self , folderid , username = "" , offset = 0 , limit = 10 ) :
"""Fetch collection folder contents
: param folderid : UUID of the folder to list
: param username : The user to list folders for , if omitted the authenticated user is used
: param offset : the pagination offset
: param limi... | if not username and self . standard_grant_type == "authorization_code" :
response = self . _req ( '/collections/{}' . format ( folderid ) , { "offset" : offset , "limit" : limit } )
else :
if not username :
raise DeviantartError ( "No username defined." )
else :
response = self . _req ( '/co... |
def _cleanSessions ( self ) :
"""Clean expired sesisons .""" | tooOld = extime . Time ( ) - timedelta ( seconds = PERSISTENT_SESSION_LIFETIME )
self . store . query ( PersistentSession , PersistentSession . lastUsed < tooOld ) . deleteFromStore ( )
self . _lastClean = self . _clock . seconds ( ) |
def ver_dec_content ( parts , sign_key = None , enc_key = None , sign_alg = 'SHA256' ) :
"""Verifies the value of a cookie
: param parts : The parts of the payload
: param sign _ key : A : py : class : ` cryptojwt . jwk . hmac . SYMKey ` instance
: param enc _ key : A : py : class : ` cryptojwt . jwk . hmac .... | if parts is None :
return None
elif len ( parts ) == 3 : # verify the cookie signature
timestamp , load , b64_mac = parts
mac = base64 . b64decode ( b64_mac )
verifier = HMACSigner ( algorithm = sign_alg )
if verifier . verify ( load . encode ( 'utf-8' ) + timestamp . encode ( 'utf-8' ) , mac , sign... |
def _build_graph ( self ) -> nx . DiGraph :
"""Private method to build the graph from the model .""" | digraph = nx . DiGraph ( )
for state in self . model . all_states ( ) :
self . _number_of_states += 1
for next_state in self . model . available_state ( state ) :
self . _number_of_transitions += 1
digraph . add_edge ( self . _transform_state_to_string ( state ) , self . _transform_state_to_stri... |
def get_conv ( bits , bin_point , signed = False , scaling = 1.0 ) :
"""Creates a I { conversion structure } implented as a dictionary containing all parameters
needed to switch between number representations .
@ param bits : the number of bits
@ param bin _ point : binary point position
@ param signed : Tr... | conversion_t = { }
conversion_t [ "bits" ] = bits
conversion_t [ "bin_point" ] = bin_point
conversion_t [ "signed" ] = signed
conversion_t [ "scaling" ] = scaling
conversion_t [ "dec_step" ] = 1.0 / ( 2 ** bin_point )
# dec _ max = dec _ mask * dec _ step
conversion_t [ "dec_mask" ] = sum ( [ 2 ** i for i in range ( bi... |
def p_or_p_expression ( tok ) :
"""or _ p _ expression : xor _ p _ expression OP _ OR _ P or _ p _ expression
| xor _ p _ expression""" | if len ( tok ) == 4 :
tok [ 0 ] = LogicalBinOpRule ( tok [ 2 ] , tok [ 1 ] , tok [ 3 ] )
else :
tok [ 0 ] = tok [ 1 ] |
def create_property_nod_worksheets ( workbook , data_list , result_info_key , identifier_keys ) :
"""Creates two worksheets out of the property / nod data because the data
doesn ' t come flat enough to make sense on one sheet .
Args :
workbook : the main workbook to add the sheets to
data _ list : the main ... | nod_details_list = [ ]
nod_default_history_list = [ ]
for prop_data in data_list :
nod_data = prop_data [ 'property/nod' ]
if nod_data is None :
nod_data = { }
default_history_data = nod_data . pop ( 'default_history' , [ ] )
_set_identifier_fields ( nod_data , prop_data , result_info_key , iden... |
def generate_dynamodb_tables ( ) :
"""Create the Blockade DynamoDB tables .""" | logger . debug ( "[#] Setting up DynamoDB tables" )
client = boto3 . client ( 'dynamodb' , region_name = PRIMARY_REGION )
existing_tables = client . list_tables ( ) [ 'TableNames' ]
responses = list ( )
for label in DYNAMODB_TABLES :
if label in existing_tables :
logger . debug ( "[*] Table %s already exist... |
def nearest_neighbors ( X , n_neighbors , metric , metric_kwds , angular , random_state , verbose = False ) :
"""Compute the ` ` n _ neighbors ` ` nearest points for each data point in ` ` X ` `
under ` ` metric ` ` . This may be exact , but more likely is approximated via
nearest neighbor descent .
Parameter... | if verbose :
print ( ts ( ) , "Finding Nearest Neighbors" )
if metric == "precomputed" : # Note that this does not support sparse distance matrices yet . . .
# Compute indices of n nearest neighbors
knn_indices = np . argsort ( X ) [ : , : n_neighbors ]
# Compute the nearest neighbor distances
# ( equiv... |
def _run_bcbio_variation ( vrn_file , rm_file , rm_interval_file , base_dir , sample , caller , data ) :
"""Run validation of a caller against the truth set using bcbio . variation .""" | val_config_file = _create_validate_config_file ( vrn_file , rm_file , rm_interval_file , base_dir , data )
work_dir = os . path . join ( base_dir , "work" )
out = { "summary" : os . path . join ( work_dir , "validate-summary.csv" ) , "grading" : os . path . join ( work_dir , "validate-grading.yaml" ) , "discordant" : o... |
def has_delete_permission ( self , request , obj = None ) :
"""Returns True if the given request has permission to change the given
Django model instance , the default implementation doesn ' t examine the
` obj ` parameter .
Can be overriden by the user in subclasses . In such case it should
return True if ... | opts = self . opts
return request . user . has_perm ( opts . app_label + '.' + opts . get_delete_permission ( ) , obj ) |
def list_namespaced_limit_range ( self , namespace , ** kwargs ) :
"""list or watch objects of kind LimitRange
This method makes a synchronous HTTP request by default . To make an
asynchronous HTTP request , please pass async _ req = True
> > > thread = api . list _ namespaced _ limit _ range ( namespace , as... | kwargs [ '_return_http_data_only' ] = True
if kwargs . get ( 'async_req' ) :
return self . list_namespaced_limit_range_with_http_info ( namespace , ** kwargs )
else :
( data ) = self . list_namespaced_limit_range_with_http_info ( namespace , ** kwargs )
return data |
def add_callback ( self , f ) :
"""Magic method assigned to f . callback that allows a callback to be
defined as follows :
@ bucket
def fun ( . . . ) :
@ fun . callback
def fun ( ) :
In the event that a cached result is used , the callback is fired .""" | self . callback = f
return self . decorate ( self . fref ( ) ) |
def scan_process_filenames ( self ) :
"""Update the filename for each process in the snapshot when possible .
@ note : Tipically you don ' t need to call this method . It ' s called
automatically by L { scan } to get the full pathname for each process
when possible , since some scan methods only get filenames... | complete = True
for aProcess in self . __processDict . values ( ) :
try :
new_name = None
old_name = aProcess . fileName
try :
aProcess . fileName = None
new_name = aProcess . get_filename ( )
finally :
if not new_name :
aProcess . ... |
def get_addr ( iface = 'lo0' , iface_type = 'link' ) :
"""获取网络接口 ` ` iface ` ` 的 ` ` mac ` `
- 如果系统类型为 ` ` mac ` ` , 使用 ` ` psutil ` `
- 其他使用 ` ` socket ` `
: param iface : ` ` 网络接口 ` `
: type iface : str
: return : ` ` mac地址 / 空 ` `
: rtype : str / None""" | if platform . system ( ) in [ 'Darwin' , 'Linux' ] :
if iface_type == 'link' :
_AF_FAMILY = psutil . AF_LINK
elif iface_type in [ 'inet' , 'inet6' ] :
_AF_FAMILY = getattr ( socket , 'AF_{}' . format ( iface_type . upper ( ) ) )
else :
raise SystemError ( 'Not valid address FAMILY' )... |
def create_api_pool ( self ) :
"""Get an instance of Api Pool services facade .""" | return ApiPool ( self . networkapi_url , self . user , self . password , self . user_ldap ) |
def _extract_member ( self , member , targetpath , pwd ) :
"""Extract the ZipInfo object ' member ' to a physical
file on the path targetpath .""" | # build the destination pathname , replacing
# forward slashes to platform specific separators .
arcname = member . filename . replace ( '/' , os . path . sep )
if os . path . altsep :
arcname = arcname . replace ( os . path . altsep , os . path . sep )
# interpret absolute pathname as relative , remove drive lette... |
def set_zonefile_present ( self , zfhash , block_height , con = None , path = None ) :
"""Set a zonefile as present , and if it was previously absent , inform the storage listener""" | was_present = atlasdb_set_zonefile_present ( zfhash , True , con = con , path = path )
# tell anyone who cares that we got this zone file , if it was new
if not was_present and self . store_zonefile_cb :
log . debug ( '{} was new, so passing it along to zonefile storage watchers...' . format ( zfhash ) )
self .... |
def ae_latent_sample ( latents_dense , inputs , ed , embed , iters , hparams ) :
"""Sample from the latent space in the autoencoder .""" | if hparams . num_decode_blocks < 2 and hparams . sampling_temp == 0.0 : # TODO ( lukaszkaiser ) : beam - search only works in non - blocked mode for now .
tf . logging . info ( "Running beam-search for latents with beam size 1." )
return ae_latent_sample_beam ( latents_dense , inputs , ed , embed , hparams )
la... |
def _detect_timezone_etc_localtime ( ) :
"""Detect timezone based on / etc / localtime file .""" | matches = [ ]
if os . path . exists ( "/etc/localtime" ) :
f = open ( "/etc/localtime" , "rb" )
localtime = pytz . tzfile . build_tzinfo ( "/etc/localtime" , f )
f . close ( )
# We want to match against the local database because / etc / localtime will
# be copied from that . Once we have found a na... |
def centre_of_mass ( self ) :
"""Returns the centre of mass of AMPAL object .
Notes
All atoms are included in calculation , call ` centre _ of _ mass `
manually if another selection is require .
Returns
centre _ of _ mass : numpy . array
3D coordinate for the centre of mass .""" | elts = set ( [ x . element for x in self . get_atoms ( ) ] )
masses_dict = { e : ELEMENT_DATA [ e ] [ 'atomic mass' ] for e in elts }
points = [ x . _vector for x in self . get_atoms ( ) ]
masses = [ masses_dict [ x . element ] for x in self . get_atoms ( ) ]
return centre_of_mass ( points = points , masses = masses ) |
def check_permissions ( self , request ) :
"""Check if the request should be permitted .
Raises an appropriate exception if the request is not permitted .
: param request : Pyramid Request object .""" | for permission in self . get_permissions ( ) :
if not permission . has_permission ( request , self ) :
self . permission_denied ( request , message = getattr ( permission , 'message' , None ) ) |
def uri_split_tree ( uri ) :
"""Return ( scheme , ( user , passwd , host , port ) , path ,
( ( k1 , v1 ) , ( k2 , v2 ) , . . . ) , fragment ) using
basic _ urisplit ( ) , then split _ authority ( ) and split _ query ( ) on the
result .
> > > uri _ split _ tree (
. . . ' http : / / % 42%20 + blabla : lol @... | scheme , authority , path , query , fragment = basic_urisplit ( uri )
if authority :
authority = split_authority ( authority )
if query :
query = split_query ( query )
return ( scheme and scheme or None , authority and authority or None , path and path or None , query and query or None , fragment and fragment o... |
def is_element_present ( driver , selector , by = By . CSS_SELECTOR ) :
"""Returns whether the specified element selector is present on the page .
@ Params
driver - the webdriver object ( required )
selector - the locator that is used ( required )
by - the method to search for the locator ( Default : By . C... | try :
driver . find_element ( by = by , value = selector )
return True
except Exception :
return False |
def add_attribute_group_items ( attributegroupitems , ** kwargs ) :
"""Populate attribute groups with items .
* * attributegroupitems : a list of items , of the form :
' attr _ id ' : X ,
' group _ id ' : Y ,
' network _ id ' : Z ,
Note that this approach supports the possibility of populating groups
wi... | user_id = kwargs . get ( 'user_id' )
if not isinstance ( attributegroupitems , list ) :
raise HydraError ( "Cannpt add attribute group items. Attributegroupitems must be a list" )
new_agis_i = [ ]
group_lookup = { }
# for each network , keep track of what attributes are contained in which groups it ' s in
# structu... |
def dump_p ( self , filename ) :
"""Dump parameter values ( ` ` fit . p ` ` ) into file ` ` filename ` ` .
` ` fit . dump _ p ( filename ) ` ` saves the best - fit parameter values
( ` ` fit . p ` ` ) from a ` ` nonlinear _ fit ` ` called ` ` fit ` ` . These values
are recovered using
` ` p = nonlinear _ fi... | warnings . warn ( "nonlinear_fit.dump_p deprecated; use gvar.dump instead" , DeprecationWarning )
with open ( filename , "wb" ) as f :
pickle . dump ( self . palt , f ) |
def list_services ( self ) :
"""List Services .""" | content = self . _fetch ( "/service" )
return map ( lambda x : FastlyService ( self , x ) , content ) |
def update ( self , buf ) :
"""Update this hash object ' s state with the provided string .""" | if self . _final :
raise InvalidOperation ( "Cannot update finalised tlsh" )
else :
self . _buf_len += len ( buf )
return self . _tlsh . update ( buf ) |
def next_frame_base ( ) :
"""Common HParams for next _ frame models .""" | hparams = common_hparams . basic_params1 ( )
# Loss cutoff .
hparams . add_hparam ( "video_modality_loss_cutoff" , 0.01 )
# Additional resizing the frames before feeding them to model .
hparams . add_hparam ( "preprocess_resize_frames" , None )
# How many data points to suffle . Ideally should be part of problem not mo... |
def bind_socket ( address , port ) :
"""Returns a socket bound on ( address : port ) .""" | assert address
assert port
bindsocket = socket . socket ( )
try :
bindsocket . bind ( ( address , port ) )
except socket . error :
logger . error ( "Couldn't bind socket on %s:%s" , address , port )
return None
logger . info ( 'Listening on %s:%s' , address , port )
bindsocket . listen ( 0 )
return bindsock... |
def search_app_root ( ) :
"""Search your Django application root
returns :
- ( String ) Django application root path""" | while True :
current = os . getcwd ( )
if pathlib . Path ( "apps.py" ) . is_file ( ) :
return current
elif pathlib . Path . cwd ( ) == "/" :
raise FileNotFoundError
else :
os . chdir ( "../" ) |
def zadd ( self , key , score , member , mode , client = None ) :
"""Like ZADD , but supports different score update modes , in case the
member already exists in the ZSET :
- " nx " : Don ' t update the score
- " xx " : Only update elements that already exist . Never add elements .
- " min " : Use the small... | if mode == 'nx' :
f = self . _zadd_noupdate
elif mode == 'xx' :
f = self . _zadd_update_existing
elif mode == 'min' :
f = self . _zadd_update_min
elif mode == 'max' :
f = self . _zadd_update_max
else :
raise NotImplementedError ( 'mode "%s" unsupported' % mode )
return f ( keys = [ key ] , args = [ ... |
def clear_state ( self , activity , agent , registration = None ) :
"""Clear state ( s ) with specified activity and agent
: param activity : Activity object of state ( s ) to be deleted
: type activity : : class : ` tincan . activity . Activity `
: param agent : Agent object of state ( s ) to be deleted
: ... | return self . _delete_state ( activity = activity , agent = agent , registration = registration ) |
def exception ( self ) :
'''Return an instance of the corresponding exception''' | code , _ , message = self . data . partition ( ' ' )
return self . find ( code ) ( message ) |
def AddContract ( self , contract ) :
"""Add a contract to the database .
Args :
contract ( neo . SmartContract . Contract ) : a Contract instance .""" | super ( UserWallet , self ) . AddContract ( contract )
try :
db_contract = Contract . get ( ScriptHash = contract . ScriptHash . ToBytes ( ) )
db_contract . delete_instance ( )
except Exception as e :
logger . debug ( "contract does not exist yet" )
sh = bytes ( contract . ScriptHash . ToArray ( ) )
address... |
def get_class ( kls ) :
""": param kls - string of fully identified starter function or starter method path
for instance :
- workers . abstract _ worker . AbstractWorker . start
- workers . example _ script _ worker . main
: return tuple ( type , object , starter )
for instance :
- ( FunctionType , < fu... | parts = kls . split ( '.' )
try : # First , try to import module hosting starter function
module = '.' . join ( parts [ : - 1 ] )
m = __import__ ( module )
except ImportError : # Alternatively , try to import module hosting Class with a starter method
module = '.' . join ( parts [ : - 2 ] )
m = __import... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.