code stringlengths 75 104k | docstring stringlengths 1 46.9k |
|---|---|
def get_results(cmd):
"""
def get_results(cmd: list) -> str:
return lines
Get the ping results using fping.
:param cmd: List - the fping command and its options
:return: String - raw string output containing csv fping results
including the newline characters
... | def get_results(cmd: list) -> str:
return lines
Get the ping results using fping.
:param cmd: List - the fping command and its options
:return: String - raw string output containing csv fping results
including the newline characters |
def download(self, filename=None):
"""Download an attachment. The files are currently not cached since they
can be overwritten on the server.
Parameters
----------
filename : string, optional
Optional name for the file on local disk.
Returns
-------
... | Download an attachment. The files are currently not cached since they
can be overwritten on the server.
Parameters
----------
filename : string, optional
Optional name for the file on local disk.
Returns
-------
string
Path to downloaded ... |
def render_revalidation_failure(self, failed_step, form, **kwargs):
"""
When a step fails, we have to redirect the user to the first failing
step.
"""
self.storage.current_step = failed_step
return redirect(self.url_name, step=failed_step) | When a step fails, we have to redirect the user to the first failing
step. |
def __start_commoncrawl_extractor(warc_download_url, callback_on_article_extracted=None, valid_hosts=None,
start_date=None, end_date=None,
strict_date=True, reuse_previously_downloaded_files=True,
local_download_dir_wa... | Starts a single CommonCrawlExtractor
:param warc_download_url:
:param callback_on_article_extracted:
:param valid_hosts:
:param start_date:
:param end_date:
:param strict_date:
:param reuse_previously_downloaded_files:
:param local_download_dir_warc:
:param continue_after_error:
... |
def enable_disable(self):
"""
Enable or disable this endpoint. If enabled, it will be disabled
and vice versa.
:return: None
"""
if self.enabled:
self.data['enabled'] = False
else:
self.data['enabled'] = True
self.update() | Enable or disable this endpoint. If enabled, it will be disabled
and vice versa.
:return: None |
def loadSignal(self, name, start=None, end=None):
"""
Loads the named entry from the upload cache as a signal.
:param name: the name.
:param start: the time to start from in HH:mm:ss.SSS format
:param end: the time to end at in HH:mm:ss.SSS format.
:return: the signal if ... | Loads the named entry from the upload cache as a signal.
:param name: the name.
:param start: the time to start from in HH:mm:ss.SSS format
:param end: the time to end at in HH:mm:ss.SSS format.
:return: the signal if the named upload exists. |
def generate_key_pair(size=2048, public_exponent=65537, as_string=True):
"""
Generate a public/private key pair.
:param size: Optional. Describes how many bits long the key should be, larger keys provide more security,
currently 1024 and below are considered breakable, and 2048 or 4096 are reasonab... | Generate a public/private key pair.
:param size: Optional. Describes how many bits long the key should be, larger keys provide more security,
currently 1024 and below are considered breakable, and 2048 or 4096 are reasonable default
key sizes for new keys. Defaults to 2048.
:param public_expone... |
def compute_curl(self, vector_field):
"""Computes the curl of a vector field over the mesh. While the vector
field is point-based, the curl will be cell-based. The approximation is
based on
.. math::
n\\cdot curl(F) = \\lim_{A\\to 0} |A|^{-1} <\\int_{dGamma}, F> dr;
... | Computes the curl of a vector field over the mesh. While the vector
field is point-based, the curl will be cell-based. The approximation is
based on
.. math::
n\\cdot curl(F) = \\lim_{A\\to 0} |A|^{-1} <\\int_{dGamma}, F> dr;
see <https://en.wikipedia.org/wiki/Curl_(mathema... |
def __add_annotation_tier(self, docgraph, body, annotation_layer):
"""
adds a span-based annotation layer as a <tier> to the Exmaralda <body>.
Parameter
---------
docgraph : DiscourseDocumentGraph
the document graph from which the chains will be extracted
bod... | adds a span-based annotation layer as a <tier> to the Exmaralda <body>.
Parameter
---------
docgraph : DiscourseDocumentGraph
the document graph from which the chains will be extracted
body : etree._Element
an etree representation of the <basic_body> element (and... |
def pulse_magnitude(time, magnitude, start, repeat_time=0):
""" Implements xmile's PULSE function
PULSE: Generate a one-DT wide pulse at the given time
Parameters: 2 or 3: (magnitude, first time[, interval])
Without interval or when interval = 0, the PULSE is ... | Implements xmile's PULSE function
PULSE: Generate a one-DT wide pulse at the given time
Parameters: 2 or 3: (magnitude, first time[, interval])
Without interval or when interval = 0, the PULSE is generated only once
Example: PULSE(20, 12, 5) generate... |
def interactive(proto_dataset_uri):
"""Interactive prompting to populate the readme."""
proto_dataset = dtoolcore.ProtoDataSet.from_uri(
uri=proto_dataset_uri,
config_path=CONFIG_PATH)
# Create an CommentedMap representation of the yaml readme template.
readme_template = _get_readme_tem... | Interactive prompting to populate the readme. |
def _process_infohash_list(infohash_list):
"""
Method to convert the infohash_list to qBittorrent API friendly values.
:param infohash_list: List of infohash.
"""
if isinstance(infohash_list, list):
data = {'hashes': '|'.join([h.lower() for h in infohash_list])}
... | Method to convert the infohash_list to qBittorrent API friendly values.
:param infohash_list: List of infohash. |
def status(self):
"""
Returns modified, added, removed, deleted files for current changeset
"""
return self.repository._repo.status(self._ctx.p1().node(),
self._ctx.node()) | Returns modified, added, removed, deleted files for current changeset |
def get_longest_target_alignment_coords_by_name(self,name):
"""For a name get the best alignment
:return: [filebyte,innerbyte] describing the to distance the zipped block start, and the distance within the unzipped block
:rtype: list
"""
longest = -1
coord = None
#for x in self._queries[sel... | For a name get the best alignment
:return: [filebyte,innerbyte] describing the to distance the zipped block start, and the distance within the unzipped block
:rtype: list |
def resources(self):
''' get total resources and available ones '''
used_resources = self._used_resources()
ret = collections.defaultdict(dict)
for resource, total in six.iteritems(self._resources):
ret[resource]['total'] = total
if resource in used_resources:
... | get total resources and available ones |
def angular_distance(first, second, bidirectional=True):
"""
Calculate the angular distance between two linear features or elementwise
angular distance between two sets of linear features. (Note: a linear
feature in this context is a point on a stereonet represented
by a single latitude and longitud... | Calculate the angular distance between two linear features or elementwise
angular distance between two sets of linear features. (Note: a linear
feature in this context is a point on a stereonet represented
by a single latitude and longitude.)
Parameters
----------
first : (lon, lat) 2xN array-l... |
def save(self, path_or_file, strict=True, fmt='auto'):
"""Serialize annotation as a JSON formatted stream to file.
Parameters
----------
path_or_file : str or file-like
Path to save the JAMS object on disk
OR
An open file descriptor to write into
... | Serialize annotation as a JSON formatted stream to file.
Parameters
----------
path_or_file : str or file-like
Path to save the JAMS object on disk
OR
An open file descriptor to write into
strict : bool
Force strict schema validation
... |
def json(self, path, schema=None, primitivesAsString=None, prefersDecimal=None,
allowComments=None, allowUnquotedFieldNames=None, allowSingleQuotes=None,
allowNumericLeadingZero=None, allowBackslashEscapingAnyCharacter=None,
mode=None, columnNameOfCorruptRecord=None, dateFormat=No... | Loads JSON files and returns the results as a :class:`DataFrame`.
`JSON Lines <http://jsonlines.org/>`_ (newline-delimited JSON) is supported by default.
For JSON (one record per file), set the ``multiLine`` parameter to ``true``.
If the ``schema`` parameter is not specified, this function goe... |
def to_dict(self):
"""
Constructs an dictionary representation of the Identity Object to be used in serializing to JSON
:return: dict representing the object
"""
json_dict = {"apiKey": self.api_key,
"userArn": self.user_arn,
"cognitoAuth... | Constructs an dictionary representation of the Identity Object to be used in serializing to JSON
:return: dict representing the object |
def button_change_send(self, time_boot_ms, last_change_ms, state, force_mavlink1=False):
'''
Report button state change
time_boot_ms : Timestamp (milliseconds since system boot) (uint32_t)
last_change_ms : Time of last change of bu... | Report button state change
time_boot_ms : Timestamp (milliseconds since system boot) (uint32_t)
last_change_ms : Time of last change of button state (uint32_t)
state : Bitmap state of buttons (uint8_t) |
def isbase(path1, path2):
# type: (Text, Text) -> bool
"""Check if ``path1`` is a base of ``path2``.
Arguments:
path1 (str): A PyFilesytem path.
path2 (str): A PyFilesytem path.
Returns:
bool: `True` if ``path2`` starts with ``path1``
Example:
>>> isbase('foo/bar',... | Check if ``path1`` is a base of ``path2``.
Arguments:
path1 (str): A PyFilesytem path.
path2 (str): A PyFilesytem path.
Returns:
bool: `True` if ``path2`` starts with ``path1``
Example:
>>> isbase('foo/bar', 'foo/bar/baz/egg.txt')
True |
def multicore(function, cores, multiargs, **singleargs):
"""
wrapper for multicore process execution
Parameters
----------
function
individual function to be applied to each process item
cores: int
the number of subprocesses started/CPUs used;
this value is reduced in ca... | wrapper for multicore process execution
Parameters
----------
function
individual function to be applied to each process item
cores: int
the number of subprocesses started/CPUs used;
this value is reduced in case the number of subprocesses is smaller
multiargs: dict
... |
def __check_label_image(label_image):
"""Check the label image for consistent labelling starting from 1."""
encountered_indices = scipy.unique(label_image)
expected_indices = scipy.arange(1, label_image.max() + 1)
if not encountered_indices.size == expected_indices.size or \
not (encountered_indi... | Check the label image for consistent labelling starting from 1. |
def create_job(self,
builder_job, # type: Dict[Text, Any]
wf_job=None, # type: Callable[[Dict[Text, Text], Callable[[Any, Any], Any], RuntimeContext], Generator[Any, None, None]]
is_output=False
): # type: (...) -> Dict
#TODO cust... | Generate the new job object with RO specific relative paths. |
def parse_url_or_log(url, encoding='utf-8'):
'''Parse and return a URLInfo.
This function logs a warning if the URL cannot be parsed and returns
None.
'''
try:
url_info = URLInfo.parse(url, encoding=encoding)
except ValueError as error:
_logger.warning(__(
_('Unable ... | Parse and return a URLInfo.
This function logs a warning if the URL cannot be parsed and returns
None. |
def queryset(self, request, queryset):
"""
Returns the filtered queryset based on the value
provided in the query string and retrievable via
`self.value()`.
"""
if self.value():
try:
section = SectionPage.objects.get(id=self.value())
... | Returns the filtered queryset based on the value
provided in the query string and retrievable via
`self.value()`. |
def __make_request(self, url, method, data, auth, cookies, headers, proxies, timeout, verify):
"""Execute a request with the given data.
Args:
url (str): The URL to call.
method (str): The method (e.g. `get` or `post`).
data (str): The data to call the URL with.
... | Execute a request with the given data.
Args:
url (str): The URL to call.
method (str): The method (e.g. `get` or `post`).
data (str): The data to call the URL with.
auth (obj): The authentication class.
cookies (obj): The cookie dict.
head... |
def solar_irradiation(latitude, longitude, Z, moment, surface_tilt,
surface_azimuth, T=None, P=None, solar_constant=1366.1,
atmos_refract=0.5667, albedo=0.25, linke_turbidity=None,
extraradiation_method='spencer',
airmass_model='k... | r'''Calculates the amount of solar radiation and radiation reflected back
the atmosphere which hits a surface at a specified tilt, and facing a
specified azimuth.
This functions is a wrapper for the incredibly
comprehensive `pvlib library <https://github.com/pvlib/pvlib-python>`_,
and requir... |
def setPositionLinkedTo(self, widgets):
"""
Sets the widget that this popup will be linked to for positional
changes.
:param widgets | <QWidget> || [<QWidget>, ..]
"""
if type(widgets) in (list, set, tuple):
new_widgets = list(widgets)
... | Sets the widget that this popup will be linked to for positional
changes.
:param widgets | <QWidget> || [<QWidget>, ..] |
def run(command, parser, cl_args, unknown_args):
'''
:param command:
:param parser:
:param cl_args:
:param unknown_args:
:return:
'''
Log.debug("Restart Args: %s", cl_args)
container_id = cl_args['container-id']
if cl_args['deploy_mode'] == config.SERVER_MODE:
dict_extra_args = {"container_id":... | :param command:
:param parser:
:param cl_args:
:param unknown_args:
:return: |
def compute_cumsum(
df,
id_cols: List[str],
reference_cols: List[str],
value_cols: List[str],
new_value_cols: List[str] = None,
cols_to_keep: List[str] = None
):
"""
Compute cumsum for a group of columns.
---
### Parameters
*mandatory :*
- `id_cols` (*list*): the colum... | Compute cumsum for a group of columns.
---
### Parameters
*mandatory :*
- `id_cols` (*list*): the columns id to create each group
- `reference_cols` (*list*): the columns to order the cumsum
- `value_cols` (*list*): the columns to cumsum
*optional :*
- `new_value_cols` (*list*): the ... |
def on_cache_changed(self, direct, which=None):
"""
A callback funtion, which sets local flags when the elements of some cached inputs change
this function gets 'hooked up' to the inputs when we cache them, and upon their elements being changed we update here.
"""
for what in [d... | A callback funtion, which sets local flags when the elements of some cached inputs change
this function gets 'hooked up' to the inputs when we cache them, and upon their elements being changed we update here. |
def byte_number_string(
number, thousandsSep=True, partition=False, base1024=True, appendBytes=True
):
"""Convert bytes into human-readable representation."""
magsuffix = ""
bytesuffix = ""
if partition:
magnitude = 0
if base1024:
while number >= 1024:
ma... | Convert bytes into human-readable representation. |
def extend_name(suffix):
"""A factory for class decorators that modify the class name by appending some text to it.
Example:
@extend_name('_Foo')
class Class:
pass
assert Class.__name__ == 'Class_Foo'
"""
def dec(cls):
name = '{}{}'.format(cls.__name__, su... | A factory for class decorators that modify the class name by appending some text to it.
Example:
@extend_name('_Foo')
class Class:
pass
assert Class.__name__ == 'Class_Foo' |
def _write_local_data_files(self, cursor):
"""
Takes a cursor, and writes results to a local file.
:return: A dictionary where keys are filenames to be used as object
names in GCS, and values are file handles to local files that
contain the data for the GCS objects.
... | Takes a cursor, and writes results to a local file.
:return: A dictionary where keys are filenames to be used as object
names in GCS, and values are file handles to local files that
contain the data for the GCS objects. |
def fsqrt(q):
''' given a non-negative fraction q, return a pair (a,b) such that q = a * a * b
where b is a square-free integer.
if q is a perfect square, a is its square root and b is one.
'''
if q == 0:
return q, 1
if q < 0:
raise ValueError('math domain error %s' % q... | given a non-negative fraction q, return a pair (a,b) such that q = a * a * b
where b is a square-free integer.
if q is a perfect square, a is its square root and b is one. |
def get_page_objects_by_ext_type(context, object_type):
"""
**Arguments**
``object_type``
object type
:return selected objects
"""
try:
objects = context['page']['ext_content'][object_type]
except KeyError:
raise template.TemplateSyntaxError('wrong content type: {0:... | **Arguments**
``object_type``
object type
:return selected objects |
def patch_traces(
self,
project_id,
traces,
retry=google.api_core.gapic_v1.method.DEFAULT,
timeout=google.api_core.gapic_v1.method.DEFAULT,
metadata=None,
):
"""
Sends new traces to Stackdriver Trace or updates existing traces. If the ID
of a t... | Sends new traces to Stackdriver Trace or updates existing traces. If the ID
of a trace that you send matches that of an existing trace, any fields
in the existing trace and its spans are overwritten by the provided values,
and any new fields provided are merged with the existing trace data. If t... |
def check_lengths(*arrays):
"""
tool to ensure input and output data have the same number of samples
Parameters
----------
*arrays : iterable of arrays to be checked
Returns
-------
None
"""
lengths = [len(array) for array in arrays]
if len(np.unique(lengths)) > 1:
... | tool to ensure input and output data have the same number of samples
Parameters
----------
*arrays : iterable of arrays to be checked
Returns
-------
None |
def apply_update(self, doc, update_spec):
"""Override DocManagerBase.apply_update to have flat documents."""
# Replace a whole document
if not '$set' in update_spec and not '$unset' in update_spec:
# update_spec contains the new document.
# Update the key in Solr based on... | Override DocManagerBase.apply_update to have flat documents. |
def register(cls, use_admin=True):
"""Register with the API a :class:`sandman.model.Model` class and
associated endpoint.
:param cls: User-defined class derived from :class:`sandman.model.Model` to
be registered with the endpoint returned by :func:`endpoint()`
:type cls: :class:`sandman... | Register with the API a :class:`sandman.model.Model` class and
associated endpoint.
:param cls: User-defined class derived from :class:`sandman.model.Model` to
be registered with the endpoint returned by :func:`endpoint()`
:type cls: :class:`sandman.model.Model` or tuple |
def get_owner(self, default=True):
"""Return (User ID, Group ID) tuple
:param bool default: Whether to return default if not set.
:rtype: tuple[int, int]
"""
uid, gid = self.owner
if not uid and default:
uid = os.getuid()
if not gid and default:
... | Return (User ID, Group ID) tuple
:param bool default: Whether to return default if not set.
:rtype: tuple[int, int] |
def is_email():
"""
Validates that a fields value is a valid email address.
"""
email = (
ur'(?!^\.)' # No dot at start
ur'(?!.*\.@)' # No dot before at sign
ur'(?!.*@\.)' # No dot after at sign
ur'(?!.*\.$)' # No dot at the end
ur'(?!.*\.\.)' # No dou... | Validates that a fields value is a valid email address. |
def update_user(self, user_id, **kwargs):
"""
Updates a user.
:param user_id: The unique ID of the user.
:type user_id: ``str``
"""
properties = {}
for attr, value in kwargs.items():
properties[self._underscore_to_camelcase(attr)] = value... | Updates a user.
:param user_id: The unique ID of the user.
:type user_id: ``str`` |
def build_tree(self, *args, **kwargs):
"""Dispatch a tree build call. Note that you need at least four
taxa to express some evolutionary history on an unrooted tree."""
# Check length #
assert len(self) > 3
# Default option #
algorithm = kwargs.pop(kwargs, None)
i... | Dispatch a tree build call. Note that you need at least four
taxa to express some evolutionary history on an unrooted tree. |
def mqtt_connected(func):
"""
MQTTClient coroutines decorator which will wait until connection before calling the decorated method.
:param func: coroutine to be called once connected
:return: coroutine result
"""
@asyncio.coroutine
@wraps(func)
def wrapper(self, *args, **kwar... | MQTTClient coroutines decorator which will wait until connection before calling the decorated method.
:param func: coroutine to be called once connected
:return: coroutine result |
def is_dot(ip):
"""Return true if the IP address is in dotted decimal notation."""
octets = str(ip).split('.')
if len(octets) != 4:
return False
for i in octets:
try:
val = int(i)
except ValueError:
return False
if val > 255 or val < 0:
... | Return true if the IP address is in dotted decimal notation. |
def export(self, file_path=None, export_format=None):
""" Write the users to a file. """
with io.open(file_path, mode='w', encoding="utf-8") as export_file:
if export_format == 'yaml':
import yaml
yaml.safe_dump(self.to_dict(), export_file, default_flow_style=... | Write the users to a file. |
def _plot_histogram(series, bins=10, figsize=(6, 4), facecolor='#337ab7'):
"""Plot an histogram from the data and return the AxesSubplot object.
Parameters
----------
series : Series
The data to plot
figsize : tuple
The size of the figure (width, height) in inches, default (6,4)
... | Plot an histogram from the data and return the AxesSubplot object.
Parameters
----------
series : Series
The data to plot
figsize : tuple
The size of the figure (width, height) in inches, default (6,4)
facecolor : str
The color code.
Returns
-------
matplotlib.A... |
def save_performance(db, job_id, records):
"""
Save in the database the performance information about the given job.
:param db: a :class:`openquake.server.dbapi.Db` instance
:param job_id: a job ID
:param records: a list of performance records
"""
# NB: rec['counts'] is a numpy.uint64 which... | Save in the database the performance information about the given job.
:param db: a :class:`openquake.server.dbapi.Db` instance
:param job_id: a job ID
:param records: a list of performance records |
def needs_sync(self):
"""
Check if enough time has elapsed to perform a sync().
A call to sync() should be performed every now and then, no matter what
has_state_changed() says. This is really just a safety thing to enforce
consistency in case the state gets messed up.
... | Check if enough time has elapsed to perform a sync().
A call to sync() should be performed every now and then, no matter what
has_state_changed() says. This is really just a safety thing to enforce
consistency in case the state gets messed up.
:rtype: boolean |
def unique_cpx_roots(rlist,tol = 0.001):
"""
The average of the root values is used when multiplicity
is greater than one.
Mark Wickert October 2016
"""
uniq = [rlist[0]]
mult = [1]
for k in range(1,len(rlist)):
N_uniq = len(uniq)
for m in range(N_uniq)... | The average of the root values is used when multiplicity
is greater than one.
Mark Wickert October 2016 |
def xdg_config_dir():
'''
Check xdg locations for config files
'''
xdg_config = os.getenv('XDG_CONFIG_HOME', os.path.expanduser('~/.config'))
xdg_config_directory = os.path.join(xdg_config, 'salt')
return xdg_config_directory | Check xdg locations for config files |
def set_generator_training_nb(self, number):
"""
sets self.samples_per_epoch which is used in model.fit if input is a generator
:param number:
:return:
"""
self.samples_per_epoch = number
diff_to_batch = number % self.get_batch_size()
if diff_to_batch > 0... | sets self.samples_per_epoch which is used in model.fit if input is a generator
:param number:
:return: |
def get_input(prompt, check, *, redo_prompt=None, repeat_prompt=False):
"""
Ask the user to input something on the terminal level, check their response
and ask again if they didn't answer correctly
"""
if isinstance(check, str):
check = (check,)
to_join = []
for item in check:
... | Ask the user to input something on the terminal level, check their response
and ask again if they didn't answer correctly |
def gauge(self, name, value, rate=1):
# type: (str, float, float) -> None
"""Send a Gauge metric with the specified value"""
if self._should_send_metric(name, rate):
if not is_numeric(value):
value = float(value)
self._request(
Gauge(
... | Send a Gauge metric with the specified value |
def addElement(self,etype='hex8',corners=[-1.0,-1.0,-1.0,1.,-1.0,-1.0,1.0,1.0,-1.0,-1.0,1.0,-1.0,-1.0,-1.0,1.0,1.0,-1.0,1.0,1.0,1.0,1.0,-1.0,1.0,1.0],name='new_elem'):
'''
corners - list of nodal coordinates properly ordered for element type (counter clockwise)
'''
lastelm = self.element... | corners - list of nodal coordinates properly ordered for element type (counter clockwise) |
def first_produced_mesh(self):
"""The first produced mesh.
:return: the first produced mesh
:rtype: knittingpattern.Mesh.Mesh
:raises IndexError: if no mesh is produced
.. seealso:: :attr:`number_of_produced_meshes`
"""
for instruction in self.instructions:
... | The first produced mesh.
:return: the first produced mesh
:rtype: knittingpattern.Mesh.Mesh
:raises IndexError: if no mesh is produced
.. seealso:: :attr:`number_of_produced_meshes` |
def pinyin_to_ipa(s):
"""Convert all Pinyin syllables in *s* to IPA.
Spaces are added between connected syllables and syllable-separating
apostrophes are removed.
"""
return _convert(s, zhon.pinyin.syllable, pinyin_syllable_to_ipa,
remove_apostrophes=True, separate_syllables=Tr... | Convert all Pinyin syllables in *s* to IPA.
Spaces are added between connected syllables and syllable-separating
apostrophes are removed. |
def pre_release(self):
""" Return true if version is a pre-release. """
label = self.version_info.get('label', None)
pre = self.version_info.get('pre', None)
return True if (label is not None and pre is not None) else False | Return true if version is a pre-release. |
def unsubscribe(self, coro):
"""
Unsubscribe from status updates from the Opentherm Gateway.
Can only be used after connect()
@coro is a coroutine which has been subscribed with subscribe()
earlier.
Return True on success, false if not connected or subscribed.
"""... | Unsubscribe from status updates from the Opentherm Gateway.
Can only be used after connect()
@coro is a coroutine which has been subscribed with subscribe()
earlier.
Return True on success, false if not connected or subscribed. |
def send_start(remote, code, device=None, address=None):
"""
All parameters are passed to irsend. See the man page for irsend
for details about their usage.
Parameters
----------
remote: str
code: str
device: str
address: str
Notes
-----
No attempt is made to catch or h... | All parameters are passed to irsend. See the man page for irsend
for details about their usage.
Parameters
----------
remote: str
code: str
device: str
address: str
Notes
-----
No attempt is made to catch or handle errors. See the documentation
for subprocess.check_output t... |
def p_parens_expr(p):
"""
expr : LPAREN expr RPAREN
"""
p[0] = node.expr(op="parens", args=node.expr_list([p[2]])) | expr : LPAREN expr RPAREN |
def get_number_of_partitions_for(self, ar):
"""Return the number of selected partitions
"""
# fetch the number of partitions from the request
uid = api.get_uid(ar)
num = self.request.get("primary", {}).get(uid)
if num is None:
# get the number of partitions f... | Return the number of selected partitions |
def _sort(values, axis=-1, direction='ASCENDING', stable=False, name=None): # pylint: disable=unused-argument
"""Numpy implementation of `tf.sort`."""
if direction == 'ASCENDING':
pass
elif direction == 'DESCENDING':
values = np.negative(values)
else:
raise ValueError('Unrecognized direction: {}.'.... | Numpy implementation of `tf.sort`. |
def rescan(self):
"""Checks files and directories on watchlist for updates, rescans them for new data products.
If any are found, returns them. Skips those in directories whose watchingState is set to Purr.UNWATCHED.
"""
if not self.attached:
return
dprint(5, "startin... | Checks files and directories on watchlist for updates, rescans them for new data products.
If any are found, returns them. Skips those in directories whose watchingState is set to Purr.UNWATCHED. |
def inspect_image(self, image_name, image_tag=''):
'''
a method to retrieve the settings of an image
:param image_name: string with name or id of image
:param image_tag: [optional] string with tag associated with image
:return: dictionary of settings of imag... | a method to retrieve the settings of an image
:param image_name: string with name or id of image
:param image_tag: [optional] string with tag associated with image
:return: dictionary of settings of image
{ TOO MANY TO LIST } |
def _ceil(self, address):
"""
Returns the smallest page boundary value not less than the address.
:rtype: int
:param address: the address to calculate its ceil.
:return: the ceil of C{address}.
"""
return (((address - 1) + self.page_size) & ~self.page_mask) & self... | Returns the smallest page boundary value not less than the address.
:rtype: int
:param address: the address to calculate its ceil.
:return: the ceil of C{address}. |
def merge_with_master_config(self, config, defaults={}, delete_orphan_fields=False) -> dict:
"""
Merge current ontology with input master config.
:param config: master config, should be str or dict
:param defaults: a dict that sets default color and icon
:param delete_orphan_fie... | Merge current ontology with input master config.
:param config: master config, should be str or dict
:param defaults: a dict that sets default color and icon
:param delete_orphan_fields: if a property doesn't exist in the ontology then delete it
:return: merged master config in dict |
def new_workspace(self, name=None, layout=None, workspace_id=None, index=None) -> WorkspaceLayout.WorkspaceLayout:
""" Create a new workspace, insert into document_model, and return it. """
workspace = WorkspaceLayout.WorkspaceLayout()
self.document_model.insert_workspace(index if index is not N... | Create a new workspace, insert into document_model, and return it. |
def decode_list(input_props, name):
# type: (Dict[str, str], str) -> List[str]
"""
Decodes a space-separated list
"""
val_str = input_props.get(name, None)
if val_str:
return val_str.split(" ")
return [] | Decodes a space-separated list |
def shadowUpdate(self, srcJSONPayload, srcCallback, srcTimeout):
"""
**Description**
Update the device shadow JSON document string from AWS IoT by publishing the provided JSON
document to the corresponding shadow topics. Shadow response topics will be subscribed to
receive res... | **Description**
Update the device shadow JSON document string from AWS IoT by publishing the provided JSON
document to the corresponding shadow topics. Shadow response topics will be subscribed to
receive responses from AWS IoT regarding the result of the get operation. Response will be
... |
def secret_file(filename):
"""Will check the permissions of things which really
should be secret files"""
filestat = os.stat(abspath(filename))
if stat.S_ISREG(filestat.st_mode) == 0 and \
stat.S_ISLNK(filestat.st_mode) == 0:
e_msg = "Secret file %s must be a real file or symlink" % filen... | Will check the permissions of things which really
should be secret files |
def compile_loaderplugin_entry(self, spec, entry):
"""
Generic loader plugin entry handler.
The default implementation assumes that everything up to the
first '!' symbol resolves to some known loader plugin within
the registry.
The registry instance responsible for the ... | Generic loader plugin entry handler.
The default implementation assumes that everything up to the
first '!' symbol resolves to some known loader plugin within
the registry.
The registry instance responsible for the resolution of the
loader plugin handlers must be available in t... |
def define_magic(self, name, func):
"""[Deprecated] Expose own function as magic function for IPython.
Example::
def foo_impl(self, parameter_s=''):
'My very own magic!. (Use docstrings, IPython reads them).'
print 'Magic function. Passed parameter is betwee... | [Deprecated] Expose own function as magic function for IPython.
Example::
def foo_impl(self, parameter_s=''):
'My very own magic!. (Use docstrings, IPython reads them).'
print 'Magic function. Passed parameter is between < >:'
print '<%s>' % paramete... |
def hicup_filtering_chart(self):
""" Generate the HiCUP filtering plot """
# Specify the order of the different possible categories
keys = OrderedDict()
keys['Valid_Pairs'] = { 'color': '#2f7ed8', 'name': 'Valid Pairs' }
keys['Same_Fragment_Internal'] = { 'color': '#0... | Generate the HiCUP filtering plot |
def vhost_exists(name, runas=None):
'''
Return whether the vhost exists based on rabbitmqctl list_vhosts.
CLI Example:
.. code-block:: bash
salt '*' rabbitmq.vhost_exists rabbit_host
'''
if runas is None and not salt.utils.platform.is_windows():
runas = salt.utils.user.get_use... | Return whether the vhost exists based on rabbitmqctl list_vhosts.
CLI Example:
.. code-block:: bash
salt '*' rabbitmq.vhost_exists rabbit_host |
def validate(self):
r"""Validate user credentials.
Returns
-------
bool
Examples
--------
Validate credentials.
>>> from srpenergy.client import SrpEnergyClient
>>>
>>> accountid = 'your account id'
>>> username = '... | r"""Validate user credentials.
Returns
-------
bool
Examples
--------
Validate credentials.
>>> from srpenergy.client import SrpEnergyClient
>>>
>>> accountid = 'your account id'
>>> username = 'your username'
>>> p... |
def clear_bucket_props(self, bucket):
"""
Clear bucket properties, resetting them to their defaults
"""
if not self.pb_clear_bucket_props():
return False
msg_code = riak.pb.messages.MSG_CODE_RESET_BUCKET_REQ
codec = self._get_codec(msg_code)
msg = code... | Clear bucket properties, resetting them to their defaults |
def close(self):
""" Stops the read thread, waits for it to exit cleanly, then closes the underlying serial port """
self.alive = False
self.rxThread.join()
self.serial.close() | Stops the read thread, waits for it to exit cleanly, then closes the underlying serial port |
def fastaParseSgd(header):
"""Custom parser for fasta headers in the SGD format, see
www.yeastgenome.org.
:param header: str, protein entry header from a fasta file
:returns: dict, parsed header
"""
rePattern = '([\S]+)\s([\S]+).+(\".+\")'
ID, name, description = re.match(rePattern, header... | Custom parser for fasta headers in the SGD format, see
www.yeastgenome.org.
:param header: str, protein entry header from a fasta file
:returns: dict, parsed header |
def import_parms(self, args):
"""Import external dict to internal dict"""
for key, val in args.items():
self.set_parm(key, val) | Import external dict to internal dict |
def as_unordered(self, inplace=False):
"""
Set the Categorical to be unordered.
Parameters
----------
inplace : bool, default False
Whether or not to set the ordered attribute in-place or return
a copy of this categorical with ordered set to False.
... | Set the Categorical to be unordered.
Parameters
----------
inplace : bool, default False
Whether or not to set the ordered attribute in-place or return
a copy of this categorical with ordered set to False. |
def _cast_to_type(self, value):
""" Convert the value to a float and raise error on failures"""
try:
return float(value)
except (ValueError, TypeError):
self.fail('invalid', value=value) | Convert the value to a float and raise error on failures |
def resize(self, height, width, **kwargs):
"""
resize pty of an execed process
"""
self.client.exec_resize(self.exec_id, height=height, width=width) | resize pty of an execed process |
def delete(block_id):
"""Scheduling block detail resource."""
_url = get_root_url()
LOG.debug('Requested delete of SBI %s', block_id)
try:
DB.delete_sched_block_instance(block_id)
response = dict(message='Deleted block: _id = {}'.format(block_id))
response['_links'] = {
... | Scheduling block detail resource. |
def has_key(self, key):
"""Case insensitive test whether 'key' exists."""
k = self._lowerOrReturn(key)
return k in self.data | Case insensitive test whether 'key' exists. |
def isASLREnabled(self):
"""
Determines if the current L{PE} instance has the DYNAMICBASE (Use address space layout randomization) flag enabled.
@see: U{http://msdn.microsoft.com/en-us/library/bb384887.aspx}
@rtype: bool
@return: Returns C{True} if the current L{PE} instance has... | Determines if the current L{PE} instance has the DYNAMICBASE (Use address space layout randomization) flag enabled.
@see: U{http://msdn.microsoft.com/en-us/library/bb384887.aspx}
@rtype: bool
@return: Returns C{True} if the current L{PE} instance has the DYNAMICBASE flag enabled. Otherwise, ret... |
def _cluster_hits(hits, clusters, assigned_hit_array, cluster_hit_indices, column_cluster_distance, row_cluster_distance, frame_cluster_distance, min_hit_charge, max_hit_charge, ignore_same_hits, noisy_pixels, disabled_pixels):
''' Main precompiled function that loopes over the hits and clusters them
'''
to... | Main precompiled function that loopes over the hits and clusters them |
def phase_by_transmission(g, window_size, copy=True):
"""Phase genotypes in a trio or cross where possible using Mendelian
transmission.
Parameters
----------
g : array_like, int, shape (n_variants, n_samples, 2)
Genotype array, with parents as first two columns and progeny as
remai... | Phase genotypes in a trio or cross where possible using Mendelian
transmission.
Parameters
----------
g : array_like, int, shape (n_variants, n_samples, 2)
Genotype array, with parents as first two columns and progeny as
remaining columns.
window_size : int
Number of previou... |
def _bld_pab_generic(self, funcname, **kwargs):
"""
implements a generic version of an attribute based pandas function
"""
margs = {'mtype': pab, 'kwargs': kwargs}
setattr(self, funcname, margs) | implements a generic version of an attribute based pandas function |
def apply_noise(data, noise):
"""
Applies noise to a sparse matrix. Noise can be an integer between 0 and
100, indicating the percentage of ones in the original input to move, or
a float in [0, 1), indicating the same thing.
The input matrix is modified in-place, and nothing is returned.
This operation doe... | Applies noise to a sparse matrix. Noise can be an integer between 0 and
100, indicating the percentage of ones in the original input to move, or
a float in [0, 1), indicating the same thing.
The input matrix is modified in-place, and nothing is returned.
This operation does not affect the sparsity of the matri... |
def groups_dynamic(self):
""" returns dynamic relationship for groups - allowing for
filtering of data """
return sa.orm.relationship(
"Group",
secondary="users_groups",
lazy="dynamic",
passive_deletes=True,
passive_updates=True,
... | returns dynamic relationship for groups - allowing for
filtering of data |
def _unpack_tableswitch(bc, offset):
"""
function for unpacking the tableswitch op arguments
"""
jump = (offset % 4)
if jump:
offset += (4 - jump)
(default, low, high), offset = _unpack(_struct_iii, bc, offset)
joffs = list()
for _index in range((high - low) + 1):
j, o... | function for unpacking the tableswitch op arguments |
def __search_iterable(self,
obj,
item,
parent="root",
parents_ids=frozenset({})):
"""Search iterables except dictionaries, sets and strings."""
for i, thing in enumerate(obj):
new_parent ... | Search iterables except dictionaries, sets and strings. |
def identify_sep(filepath):
"""
Identifies the separator of data in a filepath.
It reads the first line of the file and counts supported separators.
Currently supported separators: ['|', ';', ',','\t',':']
"""
ext = os.path.splitext(filepath)[1].lower()
allowed_exts = ['.csv', '.txt', '.tsv'... | Identifies the separator of data in a filepath.
It reads the first line of the file and counts supported separators.
Currently supported separators: ['|', ';', ',','\t',':'] |
def Nu_x(self, L, theta, Ts, **statef):
"""
Calculate the local Nusselt number.
:param L: [m] characteristic length of the heat transfer surface
:param theta: [°] angle of the surface with the vertical
:param Ts: [K] heat transfer surface temperature
:param Tf: [K] bulk ... | Calculate the local Nusselt number.
:param L: [m] characteristic length of the heat transfer surface
:param theta: [°] angle of the surface with the vertical
:param Ts: [K] heat transfer surface temperature
:param Tf: [K] bulk fluid temperature
:returns: float |
def get_freq_map_and_normalizations(self, frequency_list,
upper_freq_formula):
"""
If using the --vary-fupper capability we need to store the mapping
between index and frequencies in the list. We also precalculate the
normalization factor at every ... | If using the --vary-fupper capability we need to store the mapping
between index and frequencies in the list. We also precalculate the
normalization factor at every frequency, which is used when estimating
overlaps to account for abrupt changes in termination frequency.
Parameters
... |
def _oauth_request_parameters(self, url, access_token, parameters={},
method="GET"):
"""Returns the OAuth parameters as a dict for the given request.
parameters should include all POST arguments and query string arguments
that will be sent with the request.
... | Returns the OAuth parameters as a dict for the given request.
parameters should include all POST arguments and query string arguments
that will be sent with the request. |
def unicode_to_bytes(s, encoding='utf-8', errors='replace'):
"""
Helper to convert unicode strings to bytes for data that needs to be
written to on output stream (i.e. terminal)
For Python 3 this should be called str_to_bytes
:param str s: string to encode
:param str encoding: utf-8 by default
... | Helper to convert unicode strings to bytes for data that needs to be
written to on output stream (i.e. terminal)
For Python 3 this should be called str_to_bytes
:param str s: string to encode
:param str encoding: utf-8 by default
:param str errors: what to do when encoding fails
:return: byte s... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.