signature stringlengths 29 44.1k | implementation stringlengths 0 85.2k |
|---|---|
def tojson ( self ) -> str :
"""Serialize an Event into JSON .
Returns
str
JSON - serialized Event .""" | return json . dumps ( { 'event_id' : str ( self . id ) , 'event_type' : self . type , 'schema_name' : self . schema_name , 'table_name' : self . table_name , 'row_id' : self . row_id } ) |
def call_func ( self , req , * args , ** kwargs ) :
"""Add json _ error _ formatter to any webob HTTPExceptions .""" | try :
return super ( SdkWsgify , self ) . call_func ( req , * args , ** kwargs )
except webob . exc . HTTPException as exc :
msg = ( 'encounter %(error)s error' ) % { 'error' : exc }
LOG . debug ( msg )
exc . json_formatter = json_error_formatter
code = exc . status_int
explanation = six . text_... |
def get_content_version ( cls , abspath ) :
"""Returns a version string for the resource at the given path .
This class method may be overridden by subclasses . The
default implementation is a hash of the file ' s contents .
. . versionadded : : 3.1""" | data = cls . get_content ( abspath )
hasher = hashlib . md5 ( )
mtime_data = format ( cls . get_content_modified_time ( abspath ) , "%Y-%m-%d %H:%M:%S" )
hasher . update ( mtime_data . encode ( ) )
if isinstance ( data , bytes ) :
hasher . update ( data )
else :
for chunk in data :
hasher . update ( chu... |
def _detect ( self ) :
"""Detect un - indexed ERC20 event parameters in all contracts .""" | results = [ ]
for c in self . contracts :
unindexed_params = self . detect_erc20_unindexed_event_params ( c )
if unindexed_params :
info = "{} ({}) does not mark important ERC20 parameters as 'indexed':\n"
info = info . format ( c . name , c . source_mapping_str )
for ( event , parameter... |
def render ( self , ** kwargs ) :
"""Renders the HTML representation of the element .""" | vegalite_major_version = self . _get_vegalite_major_versions ( self . data )
self . _parent . html . add_child ( Element ( Template ( """
<div id="{{this.get_name()}}"></div>
""" ) . render ( this = self , kwargs = kwargs ) ) , name = self . get_name ( ) )
figure = self . get_root ( )
assert isi... |
def update_contents ( self , contents , mime_type ) :
"""Update the contents and set the hash and modification time""" | import hashlib
import time
new_size = len ( contents )
self . mime_type = mime_type
if mime_type == 'text/plain' :
self . contents = contents . encode ( 'utf-8' )
else :
self . contents = contents
old_hash = self . hash
self . hash = hashlib . md5 ( self . contents ) . hexdigest ( )
if self . size and ( old_has... |
def whoami ( self ) -> dict :
"""Returns the basic information about the authenticated character .
Obviously doesn ' t do anything if this Preston instance is not
authenticated , so it returns an empty dict .
Args :
None
Returns :
character info if authenticated , otherwise an empty dict""" | if not self . access_token :
return { }
self . _try_refresh_access_token ( )
return self . session . get ( self . WHOAMI_URL ) . json ( ) |
def sends ( self , tag = None , fromdate = None , todate = None ) :
"""Gets a total count of emails you ’ ve sent out .""" | return self . call ( "GET" , "/stats/outbound/sends" , tag = tag , fromdate = fromdate , todate = todate ) |
def reduce ( self , reduce_fn ) :
"""Applies a rolling sum operator to the stream .
Attributes :
sum _ attribute _ index ( int ) : The index of the attribute to sum
( assuming tuple records ) .""" | op = Operator ( _generate_uuid ( ) , OpType . Reduce , "Sum" , reduce_fn , num_instances = self . env . config . parallelism )
return self . __register ( op ) |
def copy ( self , src_url , dst_url ) :
"""Copy an S3 object to another S3 location .""" | src_bucket , src_key = _parse_url ( src_url )
dst_bucket , dst_key = _parse_url ( dst_url )
if not dst_bucket :
dst_bucket = src_bucket
params = { 'copy_source' : '/' . join ( ( src_bucket , src_key ) ) , 'bucket' : dst_bucket , 'key' : dst_key , }
return self . call ( "CopyObject" , ** params ) |
def splitFASTA ( params ) :
"""Read the FASTA file named params [ ' fastaFile ' ] and print out its
sequences into files named 0 . fasta , 1 . fasta , etc . with
params [ ' seqsPerJob ' ] sequences per file .""" | assert params [ 'fastaFile' ] [ - 1 ] == 'a' , ( 'You must specify a file in ' 'fasta-format that ends in ' '.fasta' )
fileCount = count = seqCount = 0
outfp = None
with open ( params [ 'fastaFile' ] ) as infp :
for seq in SeqIO . parse ( infp , 'fasta' ) :
seqCount += 1
if count == params [ 'seqsPe... |
def get_default_config ( self ) :
"""Returns the default collector settings""" | config = super ( ExampleCollector , self ) . get_default_config ( )
config . update ( { 'path' : 'example' } )
return config |
def arrow_respond ( slider , event ) :
"""Event handler for arrow key events in plot windows .
Pass the slider object to update as a masked argument using a lambda function : :
lambda evt : arrow _ respond ( my _ slider , evt )
Parameters
slider : Slider instance associated with this handler .
event : Eve... | if event . key == 'right' :
slider . set_val ( min ( slider . val + 1 , slider . valmax ) )
elif event . key == 'left' :
slider . set_val ( max ( slider . val - 1 , slider . valmin ) ) |
def translatePoints ( points , movex , movey ) :
"""Returns a generator that produces all of the ( x , y ) tuples in ` points ` moved over by ` movex ` and ` movey ` .
> > > points = [ ( 0 , 0 ) , ( 5 , 10 ) , ( 25 , 25 ) ]
> > > list ( translatePoints ( points , 1 , - 3 ) )
[ ( 1 , - 3 ) , ( 6 , 7 ) , ( 26 ,... | # Note : There is no translatePoint ( ) function because that ' s trivial .
_checkForIntOrFloat ( movex )
_checkForIntOrFloat ( movey )
try :
for x , y in points :
_checkForIntOrFloat ( x )
_checkForIntOrFloat ( y )
yield x + movex , y + movey
except :
raise PyBresenhamException ( '`poin... |
def to_array ( self ) :
"""Serializes this Contact to a dictionary .
: return : dictionary representation of this object .
: rtype : dict""" | array = super ( Contact , self ) . to_array ( )
array [ 'phone_number' ] = u ( self . phone_number )
# py2 : type unicode , py3 : type str
array [ 'first_name' ] = u ( self . first_name )
# py2 : type unicode , py3 : type str
if self . last_name is not None :
array [ 'last_name' ] = u ( self . last_name )
# py2 : t... |
def convertColors ( element ) :
"""Recursively converts all color properties into # RRGGBB format if shorter""" | numBytes = 0
if element . nodeType != Node . ELEMENT_NODE :
return 0
# set up list of color attributes for each element type
attrsToConvert = [ ]
if element . nodeName in [ 'rect' , 'circle' , 'ellipse' , 'polygon' , 'line' , 'polyline' , 'path' , 'g' , 'a' ] :
attrsToConvert = [ 'fill' , 'stroke' ]
elif elemen... |
def list ( self ) :
"""Get a list of the names of the functions stored in this database .""" | return [ x [ "_id" ] for x in self . _db . system . js . find ( projection = [ "_id" ] ) ] |
def getPlainText ( self , iv , key , ciphertext ) :
""": type iv : bytearray
: type key : bytearray
: type ciphertext : bytearray""" | try :
cipher = AESCipher ( key , iv )
plaintext = cipher . decrypt ( ciphertext )
if sys . version_info >= ( 3 , 0 ) :
return plaintext . decode ( )
return plaintext
except Exception as e :
raise InvalidMessageException ( e ) |
def to_hemi_str ( s ) :
'''to _ hemi _ str ( s ) yields either ' lh ' , ' rh ' , or ' lr ' depending on the input s .
The match rules for s are as follows :
* if s is None or Ellipsis , returns ' lr '
* if s is not a string , error ; otherwise s becomes s . lower ( )
* if s is in ( ' lh ' , ' rh ' , ' lr ' ... | if s is None or s is Ellipsis :
return 'lr'
if not pimms . is_str ( s ) :
raise ValueError ( 'to_hemi_str(%s): not a string or ... or None' % s )
s = s . lower ( )
if s in ( 'lh' , 'rh' , 'lr' ) :
return s
elif s in ( 'left' , 'l' , 'sh' ) :
return 'lh'
elif s in ( 'right' , 'r' , 'dh' ) :
return 'r... |
def compute_feed_stats ( feed : "Feed" , trip_stats : DataFrame , dates : List [ str ] ) -> DataFrame :
"""Compute some feed stats for the given dates and trip stats .
Parameters
feed : Feed
trip _ stats : DataFrame
Trip stats to consider in the format output by
: func : ` . trips . compute _ trip _ stats... | dates = feed . restrict_dates ( dates )
if not dates :
return pd . DataFrame ( )
ts = trip_stats . copy ( )
activity = feed . compute_trip_activity ( dates )
stop_times = feed . stop_times . copy ( )
# Convert timestrings to seconds for quicker calculations
ts [ [ "start_time" , "end_time" ] ] = ts [ [ "start_time"... |
def set_mode ( self , * modes , ** kwargs ) :
"""Set ( enable ) a given list of modes .
: param list modes : modes to set , where each mode is a constant
from : mod : ` pyte . modes ` .""" | # Private mode codes are shifted , to be distingiushed from non
# private ones .
if kwargs . get ( "private" ) :
modes = [ mode << 5 for mode in modes ]
if mo . DECSCNM in modes :
self . dirty . update ( range ( self . lines ) )
self . mode . update ( modes )
# When DECOLM mode is set , the screen is er... |
def default_sort_key ( item , order = None ) :
"""Return a key that can be used for sorting .
The key has the structure :
( class _ key , ( len ( args ) , args ) , exponent . sort _ key ( ) , coefficient )
This key is supplied by the sort _ key routine of Basic objects when
` ` item ` ` is a Basic object or... | from sympy . core import S , Basic
from sympy . core . sympify import sympify , SympifyError
from sympy . core . compatibility import iterable
if isinstance ( item , Basic ) :
return item . sort_key ( order = order )
if iterable ( item , exclude = string_types ) :
if isinstance ( item , dict ) :
args = ... |
def group_num ( self ) :
"""Current group number .
: getter : Returns current group number
: setter : Sets current group number
: type : int""" | xkb_state = XkbStateRec ( )
XkbGetState ( self . _display , XkbUseCoreKbd , byref ( xkb_state ) )
return xkb_state . group |
def _algebraic_rules_circuit ( ) :
"""Set the default algebraic rules for the operations defined in this
module""" | A_CPermutation = wc ( "A" , head = CPermutation )
B_CPermutation = wc ( "B" , head = CPermutation )
C_CPermutation = wc ( "C" , head = CPermutation )
D_CPermutation = wc ( "D" , head = CPermutation )
A_Concatenation = wc ( "A" , head = Concatenation )
B_Concatenation = wc ( "B" , head = Concatenation )
A_SeriesProduct ... |
def _find_global ( self , module , func ) :
"""Return the class implementing ` module _ name . class _ name ` or raise
` StreamError ` if the module is not whitelisted .""" | if module == __name__ :
if func == '_unpickle_call_error' or func == 'CallError' :
return _unpickle_call_error
elif func == '_unpickle_sender' :
return self . _unpickle_sender
elif func == '_unpickle_context' :
return self . _unpickle_context
elif func == 'Blob' :
return ... |
def enabled_actions_for_env ( env ) :
"""Returns actions to perform when processing the given environment .""" | def enabled ( config_value , required ) :
if config_value is Config . TriBool . No :
return False
if config_value is Config . TriBool . Yes :
return True
assert config_value is Config . TriBool . IfNeeded
return bool ( required )
# Some old Python versions do not support HTTPS downloads ... |
def remove_all_cts_records_by ( self , crypto_idfp ) :
"""Remove all CTS records from the specified player
: param crypto _ idfp :
: return :""" | regex = re . compile ( '(.+)/cts100record/crypto_idfp(\d+)' )
to_remove = [ ]
for k , v in self . filter ( regex , is_regex = True ) :
if v == crypto_idfp :
match = regex . match ( k )
to_remove . append ( ( match . group ( 1 ) , int ( match . group ( 2 ) ) ) )
for i in to_remove :
self . remove... |
def _build_request ( self , type , commands ) :
'''Build NX - API JSON request .''' | request = { }
headers = { 'content-type' : 'application/json' , }
if self . nxargs [ 'connect_over_uds' ] :
user = self . nxargs [ 'cookie' ]
headers [ 'cookie' ] = 'nxapi_auth=' + user + ':local'
request [ 'url' ] = self . NXAPI_UDS_URI_PATH
else :
request [ 'url' ] = '{transport}://{host}:{port}{uri}'... |
def mean ( name , add , match ) :
'''Accept a numeric value from the matched events and store a running average
of the values in the given register . If the specified value is not numeric
it will be skipped
USAGE :
. . code - block : : yaml
foo :
reg . mean :
- add : data _ field
- match : my / cust... | ret = { 'name' : name , 'changes' : { } , 'comment' : '' , 'result' : True }
if name not in __reg__ :
__reg__ [ name ] = { }
__reg__ [ name ] [ 'val' ] = 0
__reg__ [ name ] [ 'total' ] = 0
__reg__ [ name ] [ 'count' ] = 0
for event in __events__ :
try :
event_data = event [ 'data' ] [ 'data'... |
def get_supported_file_loaders_2 ( force = False ) :
"""Returns a list of file - based module loaders .
Each item is a tuple ( loader , suffixes ) .""" | if force or ( 2 , 7 ) <= sys . version_info < ( 3 , 4 ) : # valid until which py3 version ?
import imp
loaders = [ ]
for suffix , mode , type in imp . get_suffixes ( ) :
if type == imp . PY_SOURCE :
loaders . append ( ( SourceFileLoader2 , [ suffix ] ) )
else :
loader... |
def listBlockChildren ( self , block_name = "" ) :
"""list parents of a block""" | if ( not block_name ) or re . search ( "['%','*']" , block_name ) :
dbsExceptionHandler ( "dbsException-invalid-input" , "DBSBlock/listBlockChildren. Block_name must be provided." )
conn = self . dbi . connection ( )
try :
results = self . blockchildlist . execute ( conn , block_name )
return results
finall... |
def probes_used_extract_scores ( full_scores , same_probes ) :
"""Extracts a matrix of scores for a model , given a probes _ used row vector of boolean""" | if full_scores . shape [ 1 ] != same_probes . shape [ 0 ] :
raise "Size mismatch"
import numpy as np
model_scores = np . ndarray ( ( full_scores . shape [ 0 ] , np . sum ( same_probes ) ) , 'float64' )
c = 0
for i in range ( 0 , full_scores . shape [ 1 ] ) :
if same_probes [ i ] :
for j in range ( 0 , f... |
def combined_properties ( self , suffix ) :
"""Get the value of all properties whose name ends with suffix and join them
together into a list .""" | props = [ y for x , y in self . settings . items ( ) if x . endswith ( suffix ) ]
properties = itertools . chain ( * props )
processed_props = [ x for x in properties ]
return processed_props |
def pyxwriter ( self ) :
"""Update the pyx file .""" | model = self . Model ( )
if hasattr ( self , 'Parameters' ) :
model . parameters = self . Parameters ( vars ( self ) )
else :
model . parameters = parametertools . Parameters ( vars ( self ) )
if hasattr ( self , 'Sequences' ) :
model . sequences = self . Sequences ( model = model , ** vars ( self ) )
else ... |
def migrate ( self , id_or_uri , timeout = - 1 ) :
"""Initiates a migration of an enclosure specified by the ID or URI of a migration report .
Args :
id _ or _ uri : ID or URI of the migration report .
timeout : Timeout in seconds . Waits for task completion by default . The timeout does not abort the task in... | # create the special payload to tell the VC Migration Manager to migrate the VC domain
migrationInformation = { 'migrationState' : 'Migrated' , 'type' : 'migratable-vc-domains' , 'category' : 'migratable-vc-domains' }
# call build _ uri manually since . update ( . . . ) doesn ' t do it and the URI is not to be included... |
def mi ( x , y , bins_x = None , bins_y = None , bins_xy = None , method = 'nearest-neighbors' , units = 'bits' ) :
'''compute and return the mutual information between x and y
inputs :
x , y : numpy arrays of shape samples x dimension
method : ' nearest - neighbors ' , ' gaussian ' , or ' bin '
units : ' b... | # dict . values ( ) returns a view object that has to be converted to a list before being
# converted to an array
# the following lines will execute properly in python3 , but not python2 because there
# is no zip object
try :
if isinstance ( x , zip ) :
x = list ( x )
if isinstance ( y , zip ) :
... |
def exact_match ( pred , target ) :
"""Compute " Exact match " metric , also called " Subset accuracy " indicating the
number of samples that have all their labels classified correctly .
See https : / / en . wikipedia . org / wiki / Multi - label _ classification
: param pred : Predicted labels
: param targ... | res = torch . eq ( target . sort ( dim = 1 ) [ 0 ] , pred . sort ( dim = 1 ) [ 0 ] )
return res . prod ( dim = 1 ) |
def GetMessages ( self , formatter_mediator , event ) :
"""Determines the formatted message strings for an event object .
Args :
formatter _ mediator ( FormatterMediator ) : mediates the interactions between
formatters and other components , such as storage and Windows EventLog
resources .
event ( EventOb... | regvalue = getattr ( event , 'regvalue' , { } )
# Loop over all the registry value names in the service key .
for service_value_name in regvalue . keys ( ) : # A temporary variable so we can refer to this long name more easily .
service_enums = human_readable_service_enums . SERVICE_ENUMS
# Check if we need to ... |
def trigger ( self_ , * param_names ) :
"""Trigger watchers for the given set of parameter names . Watchers
will be triggered whether or not the parameter values have
actually changed .""" | events = self_ . self_or_cls . param . _events
watchers = self_ . self_or_cls . param . _watchers
self_ . self_or_cls . param . _events = [ ]
self_ . self_or_cls . param . _watchers = [ ]
param_values = dict ( self_ . get_param_values ( ) )
params = { name : param_values [ name ] for name in param_names }
self_ . self_... |
def _try_inline_read ( self ) -> None :
"""Attempt to complete the current read operation from buffered data .
If the read can be completed without blocking , schedules the
read callback on the next IOLoop iteration ; otherwise starts
listening for reads on the socket .""" | # See if we ' ve already got the data from a previous read
pos = self . _find_read_pos ( )
if pos is not None :
self . _read_from_buffer ( pos )
return
self . _check_closed ( )
pos = self . _read_to_buffer_loop ( )
if pos is not None :
self . _read_from_buffer ( pos )
return
# We couldn ' t satisfy the ... |
def do_put ( self , line ) :
"put [ : tablename ] [ ! fieldname : expectedvalue ] { json - body } [ { json - body } , { json - body } . . . ]" | table , line = self . get_table_params ( line )
expected , line = self . get_expected ( line )
if expected :
print "expected: not yet implemented"
return
if line . startswith ( '(' ) or line . startswith ( '[' ) :
print "batch: not yet implemented"
return
list = self . get_list ( line )
wlist = ... |
def is_metric_cls ( cls ) :
"""A metric class is defined as follows :
- It inherits DiffParserBase
- It is not DiffParserBase
- It does not have _ _ metric _ _ = False""" | return ( cls is not DiffParserBase and cls . __dict__ . get ( '__metric__' , True ) and issubclass ( cls , DiffParserBase ) ) |
def show_bgp_peer ( self , peer_id , ** _params ) :
"""Fetches information of a certain BGP peer .""" | return self . get ( self . bgp_peer_path % peer_id , params = _params ) |
def _validate_publish_parameters ( body , exchange , immediate , mandatory , properties , routing_key ) :
"""Validate Publish Parameters .
: param bytes | str | unicode body : Message payload
: param str routing _ key : Message routing key
: param str exchange : The exchange to publish the message to
: para... | if not compatibility . is_string ( body ) :
raise AMQPInvalidArgument ( 'body should be a string' )
elif not compatibility . is_string ( routing_key ) :
raise AMQPInvalidArgument ( 'routing_key should be a string' )
elif not compatibility . is_string ( exchange ) :
raise AMQPInvalidArgument ( 'exchange shou... |
def apply_pairwise ( self , function , symmetric = True , diagonal = False , block = None , ** kwargs ) :
"""Helper function for pairwise apply .
Args :
steps : an ordered collection of steps
function : function to apply , first two positional arguments are steps
symmetric : whether function is symmetric in... | steps = self . index
r = pd . DataFrame ( index = steps , columns = steps )
for i , s1 in enumerate ( steps ) :
j = range ( i + 1 if symmetric else len ( steps ) )
if not diagonal :
j . remove ( i )
other = set ( steps [ j ] )
if block is not None :
df = self . reset_index ( )
df... |
def copy_from_model ( cls , model_name , reference , ** kwargs ) :
"""Set - up a user - defined grid using specifications of a reference
grid model .
Parameters
model _ name : string
name of the user - defined grid model .
reference : string or : class : ` CTMGrid ` instance
Name of the reference model ... | if isinstance ( reference , cls ) :
settings = reference . __dict__ . copy ( )
settings . pop ( 'model' )
else :
settings = _get_model_info ( reference )
settings . pop ( 'model_name' )
settings . update ( kwargs )
settings [ 'reference' ] = reference
return cls ( model_name , ** settings ) |
def wait_for_subworkflows ( self , workflow_results ) :
'''Wait for results from subworkflows''' | wf_ids = sum ( [ x [ 'pending_workflows' ] for x in workflow_results ] , [ ] )
for wf_id in wf_ids : # here we did not check if workflow ids match
yield self . socket
res = self . socket . recv_pyobj ( )
if res is None :
sys . exit ( 0 )
elif isinstance ( res , Exception ) :
raise res |
def get_customjs ( self , references , plot_id = None ) :
"""Creates a CustomJS callback that will send the requested
attributes back to python .""" | # Generate callback JS code to get all the requested data
if plot_id is None :
plot_id = self . plot . id or 'PLACEHOLDER_PLOT_ID'
self_callback = self . js_callback . format ( comm_id = self . comm . id , timeout = self . timeout , debounce = self . debounce , plot_id = plot_id )
attributes = self . attributes_js ... |
def _find_ble_controllers ( self ) :
"""Get a list of the available and powered BLE controllers""" | controllers = self . bable . list_controllers ( )
return [ ctrl for ctrl in controllers if ctrl . powered and ctrl . low_energy ] |
def _get_stmt_matching_groups ( stmts ) :
"""Use the matches _ key method to get sets of matching statements .""" | def match_func ( x ) :
return x . matches_key ( )
# Remove exact duplicates using a set ( ) call , then make copies :
logger . debug ( '%d statements before removing object duplicates.' % len ( stmts ) )
st = list ( set ( stmts ) )
logger . debug ( '%d statements after removing object duplicates.' % len ( stmts ) )... |
def create_isobaric_quant_lookup ( quantdb , specfn_consensus_els , channelmap ) :
"""Creates an sqlite lookup table of scannrs with quant data .
spectra - an iterable of tupled ( filename , spectra )
consensus _ els - a iterable with consensusElements""" | # store quantchannels in lookup and generate a db _ id vs channel map
channels_store = ( ( name , ) for name , c_id in sorted ( channelmap . items ( ) , key = lambda x : x [ 1 ] ) )
quantdb . store_channelmap ( channels_store )
channelmap_dbid = { channelmap [ ch_name ] : ch_id for ch_id , ch_name in quantdb . get_chan... |
def beautify ( string , * args , ** kwargs ) :
"""Convenient interface to the ecstasy package .
Arguments :
string ( str ) : The string to beautify with ecstasy .
args ( list ) : The positional arguments .
kwargs ( dict ) : The keyword ( ' always ' ) arguments .""" | parser = Parser ( args , kwargs )
return parser . beautify ( string ) |
def getAnalysesNum ( self ) :
"""Returns an array with the number of analyses for the current AR in
different statuses , like follows :
[ verified , total , not _ submitted , to _ be _ verified ]""" | an_nums = [ 0 , 0 , 0 , 0 ]
for analysis in self . getAnalyses ( ) :
review_state = analysis . review_state
if review_state in [ 'retracted' , 'rejected' , 'cancelled' ] :
continue
if review_state == 'to_be_verified' :
an_nums [ 3 ] += 1
elif review_state in [ 'published' , 'verified' ] ... |
def read_pmid_sentences ( pmid_sentences , ** drum_args ) :
"""Read sentences from a PMID - keyed dictonary and return all Statements
Parameters
pmid _ sentences : dict [ str , list [ str ] ]
A dictonary where each key is a PMID pointing to a list of sentences
to be read .
* * drum _ args
Keyword argume... | def _set_pmid ( statements , pmid ) :
for stmt in statements :
for evidence in stmt . evidence :
evidence . pmid = pmid
# See if we need to start DRUM as a subprocess
run_drum = drum_args . get ( 'run_drum' , False )
drum_process = None
all_statements = { }
# Iterate over all the keys and senten... |
def _update_limits_from_api ( self ) :
"""Query Lambda ' s DescribeLimits API action , and update limits
with the quotas returned . Updates ` ` self . limits ` ` .""" | logger . debug ( "Updating limits for Lambda from the AWS API" )
if len ( self . limits ) == 2 :
return
self . connect ( )
lims = self . conn . get_account_settings ( ) [ 'AccountLimit' ]
self . limits [ 'Total Code Size (MiB)' ] . _set_api_limit ( ( lims [ 'TotalCodeSize' ] / 1048576 ) )
self . limits [ 'Code Size... |
def advance_recurring_todo ( p_todo , p_offset = None , p_strict = False ) :
"""Given a Todo item , return a new instance of a Todo item with the dates
shifted according to the recurrence rule .
Strict means that the real due date is taken as a offset , not today or a
future date to determine the offset .
W... | todo = Todo ( p_todo . source ( ) )
pattern = todo . tag_value ( 'rec' )
if not pattern :
raise NoRecurrenceException ( )
elif pattern . startswith ( '+' ) :
p_strict = True
# strip off the +
pattern = pattern [ 1 : ]
if p_strict :
offset = p_todo . due_date ( ) or p_offset or date . today ( )
else ... |
def sortable_sortkey_title ( instance ) :
"""Returns a sortable title as a mxin of sortkey + lowercase sortable _ title""" | title = sortable_title ( instance )
if safe_callable ( title ) :
title = title ( )
sort_key = instance . getSortKey ( )
if sort_key is None :
sort_key = 999999
return "{:010.3f}{}" . format ( sort_key , title ) |
def constant ( X , n , mu , hyper_deriv = None ) :
"""Function implementing a constant mean suitable for use with : py : class : ` MeanFunction ` .""" | if ( n == 0 ) . all ( ) :
if hyper_deriv is not None :
return scipy . ones ( X . shape [ 0 ] )
else :
return mu * scipy . ones ( X . shape [ 0 ] )
else :
return scipy . zeros ( X . shape [ 0 ] ) |
def _fields ( self , resource ) :
"""Get projection fields for given resource .""" | datasource = self . get_datasource ( resource )
keys = datasource [ 2 ] . keys ( )
return ',' . join ( keys ) + ',' . join ( [ config . LAST_UPDATED , config . DATE_CREATED ] ) |
def from_pymatgen_molecule ( cls , molecule ) :
"""Create an instance of the own class from a pymatgen molecule
Args :
molecule ( : class : ` pymatgen . core . structure . Molecule ` ) :
Returns :
Cartesian :""" | new = cls ( atoms = [ el . value for el in molecule . species ] , coords = molecule . cart_coords )
return new . _to_numeric ( ) |
def sun_events ( latitude , longitude , date , timezone = 0 , zenith = None ) :
"""Convenience function for calculating sunrise and sunset .
Civil twilight starts / ends when the Sun ' s centre is 6 degrees below
the horizon .
Nautical twilight starts / ends when the Sun ' s centre is 12 degrees
below the h... | return ( sun_rise_set ( latitude , longitude , date , 'rise' , timezone , zenith ) , sun_rise_set ( latitude , longitude , date , 'set' , timezone , zenith ) ) |
def render_payment_form ( self ) :
"""Display the DirectPayment for entering payment information .""" | self . context [ self . form_context_name ] = self . payment_form_cls ( )
return TemplateResponse ( self . request , self . payment_template , self . context ) |
def getInspectorActionById ( self , identifier ) :
"""Sets the inspector and draw the contents
Triggers the corresponding action so that it is checked in the menus .""" | for action in self . inspectorActionGroup . actions ( ) :
if action . data ( ) == identifier :
return action
raise KeyError ( "No action found with ID: {!r}" . format ( identifier ) ) |
def fetch_routing_info ( self , address ) :
"""Fetch raw routing info from a given router address .
: param address : router address
: return : list of routing records or
None if no connection could be established
: raise ServiceUnavailable : if the server does not support routing or
if routing support is... | metadata = { }
records = [ ]
def fail ( md ) :
if md . get ( "code" ) == "Neo.ClientError.Procedure.ProcedureNotFound" :
raise RoutingProtocolError ( "Server {!r} does not support routing" . format ( address ) )
else :
raise RoutingProtocolError ( "Routing support broken on server {!r}" . format... |
async def load_credentials ( self , credentials ) :
"""Load existing credentials .""" | split = credentials . split ( ':' )
self . identifier = split [ 0 ]
self . srp . initialize ( binascii . unhexlify ( split [ 1 ] ) )
_LOGGER . debug ( 'Loaded AirPlay credentials: %s' , credentials ) |
def request ( self ) :
"""Send the request to the API .
This method will send the request to the API . It will try to handle
all the types of responses and provide the relevant data when possible .
Some basic error detection and handling is implemented , but not all failure
cases will get caught .
Return ... | # self . _ request . authorization _ method ( self . _ authorization _ method )
self . _request . url = '{}/v2/{}' . format ( self . tcex . default_args . tc_api_path , self . _request_uri )
self . _apply_filters ( )
self . tcex . log . debug ( u'Resource URL: ({})' . format ( self . _request . url ) )
response = self ... |
def _unlock ( self , closing = False ) :
"""Remove lock file to the target root folder .""" | # write ( " _ unlock " , closing )
try :
if self . cur_dir != self . root_dir :
if closing :
write ( "Changing to ftp root folder to remove lock file: {}" . format ( self . root_dir ) )
self . cwd ( self . root_dir )
else :
write_error ( "Could not remove lock fil... |
def processV3 ( self , sessionRecord , message ) :
""": param sessionRecord :
: param message :
: type message : PreKeyWhisperMessage
: return :""" | if sessionRecord . hasSessionState ( message . getMessageVersion ( ) , message . getBaseKey ( ) . serialize ( ) ) :
logger . warn ( "We've already setup a session for this V3 message, letting bundled message fall through..." )
return None
ourSignedPreKey = self . signedPreKeyStore . loadSignedPreKey ( message .... |
def learn ( self , grad_arr , fix_opt_flag = False ) :
'''Update this Discriminator by ascending its stochastic gradient .
Args :
grad _ arr : ` np . ndarray ` of gradients .
fix _ opt _ flag : If ` False ` , no optimization in this model will be done .
Returns :
` np . ndarray ` of delta or gradients .''... | channel = grad_arr . shape [ 1 ] // 2
grad_arr = self . __deconvolution_model . learn ( grad_arr [ : , : channel ] , fix_opt_flag = fix_opt_flag )
delta_arr = self . __cnn . back_propagation ( grad_arr )
if fix_opt_flag is False :
self . __cnn . optimize ( self . __learning_rate , 1 )
return delta_arr |
def from_pubkey_line ( cls , line ) :
"""Generate Key instance from a a string . Raise ValueError if string is
malformed""" | options , key_without_options = cls . _extract_options ( line )
if key_without_options == '' :
raise ValueError ( "Empty key" )
# the key ( with options stripped out ) should consist of the fields
# " type " , " data " , and optionally " comment " , separated by a space .
# The comment field may contain additional ... |
def run ( self , args ) :
"""Give the user with user _ full _ name the auth _ role permissions on the remote project with project _ name .
: param args Namespace arguments parsed from the command line""" | email = args . email
# email of person to give permissions , will be None if username is specified
username = args . username
# username of person to give permissions , will be None if email is specified
auth_role = args . auth_role
# type of permission ( project _ admin )
project = self . fetch_project ( args , must_e... |
def permit_gitrepo ( config_fpath , writeback = False ) :
"""Changes https : / / in . git / config files to git @ and makes
appropriate changes to colons and slashses""" | # Define search replace patterns
username_regex = utool . named_field ( 'username' , utool . REGEX_VARNAME )
username_repl = utool . backref_field ( 'username' )
regexpat = r'https://github.com/' + username_regex + '/'
replpat = r'git@github.com:' + username_repl + '/'
# Read and replace
lines = utool . read_from ( con... |
def total_tax ( self ) :
"""Returns the sum of all Tax objects .""" | q = Tax . objects . filter ( receipt = self ) . aggregate ( total = Sum ( 'amount' ) )
return q [ 'total' ] or 0 |
def instance ( ) :
"""Return an PyVabamorf instance .
It returns the previously initialized instance or creates a new
one if nothing exists . Also creates new instance in case the
process has been forked .""" | if not hasattr ( Vabamorf , 'pid' ) or Vabamorf . pid != os . getpid ( ) :
Vabamorf . pid = os . getpid ( )
Vabamorf . morf = Vabamorf ( )
return Vabamorf . morf |
def update_model ( self , tfi ) :
"""Update the model for the given tfi
: param tfi : taskfile info
: type tfi : : class : ` TaskFileInfo `
: returns : None
: rtype : None
: raises : None""" | if tfi . task . department . assetflag :
browser = self . assetbrws
else :
browser = self . shotbrws
if tfi . version == 1 : # add descriptor
parent = browser . selected_indexes ( 2 ) [ 0 ]
ddata = treemodel . ListItemData ( [ tfi . descriptor ] )
ditem = treemodel . TreeItem ( ddata )
browser .... |
def _load_from ( self , line ) :
'''load the From section of the recipe for the Dockerfile .''' | # Remove any comments
line = line . split ( '#' , 1 ) [ 0 ]
line = re . sub ( '(F|f)(R|r)(O|o)(M|m):' , '' , line ) . strip ( )
bot . info ( 'FROM %s' % line )
self . config [ 'from' ] = line |
def add_environment ( self , environ ) :
"""Updates the environment dictionary with the given one .
Existing entries are overridden by the given ones
: param environ : New environment variables""" | if isinstance ( environ , dict ) :
self . _environment . update ( environ ) |
def match_completion ( self , start , end , match ) :
"""Sets the completion for this query to match completion percentages between the given range inclusive .
arg : start ( decimal ) : start of range
arg : end ( decimal ) : end of range
arg : match ( boolean ) : ` ` true ` ` for a positive match ,
` ` fals... | try :
start = float ( start )
except ValueError :
raise errors . InvalidArgument ( 'Invalid start value' )
try :
end = float ( end )
except ValueError :
raise errors . InvalidArgument ( 'Invalid end value' )
if match :
if end < start :
raise errors . InvalidArgument ( 'end value must be >= s... |
def profile_get ( name , remote_addr = None , cert = None , key = None , verify_cert = True , _raw = False ) :
'''Gets a profile from the LXD
name :
The name of the profile to get .
remote _ addr :
An URL to a remote Server , you also have to give cert and key if
you provide remote _ addr and its a TCP Ad... | client = pylxd_client_get ( remote_addr , cert , key , verify_cert )
profile = None
try :
profile = client . profiles . get ( name )
except pylxd . exceptions . LXDAPIException :
raise SaltInvocationError ( 'Profile \'{0}\' not found' . format ( name ) )
if _raw :
return profile
return _pylxd_model_to_dict ... |
def customize_base_cfg ( cfgname , cfgopt_strs , base_cfg , cfgtype , alias_keys = None , valid_keys = None , offset = 0 , strict = True ) :
"""Args :
cfgname ( str ) : config name
cfgopt _ strs ( str ) : mini - language defining key variations
base _ cfg ( dict ) : specifies the default cfg to customize
cf... | import utool as ut
cfg = base_cfg . copy ( )
# Parse config options without expansion
cfg_options = noexpand_parse_cfgstrs ( cfgopt_strs , alias_keys )
# Ensure that nothing bad is being updated
if strict :
parsed_keys = cfg_options . keys ( )
if valid_keys is not None :
ut . assert_all_in ( parsed_keys... |
def write_channel_list_file ( channels , fobj ) :
"""Write a ` ~ gwpy . detector . ChannelList ` to a INI - format channel list file""" | if not isinstance ( fobj , FILE_LIKE ) :
with open ( fobj , "w" ) as fobj :
return write_channel_list_file ( channels , fobj )
out = configparser . ConfigParser ( dict_type = OrderedDict )
for channel in channels :
group = channel . group
if not out . has_section ( group ) :
out . add_sectio... |
def add_options ( cls , parser ) :
"""Add options for command line and config file .""" | parser . add_option ( '--putty-select' , metavar = 'errors' , default = '' , help = 'putty select list' , )
parser . add_option ( '--putty-ignore' , metavar = 'errors' , default = '' , help = 'putty ignore list' , )
parser . add_option ( '--putty-no-auto-ignore' , action = 'store_false' , dest = 'putty_auto_ignore' , d... |
def command_children ( self , command ) :
"""Run a command on the direct children of the currently selected
container .
: rtype : List of CommandReply ? ? ? ?""" | if not len ( self . nodes ) :
return
commands = [ ]
for c in self . nodes :
commands . append ( '[con_id="{}"] {};' . format ( c . id , command ) )
self . _conn . command ( ' ' . join ( commands ) ) |
def int_flux_threshold ( self , skydir , fn , ts_thresh , min_counts ) :
"""Compute the integral flux threshold for a point source at
position ` ` skydir ` ` with spectral parameterization ` ` fn ` ` .""" | ebins = 10 ** np . linspace ( np . log10 ( self . ebins [ 0 ] ) , np . log10 ( self . ebins [ - 1 ] ) , 33 )
ectr = np . sqrt ( ebins [ 0 ] * ebins [ - 1 ] )
sig , bkg , bkg_fit = self . compute_counts ( skydir , fn , ebins )
norms = irfs . compute_norm ( sig , bkg , ts_thresh , min_counts , sum_axes = [ 1 , 2 , 3 ] , ... |
def ensure_datetime ( obj ) :
"""Return the object if it is a datetime - like object
Parameters
obj : Object to be tested .
Returns
The original object if it is a datetime - like object
Raises
TypeError if ` obj ` is not datetime - like""" | _VALID_TYPES = ( str , datetime . datetime , cftime . datetime , np . datetime64 )
if isinstance ( obj , _VALID_TYPES ) :
return obj
raise TypeError ( "datetime-like object required. " "Type given: {}" . format ( type ( obj ) ) ) |
def _moving_average ( data , wind_size = 3 ) :
"""Brief
Application of a moving average filter for signal smoothing .
Description
In certain situations it will be interesting to simplify a signal , particularly in cases where
some events with a random nature take place ( the random nature of EMG activation ... | wind_size = int ( wind_size )
ret = numpy . cumsum ( data , dtype = float )
ret [ wind_size : ] = ret [ wind_size : ] - ret [ : - wind_size ]
return numpy . concatenate ( ( numpy . zeros ( wind_size - 1 ) , ret [ wind_size - 1 : ] / wind_size ) ) |
def index_exists ( self ) :
"""Check to see if index exists .""" | headers = { 'Content-Type' : 'application/json' , 'DB-Method' : 'GET' }
url = '/v2/exchange/db/{}/{}/_search' . format ( self . domain , self . data_type )
r = self . tcex . session . post ( url , headers = headers )
if not r . ok :
self . tcex . log . warning ( 'The provided index was not found ({}).' . format ( r... |
def copies ( mapping , s2bins , rna , min_rna = 800 , mismatches = 0 ) :
"""1 . determine bin coverage
2 . determine rRNA gene coverage
3 . compare""" | cov = { }
# cov [ scaffold ] = [ bases , length ]
s2bins , bins2s = parse_s2bins ( s2bins )
rna_cov = parse_rna ( rna , s2bins , min_rna )
s2bins , bins2s = filter_missing_rna ( s2bins , bins2s , rna_cov )
# count bases mapped to scaffolds and rRNA gene regions
for line in mapping :
line = line . strip ( ) . split ... |
def _mdens_deriv ( self , m ) :
"""Derivative of the density as a function of m""" | return - self . _mdens ( m ) * ( self . a * self . alpha + self . beta * m ) / m / ( self . a + m ) |
def get_user_mentions ( tweet ) :
"""Get the @ - mentions in the Tweet as dictionaries .
Note that in the case of a quote - tweet , this does not return the users
mentioned in the quoted status . The recommended way to get that list would
be to use get _ user _ mentions on the quoted status .
Also note that... | entities = get_entities ( tweet )
user_mentions = entities . get ( "user_mentions" ) if entities else None
return user_mentions if user_mentions else [ ] |
def read_prologs ( filename ) :
"""Given a filename , search for SST prologues
and returns a dict where the keys are the name of the
prolog ( from the " Name " field ) and the keys are another
dict with keys correspding fo the SST labels in lowercase .
prologs = read _ prologs ( filename )
Common SST labe... | results = { }
prolog = { }
heading_re = re . compile ( r"^\* ([A-Z].*):$" )
heading = ""
content = ""
counter = 0
for line in open ( filename ) :
line = line . strip ( )
# Start of a completely new prolog so reset everything
if line . startswith ( "*+" ) :
if counter != 0 :
raise ValueE... |
def upload_path ( instance , filename ) :
'''Sanitize the user - provided file name , add timestamp for uniqness .''' | filename = filename . replace ( " " , "_" )
filename = unicodedata . normalize ( 'NFKD' , filename ) . lower ( )
return os . path . join ( str ( timezone . now ( ) . date ( ) . isoformat ( ) ) , filename ) |
def resource_response ( resource , depth = 0 ) :
"""Return a response for the * resource * of the appropriate content type .
: param resource : resource to be returned in request
: type resource : : class : ` sandman . model . Model `
: rtype : : class : ` flask . Response `""" | if _get_acceptable_response_type ( ) == JSON :
depth = 0
if 'expand' in request . args :
depth = 1
return _single_resource_json_response ( resource , depth )
else :
return _single_resource_html_response ( resource ) |
def address ( self , num ) :
"""Search for company addresses by company number .
Args :
num ( str ) : Company number to search on .""" | url_root = "company/{}/registered-office-address"
baseuri = self . _BASE_URI + url_root . format ( num )
res = self . session . get ( baseuri )
self . handle_http_error ( res )
return res |
def populate_event_que ( self , que_obj ) :
"""Populates the event queue object .
This is for sending router events to event handler .""" | for ip in self . obj_dict :
drvr_obj = self . obj_dict . get ( ip ) . get ( 'drvr_obj' )
drvr_obj . populate_event_que ( que_obj ) |
def start ( name , quiet = False , path = None ) :
'''Start the named container .
path
path to the container parent
default : / var / lib / lxc ( system default )
. . versionadded : : 2015.8.0
. . code - block : : bash
salt - run lxc . start name''' | data = _do_names ( name , 'start' , path = path )
if data and not quiet :
__jid_event__ . fire_event ( { 'data' : data , 'outputter' : 'lxc_start' } , 'progress' )
return data |
def logical_chassis_fwdl_sanity_input_host ( self , ** kwargs ) :
"""Auto Generated Code""" | config = ET . Element ( "config" )
logical_chassis_fwdl_sanity = ET . Element ( "logical_chassis_fwdl_sanity" )
config = logical_chassis_fwdl_sanity
input = ET . SubElement ( logical_chassis_fwdl_sanity , "input" )
host = ET . SubElement ( input , "host" )
host . text = kwargs . pop ( 'host' )
callback = kwargs . pop (... |
def scaffold ( args ) :
"""% prog scaffold scaffold . fasta synteny . blast synteny . sizes synteny . bed
physicalmap . blast physicalmap . sizes physicalmap . bed
As evaluation of scaffolding , visualize external line of evidences :
* Plot synteny to an external genome
* Plot alignments to physical map
*... | from jcvi . utils . iter import grouper
p = OptionParser ( scaffold . __doc__ )
p . add_option ( "--cutoff" , type = "int" , default = 1000000 , help = "Plot scaffolds with size larger than [default: %default]" )
p . add_option ( "--highlights" , help = "A set of regions in BED format to highlight [default: %default]" ... |
def _read_para_transaction_pacing ( self , code , cbit , clen , * , desc , length , version ) :
"""Read HIP TRANSACTION _ PACING parameter .
Structure of HIP TRANSACTION _ PACING parameter [ RFC 5770 ] :
0 1 2 3
0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
| Type | Length |
| Min Ta |
... | if clen != 4 :
raise ProtocolError ( f'HIPv{version}: [Parano {code}] invalid format' )
_data = self . _read_unpack ( 4 )
transaction_pacing = dict ( type = desc , critical = cbit , length = clen , min_ta = _data , )
return transaction_pacing |
def debugfile ( filename , args = None , wdir = None , post_mortem = False ) :
"""Debug filename
args : command line arguments ( string )
wdir : working directory
post _ mortem : boolean , included for compatiblity with runfile""" | debugger = pdb . Pdb ( )
filename = debugger . canonic ( filename )
debugger . _wait_for_mainpyfile = 1
debugger . mainpyfile = filename
debugger . _user_requested_quit = 0
if os . name == 'nt' :
filename = filename . replace ( '\\' , '/' )
debugger . run ( "runfile(%r, args=%r, wdir=%r)" % ( filename , args , wdir... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.