positive stringlengths 100 30.3k | anchor stringlengths 1 15k |
|---|---|
def get_cancellation_status(brain_or_object, default="active"):
"""Get the `cancellation_state` of an object
:param brain_or_object: A single catalog brain or content object
:type brain_or_object: ATContentType/DexterityContentType/CatalogBrain
:returns: Value of the review_status variable
:rtype: ... | Get the `cancellation_state` of an object
:param brain_or_object: A single catalog brain or content object
:type brain_or_object: ATContentType/DexterityContentType/CatalogBrain
:returns: Value of the review_status variable
:rtype: String |
def overlap(intv1, intv2):
"""Overlaping of two intervals"""
return max(0, min(intv1[1], intv2[1]) - max(intv1[0], intv2[0])) | Overlaping of two intervals |
def follow(self, delay=1.0):
"""\
Iterator generator that returns lines as data is added to the file.
Based on: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/157035
"""
# TODO: Handle log file rotation
self.trailing = True
unchanged_stats = 0
... | \
Iterator generator that returns lines as data is added to the file.
Based on: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/157035 |
def receive(self, data_only = True, **options):
'''Reads and (optionally) parses the response from a q service.
Retrieves query result along with meta-information:
>>> q.query(qconnection.MessageType.SYNC,'{x}', 10)
>>> print(q.receive(data_only = False, raw = F... | Reads and (optionally) parses the response from a q service.
Retrieves query result along with meta-information:
>>> q.query(qconnection.MessageType.SYNC,'{x}', 10)
>>> print(q.receive(data_only = False, raw = False))
QMessage: message type: 2, data size: 13... |
def ReadByte(self, do_ord=True):
"""
Read a single byte.
Args:
do_ord (bool): (default True) convert the byte to an ordinal first.
Returns:
bytes: a single byte if successful. 0 (int) if an exception occurred.
"""
try:
if do_ord:
... | Read a single byte.
Args:
do_ord (bool): (default True) convert the byte to an ordinal first.
Returns:
bytes: a single byte if successful. 0 (int) if an exception occurred. |
def scrape(cls, start, end, output):
"""
Scrape a MLBAM Data
:param start: Start Day(YYYYMMDD)
:param end: End Day(YYYYMMDD)
:param output: Output directory
"""
# Logger setting
logging.basicConfig(
level=logging.INFO,
format="time:... | Scrape a MLBAM Data
:param start: Start Day(YYYYMMDD)
:param end: End Day(YYYYMMDD)
:param output: Output directory |
def json(self):
"""Produce a JSON representation for the web interface"""
d = { 'id': self.id, 'format': self.formatclass.__name__,'label': self.label, 'mimetype': self.formatclass.mimetype, 'schema': self.formatclass.schema }
if self.unique:
d['unique'] = True
if self.filen... | Produce a JSON representation for the web interface |
def ask_folder(message='Select folder.', default='', title=''):
"""
A dialog to get a directory name.
Returns the name of a directory, or None if user chose to cancel.
If the "default" argument specifies a directory name, and that
directory exists, then the dialog box will start with that directory.... | A dialog to get a directory name.
Returns the name of a directory, or None if user chose to cancel.
If the "default" argument specifies a directory name, and that
directory exists, then the dialog box will start with that directory.
:param message: message to be displayed.
:param title: window titl... |
def walk_code(co, _prefix=''):
"""
Traverse a code object, finding all consts which are also code objects.
Yields pairs of (name, code object).
"""
name = _prefix + co.co_name
yield name, co
yield from chain.from_iterable(
walk_code(c, _prefix=_extend_name(name, co))
for c i... | Traverse a code object, finding all consts which are also code objects.
Yields pairs of (name, code object). |
def _resourcePath(self):
"""
The path to the directory that should be used when shipping this module and its siblings
around as a resource.
"""
if self.fromVirtualEnv:
return self.dirPath
elif '.' in self.name:
return os.path.join(self.dirPath, sel... | The path to the directory that should be used when shipping this module and its siblings
around as a resource. |
def _parse_target(target):
"""Parse a binary targeting information structure.
This function only supports extracting the slot number or controller from
the target and will raise an ArgumentError if more complicated targeting
is desired.
Args:
target (bytes): The binary targeting data blob.... | Parse a binary targeting information structure.
This function only supports extracting the slot number or controller from
the target and will raise an ArgumentError if more complicated targeting
is desired.
Args:
target (bytes): The binary targeting data blob.
Returns:
dict: The p... |
def add(self, delta, data):
"""
Adds (enqueues) an iterable event to the mixer.
Parameters
----------
delta :
Time in samples since last added event. This can be zero and can be
float. Use "s" object from sHz for time conversion.
data :
Iterable (e.g. a list, a tuple, a Stream... | Adds (enqueues) an iterable event to the mixer.
Parameters
----------
delta :
Time in samples since last added event. This can be zero and can be
float. Use "s" object from sHz for time conversion.
data :
Iterable (e.g. a list, a tuple, a Stream) to be "played" by the mixer at
t... |
def detectMeegoPhone(self):
"""Return detection of a Meego phone
Detects a phone running the Meego OS.
"""
return UAgentInfo.deviceMeego in self.__userAgent \
and UAgentInfo.mobi in self.__userAgent | Return detection of a Meego phone
Detects a phone running the Meego OS. |
def get_base_input(test=False):
"""
Return DateTimeBaseInput class from django.forms.widgets module
Return _compatibility.DateTimeBaseInput class for older django versions.
"""
from django.forms.widgets import DateTimeBaseInput
if 'get_context' in dir(DateTimeBaseInput) and not test:
# ... | Return DateTimeBaseInput class from django.forms.widgets module
Return _compatibility.DateTimeBaseInput class for older django versions. |
def _serialize(self, value, attr, obj):
"""Serialize an ISO8601-formatted date."""
try:
return super(DateString, self)._serialize(
arrow.get(value).date(), attr, obj)
except ParserError:
return missing | Serialize an ISO8601-formatted date. |
def properties_for_args(cls, arg_names='_arg_names'):
"""For a class with an attribute `arg_names` containing a list of names,
add a property for every name in that list.
It is assumed that there is an instance attribute ``self._<arg_name>``,
which is returned by the `arg_name` property. The decorator... | For a class with an attribute `arg_names` containing a list of names,
add a property for every name in that list.
It is assumed that there is an instance attribute ``self._<arg_name>``,
which is returned by the `arg_name` property. The decorator also adds a
class attribute :attr:`_has_properties_for_a... |
def set_parameter(self, name, value):
"""Set a parameter."""
self.lib.tdSetDeviceParameter(self.id, name, str(value)) | Set a parameter. |
def soma_points(self):
'''Get the soma points'''
db = self.data_block
return db[db[:, COLS.TYPE] == POINT_TYPE.SOMA] | Get the soma points |
def read_atsplib(filename):
"basic function for reading a ATSP problem on the TSPLIB format"
"NOTE: only works for explicit matrices"
if filename[-3:] == ".gz":
f = gzip.open(filename, 'r')
data = f.readlines()
else:
f = open(filename, 'r')
data = f.readlines()
for ... | basic function for reading a ATSP problem on the TSPLIB format |
def _reldiff(a, b):
"""
Computes the relative difference of two floating-point numbers
rel = abs(a-b)/min(abs(a), abs(b))
If a == 0 and b == 0, then 0.0 is returned
Otherwise if a or b is 0.0, inf is returned.
"""
a = float(a)
b = float(b)
aa = abs(a)
ba = abs(b)
if a == ... | Computes the relative difference of two floating-point numbers
rel = abs(a-b)/min(abs(a), abs(b))
If a == 0 and b == 0, then 0.0 is returned
Otherwise if a or b is 0.0, inf is returned. |
def get_broadcast_events(cls, script):
"""Return a Counter of event-names that were broadcast.
The Count will contain the key True if any of the broadcast blocks
contain a parameter that is a variable.
"""
events = Counter()
for name, _, block in cls.iter_blocks(script)... | Return a Counter of event-names that were broadcast.
The Count will contain the key True if any of the broadcast blocks
contain a parameter that is a variable. |
def log_ncr(a, b):
"""
Returns log(nCr(a,b)), given that b<a. Does not assume that a and b
are integers (uses log-gamma).
"""
val = gammaln(a+1) - gammaln(a-b+1) - gammaln(b+1)
return val | Returns log(nCr(a,b)), given that b<a. Does not assume that a and b
are integers (uses log-gamma). |
def list_subscriptions(self, publisher_id=None, event_type=None, consumer_id=None, consumer_action_id=None):
"""ListSubscriptions.
Get a list of subscriptions.
:param str publisher_id: ID for a subscription.
:param str event_type: Maximum number of notifications to return. Default is 100... | ListSubscriptions.
Get a list of subscriptions.
:param str publisher_id: ID for a subscription.
:param str event_type: Maximum number of notifications to return. Default is 100.
:param str consumer_id: ID for a consumer.
:param str consumer_action_id: ID for a consumerActionId.
... |
def IterReferenceInstancePaths(self, InstanceName, ResultClass=None,
Role=None,
FilterQueryLanguage=None, FilterQuery=None,
OperationTimeout=None, ContinueOnError=None,
MaxObjectCo... | Retrieve the instance paths of the association instances that reference
a source instance, using the Python :term:`py:generator` idiom to
return the result.
*New in pywbem 0.10 as experimental and finalized in 0.12.*
This method uses the corresponding pull operations if supported by th... |
def printPre(self, *args):
"""
get/set the str_pre string.
"""
if len(args):
self.b_printPre = args[0]
else:
return self.b_printPre | get/set the str_pre string. |
def _send_rpc_response(self, *packets):
"""Send an RPC response.
It is executed in the baBLE working thread: should not be blocking.
The RPC response is notified in one or two packets depending on whether or not
response data is included. If there is a temporary error sending one of the... | Send an RPC response.
It is executed in the baBLE working thread: should not be blocking.
The RPC response is notified in one or two packets depending on whether or not
response data is included. If there is a temporary error sending one of the packets
it is retried automatically. If th... |
def match_regexp(self, value, q, strict=False):
"""if value matches a regexp q"""
value = stringify(value)
mr = re.compile(q)
if value is not None:
if mr.match(value):
return
self.shout('%r not matching the regexp %r', strict, value, q) | if value matches a regexp q |
def write_single_register(self, reg_addr, reg_value):
"""Modbus function WRITE_SINGLE_REGISTER (0x06)
:param reg_addr: register address (0 to 65535)
:type reg_addr: int
:param reg_value: register value to write
:type reg_value: int
:returns: True if write ok or None if f... | Modbus function WRITE_SINGLE_REGISTER (0x06)
:param reg_addr: register address (0 to 65535)
:type reg_addr: int
:param reg_value: register value to write
:type reg_value: int
:returns: True if write ok or None if fail
:rtype: bool or None |
def decode_numpy_dict_values(attrs: Mapping[K, V]) -> Dict[K, V]:
"""Convert attribute values from numpy objects to native Python objects,
for use in to_dict
"""
attrs = dict(attrs)
for k, v in attrs.items():
if isinstance(v, np.ndarray):
attrs[k] = v.tolist()
elif isinst... | Convert attribute values from numpy objects to native Python objects,
for use in to_dict |
def set_image(self, image='auto'):
"""
Set which pylab image to tweak.
"""
if image=="auto": image = _pylab.gca().images[0]
self._image=image
self.update_image() | Set which pylab image to tweak. |
def _add_tile(self, new_tile, ijk):
"""Add a tile with a label indicating its tiling position. """
tile_label = "{0}_{1}".format(self.name, '-'.join(str(d) for d in ijk))
self.add(new_tile, label=tile_label, inherit_periodicity=False) | Add a tile with a label indicating its tiling position. |
def _strip_top_comments(lines: Sequence[str], line_separator: str) -> str:
"""Strips # comments that exist at the top of the given lines"""
lines = copy.copy(lines)
while lines and lines[0].startswith("#"):
lines = lines[1:]
return line_separator.join(lines) | Strips # comments that exist at the top of the given lines |
def remove_user_role(self, user_role):
"""
Remove the specified User Role from this User.
This User must not be a system-defined or pattern-based user.
Authorization requirements:
* Task permission to the "Manage Users" task to modify a standard user
or the "Manage U... | Remove the specified User Role from this User.
This User must not be a system-defined or pattern-based user.
Authorization requirements:
* Task permission to the "Manage Users" task to modify a standard user
or the "Manage User Templates" task to modify a template user.
Par... |
def ProduceExtractionWarning(self, message, path_spec=None):
"""Produces an extraction warning.
Args:
message (str): message of the warning.
path_spec (Optional[dfvfs.PathSpec]): path specification, where None
will use the path specification of current file entry set in
the medi... | Produces an extraction warning.
Args:
message (str): message of the warning.
path_spec (Optional[dfvfs.PathSpec]): path specification, where None
will use the path specification of current file entry set in
the mediator.
Raises:
RuntimeError: when storage writer is not se... |
def set_http_application_url_output_status_string(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
set_http_application_url = ET.Element("set_http_application_url")
config = set_http_application_url
output = ET.SubElement(set_http_application_url,... | Auto Generated Code |
def navigation(self):
"""Creates a :class:`QuerySet` of the published root pages."""
return self.on_site().filter(
status=self.model.PUBLISHED).filter(parent__isnull=True) | Creates a :class:`QuerySet` of the published root pages. |
def memoize(self, hasher=None):
""" Memoize an expensive function by storing its results.
"""
ns = self.Namespace()
ns.memo = {}
if hasher is None:
hasher = lambda x: x
def memoized(*args, **kwargs):
key = hasher(*args)
if key not in n... | Memoize an expensive function by storing its results. |
def company_path(cls, project, company):
"""Return a fully-qualified company string."""
return google.api_core.path_template.expand(
"projects/{project}/companies/{company}", project=project, company=company
) | Return a fully-qualified company string. |
def get_property(self, name=None):
"""
Helper to get a property value by name or all
properties as a dictionary.
See also :py:meth:`set_property`
:param str name: defaults to None which means all properties
in the object's dictionary are returned as a dict.
... | Helper to get a property value by name or all
properties as a dictionary.
See also :py:meth:`set_property`
:param str name: defaults to None which means all properties
in the object's dictionary are returned as a dict.
Otherwise, the property name key is used and its va... |
def get_interfaces_ip(self):
"""
Get interface IP details. Returns a dictionary of dictionaries.
Sample output:
{
"Ethernet2/3": {
"ipv4": {
"4.4.4.4": {
"prefix_length": 16
}
},
... | Get interface IP details. Returns a dictionary of dictionaries.
Sample output:
{
"Ethernet2/3": {
"ipv4": {
"4.4.4.4": {
"prefix_length": 16
}
},
"ipv6": {
"20... |
def make_plot(self):
"""Creates the ratio plot.
"""
# sets colormap for ratio comparison plot
cmap = getattr(cm, self.colormap)
# set values of ratio comparison contour
normval = 2.0
num_contours = 40 # must be even
levels = np.linspace(-normval, normva... | Creates the ratio plot. |
def enc_setup(self, enc_alg, msg, auth_data=b'', key=None, iv=""):
""" Encrypt JWE content.
:param enc_alg: The JWE "enc" value specifying the encryption algorithm
:param msg: The plain text message
:param auth_data: Additional authenticated data
:param key: Key (CEK)
:r... | Encrypt JWE content.
:param enc_alg: The JWE "enc" value specifying the encryption algorithm
:param msg: The plain text message
:param auth_data: Additional authenticated data
:param key: Key (CEK)
:return: Tuple (ciphertext, tag), both as bytes |
def calibration_lines(freqs, data, tref=None):
""" Extract the calibration lines from strain data.
Parameters
----------
freqs: list
List containing the frequencies of the calibration lines.
data: pycbc.types.TimeSeries
Strain data to extract the calibration lines from.
tref: {N... | Extract the calibration lines from strain data.
Parameters
----------
freqs: list
List containing the frequencies of the calibration lines.
data: pycbc.types.TimeSeries
Strain data to extract the calibration lines from.
tref: {None, float}, optional
Reference time for the li... |
def get_itemtypesinsertion(cls, itemgroup, indent) -> str:
"""Return a string defining the required types for the given
exchange item group.
>>> from hydpy.auxs.xmltools import XSDWriter
>>> print(XSDWriter.get_itemtypesinsertion(
... 'setitems', 1)) # doctest: +ELLIPSIS
... | Return a string defining the required types for the given
exchange item group.
>>> from hydpy.auxs.xmltools import XSDWriter
>>> print(XSDWriter.get_itemtypesinsertion(
... 'setitems', 1)) # doctest: +ELLIPSIS
<complexType name="arma_v1_setitemsType">
...
... |
def StreamSignedBinaryContents(blob_iterator,
chunk_size = 1024
):
"""Yields the contents of the given binary in chunks of the given size.
Args:
blob_iterator: An Iterator over all the binary's blobs.
chunk_size: Size, in bytes, of the chunks to ... | Yields the contents of the given binary in chunks of the given size.
Args:
blob_iterator: An Iterator over all the binary's blobs.
chunk_size: Size, in bytes, of the chunks to yield. |
def sign_array(p_values, alpha=0.05):
"""
Significance array
Converts an array with p values to a significance array where
0 is False (not significant), 1 is True (significant),
and -1 is for diagonal elements.
Parameters
----------
p_values : array_like or ndarray
An array, an... | Significance array
Converts an array with p values to a significance array where
0 is False (not significant), 1 is True (significant),
and -1 is for diagonal elements.
Parameters
----------
p_values : array_like or ndarray
An array, any object exposing the array interface, containing
... |
def choice_info(self):
"""View .info file
"""
info = ReadSBo(self.sbo_url).info(self.name, ".info")
fill = self.fill_pager(info)
self.pager(info + fill) | View .info file |
def _parse_block(self):
"""Parse metadata and rows from the block only once."""
if self._iter_rows is not None:
return
rows = _avro_rows(self._block, self._avro_schema)
self._num_items = self._block.avro_rows.row_count
self._remaining = self._block.avro_rows.row_coun... | Parse metadata and rows from the block only once. |
def get_dict_properties(item, fields, mixed_case_fields=[], formatters={}):
"""Return a tuple containing the item properties.
:param item: a single dict resource
:param fields: tuple of strings with the desired field names
:param mixed_case_fields: tuple of field names to preserve case
:param format... | Return a tuple containing the item properties.
:param item: a single dict resource
:param fields: tuple of strings with the desired field names
:param mixed_case_fields: tuple of field names to preserve case
:param formatters: dictionary mapping field names to callables
to format the values |
def restore_organization_to_ckan(catalog, owner_org, portal_url, apikey,
dataset_list=None, download_strategy=None,
generate_new_access_url=None):
"""Restaura los datasets de la organización de un catálogo al portal pasado
por parámetro. Si ha... | Restaura los datasets de la organización de un catálogo al portal pasado
por parámetro. Si hay temas presentes en el DataJson que no están en el
portal de CKAN, los genera.
Args:
catalog (DataJson): El catálogo de origen que se restaura.
portal_url (str): La URL del portal... |
def import_vmesh(file):
""" Imports NURBS volume(s) from volume mesh (vmesh) file(s).
:param file: path to a directory containing mesh files or a single mesh file
:type file: str
:return: list of NURBS volumes
:rtype: list
:raises GeomdlException: an error occurred reading the file
"""
... | Imports NURBS volume(s) from volume mesh (vmesh) file(s).
:param file: path to a directory containing mesh files or a single mesh file
:type file: str
:return: list of NURBS volumes
:rtype: list
:raises GeomdlException: an error occurred reading the file |
def _set_bin_view(self, session):
"""Sets the underlying bin view to match current view"""
if self._bin_view == FEDERATED:
try:
session.use_federated_bin_view()
except AttributeError:
pass
else:
try:
session.use_... | Sets the underlying bin view to match current view |
def login(self, request, extra_context=None):
"""
Displays the login form for the given HttpRequest.
"""
from django.contrib.auth.views import login
context = {
'title': _('Log in'),
'app_path': request.get_full_path(),
REDIRECT_FIELD_NAME: req... | Displays the login form for the given HttpRequest. |
def mergeidngram(output_file, input_files, n=3, ascii_input=False, ascii_output=False):
"""
Takes a set of id n-gram files (in either binary (by default) or ASCII (if specified) format - note that they should all be in the same format, however) and outputs a merged id N-gram.
Notes : This function ... | Takes a set of id n-gram files (in either binary (by default) or ASCII (if specified) format - note that they should all be in the same format, however) and outputs a merged id N-gram.
Notes : This function can also be used to convert id n-gram files between ascii and binary formats. |
def inverted(self):
"""
Returns an inverted copy of this query.
:return <orb.Query>
"""
out = self.copy()
out.setInverted(not self.isInverted())
return out | Returns an inverted copy of this query.
:return <orb.Query> |
def has_sample(self, md5):
"""Checks if data store has this sample.
Args:
md5: The md5 digest of the required sample.
Returns:
True if sample with this md5 is present, else False.
"""
# The easiest thing is to simply get the sample and if that
#... | Checks if data store has this sample.
Args:
md5: The md5 digest of the required sample.
Returns:
True if sample with this md5 is present, else False. |
def clean_jobs(self, recursive=False):
"""Clean up all the jobs associated with this object.
If recursive is True this also clean jobs dispatch by this
object."""
self._interface.clean_jobs(self.scatter_link,
clean_all=recursive) | Clean up all the jobs associated with this object.
If recursive is True this also clean jobs dispatch by this
object. |
def slicewise(tf_fn,
xs,
output_shape=None,
output_dtype=None,
splittable_dims=None,
grad_function=None,
name=None):
"""Slice-wise call to any tensorflow function.
The output shape and dtype default to those of the first input.
s... | Slice-wise call to any tensorflow function.
The output shape and dtype default to those of the first input.
splittable_dims is a list of Dimensions which can be split while keeping the
computation valid.
Args:
tf_fn: a function taking n tf.Tensors and returning a tf.Tensor
xs: a list of n Tensors
... |
def get(self, uri, default_response=None, **kwargs):
"""
Call GET on the Gitlab server
>>> gitlab = Gitlab(host='http://localhost:10080', verify_ssl=False)
>>> gitlab.login(user='root', password='5iveL!fe')
>>> gitlab.get('/users/5')
:param uri: String with the URI for ... | Call GET on the Gitlab server
>>> gitlab = Gitlab(host='http://localhost:10080', verify_ssl=False)
>>> gitlab.login(user='root', password='5iveL!fe')
>>> gitlab.get('/users/5')
:param uri: String with the URI for the endpoint to GET from
:param default_response: Return value if... |
def open_url(self, url, stale_after, parse_as_html = True, **kwargs):
"""
Download or retrieve from cache.
url -- The URL to be downloaded, as a string.
stale_after -- A network request for the url will be performed if the
cached copy does not exist or if it exists but its age (in days) is
larger ... | Download or retrieve from cache.
url -- The URL to be downloaded, as a string.
stale_after -- A network request for the url will be performed if the
cached copy does not exist or if it exists but its age (in days) is
larger or equal to the stale_after value. A non-positive value will
force re-downloa... |
def summary_pairwise_indices(self):
"""ndarray containing tuples of pairwise indices for the column summary."""
summary_pairwise_indices = np.empty(
self.values[0].t_stats.shape[1], dtype=object
)
summary_pairwise_indices[:] = [
sig.summary_pairwise_indices for si... | ndarray containing tuples of pairwise indices for the column summary. |
def make_column_suffixes(self):
""" Make sure we have the right column suffixes. These will be appended
to `id` when generating the query.
"""
if self.column_suffixes:
return self.column_suffixes
if len(self.columns) == 0:
return ()
elif len(self... | Make sure we have the right column suffixes. These will be appended
to `id` when generating the query. |
def visit_FunctionDef(self, node):
'''
Initialise aliasing default value before visiting.
Add aliasing values for :
- Pythonic
- globals declarations
- current function arguments
'''
self.aliases = IntrinsicAliases.copy()
self.aliases... | Initialise aliasing default value before visiting.
Add aliasing values for :
- Pythonic
- globals declarations
- current function arguments |
def regex(self, *pattern, **kwargs):
"""
Add re pattern
:param pattern:
:type pattern:
:return: self
:rtype: Rebulk
"""
self.pattern(self.build_re(*pattern, **kwargs))
return self | Add re pattern
:param pattern:
:type pattern:
:return: self
:rtype: Rebulk |
def _join_strings(x):
"""Joins adjacent Str elements found in the element list 'x'."""
for i in range(len(x)-1): # Process successive pairs of elements
if x[i]['t'] == 'Str' and x[i+1]['t'] == 'Str':
x[i]['c'] += x[i+1]['c']
del x[i+1] # In-place deletion of element from list
... | Joins adjacent Str elements found in the element list 'x'. |
def data_period_start_day_of_week(self, value=None):
"""Corresponds to IDD Field `data_period_start_day_of_week`
Args:
value (str): value for IDD Field `data_period_start_day_of_week`
Accepted values are:
- Sunday
- Monday
... | Corresponds to IDD Field `data_period_start_day_of_week`
Args:
value (str): value for IDD Field `data_period_start_day_of_week`
Accepted values are:
- Sunday
- Monday
- Tuesday
- Wednesday
... |
def _match_registers(self, query):
"""Tries to match in status registers
:param query: message tuple
:type query: Tuple[bytes]
:return: response if found or None
:rtype: Tuple[bytes] | None
"""
if query in self._status_registers:
register = self._stat... | Tries to match in status registers
:param query: message tuple
:type query: Tuple[bytes]
:return: response if found or None
:rtype: Tuple[bytes] | None |
def id(self): # pylint: disable=invalid-name,too-many-branches,too-many-return-statements
"""Return a unique id for the detected chip, if any."""
# There are some times we want to trick the platform detection
# say if a raspberry pi doesn't have the right ID, or for testing
try:
... | Return a unique id for the detected chip, if any. |
def error_retry_codes(self, value):
"""Set value for error_retry_codes."""
if isinstance(value, six.string_types):
value = [int(x) for x in value.split(",")]
self._set_option("error_retry_codes", value) | Set value for error_retry_codes. |
def focal(self):
"""
Get the focal length in pixels for the camera.
Returns
------------
focal : (2,) float
Focal length in pixels
"""
if self._focal is None:
# calculate focal length from FOV
focal = [(px / 2.0) / np.tan(np.radi... | Get the focal length in pixels for the camera.
Returns
------------
focal : (2,) float
Focal length in pixels |
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 get_serial_port():
""" Return serial.Serial instance, ready to use for RS485."""
port = Serial(port='/dev/ttyS1', baudrate=9600, parity=PARITY_NONE,
stopbits=1, bytesize=8, timeout=1)
fh = port.fileno()
# A struct with configuration for serial port.
serial_rs485 = struct.pack... | Return serial.Serial instance, ready to use for RS485. |
def add_pypiper_args(parser, groups=("pypiper", ), args=None,
required=None, all_args=False):
"""
Use this to add standardized pypiper arguments to your python pipeline.
There are two ways to use `add_pypiper_args`: by specifying argument groups,
or by specifying individual argumen... | Use this to add standardized pypiper arguments to your python pipeline.
There are two ways to use `add_pypiper_args`: by specifying argument groups,
or by specifying individual arguments. Specifying argument groups will add
multiple arguments to your parser; these convenient argument groupings
make it ... |
def worker_edit(worker, lbn, settings, profile='default'):
'''
Edit the worker settings
Note: http://tomcat.apache.org/connectors-doc/reference/status.html
Data Parameters for the standard Update Action
CLI Examples:
.. code-block:: bash
salt '*' modjk.worker_edit node1 loadbalancer1... | Edit the worker settings
Note: http://tomcat.apache.org/connectors-doc/reference/status.html
Data Parameters for the standard Update Action
CLI Examples:
.. code-block:: bash
salt '*' modjk.worker_edit node1 loadbalancer1 "{'vwf': 500, 'vwd': 60}"
salt '*' modjk.worker_edit node1 loa... |
def get_font_files():
"""Returns a list of all font files we could find
Returned as a list of dir/files tuples::
get_font_files() -> {'FontName': '/abs/FontName.ttf', ...]
For example::
>>> fonts = get_font_files()
>>> 'NotoSans-Bold' in fonts
True
>>> fonts['Noto... | Returns a list of all font files we could find
Returned as a list of dir/files tuples::
get_font_files() -> {'FontName': '/abs/FontName.ttf', ...]
For example::
>>> fonts = get_font_files()
>>> 'NotoSans-Bold' in fonts
True
>>> fonts['NotoSans-Bold'].endswith('/NotoSa... |
def generateCatalog(wcs, mode='automatic', catalog=None,
src_find_filters=None, **kwargs):
""" Function which determines what type of catalog object needs to be
instantiated based on what type of source selection algorithm the user
specified.
Parameters
----------
wcs : obj
... | Function which determines what type of catalog object needs to be
instantiated based on what type of source selection algorithm the user
specified.
Parameters
----------
wcs : obj
WCS object generated by STWCS or PyWCS
catalog : str or ndarray
Filename of existing catalog or nd... |
def _check_quotas(self, time_ms):
"""
Check if we have violated our quota for any metric that
has a configured quota
"""
for metric in self._metrics:
if metric.config and metric.config.quota:
value = metric.value(time_ms)
if not metric.... | Check if we have violated our quota for any metric that
has a configured quota |
def google_app_engine_ndb_delete_expired_sessions(dormant_for=86400, limit=500):
"""
Deletes expired sessions
A session is expired if it expires date is set and has passed or
if it has not been accessed for a given period of time.
:param dormant_for: seconds since last access to delete sessions, de... | Deletes expired sessions
A session is expired if it expires date is set and has passed or
if it has not been accessed for a given period of time.
:param dormant_for: seconds since last access to delete sessions, defaults to 24 hours.
:type dormant_for: int
:param limit: amount to delete in one call... |
def get_default_config(self):
"""
Returns the default collector settings
"""
config = super(OneWireCollector, self).get_default_config()
config.update({
'path': 'owfs',
'owfs': '/mnt/1wire',
# 'scan': {'temperature': 't'},
# 'id:24.... | Returns the default collector settings |
def RestrictFeedItemToAdGroup(client, feed_item, adgroup_id):
"""Restricts the feed item to an ad group.
Args:
client: an AdWordsClient instance.
feed_item: The feed item.
adgroup_id: The ad group ID.
"""
# Get the FeedItemTargetService
feed_item_target_service = client.GetService(
'FeedIte... | Restricts the feed item to an ad group.
Args:
client: an AdWordsClient instance.
feed_item: The feed item.
adgroup_id: The ad group ID. |
def update_visited(self):
"""
Updates exploration map visited status
"""
assert isinstance(self.player.cshape.center, eu.Vector2)
pos = self.player.cshape.center
# Helper function
def set_visited(layer, cell):
if cell and not cell.properties.get('visi... | Updates exploration map visited status |
def read_vensim(mdl_file):
"""
Construct a model from Vensim `.mdl` file.
Parameters
----------
mdl_file : <string>
The relative path filename for a raw Vensim `.mdl` file
Returns
-------
model: a PySD class object
Elements from the python model are loaded into the PySD... | Construct a model from Vensim `.mdl` file.
Parameters
----------
mdl_file : <string>
The relative path filename for a raw Vensim `.mdl` file
Returns
-------
model: a PySD class object
Elements from the python model are loaded into the PySD class and ready to run
Examples
... |
def make_mapcube_source(name, Spatial_Filename, spectrum):
"""Construct and return a `fermipy.roi_model.MapCubeSource` object
"""
data = dict(Spatial_Filename=Spatial_Filename)
if spectrum is not None:
data.update(spectrum)
return roi_model.MapCubeSource(name, data) | Construct and return a `fermipy.roi_model.MapCubeSource` object |
def build(self, builder):
"""Build XML by appending to builder"""
params = {}
if self.lang is not None:
params["xml:lang"] = self.lang
builder.start("TranslatedText", params)
builder.data(self.text)
builder.end("TranslatedText") | Build XML by appending to builder |
def spectral_density_vega(wav, vegaflux):
"""Flux equivalencies between PHOTLAM and VEGAMAG.
Parameters
----------
wav : `~astropy.units.quantity.Quantity`
Quantity associated with values being converted
(e.g., wavelength or frequency).
vegaflux : `~astropy.units.quantity.Quantity`... | Flux equivalencies between PHOTLAM and VEGAMAG.
Parameters
----------
wav : `~astropy.units.quantity.Quantity`
Quantity associated with values being converted
(e.g., wavelength or frequency).
vegaflux : `~astropy.units.quantity.Quantity`
Flux of Vega at ``wav``.
Returns
... |
def get_or_connect(self, address, authenticator=None):
"""
Gets the existing connection for a given address. If it does not exist, the system will try to connect
asynchronously. In this case, it returns a Future. When the connection is established at some point in time, it
can be retriev... | Gets the existing connection for a given address. If it does not exist, the system will try to connect
asynchronously. In this case, it returns a Future. When the connection is established at some point in time, it
can be retrieved by using the get_connection(:class:`~hazelcast.core.Address`) or from Fu... |
def check_structure(self, keys):
r"""Check structure availability by ``attrkey`` and ``valuekey`` option.
"""
return set(keys) <= set([self.__options['attrkey'], self.__options['valuekey']]) | r"""Check structure availability by ``attrkey`` and ``valuekey`` option. |
def from_csv(cls, filename: str):
"""
Imports PDEntries from a csv.
Args:
filename: Filename to import from.
Returns:
List of Elements, List of PDEntries
"""
with open(filename, "r", encoding="utf-8") as f:
reader = csv.reader(f, deli... | Imports PDEntries from a csv.
Args:
filename: Filename to import from.
Returns:
List of Elements, List of PDEntries |
def _parse_keys(row, line_num):
""" Perform some sanity checks on they keys
Each key in the row should not be named None cause
(that's an overrun). A key named `type` MUST be
present on the row & have a string value.
:param row: dict
:param line_num: int
"""
... | Perform some sanity checks on they keys
Each key in the row should not be named None cause
(that's an overrun). A key named `type` MUST be
present on the row & have a string value.
:param row: dict
:param line_num: int |
def set_client_info(cls, client_id, client_ver):
"""
.. py:function:: set_client_info(cls, client_id, client_ver)
设置调用api的客户端信息, 非必调接口
:param client_id: str, 客户端标识
:param client_ver: int, 客户端版本号
:return: None
:example:
.. code:: python
from ... | .. py:function:: set_client_info(cls, client_id, client_ver)
设置调用api的客户端信息, 非必调接口
:param client_id: str, 客户端标识
:param client_ver: int, 客户端版本号
:return: None
:example:
.. code:: python
from futuquant import *
SysConfig.set_client_info("MyFutuQuant", ... |
def fire(obj, name, *args, **kwargs):
"""
Arrange for `func(*args, **kwargs)` to be invoked for every function
registered for the named signal on `obj`.
"""
signals = vars(obj).get('_signals', {})
for func in signals.get(name, ()):
func(*args, **kwargs) | Arrange for `func(*args, **kwargs)` to be invoked for every function
registered for the named signal on `obj`. |
def _bnd(self, xloc, left, right, cache):
"""
Distribution bounds.
Example:
>>> print(chaospy.Uniform().range([-2, 0, 2, 4]))
[[0. 0. 0. 0.]
[1. 1. 1. 1.]]
>>> print(Mul(chaospy.Uniform(), 2).range([-2, 0, 2, 4]))
[[0. 0. 0. 0.]
... | Distribution bounds.
Example:
>>> print(chaospy.Uniform().range([-2, 0, 2, 4]))
[[0. 0. 0. 0.]
[1. 1. 1. 1.]]
>>> print(Mul(chaospy.Uniform(), 2).range([-2, 0, 2, 4]))
[[0. 0. 0. 0.]
[2. 2. 2. 2.]]
>>> print(Mul(2, chaospy.Un... |
def unit_targeting(w, k):
"""Unit-level magnitude pruning."""
k = tf.to_int32(k)
w_shape = shape_list(w)
size = tf.to_int32(tf.reduce_prod(w_shape[:-1]))
w = tf.reshape(w, [size, w_shape[-1]])
norm = tf.norm(w, axis=0)
thres = tf.contrib.framework.sort(norm, axis=0)[k]
mask = to_float(thres >= norm)[No... | Unit-level magnitude pruning. |
def get_composition_form_for_create(self, composition_record_types):
"""Gets the composition form for creating new compositions.
A new form should be requested for each create transaction.
arg: composition_record_types (osid.type.Type[]): array of
composition record types
... | Gets the composition form for creating new compositions.
A new form should be requested for each create transaction.
arg: composition_record_types (osid.type.Type[]): array of
composition record types
return: (osid.repository.CompositionForm) - the composition form
r... |
def get(self, name):
"""Get a tag.
:param name: Tag name as string.
:return: :class:`tags.Tag <tags.Tag>` object
:rtype: tags.Tag
"""
schema = TagSchema()
resp = self.service.get_id(self.base, name)
return self.service.decode(schema, resp) | Get a tag.
:param name: Tag name as string.
:return: :class:`tags.Tag <tags.Tag>` object
:rtype: tags.Tag |
def checks(self, format, raises=()):
"""
Register a decorated function as validating a new format.
Arguments:
format (str):
The format that the decorated function will check.
raises (Exception):
The exception(s) raised by the decorated... | Register a decorated function as validating a new format.
Arguments:
format (str):
The format that the decorated function will check.
raises (Exception):
The exception(s) raised by the decorated function when an
invalid instance is fou... |
def get_volume(cont, pos_x, pos_y, pix):
"""Calculate the volume of a polygon revolved around an axis
The volume estimation assumes rotational symmetry.
Green`s theorem and the Gaussian divergence theorem allow to
formulate the volume as a line integral.
Parameters
----------
cont: ndarray... | Calculate the volume of a polygon revolved around an axis
The volume estimation assumes rotational symmetry.
Green`s theorem and the Gaussian divergence theorem allow to
formulate the volume as a line integral.
Parameters
----------
cont: ndarray or list of ndarrays of shape (N,2)
A 2D... |
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 validate_row(self, row):
"""
Ensure each element in the row matches the schema.
"""
clean_row = {}
if isinstance(row, (tuple, list)):
assert self.header_order, "No attribute order specified."
assert len(row) == len(self.header_order), \
... | Ensure each element in the row matches the schema. |
def _extract_features(self):
"""
Get the feature data from the log file necessary for a reduction
"""
for parsed_line in self.parsed_lines:
result = {'raw': parsed_line}
if 'ip' in parsed_line:
result['ip'] = parsed_line['ip']
if r... | Get the feature data from the log file necessary for a reduction |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.