signature stringlengths 29 44.1k | implementation stringlengths 0 85.2k |
|---|---|
def patterson_d ( aca , acb , acc , acd ) :
"""Unbiased estimator for D ( A , B ; C , D ) , the normalised four - population
test for admixture between ( A or B ) and ( C or D ) , also known as the
" ABBA BABA " test .
Parameters
aca : array _ like , int , shape ( n _ variants , 2 ) ,
Allele counts for po... | # check inputs
aca = AlleleCountsArray ( aca , copy = False )
assert aca . shape [ 1 ] == 2 , 'only biallelic variants supported'
acb = AlleleCountsArray ( acb , copy = False )
assert acb . shape [ 1 ] == 2 , 'only biallelic variants supported'
acc = AlleleCountsArray ( acc , copy = False )
assert acc . shape [ 1 ] == ... |
def build_mxnet ( app ) :
"""Build mxnet . so lib""" | if not os . path . exists ( os . path . join ( app . builder . srcdir , '..' , 'config.mk' ) ) :
_run_cmd ( "cd %s/.. && cp make/config.mk config.mk && make -j$(nproc) USE_MKLDNN=0 USE_CPP_PACKAGE=1 " % app . builder . srcdir )
else :
_run_cmd ( "cd %s/.. && make -j$(nproc) USE_MKLDNN=0 USE_CPP_PACKAGE=1 " % ap... |
def main ( ) :
"""Main function called upon script execution .""" | if OPTIONS . get ( '--no-colors' ) :
disable_all_colors ( )
elif OPTIONS . get ( '--colors' ) :
enable_all_colors ( )
if is_enabled ( ) and os . name == 'nt' :
Windows . enable ( auto_colors = True , reset_atexit = True )
elif OPTIONS . get ( '--light-bg' ) :
set_light_background ( )
elif OPTIONS . get ... |
def exists ( self , session_key ) :
"""Checks to see if a session currently exists in DynamoDB .
: rtype : bool
: returns : ` ` True ` ` if a session with the given key exists in the DB ,
` ` False ` ` if not .""" | response = self . table . get_item ( Key = { 'session_key' : session_key } , ConsistentRead = ALWAYS_CONSISTENT )
if 'Item' in response :
return True
else :
return False |
def dump_travis_configuration ( config , path ) :
"""Dump the travis configuration settings to the travis . yml file .
The configuration settings from the travis . yml will be dumped with
ordering preserved . Thus , when a password is added to the travis . yml
file , a diff will show that only the password wa... | with open ( path , 'w' ) as config_file :
ordered_dump ( config , config_file , default_flow_style = False ) |
def least_role ( ) -> Role :
"""Return the TRUSTEE indy - sdk role for an anchor acting in an AnchorSmith capacity .
: return : TRUSTEE role""" | LOGGER . debug ( 'AnchorSmith.least_role >>>' )
rv = Role . TRUSTEE . token ( )
LOGGER . debug ( 'AnchorSmith.least_role <<< %s' , rv )
return rv |
def _convert_to_font ( cls , font_dict ) :
"""Convert ` ` font _ dict ` ` to an openpyxl v2 Font object
Parameters
font _ dict : dict
A dict with zero or more of the following keys ( or their synonyms ) .
' name '
' size ' ( ' sz ' )
' bold ' ( ' b ' )
' italic ' ( ' i ' )
' underline ' ( ' u ' )
... | from openpyxl . styles import Font
_font_key_map = { 'sz' : 'size' , 'b' : 'bold' , 'i' : 'italic' , 'u' : 'underline' , 'strike' : 'strikethrough' , 'vertalign' : 'vertAlign' , }
font_kwargs = { }
for k , v in font_dict . items ( ) :
if k in _font_key_map :
k = _font_key_map [ k ]
if k == 'color' :
... |
def search_users ( self , user ) :
"""Search for LDAP users .
Args :
user : User to search for . It is not entirely clear how the
JSS determines the results - are regexes allowed , or
globbing ?
Returns :
LDAPUsersResult object .
Raises :
Will raise a JSSGetError if no results are found .""" | user_url = "%s/%s/%s" % ( self . url , "user" , user )
response = self . jss . get ( user_url )
return LDAPUsersResults ( self . jss , response ) |
def cluster ( seqs , threshold = 0.975 , out_file = None , temp_dir = None , make_db = True , quiet = False , threads = 0 , return_just_seq_ids = False , max_memory = 800 , debug = False ) :
'''Perform sequence clustering with CD - HIT .
Args :
seqs ( list ) : An iterable of sequences , in any format that ` abu... | if make_db :
ofile , cfile , seq_db , db_path = cdhit ( seqs , out_file = out_file , temp_dir = temp_dir , threshold = threshold , make_db = True , quiet = quiet , threads = threads , max_memory = max_memory , debug = debug )
return parse_clusters ( ofile , cfile , seq_db = seq_db , db_path = db_path , return_j... |
def Spheres ( centers , r = 1 , c = "r" , alpha = 1 , res = 8 ) :
"""Build a ( possibly large ) set of spheres at ` centers ` of radius ` r ` .
Either ` c ` or ` r ` can be a list of RGB colors or radii .
. . hint : : | manyspheres | | manyspheres . py | _""" | cisseq = False
if utils . isSequence ( c ) :
cisseq = True
if cisseq :
if len ( centers ) > len ( c ) :
colors . printc ( "~times Mismatch in Spheres() colors" , len ( centers ) , len ( c ) , c = 1 )
exit ( )
if len ( centers ) != len ( c ) :
colors . printc ( "~lightningWarning: mis... |
def apply ( self , doc ) :
"""Generate MentionParagraphs from a Document by parsing all of its Paragraphs .
: param doc : The ` ` Document ` ` to parse .
: type doc : ` ` Document ` `
: raises TypeError : If the input doc is not of type ` ` Document ` ` .""" | if not isinstance ( doc , Document ) :
raise TypeError ( "Input Contexts to MentionParagraphs.apply() must be of type Document" )
for paragraph in doc . paragraphs :
yield TemporaryParagraphMention ( paragraph ) |
def fcoe_get_interface_output_fcoe_intf_list_interface_name ( self , ** kwargs ) :
"""Auto Generated Code""" | config = ET . Element ( "config" )
fcoe_get_interface = ET . Element ( "fcoe_get_interface" )
config = fcoe_get_interface
output = ET . SubElement ( fcoe_get_interface , "output" )
fcoe_intf_list = ET . SubElement ( output , "fcoe-intf-list" )
fcoe_intf_fcoe_port_id_key = ET . SubElement ( fcoe_intf_list , "fcoe-intf-f... |
def _medianindex ( self , v ) :
"""find new position of vertex v according to adjacency in layer l + dir .
position is given by the median value of adjacent positions .
median heuristic is proven to achieve at most 3 times the minimum
of crossings ( while barycenter achieve in theory the order of | V | )""" | assert self . prevlayer ( ) != None
N = self . _neighbors ( v )
g = self . layout . grx
pos = [ g [ x ] . pos for x in N ]
lp = len ( pos )
if lp == 0 :
return [ ]
pos . sort ( )
pos = pos [ : : self . layout . dirh ]
i , j = divmod ( lp - 1 , 2 )
return [ pos [ i ] ] if j == 0 else [ pos [ i ] , pos [ i + j ] ] |
def get_var_type ( self , name ) :
"""Return type string , compatible with numpy .""" | name = create_string_buffer ( name )
type_ = create_string_buffer ( MAXSTRLEN )
self . library . get_var_type . argtypes = [ c_char_p , c_char_p ]
self . library . get_var_type ( name , type_ )
return type_ . value |
def check_manual_seed ( seed ) :
"""If manual seed is not specified , choose a random one and communicate it to the user .""" | seed = seed or random . randint ( 1 , 10000 )
random . seed ( seed )
torch . manual_seed ( seed )
print ( 'Using manual seed: {seed}' . format ( seed = seed ) ) |
def extract_docstring ( self ) :
"""Extract a module - level docstring""" | lines = open ( self . filename ) . readlines ( )
start_row = 0
if lines [ 0 ] . startswith ( '#!' ) :
lines . pop ( 0 )
start_row = 1
docstring = ''
first_par = ''
line_iter = lines . __iter__ ( )
tokens = tokenize . generate_tokens ( lambda : next ( line_iter ) )
for tok_type , tok_content , _ , ( erow , _ ) ,... |
def _debug_mode_responses ( self , request , response ) :
"""Extra functionality available in debug mode .
- If pretty printed output was requested , force the content type to text . This
causes the browser to not try to format the output in any way .
- If SQL profiling is turned on , return a page with SQL q... | if django . conf . settings . DEBUG_GMN :
if 'pretty' in request . GET :
response [ 'Content-Type' ] = d1_common . const . CONTENT_TYPE_TEXT
if ( 'HTTP_VENDOR_PROFILE_SQL' in request . META or django . conf . settings . DEBUG_PROFILE_SQL ) :
response_list = [ ]
for query in django . db .... |
def _draw_text ( self , coords , text , foreground , font ) :
"""Draw the text and shorten it if required""" | if text is None :
return None
x1_r , _ , x2_r , _ = coords
while True :
text_id = self . _timeline . create_text ( ( 0 , 0 ) , text = text , fill = foreground if foreground != "default" else self . _marker_foreground , font = font if font != "default" else self . _marker_font , tags = ( "marker" , ) )
x1_t ... |
def show ( self ) :
"""Show the data graphically in a new pop - up window .""" | # prevent the following error :
# ' _ tkinter . TclError : no display name and no $ DISPLAY environment
# variable '
# import matplotlib
# matplotlib . use ( ' GTK3Agg ' , warn = False )
import matplotlib . pyplot as plt
pointlist = self . get_pointlist ( )
if 'pen_down' in pointlist [ 0 ] [ 0 ] :
assert len ( poin... |
def frac ( x , context = None ) :
"""Return the fractional part of ` ` x ` ` .
The result has the same sign as ` ` x ` ` .""" | return _apply_function_in_current_context ( BigFloat , mpfr . mpfr_frac , ( BigFloat . _implicit_convert ( x ) , ) , context , ) |
def get_tunneling ( handler , registry ) :
"""Allows all methods to be tunneled via GET for dev / debuging
purposes .""" | log . info ( 'get_tunneling enabled' )
def get_tunneling ( request ) :
if request . method == 'GET' :
method = request . GET . pop ( '_m' , 'GET' )
request . method = method
if method in [ 'POST' , 'PUT' , 'PATCH' ] :
get_params = request . GET . mixed ( )
valid_param... |
def _build_loop ( self , lexer ) :
"""Build saveframe loop .
: param lexer : instance of lexical analyzer .
: type lexer : : func : ` ~ nmrstarlib . bmrblex . bmrblex `
: return : Fields and values of the loop .
: rtype : : py : class : ` tuple `""" | fields = [ ]
values = [ ]
token = next ( lexer )
while token [ 0 ] == u"_" :
fields . append ( token [ 1 : ] )
token = next ( lexer )
while token != u"stop_" :
values . append ( token )
token = next ( lexer )
assert float ( len ( values ) / len ( fields ) ) . is_integer ( ) , "Error in loop construction... |
def put_headers_in_environ ( headers , environ ) :
"""Given a list of headers , put them into environ based on PEP - 333.
This converts headers to uppercase , prefixes them with ' HTTP _ ' , and
converts dashes to underscores before adding them to the environ dict .
Args :
headers : A list of ( header , val... | for key , value in headers :
environ [ 'HTTP_%s' % key . upper ( ) . replace ( '-' , '_' ) ] = value |
def block_sep0 ( self , Y ) :
r"""Separate variable into component corresponding to
: math : ` \ mathbf { y } _ 0 ` in : math : ` \ mathbf { y } \ ; \ ; ` .""" | return Y [ ( slice ( None ) , ) * self . blkaxis + ( slice ( 0 , self . blkidx ) , ) ] |
def run_processor ( processorClass , ocrd_tool = None , mets_url = None , resolver = None , workspace = None , page_id = None , log_level = None , input_file_grp = None , output_file_grp = None , parameter = None , working_dir = None , ) : # pylint : disable = too - many - locals
"""Create a workspace for mets _ ur... | workspace = _get_workspace ( workspace , resolver , mets_url , working_dir )
if parameter is not None :
if not '://' in parameter :
fname = os . path . abspath ( parameter )
else :
fname = workspace . download_url ( parameter )
with open ( fname , 'r' ) as param_json_file :
parameter... |
def cdslen ( self ) :
"""Translated length of this feature .
Undefined for non - mRNA features .""" | if self . type != 'mRNA' :
return None
return sum ( [ len ( c ) for c in self . children if c . type == 'CDS' ] ) |
def RESTrequest ( * args , ** kwargs ) :
"""return and save the blob of data that is returned
from kegg without caring to the format""" | verbose = kwargs . get ( 'verbose' , False )
force_download = kwargs . get ( 'force' , False )
save = kwargs . get ( 'force' , True )
# so you can copy paste from kegg
args = list ( chain . from_iterable ( a . split ( '/' ) for a in args ) )
args = [ a for a in args if a ]
request = 'http://rest.kegg.jp/' + "/" . join ... |
def swarm_denovo_cluster ( seq_path , d = 1 , threads = 1 , HALT_EXEC = False ) :
"""Function : launch the Swarm de novo OTU picker
Parameters : seq _ path , filepath to reads
d , resolution
threads , number of threads to use
Return : clusters , list of lists""" | # Check sequence file exists
if not exists ( seq_path ) :
raise ValueError ( "%s does not exist" % seq_path )
# Instantiate the object
swarm = Swarm ( HALT_EXEC = HALT_EXEC )
# Set the resolution
if d > 0 :
swarm . Parameters [ '-d' ] . on ( d )
else :
raise ValueError ( "Resolution -d must be a positive in... |
def add ( self , handler , allow_dupe = False , send_event = True ) :
"""Add handler instance and attach any events to it .
: param object handler : handler instance
: param bool allow _ dupe : If True , allow registering a handler more than once .
: return object : The handler you added is given back so this... | self . _add ( handler , allow_dupe = allow_dupe , send_event = send_event )
return handler |
def wr_pydot_dag ( self , fout_img , dag ) :
"""Plot using the pydot graphics engine .""" | img_fmt = os . path . splitext ( fout_img ) [ 1 ] [ 1 : ]
dag . write ( fout_img , format = img_fmt )
self . log . write ( " {GO_USR:>3} usr {GO_ALL:>3} GOs WROTE: {F}\n" . format ( F = fout_img , GO_USR = len ( self . gosubdag . go_sources ) , GO_ALL = len ( dag . obj_dict [ 'nodes' ] ) ) ) |
def MatMul ( a , b , transpose_a , transpose_b ) :
"""Matrix multiplication op .""" | return np . dot ( a if not transpose_a else np . transpose ( a ) , b if not transpose_b else np . transpose ( b ) ) , |
def _build_pyramid ( self , image , levels ) :
"""Returns a list of reduced - size images , from smallest to original size""" | pyramid = [ image ]
for l in range ( levels - 1 ) :
if any ( x < 20 for x in pyramid [ - 1 ] . shape [ : 2 ] ) :
break
pyramid . append ( cv2 . pyrDown ( pyramid [ - 1 ] ) )
return list ( reversed ( pyramid ) ) |
def on_input_timeout ( self , cli ) :
"""brings up the metadata for the command if there is a valid command already typed""" | document = cli . current_buffer . document
text = document . text
text = text . replace ( 'az ' , '' )
if self . default_command :
text = self . default_command + ' ' + text
param_info , example = self . generate_help_text ( )
self . param_docs = u'{}' . format ( param_info )
self . example_docs = u'{}' . format ( ... |
def validateOneAttribute ( self , doc , elem , attr , value ) :
"""Try to validate a single attribute for an element basically
it does the following checks as described by the XML - 1.0
recommendation : - [ VC : Attribute Value Type ] - [ VC :
Fixed Attribute Default ] - [ VC : Entity Name ] - [ VC :
Name T... | if doc is None :
doc__o = None
else :
doc__o = doc . _o
if elem is None :
elem__o = None
else :
elem__o = elem . _o
if attr is None :
attr__o = None
else :
attr__o = attr . _o
ret = libxml2mod . xmlValidateOneAttribute ( self . _o , doc__o , elem__o , attr__o , value )
return ret |
def standardized_mortality_ratio ( e , b , s_e , s_b , n ) :
"""A utility function to compute standardized mortality ratio ( SMR ) .
Parameters
e : array
( n * h , 1 ) , event variable measured for each age group across n spatial units
b : array
( n * h , 1 ) , population at risk variable measured for eac... | s_r = s_e * 1.0 / s_b
e_by_n = sum_by_n ( e , 1.0 , n )
expected = sum_by_n ( b , s_r , n )
smr = e_by_n * 1.0 / expected
return smr |
def split_by_regex ( self , regex_or_pattern , flags = re . U , gaps = True ) :
"""Split the text into multiple instances using a regex .
Parameters
regex _ or _ pattern : str or compiled pattern
The regular expression to use for splitting .
flags : int ( default : re . U )
The regular expression flags ( ... | text = self [ TEXT ]
regex = regex_or_pattern
if isinstance ( regex , six . string_types ) :
regex = re . compile ( regex_or_pattern , flags = flags )
# else is assumed pattern
last_end = 0
spans = [ ]
if gaps : # tag cap spans
for mo in regex . finditer ( text ) :
start , end = mo . start ( ) , mo . en... |
def _maybe_location ( cls , response , uri = None ) :
"""Get the Location : if there is one .""" | location = response . headers . getRawHeaders ( b'location' , [ None ] ) [ 0 ]
if location is not None :
return location . decode ( 'ascii' )
return uri |
def parse ( cls , requester , entry ) :
"""Turns a JSON object into a model instance .""" | if not type ( entry ) is dict :
return entry
for key_to_parse , cls_to_parse in six . iteritems ( cls . parser ) :
if key_to_parse in entry :
entry [ key_to_parse ] = cls_to_parse . parse ( requester , entry [ key_to_parse ] )
return cls ( requester , ** entry ) |
def _validate_swagger_file ( self ) :
'''High level check / validation of the input swagger file based on
https : / / github . com / swagger - api / swagger - spec / blob / master / versions / 2.0 . md
This is not a full schema compliance check , but rather make sure that the input file ( YAML or
JSON ) can b... | # check for any invalid fields for Swagger Object V2
for field in self . _cfg :
if ( field not in _Swagger . SWAGGER_OBJ_V2_FIELDS and not _Swagger . VENDOR_EXT_PATTERN . match ( field ) ) :
raise ValueError ( 'Invalid Swagger Object Field: {0}' . format ( field ) )
# check for Required Swagger fields by Sa... |
def _set_member_entry ( self , v , load = False ) :
"""Setter method for member _ entry , mapped from YANG variable / rbridge _ id / secpolicy / defined _ policy / policies / member _ entry ( list )
If this variable is read - only ( config : false ) in the
source YANG file , then _ set _ member _ entry is consi... | if hasattr ( v , "_utype" ) :
v = v . _utype ( v )
try :
t = YANGDynClass ( v , base = YANGListType ( "member" , member_entry . member_entry , yang_name = "member-entry" , rest_name = "member-entry" , parent = self , is_container = 'list' , user_ordered = False , path_helper = self . _path_helper , yang_keys = ... |
def isotime ( s ) :
"Convert timestamps in ISO8661 format to and from Unix time ." | if type ( s ) == type ( 1 ) :
return time . strftime ( "%Y-%m-%dT%H:%M:%S" , time . gmtime ( s ) )
elif type ( s ) == type ( 1.0 ) :
date = int ( s )
msec = s - date
date = time . strftime ( "%Y-%m-%dT%H:%M:%S" , time . gmtime ( s ) )
return date + "." + repr ( msec ) [ 3 : ]
elif type ( s ) == type... |
def monitor_counters ( mc , output , counters , detailed , f ) :
"""Monitor the counters on a specified machine , taking a snap - shot every
time the generator ' f ' yields .""" | # Print CSV header
output . write ( "time,{}{}\n" . format ( "x,y," if detailed else "" , "," . join ( counters ) ) )
system_info = mc . get_system_info ( )
# Make an initial sample of the counters
last_counter_values = sample_counters ( mc , system_info )
start_time = time . time ( )
for _ in f ( ) : # Snapshot the ch... |
def hash ( self ) :
"""Hash value based on file name and . ini file content""" | if self . _hash is None : # Only hash _ camera . ini and _ para . ini
fsh = [ self . path . with_name ( self . _mid + "_camera.ini" ) , self . path . with_name ( self . _mid + "_para.ini" ) ]
tohash = [ hashfile ( f ) for f in fsh ]
tohash . append ( self . path . name )
# Hash a maximum of ~ 1MB of the... |
def _prob_match ( self , features ) :
"""Compute match probabilities .
Parameters
features : numpy . ndarray
The data to train the model on .
Returns
numpy . ndarray
The match probabilties .""" | # compute the probabilities
probs = self . kernel . predict_proba ( features )
# get the position of match probabilities
classes = list ( self . kernel . classes_ )
match_class_position = classes . index ( 1 )
return probs [ : , match_class_position ] |
def setdict ( self , D = None , B = None ) :
"""Set dictionary array .""" | if D is not None :
self . D = np . asarray ( D , dtype = self . dtype )
if B is not None :
self . B = np . asarray ( B , dtype = self . dtype )
if B is not None or not hasattr ( self , 'Gamma' ) :
self . Gamma , self . Q = np . linalg . eigh ( self . B . T . dot ( self . B ) )
self . Gamma = np . abs ( ... |
def values_list ( self , * fields , ** kwargs ) :
"""Ask the collection to return a list of tuples of given fields ( in the
given order ) for each instance found in the collection .
If ' flat = True ' is passed , the resulting list will be flat , ie without
tuple . It ' s a valid kwarg only if only one field ... | flat = kwargs . pop ( 'flat' , False )
if kwargs :
raise ValueError ( 'Unexpected keyword arguments for the values method: %s' % list ( kwargs ) )
if not fields :
fields = self . _get_simple_fields ( )
if flat and len ( fields ) > 1 :
raise ValueError ( "'flat' is not valid when values is called with more t... |
def _add_unknown_char ( self , string ) :
'''Adds an unknown character to the stack .''' | if self . has_xvowel : # Ensure an xvowel gets printed if we ' ve got an active
# one right now .
self . _promote_solitary_xvowel ( )
self . unknown_char = string
self . _flush_char ( ) |
def _get_hosts_from_names ( self , names ) :
"""validate hostnames from a list of names""" | result = set ( )
hosts = map ( lambda x : x . strip ( ) , names . split ( ',' ) )
for h in hosts :
if valid_hostname ( h . split ( ':' ) [ 0 ] ) :
result . add ( h if ':' in h else '%s:%d' % ( h , self . PORT ) )
else :
raise conferr ( 'Invalid hostname: %s' % h . split ( ':' ) [ 0 ] )
return li... |
def get_dssp_annotations_parallelize ( self , sc , representatives_only = True , force_rerun = False ) :
"""Run DSSP on structures and store calculations .
Annotations are stored in the protein structure ' s chain sequence at :
` ` < chain _ prop > . seq _ record . letter _ annotations [ ' * - dssp ' ] ` `
Ar... | genes_rdd = sc . parallelize ( self . genes )
def get_dssp_annotation ( g ) :
g . protein . get_dssp_annotations ( representative_only = representatives_only , force_rerun = force_rerun )
return g
result = genes_rdd . map ( get_dssp_annotation ) . collect ( )
for modified_g in result :
original_gene = self ... |
def get_perm_names ( cls , resource ) :
"""Return all permissions supported by the resource .
This is used for auto - generating missing permissions rows into
database in syncdb .""" | return [ cls . get_perm_name ( resource , method ) for method in cls . METHODS ] |
def name_to_object ( repo , name , return_ref = False ) :
""": return : object specified by the given name , hexshas ( short and long )
as well as references are supported
: param return _ ref : if name specifies a reference , we will return the reference
instead of the object . Otherwise it will raise BadObj... | hexsha = None
# is it a hexsha ? Try the most common ones , which is 7 to 40
if repo . re_hexsha_shortened . match ( name ) :
if len ( name ) != 40 : # find long sha for short sha
hexsha = short_to_long ( repo . odb , name )
else :
hexsha = name
# END handle short shas
# END find sha if it m... |
def get_all_modified_on ( chebi_ids ) :
'''Returns all modified on''' | all_modified_ons = [ get_modified_on ( chebi_id ) for chebi_id in chebi_ids ]
all_modified_ons = [ modified_on for modified_on in all_modified_ons if modified_on is not None ]
return None if len ( all_modified_ons ) == 0 else sorted ( all_modified_ons ) [ - 1 ] |
def _mouseUp ( x , y , button ) :
"""Send the mouse up event to Windows by calling the mouse _ event ( ) win32
function .
Args :
x ( int ) : The x position of the mouse event .
y ( int ) : The y position of the mouse event .
button ( str ) : The mouse button , either ' left ' , ' middle ' , or ' right '
... | if button == 'left' :
try :
_sendMouseEvent ( MOUSEEVENTF_LEFTUP , x , y )
except ( PermissionError , OSError ) : # TODO : We need to figure out how to prevent these errors , see https : / / github . com / asweigart / pyautogui / issues / 60
pass
elif button == 'middle' :
try :
_send... |
def _split_string_to_tokens ( text ) :
"""Splits text to a list of string tokens .""" | if not text :
return [ ]
ret = [ ]
token_start = 0
# Classify each character in the input string
is_alnum = [ c in _ALPHANUMERIC_CHAR_SET for c in text ]
for pos in xrange ( 1 , len ( text ) ) :
if is_alnum [ pos ] != is_alnum [ pos - 1 ] :
token = text [ token_start : pos ]
if token != u" " or ... |
def make_user_list ( self , emails , usernames ) :
"""Given a list of emails and usernames fetch DukeDS user info .
Parameters that are None will be skipped .
: param emails : [ str ] : list of emails ( can be null )
: param usernames : [ str ] : list of usernames ( netid )
: return : [ RemoteUser ] : detai... | to_users = [ ]
remaining_emails = [ ] if not emails else list ( emails )
remaining_usernames = [ ] if not usernames else list ( usernames )
for user in self . remote_store . fetch_users ( ) :
if user . email in remaining_emails :
to_users . append ( user )
remaining_emails . remove ( user . email )
... |
def overloaded_constants ( type_ , __doc__ = None ) :
"""A factory for transformers that apply functions to literals .
Parameters
type _ : type
The type to overload .
_ _ doc _ _ : str , optional
Docstring for the generated transformer .
Returns
transformer : subclass of CodeTransformer
A new code t... | typename = type_ . __name__
if typename . endswith ( 'x' ) :
typename += 'es'
elif not typename . endswith ( 's' ) :
typename += 's'
if __doc__ is None :
__doc__ = _format_constant_docstring ( type_ )
return type ( "overloaded_" + typename , ( _ConstantTransformerBase , ) , { '_type' : type_ , '__doc__' : _... |
def _generate_G_points ( self , kpoint ) :
"""Helper function to generate G - points based on nbmax .
This function iterates over possible G - point values and determines
if the energy is less than G _ { cut } . Valid values are appended to
the output array . This function should not be called outside of
in... | gpoints = [ ]
for i in range ( 2 * self . _nbmax [ 2 ] + 1 ) :
i3 = i - 2 * self . _nbmax [ 2 ] - 1 if i > self . _nbmax [ 2 ] else i
for j in range ( 2 * self . _nbmax [ 1 ] + 1 ) :
j2 = j - 2 * self . _nbmax [ 1 ] - 1 if j > self . _nbmax [ 1 ] else j
for k in range ( 2 * self . _nbmax [ 0 ] +... |
def run ( ** kwargs ) :
"""Start to run a strategy""" | config_path = kwargs . get ( 'config_path' , None )
if config_path is not None :
config_path = os . path . abspath ( config_path )
kwargs . pop ( 'config_path' )
if not kwargs . get ( 'base__securities' , None ) :
kwargs . pop ( 'base__securities' , None )
from rqalpha import main
source_code = kwargs . get... |
def alterar ( self , id_script , id_script_type , script , description , model = None ) :
"""Change Script from by the identifier .
: param id _ script : Identifier of the Script . Integer value and greater than zero .
: param id _ script _ type : Identifier of the Script Type . Integer value and greater than z... | if not is_valid_int_param ( id_script ) :
raise InvalidParameterError ( u'The identifier of Script is invalid or was not informed.' )
script_map = dict ( )
script_map [ 'id_script_type' ] = id_script_type
script_map [ 'script' ] = script
script_map [ 'model' ] = model
script_map [ 'description' ] = description
url ... |
def LOO ( self , kern , X , Y , likelihood , posterior , Y_metadata = None , K = None ) :
"""Leave one out error as found in
" Bayesian leave - one - out cross - validation approximations for Gaussian latent variable models "
Vehtari et al . 2014.""" | g = posterior . woodbury_vector
c = posterior . woodbury_inv
c_diag = np . diag ( c ) [ : , None ]
neg_log_marginal_LOO = 0.5 * np . log ( 2 * np . pi ) - 0.5 * np . log ( c_diag ) + 0.5 * ( g ** 2 ) / c_diag
# believe from Predictive Approaches for Choosing Hyperparameters in Gaussian Processes
# this is the negative ... |
def dump ( obj , fp ) :
'''Serialize an object representing the ARFF document to a given file - like
object .
: param obj : a dictionary .
: param fp : a file - like object .''' | encoder = ArffEncoder ( )
generator = encoder . iter_encode ( obj )
last_row = next ( generator )
for row in generator :
fp . write ( last_row + u'\n' )
last_row = row
fp . write ( last_row )
return fp |
async def delete ( self , * , reason = None ) :
"""| coro |
Deletes the custom emoji .
You must have : attr : ` ~ Permissions . manage _ emojis ` permission to
do this .
Parameters
reason : Optional [ : class : ` str ` ]
The reason for deleting this emoji . Shows up on the audit log .
Raises
Forbidd... | await self . _state . http . delete_custom_emoji ( self . guild . id , self . id , reason = reason ) |
def prepare ( args ) :
"""% prog prepare - - rearray _ lib = < rearraylibrary > - - orig _ lib _ file = < origlibfile >
Inferred file names
` lookuptblfile ` : rearraylibrary . lookup
` rearraylibfile ` : rearraylibrary . fasta
Pick sequences from the original library file and the rearrayed library file
b... | from operator import itemgetter
from jcvi . formats . fasta import Fasta , SeqIO
p = OptionParser ( prepare . __doc__ )
p . add_option ( "--rearray_lib" , default = None , help = "name of the rearrayed library [default: %default]" )
p . add_option ( "--orig_lib_file" , help = "fasta file containing reads from the origi... |
def changelog ( since , to , write , force ) :
"""Generates a markdown file containing the list of checks that changed for a
given Agent release . Agent version numbers are derived inspecting tags on
` integrations - core ` so running this tool might provide unexpected results
if the repo is not up to date wi... | agent_tags = get_agent_tags ( since , to )
# store the changes in a mapping { agent _ version - - > { check _ name - - > current _ version } }
changes_per_agent = OrderedDict ( )
# to keep indexing easy , we run the loop off - by - one
for i in range ( 1 , len ( agent_tags ) ) :
req_file_name = os . path . basename... |
def getkeypress ( self ) :
u'''Return next key press event from the queue , ignoring others .''' | ck = System . ConsoleKey
while 1 :
e = System . Console . ReadKey ( True )
if e . Key == System . ConsoleKey . PageDown : # PageDown
self . scroll_window ( 12 )
elif e . Key == System . ConsoleKey . PageUp : # PageUp
self . scroll_window ( - 12 )
elif str ( e . KeyChar ) == u"\000" : # D... |
def infos ( self ) :
""": py : class : ` OrbitInfos ` object of ` ` self ` `""" | if not hasattr ( self , '_infos' ) :
self . _infos = OrbitInfos ( self )
return self . _infos |
def list_members ( self , list_id ) :
"""List users in a list
: param list _ id : list ID number
: return : list of : class : ` ~ responsebot . models . User ` objects""" | return [ User ( user . _json ) for user in self . _client . list_members ( list_id = list_id ) ] |
def _get_pos ( self ) :
"""Get current position for scroll bar .""" | if self . _h >= len ( self . _options ) :
return 0
else :
return self . _start_line / ( len ( self . _options ) - self . _h ) |
def pick_kmersize ( fq ) :
"""pick an appropriate kmer size based off of https : / / www . biostars . org / p / 201474/
tl ; dr version : pick 31 unless the reads are very small , if not then guess
that readlength / 2 is about right .""" | if bam . is_bam ( fq ) :
readlength = bam . estimate_read_length ( fq )
else :
readlength = fastq . estimate_read_length ( fq )
halfread = int ( round ( readlength / 2 ) )
if halfread >= 31 :
kmersize = 31
else :
kmersize = halfread
if kmersize % 2 == 0 :
kmersize += 1
return kmersize |
def build_index ( self , idx_name , _type = 'default' ) :
"Build the index related to the ` name ` ." | indexes = { }
has_non_string_values = False
for key , item in self . data . items ( ) :
if idx_name in item :
value = item [ idx_name ]
# A non - string index value switches it into a lazy one .
if not isinstance ( value , six . string_types ) :
has_non_string_values = True
... |
def dmgprof_misinc_stats ( self , dict_to_plot , readend , substitution ) :
"""Take the parsed stats from the DamageProfiler and add it to the
basic stats table at the top of the report""" | headers = OrderedDict ( )
headers [ '{}1' . format ( readend ) ] = { 'id' : 'misinc-stats-1st-{}-{}' . format ( readend , substitution ) , 'title' : '{} {} 1st base' . format ( readend , substitution ) , 'description' : '{} 1st base substitution frequency for {}' . format ( readend , substitution ) , 'max' : 100 , 'min... |
def initial_edges ( self ) -> iter :
"""Yield edges in the initial ( uncompressed ) graphs . Possible doublons .""" | nodes_in = lambda n : ( [ n ] if self . is_node ( n ) else self . nodes_in ( n ) )
for node , succs in self . edges . items ( ) :
twos = tuple ( two for succ in succs for two in nodes_in ( succ ) )
for one in nodes_in ( node ) :
for two in twos :
yield one , two |
def authnkey ( self ) -> dict :
"""Accessor for public keys marked as authentication keys , by identifier .""" | return { k : self . _pubkey [ k ] for k in self . _pubkey if self . _pubkey [ k ] . authn } |
def tryMatchedAnchor ( self , block , autoIndent ) :
"""find out whether we pressed return in something like { } or ( ) or [ ] and indent properly :
becomes :""" | oposite = { ')' : '(' , '}' : '{' , ']' : '[' }
char = self . _firstNonSpaceChar ( block )
if not char in oposite . keys ( ) :
return None
# we pressed enter in e . g . ( )
try :
foundBlock , foundColumn = self . findBracketBackward ( block , 0 , oposite [ char ] )
except ValueError :
return None
if autoInd... |
def data ( value ) :
"""list or KeyedList of ` ` Data ` ` : Data definitions
This defines the data being visualized . See the : class : ` Data ` class
for details .""" | for i , entry in enumerate ( value ) :
_assert_is_type ( 'data[{0}]' . format ( i ) , entry , Data ) |
def cmd ( send , msg , args ) :
"""Searches tumblr
Syntax : { command } < blogname > < - - submit content | - - random >""" | parser = arguments . ArgParser ( args [ 'config' ] )
parser . add_argument ( 'blogname' , action = arguments . TumblrParser )
group = parser . add_mutually_exclusive_group ( )
group . add_argument ( '--submit' , nargs = '*' )
group . add_argument ( '--random' , action = 'store_true' )
try :
cmdargs = parser . parse... |
def per_implementation_data ( self ) :
"""Return download data by python impelementation name and version .
: return : dict of cache data ; keys are datetime objects , values are
dict of implementation name / version ( str ) to count ( int ) .
: rtype : dict""" | ret = { }
for cache_date in self . cache_dates :
data = self . _cache_get ( cache_date )
ret [ cache_date ] = { }
for impl_name , impl_data in data [ 'by_implementation' ] . items ( ) :
for impl_ver , count in impl_data . items ( ) :
k = self . _compound_column_value ( impl_name , self .... |
def create_notifications ( self , n_type , notification_period , hosts , services , t_wished = None , author_data = None ) :
"""Create a " master " notification here , which will later
( immediately before the reactionner gets it ) be split up
in many " child " notifications , one for each contact .
: param n... | cls = self . __class__
# t _ wished = = None for the first notification launch after consume
# here we must look at the self . notification _ period
if t_wished is None :
t_wished = time . time ( )
# if first notification , we must add first _ notification _ delay
if self . current_notification_number == 0 ... |
def has_role ( self , role ) :
"""Check if a person has a given role within its : any : ` GroupEntity `
Example :
> > > person . has _ role ( Household . CHILD )
> > > array ( [ False ] )""" | self . entity . check_role_validity ( role )
group_population = self . simulation . get_population ( role . entity . plural )
if role . subroles :
return np . logical_or . reduce ( [ group_population . members_role == subrole for subrole in role . subroles ] )
else :
return group_population . members_role == ro... |
async def _setops ( self , name , valu , editatom , init = False ) :
'''Generate operations to set a property on a node .''' | prop = self . form . prop ( name )
if prop is None :
if self . snap . strict :
raise s_exc . NoSuchProp ( name = name )
await self . snap . warn ( f'NoSuchProp: name={name}' )
return False
if self . isrunt :
if prop . info . get ( 'ro' ) :
raise s_exc . IsRuntForm ( mesg = 'Cannot set re... |
def rename ( self , data , variables = None ) :
"""Renames the columns according the variable mapping .
Parameters
data : DataFrame
variables : None or dict , default None
If None , uses self . variables
Returns
data : DataFrame
Renamed data .""" | if variables is None :
variables = self . variables
return data . rename ( columns = { y : x for x , y in variables . items ( ) } ) |
def trans_coeff ( eq , x , y , z ) :
"""This function is provided by MOKA2 Development Team ( 1996 . xx . xx )
and used in SOSS system .""" | tt = ( eq - 2000.0 ) / 100.0
zeta = 2306.2181 * tt + 0.30188 * tt * tt + 0.017998 * tt * tt * tt
zetto = 2306.2181 * tt + 1.09468 * tt * tt + 0.018203 * tt * tt * tt
theta = 2004.3109 * tt - 0.42665 * tt * tt - 0.041833 * tt * tt * tt
zeta = math . radians ( zeta ) / 3600.0
zetto = math . radians ( zetto ) / 3600.0
the... |
def parse_example_tensor ( examples , train_config , keep_target ) :
"""Read the csv files .
Args :
examples : string tensor
train _ config : training config
keep _ target : if true , the target column is expected to exist and it is
returned in the features dict .
Returns :
Dict of feature _ name to t... | csv_header = [ ]
if keep_target :
csv_header = train_config [ 'csv_header' ]
else :
csv_header = [ name for name in train_config [ 'csv_header' ] if name != train_config [ 'target_column' ] ]
# record _ defaults are used by tf . decode _ csv to insert defaults , and to infer
# the datatype .
record_defaults = [... |
def handle_decode_replace ( e ) :
"""this handles replacing bad characters when printing out
http : / / www . programcreek . com / python / example / 3643 / codecs . register _ error
http : / / bioportal . weizmann . ac . il / course / python / PyMOTW / PyMOTW / docs / codecs / index . html
https : / / pymotw... | count = e . end - e . start
# return " . " * count , e . end
global ENCODING_REPLACE_CHAR
return ENCODING_REPLACE_CHAR * count , e . end |
def subdomain_try_insert ( self , cursor , subdomain_rec , history_neighbors ) :
"""Try to insert a subdomain record into its history neighbors .
This is an optimization that handles the " usual " case .
We can do this without having to rewrite this subdomain ' s past and future
if ( 1 ) we can find a previou... | blockchain_order = history_neighbors [ 'prev' ] + history_neighbors [ 'cur' ] + history_neighbors [ 'fut' ]
last_accepted = - 1
for i in range ( 0 , len ( blockchain_order ) ) :
if blockchain_order [ i ] . accepted :
last_accepted = i
break
if blockchain_order [ i ] . n > subdomain_rec . n or ( ... |
def call_servo ( examples , serving_bundle ) :
"""Send an RPC request to the Servomatic prediction service .
Args :
examples : A list of examples that matches the model spec .
serving _ bundle : A ` ServingBundle ` object that contains the information to
make the serving request .
Returns :
A Classifica... | parsed_url = urlparse ( 'http://' + serving_bundle . inference_address )
channel = implementations . insecure_channel ( parsed_url . hostname , parsed_url . port )
stub = prediction_service_pb2 . beta_create_PredictionService_stub ( channel )
if serving_bundle . use_predict :
request = predict_pb2 . PredictRequest ... |
def dump ( self ) -> dict :
"""Dumps data from the ConfigKey into a dict .
: return : The keys and values from the ConfigKey encapsulated in a dict .""" | d = { }
for item in self . __dict__ :
if item in [ 'parsed' , 'dump' , 'parse_data' , 'iter_list' , 'safe_load' ] :
continue
if isinstance ( self . __dict__ [ item ] , ConfigKey ) :
d [ item ] = self . __dict__ [ item ] . dump ( )
elif isinstance ( self . __dict__ [ item ] , list ) :
... |
def put ( request , obj_id = None ) :
"""Adds tags from objects resolved from guids
: param tags : Tags to add
: type tags : list
: param guids : Guids to add tags from
: type guids : list
: returns : json""" | res = Result ( )
data = request . PUT or json . loads ( request . body ) [ 'body' ]
if obj_id : # - - Edit the tag
tag = Tag . objects . get ( pk = obj_id )
tag . name = data . get ( 'name' , tag . name )
tag . artist = data . get ( 'artist' , tag . artist )
tag . save ( )
else :
tags = [ _ for _ in... |
def getDuration ( self ) :
"""Returns the time in minutes taken for this analysis .
If the analysis is not yet ' ready to process ' , returns 0
If the analysis is still in progress ( not yet verified ) ,
duration = date _ verified - date _ start _ process
Otherwise :
duration = current _ datetime - date _... | starttime = self . getStartProcessDate ( )
if not starttime : # The analysis is not yet ready to be processed
return 0
endtime = self . getDateVerified ( ) or DateTime ( )
# Duration in minutes
duration = ( endtime - starttime ) * 24 * 60
return duration |
def destination ( globs , locator , distance , bearing ) :
"""Calculate destination from locations .""" | globs . locations . destination ( distance , bearing , locator ) |
def cmalign_from_file ( cm_file_path , seqs , moltype = DNA , alignment_file_path = None , include_aln = False , return_stdout = False , params = None ) :
"""Uses cmalign to align seqs to alignment in cm _ file _ path .
- cm _ file _ path : path to the file created by cmbuild , containing aligned
sequences . Th... | # NOTE : Must degap seqs or Infernal well seg fault !
seqs = SequenceCollection ( seqs , MolType = moltype ) . degap ( )
# Create mapping between abbreviated IDs and full IDs
int_map , int_keys = seqs . getIntMap ( )
# Create SequenceCollection from int _ map .
int_map = SequenceCollection ( int_map , MolType = moltype... |
def _post_create ( atdepth , entry , result ) :
"""Finishes the entry logging if applicable .""" | if not atdepth and entry is not None :
if result is not None : # We need to get these results a UUID that will be saved so that any
# instance methods applied to this object has a parent to refer to .
retid = _tracker_str ( result )
entry [ "r" ] = retid
ekey = retid
else : # pragma ... |
def run_path ( path_name , init_globals = None , run_name = None ) :
"""Execute code located at the specified filesystem location
Returns the resulting top level namespace dictionary
The file path may refer directly to a Python script ( i . e .
one that could be directly executed with execfile ) or else
it ... | if run_name is None :
run_name = "<run_path>"
importer = _get_importer ( path_name )
if isinstance ( importer , imp . NullImporter ) : # Not a valid sys . path entry , so run the code directly
# execfile ( ) doesn ' t help as we want to allow compiled files
code = _get_code_from_file ( path_name )
return _r... |
def elekta_icon_space ( shape = ( 448 , 448 , 448 ) , ** kwargs ) :
"""Default reconstruction space for the Elekta Icon CBCT .
See the [ whitepaper ] _ for further information .
Parameters
shape : sequence of int , optional
Shape of the space , in voxels .
kwargs :
Keyword arguments to pass to ` uniform... | if 'dtype' not in kwargs :
kwargs [ 'dtype' ] = 'float32'
return odl . uniform_discr ( min_pt = [ - 112.0 , - 112.0 , 0.0 ] , max_pt = [ 112.0 , 112.0 , 224.0 ] , shape = shape , ** kwargs ) |
def write_unitth ( suites , out_dir ) :
"""Write UnitTH - style test reports
Args :
suites ( : obj : ` dict ` ) : dictionary of test suites
out _ dir ( : obj : ` str ` ) : path to save UnitTH - style test reports""" | if not os . path . isdir ( out_dir ) :
os . mkdir ( out_dir )
for classname , cases in suites . items ( ) :
doc_xml = minidom . Document ( )
suite_xml = doc_xml . createElement ( 'testsuite' )
suite_xml . setAttribute ( 'name' , classname )
suite_xml . setAttribute ( 'tests' , str ( len ( cases ) ) ... |
def _should_skip_entry ( self , entry ) :
"""Determine if this oplog entry should be skipped .
This has the possible side effect of modifying the entry ' s namespace
and filtering fields from updates and inserts .""" | # Don ' t replicate entries resulting from chunk moves
if entry . get ( "fromMigrate" ) :
return True , False
# Ignore no - ops
if entry [ "op" ] == "n" :
return True , False
ns = entry [ "ns" ]
if "." not in ns :
return True , False
coll = ns . split ( "." , 1 ) [ 1 ]
# Ignore system collections
if coll . ... |
def exp ( self ) :
"""Returns the exponent of the quaternion .
( not tested )""" | # Init
vecNorm = self . x ** 2 + self . y ** 2 + self . z ** 2
wPart = np . exp ( self . w )
q = Quaternion ( )
# Calculate
q . w = wPart * np . cos ( vecNorm )
q . x = wPart * self . x * np . sin ( vecNorm ) / vecNorm
q . y = wPart * self . y * np . sin ( vecNorm ) / vecNorm
q . z = wPart * self . z * np . sin ( vecNo... |
def redeem_bitstamp_code ( self , code ) :
"""Returns JSON dictionary containing USD and BTC amount added to user ' s
account .""" | data = { 'code' : code }
return self . _post ( "redeem_code/" , data = data , return_json = True , version = 1 ) |
def fastaIterator ( fastaFN ) :
'''Iterator that yields tuples containing a sequence label and the sequence itself
@ param fastaFN - the FASTA filename to open and parse
@ return - an iterator yielding tuples of the form ( label , sequence ) from the FASTA file''' | if fastaFN [ len ( fastaFN ) - 3 : ] == '.gz' :
fp = gzip . open ( fastaFN , 'r' )
else :
fp = open ( fastaFN , 'r' )
label = ''
segments = [ ]
line = ''
for line in fp :
if line [ 0 ] == '>' :
if label != '' :
yield ( label , '' . join ( segments ) )
label = ( line . strip ( '\n... |
def json_traceback ( error_msg = None ) :
"""Generate a stack trace as a JSON - formatted error message .
Optionally use error _ msg as the error field .
Return { ' error ' : . . . , ' traceback ' . . . }""" | exception_data = traceback . format_exc ( ) . splitlines ( )
if error_msg is None :
error_msg = '\n' . join ( exception_data )
else :
error_msg = 'Remote RPC error: {}' . format ( error_msg )
return { 'error' : error_msg , 'traceback' : exception_data } |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.