code stringlengths 75 104k | docstring stringlengths 1 46.9k |
|---|---|
def get_system_offset():
"""Get system's timezone offset using built-in library time.
For the Timezone constants (altzone, daylight, timezone, and tzname), the
value is determined by the timezone rules in effect at module load time or
the last time tzset() is called and may be incorrect for times in th... | Get system's timezone offset using built-in library time.
For the Timezone constants (altzone, daylight, timezone, and tzname), the
value is determined by the timezone rules in effect at module load time or
the last time tzset() is called and may be incorrect for times in the past.
To keep compatibili... |
def _get_initial_residual(self, x0):
'''Return the projected initial residual.
Returns :math:`MPM_l(b-Ax_0)`.
'''
if x0 is None:
Mlr = self.linear_system.Mlb
else:
r = self.linear_system.b - self.linear_system.A*x0
Mlr = self.linear_system.Ml*... | Return the projected initial residual.
Returns :math:`MPM_l(b-Ax_0)`. |
def remove_rule(self, rule):
"""Remove rule from :attr:`R` and its corresponding weight from
:attr:`W`.
:param rule: rule to remove
:type rule:
:class:`~creamas.rules.rule.Rule` or
:class:`~creamas.rules.rule.RuleLeaf`
:raises TypeError:
If ru... | Remove rule from :attr:`R` and its corresponding weight from
:attr:`W`.
:param rule: rule to remove
:type rule:
:class:`~creamas.rules.rule.Rule` or
:class:`~creamas.rules.rule.RuleLeaf`
:raises TypeError:
If rule is not derived from :class:`Rule` or ... |
def get_recent_linkbacks(number=5,
template='zinnia/tags/linkbacks_recent.html'):
"""
Return the most recent linkbacks.
"""
entry_published_pks = map(smart_text,
Entry.published.values_list('id', flat=True))
content_type = ContentType.objects.ge... | Return the most recent linkbacks. |
def load_data(path, dense=False):
"""Load data from a CSV, LibSVM or HDF5 file based on the file extension.
Args:
path (str): A path to the CSV, LibSVM or HDF5 format file containing data.
dense (boolean): An optional variable indicating if the return matrix
should be d... | Load data from a CSV, LibSVM or HDF5 file based on the file extension.
Args:
path (str): A path to the CSV, LibSVM or HDF5 format file containing data.
dense (boolean): An optional variable indicating if the return matrix
should be dense. By default, it is false.
Retu... |
def check_description(package_info, *args):
"""
Does the package have a description listed?
:param package_info: package_info dictionary
:return: Tuple (is the condition True or False?, reason if it is False else None)
"""
reason = "Description missing"
result = False
if package_info.ge... | Does the package have a description listed?
:param package_info: package_info dictionary
:return: Tuple (is the condition True or False?, reason if it is False else None) |
def signingPayloadState(self, identifier=None):
"""
Special signing state where the the data for an attribute is hashed
before signing
:return: state to be used when signing
"""
if self.operation.get(TXN_TYPE) == ATTRIB:
d = deepcopy(super().signingPayloadStat... | Special signing state where the the data for an attribute is hashed
before signing
:return: state to be used when signing |
def _read_motifs_from_filehandle(handle, fmt):
"""
Read motifs from a file-like object.
Parameters
----------
handle : file-like object
Motifs.
fmt : string, optional
Motif format, can be 'pwm', 'transfac', 'xxmotif', 'jaspar' or 'align'.
Returns
-------
motifs... | Read motifs from a file-like object.
Parameters
----------
handle : file-like object
Motifs.
fmt : string, optional
Motif format, can be 'pwm', 'transfac', 'xxmotif', 'jaspar' or 'align'.
Returns
-------
motifs : list
List of Motif instances. |
def ceil(cls, x: 'TensorFluent') -> 'TensorFluent':
'''Returns a TensorFluent for the ceil function.
Args:
x: The input fluent.
Returns:
A TensorFluent wrapping the ceil function.
'''
return cls._unary_op(x, tf.ceil, tf.float32) | Returns a TensorFluent for the ceil function.
Args:
x: The input fluent.
Returns:
A TensorFluent wrapping the ceil function. |
def create(self, task_name, clone_task=None):
""" Creates a new task directory.
`task_name`
Task name.
`clone_task`
Existing task name to use as a template for new task.
Returns boolean.
* Raises ``Value`` if task name is invalid... | Creates a new task directory.
`task_name`
Task name.
`clone_task`
Existing task name to use as a template for new task.
Returns boolean.
* Raises ``Value`` if task name is invalid, ``TaskExists`` if task
already exists, or ... |
async def request(self, method, path, json=None, auth=True):
"""Make a request to the API."""
url = 'http://{}/api/'.format(self.host)
if auth:
url += '{}/'.format(self.username)
url += path
try:
async with self.websession.request(method, url, json=json) ... | Make a request to the API. |
def isBool(self, type):
"""
is the type a boolean value?
:param type: PKCS#11 type like `CKA_ALWAYS_SENSITIVE`
:rtype: bool
"""
if type in (CKA_ALWAYS_SENSITIVE,
CKA_DECRYPT,
CKA_DERIVE,
CKA_ENCRYPT,
... | is the type a boolean value?
:param type: PKCS#11 type like `CKA_ALWAYS_SENSITIVE`
:rtype: bool |
def first(self, default=None, as_dict=False, as_ordereddict=False):
"""Returns a single record for the RecordCollection, or `default`. If
`default` is an instance or subclass of Exception, then raise it
instead of returning it."""
# Try to get a record, or return/raise default.
... | Returns a single record for the RecordCollection, or `default`. If
`default` is an instance or subclass of Exception, then raise it
instead of returning it. |
def eccentricity(self):
"""
The eccentricity of the 2D Gaussian function that has the same
second-order moments as the source.
The eccentricity is the fraction of the distance along the
semimajor axis at which the focus lies.
.. math:: e = \\sqrt{1 - \\frac{b^2}{a^2}}
... | The eccentricity of the 2D Gaussian function that has the same
second-order moments as the source.
The eccentricity is the fraction of the distance along the
semimajor axis at which the focus lies.
.. math:: e = \\sqrt{1 - \\frac{b^2}{a^2}}
where :math:`a` and :math:`b` are th... |
def get_data_iters(dataset, batch_size, opt):
"""get dataset iterators"""
if dataset == 'mnist':
train_data, val_data = get_mnist_iterator(batch_size, (1, 28, 28),
num_parts=kv.num_workers, part_index=kv.rank)
elif dataset == 'cifar10':
train... | get dataset iterators |
def settings(self):
"""Retrieve and cache settings from server"""
if not self.__settings:
self.__settings = self.request('get', 'settings').json()
return self.__settings | Retrieve and cache settings from server |
def _multiplexed_response_stream_helper(self, response):
"""A generator of multiplexed data blocks coming from a response
stream."""
# Disable timeout on the underlying socket to prevent
# Read timed out(s) for long running processes
socket = self._get_raw_response_socket(respon... | A generator of multiplexed data blocks coming from a response
stream. |
def script_run(trun, script):
"""Execute a script or testcase"""
if trun["conf"]["VERBOSE"]:
cij.emph("rnr:script:run { script: %s }" % script)
cij.emph("rnr:script:run:evars: %s" % script["evars"])
launchers = {
".py": "python",
".sh": "source"
}
ext = os.path.spl... | Execute a script or testcase |
def exposure_units(exposure):
"""Helper to get unit of an exposure.
:param exposure: Exposure type.
:type exposure: str
:returns: List of exposure units.
:rtype: list
"""
units = definition(exposure)['units']
return sorted(units, key=lambda k: k['key']) | Helper to get unit of an exposure.
:param exposure: Exposure type.
:type exposure: str
:returns: List of exposure units.
:rtype: list |
def get_properties_obj(self):
"""Get the underlying C reference from this object.
:rtype: uamqp.c_uamqp.cProperties
"""
properties = c_uamqp.cProperties()
self._set_attr('message_id', properties)
self._set_attr('user_id', properties)
self._set_attr('to', properti... | Get the underlying C reference from this object.
:rtype: uamqp.c_uamqp.cProperties |
def _elements(self):
"""Composed tuple storing actual sequence of element objects."""
ElementCls, element_dicts = self._element_makings
return tuple(
ElementCls(element_dict, idx, element_dicts)
for idx, element_dict in enumerate(element_dicts)
) | Composed tuple storing actual sequence of element objects. |
def to_segmentlistdict(self):
"""
Return a segmentlistdict object describing the instruments
and times spanned by the entries in this Cache. The return
value is coalesced.
"""
d = segments.segmentlistdict()
for entry in self:
d |= entry.segmentlistdict
return d | Return a segmentlistdict object describing the instruments
and times spanned by the entries in this Cache. The return
value is coalesced. |
def sum(self, expression, binby=[], limits=None, shape=default_shape, selection=False, delay=False, progress=None, edges=False):
"""Calculate the sum for the given expression, possible on a grid defined by binby
Example:
>>> df.sum("L")
304054882.49378014
>>> df.sum("L", binby=... | Calculate the sum for the given expression, possible on a grid defined by binby
Example:
>>> df.sum("L")
304054882.49378014
>>> df.sum("L", binby="E", shape=4)
array([ 8.83517994e+06, 5.92217598e+07, 9.55218726e+07,
1.40008776e+08])
:param... |
def weekday_series(self, start, end, weekday, return_date=False):
"""Generate a datetime series with same weekday number.
ISO weekday number: Mon to Sun = 1 to 7
Usage::
>>> start, end = "2014-01-01 06:30:25", "2014-02-01 06:30:25"
>>> rolex.weekday_series(start, end, ... | Generate a datetime series with same weekday number.
ISO weekday number: Mon to Sun = 1 to 7
Usage::
>>> start, end = "2014-01-01 06:30:25", "2014-02-01 06:30:25"
>>> rolex.weekday_series(start, end, weekday=2) # All Tuesday
[
datetime(2014, 1, 7, 6... |
def filter_repo_urls(candidates):
"""
Filters down a list of URL candidates
:param candidates: list, URL candidates
:return: set, Repo URLs
"""
# first, we are going to filter down the URL candidates to be all valid urls
candidates = set(url for url in [validate_url(_url) for _url in candida... | Filters down a list of URL candidates
:param candidates: list, URL candidates
:return: set, Repo URLs |
def merge_adjacent(dom, tag_name):
"""
Merge all adjacent tags with the specified tag name.
Return the number of merges performed.
"""
for node in dom.getElementsByTagName(tag_name):
prev_sib = node.previousSibling
if prev_sib and prev_sib.nodeName == node.tagName:
for ch... | Merge all adjacent tags with the specified tag name.
Return the number of merges performed. |
def timethis(label, receiver_fn=None):
""" Times a block of code
Inspired from David Beazley talk - Generators: The Final Frontier"""
start = time.time()
try:
yield
finally:
end = time.time()
if receiver_fn:
receiver_fn(label, start, end)
else:
... | Times a block of code
Inspired from David Beazley talk - Generators: The Final Frontier |
def plot(self,
data,
chart_type,
chart_package='corechart',
options=None,
w=800,
h=420):
"""Output an iframe containing the plot in the notebook without saving."""
return HTML(
self.iframe.format(
s... | Output an iframe containing the plot in the notebook without saving. |
def _match_tag_regex(self, event_tag, search_tag):
'''
Check if the event_tag matches the search check.
Uses regular expression search to check.
Return True (matches) or False (no match)
'''
return self.cache_regex.get(search_tag).search(event_tag) is not None | Check if the event_tag matches the search check.
Uses regular expression search to check.
Return True (matches) or False (no match) |
def color_mask(self) -> Tuple[bool, bool, bool, bool]:
'''
tuple: The color mask of the framebuffer.
'''
return self.mglo.color_mask | tuple: The color mask of the framebuffer. |
def set_value(self, value):
"""
Set the current value of the property.
value -- the value to set
"""
self.validate_value(value)
self.value.set(value) | Set the current value of the property.
value -- the value to set |
def get_by_id(self, id_interface):
"""Get an interface by id.
:param id_interface: Interface identifier.
:return: Following dictionary:
::
{'interface': {'id': < id >,
'interface': < interface >,
'descricao': < descricao >,
'protegida':... | Get an interface by id.
:param id_interface: Interface identifier.
:return: Following dictionary:
::
{'interface': {'id': < id >,
'interface': < interface >,
'descricao': < descricao >,
'protegida': < protegida >,
'tipo_equip': < id... |
def load_state(cls, fname):
"""
Load the state of this node (the alpha/ksize/id/immediate neighbors)
from a cache file with the given fname.
"""
log.info("Loading state from %s", fname)
with open(fname, 'rb') as file:
data = pickle.load(file)
svr = Ser... | Load the state of this node (the alpha/ksize/id/immediate neighbors)
from a cache file with the given fname. |
def get_es_mappings(self):
"""
Returns the mapping defitions presetn in elasticsearh
"""
es_mappings = json.loads(requests.get(self.mapping_url).text)
es_mappings = {"_".join(key.split("_")[:-1]): value['mappings'] \
for key, value in es_mappings.it... | Returns the mapping defitions presetn in elasticsearh |
def _process_node(self,node):
"""Process first level element of the stream.
Handle component handshake (authentication) element, and
treat elements in "jabber:component:accept", "jabber:client"
and "jabber:server" equally (pass to `self.process_stanza`).
All other elements are p... | Process first level element of the stream.
Handle component handshake (authentication) element, and
treat elements in "jabber:component:accept", "jabber:client"
and "jabber:server" equally (pass to `self.process_stanza`).
All other elements are passed to `Stream._process_node`.
... |
def value_to_python(self, value):
"""
Converts the input single value into the expected Python data type,
raising django.core.exceptions.ValidationError if the data can't be
converted. Returns the converted value. Subclasses should override
this.
"""
if not isins... | Converts the input single value into the expected Python data type,
raising django.core.exceptions.ValidationError if the data can't be
converted. Returns the converted value. Subclasses should override
this. |
def get_version_list(path=None, module=None):
"""Return the version information as a tuple.
This uses get_version and breaks the string up. Would make more sense if
the version was a tuple throughout katversion.
"""
major = 0
minor = 0
patch = '' # PEP440 calls this prerelease, postreleas... | Return the version information as a tuple.
This uses get_version and breaks the string up. Would make more sense if
the version was a tuple throughout katversion. |
def _strategy(codes, context):
"""
Convert SRE regex parse tree to strategy that generates strings matching that
regex represented by that parse tree.
`codes` is either a list of SRE regex elements representations or a particular
element representation. Each element is a tuple of element code (as s... | Convert SRE regex parse tree to strategy that generates strings matching that
regex represented by that parse tree.
`codes` is either a list of SRE regex elements representations or a particular
element representation. Each element is a tuple of element code (as string) and
parameters. E.g. regex 'ab[0... |
def get_as_array(self, key):
"""
Converts map element into an AnyValueMap or returns empty AnyValueMap if conversion is not possible.
:param key: an index of element to get.
:return: AnyValueMap value of the element or empty AnyValueMap if conversion is not supported.
"""
... | Converts map element into an AnyValueMap or returns empty AnyValueMap if conversion is not possible.
:param key: an index of element to get.
:return: AnyValueMap value of the element or empty AnyValueMap if conversion is not supported. |
def read_binary_matrix(filename):
"""Reads and returns binary formatted matrix stored in filename.
The file format is described on the data set page:
https://cs.nyu.edu/~ylclab/data/norb-v1.0-small/
Args:
filename: String with path to the file.
Returns:
Numpy array contained in the file.
"""
wi... | Reads and returns binary formatted matrix stored in filename.
The file format is described on the data set page:
https://cs.nyu.edu/~ylclab/data/norb-v1.0-small/
Args:
filename: String with path to the file.
Returns:
Numpy array contained in the file. |
def list_organizations(container_id=None, include_validation=True):
'''
List organizations that CertCentral knows about. You can filter by
container_id (also known as "Division") by passing a container_id.
This function returns validation information by default; pass
``include_validation=False`` to ... | List organizations that CertCentral knows about. You can filter by
container_id (also known as "Division") by passing a container_id.
This function returns validation information by default; pass
``include_validation=False`` to turn it off.
CLI Example:
.. code-block:: bash
salt-run digic... |
def diffusive_heat_transport(self):
"""Compute instantaneous diffusive heat transport in unit :math:`\\textrm{PW}`
on the staggered grid (bounds) through calculating:
.. math::
H(\\varphi) = - 2 \pi R^2 cos(\\varphi) D \\frac{dT}{d\\varphi}
\\approx - 2 \pi ... | Compute instantaneous diffusive heat transport in unit :math:`\\textrm{PW}`
on the staggered grid (bounds) through calculating:
.. math::
H(\\varphi) = - 2 \pi R^2 cos(\\varphi) D \\frac{dT}{d\\varphi}
\\approx - 2 \pi R^2 cos(\\varphi) D \\frac{\Delta T}{\Delta \\v... |
def list_group_users(self, group_id, **kwargs):
"""List users of a group.
:param str group_id: The group ID (Required)
:param int limit: The number of users to retrieve
:param str order: The ordering direction, ascending (asc) or descending (desc)
:param str after: Get API keys ... | List users of a group.
:param str group_id: The group ID (Required)
:param int limit: The number of users to retrieve
:param str order: The ordering direction, ascending (asc) or descending (desc)
:param str after: Get API keys after/starting at given user ID
:returns: a list of... |
def box(b, line_width=2, color='g', style='-'):
""" Draws a box on the current plot.
Parameters
----------
b : :obj:`autolab_core.Box`
box to draw
line_width : int
width of lines on side of box
color : :obj:`str`
color of box
s... | Draws a box on the current plot.
Parameters
----------
b : :obj:`autolab_core.Box`
box to draw
line_width : int
width of lines on side of box
color : :obj:`str`
color of box
style : :obj:`str`
style of lines to draw |
def xview(self, *args):
"""Update inplace widgets position when doing horizontal scroll"""
self.after_idle(self.__updateWnds)
ttk.Treeview.xview(self, *args) | Update inplace widgets position when doing horizontal scroll |
def CreateAndStartHunt(flow_name, flow_args, creator, **kwargs):
"""Creates and starts a new hunt."""
# This interface takes a time when the hunt expires. However, the legacy hunt
# starting interface took an rdfvalue.Duration object which was then added to
# the current time to get the expiry. This check exis... | Creates and starts a new hunt. |
def debug_async(self, conn_id, cmd_name, cmd_args, progress_callback, callback):
"""Asynchronously complete a named debug command.
The command name and arguments are passed to the underlying device adapter
and interpreted there. If the command is long running, progress_callback
may be ... | Asynchronously complete a named debug command.
The command name and arguments are passed to the underlying device adapter
and interpreted there. If the command is long running, progress_callback
may be used to provide status updates. Callback is called when the command
has finished.
... |
def send_ping(self, payload=None):
"""
Sends the ping after the interval specified when initializing
"""
yield from asyncio.sleep(self._interval)
self._handler.send_ping(payload=payload)
self._start_timer(payload=payload) | Sends the ping after the interval specified when initializing |
def directive_DCB(self, label, params):
"""
label DCB value[, value ...]
Allocate a byte space in read only memory for the value or list of values
"""
# TODO make this read only
# TODO check for byte size
self.labels[label] = self.space_pointer
if param... | label DCB value[, value ...]
Allocate a byte space in read only memory for the value or list of values |
def _get_shard_names(self, args):
"""
Get the shard names based on the self.args['sharded'] parameter.
If it's a number, create shard names of type shard##, where ## is a
2-digit number. Returns a list [None] if no shards are present.
"""
if 'sharded' in args and args['s... | Get the shard names based on the self.args['sharded'] parameter.
If it's a number, create shard names of type shard##, where ## is a
2-digit number. Returns a list [None] if no shards are present. |
def rp_module_level_in_stack():
"""
Returns true if we're during a rootpy import
"""
from traceback import extract_stack
from rootpy import _ROOTPY_SOURCE_PATH
modlevel_files = [filename for filename, _, func, _ in extract_stack()
if func == "<module>"]
return any(path... | Returns true if we're during a rootpy import |
def as_security_error(node, secid):
""" convert the securityError element to a SecurityError """
assert node.Name == 'securityError'
src = XmlHelper.get_child_value(node, 'source')
code = XmlHelper.get_child_value(node, 'code')
cat = XmlHelper.get_child_value(node, 'category')
... | convert the securityError element to a SecurityError |
def stopword_remove(self, items, threshold=False):
"""
Remove stopwords from either tokens (items = "tokens")
or stems (items = "stems")
"""
def remove(tokens):
return [t for t in tokens if t not in self.stopwords]
if items == 'tokens':
self.tok... | Remove stopwords from either tokens (items = "tokens")
or stems (items = "stems") |
def ensure_geo_reference(origin):
"""
Given a list/tuple of zone, xllcorner and yllcorner of a geo-ref object,
return a geo ref object.
If the origin is None, return None, so calling this function doesn't
effect code logic
"""
if isinstance(origin, Geo_reference):
geo_ref = origin
... | Given a list/tuple of zone, xllcorner and yllcorner of a geo-ref object,
return a geo ref object.
If the origin is None, return None, so calling this function doesn't
effect code logic |
def _process_dbxref(self):
"""
We bring in the dbxref identifiers and store them in a hashmap for
lookup in other functions.
Note that some dbxrefs aren't mapped to identifiers.
For example, 5004018 is mapped to a string,
"endosome & imaginal disc epithelial cell | so... | We bring in the dbxref identifiers and store them in a hashmap for
lookup in other functions.
Note that some dbxrefs aren't mapped to identifiers.
For example, 5004018 is mapped to a string,
"endosome & imaginal disc epithelial cell | somatic clone..."
In those cases, there j... |
def get_charset(response):
""" Return charset from ``response`` or default charset.
:rtype: str
"""
# Set default charset
charset = DEFAULT_CHARSET
m = re.findall(r';charset=(.*)', response.get('mimeType', ''))
if m:
charset = m[0]
return charset | Return charset from ``response`` or default charset.
:rtype: str |
def extract_locals(trcback):
"""
Extracts the frames locals of given traceback.
:param trcback: Traceback.
:type trcback: Traceback
:return: Frames locals.
:rtype: list
"""
output = []
stack = extract_stack(get_inner_most_frame(trcback))
for frame, file_name, line_number, name,... | Extracts the frames locals of given traceback.
:param trcback: Traceback.
:type trcback: Traceback
:return: Frames locals.
:rtype: list |
def generate_nb_state_data(means, weights, R):
"""
Generates data according to the Negative Binomial Convex Mixture Model.
Args:
means (array): Cell types- genes x clusters
weights (array): Cell cluster assignments- clusters x cells
R (array): dispersion parameter - 1 x genes
R... | Generates data according to the Negative Binomial Convex Mixture Model.
Args:
means (array): Cell types- genes x clusters
weights (array): Cell cluster assignments- clusters x cells
R (array): dispersion parameter - 1 x genes
Returns:
data matrix - genes x cells |
def usufyToXlsxExport(d, fPath):
"""
Workaround to export to a .xlsx file.
Args:
-----
d: Data to export.
fPath: File path for the output file.
"""
from pyexcel_xlsx import get_data
try:
#oldData = get_data(fPath)
# A change in the API now returns only an arr... | Workaround to export to a .xlsx file.
Args:
-----
d: Data to export.
fPath: File path for the output file. |
def _makedirs(self, path):
"""Make folders recursively for the given path and
check read and write permission on the path
Args:
path -- path to the leaf folder
"""
try:
oldmask = os.umask(0)
os.makedirs(path, self._conf['dmode'])
... | Make folders recursively for the given path and
check read and write permission on the path
Args:
path -- path to the leaf folder |
def draw_on(self, folium_map):
"""Add feature to Folium map object."""
f = getattr(folium_map, self._map_method_name)
f(**self._folium_kwargs) | Add feature to Folium map object. |
def read_raw_pressure(self):
"""Reads the raw (uncompensated) pressure level from the sensor."""
self._device.write8(BMP085_CONTROL, BMP085_READPRESSURECMD + (self._mode << 6))
if self._mode == BMP085_ULTRALOWPOWER:
time.sleep(0.005)
elif self._mode == BMP085_HIGHRES:
... | Reads the raw (uncompensated) pressure level from the sensor. |
def reset(self):
'''
Reset the scheduler to defaults
'''
self.skip_function = None
self.skip_during_range = None
self.enabled = True
self.splay = None
self.opts['schedule'] = {} | Reset the scheduler to defaults |
def find_version(include_dev_version=True, version_file='version.txt',
version_module_paths=(),
git_args=('git', 'describe', '--tags', '--long'),
Popen=subprocess.Popen):
"""Find an appropriate version number from version control.
It's much more convenient to ... | Find an appropriate version number from version control.
It's much more convenient to be able to use your version control system's
tagging mechanism to derive a version number than to have to duplicate that
information all over the place. Currently, only git is supported.
The default behavior is to wr... |
def set_temperature(self, target_temperature):
""" Set the target temperature. """
try:
target_temperature = float(target_temperature)
except Exception as err:
LOG.debug("Thermostat.set_temperature: Exception %s" % (err,))
return False
self.writeNodeDa... | Set the target temperature. |
def showConfig( self ):
"""
Show the config widget for the currently selected plugin.
"""
item = self.uiPluginTREE.currentItem()
if not isinstance(item, PluginItem):
return
plugin = item.plugin()
widget = self.findChild(QWidget, plugin.uniqueN... | Show the config widget for the currently selected plugin. |
def init_manifest(
package_name: str, version: str, manifest_version: Optional[str] = "2"
) -> Dict[str, Any]:
"""
Returns an initial dict with the minimal requried fields for a valid manifest.
Should only be used as the first fn to be piped into a `build()` pipeline.
"""
return {
"packa... | Returns an initial dict with the minimal requried fields for a valid manifest.
Should only be used as the first fn to be piped into a `build()` pipeline. |
def save(self, filename, strip_prefix=''):
"""Save parameters to file.
Parameters
----------
filename : str
Path to parameter file.
strip_prefix : str, default ''
Strip prefix from parameter names before saving.
"""
arg_dict = {}
f... | Save parameters to file.
Parameters
----------
filename : str
Path to parameter file.
strip_prefix : str, default ''
Strip prefix from parameter names before saving. |
def write_feedback(self, feedback, cr=True):
""" Store feedback. Keep specified feedback as previous output
:param feedback: data to store
:param cr: whether to write carriage return to the end or not
:return: None
"""
self.__previous_data += feedback
if cr is True:
self.__previous_data += '\n' | Store feedback. Keep specified feedback as previous output
:param feedback: data to store
:param cr: whether to write carriage return to the end or not
:return: None |
def field_choices_attibute(function):
"""
Selection from field.choices
"""
def _wrapper(field, **kwargs):
if hasattr(field.widget, 'choices'):
return random.choice(list(valid_choices(field.widget.choices)))
return function(field, **kwargs)
return _wrapper | Selection from field.choices |
def _remove_node(self, node):
"""
Remove a CFGNode from self.graph as well as from the function manager (if it is the beginning of a function)
:param CFGNode node: The CFGNode to remove from the graph.
:return: None
"""
self.graph.remove_node(node)
if node.addr ... | Remove a CFGNode from self.graph as well as from the function manager (if it is the beginning of a function)
:param CFGNode node: The CFGNode to remove from the graph.
:return: None |
def current_rev_reg_id(base_dir: str, cd_id: str) -> str:
"""
Return the current revocation registry identifier for
input credential definition identifier, in input directory.
Raise AbsentTails if no corresponding tails file, signifying no such revocation registry defined.
:par... | Return the current revocation registry identifier for
input credential definition identifier, in input directory.
Raise AbsentTails if no corresponding tails file, signifying no such revocation registry defined.
:param base_dir: base directory for tails files, thereafter split by cred def id
... |
def json(self):
"""Custom JSON encoder"""
attributes = {
'type': self.type,
'filename': self.filename,
'line_number': self.lineno,
'hashed_secret': self.secret_hash,
}
if self.is_secret is not None:
attributes['is_secret'] = se... | Custom JSON encoder |
def segment_area(self):
'''Returns the area of the corresponding arc segment.
>>> Arc((0,0), 2, 0, 360, True).segment_area()
12.566...
>>> Arc((0,0), 2, 0, 180, True).segment_area()
6.283...
>>> Arc((0,0), 2, 0, 90, True).segment_area()
1.14159...
... | Returns the area of the corresponding arc segment.
>>> Arc((0,0), 2, 0, 360, True).segment_area()
12.566...
>>> Arc((0,0), 2, 0, 180, True).segment_area()
6.283...
>>> Arc((0,0), 2, 0, 90, True).segment_area()
1.14159...
>>> Arc((0,0), 2, 0, 90, False).se... |
def services(self):
"""gets the services in the current folder"""
services = []
if self._services is None:
self.__init()
for service in self._services:
url = "%s/%s/%s" % (self.root, service['name'], service['type'])
if service['type'] == "GPServer":
... | gets the services in the current folder |
def restrict_to_version(self, version):
"""Restricts the generated PDF file to :obj:`version`.
See :meth:`get_versions` for a list of available version values
that can be used here.
This method should only be called
before any drawing operations have been performed on the given... | Restricts the generated PDF file to :obj:`version`.
See :meth:`get_versions` for a list of available version values
that can be used here.
This method should only be called
before any drawing operations have been performed on the given surface.
The simplest way to do this is to... |
def replace_evict_func(self, func, only_read=False):
"""
>>> cache = Cache(log_level=logging.WARNING)
>>> def evict(dict, evict_number=10): pass
>>> cache.replace_evict_func(evict)
True
>>> def evict_b(dict): pass
>>> cache.replace_evict_func(evict_b)
Fals... | >>> cache = Cache(log_level=logging.WARNING)
>>> def evict(dict, evict_number=10): pass
>>> cache.replace_evict_func(evict)
True
>>> def evict_b(dict): pass
>>> cache.replace_evict_func(evict_b)
False
>>> def evict_c(dict, a, b): pass
>>> cache.replace_evi... |
def convert_coerce_type_and_add_to_where_block(coerce_type_block, where_block):
"""Create an "INSTANCEOF" Filter from a CoerceType, adding to an existing Filter if any."""
instanceof_filter = convert_coerce_type_to_instanceof_filter(coerce_type_block)
if where_block:
# There was already a Filter bl... | Create an "INSTANCEOF" Filter from a CoerceType, adding to an existing Filter if any. |
def get_hypervisors(self):
"""
Initialize the internal list containing each template available for each
hypervisor.
:return: [bool] True in case of success, otherwise False
"""
json_scheme = self.gen_def_json_scheme('GetHypervisors')
json_obj = self.call_method_p... | Initialize the internal list containing each template available for each
hypervisor.
:return: [bool] True in case of success, otherwise False |
def get_keys(self, bucket, timeout=None):
"""
Fetch a list of keys for the bucket
"""
bucket_type = self._get_bucket_type(bucket.bucket_type)
url = self.key_list_path(bucket.name, bucket_type=bucket_type,
timeout=timeout)
status, _, body =... | Fetch a list of keys for the bucket |
def parse_variant(variant, case, variant_type='clinical',
rank_results_header=None, vep_header=None,
individual_positions=None, category=None):
"""Return a parsed variant
Get all the necessary information to build a variant object
Args:
variant(cyvcf2.Variant)... | Return a parsed variant
Get all the necessary information to build a variant object
Args:
variant(cyvcf2.Variant)
case(dict)
variant_type(str): 'clinical' or 'research'
rank_results_header(list)
vep_header(list)
individual_positions(dict): Explain what posit... |
def list_roles():
"""Show a list of all available roles"""
for role in lib.get_roles():
margin_left = lib.get_margin(len(role['fullname']))
print("{0}{1}{2}".format(
role['fullname'], margin_left,
role.get('description', '(no description)'))) | Show a list of all available roles |
def get_default(self):
"""Get a string representation of a param's default value.
Returns None if there is no default value for this param.
"""
definfo = functionutils.DefinitionInfo.read(self._function)
for arg, default in definfo.args_with_defaults:
if self.argname... | Get a string representation of a param's default value.
Returns None if there is no default value for this param. |
def update(self, labels, preds):
"""
Implementation of updating metrics
"""
# get generated multi label from network
cls_prob = preds[0].asnumpy()
loc_loss = preds[1].asnumpy()
cls_label = preds[2].asnumpy()
valid_count = np.sum(cls_label >= 0)
# o... | Implementation of updating metrics |
def GetNotifications(user=None, token=None):
"""Show pending notifications for a user."""
if not user:
user = getpass.getuser()
user_obj = aff4.FACTORY.Open(
aff4.ROOT_URN.Add("users").Add(user), token=token)
return list(user_obj.Get(user_obj.Schema.PENDING_NOTIFICATIONS)) | Show pending notifications for a user. |
def cleanup_temporary_directories(self):
"""Delete the build directories and any temporary directories created by pip."""
while self.build_directories:
shutil.rmtree(self.build_directories.pop())
for requirement in self.reported_requirements:
requirement.remove_temporary_... | Delete the build directories and any temporary directories created by pip. |
def ranged_property(min=None, max=None):
"""Decorator for creating ranged property with fixed bounds."""
min_value = -_INF if min is None else min
max_value = _INF if max is None else max
return lambda fget: RangedProperty(
fget, fmin=lambda obj: min_value, fmax=lambda obj: max_value) | Decorator for creating ranged property with fixed bounds. |
def authorize_get(self, session, fields=[]):
'''taobao.itemcats.authorize.get 查询B商家被授权品牌列表和类目列表'''
sellerAuthorize = SellerAuthorize()
request = TOPRequest('taobao.authorize.get')
if not fields:
fields = sellerAuthorize.fields
request['fields'] = ','.join(fields)
... | taobao.itemcats.authorize.get 查询B商家被授权品牌列表和类目列表 |
def format(x, format):
"""Uses http://www.cplusplus.com/reference/string/to_string/ for formatting"""
# don't change the dtype, otherwise for each block the dtype may be different (string length)
sl = vaex.strings.format(x, format)
return column.ColumnStringArrow(sl.bytes, sl.indices, sl.length, sl.offs... | Uses http://www.cplusplus.com/reference/string/to_string/ for formatting |
def get_address(self, address_id, **params):
"""https://developers.coinbase.com/api/v2#show-addresss"""
return self.api_client.get_address(self.id, address_id, **params) | https://developers.coinbase.com/api/v2#show-addresss |
def run(self):
'''Run loop'''
logger.info("result_worker starting...")
while not self._quit:
try:
task, result = self.inqueue.get(timeout=1)
self.on_result(task, result)
except Queue.Empty as e:
continue
except ... | Run loop |
def check(self, url_data):
"""Parse Word data."""
content = url_data.get_content()
filename = get_temp_filename(content)
# open word file and parse hyperlinks
try:
app = get_word_app()
try:
doc = open_wordfile(app, filename)
... | Parse Word data. |
def strongly_connected_components(graph: Graph) -> List:
"""Find the strongly connected components in a graph using Tarjan's algorithm.
The `graph` argument should be a dictionary mapping node names to sequences of successor nodes.
"""
assert check_argument_types()
result = []
stack = []
low = {}
def vi... | Find the strongly connected components in a graph using Tarjan's algorithm.
The `graph` argument should be a dictionary mapping node names to sequences of successor nodes. |
def merge(cls, predictors):
"""
Merge the ensembles of two or more `Class1AffinityPredictor` instances.
Note: the resulting merged predictor will NOT have calibrated percentile
ranks. Call `calibrate_percentile_ranks` on it if these are needed.
Parameters
----------
... | Merge the ensembles of two or more `Class1AffinityPredictor` instances.
Note: the resulting merged predictor will NOT have calibrated percentile
ranks. Call `calibrate_percentile_ranks` on it if these are needed.
Parameters
----------
predictors : sequence of `Class1AffinityPre... |
def autojump():
"""Initializes a virtualenv"""
currently_enabled = autojump_enabled()
toggle_autojump()
if not currently_enabled:
click.secho("Autojump enabled", fg='green')
else:
click.secho("Autojump disabled", fg='red') | Initializes a virtualenv |
def _read_bytes_from_framed_body(self, b):
"""Reads the requested number of bytes from a streaming framed message body.
:param int b: Number of bytes to read
:returns: Bytes read from source stream and decrypted
:rtype: bytes
"""
plaintext = b""
final_frame = Fal... | Reads the requested number of bytes from a streaming framed message body.
:param int b: Number of bytes to read
:returns: Bytes read from source stream and decrypted
:rtype: bytes |
def to_array(self):
"""
Serializes this ChatActionMessage to a dictionary.
:return: dictionary representation of this object.
:rtype: dict
"""
array = super(ChatActionMessage, self).to_array()
array['action'] = u(self.action) # py2: type unicode, py3: type str
... | Serializes this ChatActionMessage to a dictionary.
:return: dictionary representation of this object.
:rtype: dict |
def cree_local_DB(scheme):
"""Create emmpt DB according to the given scheme : dict { table : [ (column_name, column_type), .. ]}
Usefull at installation of application (and for developement)
"""
conn = LocalConnexion()
req = ""
for table, fields in scheme.items():
req += f"DROP TABLE IF ... | Create emmpt DB according to the given scheme : dict { table : [ (column_name, column_type), .. ]}
Usefull at installation of application (and for developement) |
def evaluate(self, simplify=False, empty_val=0):
"""
Return the lazy array as a real NumPy array.
If the array is homogeneous and ``simplify`` is ``True``, return a
single numerical value.
"""
# need to catch the situation where a generator-based larray is evaluated a se... | Return the lazy array as a real NumPy array.
If the array is homogeneous and ``simplify`` is ``True``, return a
single numerical value. |
def OnDirectionChoice(self, event):
"""Direction choice event handler"""
label = self.direction_choicectrl.GetItems()[event.GetSelection()]
param = self.choice_label2param[label]
self.attrs["direction"] = param
post_command_event(self, self.DrawChartMsg) | Direction choice event handler |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.