signature stringlengths 29 44.1k | implementation stringlengths 0 85.2k |
|---|---|
def remove_indicator ( self , nid , prune = False ) :
"""Removes a Indicator or IndicatorItem node from the IOC . By default ,
if nodes are removed , any children nodes are inherited by the removed
node . It has the ability to delete all children Indicator and
IndicatorItem nodes underneath an Indicator node ... | try :
node_to_remove = self . top_level_indicator . xpath ( '//IndicatorItem[@id="{}"]|//Indicator[@id="{}"]' . format ( str ( nid ) , str ( nid ) ) ) [ 0 ]
except IndexError :
log . exception ( 'Node [{}] not present' . format ( nid ) )
return False
if node_to_remove . tag == 'IndicatorItem' :
node_to_... |
def generate_plaintext_traceback ( self ) :
"""Like the plaintext attribute but returns a generator""" | yield text_ ( 'Traceback (most recent call last):' )
for frame in self . frames :
yield text_ ( ' File "%s", line %s, in %s' % ( frame . filename , frame . lineno , frame . function_name ) )
yield text_ ( ' ' + frame . current_line . strip ( ) )
yield text_ ( self . exception ) |
def stream_interactions ( self ) :
"""Generate a temporal ordered stream of interactions .
Returns
nd _ iter : an iterator
The iterator returns a 4 - tuples of ( node , node , op , timestamp ) .
Examples
> > > G = dn . DynGraph ( )
> > > G . add _ path ( [ 0,1,2,3 ] , t = 0)
> > > G . add _ path ( [ 3... | timestamps = sorted ( self . time_to_edge . keys ( ) )
for t in timestamps :
for e in self . time_to_edge [ t ] :
yield ( e [ 0 ] , e [ 1 ] , e [ 2 ] , t ) |
def write_result ( self , buf ) :
"""Render a DataFrame to a LaTeX tabular / longtable environment output .""" | # string representation of the columns
if len ( self . frame . columns ) == 0 or len ( self . frame . index ) == 0 :
info_line = ( 'Empty {name}\nColumns: {col}\nIndex: {idx}' . format ( name = type ( self . frame ) . __name__ , col = self . frame . columns , idx = self . frame . index ) )
strcols = [ [ info_li... |
def postParse ( self , instring , loc , token_list ) :
"""Create a list from the tokens
: param instring :
: param loc :
: param token _ list :
: return :""" | cleaned_token_list = [ token for tokens in ( token . tokens if isinstance ( token , ConfigInclude ) else [ token ] for token in token_list if token != '' ) for token in tokens ]
config_list = ConfigList ( cleaned_token_list )
return [ config_list ] |
def _sigma_1 ( gam , eps ) :
"""gam and eps in units of m _ e c ^ 2
Eq . A2 of Baring et al . ( 1999)
Return in units of cm2 / mec2""" | s1 = 4 * r0 ** 2 * alpha / eps / mec2_unit
s2 = 1 + ( 1.0 / 3.0 - eps / gam ) * ( 1 - eps / gam )
s3 = np . log ( 2 * gam * ( gam - eps ) / eps ) - 1.0 / 2.0
s3 [ np . where ( gam < eps ) ] = 0.0
return s1 * s2 * s3 |
def get_implicit_depends_on ( input_hash , depends_on ) :
'''Add DNAnexus links to non - closed data objects in input _ hash to depends _ on''' | q = [ ]
for field in input_hash :
possible_dep = get_nonclosed_data_obj_link ( input_hash [ field ] )
if possible_dep is not None :
depends_on . append ( possible_dep )
elif isinstance ( input_hash [ field ] , list ) or isinstance ( input_hash [ field ] , dict ) :
q . append ( input_hash [ f... |
def main ( master_dsn , slave_dsn , tables , blocking = False ) :
"""DB Replication app .
This script will replicate data from mysql master to other databases (
including mysql , postgres , sqlite ) .
This script only support a very limited replication :
1 . data only . The script only replicates data , so ... | # currently only supports mysql master
assert master_dsn . startswith ( "mysql" )
logger = logging . getLogger ( __name__ )
logger . info ( "replicating tables: %s" % ", " . join ( tables ) )
repl_db_sub ( master_dsn , slave_dsn , tables )
mysql_pub ( master_dsn , blocking = blocking ) |
def model_deleted ( sender , instance , using , ** kwargs ) :
"""Automatically triggers " deleted " actions .""" | opts = get_opts ( instance )
model = '.' . join ( [ opts . app_label , opts . object_name ] )
distill_model_event ( instance , model , 'deleted' ) |
def cache_clear ( self ) :
"""Clear local cache by deleting all cached resources and their
downloaded files .""" | # Delete content of local cache directory
for f in os . listdir ( self . directory ) :
f = os . path . join ( self . directory , f )
if os . path . isfile ( f ) :
os . remove ( f )
elif os . path . isdir ( f ) :
shutil . rmtree ( f )
# Empty cache index
self . cache = { } |
def buildType ( columns = [ ] , extra = [ ] ) :
"""Build a table
: param list columns : List of column names and types . eg [ ( ' colA ' , ' d ' ) ]
: param list extra : A list of tuples describing additional non - standard fields
: returns : A : py : class : ` Type `""" | return Type ( id = "epics:nt/NTTable:1.0" , spec = [ ( 'labels' , 'as' ) , ( 'value' , ( 'S' , None , columns ) ) , ( 'descriptor' , 's' ) , ( 'alarm' , alarm ) , ( 'timeStamp' , timeStamp ) , ] + extra ) |
def list ( self , ** params ) :
"""Retrieve all sources
Returns all deal sources available to the user according to the parameters provided
: calls : ` ` get / sources ` `
: param dict params : ( optional ) Search options .
: return : List of dictionaries that support attriubte - style access , which repres... | _ , _ , sources = self . http_client . get ( "/sources" , params = params )
return sources |
def plot_discrete ( self , show = False ) :
"""Plot closed curves
Parameters
show : bool
If False will not execute matplotlib . pyplot . show""" | import matplotlib . pyplot as plt
from mpl_toolkits . mplot3d import Axes3D
# NOQA
fig = plt . figure ( )
axis = fig . add_subplot ( 111 , projection = '3d' )
for discrete in self . discrete :
axis . plot ( * discrete . T )
if show :
plt . show ( ) |
def to_dict ( self ) :
"""Convert this VirtualIP to a dict representation for passing
to the API .""" | if self . id :
return { "id" : self . id }
return { "type" : self . type , "ipVersion" : self . ip_version } |
def _name_from_project_path ( path , project , template ) :
"""Validate a URI path and get the leaf object ' s name .
: type path : str
: param path : URI path containing the name .
: type project : str
: param project : ( Optional ) The project associated with the request . It is
included for validation ... | if isinstance ( template , str ) :
template = re . compile ( template )
match = template . match ( path )
if not match :
raise ValueError ( 'path "%s" did not match expected pattern "%s"' % ( path , template . pattern ) )
if project is not None :
found_project = match . group ( "project" )
if found_proj... |
def drop_partition ( self , db_name , tbl_name , part_vals , deleteData ) :
"""Parameters :
- db _ name
- tbl _ name
- part _ vals
- deleteData""" | self . send_drop_partition ( db_name , tbl_name , part_vals , deleteData )
return self . recv_drop_partition ( ) |
def _set_syslog_client ( self , v , load = False ) :
"""Setter method for syslog _ client , mapped from YANG variable / logging / syslog _ client ( container )
If this variable is read - only ( config : false ) in the
source YANG file , then _ set _ syslog _ client is considered as a private
method . Backends... | if hasattr ( v , "_utype" ) :
v = v . _utype ( v )
try :
t = YANGDynClass ( v , base = syslog_client . syslog_client , is_container = 'container' , presence = False , yang_name = "syslog-client" , rest_name = "syslog-client" , parent = self , path_helper = self . _path_helper , extmethods = self . _extmethods ,... |
def featurize ( * features ) :
"""Put features into proper MRO order .""" | from functools import cmp_to_key
def compare_subclass ( left , right ) :
if issubclass ( left , right ) :
return - 1
elif issubclass ( right , left ) :
return 1
return 0
sorted_features = sorted ( features , key = cmp_to_key ( compare_subclass ) )
name = 'FeaturizedClient[{features}]' . form... |
def _EntriesGenerator ( self ) :
"""Retrieves directory entries .
Since a directory can contain a vast number of entries using
a generator is more memory efficient .
Yields :
APFSPathSpec : APFS path specification .""" | try :
fsapfs_file_entry = self . _file_system . GetAPFSFileEntryByPathSpec ( self . path_spec )
except errors . PathSpecError :
return
location = getattr ( self . path_spec , 'location' , None )
for fsapfs_sub_file_entry in fsapfs_file_entry . sub_file_entries :
directory_entry = fsapfs_sub_file_entry . nam... |
def run_migrations_online ( ) :
"""Run migrations in ' online ' mode .
In this scenario we need to create an Engine
and associate a connection with the context .""" | engine = create_engine ( get_url ( ) )
connection = engine . connect ( )
context . configure ( connection = connection , target_metadata = target_metadata , version_table = "alembic_ziggurat_foundations_version" , transaction_per_migration = True , )
try :
with context . begin_transaction ( ) :
context . ru... |
def annotateText ( self , text , layer , addEmptyAnnotations = True ) :
'''Applies this WordTemplate ( more specifically : its method self . matchingTokens ( ) )
on all words of given text , and adds results of the matching to the text as
a new annotation layer . Returns the input text ( which is augmented with... | from estnltk . text import Text
assert isinstance ( text , Text ) , "the input should be Text, but it is: " + str ( text )
# 1 ) Find words in text that match the given pattern
tokens = self . matchingTokens ( text [ WORDS ] )
if not addEmptyAnnotations and not tokens : # if we are not interested in empty annotations
... |
def create ( self , update_request ) :
"""Create a new BulkCountryUpdateInstance
: param unicode update _ request : URL encoded JSON array of update objects
: returns : Newly created BulkCountryUpdateInstance
: rtype : twilio . rest . voice . v1 . dialing _ permissions . bulk _ country _ update . BulkCountryU... | data = values . of ( { 'UpdateRequest' : update_request , } )
payload = self . _version . create ( 'POST' , self . _uri , data = data , )
return BulkCountryUpdateInstance ( self . _version , payload , ) |
def _parse_lifecycle_config ( self , ( response , xml_bytes ) ) :
"""Parse a C { LifecycleConfiguration } XML document .""" | root = XML ( xml_bytes )
rules = [ ]
for content_data in root . findall ( "Rule" ) :
id = content_data . findtext ( "ID" )
prefix = content_data . findtext ( "Prefix" )
status = content_data . findtext ( "Status" )
expiration = int ( content_data . findtext ( "Expiration/Days" ) )
rules . append ( L... |
def load ( self , * objs ) -> "ReadTransaction" :
"""Add one or more objects to be loaded in this transaction .
At most 10 items can be loaded in the same transaction . All objects will be loaded each time you
call commit ( ) .
: param objs : Objects to add to the set that are loaded in this transaction .
:... | self . _extend ( [ TxItem . new ( "get" , obj ) for obj in objs ] )
return self |
def check_matching_coordinates ( func ) :
"""Decorate a function to make sure all given DataArrays have matching coordinates .""" | @ functools . wraps ( func )
def wrapper ( * args , ** kwargs ) :
data_arrays = ( [ a for a in args if isinstance ( a , xr . DataArray ) ] + [ a for a in kwargs . values ( ) if isinstance ( a , xr . DataArray ) ] )
if len ( data_arrays ) > 1 :
first = data_arrays [ 0 ]
for other in data_arrays [... |
def n_exec_stmt ( self , node ) :
"""exec _ stmt : : = EXEC expr
exec _ stmt : : = EXEC expr IN test
exec _ stmt : : = EXEC expr IN test COMMA test""" | self . write ( self . indent , 'exec ' )
self . preorder ( node [ 1 ] )
if len ( node ) > 2 :
self . write ( self . indent , ' in ' )
self . preorder ( node [ 3 ] )
if len ( node ) > 5 :
self . write ( self . indent , ', ' )
self . preorder ( node [ 5 ] )
self . println ( )
self . prune ( ) |
def _do_broker_main ( self ) :
"""Broker thread main function . Dispatches IO events until
: meth : ` shutdown ` is called .""" | # For Python 2.4 , no way to retrieve ident except on thread .
self . _waker . broker_ident = thread . get_ident ( )
try :
while self . _alive :
self . _loop_once ( )
fire ( self , 'shutdown' )
self . _broker_shutdown ( )
except Exception :
LOG . exception ( '_broker_main() crashed' )
self . _al... |
def run ( self , argv ) :
"""Dispatch the given command & args .""" | command = argv [ 0 ]
handlers = { 'clean' : self . clean , 'create' : self . create , 'disable' : self . disable , 'enable' : self . enable , 'list' : self . list , 'update' : self . update , }
handler = handlers . get ( command , None )
if handler is None :
error ( "Unrecognized command: %s" % command , 2 )
handle... |
def append ( self , data ) :
"""Append a Data instance to self""" | for k in self . _entries . keys ( ) :
self . _entries [ k ] . append ( data . _entries [ k ] ) |
def cross_successors ( state , last_action = None ) :
"""Successors function for solving the cross .""" | centres , edges = state
acts = sum ( [ [ s , s . inverse ( ) , s * 2 ] for s in map ( Step , "RUFDRB" . replace ( last_action . face if last_action else "" , "" , 1 ) ) ] , [ ] )
for step in acts :
yield step , ( centres , CrossSolver . _rotate ( edges , step ) ) |
def _trim_base64 ( s ) :
"""Trim and hash base64 strings""" | if len ( s ) > 64 and _base64 . match ( s . replace ( '\n' , '' ) ) :
h = hash_string ( s )
s = '%s...<snip base64, md5=%s...>' % ( s [ : 8 ] , h [ : 16 ] )
return s |
def free_processed_queue ( self ) :
'''call the Aspera sdk to freeup resources''' | with self . _lock :
if len ( self . _processed_coordinators ) > 0 :
for _coordinator in self . _processed_coordinators :
_coordinator . free_resources ( )
self . _processed_coordinators = [ ] |
def reassign ( self , from_email , user_ids ) :
"""Reassign an incident to other users using a valid email address .""" | endpoint = '/' . join ( ( self . endpoint , self . id , ) )
if from_email is None or not isinstance ( from_email , six . string_types ) :
raise MissingFromEmail ( from_email )
if user_ids is None or not isinstance ( user_ids , list ) :
raise InvalidArguments ( user_ids )
if not all ( [ isinstance ( i , six . st... |
def recrad ( rectan ) :
"""Convert rectangular coordinates to range , right ascension , and declination .
http : / / naif . jpl . nasa . gov / pub / naif / toolkit _ docs / C / cspice / recrad _ c . html
: param rectan : Rectangular coordinates of a point .
: type rectan : 3 - Element Array of floats
: retu... | rectan = stypes . toDoubleVector ( rectan )
outrange = ctypes . c_double ( )
ra = ctypes . c_double ( )
dec = ctypes . c_double ( )
libspice . recrad_c ( rectan , ctypes . byref ( outrange ) , ctypes . byref ( ra ) , ctypes . byref ( dec ) )
return outrange . value , ra . value , dec . value |
def generate_RF_bins ( data , dim = 40 , num_bins = 10 ) :
"""Generates bins for the encoder . Bins are designed to have equal frequency ,
per Poirazi & Mel ( 2001 ) , which requires reading the data once .
Bins are represented as the intervals dividing them .""" | intervals = [ ]
for i in range ( dim ) :
current_dim_data = [ data [ x ] [ i ] for x in range ( len ( data ) ) ]
current_dim_data = numpy . sort ( current_dim_data )
intervals . append ( [ current_dim_data [ int ( len ( current_dim_data ) * x / num_bins ) ] for x in range ( 1 , num_bins ) ] )
return interva... |
def update_jail ( name ) :
'''Run freebsd - update on ` name ` poudriere jail
CLI Example :
. . code - block : : bash
salt ' * ' poudriere . update _ jail freebsd : 10 : x86:64''' | if is_jail ( name ) :
cmd = 'poudriere jail -u -j {0}' . format ( name )
ret = __salt__ [ 'cmd.run' ] ( cmd )
return ret
else :
return 'Could not find jail {0}' . format ( name ) |
def ceiling_func ( self , addr ) :
"""Return the function who has the least address that is greater than or equal to ` addr ` .
: param int addr : The address to query .
: return : A Function instance , or None if there is no other function after ` addr ` .
: rtype : Function or None""" | try :
next_addr = self . _function_map . ceiling_addr ( addr )
return self . _function_map . get ( next_addr )
except KeyError :
return None |
def create_nic ( access_token , subscription_id , resource_group , nic_name , public_ip_id , subnet_id , location , nsg_id = None ) :
'''Create a network interface with an associated public ip address .
Args :
access _ token ( str ) : A valid Azure authentication token .
subscription _ id ( str ) : Azure subs... | endpoint = '' . join ( [ get_rm_endpoint ( ) , '/subscriptions/' , subscription_id , '/resourceGroups/' , resource_group , '/providers/Microsoft.Network/networkInterfaces/' , nic_name , '?api-version=' , NETWORK_API ] )
nic_body = { 'location' : location }
ipconfig = { 'name' : 'ipconfig1' }
ipc_properties = { 'private... |
def apply ( self , func , axis = 0 , broadcast = None , reduce = None , result_type = None ) :
"""Analogous to DataFrame . apply , for SparseDataFrame
Parameters
func : function
Function to apply to each column
axis : { 0 , 1 , ' index ' , ' columns ' }
broadcast : bool , default False
For aggregation f... | if not len ( self . columns ) :
return self
axis = self . _get_axis_number ( axis )
if isinstance ( func , np . ufunc ) :
new_series = { }
for k , v in self . items ( ) :
applied = func ( v )
applied . fill_value = func ( v . fill_value )
new_series [ k ] = applied
return self . ... |
def random_restore ( rnd : Optional [ tcod . random . Random ] , backup : tcod . random . Random ) -> None :
"""Restore a random number generator from a backed up copy .
Args :
rnd ( Optional [ Random ] ) : A Random instance , or None to use the default .
backup ( Random ) : The Random instance which was used... | lib . TCOD_random_restore ( rnd . random_c if rnd else ffi . NULL , backup . random_c ) |
def hue ( self , hue ) :
"""Set the group hue .
: param hue : Hue in decimal percent ( 0.0-1.0 ) .""" | if hue < 0 or hue > 1 :
raise ValueError ( "Hue must be a percentage " "represented as decimal 0-1.0" )
self . _hue = hue
cmd = self . command_set . hue ( hue )
self . send ( cmd ) |
def _load_settings ( self , info ) :
"""Load settings for a module .""" | modname , modsettings , architectures , targets , release_info = info
self . settings = modsettings
# Name is converted to all lowercase to canonicalize it
prepend = ''
if 'domain' in modsettings :
prepend = modsettings [ 'domain' ] . lower ( ) + '/'
key = prepend + modname . lower ( )
# Copy over some key properti... |
def add ( self , tool ) :
"""Adds a Tool to the list , logs the reference and TODO""" | self . lstTools . append ( tool )
self . lg . record_process ( self . _get_tool_str ( tool ) ) |
def rename ( self , name ) :
"""Rename the table""" | sql = """ALTER TABLE {s}.{t} RENAME TO {name}
""" . format ( s = self . schema , t = self . name , name = name )
self . engine . execute ( sql )
self . table = SQLATable ( name , self . metadata , schema = self . schema , autoload = True ) |
def find_version ( * file_paths ) :
"""This pattern was modeled on a method from the Python Packaging User Guide :
https : / / packaging . python . org / en / latest / single _ source _ version . html
We read instead of importing so we don ' t get import errors if our code
imports from dependencies listed in ... | base_module_file = os . path . join ( * file_paths )
with open ( base_module_file ) as f :
base_module_data = f . read ( )
version_match = re . search ( r"^__version__ = ['\"]([^'\"]*)['\"]" , base_module_data , re . M )
if version_match :
return version_match . group ( 1 )
raise RuntimeError ( "Unable to find ... |
def get_folding_model_data ( nstep , rvec0 = np . zeros ( ( 5 ) ) , nskip = 1 , dt = 0.01 , kT = 10.0 , mass = 1.0 , damping = 1.0 , rcut = 3.0 ) :
r"""wrapper for the folding model generator""" | fm = FoldingModel ( dt , kT , mass = mass , damping = damping , rcut = rcut )
return fm . sample ( rvec0 , nstep , nskip = nskip ) |
def _run_command ( self , packet ) :
"""Execute a run command from the client .""" | create_temp_cli = self . client_states is None
if create_temp_cli : # If this client doesn ' t have a CLI . Create a Fake CLI where the
# window containing this pane , is the active one . ( The CLI instance
# will be removed before the render function is called , so it doesn ' t
# hurt too much and makes the code easie... |
def read_file ( self , filepath = None , filename = None ) :
"""Tries to read JSON content from filename and convert it to a dict .
: param filepath : Path where the file is
: param filename : File name
: return : Dictionary read from the file
: raises EnvironmentError , ValueError""" | name = filename if filename else self . filename
path = filepath if filepath else self . filepath
name = self . _ends_with ( name , ".json" )
path = self . _ends_with ( path , os . path . sep )
try :
return self . _read_json ( path , name )
except EnvironmentError as error :
self . logger . error ( "Error while... |
async def stop_listen_notifications ( self ) :
"""Stop listening on notifications .""" | _LOGGER . debug ( "Stopping listening for notifications.." )
for serv in self . services . values ( ) :
await serv . stop_listen_notifications ( )
return True |
def populate_iteration ( self , iteration ) :
"""Parse genotypes from the file and iteration with relevant marker details .
: param iteration : ParseLocus object which is returned per iteration
: return : True indicates current locus is valid .
StopIteration is thrown if the marker reaches the end of the file... | cur_idx = iteration . cur_idx
if cur_idx < self . total_locus_count :
buffer = struct . unpack ( self . fmt_string , self . genotype_file . read ( self . bytes_per_read ) )
genotypes = numpy . ma . MaskedArray ( self . extract_genotypes ( buffer ) , self . ind_mask ) . compressed ( )
iteration . chr , itera... |
def merge_dependency ( self , item , resolve_parent , parents ) :
"""Merge dependencies of current configuration with further dependencies ; in this instance , it means that in case
of container configuration first parent dependencies are checked , and then immediate dependencies of the current
configuration sh... | dep = [ ]
for parent_key in parents :
if item == parent_key :
raise CircularDependency ( item , True )
if parent_key . config_type == ItemType . CONTAINER :
parent_dep = resolve_parent ( parent_key )
if item in parent_dep :
raise CircularDependency ( item )
merge_list... |
def connect ( self , src , dst = None , callback = None ) :
''': param src : source node , if dst is None it will be destination node and the root ( dummy ) node will be source
: param dst : destination node ( default : None )
: type callback : func ( fuzzer , edge , response ) - > None
: param callback : a f... | assert src
if dst is None :
dst = src
src = self . _root
src_id = src . hash ( )
dst_id = dst . hash ( )
if src_id not in self . _graph :
raise KittyException ( 'source node id (%#x) (%s) is not in the node list ' % ( src_id , src ) )
self . _graph [ src_id ] . append ( Connection ( src , dst , callback ) )... |
def pages_to_json ( queryset ) :
"""Return a JSON string export of the pages in queryset .""" | # selection may be in the wrong order , and order matters
queryset = queryset . order_by ( 'tree_id' , 'lft' )
return simplejson . dumps ( { JSON_PAGE_EXPORT_NAME : JSON_PAGE_EXPORT_VERSION , 'pages' : [ page . dump_json_data ( ) for page in queryset ] } , indent = JSON_PAGE_EXPORT_INDENT , sort_keys = True ) |
def _get_function_type ( self , function_name ) :
"""Returns the function object that matches the provided name .
Only Fn : : and Ref functions are supported here so that other
functions specific to troposphere are skipped .""" | if ( function_name . startswith ( "Fn::" ) and function_name [ 4 : ] in self . inspect_functions ) :
return self . inspect_functions [ function_name [ 4 : ] ]
return ( self . inspect_functions [ 'Ref' ] if function_name == "Ref" else None ) |
def phmmer ( query , db , type , out , threads = '4' , evalue = '0.01' ) :
"""run phmmer""" | if os . path . exists ( out ) is False :
print ( '# ... running phmmer with %s as query and %s as database' % ( query , db ) )
os . system ( 'phmmer -o %s.ph1 --tblout %s.ph2 --acc --noali --notextw -E %s --cpu %s %s %s' % ( out , out , evalue , threads , query , db ) )
else :
print ( '# ... phmmer output f... |
def get_blast ( pdb_id , chain_id = 'A' ) :
"""Return BLAST search results for a given PDB ID
The key of the output dict ( ) ) that outputs the full search results is
' BlastOutput _ iterations '
To get a list of just the results without the metadata of the search use :
hits = full _ results [ ' BlastOutput... | raw_results = get_raw_blast ( pdb_id , output_form = 'XML' , chain_id = chain_id )
out = xmltodict . parse ( raw_results , process_namespaces = True )
out = to_dict ( out )
out = out [ 'BlastOutput' ]
return out |
def save_linked_hdds_info ( self ) :
"""Save linked cloned hard disks information .
: returns : disk table information""" | hdd_table = [ ]
if self . linked_clone :
if os . path . exists ( self . working_dir ) :
hdd_files = yield from self . _get_all_hdd_files ( )
vm_info = yield from self . _get_vm_info ( )
for entry , value in vm_info . items ( ) :
match = re . search ( "^([\s\w]+)\-(\d)\-(\d)$" , e... |
def validate_integrity ( self ) :
"""Validate the integrity of the DataFrame . This checks that the indexes , column names and internal data are not
corrupted . Will raise an error if there is a problem .
: return : nothing""" | self . _validate_columns ( self . _columns )
self . _validate_index ( self . _index )
self . _validate_data ( ) |
def to_xml ( cls , enum_val ) :
"""Return the XML value of the enumeration value * enum _ val * .""" | if enum_val not in cls . _member_to_xml :
raise ValueError ( "value '%s' not in enumeration %s" % ( enum_val , cls . __name__ ) )
return cls . _member_to_xml [ enum_val ] |
def metadata ( abbr , __metadata = __metadata ) :
"""Grab the metadata for the given two - letter abbreviation .""" | # This data should change very rarely and is queried very often so
# cache it here
abbr = abbr . lower ( )
if abbr in __metadata :
return __metadata [ abbr ]
rv = db . metadata . find_one ( { '_id' : abbr } )
__metadata [ abbr ] = rv
return rv |
def migrated ( name , remote_addr , cert , key , verify_cert , src_remote_addr , stop_and_start = False , src_cert = None , src_key = None , src_verify_cert = None ) :
'''Ensure a container is migrated to another host
If the container is running , it either must be shut down
first ( use stop _ and _ start = Tru... | ret = { 'name' : name , 'remote_addr' : remote_addr , 'cert' : cert , 'key' : key , 'verify_cert' : verify_cert , 'src_remote_addr' : src_remote_addr , 'src_and_start' : stop_and_start , 'src_cert' : src_cert , 'src_key' : src_key , 'changes' : { } }
dest_container = None
try :
dest_container = __salt__ [ 'lxd.cont... |
def _sha256_sign ( self , method , url , headers , body ) :
"""Sign the request with SHA256.""" | d = ''
sign_headers = method . upper ( ) + '|' + url + '|'
for key , value in sorted ( headers . items ( ) ) :
if key . startswith ( 'X-Mcash-' ) :
sign_headers += d + key . upper ( ) + '=' + value
d = '&'
rsa_signature = base64 . b64encode ( self . signer . sign ( SHA256 . new ( sign_headers ) ) )
... |
def execute_remote ( self , remote_target , cmd , ** kwargs ) :
"""Executes the given command ( with the given arguments )
on the given remote target of the connected machine""" | data = self . _build_command ( cmd , kwargs , self . _contexts [ - 1 ] , remote_target )
with self . _lock :
rootelem = self . transport . send ( data )
try :
return self . _build_response ( rootelem )
except ElementNotFoundException :
xlog . exception ( "XCLIClient.execute" )
raise chained ( CorruptRes... |
def filter_publication ( publication ) :
"""Filter : class : ` . Publication ` objects using settings declared in
: mod : ` ~ harvester . settings ` submodule .
Args :
publication ( obj ) : : class : ` . Publication ` instance .
Returns :
obj / None : None if the publication was found in Aleph or ` public... | if settings . USE_DUP_FILTER :
publication = dup_filter . filter_publication ( publication )
if publication and settings . USE_ALEPH_FILTER :
publication = aleph_filter . filter_publication ( publication , cmp_authors = settings . ALEPH_FILTER_BY_AUTHOR )
return publication |
def setKWARGS ( self , ** kwargs ) :
"""Used to set all attributes given in a * * kwargs parameter .
Might throw an Exception if attribute was not found .
# TODO : check if we should fix this using " setAttribute " """ | for key in list ( kwargs . keys ( ) ) : # try :
f = getattr ( self , 'set_' + key )
f ( kwargs [ key ] ) |
def _cbCvtReply ( self , msg , returnSignature ) :
"""Converts a remote method call reply message into an appropriate
callback
value .""" | if msg is None :
return None
if returnSignature != _NO_CHECK_RETURN :
if not returnSignature :
if msg . signature :
raise error . RemoteError ( 'Unexpected return value signature' )
else :
if not msg . signature or msg . signature != returnSignature :
msg = 'Expected ... |
def toggle_shells ( command , enable ) :
"""Enable or disable the specified shells . If the command would have
no effect , it changes all other shells to the inverse enable value .""" | selection = list ( selected_shells ( command ) )
if command and command != '*' and selection :
for i in selection :
if i . state != remote_dispatcher . STATE_DEAD and i . enabled != enable :
break
else :
toggle_shells ( '*' , not enable )
for i in selection :
if i . state != remo... |
def guess_project_dir ( ) :
"""Find the top - level Django project directory .
This function guesses the top - level Django project directory based on
the current environment . It looks for module containing the currently -
active settings module , in both pre - 1.4 and post - 1.4 layours .""" | projname = settings . SETTINGS_MODULE . split ( "." , 1 ) [ 0 ]
projmod = import_module ( projname )
projdir = os . path . dirname ( projmod . __file__ )
# For Django 1.3 and earlier , the manage . py file was located
# in the same directory as the settings file .
if os . path . isfile ( os . path . join ( projdir , "m... |
def _simulate_client ( plaintext_password , init_pbkdf2_salt , cnonce , server_challenge ) :
"""A implementation of the JavaScript client part .
Needful for finding bugs .""" | # log . debug ( " _ simulate _ client ( plaintext _ password = ' % s ' , init _ pbkdf2 _ salt = ' % s ' , cnonce = ' % s ' , server _ challenge = ' % s ' ) " ,
# plaintext _ password , init _ pbkdf2 _ salt , cnonce , server _ challenge
pbkdf2_temp_hash = hexlify_pbkdf2 ( plaintext_password , salt = init_pbkdf2_salt , i... |
def del_key ( cls , k ) :
"""Matching get method for ` ` set _ key ` `""" | k = cls . __name__ + "__" + k
session . pop ( k ) |
def _authenticated_path ( self ) :
"""Get the path of our XML - RPC endpoint with session auth params added .
For example :
/ kojihub ? session - id = 123456 & session - key = 1234 - asdf & callnum = 0
If we ' re making an authenticated request , we must add these session
parameters to the hub ' s XML - RPC... | basepath = self . proxy . path . decode ( ) . split ( '?' ) [ 0 ]
params = urlencode ( { 'session-id' : self . session_id , 'session-key' : self . session_key , 'callnum' : self . callnum } )
result = '%s?%s' % ( basepath , params )
return result . encode ( 'utf-8' ) |
def get ( cls , bucket , key , upload_id , with_completed = False ) :
"""Fetch a specific multipart object .""" | q = cls . query . filter_by ( upload_id = upload_id , bucket_id = as_bucket_id ( bucket ) , key = key , )
if not with_completed :
q = q . filter ( cls . completed . is_ ( False ) )
return q . one_or_none ( ) |
def _validate_type ( self ) : # type : ( ) - > None
"""Validation to ensure value is the correct type""" | if not isinstance ( self . _value , self . _type ) :
title = '{} has an invalid type' . format ( self . _key_name ( ) )
description = '{} must be a {}' . format ( self . _key_name ( ) , self . _type . __name__ )
self . _add_error ( title = title , description = description ) |
def _from_string ( cls , serialized ) :
"""see super""" | # Allow access to _ from _ string protected method
parsed_parts = cls . parse_url ( serialized )
course_key = CourseLocator ( parsed_parts . get ( 'org' ) , parsed_parts . get ( 'course' ) , parsed_parts . get ( 'run' ) , # specifically not saying deprecated = True b / c that would lose the run on serialization
)
block... |
def _generate_report ( self ) :
"""Generates the visual report""" | from niworkflows . viz . utils import plot_registration
NIWORKFLOWS_LOG . info ( 'Generating visual report' )
fixed_image_nii = load_img ( self . _fixed_image )
moving_image_nii = load_img ( self . _moving_image )
contour_nii = load_img ( self . _contour ) if self . _contour is not None else None
if self . _fixed_image... |
def feed ( self , new_bytes ) :
"""Feed a new set of bytes into the protocol handler
These bytes will be immediately fed into the parsing state machine and
if new packets are found , the ` ` packet _ callback ` ` will be executed
with the fully - formed message .
: param new _ bytes : The new bytes to be fe... | self . _available_bytes += new_bytes
callbacks = [ ]
try :
while True :
packet = six . next ( self . _packet_generator )
if packet is None :
break
else :
callbacks . append ( partial ( self . packet_callback , packet ) )
except Exception : # When we receive an excepti... |
def get_iter_string_reader ( stdin ) :
"""return an iterator that returns a chunk of a string every time it is
called . notice that even though bufsize _ type might be line buffered , we ' re
not doing any line buffering here . that ' s because our StreamBufferer
handles all buffering . we just need to return... | bufsize = 1024
iter_str = ( stdin [ i : i + bufsize ] for i in range ( 0 , len ( stdin ) , bufsize ) )
return get_iter_chunk_reader ( iter_str ) |
def on_paint ( self , event ) :
'''repaint the image''' | dc = wx . AutoBufferedPaintDC ( self )
dc . DrawBitmap ( self . _bmp , 0 , 0 ) |
def _config_parser_to_defaultdict ( config_parser ) :
"""Convert a ConfigParser to a defaultdict .
Args :
config _ parser ( ConfigParser ) : A ConfigParser .""" | config = defaultdict ( defaultdict )
for section , section_content in config_parser . items ( ) :
if section != 'DEFAULT' :
for option , option_value in section_content . items ( ) :
config [ section ] [ option ] = option_value
return config |
def update ( self , vips ) :
"""Method to update vip ' s
: param vips : List containing vip ' s desired to updated
: return : None""" | data = { 'vips' : vips }
vips_ids = [ str ( vip . get ( 'id' ) ) for vip in vips ]
return super ( ApiVipRequest , self ) . put ( 'api/v3/vip-request/%s/' % ';' . join ( vips_ids ) , data ) |
def GetSystemConfigurationArtifact ( self , session_identifier = CURRENT_SESSION ) :
"""Retrieves the knowledge base as a system configuration artifact .
Args :
session _ identifier ( Optional [ str ] ) ) : session identifier , where
CURRENT _ SESSION represents the active session .
Returns :
SystemConfig... | system_configuration = artifacts . SystemConfigurationArtifact ( )
system_configuration . code_page = self . GetValue ( 'codepage' , default_value = self . _codepage )
system_configuration . hostname = self . _hostnames . get ( session_identifier , None )
system_configuration . keyboard_layout = self . GetValue ( 'keyb... |
def setVisible ( self , state ) :
"""Closes this widget and kills the result .""" | super ( XOverlayWidget , self ) . setVisible ( state )
if not state :
self . setResult ( 0 ) |
def _get_other_allele_by_zygosity ( allele_id , zygosity ) :
"""A helper function to switch on the zygosity ,
and return the appropriate allele id , or symbol .
: param allele _ id :
: param zygosity :
: return :""" | other_allele = None
if zygosity == 'homozygous' :
other_allele = allele_id
elif zygosity == 'hemizygous' :
other_allele = '0'
elif zygosity == 'unknown' : # we ' ll use this as a convention
other_allele = '?'
elif zygosity == 'complex' : # transgenics
other_allele = '0'
elif zygosity == 'heterozygous' :... |
def setup_formats ( self ) :
"""Inspects its methods to see what it can convert from and to""" | methods = self . get_methods ( )
for m in methods : # Methods named " from _ X " will be assumed to convert from format X to the common format
if m . startswith ( "from_" ) :
self . input_formats . append ( re . sub ( "from_" , "" , m ) )
# Methods named " to _ X " will be assumed to convert from the co... |
def get_arg_parse_arguments ( self ) :
"""During the element declaration , all configuration file requirements
and all cli requirements have been described once .
This method will build a dict containing all argparse options .
It can be used to feed argparse . ArgumentParser .
You does not need to have mult... | ret = dict ( )
if self . _required :
if self . value is not None :
ret [ "default" ] = self . value
else :
ret [ "required" ] = True
ret [ "dest" ] = self . _name
if not self . e_type_exclude :
if self . e_type == int or self . e_type == float : # Just override argparse . add _ argument ' ty... |
def pages ( self ) :
"""This is a list of HarPage objects , each of which represents a page
from the HAR file .""" | # Start with a page object for unknown entries if the HAR data has
# any entries with no page ID
pages = [ ]
if any ( 'pageref' not in entry for entry in self . har_data [ 'entries' ] ) :
pages . append ( HarPage ( 'unknown' , har_parser = self ) )
for har_page in self . har_data [ 'pages' ] :
page = HarPage ( ... |
def _consolidate_inplace ( self ) :
"""Consolidate data in place and return None""" | def f ( ) :
self . _data = self . _data . consolidate ( )
self . _protect_consolidate ( f ) |
def bins ( self ) -> List [ np . ndarray ] :
"""List of bin matrices .""" | return [ binning . bins for binning in self . _binnings ] |
def seq ( ) :
"""Counts up sequentially from a number based on the current time
: rtype int :""" | current_frame = inspect . currentframe ( ) . f_back
trace_string = ""
while current_frame . f_back :
trace_string = trace_string + current_frame . f_back . f_code . co_name
current_frame = current_frame . f_back
return counter . get_from_trace ( trace_string ) |
def renderHTTP ( self , context ) :
"""Render the wrapped resource if HTTPS is already being used , otherwise
invoke a helper which may generate a redirect .""" | request = IRequest ( context )
if request . isSecure ( ) :
renderer = self . wrappedResource
else :
renderer = _SecureWrapper ( self . urlGenerator , self . wrappedResource )
return renderer . renderHTTP ( context ) |
def _configure_from_module ( self , item ) :
"""Configure from a module by import path .
Effectively , you give this an absolute or relative import path , it will
import it , and then pass the resulting object to
` ` _ configure _ from _ object ` ` .
Args :
item ( str ) :
A string pointing to a valid im... | package = None
if item [ 0 ] == '.' :
package = self . import_name
obj = importlib . import_module ( item , package = package )
self . config . from_object ( obj )
return self |
def start ( self ) :
"""Make an HTTP request with a specific method""" | # TODO : Use Timeout here and _ ignore _ request _ idle
from . nurest_session import NURESTSession
session = NURESTSession . get_current_session ( )
if self . async :
thread = threading . Thread ( target = self . _make_request , kwargs = { 'session' : session } )
thread . is_daemon = False
thread . start ( ... |
def execute_route ( self , meta_data , request_pdu ) :
"""Execute configured route based on requests meta data and request
PDU .
: param meta _ data : A dict with meta data . It must at least contain
key ' unit _ id ' .
: param request _ pdu : A bytearray containing request PDU .
: return : A bytearry con... | try :
function = create_function_from_request_pdu ( request_pdu )
results = function . execute ( meta_data [ 'unit_id' ] , self . route_map )
try : # ReadFunction ' s use results of callbacks to build response
# PDU . . .
return function . create_response_pdu ( results )
except TypeError : #... |
async def set_playback_settings ( self , target , value ) -> None :
"""Set playback settings such a shuffle and repeat .""" | params = { "settings" : [ { "target" : target , "value" : value } ] }
return await self . services [ "avContent" ] [ "setPlaybackModeSettings" ] ( params ) |
def forceValue ( self , newVal , noteEdited = False ) :
"""Force - set a parameter entry to the given value""" | if newVal is None :
newVal = ""
self . choice . set ( newVal )
if noteEdited :
self . widgetEdited ( val = newVal , skipDups = False ) |
def fname ( self , model_or_obj_or_qs ) :
"""Return the field name on the : class : ` Follow ` model for ` ` model _ or _ obj _ or _ qs ` ` .""" | if isinstance ( model_or_obj_or_qs , QuerySet ) :
_ , fname = model_map [ model_or_obj_or_qs . model ]
else :
cls = model_or_obj_or_qs if inspect . isclass ( model_or_obj_or_qs ) else model_or_obj_or_qs . __class__
_ , fname = model_map [ cls ]
return fname |
def decode_utf_text_buffer ( buf , default_encoding = 'UTF-8' , use_utf8_strings = True ) :
""": param buf : Binary file contents with optional BOM prefix .
: param default _ encoding : The encoding to be used if the buffer
doesn ' t have a BOM prefix .
: param use _ utf8 _ strings : Used only in case of pyth... | buf , encoding = detect_encoding_and_remove_bom ( buf , default_encoding )
if python2 and use_utf8_strings :
if are_encoding_names_equivalent ( encoding , 'UTF-8' ) :
return buf
return buf . decode ( encoding ) . encode ( 'UTF-8' )
return buf . decode ( encoding ) |
def d2logpdf_df2 ( self , f , y , Y_metadata = None ) :
"""Evaluates the link function link ( f ) then computes the second derivative of log likelihood using it
Uses the Faa di Bruno ' s formula for the chain rule
. . math : :
\\ frac { d ^ { 2} \\ log p ( y | \\ lambda ( f ) ) } { df ^ { 2 } } = \\ frac { d ... | if isinstance ( self . gp_link , link_functions . Identity ) :
d2logpdf_df2 = self . d2logpdf_dlink2 ( f , y , Y_metadata = Y_metadata )
else :
inv_link_f = self . gp_link . transf ( f )
d2logpdf_dlink2 = self . d2logpdf_dlink2 ( inv_link_f , y , Y_metadata = Y_metadata )
dlink_df = self . gp_link . dtr... |
def drawLeftStatus ( self , scr , vs ) :
'Draw left side of status bar .' | cattr = CursesAttr ( colors . color_status )
attr = cattr . attr
error_attr = cattr . update_attr ( colors . color_error , 1 ) . attr
warn_attr = cattr . update_attr ( colors . color_warning , 2 ) . attr
sep = options . disp_status_sep
try :
lstatus = vs . leftStatus ( )
maxwidth = options . disp_lstatus_max
... |
def get_password ( self ) :
'''a method to retrieve the password for the group mosquitto server
: return : string with group mosquitto server password
NOTE : result is added to self . password property''' | import requests
url = '%s/mqtt' % self . endpoint
params = { 'group' : self . group_name }
response = requests . put ( url , params = params )
response_details = response . json ( )
self . password = response_details [ 'password' ]
return self . password |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.