code stringlengths 75 104k | docstring stringlengths 1 46.9k |
|---|---|
def acosh(wave):
r"""
Return the hyperbolic arc cosine of a waveform's dependent variable vector.
:param wave: Waveform
:type wave: :py:class:`peng.eng.Waveform`
:rtype: :py:class:`peng.eng.Waveform`
.. [[[cog cog.out(exobj_eng.get_sphinx_autodoc()) ]]]
.. Auto-generated exceptions docum... | r"""
Return the hyperbolic arc cosine of a waveform's dependent variable vector.
:param wave: Waveform
:type wave: :py:class:`peng.eng.Waveform`
:rtype: :py:class:`peng.eng.Waveform`
.. [[[cog cog.out(exobj_eng.get_sphinx_autodoc()) ]]]
.. Auto-generated exceptions documentation for
.. p... |
def QA_fetch_stock_min_adv(
code,
start, end=None,
frequence='1min',
if_drop_index=True,
# 🛠 todo collections 参数没有用到, 且数据库是固定的, 这个变量后期去掉
collections=DATABASE.stock_min):
'''
'获取股票分钟线'
:param code: 字符串str eg 600085
:param start: 字符串str 开始日期 eg 2011-01-01
... | '获取股票分钟线'
:param code: 字符串str eg 600085
:param start: 字符串str 开始日期 eg 2011-01-01
:param end: 字符串str 结束日期 eg 2011-05-01
:param frequence: 字符串str 分钟线的类型 支持 1min 1m 5min 5m 15min 15m 30min 30m 60min 60m 类型
:param if_drop_index: Ture False , dataframe drop index or not
:param collections: mongodb ... |
def set_principal_credit_string(self, credit_string=None):
"""Sets the principal credit string.
:param credit_string: the new credit string
:type credit_string: ``string``
:raise: ``InvalidArgument`` -- ``credit_string`` is invalid
:raise: ``NoAccess`` -- ``Metadata.isReadOnly()... | Sets the principal credit string.
:param credit_string: the new credit string
:type credit_string: ``string``
:raise: ``InvalidArgument`` -- ``credit_string`` is invalid
:raise: ``NoAccess`` -- ``Metadata.isReadOnly()`` is ``true``
:raise: ``NullArgument`` -- ``credit_string`` i... |
def getGameHighScores(self, user_id, game_message_identifier):
"""
See: https://core.telegram.org/bots/api#getgamehighscores
:param game_message_identifier: Same as ``msg_identifier`` in :meth:`telepot.Bot.editMessageText`
"""
p = _strip(locals(), more=['game_message_identifier'... | See: https://core.telegram.org/bots/api#getgamehighscores
:param game_message_identifier: Same as ``msg_identifier`` in :meth:`telepot.Bot.editMessageText` |
def p_propertyDeclaration_5(p):
"""propertyDeclaration_5 : qualifierList dataType propertyName ';'"""
quals = OrderedDict([(x.name, x) for x in p[1]])
p[0] = CIMProperty(p[3], None, type=p[2], qualifiers=quals) | propertyDeclaration_5 : qualifierList dataType propertyName '; |
def svevent_reader(in_file):
"""Lazy generator of SV events, returned as dictionary of parts.
"""
with open(in_file) as in_handle:
while 1:
line = next(in_handle)
if line.startswith(">"):
break
header = line[1:].rstrip().split("\t")
reader = cs... | Lazy generator of SV events, returned as dictionary of parts. |
def cluster(dupes, threshold=.5, max_components=30000):
'''
Takes in a list of duplicate pairs and clusters them in to a
list records that all refer to the same entity based on a given
threshold
Keyword arguments:
threshold -- number betweent 0 and 1 (default is .5). lowering the
... | Takes in a list of duplicate pairs and clusters them in to a
list records that all refer to the same entity based on a given
threshold
Keyword arguments:
threshold -- number betweent 0 and 1 (default is .5). lowering the
number will increase precision, raising it will increase
... |
def cache_control(self):
"""The Cache-Control general-header field is used to specify
directives that MUST be obeyed by all caching mechanisms along the
request/response chain.
"""
def on_update(cache_control):
if not cache_control and 'cache-control' in self.headers:... | The Cache-Control general-header field is used to specify
directives that MUST be obeyed by all caching mechanisms along the
request/response chain. |
def scatter(self, x, y, xerr=[], yerr=[], mark='o', markstyle=None):
"""Plot a series of points.
Plot a series of points (marks) that are not connected by a
line. Shortcut for plot with linestyle=None.
:param x: array containing x-values.
:param y: array containing y-values.
... | Plot a series of points.
Plot a series of points (marks) that are not connected by a
line. Shortcut for plot with linestyle=None.
:param x: array containing x-values.
:param y: array containing y-values.
:param xerr: array containing errors on the x-values.
:param yerr:... |
def _expected_condition_find_element_containing_text(self, element_text_pair):
"""Tries to find the element and checks that it contains the specified text, but does not thrown an exception if the element is
not found
:param element_text_pair: Tuple with 2 items where:
[0] elemen... | Tries to find the element and checks that it contains the specified text, but does not thrown an exception if the element is
not found
:param element_text_pair: Tuple with 2 items where:
[0] element: PageElement or element locator as a tuple (locator_type, locator_value) to be found
... |
def prepare_mac_header(token, uri, key, http_method,
nonce=None,
headers=None,
body=None,
ext='',
hash_algorithm='hmac-sha-1',
issue_time=None,
draft=0):
"... | Add an `MAC Access Authentication`_ signature to headers.
Unlike OAuth 1, this HMAC signature does not require inclusion of the
request payload/body, neither does it use a combination of client_secret
and token_secret but rather a mac_key provided together with the access
token.
Currently two algo... |
def write_xml(self, outfile, encoding="UTF-8"):
"""Write the Media RSS Feed's XML representation to the given file."""
# we add the media namespace if we see any media items
if any([key for item in self.items for key in vars(item) if
key.startswith('media_') and getattr(item, key... | Write the Media RSS Feed's XML representation to the given file. |
def code_events(self):
"""Returns processed memory usage."""
if self._resulting_events:
return self._resulting_events
for i, (lineno, mem, func, fname) in enumerate(self._events_list):
mem_in_mb = float(mem - self.mem_overhead) / _BYTES_IN_MB
if (self._resulti... | Returns processed memory usage. |
def verify_ticket_signature(self, data, sig):
"""Verify ticket signature. """
try:
signature = base64.b64decode(sig)
except TypeError as e:
if hasattr(self, "debug"):
print("Exception in function base64.b64decode. File %s" % (__file__))
... | Verify ticket signature. |
def sqs_delete_queue(queue_url, client=None):
"""This deletes an SQS queue given its URL
Parameters
----------
queue_url : str
The SQS URL of the queue to delete.
client : boto3.Client or None
If None, this function will instantiate a new `boto3.Client` object to
use in it... | This deletes an SQS queue given its URL
Parameters
----------
queue_url : str
The SQS URL of the queue to delete.
client : boto3.Client or None
If None, this function will instantiate a new `boto3.Client` object to
use in its operations. Alternatively, pass in an existing `bot... |
def cycle_data(self, repository, cycle_interval, chunk_size, sleep_time):
"""
Delete data older than cycle_interval, splitting the target data into
chunks of chunk_size size. Returns the number of result sets deleted
"""
# Retrieve list of jobs to delete
jobs_max_timesta... | Delete data older than cycle_interval, splitting the target data into
chunks of chunk_size size. Returns the number of result sets deleted |
def _load(self, slug):
"""Load the page. The _file_name param is known, because this
method is only called after having checked that the page exists.
"""
#here we know that the slug exists
self._slug = slug
page_dir = os.path.join(self.site.dirs['source'], self._slug)
... | Load the page. The _file_name param is known, because this
method is only called after having checked that the page exists. |
def totalNumberOfTiles(self, minZoom=None, maxZoom=None):
"Return the total number of tiles for this instance extent"
nbTiles = 0
minZoom = minZoom or 0
if maxZoom:
maxZoom = maxZoom + 1
else:
maxZoom = len(self.RESOLUTIONS)
for zoom in xrange(minZ... | Return the total number of tiles for this instance extent |
def _checkNumerical(inputvalue, minvalue=None, maxvalue=None, description='inputvalue'):
"""Check that the given numerical value is valid.
Args:
* inputvalue (numerical): The value to be checked.
* minvalue (numerical): Minimum value Use None to skip this part of the test.
* maxvalue (... | Check that the given numerical value is valid.
Args:
* inputvalue (numerical): The value to be checked.
* minvalue (numerical): Minimum value Use None to skip this part of the test.
* maxvalue (numerical): Maximum value. Use None to skip this part of the test.
* description (string... |
def save(f, arr, vocab):
"""
Save word embedding file.
Check :func:`word_embedding_loader.saver.glove.save` for the API.
"""
f.write(('%d %d' % (arr.shape[0], arr.shape[1])).encode('utf-8'))
for word, idx in vocab:
_write_line(f, arr[idx], word) | Save word embedding file.
Check :func:`word_embedding_loader.saver.glove.save` for the API. |
def _add_or_remove_flag(self, flag, add):
"""
Add the given `flag` if `add` is True, remove it otherwise.
"""
meth = self.add_flag if add else self.remove_flag
meth(flag) | Add the given `flag` if `add` is True, remove it otherwise. |
def fail_tmp(item, max_tries=None, ttl=None):
'''Try to fail a work-item temporarily (up recount and keep in queue),
if max tries or ttl is exhausted, escalate to permanant failure.'''
try:
max_tries = item.max_tries if max_tries is None else max_tries
ttl = item.ttl if ttl is None else t... | Try to fail a work-item temporarily (up recount and keep in queue),
if max tries or ttl is exhausted, escalate to permanant failure. |
def find(self, keys, _index=0):
"""
:param keys: key path. ``'a.b'`` is equivalent to ``['a', 'b']``
:type keys: :class:`str` or :class:`list`
Find a nested :class:`Component` by a "`.`" separated list of names.
for example::
>>> motor.find('bearing.outer_ring')
... | :param keys: key path. ``'a.b'`` is equivalent to ``['a', 'b']``
:type keys: :class:`str` or :class:`list`
Find a nested :class:`Component` by a "`.`" separated list of names.
for example::
>>> motor.find('bearing.outer_ring')
would return the Part instance of the motor be... |
def _CreateOutputFileHandles(self, output_type):
"""Creates a new gzipped output tempfile for the output type.
We write to JSON data to gzip_filehandle to get compressed data. We hold a
reference to the original filehandle (gzip_filehandle_parent) so we can pass
the gzip data to bigquery.
Args:
... | Creates a new gzipped output tempfile for the output type.
We write to JSON data to gzip_filehandle to get compressed data. We hold a
reference to the original filehandle (gzip_filehandle_parent) so we can pass
the gzip data to bigquery.
Args:
output_type: string of export type to be used in fil... |
def waiver2mef(sciname, newname=None, convert_dq=True, writefits=True):
"""
Converts a GEIS science file and its corresponding
data quality file (if present) to MEF format
Writes out both files to disk.
Returns the new name of the science image.
"""
if isinstance(sciname, fits.HDUList):
... | Converts a GEIS science file and its corresponding
data quality file (if present) to MEF format
Writes out both files to disk.
Returns the new name of the science image. |
def intensity(image):
'''Calculates the average intensity of the pixels in an image.
Accepts both RGB and grayscale images.
:param image: numpy.ndarray
:returns: image intensity
:rtype: float
'''
if len(image.shape) > 2:
# Convert to grayscale
image = cv2.cvtColor(image, cv2... | Calculates the average intensity of the pixels in an image.
Accepts both RGB and grayscale images.
:param image: numpy.ndarray
:returns: image intensity
:rtype: float |
def encodeIntoArray(self, inputData, output):
"""
See `nupic.encoders.base.Encoder` for more information.
:param: inputData (tuple) Contains speed (float), longitude (float),
latitude (float), altitude (float)
:param: output (numpy.array) Stores encoded SDR in this numpy ar... | See `nupic.encoders.base.Encoder` for more information.
:param: inputData (tuple) Contains speed (float), longitude (float),
latitude (float), altitude (float)
:param: output (numpy.array) Stores encoded SDR in this numpy array |
def of(self, *indented_blocks) -> "CodeBlock":
"""
By default, marks the block as expecting an indented "body" blocks of which are then supplied
as arguments to this method.
Unless the block specifies a "closed_by", if no body blocks are supplied or they are all Nones,
this will... | By default, marks the block as expecting an indented "body" blocks of which are then supplied
as arguments to this method.
Unless the block specifies a "closed_by", if no body blocks are supplied or they are all Nones,
this will generate a "pass" statement as the body. If there is a "closed_by"... |
def direct_dispatch(self, arg, callback):
"""Directly dispatch a work item.
This method MUST only be called from inside of another work item and
will synchronously invoke the work item as if it was passed to
dispatch(). Calling this method from any other thread has undefined
co... | Directly dispatch a work item.
This method MUST only be called from inside of another work item and
will synchronously invoke the work item as if it was passed to
dispatch(). Calling this method from any other thread has undefined
consequences since it will be unsynchronized with respe... |
def duration_minutes(duration):
"""returns minutes from duration, otherwise we keep bashing in same math"""
if isinstance(duration, list):
res = dt.timedelta()
for entry in duration:
res += entry
return duration_minutes(res)
elif isinstance(duration, dt.timedelta):
... | returns minutes from duration, otherwise we keep bashing in same math |
def queryFilter(self, function=None):
"""
Defines a decorator that can be used to filter
queries. It will assume the function being associated
with the decorator will take a query as an input and
return a modified query to use.
:usage
class MyModel(orb.Mode... | Defines a decorator that can be used to filter
queries. It will assume the function being associated
with the decorator will take a query as an input and
return a modified query to use.
:usage
class MyModel(orb.Model):
objects = orb.ReverseLookup('Object')
... |
async def get_or_create(self, model_, defaults=None, **kwargs):
"""Try to get an object or create it with the specified defaults.
Return 2-tuple containing the model instance and a boolean
indicating whether the instance was created.
"""
try:
return (await self.get(m... | Try to get an object or create it with the specified defaults.
Return 2-tuple containing the model instance and a boolean
indicating whether the instance was created. |
def get_cidr_name(cidr, ip_ranges_files, ip_ranges_name_key):
"""
Read display name for CIDRs from ip-ranges files
:param cidr:
:param ip_ranges_files:
:param ip_ranges_name_key:
:return:
"""
for filename in ip_ranges_files:
ip_ranges = read_ip_ranges(filename, local_file=True)
... | Read display name for CIDRs from ip-ranges files
:param cidr:
:param ip_ranges_files:
:param ip_ranges_name_key:
:return: |
def _set_fru(self, v, load=False):
"""
Setter method for fru, mapped from YANG variable /system_monitor_mail/fru (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_fru is considered as a private
method. Backends looking to populate this variable should
d... | Setter method for fru, mapped from YANG variable /system_monitor_mail/fru (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_fru is considered as a private
method. Backends looking to populate this variable should
do so via calling thisObj._set_fru() directly. |
def radiansBetween(self, other):
'''
:param: other - Line subclass
:return: float
Returns the angle measured between two lines in radians
with a range of [0, 2 * math.pi].
'''
# a dot b = |a||b| * cos(theta)
# a dot b / |a||b| = cos(theta)
# cos-... | :param: other - Line subclass
:return: float
Returns the angle measured between two lines in radians
with a range of [0, 2 * math.pi]. |
def create_cell_volumes(self):
"""Computes the volumes of the "cells" in the mesh.
"""
self.cell_volumes = numpy.array(
[
abs(
self.node_coords[cell["nodes"]][1]
- self.node_coords[cell["nodes"]][0]
)
... | Computes the volumes of the "cells" in the mesh. |
def slots(self):
"""Iterate over the Slots of the Template."""
if self.implied:
return ()
data = clips.data.DataObject(self._env)
lib.EnvDeftemplateSlotNames(self._env, self._tpl, data.byref)
return tuple(
TemplateSlot(self._env, self._tpl, n.encode()) ... | Iterate over the Slots of the Template. |
def search(query, stats):
""" Perform issue search for given stats instance """
log.debug("Search query: {0}".format(query))
issues = []
# Fetch data from the server in batches of MAX_RESULTS issues
for batch in range(MAX_BATCHES):
response = stats.parent.session.get(... | Perform issue search for given stats instance |
def make_zip_archive(self,
dst=None,
filters=all_true,
compress=True,
overwrite=False,
makedirs=False,
verbose=False): # pragma: no cover
"""
Make a zip ... | Make a zip archive.
:param dst: output file path. if not given, will be automatically assigned.
:param filters: custom path filter. By default it allows any file.
:param compress: compress or not.
:param overwrite: overwrite exists or not.
:param verbose: display log or not.
... |
def can_process(self, statement):
"""
Determines whether it is appropriate for this
adapter to respond to the user input.
"""
response = self.process(statement)
self.cache[statement.text] = response
return response.confidence == 1 | Determines whether it is appropriate for this
adapter to respond to the user input. |
def GuinierPorodMulti(q, G, *Rgsalphas):
"""Empirical multi-part Guinier-Porod scattering
Inputs:
-------
``q``: independent variable
``G``: factor for the first Guinier-branch
other arguments: [Rg1, alpha1, Rg2, alpha2, Rg3 ...] the radii of
gyration and power-law exponents... | Empirical multi-part Guinier-Porod scattering
Inputs:
-------
``q``: independent variable
``G``: factor for the first Guinier-branch
other arguments: [Rg1, alpha1, Rg2, alpha2, Rg3 ...] the radii of
gyration and power-law exponents of the consecutive parts
Formula:
----... |
def to_monthly(series, method='ffill', how='end'):
"""
Convenience method that wraps asfreq_actual
with 'M' param (method='ffill', how='end').
"""
return series.asfreq_actual('M', method=method, how=how) | Convenience method that wraps asfreq_actual
with 'M' param (method='ffill', how='end'). |
def timestamp(_, dt):
'get microseconds since 2000-01-01 00:00'
# see http://stackoverflow.com/questions/2956886/
dt = util.to_utc(dt)
unix_timestamp = calendar.timegm(dt.timetuple())
# timetuple doesn't maintain microseconds
# see http://stackoverflow.com/a/14369386/519015
val = ((unix_time... | get microseconds since 2000-01-01 00:00 |
def delay_service(self, t=None):
"""Adds an extra service time to the next departing
:class:`Agent's<.Agent>` service time.
Parameters
----------
t : float (optional)
Specifies the departing time for the agent scheduled
to depart next. If ``t`` is not giv... | Adds an extra service time to the next departing
:class:`Agent's<.Agent>` service time.
Parameters
----------
t : float (optional)
Specifies the departing time for the agent scheduled
to depart next. If ``t`` is not given, then an additional
service t... |
def rm_arrow(self, orig, dest, *args):
"""Remove the :class:`Arrow` that goes from ``orig`` to ``dest``."""
if (
orig not in self.arrow or
dest not in self.arrow[orig]
):
raise KeyError("No Arrow from {} to {}".format(orig, dest))
arr = self.ar... | Remove the :class:`Arrow` that goes from ``orig`` to ``dest``. |
def word_error_rate(raw_predictions,
labels,
lookup=None,
weights_fn=common_layers.weights_nonzero):
"""Calculate word error rate.
Args:
raw_predictions: The raw predictions.
labels: The actual labels.
lookup: A tf.constant mapping indices to ... | Calculate word error rate.
Args:
raw_predictions: The raw predictions.
labels: The actual labels.
lookup: A tf.constant mapping indices to output tokens.
weights_fn: Weighting function.
Returns:
The word error rate. |
def PrintVmInfo(vm, depth=1):
"""
Print information for a particular virtual machine or recurse into a folder
or vApp with depth protection
"""
maxdepth = 10
# if this is a group it will have children. if it does, recurse into them
# and then return
if hasattr(vm, 'childEntity'):
if depth... | Print information for a particular virtual machine or recurse into a folder
or vApp with depth protection |
def user_parse(data):
"""Parse information from provider."""
yield 'id', data.get('id')
yield 'email', data.get('email')
yield 'first_name', data.get('given_name')
yield 'last_name', data.get('family_name')
yield 'link', data.get('link')
yield 'locale', data.get('... | Parse information from provider. |
def create_instance(self, collection_or_class, attributes, lazy=False, call_hook=True, deserialize=True, db_loader=None):
"""
Creates an instance of a `Document` class corresponding to the given collection name or class.
:param collection_or_class: The name of the collection or a reference to t... | Creates an instance of a `Document` class corresponding to the given collection name or class.
:param collection_or_class: The name of the collection or a reference to the class for which to create an instance.
:param attributes: The attributes of the instance to be created
:param lazy: Whether... |
def solve_T(self, P, V, quick=True):
r'''Method to calculate `T` from a specified `P` and `V` for the RK
EOS. Uses `a`, and `b`, obtained from the class's namespace.
Parameters
----------
P : float
Pressure, [Pa]
V : float
Molar volume, [m^3/mol]
... | r'''Method to calculate `T` from a specified `P` and `V` for the RK
EOS. Uses `a`, and `b`, obtained from the class's namespace.
Parameters
----------
P : float
Pressure, [Pa]
V : float
Molar volume, [m^3/mol]
quick : bool, optional
Wh... |
def _relay_message(self, message):
"""
Relay messages from the forum on the server to the client represented
by this actor.
"""
info("relaying message: {message}")
if not message.was_sent_by(self._id_factory):
self.pipe.send(message)
self.pipe.de... | Relay messages from the forum on the server to the client represented
by this actor. |
def get(cls, **kwargs):
"""Get cart.
Retrieve the shopping cart of the current session.
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async=True
>>> thread = api.get(async=True)
>>> result = thread.get()
... | Get cart.
Retrieve the shopping cart of the current session.
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async=True
>>> thread = api.get(async=True)
>>> result = thread.get()
:param async bool
:retur... |
def retrieve_all_pages(api_endpoint, **kwargs):
"""
Some MTP apis are paginated using Django Rest Framework's LimitOffsetPagination paginator,
this method loads all pages into a single results list
:param api_endpoint: slumber callable, e.g. `[api_client].cashbook.transactions.locked.get`
:param kwa... | Some MTP apis are paginated using Django Rest Framework's LimitOffsetPagination paginator,
this method loads all pages into a single results list
:param api_endpoint: slumber callable, e.g. `[api_client].cashbook.transactions.locked.get`
:param kwargs: additional arguments to pass into api callable |
def connect_pull(self, timeout=1):
'''
Establish a connection with the event pull socket
Default timeout is 1 s
'''
if self.cpush:
return True
if self._run_io_loop_sync:
with salt.utils.asynchronous.current_ioloop(self.io_loop):
if... | Establish a connection with the event pull socket
Default timeout is 1 s |
def _data_format_resolver(data_format, resolver_dict):
"""Resolve a value from :attr:`resolver_dict` based on the
:attr:`data_format`.
Args:
data_format (:class:`~.DataFormat` or str): The data format;
must be a member of :class:`~.DataFormat` or a string
equivalent.
... | Resolve a value from :attr:`resolver_dict` based on the
:attr:`data_format`.
Args:
data_format (:class:`~.DataFormat` or str): The data format;
must be a member of :class:`~.DataFormat` or a string
equivalent.
resolver_dict (dict): the resolving dict. Can hold any value
... |
def get_mean_and_stddevs(self, sites, rup, dists, imt, stddev_types):
"""
See :meth:`superclass method
<.base.GroundShakingIntensityModel.get_mean_and_stddevs>`
for spec of input and result values.
"""
C = self.COEFFS[imt]
mean = (self._compute_magnitude_term(C, ... | See :meth:`superclass method
<.base.GroundShakingIntensityModel.get_mean_and_stddevs>`
for spec of input and result values. |
def density(self):
"""Gives emprical PDF, like np.histogram(...., density=True)"""
h = self.histogram.astype(np.float)
bindifs = np.array(np.diff(self.bin_edges), float)
return h / (bindifs * self.n) | Gives emprical PDF, like np.histogram(...., density=True) |
def add_commit_variables(traj, commit):
"""Adds commit information to the trajectory."""
git_time_value = time.strftime('%Y_%m_%d_%Hh%Mm%Ss', time.localtime(commit.committed_date))
git_short_name = str(commit.hexsha[0:7])
git_commit_name = 'commit_%s_' % git_short_name
git_commit_name = 'git.' + g... | Adds commit information to the trajectory. |
def _get_countdown_for_next_slice(self, spec):
"""Get countdown for next slice's task.
When user sets processing rate, we set countdown to delay task execution.
Args:
spec: model.MapreduceSpec
Returns:
countdown in int.
"""
countdown = 0
if self._processing_limit(spec) != -1:
... | Get countdown for next slice's task.
When user sets processing rate, we set countdown to delay task execution.
Args:
spec: model.MapreduceSpec
Returns:
countdown in int. |
def address(lat, lng, *, raw=False):
"""
DVB Map Address
(GET https://www.dvb.de/apps/map/address)
:param lat: Latitude
:param lng: Longitude
:param raw: Return raw response
:return: Dict of address
"""
try:
lat, lng = wgs_to_gk4(lat, lng)
r = requests.get(
... | DVB Map Address
(GET https://www.dvb.de/apps/map/address)
:param lat: Latitude
:param lng: Longitude
:param raw: Return raw response
:return: Dict of address |
def kill(self, exit_code: Any = None):
"""
Stops the behaviour
Args:
exit_code (object, optional): the exit code of the behaviour (Default value = None)
"""
self._force_kill.set()
if exit_code is not None:
self._exit_code = exit_code
logger... | Stops the behaviour
Args:
exit_code (object, optional): the exit code of the behaviour (Default value = None) |
def start_scan(self, timeout_sec=TIMEOUT_SEC):
"""Start scanning for BLE devices."""
get_provider()._central_manager.scanForPeripheralsWithServices_options_(None, None)
self._is_scanning = True | Start scanning for BLE devices. |
def giflogo(self,id,title=None,scale=0.8,info_str=''):
"""
m.giflogo(id,title=None,scale=0.8) -- (Requires seqlogo package) Make a gif sequence logo
"""
return giflogo(self,id,title,scale) | m.giflogo(id,title=None,scale=0.8) -- (Requires seqlogo package) Make a gif sequence logo |
async def get_frozen(self, *args, **kwargs):
"""
Get frozen users balance
Accepts:
- uid [integer] (users id)
- types [list | string] (array with needed types or "all")
Returns:
{
type [string] (blockchain type): amount
}
"""
super().validate(*args, **kwargs)
if kwargs.get("message"):
... | Get frozen users balance
Accepts:
- uid [integer] (users id)
- types [list | string] (array with needed types or "all")
Returns:
{
type [string] (blockchain type): amount
} |
def __assert_false(returned):
'''
Test if an boolean is False
'''
result = "Pass"
if isinstance(returned, str):
try:
returned = bool(returned)
except ValueError:
raise
try:
assert (returned is False), "{0... | Test if an boolean is False |
def ValidateDate(date, column_name=None, problems=None):
"""
Validates a non-required date string value using IsValidDate():
- if invalid adds InvalidValue error (if problems accumulator is provided)
- an empty date string is regarded as valid! Otherwise we might end up
with many duplicate errors beca... | Validates a non-required date string value using IsValidDate():
- if invalid adds InvalidValue error (if problems accumulator is provided)
- an empty date string is regarded as valid! Otherwise we might end up
with many duplicate errors because of the required field checks. |
def _validate_input_para(self, para, column_names):
""" Convert the input classificaton para to the correct df column name
Parameters
----------
para : string
column_names : list of strings
Returns
-------
validated_para : string
Converted ... | Convert the input classificaton para to the correct df column name
Parameters
----------
para : string
column_names : list of strings
Returns
-------
validated_para : string
Converted to the case used in the country file |
def is_subdomains_enabled(blockstack_opts):
"""
Can we do subdomain operations?
"""
if not is_atlas_enabled(blockstack_opts):
log.debug("Subdomains are disabled")
return False
if 'subdomaindb_path' not in blockstack_opts:
log.debug("Subdomains are disabled: no 'subdomaindb_p... | Can we do subdomain operations? |
def _initialize_integrity_checkers(self, options):
# type: (Descriptor, blobxfer.models.options.Upload) -> None
"""Initialize file integrity checkers
:param Descriptor self: this
:param blobxfer.models.options.Upload options: upload options
"""
if self._ase.is_encrypted:
... | Initialize file integrity checkers
:param Descriptor self: this
:param blobxfer.models.options.Upload options: upload options |
def debug_sql(sql: str, *args: Any) -> None:
"""Writes SQL and arguments to the log."""
log.debug("SQL: %s" % sql)
if args:
log.debug("Args: %r" % args) | Writes SQL and arguments to the log. |
def put_path(self, path):
"""
Given path identify in which environment the path belong to and
append it.
"""
if self.is_package(path):
logger.debug('PYTHON PACKAGE: {}'.format(path))
self.python_paths.append(path.parent)
site.addsitedir... | Given path identify in which environment the path belong to and
append it. |
def show_slug_with_level(context, page, lang=None, fallback=True):
"""Display slug with level by language."""
if not lang:
lang = context.get('lang', pages_settings.PAGE_DEFAULT_LANGUAGE)
page = get_page_from_string_or_id(page, lang)
if not page:
return ''
return {'content': page.s... | Display slug with level by language. |
def add_option(self, opts, dest, action=None, nargs=1, const=None,
obj=None):
"""Adds a new option named `dest` to the parser. The destination
is not inferred (unlike with optparse) and needs to be explicitly
provided. Action can be any of ``store``, ``store_const``,
... | Adds a new option named `dest` to the parser. The destination
is not inferred (unlike with optparse) and needs to be explicitly
provided. Action can be any of ``store``, ``store_const``,
``append``, ``appnd_const`` or ``count``.
The `obj` can be used to identify the option in the orde... |
def on(self,
*qubits: raw_types.Qid) -> 'SingleQubitPauliStringGateOperation':
"""Returns an application of this gate to the given qubits.
Args:
*qubits: The collection of qubits to potentially apply the gate to.
"""
if len(qubits) != 1:
raise ValueErr... | Returns an application of this gate to the given qubits.
Args:
*qubits: The collection of qubits to potentially apply the gate to. |
def _bucket_time(self, event_time):
"""
The seconds since epoch that represent a computed bucket.
An event bucket is the time of the earliest possible event for
that `bucket_width`. Example: if `bucket_width =
timedelta(minutes=10)`, bucket times will be the number of seconds
since epoch at 12... | The seconds since epoch that represent a computed bucket.
An event bucket is the time of the earliest possible event for
that `bucket_width`. Example: if `bucket_width =
timedelta(minutes=10)`, bucket times will be the number of seconds
since epoch at 12:00, 12:10, ... on each day. |
def register_logger(self, logger):
"""
Register a new logger.
"""
handler = CommandHandler(self)
handler.setFormatter(CommandFormatter())
logger.handlers = [handler]
logger.propagate = False
output = self.output
level = logging.WARNING
if ... | Register a new logger. |
def _transfer_data(self, remote_path, data):
"""
Used by the base _execute_module(), and in <2.4 also by the template
action module, and probably others.
"""
if isinstance(data, dict):
data = jsonify(data)
if not isinstance(data, bytes):
data = to_... | Used by the base _execute_module(), and in <2.4 also by the template
action module, and probably others. |
def getquerydict(self, sep='&', encoding='utf-8', errors='strict'):
"""Split the query component into individual `name=value` pairs
separated by `sep` and return a dictionary of query variables.
The dictionary keys are the unique query variable names and
the values are lists of values fo... | Split the query component into individual `name=value` pairs
separated by `sep` and return a dictionary of query variables.
The dictionary keys are the unique query variable names and
the values are lists of values for each name. |
def on_resize(self, width, height):
"""
Handle resized windows.
"""
width, height = self._update_perspective(width, height)
self.scene.camera.resolution = (width, height)
self.view['ball'].resize(self.scene.camera.resolution)
self.scene.camera.transform = self.vie... | Handle resized windows. |
def get_results(self, gene_list):
"""Enrichr API"""
ADDLIST_URL = 'http://amp.pharm.mssm.edu/%sEnrichr/addList'%self._organism
job_id = self.send_genes(gene_list, ADDLIST_URL)
user_list_id = job_id['userListId']
RESULTS_URL = 'http://amp.pharm.mssm.edu/%sEnrichr/export'%self._or... | Enrichr API |
def make_datastore_query(self, cursor=None):
"""Returns a datastore.Query that generates all namespaces in the range.
Args:
cursor: start cursor for the query.
Returns:
A datastore.Query instance that generates db.Keys for each namespace in
the NamespaceRange.
"""
filters = {}
... | Returns a datastore.Query that generates all namespaces in the range.
Args:
cursor: start cursor for the query.
Returns:
A datastore.Query instance that generates db.Keys for each namespace in
the NamespaceRange. |
def trace_grpc(tracer=None):
"""Integrate with gRPC."""
# Wrap google.cloud._helpers.make_secure_channel
make_secure_channel_func = getattr(_helpers, MAKE_SECURE_CHANNEL)
make_secure_channel_wrapped = wrap_make_secure_channel(
make_secure_channel_func, tracer)
setattr(
_helpers,
... | Integrate with gRPC. |
def abi_splitext(filename):
"""
Split the ABINIT extension from a filename.
"Extension" are found by searching in an internal database.
Returns "(root, ext)" where ext is the registered ABINIT extension
The final ".nc" is included (if any)
>>> assert abi_splitext("foo_WFK") == ('foo_', 'WFK')
... | Split the ABINIT extension from a filename.
"Extension" are found by searching in an internal database.
Returns "(root, ext)" where ext is the registered ABINIT extension
The final ".nc" is included (if any)
>>> assert abi_splitext("foo_WFK") == ('foo_', 'WFK')
>>> assert abi_splitext("/home/guido... |
def load(self, filename):
"""Load a result from the given JSON file."""
LOGGER.info("Loading result from '%s'.", filename)
if filename.endswith(".gz"):
with gzip.open(filename, "rb") as file_handle:
result = MemoteResult(
json.loads(file_handle.rea... | Load a result from the given JSON file. |
def acquire_metadata(self):
"""
Handles the acquisition of metadata for both collection mode and single
mode, uses the metadata methods belonging to the article's publisher
attribute.
"""
#For space economy
publisher = self.article.publisher
if self.colle... | Handles the acquisition of metadata for both collection mode and single
mode, uses the metadata methods belonging to the article's publisher
attribute. |
def get(self, counter):
"""
Gets pipeline instance object.
:param counter pipeline counter:
:return: A pipeline instance object :class:`yagocd.resources.pipeline.PipelineInstance`.
:rtype: yagocd.resources.pipeline.PipelineInstance
"""
return self._pipeline.get(n... | Gets pipeline instance object.
:param counter pipeline counter:
:return: A pipeline instance object :class:`yagocd.resources.pipeline.PipelineInstance`.
:rtype: yagocd.resources.pipeline.PipelineInstance |
def __execute(model, iteration_number):
"""
Execute a simulation model
:param model: a configured diffusion model
:param iteration_number: number of iterations
:return: computed trends
"""
iterations = model.iteration_bunch(iteration_number, False)
trends = model.build_trends(iterations... | Execute a simulation model
:param model: a configured diffusion model
:param iteration_number: number of iterations
:return: computed trends |
def in_(self, value):
"""
Sets the operator type to Query.Op.IsIn and sets the value
to the inputted value.
:param value <variant>
:return <Query>
:usage |>>> from orb import Query as Q
|>>> query = Q('tes... | Sets the operator type to Query.Op.IsIn and sets the value
to the inputted value.
:param value <variant>
:return <Query>
:usage |>>> from orb import Query as Q
|>>> query = Q('test').isIn([1,2])
|>>> p... |
def get_relationships_by_genus_type_for_source_on_date(self, source_id, relationship_genus_type, from_, to):
"""Gets a ``RelationshipList`` corresponding to the given peer ``Id`` and relationship genus ``Type`` and effective during the entire given date range inclusive but not confined to the date range.
... | Gets a ``RelationshipList`` corresponding to the given peer ``Id`` and relationship genus ``Type`` and effective during the entire given date range inclusive but not confined to the date range.
arg: source_id (osid.id.Id): a peer ``Id``
arg: relationship_genus_type (osid.type.Type): a relationshi... |
def write_points(self,
points,
time_precision=None,
database=None,
retention_policy=None,
tags=None,
batch_size=None,
protocol='json',
consistency=None
... | Write to multiple time series names.
:param points: the list of points to be written in the database
:type points: list of dictionaries, each dictionary represents a point
:type points: (if protocol is 'json') list of dicts, where each dict
represents... |
def follow(self, login):
"""Make the authenticated user follow login.
:param str login: (required), user to follow
:returns: bool
"""
resp = False
if login:
url = self._build_url('user', 'following', login)
resp = self._boolean(self._put(url), 204... | Make the authenticated user follow login.
:param str login: (required), user to follow
:returns: bool |
def _pluck_provider_state(raw_provider_state: Dict) -> ProviderState:
"""
>>> _pluck_provider_state({'name': 'there is an egg'})
ProviderState(descriptor='there is an egg', params=None)
>>> _pluck_provider_state({'name': 'there is an egg called', 'params': {'name': 'humpty'}})
ProviderState(descrip... | >>> _pluck_provider_state({'name': 'there is an egg'})
ProviderState(descriptor='there is an egg', params=None)
>>> _pluck_provider_state({'name': 'there is an egg called', 'params': {'name': 'humpty'}})
ProviderState(descriptor='there is an egg called', params={'name': 'humpty'}) |
def job_details(job_id, connection=None):
"""Returns the job data with its scheduled timestamp.
:param job_id: the ID of the job to retrieve."""
if connection is None:
connection = r
data = connection.hgetall(job_key(job_id))
job_data = {'id': job_id, 'schedule_at': int(connection.zscore(R... | Returns the job data with its scheduled timestamp.
:param job_id: the ID of the job to retrieve. |
def urls(self, key, value):
"""Populate the ``8564`` MARC field.
Also populate the ``FFT`` field through side effects.
"""
def _is_preprint(value):
return value.get('y', '').lower() == 'preprint'
def _is_fulltext(value):
return value['u'].endswith('.pdf') and value['u'].startswith(... | Populate the ``8564`` MARC field.
Also populate the ``FFT`` field through side effects. |
def add_broadcast_message(self, rawtx, message, sender_wif,
dust_limit=common.DUST_LIMIT):
"""TODO add docstring"""
tx = deserialize.tx(rawtx)
message = deserialize.unicode_str(message)
sender_key = deserialize.key(self.testnet, sender_wif)
tx = cont... | TODO add docstring |
def effect_associated_with_protein_coding_gene(effect):
"""
Parameters
----------
effect : subclass of MutationEffect
Returns True if effect is associated with a gene and that gene
has a protein_coding biotype.
"""
return apply_to_gene_if_exists(
effect=effect,
fn=lambda... | Parameters
----------
effect : subclass of MutationEffect
Returns True if effect is associated with a gene and that gene
has a protein_coding biotype. |
def clipandmerge_alignment_plot (self):
""" Make the HighCharts HTML to plot the duplication rates """
# Specify the order of the different possible categories
keys = OrderedDict()
keys['merged_reads'] = { 'name': 'Merged Reads' }
keys['usable_not_merged_forward'] = { 'name': 'U... | Make the HighCharts HTML to plot the duplication rates |
def makeblastdb(self):
"""
Makes blast database files from targets as necessary
"""
# Iterate through the samples to set the bait file.
for sample in self.runmetadata.samples:
if sample.general.bestassemblyfile != 'NA':
# Remove the file extension
... | Makes blast database files from targets as necessary |
def compute_merkle_tree(items: Iterable[bytes]) -> MerkleTree:
""" Calculates the merkle root for a given list of items """
if not all(isinstance(l, bytes) and len(l) == 32 for l in items):
raise ValueError('Not all items are hashes')
leaves = sorted(items)
if len(leaves) == 0:
return ... | Calculates the merkle root for a given list of items |
def update_settings(self, integration_id, settings):
"""Updates settings for given integration."""
(integration, created) = self.get_or_create(integration_id=integration_id)
try:
current_settings = json.loads(integration.settings)
except ValueError:
current_sett... | Updates settings for given integration. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.