signature stringlengths 29 44.1k | implementation stringlengths 0 85.2k |
|---|---|
def certificate_authority ( self ) :
"""Gets the Certificate Authority API client .
Returns :
CertificateAuthority :""" | if not self . __certificate_authority :
self . __certificate_authority = CertificateAuthority ( self . __connection )
return self . __certificate_authority |
def handle_log ( self , obj ) :
"""Handle an incoming log processing request .
: param obj : The Channels message object . Command object format :
. . code - block : : none
' command ' : ' log ' ,
' message ' : [ log message ]""" | record_dict = json . loads ( obj [ ExecutorProtocol . LOG_MESSAGE ] )
record_dict [ 'msg' ] = record_dict [ 'msg' ]
executors_dir = os . path . join ( os . path . dirname ( os . path . dirname ( __file__ ) ) , 'executors' )
record_dict [ 'pathname' ] = os . path . join ( executors_dir , record_dict [ 'pathname' ] )
log... |
def schedule ( func , * args , ** kwargs ) :
"""Create a schedule .
: param func : function to schedule .
: param args : function arguments .
: param name : optional name for the schedule .
: param hook : optional result hook function .
: type schedule _ type : Schedule . TYPE
: param repeats : how many... | name = kwargs . pop ( 'name' , None )
hook = kwargs . pop ( 'hook' , None )
schedule_type = kwargs . pop ( 'schedule_type' , Schedule . ONCE )
minutes = kwargs . pop ( 'minutes' , None )
repeats = kwargs . pop ( 'repeats' , - 1 )
next_run = kwargs . pop ( 'next_run' , timezone . now ( ) )
# check for name duplicates in... |
def decode ( self , check_trailer = False ) : # pylint : disable = I0011 , R0912
"""Decode data in C { self . data } and return deserialized object .
@ param check _ trailer : Raise error if trailing junk is found in data ?
@ raise BencodeError : Invalid data .""" | try :
kind = self . data [ self . offset ]
except IndexError :
raise BencodeError ( "Unexpected end of data at offset %d/%d" % ( self . offset , len ( self . data ) , ) )
if kind . isdigit ( ) : # String
try :
end = self . data . find ( ':' , self . offset )
length = int ( self . data [ self... |
def send_msg ( self , msg , wait_nak = True , wait_timeout = WAIT_TIMEOUT ) :
"""Place a message on the send queue for sending .
Message are sent in the order they are placed in the queue .""" | msg_info = MessageInfo ( msg = msg , wait_nak = wait_nak , wait_timeout = wait_timeout )
_LOGGER . debug ( "Queueing msg: %s" , msg )
self . _send_queue . put_nowait ( msg_info ) |
def open_db ( db , zipped = None , encoding = None , fieldnames_lower = True , case_sensitive = True ) :
"""Context manager . Allows reading DBF file ( maybe even from zip ) .
: param str | unicode | file db : . dbf file name or a file - like object .
: param str | unicode zipped : . zip file path or a file - l... | kwargs = dict ( encoding = encoding , fieldnames_lower = fieldnames_lower , case_sensitive = case_sensitive , )
if zipped :
with Dbf . open_zip ( db , zipped , ** kwargs ) as dbf :
yield dbf
else :
with Dbf . open ( db , ** kwargs ) as dbf :
yield dbf |
def iterator ( self ) :
"""If search has occurred and no ordering has occurred , decorate
each result with the number of search terms so that it can be
sorted by the number of occurrence of terms .
In the case of search fields that span model relationships , we
cannot accurately match occurrences without so... | results = super ( SearchableQuerySet , self ) . iterator ( )
if self . _search_terms and not self . _search_ordered :
results = list ( results )
for i , result in enumerate ( results ) :
count = 0
related_weights = [ ]
for ( field , weight ) in self . _search_fields . items ( ) :
... |
def _GetParsersFromPresetCategory ( cls , category ) :
"""Retrieves the parser names of specific preset category .
Args :
category ( str ) : parser preset categories .
Returns :
list [ str ] : parser names in alphabetical order .""" | preset_definition = cls . _presets . GetPresetByName ( category )
if preset_definition is None :
return [ ]
preset_names = cls . _presets . GetNames ( )
parser_names = set ( )
for element_name in preset_definition . parsers :
if element_name in preset_names :
category_parser_names = cls . _GetParsersFro... |
def _pad_nochord ( target , axis = - 1 ) :
'''Pad a chord annotation with no - chord flags .
Parameters
target : np . ndarray
the input data
axis : int
the axis along which to pad
Returns
target _ pad
` target ` expanded by 1 along the specified ` axis ` .
The expanded dimension will be 0 when ` t... | ncmask = ~ np . max ( target , axis = axis , keepdims = True )
return np . concatenate ( [ target , ncmask ] , axis = axis ) |
def stdrepr_iterable ( self , obj , * , cls = None , before = None , after = None ) :
"""Helper function to represent iterables . StdHRepr calls this on
lists , tuples , sets and frozensets , but NOT on iterables in general .
This method may be called to produce custom representations .
Arguments :
obj ( it... | if cls is None :
cls = f'hrepr-{obj.__class__.__name__}'
children = [ self ( a ) for a in obj ]
return self . titled_box ( ( before , after ) , children , 'h' , 'h' ) [ cls ] |
def instant_articles ( self , ** kwargs ) :
"""QuerySet including all published content approved for instant articles .
Instant articles are configured via FeatureType . FeatureType . instant _ article = True .""" | eqs = self . search ( ** kwargs ) . sort ( '-last_modified' , '-published' )
return eqs . filter ( InstantArticle ( ) ) |
def reproject ( self , projection ) :
"""in - memory reprojection
Parameters
projection : int , str or : osgeo : class : ` osr . SpatialReference `
the target CRS . See : func : ` spatialist . auxil . crsConvert ` .
Returns""" | srs_out = crsConvert ( projection , 'osr' )
if self . srs . IsSame ( srs_out ) == 0 : # create the CoordinateTransformation
coordTrans = osr . CoordinateTransformation ( self . srs , srs_out )
layername = self . layername
geomType = self . geomType
features = self . getfeatures ( )
feat_def = featur... |
def connect ( slug , config_loader ) :
"""Ensure . cs50 . yaml and tool key exists , raises Error otherwise
Check that all required files as per . cs50 . yaml are present
Returns tool specific portion of . cs50 . yaml""" | with ProgressBar ( _ ( "Connecting" ) ) : # Parse slug
slug = Slug ( slug )
# Get . cs50 . yaml
try :
config = config_loader . load ( _get_content ( slug . org , slug . repo , slug . branch , slug . problem / ".cs50.yaml" ) )
except InvalidConfigError :
raise InvalidSlugError ( _ ( "Inva... |
def arp_access_list_permit_permit_list_mac_type ( self , ** kwargs ) :
"""Auto Generated Code""" | config = ET . Element ( "config" )
arp = ET . SubElement ( config , "arp" , xmlns = "urn:brocade.com:mgmt:brocade-dai" )
access_list = ET . SubElement ( arp , "access-list" )
acl_name_key = ET . SubElement ( access_list , "acl-name" )
acl_name_key . text = kwargs . pop ( 'acl_name' )
permit = ET . SubElement ( access_l... |
def _tobinarray_really ( self , start , end , pad , size ) :
"""Return binary array .""" | if pad is None :
pad = self . padding
bin = array ( 'B' )
if self . _buf == { } and None in ( start , end ) :
return bin
if size is not None and size <= 0 :
raise ValueError ( "tobinarray: wrong value for size" )
start , end = self . _get_start_end ( start , end , size )
for i in range_g ( start , end + 1 )... |
def generate_uuid4 ( self ) -> list :
"""Generate a list of parts of a UUID version 4 string .
Usually , these parts are concatenated together using dashes .""" | # uuid4 : 8-4-4-4-12 : xxxxx - xxxx - 4xxx - { 8,9 , a , b } xxx - xxxxx
# instead of requesting small amounts of bytes , it ' s better to do it
# for the full amount of them .
hexstr = randhex ( 30 )
uuid4 = [ hexstr [ : 8 ] , hexstr [ 8 : 12 ] , '4' + hexstr [ 12 : 15 ] , '{:x}{}' . format ( randbetween ( 8 , 11 ) , ... |
def _augment_stmt ( self , stmt : Statement , sctx : SchemaContext ) -> None :
"""Handle * * augment * * statement .""" | if not sctx . schema_data . if_features ( stmt , sctx . text_mid ) :
return
path = sctx . schema_data . sni2route ( stmt . argument , sctx )
target = self . get_schema_descendant ( path )
if stmt . find1 ( "when" ) :
gr = GroupNode ( )
target . _add_child ( gr )
target = gr
target . _handle_substatement... |
def _initialize_indices ( model_class , name , bases , attrs ) :
"""Stores the list of indexed attributes .""" | model_class . _indices = [ ]
for k , v in attrs . iteritems ( ) :
if isinstance ( v , ( Attribute , ListField ) ) and v . indexed :
model_class . _indices . append ( k )
if model_class . _meta [ 'indices' ] :
model_class . _indices . extend ( model_class . _meta [ 'indices' ] ) |
def comment ( node ) :
"""Converts the node received to a comment , in place , and will also return the
comment element .""" | parent = node . parentNode
comment = node . ownerDocument . createComment ( node . toxml ( ) )
parent . replaceChild ( comment , node )
return comment |
def get ( self ) :
"""Constructs a TaskQueueStatisticsContext
: returns : twilio . rest . taskrouter . v1 . workspace . task _ queue . task _ queue _ statistics . TaskQueueStatisticsContext
: rtype : twilio . rest . taskrouter . v1 . workspace . task _ queue . task _ queue _ statistics . TaskQueueStatisticsCont... | return TaskQueueStatisticsContext ( self . _version , workspace_sid = self . _solution [ 'workspace_sid' ] , task_queue_sid = self . _solution [ 'task_queue_sid' ] , ) |
def find_max_label_length ( labels ) :
"""Return the maximum length for the labels .""" | length = 0
for i in range ( len ( labels ) ) :
if len ( labels [ i ] ) > length :
length = len ( labels [ i ] )
return length |
def index ( ) :
"""List linked accounts .""" | oauth = current_app . extensions [ 'oauthlib.client' ]
services = [ ]
service_map = { }
i = 0
for appid , conf in six . iteritems ( current_app . config [ 'OAUTHCLIENT_REMOTE_APPS' ] ) :
if not conf . get ( 'hide' , False ) :
services . append ( dict ( appid = appid , title = conf [ 'title' ] , icon = conf ... |
def has_axon ( neuron , treefun = _read_neurite_type ) :
'''Check if a neuron has an axon
Arguments :
neuron ( Neuron ) : The neuron object to test
treefun : Optional function to calculate the tree type of
neuron ' s neurites
Returns :
CheckResult with result''' | return CheckResult ( NeuriteType . axon in ( treefun ( n ) for n in neuron . neurites ) ) |
def email_verifier ( self , email , raw = False ) :
"""Verify the deliverability of a given email adress . abs
: param email : The email adress to check .
: param raw : Gives back the entire response instead of just the ' data ' .
: return : Full payload of the query as a dict .""" | params = { 'email' : email , 'api_key' : self . api_key }
endpoint = self . base_endpoint . format ( 'email-verifier' )
return self . _query_hunter ( endpoint , params , raw = raw ) |
def login ( self , account = None , app_account = None , flush = True ) :
"""Log into the connected host using the best method available .
If an account is not given , default to the account that was
used during the last call to login ( ) . If a previous call was not
made , use the account that was passed to ... | with self . _get_account ( account ) as account :
if app_account is None :
app_account = account
self . authenticate ( account , flush = False )
if self . get_driver ( ) . supports_auto_authorize ( ) :
self . expect_prompt ( )
self . auto_app_authorize ( app_account , flush = flush ) |
def random_stochastic_matrix ( n , k = None , sparse = False , format = 'csr' , random_state = None ) :
"""Return a randomly sampled n x n stochastic matrix with k nonzero
entries for each row .
Parameters
n : scalar ( int )
Number of states .
k : scalar ( int ) , optional ( default = None )
Number of n... | P = _random_stochastic_matrix ( m = n , n = n , k = k , sparse = sparse , format = format , random_state = random_state )
return P |
def on_retry ( self , exc , task_id , args , kwargs , einfo ) :
"""Capture the exception that caused the task to be retried , if any .""" | super ( LoggedTask , self ) . on_retry ( exc , task_id , args , kwargs , einfo )
log . warning ( '[{}] retried due to {}' . format ( task_id , getattr ( einfo , 'traceback' , None ) ) ) |
def expand_cause_repertoire ( self , repertoire , new_purview = None ) :
"""Alias for | expand _ repertoire ( ) | with ` ` direction ` ` set to | CAUSE | .""" | return self . expand_repertoire ( Direction . CAUSE , repertoire , new_purview ) |
def insert_execution_history ( self , parent , execution_history , is_root = False ) :
"""Insert a list of history items into a the tree store
If there are concurrency history items , the method is called recursively .
: param Gtk . TreeItem parent : the parent to add the next history item to
: param Executio... | current_parent = parent
execution_history_iterator = iter ( execution_history )
for history_item in execution_history_iterator :
if isinstance ( history_item , ConcurrencyItem ) :
self . insert_concurrent_execution_histories ( current_parent , history_item . execution_histories )
elif isinstance ( histo... |
def execute_query ( self , verb , verb_arguments ) :
"""Executes query ( ex . get ) via a dedicated http object .
Args :
verb ( str ) : Method to execute on the component ( ex . get , list ) .
verb _ arguments ( dict ) : key - value pairs to be passed to _ BuildRequest .
Returns :
dict : Service Response ... | request = self . _build_request ( verb , verb_arguments )
return self . _execute ( request ) |
def _process_interval ( self , mod , interval ) :
'''Process beacons with intervals
Return True if a beacon should be run on this loop''' | log . trace ( 'Processing interval %s for beacon mod %s' , interval , mod )
loop_interval = self . opts [ 'loop_interval' ]
if mod in self . interval_map :
log . trace ( 'Processing interval in map' )
counter = self . interval_map [ mod ]
log . trace ( 'Interval counter: %s' , counter )
if counter * loo... |
def to_timestamp ( self , freq = None , how = 'start' , axis = 0 , copy = True ) :
"""Cast to DatetimeIndex of timestamps , at * beginning * of period .
Parameters
freq : str , default frequency of PeriodIndex
Desired frequency .
how : { ' s ' , ' e ' , ' start ' , ' end ' }
Convention for converting peri... | new_data = self . _data
if copy :
new_data = new_data . copy ( )
axis = self . _get_axis_number ( axis )
if axis == 0 :
new_data . set_axis ( 1 , self . index . to_timestamp ( freq = freq , how = how ) )
elif axis == 1 :
new_data . set_axis ( 0 , self . columns . to_timestamp ( freq = freq , how = how ) )
e... |
def _get_gosubdagplotnts ( self , hdrgo , usrgos , pltargs , go2parentids ) :
"""Get list of GoSubDagPlotNt for plotting an exploratory GODAG for 1 Group of user GOs .""" | dotgraphs = [ ]
go2color = pltargs . get_go2color_inst ( hdrgo )
# namedtuple fields : hdrgo gosubdag tot _ usrgos parentcnt desc
ntpltgo0 = self . _get_pltdag_ancesters ( hdrgo , usrgos , desc = "" )
ntpltgo1 = self . _get_pltdag_path_hdr ( hdrgo , usrgos , desc = "pruned" )
num_go0 = len ( ntpltgo0 . gosubdag . go2ob... |
def report ( ctx , file , metrics , number , message , format , console_format , output ) :
"""Show metrics for a given file .""" | config = ctx . obj [ "CONFIG" ]
if not exists ( config ) :
handle_no_cache ( ctx )
if not metrics :
metrics = get_default_metrics ( config )
logger . info ( f"Using default metrics {metrics}" )
new_output = Path ( ) . cwd ( )
if output :
new_output = new_output / Path ( output )
else :
new_output = ... |
def velvet ( readsize , genomesize , numreads , K ) :
"""Calculate velvet memory requirement .
< http : / / seqanswers . com / forums / showthread . php ? t = 2101 >
Ram required for velvetg = - 109635 + 18977 * ReadSize + 86326 * GenomeSize +
233353 * NumReads - 51092 * K
Read size is in bases .
Genome s... | ram = - 109635 + 18977 * readsize + 86326 * genomesize + 233353 * numreads - 51092 * K
print ( "ReadSize: {0}" . format ( readsize ) , file = sys . stderr )
print ( "GenomeSize: {0}Mb" . format ( genomesize ) , file = sys . stderr )
print ( "NumReads: {0}M" . format ( numreads ) , file = sys . stderr )
print ( "K: {0}"... |
def _parse_attribute_details ( self , prop = ATTRIBUTES ) :
"""Concatenates a list of Attribute Details data structures parsed from a remote file""" | parsed_attributes = self . _parse_attribute_details_file ( prop )
if parsed_attributes is None : # If not in the ( official ) remote location , try the tree itself
parsed_attributes = self . _parse_complex_list ( prop )
for attribute in ( a for a in parsed_attributes if not a [ 'aliases' ] ) : # Aliases are not in ... |
def _parse_jing_output ( output ) :
"""Parse the jing output into a tuple of line , column , type and message .""" | output = output . strip ( )
values = [ _parse_jing_line ( l ) for l in output . split ( '\n' ) if l ]
return tuple ( values ) |
def set_clipboard ( clipboard ) :
'''Explicitly sets the clipboard mechanism . The " clipboard mechanism " is how
the copy ( ) and paste ( ) functions interact with the operating system to
implement the copy / paste feature . The clipboard parameter must be one of :
- pbcopy
- pbobjc ( default on Mac OS X )... | global copy , paste
clipboard_types = { 'pbcopy' : init_osx_pbcopy_clipboard , 'pyobjc' : init_osx_pyobjc_clipboard , 'gtk' : init_gtk_clipboard , 'qt' : init_qt_clipboard , # TODO - split this into ' qtpy ' , ' pyqt4 ' , and ' pyqt5'
'xclip' : init_xclip_clipboard , 'xsel' : init_xsel_clipboard , 'klipper' : init_klip... |
def send_message ( self , message ) :
'''Send a Bokeh Server protocol message to the connected client .
Args :
message ( Message ) : a message to send''' | try :
if _message_test_port is not None :
_message_test_port . sent . append ( message )
yield message . send ( self )
except ( WebSocketClosedError , StreamClosedError ) : # Tornado 4 . x may raise StreamClosedError
# on _ close ( ) is / will be called anyway
log . warning ( "Failed sending message... |
def multiprocess_permutation ( bed_dict , mut_df , opts , indel_df = None ) :
"""Handles parallelization of permutations by splitting work
by chromosome .""" | chroms = sorted ( bed_dict . keys ( ) , key = lambda x : len ( bed_dict [ x ] ) , reverse = True )
multiprocess_flag = opts [ 'processes' ] > 0
if multiprocess_flag :
num_processes = opts [ 'processes' ]
else :
num_processes = 1
# file _ handle = open ( opts [ ' output ' ] , ' w ' )
file_handle = opts [ 'handle... |
def _build_tree ( self ) :
"""Builds the tree finding an augmenting path . Alternates along
matched and unmatched edges between X and Y . The paths are
stored in _ pred ( new predecessor of nodes in Y ) , and
self . _ x and self . _ y""" | # find unassigned i *
istar = np . argmin ( self . _x )
# compute distances
self . _d = self . c [ istar ] - self . _v
_pred = np . zeros ( self . n , dtype = np . int ) + istar
# initialize sets
# READY : set of nodes visited and in the path ( whose price gets
# updated in augment )
# SCAN : set of nodes at the bottom... |
def set_boot_order ( self , position , device ) :
"""Puts the given device to the specified position in
the boot order .
To indicate that no device is associated with the given position ,
: py : attr : ` DeviceType . null ` should be used .
@ todo setHardDiskBootOrder ( ) , setNetworkBootOrder ( )
in posi... | if not isinstance ( position , baseinteger ) :
raise TypeError ( "position can only be an instance of type baseinteger" )
if not isinstance ( device , DeviceType ) :
raise TypeError ( "device can only be an instance of type DeviceType" )
self . _call ( "setBootOrder" , in_p = [ position , device ] ) |
def matrix_from_edges ( edges ) :
'''Returns a sparse penalty matrix ( D ) from a list of edge pairs . Each edge
can have an optional weight associated with it .''' | max_col = 0
cols = [ ]
rows = [ ]
vals = [ ]
if type ( edges ) is defaultdict :
edge_list = [ ]
for i , neighbors in edges . items ( ) :
for j in neighbors :
if i <= j :
edge_list . append ( ( i , j ) )
edges = edge_list
for i , edge in enumerate ( edges ) :
s , t = e... |
def Scharr_edge ( im , blurRadius = 10 , imblur = None ) :
"""Extract the edges using Scharr kernel ( Sobel optimized for rotation
invariance )
Parameters :
im : 2d array
The image
blurRadius : number , default 10
The gaussian blur raduis ( The kernel has size 2 * blurRadius + 1)
imblur : 2d array , O... | im = np . asarray ( im , dtype = 'float32' )
blurRadius = 2 * blurRadius + 1
im = cv2 . GaussianBlur ( im , ( blurRadius , blurRadius ) , 0 )
Gx = cv2 . Scharr ( im , - 1 , 0 , 1 )
Gy = cv2 . Scharr ( im , - 1 , 1 , 0 )
ret = cv2 . magnitude ( Gx , Gy )
if imblur is not None and imblur . shape == im . shape :
imblu... |
def plot ( self , channel_names , kind = 'histogram' , gates = None , gate_colors = None , ids = None , row_labels = None , col_labels = None , xlim = 'auto' , ylim = 'auto' , autolabel = True , ** kwargs ) :
"""Produces a grid plot with each subplot corresponding to the data at the given position .
Parameters
... | # Note
# The function assumes that grid _ plot and FCMeasurement . plot use unique key words .
# Any key word arguments that appear in both functions are passed only to grid _ plot in the end .
# Automatically figure out which of the kwargs should
# be sent to grid _ plot instead of two sample . plot
# ( May not be a r... |
def create_points ( self , draw , point_chance , width , height ) :
'''绘制干扰点''' | chance = min ( 100 , max ( 0 , int ( point_chance ) ) )
# 大小限制在 [ 0 , 100]
for w in range ( width ) :
for h in range ( height ) :
tmp = randint ( 0 , 100 )
if tmp > 100 - chance :
draw . point ( ( w , h ) , fill = ( 0 , 0 , 0 ) ) |
def file_fingerprint ( fullpath ) :
"""Get a metadata fingerprint for a file""" | stat = os . stat ( fullpath )
return ',' . join ( [ str ( value ) for value in [ stat . st_ino , stat . st_mtime , stat . st_size ] if value ] ) |
def add_embedding_path ( self , x , dimensions , vectors_path , metadata = None , image_shape = None , image = None ) :
"""Adds a new embedding with optional metadata .
Example how to generate vectors based on 2D numpy array :
# 4 vectors , each size of 3
vectors = [
[2.3 , 4.0 , 33 ] ,
[2.4 , 4.2 , 44 ] ... | if not os . path . exists ( vectors_path ) :
raise Exception ( "Given embedding vectors file does not exist: " + vectors_path )
if metadata and not os . path . exists ( metadata ) :
raise Exception ( "Given embedding metadata file does not exist: " + metadata )
name = os . path . basename ( vectors_path )
self ... |
def GetStatusInformation ( self ) :
"""Retrieves status information about the tasks .
Returns :
TasksStatus : tasks status information .""" | status = processing_status . TasksStatus ( )
with self . _lock :
status . number_of_abandoned_tasks = len ( self . _tasks_abandoned )
status . number_of_queued_tasks = len ( self . _tasks_queued )
status . number_of_tasks_pending_merge = ( len ( self . _tasks_pending_merge ) + len ( self . _tasks_merging ) ... |
def get_store_local_final_result ( self ) :
"""Store / Retrieve the final result .
Retrieve the final result for FW create / delete from DB and store it
locally .""" | fw_dict = self . get_fw_dict ( )
fw_data , fw_data_dict = self . get_fw ( fw_dict . get ( 'fw_id' ) )
res = fw_data . result
self . store_local_final_result ( res ) |
def view_change_started ( self , viewNo : int ) :
"""Notifies primary decider about the fact that view changed to let it
prepare for election , which then will be started from outside by
calling decidePrimaries ( )""" | if viewNo <= self . viewNo :
logger . warning ( "{}Provided view no {} is not greater" " than the current view no {}" . format ( VIEW_CHANGE_PREFIX , viewNo , self . viewNo ) )
return False
self . previous_master_primary = self . node . master_primary_name
for replica in self . replicas . values ( ) :
repli... |
def get_eidos_scorer ( ) :
"""Return a SimpleScorer based on Eidos curated precision estimates .""" | table = load_eidos_curation_table ( )
# Get the overall precision
total_num = table [ 'COUNT of RULE' ] . sum ( )
weighted_sum = table [ 'COUNT of RULE' ] . dot ( table [ '% correct' ] )
precision = weighted_sum / total_num
# We have to divide this into a random and systematic component , for now
# in an ad - hoc manne... |
def append_executable ( self , executable ) :
"""Append san executable os command to the list to be called .
Argument :
executable ( str ) : os callable executable .""" | if isinstance ( executable , str ) and not isinstance ( executable , unicode ) :
executable = unicode ( executable )
if not isinstance ( executable , unicode ) :
raise TypeError ( "expected executable name as str, not {}" . format ( executable . __class__ . __name__ ) )
self . _executables . append ( executable... |
def temperature_effectiveness_TEMA_E ( R1 , NTU1 , Ntp = 1 , optimal = True ) :
r'''Returns temperature effectiveness ` P1 ` of a TEMA E type heat exchanger
with a specified heat capacity ratio , number of transfer units ` NTU1 ` ,
number of tube passes ` Ntp ` , and whether or not it is arranged in a more
co... | if Ntp == 1 : # Just the basic counterflow case
if R1 != 1 :
P1 = ( 1 - exp ( - NTU1 * ( 1 - R1 ) ) ) / ( 1 - R1 * exp ( - NTU1 * ( 1 - R1 ) ) )
else :
P1 = NTU1 / ( 1. + NTU1 )
elif Ntp == 2 and optimal :
if R1 != 1 :
E = ( 1. + R1 ** 2 ) ** 0.5
P1 = 2. / ( 1 + R1 + E / tanh... |
def optimize ( self ) :
"""Tries to detect peep - hole patterns in this basic block
and remove them .""" | changed = OPTIONS . optimization . value > 2
# only with - O3 will enter here
while changed :
changed = False
regs = Registers ( )
if len ( self ) and self [ - 1 ] . inst in ( 'jp' , 'jr' ) and self . original_next is LABELS [ self [ - 1 ] . opers [ 0 ] ] . basic_block : # { jp Label ; Label : ; . . . } = >... |
def load_identity_signer ( key_dir , key_name ) :
"""Loads a private key from the key directory , based on a validator ' s
identity .
Args :
key _ dir ( str ) : The path to the key directory .
key _ name ( str ) : The name of the key to load .
Returns :
Signer : the cryptographic signer for the key""" | key_path = os . path . join ( key_dir , '{}.priv' . format ( key_name ) )
if not os . path . exists ( key_path ) :
raise LocalConfigurationError ( "No such signing key file: {}" . format ( key_path ) )
if not os . access ( key_path , os . R_OK ) :
raise LocalConfigurationError ( "Key file is not readable: {}" .... |
def _generic_placeobject_parser ( self , obj , version ) :
"""A generic parser for several PlaceObjectX .""" | bc = BitConsumer ( self . _src )
obj . PlaceFlagHasClipActions = bc . u_get ( 1 )
obj . PlaceFlagHasClipDepth = bc . u_get ( 1 )
obj . PlaceFlagHasName = bc . u_get ( 1 )
obj . PlaceFlagHasRatio = bc . u_get ( 1 )
obj . PlaceFlagHasColorTransform = bc . u_get ( 1 )
obj . PlaceFlagHasMatrix = bc . u_get ( 1 )
obj . Plac... |
def initial_populate ( self , data ) :
"""Populate a newly created config object with data .
If it was populated , this returns True . If it wasn ' t , this returns False .
It is recommended to run a . dump ( ) and . reload ( ) after running this .""" | if self . config . parsed :
return False
# Otherwise , create a new ConfigKey .
self . config . load_from_dict ( data )
return True |
def check_download ( obj , * args , ** kwargs ) :
"""Verify a download""" | version = args [ 0 ]
workdir = args [ 1 ]
signame = args [ 2 ]
if version :
local_version = get_local_version ( workdir , signame )
if not verify_sigfile ( workdir , signame ) or version != local_version :
error ( "[-] \033[91mFailed to verify signature: %s from: %s\033[0m" % ( signame , obj . url ) )
... |
def get_efs_dict ( ) :
"""Returns dictionary of { efs _ name : efs _ id }""" | # there ' s no EC2 resource for EFS objects , so return EFS _ ID instead
# https : / / stackoverflow . com / questions / 47870342 / no - ec2 - resource - for - efs - objects
efs_client = get_efs_client ( )
response = call_with_retries ( efs_client . describe_file_systems , 'efs_client.describe_file_systems' )
assert is... |
def read_time_h5 ( h5folder ) :
"""Iterate through ( isnap , istep ) recorded in h5folder / ' time _ botT . h5 ' .
Args :
h5folder ( : class : ` pathlib . Path ` ) : directory of HDF5 output files .
Yields :
tuple of int : ( isnap , istep ) .""" | with h5py . File ( h5folder / 'time_botT.h5' , 'r' ) as h5f :
for name , dset in h5f . items ( ) :
yield int ( name [ - 5 : ] ) , int ( dset [ 2 ] ) |
def convert_to_push ( ir , node ) :
"""Convert a call to a PUSH operaiton
The funciton assume to receive a correct IR
The checks must be done by the caller
May necessitate to create an intermediate operation ( InitArray )
Necessitate to return the lenght ( see push documentation )
As a result , the functi... | lvalue = ir . lvalue
if isinstance ( ir . arguments [ 0 ] , list ) :
ret = [ ]
val = TemporaryVariable ( node )
operation = InitArray ( ir . arguments [ 0 ] , val )
ret . append ( operation )
ir = Push ( ir . destination , val )
length = Literal ( len ( operation . init_values ) )
t = operat... |
def key_exists ( self , namespace , key ) :
"""Checks a namespace for the existence of a specific key
Args :
namespace ( str ) : Namespace to check in
key ( str ) : Name of the key to check for
Returns :
` True ` if key exists in the namespace , else ` False `""" | return namespace in self . __data and key in self . __data [ namespace ] |
def profile_device_delete ( name , device_name , remote_addr = None , cert = None , key = None , verify_cert = True ) :
'''Delete a profile device .
name :
The name of the profile to delete the device .
device _ name :
The name of the device to delete .
remote _ addr :
An URL to a remote Server , you al... | profile = profile_get ( name , remote_addr , cert , key , verify_cert , _raw = True )
return _delete_property_dict_item ( profile , 'devices' , device_name ) |
def emoticons_tag ( parser , token ) :
"""Tag for rendering emoticons .""" | exclude = ''
args = token . split_contents ( )
if len ( args ) == 2 :
exclude = args [ 1 ]
elif len ( args ) > 2 :
raise template . TemplateSyntaxError ( 'emoticons tag has only one optional argument' )
nodelist = parser . parse ( [ 'endemoticons' ] )
parser . delete_first_token ( )
return EmoticonNode ( nodeli... |
def session_to_epoch ( timestamp ) :
"""converts Synergy Timestamp for session to UTC zone seconds since epoch""" | utc_timetuple = datetime . strptime ( timestamp , SYNERGY_SESSION_PATTERN ) . replace ( tzinfo = None ) . utctimetuple ( )
return calendar . timegm ( utc_timetuple ) |
def fmtradec ( rarad , decrad , precision = 2 , raseps = '::' , decseps = '::' , intersep = ' ' ) :
"""Format equatorial coordinates in a single sexagesimal string .
Returns a string of the RA / lon coordinate , formatted as sexagesimal hours ,
then * intersep * , then the Dec / lat coordinate , formatted as de... | return ( fmthours ( rarad , precision = precision + 1 , seps = raseps ) + text_type ( intersep ) + fmtdeglat ( decrad , precision = precision , seps = decseps ) ) |
def _parse_sid_iter ( data ) :
"""Parses the given : class : ` bytes ` data as a list of : class : ` SymbolToken `""" | limit = len ( data )
buf = BytesIO ( data )
while buf . tell ( ) < limit :
sid = _parse_var_int ( buf , signed = False )
yield SymbolToken ( None , sid ) |
def add_middleware ( self , middleware ) :
"""Adds a middleware object used to process all incoming requests against the API""" | if self . middleware is None :
self . _middleware = [ ]
self . middleware . append ( middleware ) |
def image_predict ( self , X ) :
"""Predicts class label for the entire image .
Parameters :
X : array , shape = [ n _ samples , n _ pixels _ y , n _ pixels _ x , n _ bands ]
Array of training images
y : array , shape = [ n _ samples ] or [ n _ samples , n _ pixels _ y , n _ pixels _ x ]
Target labels or ... | self . _check_image ( X )
if self . mode == 'majority_class' :
predictions = self . pixel_classifier . image_predict ( X )
elif self . mode == 'mean_prob' :
probabilities = self . image_predict_proba ( X )
predictions = ( probabilities [ ... , self . target ] > self . target_threshold ) . astype ( np . int ... |
def get_fun ( fun ) :
'''Return the most recent jobs that have executed the named function''' | conn , mdb = _get_conn ( ret = None )
ret = { }
rdata = mdb . saltReturns . find_one ( { 'fun' : fun } , { '_id' : 0 } )
if rdata :
ret = rdata
return ret |
def classes_can_admin ( self ) :
"""Return all the classes ( sorted ) that this user can admin .""" | if self . is_admin :
return sorted ( Session . query ( Class ) . all ( ) )
else :
return sorted ( self . admin_for ) |
def load ( self ) :
"""Load all available DRPs in ' entry _ point ' .""" | for drpins in self . iload ( self . entry ) :
self . drps [ drpins . name ] = drpins
return self |
def scoreatpercentile ( inlist , percent ) :
"""Returns the score at a given percentile relative to the distribution
given by inlist .
Usage : lscoreatpercentile ( inlist , percent )""" | if percent > 1 :
print ( "\nDividing percent>1 by 100 in lscoreatpercentile().\n" )
percent = percent / 100.0
targetcf = percent * len ( inlist )
h , lrl , binsize , extras = histogram ( inlist )
cumhist = cumsum ( copy . deepcopy ( h ) )
for i in range ( len ( cumhist ) ) :
if cumhist [ i ] >= targetcf :
... |
def get_max_sinkhole ( self , length ) :
"""Find a sinkhole which is large enough to support ` length ` bytes .
This uses first - fit . The first sinkhole ( ordered in descending order by their address )
which can hold ` length ` bytes is chosen . If there are more than ` length ` bytes in the
sinkhole , a ne... | ordered_sinks = sorted ( list ( self . sinkholes ) , key = operator . itemgetter ( 0 ) , reverse = True )
max_pair = None
for addr , sz in ordered_sinks :
if sz >= length :
max_pair = ( addr , sz )
break
if max_pair is None :
return None
remaining = max_pair [ 1 ] - length
max_addr = max_pair [ ... |
def assign_yourself ( self ) :
"""Assigning the workflow to itself .
The selected job is checked to see if there is an assigned role .
If it does not have a role assigned to it , it takes the job to itself
and displays a message that the process is successful .
If there is a role assigned to it , it does no... | task_invitation = TaskInvitation . objects . get ( self . task_invitation_key )
wfi = task_invitation . instance
if not wfi . current_actor . exist :
wfi . current_actor = self . current . role
wfi . save ( )
[ inv . delete ( ) for inv in TaskInvitation . objects . filter ( instance = wfi ) if not inv == ta... |
def get_placement_group_dict ( ) :
"""Returns dictionary of { placement _ group _ name : ( state , strategy ) }""" | client = get_ec2_client ( )
response = client . describe_placement_groups ( )
assert is_good_response ( response )
result = OrderedDict ( )
ec2 = get_ec2_resource ( )
for placement_group_response in response [ 'PlacementGroups' ] :
key = placement_group_response [ 'GroupName' ]
if key in result :
util .... |
def export_data ( self , directory , filename , with_md5_hash = False ) :
"""Save model data in a JSON file .
Parameters
: param directory : string
The directory .
: param filename : string
The filename .
: param with _ md5 _ hash : bool
Whether to append the checksum to the filename or not .""" | model_data = [ ]
for est in self . estimators :
model_data . append ( { 'childrenLeft' : est . tree_ . children_left . tolist ( ) , 'childrenRight' : est . tree_ . children_right . tolist ( ) , 'thresholds' : est . tree_ . threshold . tolist ( ) , 'classes' : [ e [ 0 ] for e in est . tree_ . value . tolist ( ) ] , ... |
def verify ( zone ) :
'''Check to make sure the configuration of the specified
zone can safely be installed on the machine .
zone : string
name of the zone
CLI Example :
. . code - block : : bash
salt ' * ' zoneadm . verify dolores''' | ret = { 'status' : True }
# # verify zone
res = __salt__ [ 'cmd.run_all' ] ( 'zoneadm -z {zone} verify' . format ( zone = zone , ) )
ret [ 'status' ] = res [ 'retcode' ] == 0
ret [ 'message' ] = res [ 'stdout' ] if ret [ 'status' ] else res [ 'stderr' ]
ret [ 'message' ] = ret [ 'message' ] . replace ( 'zoneadm: ' , ''... |
def post ( self , url , postParameters = None , urlParameters = None ) :
"""Convenience method for requesting to google with proper cookies / params .""" | if self . authorized_client :
if urlParameters :
getString = self . getParameters ( urlParameters )
req = urllib2 . Request ( url + "?" + getString )
else :
req = urllib2 . Request ( url )
postString = self . postParameters ( postParameters )
resp , content = self . authorized_cl... |
def load_cells ( self , datum = None ) :
"""Load the row ' s data and initialize all the cells in the row .
It also set the appropriate row properties which require
the row ' s data to be determined .
The row ' s data is provided either at initialization or as an
argument to this function .
This function ... | # Compile all the cells on instantiation .
table = self . table
if datum :
self . datum = datum
else :
datum = self . datum
cells = [ ]
for column in table . columns . values ( ) :
cell = table . _meta . cell_class ( datum , column , self )
cells . append ( ( column . name or column . auto , cell ) )
se... |
def word_tokenize ( self , text : str ) -> List [ str ] :
""": param str text : text to be tokenized
: return : list of words , tokenized from the text""" | return word_tokenize ( text , custom_dict = self . __trie_dict , engine = self . __engine ) |
def poissonVectorRDD ( sc , mean , numRows , numCols , numPartitions = None , seed = None ) :
"""Generates an RDD comprised of vectors containing i . i . d . samples drawn
from the Poisson distribution with the input mean .
: param sc : SparkContext used to create the RDD .
: param mean : Mean , or lambda , f... | return callMLlibFunc ( "poissonVectorRDD" , sc . _jsc , float ( mean ) , numRows , numCols , numPartitions , seed ) |
def superimposition_matrix ( v0 , v1 , scale = False , usesvd = True ) :
"""Return matrix to transform given 3D point set into second point set .
v0 and v1 are shape ( 3 , \ * ) or ( 4 , \ * ) arrays of at least 3 points .
The parameters scale and usesvd are explained in the more general
affine _ matrix _ fro... | v0 = numpy . array ( v0 , dtype = numpy . float64 , copy = False ) [ : 3 ]
v1 = numpy . array ( v1 , dtype = numpy . float64 , copy = False ) [ : 3 ]
return affine_matrix_from_points ( v0 , v1 , shear = False , scale = scale , usesvd = usesvd ) |
def _load ( cls , path ) :
""": type path : str""" | bytesIO = BytesIO ( )
initfile = os . path . join ( path , '__init__.py' )
if os . path . isfile ( initfile ) : # This is a package directory . To emulate
# PyZipFile . writepy ' s behavior , we need to keep everything
# relative to this path ' s parent directory .
rootDir = os . path . dirname ( path )
else : # Th... |
def search ( cls , five9 , filters ) :
"""Search for a record on the remote and return the results .
Args :
five9 ( five9 . Five9 ) : The authenticated Five9 remote .
filters ( dict ) : A dictionary of search parameters , keyed by the
name of the field to search . This should conform to the
schema defined... | return cls . _name_search ( five9 . configuration . getWebConnectors , filters ) |
def setnx ( self , key , value ) :
"""Set the value of a key , only if the key does not exist .""" | fut = self . execute ( b'SETNX' , key , value )
return wait_convert ( fut , bool ) |
def inspect ( self , ** kwargs ) :
"""Plot the evolution of the structural relaxation with matplotlib .
Args :
what : Either " hist " or " scf " . The first option ( default ) extracts data
from the HIST file and plot the evolution of the structural
parameters , forces , pressures and energies .
The secon... | what = kwargs . pop ( "what" , "hist" )
if what == "hist" : # Read the hist file to get access to the structure .
with self . open_hist ( ) as hist :
return hist . plot ( ** kwargs ) if hist else None
elif what == "scf" : # Get info on the different SCF cycles
relaxation = abiinspect . Relaxation . from... |
def ceilpow2 ( n ) :
"""convenience function to determine a power - of - 2 upper frequency limit""" | signif , exponent = frexp ( n )
if ( signif < 0 ) :
return 1 ;
if ( signif == 0.5 ) :
exponent -= 1 ;
return ( 1 ) << exponent ; |
def mask_between_time ( dts , start , end , include_start = True , include_end = True ) :
"""Return a mask of all of the datetimes in ` ` dts ` ` that are between
` ` start ` ` and ` ` end ` ` .
Parameters
dts : pd . DatetimeIndex
The index to mask .
start : time
Mask away times less than the start .
... | # This function is adapted from
# ` pandas . Datetime . Index . indexer _ between _ time ` which was originally
# written by Wes McKinney , Chang She , and Grant Roch .
time_micros = dts . _get_time_micros ( )
start_micros = _time_to_micros ( start )
end_micros = _time_to_micros ( end )
left_op , right_op , join_op = _... |
def select_date ( self , rows : List [ Row ] , column : DateColumn ) -> Date :
"""Select function takes a row as a list and a column name and returns the date in that column .""" | dates : List [ Date ] = [ ]
for row in rows :
cell_value = row . values [ column . name ]
if isinstance ( cell_value , Date ) :
dates . append ( cell_value )
return dates [ 0 ] if dates else Date ( - 1 , - 1 , - 1 ) |
def get_assignments ( self , site ) :
"""Gets a list of assignments associated with a site ( class ) . Returns
a list of TSquareAssignment objects .
@ param site ( TSquareSite ) - The site to use with the assignment query
@ returns - A list of TSquareSite objects . May be an empty list if
the site has defin... | tools = self . get_tools ( site )
assignment_tool_filter = [ x . href for x in tools if x . name == 'assignment-grades' ]
if not assignment_tool_filter :
return [ ]
assignment_tool_url = assignment_tool_filter [ 0 ] . href
response = self . _session . get ( assignment_tool_url )
response . raise_for_status ( )
ifra... |
def argsort ( self , * args , ** kwargs ) :
"""Returns the indices that would sort the index and its
underlying data .
Returns
argsorted : numpy array
See Also
numpy . ndarray . argsort""" | nv . validate_argsort ( args , kwargs )
if self . _step > 0 :
return np . arange ( len ( self ) )
else :
return np . arange ( len ( self ) - 1 , - 1 , - 1 ) |
def _parse_names_set ( feature_names ) :
"""Helping function of ` _ parse _ feature _ names ` that parses a set of feature names .""" | feature_collection = OrderedDict ( )
for feature_name in feature_names :
if isinstance ( feature_name , str ) :
feature_collection [ feature_name ] = ...
else :
raise ValueError ( 'Failed to parse {}, expected string' . format ( feature_name ) )
return feature_collection |
def feed_backend ( url , clean , fetch_archive , backend_name , backend_params , es_index = None , es_index_enrich = None , project = None , arthur = False , es_aliases = None , projects_json_repo = None ) :
"""Feed Ocean with backend data""" | backend = None
repo = { 'backend_name' : backend_name , 'backend_params' : backend_params }
# repository data to be stored in conf
if es_index :
clean = False
# don ' t remove index , it could be shared
if not get_connector_from_name ( backend_name ) :
raise RuntimeError ( "Unknown backend %s" % backend_name )
... |
def scroll_to_bottom ( self ) :
"""Scoll to the very bottom of the page
TODO : add increment & delay options to scoll slowly down the whole page to let each section load in""" | if self . driver . selenium is not None :
try :
self . driver . selenium . execute_script ( "window.scrollTo(0, document.body.scrollHeight);" )
except WebDriverException :
self . driver . selenium . execute_script ( "window.scrollTo(0, 50000);" )
except Exception :
logger . exception... |
def mfpts ( msm , sinks = None , lag_time = 1. , errors = False , n_samples = 100 ) :
"""Gets the Mean First Passage Time ( MFPT ) for all states to a * set *
of sinks .
Parameters
msm : msmbuilder . MarkovStateModel
MSM fit to the data .
sinks : array _ like , int , optional
Indices of the sink states ... | if hasattr ( msm , 'all_transmats_' ) :
if errors :
output = [ ]
for i in range ( n_samples ) :
mfpts = np . zeros_like ( msm . all_transmats_ )
for i , el in enumerate ( zip ( msm . all_transmats_ , msm . all_countsmats_ ) ) :
loc , scale = create_perturb_par... |
def create ( self , ** attributes ) :
"""Create a collection of models and persist them to the database .
: param attributes : The models attributes
: type attributes : dict
: return : mixed""" | results = self . make ( ** attributes )
if self . _amount == 1 :
if self . _resolver :
results . set_connection_resolver ( self . _resolver )
results . save ( )
else :
if self . _resolver :
results . each ( lambda r : r . set_connection_resolver ( self . _resolver ) )
for result in resul... |
def _Vapor_Density ( cls , T ) :
"""Auxiliary equation for the density of saturated vapor
Parameters
T : float
Temperature , [ K ]
Returns
rho : float
Saturated vapor density , [ kg / m3]
References
IAPWS , Revised Supplementary Release on Saturation Properties of
Ordinary Water Substance Septembe... | eq = cls . _rhoG [ "eq" ]
Tita = 1 - T / cls . Tc
if eq == 4 :
Tita = Tita ** ( 1. / 3 )
suma = 0
for n , x in zip ( cls . _rhoG [ "ao" ] , cls . _rhoG [ "exp" ] ) :
suma += n * Tita ** x
Pr = exp ( suma )
rho = Pr * cls . rhoc
return rho |
def _concat_datetime ( to_concat , axis = 0 , typs = None ) :
"""provide concatenation of an datetimelike array of arrays each of which is a
single M8 [ ns ] , datetimet64 [ ns , tz ] or m8 [ ns ] dtype
Parameters
to _ concat : array of arrays
axis : axis to provide concatenation
typs : set of to _ concat... | if typs is None :
typs = get_dtype_kinds ( to_concat )
# multiple types , need to coerce to object
if len ( typs ) != 1 :
return _concatenate_2d ( [ _convert_datetimelike_to_object ( x ) for x in to_concat ] , axis = axis )
# must be single dtype
if any ( typ . startswith ( 'datetime' ) for typ in typs ) :
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.