code stringlengths 75 104k | docstring stringlengths 1 46.9k |
|---|---|
def clear_assessments(self):
"""Clears the assessments.
raise: NoAccess - ``Metadata.isRequired()`` or
``Metadata.isReadOnly()`` is ``true``
*compliance: mandatory -- This method must be implemented.*
"""
# Implemented from template for osid.learning.ActivityFo... | Clears the assessments.
raise: NoAccess - ``Metadata.isRequired()`` or
``Metadata.isReadOnly()`` is ``true``
*compliance: mandatory -- This method must be implemented.* |
def mask_hash(hash, show=6, char="*"):
"""
Return the given hash, with only the first ``show`` number shown. The
rest are masked with ``char`` for security reasons.
"""
masked = hash[:show]
masked += char * len(hash[show:])
return masked | Return the given hash, with only the first ``show`` number shown. The
rest are masked with ``char`` for security reasons. |
def save(self, *args, **kwargs):
"""
Validate that the rating falls between the min and max values.
"""
valid = map(str, settings.RATINGS_RANGE)
if str(self.value) not in valid:
raise ValueError("Invalid rating. %s is not in %s" % (self.value,
", ".joi... | Validate that the rating falls between the min and max values. |
def given_i_am_logged_in(context, username):
"""
:type username: str
:type context: behave.runner.Context
"""
user = get_user_model().objects.get(username=username)
context.apiClient.force_authenticate(user=user) | :type username: str
:type context: behave.runner.Context |
def parse_table(fq_table: str) -> Tuple[str, str]:
"""Parse a tablename into tuple(<schema>, <table>).
Schema defaults to doc if the table name doesn't contain a schema.
>>> parse_table('x.users')
('x', 'users')
>>> parse_table('users')
('doc', 'users')
"""
parts = fq_table.split('.')... | Parse a tablename into tuple(<schema>, <table>).
Schema defaults to doc if the table name doesn't contain a schema.
>>> parse_table('x.users')
('x', 'users')
>>> parse_table('users')
('doc', 'users') |
def analog_message(self, data):
"""
This method handles the incoming analog data message.
It stores the data value for the pin in the analog response table.
If a callback function was associated with this pin, the callback function is invoked.
This method also checks to see if la... | This method handles the incoming analog data message.
It stores the data value for the pin in the analog response table.
If a callback function was associated with this pin, the callback function is invoked.
This method also checks to see if latching was requested for the pin. If the latch crite... |
def add_volume_bricks(name, bricks):
'''
Add brick(s) to an existing volume
name
Volume name
bricks
List of bricks to add to the volume
.. code-block:: yaml
myvolume:
glusterfs.add_volume_bricks:
- bricks:
- host1:/srv/gluster/drive1
... | Add brick(s) to an existing volume
name
Volume name
bricks
List of bricks to add to the volume
.. code-block:: yaml
myvolume:
glusterfs.add_volume_bricks:
- bricks:
- host1:/srv/gluster/drive1
- host2:/srv/gluster/drive2
... |
def draw_qubit_graph(G, layout, linear_biases={}, quadratic_biases={},
nodelist=None, edgelist=None, cmap=None, edge_cmap=None, vmin=None, vmax=None,
edge_vmin=None, edge_vmax=None,
**kwargs):
"""Draws graph G according to layout.
If `linear_biases... | Draws graph G according to layout.
If `linear_biases` and/or `quadratic_biases` are provided, these
are visualized on the plot.
Parameters
----------
G : NetworkX graph
The graph to be drawn
layout : dict
A dict of coordinates associated with each node in G. Should
be... |
def load(text, match=None):
"""This function reads a string that contains the XML of an Atom Feed, then
returns the
data in a native Python structure (a ``dict`` or ``list``). If you also
provide a tag name or path to match, only the matching sub-elements are
loaded.
:param text: The XML text t... | This function reads a string that contains the XML of an Atom Feed, then
returns the
data in a native Python structure (a ``dict`` or ``list``). If you also
provide a tag name or path to match, only the matching sub-elements are
loaded.
:param text: The XML text to load.
:type text: ``string``
... |
def alias(self):
"""
Returns the device's alias (name).
"""
try:
return self._properties.Get('org.bluez.Device1', 'Alias')
except dbus.exceptions.DBusException as e:
if e.get_dbus_name() == 'org.freedesktop.DBus.Error.UnknownObject':
# Blue... | Returns the device's alias (name). |
def update_file(self):
"""Update the read-in configuration file.
"""
if self._filename is None:
raise NoConfigFileReadError()
with open(self._filename, 'w') as fb:
self.write(fb) | Update the read-in configuration file. |
def values_to_labels(fg_vals, bg_vals):
"""
Convert two arrays of values to an array of labels and an array of scores.
Parameters
----------
fg_vals : array_like
The list of values for the positive set.
bg_vals : array_like
The list of values for the negative set.
Returns
... | Convert two arrays of values to an array of labels and an array of scores.
Parameters
----------
fg_vals : array_like
The list of values for the positive set.
bg_vals : array_like
The list of values for the negative set.
Returns
-------
y_true : array
Labels.
y... |
def add(key, value):
"""Adds context to the currently executing request.
:key: Any String identifying the request context.
Example: "user_ip", "plan", "alert_count"
:value: Any json-serializable type.
Example: "1.1.1.1", "free", 100
:returns: nothing.
... | Adds context to the currently executing request.
:key: Any String identifying the request context.
Example: "user_ip", "plan", "alert_count"
:value: Any json-serializable type.
Example: "1.1.1.1", "free", 100
:returns: nothing. |
def track_size(self, ts, sizer):
"""
Store timestamp and current size for later evaluation.
The 'sizer' is a stateful sizing facility that excludes other tracked
objects.
"""
obj = self.ref()
self.snapshots.append(
(ts, sizer.asized(obj, detail=self._r... | Store timestamp and current size for later evaluation.
The 'sizer' is a stateful sizing facility that excludes other tracked
objects. |
def mins(self, value):
""" Sets de minimum values of x, y, z as a numpy array
"""
self.x_min, self.y_min, self.z_min = value | Sets de minimum values of x, y, z as a numpy array |
def get_abi(self, hsh: bytes) -> Dict[str, Any]:
"""Returns a copy of the Solidity JSON ABI item for the function associated with the selector ``hsh``.
If no normal contract function has the specified selector, a dict describing the default or non-default
fallback function is returned.
... | Returns a copy of the Solidity JSON ABI item for the function associated with the selector ``hsh``.
If no normal contract function has the specified selector, a dict describing the default or non-default
fallback function is returned.
The content of the returned dict is described at https://so... |
def can_add_new_content(self, block, file_info):
"""
new content from file_info can be added into block iff
- file count limit hasn't been reached for the block
- there is enough space to completely fit the info into the block
- OR the info can be split and some info can fit into... | new content from file_info can be added into block iff
- file count limit hasn't been reached for the block
- there is enough space to completely fit the info into the block
- OR the info can be split and some info can fit into the block |
def connect_gs(gs_access_key_id=None, gs_secret_access_key=None, **kwargs):
"""
@type gs_access_key_id: string
@param gs_access_key_id: Your Google Cloud Storage Access Key ID
@type gs_secret_access_key: string
@param gs_secret_access_key: Your Google Cloud Storage Secret Access Key
@rtype: L{... | @type gs_access_key_id: string
@param gs_access_key_id: Your Google Cloud Storage Access Key ID
@type gs_secret_access_key: string
@param gs_secret_access_key: Your Google Cloud Storage Secret Access Key
@rtype: L{GSConnection<boto.gs.connection.GSConnection>}
@return: A connection to Google's Sto... |
def decode_async_options(options):
"""Decode Async options from JSON decoding."""
async_options = copy.deepcopy(options)
# JSON don't like datetimes.
eta = async_options.get('task_args', {}).get('eta')
if eta:
from datetime import datetime
async_options['task_args']['eta'] = dateti... | Decode Async options from JSON decoding. |
def find_playground_segments(segs):
'''Finds playground time in a list of segments.
Playground segments include the first 600s of every 6370s stride starting
at GPS time 729273613.
Parameters
----------
segs : segmentfilelist
A segmentfilelist to find playground segments.
... | Finds playground time in a list of segments.
Playground segments include the first 600s of every 6370s stride starting
at GPS time 729273613.
Parameters
----------
segs : segmentfilelist
A segmentfilelist to find playground segments.
Returns
-------
outlist :... |
def local_ip():
"""Get the local network IP of this machine"""
try:
ip = socket.gethostbyname(socket.gethostname())
except IOError:
ip = socket.gethostbyname('localhost')
if ip.startswith('127.'):
ip = get_local_ip_by_interfaces()
if ip is None:
ip = get_local... | Get the local network IP of this machine |
def _update_container_metrics(self, instance, subcontainer, kube_labels):
"""Publish metrics for a subcontainer and handle filtering on tags"""
tags = list(instance.get('tags', [])) # add support for custom tags
if len(subcontainer.get('aliases', [])) >= 1:
# The first alias seems ... | Publish metrics for a subcontainer and handle filtering on tags |
def add_data_attribute(self, data_attr):
'''Interprets a DATA attribute and add it to the datastream.'''
if data_attr.header.attr_type_id is not AttrTypes.DATA:
raise DataStreamError("Invalid attribute. A Datastream deals only with DATA attributes")
if data_attr.header.attr_name != s... | Interprets a DATA attribute and add it to the datastream. |
def inject_method(self, func, name=None):
"""
Injects a function into an object instance as a bound method
The main use case of this function is for monkey patching. While monkey
patching is sometimes necessary it should generally be avoided. Thus, we
simply remind the developer that there might be... | Injects a function into an object instance as a bound method
The main use case of this function is for monkey patching. While monkey
patching is sometimes necessary it should generally be avoided. Thus, we
simply remind the developer that there might be a better way.
Args:
self (object): insta... |
def is_parseable (self):
"""See if URL target is parseable for recursion."""
if self.is_directory():
return True
if self.content_type in self.ContentMimetypes:
return True
log.debug(LOG_CHECK, "URL with content type %r is not parseable.", self.content_type)
... | See if URL target is parseable for recursion. |
def _import(klass):
'''1) Get a reference to the module
2) Check the file that module's imported from
3) If that file's been updated, force a reload of that module
return it'''
mod = __import__(klass.rpartition('.')[0])
for segment in klass.split('.')[1:-1]:... | 1) Get a reference to the module
2) Check the file that module's imported from
3) If that file's been updated, force a reload of that module
return it |
def authenticate(remote_addr, password, cert, key, verify_cert=True):
'''
Authenticate with a remote LXDaemon.
remote_addr :
An URL to a remote Server, you also have to give cert and key if you
provide remote_addr and its a TCP Address!
Examples:
https://myserver.lan:84... | Authenticate with a remote LXDaemon.
remote_addr :
An URL to a remote Server, you also have to give cert and key if you
provide remote_addr and its a TCP Address!
Examples:
https://myserver.lan:8443
password :
The password of the remote.
cert :
PEM For... |
def do_execute(self):
"""
The actual execution of the actor.
:return: None if successful, otherwise error message
:rtype: str
"""
expr = str(self.resolve_option("expression"))
expr = expr.replace("{X}", str(self.input.payload))
self._output.append(Token(e... | The actual execution of the actor.
:return: None if successful, otherwise error message
:rtype: str |
def _add(self, other):
"""Add a interval to the underlying IntervalSet data store. This does not perform any tests as we assume that
any requirements have already been checked and that this function is being called by an internal function such
as union(), intersection() or add().
:param ... | Add a interval to the underlying IntervalSet data store. This does not perform any tests as we assume that
any requirements have already been checked and that this function is being called by an internal function such
as union(), intersection() or add().
:param other: An Interval to add to this ... |
def filterfalse(coro, iterable, limit=0, loop=None):
"""
Returns a list of all the values in coll which pass an asynchronous truth
test coroutine.
Operations are executed concurrently by default, but results
will be in order.
You can configure the concurrency via `limit` param.
This funct... | Returns a list of all the values in coll which pass an asynchronous truth
test coroutine.
Operations are executed concurrently by default, but results
will be in order.
You can configure the concurrency via `limit` param.
This function is the asynchronous equivalent port Python built-in
`filt... |
def release():
"""
Release new package version to pypi
:return:
"""
from secrets import pypi_auth
# Check that all changes are committed before creating a new version
git_check()
# Test package
test()
# Increment version
inc_version()
# Commit new version, create tag... | Release new package version to pypi
:return: |
def parse_glob(path, included):
"""Parse a glob."""
files = glob.glob(path, recursive=True)
array = []
for file in files:
file = os.path.abspath(file)
if file not in included:
array.append(file)
included += array
return array | Parse a glob. |
def to_json(data, compress=False):
"""Converts the output of `generate(...)` to formatted json.
Floats are rounded to three decimals and positional vectors are printed on
one line with some whitespace buffer.
"""
return json.compress(data) if compress else json.dumps(data) | Converts the output of `generate(...)` to formatted json.
Floats are rounded to three decimals and positional vectors are printed on
one line with some whitespace buffer. |
def connect(self):
"""Connect to Mongo and return a new SocketInfo.
Can raise ConnectionFailure or CertificateError.
Note that the pool does not keep a reference to the socket -- you
must call return_socket() when you're done with it.
"""
sock = None
try:
... | Connect to Mongo and return a new SocketInfo.
Can raise ConnectionFailure or CertificateError.
Note that the pool does not keep a reference to the socket -- you
must call return_socket() when you're done with it. |
def get_users(self, page=None):
"""Get users"""
opts = {}
if page:
opts['page'] = page
return self.api_call(ENDPOINTS['users']['list'], **opts) | Get users |
def slope_percentile(self, date, mag):
"""
Return 10% and 90% percentile of slope.
Parameters
----------
date : array_like
An array of phase-folded date. Sorted.
mag : array_like
An array of phase-folded magnitudes. Sorted by date.
Return... | Return 10% and 90% percentile of slope.
Parameters
----------
date : array_like
An array of phase-folded date. Sorted.
mag : array_like
An array of phase-folded magnitudes. Sorted by date.
Returns
-------
per_10 : float
10% pe... |
def setup_random_indices_local_geometry(self, coordination):
"""
Sets up random indices for the local geometry, for testing purposes
:param coordination: coordination of the local geometry
"""
self.icentral_site = 0
self.indices = list(range(1, coordination + 1))
... | Sets up random indices for the local geometry, for testing purposes
:param coordination: coordination of the local geometry |
def delete_view(self, request, object_id, extra_context=None):
"""Sets is_popup context variable to hide admin header."""
if not extra_context:
extra_context = {}
extra_context['is_popup'] = request.REQUEST.get('_popup', 0)
return super(EnhancedAdminMixin, self).delete_view(r... | Sets is_popup context variable to hide admin header. |
def suggest_type(full_text, text_before_cursor):
"""Takes the full_text that is typed so far and also the text before the
cursor to suggest completion type and scope.
Returns a tuple with a type of entity ('table', 'column' etc) and a scope.
A scope for a column category will be a list of tables.
""... | Takes the full_text that is typed so far and also the text before the
cursor to suggest completion type and scope.
Returns a tuple with a type of entity ('table', 'column' etc) and a scope.
A scope for a column category will be a list of tables. |
def bbox_overlaps(boxes, query_boxes):
"""
determine overlaps between boxes and query_boxes
:param boxes: n * 4 bounding boxes
:param query_boxes: k * 4 bounding boxes
:return: overlaps: n * k overlaps
"""
n_ = boxes.shape[0]
k_ = query_boxes.shape[0]
overlaps = np.zeros((n_, k_), dt... | determine overlaps between boxes and query_boxes
:param boxes: n * 4 bounding boxes
:param query_boxes: k * 4 bounding boxes
:return: overlaps: n * k overlaps |
def codes_get_api_version():
"""
Get the API version.
Returns the version of the API as a string in the format "major.minor.revision".
"""
ver = lib.codes_get_api_version()
patch = ver % 100
ver = ver // 100
minor = ver % 100
major = ver // 100
return "%d.%d.%d" % (major, minor... | Get the API version.
Returns the version of the API as a string in the format "major.minor.revision". |
def pointToLineDistance(p, p1, p2):
"""Compute the distance of a point to a line (not the segment) defined by `p1` and `p2`."""
d = np.sqrt(vtk.vtkLine.DistanceToLine(p, p1, p2))
return d | Compute the distance of a point to a line (not the segment) defined by `p1` and `p2`. |
def parse(cls, fptr, offset, length):
"""Parse JPEG 2000 file type box.
Parameters
----------
f : file
Open file object.
offset : int
Start position of box in bytes.
length : int
Length of the box in bytes.
Returns
---... | Parse JPEG 2000 file type box.
Parameters
----------
f : file
Open file object.
offset : int
Start position of box in bytes.
length : int
Length of the box in bytes.
Returns
-------
FileTypeBox
Instance of ... |
def _handle_switch(self, node, scope, ctxt, stream):
"""Handle break node
:node: TODO
:scope: TODO
:ctxt: TODO
:stream: TODO
:returns: TODO
"""
def exec_case(idx, cases):
# keep executing cases until a break is found,
# or they've... | Handle break node
:node: TODO
:scope: TODO
:ctxt: TODO
:stream: TODO
:returns: TODO |
def draw(vertexes, edges):
"""Build a DAG and draw it in ASCII.
Args:
vertexes (list): list of graph vertexes.
edges (list): list of graph edges.
"""
# pylint: disable=too-many-locals
# NOTE: coordinates might me negative, so we need to shift
# everything to the positive plane b... | Build a DAG and draw it in ASCII.
Args:
vertexes (list): list of graph vertexes.
edges (list): list of graph edges. |
def build_vocab(self, texts, verbose=1, **kwargs):
"""Builds the internal vocabulary and computes various statistics.
Args:
texts: The list of text items to encode.
verbose: The verbosity level for progress. Can be 0, 1, 2. (Default value = 1)
**kwargs: The kwargs fo... | Builds the internal vocabulary and computes various statistics.
Args:
texts: The list of text items to encode.
verbose: The verbosity level for progress. Can be 0, 1, 2. (Default value = 1)
**kwargs: The kwargs for `token_generator`. |
def _ensure_scope(level, global_dict=None, local_dict=None, resolvers=(),
target=None, **kwargs):
"""Ensure that we are grabbing the correct scope."""
return Scope(level + 1, global_dict=global_dict, local_dict=local_dict,
resolvers=resolvers, target=target) | Ensure that we are grabbing the correct scope. |
def _wrapped_signed_mul(a, b):
"""
Perform wrapped signed multiplication on two StridedIntervals.
:param a: The first operand (StridedInterval)
:param b: The second operand (StridedInterval)
:return: The product
"""
#NOTE: interval here should never straddle pol... | Perform wrapped signed multiplication on two StridedIntervals.
:param a: The first operand (StridedInterval)
:param b: The second operand (StridedInterval)
:return: The product |
def _match_view(self, method, route_params):
""" Detect a view matching the query
:param method: HTTP method
:param route_params: Route parameters dict
:return: Method
:rtype: Callable|None
"""
method = method.upper()
route_params = frozenset(k for k, v i... | Detect a view matching the query
:param method: HTTP method
:param route_params: Route parameters dict
:return: Method
:rtype: Callable|None |
def cache(self):
"""Memoize access to the cache backend."""
if self._cache is None:
self._cache = django_cache.get_cache(self.cache_name)
return self._cache | Memoize access to the cache backend. |
def change_cash(self, money):
"""
外部操作|高危|
"""
res = self.cash[-1] + money
if res >= 0:
# 高危操作
self.cash[-1] = res | 外部操作|高危| |
def execute(function, name):
"""
Execute a task, returning a TaskResult
"""
try:
return TaskResult(name, True, None, function())
except Exception as exc:
return TaskResult(name, False, exc, None) | Execute a task, returning a TaskResult |
def get_firmware_version(self, cb=None):
"""
This method retrieves the Firmata firmware version
:param cb: Reference to a callback function
:returns:If no callback is specified, the firmware version
"""
task = asyncio.ensure_future(self.core.get_firmware_version())
... | This method retrieves the Firmata firmware version
:param cb: Reference to a callback function
:returns:If no callback is specified, the firmware version |
def p_file_contrib_1(self, p):
"""file_contrib : FILE_CONTRIB LINE"""
try:
if six.PY2:
value = p[2].decode(encoding='utf-8')
else:
value = p[2]
self.builder.add_file_contribution(self.document, value)
except OrderError:
... | file_contrib : FILE_CONTRIB LINE |
def create_roles(apps, schema_editor):
"""Create the enterprise roles if they do not already exist."""
SystemWideEnterpriseRole = apps.get_model('enterprise', 'SystemWideEnterpriseRole')
SystemWideEnterpriseRole.objects.update_or_create(name=ENTERPRISE_OPERATOR_ROLE) | Create the enterprise roles if they do not already exist. |
def call_plugins(self, step):
'''
For each plugins, check if a "step" method exist on it, and call it
Args:
step (str): The method to search and call on each plugin
'''
for plugin in self.plugins:
try:
getattr(plugin, step)()
e... | For each plugins, check if a "step" method exist on it, and call it
Args:
step (str): The method to search and call on each plugin |
def __read_directory(usr_path, file_type):
"""
Universal read directory. Given a path and a type, it will do the appropriate read actions
:param str usr_path: Path to directory
:param str file_type: .xls, .xlsx, .txt, .lpd
:return none:
"""
# no path provided. start gui browse
if not us... | Universal read directory. Given a path and a type, it will do the appropriate read actions
:param str usr_path: Path to directory
:param str file_type: .xls, .xlsx, .txt, .lpd
:return none: |
def serial_load(workflow_file, specification, parameters=None, original=None):
"""Validate and return a expanded REANA Serial workflow specification.
:param workflow_file: A specification file compliant with
REANA Serial workflow specification.
:returns: A dictionary which represents the valid Seri... | Validate and return a expanded REANA Serial workflow specification.
:param workflow_file: A specification file compliant with
REANA Serial workflow specification.
:returns: A dictionary which represents the valid Serial workflow with all
parameters expanded. |
def command_list(self):
'''returns the 3dDeconvolve command as a list
The list returned can be run by passing it into a subprocess-like command
(e.g., neural.run())
'''
cmd = ['3dDeconvolve']
cmd += ['-jobs',multiprocessing.cpu_count()]
cmd += self.opts
... | returns the 3dDeconvolve command as a list
The list returned can be run by passing it into a subprocess-like command
(e.g., neural.run()) |
def get_stp_mst_detail_output_cist_port_configured_path_cost(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_mst_detail = ET.Element("get_stp_mst_detail")
config = get_stp_mst_detail
output = ET.SubElement(get_stp_mst_detail, "output")
... | Auto Generated Code |
def set_dump_directory(base=None, sub_dir=None):
"""Create directory for dumping SQL commands."""
# Set current timestamp
timestamp = datetime.fromtimestamp(time()).strftime('%Y-%m-%d %H-%M-%S')
# Clean sub_dir
if sub_dir and '.' in sub_dir:
sub_dir = sub_dir.rsplit('.', 1)[0]
# Create... | Create directory for dumping SQL commands. |
def main():
"""
expected output:
1a2
aba
3a4
"""
colorama.init()
print("aaa")
print("aaa")
print("aaa")
print(forward() + up(2) + "b" + up() + back(2) + "1" + forward() + "2" + back(3) + down(2) + "3" + forward() + "4") | expected output:
1a2
aba
3a4 |
def _add_to_bulk(self, bulkobj):
"""Add this operation to the _Bulk instance `bulkobj`."""
bulkobj.add_replace(self._filter, self._doc, self._upsert,
collation=self._collation) | Add this operation to the _Bulk instance `bulkobj`. |
def _is_bval_type_a(grouped_dicoms):
"""
Check if the bvals are stored in the first of 2 currently known ways for single frame dti
"""
bval_tag = Tag(0x2001, 0x1003)
bvec_x_tag = Tag(0x2005, 0x10b0)
bvec_y_tag = Tag(0x2005, 0x10b1)
bvec_z_tag = Tag(0x2005, 0x10b2)
for group in grouped_di... | Check if the bvals are stored in the first of 2 currently known ways for single frame dti |
def current_dir(self, hidex86=False, x64=False):
"""
Current platform specific subfolder.
Parameters
----------
hidex86: bool
return '' and not '\x86' if architecture is x86.
x64: bool
return '\x64' and not '\amd64' if architecture is amd64.
... | Current platform specific subfolder.
Parameters
----------
hidex86: bool
return '' and not '\x86' if architecture is x86.
x64: bool
return '\x64' and not '\amd64' if architecture is amd64.
Return
------
subfolder: str
'\target... |
def related_items_changed(self, instance, related_manager):
"""
Calculates and saves the average rating.
"""
ratings = [r.value for r in related_manager.all()]
count = len(ratings)
_sum = sum(ratings)
average = _sum / count if count > 0 else 0
setattr(inst... | Calculates and saves the average rating. |
def _process_legend(self):
"""
Disables legends if show_legend is disabled.
"""
for l in self.handles['plot'].legend:
l.items[:] = []
l.border_line_alpha = 0
l.background_fill_alpha = 0 | Disables legends if show_legend is disabled. |
def register_items(self, items):
"""Bulk ``register_item``.
Args:
items (iterable[Tree]):
Sequence of nodes to be registered as children.
"""
for item in items:
item.set_parent(self)
self.items.extend(items) | Bulk ``register_item``.
Args:
items (iterable[Tree]):
Sequence of nodes to be registered as children. |
def _get_dict_of_block_index(self, axis, indices, ordered=False):
"""Convert indices to a dict of block index to internal index mapping.
Note: See `_get_blocks_containing_index` for primary usage. This method
accepts a list of indices rather than just a single value, and uses
`_... | Convert indices to a dict of block index to internal index mapping.
Note: See `_get_blocks_containing_index` for primary usage. This method
accepts a list of indices rather than just a single value, and uses
`_get_blocks_containing_index`.
Args:
axis: The axis along... |
def nl_groups(self, value):
"""Group setter."""
self.bytearray[self._get_slicers(3)] = bytearray(c_uint32(value or 0)) | Group setter. |
def _fill(self, values):
"""Add extra values to fill the line"""
zero = self.view.y(min(max(self.zero, self._box.ymin), self._box.ymax))
# Check to see if the data has been padded with "none's"
# Fill doesn't work correctly otherwise
end = len(values) - 1
while end > 0:
... | Add extra values to fill the line |
def is_sql_equal(sqls1, sqls2):
"""
Find out equality of two SQL items.
See https://docs.djangoproject.com/en/1.8/ref/migration-operations/#runsql.
Args:
sqls1, sqls2: SQL items, have the same format as supported by Django's RunSQL operation.
Returns:
(bool) `True` if equal, otherwi... | Find out equality of two SQL items.
See https://docs.djangoproject.com/en/1.8/ref/migration-operations/#runsql.
Args:
sqls1, sqls2: SQL items, have the same format as supported by Django's RunSQL operation.
Returns:
(bool) `True` if equal, otherwise `False`. |
def _replace_faker_attr(self, matchobj):
"""
Callable used in re.sub to match, generate and replace the
valid syntax found in the mock response specifications.
"""
attr = matchobj.group(0).replace('<', '').replace('>', '')
# Prepare template to handle quotes
# Fo... | Callable used in re.sub to match, generate and replace the
valid syntax found in the mock response specifications. |
def cpmap(cores=1):
"""Configurable parallel map context manager.
Returns appropriate map compatible function based on configuration:
- Local single core (the default)
- Multiple local cores
"""
if int(cores) == 1:
yield itertools.imap
else:
if futures is None:
r... | Configurable parallel map context manager.
Returns appropriate map compatible function based on configuration:
- Local single core (the default)
- Multiple local cores |
def annotation_path(cls, project, incident, annotation):
"""Return a fully-qualified annotation string."""
return google.api_core.path_template.expand(
"projects/{project}/incidents/{incident}/annotations/{annotation}",
project=project,
incident=incident,
... | Return a fully-qualified annotation string. |
def sas_logical_jbod_attachments(self):
"""
Gets the SAS Logical JBOD Attachments client.
Returns:
SasLogicalJbodAttachments:
"""
if not self.__sas_logical_jbod_attachments:
self.__sas_logical_jbod_attachments = SasLogicalJbodAttachments(self.__connection... | Gets the SAS Logical JBOD Attachments client.
Returns:
SasLogicalJbodAttachments: |
def main(c, prefix, csv, db, sql, o, w, h, scale):
"""
ggplot2 syntax in Python.
Run pygg command from command line
python pygg -c "ggplot('diamonds', aes('carat', 'price')) + geom_point()"
Import into your python program to use ggplot
\b
from pygg import *
p = ggplot('diamonds', aes('carat'... | ggplot2 syntax in Python.
Run pygg command from command line
python pygg -c "ggplot('diamonds', aes('carat', 'price')) + geom_point()"
Import into your python program to use ggplot
\b
from pygg import *
p = ggplot('diamonds', aes('carat', y='price')) + geom_point()
p = p + facet_wrap(None, "... |
def dtable(self, query):
"""Compute a distance table for a query vector.
The distances are computed by comparing each sub-vector of the query
to the codewords for each sub-subspace.
`dtable[m][ks]` contains the squared Euclidean distance between
the `m`-th sub-vector of the query... | Compute a distance table for a query vector.
The distances are computed by comparing each sub-vector of the query
to the codewords for each sub-subspace.
`dtable[m][ks]` contains the squared Euclidean distance between
the `m`-th sub-vector of the query and the `ks`-th codeword
fo... |
def create_n_connect(self,
socket_type,
address: str,
bind=False,
on_error='log',
socket_name=''):
"""
Creates and connects or binds the sockets
on_error:
'log... | Creates and connects or binds the sockets
on_error:
'log': will log error
'exit': will exit the program
socket_name:
used for troubleshooting/logging |
def get(self, section, option, **kwargs):
"""
Get method that raises MissingSetting if the value was unset.
This differs from the SafeConfigParser which may raise either a
NoOptionError or a NoSectionError.
We take extra **kwargs because the Python 3.5 configparser extends the
... | Get method that raises MissingSetting if the value was unset.
This differs from the SafeConfigParser which may raise either a
NoOptionError or a NoSectionError.
We take extra **kwargs because the Python 3.5 configparser extends the
get method signature and it calls self with those para... |
def new_value(self, name, value):
"""Create new value in data"""
try:
# We need to enclose values in a list to be able to send
# them to the kernel in Python 2
svalue = [cloudpickle.dumps(value, protocol=PICKLE_PROTOCOL)]
# Needed to prevent memory... | Create new value in data |
def show_firmware_version_output_show_firmware_version_node_info_is_active_cp(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
show_firmware_version = ET.Element("show_firmware_version")
config = show_firmware_version
output = ET.SubElement(show_f... | Auto Generated Code |
def sort_data(x_vals, y_vals):
"""Sort the data so that x is monotonically increasing and contains
no duplicates.
"""
# Sort data
idxs = np.argsort(x_vals)
x_vals = x_vals[idxs]
y_vals = y_vals[idxs]
# De-duplicate data
mask = np.r_[True, (np.diff(x_vals) > 0)]
if not mask.all()... | Sort the data so that x is monotonically increasing and contains
no duplicates. |
def remove_length_outliers(df, columnname):
"""Remove records with length-outliers above 3 standard deviations from the median."""
return df[df[columnname] < (np.median(df[columnname]) + 3 * np.std(df[columnname]))] | Remove records with length-outliers above 3 standard deviations from the median. |
def _create_penwidth_combo(self):
"""Create pen width combo box"""
choices = map(unicode, xrange(12))
self.pen_width_combo = \
_widgets.PenWidthComboBox(self, choices=choices,
style=wx.CB_READONLY, size=(50, -1))
self.pen_width_combo.Se... | Create pen width combo box |
def get_parameters(folder):
"""Get the parameters of the preprocessing done within `folder`.
Parameters
----------
folder : string
Returns
-------
tuple : (path of raw data,
path where preprocessed data gets stored,
list of preprocessing algorithms)
"""
#... | Get the parameters of the preprocessing done within `folder`.
Parameters
----------
folder : string
Returns
-------
tuple : (path of raw data,
path where preprocessed data gets stored,
list of preprocessing algorithms) |
def get_elastic_items(self, elastic_scroll_id=None, _filter=None, ignore_incremental=False):
""" Get the items from the index related to the backend applying and
optional _filter if provided"""
headers = {"Content-Type": "application/json"}
if not self.elastic:
return None
... | Get the items from the index related to the backend applying and
optional _filter if provided |
def doubleprox_dc_simple(x, y, f, phi, g, K, niter, gamma, mu):
"""Non-optimized version of ``doubleprox_dc``.
This function is intended for debugging. It makes a lot of copies and
performs no error checking.
"""
for _ in range(niter):
f.proximal(gamma)(x + gamma * K.adjoint(y) -
... | Non-optimized version of ``doubleprox_dc``.
This function is intended for debugging. It makes a lot of copies and
performs no error checking. |
def zone_floor2roofheight(idf, zonename, debug=False):
"""zone floor to roof height"""
zone = idf.getobject('ZONE', zonename)
surfs = idf.idfobjects['BuildingSurface:Detailed'.upper()]
zone_surfs = [s for s in surfs if s.Zone_Name == zone.Name]
floors = [s for s in zone_surfs if s.Surface_Type.upper... | zone floor to roof height |
def info(self, name, args):
"""Interfaces with the info dumpers (DBGFInfo).
This feature is not implemented in the 4.0.0 release but it may show up
in a dot release.
in name of type str
The name of the info item.
in args of type str
Arguments to... | Interfaces with the info dumpers (DBGFInfo).
This feature is not implemented in the 4.0.0 release but it may show up
in a dot release.
in name of type str
The name of the info item.
in args of type str
Arguments to the info dumper.
return info ... |
def outbound_message_filter(f):
"""
Register the decorated function as a service-level outbound message filter.
:raise TypeError: if the decorated object is a coroutine function
.. seealso::
:class:`StanzaStream`
for important remarks regarding the use of stanza filters.
"""
... | Register the decorated function as a service-level outbound message filter.
:raise TypeError: if the decorated object is a coroutine function
.. seealso::
:class:`StanzaStream`
for important remarks regarding the use of stanza filters. |
def submit_and_connect(self, spec):
"""Submit a new skein application, and wait to connect to it.
If an error occurs before the application connects, the application is
killed.
Parameters
----------
spec : ApplicationSpec, str, or dict
A description of the a... | Submit a new skein application, and wait to connect to it.
If an error occurs before the application connects, the application is
killed.
Parameters
----------
spec : ApplicationSpec, str, or dict
A description of the application to run. Can be an
``Appl... |
def _get_link(self, cobj):
"""Get a valid link, False if not found"""
fullname = cobj['module_short'] + '.' + cobj['name']
try:
value = self._searchindex['objects'][cobj['module_short']]
match = value[cobj['name']]
except KeyError:
link = False
... | Get a valid link, False if not found |
def validate_symbol(text):
"""
Verifying whether symbol(s) included in the ``text`` or not.
:param str text: Input text.
:raises pathvalidate.InvalidCharError:
If symbol(s) included in the ``text``.
"""
match_list = __RE_SYMBOL.findall(preprocess(text))
if match_list:
raise... | Verifying whether symbol(s) included in the ``text`` or not.
:param str text: Input text.
:raises pathvalidate.InvalidCharError:
If symbol(s) included in the ``text``. |
def _set_offline_if(self, v, load=False):
"""
Setter method for offline_if, mapped from YANG variable /rbridge_id/snmp_server/offline_if (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_offline_if is considered as a private
method. Backends looking to popu... | Setter method for offline_if, mapped from YANG variable /rbridge_id/snmp_server/offline_if (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_offline_if is considered as a private
method. Backends looking to populate this variable should
do so via calling thisOb... |
def histogram1d(x, bins, range, weights=None):
"""
Compute a 1D histogram assuming equally spaced bins.
Parameters
----------
x : `~numpy.ndarray`
The position of the points to bin in the 1D histogram
bins : int
The number of bins
range : iterable
The range as a tupl... | Compute a 1D histogram assuming equally spaced bins.
Parameters
----------
x : `~numpy.ndarray`
The position of the points to bin in the 1D histogram
bins : int
The number of bins
range : iterable
The range as a tuple of (xmin, xmax)
weights : `~numpy.ndarray`
Th... |
def expired(self):
"""Boolean property if this action has expired
"""
if self.timeout is None:
return False
return monotonic() - self.start_time > self.timeout | Boolean property if this action has expired |
def tick(self):
"""
Advances time in the game. Use this once all "choices" have been submitted for the current
game state using the other methods.
"""
if self.state == AuctionState.NOMINATE:
# if no nominee submitted, exception
if self.nominee is None:
... | Advances time in the game. Use this once all "choices" have been submitted for the current
game state using the other methods. |
def global_avgpooling(attrs, inputs, proto_obj):
"""Performs avg pooling on the input."""
new_attrs = translation_utils._add_extra_attributes(attrs, {'global_pool': True,
'kernel': (1, 1),
... | Performs avg pooling on the input. |
def update_filter(self):
"""
Update the filter according to the new properties
:return: True if the filter changed, else False
:raise ValueError: The filter is invalid
"""
# Consider the filter invalid
self.valid_filter = False
try:
# Format ... | Update the filter according to the new properties
:return: True if the filter changed, else False
:raise ValueError: The filter is invalid |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.