signature stringlengths 29 44.1k | implementation stringlengths 0 85.2k |
|---|---|
def current_frame ( self ) :
"""Compute the number of the current frame ( 0 - indexed )""" | if not self . _pause_level :
return ( int ( ( self . _clock ( ) + self . _offset ) * self . frames_per_second ) % len ( self . _frames ) )
else :
return self . _paused_frame |
def _strip ( string , pattern ) :
"""Return complement of pattern in string""" | m = re . compile ( pattern ) . search ( string )
if m :
return string [ 0 : m . start ( ) ] + string [ m . end ( ) : len ( string ) ]
else :
return string |
def write_versions ( dirs , config = None , is_wrapper = False ) :
"""Write CSV file with versions used in analysis pipeline .""" | out_file = _get_program_file ( dirs )
if is_wrapper :
assert utils . file_exists ( out_file ) , "Failed to create program versions from VM"
elif out_file is None :
for p in _get_versions ( config ) :
print ( "{program},{version}" . format ( ** p ) )
else :
with open ( out_file , "w" ) as out_handle ... |
def to_dict ( self ) :
"""Render a MessageElement as python dict .
: return : Python dict representation
: rtype : dict""" | return { 'type' : self . __class__ . __name__ , 'element_id' : self . element_id , 'style_class' : self . style_class , 'icon' : self . icon , 'attributes' : self . attributes } |
def _depth_to_seq2cov ( input_fpath , output_fpath , sample_name ) :
"""Args :
input _ fpath : output of " mosdepth " :
chr22 14250 15500 name3 5.54
chrM 100 1000 name1 916.08
output _ fpath : path to write results - input for Seq2C ' s cov2lr . pl , e . g . :
seq2cov :
chr20 _ tumor _ 1 DEFB125 chr20 6... | # First round : collecting gene ends
gene_end_by_gene = defaultdict ( lambda : - 1 )
with utils . open_gzipsafe ( input_fpath ) as f :
for xs in ( l . rstrip ( ) . split ( ) for l in f if not l . startswith ( "#" ) ) :
xs = [ x for x in xs if x . strip ( ) ]
if any ( x == "." for x in xs ) :
... |
def select2 ( self , box , drop , text ) :
''': param box : the locator for Selection Box
: param drop : the locator for Selection Dropdown
: param text : the text value to select or the index of the option to select
: return : True
: example : https : / / github . com / ldiary / marigoso / blob / master / ... | if not self . is_available ( drop ) :
if isinstance ( box , str ) :
self . get_element ( box ) . click ( )
else :
box . click ( )
ul_dropdown = self . get_element ( drop )
options = ul_dropdown . get_children ( 'tag=li' )
if isinstance ( text , int ) :
options [ text ] . click ( )
return... |
def add_subprocess_to_diagram ( self , process_id , subprocess_name , is_expanded = False , triggered_by_event = False , node_id = None ) :
"""Adds a SubProcess element to BPMN diagram .
User - defined attributes :
- name
- triggered _ by _ event
: param process _ id : string object . ID of parent process ,... | subprocess_id , subprocess = self . add_flow_node_to_diagram ( process_id , consts . Consts . subprocess , subprocess_name , node_id )
self . diagram_graph . node [ subprocess_id ] [ consts . Consts . is_expanded ] = "true" if is_expanded else "false"
self . diagram_graph . node [ subprocess_id ] [ consts . Consts . tr... |
def is_stopped ( self , * args , ** kwargs ) :
"""Return whether this container is stopped""" | kwargs [ "waiting" ] = False
return self . wait_till_stopped ( * args , ** kwargs ) |
def to_html ( doc , output = "/tmp" , style = "dep" ) :
"""Doc method extension for saving the current state as a displaCy
visualization .""" | # generate filename from first six non - punct tokens
file_name = "-" . join ( [ w . text for w in doc [ : 6 ] if not w . is_punct ] ) + ".html"
html = displacy . render ( doc , style = style , page = True )
# render markup
if output is not None :
output_path = Path ( output )
if not output_path . exists ( ) :
... |
def task ( self , func , * args , ** kwargs ) :
"""Pushes a task onto the queue ( with the specified options ) .
This will instantiate a ` ` Gator . task _ class ` ` instance , configure the
task execution options , configure the callable & its arguments , then
push it onto the queue .
You ' ll typically ca... | task = self . gator . task_class ( ** self . task_kwargs )
return self . gator . push ( task , func , * args , ** kwargs ) |
def write ( self , oprot ) :
'''Write this object to the given output protocol and return self .
: type oprot : thryft . protocol . _ output _ protocol . _ OutputProtocol
: rtype : pastpy . gen . database . impl . dbf . dbf _ database _ configuration . DbfDatabaseConfiguration''' | oprot . write_struct_begin ( 'DbfDatabaseConfiguration' )
if self . pp_images_dir_path is not None :
oprot . write_field_begin ( name = 'pp_images_dir_path' , type = 11 , id = None )
oprot . write_string ( self . pp_images_dir_path )
oprot . write_field_end ( )
if self . pp_install_dir_path is not None :
... |
def _load_all ( self ) :
'''Load all of them''' | with self . _lock :
for name in self . file_mapping :
if name in self . loaded_files or name in self . missing_modules :
continue
self . _load_module ( name )
self . loaded = True |
def _get_hierarchy ( cls ) :
"""Internal helper to return the list of polymorphic base classes .
This returns a list of class objects , e . g . [ Animal , Feline , Cat ] .""" | bases = [ ]
for base in cls . mro ( ) : # pragma : no branch
if hasattr ( base , '_get_hierarchy' ) :
bases . append ( base )
del bases [ - 1 ]
# Delete PolyModel itself
bases . reverse ( )
return bases |
def tickets ( self , extra_params = None ) :
"""All Tickets which are a part of this Milestone""" | return filter ( lambda ticket : ticket . get ( 'milestone_id' , None ) == self [ 'id' ] , self . space . tickets ( extra_params = extra_params ) ) |
def js_exec ( self , method : str , * args : Union [ int , str , bool ] ) -> None :
"""Execute ` ` method ` ` in the related node on browser .
Other keyword arguments are passed to ` ` params ` ` attribute .
If this node is not in any document tree ( namely , this node does not
have parent node ) , the ` ` me... | if self . connected :
self . ws_send ( dict ( method = method , params = args ) ) |
def push_concurrency_history_item ( self , state , number_concurrent_threads ) :
"""Adds a new concurrency - history - item to the history item list
A concurrent history item stores information about the point in time where a certain number of states is
launched concurrently
( e . g . in a barrier concurrency... | last_history_item = self . get_last_history_item ( )
return_item = ConcurrencyItem ( state , self . get_last_history_item ( ) , number_concurrent_threads , state . run_id , self . execution_history_storage )
return self . _push_item ( last_history_item , return_item ) |
def get_event_with_balance_proof_by_balance_hash ( storage : sqlite . SQLiteStorage , canonical_identifier : CanonicalIdentifier , balance_hash : BalanceHash , ) -> sqlite . EventRecord :
"""Returns the event which contains the corresponding balance
proof .
Use this function to find a balance proof for a call t... | return storage . get_latest_event_by_data_field ( { 'balance_proof.canonical_identifier.chain_identifier' : str ( canonical_identifier . chain_identifier , ) , 'balance_proof.canonical_identifier.token_network_address' : to_checksum_address ( canonical_identifier . token_network_address , ) , 'balance_proof.canonical_i... |
def _flush ( self ) :
"""Returns a list of all current data""" | if self . _recording :
raise Exception ( "Cannot flush data queue while recording!" )
if self . _saving_cache :
logging . warn ( "Flush when using cache means unsaved data will be lost and not returned!" )
self . _cmds_q . put ( ( "reset_data_segment" , ) )
else :
data = self . _extract_q ( 0 )
retu... |
def glow_hparams ( ) :
"""Glow Hparams .""" | hparams = common_hparams . basic_params1 ( )
hparams . clip_grad_norm = None
hparams . weight_decay = 0.0
hparams . learning_rate_constant = 3e-4
hparams . batch_size = 32
# can be prev _ level , prev _ step or normal .
# see : glow _ ops . merge _ level _ and _ latent _ dist
hparams . add_hparam ( "level_scale" , "pre... |
def get_manager ( self , identity ) :
"""Given the identity return a HPEManager object
: param identity : The identity of the Manager resource
: returns : The Manager object""" | return manager . HPEManager ( self . _conn , identity , redfish_version = self . redfish_version ) |
def fixed ( self ) :
"""Returns a list of just the fixed source roots in the trie .""" | for key , child in self . _root . children . items ( ) :
if key == '^' :
return list ( child . subpatterns ( ) )
return [ ] |
def get_top_level_indicator_node ( root_node ) :
"""This returns the first top level Indicator node under the criteria node .
: param root _ node : Root node of an etree .
: return : an elementTree Element item , or None if no item is found .""" | if root_node . tag != 'OpenIOC' :
raise IOCParseError ( 'Root tag is not "OpenIOC" [{}].' . format ( root_node . tag ) )
elems = root_node . xpath ( 'criteria/Indicator' )
if len ( elems ) == 0 :
log . warning ( 'No top level Indicator node found.' )
return None
elif len ( elems ) > 1 :
log . warning ( ... |
def get_cpu_property ( self , property_p ) :
"""Returns the virtual CPU boolean value of the specified property .
in property _ p of type : class : ` CPUPropertyType `
Property type to query .
return value of type bool
Property value .
raises : class : ` OleErrorInvalidarg `
Invalid property .""" | if not isinstance ( property_p , CPUPropertyType ) :
raise TypeError ( "property_p can only be an instance of type CPUPropertyType" )
value = self . _call ( "getCPUProperty" , in_p = [ property_p ] )
return value |
def schedule ( code , interval , secret_key = None , url = None ) :
"""Schedule a string of ` code ` to be executed every ` interval `
Specificying an ` interval ` of 0 indicates the event should only be run
one time and will not be rescheduled .""" | if not secret_key :
secret_key = default_key ( )
if not url :
url = default_url ( )
url = '%s/schedule' % url
values = { 'interval' : interval , 'code' : code , }
return _send_with_auth ( values , secret_key , url ) |
def get_api_group ( self , ** kwargs ) :
"""get information of a group
This method makes a synchronous HTTP request by default . To make an
asynchronous HTTP request , please pass async _ req = True
> > > thread = api . get _ api _ group ( async _ req = True )
> > > result = thread . get ( )
: param async... | kwargs [ '_return_http_data_only' ] = True
if kwargs . get ( 'async_req' ) :
return self . get_api_group_with_http_info ( ** kwargs )
else :
( data ) = self . get_api_group_with_http_info ( ** kwargs )
return data |
def get_profiles ( self , profile_base = "/data/b2g/mozilla" , timeout = None ) :
"""Return a list of paths to gecko profiles on the device ,
: param timeout : Timeout of each adb command run
: param profile _ base : Base directory containing the profiles . ini file""" | rv = { }
if timeout is None :
timeout = self . _timeout
profile_path = posixpath . join ( profile_base , "profiles.ini" )
try :
proc = self . shell ( "cat %s" % profile_path , timeout = timeout )
config = ConfigParser . ConfigParser ( )
config . readfp ( proc . stdout_file )
for section in config . ... |
def find_by_tag ( self , tag , params = { } , ** options ) :
"""Returns the compact task records for all tasks with the given tag .
Parameters
tag : { Id } The tag in which to search for tasks .
[ params ] : { Object } Parameters for the request""" | path = "/tags/%s/tasks" % ( tag )
return self . client . get_collection ( path , params , ** options ) |
def _to_bytes ( self , data ) :
"""Normalize a text data to bytes ( type ` bytes ` ) so that the go bindings can
handle it easily .""" | # TODO : On Python 3 , move this ` if ` line to the ` except ` branch
# as the common case will indeed no longer be bytes .
if not isinstance ( data , bytes ) :
try :
return data . encode ( 'utf-8' )
except Exception :
return None
return data |
def calc_uvw ( sdmfile , scan = 0 , datetime = 0 , radec = ( ) ) :
"""Calculates and returns uvw in meters for a given SDM , time , and pointing direction .
sdmfile is path to sdm directory that includes " Station . xml " file .
scan is scan number defined by observatory .
datetime is time ( as string ) to ca... | # set up CASA tools
try :
import casautil
except ImportError :
try :
import pwkit . environments . casa . util as casautil
except ImportError :
logger . info ( 'Cannot find pwkit/casautil. No calc_uvw possible.' )
return
me = casautil . tools . measures ( )
qa = casautil . tools . qu... |
def chunk ( seq , n ) : # http : / / stackoverflow . com / a / 312464/190597 ( Ned Batchelder )
"""Yield successive n - sized chunks from seq .""" | for i in range ( 0 , len ( seq ) , n ) :
yield seq [ i : i + n ] |
def destroy ( self ) :
"""destroy the server .""" | logger . info ( "destroying server" )
if self . library :
self . library . Srv_Destroy ( ctypes . byref ( self . pointer ) ) |
def BindVar ( self , var_id , value ) :
"""Associates a value with given variable .
This can be called multiple times to associate multiple values .
Args :
var _ id : A variable id to bind the values to .
value : A value to bind to the specified variable .
Raises :
KeyError : If given variable is not sp... | if var_id not in self . _vars :
raise KeyError ( var_id )
self . _var_bindings [ var_id ] . append ( value ) |
def register_entity ( self , entity_value , entity_type , alias_of = None ) :
"""Register an entity to be tagged in potential parse results
Args :
entity _ value ( str ) : the value / proper name of an entity instance ( Ex : " The Big Bang Theory " )
entity _ type ( str ) : the type / tag of an entity instanc... | if alias_of :
self . trie . insert ( entity_value . lower ( ) , data = ( alias_of , entity_type ) )
else :
self . trie . insert ( entity_value . lower ( ) , data = ( entity_value , entity_type ) )
self . trie . insert ( entity_type . lower ( ) , data = ( entity_type , 'Concept' ) ) |
def _sort_text ( definition ) :
"""Ensure builtins appear at the bottom .
Description is of format < type > : < module > . < item >""" | # If its ' hidden ' , put it next last
prefix = 'z{}' if definition . name . startswith ( '_' ) else 'a{}'
return prefix . format ( definition . name ) |
def tsqr ( a ) :
"""Perform a QR decomposition of a tall - skinny matrix .
Args :
a : A distributed matrix with shape MxN ( suppose K = min ( M , N ) ) .
Returns :
A tuple of q ( a DistArray ) and r ( a numpy array ) satisfying the
following .
- If q _ full = ray . get ( DistArray , q ) . assemble ( ) ,... | if len ( a . shape ) != 2 :
raise Exception ( "tsqr requires len(a.shape) == 2, but a.shape is " "{}" . format ( a . shape ) )
if a . num_blocks [ 1 ] != 1 :
raise Exception ( "tsqr requires a.num_blocks[1] == 1, but a.num_blocks " "is {}" . format ( a . num_blocks ) )
num_blocks = a . num_blocks [ 0 ]
K = int ... |
def encrypt ( self , serialized ) :
"""Encrypts the serialized message using Fernet
: param serialized : the serialized object to encrypt
: type serialized : bytes
: returns : an encrypted bytes returned by Fernet""" | fernet = Fernet ( self . encryption_cipher_key )
return fernet . encrypt ( serialized ) |
def p_if_statement_1 ( self , p ) :
"""if _ statement : IF LPAREN expr RPAREN statement""" | p [ 0 ] = ast . If ( predicate = p [ 3 ] , consequent = p [ 5 ] ) |
def approvewitness ( ctx , witnesses , account ) :
"""Approve witness ( es )""" | print_tx ( ctx . bitshares . approvewitness ( witnesses , account = account ) ) |
def assert_valid_sdl_extension ( document_ast : DocumentNode , schema : GraphQLSchema ) -> None :
"""Assert document is a valid SDL extension .
Utility function which asserts a SDL document is valid by throwing an error if it
is invalid .""" | errors = validate_sdl ( document_ast , schema )
if errors :
raise TypeError ( "\n\n" . join ( error . message for error in errors ) ) |
def srbt ( peer , pkts , inter = 0.1 , * args , ** kargs ) :
"""send and receive using a bluetooth socket""" | s = conf . BTsocket ( peer = peer )
a , b = sndrcv ( s , pkts , inter = inter , * args , ** kargs )
s . close ( )
return a , b |
def _load_neighbors_from_external_source ( self ) -> None :
"""Loads the neighbors of the node from the igraph ` Graph ` instance that is
wrapped by the graph that has this node .""" | graph : IGraphWrapper = self . _graph
ig_vertex : IGraphVertex = graph . wrapped_graph . vs [ self . _igraph_index ]
ig_neighbors : List [ IGraphVertex ] = ig_vertex . neighbors ( )
for ig_neighbor in ig_neighbors :
try :
name : str = ig_neighbor [ "name" ]
except KeyError :
name : str = str ( i... |
def step1 ( self , username , password ) :
"""First authentication step .""" | self . _check_initialized ( )
context = AtvSRPContext ( str ( username ) , str ( password ) , prime = constants . PRIME_2048 , generator = constants . PRIME_2048_GEN )
self . session = SRPClientSession ( context , binascii . hexlify ( self . _auth_private ) . decode ( ) ) |
def explain ( self ) :
"""Returns an explain plan record for this cursor .
. . mongodoc : : explain""" | clone = self . _clone ( deepcopy = True , base = Cursor ( self . collection ) )
return clone . explain ( ) |
def get_google_token ( account_email , oauth_client_id , oauth_redirect_uri , oauth_scope , account_password = None , account_otp_secret = None , ** kwargs ) :
""": param account _ email : ( REQUIRED )
: param oauth _ client _ id : ( REQUIRED )
: param oauth _ redirect _ uri : ( REQUIRED )
: param oauth _ sco... | items = { "account_email" : account_email , "oauth_client_id" : oauth_client_id , "oauth_redirect_uri" : oauth_redirect_uri , "oauth_scope" : oauth_scope , "account_password" : account_password , "account_otp_secret" : account_otp_secret }
for key , value in kwargs . items ( ) :
if key not in items :
items ... |
def _get_timestamp_ms ( when ) :
"""Converts a datetime . datetime to integer milliseconds since the epoch .
Requires special handling to preserve microseconds .
Args :
when : A datetime . datetime instance .
Returns :
Integer time since the epoch in milliseconds . If the supplied ' when ' is
None , the... | if when is None :
return None
ms_since_epoch = float ( time . mktime ( when . utctimetuple ( ) ) * 1000.0 )
ms_since_epoch += when . microsecond / 1000.0
return int ( ms_since_epoch ) |
def to_hising ( self ) :
"""Construct a higher - order Ising problem from a binary polynomial .
Returns :
tuple : A 3 - tuple of the form ( ` h ` , ` J ` , ` offset ` ) where ` h ` includes
the linear biases , ` J ` has the higher - order biases and ` offset ` is
the linear offset .
Examples :
> > > pol... | if self . vartype is Vartype . BINARY :
return self . to_spin ( ) . to_hising ( )
h = { }
J = { }
offset = 0
for term , bias in self . items ( ) :
if len ( term ) == 0 :
offset += bias
elif len ( term ) == 1 :
v , = term
h [ v ] = bias
else :
J [ tuple ( term ) ] = bias
r... |
def train_episode ( agent , envs , preprocessors , t_max , render ) :
"""Complete an episode ' s worth of training for each environment .""" | num_envs = len ( envs )
# Buffers to hold trajectories , e . g . ` env _ xs [ i ] ` will hold the observations
# for environment ` i ` .
env_xs , env_as = _2d_list ( num_envs ) , _2d_list ( num_envs )
env_rs , env_vs = _2d_list ( num_envs ) , _2d_list ( num_envs )
episode_rs = np . zeros ( num_envs , dtype = np . float... |
def _reconnect ( self ) :
"""Reconnect to the ReadRows stream using the most recent offset .""" | self . _wrapped = self . _client . read_rows ( _copy_stream_position ( self . _position ) , ** self . _read_rows_kwargs ) |
def make_type ( typename , lineno , implicit = False ) :
"""Converts a typename identifier ( e . g . ' float ' ) to
its internal symbol table entry representation .
Creates a type usage symbol stored in a AST
E . g . DIM a As Integer
will access Integer type""" | assert isinstance ( typename , str )
if not SYMBOL_TABLE . check_is_declared ( typename , lineno , 'type' ) :
return None
type_ = symbols . TYPEREF ( SYMBOL_TABLE . get_entry ( typename ) , lineno , implicit )
return type_ |
def _build_params_from_kwargs ( self , ** kwargs ) :
"""Builds parameters from passed arguments
Search passed parameters in available methods ,
prepend specified API key , and return dictionary
which can be sent directly to API server .
: param kwargs :
: type param : dict
: raises ValueError : If type ... | api_methods = self . get_api_params ( )
required_methods = self . get_api_required_params ( )
ret_kwargs = { }
for key , val in kwargs . items ( ) :
if key not in api_methods :
warnings . warn ( 'Passed uknown parameter [{}]' . format ( key ) , Warning )
continue
if key not in required_methods a... |
def community_topic_delete ( self , id , ** kwargs ) :
"https : / / developer . zendesk . com / rest _ api / docs / help _ center / topics # delete - topic" | api_path = "/api/v2/community/topics/{id}.json"
api_path = api_path . format ( id = id )
return self . call ( api_path , method = "DELETE" , ** kwargs ) |
def is_name_valid ( fqn ) :
"""Is a fully - qualified name acceptable ?
Return True if so
Return False if not
> > > is _ name _ valid ( ' abcd ' )
False
> > > is _ name _ valid ( ' abcd . ' )
False
> > > is _ name _ valid ( ' . abcd ' )
False
> > > is _ name _ valid ( ' Abcd . abcd ' )
False
>... | if not isinstance ( fqn , ( str , unicode ) ) :
return False
if fqn . count ( "." ) != 1 :
return False
name , namespace_id = fqn . split ( "." )
if len ( name ) == 0 or len ( namespace_id ) == 0 :
return False
if not is_b40 ( name ) or "+" in name or "." in name :
return False
if not is_namespace_valid... |
def collect_via_nvidia_smi ( self , stats_config ) :
"""Use nvidia smi command line tool to collect metrics
: param stats _ config :
: return :""" | raw_output = self . run_command ( [ '--query-gpu={query_gpu}' . format ( query_gpu = ',' . join ( stats_config ) ) , '--format=csv,nounits,noheader' ] )
if raw_output is None :
return
results = raw_output [ 0 ] . strip ( ) . split ( "\n" )
for result in results :
stats = result . strip ( ) . split ( ',' )
a... |
def get_datetime ( formatted_str , user_fmt = None ) : # type : ( AnyStr , Optional [ AnyStr ] ) - > datetime
"""get datetime ( ) object from string formatted % Y - % m - % d % H : % M : % S
Examples :
> > > StringClass . get _ datetime ( ' 2008-11-9 ' )
datetime . datetime ( 2008 , 11 , 9 , 0 , 0)
> > > St... | date_fmts = [ '%m-%d-%Y' , '%Y-%m-%d' , '%m-%d-%y' , '%y-%m-%d' ]
date_fmts += [ d . replace ( '-' , '/' ) for d in date_fmts ]
date_fmts += [ d . replace ( '-' , '' ) for d in date_fmts ]
time_fmts = [ '%H:%M' , '%H:%M:%S' ]
fmts = date_fmts + [ '%s %s' % ( d , t ) for d in date_fmts for t in time_fmts ]
if user_fmt i... |
def pack_found_items ( self , s_text , target ) :
"""pack up found items for search ctrl
: param target : treectrl obj
: param s _ text : text to search , lower case
return list of found items""" | all_children = self . all_children
all_text = [ target . GetItemText ( i ) . lower ( ) for i in all_children ]
found_items = [ child for i , child in enumerate ( all_children ) if s_text in all_text [ i ] ]
return found_items |
def setup_tree ( self ) :
"""Setup an example Treeview""" | self . tree . insert ( "" , tk . END , text = "Example 1" , iid = "1" )
self . tree . insert ( "" , tk . END , text = "Example 2" , iid = "2" )
self . tree . insert ( "2" , tk . END , text = "Example Child" )
self . tree . heading ( "#0" , text = "Example heading" ) |
def col_mod ( df , col_name , func , * args , ** kwargs ) :
"""Changes a column of a DataFrame according to a given function
Parameters :
df - DataFrame
DataFrame to operate on
col _ name - string
Name of column to modify
func - function
The function to use to modify the column""" | backup = df [ col_name ] . copy ( )
try :
return_val = func ( df , col_name , * args , ** kwargs )
if return_val is not None :
set_col ( df , col_name , return_val )
except :
df [ col_name ] = backup |
def is_valid_hexameter ( self , scanned_line : str ) -> bool :
"""Determine if a scansion pattern is one of the valid hexameter metrical patterns
: param scanned _ line : a line containing a sequence of stressed and unstressed syllables
: return bool
> > > print ( MetricalValidator ( ) . is _ valid _ hexamete... | line = scanned_line . replace ( self . constants . FOOT_SEPARATOR , "" )
line = line . replace ( " " , "" )
if len ( line ) < 12 :
return False
line = line [ : - 1 ] + self . constants . OPTIONAL_ENDING
return self . VALID_HEXAMETERS . __contains__ ( line ) |
def summary ( args ) :
"""% prog summary coordsfile
provide summary on id % and cov % , for both query and reference""" | from jcvi . formats . blast import AlignStats
p = OptionParser ( summary . __doc__ )
p . add_option ( "-s" , dest = "single" , default = False , action = "store_true" , help = "provide stats per reference seq" )
opts , args = p . parse_args ( args )
if len ( args ) != 1 :
sys . exit ( p . print_help ( ) )
coordsfil... |
def to_array ( self ) :
"""Serializes this Voice to a dictionary .
: return : dictionary representation of this object .
: rtype : dict""" | array = super ( Voice , self ) . to_array ( )
array [ 'file_id' ] = u ( self . file_id )
# py2 : type unicode , py3 : type str
array [ 'duration' ] = int ( self . duration )
# type int
if self . mime_type is not None :
array [ 'mime_type' ] = u ( self . mime_type )
# py2 : type unicode , py3 : type str
if self . fi... |
def set_debugged_thread ( self , target_thread_ident = None ) :
"""Allows to reset or set the thread to debug .""" | if target_thread_ident is None :
self . debugged_thread_ident = None
self . debugged_thread_name = ''
return { "result" : self . get_threads ( ) , "error" : "" }
thread_list = self . get_threads ( )
if target_thread_ident not in thread_list :
return { "result" : None , "error" : "No thread with ident:%s... |
async def revoke ( self , username , acl = 'login' ) :
"""Removes some or all access of a user to from a controller
If ' login ' access is revoked , the user will no longer have any
permissions on the controller . Revoking a higher privilege from
a user without that privilege will have no effect .
: param s... | controller_facade = client . ControllerFacade . from_connection ( self . connection ( ) )
user = tag . user ( username )
changes = client . ModifyControllerAccess ( 'login' , 'revoke' , user )
return await controller_facade . ModifyControllerAccess ( [ changes ] ) |
def get_default_classes ( self ) :
"""Returns a list of the default classes for the tab group .
Defaults to ` ` [ " nav " , " nav - tabs " , " ajax - tabs " ] ` ` .""" | default_classes = super ( TabGroup , self ) . get_default_classes ( )
default_classes . extend ( CSS_TAB_GROUP_CLASSES )
return default_classes |
def to_designspace ( font , family_name = None , instance_dir = None , propagate_anchors = True , ufo_module = defcon , minimize_glyphs_diffs = False , generate_GDEF = True , store_editor_state = True , ) :
"""Take a GSFont object and convert it into a Designspace Document + UFOS .
The UFOs are available as the a... | builder = UFOBuilder ( font , ufo_module = ufo_module , family_name = family_name , instance_dir = instance_dir , propagate_anchors = propagate_anchors , use_designspace = True , minimize_glyphs_diffs = minimize_glyphs_diffs , generate_GDEF = generate_GDEF , store_editor_state = store_editor_state , )
return builder . ... |
def end_subsegment ( self , end_time = None ) :
"""End the current active subsegment . If this is the last one open
under its parent segment , the entire segment will be sent .
: param float end _ time : subsegment compeletion in unix epoch in seconds .""" | if not self . context . end_subsegment ( end_time ) :
return
# if segment is already close , we check if we can send entire segment
# otherwise we check if we need to stream some subsegments
if self . current_segment ( ) . ready_to_send ( ) :
self . _send_segment ( )
else :
self . stream_subsegments ( ) |
def gcommer_claim ( address = None ) :
"""Try to get a token for this server address .
` address ` has to be ip : port , e . g . ` ' 1.2.3.4:1234 ' `
Returns tuple ( address , token )""" | if not address : # get token for any world
# this is only useful for testing ,
# because that is exactly what m . agar . io does
url = 'http://at.gcommer.com/status'
text = urllib . request . urlopen ( url ) . read ( ) . decode ( )
j = json . loads ( text )
for address , num in j [ 'status' ] . items ( ... |
def syncView ( self ) :
"""Syncs all the items to the view .""" | if not self . updatesEnabled ( ) :
return
for item in self . topLevelItems ( ) :
try :
item . syncView ( recursive = True )
except AttributeError :
continue |
def erase_text ( self , locator , click = True , clear = False , backspace = 0 , params = None ) :
"""Various ways to erase text from web element .
: param locator : locator tuple or WebElement instance
: param click : clicks the input field
: param clear : clears the input field
: param backspace : how man... | element = locator
if not isinstance ( element , WebElement ) :
element = self . get_visible_element ( locator , params )
if click :
self . click ( element )
if clear :
element . clear ( )
if backspace :
actions = ActionChains ( self . driver )
for _ in range ( backspace ) :
actions . send_ke... |
def process_composite ( self , response ) :
"""Process a composite response .
composites do not have inter item separators as they appear joined .
We need to respect the universal options too .""" | composite = response [ "composite" ]
# if the composite is of not Composite make it one so we can simplify
# it .
if not isinstance ( composite , Composite ) :
composite = Composite ( composite )
# simplify and get underlying list .
composite = composite . simplify ( ) . get_content ( )
response [ "composite" ] = c... |
def resolve_service_id ( self , service_name = None , service_type = None ) :
"""Find the service _ id of a given service""" | services = [ s . _info for s in self . api . services . list ( ) ]
service_name = service_name . lower ( )
for s in services :
name = s [ 'name' ] . lower ( )
if service_type and service_name :
if ( service_name == name and service_type == s [ 'type' ] ) :
return s [ 'id' ]
elif service_... |
def list_topic ( self , k , Nwords = 10 ) :
"""List the top ` ` topn ` ` words for topic ` ` k ` ` .
Examples
. . code - block : : python
> > > model . list _ topic ( 1 , Nwords = 5)
[ ' opposed ' , ' terminates ' , ' trichinosis ' , ' cistus ' , ' acaule ' ]""" | return [ ( self . vocabulary [ w ] , p ) for w , p in self . phi . features [ k ] . top ( Nwords ) ] |
def select ( cls , dataset , selection_mask = None , ** selection ) :
"""Slice the underlying numpy array in sheet coordinates .""" | selection = { k : slice ( * sel ) if isinstance ( sel , tuple ) else sel for k , sel in selection . items ( ) }
coords = tuple ( selection [ kd . name ] if kd . name in selection else slice ( None ) for kd in dataset . kdims )
if not any ( [ isinstance ( el , slice ) for el in coords ] ) :
return dataset . data [ d... |
def set_index ( self , index ) :
"""Display the data of the given index
: param index : the index to paint
: type index : QtCore . QModelIndex
: returns : None
: rtype : None
: raises : None""" | item = index . internalPointer ( )
note = item . internal_data ( )
self . content_lb . setText ( note . content )
self . created_dte . setDateTime ( dt_to_qdatetime ( note . date_created ) )
self . updated_dte . setDateTime ( dt_to_qdatetime ( note . date_updated ) )
self . username_lb . setText ( note . user . usernam... |
def update ( self , key , item ) :
"""Update or insert item into hash table with specified key and item . If the
key is already present , destroys old item and inserts new one . If you set
a container item destructor , this is called on the old value . If the key
was not already present , inserts a new item .... | return lib . zhashx_update ( self . _as_parameter_ , key , item ) |
def initialize ( # type : ignore
self , max_clients : int = 10 , hostname_mapping : Dict [ str , str ] = None , max_buffer_size : int = 104857600 , resolver : Resolver = None , defaults : Dict [ str , Any ] = None , max_header_size : int = None , max_body_size : int = None , ) -> None :
"""Creates a AsyncHTTPClient... | super ( SimpleAsyncHTTPClient , self ) . initialize ( defaults = defaults )
self . max_clients = max_clients
self . queue = ( collections . deque ( ) )
# type : Deque [ Tuple [ object , HTTPRequest , Callable [ [ HTTPResponse ] , None ] ] ]
self . active = ( { } )
# type : Dict [ object , Tuple [ HTTPRequest , Callable... |
def spectral_embedding_ ( self , n ) :
"""Old method for generating coords , used on original analysis
of yeast data . Included to reproduce yeast result from paper .
Reason for difference - switched to using spectral embedding
method provided by scikit - learn ( mainly because it spreads
points over a sphe... | aff = self . _affinity . copy ( )
aff . flat [ : : aff . shape [ 0 ] + 1 ] = 0
laplacian = laplace ( aff )
decomp = eigen ( laplacian )
return CoordinateMatrix ( normalise_rows ( decomp . vecs [ : , : n ] ) ) |
def restart_minecraft ( world_state , agent_host , client_info , message ) :
"""" Attempt to quit mission if running and kill the client""" | if world_state . is_mission_running :
agent_host . sendCommand ( "quit" )
time . sleep ( 10 )
agent_host . killClient ( client_info )
raise MissionTimeoutException ( message ) |
def drag_sphere ( Re , Method = None , AvailableMethods = False ) :
r'''This function handles calculation of drag coefficient on spheres .
Twenty methods are available , all requiring only the Reynolds number of the
sphere . Most methods are valid from Re = 0 to Re = 200,000 . A correlation will
be automatica... | def list_methods ( ) :
methods = [ ]
for key , ( func , Re_min , Re_max ) in drag_sphere_correlations . items ( ) :
if ( Re_min is None or Re > Re_min ) and ( Re_max is None or Re < Re_max ) :
methods . append ( key )
return methods
if AvailableMethods :
return list_methods ( )
if no... |
def _verify_pair ( prev , curr ) :
"""Verify a pair of sides share an endpoint .
. . note : :
This currently checks that edge endpoints match * * exactly * *
but allowing some roundoff may be desired .
Args :
prev ( . Curve ) : " Previous " curve at piecewise junction .
curr ( . Curve ) : " Next " curve... | if prev . _dimension != 2 :
raise ValueError ( "Curve not in R^2" , prev )
end = prev . _nodes [ : , - 1 ]
start = curr . _nodes [ : , 0 ]
if not _helpers . vector_close ( end , start ) :
raise ValueError ( "Not sufficiently close" , "Consecutive sides do not have common endpoint" , prev , curr , ) |
def execute ( self , input_data ) :
"""Info objects all have a type _ tag of ( ' help ' , ' worker ' , ' command ' , or ' other ' )""" | input_data = input_data [ 'info' ]
type_tag = input_data [ 'type_tag' ]
if type_tag == 'help' :
return { 'help' : input_data [ 'help' ] , 'type_tag' : input_data [ 'type_tag' ] }
elif type_tag == 'worker' :
out_keys = [ 'name' , 'dependencies' , 'docstring' , 'type_tag' ]
return { key : value for key , valu... |
def run_plink ( in_prefix , out_prefix , extract_filename ) :
"""Runs Plink with the geno option .
: param in _ prefix : the input prefix .
: param out _ prefix : the output prefix .
: param extract _ filename : the name of the file containing markers to
extract .
: type in _ prefix : str
: type out _ p... | # The plink command
plink_command = [ "plink" , "--noweb" , "--bfile" , in_prefix , "--extract" , extract_filename , "--freq" , "--out" , out_prefix , ]
output = None
try :
output = subprocess . check_output ( plink_command , stderr = subprocess . STDOUT , shell = False )
except subprocess . CalledProcessError as e... |
def _thread_main ( self ) :
"""The entry point for the worker thread .
Pulls pending data off the queue and writes them in
batches to the specified tracing backend using the exporter .""" | quit_ = False
while True :
items = self . _get_items ( )
data = [ ]
for item in items :
if item is _WORKER_TERMINATOR :
quit_ = True
# Continue processing items , don ' t break , try to process
# all items we got back before quitting .
else :
d... |
def signature ( array ) :
"""Returns the first 262 bytes of the given bytearray
as part of the file header signature .
Args :
array : bytearray to extract the header signature .
Returns :
First 262 bytes of the file content as bytearray type .""" | length = len ( array )
index = _NUM_SIGNATURE_BYTES if length > _NUM_SIGNATURE_BYTES else length
return array [ : index ] |
def only_owner ( func ) :
"""Only owner decorator
Restricts access to view ony to profile owner""" | def decorated ( * _ , ** kwargs ) :
id = kwargs [ 'id' ]
if not current_user . is_authenticated :
abort ( 401 )
elif current_user . id != id :
abort ( 403 )
return func ( ** kwargs )
return decorated |
def view_count_plus ( slug ) :
'''View count plus one .''' | entry = TabWiki . update ( view_count = TabWiki . view_count + 1 , ) . where ( TabWiki . uid == slug )
entry . execute ( ) |
def next_job ( self , timeout_seconds = None ) :
"""Retuns the next job in the queue , or None if is nothing there""" | if timeout_seconds is not None :
timeout = timeout_seconds
else :
timeout = BLOCK_SECONDS
response = self . lua_next ( keys = [ self . queue_name ] )
if not response :
return
job = Job . from_serialized ( response )
if not job :
self . log . warn ( "could not deserialize job from: %s" , serialized_job )... |
def get_mac_acl_for_intf_output_interface_interface_name ( self , ** kwargs ) :
"""Auto Generated Code""" | config = ET . Element ( "config" )
get_mac_acl_for_intf = ET . Element ( "get_mac_acl_for_intf" )
config = get_mac_acl_for_intf
output = ET . SubElement ( get_mac_acl_for_intf , "output" )
interface = ET . SubElement ( output , "interface" )
interface_type_key = ET . SubElement ( interface , "interface-type" )
interfac... |
def _escape_token ( token , alphabet ) :
r"""Replace characters that aren ' t in the alphabet and append " _ " to token .
Apply three transformations to the token :
1 . Replace underline character " _ " with " \ u " , and backslash " \ " with " \ \ " .
2 . Replace characters outside of the alphabet with " \ #... | token = token . replace ( u"\\" , u"\\\\" ) . replace ( u"_" , u"\\u" )
ret = [ c if c in alphabet and c != u"\n" else r"\%d;" % ord ( c ) for c in token ]
return u"" . join ( ret ) + "_" |
def is_running ( self , submissionid , user_check = True ) :
"""Tells if a submission is running / in queue""" | submission = self . get_submission ( submissionid , user_check )
return submission [ "status" ] == "waiting" |
def check_large_images ( self , node , parent_depth_level , sibling_depth_level ) :
"""although slow the best way to determine the best image is to download
them and check the actual dimensions of the image when on disk
so we ' ll go through a phased approach . . .
1 . get a list of ALL images from the parent... | good_images = self . get_image_candidates ( node )
if good_images :
scored_images = self . fetch_images ( good_images , parent_depth_level )
if scored_images :
highscore_image = sorted ( scored_images . items ( ) , key = lambda x : x [ 1 ] , reverse = True ) [ 0 ] [ 0 ]
main_image = Image ( )
... |
def upper_diag_self_prodx ( list_ ) :
"""upper diagnoal of cartesian product of self and self .
Weird name . fixme
Args :
list _ ( list ) :
Returns :
list :
CommandLine :
python - m utool . util _ alg - - exec - upper _ diag _ self _ prodx
Example :
> > > # ENABLE _ DOCTEST
> > > from utool . ut... | return [ ( item1 , item2 ) for n1 , item1 in enumerate ( list_ ) for n2 , item2 in enumerate ( list_ ) if n1 < n2 ] |
def __request ( self , endpoint , method = 'GET' , params = None , convJSON = False ) :
"""request - Returns dict of response from postcode . nl API .
This method is called only by the EndpointMixin methods .""" | url = '%s/%s' % ( self . api_url , endpoint )
method = method . lower ( )
params = params or { }
if convJSON :
params = json . dumps ( params )
func = getattr ( self . client , method )
request_args = { }
if method == 'get' :
request_args [ 'params' ] = params
else :
request_args [ 'data' ] = params
try : #... |
def get_data_by_slug ( model , slug , kind = '' , ** kwargs ) :
"""Get instance data by slug and kind . Raise 404 Not Found if there is no data .
This function requires model has a ` slug ` column .
: param model : a string , model name in rio . models
: param slug : a string used to query by ` slug ` . This ... | instance = get_instance_by_slug ( model , slug , ** kwargs )
if not instance :
return
return ins2dict ( instance , kind ) |
def match_entry_line ( str_to_match , regex_obj = MAIN_REGEX_OBJ ) :
"""Does a regex match of the mount entry string""" | match_obj = regex_obj . match ( str_to_match )
if not match_obj :
error_message = ( 'Line "%s" is unrecognized by overlay4u. ' 'This is only meant for use with Ubuntu Linux.' )
raise UnrecognizedMountEntry ( error_message % str_to_match )
return match_obj . groupdict ( ) |
def qteRemoveHighlighting ( self , widgetObj ) :
"""Remove the highlighting from previously highlighted characters .
The method access instance variables to determine which
characters are currently highlighted and have to be converted
to non - highlighted ones .
| Args |
* ` ` widgetObj ` ` ( * * QWidget ... | # Retrieve the widget specific macro data .
data = self . qteMacroData ( widgetObj )
if not data :
return
# If the data structure is empty then no previously
# highlighted characters exist in this particular widget , so
# do nothing .
if not data . matchingPositions :
return
# Restore the original character for... |
def _find_compositor ( self , dataset_key , ** dfilter ) :
"""Find the compositor object for the given dataset _ key .""" | # NOTE : This function can not find a modifier that performs
# one or more modifications if it has modifiers see if we can find
# the unmodified version first
src_node = None
if isinstance ( dataset_key , DatasetID ) and dataset_key . modifiers :
new_prereq = DatasetID ( * dataset_key [ : - 1 ] + ( dataset_key . mo... |
def post ( f , * args , ** kwargs ) :
"""Automatically log progress on function exit . Default logging value :
info .
* Logging with values contained in the parameters of the decorated function *
Message ( args [ 0 ] ) may be a string to be formatted with parameters passed to
the decorated function . Each '... | kwargs . update ( { 'postfix_only' : True } )
return _stump ( f , * args , ** kwargs ) |
def decode ( self , payload ) :
"""Decode payload""" | try :
return self . encoder . decode ( payload )
except Exception as exception :
raise DecodeError ( str ( exception ) ) |
def check_routes ( feed : "Feed" , * , as_df : bool = False , include_warnings : bool = False ) -> List :
"""Analog of : func : ` check _ agency ` for ` ` feed . routes ` ` .""" | table = "routes"
problems = [ ]
# Preliminary checks
if feed . routes is None :
problems . append ( [ "error" , "Missing table" , table , [ ] ] )
else :
f = feed . routes . copy ( )
problems = check_for_required_columns ( problems , table , f )
if problems :
return format_problems ( problems , as_df = a... |
def global_id_field ( type_name , id_fetcher = None ) :
'''Creates the configuration for an id field on a node , using ` to _ global _ id ` to
construct the ID from the provided typename . The type - specific ID is fetcher
by calling id _ fetcher on the object , or if not provided , by accessing the ` id `
pr... | return GraphQLField ( GraphQLNonNull ( GraphQLID ) , description = 'The ID of an object' , resolver = lambda obj , args , context , info : to_global_id ( type_name or info . parent_type . name , id_fetcher ( obj , context , info ) if id_fetcher else obj . id ) ) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.