_id stringlengths 2 7 | title stringlengths 1 88 | partition stringclasses 3
values | text stringlengths 75 19.8k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q38000 | DeflateDecompressor.decompress | train | def decompress(self, chunk):
"""Decompress the chunk of data.
:param bytes chunk: data chunk
:rtype: bytes
"""
try:
return self._decompressobj.decompress(chunk)
except zlib.error:
# ugly hack to work with raw deflate content that may
... | python | {
"resource": ""
} |
q38001 | makeOuputDir | train | def makeOuputDir(outputDir, force):
"""
Create or check for an output directory.
@param outputDir: A C{str} output directory name, or C{None}.
@param force: If C{True}, allow overwriting of pre-existing files.
@return: The C{str} output directory name.
"""
if outputDir:
if exists(ou... | python | {
"resource": ""
} |
q38002 | samtoolsMpileup | train | def samtoolsMpileup(outFile, referenceFile, alignmentFile, executor):
"""
Use samtools mpileup to generate VCF.
@param outFile: The C{str} name to write the output to.
@param referenceFile: The C{str} name of the FASTA file with the reference
sequence.
@param alignmentFile: The C{str} name ... | python | {
"resource": ""
} |
q38003 | bcftoolsMpileup | train | def bcftoolsMpileup(outFile, referenceFile, alignmentFile, executor):
"""
Use bcftools mpileup to generate VCF.
@param outFile: The C{str} name to write the output to.
@param referenceFile: The C{str} name of the FASTA file with the reference
sequence.
@param alignmentFile: The C{str} name ... | python | {
"resource": ""
} |
q38004 | bcftoolsConsensus | train | def bcftoolsConsensus(outFile, vcfFile, id_, referenceFile, executor):
"""
Use bcftools to extract consensus FASTA.
@param outFile: The C{str} name to write the output to.
@param vcfFile: The C{str} name of the VCF file with the calls from
the pileup.
@param id_: The C{str} identifier to us... | python | {
"resource": ""
} |
q38005 | vcfutilsConsensus | train | def vcfutilsConsensus(outFile, vcfFile, id_, _, executor):
"""
Use vcftools to extract consensus FASTA.
@param outFile: The C{str} name to write the output to.
@param vcfFile: The C{str} name of the VCF file with the calls from
the pileup.
@param id_: The C{str} identifier to use in the res... | python | {
"resource": ""
} |
q38006 | Ctx.translator | train | def translator(self):
"""Get a valid translator object from one or several languages names."""
if self._translator is None:
languages = self.lang
if not languages:
return gettext.NullTranslations()
if not isinstance(languages, list):
la... | python | {
"resource": ""
} |
q38007 | LineageFetcher.lineage | train | def lineage(self, title):
"""
Get lineage information from the taxonomy database for a given title.
@param title: A C{str} sequence title (e.g., from a BLAST hit). Of the
form 'gi|63148399|gb|DQ011818.1| Description...'. It is the gi
number (63148399 in this example) tha... | python | {
"resource": ""
} |
q38008 | LineageFetcher.close | train | def close(self):
"""
Close the database connection and render self invalid. Any subsequent
re-use of self will raise an error.
"""
self._cursor.close()
self._db.close()
self._cursor = self._db = self._cache = None | python | {
"resource": ""
} |
q38009 | retry_handler | train | def retry_handler(retries=0, delay=timedelta(), conditions=[]):
"""
A simple wrapper function that creates a handler function by using
on the retry_loop function.
Args:
retries (Integral): The number of times to retry if a failure occurs.
delay (timedelta, optional, 0 seconds): A timede... | python | {
"resource": ""
} |
q38010 | retry | train | def retry(retries=0, delay=timedelta(), conditions=[]):
"""
A decorator for making a function that retries on failure.
Args:
retries (Integral): The number of times to retry if a failure occurs.
delay (timedelta, optional, 0 seconds): A timedelta representing
the amount of time ... | python | {
"resource": ""
} |
q38011 | retry_loop | train | def retry_loop(retries, delay_in_seconds, conditions, function):
"""
Actually performs the retry loop used by the retry decorator
and handler functions. Failures for retrying are defined by
the RetryConditions passed in. If the maximum number of
retries has been reached then it raises the most recen... | python | {
"resource": ""
} |
q38012 | DiamondTabularFormatReader.saveAsJSON | train | def saveAsJSON(self, fp, writeBytes=False):
"""
Write the records out as JSON. The first JSON object saved contains
information about the DIAMOND algorithm.
@param fp: A C{str} file pointer to write to.
@param writeBytes: If C{True}, the JSON will be written out as bytes
... | python | {
"resource": ""
} |
q38013 | object_as_dict | train | def object_as_dict(obj):
"""Turn an SQLAlchemy model into a dict of field names and values.
Based on https://stackoverflow.com/a/37350445/1579058
"""
return {c.key: getattr(obj, c.key)
for c in inspect(obj).mapper.column_attrs} | python | {
"resource": ""
} |
q38014 | SQLAReference.fetch_object | train | def fetch_object(self, model_id):
"""Fetch the model by its ID."""
pk_field_instance = getattr(self.object_class, self.pk_field)
qs = self.object_class.query.filter(pk_field_instance == model_id)
model = qs.one_or_none()
if not model:
raise ReferenceNotFoundError
... | python | {
"resource": ""
} |
q38015 | init_ixe | train | def init_ixe(logger, host, port=4555, rsa_id=None):
""" Connect to Tcl Server and Create IxExplorer object.
:param logger: python logger object
:param host: host (IxTclServer) IP address
:param port: Tcl Server port
:param rsa_id: full path to RSA ID file for Linux based IxVM
:return: IXE objec... | python | {
"resource": ""
} |
q38016 | IxeApp.connect | train | def connect(self, user=None):
""" Connect to host.
:param user: if user - login session.
"""
self.api._tcl_handler.connect()
if user:
self.session.login(user) | python | {
"resource": ""
} |
q38017 | IxeApp.add | train | def add(self, chassis):
""" add chassis.
:param chassis: chassis IP address.
"""
self.chassis_chain[chassis] = IxeChassis(self.session, chassis, len(self.chassis_chain) + 1)
self.chassis_chain[chassis].connect() | python | {
"resource": ""
} |
q38018 | IxeSession.wait_for_up | train | def wait_for_up(self, timeout=16, ports=None):
""" Wait until ports reach up state.
:param timeout: seconds to wait.
:param ports: list of ports to wait for.
:return:
"""
port_list = []
for port in ports:
port_list.append(self.set_ports_list(port))
... | python | {
"resource": ""
} |
q38019 | IxeSession.start_transmit | train | def start_transmit(self, blocking=False, start_packet_groups=True, *ports):
""" Start transmit on ports.
:param blocking: True - wait for traffic end, False - return after traffic start.
:param start_packet_groups: True - clear time stamps and start collecting packet groups stats, False - don't... | python | {
"resource": ""
} |
q38020 | IxeSession.start_packet_groups | train | def start_packet_groups(self, clear_time_stamps=True, *ports):
""" Start packet groups on ports.
:param clear_time_stamps: True - clear time stamps, False - don't.
:param ports: list of ports to start traffic on, if empty start on all ports.
"""
port_list = self.set_ports_list(*... | python | {
"resource": ""
} |
q38021 | IxeSession.stop_transmit | train | def stop_transmit(self, *ports):
""" Stop traffic on ports.
:param ports: list of ports to stop traffic on, if empty start on all ports.
"""
port_list = self.set_ports_list(*ports)
self.api.call_rc('ixStopTransmit {}'.format(port_list))
time.sleep(0.2) | python | {
"resource": ""
} |
q38022 | IxeSession.wait_transmit | train | def wait_transmit(self, *ports):
""" Wait for traffic end on ports.
:param ports: list of ports to wait for, if empty wait for all ports.
"""
port_list = self.set_ports_list(*ports)
self.api.call_rc('ixCheckTransmitDone {}'.format(port_list)) | python | {
"resource": ""
} |
q38023 | IxeSession.start_capture | train | def start_capture(self, *ports):
""" Start capture on ports.
:param ports: list of ports to start capture on, if empty start on all ports.
"""
IxeCapture.current_object = None
IxeCaptureBuffer.current_object = None
if not ports:
ports = self.ports.values()
... | python | {
"resource": ""
} |
q38024 | chr22XY | train | def chr22XY(c):
"""force to name from 1..22, 23, 24, X, Y, M
to in chr1..chr22, chrX, chrY, chrM
str or ints accepted
>>> chr22XY('1')
'chr1'
>>> chr22XY(1)
'chr1'
>>> chr22XY('chr1')
'chr1'
>>> chr22XY(23)
'chrX'
>>> chr22XY(24)
'chrY'
>>> chr22XY("X")
'chr... | python | {
"resource": ""
} |
q38025 | infer_namespace | train | def infer_namespace(ac):
"""Infer the single namespace of the given accession
This function is convenience wrapper around infer_namespaces().
Returns:
* None if no namespaces are inferred
* The (single) namespace if only one namespace is inferred
* Raises an exception if more than one nam... | python | {
"resource": ""
} |
q38026 | infer_namespaces | train | def infer_namespaces(ac):
"""infer possible namespaces of given accession based on syntax
Always returns a list, possibly empty
>>> infer_namespaces("ENST00000530893.6")
['ensembl']
>>> infer_namespaces("ENST00000530893")
['ensembl']
>>> infer_namespaces("ENSQ00000530893")
[]
>>> in... | python | {
"resource": ""
} |
q38027 | IntervalSet.add | train | def add(self, other):
"""
Add an Interval to the IntervalSet by taking the union of the given Interval object with the existing
Interval objects in self.
This has no effect if the Interval is already represented.
:param other: an Interval to add to this IntervalSet.
"""
... | python | {
"resource": ""
} |
q38028 | IntervalSet.difference | train | def difference(self, other):
"""
Subtract an Interval or IntervalSet from the intervals in the set.
"""
intervals = other if isinstance(other, IntervalSet) else IntervalSet((other,))
result = IntervalSet()
for left in self:
for right in intervals:
... | python | {
"resource": ""
} |
q38029 | Notifications.send_notification | train | def send_notification(self, subject="", message="", sender="", source=None, actions=None):
"""
Sends a notification. Blocks as long as necessary.
:param subject: The subject.
:type subject: str
:param message: The message.
:type message: str
:param sender: The se... | python | {
"resource": ""
} |
q38030 | DjipsumFields.randomBinaryField | train | def randomBinaryField(self):
"""
Return random bytes format.
"""
lst = [
b"hello world",
b"this is bytes",
b"awesome django",
b"djipsum is awesome",
b"\x00\x01\x02\x03\x04\x05\x06\x07",
b"\x0b\x0c\x0e\x0f"
]
... | python | {
"resource": ""
} |
q38031 | DjipsumFields.randomUUIDField | train | def randomUUIDField(self):
"""
Return the unique uuid from uuid1, uuid3, uuid4, or uuid5.
"""
uuid1 = uuid.uuid1().hex
uuid3 = uuid.uuid3(
uuid.NAMESPACE_URL,
self.randomize(['python', 'django', 'awesome'])
).hex
uuid4 = uuid.uuid4().hex
... | python | {
"resource": ""
} |
q38032 | trade_day | train | def trade_day(dt, cal='US'):
"""
Latest trading day w.r.t given dt
Args:
dt: date of reference
cal: trading calendar
Returns:
pd.Timestamp: last trading day
Examples:
>>> trade_day('2018-12-25').strftime('%Y-%m-%d')
'2018-12-24'
"""
from xone import... | python | {
"resource": ""
} |
q38033 | align_data | train | def align_data(*args):
"""
Resample and aligh data for defined frequency
Args:
*args: DataFrame of data to be aligned
Returns:
pd.DataFrame: aligned data with renamed columns
Examples:
>>> start = '2018-09-10T10:10:00'
>>> tz = 'Australia/Sydney'
>>> idx = ... | python | {
"resource": ""
} |
q38034 | cat_data | train | def cat_data(data_kw):
"""
Concatenate data with ticker as sub column index
Args:
data_kw: key = ticker, value = pd.DataFrame
Returns:
pd.DataFrame
Examples:
>>> start = '2018-09-10T10:10:00'
>>> tz = 'Australia/Sydney'
>>> idx = pd.date_range(start=start, ... | python | {
"resource": ""
} |
q38035 | to_frame | train | def to_frame(data_list, exc_cols=None, **kwargs):
"""
Dict in Python 3.6 keeps insertion order, but cannot be relied upon
This method is to keep column names in order
In Python 3.7 this method is redundant
Args:
data_list: list of dict
exc_cols: exclude columns
Returns:
... | python | {
"resource": ""
} |
q38036 | spline_curve | train | def spline_curve(x, y, step, val_min=0, val_max=None, kind='quadratic', **kwargs):
"""
Fit spline curve for given x, y values
Args:
x: x-values
y: y-values
step: step size for interpolation
val_min: minimum value of result
val_max: maximum value of result
kin... | python | {
"resource": ""
} |
q38037 | format_float | train | def format_float(digit=0, is_pct=False):
"""
Number display format for pandas
Args:
digit: number of digits to keep
if negative, add one space in front of positive pct
is_pct: % display
Returns:
lambda function to format floats
Examples:
>>> format_f... | python | {
"resource": ""
} |
q38038 | SQLConstructor.join | train | def join(self, source, op='LEFT JOIN', on=''):
"""
Join `source`.
>>> sc = SQLConstructor('main', ['c1', 'c2'])
>>> sc.join('sub', 'JOIN', 'main.id = sub.id')
>>> (sql, params, keys) = sc.compile()
>>> sql
'SELECT c1, c2 FROM main JOIN sub ON main.id = sub.id'
... | python | {
"resource": ""
} |
q38039 | SQLConstructor.add_and_matches | train | def add_and_matches(self, matcher, lhs, params, numq=1, flatten=None):
"""
Add AND conditions to match to `params`.
:type matcher: str or callable
:arg matcher: if `str`, `matcher.format` is used.
:type lhs: str
:arg lhs: the first argument to `matcher`.
... | python | {
"resource": ""
} |
q38040 | SQLConstructor.add_matches | train | def add_matches(self, matcher, lhs,
match_params=[], include_params=[], exclude_params=[],
numq=1, flatten=None):
"""
Quick way to call `add_or_matches` and `add_and_matches`.
"""
matcher = adapt_matcher(matcher)
notmatcher = negate(matcher... | python | {
"resource": ""
} |
q38041 | SQLConstructor.uniquify_by | train | def uniquify_by(self, column, chooser=None, aggregate='MAX'):
"""
Group by `column` and run `aggregate` function on `chooser` column.
"""
self.group_by.append(column)
if chooser:
i = self.columns.index(chooser)
self.columns[i] = '{0}({1})'.format(aggregate... | python | {
"resource": ""
} |
q38042 | SQLConstructor.move_where_clause_to_column | train | def move_where_clause_to_column(self, column='condition', key=None):
"""
Move whole WHERE clause to a column named `column`.
"""
if self.conditions:
expr = " AND ".join(self.conditions)
params = self.params
self.params = []
self.conditions ... | python | {
"resource": ""
} |
q38043 | remove_axis_junk | train | def remove_axis_junk(ax, which=['right', 'top']):
'''remove upper and right axis'''
for loc, spine in ax.spines.items():
if loc in which:
spine.set_color('none')
ax.xaxis.set_ticks_position('bottom')
ax.yaxis.set_ticks_position('left') | python | {
"resource": ""
} |
q38044 | normalize | train | def normalize(x):
'''normalize x to have mean 0 and unity standard deviation'''
x = x.astype(float)
x -= x.mean()
return x / float(x.std()) | python | {
"resource": ""
} |
q38045 | Indexer.find_record_files | train | def find_record_files(self):
"""
Yield paths to record files.
"""
for (root, _, files) in os.walk(self.record_path):
for f in (f for f in files if f.endswith('.json')):
yield os.path.join(root, f) | python | {
"resource": ""
} |
q38046 | Field.buffer_to_value | train | def buffer_to_value(self, obj, buffer, offset, default_endianness=DEFAULT_ENDIANNESS):
"""
Converts the bytes in ``buffer`` at ``offset`` to a native Python value. Returns that value and the number of
bytes consumed to create it.
:param obj: The parent :class:`.PebblePacket` of this fie... | python | {
"resource": ""
} |
q38047 | Field.value_to_bytes | train | def value_to_bytes(self, obj, value, default_endianness=DEFAULT_ENDIANNESS):
"""
Converts the given value to an appropriately encoded string of bytes that represents it.
:param obj: The parent :class:`.PebblePacket` of this field
:type obj: .PebblePacket
:param value: The python... | python | {
"resource": ""
} |
q38048 | profile | train | def profile(func):
"""
Decorator to profile functions with cProfile
Args:
func: python function
Returns:
profile report
References:
https://osf.io/upav8/
"""
def inner(*args, **kwargs):
pr = cProfile.Profile()
pr.enable()
res = func(*args, ... | python | {
"resource": ""
} |
q38049 | EjabberdXMLRPCBackend.rpc | train | def rpc(self, cmd, **kwargs):
"""Generic helper function to call an RPC method."""
func = getattr(self.client, cmd)
try:
if self.credentials is None:
return func(kwargs)
else:
return func(self.credentials, kwargs)
except socket.err... | python | {
"resource": ""
} |
q38050 | _parse_chemical_equation | train | def _parse_chemical_equation(value):
"""
Parse the chemical equation mini-language.
See the docstring of `ChemicalEquation` for more.
Parameters
----------
value : `str`
A string in chemical equation mini-language.
Returns
-------
mapping
A mapping in the format sp... | python | {
"resource": ""
} |
q38051 | _get_chemical_equation_piece | train | def _get_chemical_equation_piece(species_list, coefficients):
"""
Produce a string from chemical species and their coefficients.
Parameters
----------
species_list : iterable of `str`
Iterable of chemical species.
coefficients : iterable of `float`
Nonzero stoichiometric coeffic... | python | {
"resource": ""
} |
q38052 | _check_data | train | def _check_data(data):
"""
Check a data object for inconsistencies.
Parameters
----------
data : `pandas.DataFrame`
A `data` object, i.e., a table whose rows store information about
chemical species, indexed by chemical species.
Warns
-----
UserWarning
Warned if... | python | {
"resource": ""
} |
q38053 | _split_chemical_equations | train | def _split_chemical_equations(value):
"""
Split a string with sequential chemical equations into separate strings.
Each string in the returned iterable represents a single chemical equation
of the input.
See the docstrings of `ChemicalEquation` and `ChemicalSystem` for more.
Parameters
---... | python | {
"resource": ""
} |
q38054 | ChemicalEquation.to_series | train | def to_series(self, only=None,
intensive_columns=["temperature", "pressure"],
check_data=True):
"""
Produce a data record for `ChemicalEquation`.
All possible linear differences for all numeric attributes are computed
and stored in the returned `panda... | python | {
"resource": ""
} |
q38055 | ChemicalSystem.to_dataframe | train | def to_dataframe(self, *args, **kwargs):
"""
Produce a data table with records for all chemical equations.
All possible differences for numeric attributes are computed and stored
as columns in the returned `pandas.DataFrame` object (see examples
below), whose rows represent chem... | python | {
"resource": ""
} |
q38056 | ChemicalSystem.to_digraph | train | def to_digraph(self, *args, **kwargs):
"""
Compute a directed graph for the chemical system.
Returns
-------
digraph : `networkx.DiGraph`
Graph nodes are reactants and/or products of chemical equations,
while edges represent the equations themselves. Doub... | python | {
"resource": ""
} |
q38057 | read_cclib | train | def read_cclib(value, name=None):
"""
Create an `Atoms` object from data attributes parsed by cclib.
`cclib <https://cclib.github.io/>`_ is an open source library, written in
Python, for parsing and interpreting the results (logfiles) of
computational chemistry packages.
Parameters
-------... | python | {
"resource": ""
} |
q38058 | read_pybel | train | def read_pybel(value, name=None):
"""
Create an `Atoms` object from content parsed by Pybel.
`Pybel <https://openbabel.org/docs/dev/UseTheLibrary/Python_Pybel.html>`_
is a Python module that simplifies access to the OpenBabel API, a chemical
toolbox designed to speak the many languages of chemical ... | python | {
"resource": ""
} |
q38059 | create_data | train | def create_data(*args):
"""
Produce a single data object from an arbitrary number of different objects.
This function returns a single `pandas.DataFrame` object from a collection
of `Atoms` and `pandas.DataFrame` objects. The returned object, already
indexed by `Atoms.name`, can be promptly used by... | python | {
"resource": ""
} |
q38060 | Atoms.split | train | def split(self, pattern=None):
r"""
Break molecule up into constituent fragments.
By default (i.e., if `pattern` is `None`), each disconnected fragment
is returned as a separate new `Atoms` object. This uses OpenBabel
(through `OBMol.Separate`) and might not preserve atom order,... | python | {
"resource": ""
} |
q38061 | Atoms.to_pybel | train | def to_pybel(self):
"""
Produce a Pybel Molecule object.
It is based on the capabilities of OpenBabel through Pybel. The present
object must have at least `atomcoords`, `atomnos`, `charge` and `mult`
defined.
Returns
-------
`pybel.Molecule`
Exa... | python | {
"resource": ""
} |
q38062 | Atoms.to_string | train | def to_string(self, format="smi", dialect=None, with_header=False,
fragment_id=None, constraints=None):
r"""
Produce a string representation of the molecule.
This function wraps and extends the functionality of OpenBabel (which
is accessible through `to_pybel`). Many c... | python | {
"resource": ""
} |
q38063 | run | train | def run(macro, output_files=[], force_close=True):
"""
Runs Fiji with the suplied macro. Output of Fiji can be viewed by
setting environment variable `DEBUG=fijibin`.
Parameters
----------
macro : string or list of strings
IJM-macro(s) to run. If list of strings, it will be joined with
... | python | {
"resource": ""
} |
q38064 | _exists | train | def _exists(filenames):
"""Check if every filename exists. If not, print an error
message and remove the item from the list.
Parameters
----------
filenames : list
List of filenames to check for existence.
Returns
-------
list
Filtered list of filenames that exists.
... | python | {
"resource": ""
} |
q38065 | VoiceService.send_stop_audio | train | def send_stop_audio(self):
'''
Stop an audio streaming session
'''
assert self._session_id != VoiceService.SESSION_ID_INVALID
self._pebble.send_packet(AudioStream(session_id=self._session_id, data=StopTransfer())) | python | {
"resource": ""
} |
q38066 | VoiceService.send_session_setup_result | train | def send_session_setup_result(self, result, app_uuid=None):
'''
Send the result of setting up a dictation session requested by the watch
:param result: result of setting up the session
:type result: .SetupResult
:param app_uuid: UUID of app that initiated the session
:t... | python | {
"resource": ""
} |
q38067 | VoiceService.send_dictation_result | train | def send_dictation_result(self, result, sentences=None, app_uuid=None):
'''
Send the result of a dictation session
:param result: Result of the session
:type result: DictationResult
:param sentences: list of sentences, each of which is a list of words and punctuation
:pa... | python | {
"resource": ""
} |
q38068 | load_ipython_extension | train | def load_ipython_extension(ip):
"""
register magics function, can be called from a notebook
"""
#ip = get_ipython()
ip.register_magics(CustomMagics)
# enable C# (CSHARP) highlight
patch = ("IPython.config.cell_magic_highlight['clrmagic'] = "
"{'reg':[/^%%CS/]};")
js = displa... | python | {
"resource": ""
} |
q38069 | XmppBackendBase.module | train | def module(self):
"""The module specified by the ``library`` attribute."""
if self._module is None:
if self.library is None:
raise ValueError(
"Backend '%s' doesn't specify a library attribute" % self.__class__)
try:
if '.' in... | python | {
"resource": ""
} |
q38070 | XmppBackendBase.datetime_to_timestamp | train | def datetime_to_timestamp(self, dt):
"""Helper function to convert a datetime object to a timestamp.
If datetime instance ``dt`` is naive, it is assumed that it is in UTC.
In Python 3, this just calls ``datetime.timestamp()``, in Python 2, it substracts any timezone offset
and returns ... | python | {
"resource": ""
} |
q38071 | XmppBackendBase.get_random_password | train | def get_random_password(self, length=32, chars=None):
"""Helper function that gets a random password.
:param length: The length of the random password.
:type length: int
:param chars: A string with characters to choose from. Defaults to all ASCII letters and digits.
:type ch... | python | {
"resource": ""
} |
q38072 | XmppBackendBase.create_reservation | train | def create_reservation(self, username, domain, email=None):
"""Reserve a new account.
This method is called when a user account should be reserved, meaning that the account can no longer
be registered by anybody else but the user cannot yet log in either. This is useful if e.g. an email
... | python | {
"resource": ""
} |
q38073 | XmppBackendBase.confirm_reservation | train | def confirm_reservation(self, username, domain, password, email=None):
"""Confirm a reservation for a username.
The default implementation just calls :py:func:`~xmpp_backends.base.XmppBackendBase.set_password` and
optionally :py:func:`~xmpp_backends.base.XmppBackendBase.set_email`.
"""
... | python | {
"resource": ""
} |
q38074 | XmppBackendBase.block_user | train | def block_user(self, username, domain):
"""Block the specified user.
The default implementation calls :py:func:`~xmpp_backends.base.XmppBackendBase.set_password` with a
random password.
:param username: The username of the user.
:type username: str
:param domain: The... | python | {
"resource": ""
} |
q38075 | EjabberdBackendBase.parse_connection_string | train | def parse_connection_string(self, connection):
"""Parse string as returned by the ``connected_users_info`` or ``user_sessions_info`` API calls.
>>> EjabberdBackendBase().parse_connection_string('c2s_tls')
(0, True, False)
>>> EjabberdBackendBase().parse_connection_string('c2s_compressed... | python | {
"resource": ""
} |
q38076 | EjabberdBackendBase.parse_ip_address | train | def parse_ip_address(self, ip_address):
"""Parse an address as returned by the ``connected_users_info`` or ``user_sessions_info`` API calls.
Example::
>>> EjabberdBackendBase().parse_ip_address('192.168.0.1') # doctest: +FORCE_TEXT
IPv4Address('192.168.0.1')
>>> Ej... | python | {
"resource": ""
} |
q38077 | PebbleConnection.pump_reader | train | def pump_reader(self):
"""
Synchronously reads one message from the watch, blocking until a message is available.
All events caused by the message read will be processed before this method returns.
.. note::
You usually don't need to invoke this method manually; instead, see ... | python | {
"resource": ""
} |
q38078 | PebbleConnection.run_sync | train | def run_sync(self):
"""
Runs the message loop until the Pebble disconnects. This method will block until the watch disconnects or
a fatal error occurs.
For alternatives that don't block forever, see :meth:`pump_reader` and :meth:`run_async`.
"""
while self.connected:
... | python | {
"resource": ""
} |
q38079 | PebbleConnection._handle_watch_message | train | def _handle_watch_message(self, message):
"""
Processes a binary message received from the watch and broadcasts the relevant events.
:param message: A raw message from the watch, without any transport framing.
:type message: bytes
"""
if self.log_protocol_level is not No... | python | {
"resource": ""
} |
q38080 | PebbleConnection._broadcast_transport_message | train | def _broadcast_transport_message(self, origin, message):
"""
Broadcasts an event originating from a transport that does not represent a message from the Pebble.
:param origin: The type of transport responsible for the message.
:type origin: .MessageTarget
:param message: The mes... | python | {
"resource": ""
} |
q38081 | PebbleConnection.register_transport_endpoint | train | def register_transport_endpoint(self, origin, message_type, handler):
"""
Register a handler for a message received from a transport that does not indicate a message from the connected
Pebble.
:param origin: The type of :class:`.MessageTarget` that triggers the message
:param me... | python | {
"resource": ""
} |
q38082 | PebbleConnection.register_endpoint | train | def register_endpoint(self, endpoint, handler):
"""
Register a handler for a message received from the Pebble.
:param endpoint: The type of :class:`.PebblePacket` that is being listened for.
:type endpoint: .PacketType
:param handler: A callback to be called when a message is re... | python | {
"resource": ""
} |
q38083 | PebbleConnection.read_transport_message | train | def read_transport_message(self, origin, message_type, timeout=15):
"""
Blocking read of a transport message that does not indicate a message from the Pebble.
Will block until a message is received, or it times out.
.. warning::
Avoid calling this method from an endpoint call... | python | {
"resource": ""
} |
q38084 | PebbleConnection.send_packet | train | def send_packet(self, packet):
"""
Sends a message to the Pebble.
:param packet: The message to send.
:type packet: .PebblePacket
"""
if self.log_packet_level:
logger.log(self.log_packet_level, "-> %s", packet)
serialised = packet.serialise_packet()
... | python | {
"resource": ""
} |
q38085 | PebbleConnection.send_and_read | train | def send_and_read(self, packet, endpoint, timeout=15):
"""
Sends a packet, then returns the next response received from that endpoint. This method sets up a listener
before it actually sends the message, avoiding a potential race.
.. warning::
Avoid calling this method from a... | python | {
"resource": ""
} |
q38086 | PebbleConnection.send_raw | train | def send_raw(self, message):
"""
Sends a raw binary message to the Pebble. No processing will be applied, but any transport framing should be
omitted.
:param message: The message to send to the pebble.
:type message: bytes
"""
if self.log_protocol_level:
... | python | {
"resource": ""
} |
q38087 | PebbleConnection.firmware_version | train | def firmware_version(self):
"""
Provides information on the connected Pebble, including its firmware version, language, capabilities, etc.
.. note:
This is a blocking call if :meth:`fetch_watch_info` has not yet been called, which could lead to deadlock
if called in an end... | python | {
"resource": ""
} |
q38088 | GDF._blockread | train | def _blockread(self, fname):
"""
Generator yields bsize lines from gdf file.
Hidden method.
Parameters
----------
fname : str
Name of gdf-file.
Yields
------
list
file contents
""... | python | {
"resource": ""
} |
q38089 | GDF.create | train | def create(self, re='brunel-py-ex-*.gdf', index=True):
"""
Create db from list of gdf file glob
Parameters
----------
re : str
File glob to load.
index : bool
Create index on neurons for speed.
Returns
... | python | {
"resource": ""
} |
q38090 | GDF.create_from_list | train | def create_from_list(self, re=[], index=True):
"""
Create db from list of arrays.
Parameters
----------
re : list
Index of element is cell index, and element `i` an array of spike times in ms.
index : bool
Create index on neurons for speed.
... | python | {
"resource": ""
} |
q38091 | GDF.select | train | def select(self, neurons):
"""
Select spike trains.
Parameters
----------
neurons : numpy.ndarray or list
Array of list of neurons.
Returns
-------
list
List of numpy.ndarray objects containing spike times.
See also
... | python | {
"resource": ""
} |
q38092 | GDF.interval | train | def interval(self, T=[0, 1000]):
"""
Get all spikes in a time interval T.
Parameters
----------
T : list
Time interval.
Returns
-------
s : list
Nested list with spike times.
See also
--------
sqlite3.... | python | {
"resource": ""
} |
q38093 | GDF.neurons | train | def neurons(self):
"""
Return list of neuron indices.
Parameters
----------
None
Returns
-------
list
list of neuron indices
See also
--------
sqlite3.connect.cursor
"""
... | python | {
"resource": ""
} |
q38094 | GDF.num_spikes | train | def num_spikes(self):
"""
Return total number of spikes.
Parameters
----------
None
Returns
-------
list
"""
self.cursor.execute('SELECT Count(*) from spikes')
rows = self.cursor.fetchall()[0]
# Check ag... | python | {
"resource": ""
} |
q38095 | GDF.plotstuff | train | def plotstuff(self, T=[0, 1000]):
"""
Create a scatter plot of the contents of the database,
with entries on the interval T.
Parameters
----------
T : list
Time interval.
Returns
-------
None
... | python | {
"resource": ""
} |
q38096 | get_config_directory | train | def get_config_directory(appname):
"""
Get OS-specific configuration directory.
:type appname: str
:arg appname: capitalized name of the application
"""
if platform.system().lower() == 'windows':
path = os.path.join(os.getenv('APPDATA') or '~', appname, appname)
elif platform.syst... | python | {
"resource": ""
} |
q38097 | SendEmailAdmin.save_model | train | def save_model(self, request, obj, form, change):
"""
sends the email and does not save it
"""
email = message.EmailMessage(
subject=obj.subject,
body=obj.body,
from_email=obj.from_email,
to=[t.strip() for t in obj.to_emails.split(',')],
... | python | {
"resource": ""
} |
q38098 | dump_dict_of_nested_lists_to_h5 | train | def dump_dict_of_nested_lists_to_h5(fname, data):
"""
Take nested list structure and dump it in hdf5 file.
Parameters
----------
fname : str
Filename
data : dict(list(numpy.ndarray))
Dict of nested lists with variable len arrays.
Returns
-------
None
... | python | {
"resource": ""
} |
q38099 | load_dict_of_nested_lists_from_h5 | train | def load_dict_of_nested_lists_from_h5(fname, toplevelkeys=None):
"""
Load nested list structure from hdf5 file
Parameters
----------
fname : str
Filename
toplevelkeys : None or iterable,
Load a two(default) or three-layered structure.
Returns
-------
dict... | python | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.