code stringlengths 75 104k | docstring stringlengths 1 46.9k |
|---|---|
def push_channel(self, content, channel, content_url=None):
'''Push a notification to a Pushed channel.
Param: content -> content of Pushed notification message
channel -> string identifying a Pushed channel
content_url (optional) -> enrich message with URL
Returns... | Push a notification to a Pushed channel.
Param: content -> content of Pushed notification message
channel -> string identifying a Pushed channel
content_url (optional) -> enrich message with URL
Returns Shipment ID as string |
def singleton(cls):
"""
See <Singleton> design pattern for detail: http://www.oodesign.com/singleton-pattern.html
Python <Singleton> reference: http://stackoverflow.com/questions/6760685/creating-a-singleton-in-python
Recommend use Singleton as a metaclass
Usage:
@singleton
class My... | See <Singleton> design pattern for detail: http://www.oodesign.com/singleton-pattern.html
Python <Singleton> reference: http://stackoverflow.com/questions/6760685/creating-a-singleton-in-python
Recommend use Singleton as a metaclass
Usage:
@singleton
class MyClass(object):
pass |
def remove_ancestors_of(self, node):
"""Remove all of the ancestor operation nodes of node."""
if isinstance(node, int):
warnings.warn('Calling remove_ancestors_of() with a node id is deprecated,'
' use a DAGNode instead',
DeprecationWarnin... | Remove all of the ancestor operation nodes of node. |
def _LegacyCheckHashesWithFileStore(self):
"""Check all queued up hashes for existence in file store (legacy).
Hashes which do not exist in the file store will be downloaded. This
function flushes the entire queue (self.state.pending_hashes) in order to
minimize the round trips to the file store.
... | Check all queued up hashes for existence in file store (legacy).
Hashes which do not exist in the file store will be downloaded. This
function flushes the entire queue (self.state.pending_hashes) in order to
minimize the round trips to the file store.
If a file was found in the file store it is copied... |
def lookup(self, query=''):
"""looks up all contacts where name or address match query"""
res = []
query = re.compile('.*%s.*' % re.escape(query), self.reflags)
for name, email in self.get_contacts():
if query.match(name) or query.match(email):
res.append((nam... | looks up all contacts where name or address match query |
def _get_image_workaround_seek(self, idx):
"""Same as __getitem__ but seek through the video beforehand
This is a workaround for an all-zero image returned by `imageio`.
"""
warnings.warn("imageio workaround used!")
cap = self.video_handle
mult = 50
for ii in ran... | Same as __getitem__ but seek through the video beforehand
This is a workaround for an all-zero image returned by `imageio`. |
def convert_units(self, desired, guess=False):
"""
Convert the units of the mesh into a specified unit.
Parameters
----------
desired : string
Units to convert to (eg 'inches')
guess : boolean
If self.units are not defined should we
guess th... | Convert the units of the mesh into a specified unit.
Parameters
----------
desired : string
Units to convert to (eg 'inches')
guess : boolean
If self.units are not defined should we
guess the current units of the document and then convert? |
def mine(self): # pragma: no cover
"""
Search for domain or URL related to the original URL or domain.
:return: The mined domains or URL.
:rtype: dict
"""
if PyFunceble.CONFIGURATION["mining"]:
# The mining is activated.
try:
# ... | Search for domain or URL related to the original URL or domain.
:return: The mined domains or URL.
:rtype: dict |
def _write_comparison_plot_table(spid, models, options, core_results,
fit_results):
"""
Notes
-----
Only applies to analysis using functions from empirical in which models are
also given.
"""
# TODO: Clean up sorting, may not work if SAR x out of order, e.g.... | Notes
-----
Only applies to analysis using functions from empirical in which models are
also given. |
def _pload(offset, size):
""" Generic parameter loading.
Emmits output code for setting IX at the right location.
size = Number of bytes to load:
1 => 8 bit value
2 => 16 bit value / string
4 => 32 bit value / f16 value
5 => 40 bit value
"""
output = []
indirect ... | Generic parameter loading.
Emmits output code for setting IX at the right location.
size = Number of bytes to load:
1 => 8 bit value
2 => 16 bit value / string
4 => 32 bit value / f16 value
5 => 40 bit value |
def iterfd(fd):
'''
Generator which unpacks a file object of msgpacked content.
Args:
fd: File object to consume data from.
Notes:
String objects are decoded using utf8 encoding. In order to handle
potentially malformed input, ``unicode_errors='surrogatepass'`` is set
... | Generator which unpacks a file object of msgpacked content.
Args:
fd: File object to consume data from.
Notes:
String objects are decoded using utf8 encoding. In order to handle
potentially malformed input, ``unicode_errors='surrogatepass'`` is set
to allow decoding bad input ... |
def toggle(self, rows):
'Toggle selection of given `rows`.'
for r in Progress(rows, 'toggling', total=len(self.rows)):
if not self.unselectRow(r):
self.selectRow(r) | Toggle selection of given `rows`. |
def get_index(self, field_name, catalog):
"""Returns the index of the catalog for the given field_name, if any
"""
index = catalog.Indexes.get(field_name, None)
if not index and field_name == "Title":
# Legacy
return self.get_index("sortable_title", catalog)
... | Returns the index of the catalog for the given field_name, if any |
def dirsplit(path):
r"""
Args:
path (str):
Returns:
list: components of the path
CommandLine:
python -m utool.util_path --exec-dirsplit
Example:
>>> # DISABLE_DOCTEST
>>> from utool.util_path import * # NOQA
>>> paths = []
>>> paths.append(... | r"""
Args:
path (str):
Returns:
list: components of the path
CommandLine:
python -m utool.util_path --exec-dirsplit
Example:
>>> # DISABLE_DOCTEST
>>> from utool.util_path import * # NOQA
>>> paths = []
>>> paths.append('E:/window file/foo')
... |
def get_token_func():
"""
This function makes a call to AAD to fetch an OAuth token
:return: the OAuth token and the interval to wait before refreshing it
"""
print("{}: token updater was triggered".format(datetime.datetime.now()))
# in this example, the OAuth token is o... | This function makes a call to AAD to fetch an OAuth token
:return: the OAuth token and the interval to wait before refreshing it |
def list_all_customers(cls, **kwargs):
"""List Customers
Return a list of Customers
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async=True
>>> thread = api.list_all_customers(async=True)
>>> result = thread.g... | List Customers
Return a list of Customers
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async=True
>>> thread = api.list_all_customers(async=True)
>>> result = thread.get()
:param async bool
:param int... |
def libvlc_media_get_mrl(p_md):
'''Get the media resource locator (mrl) from a media descriptor object.
@param p_md: a media descriptor object.
@return: string with mrl of media descriptor object.
'''
f = _Cfunctions.get('libvlc_media_get_mrl', None) or \
_Cfunction('libvlc_media_get_mrl', (... | Get the media resource locator (mrl) from a media descriptor object.
@param p_md: a media descriptor object.
@return: string with mrl of media descriptor object. |
def update_url(self, url=None, regex=None):
"""
Accepts a fully-qualified url, or regex.
Returns True if successful, False if not successful.
"""
if not url and not regex:
raise ValueError("Neither a url or regex was provided to update_url.")
headers = {
... | Accepts a fully-qualified url, or regex.
Returns True if successful, False if not successful. |
def _get_component_from_result(self, result, lookup):
"""
Helper function to get a particular address component from a Google result.
Since the address components in results are an array of objects containing a types array,
we have to search for a particular component rather than being ... | Helper function to get a particular address component from a Google result.
Since the address components in results are an array of objects containing a types array,
we have to search for a particular component rather than being able to look it up directly.
Returns the first match, so this sho... |
def update_machine_state(state_path):
"""Update the machine state using the provided state declaration."""
charmhelpers.contrib.templating.contexts.juju_state_to_yaml(
salt_grains_path)
subprocess.check_call([
'salt-call',
'--local',
'state.template',
state_path,
... | Update the machine state using the provided state declaration. |
def friendly_load(parser, token):
"""
Tries to load a custom template tag set. Non existing tag libraries
are ignored.
This means that, if used in conjunction with ``if_has_tag``, you can try to
load the comments template tag library to enable comments even if the
comments framework is not inst... | Tries to load a custom template tag set. Non existing tag libraries
are ignored.
This means that, if used in conjunction with ``if_has_tag``, you can try to
load the comments template tag library to enable comments even if the
comments framework is not installed.
For example::
{% load fri... |
def _update_pwm(self):
"""Update the pwm values of the driver regarding the current state."""
if self._is_on:
values = self._get_pwm_values()
else:
values = [0] * len(self._driver.pins)
self._driver.set_pwm(values) | Update the pwm values of the driver regarding the current state. |
def fill_package(app_name, build_dir=None, install_dir=None):
"""
Creates the theme package (.zip) from templates and optionally
assets installed in the ``build_dir``.
"""
zip_path = os.path.join(install_dir, '%s.zip' % app_name)
with zipfile.ZipFile(zip_path, 'w') as zip_file:
fill_pack... | Creates the theme package (.zip) from templates and optionally
assets installed in the ``build_dir``. |
def _path_to_id(path):
"""
Name of the root directory is used as ``<packageid>`` in ``info.xml``.
This function makes sure, that :func:`os.path.basename` doesn't return
blank string in case that there is `/` at the end of the `path`.
Args:
path (str): Path to the root directory.
Retur... | Name of the root directory is used as ``<packageid>`` in ``info.xml``.
This function makes sure, that :func:`os.path.basename` doesn't return
blank string in case that there is `/` at the end of the `path`.
Args:
path (str): Path to the root directory.
Returns:
str: Basename of the `p... |
def as_dtype(type_value):
"""Converts the given `type_value` to a `DType`.
Args:
type_value: A value that can be converted to a `tf.DType` object. This may
currently be a `tf.DType` object, a [`DataType`
enum](https://www.tensorflow.org/code/tensorflow/core/framework/types.proto),
... | Converts the given `type_value` to a `DType`.
Args:
type_value: A value that can be converted to a `tf.DType` object. This may
currently be a `tf.DType` object, a [`DataType`
enum](https://www.tensorflow.org/code/tensorflow/core/framework/types.proto),
a string type name, or a `numpy.... |
def _make_concept(self, entity):
"""Return Concept from a Hume entity."""
# Use the canonical name as the name of the Concept by default
name = self._sanitize(entity['canonicalName'])
# But if there is a trigger head text, we prefer that since
# it almost always results in a clea... | Return Concept from a Hume entity. |
def populate(self, compound_dict=None, x=1, y=1, z=1):
"""Expand lattice and create compound from lattice.
populate will expand lattice based on user input. The user must also
pass in a dictionary that contains the keys that exist in the
basis_dict. The corresponding Compound will be th... | Expand lattice and create compound from lattice.
populate will expand lattice based on user input. The user must also
pass in a dictionary that contains the keys that exist in the
basis_dict. The corresponding Compound will be the full lattice
returned to the user.
If no dictio... |
def projR(gamma, p):
"""return the KL projection on the row constrints """
return np.multiply(gamma.T, p / np.maximum(np.sum(gamma, axis=1), 1e-10)).T | return the KL projection on the row constrints |
def _normalize_histogram2d(self, counts, type):
"""Normalize the values of the counts for a 2D histogram.
This normalizes the values of a numpy array to the range 0-255.
:param counts: a NumPy array which is to be rescaled.
:param type: either 'bw' or 'reverse_bw'.
"""
... | Normalize the values of the counts for a 2D histogram.
This normalizes the values of a numpy array to the range 0-255.
:param counts: a NumPy array which is to be rescaled.
:param type: either 'bw' or 'reverse_bw'. |
def _buildElementTree(self,):
"""Turn object into an ElementTree
"""
t_elt = ctree.Element(self.name)
for k,v in [ (key,value) for key,value in self.__dict__.items() if key != 'name']: # Excluding name from list of items
if v and v != 'false' :
t_elt.set(k if... | Turn object into an ElementTree |
def _tarboton_slopes_directions(data, dX, dY, facets, ang_adj):
"""
Calculate the slopes and directions based on the 8 sections from
Tarboton http://www.neng.usu.edu/cee/faculty/dtarb/96wr03137.pdf
"""
shp = np.array(data.shape) - 1
direction = np.full(data.shape, FLAT_ID_INT, 'float64')
m... | Calculate the slopes and directions based on the 8 sections from
Tarboton http://www.neng.usu.edu/cee/faculty/dtarb/96wr03137.pdf |
def launch_tor(config, reactor,
tor_binary=None,
progress_updates=None,
connection_creator=None,
timeout=None,
kill_on_stderr=True,
stdout=None, stderr=None):
"""
Deprecated; use launch() instead.
See also controller.... | Deprecated; use launch() instead.
See also controller.py |
def pupv_to_vRvz(pu,pv,u,v,delta=1.,oblate=False):
"""
NAME:
pupv_to_vRvz
PURPOSE:
calculate cylindrical vR and vz from momenta in prolate or oblate confocal u and v coordinates for a given focal length delta
INPUT:
pu - u momentum
pv - v momentum
u - u coordina... | NAME:
pupv_to_vRvz
PURPOSE:
calculate cylindrical vR and vz from momenta in prolate or oblate confocal u and v coordinates for a given focal length delta
INPUT:
pu - u momentum
pv - v momentum
u - u coordinate
v - v coordinate
delta= focus
oblate... |
def upload_to_s3(self, key, filename):
"""
Set the content type and gzip headers if applicable
and upload the item to S3
"""
extra_args = {'ACL': self.acl}
# determine the mimetype of the file
guess = mimetypes.guess_type(filename)
content_type = guess[0]
... | Set the content type and gzip headers if applicable
and upload the item to S3 |
def get_cutoff(value: float, cutoff: Optional[float] = None) -> int:
"""Assign if a value is greater than or less than a cutoff."""
cutoff = cutoff if cutoff is not None else 0
if value > cutoff:
return 1
if value < (-1 * cutoff):
return - 1
return 0 | Assign if a value is greater than or less than a cutoff. |
def _get_comments(session, group_or_user_id, wall_id):
"""
https://vk.com/dev/wall.getComments
"""
return session.fetch_items("wall.getComments", Comment.from_json, count=100, owner_id=group_or_user_id, post_id=wall_id, need_likes=1) | https://vk.com/dev/wall.getComments |
def leaves(self):
""" Returns a :class:`QuerySet` of all leaf nodes (nodes with no
children).
:return: A :class:`QuerySet` of all leaf nodes (nodes with no
children).
"""
# We need to read the _cte_node_children attribute, so ensure it exists.
sel... | Returns a :class:`QuerySet` of all leaf nodes (nodes with no
children).
:return: A :class:`QuerySet` of all leaf nodes (nodes with no
children). |
def union(self, *iterables):
"""
Return a new SortedSet with elements from the set and all *iterables*.
"""
return self.__class__(chain(iter(self), *iterables), key=self._key) | Return a new SortedSet with elements from the set and all *iterables*. |
def _register(self, name):
"""
@Api private
Add new :py:class:`TemplateHook` into the registry
:param str name: Hook name
:return: Instance of :py:class:`TemplateHook`
:rtype: :py:class:`TemplateHook`
"""
templatehook = TemplateHook()
self._regist... | @Api private
Add new :py:class:`TemplateHook` into the registry
:param str name: Hook name
:return: Instance of :py:class:`TemplateHook`
:rtype: :py:class:`TemplateHook` |
def make_shell_logfile_data_url(host, shell_port, instance_id, offset, length):
"""
Make the url for log-file data in heron-shell
from the info stored in stmgr.
"""
return "http://%s:%d/filedata/log-files/%s.log.0?offset=%s&length=%s" % \
(host, shell_port, instance_id, offset, length) | Make the url for log-file data in heron-shell
from the info stored in stmgr. |
def jinja_fragment_extension(tag, endtag=None, name=None, tag_only=False, allow_args=True, callblock_args=None):
"""Decorator to easily create a jinja extension which acts as a fragment.
"""
if endtag is None:
endtag = "end" + tag
def decorator(f):
def parse(self, parser):
l... | Decorator to easily create a jinja extension which acts as a fragment. |
def align_epi_anat(anatomy,epi_dsets,skull_strip_anat=True):
''' aligns epis to anatomy using ``align_epi_anat.py`` script
:epi_dsets: can be either a string or list of strings of the epi child datasets
:skull_strip_anat: if ``True``, ``anatomy`` will be skull-stripped using the default method
... | aligns epis to anatomy using ``align_epi_anat.py`` script
:epi_dsets: can be either a string or list of strings of the epi child datasets
:skull_strip_anat: if ``True``, ``anatomy`` will be skull-stripped using the default method
The default output suffix is "_al" |
def colors(palette):
"""Example endpoint return a list of colors by palette
This is using docstring for specifications
---
tags:
- colors
parameters:
- name: palette
in: path
type: string
enum: ['all', 'rgb', 'cmyk']
required: true
default: all
... | Example endpoint return a list of colors by palette
This is using docstring for specifications
---
tags:
- colors
parameters:
- name: palette
in: path
type: string
enum: ['all', 'rgb', 'cmyk']
required: true
default: all
description: Which pale... |
def mkCuttingStock(s):
"""mkCuttingStock: convert a bin packing instance into cutting stock format"""
w,q = [],[] # list of different widths (sizes) of items, their quantities
for item in sorted(s):
if w == [] or item != w[-1]:
w.append(item)
q.append(1)
else:
... | mkCuttingStock: convert a bin packing instance into cutting stock format |
def add_listener(self, on_message=None):
"""
Subscribes to this topic. When someone publishes a message on this topic, on_message() function is called if
provided.
:param on_message: (Function), function to be called when a message is published.
:return: (str), a registration id... | Subscribes to this topic. When someone publishes a message on this topic, on_message() function is called if
provided.
:param on_message: (Function), function to be called when a message is published.
:return: (str), a registration id which is used as a key to remove the listener. |
def build_query(self, case_id, query=None, variant_ids=None, category='snv'):
"""Build a mongo query
These are the different query options:
{
'genetic_models': list,
'chrom': str,
'thousand_genomes_frequency': float,
'exac_freq... | Build a mongo query
These are the different query options:
{
'genetic_models': list,
'chrom': str,
'thousand_genomes_frequency': float,
'exac_frequency': float,
'clingen_ngi': int,
'cadd_score': float,
... |
def warn_quirks(message, recommend, pattern, index):
"""Warn quirks."""
import traceback
import bs4 # noqa: F401
# Acquire source code line context
paths = (MODULE, sys.modules['bs4'].__path__[0])
tb = traceback.extract_stack()
previous = None
filename = None
lineno = None
for... | Warn quirks. |
def vsan_datastore_configured(name, datastore_name):
'''
Configures the cluster's VSAN datastore
WARNING: The VSAN datastore is created automatically after the first
ESXi host is added to the cluster; the state assumes that the datastore
exists and errors if it doesn't.
'''
cluster_name, d... | Configures the cluster's VSAN datastore
WARNING: The VSAN datastore is created automatically after the first
ESXi host is added to the cluster; the state assumes that the datastore
exists and errors if it doesn't. |
def TBH(cpu, dest):
"""
Table Branch Halfword causes a PC-relative forward branch using a table of single halfword offsets. A base
register provides a pointer to the table, and a second register supplies an index into the table. The branch
length is twice the value of the halfword return... | Table Branch Halfword causes a PC-relative forward branch using a table of single halfword offsets. A base
register provides a pointer to the table, and a second register supplies an index into the table. The branch
length is twice the value of the halfword returned from the table.
:param ARMv7... |
def hashleftjoin(left, right, key=None, lkey=None, rkey=None, missing=None,
cache=True, lprefix=None, rprefix=None):
"""Alternative implementation of :func:`petl.transform.joins.leftjoin`,
where the join is executed by constructing an in-memory lookup for the
right hand table, then iteratin... | Alternative implementation of :func:`petl.transform.joins.leftjoin`,
where the join is executed by constructing an in-memory lookup for the
right hand table, then iterating over rows from the left hand table.
May be faster and/or more resource efficient where the right table is small
and the left t... |
def write_kwargs_to_attrs(cls, attrs, **kwargs):
"""Writes the given keywords to the given ``attrs``.
If any keyword argument points to a dict, the keyword will point to a
list of the dict's keys. Each key is then written to the attrs with its
corresponding value.
Parameters
... | Writes the given keywords to the given ``attrs``.
If any keyword argument points to a dict, the keyword will point to a
list of the dict's keys. Each key is then written to the attrs with its
corresponding value.
Parameters
----------
attrs : an HDF attrs
Th... |
def search(self, title=None, libtype=None, **kwargs):
""" Searching within a library section is much more powerful. It seems certain
attributes on the media objects can be targeted to filter this search down
a bit, but I havent found the documentation for it.
Example: "studi... | Searching within a library section is much more powerful. It seems certain
attributes on the media objects can be targeted to filter this search down
a bit, but I havent found the documentation for it.
Example: "studio=Comedy%20Central" or "year=1999" "title=Kung Fu" all work. Other... |
def create_linear(num_finite_buckets, width, offset):
"""Creates a new instance of distribution with linear buckets.
Args:
num_finite_buckets (int): initializes number of finite buckets
width (float): initializes the width of each bucket
offset (float): initializes the offset
Return:
... | Creates a new instance of distribution with linear buckets.
Args:
num_finite_buckets (int): initializes number of finite buckets
width (float): initializes the width of each bucket
offset (float): initializes the offset
Return:
:class:`endpoints_management.gen.servicecontrol_v1_mes... |
def uhstack(arrs):
"""Stack arrays in sequence horizontally while preserving units
This is a wrapper around np.hstack that preserves units.
Examples
--------
>>> from unyt import km
>>> a = [1, 2, 3]*km
>>> b = [2, 3, 4]*km
>>> print(uhstack([a, b]))
[1 2 3 2 3 4] km
>>> a = [[... | Stack arrays in sequence horizontally while preserving units
This is a wrapper around np.hstack that preserves units.
Examples
--------
>>> from unyt import km
>>> a = [1, 2, 3]*km
>>> b = [2, 3, 4]*km
>>> print(uhstack([a, b]))
[1 2 3 2 3 4] km
>>> a = [[1],[2],[3]]*km
>>> b =... |
def observable(operator, rho, unfolding, complex=False):
r"""Return an observable ammount.
INPUT:
- ``operator`` - An square matrix representing a hermitian operator \
in thesame basis as the density matrix.
- ``rho`` - A density matrix in unfolded format, or a list of such \
density matrice... | r"""Return an observable ammount.
INPUT:
- ``operator`` - An square matrix representing a hermitian operator \
in thesame basis as the density matrix.
- ``rho`` - A density matrix in unfolded format, or a list of such \
density matrices.
- ``unfolding`` - A mapping from matrix element indic... |
def intersection(self, other):
"""
Returns a new tree of all intervals common to both self and
other.
"""
ivs = set()
shorter, longer = sorted([self, other], key=len)
for iv in shorter:
if iv in longer:
ivs.add(iv)
return Interv... | Returns a new tree of all intervals common to both self and
other. |
def _consolidate_repo_sources(sources):
'''
Consolidate APT sources.
'''
if not isinstance(sources, sourceslist.SourcesList):
raise TypeError(
'\'{0}\' not a \'{1}\''.format(
type(sources),
sourceslist.SourcesList
)
)
consolida... | Consolidate APT sources. |
def init(self):
"Initialize the message-digest and set all fields to zero."
self.length = 0L
self.input = []
# Load magic initialization constants.
self.A = 0x67452301L
self.B = 0xefcdab89L
self.C = 0x98badcfeL
self.D = 0x10325476L | Initialize the message-digest and set all fields to zero. |
def add_states(self, *states):
'''
Add @states.
'''
for state in states:
self.states[state] = EventManagerPlus(self) | Add @states. |
def load_data(filespec, idx=None, logger=None, **kwargs):
"""Load data from a file.
This call is used to load a data item from a filespec (path or URL)
Parameters
----------
filespec : str
The path of the file to load (can be a URL).
idx : int or string (optional)
The index or... | Load data from a file.
This call is used to load a data item from a filespec (path or URL)
Parameters
----------
filespec : str
The path of the file to load (can be a URL).
idx : int or string (optional)
The index or name of the data unit in the file (e.g. an HDU name)
logger... |
def run_work(self):
"""Run attacks and defenses"""
if os.path.exists(LOCAL_EVAL_ROOT_DIR):
sudo_remove_dirtree(LOCAL_EVAL_ROOT_DIR)
self.run_attacks()
self.run_defenses() | Run attacks and defenses |
def move_items(self, from_group, to_group):
"""Take all elements from the from_group and add it to the to_group."""
if from_group not in self.keys() or len(self.groups[from_group]) == 0:
return
self.groups.setdefault(to_group, list()).extend(self.groups.get
... | Take all elements from the from_group and add it to the to_group. |
def _attr_sort_func(model, iter1, iter2, attribute):
"""Internal helper
"""
attr1 = getattr(model[iter1][0], attribute, None)
attr2 = getattr(model[iter2][0], attribute, None)
return cmp(attr1, attr2) | Internal helper |
def _find_usage_security_groups(self):
"""find usage for security groups"""
vpc_count = 0
paginator = self.conn.get_paginator('describe_db_security_groups')
for page in paginator.paginate():
for group in page['DBSecurityGroups']:
if 'VpcId' in group and group... | find usage for security groups |
def diagnose_cluster(
self,
project_id,
region,
cluster_name,
retry=google.api_core.gapic_v1.method.DEFAULT,
timeout=google.api_core.gapic_v1.method.DEFAULT,
metadata=None,
):
"""
Gets cluster diagnostic information. After the operation complet... | Gets cluster diagnostic information. After the operation completes, the
Operation.response field contains ``DiagnoseClusterOutputLocation``.
Example:
>>> from google.cloud import dataproc_v1beta2
>>>
>>> client = dataproc_v1beta2.ClusterControllerClient()
... |
def fetch_access_token(self):
"""
获取 access token
详情请参考 http://mp.weixin.qq.com/wiki/index.php?title=通用接口文档
:return: 返回的 JSON 数据包
"""
return self._fetch_access_token(
url='https://api.weixin.qq.com/cgi-bin/token',
params={
'grant_t... | 获取 access token
详情请参考 http://mp.weixin.qq.com/wiki/index.php?title=通用接口文档
:return: 返回的 JSON 数据包 |
def removi(item, inset):
"""
Remove an item from an integer set.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/removi_c.html
:param item: Item to be removed.
:type item: int
:param inset: Set to be updated.
:type inset: spiceypy.utils.support_types.SpiceCell
"""
assert is... | Remove an item from an integer set.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/removi_c.html
:param item: Item to be removed.
:type item: int
:param inset: Set to be updated.
:type inset: spiceypy.utils.support_types.SpiceCell |
def _get_representative(self, obj):
"""Finds and returns the root of the set containing `obj`."""
if obj not in self._parents:
self._parents[obj] = obj
self._weights[obj] = 1
self._prev_next[obj] = [obj, obj]
self._min_values[obj] = obj
return... | Finds and returns the root of the set containing `obj`. |
def set_finished(self):
"""This stores the number of items that have been pushed, and
transitions the current component to the FINISHED state (which precedes
the STOPPED state). The FINISHED state isn't really necessary unless
methods/hooks are overridden to depend on it, but the coun... | This stores the number of items that have been pushed, and
transitions the current component to the FINISHED state (which precedes
the STOPPED state). The FINISHED state isn't really necessary unless
methods/hooks are overridden to depend on it, but the count must be
stored at one po... |
def parse_keys_and_ranges(i_str, keyfunc, rangefunc):
'''Parse the :class:`from_kvlayer` input string.
This accepts two formats. In the textual format, it accepts any
number of stream IDs in timestamp-docid format, separated by ``,``
or ``;``, and processes those as individual stream IDs. In the
... | Parse the :class:`from_kvlayer` input string.
This accepts two formats. In the textual format, it accepts any
number of stream IDs in timestamp-docid format, separated by ``,``
or ``;``, and processes those as individual stream IDs. In the
binary format, it accepts 20-byte key blobs (16 bytes md5 has... |
def list_versions(self, layer_id):
"""
Filterable list of versions of a layer, always ordered newest to oldest.
If the version’s source supports revisions, you can get a specific revision using
``.filter(data__source__revision=value)``. Specific values depend on the source type.
... | Filterable list of versions of a layer, always ordered newest to oldest.
If the version’s source supports revisions, you can get a specific revision using
``.filter(data__source__revision=value)``. Specific values depend on the source type.
Use ``data__source_revision__lt`` or ``data__source_re... |
def sigma_clipping(date, mag, err, threshold=3, iteration=1):
"""
Remove any fluctuated data points by magnitudes.
Parameters
----------
date : array_like
An array of dates.
mag : array_like
An array of magnitudes.
err : array_like
An array of magnitude errors.
t... | Remove any fluctuated data points by magnitudes.
Parameters
----------
date : array_like
An array of dates.
mag : array_like
An array of magnitudes.
err : array_like
An array of magnitude errors.
threshold : float, optional
Threshold for sigma-clipping.
itera... |
def delete(self, id):
"""
Delete a resource by bson id
:raises: 404 Not Found
:raises: 400 Bad request
:raises: 500 Server Error
"""
try:
response = yield self.client.delete(id)
if response.get("n") > 0:
self.write({"messag... | Delete a resource by bson id
:raises: 404 Not Found
:raises: 400 Bad request
:raises: 500 Server Error |
def get_sequence_rule_mdata():
"""Return default mdata map for SequenceRule"""
return {
'next_assessment_part': {
'element_label': {
'text': 'next assessment part',
'languageTypeId': str(DEFAULT_LANGUAGE_TYPE),
'scriptTypeId': str(DEFAULT_SCRIP... | Return default mdata map for SequenceRule |
def down_capture(returns, factor_returns, **kwargs):
"""
Compute the capture ratio for periods when the benchmark return is negative
Parameters
----------
returns : pd.Series or np.ndarray
Returns of the strategy, noncumulative.
- See full explanation in :func:`~empyrical.stats.cum_... | Compute the capture ratio for periods when the benchmark return is negative
Parameters
----------
returns : pd.Series or np.ndarray
Returns of the strategy, noncumulative.
- See full explanation in :func:`~empyrical.stats.cum_returns`.
factor_returns : pd.Series or np.ndarray
No... |
def _setup_subpix(self,nside=2**16):
"""
Subpixels for random position generation.
"""
# Only setup once...
if hasattr(self,'subpix'): return
# Simulate over full ROI
self.roi_radius = self.config['coords']['roi_radius']
# Setup background spatial stuff... | Subpixels for random position generation. |
def insert_from_segmentlistdict(self, seglists, name, version = None, comment = None, valid=None):
"""
Insert the segments from the segmentlistdict object
seglists as a new list of "active" segments into this
LigolwSegments object. The dictionary's keys are assumed
to provide the instrument name for each seg... | Insert the segments from the segmentlistdict object
seglists as a new list of "active" segments into this
LigolwSegments object. The dictionary's keys are assumed
to provide the instrument name for each segment list. A
new entry will be created in the segment_definer table for
the segment lists, and the dic... |
def assign(self, attrs):
"""Merge new attributes
"""
for k, v in attrs.items():
setattr(self, k, v) | Merge new attributes |
def discretize_wd_style(N, q, F, d, Phi):
"""
TODO: add documentation
New implementation. I'll make this work first, then document.
"""
DEBUG = False
Ts = []
potential = 'BinaryRoche'
r0 = libphoebe.roche_pole(q, F, d, Phi)
# The following is a hack that needs to go!
pot_nam... | TODO: add documentation
New implementation. I'll make this work first, then document. |
def on_service_departure(self, svc_ref):
"""
Called when a service has been unregistered from the framework
:param svc_ref: A service reference
"""
with self._lock:
if svc_ref is self.reference:
# Forget about the service
self._value.u... | Called when a service has been unregistered from the framework
:param svc_ref: A service reference |
def run_friedman_smooth(x, y, span):
"""Run the FORTRAN smoother."""
N = len(x)
weight = numpy.ones(N)
results = numpy.zeros(N)
residuals = numpy.zeros(N)
mace.smooth(x, y, weight, span, 1, 1e-7, results, residuals)
return results, residuals | Run the FORTRAN smoother. |
def forwards(self, orm):
"Write your forwards methods here."
db_table = orm['samples.CohortVariant']._meta.db_table
db.execute('TRUNCATE TABLE "{0}"'.format(db_table))
db.execute('ALTER SEQUENCE "{0}_id_seq" RESTART 1'.format(db_table))
cohorts = list(orm['samples.Cohort'].object... | Write your forwards methods here. |
def ObsBandpass(obstring, graphtable=None, comptable=None, component_dict={}):
"""Generate a bandpass object from observation mode.
If the bandpass consists of multiple throughput files
(e.g., "acs,hrc,f555w"), then `ObsModeBandpass` is returned.
Otherwise, if it consists of a single throughput file
... | Generate a bandpass object from observation mode.
If the bandpass consists of multiple throughput files
(e.g., "acs,hrc,f555w"), then `ObsModeBandpass` is returned.
Otherwise, if it consists of a single throughput file
(e.g., "johnson,v"), then `~pysynphot.spectrum.TabularSpectralElement`
is return... |
def getLayout(kind=None,theme=None,title='',xTitle='',yTitle='',zTitle='',barmode='',bargap=None,bargroupgap=None,
margin=None, dimensions=None, width=None, height=None,
annotations=None,is3d=False,**kwargs):
"""
Generates a plotly Layout
Parameters:
-----------
theme : string
Layout Theme
solar... | Generates a plotly Layout
Parameters:
-----------
theme : string
Layout Theme
solar
pearl
white
title : string
Chart Title
xTitle : string
X Axis Title
yTitle : string
Y Axis Title
zTitle : string
Z Axis Title
Applicable only for 3d charts
barmode : string
Mode when displ... |
def memoized(maxsize=1024):
"""
Momoization decorator for immutable classes and pure functions.
"""
cache = SimpleCache(maxsize=maxsize)
def decorator(obj):
@wraps(obj)
def new_callable(*a, **kw):
def create_new():
return obj(*a, **kw)
key = ... | Momoization decorator for immutable classes and pure functions. |
def build_map_type_validator(item_validator):
"""Return a function which validates that the value is a mapping of
items. The function should return pairs of items that will be
passed to the `dict` constructor.
"""
def validate_mapping(value):
return dict(item_validator(item) for item in vali... | Return a function which validates that the value is a mapping of
items. The function should return pairs of items that will be
passed to the `dict` constructor. |
def calc_remotedemand_v1(self):
"""Estimate the discharge demand of a cross section far downstream.
Required control parameter:
|RemoteDischargeMinimum|
Required derived parameters:
|dam_derived.TOY|
Required flux sequence:
|dam_derived.TOY|
Calculated flux sequence:
|Rem... | Estimate the discharge demand of a cross section far downstream.
Required control parameter:
|RemoteDischargeMinimum|
Required derived parameters:
|dam_derived.TOY|
Required flux sequence:
|dam_derived.TOY|
Calculated flux sequence:
|RemoteDemand|
Basic equation:
:... |
def create_frames(until=None):
"""Create frames available in the JPL files
Args:
until (str): Name of the body you want to create the frame of, and all frames in between.
If ``None`` all the frames available in the .bsp files will be created
Example:
.. code-block:: pytho... | Create frames available in the JPL files
Args:
until (str): Name of the body you want to create the frame of, and all frames in between.
If ``None`` all the frames available in the .bsp files will be created
Example:
.. code-block:: python
# All frames between Earth ... |
def edit_item(self):
"""Edit item"""
index = self.currentIndex()
if not index.isValid():
return
# TODO: Remove hard coded "Value" column number (3 here)
self.edit(index.child(index.row(), 3)) | Edit item |
def _find_cont_fitfunc(fluxes, ivars, contmask, deg, ffunc, n_proc=1):
""" Fit a continuum to a continuum pixels in a segment of spectra
Functional form can be either sinusoid or chebyshev, with specified degree
Parameters
----------
fluxes: numpy ndarray of shape (nstars, npixels)
trainin... | Fit a continuum to a continuum pixels in a segment of spectra
Functional form can be either sinusoid or chebyshev, with specified degree
Parameters
----------
fluxes: numpy ndarray of shape (nstars, npixels)
training set or test set pixel intensities
ivars: numpy ndarray of shape (nstars,... |
def _polar(self):
"""The "hidden" polar axis used for azimuth labels."""
# This will be called inside LambertAxes.__init__ as well as every
# time the axis is cleared, so we need the try/except to avoid having
# multiple hidden axes when `cla` is _manually_ called.
try:
... | The "hidden" polar axis used for azimuth labels. |
def covar_plotter3d_plotly(embedding, rieman_metric, inspect_points_idx,
colors, **kwargs):
"""3 Dimensional Covariance plotter using matplotlib backend."""
def rgb2hex(rgb):
return '#%02x%02x%02x' % tuple(rgb)
return [ plt_data for idx in inspect_points_idx
f... | 3 Dimensional Covariance plotter using matplotlib backend. |
def make_input_from_plain_string(sentence_id: SentenceId, string: str) -> TranslatorInput:
"""
Returns a TranslatorInput object from a plain string.
:param sentence_id: Sentence id.
:param string: An input string.
:return: A TranslatorInput.
"""
return TranslatorInput(sentence_id, tokens=li... | Returns a TranslatorInput object from a plain string.
:param sentence_id: Sentence id.
:param string: An input string.
:return: A TranslatorInput. |
def delete(self, name):
'''
Delete time series by name across all intervals. Returns the number of
records deleted.
'''
conn = self._client.connect()
conn.execute( self._table.delete().where(self._table.c.name==name) ) | Delete time series by name across all intervals. Returns the number of
records deleted. |
def max_profit_optimized(prices):
"""
input: [7, 1, 5, 3, 6, 4]
diff : [X, -6, 4, -2, 3, -2]
:type prices: List[int]
:rtype: int
"""
cur_max, max_so_far = 0, 0
for i in range(1, len(prices)):
cur_max = max(0, cur_max + prices[i] - prices[i-1])
max_so_far = max(max_so_far,... | input: [7, 1, 5, 3, 6, 4]
diff : [X, -6, 4, -2, 3, -2]
:type prices: List[int]
:rtype: int |
def find_view_function(module_name, function_name, fallback_app=None, fallback_template=None, verify_decorator=True):
'''
Finds a view function, class-based view, or template view.
Raises ViewDoesNotExist if not found.
'''
dmp = apps.get_app_config('django_mako_plus')
# I'm first calling find_s... | Finds a view function, class-based view, or template view.
Raises ViewDoesNotExist if not found. |
def get_timedelta_str(timedelta, exclude_zeros=False):
"""
get_timedelta_str
Returns:
str: timedelta_str, formated time string
References:
http://stackoverflow.com/questions/8906926/formatting-python-timedelta-objects
Example:
>>> # ENABLE_DOCTEST
>>> from utool.ut... | get_timedelta_str
Returns:
str: timedelta_str, formated time string
References:
http://stackoverflow.com/questions/8906926/formatting-python-timedelta-objects
Example:
>>> # ENABLE_DOCTEST
>>> from utool.util_time import * # NOQA
>>> timedelta = get_unix_timedelta... |
def from_response(cls, response, attrs):
""" Create an index from returned Dynamo data """
proj = response['Projection']
index = cls(proj['ProjectionType'], response['IndexName'],
attrs[response['KeySchema'][1]['AttributeName']],
proj.get('NonKeyAttributes... | Create an index from returned Dynamo data |
def patch_clean_fields(model):
"""
Patch clean_fields method to handle different form types submission.
"""
old_clean_fields = model.clean_fields
def new_clean_fields(self, exclude=None):
if hasattr(self, '_mt_form_pending_clear'):
# Some form translation fields has been marked ... | Patch clean_fields method to handle different form types submission. |
def get(self, name):
"""Returns an interface as a set of key/value pairs
Args:
name (string): the interface identifier to retrieve the from
the configuration
Returns:
A Python dictionary object of key/value pairs that represent
the current co... | Returns an interface as a set of key/value pairs
Args:
name (string): the interface identifier to retrieve the from
the configuration
Returns:
A Python dictionary object of key/value pairs that represent
the current configuration for the specified no... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.