signature stringlengths 29 44.1k | implementation stringlengths 0 85.2k |
|---|---|
def find_and_refine_peaks ( self , threshold , min_separation = 1.0 , use_cumul = False ) :
"""Run a simple peak - finding algorithm , and fit the peaks to
paraboloids to extract their positions and error ellipses .
Parameters
threshold : float
Peak threshold in TS .
min _ separation : float
Radius of r... | if use_cumul :
theMap = self . _ts_cumul
else :
theMap = self . _tsmap
peaks = find_peaks ( theMap , threshold , min_separation )
for peak in peaks :
o , skydir = fit_error_ellipse ( theMap , ( peak [ 'ix' ] , peak [ 'iy' ] ) , dpix = 2 )
peak [ 'fit_loc' ] = o
peak [ 'fit_skydir' ] = skydir
if ... |
def get_input_location ( location ) :
"""Similar to : meth : ` get _ input _ peer ` , but for input messages .
Note that this returns a tuple ` ` ( dc _ id , location ) ` ` , the
` ` dc _ id ` ` being present if known .""" | try :
if location . SUBCLASS_OF_ID == 0x1523d462 :
return None , location
# crc32 ( b ' InputFileLocation ' ) :
except AttributeError :
_raise_cast_fail ( location , 'InputFileLocation' )
if isinstance ( location , types . Message ) :
location = location . media
if isinstance ( location , ty... |
def on_state_changed ( self , state ) :
"""Connects / Disconnects to the painted event of the editor
: param state : Enable state""" | if state :
self . editor . painted . connect ( self . _paint_margin )
self . editor . repaint ( )
else :
self . editor . painted . disconnect ( self . _paint_margin )
self . editor . repaint ( ) |
def bootstrap ( self ) :
"""When the software is first started , it needs to retrieve
a list of nodes to connect to the network to . This function
asks the server for N nodes which consists of at least N
passive nodes and N simultaneous nodes . The simultaneous
nodes are prioritized if the node _ type for t... | # Disable bootstrap .
if not self . enable_bootstrap :
return None
# Avoid raping the rendezvous server .
t = time . time ( )
if self . last_bootstrap is not None :
if t - self . last_bootstrap <= rendezvous_interval :
self . debug_print ( "Bootstrapped recently" )
return None
self . last_bootst... |
def missing_uniprot_mapping ( self ) :
"""list : List of genes with no mapping to UniProt .""" | uniprot_missing = [ ]
for g in self . genes :
ups = g . protein . filter_sequences ( UniProtProp )
no_sequence_file_available = True
for u in ups :
if u . sequence_file or u . metadata_file :
no_sequence_file_available = False
break
if no_sequence_file_available :
... |
def export_data_to_uris ( self , destination_uris , dataset , table , job = None , compression = None , destination_format = None , print_header = None , field_delimiter = None , project_id = None , ) :
"""Export data from a BigQuery table to cloud storage . Optional arguments
that are not specified are determine... | destination_uris = destination_uris if isinstance ( destination_uris , list ) else [ destination_uris ]
project_id = self . _get_project_id ( project_id )
configuration = { "sourceTable" : { "projectId" : project_id , "tableId" : table , "datasetId" : dataset } , "destinationUris" : destination_uris , }
if compression ... |
def allowed ( self , method , _dict , allow ) :
"""Only these items are allowed in the dictionary""" | for key in _dict . keys ( ) :
if key not in allow :
raise LunrError ( "'%s' is not an argument for method '%s'" % ( key , method ) ) |
def loading_failed ( self , rdf_format_opts , uri = "" ) :
"""default message if we need to abort loading""" | if uri :
uri = " <%s>" % str ( uri )
printDebug ( "----------\nFatal error parsing graph%s\n(using RDF serializations: %s)" % ( uri , str ( rdf_format_opts ) ) , "red" )
printDebug ( "----------\nTIP: You can try one of the following RDF validation services\n<http://mowl-power.cs.man.ac.uk:8080/validator/validate>\... |
def InitUI ( self ) :
"""Build the mainframe""" | menubar = pmag_gui_menu . MagICMenu ( self , data_model_num = self . data_model_num )
self . SetMenuBar ( menubar )
# pnl = self . panel
# - - - sizer logo - - - -
# start _ image = wx . Image ( " / Users / ronshaar / PmagPy / images / logo2 . png " )
# start _ image = wx . Image ( " / Users / Python / simple _ example... |
def highlightByAlternate ( self ) :
"""Sets the palette highlighting for this tree widget to use a darker
version of the alternate color vs . the standard highlighting .""" | palette = QtGui . QApplication . palette ( )
palette . setColor ( palette . HighlightedText , palette . color ( palette . Text ) )
clr = palette . color ( palette . AlternateBase )
palette . setColor ( palette . Highlight , clr . darker ( 110 ) )
self . setPalette ( palette ) |
def rpc_request ( method_name : str , * args , ** kwargs ) -> rpcq . messages . RPCRequest :
"""Create RPC request
: param method _ name : Method name
: param args : Positional arguments
: param kwargs : Keyword arguments
: return : JSON RPC formatted dict""" | if args :
kwargs [ '*args' ] = args
return rpcq . messages . RPCRequest ( jsonrpc = '2.0' , id = str ( uuid . uuid4 ( ) ) , method = method_name , params = kwargs ) |
def list ( self , per_page = None , page = None , status = None , service = 'facebook' ) :
"""Get a list of Pylon tasks
: param per _ page : How many tasks to display per page
: type per _ page : int
: param page : Which page of tasks to display
: type page : int
: param status : The status of the tasks t... | params = { }
if per_page is not None :
params [ 'per_page' ] = per_page
if page is not None :
params [ 'page' ] = page
if status :
params [ 'status' ] = status
return self . request . get ( service + '/task' , params ) |
def put_container ( self , url , container , container_headers = None ) :
"""Create a container if it is not Found .
: param url :
: param container :""" | headers , container_uri = self . _return_base_data ( url = url , container = container , container_headers = container_headers )
resp = self . _header_getter ( uri = container_uri , headers = headers )
if resp . status_code == 404 :
return self . _putter ( uri = container_uri , headers = headers )
else :
return... |
def help_me ( parser , opt ) :
"""Handle display of help and whatever diagnostics""" | print ( "aomi v%s" % version )
print ( 'Get started with aomi' ' https://autodesk.github.io/aomi/quickstart' )
if opt . verbose == 2 :
tf_str = 'Token File,' if token_file ( ) else ''
app_str = 'AppID File,' if appid_file ( ) else ''
approle_str = 'Approle File,' if approle_file ( ) else ''
tfe_str = 'T... |
def update_payload ( self , fields = None ) :
"""Create a payload of values that can be sent to the server .
By default , this method behaves just like : func : ` _ payload ` . However ,
one can also specify a certain set of fields that should be returned .
For more information , see : meth : ` update ` .""" | values = self . get_values ( )
if fields is not None :
values = { field : values [ field ] for field in fields }
return _payload ( self . get_fields ( ) , values ) |
def fix_config ( self , options ) :
"""Fixes the options , if necessary . I . e . , it adds all required elements to the dictionary .
: param options : the options to fix
: type options : dict
: return : the ( potentially ) fixed options
: rtype : dict""" | options = super ( DeleteStorageValue , self ) . fix_config ( options )
opt = "storage_name"
if opt not in options :
options [ opt ] = "unknown"
if opt not in self . help :
self . help [ opt ] = "The name of the storage value to delete (string)."
return options |
def read_xlsx_catalog ( xlsx_path_or_url , logger = None ) :
"""Toma el path a un catálogo en formato XLSX y devuelve el diccionario
que representa .
Se asume que el parámetro es una URL si comienza con ' http ' o ' https ' , o
un path local de lo contrario .
Args :
xlsx _ path _ or _ url ( str ) : Path... | logger = logger or pydj_logger
assert isinstance ( xlsx_path_or_url , string_types )
parsed_url = urlparse ( xlsx_path_or_url )
if parsed_url . scheme in [ "http" , "https" ] :
res = requests . get ( xlsx_path_or_url , verify = False )
tmpfilename = ".tmpfile.xlsx"
with io . open ( tmpfilename , 'wb' ) as t... |
def construct_all ( templates , ** unbound_var_values ) :
"""Constructs all the given templates in a single pass without redundancy .
This is useful when the templates have a common substructure and you want the
smallest possible graph .
Args :
templates : A sequence of templates .
* * unbound _ var _ val... | def _merge_dicts ( src , dst ) :
for k , v in six . iteritems ( src ) :
if dst . get ( k , v ) != v :
raise ValueError ( 'Conflicting values bound for %s: %s and %s' % ( k , v , dst [ k ] ) )
else :
dst [ k ] = v
# pylint : disable = protected - access
all_unbound_vars = { }
... |
def shebang ( self ) :
"""The # ! entry from the first line of the file
If no shebang is present , return an empty string""" | try :
try :
first_line = self . lines ( ) [ 0 ]
except ( OSError , UnicodeDecodeError ) :
return ''
if first_line . startswith ( '#!' ) :
rest_of_line = first_line [ 2 : ] . strip ( )
parts = rest_of_line . split ( ' ' )
interpreter = parts [ 0 ]
return makepa... |
def _get_seqs_from_cluster ( seqs , seen ) :
"""Returns the sequences that are already part of the cluster
: param seqs : list of sequences ids
: param clus _ id : dict of sequences ids that are part of a cluster
: returns :
* : code : ` already _ in ` list of cluster id that contained some of the sequences... | already_in = set ( )
not_in = [ ]
already_in = map ( seen . get , seqs )
# if isinstance ( already _ in , list ) :
already_in = filter ( None , already_in )
not_in = set ( seqs ) - set ( seen . keys ( ) )
# for s in seqs :
# if s in seen :
# already _ in . add ( seen [ s ] )
# else :
# not _ in . append ( s )
return li... |
def _get_node_key ( self , node_dict_item ) :
"""Return a tuple of sorted sources and targets given a node dict .""" | s = tuple ( sorted ( node_dict_item [ 'sources' ] ) )
t = tuple ( sorted ( node_dict_item [ 'targets' ] ) )
return ( s , t ) |
def calc_move ( self , c ) :
"""calculate the amount of damage down using the battle . rules file
WARNING - shitty eval functions - careful with user input .
TODO = max _ hit = parser . parse ( self . rules [ ' hit _ max ' ] ) . to _ pyfunc ( )""" | # first get local variables the same as battle . rules file so parser can interpret .
AGI = c . stats [ 'AGI' ]
INT = c . stats [ 'INT' ]
STR = c . stats [ 'STR' ]
# STA = c . stats [ ' STA ' ]
# print ( ' calc move : self . rules . all _ rules [ hit _ min ] = ' , self . rules . all _ rules [ ' hit _ min ' ] )
# print ... |
async def start ( self ) :
"""Starts receiving messages on the underlying socket and passes them
to the message router .""" | self . _is_running = True
while self . _is_running :
try :
zmq_msg = await self . _socket . recv_multipart ( )
message = Message ( )
message . ParseFromString ( zmq_msg [ - 1 ] )
await self . _msg_router . route_msg ( message )
except DecodeError as e :
LOGGER . warning (... |
def get_descriptives ( data ) :
"""Get mean , SD , and mean and SD of log values .
Parameters
data : ndarray
Data with segment as first dimension
and all other dimensions raveled into second dimension .
Returns
dict of ndarray
each entry is a 1 - D vector of descriptives over segment dimension""" | output = { }
dat_log = log ( abs ( data ) )
output [ 'mean' ] = nanmean ( data , axis = 0 )
output [ 'sd' ] = nanstd ( data , axis = 0 )
output [ 'mean_log' ] = nanmean ( dat_log , axis = 0 )
output [ 'sd_log' ] = nanstd ( dat_log , axis = 0 )
return output |
def histogram_distance ( arr1 , arr2 , bins = None ) :
"""This function returns the sum of the squared error
Parameters :
two arrays constrained to 0 . . 1
Returns :
sum of the squared error between the histograms""" | eps = 1e-6
assert arr1 . min ( ) > 0 - eps
assert arr1 . max ( ) < 1 + eps
assert arr2 . min ( ) > 0 - eps
assert arr2 . max ( ) < 1 + eps
if not bins :
bins = [ x / 10 for x in range ( 11 ) ]
hist1 = np . histogram ( arr1 , bins = bins ) [ 0 ] / arr1 . size
hist2 = np . histogram ( arr2 , bins = bins ) [ 0 ] / arr... |
def set ( self , name , * components , ** parameters ) :
"""Set available components and the options of one block .
: param name : block name
: param components : the components ( see : meth : ` Block . set ` )
: param parameters : block configuration ( see : meth : ` Block . setup ` )
for example :
> > >... | self . _logger . info ( " ** SET ** '%s' " % name )
if name not in self :
raise ValueError ( "'%s' is not a block (%s)" % ( name , "," . join ( self . names ( ) ) ) )
self [ name ] . set ( * components )
self [ name ] . setup ( ** parameters ) |
def warn ( self , correlation_id , message , * args , ** kwargs ) :
"""Logs a warning that may or may not have a negative impact .
: param correlation _ id : ( optional ) transaction id to trace execution through call chain .
: param message : a human - readable message to log .
: param args : arguments to pa... | self . _format_and_write ( LogLevel . Warn , correlation_id , None , message , args , kwargs ) |
def _derive_db ( self ) :
"""this may not have a client on _ _ init _ _ , so this is deferred to
a @ property descriptor""" | client = self
while hasattr ( client , 'proxied' ) :
client = client . proxied
if hasattr ( client , 'client' ) :
client = client . client
self . _connection_kwargs = client . connection_pool . connection_kwargs
self . _db = self . _connection_kwargs [ 'db' ]
else :
self . _connection_kwargs = False... |
def __properties_update ( self , properties ) :
"""Internal update of configuration properties . Does not notifies the
ConfigurationAdmin of this modification .
: param properties : the new set of properties for this configuration
: return : True if the properties have been updated , else False""" | if not properties : # Nothing to do
return False
with self . __lock : # Make a copy of the properties
properties = properties . copy ( )
# Override properties
properties [ services . CONFIG_PROP_PID ] = self . __pid
if self . __location :
properties [ services . CONFIG_PROP_BUNDLE_LOCATION ]... |
def simxSetBooleanParameter ( clientID , paramIdentifier , paramValue , operationMode ) :
'''Please have a look at the function description / documentation in the V - REP user manual''' | return c_SetBooleanParameter ( clientID , paramIdentifier , paramValue , operationMode ) |
def get ( self , item , default = None ) :
"""Returns the value ` ` item ` ` from the host or hosts group variables .
Arguments :
item ( ` ` str ` ` ) : The variable to get
default ( ` ` any ` ` ) : Return value if item not found""" | if hasattr ( self , item ) :
return getattr ( self , item )
try :
return self . __getitem__ ( item )
except KeyError :
return default |
def _create_socket ( self ) :
"""Creates ssl socket , connects to stream api and
sets timeout .""" | s = socket . socket ( socket . AF_INET , socket . SOCK_STREAM )
s = ssl . wrap_socket ( s )
s . connect ( ( self . host , self . __port ) )
s . settimeout ( self . timeout )
return s |
def _validate ( self , writing = False ) :
"""Validate the box before writing to file .""" | if self . brand not in [ 'jp2 ' , 'jpx ' ] :
msg = ( "The file type brand was '{brand}'. " "It should be either 'jp2 ' or 'jpx '." )
msg = msg . format ( brand = self . brand )
if writing :
raise IOError ( msg )
else :
warnings . warn ( msg , UserWarning )
for item in self . compatibili... |
def encode_params ( params , ** kwargs ) :
"""Clean and JSON - encode a dict of parameters .""" | cleaned = clean_params ( params , ** kwargs )
return json . dumps ( cleaned ) |
def ru_strftime ( date , format = "%d.%m.%Y" , inflected_day = False , preposition = False ) :
"""Russian strftime , formats date with given format .
Value is a date ( supports datetime . date and datetime . datetime ) ,
parameter is a format ( string ) . For explainings about format ,
see documentation for o... | try :
res = dt . ru_strftime ( format , date , inflected = True , inflected_day = inflected_day , preposition = preposition )
except Exception as err : # because filter must die silently
try :
default_date = date . strftime ( format )
except Exception :
default_date = str ( date )
res = ... |
def to_subject_paths ( paths ) :
'''to _ subject _ paths ( paths ) accepts either a string that is a : - separated list of directories or a
list of directories and yields a list of all the existing directories .''' | if paths is None :
return [ ]
if pimms . is_str ( paths ) :
paths = paths . split ( ':' )
paths = [ os . path . expanduser ( p ) for p in paths ]
return [ p for p in paths if os . path . isdir ( p ) ] |
def before_func_accept_retry_state ( fn ) :
"""Wrap " before " function to accept " retry _ state " .""" | if not six . callable ( fn ) :
return fn
if func_takes_retry_state ( fn ) :
return fn
@ _utils . wraps ( fn )
def wrapped_before_func ( retry_state ) : # func , trial _ number , trial _ time _ taken
warn_about_non_retry_state_deprecation ( 'before' , fn , stacklevel = 4 )
return fn ( retry_state . fn , ... |
def plot_intrusion_curve ( self , fig = None ) :
r"""Plot the percolation curve as the invader volume or number fraction vs
the applied capillary pressure .""" | # Begin creating nicely formatted plot
x , y = self . get_intrusion_data ( )
if fig is None :
fig = plt . figure ( )
plt . semilogx ( x , y , 'ko-' )
plt . ylabel ( 'Invading Phase Saturation' )
plt . xlabel ( 'Capillary Pressure' )
plt . grid ( True )
return fig |
def pageSize ( self ) :
"""Returns the current page size for this wizard .
: return < QtCore . QSize >""" | # update the size based on the new size
page_size = self . fixedPageSize ( )
if page_size . isEmpty ( ) :
w = self . width ( ) - 80
h = self . height ( ) - 80
min_w = self . minimumPageSize ( ) . width ( )
min_h = self . minimumPageSize ( ) . height ( )
max_w = self . maximumPageSize ( ) . width ( )... |
def user_roles_exists ( name , roles , database , user = None , password = None , host = None , port = None , authdb = None ) :
'''Checks if a user of a MongoDB database has specified roles
CLI Examples :
. . code - block : : bash
salt ' * ' mongodb . user _ roles _ exists johndoe ' [ " readWrite " ] ' dbname... | try :
roles = _to_dict ( roles )
except Exception :
return 'Roles provided in wrong format'
users = user_list ( user , password , host , port , database , authdb )
if isinstance ( users , six . string_types ) :
return 'Failed to connect to mongo database'
for user in users :
if name == dict ( user ) . g... |
def get_vault_ids_by_authorization ( self , authorization_id ) :
"""Gets the list of ` ` Vault ` ` ` ` Ids ` ` mapped to an ` ` Authorization ` ` .
arg : authorization _ id ( osid . id . Id ) : ` ` Id ` ` of an
` ` Authorization ` `
return : ( osid . id . IdList ) - list of vault ` ` Ids ` `
raise : NotFoun... | # Implemented from template for
# osid . resource . ResourceBinSession . get _ bin _ ids _ by _ resource
mgr = self . _get_provider_manager ( 'AUTHORIZATION' , local = True )
lookup_session = mgr . get_authorization_lookup_session ( proxy = self . _proxy )
lookup_session . use_federated_vault_view ( )
authorization = l... |
def _viewdata_to_view ( self , p_data ) :
"""Converts a dictionary describing a view to an actual UIView instance .""" | sorter = Sorter ( p_data [ 'sortexpr' ] , p_data [ 'groupexpr' ] )
filters = [ ]
if not p_data [ 'show_all' ] :
filters . append ( DependencyFilter ( self . todolist ) )
filters . append ( RelevanceFilter ( ) )
filters . append ( HiddenTagFilter ( ) )
filters += get_filter_list ( p_data [ 'filterexpr' ] . s... |
def find_replace_string ( obj , find , replace ) :
"""Performs a string . replace ( ) on the input object .
Args :
obj ( object ) : The object to find / replace . It will be cast to ` ` str ` ` .
find ( str ) : The string to search for .
replace ( str ) : The string to replace with .
Returns :
str : The... | try :
strobj = str ( obj )
newStr = string . replace ( strobj , find , replace )
if newStr == strobj :
return obj
else :
return newStr
except :
line , filename , synerror = trace ( )
raise ArcRestHelperError ( { "function" : "find_replace_string" , "line" : line , "filename" : fi... |
def deselect_by_index ( self , index ) :
"""Deselect the option at the given index . This is done by examing the " index " attribute of an
element , and not merely by counting .
: Args :
- index - The option at this index will be deselected
throws NoSuchElementException If there is no option with specified ... | if not self . is_multiple :
raise NotImplementedError ( "You may only deselect options of a multi-select" )
for opt in self . options :
if opt . get_attribute ( "index" ) == str ( index ) :
self . _unsetSelected ( opt )
return
raise NoSuchElementException ( "Could not locate element with index %... |
def check_if_exists ( self ) :
"""Find an installed distribution that satisfies or conflicts
with this requirement , and set self . satisfied _ by or
self . conflicts _ with appropriately .""" | if self . req is None :
return False
try :
self . satisfied_by = pkg_resources . get_distribution ( self . req )
except pkg_resources . DistributionNotFound :
return False
except pkg_resources . VersionConflict :
self . conflicts_with = pkg_resources . get_distribution ( self . req . project_name )
retu... |
def get_extrapolated_conductivity ( temps , diffusivities , new_temp , structure , species ) :
"""Returns extrapolated mS / cm conductivity .
Args :
temps ( [ float ] ) : A sequence of temperatures . units : K
diffusivities ( [ float ] ) : A sequence of diffusivities ( e . g . ,
from DiffusionAnalyzer . dif... | return get_extrapolated_diffusivity ( temps , diffusivities , new_temp ) * get_conversion_factor ( structure , species , new_temp ) |
def append ( self , electrode_id ) :
'''Append the specified electrode to the route .
The route is not modified ( i . e . , electrode is not appended ) if
electrode is not connected to the last electrode in the existing route .
Parameters
electrode _ id : str
Electrode identifier .''' | do_append = False
if not self . electrode_ids :
do_append = True
elif self . device . shape_indexes . shape [ 0 ] > 0 :
source = self . electrode_ids [ - 1 ]
target = electrode_id
if not ( source == target ) :
source_id , target_id = self . device . shape_indexes [ [ source , target ] ]
... |
def up_threshold ( x , s , p ) :
"""function to decide if similarity is
below cutoff""" | if 1.0 * x / s >= p :
return True
elif stat . binom_test ( x , s , p ) > 0.01 :
return True
return False |
def _label_path_from_index ( self , index ) :
"""given image index , find out annotation path
Parameters :
index : int
index of a specific image
Returns :
full path of annotation file""" | label_file = os . path . join ( self . data_path , 'Annotations' , index + '.xml' )
assert os . path . exists ( label_file ) , 'Path does not exist: {}' . format ( label_file )
return label_file |
def parse_bamPEFragmentSizeDistribution ( self ) :
"""Find bamPEFragmentSize output . Supports the - - outRawFragmentLengths option""" | self . deeptools_bamPEFragmentSizeDistribution = dict ( )
for f in self . find_log_files ( 'deeptools/bamPEFragmentSizeDistribution' , filehandles = False ) :
parsed_data = self . parseBamPEFDistributionFile ( f )
for k , v in parsed_data . items ( ) :
if k in self . deeptools_bamPEFragmentSizeDistribut... |
def get_meta ( self , name , meta_key = None ) :
'''Get the ` ` content ` ` attribute of a meta tag ` ` name ` ` .
For example : :
head . get _ meta ( ' decription ' )
returns the ` ` content ` ` attribute of the meta tag with attribute
` ` name ` ` equal to ` ` description ` ` or ` ` None ` ` .
If a diff... | meta_key = meta_key or 'name'
for child in self . meta . _children :
if isinstance ( child , Html ) and child . attr ( meta_key ) == name :
return child . attr ( 'content' ) |
def value ( self ) :
"""Returns the current disk usage as a value between 0.0 and 1.0 by
dividing : attr : ` usage ` by 100.""" | # This slightly convoluted calculation is equivalent to df ' s " Use % " ;
# it calculates the percentage of FS usage as a proportion of the
# space available to * non - root users * . Technically this means it can
# exceed 100 % ( when FS is filled to the point that only root can write
# to it ) , hence the clamp .
vf... |
def submit_all ( self ) :
""": returns : an IterResult object""" | for args in self . task_args :
self . submit ( * args )
return self . get_results ( ) |
def to_json ( self ) :
"""Serializes all the data in this query range into json form .
Returns :
all the data in json - compatible map .""" | return { self . NAMESPACE_RANGE_PARAM : self . ns_range . to_json_object ( ) , self . BATCH_SIZE_PARAM : self . _batch_size } |
def gotResolverError ( self , failure , protocol , message , address ) :
'''Copied from twisted . names .
Removes logging the whole failure traceback .''' | if failure . check ( dns . DomainError , dns . AuthoritativeDomainError ) :
message . rCode = dns . ENAME
else :
message . rCode = dns . ESERVER
log . msg ( failure . getErrorMessage ( ) )
self . sendReply ( protocol , message , address )
if self . verbose :
log . msg ( "Lookup failed" ) |
def finish_async_rpc ( self , address , rpc_id , response ) :
"""Finish a previous asynchronous RPC .
This method should be called by a peripheral tile that previously
had an RPC called on it and chose to response asynchronously by
raising ` ` AsynchronousRPCResponse ` ` in the RPC handler itself .
The resp... | try :
self . emulator . finish_async_rpc ( address , rpc_id , response )
self . _track_change ( 'device.rpc_finished' , ( address , rpc_id , None , response , None ) , formatter = format_rpc )
except Exception as exc :
self . _track_change ( 'device.rpc_exception' , ( address , rpc_id , None , response , ex... |
def copy ( self , site_properties = None , sanitize = False ) :
"""Convenience method to get a copy of the structure , with options to add
site properties .
Args :
site _ properties ( dict ) : Properties to add or override . The
properties are specified in the same way as the constructor ,
i . e . , as a ... | props = self . site_properties
if site_properties :
props . update ( site_properties )
if not sanitize :
return self . __class__ ( self . _lattice , self . species_and_occu , self . frac_coords , charge = self . _charge , site_properties = props )
else :
reduced_latt = self . _lattice . get_lll_reduced_latt... |
def results ( self , query_name ) :
"""Gets a single saved query with a ' result ' object for a project from the
Keen IO API given a query name .
Read or Master key must be set .""" | url = "{0}/{1}/result" . format ( self . saved_query_url , query_name )
response = self . _get_json ( HTTPMethods . GET , url , self . _get_read_key ( ) )
return response |
def _set_node_hw_sync_state ( self , v , load = False ) :
"""Setter method for node _ hw _ sync _ state , mapped from YANG variable / brocade _ vcs _ rpc / show _ vcs / output / vcs _ nodes / vcs _ node _ info / node _ hw _ sync _ state ( node - hw - sync - state - type )
If this variable is read - only ( config ... | if hasattr ( v , "_utype" ) :
v = v . _utype ( v )
try :
t = YANGDynClass ( v , base = RestrictedClassType ( base_type = unicode , restriction_type = "dict_key" , restriction_arg = { u'node-in-sync' : { 'value' : 4 } , u'node-uninitialized' : { 'value' : 2 } , u'node-unknown' : { 'value' : 1 } , u'node-synchron... |
def QA_indicator_PBX ( DataFrame , N1 = 3 , N2 = 5 , N3 = 8 , N4 = 13 , N5 = 18 , N6 = 24 ) :
'瀑布线' | C = DataFrame [ 'close' ]
PBX1 = ( EMA ( C , N1 ) + EMA ( C , 2 * N1 ) + EMA ( C , 4 * N1 ) ) / 3
PBX2 = ( EMA ( C , N2 ) + EMA ( C , 2 * N2 ) + EMA ( C , 4 * N2 ) ) / 3
PBX3 = ( EMA ( C , N3 ) + EMA ( C , 2 * N3 ) + EMA ( C , 4 * N3 ) ) / 3
PBX4 = ( EMA ( C , N4 ) + EMA ( C , 2 * N4 ) + EMA ( C , 4 * N4 ) ) / 3
PBX5 =... |
def equalspairs ( X , Y ) :
"""Indices of elements in a sorted numpy array equal to those in another .
Given numpy array ` X ` and sorted numpy array ` Y ` , determine the indices in
Y equal to indices in X .
Returns ` [ A , B ] ` where ` A ` and ` B ` are numpy arrays of indices in ` X ` such
that : :
Y ... | T = Y . copy ( )
R = ( T [ 1 : ] != T [ : - 1 ] ) . nonzero ( ) [ 0 ]
R = np . append ( R , np . array ( [ len ( T ) - 1 ] ) )
M = R [ R . searchsorted ( range ( len ( T ) ) ) ]
D = T . searchsorted ( X )
T = np . append ( T , np . array ( [ 0 ] ) )
M = np . append ( M , np . array ( [ 0 ] ) )
A = ( T [ D ] == X ) * D
... |
def select_dataset ( self , elangle , quantity ) :
"""Selects the matching dataset and returns its path .
Parameters
elangle : str
Upper case ascii letter defining the elevation angle
quantity : str
Name of the quantity e . g . DBZH , VRAD , RHOHV . . .
Returns
dataset : str
Path of the matching dat... | elangle_path = None
try :
search_results = self . search ( 'elangle' , self . elangles [ elangle ] )
except KeyError :
return None
if search_results == [ ] :
print ( 'Elevation angle {} is not found from file' . format ( elangle ) )
print ( 'File contains elevation angles:{}' . format ( self . elangles ... |
def next_monday ( dt ) :
"""If holiday falls on Saturday , use following Monday instead ;
if holiday falls on Sunday , use Monday instead""" | if dt . weekday ( ) == 5 :
return dt + timedelta ( 2 )
elif dt . weekday ( ) == 6 :
return dt + timedelta ( 1 )
return dt |
def full_address ( anon , obj , field , val ) :
"""Generates a random full address , using newline characters between the lines .
Resembles a US address""" | return anon . faker . address ( field = field ) |
def to_XML ( self , xml_declaration = True , xmlns = True ) :
"""Dumps object fields to an XML - formatted string . The ' xml _ declaration '
switch enables printing of a leading standard XML line containing XML
version and encoding . The ' xmlns ' switch enables printing of qualified
XMLNS prefixes .
: par... | root_node = self . _to_DOM ( )
if xmlns :
xmlutils . annotate_with_XMLNS ( root_node , UVINDEX_XMLNS_PREFIX , UVINDEX_XMLNS_URL )
return xmlutils . DOM_node_to_XML ( root_node , xml_declaration ) |
def upgrade ( refresh = True ) :
'''Upgrade all of the packages to the latest available version .
Returns a dict containing the changes : :
{ ' < package > ' : { ' old ' : ' < old - version > ' ,
' new ' : ' < new - version > ' } }
CLI Example :
. . code - block : : bash
salt ' * ' pkgutil . upgrade''' | if salt . utils . data . is_true ( refresh ) :
refresh_db ( )
old = list_pkgs ( )
# Install or upgrade the package
# If package is already installed
cmd = '/opt/csw/bin/pkgutil -yu'
__salt__ [ 'cmd.run_all' ] ( cmd )
__context__ . pop ( 'pkg.list_pkgs' , None )
new = list_pkgs ( )
return salt . utils . data . compa... |
def _proxy ( self ) :
"""Generate an instance context for the instance , the context is capable of
performing various actions . All instance actions are proxied to the context
: returns : FaxContext for this FaxInstance
: rtype : twilio . rest . fax . v1 . fax . FaxContext""" | if self . _context is None :
self . _context = FaxContext ( self . _version , sid = self . _solution [ 'sid' ] , )
return self . _context |
def get_xray_daemon ( ) :
"""Parse X - Ray Daemon address environment variable .
If the environment variable is not set , raise an exception to signal that
we ' re unable to send data to X - Ray .""" | env_value = os . environ . get ( 'AWS_XRAY_DAEMON_ADDRESS' )
if env_value is None :
raise XRayDaemonNotFoundError ( )
xray_ip , xray_port = env_value . split ( ':' )
return XRayDaemon ( ip_address = xray_ip , port = int ( xray_port ) ) |
def from_mpl ( fig , savefig_kw = None ) :
"""Create a SVG figure from a ` ` matplotlib ` ` figure .
Parameters
fig : matplotlib . Figure instance
savefig _ kw : dict
keyword arguments to be passed to matplotlib ' s
` savefig `
Returns
SVGFigure
newly created : py : class : ` SVGFigure ` initialised... | fid = StringIO ( )
if savefig_kw is None :
savefig_kw = { }
try :
fig . savefig ( fid , format = 'svg' , ** savefig_kw )
except ValueError :
raise ( ValueError , "No matplotlib SVG backend" )
fid . seek ( 0 )
fig = fromstring ( fid . read ( ) )
# workaround mpl units bug
w , h = fig . get_size ( )
fig . set... |
def _geograins ( self ) :
"""Create a map geographic area terms to the geo grain GVid values""" | from geoid . civick import GVid
geo_grains = { }
for sl , cls in GVid . sl_map . items ( ) :
if '_' not in cls . level :
geo_grains [ self . stem ( cls . level ) ] = str ( cls . nullval ( ) . summarize ( ) )
return geo_grains |
def _add_results ( self , results , trial_id ) :
"""Add a list of results into db .
Args :
results ( list ) : A list of json results .
trial _ id ( str ) : Id of the trial .""" | for result in results :
self . logger . debug ( "Appending result: %s" % result )
result [ "trial_id" ] = trial_id
result_record = ResultRecord . from_json ( result )
result_record . save ( ) |
def dump_results ( self ) :
"""Save eigenvalue analysis reports
Returns
None""" | system = self . system
mu = self . mu
partfact = self . part_fact
if system . files . no_output :
return
text = [ ]
header = [ ]
rowname = [ ]
data = [ ]
neig = len ( mu )
mu_real = mu . real ( )
mu_imag = mu . imag ( )
npositive = sum ( 1 for x in mu_real if x > 0 )
nzero = sum ( 1 for x in mu_real if x == 0 )
nne... |
def get_userid_presence ( self , user_id : str ) -> UserPresence :
"""Return the current presence state of ` ` user _ id ` ` .""" | return self . _userid_to_presence . get ( user_id , UserPresence . UNKNOWN ) |
def check_var ( var , var_types : Union [ type , List [ type ] ] = None , var_name = None , enforce_not_none : bool = True , allowed_values : Set = None , min_value = None , min_strict : bool = False , max_value = None , max_strict : bool = False , min_len : int = None , min_len_strict : bool = False , max_len : int = ... | var_name = var_name or 'object'
if enforce_not_none and ( var is None ) : # enforce not none
raise MissingMandatoryParameterException ( 'Error, ' + var_name + '" is mandatory, it should be non-None' )
if not ( var is None ) and not ( var_types is None ) : # enforce type
if not isinstance ( var_types , list ) :
... |
def get_hosts_by_explosion ( self , hostgroups ) : # pylint : disable = access - member - before - definition
"""Get hosts of this group
: param hostgroups : Hostgroup object
: type hostgroups : alignak . objects . hostgroup . Hostgroups
: return : list of hosts of this group
: rtype : list""" | # First we tag the hg so it will not be explode
# if a son of it already call it
self . already_exploded = True
# Now the recursive part
# rec _ tag is set to False every HG we explode
# so if True here , it must be a loop in HG
# calls . . . not GOOD !
if self . rec_tag :
logger . error ( "[hostgroup::%s] got a lo... |
def build_cmd ( self , * args ) :
'''adb command array
For example :
build _ cmd ( " shell " , " uptime " ) will get
[ " adb " , " - s " , " xx . . " , " - P " , " 5037 " , " shell " , " uptime " ]''' | return [ self . adb ( ) , "-s" , self . serial ] + self . adb_host_port_options + list ( args ) |
def WriteFlowLogEntries ( self , entries ) :
"""Writes flow output plugin log entries for a given flow .""" | flow_ids = [ ( e . client_id , e . flow_id ) for e in entries ]
for f in flow_ids :
if f not in self . flows :
raise db . AtLeastOneUnknownFlowError ( flow_ids )
for e in entries :
dest = self . flow_log_entries . setdefault ( ( e . client_id , e . flow_id ) , [ ] )
to_write = e . Copy ( )
to_wr... |
def find_by_keyword ( self , keywords = "" , strict_match = False , book = - 1 ) :
self . fyi ( "find_by_keyword, ... book=%s" % book )
'''Search notes for a given keyword''' | self . fyi ( "nota.find_by_keyword() with keywords %s; book=%s" % ( keywords , book ) )
keywordsKnown = [ ]
if not strict_match :
keywords [ 0 ] = keywords [ 0 ] . lower ( )
for k in self . cur . execute ( "SELECT keyword FROM keyword;" ) . fetchall ( ) :
if strict_match :
keywordsKnown . extend ( k )
... |
def readGDF ( filename = "../data/RenatoFabbri06022014.gdf" ) :
"""Made to work with gdf files from my own network and friends and groups""" | with open ( filename , "r" ) as f :
data = f . read ( )
lines = data . split ( "\n" )
columns = lines [ 0 ] . split ( ">" ) [ 1 ] . split ( "," )
column_names = [ i . split ( " " ) [ 0 ] for i in columns ]
data_friends = { cn : [ ] for cn in column_names }
for line in lines [ 1 : ] :
if not line :
break... |
def ListLanguageIdentifiers ( self ) :
"""Lists the language identifiers .""" | table_view = views . ViewsFactory . GetTableView ( self . _views_format_type , column_names = [ 'Identifier' , 'Language' ] , title = 'Language identifiers' )
for language_id , value_list in sorted ( language_ids . LANGUAGE_IDENTIFIERS . items ( ) ) :
table_view . AddRow ( [ language_id , value_list [ 1 ] ] )
table... |
def save ( self ) :
"""Save / updates the user""" | import json
payload = { }
payload . update ( self . _store )
payload [ "user" ] = payload [ "username" ]
payload [ "passwd" ] = payload [ "password" ]
del ( payload [ "username" ] )
del ( payload [ "password" ] )
payload = json . dumps ( payload , default = str )
if not self . URL :
if "username" not in self . _sto... |
def RegisterKey ( cls , key , getter = None , setter = None , deleter = None , lister = None ) :
"""Register a new key mapping .
A key mapping is four functions , a getter , setter , deleter ,
and lister . The key may be either a string or a glob pattern .
The getter , deleted , and lister receive an MP4Tags ... | key = key . lower ( )
if getter is not None :
cls . Get [ key ] = getter
if setter is not None :
cls . Set [ key ] = setter
if deleter is not None :
cls . Delete [ key ] = deleter
if lister is not None :
cls . List [ key ] = lister |
def count_lines ( path , extensions = None , excluded_dirnames = None ) :
"""Return number of source code lines for all filenames in subdirectories
of * path * with names ending with * extensions *
Directory names * excluded _ dirnames * will be ignored""" | if extensions is None :
extensions = [ '.py' , '.pyw' , '.ipy' , '.enaml' , '.c' , '.h' , '.cpp' , '.hpp' , '.inc' , '.' , '.hh' , '.hxx' , '.cc' , '.cxx' , '.cl' , '.f' , '.for' , '.f77' , '.f90' , '.f95' , '.f2k' , '.f03' , '.f08' ]
if excluded_dirnames is None :
excluded_dirnames = [ 'build' , 'dist' , '.hg'... |
def normalize ( self ) :
"""Normalize this node and all rules contained within . The SLD model is
modified in place .""" | for i , rnode in enumerate ( self . _nodes ) :
rule = Rule ( self , i - 1 , descendant = False )
rule . normalize ( ) |
def from_header ( self , binary ) :
"""Generate a SpanContext object using the trace context header .
The value of enabled parsed from header is int . Need to convert to
bool .
: type binary : bytes
: param binary : Trace context header which was extracted from the
request headers .
: rtype : : class : ... | # If no binary provided , generate a new SpanContext
if binary is None :
return span_context_module . SpanContext ( from_header = False )
# If cannot parse , return a new SpanContext and ignore the context
# from binary .
try :
data = Header . _make ( struct . unpack ( BINARY_FORMAT , binary ) )
except struct .... |
def parse ( bin_payload , sender_script , recipient_address ) :
"""NOTE : the first three bytes will be missing""" | if len ( bin_payload ) < MIN_OP_LENGTHS [ 'namespace_reveal' ] :
raise AssertionError ( "Payload is too short to be a namespace reveal" )
off = 0
life = None
coeff = None
base = None
bucket_hex = None
buckets = [ ]
discount_hex = None
nonalpha_discount = None
no_vowel_discount = None
version = None
namespace_id = N... |
def convert_from_bytes ( pdf_file , dpi = 200 , output_folder = None , first_page = None , last_page = None , fmt = 'ppm' , thread_count = 1 , userpw = None , use_cropbox = False , strict = False , transparent = False , output_file = str ( uuid . uuid4 ( ) ) , poppler_path = None ) :
"""Description : Convert PDF to... | fh , temp_filename = tempfile . mkstemp ( )
try :
with open ( temp_filename , 'wb' ) as f :
f . write ( pdf_file )
f . flush ( )
return convert_from_path ( f . name , dpi = dpi , output_folder = output_folder , first_page = first_page , last_page = last_page , fmt = fmt , thread_count = thre... |
def get_dir ( self , obj ) :
"""Return the dirattr of obj formatted with the dirfomat specified in the constructor .
If the attr is None then ` ` None ` ` is returned not the string ` ` \' None \' ` ` .
: param obj : the fileinfo with information .
: type obj : : class : ` FileInfo `
: returns : the directo... | if self . _dirattr is None :
return
a = attrgetter ( self . _dirattr ) ( obj )
if a is None :
return
s = self . _dirformat % a
return s |
def _validate_install ( self ) :
'''a method to validate docker is installed''' | from subprocess import check_output , STDOUT
sys_command = 'docker --help'
try :
check_output ( sys_command , shell = True , stderr = STDOUT ) . decode ( 'utf-8' )
# call ( sys _ command , stdout = open ( devnull , ' wb ' ) )
except Exception as err :
raise Exception ( '"docker" not installed. GoTo: https:/... |
def reduceRight ( self , func ) :
"""The right - associative version of reduce , also known as ` foldr ` .""" | # foldr = lambda f , i : lambda s : reduce ( f , s , i )
x = self . obj [ : ]
x . reverse ( )
return self . _wrap ( functools . reduce ( func , x ) ) |
def time ( self , intervals = 1 , * args , _show_progress = True , _print = True , _collect_garbage = True , _quiet = True , ** kwargs ) :
"""Measures the execution time of : prop : _ callable for @ intervals
@ intervals : # int number of intervals to measure the execution time
of the function for
@ * args : ... | self . reset ( )
args = list ( args ) + list ( self . _callableargs [ 0 ] )
_kwargs = self . _callableargs [ 1 ]
_kwargs . update ( kwargs )
kwargs = _kwargs
if not _collect_garbage :
gc . disable ( )
# Garbage collection setting
gc . collect ( )
self . allocated_memory = 0
for x in self . progress ( intervals ... |
def launch_ipython ( argv = None , ipython_app = None ) :
"""Launch IPython from this interpreter with custom args if needed .
Chimera magic commands are also enabled automatically .""" | try :
if ipython_app is None :
from IPython . terminal . ipapp import TerminalIPythonApp as ipython_app
from traitlets . config import Config
except ImportError :
sys . exit ( "ERROR: IPython not installed in this environment. " "Try with `conda install ipython`" )
else : # launch _ new _ instance (... |
def get_chat_members_count ( chat_id , ** kwargs ) :
"""Use this method to get the number of members in a chat .
: param chat _ id : Unique identifier for the target chat or username of the target channel ( in the format @ channelusername )
: param kwargs : Args that get passed down to : class : ` TelegramBotRP... | # required args
params = dict ( chat_id = chat_id , )
return TelegramBotRPCRequest ( 'getChatMembersCount' , params = params , on_result = lambda result : result , ** kwargs ) |
def find_subscript_name ( subscript_dict , element ) :
"""Given a subscript dictionary , and a member of a subscript family ,
return the first key of which the member is within the value list .
If element is already a subscript name , return that
Parameters
subscript _ dict : dictionary
Follows the { ' su... | if element in subscript_dict . keys ( ) :
return element
for name , elements in subscript_dict . items ( ) :
if element in elements :
return name |
def call_with_search_field ( self , name , callback ) :
"""Calls a piece of code with the DOM element that corresponds to
a search field of the table .
If the callback causes a ` ` StaleElementReferenceException ` ` ,
this method will refetch the search fields and try
again . Consequently * * the callback s... | done = False
while not done :
def check ( * _ ) :
if name in self . _search_fields :
return True
# Force a refetch
self . _found_fields = None
return False
self . util . wait ( check )
field = self . _search_fields [ name ]
try :
callback ( field )
... |
def write_json_file ( path : str , contents : dict , mode : str = 'w' , retry_count : int = 3 ) -> typing . Tuple [ bool , typing . Union [ None , Exception ] ] :
"""Writes the specified dictionary to a file as a JSON - serialized string ,
with retry attempts if the write operation fails . This is useful to preve... | error = None
for i in range ( retry_count ) :
error = attempt_json_write ( path , contents , mode )
if error is None :
return True , None
time . sleep ( 0.2 )
return False , error |
def int_to_roman ( integer ) :
"""Convert an integer into a string of roman numbers .
. . code : python
reusables . int _ to _ roman ( 445)
# ' CDXLV '
: param integer :
: return : roman string""" | if not isinstance ( integer , int ) :
raise ValueError ( "Input integer must be of type int" )
output = [ ]
while integer > 0 :
for r , i in sorted ( _roman_dict . items ( ) , key = lambda x : x [ 1 ] , reverse = True ) :
while integer >= i :
output . append ( r )
integer -= i
re... |
def sql_flush ( self , style , tables , sequences , allow_cascade = False ) :
"""Truncate all existing tables in current keyspace .
: returns : an empty list""" | for table in tables :
qs = "TRUNCATE {}" . format ( table )
self . connection . connection . execute ( qs )
return [ ] |
def release_data ( request , package_name , version ) :
"""Retrieve metadata describing a specific package release .
Returns a dict with keys for :
name
version
stable _ version
author
author _ email
maintainer
maintainer _ email
home _ page
license
summary
description
keywords
platform ... | session = DBSession ( )
release = Release . by_version ( session , package_name , version )
if release :
result = { 'name' : release . package . name , 'version' : release . version , 'stable_version' : '' , 'author' : release . author . name , 'author_email' : release . author . email , 'home_page' : release . hom... |
def neighbors ( self , obj ) :
"""Return all neighbors adjacent to the given node .
@ type obj : node
@ param obj : Object identifier .
@ rtype : list
@ return : List of all node objects adjacent to the given node .""" | neighbors = set ( [ ] )
for e in self . node_links [ obj ] :
neighbors . update ( set ( self . edge_links [ e ] ) )
return list ( neighbors - set ( [ obj ] ) ) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.