signature stringlengths 29 44.1k | implementation stringlengths 0 85.2k |
|---|---|
def append ( self , item ) :
"""Append one item to the list .
Args :
item : Item to be appended . Its type must match the one defined in
the constructor .
Raises :
: exc : ` ~ . exceptions . WrongListItemType ` : If the item has a different
type than the one specified in the constructor .""" | if isinstance ( item , list ) :
self . extend ( item )
elif issubclass ( item . __class__ , self . _pyof_class ) :
list . append ( self , item )
else :
raise exceptions . WrongListItemType ( item . __class__ . __name__ , self . _pyof_class . __name__ ) |
def fixup_for_packaged ( ) :
'''If we are installing FROM an sdist , then a pre - built BokehJS is
already installed in the python source tree .
The command line options ` ` - - build - js ` ` or ` ` - - install - js ` ` are
removed from ` ` sys . argv ` ` , with a warning .
Also adds ` ` - - existing - js ... | if exists ( join ( ROOT , 'PKG-INFO' ) ) :
if "--build-js" in sys . argv or "--install-js" in sys . argv :
print ( SDIST_BUILD_WARNING )
if "--build-js" in sys . argv :
sys . argv . remove ( '--build-js' )
if "--install-js" in sys . argv :
sys . argv . remove ( '--ins... |
def add_elasticache_node ( self , node , cluster , region ) :
'''Adds an ElastiCache node to the inventory and index , as long as
it is addressable''' | # Only want available nodes unless all _ elasticache _ nodes is True
if not self . all_elasticache_nodes and node [ 'CacheNodeStatus' ] != 'available' :
return
# Select the best destination address
dest = node [ 'Endpoint' ] [ 'Address' ]
if not dest : # Skip nodes we cannot address ( e . g . private VPC subnet )
... |
def _build_query ( self , uri , params = None , action_token_type = None ) :
"""Prepare query string""" | if params is None :
params = QueryParams ( )
params [ 'response_format' ] = 'json'
session_token = None
if action_token_type in self . _action_tokens : # Favor action token
using_action_token = True
session_token = self . _action_tokens [ action_token_type ]
else :
using_action_token = False
if self... |
def import_datasource ( session , i_datasource , lookup_database , lookup_datasource , import_time ) :
"""Imports the datasource from the object to the database .
Metrics and columns and datasource will be overrided if exists .
This function can be used to import / export dashboards between multiple
superset ... | make_transient ( i_datasource )
logging . info ( 'Started import of the datasource: {}' . format ( i_datasource . to_json ( ) ) )
i_datasource . id = None
i_datasource . database_id = lookup_database ( i_datasource ) . id
i_datasource . alter_params ( import_time = import_time )
# override the datasource
datasource = l... |
def names ( expr : AST ) -> Set [ str ] :
"""Names of globals in ` expr ` .""" | nodes = [ node for node in ast . walk ( expr ) if isinstance ( node , ast . Name ) ]
loaded = { node . id for node in nodes if isinstance ( node . ctx , ast . Load ) }
stored = { node . id for node in nodes if isinstance ( node . ctx , ast . Store ) }
return loaded - stored |
def extract_xyz_matrix_from_chain ( self , chain_id , atoms_of_interest = [ ] ) :
'''Create a pandas coordinates dataframe from the lines in the specified chain .''' | chains = [ l [ 21 ] for l in self . structure_lines if len ( l ) > 21 ]
chain_lines = [ l for l in self . structure_lines if len ( l ) > 21 and l [ 21 ] == chain_id ]
return PDB . extract_xyz_matrix_from_pdb ( chain_lines , atoms_of_interest = atoms_of_interest , include_all_columns = True ) |
def _prepare_upload ( self , ase ) : # type : ( Uploader , blobxfer . models . azure . StorageEntity ) - > None
"""Prepare upload
: param Uploader self : this
: param blobxfer . models . azure . StorageEntity ase : Storage entity""" | if ase . mode == blobxfer . models . azure . StorageModes . Append :
if ase . append_create : # create container if necessary
blobxfer . operations . azure . blob . create_container ( ase , self . _containers_created )
# create remote blob
blobxfer . operations . azure . blob . append . crea... |
def load_hdf ( cls , filename , path = '' , name = None ) :
"""A class method to load a saved StarModel from an HDF5 file .
File must have been created by a call to : func : ` StarModel . save _ hdf ` .
: param filename :
H5 file to load .
: param path : ( optional )
Path within HDF file .
: return :
... | if not os . path . exists ( filename ) :
raise IOError ( '{} does not exist.' . format ( filename ) )
store = pd . HDFStore ( filename )
try :
samples = store [ path + '/samples' ]
attrs = store . get_storer ( path + '/samples' ) . attrs
except :
store . close ( )
raise
try :
ic = attrs . ic_typ... |
def remote_path ( self ) :
"""turns an ebook _ id into a path on PG ' s server ( s )
4443 - > 4/4/4/4443/""" | # TODO : move this property into independent object for PG
if len ( self . book_id ) > 1 :
path_parts = list ( self . book_id [ : - 1 ] )
else :
path_parts = [ '0' ]
path_parts . append ( self . book_id )
return os . path . join ( * path_parts ) + '/' |
def identify ( fn ) :
'''returns a tuple that is used to match
functions to their neighbors in their
resident namespaces''' | return ( fn . __globals__ [ '__name__' ] , # module namespace
getattr ( fn , '__qualname__' , getattr ( fn , '__name__' , '' ) ) # class and function namespace
)
def __init__ ( self , fn ) :
self . validate_function ( fn )
self . configured = False
self . has_backup_plan = False
if self . has_args ( ) :... |
def dump ( self ) :
"""dump Swagger Spec in dict ( which can be
convert to JSON )""" | r = { }
def _dump_ ( obj ) :
if isinstance ( obj , dict ) :
ret = { }
for k , v in six . iteritems ( obj ) :
ret [ k ] = _dump_ ( v )
return None if ret == { } else ret
elif isinstance ( obj , list ) :
ret = [ ]
for v in obj :
ret . append ( _dump_... |
def combine_variant_files ( orig_files , out_file , ref_file , config , quiet_out = True , region = None ) :
"""Combine VCF files from the same sample into a single output file .
Handles cases where we split files into SNPs / Indels for processing then
need to merge back into a final file .""" | in_pipeline = False
if isinstance ( orig_files , dict ) :
file_key = config [ "file_key" ]
in_pipeline = True
orig_files = orig_files [ file_key ]
if not utils . file_exists ( out_file ) :
with file_transaction ( config , out_file ) as tx_out_file :
exist_files = [ x for x in orig_files if os . ... |
def create_waf ( self , name , waf_type ) :
"""Creates a WAF with the given type .
: param name : Name of the WAF .
: param waf _ type : WAF type . ( ' mod _ security ' , ' Snort ' , ' Imperva SecureSphere ' , ' F5 BigIP ASM ' , ' DenyAll rWeb ' )""" | params = { 'name' : name , 'type' : waf_type }
return self . _request ( 'POST' , 'rest/wafs/new' , params ) |
def _update_index ( self , axis , key , value ) :
"""Update the current axis index based on a given key or value
This is an internal method designed to set the origin or step for
an index , whilst updating existing Index arrays as appropriate
Examples
> > > self . _ update _ index ( " x0 " , 0)
> > > self... | # delete current value if given None
if value is None :
return delattr ( self , key )
_key = "_{}" . format ( key )
index = "{[0]}index" . format ( axis )
unit = "{[0]}unit" . format ( axis )
# convert float to Quantity
if not isinstance ( value , Quantity ) :
try :
value = Quantity ( value , getattr ( ... |
def _get_plotbounds_from_cf ( coord , bounds ) :
"""Get plot bounds from the bounds stored as defined by CFConventions
Parameters
coord : xarray . Coordinate
The coordinate to get the bounds for
bounds : xarray . DataArray
The bounds as inferred from the attributes of the given ` coord `
Returns
% ( C... | if bounds . shape [ : - 1 ] != coord . shape or bounds . shape [ - 1 ] != 2 :
raise ValueError ( "Cannot interprete bounds with shape {0} for {1} " "coordinate with shape {2}." . format ( bounds . shape , coord . name , coord . shape ) )
ret = np . zeros ( tuple ( map ( lambda i : i + 1 , coord . shape ) ) )
ret [ ... |
def subdomains ( self , value = None ) :
"""Returns a list of subdomains or set the subdomains and returns a
new : class : ` URL ` instance .
: param list value : a list of subdomains""" | if value is not None :
return URL . _mutate ( self , host = '.' . join ( value ) )
return self . host ( ) . split ( '.' ) |
def _ranging ( self ) :
"""Should be a list of values to designate the buckets""" | agg_ranges = [ ]
for i , val in enumerate ( self . range_list ) :
if i == 0 :
agg_ranges . append ( { "to" : val } )
else :
previous = self . range_list [ i - 1 ]
agg_ranges . append ( { "from" : previous , "to" : val } )
if i + 1 == len ( self . range_list ) :
agg_ranges . a... |
def get_tags ( self ) :
"""Returns a list of the tags set by the user to this object .""" | # Uncacheable because it can be dynamically changed by the user .
params = self . _get_params ( )
doc = self . _request ( self . ws_prefix + ".getTags" , False , params )
tag_names = _extract_all ( doc , "name" )
tags = [ ]
for tag in tag_names :
tags . append ( Tag ( tag , self . network ) )
return tags |
def renavactive ( request , pattern ) :
"""{ % renavactive request " ^ / a _ regex " % }""" | if re . search ( pattern , request . path ) :
return getattr ( settings , "NAVHELPER_ACTIVE_CLASS" , "active" )
return getattr ( settings , "NAVHELPER_NOT_ACTIVE_CLASS" , "" ) |
def default ( self ) :
"""Default value of the property""" | prop_def = getattr ( self , '_default' , utils . undefined )
for prop in self . props :
if prop . default is utils . undefined :
continue
if prop_def is utils . undefined :
prop_def = prop . default
break
return prop_def |
def from_coords ( cls , coords , sort = True ) :
"""Create a mesh object from a list of 3D coordinates ( by sorting them )
: params coords : list of coordinates
: param sort : flag ( default True )
: returns : a : class : ` Mesh ` instance""" | coords = list ( coords )
if sort :
coords . sort ( )
if len ( coords [ 0 ] ) == 2 : # 2D coordinates
lons , lats = zip ( * coords )
depths = None
else : # 3D coordinates
lons , lats , depths = zip ( * coords )
depths = numpy . array ( depths )
return cls ( numpy . array ( lons ) , numpy . array ( la... |
def batch_update ( self , outcomes , expparams , resample_interval = 5 ) :
r"""Updates based on a batch of outcomes and experiments , rather than just
one .
: param numpy . ndarray outcomes : An array of outcomes of the experiments that
were performed .
: param numpy . ndarray expparams : Either a scalar or... | # TODO : write a faster implementation here using vectorized calls to
# likelihood .
# Check that the number of outcomes and experiments is the same .
n_exps = outcomes . shape [ 0 ]
if expparams . shape [ 0 ] != n_exps :
raise ValueError ( "The number of outcomes and experiments must match." )
if len ( expparams .... |
def to_transfac ( self ) :
"""Return motif formatted in TRANSFAC format
Returns
m : str
String of motif in TRANSFAC format .""" | m = "%s\t%s\t%s\n" % ( "DE" , self . id , "unknown" )
for i , ( row , cons ) in enumerate ( zip ( self . pfm , self . to_consensus ( ) ) ) :
m += "%i\t%s\t%s\n" % ( i , "\t" . join ( [ str ( int ( x ) ) for x in row ] ) , cons )
m += "XX"
return m |
def _OpenDatabaseWithWAL ( self , parser_mediator , database_file_entry , database_file_object , filename ) :
"""Opens a database with its Write - Ahead Log ( WAL ) committed .
Args :
parser _ mediator ( ParserMediator ) : parser mediator .
database _ file _ entry ( dfvfs . FileEntry ) : file entry of the dat... | path_spec = database_file_entry . path_spec
location = getattr ( path_spec , 'location' , None )
if not path_spec or not location :
return None , None
location_wal = '{0:s}-wal' . format ( location )
file_system = database_file_entry . GetFileSystem ( )
wal_path_spec = dfvfs_factory . Factory . NewPathSpec ( file_s... |
def set_limit_override ( self , limit_value , override_ta = True ) :
"""Set a new value for this limit , to override the default
( such as when AWS Support has increased a limit of yours ) .
If ` ` override _ ta ` ` is True , this value will also supersede
any found through Trusted Advisor .
: param limit _... | self . limit_override = limit_value
self . override_ta = override_ta |
def _add_dbsnp ( orig_file , dbsnp_file , data , out_file = None , post_cl = None ) :
"""Annotate a VCF file with dbSNP .
vcfanno has flexible matching for NON _ REF gVCF positions , matching
at position and REF allele , matching ALT NON _ REF as a wildcard .""" | orig_file = vcfutils . bgzip_and_index ( orig_file , data [ "config" ] )
if out_file is None :
out_file = "%s-wdbsnp.vcf.gz" % utils . splitext_plus ( orig_file ) [ 0 ]
if not utils . file_uptodate ( out_file , orig_file ) :
with file_transaction ( data , out_file ) as tx_out_file :
conf_file = os . pat... |
def main ( ) :
"""Example to show AIKIF logging of results .
Generates a sequence of random grids and runs the
Game of Life , saving results""" | iterations = 9
# how many simulations to run
years = 3
# how many times to run each simulation
width = 22
# grid height
height = 78
# grid width
time_delay = 0.03
# delay when printing on screen
lg = mod_log . Log ( 'test' )
lg . record_process ( 'Game of Life' , 'game_of_life_console.py' )
for _ in range ( iterations ... |
def read_key ( suppress = False ) :
"""Blocks until a keyboard event happens , then returns that event ' s name or ,
if missing , its scan code .""" | event = read_event ( suppress )
return event . name or event . scan_code |
def from_config ( cls , cp , section , variable_args ) :
"""Returns a distribution based on a configuration file . The parameters
for the distribution are retrieved from the section titled
" [ ` section ` - ` variable _ args ` ] " in the config file .
Parameters
cp : pycbc . workflow . WorkflowConfigParser ... | return super ( UniformPowerLaw , cls ) . from_config ( cp , section , variable_args , bounds_required = True ) |
def get_magnitude_term ( self , C , rup ) :
"""Returns the magnitude scaling term in equation 3""" | b0 , stress_drop = self . _get_sof_terms ( C , rup . rake )
if rup . mag <= C [ "m1" ] :
return b0
else : # Calculate moment ( equation 5)
m_0 = 10.0 ** ( 1.5 * rup . mag + 16.05 )
# Get stress - drop scaling ( equation 6)
if rup . mag > C [ "m2" ] :
stress_drop += ( C [ "b2" ] * ( C [ "m2" ] - ... |
def ipfix ( ) :
"""Return a list of values from the list of IANA IP Flow Information Export
( IPFIX ) Entities , or an empty list if the IANA website is unreachable .
Store it as a function attribute so that we only build the list once .""" | if not hasattr ( ipfix , 'ipflist' ) :
ilist = [ ]
try :
data = requests . get ( 'http://www.iana.org/assignments/ipfix/ipfix-' 'information-elements.csv' )
except requests . exceptions . RequestException :
return [ ]
for line in data . iter_lines ( ) :
if line :
line... |
def angle ( x , y ) :
"""Calculate the angle between two vectors , in degrees .
Args :
x ( np . array ) : one vector .
y ( np . array ) : the other vector .
Returns :
( float ) : the angle between x and y in degrees .""" | dot = np . dot ( x , y )
x_mod = np . linalg . norm ( x )
y_mod = np . linalg . norm ( y )
cos_angle = dot / ( x_mod * y_mod )
return np . degrees ( np . arccos ( cos_angle ) ) |
def is_arxiv ( obj ) :
"""Return ` ` True ` ` if ` ` obj ` ` contains an arXiv identifier .
The ` ` idutils ` ` library ' s ` ` is _ arxiv ` ` function has been
modified here to work with two regular expressions instead
of three and adding a check for valid arxiv categories only""" | arxiv_test = obj . split ( )
if not arxiv_test :
return False
matched_arxiv = ( RE_ARXIV_PRE_2007_CLASS . match ( arxiv_test [ 0 ] ) or RE_ARXIV_POST_2007_CLASS . match ( arxiv_test [ 0 ] ) )
if not matched_arxiv :
return False
if not matched_arxiv . group ( 'category' ) :
return True
valid_arxiv_categories... |
def _get_value ( self , var ) :
"""Return value of variable in solution .""" | return self . _problem . _p . get_value ( self . _problem . _variables [ var ] ) |
def rescale_field ( self , new_dim ) :
"""Changes the discretization of the potential field by linear
interpolation . This is necessary if the potential field
obtained from DFT is strangely skewed , or is too fine or coarse . Obeys
periodic boundary conditions at the edges of
the cell . Alternatively useful... | v_dim = self . __v . shape
padded_v = np . lib . pad ( self . __v , ( ( 0 , 1 ) , ( 0 , 1 ) , ( 0 , 1 ) ) , mode = 'wrap' )
ogrid_list = np . array ( [ list ( c ) for c in list ( np . ndindex ( v_dim [ 0 ] + 1 , v_dim [ 1 ] + 1 , v_dim [ 2 ] + 1 ) ) ] )
v_ogrid = padded_v . reshape ( ( ( v_dim [ 0 ] + 1 ) * ( v_dim [ 1... |
def get_objects ( self , subject , predicate ) :
"""Search for all subjects related to the specified subject and predicate .
: param subject :
: param object :
: rtype : generator of RDF statements""" | for statement in self . spo_search ( subject = subject , predicate = predicate ) :
yield str ( statement [ 2 ] ) |
def returned ( self , user ) :
"""Moved to ASSIGNED by given user ( but not from NEW )""" | for who , record in self . logs :
if ( record [ "field_name" ] == "status" and record [ "added" ] == "ASSIGNED" and record [ "removed" ] != "NEW" and who == user . email or who == user . name ) :
return True
return False |
def calculate_total_hamming_distance ( n ) :
"""This function calculates the total Hamming distance for all consecutive numbers from 0 to n .
The Hamming distance is the number of positions at which the corresponding binary digits
are different for two numbers .
Examples :
calculate _ total _ hamming _ dist... | i = 1
total_distance = 0
while ( ( n // i ) > 0 ) :
total_distance += ( n // i )
i *= 2
return total_distance |
def findalliter ( string , sub , regex = False , case_sensitive = False , whole_word = False ) :
"""Generator that finds all occurrences of ` ` sub ` ` in ` ` string ` `
: param string : string to parse
: param sub : string to search
: param regex : True to search using regex
: param case _ sensitive : True... | if not sub :
return
if regex :
flags = re . MULTILINE
if not case_sensitive :
flags |= re . IGNORECASE
for val in re . finditer ( sub , string , flags ) :
yield val . span ( )
else :
if not case_sensitive :
string = string . lower ( )
sub = sub . lower ( )
for val... |
def extend ( self , workflow : 'SoS_Workflow' ) -> None :
'''Append another workflow to existing one to created a combined workflow''' | # all sections are simply appended . . .
# but we will need to make sure that the new workflow is
# executed after the previous one .
if not workflow . sections :
return
if not self . sections :
self . sections = workflow . sections
return
section = workflow . sections [ 0 ]
depends_idx = [ idx for idx , st... |
def _parse_version_string ( version_conditions_string ) :
'''Returns a list of two - tuples containing ( operator , version ) .''' | result = [ ]
version_conditions_string = version_conditions_string . strip ( )
if not version_conditions_string :
return result
for version_condition in version_conditions_string . split ( ',' ) :
operator_and_version = _get_comparison_spec ( version_condition )
result . append ( operator_and_version )
retu... |
def _validate_parse_dates_arg ( parse_dates ) :
"""Check whether or not the ' parse _ dates ' parameter
is a non - boolean scalar . Raises a ValueError if
that is the case .""" | msg = ( "Only booleans, lists, and " "dictionaries are accepted " "for the 'parse_dates' parameter" )
if parse_dates is not None :
if is_scalar ( parse_dates ) :
if not lib . is_bool ( parse_dates ) :
raise TypeError ( msg )
elif not isinstance ( parse_dates , ( list , dict ) ) :
rai... |
def listen ( self , listen ) :
"""Attach an : class : ` txtorcon . interface . IStreamListener ` to this stream .
See also : meth : ` txtorcon . TorState . add _ stream _ listener ` to
listen to all streams .
: param listen : something that knows
: class : ` txtorcon . interface . IStreamListener `""" | listener = IStreamListener ( listen )
if listener not in self . listeners :
self . listeners . append ( listener ) |
async def deleteChatStickerSet ( self , chat_id ) :
"""See : https : / / core . telegram . org / bots / api # deletechatstickerset""" | p = _strip ( locals ( ) )
return await self . _api_request ( 'deleteChatStickerSet' , _rectify ( p ) ) |
def paths_update ( self , al_branchNodes ) :
"""Add each node in < al _ branchNodes > to the self . ml _ cwd and
append the combined list to ml _ allPaths . This method is
typically not called by a user , but by other methods in
this module .
Returns the list of all paths .""" | for node in al_branchNodes : # print " appending % s " % node
l_pwd = self . l_cwd [ : ]
l_pwd . append ( node )
# print " l _ pwd : % s " % l _ pwd
# print " ml _ cwd : % s " % self . ml _ cwd
self . l_allPaths . append ( l_pwd )
return self . l_allPaths |
async def field ( self , elem = None , elem_type = None , params = None , obj = None ) :
"""Archive field
: param elem :
: param elem _ type :
: param params :
: param obj :
: return :""" | elem_type = elem_type if elem_type else elem . __class__
fvalue = None
src = elem if self . writing else obj
dst = obj if self . writing else elem
# TODO : optional elem , default value for deserialization . . .
# Blob wrapper . Underlying structure should be serialized as blob .
if x . is_type ( elem_type , BlobFieldW... |
def astra_supports ( feature ) :
"""Return bool indicating whether current ASTRA supports ` ` feature ` ` .
Parameters
feature : str
Name of a potential feature of ASTRA . See ` ` ASTRA _ FEATURES ` ` for
possible values .
Returns
supports : bool
` ` True ` ` if the currently imported version of ASTRA... | from odl . util . utility import pkg_supports
return pkg_supports ( feature , ASTRA_VERSION , ASTRA_FEATURES ) |
def server ( port ) :
"""Serve application in development mode""" | header ( "Serving application in development mode ... " )
print ( "" )
print ( "- Port: %s" % port )
print ( "" )
cwd_to_sys_path ( )
application . app . run ( debug = True , host = '0.0.0.0' , port = port ) |
def get_user_attempts ( request , get_username = get_username_from_request , username = None ) :
"""Returns number of access attempts for this ip , username""" | ip_address = get_ip ( request )
username = lower_username ( username or get_username ( request ) )
# get by IP
ip_count = REDIS_SERVER . get ( get_ip_attempt_cache_key ( ip_address ) )
if not ip_count :
ip_count = 0
ip_count = int ( ip_count )
# get by username
username_count = REDIS_SERVER . get ( get_username_att... |
def _get_skiprows ( skiprows ) :
"""Get an iterator given an integer , slice or container .
Parameters
skiprows : int , slice , container
The iterator to use to skip rows ; can also be a slice .
Raises
TypeError
* If ` skiprows ` is not a slice , integer , or Container
Returns
it : iterable
A prop... | if isinstance ( skiprows , slice ) :
return lrange ( skiprows . start or 0 , skiprows . stop , skiprows . step or 1 )
elif isinstance ( skiprows , numbers . Integral ) or is_list_like ( skiprows ) :
return skiprows
elif skiprows is None :
return 0
raise TypeError ( '%r is not a valid type for skipping rows'... |
def _browse_body ( self , search_id ) :
"""Return the browse XML body .
The XML is formed by adding , to the envelope of the XML returned by
` ` self . _ base _ body ` ` , the following ` ` Body ` ` part :
. . code : : xml
< s : Body >
< getMetadata xmlns = " http : / / www . sonos . com / Services / 1.1 ... | xml = self . _base_body ( )
# Add the Body part
XML . SubElement ( xml , 's:Body' )
item_attrib = { 'xmlns' : 'http://www.sonos.com/Services/1.1' }
search = XML . SubElement ( xml [ 1 ] , 'getMetadata' , item_attrib )
XML . SubElement ( search , 'id' ) . text = search_id
# Investigate this index , count stuff more
XML ... |
def _get_next_code_addr ( self , initial_state ) :
"""Besides calling _ get _ next _ addr , we will check if data locates at that address seems to be code or not . If not ,
we ' ll move on to request for next valid address .""" | next_addr = self . _get_next_addr_to_search ( )
if next_addr is None :
return None
start_addr = next_addr
sz = ""
is_sz = True
while is_sz : # Get data until we meet a 0
while next_addr in initial_state . memory :
try :
l . debug ( "Searching address %x" , next_addr )
val = initi... |
def top ( ** kwargs ) :
'''Run the command configured''' | if 'id' not in kwargs [ 'opts' ] :
return { }
cmd = '{0} {1}' . format ( __opts__ [ 'master_tops' ] [ 'ext_nodes' ] , kwargs [ 'opts' ] [ 'id' ] )
ndata = salt . utils . yaml . safe_load ( subprocess . Popen ( cmd , shell = True , stdout = subprocess . PIPE ) . communicate ( ) [ 0 ] )
if not ndata :
log . info ... |
def handle_error ( self , error , req , schema , error_status_code , error_headers ) :
"""Handles errors during parsing . Aborts the current request with a
400 error .""" | status_code = error_status_code or self . DEFAULT_VALIDATION_STATUS
raise bottle . HTTPError ( status = status_code , body = error . messages , headers = error_headers , exception = error , ) |
def is_satisfied_by ( self , candidate : Any , ** kwds : Any ) -> bool :
"""Return True if ` candidate ` satisfies the specification .""" | candidate_name = self . _candidate_name
context = self . _context
if context :
if candidate_name in kwds :
raise ValueError ( f"Candidate name '{candidate_name}' must " "not be given as keyword." )
context . update ( kwds )
context [ candidate_name ] = candidate
try :
code = self . _code
except Attr... |
def function_begin ( self ) :
"""Inserts function name label and function frame initialization""" | self . newline_label ( self . shared . function_name , False , True )
self . push ( "%14" )
self . move ( "%15" , "%14" ) |
def config_parse ( files = None , config = None , config_profile = ".fissconfig" , ** kwargs ) :
'''Read initial configuration state , from named config files ; store
this state within a config dictionary ( which may be nested ) whose keys may
also be referenced as attributes ( safely , defaulting to None if un... | local_config = config
config = __fcconfig
cfgparser = configparser . SafeConfigParser ( )
filenames = list ( )
# Give personal / user followed by current working directory configuration the first say
filenames . append ( os . path . join ( os . path . expanduser ( '~' ) , config_profile ) )
filenames . append ( os . pa... |
def bundle_attacks ( sess , model , x , y , attack_configs , goals , report_path , attack_batch_size = BATCH_SIZE , eval_batch_size = BATCH_SIZE ) :
"""Runs attack bundling .
Users of cleverhans may call this function but are more likely to call
one of the recipes above .
Reference : https : / / openreview . ... | assert isinstance ( sess , tf . Session )
assert isinstance ( model , Model )
assert all ( isinstance ( attack_config , AttackConfig ) for attack_config in attack_configs )
assert all ( isinstance ( goal , AttackGoal ) for goal in goals )
assert isinstance ( report_path , six . string_types )
if x . shape [ 0 ] != y . ... |
def bulk ( self , actions , stats_only = False , ** kwargs ) :
"""Executes bulk api by elasticsearch . helpers . bulk .
: param actions : iterator containing the actions
: param stats _ only : if ` True ` only report number of successful / failed
operations instead of just number of successful and a list of e... | success , failed = es_helpers . bulk ( self . client , actions , stats_only , ** kwargs )
logger . info ( 'Bulk is done success %s failed %s actions: \n %s' % ( success , failed , actions ) ) |
def _parse_cluster_manage_command ( cls , args , action ) :
"""Parse command line arguments for cluster manage commands .""" | argparser = ArgumentParser ( prog = "cluster_manage_command" )
group = argparser . add_mutually_exclusive_group ( required = True )
group . add_argument ( "--id" , dest = "cluster_id" , help = "execute on cluster with this id" )
group . add_argument ( "--label" , dest = "label" , help = "execute on cluster with this la... |
def merge_includes ( code ) :
"""Merge all includes recursively .""" | pattern = '\#\s*include\s*"(?P<filename>[a-zA-Z0-9\_\-\.\/]+)"'
regex = re . compile ( pattern )
includes = [ ]
def replace ( match ) :
filename = match . group ( "filename" )
if filename not in includes :
includes . append ( filename )
path = glsl . find ( filename )
if not path :
... |
def find ( self , selector : str = "*" , * , containing : _Containing = None , clean : bool = False , first : bool = False , _encoding : str = None ) -> _Find :
"""Given a CSS Selector , returns a list of
: class : ` Element < Element > ` objects or a single one .
: param selector : CSS Selector to use .
: pa... | # Convert a single containing into a list .
if isinstance ( containing , str ) :
containing = [ containing ]
encoding = _encoding or self . encoding
elements = [ Element ( element = found , url = self . url , default_encoding = encoding ) for found in self . pq ( selector ) ]
if containing :
elements_copy = ele... |
def stop ( self ) :
"""Stops a a playing animation . A subsequent call to play will start from the beginning .""" | if self . state == PygAnimation . PLAYING :
self . index = 0
# set up for first image in list
self . elapsed = 0
self . nIterationsLeft = 0
elif self . state == PygAnimation . STOPPED :
pass
# nothing to do
elif self . state == PygAnimation . PAUSED :
self . index = 0
# set up for first imag... |
def _validate_address ( self , address ) :
"""Confirm that supplied address is a valid URL and
has an ` amqp ` or ` amqps ` scheme .
: param address : The endpiont URL .
: type address : str
: rtype : ~ urllib . parse . ParseResult""" | parsed = compat . urlparse ( address )
if not parsed . path :
raise ValueError ( "Invalid {} address: {}" . format ( self . __class__ . __name__ , parsed ) )
return parsed |
def continuous ( self ) :
"""Set sequence to be continuous .
: rtype : Column
: Example :
> > > # Table schema is create table test ( f1 double , f2 string )
> > > # Original continuity : f1 = DISCRETE , f2 = DISCRETE
> > > # Now we want to set ` ` f1 ` ` and ` ` f2 ` ` into continuous
> > > new _ ds = ... | field_name = self . name
new_df = copy_df ( self )
new_df . _perform_operation ( op . FieldContinuityOperation ( { field_name : True } ) )
return new_df |
def register_agent ( self , host , sweep_id = None , project_name = None ) :
"""Register a new agent
Args :
host ( str ) : hostname
persistent ( bool ) : long running or oneoff
sweep ( str ) : sweep id
project _ name : ( str ) : model that contains sweep""" | mutation = gql ( '''
mutation CreateAgent(
$host: String!
$projectName: String!,
$entityName: String!,
$sweep: String!
) {
createAgent(input: {
host: $host,
projectName: $projectName,
entityName: ... |
def full_datatype_to_mysql ( d : str ) -> str :
"""Converts a full datatype , e . g . INT , VARCHAR ( 10 ) , VARCHAR ( MAX ) , to a
MySQL equivalent .""" | d = d . upper ( )
( s , length ) = split_long_sqltype ( d )
if d in [ "VARCHAR(MAX)" , "NVARCHAR(MAX)" ] : # http : / / wiki . ispirer . com / sqlways / mysql / data - types / longtext
return "LONGTEXT"
elif d in [ "VARBINARY(MAX)" ] or s in [ "IMAGE" ] : # http : / / wiki . ispirer . com / sqlways / mysql / data -... |
def index ( self , value , start = None , stop = None ) :
"""Return the smallest * k * such that ` keysview [ k ] = = value ` and ` start < = k
< end ` . Raises ` KeyError ` if * value * is not present . * stop * defaults
to the end of the set . * start * defaults to the beginning . Negative
indexes are suppo... | return self . _list . index ( value , start , stop ) |
def merge_context ( self , tag , metadata ) :
"""merge into contextManagerFrame new entity and metadata .
Appends tag as new entity and adds keys in metadata to keys in
self . metadata .
Args :
tag ( str ) : entity to be added to self . entities
metadata ( object ) : metadata containes keys to be added to... | self . entities . append ( tag )
for k in metadata . keys ( ) :
if k not in self . metadata :
self . metadata [ k ] = k |
def get_sequence_properties ( self , clean_seq = False , representative_only = True ) :
"""Run Biopython ProteinAnalysis and EMBOSS pepstats to summarize basic statistics of the protein sequences .
Results are stored in the protein ' s respective SeqProp objects at ` ` . annotations ` `
Args :
representative ... | if representative_only : # Check if a representative sequence was set
if not self . representative_sequence :
log . warning ( '{}: no representative sequence set, cannot get sequence properties' . format ( self . id ) )
return
# Also need to check if a sequence has been stored
if not self . ... |
def find_revision_number ( self , revision = None ) :
"""Find the local revision number of the given revision .
. . note : : Bazaar has the concept of dotted revision numbers :
For revisions which have been merged into a branch , a dotted
notation is used ( e . g . , 3112.1.5 ) . Dotted revision numbers
hav... | # Make sure the local repository exists .
self . create ( )
# Try to find the revision number of the specified revision .
revision = revision or self . default_revision
output = self . context . capture ( 'bzr' , 'log' , '--revision=..%s' % revision , '--line' )
revision_number = len ( [ line for line in output . split... |
def set_select ( self , select_or_deselect = 'select' , value = None , text = None , index = None ) :
"""Private method used by select methods
@ type select _ or _ deselect : str
@ param select _ or _ deselect : Should I select or deselect the element
@ type value : str
@ type value : Value to be selected
... | # TODO : raise exception if element is not select element
if select_or_deselect is 'select' :
if value is not None :
Select ( self . element ) . select_by_value ( value )
elif text is not None :
Select ( self . element ) . select_by_visible_text ( text )
elif index is not None :
Sele... |
def calc_deltas ( data_frame , series = None ) :
"""Many of collectl ' s data values are cumulative ( monotonically
increasing ) , so subtract the previous value to determine the value
for the current interval .""" | series = series or [ ]
data_frame = data_frame . sort_index ( ascending = True )
for s in series :
prev_values = iter ( data_frame [ s ] )
# Burn the first value , so the first row we call delta _ from _ prev ( )
# for gets its previous value from the second row in the series ,
# and so on .
next ( ... |
def domain_of_validity ( self ) :
"""Return the domain of validity for this CRS as :
( west , east , south , north ) .
For example : :
> > > print ( get ( 21781 ) . domain _ of _ validity ( ) )
[5.96 , 10.49 , 45.82 , 47.81]""" | # TODO : Generalise interface to return a polygon ? ( Can we find
# something that uses a polygon instead ? )
domain = self . element . find ( GML_NS + 'domainOfValidity' )
domain_href = domain . attrib [ XLINK_NS + 'href' ]
url = '{prefix}{code}.gml?download' . format ( prefix = EPSG_IO_URL , code = domain_href )
xml ... |
def WriteObject ( moList ) :
"""Writes the managed object on the terminal in form of key value pairs .""" | from Ucs import Dn
from UcsHandle import UcsMoDiff
tabsize = 8
if ( isinstance ( moList , _GenericMO ) == True ) :
print str ( moList )
elif ( isinstance ( moList , ExternalMethod ) == True ) :
if ( hasattr ( moList , "OutConfigs" ) == True ) :
for child in moList . OutConfigs . GetChild ( ) :
... |
def render ( self ) :
'''. . versionchanged : : 0.12
Add ` ` dynamic _ electrode _ state _ shapes ` ` layer to show dynamic
electrode actuations .''' | # Render each layer and update data frame with new content for each
# surface .
surface_names = ( 'background' , 'shapes' , 'connections' , 'routes' , 'channel_labels' , 'static_electrode_state_shapes' , 'dynamic_electrode_state_shapes' , 'registration' )
for k in surface_names :
self . set_surface ( k , getattr ( ... |
def ensure_list ( value : Union [ T , Sequence [ T ] ] ) -> Sequence [ T ] :
"""Wrap value in list if it is not one .""" | if value is None :
return [ ]
return value if isinstance ( value , list ) else [ value ] |
def _put ( self , uri , data ) :
"""Simple PUT operation for a given path .""" | headers = self . _get_headers ( )
logging . debug ( "URI=" + str ( uri ) )
logging . debug ( "BODY=" + json . dumps ( data ) )
response = self . session . put ( uri , headers = headers , data = json . dumps ( data ) )
if response . status_code in [ 201 , 204 ] :
return data
else :
logging . error ( response . c... |
def b_matching ( D , k , max_iter = 1000 , damping = 1 , conv_thresh = 1e-4 , weighted = False , verbose = False ) :
'''" Belief - Propagation for Weighted b - Matchings on Arbitrary Graphs
and its Relation to Linear Programs with Integer Solutions "
Bayati et al .
Finds the minimal weight perfect b - matchin... | INTERVAL = 2
oscillation = 10
cbuff = np . zeros ( 100 , dtype = float )
cbuffpos = 0
N = D . shape [ 0 ]
assert D . shape [ 1 ] == N , 'Input distance matrix must be square'
mask = ~ np . eye ( N , dtype = bool )
# Assume all nonzero except for diagonal
W = - D [ mask ] . reshape ( ( N , - 1 ) ) . astype ( float )
deg... |
def get_merchant ( self , merchant_id , ** params ) :
"""https : / / developers . coinbase . com / api / v2 # show - a - merchant""" | response = self . _get ( 'v2' , 'merchants' , merchant_id , params = params )
return self . _make_api_object ( response , Merchant ) |
def parse_arguments ( args = sys . argv [ 1 : ] ) :
"""Parse arguments of script .""" | cmd_description = "Download tracklistings for BBC radio shows.\n\n" "Saves to a text file, tags audio file or does both.\n" "To select output file, filename " "must both be specified.\n" "If directory is not specified, directory is assumed" "to be where script is.\n" "Filename is the prefix, for someaudio.m4a, use " "-... |
def export ( options , service ) :
"""main export method : export any number of indexes""" | start = options . kwargs [ 'start' ]
end = options . kwargs [ 'end' ]
fixtail = options . kwargs [ 'fixtail' ]
once = True
squery = options . kwargs [ 'search' ]
squery = squery + " index=%s" % options . kwargs [ 'index' ]
if ( start != "" ) :
squery = squery + " earliest_time=%s" % start
if ( end != "" ) :
squ... |
def parse_value ( self , value_string : str ) :
"""Parses the amount string .""" | self . value = Decimal ( value_string )
return self . value |
def tostring ( self , fully_qualified = True , pretty_print = True , encoding = "UTF-8" ) :
"""Serialize and return a string of this METS document .
To write to file , see : meth : ` write ` .
The default encoding is ` ` UTF - 8 ` ` . This method will return a unicode
string when ` ` encoding ` ` is set to ` ... | root = self . serialize ( fully_qualified = fully_qualified )
kwargs = { "pretty_print" : pretty_print , "encoding" : encoding }
if encoding != "unicode" :
kwargs [ "xml_declaration" ] = True
return etree . tostring ( root , ** kwargs ) |
def get ( self , key ) :
'''Return the object named by key or None if it does not exist .
Args :
key : Key naming the object to retrieve
Returns :
object or None''' | path = self . object_path ( key )
return self . _read_object ( path ) |
def push ( self ) :
"""Pushes updated plot data via the Comm .""" | if self . comm is None :
raise Exception ( 'Renderer does not have a comm.' )
diff = self . renderer . diff ( self )
self . comm . send ( diff ) |
def open ( self ) :
"""Open the connection if not already open .
: return : True""" | try :
if self . conn . get_backend_pid ( ) :
return True
except psycopg2 . InterfaceError as e :
if str ( e ) == "connection already closed" : # We already lost our connection . Attempt to reforge it .
self . __reconnect__ ( )
if self . conn . get_backend_pid ( ) >= 0 :
retur... |
def fail ( self , exc = None ) :
'''Move this work unit to a failed state .
In the standard worker system , the worker calls this on the job ' s
behalf when : meth : ` run _ function ` ends with any exception :
. . code - block : : python
try :
work _ unit . run ( )
work _ unit . finish ( )
except Exc... | with self . registry . lock ( identifier = self . worker_id ) as session :
self . _refresh ( session , stopping = True )
if self . finished or self . failed :
return
if exc :
self . data [ 'traceback' ] = traceback . format_exc ( exc )
else :
self . data [ 'traceback' ] = None
... |
def bez2poly ( bez , numpy_ordering = True , return_poly1d = False ) :
"""Converts a Bezier object or tuple of Bezier control points to a tuple
of coefficients of the expanded polynomial .
return _ poly1d : returns a numpy . poly1d object . This makes computations
of derivatives / anti - derivatives and many ... | if is_bezier_segment ( bez ) :
bez = bez . bpoints ( )
return bezier2polynomial ( bez , numpy_ordering = numpy_ordering , return_poly1d = return_poly1d ) |
def convert_trunc ( trunc ) :
"""Convert BEL1 trunc ( ) to BEL2 var ( )""" | parent_fn_name = trunc . parent_function . name_short
prefix_list = { "p" : "p." , "r" : "r." , "g" : "c." }
prefix = prefix_list [ parent_fn_name ]
new_var_arg = f'"truncated at {trunc.args[0].value}"'
new_var = bel . lang . ast . Function ( "var" , bo . spec )
new_var . add_argument ( StrArg ( new_var_arg , new_var )... |
def childIds ( self ) :
"""Children of the passage
: rtype : None , CtsReference
: returns : Dictionary of chidren , where key are subreferences""" | if self . depth >= len ( self . citation . root ) :
return [ ]
elif self . _children is not None :
return self . _children
else :
self . _children = self . getReffs ( )
return self . _children |
def revoke_auth_access ( self , access_token ) :
"""授权回收接口 , 帮助开发者主动取消用户的授权 。
应用下线时 , 清空所有用户的授权
应用新上线了功能 , 需要取得用户scope权限 , 可以回收后重新引导用户授权
开发者调试应用 , 需要反复调试授权功能
应用内实现类似登出微博帐号的功能
并传递给你以下参数 , source : 应用appkey , uid : 取消授权的用户 , auth _ end : 取消授权的时间
: param access _ token :
: return : bool""" | result = self . request ( "post" , "revokeoauth2" , data = { "access_token" : access_token } )
return bool ( result . get ( "result" ) ) |
def entrance_beveled ( Di , l , angle , method = 'Rennels' ) :
r'''Returns loss coefficient for a beveled or chamfered entrance to a pipe
flush with the wall of a reservoir . This calculation has two methods
available .
The ' Rennels ' and ' Idelchik ' methods have similar trends , but the ' Rennels '
formu... | if method is None :
method = 'Rennels'
if method == 'Rennels' :
Cb = ( 1 - angle / 90. ) * ( angle / 90. ) ** ( 1. / ( 1 + l / Di ) )
lbd = 1 + 0.622 * ( 1 - 1.5 * Cb * ( l / Di ) ** ( ( 1 - ( l / Di ) ** 0.25 ) / 2. ) )
return 0.0696 * ( 1 - Cb * l / Di ) * lbd ** 2 + ( lbd - 1. ) ** 2
elif method == '... |
def cycle_data ( self , repository , cycle_interval , chunk_size , sleep_time ) :
"""Delete data older than cycle _ interval , splitting the target data into
chunks of chunk _ size size . Returns the number of result sets deleted""" | # Retrieve list of jobs to delete
jobs_max_timestamp = datetime . datetime . now ( ) - cycle_interval
jobs_cycled = 0
while True :
jobs_chunk = list ( self . filter ( repository = repository , submit_time__lt = jobs_max_timestamp ) . values_list ( 'guid' , flat = True ) [ : chunk_size ] )
if not jobs_chunk : # ... |
def save_to_path ( self , file_path , chunk_size = DOWNLOAD_FILE_CHUNK_SIZE ) :
"""Save the contents of the remote file to a local path .
: param file _ path : str : file path
: param chunk _ size : chunk size used to write local file""" | response = self . _get_download_response ( )
with open ( file_path , 'wb' ) as f :
for chunk in response . iter_content ( chunk_size = chunk_size ) :
if chunk : # filter out keep - alive new chunks
f . write ( chunk ) |
def is_safe ( self ) :
"""Check if the option is safe .
: rtype : bool
: return : True , if option is safe""" | if self . _number == defines . OptionRegistry . URI_HOST . number or self . _number == defines . OptionRegistry . URI_PORT . number or self . _number == defines . OptionRegistry . URI_PATH . number or self . _number == defines . OptionRegistry . MAX_AGE . number or self . _number == defines . OptionRegistry . URI_QUERY... |
def get_environments ( self , project_key : str ) -> dict :
"""Retrieve all environments for a given project .
Includes name , key , and mobile key .
: param project _ key : Key for project .
: returns : dictionary of environments .""" | try :
resp = self . client . get_project ( project_key )
except launchdarkly_api . rest . ApiException as ex :
msg = "Unable to get environments."
resp = "API response was {0} {1}." . format ( ex . status , ex . reason )
LOG . error ( "%s %s" , msg , resp )
sys . exit ( 1 )
envs = [ ]
for env in res... |
def _to_dict ( self ) :
"""Return a json dictionary representing this model .""" | _dict = { }
if hasattr ( self , 'size' ) and self . size is not None :
_dict [ 'size' ] = self . size
if hasattr ( self , 'hits' ) and self . hits is not None :
_dict [ 'hits' ] = self . hits . _to_dict ( )
return _dict |
def ParseObjs ( self , objs , expression ) :
"""Parse one or more objects using an objectfilter expression .""" | filt = self . _Compile ( expression )
for result in filt . Filter ( objs ) :
yield result |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.