signature stringlengths 29 44.1k | implementation stringlengths 0 85.2k |
|---|---|
def inheritdocstring ( name , bases , attrs ) :
"""Use as metaclass to inherit class and method docstrings from parent .
Adapted from http : / / stackoverflow . com / questions / 13937500 / inherit - a - parent - class - docstring - as - doc - attribute
Use this on classes defined in solver - specific interface... | if '__doc__' not in attrs or not attrs [ "__doc__" ] : # create a temporary ' parent ' to ( greatly ) simplify the MRO search
temp = type ( 'temporaryclass' , bases , { } )
for cls in inspect . getmro ( temp ) :
if cls . __doc__ is not None :
attrs [ '__doc__' ] = cls . __doc__
b... |
def add_isoquant_data ( peptides , quantpeptides , quantacc , quantfields ) :
"""Runs through a peptide table and adds quant data from ANOTHER peptide
table that contains that data .""" | for peptide in base_add_isoquant_data ( peptides , quantpeptides , peptabledata . HEADER_PEPTIDE , quantacc , quantfields ) :
yield peptide |
def is_true ( entity , prop , name ) :
"bool : True if the value of a property is True ." | return is_not_empty ( entity , prop , name ) and name in entity . _data and bool ( getattr ( entity , name ) ) |
def to_dict ( self ) :
"""Convert back to the pstats dictionary representation ( used for saving back as pstats binary file )""" | if self . subcall is not None :
if isinstance ( self . subcall , dict ) :
subcalls = self . subcall
else :
subcalls = { }
for s in self . subcall :
subcalls . update ( s . to_dict ( ) )
return { ( self . filename , self . line_number , self . name ) : ( self . ncalls , se... |
def getPeers ( self ) :
'''getPeers - Get elements who share a parent with this element
@ return - TagCollection of elements''' | parentNode = self . parentNode
# If no parent , no peers
if not parentNode :
return None
peers = parentNode . children
# Otherwise , get all children of parent excluding this node
return TagCollection ( [ peer for peer in peers if peer is not self ] ) |
def rule110_network ( ) :
"""A network of three elements which follows the logic of the Rule 110
cellular automaton with current and previous state ( 0 , 0 , 0 ) .""" | tpm = np . array ( [ [ 0 , 0 , 0 ] , [ 1 , 0 , 1 ] , [ 1 , 1 , 0 ] , [ 1 , 1 , 1 ] , [ 0 , 1 , 1 ] , [ 1 , 1 , 1 ] , [ 1 , 1 , 1 ] , [ 0 , 0 , 0 ] ] )
return Network ( tpm , node_labels = LABELS [ : tpm . shape [ 1 ] ] ) |
def get_sell ( self , account_id , sell_id , ** params ) :
"""https : / / developers . coinbase . com / api / v2 # show - a - sell""" | response = self . _get ( 'v2' , 'accounts' , account_id , 'sells' , sell_id , params = params )
return self . _make_api_object ( response , Sell ) |
def push_broks_to_broker ( self ) : # pragma : no cover - not used !
"""Send all broks from arbiter internal list to broker
The arbiter get some broks and then pushes them to all the brokers .
: return : None""" | someone_is_concerned = False
sent = False
for broker_link in self . conf . brokers : # Send only if the broker is concerned . . .
if not broker_link . manage_arbiters :
continue
someone_is_concerned = True
if broker_link . reachable :
logger . debug ( "Sending %d broks to the broker %s" , le... |
def get_stackdelta ( op ) :
"""Returns the number of elements that the instruction * op * adds to the stack .
# Arguments
op ( dis . Instruction ) : The instruction to retrieve the stackdelta value for .
# Raises
KeyError : If the instruction * op * is not supported .""" | res = opstackd [ op . opname ]
if callable ( res ) :
res = res ( op )
return res |
def verify_token ( id_token , request , audience = None , certs_url = _GOOGLE_OAUTH2_CERTS_URL ) :
"""Verifies an ID token and returns the decoded token .
Args :
id _ token ( Union [ str , bytes ] ) : The encoded token .
request ( google . auth . transport . Request ) : The object used to make
HTTP requests... | certs = _fetch_certs ( request , certs_url )
return jwt . decode ( id_token , certs = certs , audience = audience ) |
def set_exclude_replies ( self , exclude ) :
"""Sets ' exclude _ replies ' parameter used to prevent replies from appearing in the returned timeline
: param exclude : Boolean triggering the usage of the parameter
: raises : TwitterSearchException""" | if not isinstance ( exclude , bool ) :
raise TwitterSearchException ( 1008 )
self . arguments . update ( { 'exclude_replies' : 'true' if exclude else 'false' } ) |
def _find_assert_stmt ( filename , linenumber , leading = 1 , following = 2 , module_globals = None ) :
'''Given a Python module name , filename and line number , find
the lines that are part of the statement containing that line .
Python stacktraces , when reporting which line they ' re on , always
show the ... | lines = linecache . getlines ( filename , module_globals = module_globals )
_source = '' . join ( lines )
_tree = ast . parse ( _source )
finder = _StatementFinder ( linenumber )
finder . visit ( _tree )
line_range = range ( finder . found - leading , linenumber + following )
return line_range , finder . found |
def get_connection ( self , * args , ** kwargs ) :
"""Ensure assert _ hostname is set correctly on our pool
We already take care of a normal poolmanager via init _ poolmanager
But we still need to take care of when there is a proxy poolmanager""" | conn = super ( SSLHTTPAdapter , self ) . get_connection ( * args , ** kwargs )
if conn . assert_hostname != self . assert_hostname :
conn . assert_hostname = self . assert_hostname
return conn |
def decompress_amount ( x ) :
"""Undo the value compression performed by x = compress _ amount ( n ) . The input
x matches one of the following patterns :
x = n = 0
x = 1 + 10 * ( 9 * n + d - 1 ) + e
x = 1 + 10 * ( n - 1 ) + 9""" | if not x :
return 0 ;
x = x - 1 ;
# x = 10 * ( 9 * n + d - 1 ) + e
x , e = divmod ( x , 10 ) ;
n = 0 ;
if e < 9 : # x = 9 * n + d - 1
x , d = divmod ( x , 9 )
d = d + 1
# x = n
n = x * 10 + d
else :
n = x + 1
return n * 10 ** e |
def failover ( self , name ) :
"""Force a failover of a named master .""" | fut = self . execute ( b'FAILOVER' , name )
return wait_ok ( fut ) |
def import_name ( mod_name ) :
"""Import a module by module name .
@ param mod _ name : module name .""" | try :
mod_obj_old = sys . modules [ mod_name ]
except KeyError :
mod_obj_old = None
if mod_obj_old is not None :
return mod_obj_old
__import__ ( mod_name )
mod_obj = sys . modules [ mod_name ]
return mod_obj |
def make_bernstein_vazirani_circuit ( input_qubits , output_qubit , oracle ) :
"""Solves for factors in f ( a ) = a · factors + bias ( mod 2 ) with one query .""" | c = cirq . Circuit ( )
# Initialize qubits .
c . append ( [ cirq . X ( output_qubit ) , cirq . H ( output_qubit ) , cirq . H . on_each ( * input_qubits ) , ] )
# Query oracle .
c . append ( oracle )
# Measure in X basis .
c . append ( [ cirq . H . on_each ( * input_qubits ) , cirq . measure ( * input_qubits , key = 're... |
def post ( self , request , * args , ** kwargs ) :
"""The only circumstances when we POST is to submit the main form , both
updating translations ( if any changed ) and advancing to the next page of
messages .
There is no notion of validation of this content ; as implemented , unknown
fields are ignored and... | # The message text inputs are captured as hashes of their initial
# contents , preceded by " m _ " . Messages with plurals end with their
# variation number .
single_text_input_regex = re . compile ( r'^m_([0-9a-f]+)$' )
plural_text_input_regex = re . compile ( r'^m_([0-9a-f]+)_([0-9]+)$' )
file_change = False
for fiel... |
def rename_dimension ( x , old_name , new_name ) :
"""Reshape a Tensor , renaming one dimension .
Args :
x : a Tensor
old _ name : a string
new _ name : a string
Returns :
a Tensor""" | return reshape ( x , x . shape . rename_dimension ( old_name , new_name ) ) |
def hid_device_path_exists ( device_path , guid = None ) :
"""Test if required device _ path is still valid
( HID device connected to host )""" | # expecing HID devices
if not guid :
guid = winapi . GetHidGuid ( )
info_data = winapi . SP_DEVINFO_DATA ( )
info_data . cb_size = sizeof ( winapi . SP_DEVINFO_DATA )
with winapi . DeviceInterfaceSetInfo ( guid ) as h_info :
for interface_data in winapi . enum_device_interfaces ( h_info , guid ) :
test_... |
def set_title ( self , table = None , title = None , verbose = None ) :
"""Changes the visible identifier of a single table .
: param table ( string , optional ) : Specifies a table by table name . If the pr
efix SUID : is used , the table corresponding the SUID will be returne
: param title ( string , option... | PARAMS = set_param ( [ 'table' , 'title' ] , [ table , title ] )
response = api ( url = self . __url + "/set title" , PARAMS = PARAMS , method = "POST" , verbose = verbose )
return response |
def validate_schema ( sconf ) :
"""Return True if config schema is correct .
Parameters
sconf : dict
session configuration
Returns
bool""" | # verify session _ name
if 'session_name' not in sconf :
raise exc . ConfigError ( 'config requires "session_name"' )
if 'windows' not in sconf :
raise exc . ConfigError ( 'config requires list of "windows"' )
for window in sconf [ 'windows' ] :
if 'window_name' not in window :
raise exc . ConfigErr... |
def loadJSON ( self , jdata ) :
"""Initializes the information for this class from the given JSON data blob .
: param jdata : < dict >""" | # required params
self . __name = jdata [ 'name' ]
self . __field = jdata [ 'field' ]
# optional fields
self . __display = jdata . get ( 'display' ) or self . __display
self . __flags = jdata . get ( 'flags' ) or self . __flags
self . __defaultOrder = jdata . get ( 'defaultOrder' ) or self . __defaultOrder
self . __def... |
def service_timeouts ( self ) :
"""run callbacks on all expired timers
Called from the event thread
: return : next end time , or None""" | queue = self . _queue
if self . _new_timers :
new_timers = self . _new_timers
while new_timers :
heappush ( queue , new_timers . pop ( ) )
if queue :
now = time . time ( )
while queue :
try :
timer = queue [ 0 ] [ 1 ]
if timer . finish ( now ) :
he... |
def add_paths ( paths , base_path , operations ) :
"""Add paths to swagger .""" | for operation , ns , rule , func in operations :
path = build_path ( operation , ns )
if not path . startswith ( base_path ) :
continue
method = operation . value . method . lower ( )
# If there is no version number or prefix , we ' d expect the base path to be " "
# However , OpenAPI requir... |
def _analyze ( self ) :
'''Run - once function to generate analysis over all series , considering both full and partial data .
Initializes the self . analysis dict which maps :
( non - reference ) column / series - > ' full ' and / or ' partial ' - > stats dict returned by get _ xy _ dataset _ statistics''' | if not self . analysis :
for dseries in self . data_series : # Count number of non - NaN rows
dseries_count = self . df [ dseries ] . count ( )
assert ( len ( self . df_pruned ) <= dseries_count <= len ( self . df ) or dseries_count )
self . analysis [ dseries ] = dict ( partial = None , ful... |
def _extract_cell ( args , cell_body ) :
"""Implements the BigQuery extract magic used to extract query or table data to GCS .
The supported syntax is :
% bq extract < args >
Args :
args : the arguments following ' % bigquery extract ' .""" | env = google . datalab . utils . commands . notebook_environment ( )
config = google . datalab . utils . commands . parse_config ( cell_body , env , False ) or { }
parameters = config . get ( 'parameters' )
if args [ 'table' ] :
table = google . datalab . bigquery . Query . resolve_parameters ( args [ 'table' ] , p... |
def main ( ) :
"""Small run usage exemple""" | # TODO : need to be mv in . rst doc
from reliure . pipeline import Composable
@ Composable
def doc_analyse ( docs ) :
for doc in docs :
yield { "title" : doc , "url" : "http://lost.com/%s" % doc , }
@ Composable
def print_ulrs ( docs ) :
for doc in docs :
print ( doc [ "url" ] )
yield do... |
def right_join ( self , table , one = None , operator = None , two = None ) :
"""Add a right join to the query
: param table : The table to join with , can also be a JoinClause instance
: type table : str or JoinClause
: param one : The first column of the join condition
: type one : str
: param operator ... | if isinstance ( table , JoinClause ) :
table . type = "right"
return self . join ( table , one , operator , two , "right" ) |
def _makeBaseDir ( basedir , quiet ) :
"""Make worker base directory if needed .
@ param basedir : worker base directory relative path
@ param quiet : if True , don ' t print info messages
@ raise CreateWorkerError : on error making base directory""" | if os . path . exists ( basedir ) :
if not quiet :
print ( "updating existing installation" )
return
if not quiet :
print ( "mkdir" , basedir )
try :
os . mkdir ( basedir )
except OSError as exception :
raise CreateWorkerError ( "error creating directory {0}: {1}" . format ( basedir , except... |
def release ( self ) :
"""Release the lock .""" | if self . is_locked_by_me ( ) :
os . remove ( self . lock_filename )
logger . debug ( 'The lock {} is released by me (pid: {}).' . format ( self . lock_filename , self . pid ) )
if self . fd :
os . close ( self . fd )
self . fd = None |
def __tokenize_segments ( self ) :
"""tokenizes every RS3 segment ( i . e . an RST nucleus or satellite ) .
for each token , a node is added to the graph , as well as an edge from
the segment node to the token node . the token node IDs are also added
to ` ` self . tokens ` ` .""" | for seg_node_id in self . segments :
segment_toks = self . node [ seg_node_id ] [ self . ns + ':text' ] . split ( )
for i , tok in enumerate ( segment_toks ) :
tok_node_id = '{0}:{1}_{2}' . format ( self . ns , seg_node_id , i )
self . add_node ( tok_node_id , layers = { self . ns , self . ns + ... |
def is_resource_class_resource_attribute ( rc , attr_name ) :
"""Checks if the given attribute name is a resource attribute ( i . e . , either
a member or a collection attribute ) of the given registered resource .""" | attr = get_resource_class_attribute ( rc , attr_name )
return attr != RESOURCE_ATTRIBUTE_KINDS . TERMINAL |
def setup_model ( x , y , model_type = 'random_forest' , seed = None , ** kwargs ) :
"""Initializes a machine learning model
Args :
x : Pandas DataFrame , X axis of features
y : Pandas Series , Y axis of targets
model _ type : Machine Learning model to use
Valid values : ' random _ forest '
seed : Rando... | assert len ( x ) > 1 and len ( y ) > 1 , 'Not enough data objects to train on (minimum is at least two, you have (x: {0}) and (y: {1}))' . format ( len ( x ) , len ( y ) )
sets = namedtuple ( 'Datasets' , [ 'train' , 'test' ] )
x_train , x_test , y_train , y_test = train_test_split ( x , y , random_state = seed , shuff... |
def aromatize ( self ) :
"""convert structure to aromatic form
: return : number of processed rings""" | rings = [ x for x in self . sssr if 4 < len ( x ) < 7 ]
if not rings :
return 0
total = 0
while True :
c = self . _quinonize ( rings , 'order' )
if c :
total += c
elif total :
break
c = self . _aromatize ( rings , 'order' )
if not c :
break
total += c
if total :
s... |
def union_setadd ( dict1 , dict2 ) :
"""Similar to dictlib . union ( ) , but following a setadd logic ( with strings and ints ) ,
and a union ( with dictionaries ) . Assumption is that all elements of the list
are of the same type ( i . e . if first element is a dict , it tries to union all
elements )
NOT d... | for key2 , val2 in dict2 . items ( ) : # if key is in both places , do a union
if key2 in dict1 : # if dict2 val2 is a dict , assume dict1 val2 is as well
if isinstance ( val2 , dict ) :
dict1 [ key2 ] = union_setadd ( dict1 [ key2 ] , val2 )
# if dict2 val2 is a list , things get uglier... |
def split_option ( self , section , option ) :
"""Return list of strings that are made by splitting coma - separated option value . Method returns
empty list if option value is empty string
: param section : option section name
: param option : option name
: return : list of strings""" | value = self [ section ] [ option ] . strip ( )
if value == "" :
return [ ]
return [ x . strip ( ) for x in ( value . split ( "," ) ) ] |
def set_libs_flags ( self , env , arch ) :
'''Takes care to properly link libraries with python depending on our
requirements and the attribute : attr : ` opt _ depends ` .''' | def add_flags ( include_flags , link_dirs , link_libs ) :
env [ 'CPPFLAGS' ] = env . get ( 'CPPFLAGS' , '' ) + include_flags
env [ 'LDFLAGS' ] = env . get ( 'LDFLAGS' , '' ) + link_dirs
env [ 'LIBS' ] = env . get ( 'LIBS' , '' ) + link_libs
if 'sqlite3' in self . ctx . recipe_build_order :
info ( 'Activ... |
def initialize_service_agreement ( did , agreement_id , service_definition_id , signature , account_address , consume_endpoint ) :
"""Send a request to the service provider ( consume _ endpoint ) to initialize the service
agreement for the asset identified by ` did ` .
: param did : id of the asset includes the... | payload = Brizo . _prepare_consume_payload ( did , agreement_id , service_definition_id , signature , account_address )
response = Brizo . _http_client . post ( consume_endpoint , data = payload , headers = { 'content-type' : 'application/json' } )
if response and hasattr ( response , 'status_code' ) :
if response ... |
def numpy ( self , single_components = False ) :
"""Get a numpy array copy representing the underlying image data . Altering
this ndarray will have NO effect on the underlying image data .
Arguments
single _ components : boolean ( default is False )
if True , keep the extra component dimension in returned a... | array = np . array ( self . view ( single_components = single_components ) , copy = True , dtype = self . dtype )
if self . has_components or ( single_components == True ) :
array = np . rollaxis ( array , 0 , self . dimension + 1 )
return array |
def clean_str ( string ) :
"""Tokenization / string cleaning for all datasets except for SST .
Original taken from https : / / github . com / yoonkim / CNN _ sentence / blob / master / process _ data . py""" | string = re . sub ( r"[^A-Za-z0-9(),!?\'\`]" , " " , string )
string = re . sub ( r"\'s" , " \'s" , string )
string = re . sub ( r"\'ve" , " \'ve" , string )
string = re . sub ( r"n\'t" , " n\'t" , string )
string = re . sub ( r"\'re" , " \'re" , string )
string = re . sub ( r"\'d" , " \'d" , string )
string = re . sub... |
def check_config_mode ( self , check_string = "" , pattern = "" ) :
"""Checks if the device is in configuration mode or not .
: param check _ string : Identification of configuration mode from the device
: type check _ string : str
: param pattern : Pattern to terminate reading of channel
: type pattern : s... | self . write_channel ( self . RETURN )
# You can encounter an issue here ( on router name changes ) prefer delay - based solution
if not pattern :
output = self . _read_channel_timing ( )
else :
output = self . read_until_pattern ( pattern = pattern )
return check_string in output |
def is_monotonic ( full_list ) :
"""Determine whether elements in a list are monotonic . ie . unique
elements are clustered together .
ie . [ 5,5,3,4 ] is , [ 5,3,5 ] is not .""" | prev_elements = set ( { full_list [ 0 ] } )
prev_item = full_list [ 0 ]
for item in full_list :
if item != prev_item :
if item in prev_elements :
return False
prev_item = item
prev_elements . add ( item )
return True |
def _handle_tag_removeobject2 ( self ) :
"""Handle the RemoveObject2 tag .""" | obj = _make_object ( "RemoveObject2" )
obj . Depth = unpack_ui16 ( self . _src )
return obj |
def loadValues ( self , values ) :
"""Loads the values from the inputed dictionary to the widget .
: param values | < dict >""" | table = self . tableType ( )
if table :
schema = table . schema ( )
else :
schema = None
process = [ ]
for widget in self . findChildren ( QWidget ) :
prop = widget . property ( 'columnName' )
if not prop :
continue
order = widget . property ( 'columnOrder' )
if order :
order = u... |
def _proxy ( self ) :
"""Generate an instance context for the instance , the context is capable of
performing various actions . All instance actions are proxied to the context
: returns : IpAddressContext for this IpAddressInstance
: rtype : twilio . rest . api . v2010 . account . sip . ip _ access _ control ... | if self . _context is None :
self . _context = IpAddressContext ( self . _version , account_sid = self . _solution [ 'account_sid' ] , ip_access_control_list_sid = self . _solution [ 'ip_access_control_list_sid' ] , sid = self . _solution [ 'sid' ] , )
return self . _context |
def tokenize ( self : object , untokenized_string : str , include_blanks = False ) :
"""Tokenize lines by ' \n ' .
: type untokenized _ string : str
: param untokenized _ string : A string containing one of more sentences .
: param include _ blanks : Boolean ; If True , blanks will be preserved by " " in retu... | # load tokenizer
assert isinstance ( untokenized_string , str ) , 'Incoming argument must be a string.'
# make list of tokenized sentences
if include_blanks :
tokenized_lines = untokenized_string . splitlines ( )
else :
tokenized_lines = [ line for line in untokenized_string . splitlines ( ) if line != '' ]
ret... |
def auto_str ( __repr__ = False ) :
"""Use this decorator to auto implement _ _ str _ _ ( ) and optionally _ _ repr _ _ ( ) methods on classes .
Args :
_ _ repr _ _ ( bool ) : If set to true , the decorator will auto - implement the _ _ repr _ _ ( ) method as
well .
Returns :
callable : Decorating functio... | def _decorator ( cls ) :
def __str__ ( self ) :
items = [ "{name}={value}" . format ( name = name , value = vars ( self ) [ name ] . __repr__ ( ) ) for name in [ key for key in sorted ( vars ( self ) ) ] if name not in get_field_mro ( self . __class__ , '__auto_str_ignore__' ) ]
# pylint : disable =... |
def parse ( raw_email ) : # type : ( six . string _ types ) - > Tuple [ six . string _ types , six . string _ types ]
"""Extract email from a full address . Example :
' John Doe < jdoe + github @ foo . com > ' - > jdoe @ foo . com
> > > parse ( " John Doe < me + github . com @ someorg . com " )
( ' me ' , ' s... | if not isinstance ( raw_email , six . string_types ) :
raise InvalidEmail ( "Invalid email: %s" % raw_email )
if not raw_email or pd . isnull ( raw_email ) :
raise InvalidEmail ( "None or NaN is not a valid email address" )
email = raw_email . split ( "<" , 1 ) [ - 1 ] . split ( ">" , 1 ) [ 0 ]
chunks = email .... |
def getCoeffs ( date ) :
""": param gh : list from loadCoeffs
: param date : float
: return : list : g , list : h""" | if date < 1900.0 or date > 2025.0 :
print ( 'This subroutine will not work with a date of ' + str ( date ) )
print ( 'Date must be in the range 1900.0 <= date <= 2025.0' )
print ( 'On return [], []' )
return [ ] , [ ]
elif date >= 2015.0 :
if date > 2020.0 : # not adapt for the model but can calcula... |
def woe ( df , feature_name , target_name ) :
"""Calculate weight of evidence .
Parameters
df : Dataframe
feature _ name : str
Column name to encode .
target _ name : str
Target column name .
Returns
Series""" | def group_woe ( group ) :
event = float ( group . sum ( ) )
non_event = group . shape [ 0 ] - event
rel_event = event / event_total
rel_non_event = non_event / non_event_total
return np . log ( rel_non_event / rel_event ) * 100
if df [ target_name ] . nunique ( ) > 2 :
raise ValueError ( 'Target... |
async def become ( self , layer_type : Type [ L ] , request : 'Request' ) :
"""Transforms the translatable string into an actual string and put it
inside a RawText .""" | if layer_type != RawText :
super ( Text , self ) . become ( layer_type , request )
return RawText ( await render ( self . text , request ) ) |
def partition_all ( s , sep ) :
"""Uses str . partition ( ) to split every occurrence of sep in s . The returned list does not contain empty strings .
If sep is a list , all separators are evaluated .
: param s : The string to split .
: param sep : A separator string or a list of separator strings .
: retur... | if isinstance ( sep , list ) :
parts = _partition_all_internal ( s , sep [ 0 ] )
sep = sep [ 1 : ]
for s in sep :
tmp = [ ]
for p in parts :
tmp . extend ( _partition_all_internal ( p , s ) )
parts = tmp
return parts
else :
return _partition_all_internal ( s , sep... |
def _request ( self , msg_type , msg_data = None ) :
"""Helper function to wrap msg w / msg _ type .""" | msg = { }
msg [ 'type' ] = msg_type
if msg_data :
msg [ 'data' ] = msg_data
done = False
tries = 0
while not done and tries < MAX_RETRIES :
try :
MessageSocket . send ( self , self . sock , msg )
done = True
except socket . error as e :
tries += 1
if tries >= MAX_RETRIES :
... |
def _wait_until ( obj , att , desired , callback , interval , attempts , verbose , verbose_atts ) :
"""Loops until either the desired value of the attribute is reached , or the
number of attempts is exceeded .""" | if not isinstance ( desired , ( list , tuple ) ) :
desired = [ desired ]
if verbose_atts is None :
verbose_atts = [ ]
if not isinstance ( verbose_atts , ( list , tuple ) ) :
verbose_atts = [ verbose_atts ]
infinite = ( attempts == 0 )
attempt = 0
start = time . time ( )
while infinite or ( attempt < attempt... |
def touch ( fname , times = None ) :
'''Emulates the UNIX touch command .''' | with io . open ( fname , 'a' ) :
os . utime ( fname , times ) |
def parsebam ( self ) :
"""Parse the dictionaries of the sorted bam files extracted using pysam""" | # Threading is actually the worst - need multiprocessing to make this work at all
logging . info ( 'Parsing BAM files' )
# The sample objects are too big to get pickled . To hack our way around this , try to dump the sample object to
# json , and have the processing function turn the object into a dictionary .
json_fil... |
def sign_cert_request ( filepath , cert_req , ca_crt , ca_key , days , extfile , silent = False ) :
"""generate self signed ssl certificate , i . e . a private CA certificate
: param filepath : file path to the key file
: param keyfile : file path to the private key
: param days : valid duration for the certi... | message = 'sign certificate request'
cmd = ( 'openssl x509 -req -in {} -CA {} -CAkey {} -CAcreateserial' ' -out {} -days {} -extfile {} -extensions v3_req' ) . format ( cert_req , ca_crt , ca_key , filepath , days , extfile )
call_openssl ( cmd , message , silent ) |
def forbid_web_access ( f ) :
"""Forbids running task using http request .
: param f : Callable
: return Callable""" | @ wraps ( f )
def wrapper_fn ( * args , ** kwargs ) :
if isinstance ( JobContext . get_current_context ( ) , WebJobContext ) :
raise ForbiddenError ( 'Access forbidden from web.' )
return f ( * args , ** kwargs )
return wrapper_fn |
def list_pools_on_lbaas_agent ( self , lbaas_agent , ** _params ) :
"""Fetches a list of pools hosted by the loadbalancer agent .""" | return self . get ( ( self . agent_path + self . LOADBALANCER_POOLS ) % lbaas_agent , params = _params ) |
def subscribe ( self , peer_jid ) :
"""Request presence subscription with the given ` peer _ jid ` .
This is deliberately not a coroutine ; we don ’ t know whether the peer is
online ( usually ) and they may defer the confirmation very long , if they
confirm at all . Use : meth : ` on _ subscribed ` to get no... | self . client . enqueue ( stanza . Presence ( type_ = structs . PresenceType . SUBSCRIBE , to = peer_jid ) ) |
def batch_find ( self , * dbqueries ) :
"""Returns array of results from queries dbqueries .
: param dbqueries : Array of individual queries as dictionaries
: type dbqueries : ` ` array ` ` of ` ` dict ` `
: return : Results of each query
: rtype : ` ` array ` ` of ` ` array ` `""" | if len ( dbqueries ) < 1 :
raise Exception ( 'Must have at least one query.' )
data = json . dumps ( dbqueries )
return json . loads ( self . _post ( 'batch_find' , headers = KVStoreCollectionData . JSON_HEADER , body = data ) . body . read ( ) . decode ( 'utf-8' ) ) |
def files ( self ) :
"""Return the names of files to be created .""" | files_description = [ [ self . project_name , 'bootstrap' , 'BootstrapScriptFileTemplate' ] , [ self . project_name , 'CHANGES.txt' , 'PythonPackageCHANGESFileTemplate' ] , [ self . project_name , 'LICENSE.txt' , 'GPL3FileTemplate' ] , [ self . project_name , 'MANIFEST.in' , 'PythonPackageMANIFESTFileTemplate' ] , [ se... |
def from_etree ( cls , etree_element ) :
"""creates a ` ` SaltLayer ` ` instance from the etree representation of an
< layers > element from a SaltXMI file .""" | ins = SaltElement . from_etree ( etree_element )
# TODO : this looks dangerous , ask Stackoverflow about it !
# convert SaltElement into SaltLayer
ins . __class__ = SaltLayer . mro ( ) [ 0 ]
# add nodes and edges that belong to this layer ( if any )
for element in ( 'nodes' , 'edges' ) :
elem_list = [ ]
xpath_r... |
def symmetric_difference ( self , other ) :
"""Combine with another Region by performing the symmetric difference of their pixlists .
Requires both regions to have the same maxdepth .
Parameters
other : : class : ` AegeanTools . regions . Region `
The region to be combined .""" | # work only on the lowest level
# TODO : Allow this to be done for regions with different depths .
if not ( self . maxdepth == other . maxdepth ) :
raise AssertionError ( "Regions must have the same maxdepth" )
self . _demote_all ( )
opd = set ( other . get_demoted ( ) )
self . pixeldict [ self . maxdepth ] . symme... |
def cast_out ( self , klass ) :
"""Interpret the content as a particular class .""" | if _debug :
Any . _debug ( "cast_out %r" , klass )
global _sequence_of_classes , _list_of_classes
# check for a sequence element
if ( klass in _sequence_of_classes ) or ( klass in _list_of_classes ) : # build a sequence helper
helper = klass ( )
# make a copy of the tag list
t = TagList ( self . tagList... |
def getResourceFile ( self , pid , filename , destination = None ) :
"""Get a file within a resource .
: param pid : The HydroShare ID of the resource
: param filename : String representing the name of the resource file to get .
: param destination : String representing the directory to save the resource file... | url = "{url_base}/resource/{pid}/files/{filename}" . format ( url_base = self . url_base , pid = pid , filename = filename )
if destination :
if not os . path . isdir ( destination ) :
raise HydroShareArgumentException ( "{0} is not a directory." . format ( destination ) )
if not os . access ( destinati... |
def find_machine ( self , name_or_id ) :
"""Attempts to find a virtual machine given its name or UUID .
Inaccessible machines cannot be found by name , only by UUID , because their name
cannot safely be determined .
in name _ or _ id of type str
What to search for . This can either be the UUID or the name o... | if not isinstance ( name_or_id , basestring ) :
raise TypeError ( "name_or_id can only be an instance of type basestring" )
machine = self . _call ( "findMachine" , in_p = [ name_or_id ] )
machine = IMachine ( machine )
return machine |
def alter ( self , id_filter , name , description ) :
"""Change Filter by the identifier .
: param id _ filter : Identifier of the Filter . Integer value and greater than zero .
: param name : Name . String with a maximum of 50 characters and respect [ a - zA - Z \ _ - ]
: param description : Description . St... | if not is_valid_int_param ( id_filter ) :
raise InvalidParameterError ( u'The identifier of Filter is invalid or was not informed.' )
filter_map = dict ( )
filter_map [ 'name' ] = name
filter_map [ 'description' ] = description
url = 'filter/' + str ( id_filter ) + '/'
code , xml = self . submit ( { 'filter' : filt... |
def render ( self , ** kwargs ) :
"""Plots the curve and the control points polygon .""" | # Calling parent function
super ( VisCurve3D , self ) . render ( ** kwargs )
# Initialize a list to store VTK actors
vtk_actors = [ ]
# Start plotting
for plot in self . _plots : # Plot control points
if plot [ 'type' ] == 'ctrlpts' and self . vconf . display_ctrlpts : # Points as spheres
pts = np . array (... |
def abort ( self ) :
"""Abort the SBI ( and associated PBs ) .""" | self . set_status ( 'aborted' )
DB . remove_from_list ( '{}:active' . format ( self . _type ) , self . _id )
DB . append_to_list ( '{}:aborted' . format ( self . _type ) , self . _id )
sbi_pb_ids = ast . literal_eval ( DB . get_hash_value ( self . _key , 'processing_block_ids' ) )
for pb_id in sbi_pb_ids :
pb = Pro... |
def Page ( self , text = None , show_percent = None ) :
"""Page text .
Continues to page through any text supplied in the constructor . Also , any
text supplied to this method will be appended to the total text to be
displayed . The method returns when all available text has been displayed to
the user , or ... | if text is not None :
self . _text += text
if show_percent is None :
show_percent = text is None
self . _show_percent = show_percent
text = LineWrap ( self . _text ) . splitlines ( )
while True : # Get a list of new lines to display .
self . _newlines = text [ self . _displayed : self . _displayed + self . ... |
def to_XML ( self , xml_declaration = True , xmlns = True ) :
"""Dumps object fields to an XML - formatted string . The ' xml _ declaration '
switch enables printing of a leading standard XML line containing XML
version and encoding . The ' xmlns ' switch enables printing of qualified
XMLNS prefixes .
: par... | root_node = self . _to_DOM ( )
if xmlns :
xmlutils . annotate_with_XMLNS ( root_node , OBSERVATION_XMLNS_PREFIX , OBSERVATION_XMLNS_URL )
return xmlutils . DOM_node_to_XML ( root_node , xml_declaration ) |
def get_marshaller_for_type_string ( self , type_string ) :
"""Gets the appropriate marshaller for a type string .
Retrieves the marshaller , if any , that can be used to read / write
a Python object with the given type string . The modules it
requires , if available , will be loaded .
Parameters
type _ s... | if type_string in self . _type_strings :
index = self . _type_strings [ type_string ]
m = self . _marshallers [ index ]
if self . _imported_required_modules [ index ] :
return m , True
if not self . _has_required_modules [ index ] :
return m , False
success = self . _import_marshalle... |
def retry_ex ( callback , times = 3 , cap = 120000 ) :
"""Retry a callback function if any exception is raised .
: param function callback : The function to call
: keyword int times : Number of times to retry on initial failure
: keyword int cap : Maximum wait time in milliseconds
: returns : The return val... | for attempt in range ( times + 1 ) :
if attempt > 0 :
time . sleep ( retry_wait_time ( attempt , cap ) / 1000.0 )
try :
return callback ( )
except :
if attempt == times :
raise |
def find_one ( self ) :
"""Return the first index of an entry that is either one or DC .
If no item is found , return None .""" | num = quotient = 0
while num < self . _len :
chunk = self . data [ quotient ]
if chunk & self . one_mask :
remainder = 0
while remainder < self . width and num < self . _len :
item = ( chunk >> remainder ) & 3
if item == PC_ONE :
return num
rem... |
def add_tag ( self , tag , value ) :
"""as tags are kept in a sorted order , a bisection is a fastest way to identify a correct position
of or a new tag to be added . An additional check is required to make sure w don ' t add duplicates""" | index = bisect_left ( self . tags , ( tag , value ) )
contains = False
if index < len ( self . tags ) :
contains = self . tags [ index ] == ( tag , value )
if not contains :
self . tags . insert ( index , ( tag , value ) ) |
def save_data ( self , idx ) :
"""Call method ` save _ data | ` of all handled | IOSequences |
objects registered under | OutputSequencesABC | .""" | for subseqs in self :
if isinstance ( subseqs , abctools . OutputSequencesABC ) :
subseqs . save_data ( idx ) |
def command ( name , mode ) :
"""Label a method as a command with name .""" | def decorator ( fn ) :
commands [ name ] = fn . __name__
_Client . _addMethod ( fn . __name__ , name , mode )
return fn
return decorator |
def mark_offer_as_lose ( self , offer_id ) :
"""Mark offer as lose
: param offer _ id : the offer id
: return Response""" | return self . _create_put_request ( resource = OFFERS , billomat_id = offer_id , command = LOSE , ) |
def sendmail ( subject , text , mailto , sender = None ) :
"""Sends an e - mail with unix sendmail .
Args :
subject : String with the subject of the mail .
text : String with the body of the mail .
mailto : String or list of string with the recipients .
sender : string with the sender address .
If sende... | def user_at_host ( ) :
from socket import gethostname
return os . getlogin ( ) + "@" + gethostname ( )
# Body of the message .
try :
sender = user_at_host ( ) if sender is None else sender
except OSError :
sender = 'abipyscheduler@youknowwhere'
if is_string ( mailto ) :
mailto = [ mailto ]
from emai... |
def getalignedtarget ( self , index ) :
"""Returns target range only if source index aligns to a single consecutive range of target tokens .""" | targetindices = [ ]
target = None
foundindex = - 1
for sourceindex , targetindex in self . alignment :
if sourceindex == index :
targetindices . append ( targetindex )
if len ( targetindices ) > 1 :
for i in range ( 1 , len ( targetindices ) ) :
if abs ( targetindices [ i ] - targetindices [ i -... |
def monitor_session_span_command_direction ( self , ** kwargs ) :
"""Auto Generated Code""" | config = ET . Element ( "config" )
monitor = ET . SubElement ( config , "monitor" , xmlns = "urn:brocade.com:mgmt:brocade-span" )
session = ET . SubElement ( monitor , "session" )
session_number_key = ET . SubElement ( session , "session-number" )
session_number_key . text = kwargs . pop ( 'session_number' )
span_comma... |
def edit_record ( self , new_record ) :
"""Update a record in ArchivesSpace using the provided new _ record .
The format of new _ record is identical to the format returned by get _ resource _ component _ and _ children and related methods ; consult the documentation for that method in ArchivistsToolkitClient to ... | try :
record_id = new_record [ "id" ]
except KeyError :
raise ValueError ( "No record ID provided!" )
record = self . get_record ( record_id )
# TODO : add more fields ?
field_map = { "title" : "title" , "level" : "levelOfDescription" }
fields_updated = False
for field , targetfield in field_map . items ( ) :
... |
def create_transform ( ctx , transform ) :
"""Creates a new transform in the specified directory and auto - updates dependencies .""" | from canari . commands . create_transform import create_transform
create_transform ( ctx . project , transform ) |
def click_link_text ( self , link_text , timeout = settings . SMALL_TIMEOUT ) :
"""This method clicks link text on a page""" | # If using phantomjs , might need to extract and open the link directly
if self . timeout_multiplier and timeout == settings . SMALL_TIMEOUT :
timeout = self . __get_new_timeout ( timeout )
if self . browser == 'phantomjs' :
if self . is_link_text_visible ( link_text ) :
element = self . wait_for_link_t... |
def _parse_tagfile ( self ) :
"""Parse the tagfile and yield tuples of tag _ name , list of rule ASTs .""" | rules = None
tag = None
for line in self . original :
match = self . TAG_DECL_LINE . match ( line )
if match :
if tag and rules :
yield tag , rules
rules = [ ]
tag = match . group ( 1 )
continue
match = self . TAG_RULE_LINE . match ( line )
if match :
... |
def make_qscan_plot ( workflow , ifo , trig_time , out_dir , injection_file = None , data_segments = None , time_window = 100 , tags = None ) :
"""Generate a make _ qscan node and add it to workflow .
This function generates a single node of the singles _ timefreq executable
and adds it to the current workflow ... | tags = [ ] if tags is None else tags
makedir ( out_dir )
name = 'plot_qscan'
curr_exe = PlotQScanExecutable ( workflow . cp , name , ifos = [ ifo ] , out_dir = out_dir , tags = tags )
node = curr_exe . create_node ( )
# Determine start / end times , using data segments if needed .
# Begin by choosing " optimal " times
... |
def _reshape_n_vecs ( self ) :
"""return list of arrays , each array represents a different m mode""" | lst = [ ]
sl = slice ( None , None , None )
lst . append ( self . __getitem__ ( ( sl , 0 ) ) )
for m in xrange ( 1 , self . mmax + 1 ) :
lst . append ( self . __getitem__ ( ( sl , - m ) ) )
lst . append ( self . __getitem__ ( ( sl , m ) ) )
return lst |
def process_args ( ) :
"""Parse command - line arguments .""" | parser = argparse . ArgumentParser ( description = "A file for converting NeuroML v2 files into POVRay files for 3D rendering" )
parser . add_argument ( 'neuroml_file' , type = str , metavar = '<NeuroML file>' , help = 'NeuroML (version 2 beta 3+) file to be converted to PovRay format (XML or HDF5 format)' )
parser . a... |
def min ( self , axis = None , skipna = True , * args , ** kwargs ) :
"""Return the minimum value of the Array or minimum along
an axis .
See Also
numpy . ndarray . min
Index . min : Return the minimum value in an Index .
Series . min : Return the minimum value in a Series .""" | nv . validate_min ( args , kwargs )
nv . validate_minmax_axis ( axis )
result = nanops . nanmin ( self . asi8 , skipna = skipna , mask = self . isna ( ) )
if isna ( result ) : # Period . _ from _ ordinal does not handle np . nan gracefully
return NaT
return self . _box_func ( result ) |
async def amiUsage ( self , * args , ** kwargs ) :
"""See the list of AMIs and their usage
List AMIs and their usage by returning a list of objects in the form :
region : string
volumetype : string
lastused : timestamp
This method is ` ` experimental ` `""" | return await self . _makeApiCall ( self . funcinfo [ "amiUsage" ] , * args , ** kwargs ) |
def get_downstream_causal_subgraph ( graph , nbunch : Union [ BaseEntity , Iterable [ BaseEntity ] ] ) :
"""Induce a sub - graph from all of the downstream causal entities of the nodes in the nbunch .
: type graph : pybel . BELGraph
: rtype : pybel . BELGraph""" | return get_subgraph_by_edge_filter ( graph , build_downstream_edge_predicate ( nbunch ) ) |
def left ( self , speed = 1 ) :
"""Make the robot turn left by running the right motor forward and left
motor backward .
: param float speed :
Speed at which to drive the motors , as a value between 0 ( stopped )
and 1 ( full speed ) . The default is 1.""" | self . right_motor . forward ( speed )
self . left_motor . backward ( speed ) |
def append ( self , s ) :
"""Append the bytestring ` s ` to the compressor state and return the
final compressed output .""" | if self . _compressor is None :
return zlib . compress ( self . s + s , 9 )
else :
compressor = self . _compressor . copy ( )
out = self . _out
out += compressor . compress ( s )
return out + compressor . flush ( ) |
def get_cds_ranges_for_transcript ( self , transcript_id ) :
"""obtain the sequence for a transcript from ensembl""" | headers = { "content-type" : "application/json" }
self . attempt = 0
ext = "/overlap/id/{}?feature=cds" . format ( transcript_id )
r = self . ensembl_request ( ext , headers )
cds_ranges = [ ]
for cds_range in json . loads ( r ) :
if cds_range [ "Parent" ] != transcript_id :
continue
start = cds_range [... |
def pin ( self , mask : str = '####' ) -> str :
"""Generate a random PIN code .
: param mask : Mask of pin code .
: return : PIN code .""" | return self . random . custom_code ( mask = mask ) |
def fetch_hg_push_log ( repo_name , repo_url ) :
"""Run a HgPushlog etl process""" | newrelic . agent . add_custom_parameter ( "repo_name" , repo_name )
process = HgPushlogProcess ( )
process . run ( repo_url + '/json-pushes/?full=1&version=2' , repo_name ) |
def get_value ( self ) -> ScalarType :
"""Returns the value of a Scalar node .
Use is _ scalar ( type ) to check which type the node has .""" | if self . yaml_node . tag == 'tag:yaml.org,2002:str' :
return self . yaml_node . value
if self . yaml_node . tag == 'tag:yaml.org,2002:int' :
return int ( self . yaml_node . value )
if self . yaml_node . tag == 'tag:yaml.org,2002:float' :
return float ( self . yaml_node . value )
if self . yaml_node . tag =... |
def _construct_deutsch_jozsa_circuit ( self ) :
"""Builds the Deutsch - Jozsa circuit . Which can determine whether a function f mapping
: math : ` \ { 0,1 \ } ^ n \t o \ { 0,1 \ } ` is constant or balanced , provided that it is one of them .
: return : A program corresponding to the desired instance of Deutsch... | dj_prog = Program ( )
# Put the first ancilla qubit ( query qubit ) into minus state
dj_prog . inst ( X ( self . ancillas [ 0 ] ) , H ( self . ancillas [ 0 ] ) )
# Apply Hadamard , Oracle , and Hadamard again
dj_prog . inst ( [ H ( qubit ) for qubit in self . computational_qubits ] )
# Build the oracle
oracle_prog = Pr... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.