signature stringlengths 29 44.1k | implementation stringlengths 0 85.2k |
|---|---|
def main ( ) :
"""A CLI application for performing factory calibration of an Opentrons robot
Instructions :
- Robot must be set up with two 300ul or 50ul single - channel pipettes
installed on the right - hand and left - hand mount .
- Put a GEB 300ul tip onto the pipette .
- Use the arrow keys to jog the... | prompt = input ( ">>> Warning! Running this tool backup and clear any previous " "calibration data. Proceed (y/[n])? " )
if prompt not in [ 'y' , 'Y' , 'yes' ] :
print ( 'Exiting--prior configuration data not changed' )
sys . exit ( )
# Notes :
# - 200ul tip is 51.7mm long when attached to a pipette
# - For xyz... |
def find_root ( self ) :
"""Traverse parent refs to top .""" | cmd = self
while cmd . parent :
cmd = cmd . parent
return cmd |
def has_instance ( name , provider = None ) :
'''Return true if the instance is found on a provider
CLI Example :
. . code - block : : bash
salt minionname cloud . has _ instance myinstance''' | data = get_instance ( name , provider )
if data is None :
return False
return True |
def _expand_join ( join_definition ) :
"""Expand join definition to ` join ' call .
: param join _ definition : join definition
: return : expanded join definition""" | join_table_name = join_definition . pop ( 'table' )
join_func = getattr ( mosql_query , join_definition . pop ( 'join_type' , 'join' ) )
return join_func ( join_table_name , ** join_definition ) |
def success ( self ) :
"""Test whether the experiment has been run successfully . This will
be False if the experiment hasn ' t been run , or if it ' s been run and
failed ( in which case the exception will be stored in the metadata ) .
: returns : ` ` True ` ` if the experiment has been run successfully""" | if self . STATUS in self . metadata ( ) . keys ( ) :
return ( self . metadata ( ) ) [ self . STATUS ]
else :
return False |
def _is_metadata_of ( group , parent_group ) :
"""Check if a given group is a metadata group for a given parent _ group .""" | if group . _v_depth <= parent_group . _v_depth :
return False
current = group
while current . _v_depth > 1 :
parent = current . _v_parent
if parent == parent_group and current . _v_name == 'meta' :
return True
current = current . _v_parent
return False |
def use_project ( self , project_id ) :
"""Creates an instance of [ ProjectClient ] ( # projectclient ) ,
providing session authentication .
Parameters :
* ` project _ id ` - project identifier .
Returns :
Instance of [ ProjectClient ] ( # projectclient ) with
session authentication .
Example :
` ` ... | return ProjectClient ( base_uri = get_base_uri ( project = project_id , host = self . host , port = self . port , secure = self . secure , api_base_path = self . api_base_path ) , auth_header = self . auth_header , requests_session = self . requests_session , request_defaults = self . request_defaults , ) |
def index ( self , text , terms = None , ** kwargs ) :
"""Index all term pair distances .
Args :
text ( Text ) : The source text .
terms ( list ) : Terms to index .""" | self . clear ( )
# By default , use all terms .
terms = terms or text . terms . keys ( )
pairs = combinations ( terms , 2 )
count = comb ( len ( terms ) , 2 )
for t1 , t2 in bar ( pairs , expected_size = count , every = 1000 ) : # Set the Bray - Curtis distance .
score = text . score_braycurtis ( t1 , t2 , ** kwarg... |
def on_api_socket_reconnected ( self ) :
"""for API socket reconnected""" | self . __is_acc_sub_push = False
self . __last_acc_list = [ ]
ret , msg = RET_OK , ''
# auto unlock trade
if self . _ctx_unlock is not None :
password , password_md5 = self . _ctx_unlock
ret , data = self . unlock_trade ( password , password_md5 )
logger . debug ( 'auto unlock trade ret={},data={}' . format... |
def filter_mean ( matrix , top ) :
"""Filter genes in an expression matrix by mean expression .
Parameters
matrix : ExpMatrix
The expression matrix .
top : int
The number of genes to retain .
Returns
ExpMatrix
The filtered expression matrix .""" | assert isinstance ( matrix , ExpMatrix )
assert isinstance ( top , int )
if top >= matrix . p :
logger . warning ( 'Gene expression filter with `top` parameter that is ' '>= the number of genes!' )
top = matrix . p
a = np . argsort ( np . mean ( matrix . X , axis = 1 ) )
a = a [ : : - 1 ]
sel = np . zeros ( mat... |
def import_egg ( string ) :
"""Import a controller class from an egg . Uses the entry point group
" appathy . controller " .""" | # Split the string into a distribution and a name
dist , _sep , name = string . partition ( '#' )
return pkg_resources . load_entry_point ( dist , 'appathy.controller' , name ) |
def consume ( self , message ) :
"""Consume a JSON RPC message from the client .
Args :
message ( dict ) : The JSON RPC message sent by the client""" | if 'jsonrpc' not in message or message [ 'jsonrpc' ] != JSONRPC_VERSION :
log . warn ( "Unknown message type %s" , message )
return
if 'id' not in message :
log . debug ( "Handling notification from client %s" , message )
self . _handle_notification ( message [ 'method' ] , message . get ( 'params' ) )
... |
def screenshot ( self , filename ) :
"""Saves a screenshot of the current element to a PNG image file . Returns
False if there is any IOError , else returns True . Use full paths in
your filename .
: Args :
- filename : The full path you wish to save your screenshot to . This
should end with a ` . png ` e... | if not filename . lower ( ) . endswith ( '.png' ) :
warnings . warn ( "name used for saved screenshot does not match file " "type. It should end with a `.png` extension" , UserWarning )
png = self . screenshot_as_png
try :
with open ( filename , 'wb' ) as f :
f . write ( png )
except IOError :
retur... |
def ack ( self , msg ) :
"""Called when a MESSAGE has been received .
Override this method to handle received messages .
This function will generate an acknowledge message
for the given message and transaction ( if present ) .""" | message_id = msg [ 'headers' ] [ 'message-id' ]
subscription = msg [ 'headers' ] [ 'subscription' ]
transaction_id = None
if 'transaction-id' in msg [ 'headers' ] :
transaction_id = msg [ 'headers' ] [ 'transaction-id' ]
# print " acknowledging message id < % s > . " % message _ id
return ack ( message_id , subscri... |
def move ( self , dst ) :
"""move this file / folder the [ dst ]""" | shutil . move ( self , dst )
self = PathStr ( dst ) . join ( self . basename ( ) )
return self |
def get_rule ( name = 'all' ) :
'''. . versionadded : : 2015.5.0
Display all matching rules as specified by name
Args :
name ( Optional [ str ] ) : The full name of the rule . ` ` all ` ` will return all
rules . Default is ` ` all ` `
Returns :
dict : A dictionary of all rules or rules that match the na... | cmd = [ 'netsh' , 'advfirewall' , 'firewall' , 'show' , 'rule' , 'name={0}' . format ( name ) ]
ret = __salt__ [ 'cmd.run_all' ] ( cmd , python_shell = False , ignore_retcode = True )
if ret [ 'retcode' ] != 0 :
raise CommandExecutionError ( ret [ 'stdout' ] )
return { name : ret [ 'stdout' ] } |
def load_uncached ( location , use_json = None ) :
"""Return data at either a file location or at the raw version of a
URL , or raise an exception .
A file location either contains no colons like / usr / tom / test . txt ,
or a single character and a colon like C : / WINDOWS / STUFF .
A URL location is anyt... | if not whitelist . is_file ( location ) :
r = requests . get ( raw . raw ( location ) )
if not r . ok :
raise ValueError ( 'Couldn\'t read %s with code %s:\n%s' % ( location , r . status_code , r . text ) )
data = r . text
else :
try :
f = os . path . realpath ( os . path . abspath ( os ... |
def validate ( self , value , model = None , context = None ) :
"""Validate
Perform value validation against validation settings and return
error object .
: param value : list , value to check
: param model : parent model being validated
: param context : object or None , validation context
: return : s... | invalid = [ item for item in value if item not in self . choices ]
if len ( invalid ) :
return Error ( self . invalid_multichoice , dict ( items = ', ' . join ( invalid ) ) )
# success otherwise
return Error ( ) |
def topic_search ( text , corpus = doc_topic_vectors , pcaer = pcaer , corpus_text = corpus ) :
"""search for the most relevant document""" | tokens = tokenize ( text , vocabulary = corpus . columns )
tfidf_vector_query = np . array ( tfidfer . transform ( [ ' ' . join ( tokens ) ] ) . todense ( ) ) [ 0 ]
topic_vector_query = pcaer . transform ( [ tfidf_vector_query ] )
query_series = pd . Series ( topic_vector_query , index = corpus . columns )
return corpu... |
def list_train_dirs ( dir_ : str , recursive : bool , all_ : bool , long : bool , verbose : bool ) -> None :
"""List training dirs contained in the given dir with options and outputs similar to the regular ` ls ` command .
The function is accessible through cxflow CLI ` cxflow ls ` .
: param dir _ : dir to be l... | if verbose :
long = True
if dir_ == CXF_DEFAULT_LOG_DIR and not path . exists ( CXF_DEFAULT_LOG_DIR ) :
print ( 'The default log directory `{}` does not exist.\n' 'Consider specifying the directory to be listed as an argument.' . format ( CXF_DEFAULT_LOG_DIR ) )
quit ( 1 )
if not path . exists ( dir_ ) :
... |
def _cas_3 ( self ) :
'''Latitude overlap ( 2 images ) .''' | lonc = self . _format_lon ( self . lonm )
latc_top = self . _format_lat ( self . latM )
latc_bot = self . _format_lat ( self . latm )
img_name_top = self . _format_name_map ( lonc , latc_top )
print ( img_name_top )
img_top = BinaryTable ( img_name_top , self . path_pdsfiles )
print ( self . lonm , self . lonM , float ... |
def weight_function ( results , args = None , return_weights = False ) :
"""The default weight function utilized by : class : ` DynamicSampler ` .
Zipped parameters are passed to the function via : data : ` args ` .
Assigns each point a weight based on a weighted average of the
posterior and evidence informat... | # Initialize hyperparameters .
if args is None :
args = dict ( { } )
pfrac = args . get ( 'pfrac' , 0.8 )
if not 0. <= pfrac <= 1. :
raise ValueError ( "The provided `pfrac` {0} is not between 0. and 1." . format ( pfrac ) )
maxfrac = args . get ( 'maxfrac' , 0.8 )
if not 0. <= maxfrac <= 1. :
raise ValueEr... |
def _convert_json_response_to_entity ( response , property_resolver , require_encryption , key_encryption_key , key_resolver ) :
''': param bool require _ encryption :
If set , will enforce that the retrieved entity is encrypted and decrypt it .
: param object key _ encryption _ key :
The user - provided key ... | if response is None or response . body is None :
return None
root = loads ( response . body . decode ( 'utf-8' ) )
return _decrypt_and_deserialize_entity ( root , property_resolver , require_encryption , key_encryption_key , key_resolver ) |
def divide ( lhs , rhs ) :
"""Returns element - wise division of the input arrays with broadcasting .
Equivalent to ` ` lhs / rhs ` ` and ` ` mx . nd . broadcast _ div ( lhs , rhs ) ` ` .
. . note : :
If the corresponding dimensions of two arrays have the same size or one of them has size 1,
then the arrays... | # pylint : disable = no - member , protected - access
return _ufunc_helper ( lhs , rhs , op . broadcast_div , operator . truediv , _internal . _div_scalar , _internal . _rdiv_scalar ) |
def default ( self , obj ) :
'''The required ` ` default ` ` method for ` ` JSONEncoder ` ` subclasses .
Args :
obj ( obj ) :
The object to encode . Anything not specifically handled in
this method is passed on to the default system JSON encoder .''' | from . . model import Model
from . . colors import Color
from . has_props import HasProps
# array types - - use force _ list here , only binary
# encoding CDS columns for now
if pd and isinstance ( obj , ( pd . Series , pd . Index ) ) :
return transform_series ( obj , force_list = True )
elif isinstance ( obj , np ... |
def forward ( self , inputs : torch . Tensor ) -> Dict [ str , torch . Tensor ] : # pylint : disable = arguments - differ
"""Compute context insensitive token embeddings for ELMo representations .
Parameters
inputs : ` ` torch . Tensor ` `
Shape ` ` ( batch _ size , sequence _ length , 50 ) ` ` of character i... | # Add BOS / EOS
mask = ( ( inputs > 0 ) . long ( ) . sum ( dim = - 1 ) > 0 ) . long ( )
character_ids_with_bos_eos , mask_with_bos_eos = add_sentence_boundary_token_ids ( inputs , mask , self . _beginning_of_sentence_characters , self . _end_of_sentence_characters )
# the character id embedding
max_chars_per_token = se... |
def to_link ( self ) :
"""Returns a link for the resource .""" | link_type = self . link_type if self . type == 'Link' else self . type
return Link ( { 'sys' : { 'linkType' : link_type , 'id' : self . sys . get ( 'id' ) } } , client = self . _client ) |
def dispatch ( self , receiver ) :
'''Dispatch handling of this event to a receiver .
This method will invoke ` ` receiver . _ columns _ streamed ` ` if it exists .''' | super ( ColumnsStreamedEvent , self ) . dispatch ( receiver )
if hasattr ( receiver , '_columns_streamed' ) :
receiver . _columns_streamed ( self ) |
def _create_borderchoice_combo ( self ) :
"""Create border choice combo box""" | choices = [ c [ 0 ] for c in self . border_toggles ]
self . borderchoice_combo = _widgets . BorderEditChoice ( self , choices = choices , style = wx . CB_READONLY , size = ( 50 , - 1 ) )
self . borderchoice_combo . SetToolTipString ( _ ( u"Choose borders for which attributes are changed" ) )
self . borderstate = self .... |
def create_container ( self , name , image , hostname = 'dfis' , networkmode = 'bridge' , ports = None , volumes = None , env = None , restartpolicy = 'no' , restartretrycount = '2' , command = "" ) :
"""testing
: param name :
: param image :
: param hostname :
: param networkmode : ` class ` : ` str ` , ho... | restartpolicy = restartpolicy . lower ( )
repository , image_name , version = utils . parse_image_name ( image )
image = '{0}/{1}:{2}' . format ( DOCKER_NEG , image_name , version )
body = dict ( name = name , image = image , hostname = hostname , networkmode = networkmode , ports = ports or [ ] , volumes = volumes or ... |
def is_number ( dtype ) :
"""Return True is datatype dtype is a number kind""" | return is_float ( dtype ) or ( 'int' in dtype . name ) or ( 'long' in dtype . name ) or ( 'short' in dtype . name ) |
def decode_once ( estimator , problem_name , hparams , infer_input_fn , decode_hp , decode_to_file , output_dir , log_results = True , checkpoint_path = None ) :
"""Decodes once .
Args :
estimator : tf . estimator . Estimator instance . Used to generate encoded
predictions .
problem _ name : str . Name of p... | # Get the predictions as an iterable
predictions = estimator . predict ( infer_input_fn , checkpoint_path = checkpoint_path )
if not log_results :
return list ( predictions )
# Prepare output file writers if decode _ to _ file passed
decode_to_file = decode_to_file or decode_hp . decode_to_file
if decode_to_file :
... |
def get_url_and_revision_from_pip_url ( cls , pip_url ) :
"""Prefixes stub URLs like ' user @ hostname : user / repo . git ' with ' ssh : / / ' .
That ' s required because although they use SSH they sometimes doesn ' t
work with a ssh : / / scheme ( e . g . Github ) . But we need a scheme for
parsing . Hence ... | if '://' not in pip_url :
assert 'file:' not in pip_url
pip_url = pip_url . replace ( 'git+' , 'git+ssh://' )
url , rev = super ( GitRepo , cls ) . get_url_and_revision_from_pip_url ( pip_url )
url = url . replace ( 'ssh://' , '' )
elif 'github.com:' in pip_url :
raise exc . LibVCSException ( "Repo ... |
def get_service_version ( self , service_id , mode = 'production' , version = 'default' ) :
'''get _ service _ version ( self , service _ id , mode = ' production ' , version = ' default ' )
| Get a specific version details of a given service . Opereto will try to fetch the requested service version . If not foun... | return self . _call_rest_api ( 'get' , '/services/' + service_id + '/' + mode + '/' + version , error = 'Failed to fetch service information' ) |
def pp_hex ( raw , reverse = True ) :
"""Return a pretty - printed ( hex style ) version of a binary string .
Args :
raw ( bytes ) : any sequence of bytes
reverse ( bool ) : True if output should be in reverse order .
Returns :
Hex string corresponding to input byte sequence .""" | if not reverse :
return '' . join ( [ '{:02x}' . format ( v ) for v in bytearray ( raw ) ] )
return '' . join ( reversed ( [ '{:02x}' . format ( v ) for v in bytearray ( raw ) ] ) ) |
def wb020 ( self , value = None ) :
"""Corresponds to IDD Field ` wb020 `
Wet - bulb temperature corresponding to 02.0 % annual cumulative frequency of occurrence
Args :
value ( float ) : value for IDD Field ` wb020 `
Unit : C
if ` value ` is None it will not be checked against the
specification and is ... | if value is not None :
try :
value = float ( value )
except ValueError :
raise ValueError ( 'value {} need to be of type float ' 'for field `wb020`' . format ( value ) )
self . _wb020 = value |
def modulation_type ( self , value : int ) :
"""0 - " ASK " , 1 - " FSK " , 2 - " PSK " , 3 - " APSK ( QAM ) "
: param value :
: return :""" | if self . __modulation_type != value :
self . __modulation_type = value
self . _qad = None
self . modulation_type_changed . emit ( self . __modulation_type )
if not self . block_protocol_update :
self . protocol_needs_update . emit ( ) |
def columns_exist ( inspect_dataset ) :
"""This function will take a dataset and add expectations that each column present exists .
Args :
inspect _ dataset ( great _ expectations . dataset ) : The dataset to inspect and to which to add expectations .""" | # Attempt to get column names . For pandas , columns is just a list of strings
if not hasattr ( inspect_dataset , "columns" ) :
warnings . warn ( "No columns list found in dataset; no autoinspection performed." )
return
elif isinstance ( inspect_dataset . columns [ 0 ] , string_types ) :
columns = inspect_d... |
def raw_to_bv ( self ) :
"""A counterpart to FP . raw _ to _ bv - does nothing and returns itself .""" | if self . symbolic :
return BVS ( next ( iter ( self . variables ) ) . replace ( self . STRING_TYPE_IDENTIFIER , self . GENERATED_BVS_IDENTIFIER ) , self . length )
else :
return BVV ( ord ( self . args [ 0 ] ) , self . length ) |
def __profile_definition ( self , pipeline_name ) :
"""Prepare the profiles extraction from a specific profile""" | pipe = self . flsh . Operations [ pipeline_name ]
x_st = pipe . GetUserVariable ( PROFILE_LENGTH_ST ) . Variable ( )
x_non_st = pipe . GetUserVariable ( PROFILE_LENGTH_NON_ST ) . Variable ( )
timesteps = pipe . GetUserVariable ( PROFILE_TIME ) . Variable ( )
self . pipes [ pipeline_name ] = { 'grid' : x_st , 'non_st_gr... |
def fill ( self , postf_un_ops : str ) :
"""Insert :
* math styles
* other styles
* unary prefix operators without brackets
* defaults""" | for op , dic in self . ops . items ( ) :
if 'postf' not in dic :
dic [ 'postf' ] = self . postf
self . ops = OrderedDict ( self . styles . spec ( postf_un_ops ) + self . other_styles . spec ( postf_un_ops ) + self . pref_un_greedy . spec ( ) + list ( self . ops . items ( ) ) )
for op , dic in self . ops . i... |
def get_grading_status ( section_id , act_as = None ) :
"""Return a restclients . models . gradepage . GradePageStatus object
on the given course""" | url = "{}/{}" . format ( url_prefix , quote ( section_id ) )
headers = { }
if act_as is not None :
headers [ "X-UW-Act-as" ] = act_as
response = get_resource ( url , headers )
return _object_from_json ( url , response ) |
def is_base_tuple ( type_str ) :
"""A predicate that matches a tuple type with no array dimension list .""" | try :
abi_type = grammar . parse ( type_str )
except exceptions . ParseError :
return False
return isinstance ( abi_type , grammar . TupleType ) and abi_type . arrlist is None |
def run ( self , * coros ) :
"""Pass in all the coroutines you want to run , it will wrap each one
in a task , run it and wait for the result . Return a list with all
results , this is returned in the same order coros are passed in .""" | tasks = [ asyncio . ensure_future ( coro ( ) ) for coro in coros ]
done , _ = self . loop . run_until_complete ( asyncio . wait ( tasks ) )
return [ t . result ( ) for t in done ] |
def connection_from_host ( self , host , port = None , scheme = 'http' , pool_kwargs = None ) :
"""Get a : class : ` ConnectionPool ` based on the host , port , and scheme .
If ` ` port ` ` isn ' t given , it will be derived from the ` ` scheme ` ` using
` ` urllib3 . connectionpool . port _ by _ scheme ` ` . I... | if not host :
raise LocationValueError ( "No host specified." )
request_context = self . _merge_pool_kwargs ( pool_kwargs )
request_context [ 'scheme' ] = scheme or 'http'
if not port :
port = port_by_scheme . get ( request_context [ 'scheme' ] . lower ( ) , 80 )
request_context [ 'port' ] = port
request_contex... |
def setup_tmpltbank_without_frames ( workflow , output_dir , tags = None , independent_ifos = False , psd_files = None ) :
'''Setup CBC workflow to use a template bank ( or banks ) that are generated in
the workflow , but do not use the data to estimate a PSD , and therefore do
not vary over the duration of the... | if tags is None :
tags = [ ]
cp = workflow . cp
# Need to get the exe to figure out what sections are analysed , what is
# discarded etc . This should * not * be hardcoded , so using a new executable
# will require a bit of effort here . . . .
ifos = workflow . ifos
fullSegment = workflow . analysis_time
tmplt_bank... |
def variable_summaries ( var ) :
"""Attach a lot of summaries to a Tensor ( for TensorBoard visualization ) .""" | with tf . name_scope ( 'summaries' ) :
mean = tf . reduce_mean ( var )
tf . summary . scalar ( 'mean' , mean )
with tf . name_scope ( 'stddev' ) :
stddev = tf . sqrt ( tf . reduce_mean ( tf . square ( var - mean ) ) )
tf . summary . scalar ( 'stddev' , stddev )
tf . summary . scalar ( 'max' ... |
def get_between_times ( self , t1 , t2 , target = None ) :
"""Query for OPUS data between times t1 and t2.
Parameters
t1 , t2 : datetime . datetime , strings
Start and end time for the query . If type is datetime , will be
converted to isoformat string . If type is string already , it needs
to be in an ac... | try : # checking if times have isoformat ( ) method ( datetimes have )
t1 = t1 . isoformat ( )
t2 = t2 . isoformat ( )
except AttributeError : # if not , should already be a string , so do nothing .
pass
myquery = self . _get_time_query ( t1 , t2 )
if target is not None :
myquery [ "target" ] = target
s... |
def list_blobs ( storage_conn = None , ** kwargs ) :
'''. . versionadded : : 2015.8.0
List blobs associated with the container''' | if not storage_conn :
storage_conn = get_storage_conn ( opts = kwargs )
if 'container' not in kwargs :
raise SaltSystemExit ( code = 42 , msg = 'An storage container name must be specified as "container"' )
data = storage_conn . list_blobs ( container_name = kwargs [ 'container' ] , prefix = kwargs . get ( 'pre... |
def Decode ( self , attribute , value ) :
"""Decode the value to the required type .""" | required_type = self . _attribute_types . get ( attribute , "bytes" )
if required_type == "integer" :
return rdf_structs . SignedVarintReader ( value , 0 ) [ 0 ]
elif required_type == "unsigned_integer" :
return rdf_structs . VarintReader ( value , 0 ) [ 0 ]
elif required_type == "string" :
if isinstance ( ... |
def setColorAlpha ( self , fixed = None , proportional = None ) :
"""Change the alpha of the current : py : class : ` Color ` .
: param fixed : Set the absolute 0-1 value of the alpha .
: param proportional : Set the relative value of the alpha ( Es : If the current alpha is 0.8 , a proportional value of 0.5 wi... | if fixed != None :
self . color . set_alpha ( fixed )
elif proportional != None :
self . color . set_alpha ( self . color . get_alpha ( ) * proportional ) |
def add_to_collection ( self , request , pk = None ) :
"""Add Entity to a collection .""" | entity = self . get_object ( )
# TODO use ` self . get _ ids ` ( and elsewhere ) . Backwards
# incompatible because raised error ' s response contains
# ` ` detail ` ` instead of ` ` error ` ` ) .
if 'ids' not in request . data :
return Response ( { "error" : "`ids` parameter is required" } , status = status . HTTP... |
def setup_sort_column ( widget , column = 0 , attribute = None , model = None ) :
"""* model * is the : class : ` TreeModelSort ` to act on . Defaults to what is
displayed . Pass this if you sort before filtering .
* widget * is a clickable : class : ` TreeViewColumn ` .
* column * is an integer addressing th... | if not attribute :
attribute = widget . get_name ( )
if attribute is None :
raise TypeError ( "Column not named" )
widget . connect ( 'clicked' , _clicked , column , attribute , model ) |
def namespace ( self , value ) :
"""Update the query ' s namespace .
: type value : str""" | if not isinstance ( value , str ) :
raise ValueError ( "Namespace must be a string" )
self . _namespace = value |
def simple_merge ( kls , skeletons ) :
"""Simple concatenation of skeletons into one object
without adding edges between them .""" | if len ( skeletons ) == 0 :
return PrecomputedSkeleton ( )
if type ( skeletons [ 0 ] ) is np . ndarray :
skeletons = [ skeletons ]
ct = 0
edges = [ ]
for skel in skeletons :
edge = skel . edges + ct
edges . append ( edge )
ct += skel . vertices . shape [ 0 ]
return PrecomputedSkeleton ( vertices = n... |
def moving_average ( iterable , n ) :
"""From Python collections module documentation
moving _ average ( [ 40 , 30 , 50 , 46 , 39 , 44 ] ) - - > 40.0 42.0 45.0 43.0""" | it = iter ( iterable )
d = collections . deque ( itertools . islice ( it , n - 1 ) )
d . appendleft ( 0 )
s = sum ( d )
for elem in it :
s += elem - d . popleft ( )
d . append ( elem )
yield s / float ( n ) |
def ParseOptions ( cls , options , configuration_object ) :
"""Parses and validates options .
Args :
options ( argparse . Namespace ) : parser options .
configuration _ object ( CLITool ) : object to be configured by the argument
helper .
Raises :
BadConfigObject : when the configuration object is of th... | if not isinstance ( configuration_object , tools . CLITool ) :
raise errors . BadConfigObject ( 'Configuration object is not an instance of CLITool' )
number_of_extraction_workers = cls . _ParseNumericOption ( options , 'workers' , default_value = 0 )
if number_of_extraction_workers < 0 :
raise errors . BadConf... |
def G_calc ( item1 , item2 ) :
"""Calculate G - measure & G - mean .
: param item1 : PPV or TPR or TNR
: type item1 : float
: param item2 : PPV or TPR or TNR
: type item2 : float
: return : G - measure or G - mean as float""" | try :
result = math . sqrt ( item1 * item2 )
return result
except Exception :
return "None" |
def p_x_boolx ( self , t ) :
"""expression : unop expression
| expression binop expression""" | # todo : ply exposes precedence with % prec , use it .
if len ( t ) == 4 :
t [ 0 ] = bin_priority ( t [ 2 ] , t [ 1 ] , t [ 3 ] )
elif len ( t ) == 3 :
t [ 0 ] = un_priority ( t [ 1 ] , t [ 2 ] )
else :
raise NotImplementedError ( 'unk_len' , len ( t ) )
# pragma : no cover |
def set_map_alpha ( alpha ) :
"""Alpha color of the map tiles
: param alpha : int between 0 and 255 . 0 is completely dark , 255 is full brightness""" | if alpha < 0 or alpha > 255 :
raise Exception ( 'invalid alpha ' + str ( alpha ) )
_global_config . map_alpha = alpha |
def sync_config_tasks ( self ) :
"""Performs the first sync of a list of tasks , often defined in the config file .""" | tasks_by_hash = { _hash_task ( t ) : t for t in self . config_tasks }
for task in self . all_tasks :
if tasks_by_hash . get ( task [ "hash" ] ) :
del tasks_by_hash [ task [ "hash" ] ]
else :
self . collection . remove ( { "_id" : task [ "_id" ] } )
log . debug ( "Scheduler: deleted %s" %... |
def t384 ( args ) :
"""% prog t384
Print out a table converting between 96 well to 384 well""" | p = OptionParser ( t384 . __doc__ )
opts , args = p . parse_args ( args )
plate , splate = get_plate ( )
fw = sys . stdout
for i in plate :
for j , p in enumerate ( i ) :
if j != 0 :
fw . write ( '|' )
fw . write ( p )
fw . write ( '\n' ) |
def hessian ( self , x , y , coeffs , beta , center_x = 0 , center_y = 0 ) :
"""returns Hessian matrix of function d ^ 2f / dx ^ 2 , d ^ f / dy ^ 2 , d ^ 2 / dxdy""" | shapelets = self . _createShapelet ( coeffs )
n_order = self . _get_num_n ( len ( coeffs ) )
dxx_shapelets = self . _dxx_shapelets ( shapelets , beta )
dyy_shapelets = self . _dyy_shapelets ( shapelets , beta )
dxy_shapelets = self . _dxy_shapelets ( shapelets , beta )
n = len ( np . atleast_1d ( x ) )
if n <= 1 :
... |
def build ( self , client , nobuild = False , usecache = True , pull = False ) :
"""Drives the build of the final image - get the list of steps and execute them .
Args :
client ( docker . Client ) : docker client object that will build the image
nobuild ( bool ) : just create dockerfiles , don ' t actually bu... | if not nobuild :
self . update_source_images ( client , usecache = usecache , pull = pull )
width = utils . get_console_width ( )
cprint ( '\n' + '=' * width , color = 'white' , attrs = [ 'bold' ] )
line = 'STARTING BUILD for "%s" (image definition "%s" from %s)\n' % ( self . targetname , self . imagename , self . ... |
def find_first ( data , what ) :
'''Search for ` ` what ` ` in the iterable ` ` data ` ` and return the index of the
first match . Return ` ` None ` ` if no match found .''' | for i , line in enumerate ( data ) :
if contains ( line , what ) :
return i
return None |
def _add_impact_severity ( self , variant_obj , gemini_variant ) :
"""Add the impact severity for the most severe consequence
Args :
variant _ obj ( puzzle . models . Variant )
gemini _ variant ( GeminiQueryRow )""" | gemini_impact = gemini_variant [ 'impact_severity' ]
if gemini_impact == 'MED' :
gemini_impact = 'MEDIUM'
variant_obj . impact_severity = gemini_impact |
def _narrow_unichr ( code_point ) :
"""Retrieves the unicode character representing any given code point , in a way that won ' t break on narrow builds .
This is necessary because the built - in unichr function will fail for ordinals above 0xFFFF on narrow builds ( UCS2 ) ;
ordinals above 0xFFFF would require r... | try :
if len ( code_point . char ) > 1 :
return code_point . char
except AttributeError :
pass
return six . unichr ( code_point ) |
def p_if_statement_2 ( self , p ) :
"""if _ statement : IF LPAREN expr RPAREN statement ELSE statement""" | p [ 0 ] = self . asttypes . If ( predicate = p [ 3 ] , consequent = p [ 5 ] , alternative = p [ 7 ] )
p [ 0 ] . setpos ( p ) |
def _format_exception ( err , is_failure , stdout = None , stderr = None ) :
"""Converts a sys . exc _ info ( ) - style tuple of values into a string .""" | exctype , value , tb = err
# Skip test runner traceback levels
while tb and _is_relevant_tb_level ( tb ) :
tb = tb . tb_next
if is_failure : # Skip assert * ( ) traceback levels
length = _count_relevant_tb_levels ( tb )
msgLines = traceback . format_exception ( exctype , value , tb , length )
else :
msg... |
def json ( content , request = None , response = None , ensure_ascii = False , ** kwargs ) :
"""JSON ( Javascript Serialized Object Notation )""" | if hasattr ( content , 'read' ) :
return content
if isinstance ( content , tuple ) and getattr ( content , '_fields' , None ) :
content = { field : getattr ( content , field ) for field in content . _fields }
return json_converter . dumps ( content , default = _json_converter , ensure_ascii = ensure_ascii , ** ... |
def configure_owner ( self , owner = 'www-data' ) :
"""Shortcut to set process owner data .
: param str | unicode owner : Sets user and group . Default : ` ` www - data ` ` .""" | if owner is not None :
self . main_process . set_owner_params ( uid = owner , gid = owner )
return self |
def get_command ( name ) :
'''Get the command function * name *''' | command = global_commands_table . get ( name . lower ( ) )
if not command :
raise CommandNotFound ( name )
return command |
def normalize ( code ) :
"""Normalize language codes to ISO 639-2 . If all conversions fails , return the
` code ` as it was given .
Args :
code ( str ) : Language / country code .
Returns :
str : ISO 639-2 country code .""" | if len ( code ) == 3 :
return code
normalized = translate ( code )
if normalized :
return normalized
country = countries . get ( code , None )
if country :
return country . alpha3 . lower ( )
return code |
def set_perms ( path , grant_perms = None , deny_perms = None , inheritance = True , reset = False ) :
'''Set permissions for the given path
Args :
path ( str ) :
The full path to the directory .
grant _ perms ( dict ) :
A dictionary containing the user / group and the basic permissions to
grant , ie : ... | return __utils__ [ 'dacl.set_perms' ] ( obj_name = path , obj_type = 'file' , grant_perms = grant_perms , deny_perms = deny_perms , inheritance = inheritance , reset = reset ) |
def mute ( self , mute ) :
"""Mute receiver""" | try :
if ( mute and self . _mute == STATE_OFF ) :
self . send_command ( "MUTE_TOGGLE" )
self . _mute = STATE_ON
return True
elif not mute and self . _mute == STATE_ON :
self . send_command ( "MUTE_TOGGLE" )
self . _mute = STATE_OFF
return True
except requests . ex... |
def answer ( request ) :
"""Save the answer .
GET parameters :
html :
turn on the HTML version of the API
BODY
json in following format :
" answer " : # answer , - - for one answer
" answers " : [ # answer , # answer , # answer . . . ] - - for multiple answers
answer = {
" answer _ class " : str ,... | if request . method == 'GET' :
return render ( request , 'models_answer.html' , { } , help_text = answer . __doc__ )
elif request . method == 'POST' :
practice_filter = get_filter ( request )
practice_context = PracticeContext . objects . from_content ( practice_filter )
saved_answers = _save_answers ( ... |
def get_rst_relation_root_nodes ( docgraph , data = True , rst_namespace = 'rst' ) :
"""yield all nodes that dominate one or more RST relations in the given
document graph ( in no particular order ) .
Parameters
docgraph : DiscourseDocumentGraph
a document graph which contains RST annotations
data : bool ... | rel_attr = rst_namespace + ':rel_name'
for node_id , node_attrs in docgraph . nodes_iter ( data = True ) :
if rel_attr in node_attrs and node_attrs [ rel_attr ] != 'span' :
yield ( node_id , node_attrs [ rel_attr ] , get_span ( docgraph , node_id ) ) if data else ( node_id ) |
def read ( self , ** keys ) :
"""Read the data from disk and return as a numpy array""" | if self . is_scalar :
data = self . fitshdu . read_column ( self . columns , ** keys )
else :
c = keys . get ( 'columns' , None )
if c is None :
keys [ 'columns' ] = self . columns
data = self . fitshdu . read ( ** keys )
return data |
def gene_counts ( self ) :
"""Returns number of elements overlapping each gene name . Expects the
derived class ( VariantCollection or EffectCollection ) to have
an implementation of groupby _ gene _ name .""" | return { gene_name : len ( group ) for ( gene_name , group ) in self . groupby_gene_name ( ) . items ( ) } |
async def run ( self ) :
"""Runs the agent . Answer to the requests made by the Backend .
May raise an asyncio . CancelledError , in which case the agent should clean itself and restart completely .""" | self . _logger . info ( "Agent started" )
self . __backend_socket . connect ( self . __backend_addr )
# Tell the backend we are up and have ` concurrency ` threads available
self . _logger . info ( "Saying hello to the backend" )
await ZMQUtils . send ( self . __backend_socket , AgentHello ( self . __friendly_name , se... |
def _get_table_info ( self ) :
"""Inspect the base to get field names""" | self . fields = [ ]
self . field_info = { }
self . cursor . execute ( 'PRAGMA table_info (%s)' % self . name )
for field_info in self . cursor . fetchall ( ) :
fname = field_info [ 1 ] . encode ( 'utf-8' )
self . fields . append ( fname )
ftype = field_info [ 2 ] . encode ( 'utf-8' )
info = { 'type' : f... |
def cmd ( send , msg , args ) :
"""Pesters somebody .
Syntax : { command } < nick > < message >""" | if not msg or len ( msg . split ( ) ) < 2 :
send ( "Pester needs at least two arguments." )
return
match = re . match ( '(%s+) (.*)' % args [ 'config' ] [ 'core' ] [ 'nickregex' ] , msg )
if match :
message = match . group ( 2 ) + " "
send ( '%s: %s' % ( match . group ( 1 ) , message * 3 ) )
else :
... |
def check_version ( mod , required ) :
"""Require minimum version of module using ` ` _ _ version _ _ ` ` member .""" | vers = tuple ( int ( v ) for v in mod . __version__ . split ( '.' ) [ : 3 ] )
if vers < required :
req = '.' . join ( str ( v ) for v in required )
raise ImproperlyConfigured ( "Module \"%s\" version (%s) must be >= %s." % ( mod . __name__ , mod . __version__ , req ) ) |
def vote ( session , nick , pid , response ) :
"""Votes on a poll .""" | if not response :
return "You have to vote something!"
if response == "n" or response == "nay" :
response = "no"
elif response == "y" or response == "aye" :
response = "yes"
poll = get_open_poll ( session , pid )
if poll is None :
return "That poll doesn't exist or isn't active. Use !poll list to see va... |
def record ( self , action = None , method = None , timeout = None , finish_on_key = None , max_length = None , play_beep = None , trim = None , recording_status_callback = None , recording_status_callback_method = None , recording_status_callback_event = None , transcribe = None , transcribe_callback = None , ** kwarg... | return self . nest ( Record ( action = action , method = method , timeout = timeout , finish_on_key = finish_on_key , max_length = max_length , play_beep = play_beep , trim = trim , recording_status_callback = recording_status_callback , recording_status_callback_method = recording_status_callback_method , recording_st... |
def get_details ( self ) :
"""Overrides the method in Failure so as to add a few details about the wrapped function and outcome""" | if isinstance ( self . validation_outcome , Exception ) :
if isinstance ( self . validation_outcome , Failure ) : # do not say again what was the value , it is already mentioned inside : )
end_str = ''
else :
end_str = ' for value [{value}]' . format ( value = self . wrong_value )
contents =... |
def zip_patterns ( self , patterns ) :
"""Append suffix to patterns in dictionary if
we are in a conditional FP tree .""" | suffix = self . root . value
if suffix is not None : # We are in a conditional tree .
new_patterns = { }
for key in patterns . keys ( ) :
new_patterns [ tuple ( sorted ( list ( key ) + [ suffix ] ) ) ] = patterns [ key ]
return new_patterns
return patterns |
def database_url ( self ) :
"""Returns a " database URL " for use with DJ - Database - URL and similar
libraries .""" | return 'postgres://{}:{}@{}/{}' . format ( self . user , self . password , self . name , self . database ) |
def Q_weir_V_Shen ( h1 , angle = 90 ) :
r'''Calculates the flow rate across a V - notch ( triangular ) weir from
the height of the liquid above the tip of the notch , and with the angle
of the notch . Most of these type of weir are 90 degrees . Model from [ 1 ] _
as reproduced in [ 2 ] _ .
Flow rate is give... | C = interp ( angle , angles_Shen , Cs_Shen )
k = interp ( angle , angles_Shen , k_Shen )
return C * tan ( radians ( angle ) / 2 ) * g ** 0.5 * ( h1 + k ) ** 2.5 |
def deseq2_size_factors ( counts , meta , design ) :
"""Get size factors for counts using DESeq2.
Parameters
counts : pandas . DataFrame
Counts to pass to DESeq2.
meta : pandas . DataFrame
Pandas dataframe whose index matches the columns of counts . This is
passed to DESeq2 ' s colData .
design : str ... | import rpy2 . robjects as r
from rpy2 . robjects import pandas2ri
pandas2ri . activate ( )
r . r ( 'suppressMessages(library(DESeq2))' )
r . globalenv [ 'counts' ] = counts
r . globalenv [ 'meta' ] = meta
r . r ( 'dds = DESeqDataSetFromMatrix(countData=counts, colData=meta, ' 'design={})' . format ( design ) )
r . r ( ... |
def update_contact ( self , contact_id , email = None , name = None ) :
"""Update a current contact
: param contact _ id : contact id
: param email : user email
: param name : user name""" | params = { }
if email is not None :
params [ 'email' ] = email
if name is not None :
params [ 'name' ] = name
url = self . CONTACTS_ID_URL % contact_id
connection = Connection ( self . token )
connection . set_url ( self . production , url )
connection . add_header ( 'Content-Type' , 'application/json' )
connec... |
def bgblack ( cls , string , auto = False ) :
"""Color - code entire string .
: param str string : String to colorize .
: param bool auto : Enable auto - color ( dark / light terminal ) .
: return : Class instance for colorized string .
: rtype : Color""" | return cls . colorize ( 'bgblack' , string , auto = auto ) |
def image_size ( self , pnmfile ) :
"""Get width and height of pnm file .
simeon @ homebox src > pnmfile / tmp / 214-2 . png
/ tmp / 214-2 . png : PPM raw , 100 by 100 maxval 255""" | pout = os . popen ( self . shellsetup + self . pnmfile + ' ' + pnmfile , 'r' )
pnmfileout = pout . read ( 200 )
pout . close ( )
m = re . search ( ', (\d+) by (\d+) ' , pnmfileout )
if ( m is None ) :
raise IIIFError ( text = "Bad output from pnmfile when trying to get size." )
w = int ( m . group ( 1 ) )
h = int (... |
def _get ( self , url ) :
"""Handles api . football - data . org requests""" | req = requests . get ( RequestHandler . BASE_URL + url , headers = self . headers )
status_code = req . status_code
if status_code == requests . codes . ok :
return req
elif status_code == requests . codes . bad :
raise APIErrorException ( 'Invalid request. Check parameters.' )
elif status_code == requests . co... |
def parse_json ( self , req , name , field ) :
"""Pull a json value from the request .""" | json_data = self . _cache . get ( "json" )
if json_data is None :
try :
self . _cache [ "json" ] = json_data = core . parse_json ( req . body , req . charset )
except json . JSONDecodeError as e :
if e . doc == "" :
return core . missing
else :
return self . handl... |
def set ( self , key , value , * , flags = None ) :
"""Sets the Key to the given Value
Parameters :
key ( str ) : Key to set
value ( Payload ) : Value to set , It will be encoded by flags
flags ( int ) : Flags to set with value""" | self . append ( { "Verb" : "set" , "Key" : key , "Value" : encode_value ( value , flags , base64 = True ) . decode ( "utf-8" ) , "Flags" : flags } )
return self |
def set_summary ( self ) :
"""Parses summary and set value""" | try :
self . summary = self . soup . find ( 'itunes:summary' ) . string
except AttributeError :
self . summary = None |
def parse ( self , kv ) :
"""Parses key value string into dict
Examples :
> > parser . parse ( ' test1 . test2 = value ' )
{ ' test1 ' : { ' test2 ' : ' value ' } }
> > parser . parse ( ' test = value ' )
{ ' test ' : ' value ' }""" | key , val = kv . split ( self . kv_sep , 1 )
keys = key . split ( self . keys_sep )
for k in reversed ( keys ) :
val = { k : val }
return val |
def find_iter_window ( bitstream , pattern , max_pos = None ) :
"""> > > pattern = list ( bytes2bit _ strings ( " B " ) )
> > > bitstream = bytes2bit _ strings ( " AAABCCC " )
> > > find _ iter _ window ( bitstream , pattern )
24
> > > " " . join ( list ( bitstream2string ( bitstream ) ) )
' CCC '
> > >... | assert isinstance ( bitstream , ( collections . Iterable , types . GeneratorType ) )
assert isinstance ( pattern , ( list , tuple ) )
window_size = len ( pattern )
pos = - 1
for pos , data in enumerate ( iter_window ( bitstream , window_size ) ) : # print pos , data , pattern
if data == pattern :
return pos... |
def full_research_organism ( soup ) :
"research - organism list including inline tags , such as italic" | if not raw_parser . research_organism_keywords ( soup ) :
return [ ]
return list ( map ( node_contents_str , raw_parser . research_organism_keywords ( soup ) ) ) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.