code stringlengths 75 104k | docstring stringlengths 1 46.9k |
|---|---|
def threshold_otsu(image, multiplier=1.0):
"""Return image thresholded using Otsu's method.
"""
otsu_value = skimage.filters.threshold_otsu(image)
return image > otsu_value * multiplier | Return image thresholded using Otsu's method. |
def has_changed_since_last_deploy(file_path, bucket):
"""
Checks if a file has changed since the last time it was deployed.
:param file_path: Path to file which should be checked. Should be relative
from root of bucket.
:param bucket_name: Name of S3 bucket to check against.
:... | Checks if a file has changed since the last time it was deployed.
:param file_path: Path to file which should be checked. Should be relative
from root of bucket.
:param bucket_name: Name of S3 bucket to check against.
:returns: True if the file has changed, else False. |
def mmGetMetricSequencesPredictedActiveCellsShared(self):
"""
Metric for number of sequences each predicted => active cell appears in
Note: This metric is flawed when it comes to high-order sequences.
@return (Metric) metric
"""
self._mmComputeTransitionTraces()
numSequencesForCell = defa... | Metric for number of sequences each predicted => active cell appears in
Note: This metric is flawed when it comes to high-order sequences.
@return (Metric) metric |
def latex(self):
"""Return LaTeX representation of the abstract."""
s = ('{authors}, \\textit{{{title}}}, {journal}, {volissue}, '
'{pages}, ({date}). {doi}, {scopus_url}.')
if len(self.authors) > 1:
authors = ', '.join([str(a.given_name) +
... | Return LaTeX representation of the abstract. |
def get_default_config(self):
"""
Return the default config for the handler
"""
config = super(LibratoHandler, self).get_default_config()
config.update({
'user': '',
'apikey': '',
'apply_metric_prefix': False,
'queue_max_size': 300... | Return the default config for the handler |
def QCapsulate(self, widget, name, blocking = False, nude = False):
"""Helper function that encapsulates QWidget into a QMainWindow
"""
class QuickWindow(QtWidgets.QMainWindow):
class Signals(QtCore.QObject):
close = QtCore.Signal()
show = QtCore.Si... | Helper function that encapsulates QWidget into a QMainWindow |
def rand_article(num_p=(4, 10), num_s=(2, 15), num_w=(5, 40)):
"""Random article text.
Example::
>>> rand_article()
...
"""
article = list()
for _ in range(random.randint(*num_p)):
p = list()
for _ in range(random.randint(*num_s)):
s = list()
... | Random article text.
Example::
>>> rand_article()
... |
def main():
"""
NAME
lowrie_magic.py
DESCRIPTION
plots intensity decay curves for Lowrie experiments
SYNTAX
lowrie_magic.py -h [command line options]
INPUT
takes measurements formatted input files
OPTIONS
-h prints help message and quits
-f FILE:... | NAME
lowrie_magic.py
DESCRIPTION
plots intensity decay curves for Lowrie experiments
SYNTAX
lowrie_magic.py -h [command line options]
INPUT
takes measurements formatted input files
OPTIONS
-h prints help message and quits
-f FILE: specify input file, def... |
def path_join(*args):
"""
Wrapper around `os.path.join`.
Makes sure to join paths of the same type (bytes).
"""
args = (paramiko.py3compat.u(arg) for arg in args)
return os.path.join(*args) | Wrapper around `os.path.join`.
Makes sure to join paths of the same type (bytes). |
def snr_from_loglr(loglr):
"""Returns SNR computed from the given log likelihood ratio(s). This is
defined as `sqrt(2*loglr)`.If the log likelihood ratio is < 0, returns 0.
Parameters
----------
loglr : array or float
The log likelihood ratio(s) to evaluate.
Returns
-------
arr... | Returns SNR computed from the given log likelihood ratio(s). This is
defined as `sqrt(2*loglr)`.If the log likelihood ratio is < 0, returns 0.
Parameters
----------
loglr : array or float
The log likelihood ratio(s) to evaluate.
Returns
-------
array or float
The SNRs compu... |
def _infer_sig_len(file_name, fmt, n_sig, dir_name, pb_dir=None):
"""
Infer the length of a signal from a dat file.
Parameters
----------
file_name : str
Name of the dat file
fmt : str
WFDB fmt of the dat file
n_sig : int
Number of signals contained in the dat file
... | Infer the length of a signal from a dat file.
Parameters
----------
file_name : str
Name of the dat file
fmt : str
WFDB fmt of the dat file
n_sig : int
Number of signals contained in the dat file
Notes
-----
sig_len * n_sig * bytes_per_sample == file_size |
def expect_bounded(__funcname=_qualified_name, **named):
"""
Preprocessing decorator verifying that inputs fall INCLUSIVELY between
bounds.
Bounds should be passed as a pair of ``(min_value, max_value)``.
``None`` may be passed as ``min_value`` or ``max_value`` to signify that
the input is onl... | Preprocessing decorator verifying that inputs fall INCLUSIVELY between
bounds.
Bounds should be passed as a pair of ``(min_value, max_value)``.
``None`` may be passed as ``min_value`` or ``max_value`` to signify that
the input is only bounded above or below.
Examples
--------
>>> @expect_... |
def _parse_area(self, area_xml):
"""Parses an Area tag, which is effectively a room, depending on how the
Lutron controller programming was done."""
area = Area(self._lutron,
name=area_xml.get('Name'),
integration_id=int(area_xml.get('IntegrationID')),
occupan... | Parses an Area tag, which is effectively a room, depending on how the
Lutron controller programming was done. |
def update_firmware(self, filename, component_type):
"""Updates the given firmware on the server for the given component.
:param filename: location of the raw firmware file. Extraction of the
firmware file (if in compact format) is expected to
happen pr... | Updates the given firmware on the server for the given component.
:param filename: location of the raw firmware file. Extraction of the
firmware file (if in compact format) is expected to
happen prior to this invocation.
:param component_type: Type of c... |
def read_file_snippets(file, snippet_store):
"""Parse a file and add all snippets to the snippet_store dictionary"""
start_reg = re.compile("(.*%%SNIPPET_START%% )([a-zA-Z0-9]+)")
end_reg = re.compile("(.*%%SNIPPET_END%% )([a-zA-Z0-9]+)")
open_snippets = {}
with open(file, encoding="utf-8") as w:
... | Parse a file and add all snippets to the snippet_store dictionary |
def write_timestamp(self, t, pack=Struct('>Q').pack):
"""
Write out a Python datetime.datetime object as a 64-bit integer
representing seconds since the Unix UTC epoch.
"""
# Double check timestamp, can't imagine why it would be signed
self._output_buffer.extend(pack(long... | Write out a Python datetime.datetime object as a 64-bit integer
representing seconds since the Unix UTC epoch. |
def read_hypergraph(string):
"""
Read a graph from a XML document. Nodes and hyperedges specified in the input will be added
to the current graph.
@type string: string
@param string: Input string in XML format specifying a graph.
@rtype: hypergraph
@return: Hypergraph
"""
... | Read a graph from a XML document. Nodes and hyperedges specified in the input will be added
to the current graph.
@type string: string
@param string: Input string in XML format specifying a graph.
@rtype: hypergraph
@return: Hypergraph |
def _to_list(obj):
'''
Convert snetinfo object to list
'''
ret = {}
for attr in __attrs:
if hasattr(obj, attr):
ret[attr] = getattr(obj, attr)
return ret | Convert snetinfo object to list |
def determine_inside_container(self):
"""
Set self.in_container if we're inside a container
* Inside container
* Current token starts a new container
* Current token ends all containers
"""
tokenum, value = self.current.tokenum, self.current.val... | Set self.in_container if we're inside a container
* Inside container
* Current token starts a new container
* Current token ends all containers |
def show_bare_metal_state_output_bare_metal_state(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
show_bare_metal_state = ET.Element("show_bare_metal_state")
config = show_bare_metal_state
output = ET.SubElement(show_bare_metal_state, "output")
... | Auto Generated Code |
def get_all_responses(self, service_name, receive_timeout_in_seconds=None):
"""
Receive all available responses from the service as a generator.
:param service_name: The name of the service from which to receive responses
:type service_name: union[str, unicode]
:param receive_ti... | Receive all available responses from the service as a generator.
:param service_name: The name of the service from which to receive responses
:type service_name: union[str, unicode]
:param receive_timeout_in_seconds: How long to block without receiving a message before raising
... |
async def create_new_sticker_set(self, user_id: base.Integer, name: base.String, title: base.String,
png_sticker: typing.Union[base.InputFile, base.String], emojis: base.String,
contains_masks: typing.Union[base.Boolean, None] = None,
... | Use this method to create new sticker set owned by a user. The bot will be able to edit the created sticker set.
Source: https://core.telegram.org/bots/api#createnewstickerset
:param user_id: User identifier of created sticker set owner
:type user_id: :obj:`base.Integer`
:param name: S... |
def visit_repr(self, node, parent):
"""visit a Backquote node by returning a fresh instance of it"""
newnode = nodes.Repr(node.lineno, node.col_offset, parent)
newnode.postinit(self.visit(node.value, newnode))
return newnode | visit a Backquote node by returning a fresh instance of it |
def orderrun_detail(dk_api, kitchen, pd):
"""
returns a string.
:param dk_api: -- api object
:param kitchen: string
:param pd: dict
:rtype: DKReturnCode
"""
if DKCloudCommandRunner.SUMMARY in pd:
display_summary = True
else:
... | returns a string.
:param dk_api: -- api object
:param kitchen: string
:param pd: dict
:rtype: DKReturnCode |
def get_txn_outputs(raw_tx_hex, output_addr_list, coin_symbol):
'''
Used to verify a transaction hex does what's expected of it.
Must supply a list of output addresses so that the library can try to
convert from script to address using both pubkey and script.
Returns a list of the following form:
... | Used to verify a transaction hex does what's expected of it.
Must supply a list of output addresses so that the library can try to
convert from script to address using both pubkey and script.
Returns a list of the following form:
[{'value': 12345, 'address': '1abc...'}, ...]
Uses @vbuterin's ... |
def bootstrapSampleFromData(data,weights=None,seed=0):
'''
Samples rows from the input array of data, generating a new data array with
an equal number of rows (records). Rows are drawn with equal probability
by default, but probabilities can be specified with weights (must sum to 1).
Parameters
... | Samples rows from the input array of data, generating a new data array with
an equal number of rows (records). Rows are drawn with equal probability
by default, but probabilities can be specified with weights (must sum to 1).
Parameters
----------
data : np.array
An array of data, with eac... |
def __error_middleware(self, res, res_json):
"""
Middleware that raises an exception when HTTP statuscode is an error code.
"""
if(res.status_code in [400, 401, 402, 403, 404, 405, 406, 409]):
err_dict = res_json.get('error', {})
raise UpCloudAPIError(error_code=e... | Middleware that raises an exception when HTTP statuscode is an error code. |
def mean(self, axis=None, keepdims=False):
"""
Return the mean of the array over the given axis.
Parameters
----------
axis : tuple or int, optional, default=None
Axis to compute statistic over, if None
will compute over all axes
keepdims : boole... | Return the mean of the array over the given axis.
Parameters
----------
axis : tuple or int, optional, default=None
Axis to compute statistic over, if None
will compute over all axes
keepdims : boolean, optional, default=False
Keep axis remaining aft... |
def parse_vote_data(self, vote_data):
"""
Parse data from parltrack votes db dumps (1 proposal)
"""
if 'epref' not in vote_data.keys():
logger.debug('Could not import data without epref %s',
vote_data['title'])
return
dossier_pk = self.get... | Parse data from parltrack votes db dumps (1 proposal) |
def parse_buffer(buffer, mode="exec", flags=[], version=None, engine=None):
"""
Like :meth:`parse`, but accepts a :class:`source.Buffer` instead of
source and filename, and returns comments as well.
:see: :meth:`parse`
:return: (:class:`ast.AST`, list of :class:`source.Comment`)
Abstract sy... | Like :meth:`parse`, but accepts a :class:`source.Buffer` instead of
source and filename, and returns comments as well.
:see: :meth:`parse`
:return: (:class:`ast.AST`, list of :class:`source.Comment`)
Abstract syntax tree and comments |
def restore(file_name, jail=None, chroot=None, root=None):
'''
Reads archive created by pkg backup -d and recreates the database.
CLI Example:
.. code-block:: bash
salt '*' pkg.restore /tmp/pkg
jail
Restore database to the specified jail. Note that this will run the
comma... | Reads archive created by pkg backup -d and recreates the database.
CLI Example:
.. code-block:: bash
salt '*' pkg.restore /tmp/pkg
jail
Restore database to the specified jail. Note that this will run the
command within the jail, and so the path to the file from which the pkg
... |
def contour(self, win, ngr=20, layers=0, levels=20, layout=True, labels=True,
decimals=0, color=None, newfig=True, figsize=None, legend=True):
"""Contour plot
Parameters
----------
win : list or tuple
[x1, x2, y1, y2]
ngr : scalar, tuple ... | Contour plot
Parameters
----------
win : list or tuple
[x1, x2, y1, y2]
ngr : scalar, tuple or list
if scalar: number of grid points in x and y direction
if tuple or list: nx, ny, number of grid points in x and y direction
layers ... |
def get_value(file, element):
'''
Returns the value of the matched xpath element
CLI Example:
.. code-block:: bash
salt '*' xml.get_value /tmp/test.xml ".//element"
'''
try:
root = ET.parse(file)
element = root.find(element)
return element.text
except Attri... | Returns the value of the matched xpath element
CLI Example:
.. code-block:: bash
salt '*' xml.get_value /tmp/test.xml ".//element" |
def prepare_attrib_mapping(self, primitive):
"""Pre-parse buffer mappings for each VBO to detect interleaved data for a primitive"""
buffer_info = []
for name, accessor in primitive.attributes.items():
info = VBOInfo(*accessor.info())
info.attributes.append((name, info.co... | Pre-parse buffer mappings for each VBO to detect interleaved data for a primitive |
def optimize(self, optimizer=None, start=None, messages=False, max_iters=1000, ipython_notebook=True, clear_after_finish=False, **kwargs):
"""
Optimize the model using self.log_likelihood and self.log_likelihood_gradient, as well as self.priors.
kwargs are passed to the optimizer. They can be:
... | Optimize the model using self.log_likelihood and self.log_likelihood_gradient, as well as self.priors.
kwargs are passed to the optimizer. They can be:
:param max_iters: maximum number of function evaluations
:type max_iters: int
:messages: True: Display messages during optimisation, "... |
def _varian(self, varian):
"""Mengembalikan representasi string untuk varian entri ini.
Dapat digunakan untuk "Varian" maupun "Bentuk tidak baku".
:param varian: List bentuk tidak baku atau varian
:type varian: list
:returns: String representasi varian atau bentuk tidak baku
... | Mengembalikan representasi string untuk varian entri ini.
Dapat digunakan untuk "Varian" maupun "Bentuk tidak baku".
:param varian: List bentuk tidak baku atau varian
:type varian: list
:returns: String representasi varian atau bentuk tidak baku
:rtype: str |
def as_encodable(self, index_name):
"""
:param index_name: The name of the index for the query
:return: A dict suitable for passing to `json.dumps()`
"""
if self.facets:
encoded_facets = {}
for name, facet in self.facets.items():
encoded_fa... | :param index_name: The name of the index for the query
:return: A dict suitable for passing to `json.dumps()` |
def draw_rect(grid, attr, dc, rect):
"""Draws a rect"""
dc.SetBrush(wx.Brush(wx.Colour(15, 255, 127), wx.SOLID))
dc.SetPen(wx.Pen(wx.BLUE, 1, wx.SOLID))
dc.DrawRectangleRect(rect) | Draws a rect |
def tica(data=None, lag=10, dim=-1, var_cutoff=0.95, kinetic_map=True, commute_map=False, weights='empirical',
stride=1, remove_mean=True, skip=0, reversible=True, ncov_max=float('inf'), chunksize=None, **kwargs):
r""" Time-lagged independent component analysis (TICA).
TICA is a linear transformation ... | r""" Time-lagged independent component analysis (TICA).
TICA is a linear transformation method. In contrast to PCA, which finds
coordinates of maximal variance, TICA finds coordinates of maximal
autocorrelation at the given lag time. Therefore, TICA is useful in order
to find the *slow* components in a... |
def getOverlayTransformAbsolute(self, ulOverlayHandle):
"""Gets the transform if it is absolute. Returns an error if the transform is some other type."""
fn = self.function_table.getOverlayTransformAbsolute
peTrackingOrigin = ETrackingUniverseOrigin()
pmatTrackingOriginToOverlayTransfor... | Gets the transform if it is absolute. Returns an error if the transform is some other type. |
def series_resistors(target,
pore_area='pore.area',
throat_area='throat.area',
pore_conductivity='pore.electrical_conductivity',
throat_conductivity='throat.electrical_conductivity',
conduit_lengths='throat.conduit_... | r"""
Calculate the electrical conductance of conduits in network, where a
conduit is ( 1/2 pore - full throat - 1/2 pore ). See the notes section.
Parameters
----------
target : OpenPNM Object
The object which this model is associated with. This controls the
length of the calculated... |
def convert_row(self, keyed_row, schema, fallbacks):
"""Convert row to SQL
"""
for key, value in list(keyed_row.items()):
field = schema.get_field(key)
if not field:
del keyed_row[key]
if key in fallbacks:
value = _uncast_value(... | Convert row to SQL |
def create_class(self):
"""
Build the estimator class.
Returns
-------
:return : string
The built class as string.
"""
if self.target_language in ['java', 'go']:
n_indents = 1 if self.target_language == 'java' else 0
class_head... | Build the estimator class.
Returns
-------
:return : string
The built class as string. |
def part(self, target, reason=None):
"""quit a channel"""
if reason:
target += ' :' + reason
self.send_line('PART %s' % target) | quit a channel |
def capture(self, pattern=None, negate=False, workers=None, negate_workers=False,
params=None, success=False, error=True, stats=False):
"""Starts capturing selected events in real-time. You can filter exactly what
you want to see, as the Clearly Server handles all tasks and workers updat... | Starts capturing selected events in real-time. You can filter exactly what
you want to see, as the Clearly Server handles all tasks and workers updates
being sent to celery. Several clients can see different sets of events at the
same time.
This runs in the foreground, so you can see in... |
def gcmt_to_simple_array(self, centroid_location=True):
"""
Converts the GCMT catalogue to a simple array of
[ID, year, month, day, hour, minute, second, long., lat., depth, Mw,
strike1, dip1, rake1, strike2, dip2, rake2, b-plunge, b-azimuth,
b-eigenvalue, p-plunge, p-azimuth, p-... | Converts the GCMT catalogue to a simple array of
[ID, year, month, day, hour, minute, second, long., lat., depth, Mw,
strike1, dip1, rake1, strike2, dip2, rake2, b-plunge, b-azimuth,
b-eigenvalue, p-plunge, p-azimuth, p-eigenvalue, t-plunge, t-azimuth,
t-eigenvalue, moment, f_clvd, erel] |
def get_one_file_in(dirname):
"""Return the pathname of the one file in a directory.
Raises if the directory has no files or more than one file.
"""
files = os.listdir(dirname)
if len(files) > 1:
raise Failure('More than one file exists in %s:\n%s' %
(dirname, '\n'.joi... | Return the pathname of the one file in a directory.
Raises if the directory has no files or more than one file. |
def generate_covalent_bond_graph(covalent_bonds):
"""Generates a graph of the covalent bond network described by the interactions.
Parameters
----------
covalent_bonds: [CovalentBond]
List of `CovalentBond`.
Returns
-------
bond_graph: networkx.Graph
A graph of the covalent... | Generates a graph of the covalent bond network described by the interactions.
Parameters
----------
covalent_bonds: [CovalentBond]
List of `CovalentBond`.
Returns
-------
bond_graph: networkx.Graph
A graph of the covalent bond network. |
def describe(self, *cols):
"""Computes basic statistics for numeric and string columns.
This include count, mean, stddev, min, and max. If no columns are
given, this function computes statistics for all numerical or string columns.
.. note:: This function is meant for exploratory data ... | Computes basic statistics for numeric and string columns.
This include count, mean, stddev, min, and max. If no columns are
given, this function computes statistics for all numerical or string columns.
.. note:: This function is meant for exploratory data analysis, as we make no
gu... |
def get_reconciler(config, metrics, rrset_channel, changes_channel, **kw):
"""Get a GDNSReconciler client.
A factory function that validates configuration, creates an auth
and :class:`GDNSClient` instance, and returns a GDNSReconciler
provider.
Args:
config (dict): Google Cloud Pub/Sub-rel... | Get a GDNSReconciler client.
A factory function that validates configuration, creates an auth
and :class:`GDNSClient` instance, and returns a GDNSReconciler
provider.
Args:
config (dict): Google Cloud Pub/Sub-related configuration.
metrics (obj): :interface:`IMetricRelay` implementatio... |
def tensor_info_proto_maps_match(map_a, map_b):
"""Whether two signature inputs/outputs match in dtype, shape and sparsity.
Args:
map_a: A proto map<string,TensorInfo>.
map_b: A proto map<string,TensorInfo>.
Returns:
A boolean whether `map_a` and `map_b` tensors have the same dtype, shape and
sp... | Whether two signature inputs/outputs match in dtype, shape and sparsity.
Args:
map_a: A proto map<string,TensorInfo>.
map_b: A proto map<string,TensorInfo>.
Returns:
A boolean whether `map_a` and `map_b` tensors have the same dtype, shape and
sparsity. |
def _get_headers(environ):
# type: (Dict[str, str]) -> Iterator[Tuple[str, str]]
"""
Returns only proper HTTP headers.
"""
for key, value in environ.items():
key = str(key)
if key.startswith("HTTP_") and key not in (
"HTTP_CONTENT_TYPE",
"HTTP_CONTENT_LENGTH"... | Returns only proper HTTP headers. |
def get_cameras_properties(self):
"""Return camera properties."""
resource = "cameras"
resource_event = self.publish_and_get_event(resource)
if resource_event:
self._last_refresh = int(time.time())
self._camera_properties = resource_event.get('properties') | Return camera properties. |
def datalog(self, parameter, run, maxrun=None, det_id='D_ARCA001'):
"Retrieve datalogs for given parameter, run(s) and detector"
parameter = parameter.lower()
if maxrun is None:
maxrun = run
with Timer('Database lookup'):
return self._datalog(parameter, run, maxru... | Retrieve datalogs for given parameter, run(s) and detector |
def gain(abf):
"""easy way to plot a gain function."""
Ys=np.nan_to_num(swhlab.ap.getAvgBySweep(abf,'freq'))
Xs=abf.clampValues(abf.dataX[int(abf.protoSeqX[1]+.01)])
swhlab.plot.new(abf,title="gain function",xlabel="command current (pA)",
ylabel="average inst. freq. (Hz)")
pylab.... | easy way to plot a gain function. |
def host_inventory_get(hostids, **kwargs):
'''
Retrieve host inventory according to the given parameters.
See: https://www.zabbix.com/documentation/2.4/manual/api/reference/host/object#host_inventory
.. versionadded:: 2019.2.0
:param hostids: Return only host interfaces used by the given hosts.
... | Retrieve host inventory according to the given parameters.
See: https://www.zabbix.com/documentation/2.4/manual/api/reference/host/object#host_inventory
.. versionadded:: 2019.2.0
:param hostids: Return only host interfaces used by the given hosts.
:param _connection_user: Optional - zabbix user (can ... |
async def delete(self, _id=None):
"""Delete entry from database table.
Accepts id.
delete(id) => 1 (if exists)
delete(id) => {"error":404, "reason":"Not found"} (if does not exist)
delete() => {"error":400, "reason":"Missed required fields"}
"""
if not _id:
return {"error":400,
"reason":"Missed r... | Delete entry from database table.
Accepts id.
delete(id) => 1 (if exists)
delete(id) => {"error":404, "reason":"Not found"} (if does not exist)
delete() => {"error":400, "reason":"Missed required fields"} |
def get_raw_mempool(self, id=None, endpoint=None):
"""
Returns the tx that are in the memorypool of the endpoint
Args:
id: (int, optional) id to use for response tracking
endpoint: (RPCEndpoint, optional) endpoint to specify to use
Returns:
json object... | Returns the tx that are in the memorypool of the endpoint
Args:
id: (int, optional) id to use for response tracking
endpoint: (RPCEndpoint, optional) endpoint to specify to use
Returns:
json object of the result or the error encountered in the RPC call |
def mount(device, mountpoint, options=None, persist=False, filesystem="ext3"):
"""Mount a filesystem at a particular mountpoint"""
cmd_args = ['mount']
if options is not None:
cmd_args.extend(['-o', options])
cmd_args.extend([device, mountpoint])
try:
subprocess.check_output(cmd_args... | Mount a filesystem at a particular mountpoint |
def _watch_file(self, filepath, trigger_event=True):
"""Adds the file's modified time into its internal watchlist."""
is_new = filepath not in self._watched_files
if trigger_event:
if is_new:
self.trigger_created(filepath)
else:
self.trigge... | Adds the file's modified time into its internal watchlist. |
def get_or_none(cls, **filter_kwargs):
"""
Returns a video or None.
"""
try:
video = cls.objects.get(**filter_kwargs)
except cls.DoesNotExist:
video = None
return video | Returns a video or None. |
def PrintIndented(self, file, ident, code):
"""Takes an array, add indentation to each entry and prints it."""
for entry in code:
print >>file, '%s%s' % (ident, entry) | Takes an array, add indentation to each entry and prints it. |
def move(self, direction, absolute=False, pad_name=None, refresh=True):
""" Scroll the current pad
direction : (int) move by one in the given direction
-1 is up, 1 is down. If absolute is True,
go to position direction.
B... | Scroll the current pad
direction : (int) move by one in the given direction
-1 is up, 1 is down. If absolute is True,
go to position direction.
Behaviour is affected by cursor_line and scroll_only below
absolute : (bool) |
def token_info(token, refresh=True, refresh_cb=None, session=None):
"""
:param OAuthToken token
:param bool refresh:
whether to attempt to refresh the OAuth token if it expired.
default is `True`.
:param refresh_cb:
If specified, a callable object which is given the new token
i... | :param OAuthToken token
:param bool refresh:
whether to attempt to refresh the OAuth token if it expired.
default is `True`.
:param refresh_cb:
If specified, a callable object which is given the new token
in parameter if it has been refreshed.
:param requests.Session session:
... |
def p_unrelate_statement_2(self, p):
'''statement : UNRELATE instance_name FROM instance_name ACROSS rel_id DOT phrase'''
p[0] = UnrelateNode(from_variable_name=p[2],
to_variable_name=p[4],
rel_id=p[6],
phrase=p[8]) | statement : UNRELATE instance_name FROM instance_name ACROSS rel_id DOT phrase |
def get_config( config_path=CONFIG_PATH ):
"""
Get the config
"""
parser = SafeConfigParser()
parser.read( config_path )
config_dir = os.path.dirname(config_path)
immutable_key = False
key_id = None
blockchain_id = None
hostname = socket.gethostname()
wallet = None
... | Get the config |
def draw(self, **kwargs):
"""
Renders the rfecv curve.
"""
# Compute the curves
x = self.n_feature_subsets_
means = self.cv_scores_.mean(axis=1)
sigmas = self.cv_scores_.std(axis=1)
# Plot one standard deviation above and below the mean
self.ax.f... | Renders the rfecv curve. |
def reset(cwd,
opts='',
git_opts='',
user=None,
password=None,
identity=None,
ignore_retcode=False,
output_encoding=None):
'''
Interface to `git-reset(1)`_, returns the stdout from the git command
cwd
The path to the git checkout... | Interface to `git-reset(1)`_, returns the stdout from the git command
cwd
The path to the git checkout
opts
Any additional options to add to the command line, in a single string
.. note::
On the Salt CLI, if the opts are preceded with a dash, it is
necessary to... |
def _take_forced_measurement(self):
"""Take a forced measurement.
In forced mode, the BME sensor goes back to sleep after each
measurement and we need to set it to forced mode once at this point,
so it will take the next measurement and then return to sleep again.
In normal mode... | Take a forced measurement.
In forced mode, the BME sensor goes back to sleep after each
measurement and we need to set it to forced mode once at this point,
so it will take the next measurement and then return to sleep again.
In normal mode simply does new measurements periodically. |
def _nan_minmax_object(func, fill_value, value, axis=None, **kwargs):
""" In house nanmin and nanmax for object array """
valid_count = count(value, axis=axis)
filled_value = fillna(value, fill_value)
data = getattr(np, func)(filled_value, axis=axis, **kwargs)
if not hasattr(data, 'dtype'): # scala... | In house nanmin and nanmax for object array |
def BuildChecks(self, request):
"""Parses request and returns a list of filter callables.
Each callable will be called with the StatEntry and returns True if the
entry should be suppressed.
Args:
request: A FindSpec that describes the search.
Returns:
a list of callables which return ... | Parses request and returns a list of filter callables.
Each callable will be called with the StatEntry and returns True if the
entry should be suppressed.
Args:
request: A FindSpec that describes the search.
Returns:
a list of callables which return True if the file is to be suppressed. |
def show_script_error(self, parent):
"""
Show the last script error (if any)
"""
if self.service.scriptRunner.error != '':
dlg = Gtk.MessageDialog(type=Gtk.MessageType.INFO, buttons=Gtk.ButtonsType.OK,
message_format=self.service.scriptRun... | Show the last script error (if any) |
def print_tree(self) -> str:
"""Convert AST object to tree view of BEL AST
Returns:
printed tree of BEL AST
"""
if self.ast:
return self.ast.print_tree(ast_obj=self.ast)
else:
return "" | Convert AST object to tree view of BEL AST
Returns:
printed tree of BEL AST |
def __arguments(self, ttype, tvalue):
"""Arguments parsing method
Entry point for command arguments parsing. The parser must
call this method for each parsed command (either a control,
action or test).
Syntax:
*argument [ test / test-list ]
:param ttype: cu... | Arguments parsing method
Entry point for command arguments parsing. The parser must
call this method for each parsed command (either a control,
action or test).
Syntax:
*argument [ test / test-list ]
:param ttype: current token type
:param tvalue: current t... |
def exec_event_handler(self, event, transactional=False):
"""Execute the Async set to be run on event."""
# QUESTION: Should we raise an exception if `event` is not in some
# known event-type list?
callbacks = self._options.get('callbacks', {})
handler = callbacks.get(event)
... | Execute the Async set to be run on event. |
def _http_resp_rate_limited(response):
"""Extract the ``Retry-After`` header value if the request was rate
limited and return a future to sleep for the specified duration.
:param tornado.httpclient.HTTPResponse response: The response
:rtype: tornado.concurrent.Future
"""
... | Extract the ``Retry-After`` header value if the request was rate
limited and return a future to sleep for the specified duration.
:param tornado.httpclient.HTTPResponse response: The response
:rtype: tornado.concurrent.Future |
def exit(self, status=0, message=None):
'''
Argparse expects exit() to be a terminal function and not return.
As such, this function must raise an exception which will be caught
by Cmd.hasValidOpts.
'''
self.exited = True
if message is not None:
self.m... | Argparse expects exit() to be a terminal function and not return.
As such, this function must raise an exception which will be caught
by Cmd.hasValidOpts. |
def env_float(name, required=False, default=empty):
"""Pulls an environment variable out of the environment and casts it to an
float. If the name is not present in the environment and no default is
specified then a ``ValueError`` will be raised. Similarly, if the
environment value is not castable to an ... | Pulls an environment variable out of the environment and casts it to an
float. If the name is not present in the environment and no default is
specified then a ``ValueError`` will be raised. Similarly, if the
environment value is not castable to an float, a ``ValueError`` will be
raised.
:param nam... |
def flatten(self) -> bk.BKTensor:
"""Return tensor with with qubit indices flattened"""
N = self.qubit_nb
R = self.rank
return bk.reshape(self.tensor, [2**N]*R) | Return tensor with with qubit indices flattened |
def cli(env, is_open):
"""List tickets."""
ticket_mgr = SoftLayer.TicketManager(env.client)
table = formatting.Table([
'id', 'assigned_user', 'title', 'last_edited', 'status', 'updates', 'priority'
])
tickets = ticket_mgr.list_tickets(open_status=is_open, closed_status=not is_open)
for ... | List tickets. |
def decode(self):
"""Decode this report into a list of readings
"""
fmt, len_low, len_high, device_id, report_id, sent_timestamp, signature_flags, \
origin_streamer, streamer_selector = unpack("<BBHLLLBBH", self.raw_report[:20])
assert fmt == 1
length = (len_high << 8) ... | Decode this report into a list of readings |
def max(self):
"""
Returns the maximum value of the domain.
:rtype: `float` or `np.inf`
"""
return int(self._max) if not np.isinf(self._max) else self._max | Returns the maximum value of the domain.
:rtype: `float` or `np.inf` |
def set_widgets(self):
"""Set widgets on the Threshold tab."""
clear_layout(self.gridLayoutThreshold)
# Set text in the label
layer_purpose = self.parent.step_kw_purpose.selected_purpose()
layer_subcategory = self.parent.step_kw_subcategory.\
selected_subcategory()
... | Set widgets on the Threshold tab. |
def get_rows(self, sort=False):
"""
Returns the rows of this Type2Helper.
:param bool sort: If True the rows are sorted by the pseudo key.
"""
ret = []
for _, rows in sorted(self._rows.items()) if sort else self._rows.items():
self._rows_int2date(rows)
... | Returns the rows of this Type2Helper.
:param bool sort: If True the rows are sorted by the pseudo key. |
def get_cluster_graph(self, engine="fdp", graph_attr=None, node_attr=None, edge_attr=None):
"""
Generate directory graph in the DOT language. Directories are shown as clusters
.. warning::
This function scans the entire directory tree starting from top so the resulting
... | Generate directory graph in the DOT language. Directories are shown as clusters
.. warning::
This function scans the entire directory tree starting from top so the resulting
graph can be really big.
Args:
engine: Layout command used. ['dot', 'neato', 'twopi', 'circ... |
def _define_absl_flag(self, flag_instance, suppress):
"""Defines a flag from the flag_instance."""
flag_name = flag_instance.name
short_name = flag_instance.short_name
argument_names = ['--' + flag_name]
if short_name:
argument_names.insert(0, '-' + short_name)
if suppress:
helptext ... | Defines a flag from the flag_instance. |
def filesys_decode(path):
"""
Ensure that the given path is decoded,
NONE when no expected encoding works
"""
if isinstance(path, six.text_type):
return path
fs_enc = sys.getfilesystemencoding() or 'utf-8'
candidates = fs_enc, 'utf-8'
for enc in candidates:
try:
... | Ensure that the given path is decoded,
NONE when no expected encoding works |
def default_output_format(content_type='application/json', apply_globally=False, api=None, cli=False, http=True):
"""A decorator that allows you to override the default output format for an API"""
def decorator(formatter):
formatter = hug.output_format.content_type(content_type)(formatter)
if ap... | A decorator that allows you to override the default output format for an API |
def get_namespace(self, uri):
"""Return a :class:`.Namespace` corresponding to the given ``uri``.
If the given ``uri`` is a relative URI (i.e. it does not
contain a leading slash ``/``), the ``uri`` is adjusted to
be relative to the ``uri`` of the namespace itself. This
method i... | Return a :class:`.Namespace` corresponding to the given ``uri``.
If the given ``uri`` is a relative URI (i.e. it does not
contain a leading slash ``/``), the ``uri`` is adjusted to
be relative to the ``uri`` of the namespace itself. This
method is therefore mostly useful off of the buil... |
def fetch_artifact(self, trial_id, prefix):
"""
Verifies that all children of the artifact prefix path are
available locally. Fetches them if not.
Returns the local path to the given trial's artifacts at the
specified prefix, which is always just
{log_dir}/{trial_id}/{p... | Verifies that all children of the artifact prefix path are
available locally. Fetches them if not.
Returns the local path to the given trial's artifacts at the
specified prefix, which is always just
{log_dir}/{trial_id}/{prefix} |
def _input_as_list(self, data):
'''Takes the positional arguments as input in a list.
The list input here should be [query_file_path, database_file_path,
output_file_path]'''
query, database, output = data
if (not isabs(database)) \
or (not isabs(query)) \
... | Takes the positional arguments as input in a list.
The list input here should be [query_file_path, database_file_path,
output_file_path] |
def _set_zone(self, v, load=False):
"""
Setter method for zone, mapped from YANG variable /zoning/defined_configuration/zone (list)
If this variable is read-only (config: false) in the
source YANG file, then _set_zone is considered as a private
method. Backends looking to populate this variable shou... | Setter method for zone, mapped from YANG variable /zoning/defined_configuration/zone (list)
If this variable is read-only (config: false) in the
source YANG file, then _set_zone is considered as a private
method. Backends looking to populate this variable should
do so via calling thisObj._set_zone() dir... |
def affine_shift_matrix(wrg=(-0.1, 0.1), hrg=(-0.1, 0.1), w=200, h=200):
"""Create an affine transform matrix for image shifting.
NOTE: In OpenCV, x is width and y is height.
Parameters
-----------
wrg : float or tuple of floats
Range to shift on width axis, -1 ~ 1.
- float, a f... | Create an affine transform matrix for image shifting.
NOTE: In OpenCV, x is width and y is height.
Parameters
-----------
wrg : float or tuple of floats
Range to shift on width axis, -1 ~ 1.
- float, a fixed distance.
- tuple of 2 floats, randomly sample a value as the d... |
def add_node(self, node_id, name, labels):
"""Add the node with name and labels.
Args:
node_id: Id for the node.
name: Name for the node.
labels: Label for the node.
Raises:
NotImplementedError: When adding labels is not supported.
"""
... | Add the node with name and labels.
Args:
node_id: Id for the node.
name: Name for the node.
labels: Label for the node.
Raises:
NotImplementedError: When adding labels is not supported. |
def create_function_f_i(self):
"""state reinitialization (reset) function"""
return ca.Function(
'f_i',
[self.t, self.x, self.y, self.m, self.p, self.c, self.pre_c, self.ng, self.nu],
[self.f_i],
['t', 'x', 'y', 'm', 'p', 'c', 'pre_c', 'ng', 'nu'], ['x_n']... | state reinitialization (reset) function |
def UV_B(Bg,gw):
"""
returns the implications UV based on B
Bg = B(g), g∈2^M
gw = |M|, M is the set of all attributes
"""
UV = []
p = Bwidth(gw)
pp = 2**p
while p:
pp = pp>>1
p = p-1
if Bg&pp:
uv = B012(p,gw-1)
UV.append(uv)
return ... | returns the implications UV based on B
Bg = B(g), g∈2^M
gw = |M|, M is the set of all attributes |
def currentEvent(self):
'''
Return the first event that hasn't ended yet, or if there are no
future events, the last one to end.
'''
currentEvent = self.recentEvents.filter(endTime__gte=timezone.now()).order_by('startTime').first()
if not currentEvent:
curren... | Return the first event that hasn't ended yet, or if there are no
future events, the last one to end. |
def get_matching_service_template_file(service_name, template_files):
"""
Return the template file that goes with the given service name, or return
None if there's no match. Subservices return the parent service's file.
"""
# If this is a subservice, use the parent service's template
service_na... | Return the template file that goes with the given service name, or return
None if there's no match. Subservices return the parent service's file. |
def flags(rule_or_module, variable_name, condition, values = []):
""" Specifies the flags (variables) that must be set on targets under certain
conditions, described by arguments.
rule_or_module: If contains dot, should be a rule name.
The flags will be applied when that ... | Specifies the flags (variables) that must be set on targets under certain
conditions, described by arguments.
rule_or_module: If contains dot, should be a rule name.
The flags will be applied when that rule is
used to set up build actions.
... |
def NDLimitExceeded_NDLimit(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
NDLimitExceeded = ET.SubElement(config, "NDLimitExceeded", xmlns="http://brocade.com/ns/brocade-notification-stream")
NDLimit = ET.SubElement(NDLimitExceeded, "NDLimit")
... | Auto Generated Code |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.