signature stringlengths 29 44.1k | implementation stringlengths 0 85.2k |
|---|---|
def get_members ( self , name ) :
"""Returns the member interfaces for the specified Port - Channel
Args :
name ( str ) : The Port - channel interface name to return the member
interfaces for
Returns :
A list of physical interface names that belong to the specified
interface""" | grpid = re . search ( r'(\d+)' , name ) . group ( )
command = 'show port-channel %s all-ports' % grpid
config = self . node . enable ( command , 'text' )
return re . findall ( r'\b(?!Peer)Ethernet[\d/]*\b' , config [ 0 ] [ 'result' ] [ 'output' ] ) |
def set_pipeline ( self , pipeline ) :
"""Specify the pipeline . See get _ pipeline _ alternatives to see what are avaialble . Input should be a string .""" | self . add_history ( inspect . stack ( ) [ 0 ] [ 3 ] , locals ( ) , 1 )
if not os . path . exists ( self . BIDS_dir + '/derivatives/' + pipeline ) :
print ( 'Specified direvative directory not found.' )
self . get_pipeline_alternatives ( )
else : # Todo : perform check that pipeline is valid
self . pipeline... |
def run ( self ) :
"""Computes cleared offers and bids .""" | # Start the clock .
t0 = time . time ( )
# Manage reactive power offers / bids .
haveQ = self . _isReactiveMarket ( )
# Withhold offers / bids outwith optional price limits .
self . _withholdOffbids ( )
# Convert offers / bids to pwl functions and update limits .
self . _offbidToCase ( )
# Compute dispatch points and L... |
def batch ( self , table_name , timeout = None ) :
'''Creates a batch object which can be used as a context manager . Commits the batch on exit .
: param str table _ name :
The name of the table to commit the batch to .
: param int timeout :
The server timeout , expressed in seconds .''' | batch = TableBatch ( self . require_encryption , self . key_encryption_key , self . encryption_resolver_function )
yield batch
self . commit_batch ( table_name , batch , timeout = timeout ) |
def InitFromDataPoints ( self , start_stats , complete_stats ) :
"""Check that this approval applies to the given token .
Args :
start _ stats : A list of lists , each containing two values ( a timestamp and
the number of clients started at this time ) .
complete _ stats : A list of lists , each containing ... | self . start_points = self . _ConvertToResultList ( start_stats )
self . complete_points = self . _ConvertToResultList ( complete_stats )
return self |
def render ( self , ** kwargs ) :
"""Renders the HTML representation of the element .""" | for item in self . _parent . _children . values ( ) :
if not isinstance ( item , Layer ) or not item . control :
continue
key = item . layer_name
if not item . overlay :
self . base_layers [ key ] = item . get_name ( )
if len ( self . base_layers ) > 1 :
self . layers_unt... |
def docs ( output = DOC_OUTPUT , proj_settings = PROJ_SETTINGS , github = False ) :
"""Generate API documentation ( using Sphinx ) .
: param output : Output directory .
: param proj _ settings : Django project settings to use .
: param github : Convert to GitHub - friendly format ?""" | local ( "export PYTHONPATH='' && " "export DJANGO_SETTINGS_MODULE=%s && " "sphinx-build -b html %s %s" % ( proj_settings , DOC_INPUT , output ) , capture = False )
if _parse_bool ( github ) :
local ( "touch %s/.nojekyll" % output , capture = False ) |
def setEmergencyDecel ( self , typeID , decel ) :
"""setDecel ( string , double ) - > None
Sets the maximal physically possible deceleration in m / s ^ 2 of vehicles of this type .""" | self . _connection . _sendDoubleCmd ( tc . CMD_SET_VEHICLETYPE_VARIABLE , tc . VAR_EMERGENCY_DECEL , typeID , decel ) |
def short_full_symbol ( self ) :
"""Gets the full symbol excluding the character under the cursor .""" | if self . _short_full_symbol is None :
self . _short_full_symbol = self . _symbol_extract ( cache . RE_FULL_CURSOR , False , True )
return self . _short_full_symbol |
def get_rubric ( self ) :
"""Gets the rubric .
return : ( osid . assessment . AssessmentOffered ) - the assessment
offered
raise : IllegalState - ` ` has _ rubric ( ) ` ` is ` ` false ` `
raise : OperationFailed - unable to complete request
* compliance : mandatory - - This method must be implemented . *"... | # Implemented from template for osid . resource . Resource . get _ avatar _ template
if not bool ( self . _my_map [ 'rubricId' ] ) :
raise errors . IllegalState ( 'this AssessmentOffered has no rubric' )
mgr = self . _get_provider_manager ( 'ASSESSMENT' )
if not mgr . supports_assessment_offered_lookup ( ) :
ra... |
def addSource ( self , path , name , location , copyLib = False , copyGroups = False , copyInfo = False , copyFeatures = False , muteKerning = False , muteInfo = False , mutedGlyphNames = None , familyName = None , styleName = None , ) :
"""Add a new UFO source to the document .
* path : path to this UFO , will b... | sourceElement = ET . Element ( "source" )
sourceElement . attrib [ 'filename' ] = self . _posixPathRelativeToDocument ( path )
sourceElement . attrib [ 'name' ] = name
if copyLib :
libElement = ET . Element ( 'lib' )
libElement . attrib [ 'copy' ] = "1"
sourceElement . append ( libElement )
if copyGroups :
... |
def _on_permission_result ( self , code , perms , results ) :
"""Handles a permission request result by passing it to the
handler with the given code .""" | # : Get the handler for this request
handler = self . _permission_requests . get ( code , None )
if handler is not None :
del self . _permission_requests [ code ]
# : Invoke that handler with the permission request response
handler ( code , perms , results ) |
def _find_new_partners ( self ) :
"""Search the token network for potential channel partners .""" | open_channels = views . get_channelstate_open ( chain_state = views . state_from_raiden ( self . raiden ) , payment_network_id = self . registry_address , token_address = self . token_address , )
known = set ( channel_state . partner_state . address for channel_state in open_channels )
known . add ( self . BOOTSTRAP_AD... |
def readall ( self ) :
"""Read and return all the bytes from the stream until EOF .
Returns :
bytes : Object content""" | if not self . _readable :
raise UnsupportedOperation ( 'read' )
with self . _seek_lock : # Get data starting from seek
with handle_os_exceptions ( ) :
if self . _seek and self . _seekable :
data = self . _read_range ( self . _seek )
# Get all data
else :
data = se... |
def createConnection ( self ) :
"""Return a card connection thru a remote reader .""" | uri = self . reader . createConnection ( )
return Pyro . core . getAttrProxyForURI ( uri ) |
def _bind_ldap ( self , ldap , con , username , password ) :
"""Private to bind / Authenticate a user .
If AUTH _ LDAP _ BIND _ USER exists then it will bind first with it ,
next will search the LDAP server using the username with UID
and try to bind to it ( OpenLDAP ) .
If AUTH _ LDAP _ BIND _ USER does no... | try :
if self . auth_ldap_bind_user :
self . _bind_indirect_user ( ldap , con )
user = self . _search_ldap ( ldap , con , username )
if user :
log . debug ( "LDAP got User {0}" . format ( user ) )
# username = DN from search
username = user [ 0 ] [ 0 ]
... |
def reply_to_request ( cls , req_msg , * args ) :
"""Helper method for creating reply messages to a specific request .
Copies the message name and message identifier from request message .
Parameters
req _ msg : katcp . core . Message instance
The request message that this inform if in reply to
args : lis... | return cls ( cls . REPLY , req_msg . name , args , req_msg . mid ) |
def removeRnaQuantificationSet ( self , rnaQuantificationSet ) :
"""Removes the specified rnaQuantificationSet from this repository . This
performs a cascading removal of all items within this
rnaQuantificationSet .""" | q = models . Rnaquantificationset . delete ( ) . where ( models . Rnaquantificationset . id == rnaQuantificationSet . getId ( ) )
q . execute ( ) |
def optical_flow_send ( self , time_usec , sensor_id , flow_x , flow_y , flow_comp_m_x , flow_comp_m_y , quality , ground_distance , force_mavlink1 = False ) :
'''Optical flow from a flow sensor ( e . g . optical mouse sensor )
time _ usec : Timestamp ( UNIX ) ( uint64 _ t )
sensor _ id : Sensor ID ( uint8 _ t ... | return self . send ( self . optical_flow_encode ( time_usec , sensor_id , flow_x , flow_y , flow_comp_m_x , flow_comp_m_y , quality , ground_distance ) , force_mavlink1 = force_mavlink1 ) |
def delete_alert ( self , id , ** kwargs ) : # noqa : E501
"""Delete a specific alert # noqa : E501
# noqa : E501
This method makes a synchronous HTTP request by default . To make an
asynchronous HTTP request , please pass async _ req = True
> > > thread = api . delete _ alert ( id , async _ req = True )
... | kwargs [ '_return_http_data_only' ] = True
if kwargs . get ( 'async_req' ) :
return self . delete_alert_with_http_info ( id , ** kwargs )
# noqa : E501
else :
( data ) = self . delete_alert_with_http_info ( id , ** kwargs )
# noqa : E501
return data |
def gatk_major_version ( self ) :
"""Retrieve the GATK major version , handling multiple GATK distributions .
Has special cases for GATK nightly builds , Appistry releases and
GATK prior to 2.3.""" | full_version = self . get_gatk_version ( )
# Working with a recent version if using nightlies
if full_version . startswith ( "nightly-" ) :
return "3.6"
parts = full_version . split ( "-" )
if len ( parts ) == 4 :
appistry_release , version , subversion , githash = parts
elif len ( parts ) == 3 :
version , ... |
def decode ( col , charset ) :
"""Computes the first argument into a string from a binary using the provided character set
( one of ' US - ASCII ' , ' ISO - 8859-1 ' , ' UTF - 8 ' , ' UTF - 16BE ' , ' UTF - 16LE ' , ' UTF - 16 ' ) .""" | sc = SparkContext . _active_spark_context
return Column ( sc . _jvm . functions . decode ( _to_java_column ( col ) , charset ) ) |
def report ( args ) :
"""Create report in html format""" | logger . info ( "reading sequeces" )
data = load_data ( args . json )
logger . info ( "create profile" )
data = make_profile ( data , os . path . join ( args . out , "profiles" ) , args )
logger . info ( "create database" )
make_database ( data , "seqcluster.db" , args . out )
logger . info ( "Done. Download https://gi... |
def get_curie ( self , uri ) :
'''Get a CURIE from a URI''' | prefix = self . get_curie_prefix ( uri )
if prefix is not None :
key = self . curie_map [ prefix ]
return '%s:%s' % ( prefix , uri [ len ( key ) : len ( uri ) ] )
return None |
def record_received ( self , msg ) :
"""Handle ALDB record received from device .""" | release_lock = False
userdata = msg . userdata
rec = ALDBRecord . create_from_userdata ( userdata )
self . _records [ rec . mem_addr ] = rec
_LOGGER . debug ( 'ALDB Record: %s' , rec )
rec_count = self . _load_action . rec_count
if rec_count == 1 or self . _have_all_records ( ) :
release_lock = True
if self . _is_f... |
def L2S ( lunarD , lunarM , lunarY , lunarLeap , tZ = 7 ) :
'''def L2S ( lunarD , lunarM , lunarY , lunarLeap , tZ = 7 ) : Convert a lunar date
to the corresponding solar date .''' | if ( lunarM < 11 ) :
a11 = getLunarMonth11 ( lunarY - 1 , tZ )
b11 = getLunarMonth11 ( lunarY , tZ )
else :
a11 = getLunarMonth11 ( lunarY , tZ )
b11 = getLunarMonth11 ( lunarY + 1 , tZ )
k = int ( 0.5 + ( a11 - 2415021.076998695 ) / 29.530588853 )
off = lunarM - 11
if ( off < 0 ) :
off += 12
if ( b... |
def write_generator_data ( self , file ) :
"""Writes generator data in MATPOWER format .""" | gen_attr = [ "p" , "q" , "q_max" , "q_min" , "v_magnitude" , "base_mva" , "online" , "p_max" , "p_min" , "mu_pmax" , "mu_pmin" , "mu_qmax" , "mu_qmin" ]
file . write ( "\n%%%% generator data\n" )
file . write ( "%%\tbus\tPg\tQg\tQmax\tQmin\tVg\tmBase\tstatus\tPmax\tPmin" )
file . write ( "\tmu_Pmax\tmu_Pmin\tmu_Qmax\tm... |
def _init_alphabet_from_tokens ( self , tokens ) :
"""Initialize alphabet from an iterable of token or subtoken strings .""" | # Include all characters from all tokens in the alphabet to guarantee that
# any token can be encoded . Additionally , include all escaping
# characters .
self . _alphabet = { c for token in tokens for c in token }
self . _alphabet |= _ESCAPE_CHARS |
def _detect_iplus ( self ) :
"""Check the DCNM version and determine if it ' s for iplus""" | ver_expr = "([0-9]+)\.([0-9]+)\((.*)\)"
re . compile ( ver_expr )
v1 = re . match ( ver_expr , self . _cur_ver )
v2 = re . match ( ver_expr , self . _base_ver )
if int ( v1 . group ( 1 ) ) > int ( v2 . group ( 1 ) ) :
self . _is_iplus = True
elif int ( v1 . group ( 1 ) ) == int ( v2 . group ( 1 ) ) :
if int ( v... |
def parse_uri ( uri , default_port = DEFAULT_PORT , validate = True , warn = False ) :
"""Parse and validate a MongoDB URI .
Returns a dict of the form : :
' nodelist ' : < list of ( host , port ) tuples > ,
' username ' : < username > or None ,
' password ' : < password > or None ,
' database ' : < datab... | if uri . startswith ( SCHEME ) :
is_srv = False
scheme_free = uri [ SCHEME_LEN : ]
elif uri . startswith ( SRV_SCHEME ) :
if not _HAVE_DNSPYTHON :
raise ConfigurationError ( 'The "dnspython" module must be ' 'installed to use mongodb+srv:// URIs' )
is_srv = True
scheme_free = uri [ SRV_SCHEM... |
def sample_folder ( prj , sample ) :
"""Get the path to this Project ' s root folder for the given Sample .
: param attmap . PathExAttMap | Project prj : project with which sample is associated
: param Mapping sample : Sample or sample data for which to get root output
folder path .
: return str : this Proj... | return os . path . join ( prj . metadata . results_subdir , sample [ "sample_name" ] ) |
def describe_load_balancers ( names = None , load_balancer_arns = None , region = None , key = None , keyid = None , profile = None ) :
'''Describes the specified load balancer or all of your load balancers .
Returns : list
CLI example :
. . code - block : : bash
salt myminion boto _ elbv2 . describe _ load... | if names and load_balancer_arns :
raise SaltInvocationError ( 'At most one of names or load_balancer_arns may ' 'be provided' )
if names :
albs = names
elif load_balancer_arns :
albs = load_balancer_arns
else :
albs = None
albs_list = [ ]
if albs :
if isinstance ( albs , str ) or isinstance ( albs ,... |
def kill ( self , exc_info = None ) :
"""Kill the container in a semi - graceful way .
Entrypoints are killed , followed by any active worker threads .
Next , dependencies are killed . Finally , any remaining managed threads
are killed .
If ` ` exc _ info ` ` is provided , the exception will be raised by
... | if self . _being_killed : # this happens if a managed thread exits with an exception
# while the container is being killed or if multiple errors
# happen simultaneously
_log . debug ( 'already killing %s ... waiting for death' , self )
try :
self . _died . wait ( )
except :
pass
# do... |
def burnstage_upgrade ( self , ** keyw ) :
"""This function calculates the presence of burning stages and
outputs the ages when key isotopes are depleted and uses them to
calculate burning lifetimes .
Parameters
keyw : dict
A dict of key word arguments .
Returns
list
A list containing the following ... | if ( "isoa" in keyw ) == False :
keyw [ "isoa" ] = "A"
if ( "isoz" in keyw ) == False :
keyw [ "isoz" ] = "Z"
if ( "mass" in keyw ) == False :
keyw [ "mass" ] = "mass"
if ( "age" in keyw ) == False :
keyw [ "age" ] = "age"
if ( "abund" in keyw ) == False :
keyw [ "abund" ] = "iso_massf"
if ( "cycle"... |
def _deref ( tensor : tf . Tensor , index : tf . Tensor ) -> tf . Tensor :
"""Equivalent to ` tensor [ index , . . . ] ` .
This is a workaround for XLA requiring constant tensor indices . It works
by producing a node representing hardcoded instructions like the following :
if index = = 0 : return tensor [ 0] ... | assert tensor . shape [ 0 ] > 0
return _deref_helper ( lambda i : tensor [ i , ... ] , index , 0 , tensor . shape [ 0 ] - 1 ) |
def _crc16_checksum ( bytes ) :
"""Returns the CRC - 16 checksum of bytearray bytes
Ported from Java implementation at : http : / / introcs . cs . princeton . edu / java / 61data / CRC16CCITT . java . html
Initial value changed to 0x0000 to match Stellar configuration .""" | crc = 0x0000
polynomial = 0x1021
for byte in bytes :
for i in range ( 8 ) :
bit = ( byte >> ( 7 - i ) & 1 ) == 1
c15 = ( crc >> 15 & 1 ) == 1
crc <<= 1
if c15 ^ bit :
crc ^= polynomial
return crc & 0xFFFF |
def AddTimeZoneOption ( self , argument_group ) :
"""Adds the time zone option to the argument group .
Args :
argument _ group ( argparse . _ ArgumentGroup ) : argparse argument group .""" | # Note the default here is None so we can determine if the time zone
# option was set .
argument_group . add_argument ( '-z' , '--zone' , '--timezone' , dest = 'timezone' , action = 'store' , type = str , default = None , help = ( 'explicitly define the timezone. Typically the timezone is ' 'determined automatically wh... |
def from_config ( cls , cp , ifo , section ) :
"""Read a config file to get calibration options and transfer
functions which will be used to intialize the model .
Parameters
cp : WorkflowConfigParser
An open config file .
ifo : string
The detector ( H1 , L1 ) for which the calibration model will
be lo... | # read transfer functions
tfs = [ ]
tf_names = [ "a-tst" , "a-pu" , "c" , "d" ]
for tag in [ '-' . join ( [ ifo , "transfer-function" , name ] ) for name in tf_names ] :
tf_path = cp . get_opt_tag ( section , tag , None )
tfs . append ( cls . tf_from_file ( tf_path ) )
a_tst0 = tfs [ 0 ] [ : , 1 ]
a_pu0 = tfs [... |
def export ( self , nidm_version , export_dir ) :
"""Create prov entities and activities .""" | # Create cvs file containing design matrix
np . savetxt ( os . path . join ( export_dir , self . csv_file ) , np . asarray ( self . matrix ) , delimiter = "," )
if nidm_version [ 'num' ] in [ "1.0.0" , "1.1.0" ] :
csv_location = Identifier ( "file://./" + self . csv_file )
else :
csv_location = Identifier ( sel... |
def convert_ligatures ( text_string ) :
'''Coverts Latin character references within text _ string to their corresponding unicode characters
and returns converted string as type str .
Keyword argument :
- text _ string : string instance
Exceptions raised :
- InputError : occurs should a string or NoneType... | if text_string is None or text_string == "" :
return ""
elif isinstance ( text_string , str ) :
for i in range ( 0 , len ( LIGATURES ) ) :
text_string = text_string . replace ( LIGATURES [ str ( i ) ] [ "ligature" ] , LIGATURES [ str ( i ) ] [ "term" ] )
return text_string
else :
raise InputErro... |
def editpermissions_index_view ( self , request , forum_id = None ) :
"""Allows to select how to edit forum permissions .
The view displays a form to select a user or a group in order to edit its permissions for
the considered forum .""" | forum = get_object_or_404 ( Forum , pk = forum_id ) if forum_id else None
# Set up the context
context = self . get_forum_perms_base_context ( request , forum )
context [ 'forum' ] = forum
context [ 'title' ] = _ ( 'Forum permissions' ) if forum else _ ( 'Global forum permissions' )
# Handles " copy permission from " f... |
def make_mecard ( name , reading = None , email = None , phone = None , videophone = None , memo = None , nickname = None , birthday = None , url = None , pobox = None , roomno = None , houseno = None , city = None , prefecture = None , zipcode = None , country = None ) :
"""Returns a QR Code which encodes a ` MeCa... | return segno . make_qr ( make_mecard_data ( name = name , reading = reading , email = email , phone = phone , videophone = videophone , memo = memo , nickname = nickname , birthday = birthday , url = url , pobox = pobox , roomno = roomno , houseno = houseno , city = city , prefecture = prefecture , zipcode = zipcode , ... |
def ensure_file ( path ) :
"""Checks if file exists , if fails , tries to create file""" | try :
exists = isfile ( path )
if not exists :
with open ( path , 'w+' ) as fname :
fname . write ( 'initialized' )
return ( True , path )
return ( True , 'exists' )
except OSError as e : # pragma : no cover
return ( False , e ) |
def find_required_filehandlers ( self , requirements , filename_info ) :
"""Find the necessary file handlers for the given requirements .
We assume here requirements are available .
Raises :
KeyError , if no handler for the given requirements is available .
RuntimeError , if there is a handler for the given... | req_fh = [ ]
filename_info = set ( filename_info . items ( ) )
if requirements :
for requirement in requirements :
for fhd in self . file_handlers [ requirement ] :
if set ( fhd . filename_info . items ( ) ) . issubset ( filename_info ) :
req_fh . append ( fhd )
b... |
def split_first ( s , delims ) :
"""Given a string and an iterable of delimiters , split on the first found
delimiter . Return two split parts and the matched delimiter .
If not found , then the first part is the full input string .
Example : :
> > > split _ first ( ' foo / bar ? baz ' , ' ? / = ' )
( ' f... | min_idx = None
min_delim = None
for d in delims :
idx = s . find ( d )
if idx < 0 :
continue
if min_idx is None or idx < min_idx :
min_idx = idx
min_delim = d
if min_idx is None or min_idx < 0 :
return s , '' , None
return s [ : min_idx ] , s [ min_idx + 1 : ] , min_delim |
def translate_item_ids ( self , item_ids , language , is_nested = None ) :
"""Translate a list of item ids to JSON objects which reference them .
Args :
item _ ids ( list [ int ] ) : item ids
language ( str ) : language used for further filtering ( some objects
for different languages share the same item ) ... | if is_nested is None :
def is_nested_fun ( x ) :
return True
elif isinstance ( is_nested , bool ) :
def is_nested_fun ( x ) :
return is_nested
else :
is_nested_fun = is_nested
all_item_type_ids = ItemType . objects . get_all_item_type_ids ( )
groupped = proso . list . group_by ( item_ids , b... |
def wallet_unlock ( self , wallet , password ) :
"""Unlocks * * wallet * * using * * password * *
: param wallet : Wallet to unlock
: type wallet : str
: param password : Password to enter
: type password : str
: raises : : py : exc : ` nano . rpc . RPCException `
> > > rpc . wallet _ unlock (
. . . w... | wallet = self . _process_value ( wallet , 'wallet' )
payload = { "wallet" : wallet , "password" : password }
resp = self . call ( 'wallet_unlock' , payload )
return resp [ 'valid' ] == '1' |
def build_url_parts ( self ) :
"""Set userinfo , host , port and anchor from self . urlparts .
Also checks for obfuscated IP addresses .""" | # check userinfo @ host : port syntax
self . userinfo , host = urllib . splituser ( self . urlparts [ 1 ] )
port = urlutil . default_ports . get ( self . scheme , 0 )
host , port = urlutil . splitport ( host , port = port )
if port is None :
raise LinkCheckerError ( _ ( "URL host %(host)r has invalid port" ) % { "h... |
def copy_remote_directory_to_local ( sftp , remote_path , local_path ) :
'''copy remote directory to local machine''' | try :
os . makedirs ( local_path , exist_ok = True )
files = sftp . listdir ( remote_path )
for file in files :
remote_full_path = os . path . join ( remote_path , file )
local_full_path = os . path . join ( local_path , file )
try :
if sftp . listdir ( remote_full_path )... |
def delete_message ( self , msg_id , claim_id = None ) :
"""Deletes the message whose ID matches the supplied msg _ id from the
specified queue . If the message has been claimed , the ID of that claim
must be passed as the ' claim _ id ' parameter .""" | return self . _message_manager . delete ( msg_id , claim_id = claim_id ) |
def rename_acquisition ( self , plate_name , name , new_name ) :
'''Renames an acquisition .
Parameters
plate _ name : str
name of the parent plate
name : str
name of the acquisition that should be renamed
new _ name : str
name that should be given to the acquisition
See also
: func : ` tmserver .... | logger . info ( 'rename acquisistion "%s" of experiment "%s", plate "%s"' , name , self . experiment_name , plate_name )
content = { 'name' : new_name }
acquisition_id = self . _get_acquisition_id ( plate_name , name )
url = self . _build_api_url ( '/experiments/{experiment_id}/acquisitions/{acquisition_id}' . format (... |
def _to_key_val_pairs ( defs ) :
"""Helper to split strings , lists and dicts into ( current , value ) tuples for accumulation""" | if isinstance ( defs , STRING_TYPES ) : # Convert ' a ' to [ ( ' a ' , None ) ] , or ' a . b . c ' to [ ( ' a ' , ' b . c ' ) ]
return [ defs . split ( '.' , 1 ) if '.' in defs else ( defs , None ) ]
else :
pairs = [ ]
# Convert collections of strings or lists as above ; break dicts into component items
... |
def call_status ( * args , ** kwargs ) :
'''Return the status of the lamps .
Options :
* * * id * * : Specifies a device ID . Can be a comma - separated values . All , if omitted .
CLI Example :
. . code - block : : bash
salt ' * ' hue . status
salt ' * ' hue . status id = 1
salt ' * ' hue . status id... | res = dict ( )
devices = _get_lights ( )
for dev_id in 'id' not in kwargs and sorted ( devices . keys ( ) ) or _get_devices ( kwargs ) :
dev_id = six . text_type ( dev_id )
res [ dev_id ] = { 'on' : devices [ dev_id ] [ 'state' ] [ 'on' ] , 'reachable' : devices [ dev_id ] [ 'state' ] [ 'reachable' ] }
return r... |
def implement ( self , implementation , for_type = None , for_types = None ) :
"""Registers an implementing function for for _ type .
Arguments :
implementation : Callable implementation for this type .
for _ type : The type this implementation applies to .
for _ types : Same as for _ type , but takes a tup... | unbound_implementation = self . __get_unbound_function ( implementation )
for_types = self . __get_types ( for_type , for_types )
for t in for_types :
self . _write_lock . acquire ( )
try :
self . implementations . append ( ( t , unbound_implementation ) )
finally :
self . _write_lock . rele... |
def sub_state_by_gene_name ( self , * gene_names : str ) -> 'State' :
"""Create a sub state with only the gene passed in arguments .
Example
> > > state . sub _ state _ by _ gene _ name ( ' operon ' )
{ operon : 2}
> > > state . sub _ state _ by _ gene _ name ( ' mucuB ' )
{ mucuB : 0}""" | return State ( { gene : state for gene , state in self . items ( ) if gene . name in gene_names } ) |
def apply_experimental_design ( df , f , prefix = 'Intensity ' ) :
"""Load the experimental design template from MaxQuant and use it to apply the label names to the data columns .
: param df :
: param f : File path for the experimental design template
: param prefix :
: return : dt""" | df = df . copy ( )
edt = pd . read_csv ( f , sep = '\t' , header = 0 )
edt . set_index ( 'Experiment' , inplace = True )
new_column_labels = [ ]
for l in df . columns . values :
try :
l = edt . loc [ l . replace ( prefix , '' ) ] [ 'Name' ]
except ( IndexError , KeyError ) :
pass
new_column_... |
def fhp_from_json_dict ( json_dict # type : Dict [ str , Any ]
) : # type : ( . . . ) - > FieldHashingProperties
"""Make a : class : ` FieldHashingProperties ` object from a dictionary .
: param dict json _ dict :
The dictionary must have have an ' ngram ' key
and one of k or num _ bits . It may have
' posi... | h = json_dict . get ( 'hash' , { 'type' : 'blakeHash' } )
num_bits = json_dict . get ( 'numBits' )
k = json_dict . get ( 'k' )
if not num_bits and not k :
num_bits = 200
# default for v2 schema
return FieldHashingProperties ( ngram = json_dict [ 'ngram' ] , positional = json_dict . get ( 'positional' , FieldHas... |
def _validate_data ( self , data : dict ) :
"""Validates data against provider schema . Raises : class : ` ~ notifiers . exceptions . BadArguments ` if relevant
: param data : Data to validate
: raises : : class : ` ~ notifiers . exceptions . BadArguments `""" | log . debug ( "validating provided data" )
e = best_match ( self . validator . iter_errors ( data ) )
if e :
custom_error_key = f"error_{e.validator}"
msg = ( e . schema [ custom_error_key ] if e . schema . get ( custom_error_key ) else e . message )
raise BadArguments ( validation_error = msg , provider = ... |
def pipe ( wrapped ) :
"""Decorator to create an SPL operator from a function .
A pipe SPL operator with a single input port and a single
output port . For each tuple on the input port the
function is called passing the contents of the tuple .
SPL attributes from the tuple are passed by position .
The val... | if not inspect . isfunction ( wrapped ) :
raise TypeError ( 'A function is required' )
return _wrapforsplop ( _OperatorType . Pipe , wrapped , 'position' , False ) |
async def start ( self , host = None , port = None , * , path = None , family = socket . AF_UNSPEC , flags = socket . AI_PASSIVE , sock = None , backlog = 100 , ssl = None , reuse_address = None , reuse_port = None ) :
"""Coroutine to start the server .
: param host : can be a string , containing IPv4 / v6 addres... | if path is not None and ( host is not None or port is not None ) :
raise ValueError ( "The 'path' parameter can not be used with the " "'host' or 'port' parameters." )
if self . _server is not None :
raise RuntimeError ( 'Server is already started' )
if path is not None :
self . _server = await self . _loop... |
def _compute_margin ( self ) :
"""Compute graph margins from set texts""" | self . _legend_at_left_width = 0
for series_group in ( self . series , self . secondary_series ) :
if self . show_legend and series_group :
h , w = get_texts_box ( map ( lambda x : truncate ( x , self . truncate_legend or 15 ) , [ serie . title [ 'title' ] if isinstance ( serie . title , dict ) else serie .... |
def _update_internal_data_base ( self ) :
"""Updates Internal combo knowledge for any actual transition by calling get _ possible _ combos _ for _ transition -
function for those .""" | model = self . model
# print ( " clean data base " )
# # # FOR COMBOS
# internal transitions
# - take all internal states
# - take all not used internal outcomes of this states
# external transitions
# - take all external states
# - take all external outcomes
# - take all not used own outcomes
# # # LINKING
# internal ... |
def publish_schedule_length ( self , redis_client , port , db ) :
""": param redis _ client : Redis client
: param db : Redis Database index
: param port : Redis port
: return : Redis schedule length""" | schedule_length = redis_client . zcard ( 'schedule' )
self . __publish ( port , db , 'schedule' , schedule_length ) |
def add_dplist_permission_for_user_on_portal ( self , user_email , portal_id ) :
"""Adds the ' d _ p _ list ' permission to a user object when provided
a user _ email and portal _ id .""" | _id = self . get_user_id_from_email ( user_email )
print ( self . get_user_permission_from_email ( user_email ) )
retval = self . add_user_permission ( _id , json . dumps ( [ { 'access' : 'd_p_list' , 'oid' : { 'id' : portal_id , 'type' : 'Portal' } } ] ) )
print ( self . get_user_permission_from_email ( user_email ) )... |
def log_uniform_prior ( value , umin = 0 , umax = None ) :
"""Log - uniform prior distribution .""" | if value > 0 and value >= umin :
if umax is not None :
if value <= umax :
return 1 / value
else :
return - np . inf
else :
return 1 / value
else :
return - np . inf |
def address_to_coords ( self , address ) :
"""Convert address to coordinates""" | base_coords = self . BASE_COORDS [ self . region ]
get_cord = self . COORD_SERVERS [ self . region ]
url_options = { "q" : address , "lang" : "eng" , "origin" : "livemap" , "lat" : base_coords [ "lat" ] , "lon" : base_coords [ "lon" ] }
response = requests . get ( self . WAZE_URL + get_cord , params = url_options , hea... |
def get ( self , query_path = None , return_type = list , preceding_depth = None , throw_null_return_error = False ) :
"""Traverses the list of query paths to find the data requested
: param query _ path : ( list ( str ) , str ) , list of query path branches or query string
Default behavior : returns list ( str... | function_type_lookup = { str : self . _get_path_entry_from_string , list : self . _get_path_entry_from_list }
if query_path is None :
return self . _default_config ( return_type )
try :
config_entry = function_type_lookup . get ( type ( query_path ) , str ) ( query_path )
query_result = self . config_entry_... |
def level_is_between ( level , min_level_value , max_level_value ) :
"""Returns True if level is between the specified min or max , inclusive .""" | level_value = get_level_value ( level )
if level_value is None : # unknown level value
return False
return level_value >= min_level_value and level_value <= max_level_value |
def remove ( self , key , glob = False ) :
"""Remove key value pair in a local or global namespace .""" | ns = self . namespace ( key , glob )
try :
self . keyring . delete_password ( ns , key )
except PasswordDeleteError : # OSX and gnome have no delete method
self . set ( key , '' , glob ) |
def make_hash ( o ) :
r"""Makes a hash from a dictionary , list , tuple or set to any level , that
contains only other hashable types ( including any lists , tuples , sets , and
dictionaries ) . In the case where other kinds of objects ( like classes ) need
to be hashed , pass in a collection of object attrib... | if type ( o ) == DictProxyType :
o2 = { }
for k , v in o . items ( ) :
if not k . startswith ( "__" ) :
o2 [ k ] = v
o = o2
if isinstance ( o , ( set , tuple , list ) ) :
return tuple ( [ make_hash ( e ) for e in o ] )
elif not isinstance ( o , dict ) :
return hash ( o )
new_... |
def Parse ( self , stat , file_object , knowledge_base ) :
"""Parse the passwd file .""" | _ , _ = stat , knowledge_base
lines = [ l . strip ( ) for l in utils . ReadFileBytesAsUnicode ( file_object ) . splitlines ( ) ]
for index , line in enumerate ( lines ) :
user = self . ParseLine ( index , line )
if user is not None :
yield user |
def rotate_scale ( im , angle , scale , borderValue = 0 , interp = cv2 . INTER_CUBIC ) :
"""Rotates and scales the image
Parameters
im : 2d array
The image
angle : number
The angle , in radians , to rotate
scale : positive number
The scale factor
borderValue : number , default 0
The value for the ... | im = np . asarray ( im , dtype = np . float32 )
rows , cols = im . shape
M = cv2 . getRotationMatrix2D ( ( cols / 2 , rows / 2 ) , - angle * 180 / np . pi , 1 / scale )
im = cv2 . warpAffine ( im , M , ( cols , rows ) , borderMode = cv2 . BORDER_CONSTANT , flags = interp , borderValue = borderValue )
# REPLICATE
return... |
def load_topology ( path ) :
"""Open a topology file , patch it for last GNS3 release and return it""" | log . debug ( "Read topology %s" , path )
try :
with open ( path , encoding = "utf-8" ) as f :
topo = json . load ( f )
except ( OSError , UnicodeDecodeError , ValueError ) as e :
raise aiohttp . web . HTTPConflict ( text = "Could not load topology {}: {}" . format ( path , str ( e ) ) )
if topo . get (... |
def get_members ( self , offset = None , limit = None ) :
"""Fetch team members for current team .
: param offset : Pagination offset .
: param limit : Pagination limit .
: return : Collection object .""" | extra = { 'resource' : self . __class__ . __name__ , 'query' : { 'id' : self . id } }
logger . info ( 'Get team members' , extra = extra )
response = self . _api . get ( url = self . _URL [ 'members_query' ] . format ( id = self . id ) , params = { 'offset' : offset , 'limit' : limit } )
data = response . json ( )
tota... |
def parse_subdomain_record ( domain_name , rec , block_height , parent_zonefile_hash , parent_zonefile_index , zonefile_offset , txid , domain_zonefiles_missing , resolver = None ) :
"""Parse a subdomain record , and verify its signature .
@ domain _ name : the stem name
@ rec : the parsed zone file , with ' tx... | # sanity check : need ' txt ' record list
txt_entry = rec [ 'txt' ]
if not isinstance ( txt_entry , list ) :
raise ParseError ( "Tried to parse a TXT record with only a single <character-string>" )
entries = { }
# parts of the subdomain record
for item in txt_entry : # coerce string
if isinstance ( item , unico... |
def to_unicode_from_fs ( string ) :
"""Return a unicode version of string decoded using the file system encoding .""" | if not is_string ( string ) : # string is a QString
string = to_text_string ( string . toUtf8 ( ) , 'utf-8' )
else :
if is_binary_string ( string ) :
try :
unic = string . decode ( FS_ENCODING )
except ( UnicodeError , TypeError ) :
pass
else :
return ... |
def size ( self ) :
"""The size of the element .""" | size = { }
if self . _w3c :
size = self . _execute ( Command . GET_ELEMENT_RECT ) [ 'value' ]
else :
size = self . _execute ( Command . GET_ELEMENT_SIZE ) [ 'value' ]
new_size = { "height" : size [ "height" ] , "width" : size [ "width" ] }
return new_size |
def add ( name , default_for_unspecified , total_resource_slots , max_concurrent_sessions , max_containers_per_session , max_vfolder_count , max_vfolder_size , idle_timeout , allowed_vfolder_hosts ) :
'''Add a new keypair resource policy .
NAME : NAME of a new keypair resource policy .''' | with Session ( ) as session :
try :
data = session . ResourcePolicy . create ( name , default_for_unspecified = default_for_unspecified , total_resource_slots = total_resource_slots , max_concurrent_sessions = max_concurrent_sessions , max_containers_per_session = max_containers_per_session , max_vfolder_co... |
def get_subdomain ( url ) :
"""Get the subdomain of the given URL .
Args :
url ( str ) : The URL to get the subdomain from .
Returns :
str : The subdomain ( s )""" | if url not in URLHelper . __cache :
URLHelper . __cache [ url ] = urlparse ( url )
return "." . join ( URLHelper . __cache [ url ] . netloc . split ( "." ) [ : - 2 ] ) |
def is_valid_vpnv6_prefix ( prefix ) :
"""Returns True if given prefix is a string represent vpnv6 prefix .
Vpnv6 prefix is made up of RD : Ipv6 , where RD is represents route
distinguisher and Ipv6 represents valid colon hexadecimal notation string .""" | if not isinstance ( prefix , str ) :
return False
# Split the prefix into route distinguisher and IP
tokens = prefix . split ( ':' , 2 )
if len ( tokens ) != 3 :
return False
# Validate route distinguisher
if not is_valid_route_dist ( ':' . join ( [ tokens [ 0 ] , tokens [ 1 ] ] ) ) :
return False
# Validat... |
def close_temp_file ( self ) :
"""< Purpose >
Closes the temporary file object . ' close _ temp _ file ' mimics usual
file . close ( ) , however temporary file destroys itself when
' close _ temp _ file ' is called . Further if compression is set , second
temporary file instance ' self . _ orig _ file ' is ... | self . temporary_file . close ( )
# If compression has been set , we need to explicitly close the original
# file object .
if self . _orig_file is not None :
self . _orig_file . close ( ) |
def serialize_break ( ctx , document , elem , root ) :
"Serialize break element ." | if elem . break_type == u'textWrapping' :
_div = etree . SubElement ( root , 'br' )
else :
_div = etree . SubElement ( root , 'span' )
if ctx . options [ 'embed_styles' ] :
_div . set ( 'style' , 'page-break-after: always;' )
fire_hooks ( ctx , document , elem , _div , ctx . get_hook ( 'page_break' ... |
def lookup_asset_types ( self , sids ) :
"""Retrieve asset types for a list of sids .
Parameters
sids : list [ int ]
Returns
types : dict [ sid - > str or None ]
Asset types for the provided sids .""" | found = { }
missing = set ( )
for sid in sids :
try :
found [ sid ] = self . _asset_type_cache [ sid ]
except KeyError :
missing . add ( sid )
if not missing :
return found
router_cols = self . asset_router . c
for assets in group_into_chunks ( missing ) :
query = sa . select ( ( router_... |
def AddActiveConnection ( self , devices , connection_device , specific_object , name , state ) :
'''Add an active connection to an existing WiFi device .
You have to a list of the involved WiFi devices , the connection path ,
the access point path , ActiveConnection object name and connection
state .
Pleas... | conn_obj = dbusmock . get_object ( connection_device )
settings = conn_obj . settings
conn_uuid = settings [ 'connection' ] [ 'uuid' ]
conn_type = settings [ 'connection' ] [ 'type' ]
device_objects = [ dbus . ObjectPath ( dev ) for dev in devices ]
active_connection_path = '/org/freedesktop/NetworkManager/ActiveConnec... |
def feed_forward_gaussian ( config , action_space , observations , unused_length , state = None ) :
"""Independent feed forward networks for policy and value .
The policy network outputs the mean action and the standard deviation is
learned as independent parameter vector .
Args :
config : Configuration obj... | if not isinstance ( action_space , gym . spaces . Box ) :
raise ValueError ( 'Network expects continuous actions.' )
if not len ( action_space . shape ) == 1 :
raise ValueError ( 'Network only supports 1D action vectors.' )
action_size = action_space . shape [ 0 ]
init_output_weights = tf . contrib . layers . v... |
def read_file ( self , path , ** kwargs ) :
"""Read file input into memory , returning deserialized objects
: param path : Path of file to read
: param \ * * kwargs :
* ignore ( ` ` list ` ` ) : List of file patterns to ignore""" | # TODO support JSON here
# TODO sphinx way of reporting errors in logs ?
parser_command = [ "godocjson" ]
_ignore = kwargs . get ( "ignore" )
if _ignore :
parser_command . extend ( [ "-e" , "{0}" . format ( "|" . join ( _ignore ) ) ] )
parser_command . append ( path )
try :
parsed_data = json . loads ( subproce... |
def compose ( composite_property_s , component_properties_s ) :
"""Sets the components of the given composite property .
All parameters are < feature > value strings""" | from . import property
component_properties_s = to_seq ( component_properties_s )
composite_property = property . create_from_string ( composite_property_s )
f = composite_property . feature
if len ( component_properties_s ) > 0 and isinstance ( component_properties_s [ 0 ] , property . Property ) :
component_prope... |
def checkversion ( version ) :
"""Checks foliadocserve version , returns 1 if the document is newer than the library , - 1 if it is older , 0 if it is equal""" | try :
for refversion , responseversion in zip ( [ int ( x ) for x in REQUIREFOLIADOCSERVE . split ( '.' ) ] , [ int ( x ) for x in version . split ( '.' ) ] ) :
if responseversion > refversion :
return 1
# response is newer than library
elif responseversion < refversion :
... |
def ordered_members_map ( self ) :
"""Mask to group the persons by entity
This function only caches the map value , to see what the map is used for , see value _ nth _ person method .""" | if self . _ordered_members_map is None :
return np . argsort ( self . members_entity_id )
return self . _ordered_members_map |
def rsa_base64_decrypt ( self , cipher , b64 = True ) :
"""先base64 解码 再rsa 解密数据""" | with open ( self . key_file ) as fp :
key_ = RSA . importKey ( fp . read ( ) )
_cip = PKCS1_v1_5 . new ( key_ )
cipher = base64 . b64decode ( cipher ) if b64 else cipher
plain = _cip . decrypt ( cipher , Random . new ( ) . read ( 15 + SHA . digest_size ) )
return helper . to_str ( plain ) |
def serialize ( pca , ** kwargs ) :
"""Serialize an orientation object to a dict suitable
for JSON""" | strike , dip , rake = pca . strike_dip_rake ( )
hyp_axes = sampling_axes ( pca )
return dict ( ** kwargs , principal_axes = pca . axes . tolist ( ) , hyperbolic_axes = hyp_axes . tolist ( ) , n_samples = pca . n , strike = strike , dip = dip , rake = rake , angular_errors = [ 2 * N . degrees ( i ) for i in angular_erro... |
def devectorize_utterance ( self , utterance ) :
"""Take in a sequence of indices and transform it back into a tokenized utterance""" | utterance = self . swap_pad_and_zero ( utterance )
return self . ie . inverse_transform ( utterance ) . tolist ( ) |
def _set_defaults ( self ) :
"""Set some default values in the manifest .
This method should be called after loading from disk , but before
checking the integrity of the reference package .""" | self . contents . setdefault ( 'log' , [ ] )
self . contents . setdefault ( 'rollback' , None )
self . contents . setdefault ( 'rollforward' , None ) |
def restore_state ( self , state ) :
"""Restore the current state of this emulated device .
Args :
state ( dict ) : A previously dumped state produced by dump _ state .""" | tile_states = state . get ( 'tile_states' , { } )
for address , tile_state in tile_states . items ( ) :
address = int ( address )
tile = self . _tiles . get ( address )
if tile is None :
raise DataError ( "Invalid dumped state, tile does not exist at address %d" % address , address = address )
t... |
def _get_object_from_version ( cls , operations , ident ) :
"""Returns a Python object from an Alembic migration module ( script ) .
Args :
operations : instance of ` ` alembic . operations . base . Operations ` `
ident : string of the format ` ` version . objname ` `
Returns :
the object whose name is ` ... | version , objname = ident . split ( "." )
module_ = operations . get_context ( ) . script . get_revision ( version ) . module
obj = getattr ( module_ , objname )
return obj |
def type_and_model_to_query ( self , request ) :
"""Return JSON for an individual Model instance
If the required parameters are wrong , return 400 Bad Request
If the parameters are correct but there is no data , return empty JSON""" | try :
content_type_id = request . GET [ "content_type_id" ]
object_id = request . GET [ "object_id" ]
except KeyError :
return HttpResponseBadRequest ( )
try :
content_type = ContentType . objects . get ( pk = content_type_id )
model = content_type . model_class ( )
result = model . objects . ge... |
def GetAnalyzersInformation ( cls ) :
"""Retrieves the analyzers information .
Returns :
list [ tuple ] : containing :
str : analyzer name .
str : analyzer description .""" | analyzer_information = [ ]
for _ , analyzer_class in cls . GetAnalyzers ( ) :
description = getattr ( analyzer_class , 'DESCRIPTION' , '' )
analyzer_information . append ( ( analyzer_class . NAME , description ) )
return analyzer_information |
def extend_to_data ( self , data , ** kwargs ) :
"""Build transition matrix from new data to the graph
Creates a transition matrix such that ` Y ` can be approximated by
a linear combination of landmarks . Any
transformation of the landmarks can be trivially applied to ` Y ` by
performing
` transform _ Y ... | kernel = self . build_kernel_to_data ( data , ** kwargs )
if sparse . issparse ( kernel ) :
pnm = sparse . hstack ( [ sparse . csr_matrix ( kernel [ : , self . clusters == i ] . sum ( axis = 1 ) ) for i in np . unique ( self . clusters ) ] )
else :
pnm = np . array ( [ np . sum ( kernel [ : , self . clusters ==... |
def create_default_context ( purpose = None , ** kwargs ) :
"""Create a new SSL context in the most secure way available on the current
Python version . See : func : ` ssl . create _ default _ context ` .""" | if hasattr ( ssl , 'create_default_context' ) : # Python 2.7.9 + , Python 3.4 + : take a server _ side boolean or None , in
# addition to the ssl . Purpose . XX values . This allows a user to write
# code that works on all supported Python versions .
if purpose is None or purpose is False :
purpose = ssl . ... |
def coverage ( ) :
"""Run tests and show test coverage report .""" | try :
import pytest_cov
# NOQA
except ImportError :
print_failure_message ( 'Install the pytest coverage plugin to use this task, ' "i.e., `pip install pytest-cov'." )
raise SystemExit ( 1 )
import pytest
pytest . main ( PYTEST_FLAGS + [ '--cov' , CODE_DIRECTORY , '--cov-report' , 'term-missing' , '--ju... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.