signature stringlengths 29 44.1k | implementation stringlengths 0 85.2k |
|---|---|
def _perform_binds ( self , binds ) :
"""Binds queues to exchanges .
Parameters
binds : list of dicts
a list of dicts with the following keys :
queue : string - name of the queue to bind
exchange : string - name of the exchange to bind
routing _ key : string - routing key to use for this bind""" | for bind in binds :
self . logger . debug ( "Binding queue {0} to exchange {1} with key {2}" . format ( bind [ 'queue' ] , bind [ 'exchange' ] , bind [ 'routing_key' ] ) )
self . channel . queue_bind ( ** bind ) |
def commandline_to_list ( self , cmdline_str , trigger_string ) :
'''cmdline _ str is the string of the command line
trigger _ string is the trigger string , to be removed''' | cmdline = salt . utils . args . shlex_split ( cmdline_str [ len ( trigger_string ) : ] )
# Remove slack url parsing
# Translate target = < http : / / host . domain . net | host . domain . net >
# to target = host . domain . net
cmdlist = [ ]
for cmditem in cmdline :
pattern = r'(?P<begin>.*)(<.*\|)(?P<url>.*)(>)(?P... |
def parse ( self , value ) :
"""Parse date""" | value = super ( DateOpt , self ) . parse ( value )
if value is None :
return None
if isinstance ( value , str ) :
value = self . parse_date ( value )
if isinstance ( value , datetime ) and self . date_only :
value = value . date ( )
return value |
def switch_service ( self , new_service = None ) :
"""Start a new service in a subprocess .
: param new _ service : Either a service name or a service class . If not set ,
start up a new instance of the previous class
: return : True on success , False on failure .""" | if new_service :
self . _service_factory = new_service
with self . __lock : # Terminate existing service if necessary
if self . _service is not None :
self . _terminate_service ( )
# Find service class if necessary
if isinstance ( self . _service_factory , basestring ) :
self . _service_... |
def create_dockwidget ( self ) :
"""Add to parent QMainWindow as a dock widget""" | # Creating dock widget
dock = SpyderDockWidget ( self . get_plugin_title ( ) , self . main )
# Set properties
dock . setObjectName ( self . __class__ . __name__ + "_dw" )
dock . setAllowedAreas ( self . ALLOWED_AREAS )
dock . setFeatures ( self . FEATURES )
dock . setWidget ( self )
self . update_margins ( )
dock . vis... |
def make_jobs ( ) :
"""creates a list of Job objects ,
which carry all information needed
for a function to be executed on SGE :
- function object
- arguments
- settings""" | # set up list of arguments
inputvec = [ [ 3 ] , [ 5 ] , [ 10 ] , [ 20 ] ]
# create empty job vector
jobs = [ ]
# create job objects
for arg in inputvec : # The default queue used by the Job class is all . q . You must specify
# the ` queue ` keyword argument if that is not the name of your queue .
job = Job ( compu... |
def get ( self , request , bot_id , handler_id , id , format = None ) :
"""Get url parameter by id
serializer : AbsParamSerializer
responseMessages :
- code : 401
message : Not authenticated""" | return super ( UrlParameterDetail , self ) . get ( request , bot_id , handler_id , id , format ) |
def dropNodesByCount ( grph , minCount = - float ( 'inf' ) , maxCount = float ( 'inf' ) , parameterName = 'count' , ignoreMissing = False ) :
"""Modifies _ grph _ by dropping nodes that do not have a count that is within inclusive bounds of _ minCount _ and _ maxCount _ , i . e after running _ grph _ will only have... | count = 0
total = len ( grph . nodes ( ) )
if metaknowledge . VERBOSE_MODE :
progArgs = ( 0 , "Dropping nodes by count" )
progKwargs = { }
else :
progArgs = ( 0 , "Dropping nodes by count" )
progKwargs = { 'dummy' : True }
with _ProgressBar ( * progArgs , ** progKwargs ) as PBar :
badNodes = [ ]
... |
def fail ( self ) :
"""Fail a vector .""" | if self . failed is True :
raise AttributeError ( "Cannot fail {} - it has already failed." . format ( self ) )
else :
self . failed = True
self . time_of_death = timenow ( )
for t in self . transmissions ( ) :
t . fail ( ) |
def send_and_match_output ( self , send , matches , retry = 3 , strip = True , note = None , echo = False , loglevel = logging . DEBUG ) :
"""Returns true if the output of the command matches any of the strings in
the matches list of regexp strings . Handles matching on a per - line basis
and does not cross lin... | shutit = self . shutit
shutit . handle_note ( note )
shutit . log ( 'Matching output from: "' + send + '" to one of these regexps:' + str ( matches ) , level = logging . INFO )
echo = shutit . get_echo_override ( echo )
output = self . send_and_get_output ( send , retry = retry , strip = strip , echo = echo , loglevel ... |
def fingerprint_from_keybase ( fingerprint , kb_obj ) :
"""Extracts a key matching a specific fingerprint from a
Keybase API response""" | if 'public_keys' in kb_obj and 'pgp_public_keys' in kb_obj [ 'public_keys' ] :
for key in kb_obj [ 'public_keys' ] [ 'pgp_public_keys' ] :
keyprint = fingerprint_from_var ( key ) . lower ( )
fingerprint = fingerprint . lower ( )
if fingerprint == keyprint or keyprint . startswith ( fingerpri... |
def pgrrec ( body , lon , lat , alt , re , f ) :
"""Convert planetographic coordinates to rectangular coordinates .
http : / / naif . jpl . nasa . gov / pub / naif / toolkit _ docs / C / cspice / pgrrec _ c . html
: param body : Body with which coordinate system is associated .
: type body : str
: param lon... | body = stypes . stringToCharP ( body )
lon = ctypes . c_double ( lon )
lat = ctypes . c_double ( lat )
alt = ctypes . c_double ( alt )
re = ctypes . c_double ( re )
f = ctypes . c_double ( f )
rectan = stypes . emptyDoubleVector ( 3 )
libspice . pgrrec_c ( body , lon , lat , alt , re , f , rectan )
return stypes . cVec... |
def is_isolated_list_abundance ( graph : BELGraph , node : BaseEntity , cls : Type [ ListAbundance ] = ListAbundance ) -> bool :
"""Return if the node is a list abundance but has no qualified edges .""" | return ( isinstance ( node , cls ) and 0 == graph . in_degree ( node ) and all ( data [ RELATION ] == HAS_COMPONENT for _ , __ , data in graph . out_edges ( node , data = True ) ) ) |
def quit ( self ) :
"""Quit socket server""" | logging . info ( "quiting sock server" )
if self . __quit is not None :
self . __quit . set ( )
self . join ( )
return |
def d_deta_from_phalf ( arr , pfull_coord ) :
"""Compute pressure level thickness from half level pressures .""" | d_deta = arr . diff ( dim = internal_names . PHALF_STR , n = 1 )
return replace_coord ( d_deta , internal_names . PHALF_STR , internal_names . PFULL_STR , pfull_coord ) |
def get_index ( binstr , end_index = 160 ) :
"""Return the position of the first 1 bit
from the left in the word until end _ index
: param binstr :
: param end _ index :
: return :""" | res = - 1
try :
res = binstr . index ( '1' ) + 1
except ValueError :
res = end_index
return res |
def copyWorkitem ( self , copied_from , title = None , description = None , prefix = None ) :
"""Create a workitem by copying from an existing one
: param copied _ from : the to - be - copied workitem id
: param title : the new workitem title / summary .
If ` None ` , will copy that from a to - be - copied wo... | copied_wi = self . getWorkitem ( copied_from )
if title is None :
title = copied_wi . title
if prefix is not None :
title = prefix + title
if description is None :
description = copied_wi . description
if prefix is not None :
description = prefix + description
self . log . info ( "Start ... |
def basic_auth_string ( username , password ) :
"""Encode a username and password for use in an HTTP Basic Authentication
header""" | b64 = base64 . encodestring ( '%s:%s' % ( username , password ) ) . strip ( )
return 'Basic %s' % b64 |
def main ( ) :
"""Install entry - point""" | from os import path as op
from inspect import getfile , currentframe
from setuptools import setup , find_packages
from niworkflows . __about__ import ( __packagename__ , __author__ , __email__ , __maintainer__ , __license__ , __description__ , __longdesc__ , __url__ , DOWNLOAD_URL , CLASSIFIERS , REQUIRES , SETUP_REQUI... |
def copy_file ( host , file_path , remote_path = '.' , username = None , key_path = None , action = 'put' ) :
"""Copy a file via SCP , proxied through the mesos master
: param host : host or IP of the machine to execute the command on
: type host : str
: param file _ path : the local path to the file to be co... | if not username :
username = shakedown . cli . ssh_user
if not key_path :
key_path = shakedown . cli . ssh_key_file
key = validate_key ( key_path )
transport = get_transport ( host , username , key )
transport = start_transport ( transport , username , key )
if transport . is_authenticated ( ) :
start = tim... |
def data ( self , value ) :
"""Saves a new image to disk""" | self . loader . save_image ( self . category , self . image , value ) |
def human_or_01 ( X , y , model_generator , method_name ) :
"""OR ( false / true )
This tests how well a feature attribution method agrees with human intuition
for an OR operation combined with linear effects . This metric deals
specifically with the question of credit allocation for the following function
... | return _human_or ( X , model_generator , method_name , False , True ) |
def filter ( args ) :
"""% prog filter < deltafile | coordsfile >
Produce a new delta / coords file and filter based on id % or cov % .
Use ` delta - filter ` for . delta file .""" | p = OptionParser ( filter . __doc__ )
p . set_align ( pctid = 0 , hitlen = 0 )
p . add_option ( "--overlap" , default = False , action = "store_true" , help = "Print overlap status (e.g. terminal, contained)" )
opts , args = p . parse_args ( args )
if len ( args ) != 1 :
sys . exit ( not p . print_help ( ) )
pctid ... |
def gap_to_sorl ( time_gap ) :
"""P1D to + 1DAY
: param time _ gap :
: return : solr ' s format duration .""" | quantity , unit = parse_ISO8601 ( time_gap )
if unit [ 0 ] == "WEEKS" :
return "+{0}DAYS" . format ( quantity * 7 )
else :
return "+{0}{1}" . format ( quantity , unit [ 0 ] ) |
def right_click_specimen_equalarea ( self , event ) :
"""toggles between zoom and pan effects for the specimen equal area on
right click
Parameters
event : the wx . MouseEvent that triggered the call of this function
Alters
specimen _ EA _ setting , toolbar2 setting""" | if event . LeftIsDown ( ) or event . ButtonDClick ( ) :
return
elif self . specimen_EA_setting == "Zoom" :
self . specimen_EA_setting = "Pan"
try :
self . toolbar2 . pan ( 'off' )
except TypeError :
pass
elif self . specimen_EA_setting == "Pan" :
self . specimen_EA_setting = "Zoom"
... |
def equal_to_be ( self , be_record ) : # type : ( PathTableRecord ) - > bool
'''A method to compare a little - endian path table record to its
big - endian counterpart . This is used to ensure that the ISO is sane .
Parameters :
be _ record - The big - endian object to compare with the little - endian
objec... | if not self . _initialized :
raise pycdlibexception . PyCdlibInternalError ( 'This Path Table Record is not yet initialized' )
if be_record . len_di != self . len_di or be_record . xattr_length != self . xattr_length or utils . swab_32bit ( be_record . extent_location ) != self . extent_location or utils . swab_16b... |
def get_items ( self , jid , node , * , max_items = None ) :
"""Request the most recent items from a node .
: param jid : Address of the PubSub service .
: type jid : : class : ` aioxmpp . JID `
: param node : Name of the PubSub node to query .
: type node : : class : ` str `
: param max _ items : Number ... | iq = aioxmpp . stanza . IQ ( to = jid , type_ = aioxmpp . structs . IQType . GET )
iq . payload = pubsub_xso . Request ( pubsub_xso . Items ( node , max_items = max_items ) )
return ( yield from self . client . send ( iq ) ) |
def process_data ( self , ** kwargs ) :
"""get the data from the cache
: param kwargs : contain keyword args : trigger _ id at least
: type kwargs : dict""" | cache = caches [ 'django_th' ]
cache_data = cache . get ( kwargs . get ( 'cache_stack' ) + '_' + kwargs . get ( 'trigger_id' ) )
return PublishingLimit . get_data ( kwargs . get ( 'cache_stack' ) , cache_data , int ( kwargs . get ( 'trigger_id' ) ) ) |
def check_user_can_vote ( cmt_id , client_ip_address , uid = - 1 ) :
"""Checks if a user hasn ' t already voted
: param cmt _ id : comment id
: param client _ ip _ address : IP = > use : str ( req . remote _ ip )
: param uid : user id , as given by invenio . legacy . webuser . getUid ( req )""" | cmt_id = wash_url_argument ( cmt_id , 'int' )
client_ip_address = wash_url_argument ( client_ip_address , 'str' )
uid = wash_url_argument ( uid , 'int' )
query = """SELECT "id_cmtRECORDCOMMENT"
FROM "cmtACTIONHISTORY"
WHERE "id_cmtRECORDCOMMENT"=%s"""
params = ( cmt_id , )
if uid < 0 :
... |
def _create_badges ( self ) :
"""Creates badges .""" | rn = RandomNicknames ( )
for name in rn . random_nicks ( count = 20 ) :
slug = slugify ( name )
badge = Badge . objects . create ( name = name , slug = slug , description = 'Lorem ipsum dolor sit amet, consectetur adipisicing elit' )
logger . info ( 'Created badge: %s' , badge . name ) |
def crud_fields ( obj , fields = None ) :
"""Display object fields in table rows : :
< table >
{ % crud _ fields object ' id , % }
< / table >
* ` ` fields ` ` fields to include
If fields is ` ` None ` ` all fields will be displayed .
If fields is ` ` string ` ` comma separated field names will be
dis... | if fields is None :
fields = utils . get_fields ( type ( obj ) )
elif isinstance ( fields , six . string_types ) :
field_names = [ f . strip ( ) for f in fields . split ( ',' ) ]
fields = utils . get_fields ( type ( obj ) , include = field_names )
return { 'object' : obj , 'fields' : fields , } |
def find_transitionid_by_name ( self , issue , transition_name ) :
"""Get a transitionid available on the specified issue to the current user .
Look at https : / / developer . atlassian . com / static / rest / jira / 6.1 . html # d2e1074 for json reference
: param issue : ID or key of the issue to get the trans... | transitions_json = self . transitions ( issue )
id = None
for transition in transitions_json :
if transition [ "name" ] . lower ( ) == transition_name . lower ( ) :
id = transition [ "id" ]
break
return id |
def cielab_to_xyz ( cielab , refwhite ) :
"""Convert CIE L * a * b * color values to CIE XYZ ,
* cielab * should be of shape ( * , 3 ) . * refwhite * is the reference white
value in the L * a * b * color space , of shape ( 3 , ) .
Return value has same shape as * cielab *""" | def func ( t ) :
pow = t ** 3
scale = 0.128419 * t - 0.0177129
return np . where ( t > 0.206897 , pow , scale )
xyz = np . empty_like ( cielab )
lscale = 1. / 116 * ( cielab [ ... , L ] + 16 )
xyz [ ... , X ] = func ( lscale + 0.002 * cielab [ ... , A ] )
xyz [ ... , Y ] = func ( lscale )
xyz [ ... , Z ] = ... |
def remove_badge ( self , kind ) :
'''Perform an atomic removal for a given badge''' | self . update ( __raw__ = { '$pull' : { 'badges' : { 'kind' : kind } } } )
self . reload ( )
on_badge_removed . send ( self , kind = kind )
post_save . send ( self . __class__ , document = self ) |
def stratify ( self ) :
"""Stratifies the sample based on propensity score .
By default the sample is divided into five equal - sized bins .
The number of bins can be set by modifying the object
attribute named blocks . Alternatively , custom - sized bins can
be created by setting blocks equal to a sorted l... | Y , D , X = self . raw_data [ 'Y' ] , self . raw_data [ 'D' ] , self . raw_data [ 'X' ]
pscore = self . raw_data [ 'pscore' ]
if isinstance ( self . blocks , int ) :
blocks = split_equal_bins ( pscore , self . blocks )
else :
blocks = self . blocks [ : ]
# make a copy ; should be sorted
blocks [ 0 ] = 0... |
def get_fisher_scores_vs_background ( self ) :
'''Returns
pd . DataFrame of fisher scores vs background''' | df = self . get_term_and_background_counts ( )
odds_ratio , p_values = self . _get_fisher_scores_from_counts ( df [ 'corpus' ] , df [ 'background' ] )
df [ 'Odds ratio' ] = odds_ratio
df [ 'Bonferroni-corrected p-values' ] = p_values * len ( df )
df . sort_values ( by = [ 'Bonferroni-corrected p-values' , 'Odds ratio' ... |
def from_json_dict ( dct , validate = True ) : # type : ( Dict [ str , Any ] , bool ) - > Schema
"""Create a Schema for v1 or v2 according to dct
: param dct : This dictionary must have a ` ' features ' `
key specifying the columns of the dataset . It must have
a ` ' version ' ` key containing the master sche... | if validate : # This raises iff the schema is invalid .
validate_schema_dict ( dct )
version = dct [ 'version' ]
if version == 1 :
dct = convert_v1_to_v2 ( dct )
if validate :
validate_schema_dict ( dct )
elif version != 2 :
msg = ( 'Schema version {} is not supported. ' 'Consider updating clkha... |
def tdbr2EOL ( td ) :
"""convert the < br / > in < td > block into line ending ( EOL = \n )""" | for br in td . find_all ( "br" ) :
br . replace_with ( "\n" )
txt = six . text_type ( td )
# make it back into test
# would be unicode ( id ) in python2
soup = BeautifulSoup ( txt , 'lxml' )
# read it as a BeautifulSoup
ntxt = soup . find ( 'td' )
# BeautifulSoup has lot of other html junk .
# this line will extrac... |
def forward_until ( self , condition ) :
"""Forward until one of the provided matches is found .
The returned string contains all characters found * before the condition
was met . In other words , the condition will be true for the remainder
of the buffer .
: param condition : set of valid strings""" | c = TokenWithPosition ( '' , self . peek ( ) . position )
while self . hasNext ( ) and not condition ( self . peek ( ) ) :
c += self . forward ( 1 )
return c |
def remove_request ( self , uuid ) :
"""Remove any RPC request ( s ) using this uuid .
: param str uuid : Rpc Identifier .
: return :""" | for key in list ( self . _request ) :
if self . _request [ key ] == uuid :
del self . _request [ key ] |
def get_pdb_contents_to_pose_residue_map ( pdb_file_contents , rosetta_scripts_path , rosetta_database_path = None , pdb_id = None , extra_flags = '' ) :
'''Takes a string containing a PDB file , the RosettaScripts executable , and the Rosetta database and then uses the features database to map PDB residue IDs to p... | filename = write_temp_file ( "/tmp" , pdb_file_contents )
success , mapping = get_pdb_to_pose_residue_map ( filename , rosetta_scripts_path , rosetta_database_path = rosetta_database_path , pdb_id = pdb_id , extra_flags = extra_flags )
os . remove ( filename )
return success , mapping |
def _updateInternals ( self ) :
"""Update internal attributes related to likelihood .
Should be called any time branch lengths or model parameters
are changed .""" | rootnode = self . nnodes - 1
if self . _distributionmodel :
catweights = self . model . catweights
else :
catweights = scipy . ones ( 1 , dtype = 'float' )
# When there are multiple categories , it is acceptable
# for some ( but not all ) of them to have underflow at
# any given site . Note that we still includ... |
def remove_framework_search_paths ( self , paths , target_name = None , configuration_name = None ) :
"""Removes the given search paths from the FRAMEWORK _ SEARCH _ PATHS section of the target on the configurations
: param paths : A string or array of strings
: param target _ name : Target name or list of targ... | self . remove_search_paths ( XCBuildConfigurationFlags . FRAMEWORK_SEARCH_PATHS , paths , target_name , configuration_name ) |
def poll ( self , device_code , expires_in , interval , ** kwargs ) :
"""Construct the device authentication poller .
: param device _ code : Device authentication code
: type device _ code : str
: param expires _ in : Device authentication code expiry ( in seconds )
: type in : int
: param interval : Dev... | return DeviceOAuthPoller ( self . client , device_code , expires_in , interval ) |
def _write_section ( self , fp , section_name , section_items , delimiter ) :
"""Write a single section to the specified ` fp ' .""" | fp . write ( "[{0}]\n" . format ( section_name ) )
for key , value in section_items :
value = self . _interpolation . before_write ( self , section_name , key , value )
if value is not None or not self . _allow_no_value :
value = delimiter + str ( value ) . replace ( '\n' , '\n\t' )
else :
v... |
def list_groups ( name ) :
'''Return a list of groups the named user belongs to .
name
The name of the user for which to list groups . Starting in Salt 2016.11.0,
all groups for the user , including groups beginning with an underscore
will be listed .
. . versionchanged : : 2016.11.0
CLI Example :
. .... | groups = [ group for group in salt . utils . user . get_group_list ( name ) ]
return groups |
def output_scores ( self , name = None ) :
"""Returns : N x # class scores , summed to one for each box .""" | return tf . nn . softmax ( self . label_logits , name = name ) |
def uniquelogins ( sessions ) :
"""Unique logins per days / weeks / months .
: return : daily , weekly , monthly
3 lists of dictionaries of the following format [ { ' x ' : epoch , ' y ' : value } , ]""" | # sessions = LoginSession . query . order _ by ( LoginSession . started _ at . asc ( ) ) . all ( )
if not sessions :
return [ ] , [ ] , [ ]
dates = { }
for session in sessions :
user = session . user
# time value is discarded to aggregate on days only
date = session . started_at . strftime ( "%Y/%m/%d" ... |
def query ( cls , automation = None , offset = None , limit = None , api = None ) :
"""Query ( List ) apps .
: param automation : Automation id .
: param offset : Pagination offset .
: param limit : Pagination limit .
: param api : Api instance .
: return : collection object""" | automation_id = Transform . to_automation ( automation )
api = api or cls . _API
return super ( AutomationMember , cls ) . _query ( url = cls . _URL [ 'query' ] . format ( automation_id = automation_id ) , automation_id = automation_id , offset = offset , limit = limit , api = api , ) |
def include ( code , persist = True , compilerflags = None ) :
"""This function replaces the * calling module * with a dynamic
module that generates code on demand . The code is generated from
type descriptions that are created by gccxml compiling the C code
' code ' .
If < persist > is True , generated cod... | compilerflags = compilerflags or [ "-c" ]
# create a hash for the code , and use that as basename for the
# files we have to create
fullcode = "/* compilerflags: %r */\n%s" % ( compilerflags , code )
hashval = md5 ( fullcode ) . hexdigest ( )
fnm = os . path . abspath ( os . path . join ( gen_dir , hashval ) )
h_file =... |
def _create_attach_record ( self , id , timed ) :
"""Create a new pivot attachement record .""" | record = { }
record [ self . _foreign_key ] = self . _parent . get_key ( )
record [ self . _other_key ] = id
if timed :
record = self . _set_timestamps_on_attach ( record )
return record |
def get_prev_step ( self , step = None ) :
"""Returns the previous step before the given ` step ` . If there are no
steps available , None will be returned . If the ` step ` argument is
None , the current step will be determined automatically .""" | if step is None :
step = self . steps . current
form_list = self . get_form_list ( )
key = form_list . keyOrder . index ( step ) - 1
if key >= 0 :
return form_list . keyOrder [ key ]
return None |
def get_config_dir ( program = '' , system_wide = False ) :
'''Get the configuration directory .
Get the configuration directories , optionally for a specific program .
Args :
program ( str ) : The name of the program whose configuration directories have to be found .
system _ wide ( bool ) : Gets the syste... | config_homes = [ ]
if system_wide :
if os . name == 'nt' :
config_homes . append ( winreg . ExpandEnvironmentStrings ( '%PROGRAMDATA%' ) )
else :
config_homes . append ( '/etc' )
config_homes . append ( '/etc/xdg' )
if os . name == 'darwin' :
config_homes . append ( '... |
def request_status ( r , detailed = False ) :
"""Returns a formatted string about the status , useful for logging .
args :
r - takes requests . models . Response""" | base_string = "HTTP {r.request.method} {r.request.url}: {r.status_code}"
if r . status_code in range ( 200 , 99 ) :
string = base_string
if detailed is True :
string += " - {r.json()}"
else :
string += " - 👍"
return string . format ( r = r )
else :
string = base_string
return st... |
def _is_kpoint ( line ) :
"""Is this line the start of a new k - point block""" | # Try to parse the k - point ; false otherwise
toks = line . split ( )
# k - point header lines have 4 tokens
if len ( toks ) != 4 :
return False
try : # K - points are centered at the origin
xs = [ float ( x ) for x in toks [ : 3 ] ]
# Weights are in [ 0,1]
w = float ( toks [ 3 ] )
return all ( abs... |
def find_common_elements ( list1 : list , list2 : list ) -> list :
"""This function returns a sorted list of unique common elements between two lists .
Args :
list1 ( list ) : The first list .
list2 ( list ) : The second list .
Returns :
list : A sorted list of common elements .
Example :
> > > find _... | common_elements = set ( list1 ) & set ( list2 )
return sorted ( common_elements ) |
def transform_vector_coorb_to_inertial ( vec_coorb , orbPhase , quat_copr ) :
"""Given a vector ( of size 3 ) in coorbital frame , orbital phase in
coprecessing frame and a minimal rotation frame quat , transforms
the vector from the coorbital to the inertial frame .""" | # Transform to coprecessing frame
vec_copr = rotate_in_plane ( vec_coorb , - orbPhase )
# Transform to inertial frame
vec = transformTimeDependentVector ( np . array ( [ quat_copr ] ) . T , np . array ( [ vec_copr ] ) . T ) . T [ 0 ]
return np . array ( vec ) |
def _sample_variant_file_in_population ( x ) :
"""Check if a sample file is the same as the population file .
This is true for batches where we don ' t extract into samples and do not
run decomposition for gemini .""" | if "population" in x :
a = _get_project_vcf ( x )
b = _get_variant_file ( x , ( "vrn_file" , ) )
decomposed = tz . get_in ( ( "population" , "decomposed" ) , x )
if ( a and b and not decomposed and len ( a ) > 0 and len ( b ) > 0 and vcfutils . get_samples ( a [ 0 ] [ "path" ] ) == vcfutils . get_sample... |
def QA_indicator_MACD ( DataFrame , short = 12 , long = 26 , mid = 9 ) :
"""MACD CALC""" | CLOSE = DataFrame [ 'close' ]
DIF = EMA ( CLOSE , short ) - EMA ( CLOSE , long )
DEA = EMA ( DIF , mid )
MACD = ( DIF - DEA ) * 2
return pd . DataFrame ( { 'DIF' : DIF , 'DEA' : DEA , 'MACD' : MACD } ) |
def cached_getter ( func ) :
"""Decorate a property by executing it at instatiation time and cache the
result on the instance object .""" | @ wraps ( func )
def wrapper ( self ) :
attribute = f'_{func.__name__}'
value = getattr ( self , attribute , None )
if value is None :
value = func ( self )
setattr ( self , attribute , value )
return value
return wrapper |
def solver ( A , config ) :
"""Generate an SA solver given matrix A and a configuration .
Parameters
A : array , matrix , csr _ matrix , bsr _ matrix
Matrix to invert , CSR or BSR format preferred for efficiency
config : dict
A dictionary of solver configuration parameters that is used to
generate a smo... | # Convert A to acceptable format
A = make_csr ( A )
# Generate smoothed aggregation solver
try :
return smoothed_aggregation_solver ( A , B = config [ 'B' ] , BH = config [ 'BH' ] , smooth = config [ 'smooth' ] , strength = config [ 'strength' ] , max_levels = config [ 'max_levels' ] , max_coarse = config [ 'max_co... |
def pixels ( self , value : int ) -> 'Gap' :
"""Set the margin in pixels .""" | raise_not_number ( value )
self . gap = '{}px' . format ( value )
return self |
def load_settings_sizes ( ) :
"""Load sizes from settings or fallback to the module constants""" | page_size = AGNOCOMPLETE_DEFAULT_PAGESIZE
settings_page_size = getattr ( settings , 'AGNOCOMPLETE_DEFAULT_PAGESIZE' , None )
page_size = settings_page_size or page_size
page_size_min = AGNOCOMPLETE_MIN_PAGESIZE
settings_page_size_min = getattr ( settings , 'AGNOCOMPLETE_MIN_PAGESIZE' , None )
page_size_min = settings_p... |
def dump_value ( key , value , f , indent = 0 ) :
'''Save a value of any libconfig type
This function serializes takes ` ` key ` ` and ` ` value ` ` and serializes them
into ` ` f ` ` . If ` ` key ` ` is ` ` None ` ` , a list - style output is produced .
Otherwise , output has ` ` key = value ` ` format .''' | spaces = ' ' * indent
if key is None :
key_prefix = ''
key_prefix_nl = ''
else :
key_prefix = key + ' = '
key_prefix_nl = key + ' =\n' + spaces
dtype = get_dump_type ( value )
if dtype == 'd' :
f . write ( u'{}{}{{\n' . format ( spaces , key_prefix_nl ) )
dump_dict ( value , f , indent + 4 )
... |
def easy_time_extrator ( self , string ) :
"""简单时间抽取 , 即年月日同时出现
Keyword arguments :
string - - 含有时间的文本 , str类型""" | try :
if not self . year_check and not self . month_check and not self . day_check :
str_all = re . search ( '([\u4e00-\u9fa5〇○]{4})年([\u4e00-\u9fa5]{1,3})月([\u4e00-\u9fa5]{1,3})日' , string )
str_year = self . str_to_num ( str_all . group ( 1 ) )
str_month = self . str_to_num ( str_all . gro... |
def describe_thing_type ( thingTypeName , region = None , key = None , keyid = None , profile = None ) :
'''Given a thing type name describe its properties .
Returns a dictionary of interesting properties .
. . versionadded : : 2016.11.0
CLI Example :
. . code - block : : bash
salt myminion boto _ iot . d... | try :
conn = _get_conn ( region = region , key = key , keyid = keyid , profile = profile )
res = conn . describe_thing_type ( thingTypeName = thingTypeName )
if res :
res . pop ( 'ResponseMetadata' , None )
thingTypeMetadata = res . get ( 'thingTypeMetadata' )
if thingTypeMetadata :
... |
def setup_logging ( namespace ) :
"""setup global logging""" | loglevel = { 0 : logging . ERROR , 1 : logging . WARNING , 2 : logging . INFO , 3 : logging . DEBUG , } . get ( namespace . verbosity , logging . DEBUG )
if namespace . verbosity > 1 :
logformat = '%(levelname)s csvpandas %(lineno)s %(message)s'
else :
logformat = 'csvpandas %(message)s'
logging . basicConfig (... |
def get_tile_image ( imgs , tile_shape = None , result_img = None , margin_color = None ) :
"""Concatenate images whose sizes are different .
@ param imgs : image list which should be concatenated
@ param tile _ shape : shape for which images should be concatenated
@ param result _ img : numpy array to put re... | def resize ( * args , ** kwargs ) : # anti _ aliasing arg cannot be passed to skimage < 0.14
# use LooseVersion to allow 0.14dev .
if LooseVersion ( skimage . __version__ ) < LooseVersion ( '0.14' ) :
kwargs . pop ( 'anti_aliasing' , None )
return skimage . transform . resize ( * args , ** kwargs )
def ... |
def add_event_source ( event_source , lambda_arn , target_function , boto_session , dry = False ) :
"""Given an event _ source dictionary , create the object and add the event source .""" | event_source_obj , ctx , funk = get_event_source ( event_source , lambda_arn , target_function , boto_session , dry = False )
# TODO : Detect changes in config and refine exists algorithm
if not dry :
if not event_source_obj . status ( funk ) :
event_source_obj . add ( funk )
return 'successful' if ... |
def _handle_one_message ( self ) :
"""Handle one single incoming message on any socket .
This is the inner loop of the main application loop .
Returns True if further messages should be received , False otherwise
( it should quit , that is ) .
It is crucial that this class function always respond with a
q... | result = True
requesttype = self . query_socket . recv ( )
if requesttype == b"PUBLISH" :
self . _handle_incoming_event ( )
elif requesttype == b"QUERY" :
self . _handle_event_query ( )
elif ( self . exit_message is not None and requesttype == self . exit_message ) :
_logger . warn ( "Asked to quit through ... |
def prune_graph ( graph_str , package_name ) :
"""Prune a package graph so it only contains nodes accessible from the
given package .
Args :
graph _ str ( str ) : Dot - language graph string .
package _ name ( str ) : Name of package of interest .
Returns :
Pruned graph , as a string .""" | # find nodes of interest
g = read_dot ( graph_str )
nodes = set ( )
for node , attrs in g . node_attr . iteritems ( ) :
attr = [ x for x in attrs if x [ 0 ] == "label" ]
if attr :
label = attr [ 0 ] [ 1 ]
try :
req_str = _request_from_label ( label )
request = PackageRequ... |
def add_group_coordinator ( self , group , response ) :
"""Update with metadata for a group coordinator
Arguments :
group ( str ) : name of group from GroupCoordinatorRequest
response ( GroupCoordinatorResponse ) : broker response
Returns :
bool : True if metadata is updated , False on error""" | log . debug ( "Updating coordinator for %s: %s" , group , response )
error_type = Errors . for_code ( response . error_code )
if error_type is not Errors . NoError :
log . error ( "GroupCoordinatorResponse error: %s" , error_type )
self . _groups [ group ] = - 1
return False
node_id = response . coordinator... |
def cli ( env ) :
"""Print environment variables .""" | filtered_vars = dict ( [ ( k , v ) for k , v in env . vars . items ( ) if not k . startswith ( '_' ) ] )
env . fout ( formatting . iter_to_table ( filtered_vars ) ) |
def sg_leaky_relu ( x , opt ) :
r"""" See [ Xu , et al . 2015 ] ( https : / / arxiv . org / pdf / 1505.00853v2 . pdf )
Args :
x : A tensor
opt :
name : A name for the operation ( optional ) .
Returns :
A ` Tensor ` with the same type and shape as ` x ` .""" | return tf . where ( tf . greater ( x , 0 ) , x , 0.01 * x , name = opt . name ) |
def resfinderreporter ( self ) :
"""Custom reports for ResFinder analyses . These reports link the gene ( s ) found to their resistance phenotypes""" | # Initialise resistance dictionaries from the notes . txt file
resistance_classes = ResistanceNotes . classes ( self . targetpath )
# Create a workbook to store the report . Using xlsxwriter rather than a simple csv format , as I want to be
# able to have appropriately sized , multi - line cells
workbook = xlsxwriter .... |
def read_query ( self , sql , index_col = None , coerce_float = True , parse_dates = None , params = None , chunksize = None ) :
"""Read SQL query into a DataFrame .
Parameters
sql : string
SQL query to be executed .
index _ col : string , optional , default : None
Column name to use as index for the retu... | args = _convert_params ( sql , params )
result = self . execute ( * args )
columns = result . keys ( )
if chunksize is not None :
return self . _query_iterator ( result , chunksize , columns , index_col = index_col , coerce_float = coerce_float , parse_dates = parse_dates )
else :
data = result . fetchall ( )
... |
def initialize ( plugins , exclude_files_regex = None , exclude_lines_regex = None , path = '.' , scan_all_files = False , ) :
"""Scans the entire codebase for secrets , and returns a
SecretsCollection object .
: type plugins : tuple of detect _ secrets . plugins . base . BasePlugin
: param plugins : rules to... | output = SecretsCollection ( plugins , exclude_files = exclude_files_regex , exclude_lines = exclude_lines_regex , )
if os . path . isfile ( path ) : # This option allows for much easier adhoc usage .
files_to_scan = [ path ]
elif scan_all_files :
files_to_scan = _get_files_recursively ( path )
else :
files... |
def emit ( * args ) :
"""Convert the given args to a Quad ( 3 address code ) instruction""" | quad = Quad ( * args )
__DEBUG__ ( 'EMIT ' + str ( quad ) )
MEMORY . append ( quad ) |
def reject ( self ) :
"""Reject this message .
The message will be discarded by the server .
: raises MessageStateError : If the message has already been
acknowledged / requeued / rejected .""" | if self . acknowledged :
raise self . MessageStateError ( "Message already acknowledged with state: %s" % self . _state )
self . backend . reject ( self . delivery_tag )
self . _state = "REJECTED" |
def project_decrease_permissions ( object_id , input_params = { } , always_retry = True , ** kwargs ) :
"""Invokes the / project - xxxx / decreasePermissions API method .
For more info , see : https : / / wiki . dnanexus . com / API - Specification - v1.0.0 / Project - Permissions - and - Sharing # API - method %... | return DXHTTPRequest ( '/%s/decreasePermissions' % object_id , input_params , always_retry = always_retry , ** kwargs ) |
def get_state ( self ) :
"""Return the sampler ' s current state in order to
restart sampling at a later time .""" | state = dict ( sampler = { } , stochastics = { } )
# The state of the sampler itself .
for s in self . _state :
state [ 'sampler' ] [ s ] = getattr ( self , s )
# The state of each stochastic parameter
for s in self . stochastics :
state [ 'stochastics' ] [ s . __name__ ] = s . value
return state |
def acquire ( self , blocking = True , timeout = None , shared = False ) :
"""Acquire the lock in shared or exclusive mode .""" | with self . _lock :
if shared :
self . _acquire_shared ( blocking , timeout )
else :
self . _acquire_exclusive ( blocking , timeout )
assert not ( self . is_shared and self . is_exclusive ) |
def matchers ( ) -> List [ SimAlgorithm ] :
"""Matchers in owlsim2""" | return [ SimAlgorithm . PHENODIGM , SimAlgorithm . JACCARD , SimAlgorithm . SIM_GIC , SimAlgorithm . RESNIK , SimAlgorithm . SYMMETRIC_RESNIK ] |
def validate ( self , path ) :
"""Run path against filter sets and return True if all pass""" | # Exclude hidden files and folders with ' . ' prefix
if os . path . basename ( path ) . startswith ( '.' ) :
return False
# Check that current path level is more than min path and less than max path
if not self . check_level ( path ) :
return False
if self . filters :
if not self . _level_filters ( path ) :... |
def inverse ( self , encoded , duration = None ) :
'''Inverse transformation''' | ann = jams . Annotation ( namespace = self . namespace , duration = duration )
for start , end , value in self . decode_intervals ( encoded , duration = duration , transition = self . transition , p_init = self . p_init , p_state = self . p_state ) : # Map start : end to frames
f_start , f_end = time_to_frames ( [ ... |
def get_selected_uuidtab ( self ) : # TODO DBUS ONLY
"""Returns the uuid of the current selected terminal""" | page_num = self . get_notebook ( ) . get_current_page ( )
terminals = self . get_notebook ( ) . get_terminals_for_page ( page_num )
return str ( terminals [ 0 ] . get_uuid ( ) ) |
def number_occurences ( self , proc ) :
"""Returns the number of occurencies of commands that contain given text
Returns :
int : The number of occurencies of commands with given text
. . note : :
' proc ' can match anywhere in the command path , name or arguments .""" | return len ( [ True for row in self . data if proc in row [ self . command_name ] ] ) |
def word_count ( ctx , text , by_spaces = False ) :
"""Returns the number of words in the given text string""" | text = conversions . to_string ( text , ctx )
by_spaces = conversions . to_boolean ( by_spaces , ctx )
return len ( __get_words ( text , by_spaces ) ) |
def error ( request , message , extra_tags = '' , fail_silently = False ) :
"""Adds a message with the ` ` ERROR ` ` level .""" | add_message ( request , constants . ERROR , message , extra_tags = extra_tags , fail_silently = fail_silently ) |
def get_time_to_merge_request_response ( self , item ) :
"""Get the first date at which a review was made on the PR by someone
other than the user who created the PR""" | review_dates = [ str_to_datetime ( review [ 'created_at' ] ) for review in item [ 'review_comments_data' ] if item [ 'user' ] [ 'login' ] != review [ 'user' ] [ 'login' ] ]
if review_dates :
return min ( review_dates )
return None |
def query ( url , ** kwargs ) :
'''Query a resource , and decode the return data
Passes through all the parameters described in the
: py : func : ` utils . http . query function < salt . utils . http . query > ` :
. . autofunction : : salt . utils . http . query
CLI Example :
. . code - block : : bash
s... | opts = __opts__ . copy ( )
if 'opts' in kwargs :
opts . update ( kwargs [ 'opts' ] )
del kwargs [ 'opts' ]
return salt . utils . http . query ( url = url , opts = opts , ** kwargs ) |
def lt ( self , other , axis = "columns" , level = None ) :
"""Checks element - wise that this is less than other .
Args :
other : A DataFrame or Series or scalar to compare to .
axis : The axis to perform the lt over .
level : The Multilevel index level to apply lt over .
Returns :
A new DataFrame fill... | return self . _binary_op ( "lt" , other , axis = axis , level = level ) |
def _parse_outgoing_mail ( sender , to , msgstring ) :
"""Parse an outgoing mail and put it into the OUTBOX .
Arguments :
- ` sender ` : str
- ` to ` : str
- ` msgstring ` : str
Return : None
Exceptions : None""" | global OUTBOX
OUTBOX . append ( email . message_from_string ( msgstring ) )
return |
def get_http_connection ( self , host , is_secure ) :
"""Gets a connection from the pool for the named host . Returns
None if there is no connection that can be reused .""" | if is_secure :
return AsyncHTTPSConnection ( host , http_client = self . _httpclient )
else :
return AsyncHTTPConnection ( host , http_client = self . _httpclient ) |
def generate ( directory , outfilename = DEFAULT_BUILDFILE ) :
"""Generate a build - file for quilt build from a directory of
source files .""" | try :
buildfilepath = generate_build_file ( directory , outfilename = outfilename )
except BuildException as builderror :
raise CommandException ( str ( builderror ) )
print ( "Generated build-file %s." % ( buildfilepath ) ) |
def parse_mixed_delim_str ( line ) :
"""Turns . obj face index string line into [ verts , texcoords , normals ] numeric tuples .""" | arrs = [ [ ] , [ ] , [ ] ]
for group in line . split ( ' ' ) :
for col , coord in enumerate ( group . split ( '/' ) ) :
if coord :
arrs [ col ] . append ( int ( coord ) )
return [ tuple ( arr ) for arr in arrs ] |
def check_spam ( self , ip = None , email = None , name = None , login = None , realname = None , subject = None , body = None , subject_type = 'plain' , body_type = 'plain' ) :
"""http : / / api . yandex . ru / cleanweb / doc / dg / concepts / check - spam . xml
subject _ type = plain | html | bbcode
body _ ty... | data = { 'ip' : ip , 'email' : email , 'name' : name , 'login' : login , 'realname' : realname , 'body-%s' % body_type : body , 'subject-%s' % subject_type : subject }
r = self . request ( 'post' , 'http://cleanweb-api.yandex.ru/1.0/check-spam' , data = data )
root = ET . fromstring ( r . content )
return { 'id' : root... |
def version_at_least ( version_string , major , minor , micro , patch ) :
"""This returns True if the version _ string represents a Tor version
of at least ` ` major ` ` . ` ` minor ` ` . ` ` micro ` ` . ` ` patch ` ` version ,
ignoring any trailing specifiers .""" | parts = re . match ( r'^([0-9]+)\.([0-9]+)\.([0-9]+)\.([0-9]+).*$' , version_string , )
for ver , gold in zip ( parts . group ( 1 , 2 , 3 , 4 ) , ( major , minor , micro , patch ) ) :
if int ( ver ) < int ( gold ) :
return False
elif int ( ver ) > int ( gold ) :
return True
return True |
def _create_tag_highlevel ( self , tag_name , message = None ) :
"""Create a tag on the toplevel repo if there is no patch repo ,
or a tag on the patch repo and bookmark on the top repo if there is a
patch repo
Returns a list where each entry is a dict for each bookmark or tag
created , which looks like { '... | results = [ ]
if self . patch_path : # make a tag on the patch queue
tagged = self . _create_tag_lowlevel ( tag_name , message = message , patch = True )
if tagged :
results . append ( { 'type' : 'tag' , 'patch' : True } )
# use a bookmark on the main repo since we can ' t change it
self . hg ( ... |
def flux_units ( self , units ) :
"""A setter for the flux units
Parameters
units : str , astropy . units . core . PrefixUnit
The desired units of the zeropoint flux density""" | # Check that the units are valid
dtypes = ( q . core . PrefixUnit , q . quantity . Quantity , q . core . CompositeUnit )
if not isinstance ( units , dtypes ) :
raise ValueError ( units , "units not understood." )
# Check that the units changed
if units != self . flux_units : # Convert to new units
sfd = q . spe... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.