code stringlengths 75 104k | docstring stringlengths 1 46.9k |
|---|---|
def as_dict(self, replace_value_names=True):
"""Iterate, link terms and convert to a dict"""
# This function is a hack, due to confusion between the root of the document, which
# should contain all terms, and the root section, which has only terms that are not
# in another section. So, ... | Iterate, link terms and convert to a dict |
def _getNodeData(self, name, metadata, channel=None):
""" Returns a data point from data"""
nodeChannel = None
if name in metadata:
nodeChannelList = metadata[name]
if len(nodeChannelList) > 1:
nodeChannel = channel if channel is not None else nodeChannelL... | Returns a data point from data |
def fetch_commit(self, event):
"""
Fetch commit data for specified event.
:param dict event: dictionary with event information
:rtype: dict
:return: dictionary with commit data
"""
gh = self.github
user = self.options.user
repo = self.options.pro... | Fetch commit data for specified event.
:param dict event: dictionary with event information
:rtype: dict
:return: dictionary with commit data |
def _get_fido_dollar(self, account_number, number):
"""Get current Fido dollar balance."""
# Prepare data
data = json.dumps({"fidoDollarBalanceFormList":
[{"phoneNumber": number,
"accountNumber": account_number}]})
# Prepare headers... | Get current Fido dollar balance. |
def _dump_stats_group(self, title, items, normal_formatter=None,
verbose_formatter=None):
"""Dump a statistics group.
In verbose mode, do so as a config file so
that other processors can load the information if they want to.
:param normal_formatter: the callable to apply... | Dump a statistics group.
In verbose mode, do so as a config file so
that other processors can load the information if they want to.
:param normal_formatter: the callable to apply to the value
before displaying it in normal mode
:param verbose_formatter: the callable to... |
def build_indentation_list(parser: str = 'github'):
r"""Create a data structure that holds the state of indentations.
:parameter parser: decides the length of the list.
Defaults to ``github``.
:type parser: str
:returns: indentation_list, a list that contains the state of
indentations... | r"""Create a data structure that holds the state of indentations.
:parameter parser: decides the length of the list.
Defaults to ``github``.
:type parser: str
:returns: indentation_list, a list that contains the state of
indentations given a header type.
:rtype: list
:raises: a bu... |
def get_artist(self, id_):
"""Data for a specific artist."""
endpoint = "artists/{id}".format(id=id_)
return self._make_request(endpoint) | Data for a specific artist. |
def create_packages(self):
"""Create missing packages joining the vendor root to the base of the vendored distribution.
For example, given a root at ``/home/jake/dev/pantsbuild/pex`` and a vendored distribution at
``pex/vendor/_vendored/requests`` this method would create the following package files::
... | Create missing packages joining the vendor root to the base of the vendored distribution.
For example, given a root at ``/home/jake/dev/pantsbuild/pex`` and a vendored distribution at
``pex/vendor/_vendored/requests`` this method would create the following package files::
pex/vendor/_vendored/__init__.p... |
def compile_action_preconditions(self,
state: Sequence[tf.Tensor],
action: Sequence[tf.Tensor]) -> List[TensorFluent]:
'''Compiles the action preconditions given current `state` and `action` fluents.
Args:
state (Sequence[tf.Tensor]): The current state fluents.
... | Compiles the action preconditions given current `state` and `action` fluents.
Args:
state (Sequence[tf.Tensor]): The current state fluents.
action (Sequence[tf.Tensor]): The action fluents.
Returns:
A list of :obj:`rddl2tf.fluent.TensorFluent`. |
def project(lon0, lat0, lon1, lat1):
"""This function performs a stereographic projection on the unit
vector (lon1,lat1) with the pole defined at the reference unit
vector (lon0,lat0)."""
costh = np.cos(np.pi / 2. - lat0)
cosphi = np.cos(lon0)
sinth = np.sin(np.pi / 2. - lat0)
sinphi = np.... | This function performs a stereographic projection on the unit
vector (lon1,lat1) with the pole defined at the reference unit
vector (lon0,lat0). |
def get_single_group_category(self, group_category_id):
"""
Get a single group category.
Returns the data for a single group category, or a 401 if the caller doesn't have
the rights to see it.
"""
path = {}
data = {}
params = {}
# REQU... | Get a single group category.
Returns the data for a single group category, or a 401 if the caller doesn't have
the rights to see it. |
def reply(self, incoming, user, message, prefix=None):
"""Replies to a user in a given channel or PM.
If the specified incoming is a user, simply sends a PM to user.
If the specified incoming is a channel, prefixes the message with the
user's nick and sends it to the channel.
T... | Replies to a user in a given channel or PM.
If the specified incoming is a user, simply sends a PM to user.
If the specified incoming is a channel, prefixes the message with the
user's nick and sends it to the channel.
This is specifically useful in creating responses to commands that ... |
def ensure_path(path, mode=0o777):
"""Ensure that path exists in a multiprocessing safe way.
If the path does not exist, recursively create it and its parent
directories using the provided mode. If the path already exists,
do nothing. The umask is cleared to enable the mode to be set,
and then re... | Ensure that path exists in a multiprocessing safe way.
If the path does not exist, recursively create it and its parent
directories using the provided mode. If the path already exists,
do nothing. The umask is cleared to enable the mode to be set,
and then reset to the original value after the mode i... |
def snmp_server_group_group_name(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
snmp_server = ET.SubElement(config, "snmp-server", xmlns="urn:brocade.com:mgmt:brocade-snmp")
group = ET.SubElement(snmp_server, "group")
group_version_key = ET.SubE... | Auto Generated Code |
def get_devices(self, force_reload=False, save_devices=True):
"""
get all devices that are linked to the user, if the local device
file is not existing the devices will be obtained from the LaMetric
cloud, otherwise the local device file will be read.
:param bool force_reload: W... | get all devices that are linked to the user, if the local device
file is not existing the devices will be obtained from the LaMetric
cloud, otherwise the local device file will be read.
:param bool force_reload: When True, devices are read again from cloud
:param bool save_devices: When... |
def QueryHowDoI(Query, num_answers, full_text):
'''
Kicks off a subprocess to send the 'Query' to HowDoI
Prints the result, which in this program will route to a gooeyGUI window
:param Query: text english question to ask the HowDoI web engine
:return: nothing
'''
howdoi_command = HOW_DO_I_CO... | Kicks off a subprocess to send the 'Query' to HowDoI
Prints the result, which in this program will route to a gooeyGUI window
:param Query: text english question to ask the HowDoI web engine
:return: nothing |
def idxmin(self, **kwargs):
"""Returns the first occurrence of the minimum over requested axis.
Returns:
A new QueryCompiler object containing the minimum of each column or axis.
"""
if self._is_transposed:
kwargs["axis"] = kwargs.get("axis", 0) ^ 1
r... | Returns the first occurrence of the minimum over requested axis.
Returns:
A new QueryCompiler object containing the minimum of each column or axis. |
def find_element(self, search):
'''
DOM_performSearch(self, query, includeUserAgentShadowDOM)
Python Function: DOM_performSearch
Domain: DOM
Method name: performSearch
WARNING: This function is marked 'Experimental'!
Parameters:
'query' (type: string) -... | DOM_performSearch(self, query, includeUserAgentShadowDOM)
Python Function: DOM_performSearch
Domain: DOM
Method name: performSearch
WARNING: This function is marked 'Experimental'!
Parameters:
'query' (type: string) -> Plain text or query selector or XPath s... |
def main_crop():
"""This function does the real work. It is called by main() in
pdfCropMargins.py, which just handles catching exceptions and cleaning up."""
##
## Process some of the command-line arguments.
##
if args.verbose:
print("\nProcessing the PDF with pdfCropMargins (version"... | This function does the real work. It is called by main() in
pdfCropMargins.py, which just handles catching exceptions and cleaning up. |
def partial_tempering(topfile="processed.top", outfile="scaled.top", banned_lines='',
scale_lipids=1.0, scale_protein=1.0):
"""Set up topology for partial tempering (REST2) replica exchange.
.. versionchanged:: 0.7.0
Use keyword arguments instead of an `args` Namespace... | Set up topology for partial tempering (REST2) replica exchange.
.. versionchanged:: 0.7.0
Use keyword arguments instead of an `args` Namespace object. |
def flatten_list(l: List[list]) -> list:
""" takes a list of lists, l and returns a flat list
"""
return [v for inner_l in l for v in inner_l] | takes a list of lists, l and returns a flat list |
def merge(profile, head, base, commit_message=None):
"""Merge the head of a branch into the base branch.
Args:
profile
A profile generated from ``simplygithub.authentication.profile``.
Such profiles tell this module (i) the ``repo`` to connect to,
and (ii) the ``tok... | Merge the head of a branch into the base branch.
Args:
profile
A profile generated from ``simplygithub.authentication.profile``.
Such profiles tell this module (i) the ``repo`` to connect to,
and (ii) the ``token`` to connect with.
head
The head to ... |
def _check_times(self, min_times, max_times, step):
'''
Make sure that the arguments are valid
:raises: KittyException if not valid
'''
kassert.is_int(min_times)
kassert.is_int(max_times)
kassert.is_int(step)
if not((min_times >= 0) and (max_times > 0) an... | Make sure that the arguments are valid
:raises: KittyException if not valid |
def _read_addr_resolve(self, length, htype):
"""Resolve MAC address according to protocol.
Positional arguments:
* length -- int, hardware address length
* htype -- int, hardware type
Returns:
* str -- MAC address
"""
if htype == 1: # Ether... | Resolve MAC address according to protocol.
Positional arguments:
* length -- int, hardware address length
* htype -- int, hardware type
Returns:
* str -- MAC address |
def get_pyobj(self, multihash, **kwargs):
"""Loads a pickled Python object from IPFS.
.. deprecated:: 0.4.2
The ``*_pyobj`` APIs allow for arbitrary code execution if abused.
Either switch to :meth:`~ipfsapi.Client.get_json` or use
``pickle.loads(client.cat(multihash))`... | Loads a pickled Python object from IPFS.
.. deprecated:: 0.4.2
The ``*_pyobj`` APIs allow for arbitrary code execution if abused.
Either switch to :meth:`~ipfsapi.Client.get_json` or use
``pickle.loads(client.cat(multihash))`` instead.
.. caution::
The pic... |
def get_choice(cls, value):
"""
Return the underlying :class:`ChoiceItem` for a given value.
"""
attribute_for_value = cls.attributes[value]
return cls._fields[attribute_for_value] | Return the underlying :class:`ChoiceItem` for a given value. |
def wrap_reports(cls, reports, content_type):
''' Wraps the reports in a _ReportTemplateWrapper for the given
content_type -- this allows data to be returned as HTML links, for
instance. '''
reports = [
_ReportTemplateWrapper(content_type, report)
for report in r... | Wraps the reports in a _ReportTemplateWrapper for the given
content_type -- this allows data to be returned as HTML links, for
instance. |
def dependencies(self, kwargs=None, expand_only=False):
"""Returns all dependencies of this assistant with regards to specified kwargs.
If expand_only == False, this method returns list of mappings of dependency types
to actual dependencies (keeps order, types can repeat), e.g.
Example:... | Returns all dependencies of this assistant with regards to specified kwargs.
If expand_only == False, this method returns list of mappings of dependency types
to actual dependencies (keeps order, types can repeat), e.g.
Example:
[{'rpm', ['rubygems']}, {'gem', ['mygem']}, {'rpm', ['spam... |
def load_commodities(self):
"""
Load the commodities for Amounts in this object.
"""
if isinstance(self.amount, Amount):
self.amount = Amount("{0:.8f} {1}".format(self.amount.to_double(), self.currency))
else:
self.amount = Amount("{0:.8f} {1}".format(self... | Load the commodities for Amounts in this object. |
def create_rank_dicts(self, alt_scores):
"""
Description:
Takes in the scores of the alternatives in the form alt:score and
generates the dictionaries mapping alternatives to rankings and
rankings to alternatives.
Parameters:
alt_scores: dic... | Description:
Takes in the scores of the alternatives in the form alt:score and
generates the dictionaries mapping alternatives to rankings and
rankings to alternatives.
Parameters:
alt_scores: dictionary of the scores of every alternative |
def add_eps(self, eps):
"""
Incorporate the list of EPs given by *eps*.
"""
# (nodeid, pred, label, args, lnk, surface, base)
_nodeids, _eps, _vars = self._nodeids, self._eps, self._vars
for ep in eps:
try:
if not isinstance(ep, ElementaryPredi... | Incorporate the list of EPs given by *eps*. |
def create_shn (archive, compression, cmd, verbosity, interactive, filenames):
"""Compress a WAV file to a SHN archive."""
if len(filenames) > 1:
raise util.PatoolError("multiple filenames for shorten not supported")
cmdlist = [util.shell_quote(cmd)]
cmdlist.extend(['-', util.shell_quote(archive... | Compress a WAV file to a SHN archive. |
def translate_logical_line(start, end, contents, indent_stack, endmarker=False):
"""Translate raw contents to logical lines"""
# Remove leading blank lines.
while contents[0] == '\n':
start += 1
contents.pop(0)
# Remove trailing blank lines.
while contents[-1] == '\n':
end -= 1
... | Translate raw contents to logical lines |
def parse():
"""Parses all the modules in the library specified by the script args.
"""
from fortpy.code import CodeParser
c = CodeParser()
if args["verbose"]:
c.verbose = True
f90files = {}
c.scan_path(args["source"], f90files)
for fname, fpath in f90files.items():
... | Parses all the modules in the library specified by the script args. |
def maxEntropy(n,k):
"""
The maximum enropy we could get with n units and k winners
"""
s = float(k)/n
if s > 0.0 and s < 1.0:
entropy = - s * math.log(s,2) - (1 - s) * math.log(1 - s,2)
else:
entropy = 0
return n*entropy | The maximum enropy we could get with n units and k winners |
def csv_line(self, line):
'''turn a list of values into a CSV line'''
self.csv_sep = ","
return self.csv_sep.join(['"' + str(x) + '"' for x in line]) | turn a list of values into a CSV line |
def double_click(self):
"""
Performs a double click in the element.
Currently works only on Chrome driver.
"""
self.scroll_to()
ActionChains(self.parent.driver).double_click(self._element).perform() | Performs a double click in the element.
Currently works only on Chrome driver. |
def eventFilter(self, object, event):
"""
Resizes this overlay as the widget resizes.
:param object | <QtCore.QObject>
event | <QtCore.QEvent>
:return <bool>
"""
if object == self.parent() and event.type() == QtCore.QEvent.Resize:
... | Resizes this overlay as the widget resizes.
:param object | <QtCore.QObject>
event | <QtCore.QEvent>
:return <bool> |
def copy_from(self, other):
"""Copy other onto self."""
self.verbose, self.quiet, self.path, self.name, self.tracing = other.verbose, other.quiet, other.path, other.name, other.tracing | Copy other onto self. |
def _create_rates(self, dist='uniform', size=None, eps=1e-4):
'''Create a rate parameter (usually for a recurrent network layer).
Parameters
----------
dist : {'uniform', 'log'}, optional
Distribution of rate values. Defaults to ``'uniform'``.
size : int, optional
... | Create a rate parameter (usually for a recurrent network layer).
Parameters
----------
dist : {'uniform', 'log'}, optional
Distribution of rate values. Defaults to ``'uniform'``.
size : int, optional
Number of rates to create. Defaults to ``self.output_size``.
... |
def add_to_package_numpy(self, root, ndarray, node_path, target, source_path, transform, custom_meta):
"""
Save a Numpy array to the store.
"""
filehash = self.save_numpy(ndarray)
metahash = self.save_metadata(custom_meta)
self._add_to_package_contents(root, node_path, [f... | Save a Numpy array to the store. |
def output_vlan(gandi, vlan, datacenters, output_keys, justify=10):
""" Helper to output a vlan information."""
output_generic(gandi, vlan, output_keys, justify)
if 'dc' in output_keys:
for dc in datacenters:
if dc['id'] == vlan.get('datacenter_id',
v... | Helper to output a vlan information. |
def get_ttf(self):
""" Given a search path, find file with requested extension """
font_dict = {}
families = []
rootdirlist = string.split(self.search_path, os.pathsep)
#for rootdir in rootdirlist:
# rootdir = os.path.expanduser(rootdir)
for dirName, subdirLis... | Given a search path, find file with requested extension |
def get_max_op_version():
'''
.. versionadded:: 2019.2.0
Returns the glusterfs volume's max op-version value
Requires Glusterfs version > 3.9
CLI Example:
.. code-block:: bash
salt '*' glusterfs.get_max_op_version
'''
if _get_version() < (3, 10,):
return False, 'Gluste... | .. versionadded:: 2019.2.0
Returns the glusterfs volume's max op-version value
Requires Glusterfs version > 3.9
CLI Example:
.. code-block:: bash
salt '*' glusterfs.get_max_op_version |
def initnew(self, fname):
"""
Use the current IDD and create a new empty IDF. If the IDD has not yet
been initialised then this is done first.
Parameters
----------
fname : str, optional
Path to an IDF. This does not need to be set at this point.
"""... | Use the current IDD and create a new empty IDF. If the IDD has not yet
been initialised then this is done first.
Parameters
----------
fname : str, optional
Path to an IDF. This does not need to be set at this point. |
def get_queryset(self, queryset=None):
"""
Returns a queryset for this request.
Arguments:
queryset: Optional root-level queryset.
"""
serializer = self.get_serializer()
return getattr(self, 'queryset', serializer.Meta.model.objects.all()) | Returns a queryset for this request.
Arguments:
queryset: Optional root-level queryset. |
def flush(self):
"""Flush the write buffer of the serial port, blocking until all bytes
are written.
Raises:
SerialError: if an I/O or OS error occurs.
"""
try:
termios.tcdrain(self._fd)
except termios.error as e:
raise SerialError(e.... | Flush the write buffer of the serial port, blocking until all bytes
are written.
Raises:
SerialError: if an I/O or OS error occurs. |
def set_checkbox(self, data, uncheck_other_boxes=True):
"""Set the *checked*-attribute of input elements of type "checkbox"
specified by ``data`` (i.e. check boxes).
:param data: Dict of ``{name: value, ...}``.
In the family of checkboxes whose *name*-attribute is ``name``,
... | Set the *checked*-attribute of input elements of type "checkbox"
specified by ``data`` (i.e. check boxes).
:param data: Dict of ``{name: value, ...}``.
In the family of checkboxes whose *name*-attribute is ``name``,
check the box whose *value*-attribute is ``value``. All boxes i... |
def plot(self, tick_interval=[30, 30], minor_tick_interval=None,
ax=None, ax2=None, colorbar=False, cb_orientation='vertical',
cb_label=None, grid=False, axes_labelsize=None,
tick_labelsize=None, show=True, fname=None, **kwargs):
"""
Plot the raw data using a simpl... | Plot the raw data using a simple cylindrical projection.
Usage
-----
x.plot([tick_interval, minor_tick_interval, ax, ax2, colorbar,
cb_orientation, cb_label, grid, show, fname, **kwargs])
Parameters
----------
tick_interval : list or tuple, optional, def... |
def get_grade_system_query_session_for_gradebook(self, gradebook_id):
"""Gets the ``OsidSession`` associated with the grade system query service for the given gradebook.
arg: gradebook_id (osid.id.Id): the ``Id`` of the gradebook
return: (osid.grading.GradeSystemQuerySession) - ``a
... | Gets the ``OsidSession`` associated with the grade system query service for the given gradebook.
arg: gradebook_id (osid.id.Id): the ``Id`` of the gradebook
return: (osid.grading.GradeSystemQuerySession) - ``a
GradeSystemQuerySession``
raise: NotFound - ``gradebook_id`` not ... |
def get(tag: {str, 'Language'}, normalize=True) -> 'Language':
"""
Create a Language object from a language tag string.
If normalize=True, non-standard or overlong tags will be replaced as
they're interpreted. This is recommended.
Here are several examples of language codes, wh... | Create a Language object from a language tag string.
If normalize=True, non-standard or overlong tags will be replaced as
they're interpreted. This is recommended.
Here are several examples of language codes, which are also test cases.
Most language codes are straightforward, but these... |
def send_discuss_msg_async(self, *, discuss_id, message, auto_escape=False):
"""
发送讨论组消息 (异步版本)
------------
:param int discuss_id: 讨论组 ID(正常情况下看不到,需要从讨论组消息上报的数据中获得)
:param str | list[ dict[ str, unknown ] ] message: 要发送的内容
:param bool auto_escape: 消息内容是否作为纯文本发送(即不解析 CQ... | 发送讨论组消息 (异步版本)
------------
:param int discuss_id: 讨论组 ID(正常情况下看不到,需要从讨论组消息上报的数据中获得)
:param str | list[ dict[ str, unknown ] ] message: 要发送的内容
:param bool auto_escape: 消息内容是否作为纯文本发送(即不解析 CQ 码),`message` 数据类型为 `list` 时无效
:return: None
:rtype: None |
def string_match(self, datastring, findstring, flags=None):
"""
Returns position of findstring in datastring or None if not found.
Flags is a list of strings. Supported strings are:
* "MATCH_CASE": The case has to match for valid find
* "WHOLE_WORD": The word has to be surround... | Returns position of findstring in datastring or None if not found.
Flags is a list of strings. Supported strings are:
* "MATCH_CASE": The case has to match for valid find
* "WHOLE_WORD": The word has to be surrounded by whitespace characters
if in the middle of the str... |
def load_defaults(self):
'''
Loads default extraction rules from the user and system extract.conf files.
Returns None.
'''
# Load the user extract file first to ensure its rules take precedence.
extract_files = [
self.config.settings.user.extract,
... | Loads default extraction rules from the user and system extract.conf files.
Returns None. |
def get_vmware_inventory_path():
"""
Returns VMware inventory file path.
:returns: path to the inventory file
"""
if sys.platform.startswith("win"):
return os.path.expandvars(r"%APPDATA%\Vmware\Inventory.vmls")
elif sys.platform.startswith("darwin"):
... | Returns VMware inventory file path.
:returns: path to the inventory file |
def _normalize(self, name, columns, points):
"""Normalize data for the InfluxDB's data model."""
for i, _ in enumerate(points):
# Supported type:
# https://docs.influxdata.com/influxdb/v1.5/write_protocols/line_protocol_reference/
if points[i] is None:
... | Normalize data for the InfluxDB's data model. |
def id_offset(cls):
"""
Compute an appropriate offset for future id values given the set
of ids currently defined across backends.
"""
max_ids = []
for backend in Store.renderers.keys():
store_ids = Store.custom_options(backend=backend).keys()
max_... | Compute an appropriate offset for future id values given the set
of ids currently defined across backends. |
def sub(self, x, axis):
"""Function to sub 3D View with vector or 2D array (type = numpy.ndarray or 2D Field or 2D View) or 2D View with vector (type = numpy.ndarray)
:param x: array(1D, 2D) or field (2D) or View(2D)
:param axis: specifies axis, eg. axis = (1,2) plane lies in yz-plane, axis=0 ve... | Function to sub 3D View with vector or 2D array (type = numpy.ndarray or 2D Field or 2D View) or 2D View with vector (type = numpy.ndarray)
:param x: array(1D, 2D) or field (2D) or View(2D)
:param axis: specifies axis, eg. axis = (1,2) plane lies in yz-plane, axis=0 vector along x axis
:return: ... |
def eigenvectors_left_samples(self):
r""" Samples of the left eigenvectors of the hidden transition matrix """
res = np.empty((self.nsamples, self.nstates, self.nstates), dtype=config.dtype)
for i in range(self.nsamples):
res[i, :, :] = self._sampled_hmms[i].eigenvectors_left
... | r""" Samples of the left eigenvectors of the hidden transition matrix |
def close(self):
"""
Close the SExtractor file.
"""
if self._file:
if not(self._file.closed):
self._file.close()
self.closed = True | Close the SExtractor file. |
def change_parent(sender, instance, **kwargs):
"""
When the given task instance has changed. Look at task and context and change
the corresponding item relation.
"""
if instance.id is None:
return
if len({'task', 'task_id'} & set(instance.changed_fields)) != 0:
diff = instance.di... | When the given task instance has changed. Look at task and context and change
the corresponding item relation. |
def display_graphic(self, flag_curves, ui):
"""
This function plots results of a file into the canvas.
Inputs : flag_curves : A boolean to know with we have to plot all curves or not.
ui : The main_Window.
"""
ui.graphic_widget.canvas.picture.clear()
x =... | This function plots results of a file into the canvas.
Inputs : flag_curves : A boolean to know with we have to plot all curves or not.
ui : The main_Window. |
def to_dict(self):
""" Convert the Paginator into a dict """
return {
'current': self.current,
'first': self.first,
'last': self.last,
'next': self.more,
'prev': self.prev,
} | Convert the Paginator into a dict |
def GetFileEntryByPathSpec(self, path_spec):
"""Retrieves a file entry for a path specification.
Args:
path_spec (PathSpec): a path specification.
Returns:
APFSContainerFileEntry: a file entry or None if not exists.
"""
volume_index = apfs_helper.APFSContainerPathSpecGetVolumeIndex(pat... | Retrieves a file entry for a path specification.
Args:
path_spec (PathSpec): a path specification.
Returns:
APFSContainerFileEntry: a file entry or None if not exists. |
def union(self, *others: 'Substitution') -> 'Substitution':
"""Try to merge the substitutions.
If a variable occurs in multiple substitutions, try to merge the replacements.
See :meth:`union_with_variable` to see how replacements are merged.
Does not modify any of the original substitu... | Try to merge the substitutions.
If a variable occurs in multiple substitutions, try to merge the replacements.
See :meth:`union_with_variable` to see how replacements are merged.
Does not modify any of the original substitutions.
Example:
>>> subst1 = Substitution({'x': Multi... |
def iso8601_date(d):
"""
Return a string representation of a date that the Twilio API understands
Format is YYYY-MM-DD. Returns None if d is not a string, datetime, or date
"""
if d == values.unset:
return d
elif isinstance(d, datetime.datetime):
return str(d.date())
elif isi... | Return a string representation of a date that the Twilio API understands
Format is YYYY-MM-DD. Returns None if d is not a string, datetime, or date |
def gen_assist_requests(self):
"""Yields: AssistRequest messages to send to the API."""
config = embedded_assistant_pb2.AssistConfig(
audio_in_config=embedded_assistant_pb2.AudioInConfig(
encoding='LINEAR16',
sample_rate_hertz=self.conversation_stream.sample_... | Yields: AssistRequest messages to send to the API. |
def ipython_paste(self,e):
u"""Paste windows clipboard. If enable_ipython_paste_list_of_lists is
True then try to convert tabseparated data to repr of list of lists or
repr of array.
If enable_ipython_paste_for_paths==True then change \\ to / and spaces to \space"""
if sel... | u"""Paste windows clipboard. If enable_ipython_paste_list_of_lists is
True then try to convert tabseparated data to repr of list of lists or
repr of array.
If enable_ipython_paste_for_paths==True then change \\ to / and spaces to \space |
def load_nipy_img(nii_file):
"""Read a Nifti file and return as nipy.Image
Parameters
----------
param nii_file: str
Nifti file path
Returns
-------
nipy.Image
"""
# delayed import because could not install nipy on Python 3 on OSX
import nipy
if not os.path.exists(... | Read a Nifti file and return as nipy.Image
Parameters
----------
param nii_file: str
Nifti file path
Returns
-------
nipy.Image |
def showOverlay(self, ulOverlayHandle):
"""Shows the VR overlay. For dashboard overlays, only the Dashboard Manager is allowed to call this."""
fn = self.function_table.showOverlay
result = fn(ulOverlayHandle)
return result | Shows the VR overlay. For dashboard overlays, only the Dashboard Manager is allowed to call this. |
def get_chempot_correction(element, temp, pres):
"""
Get the normalized correction term Δμ for chemical potential of a gas
phase consisting of element at given temperature and pressure,
referenced to that in the standard state (T_std = 298.15 K,
T_std = 1 bar). The gas phase is l... | Get the normalized correction term Δμ for chemical potential of a gas
phase consisting of element at given temperature and pressure,
referenced to that in the standard state (T_std = 298.15 K,
T_std = 1 bar). The gas phase is limited to be one of O2, N2, Cl2,
F2, H2. Calculation formula ... |
def pack(self, update_timestamp=False, insert_before_payload=""):
"""
Pack this object into a transmittable format
:param update_timestamp:
Should the timestamp be updated to current (default: False)
:type update_timestamp: bool
:param insert_before_payload: Insert t... | Pack this object into a transmittable format
:param update_timestamp:
Should the timestamp be updated to current (default: False)
:type update_timestamp: bool
:param insert_before_payload: Insert this after this data, but before
payload (default: "")
:type insert... |
def _archive_elements(self):
"""
Cloud Formation likes to take the template from S3 so here we put the
template into S3. We also store the parameters file that was used in
this run. Note: you can pass anything as the version string but you
should at least consider a version contr... | Cloud Formation likes to take the template from S3 so here we put the
template into S3. We also store the parameters file that was used in
this run. Note: you can pass anything as the version string but you
should at least consider a version control tag or git commit hash as
the version.... |
def clean(amount):
"""
Converts a number to a number with decimal point.
:param str amount: The input number.
:rtype: str
"""
# Return empty input immediately.
if not amount:
return amount
if re.search(r'[\. ][0-9]{3},[0-9]{1,2}$', amount):
... | Converts a number to a number with decimal point.
:param str amount: The input number.
:rtype: str |
def _check_and_install_rbenv(ret, user=None):
'''
Verify that rbenv is installed, install if unavailable
'''
ret = _check_rbenv(ret, user)
if ret['result'] is False:
if __salt__['rbenv.install'](user):
ret['result'] = True
ret['comment'] = 'Rbenv installed'
el... | Verify that rbenv is installed, install if unavailable |
def run_step(self, rewriter):
"""Do the file in to out rewrite.
Doesn't do anything more crazy than call files_in_to_out on the
rewriter.
Args:
rewriter: pypyr.filesystem.FileRewriter instance.
"""
assert rewriter, ("FileRewriter instance required to run "
... | Do the file in to out rewrite.
Doesn't do anything more crazy than call files_in_to_out on the
rewriter.
Args:
rewriter: pypyr.filesystem.FileRewriter instance. |
def update_state(self, state):
"""
Set the state of the current checklist item. Returns a new ChecklistItem object.
"""
checklistitem_json = self.fetch_json(
uri_path = self.base_uri + '/state',
http_method = 'PUT',
query_params = {'value': 'complete' ... | Set the state of the current checklist item. Returns a new ChecklistItem object. |
async def shuffle(self, state: Optional[bool] = None, *, device: Optional[SomeDevice] = None):
"""shuffle on or off for user’s playback.
Parameters
----------
state : Optional[bool]
if `True` then Shuffle user’s playback.
else if `False` do not shuffle user’s pla... | shuffle on or off for user’s playback.
Parameters
----------
state : Optional[bool]
if `True` then Shuffle user’s playback.
else if `False` do not shuffle user’s playback.
device : Optional[:obj:`SomeDevice`]
The Device object or id of the device this... |
def register_fetcher(self, name, fetcher):
"""Register a fetcher.
:param name: Fetcher name.
:param fetcher: The new fetcher.
"""
assert name not in self.fetchers
self.fetchers[name] = fetcher | Register a fetcher.
:param name: Fetcher name.
:param fetcher: The new fetcher. |
def write_hdf5_series(series, output, path=None, attrs=None, **kwargs):
"""Write a Series to HDF5.
See :func:`write_hdf5_array` for details of arguments and keywords.
"""
if attrs is None:
attrs = format_index_array_attrs(series)
return write_hdf5_array(series, output, path=path, attrs=attr... | Write a Series to HDF5.
See :func:`write_hdf5_array` for details of arguments and keywords. |
def createPregeneratedGraphs():
"""
Creates graphs based on previous runs of the scripts. Useful for editing
graph format for writeups.
"""
# Graph for computeMatchProbabilities(kw=32, nTrials=3000)
listofNValues = [250, 500, 1000, 1500, 2000, 2500]
kw = 32
errors = np.array([
[3.65083333e-03, 3.061... | Creates graphs based on previous runs of the scripts. Useful for editing
graph format for writeups. |
def _find_phrases( self, sentence, syntax_layer, cutPhrases, cutMaxThreshold ):
''' Detects NP phrases by relying on local dependency relations:
1) Identifies potential heads of NP phrases;
2) Identifies consecutive words that can form an NP phrase:
2.1) pote... | Detects NP phrases by relying on local dependency relations:
1) Identifies potential heads of NP phrases;
2) Identifies consecutive words that can form an NP phrase:
2.1) potential attribute + potential head;
2.2) quantity word or phrase + nominal;
... |
def clear_caches(self):
"""Clear all cached data."""
self.get_repository.cache_clear()
self._get_repository.cache_clear()
self.pool.clear_caches() | Clear all cached data. |
def load_urlencoded_body(handler):
"""
Automatically deserialize application/x-www-form-urlencoded bodies
Automatically returns a 400 BAD REQUEST if there is an error while parsing.
Usage::
>>> from lambda_decorators import load_urlencoded_body
>>> @load_urlencoded_body
... def hand... | Automatically deserialize application/x-www-form-urlencoded bodies
Automatically returns a 400 BAD REQUEST if there is an error while parsing.
Usage::
>>> from lambda_decorators import load_urlencoded_body
>>> @load_urlencoded_body
... def handler(event, context):
... return event... |
def _check_status(self):
"""Check repo status and except if dirty."""
logger.info('Checking repo status')
status = self.log_call(
['git', 'status', '--porcelain'],
callwith=subprocess.check_output,
cwd=self.cwd,
)
if status:
raise D... | Check repo status and except if dirty. |
def grant_bonus(self, worker_id, assignment_id, bonus_price, reason):
"""
Issues a payment of money from your account to a Worker. To
be eligible for a bonus, the Worker must have submitted
results for one of your HITs, and have had those results
approved or rejected. This payme... | Issues a payment of money from your account to a Worker. To
be eligible for a bonus, the Worker must have submitted
results for one of your HITs, and have had those results
approved or rejected. This payment happens separately from the
reward you pay to the Worker when you approve the W... |
def write_manifest(self):
"""
Write the file list in 'self.filelist' to the manifest file
named by 'self.manifest'.
"""
self.filelist._repair()
# Now _repairs should encodability, but not unicode
files = [self._manifest_normalize(f) for f in self.filelist.files]
... | Write the file list in 'self.filelist' to the manifest file
named by 'self.manifest'. |
async def _send(self,
request: Request,
content: Dict[Text, Any],
stack: Stack):
"""
Actually proceed to sending the message to the Facebook API.
"""
msg = {
'recipient': {
'id': request.conversation... | Actually proceed to sending the message to the Facebook API. |
def reconstruct_url(self, path_info=None, query_string=None, relative=False):
"""
Reconstructs the request URL using the algorithm provided by PEP3333
"""
environ = self.environ
if relative:
url = ''
else:
url = environ['wsgi.url_scheme'] + '://'
... | Reconstructs the request URL using the algorithm provided by PEP3333 |
def reduce_sum(attrs, inputs, proto_obj):
"""Reduce the array along a given axis by sum value"""
new_attrs = translation_utils._fix_attribute_names(attrs, {'axes':'axis'})
return 'sum', new_attrs, inputs | Reduce the array along a given axis by sum value |
def metadata_path_unset(self):
"""Copy features to memory and remove the association of the metadata file."""
if not self.metadata_file:
raise IOError('No metadata file to unset')
log.debug('{}: reading from metadata file {}'.format(self.id, self.metadata_path))
tmp_sr = Seq... | Copy features to memory and remove the association of the metadata file. |
def get(self, session, words, time='DAY|WEEK|MONTH|3MONTH', aFilter='PV|CLICK|AVGCPC|COMPETITION', nick=None):
'''taobao.simba.insight.wordsbase.get
===================================
词基础数据查询'''
request = TOPRequest('taobao.simba.insight.wordsbase.get')
request['words'] = words
... | taobao.simba.insight.wordsbase.get
===================================
词基础数据查询 |
def percentile(self, percentile):
"""Get a percentile of all floats in the map. Since the sorting is
done in-place, the map is no longer safe to use after calling this
or median()"""
percentile = float(percentile)
if percentile != percentile or percentile < 0 or percentile > 100:... | Get a percentile of all floats in the map. Since the sorting is
done in-place, the map is no longer safe to use after calling this
or median() |
def register_device(self, dev_name):
"""register a device to the device list"""
if dev_name not in self.devices:
self.devices.append(dev_name)
group_name = self.system.__dict__[dev_name]._group
if group_name not in self.group.keys():
self.group[group_name] = {} | register a device to the device list |
def _check_tbit(self, **keys):
"""
Check if one of the columns is a TBIT column
parameters
----------
colnums: integer array, optional
"""
colnums = keys.get('colnums', None)
if colnums is None:
colnums = self._extract_colnums()
has_... | Check if one of the columns is a TBIT column
parameters
----------
colnums: integer array, optional |
def kp_pan_zoom_set(self, viewer, event, data_x, data_y, msg=True):
"""Sets the pan position under the cursor."""
if self.canpan:
reg = 1
with viewer.suppress_redraw:
viewer.panset_xy(data_x, data_y)
scale_x, scale_y = self._save.get((viewer, 'scal... | Sets the pan position under the cursor. |
def parse(number, region=None, keep_raw_input=False,
numobj=None, _check_region=True):
"""Parse a string and return a corresponding PhoneNumber object.
The method is quite lenient and looks for a number in the input text
(raw input) and does not check whether the string is definitely only a
p... | Parse a string and return a corresponding PhoneNumber object.
The method is quite lenient and looks for a number in the input text
(raw input) and does not check whether the string is definitely only a
phone number. To do this, it ignores punctuation and white-space, as
well as any text before the numb... |
def alter_1(self, given_container_name, container_name, meta, val):
"""Get the container_name of the container if a container is specified"""
meta.container = None
if not isinstance(container_name, six.string_types):
meta.container = container_name
container_name = contai... | Get the container_name of the container if a container is specified |
def auth_check(self,
auth_list,
funs,
args,
tgt,
tgt_type='glob',
groups=None,
publish_validate=False,
minions=None,
whitelist=None):
'''
... | Returns a bool which defines if the requested function is authorized.
Used to evaluate the standard structure under external master
authentication interfaces, like eauth, peer, peer_run, etc. |
def _api_key_patch_replace(conn, apiKey, path, value):
'''
the replace patch operation on an ApiKey resource
'''
response = conn.update_api_key(apiKey=apiKey,
patchOperations=[{'op': 'replace', 'path': path, 'value': value}])
return response | the replace patch operation on an ApiKey resource |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.