code stringlengths 75 104k | docstring stringlengths 1 46.9k |
|---|---|
def printBlastRecord(record):
"""
Print a BLAST record.
@param record: A BioPython C{Bio.Blast.Record.Blast} instance.
"""
for key in sorted(record.__dict__.keys()):
if key not in ['alignments', 'descriptions', 'reference']:
print('%s: %r' % (key, record.__dict__[key]))
prin... | Print a BLAST record.
@param record: A BioPython C{Bio.Blast.Record.Blast} instance. |
def postpro_fisher(data, report=None):
"""
Performs fisher transform on everything in data.
If report variable is passed, this is added to the report.
"""
if not report:
report = {}
# Due to rounding errors
data[data < -0.99999999999999] = -1
data[data > 0.99999999999999] = 1
... | Performs fisher transform on everything in data.
If report variable is passed, this is added to the report. |
def scale_aphi(self, scale_parameter):
"""Scale the spectra by multiplying by linear scaling factor
:param scale_parameter: Linear scaling factor
"""
lg.info('Scaling a_phi by :: ' + str(scale_parameter))
try:
self.a_phi = self.a_phi * scale_parameter
except:... | Scale the spectra by multiplying by linear scaling factor
:param scale_parameter: Linear scaling factor |
def get_leaf_certificates(certs):
"""
Extracts the leaf certificates from a list of certificates. Leaf
certificates are ones whose subject does not appear as issuer among the
others.
"""
issuers = [cert.issuer.get_attributes_for_oid(x509.NameOID.COMMON_NAME)
for cert in certs]
... | Extracts the leaf certificates from a list of certificates. Leaf
certificates are ones whose subject does not appear as issuer among the
others. |
def missing(self, field, last=True):
'''
Numeric fields support specific handling for missing fields in a doc.
The missing value can be _last, _first, or a custom value
(that will be used for missing docs as the sort value).
missing('price')
> {"price" : {"missing": "_la... | Numeric fields support specific handling for missing fields in a doc.
The missing value can be _last, _first, or a custom value
(that will be used for missing docs as the sort value).
missing('price')
> {"price" : {"missing": "_last" } }
missing('price',False)
> {"price"... |
def n1ql_query(self, query, *args, **kwargs):
"""
Execute a N1QL query.
This method is mainly a wrapper around the :class:`~.N1QLQuery`
and :class:`~.N1QLRequest` objects, which contain the inputs
and outputs of the query.
Using an explicit :class:`~.N1QLQuery`::
... | Execute a N1QL query.
This method is mainly a wrapper around the :class:`~.N1QLQuery`
and :class:`~.N1QLRequest` objects, which contain the inputs
and outputs of the query.
Using an explicit :class:`~.N1QLQuery`::
query = N1QLQuery(
'SELECT airportname FROM... |
def set_assessments(self, assessment_ids=None):
"""Sets the assessments.
arg: assessmentIds (osid.id.Id): the assessment Ids
raise: INVALID_ARGUMENT - assessmentIds is invalid
raise: NullArgument - assessmentIds is null
raise: NoAccess - metadata.is_read_only() is true
... | Sets the assessments.
arg: assessmentIds (osid.id.Id): the assessment Ids
raise: INVALID_ARGUMENT - assessmentIds is invalid
raise: NullArgument - assessmentIds is null
raise: NoAccess - metadata.is_read_only() is true
compliance: mandatory - This method must be implemente... |
def make_class(name, attrs, bases=(object,), **attributes_arguments):
"""
A quick way to create a new class called *name* with *attrs*.
:param name: The name for the new class.
:type name: str
:param attrs: A list of names or a dictionary of mappings of names to
attributes.
If *at... | A quick way to create a new class called *name* with *attrs*.
:param name: The name for the new class.
:type name: str
:param attrs: A list of names or a dictionary of mappings of names to
attributes.
If *attrs* is a list or an ordered dict (:class:`dict` on Python 3.6+,
:class:`c... |
def del_edges(self, edges, *args, **kwargs):
"""
Removes edges from the graph. Takes optional arguments for
``DictGraph.del_edge``.
Arguments:
- edges(iterable) Sequence of edges to be removed from the
``DictGraph``.
"""
... | Removes edges from the graph. Takes optional arguments for
``DictGraph.del_edge``.
Arguments:
- edges(iterable) Sequence of edges to be removed from the
``DictGraph``. |
def preview(src_path):
''' Generates a preview of src_path in the requested format.
:returns: A list of preview paths, one for each page.
'''
previews = []
if sketch.is_sketchfile(src_path):
previews = sketch.preview(src_path)
if not previews:
previews = quicklook.preview(src_path)
previews = [... | Generates a preview of src_path in the requested format.
:returns: A list of preview paths, one for each page. |
def write_info_file(tensorboard_info):
"""Write TensorBoardInfo to the current process's info file.
This should be called by `main` once the server is ready. When the
server shuts down, `remove_info_file` should be called.
Args:
tensorboard_info: A valid `TensorBoardInfo` object.
Raises:
ValueError... | Write TensorBoardInfo to the current process's info file.
This should be called by `main` once the server is ready. When the
server shuts down, `remove_info_file` should be called.
Args:
tensorboard_info: A valid `TensorBoardInfo` object.
Raises:
ValueError: If any field on `info` is not of the corre... |
def fraction(self, value: float) -> 'Size':
"""Set the fraction of free space to use."""
raise_not_number(value)
self.maximum = '{}fr'.format(value)
return self | Set the fraction of free space to use. |
def get_app_prefs(app=None):
"""Returns a dictionary with preferences for a certain app/module.
:param str|unicode app:
:rtype: dict
"""
if app is None:
with Frame(stepback=1) as frame:
app = frame.f_globals['__name__'].split('.')[0]
prefs = get_prefs()
if app not i... | Returns a dictionary with preferences for a certain app/module.
:param str|unicode app:
:rtype: dict |
def _narrow_states(node, old_state, new_state, previously_widened_state): # pylint:disable=unused-argument,no-self-use
"""
Try to narrow the state!
:param old_state:
:param new_state:
:param previously_widened_state:
:returns: The narrowed state, and whether a narrowing... | Try to narrow the state!
:param old_state:
:param new_state:
:param previously_widened_state:
:returns: The narrowed state, and whether a narrowing has occurred |
def get_pastml_marginal_prob_file(method, model, column):
"""
Get the filename where the PastML marginal probabilities of node states are saved (will be None for non-marginal methods).
This file is inside the work_dir that can be specified for the pastml_pipeline method.
:param method: str, the ancestr... | Get the filename where the PastML marginal probabilities of node states are saved (will be None for non-marginal methods).
This file is inside the work_dir that can be specified for the pastml_pipeline method.
:param method: str, the ancestral state prediction method used by PASTML.
:param model: str, the ... |
def pad_positive_wrapper(fmtfct):
"""Ensure that numbers are aligned in table by appending a blank space to postive values if 'parenthesis' are
used to denote negative numbers"""
def check_and_append(*args, **kwargs):
result = fmtfct(*args, **kwargs)
if fmtfct.parens and not result.endswith... | Ensure that numbers are aligned in table by appending a blank space to postive values if 'parenthesis' are
used to denote negative numbers |
def poly_energies(samples_like, poly):
"""Calculates energy of samples from a higher order polynomial.
Args:
sample (samples_like):
A collection of raw samples. `samples_like` is an extension of
NumPy's array_like structure. See :func:`.as_samples`.
poly (dict):
... | Calculates energy of samples from a higher order polynomial.
Args:
sample (samples_like):
A collection of raw samples. `samples_like` is an extension of
NumPy's array_like structure. See :func:`.as_samples`.
poly (dict):
Polynomial as a dict of form {term: bias,... |
def register(email):
'''
Register a new user account
CLI Example:
.. code-block:: bash
salt-run venafi.register email@example.com
'''
data = __utils__['http.query'](
'{0}/useraccounts'.format(_base_url()),
method='POST',
data=salt.utils.json.dumps({
... | Register a new user account
CLI Example:
.. code-block:: bash
salt-run venafi.register email@example.com |
def _check_location_part(cls, val, regexp):
"""Deprecated. See CourseLocator._check_location_part"""
cls._deprecation_warning()
return CourseLocator._check_location_part(val, regexp) | Deprecated. See CourseLocator._check_location_part |
def choose_form(self, number=None, xpath=None, name=None, **kwargs):
"""
Set the default form.
:param number: number of form (starting from zero)
:param id: value of "id" attribute
:param name: value of "name" attribute
:param xpath: XPath query
:raises: :class:`... | Set the default form.
:param number: number of form (starting from zero)
:param id: value of "id" attribute
:param name: value of "name" attribute
:param xpath: XPath query
:raises: :class:`DataNotFound` if form not found
:raises: :class:`GrabMisuseError`
if ... |
def authorize(*args, **kwargs):
"""View for rendering authorization request."""
if request.method == 'GET':
client = Client.query.filter_by(
client_id=kwargs.get('client_id')
).first()
if not client:
abort(404)
scopes = current_oauth2server.scopes
... | View for rendering authorization request. |
def validate_tzinfo(dummy, value):
"""Validate the tzinfo option
"""
if value is not None and not isinstance(value, datetime.tzinfo):
raise TypeError("%s must be an instance of datetime.tzinfo" % value)
return value | Validate the tzinfo option |
def cli():
""" Command line interface """
ch = logging.StreamHandler()
ch.setFormatter(logging.Formatter(
'%(asctime)s.%(msecs)03d %(levelname)s: %(message)s',
datefmt="%Y-%m-%d %H:%M:%S"
))
logger.addHandler(ch)
import argparse
parser = argparse.ArgumentParser(description="... | Command line interface |
def _refresh_authentication_token(self):
"""
POST to ArcGIS requesting a new token.
"""
if self.retry == self._MAX_RETRIES:
raise GeocoderAuthenticationFailure(
'Too many retries for auth: %s' % self.retry
)
token_request_arguments = {
... | POST to ArcGIS requesting a new token. |
def Reload(self):
"""Call `Reload` on every `EventAccumulator`."""
logger.info('Beginning EventMultiplexer.Reload()')
self._reload_called = True
# Build a list so we're safe even if the list of accumulators is modified
# even while we're reloading.
with self._accumulators_mutex:
items = li... | Call `Reload` on every `EventAccumulator`. |
def update(self, params):
"""Update the dev_info data from a dictionary.
Only updates if it already exists in the device.
"""
dev_info = self.json_state.get('deviceInfo')
dev_info.update({k: params[k] for k in params if dev_info.get(k)}) | Update the dev_info data from a dictionary.
Only updates if it already exists in the device. |
def query_by_grader(self, grader_id, end_time=None, start_time=None):
"""
Query by grader.
List grade change events for a given grader.
"""
path = {}
data = {}
params = {}
# REQUIRED - PATH - grader_id
"""ID"""
path["grader_id... | Query by grader.
List grade change events for a given grader. |
def visit_module(self, node):
"""
A interface will be called when visiting a module.
@param node: node of current module
"""
if not node.file_stream:
# Failed to open the module
return
isFirstLineOfComment = True
isDocString = False
... | A interface will be called when visiting a module.
@param node: node of current module |
def reporter(metadata, analysistype, reportpath):
"""
Create the core genome report
:param metadata: type LIST: List of metadata objects
:param analysistype: type STR: Current analysis type
:param reportpath: type STR: Absolute path to folder in which the reports are to be create... | Create the core genome report
:param metadata: type LIST: List of metadata objects
:param analysistype: type STR: Current analysis type
:param reportpath: type STR: Absolute path to folder in which the reports are to be created
:return: |
def create(gandi):
""" Create a new contact.
"""
contact = {}
for field, label, checks in FIELDS:
ask_field(gandi, contact, field, label, checks)
default_pwd = randomstring(16)
contact['password'] = click.prompt('Please enter your password',
hide_... | Create a new contact. |
def create_sparse_mapping(id_array, unique_ids=None):
"""
Will create a scipy.sparse compressed-sparse-row matrix that maps
each row represented by an element in id_array to the corresponding
value of the unique ids in id_array.
Parameters
----------
id_array : 1D ndarray of ints.
E... | Will create a scipy.sparse compressed-sparse-row matrix that maps
each row represented by an element in id_array to the corresponding
value of the unique ids in id_array.
Parameters
----------
id_array : 1D ndarray of ints.
Each element should represent some id related to the corresponding ... |
def main(argv=None):
""" Script execution.
The project repo will be cloned to a temporary directory, and the desired
branch, tag, or commit will be checked out. Then, the application will be
installed into a self-contained virtualenv environment.
"""
@contextmanager
def tmpdir():
"... | Script execution.
The project repo will be cloned to a temporary directory, and the desired
branch, tag, or commit will be checked out. Then, the application will be
installed into a self-contained virtualenv environment. |
def list_projects(self, dataset_name):
"""
Lists a set of projects related to a dataset.
Arguments:
dataset_name (str): Dataset name to search projects for
Returns:
dict: Projects found based on dataset query
"""
url = self.url() + "/nd/resource/... | Lists a set of projects related to a dataset.
Arguments:
dataset_name (str): Dataset name to search projects for
Returns:
dict: Projects found based on dataset query |
def chunk(iterable, size):
"""
chunk('ABCDEFG', 3) --> ABC DEF G
"""
# TODO: only used in gui.mainwindow(deprecated)
iterator = iter(iterable)
while size:
result = []
try:
for i in range(size):
elem = next(iterator)
result.append(elem)
... | chunk('ABCDEFG', 3) --> ABC DEF G |
def _validate_relations(relations, services, add_error):
"""Validate relations, ensuring that the endpoints exist.
Receive the relations and services bundle sections.
Use the given add_error callable to register validation error.
"""
if not relations:
return
for relation in relations:
... | Validate relations, ensuring that the endpoints exist.
Receive the relations and services bundle sections.
Use the given add_error callable to register validation error. |
def sina_xml_to_url_list(xml_data):
"""str->list
Convert XML to URL List.
From Biligrab.
"""
rawurl = []
dom = parseString(xml_data)
for node in dom.getElementsByTagName('durl'):
url = node.getElementsByTagName('url')[0]
rawurl.append(url.childNodes[0].data)
return rawurl | str->list
Convert XML to URL List.
From Biligrab. |
def find_carbon_sources(model):
"""
Find all active carbon source reactions.
Parameters
----------
model : Model
A genome-scale metabolic model.
Returns
-------
list
The medium reactions with carbon input flux.
"""
try:
model.slim_optimize(error_value=N... | Find all active carbon source reactions.
Parameters
----------
model : Model
A genome-scale metabolic model.
Returns
-------
list
The medium reactions with carbon input flux. |
def set_property(self, key, value):
"""
Update only one property in the dict
"""
self.properties[key] = value
self.sync_properties() | Update only one property in the dict |
def canonical_url(app, pagename, templatename, context, doctree):
"""Build the canonical URL for a page. Appends the path for the
page to the base URL specified by the
``html_context["canonical_url"]`` config and stores it in
``html_context["page_canonical_url"]``.
"""
base = context.get("canoni... | Build the canonical URL for a page. Appends the path for the
page to the base URL specified by the
``html_context["canonical_url"]`` config and stores it in
``html_context["page_canonical_url"]``. |
def download(self, path, retry=5, timeout=10,
chunk_size=PartSize.DOWNLOAD_MINIMUM_PART_SIZE, wait=True,
overwrite=False):
"""
Downloads the file and returns a download handle.
Download will not start until .start() method is invoked.
:param path: Full p... | Downloads the file and returns a download handle.
Download will not start until .start() method is invoked.
:param path: Full path to the new file.
:param retry: Number of retries if error occurs during download.
:param timeout: Timeout for http requests.
:param chunk_size: Ch... |
def bsp_resize(node: tcod.bsp.BSP, x: int, y: int, w: int, h: int) -> None:
"""
.. deprecated:: 2.0
Assign directly to :any:`BSP` attributes instead.
"""
node.x = x
node.y = y
node.width = w
node.height = h | .. deprecated:: 2.0
Assign directly to :any:`BSP` attributes instead. |
def send_error(self, code, message=None):
"""Send and log an error reply.
Arguments are the error code, and a detailed message.
The detailed message defaults to the short entry matching the
response code.
This sends an error response (so it must be called before any
out... | Send and log an error reply.
Arguments are the error code, and a detailed message.
The detailed message defaults to the short entry matching the
response code.
This sends an error response (so it must be called before any
output has been generated), logs the error, and finally ... |
def get_insertion(cls) -> str:
"""Return the complete string to be inserted into the string of the
template file.
>>> from hydpy.auxs.xmltools import XSDWriter
>>> print(XSDWriter.get_insertion()) # doctest: +ELLIPSIS
<element name="arma_v1"
substit... | Return the complete string to be inserted into the string of the
template file.
>>> from hydpy.auxs.xmltools import XSDWriter
>>> print(XSDWriter.get_insertion()) # doctest: +ELLIPSIS
<element name="arma_v1"
substitutionGroup="hpcb:sequenceGroup"
... |
def set_run_on_node_mask(nodemask):
"""
Runs the current thread and its children only on nodes specified in nodemask.
They will not migrate to CPUs of other nodes until the node affinity is
reset with a new call to L{set_run_on_node_mask}.
@param nodemask: node mask
@type nodemask: C{set}
... | Runs the current thread and its children only on nodes specified in nodemask.
They will not migrate to CPUs of other nodes until the node affinity is
reset with a new call to L{set_run_on_node_mask}.
@param nodemask: node mask
@type nodemask: C{set} |
def get(self, resource_id=None):
"""Return an HTTP response object resulting from an HTTP GET call.
If *resource_id* is provided, return just the single resource.
Otherwise, return the full collection.
:param resource_id: The value of the resource's primary key
"""
if r... | Return an HTTP response object resulting from an HTTP GET call.
If *resource_id* is provided, return just the single resource.
Otherwise, return the full collection.
:param resource_id: The value of the resource's primary key |
def mangleIR(data, ignore_errors=False):
"""Mangle a raw Kira data packet into shorthand"""
try:
# Packet mangling algorithm inspired by Rex Becket's kirarx vera plugin
# Determine a median value for the timing packets and categorize each
# timing as longer or shorter than that. This wil... | Mangle a raw Kira data packet into shorthand |
def initialize_path(self, path_num=None):
"""
initialize consumer for next path
"""
self.state = copy(self.initial_state)
return self.state | initialize consumer for next path |
def create(obj: PersistedObject, obj_type: Type[Any], arg_name: str):
"""
Helper method provided because we actually can't put that in the constructor, it creates a bug in Nose tests
https://github.com/nose-devs/nose/issues/725
:param obj:
:param obj_type:
:param arg_nam... | Helper method provided because we actually can't put that in the constructor, it creates a bug in Nose tests
https://github.com/nose-devs/nose/issues/725
:param obj:
:param obj_type:
:param arg_name:
:return: |
def write(
contents: str,
path: Union[str, pathlib.Path],
verbose: bool = False,
logger_func=None,
) -> bool:
"""
Writes ``contents`` to ``path``.
Checks if ``path`` already exists and only write out new contents if the
old contents do not match.
Creates any intermediate missing di... | Writes ``contents`` to ``path``.
Checks if ``path`` already exists and only write out new contents if the
old contents do not match.
Creates any intermediate missing directories.
:param contents: the file contents to write
:param path: the path to write to
:param verbose: whether to print out... |
def init_gl(self):
"""
Perform the magic incantations to create an
OpenGL scene using pyglet.
"""
# default background color is white-ish
background = [.99, .99, .99, 1.0]
# if user passed a background color use it
if 'background' in self.kwargs:
... | Perform the magic incantations to create an
OpenGL scene using pyglet. |
def doubleprox_dc(x, y, f, phi, g, K, niter, gamma, mu, callback=None):
r"""Double-proxmial gradient d.c. algorithm of Banert and Bot.
This algorithm solves a problem of the form ::
min_x f(x) + phi(x) - g(Kx).
Parameters
----------
x : `LinearSpaceElement`
Initial primal guess, u... | r"""Double-proxmial gradient d.c. algorithm of Banert and Bot.
This algorithm solves a problem of the form ::
min_x f(x) + phi(x) - g(Kx).
Parameters
----------
x : `LinearSpaceElement`
Initial primal guess, updated in-place.
y : `LinearSpaceElement`
Initial dual guess, up... |
def write_to(self, group, append=False):
"""Writes the properties to a `group`, or append it"""
data = self.data
if append is True:
try:
# concatenate original and new properties in a single list
original = read_properties(group)
data =... | Writes the properties to a `group`, or append it |
def horizontal_headers(self, value):
"""
Setter for **self.__horizontal_headers** attribute.
:param value: Attribute value.
:type value: OrderedDict
"""
if value is not None:
assert type(value) is OrderedDict, "'{0}' attribute: '{1}' type is not 'OrderedDict... | Setter for **self.__horizontal_headers** attribute.
:param value: Attribute value.
:type value: OrderedDict |
def getLocalTime(date, time, *args, **kwargs):
"""
Get the time in the local timezone from date and time
"""
if time is not None:
return getLocalDateAndTime(date, time, *args, **kwargs)[1] | Get the time in the local timezone from date and time |
def activate(self):
"""Activate a Vera scene.
This will call the Vera api to activate a scene.
"""
payload = {
'id': 'lu_action',
'action': 'RunScene',
'serviceId': self.scene_service
}
result = self.vera_request(**payload)
log... | Activate a Vera scene.
This will call the Vera api to activate a scene. |
def start(self, name):
'''
End the current behaviour and run a named behaviour.
:param name: the name of the behaviour to run
:type name: str
'''
d = self.boatd.post({'active': name}, endpoint='/behaviours')
current = d.get('active')
if current is not Non... | End the current behaviour and run a named behaviour.
:param name: the name of the behaviour to run
:type name: str |
def getCSVReader(data, reader_type=csv.DictReader):
"""Take a Rave CSV output ending with a line with just EOF on it and return a DictReader"""
f = StringIO(data[:-4]) # Remove \nEOF
return reader_type(f) | Take a Rave CSV output ending with a line with just EOF on it and return a DictReader |
def frames(self, most_recent=False):
"""Retrieve a new frame from the PhoXi and convert it to a ColorImage,
a DepthImage, and an IrImage.
Parameters
----------
most_recent: bool
If true, the OpenCV buffer is emptied for the webcam before reading the most recent frame... | Retrieve a new frame from the PhoXi and convert it to a ColorImage,
a DepthImage, and an IrImage.
Parameters
----------
most_recent: bool
If true, the OpenCV buffer is emptied for the webcam before reading the most recent frame.
Returns
-------
:obj:... |
def add(self, si):
'''puts `si` into the currently open chunk, which it creates if
necessary. If this item causes the chunk to cross chunk_max,
then the chunk closed after adding.
'''
if self.o_chunk is None:
if os.path.exists(self.t_path):
os.remove... | puts `si` into the currently open chunk, which it creates if
necessary. If this item causes the chunk to cross chunk_max,
then the chunk closed after adding. |
def incr(self, key, value):
"""
Increment a key, if it exists, returns it's actual value, if it don't, return 0.
:param key: Key's name
:type key: six.string_types
:param value: Number to be incremented
:type value: int
:return: Actual value of the key on server
... | Increment a key, if it exists, returns it's actual value, if it don't, return 0.
:param key: Key's name
:type key: six.string_types
:param value: Number to be incremented
:type value: int
:return: Actual value of the key on server
:rtype: int |
def all_time(self):
"""
Access the all_time
:returns: twilio.rest.api.v2010.account.usage.record.all_time.AllTimeList
:rtype: twilio.rest.api.v2010.account.usage.record.all_time.AllTimeList
"""
if self._all_time is None:
self._all_time = AllTimeList(self._ver... | Access the all_time
:returns: twilio.rest.api.v2010.account.usage.record.all_time.AllTimeList
:rtype: twilio.rest.api.v2010.account.usage.record.all_time.AllTimeList |
def add_to_pythonpath(self, path):
"""Add path to project's PYTHONPATH
Return True if path was added, False if it was already there"""
pathlist = self.get_pythonpath()
if path in pathlist:
return False
else:
pathlist.insert(0, path)
sel... | Add path to project's PYTHONPATH
Return True if path was added, False if it was already there |
def extract_ast_species(ast):
"""Extract species from ast.species set of tuples (id, label)"""
species_id = "None"
species_label = "None"
species = [
(species_id, species_label) for (species_id, species_label) in ast.species if species_id
]
if len(species) == 1:
(species_id, sp... | Extract species from ast.species set of tuples (id, label) |
def swapColors(self):
"""
Swaps the current :py:class:`Color` with the secondary :py:class:`Color`.
:rtype: Nothing.
"""
rgba = self.color.get_0_255()
self.color = self.secondColor
self.secondColor = Color(rgba, '0-255') | Swaps the current :py:class:`Color` with the secondary :py:class:`Color`.
:rtype: Nothing. |
def all_dataset_ids(self, reader_name=None, composites=False):
"""Get names of all datasets from loaded readers or `reader_name` if
specified..
:return: list of all dataset names
"""
try:
if reader_name:
readers = [self.readers[reader_name]]
... | Get names of all datasets from loaded readers or `reader_name` if
specified..
:return: list of all dataset names |
def init(deb1, deb2=False):
"""Initialize DEBUG and DEBUGALL.
Allows other modules to set DEBUG and DEBUGALL, so their
call to dprint or dprintx generate output.
Args:
deb1 (bool): value of DEBUG to set
deb2 (bool): optional - value of DEBUGALL to set,
defaults to ... | Initialize DEBUG and DEBUGALL.
Allows other modules to set DEBUG and DEBUGALL, so their
call to dprint or dprintx generate output.
Args:
deb1 (bool): value of DEBUG to set
deb2 (bool): optional - value of DEBUGALL to set,
defaults to False. |
def is_result_edition_allowed(self, analysis_brain):
"""Checks if the edition of the result field is allowed
:param analysis_brain: Brain that represents an analysis
:return: True if the user can edit the result field, otherwise False
"""
# Always check general edition first
... | Checks if the edition of the result field is allowed
:param analysis_brain: Brain that represents an analysis
:return: True if the user can edit the result field, otherwise False |
def update_option_set_by_id(cls, option_set_id, option_set, **kwargs):
"""Update OptionSet
Update attributes of OptionSet
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async=True
>>> thread = api.update_option_set_by_i... | Update OptionSet
Update attributes of OptionSet
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async=True
>>> thread = api.update_option_set_by_id(option_set_id, option_set, async=True)
>>> result = thread.get()
... |
def My_TreeTable(self, table, heads, heads2=None):
''' Define and display a table
in which the values in first column form one or more trees.
'''
self.Define_TreeTable(heads, heads2)
self.Display_TreeTable(table) | Define and display a table
in which the values in first column form one or more trees. |
def _set_rules(self, rules: dict, overwrite=True):
"""Created a new Rules object based on the provided dict of rules."""
if not isinstance(rules, dict):
raise TypeError('rules must be an instance of dict or Rules,'
'got %r instead' % type(rules))
if over... | Created a new Rules object based on the provided dict of rules. |
def start(self, timeout=None):
"""Start the client in a new thread.
Parameters
----------
timeout : float in seconds
Seconds to wait for client thread to start. Do not specify a
timeout if start() is being called from the same ioloop that this
client ... | Start the client in a new thread.
Parameters
----------
timeout : float in seconds
Seconds to wait for client thread to start. Do not specify a
timeout if start() is being called from the same ioloop that this
client will be installed on, since it will block ... |
def p_expression_land(self, p):
'expression : expression LAND expression'
p[0] = Land(p[1], p[3], lineno=p.lineno(1))
p.set_lineno(0, p.lineno(1)) | expression : expression LAND expression |
def recognized_release(self):
"""
Check if this Release value is something we can parse.
:rtype: bool
"""
_, _, rest = self.get_release_parts()
# If "rest" is not a well-known value here, then this package is
# using a Release value pattern we cannot recognize.
... | Check if this Release value is something we can parse.
:rtype: bool |
def __set_authoring_nodes(self, source, target):
"""
Sets given editor authoring nodes.
:param source: Source file.
:type source: unicode
:param target: Target file.
:type target: unicode
"""
editor = self.__script_editor.get_editor(source)
edito... | Sets given editor authoring nodes.
:param source: Source file.
:type source: unicode
:param target: Target file.
:type target: unicode |
def getWindowByPID(self, pid, order=0):
""" Returns a handle for the first window that matches the provided PID """
if pid <= 0:
return None
EnumWindowsProc = ctypes.WINFUNCTYPE(
ctypes.c_bool,
ctypes.POINTER(ctypes.c_int),
ctypes.py_object)
... | Returns a handle for the first window that matches the provided PID |
def get(self, url, headers=None, kwargs=None):
"""Make a GET request.
To make a GET request pass, ``url``
:param url: ``str``
:param headers: ``dict``
:param kwargs: ``dict``
"""
return self._request(
method='get',
url=url,
he... | Make a GET request.
To make a GET request pass, ``url``
:param url: ``str``
:param headers: ``dict``
:param kwargs: ``dict`` |
def acl_remove_draft(self, id_vlan, type_acl):
"""
Remove Acl draft by type
:param id_vlan: Identity of Vlan
:param type_acl: Acl type v4 or v6
:return: None
:raise VlanDoesNotExistException: Vlan Does Not Exist.
:raise InvalidIdVlanExce... | Remove Acl draft by type
:param id_vlan: Identity of Vlan
:param type_acl: Acl type v4 or v6
:return: None
:raise VlanDoesNotExistException: Vlan Does Not Exist.
:raise InvalidIdVlanException: Invalid id for Vlan.
:raise NetworkAPIException: Fai... |
def parse_port_pin(name_str):
"""Parses a string and returns a (port, gpio_bit) tuple."""
if len(name_str) < 3:
raise ValueError("Expecting pin name to be at least 3 characters")
if name_str[:2] != 'GP':
raise ValueError("Expecting pin name to start with GP")
if not name_str[2:].isdigit(... | Parses a string and returns a (port, gpio_bit) tuple. |
def get_member_class(resource):
"""
Returns the registered member class for the given resource.
:param resource: registered resource
:type resource: class implementing or instance providing or subclass of
a registered resource interface.
"""
reg = get_current_registry()
if IInterfac... | Returns the registered member class for the given resource.
:param resource: registered resource
:type resource: class implementing or instance providing or subclass of
a registered resource interface. |
def position(self):
"""
Returns the current position of the motor in pulses of the rotary
encoder. When the motor rotates clockwise, the position will increase.
Likewise, rotating counter-clockwise causes the position to decrease.
Writing will set the position to that value.
... | Returns the current position of the motor in pulses of the rotary
encoder. When the motor rotates clockwise, the position will increase.
Likewise, rotating counter-clockwise causes the position to decrease.
Writing will set the position to that value. |
def merge_request(self, request_id):
"""
Merge a pull request.
:param request_id: the id of the request
:return:
"""
request_url = "{}pull-request/{}/merge".format(self.create_basic_url(),
request_id)
return_... | Merge a pull request.
:param request_id: the id of the request
:return: |
def info(environment, opts):
"""Display information about environment and running containers
Usage:
datacats info [-qr] [ENVIRONMENT]
Options:
-q --quiet Echo only the web URL or nothing if not running
ENVIRONMENT may be an environment name or a path to an environment directory.
Default: '.'
"""
... | Display information about environment and running containers
Usage:
datacats info [-qr] [ENVIRONMENT]
Options:
-q --quiet Echo only the web URL or nothing if not running
ENVIRONMENT may be an environment name or a path to an environment directory.
Default: '.' |
def get_steps_branch_len(self, length):
"""Get, how much steps will needed for a given branch length.
Returns:
float: The age the tree must achieve to reach the given branch length.
"""
return log(length/self.length, min(self.branches[0][0])) | Get, how much steps will needed for a given branch length.
Returns:
float: The age the tree must achieve to reach the given branch length. |
def list_archive(archive, verbosity=1, program=None, interactive=True):
"""List given archive."""
# Set default verbosity to 1 since the listing output should be visible.
util.check_existing_filename(archive)
if verbosity >= 0:
util.log_info("Listing %s ..." % archive)
return _handle_archive... | List given archive. |
def chebyshev_neg(h1, h2): # 12 us @array, 36 us @list \w 100 bins
r"""
Chebyshev negative distance.
Also Tchebychev distance, Minimum or :math:`L_{-\infty}` metric; equal to Minowski
distance with :math:`p=-\infty`. For the case of :math:`p=+\infty`, use `chebyshev`.
The Chebyshev distanc... | r"""
Chebyshev negative distance.
Also Tchebychev distance, Minimum or :math:`L_{-\infty}` metric; equal to Minowski
distance with :math:`p=-\infty`. For the case of :math:`p=+\infty`, use `chebyshev`.
The Chebyshev distance between two histograms :math:`H` and :math:`H'` of size :math:`m` is
... |
def get_node(self, name):
r"""
Get a tree node structure.
The structure is a dictionary with the following keys:
* **parent** (*NodeName*) Parent node name, :code:`''` if the
node is the root node
* **children** (*list of NodeName*) Children node names, an
... | r"""
Get a tree node structure.
The structure is a dictionary with the following keys:
* **parent** (*NodeName*) Parent node name, :code:`''` if the
node is the root node
* **children** (*list of NodeName*) Children node names, an
empty list if node is a leaf
... |
def generate_transit_lightcurve(
times,
mags=None,
errs=None,
paramdists={'transitperiod':sps.uniform(loc=0.1,scale=49.9),
'transitdepth':sps.uniform(loc=1.0e-4,scale=2.0e-2),
'transitduration':sps.uniform(loc=0.01,scale=0.29)},
magsareflux... | This generates fake planet transit light curves.
Parameters
----------
times : np.array
This is an array of time values that will be used as the time base.
mags,errs : np.array
These arrays will have the model added to them. If either is
None, `np.full_like(times, 0.0)` will u... |
def _force(self,z,t=0.):
"""
NAME:
_force
PURPOSE:
evaluate the force
INPUT:
z
t
OUTPUT:
F_z(z,t;R)
HISTORY:
2010-07-13 - Written - Bovy (NYU)
"""
return self._Pot.zforce(self._R,z,phi=self._... | NAME:
_force
PURPOSE:
evaluate the force
INPUT:
z
t
OUTPUT:
F_z(z,t;R)
HISTORY:
2010-07-13 - Written - Bovy (NYU) |
def _generate_docstring(self, doc_type, quote):
"""Generate docstring."""
docstring = None
self.quote3 = quote * 3
if quote == '"':
self.quote3_other = "'''"
else:
self.quote3_other = '"""'
result = self.get_function_definition_from_bel... | Generate docstring. |
def substitute_vars(template, replacements):
"""Replace certain keys with respective values in a string.
@param template: the string in which replacements should be made
@param replacements: a dict or a list of pairs of keys and values
"""
result = template
for (key, value) in replacements:
... | Replace certain keys with respective values in a string.
@param template: the string in which replacements should be made
@param replacements: a dict or a list of pairs of keys and values |
def fetch_live(self, formatter=TableFormat):
"""
Fetch a live stream query. This is the equivalent of selecting
the "Play" option for monitoring fields within the SMC UI. Data will
be streamed back in real time.
:param formatter: Formatter type for data representation. A... | Fetch a live stream query. This is the equivalent of selecting
the "Play" option for monitoring fields within the SMC UI. Data will
be streamed back in real time.
:param formatter: Formatter type for data representation. Any type
in :py:mod:`smc_monitoring.models.formatters`... |
def search_datasets(self, search_phrase, limit=None):
""" Search for datasets. """
return self.backend.dataset_index.search(search_phrase, limit=limit) | Search for datasets. |
def generate(env):
"""Add Builders and construction variables for WiX to an Environment."""
if not exists(env):
return
env['WIXCANDLEFLAGS'] = ['-nologo']
env['WIXCANDLEINCLUDE'] = []
env['WIXCANDLECOM'] = '$WIXCANDLE $WIXCANDLEFLAGS -I $WIXCANDLEINCLUDE -o ${TARGET} ${SOURCE}'
env['WIXL... | Add Builders and construction variables for WiX to an Environment. |
def agg_iter(self, lower_limit=None, upper_limit=None):
"""Aggregate and return dictionary to be indexed in ES."""
lower_limit = lower_limit or self.get_bookmark().isoformat()
upper_limit = upper_limit or (
datetime.datetime.utcnow().replace(microsecond=0).isoformat())
aggreg... | Aggregate and return dictionary to be indexed in ES. |
def next_block(self):
"""
This could probably be improved; at the moment it starts by trying to overshoot the
desired compressed block size, then it reduces the input bytes one by one until it
has met the required block size
"""
assert self.pos <= self.input_len
... | This could probably be improved; at the moment it starts by trying to overshoot the
desired compressed block size, then it reduces the input bytes one by one until it
has met the required block size |
def F_to_K(self, F, method='doubling'):
"""
Compute agent 2's best cost-minimizing response K, given F.
Parameters
----------
F : array_like(float, ndim=2)
A k x n array
method : str, optional(default='doubling')
Solution method used in solving th... | Compute agent 2's best cost-minimizing response K, given F.
Parameters
----------
F : array_like(float, ndim=2)
A k x n array
method : str, optional(default='doubling')
Solution method used in solving the associated Riccati
equation, str in {'doubling... |
def copy(self):
'''
makes a clone copy of the mapper. It won't clone the serializers or deserializers and it won't copy the events
'''
try:
tmp = self.__class__()
except Exception:
tmp = self.__class__(self._pdict)
tmp._serializers = ... | makes a clone copy of the mapper. It won't clone the serializers or deserializers and it won't copy the events |
def Setup(self):
"""
Initialize the local node.
Returns:
"""
self.Peers = [] # active nodes that we're connected to
self.KNOWN_ADDRS = [] # node addresses that we've learned about from other nodes
self.DEAD_ADDRS = [] # addresses that were performing poorly o... | Initialize the local node.
Returns: |
def _truthtable(inputs, pcdata):
"""Return a truth table."""
if len(inputs) == 0 and pcdata[0] in {PC_ZERO, PC_ONE}:
return {
PC_ZERO : TTZERO,
PC_ONE : TTONE
}[pcdata[0]]
elif len(inputs) == 1 and pcdata[0] == PC_ZERO and pcdata[1] == PC_ONE:
return inputs[0... | Return a truth table. |
def stats(self, key=None):
"""
Return server stats.
:param key: Optional if you want status from a key.
:type key: six.string_types
:return: A dict with server stats
:rtype: dict
"""
# TODO: Stats with key is not working.
returns = {}
for... | Return server stats.
:param key: Optional if you want status from a key.
:type key: six.string_types
:return: A dict with server stats
:rtype: dict |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.