code stringlengths 75 104k | docstring stringlengths 1 46.9k |
|---|---|
def parse(file_contents, file_name):
"""
This takes a list of filenames and their paths of expected yaml files and
tried to parse them, erroring if there are any parsing issues.
Args:
file_contents (str): Contents of a yml file
Raises:
yaml.parser.ParserError: Raises an error if th... | This takes a list of filenames and their paths of expected yaml files and
tried to parse them, erroring if there are any parsing issues.
Args:
file_contents (str): Contents of a yml file
Raises:
yaml.parser.ParserError: Raises an error if the file contents cannot be
... |
def validate_owner_repo_package(ctx, param, value):
"""Ensure that owner/repo/package is formatted correctly."""
# pylint: disable=unused-argument
form = "OWNER/REPO/PACKAGE"
return validate_slashes(param, value, minimum=3, maximum=3, form=form) | Ensure that owner/repo/package is formatted correctly. |
def other_object_webhook_handler(event):
"""Handle updates to transfer, charge, invoice, invoiceitem, plan, product and source objects.
Docs for:
- charge: https://stripe.com/docs/api#charges
- coupon: https://stripe.com/docs/api#coupons
- invoice: https://stripe.com/docs/api#invoices
- invoiceitem: https://stri... | Handle updates to transfer, charge, invoice, invoiceitem, plan, product and source objects.
Docs for:
- charge: https://stripe.com/docs/api#charges
- coupon: https://stripe.com/docs/api#coupons
- invoice: https://stripe.com/docs/api#invoices
- invoiceitem: https://stripe.com/docs/api#invoiceitems
- plan: https:/... |
def freeze(self, dest_dir):
"""Freezes every resource within a context"""
for resource in self.resources():
if resource.present:
resource.freeze(dest_dir) | Freezes every resource within a context |
def ungeometrize_stops(geo_stops: DataFrame) -> DataFrame:
"""
The inverse of :func:`geometrize_stops`.
Parameters
----------
geo_stops : GeoPandas GeoDataFrame
Looks like a GTFS stops table, but has a ``'geometry'`` column
of Shapely Point objects that replaces the
``'stop_... | The inverse of :func:`geometrize_stops`.
Parameters
----------
geo_stops : GeoPandas GeoDataFrame
Looks like a GTFS stops table, but has a ``'geometry'`` column
of Shapely Point objects that replaces the
``'stop_lon'`` and ``'stop_lat'`` columns.
Returns
-------
DataFra... |
async def current_position(
self,
mount: top_types.Mount,
critical_point: CriticalPoint = None) -> Dict[Axis, float]:
""" Return the postion (in deck coords) of the critical point of the
specified mount.
This returns cached position to avoid hitting the smoot... | Return the postion (in deck coords) of the critical point of the
specified mount.
This returns cached position to avoid hitting the smoothie driver
unless ``refresh`` is ``True``.
If `critical_point` is specified, that critical point will be applied
instead of the default one. ... |
def update(self, arg, allow_overwrite=False):
"""
Update our providers from either an ICatalog subclass/instance or a mapping.
If arg is an ICatalog, we update from it's ._providers attribute.
:param arg: Di/Catalog/Mapping to update from.
:type arg: ICatalog or collections.Map... | Update our providers from either an ICatalog subclass/instance or a mapping.
If arg is an ICatalog, we update from it's ._providers attribute.
:param arg: Di/Catalog/Mapping to update from.
:type arg: ICatalog or collections.Mapping
:param allow_overwrite: If True, allow overwriting ex... |
def calc_effective_permeability(self, inlets=None, outlets=None,
domain_area=None, domain_length=None):
r"""
This calculates the effective permeability in this linear transport
algorithm.
Parameters
----------
inlets : array_like
... | r"""
This calculates the effective permeability in this linear transport
algorithm.
Parameters
----------
inlets : array_like
The pores where the inlet pressure boundary conditions were
applied. If not given an attempt is made to infer them from the
... |
def _inspect(self,obj,objtype=None):
"""Return the last generated value for this parameter."""
gen=super(Dynamic,self).__get__(obj,objtype)
if hasattr(gen,'_Dynamic_last'):
return gen._Dynamic_last
else:
return gen | Return the last generated value for this parameter. |
def generate_data_for_edit_page(self):
"""
Generate a custom representation of table's fields in dictionary type
if exist edit form else use default representation.
:return: dict
"""
if not self.can_edit:
return {}
if self.edit_form:
ret... | Generate a custom representation of table's fields in dictionary type
if exist edit form else use default representation.
:return: dict |
def get_relationship_mdata():
"""Return default mdata map for Relationship"""
return {
'source': {
'element_label': {
'text': 'source',
'languageTypeId': str(DEFAULT_LANGUAGE_TYPE),
'scriptTypeId': str(DEFAULT_SCRIPT_TYPE),
'for... | Return default mdata map for Relationship |
def create_tx(network, spendables, payables, fee="standard", lock_time=0, version=1):
"""
This function provides the easiest way to create an unsigned transaction.
All coin values are in satoshis.
:param spendables: a list of Spendable objects, which act as inputs.
Each item in the list can be... | This function provides the easiest way to create an unsigned transaction.
All coin values are in satoshis.
:param spendables: a list of Spendable objects, which act as inputs.
Each item in the list can be a Spendable, or text from Spendable.as_text,
or a dictionary from Spendable.as_dict (whic... |
def add(config, username, filename):
"""Add user's SSH public key to their LDAP entry."""
try:
client = Client()
client.prepare_connection()
user_api = UserApi(client)
key_api = API(client)
key_api.add(username, user_api, filename)
exce... | Add user's SSH public key to their LDAP entry. |
def map_hmms(input_model, mapping):
"""Create a new HTK HMM model given a model and a mapping dictionary.
:param input_model: The model to transform of type dict
:param mapping: A dictionary from string -> list(string)
:return: The transformed model of type dict
"""
output_model = copy.copy(in... | Create a new HTK HMM model given a model and a mapping dictionary.
:param input_model: The model to transform of type dict
:param mapping: A dictionary from string -> list(string)
:return: The transformed model of type dict |
def var_window_closed(self, widget):
"""
Called if user clicked close button on var window
:param widget:
:return:
"""
# TODO - Clean up the menu handling stuff its a bit spagetti right now
self.action_group.get_action('vars').set_active(False)
self.show_v... | Called if user clicked close button on var window
:param widget:
:return: |
def addvlan(self, vlanid, vlan_name):
"""
Function operates on the IMCDev object. Takes input of vlanid (1-4094), str of vlan_name,
auth and url to execute the create_dev_vlan method on the IMCDev object. Device must be
supported in the HPE IMC Platform VLAN Manager module.
:para... | Function operates on the IMCDev object. Takes input of vlanid (1-4094), str of vlan_name,
auth and url to execute the create_dev_vlan method on the IMCDev object. Device must be
supported in the HPE IMC Platform VLAN Manager module.
:param vlanid: str of VLANId ( valid 1-4094 )
:param vl... |
def get_regulate_amounts(self):
"""Extract INDRA RegulateAmount Statements from the BioPAX model.
This method extracts IncreaseAmount/DecreaseAmount Statements from
the BioPAX model. It fully reuses BioPAX Pattern's
org.biopax.paxtools.pattern.PatternBox.controlsExpressionWithTemplateRe... | Extract INDRA RegulateAmount Statements from the BioPAX model.
This method extracts IncreaseAmount/DecreaseAmount Statements from
the BioPAX model. It fully reuses BioPAX Pattern's
org.biopax.paxtools.pattern.PatternBox.controlsExpressionWithTemplateReac
pattern to find TemplateReaction... |
def is_full(self):
"""Return whether the activity is full."""
capacity = self.get_true_capacity()
if capacity != -1:
num_signed_up = self.eighthsignup_set.count()
return num_signed_up >= capacity
return False | Return whether the activity is full. |
def _log_likelihood_transit_plus_line(theta, params, model, t, data_flux,
err_flux, priorbounds):
'''
Given a batman TransitModel and its proposed parameters (theta), update the
batman params object with the proposed parameters and evaluate the gaussian
likelihood.
... | Given a batman TransitModel and its proposed parameters (theta), update the
batman params object with the proposed parameters and evaluate the gaussian
likelihood.
Note: the priorbounds are only needed to parse theta. |
def autorg(filename, mininterval=None, qminrg=None, qmaxrg=None, noprint=True):
"""Execute autorg.
Inputs:
filename: either a name of an ascii file, or an instance of Curve.
mininterval: the minimum number of points in the Guinier range
qminrg: the maximum value of qmin*Rg. Default of a... | Execute autorg.
Inputs:
filename: either a name of an ascii file, or an instance of Curve.
mininterval: the minimum number of points in the Guinier range
qminrg: the maximum value of qmin*Rg. Default of autorg is 1.0
qmaxrg: the maximum value of qmax*Rg. Default of autorg is 1.3
... |
def try_unbuffered_file(file, _alreadyopen={}):
""" Try re-opening a file in an unbuffered mode and return it.
If that fails, just return the original file.
This function remembers the file descriptors it opens, so it
never opens the same one twice.
This is meant for files like sys.... | Try re-opening a file in an unbuffered mode and return it.
If that fails, just return the original file.
This function remembers the file descriptors it opens, so it
never opens the same one twice.
This is meant for files like sys.stdout or sys.stderr. |
def scatter(h1: Histogram1D, ax: Axes, *, errors: bool = False, **kwargs):
"""Scatter plot of 1D histogram."""
show_stats = kwargs.pop("show_stats", False)
show_values = kwargs.pop("show_values", False)
density = kwargs.pop("density", False)
cumulative = kwargs.pop("cumulative", False)
value_for... | Scatter plot of 1D histogram. |
def _get_serializer(self, _type):
"""Gets a serializer for a particular type. For primitives, returns the
serializer from the module-level serializers.
For arrays and objects, uses the special _get_T_serializer methods to
build the encoders and decoders.
"""
if _type in _... | Gets a serializer for a particular type. For primitives, returns the
serializer from the module-level serializers.
For arrays and objects, uses the special _get_T_serializer methods to
build the encoders and decoders. |
def must_be_same(self, klass):
"""Called to make sure a Node is a Dir. Since we're an
Entry, we can morph into one."""
if self.__class__ is not klass:
self.__class__ = klass
self._morph()
self.clear() | Called to make sure a Node is a Dir. Since we're an
Entry, we can morph into one. |
def from_pandas(cls, index):
"""Create baloo Index from pandas Index.
Parameters
----------
index : pandas.base.Index
Returns
-------
Index
"""
from pandas import Index as PandasIndex
check_type(index, PandasIndex)
return Index(... | Create baloo Index from pandas Index.
Parameters
----------
index : pandas.base.Index
Returns
-------
Index |
def pay(self, transactionAmount, senderTokenId,
recipientTokenId=None, callerTokenId=None,
chargeFeeTo="Recipient",
callerReference=None, senderReference=None, recipientReference=None,
senderDescription=None, recipientDescription=None,
callerDescription=None, ... | Make a payment transaction. You must specify the amount.
This can also perform a Reserve request if 'reserve' is set to True. |
def format_dates(self, data, columns):
""" This method translates columns values into datetime objects
:param data: original Pandas dataframe
:param columns: list of columns to cast the date to a datetime object
:type data: pandas.DataFrame
:type columns: list of strings
... | This method translates columns values into datetime objects
:param data: original Pandas dataframe
:param columns: list of columns to cast the date to a datetime object
:type data: pandas.DataFrame
:type columns: list of strings
:returns: Pandas dataframe with updated 'columns'... |
def qubits(self):
"""Return a list of qubits as (QuantumRegister, index) pairs."""
return [(v, i) for k, v in self.qregs.items() for i in range(v.size)] | Return a list of qubits as (QuantumRegister, index) pairs. |
def path_valid(self):
"""
Returns
----------
path_valid: (n,) bool, indexes of self.paths self.polygons_closed
which are valid polygons
"""
valid = [i is not None for i in self.polygons_closed]
valid = np.array(valid, dtype=np.bool)
... | Returns
----------
path_valid: (n,) bool, indexes of self.paths self.polygons_closed
which are valid polygons |
def bbox(self):
"""(left, top, right, bottom) tuple."""
if not hasattr(self, '_bbox'):
data = None
for key in ('ARTBOARD_DATA1', 'ARTBOARD_DATA2', 'ARTBOARD_DATA3'):
if key in self.tagged_blocks:
data = self.tagged_blocks.get_data(key)
... | (left, top, right, bottom) tuple. |
def closest_pair(arr, give="indicies"):
"""Find the pair of indices corresponding to the closest elements in an array.
If multiple pairs are equally close, both pairs of indicies are returned.
Optionally returns the closest distance itself.
I am sure that this could be written as a cheaper operation. ... | Find the pair of indices corresponding to the closest elements in an array.
If multiple pairs are equally close, both pairs of indicies are returned.
Optionally returns the closest distance itself.
I am sure that this could be written as a cheaper operation. I
wrote this as a quick and dirty method be... |
def reflect_table(engine, klass):
"""Inspect and reflect objects"""
try:
meta = MetaData()
meta.reflect(bind=engine)
except OperationalError as e:
raise DatabaseError(error=e.orig.args[1], code=e.orig.args[0])
# Try to reflect from any of the supported tables
table = None
... | Inspect and reflect objects |
def read_rows(self, rows, **keys):
"""
Read the specified rows.
parameters
----------
rows: list,array
A list or array of row indices.
vstorage: string, optional
Over-ride the default method to store variable length columns. Can
be 'f... | Read the specified rows.
parameters
----------
rows: list,array
A list or array of row indices.
vstorage: string, optional
Over-ride the default method to store variable length columns. Can
be 'fixed' or 'object'. See docs on fitsio.FITS for details... |
def create_logger():
"""Initial the global logger variable"""
global logger
formatter = logging.Formatter('%(asctime)s|%(levelname)s|%(message)s')
handler = TimedRotatingFileHandler(log_file, when="midnight", interval=1)
handler.setFormatter(formatter)
handler.setLevel(log_level)
handler.su... | Initial the global logger variable |
def _parse_message(self, data):
"""
Parse the message from the device.
:param data: message data
:type data: string
:raises: :py:class:`~alarmdecoder.util.InvalidMessageError`
"""
match = self._regex.match(str(data))
if match is None:
raise ... | Parse the message from the device.
:param data: message data
:type data: string
:raises: :py:class:`~alarmdecoder.util.InvalidMessageError` |
def editor_interfaces(self):
"""
Provides access to editor interface management methods for the given content type.
API reference: https://www.contentful.com/developers/docs/references/content-management-api/#/reference/editor-interface
:return: :class:`ContentTypeEditorInterfacesProxy... | Provides access to editor interface management methods for the given content type.
API reference: https://www.contentful.com/developers/docs/references/content-management-api/#/reference/editor-interface
:return: :class:`ContentTypeEditorInterfacesProxy <contentful_management.content_type_editor_inter... |
def settimeout(self, timeout):
"""
Set the timeout to the websocket.
timeout: timeout time(second).
"""
self.sock_opt.timeout = timeout
if self.sock:
self.sock.settimeout(timeout) | Set the timeout to the websocket.
timeout: timeout time(second). |
def is_equal_to_ignoring_case(self, other):
"""Asserts that val is case-insensitive equal to other."""
if not isinstance(self.val, str_types):
raise TypeError('val is not a string')
if not isinstance(other, str_types):
raise TypeError('given arg must be a string')
... | Asserts that val is case-insensitive equal to other. |
def find_step_impl(self, step):
"""
Find the implementation of the step for the given match string. Returns the StepImpl object
corresponding to the implementation, and the arguments to the step implementation. If no
implementation is found, raises UndefinedStepImpl. If more than one imp... | Find the implementation of the step for the given match string. Returns the StepImpl object
corresponding to the implementation, and the arguments to the step implementation. If no
implementation is found, raises UndefinedStepImpl. If more than one implementation is
found, raises AmbiguousStepIm... |
def padDigitalData(self, dig_data, n):
"""Pad dig_data with its last element so that the new array is a
multiple of n.
"""
n = int(n)
l0 = len(dig_data)
if l0 % n == 0:
return dig_data # no need of padding
else:
ladd = n - (l0 % n)
... | Pad dig_data with its last element so that the new array is a
multiple of n. |
def delete_namespaced_pod_preset(self, name, namespace, **kwargs): # noqa: E501
"""delete_namespaced_pod_preset # noqa: E501
delete a PodPreset # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
... | delete_namespaced_pod_preset # noqa: E501
delete a PodPreset # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.delete_namespaced_pod_preset(name, namespace, async_req=True)
>>... |
def get_output_metadata(self, path, filename):
"""
Describe a file by its metadata.
:return: dict
"""
checksums = get_checksums(path, ['md5'])
metadata = {'filename': filename,
'filesize': os.path.getsize(path),
'checksum': checks... | Describe a file by its metadata.
:return: dict |
def built(name,
runas,
dest_dir,
spec,
sources,
tgt,
template=None,
deps=None,
env=None,
results=None,
force=False,
saltenv='base',
log_dir='/var/log/salt/pkgbuild'):
'''
Ensure that the named... | Ensure that the named package is built and exists in the named directory
name
The name to track the build, the name value is otherwise unused
runas
The user to run the build process as
dest_dir
The directory on the minion to place the built package(s)
spec
The locatio... |
async def create(
cls, interface: Interface, mode: LinkMode,
subnet: Union[Subnet, int] = None, ip_address: str = None,
force: bool = False, default_gateway: bool = False):
"""
Create a link on `Interface` in MAAS.
:param interface: Interface to create the li... | Create a link on `Interface` in MAAS.
:param interface: Interface to create the link on.
:type interface: `Interface`
:param mode: Mode of the link.
:type mode: `LinkMode`
:param subnet: The subnet to create the link on (optional).
:type subnet: `Subnet` or `int`
... |
def _build(self, x, prev_state):
"""Connects the core to the graph.
Args:
x: Input `Tensor` of shape `(batch_size, input_size)`.
prev_state: Previous state. This could be a `Tensor`, or a tuple of
`Tensor`s.
Returns:
The tuple `(output, state)` for this core.
Raises:
... | Connects the core to the graph.
Args:
x: Input `Tensor` of shape `(batch_size, input_size)`.
prev_state: Previous state. This could be a `Tensor`, or a tuple of
`Tensor`s.
Returns:
The tuple `(output, state)` for this core.
Raises:
ValueError: if the `Tensor` `x` does no... |
def get_full_xml_representation(entity, private_key):
"""Get full XML representation of an entity.
This contains the <XML><post>..</post></XML> wrapper.
Accepts either a Base entity or a Diaspora entity.
Author `private_key` must be given so that certain entities can be signed.
"""
from feder... | Get full XML representation of an entity.
This contains the <XML><post>..</post></XML> wrapper.
Accepts either a Base entity or a Diaspora entity.
Author `private_key` must be given so that certain entities can be signed. |
def glob(patterns, parent=None, excludes=None, include_dotfiles=False,
ignore_false_excludes=False):
"""
Wrapper for #glob2.glob() that accepts an arbitrary number of
patterns and matches them. The paths are normalized with #norm().
Relative patterns are automaticlly joined with *parent*. If the
par... | Wrapper for #glob2.glob() that accepts an arbitrary number of
patterns and matches them. The paths are normalized with #norm().
Relative patterns are automaticlly joined with *parent*. If the
parameter is omitted, it defaults to the current working directory.
If *excludes* is specified, it must be a string or... |
def convertnumbers(table, strict=False, **kwargs):
"""
Convenience function to convert all field values to numbers where
possible. E.g.::
>>> import petl as etl
>>> table1 = [['foo', 'bar', 'baz', 'quux'],
... ['1', '3.0', '9+3j', 'aaa'],
... ['2', '1.3',... | Convenience function to convert all field values to numbers where
possible. E.g.::
>>> import petl as etl
>>> table1 = [['foo', 'bar', 'baz', 'quux'],
... ['1', '3.0', '9+3j', 'aaa'],
... ['2', '1.3', '7+2j', None]]
>>> table2 = etl.convertnumbers(table1)... |
def create_image_lists(image_dir, testing_percentage, validation_percentage):
"""Builds a list of training images from the file system.
Analyzes the sub folders in the image directory, splits them into stable
training, testing, and validation sets, and returns a data structure
describing the lists of images fo... | Builds a list of training images from the file system.
Analyzes the sub folders in the image directory, splits them into stable
training, testing, and validation sets, and returns a data structure
describing the lists of images for each label and their paths.
Args:
image_dir: String path to a folder conta... |
def textFileStream(self, directory):
"""
Create an input stream that monitors a Hadoop-compatible file system
for new files and reads them as text files. Files must be wrriten to the
monitored directory by "moving" them from another location within the same
file system. File name... | Create an input stream that monitors a Hadoop-compatible file system
for new files and reads them as text files. Files must be wrriten to the
monitored directory by "moving" them from another location within the same
file system. File names starting with . are ignored.
The text files mus... |
def coord(self, offset=(0,0)):
'''return lat,lon within a tile given (offsetx,offsety)'''
(tilex, tiley) = self.tile
(offsetx, offsety) = offset
world_tiles = 1<<self.zoom
x = ( tilex + 1.0*offsetx/TILES_WIDTH ) / (world_tiles/2.) - 1
y = ( tiley + 1.0*offsety/TILES_HEIGHT) / (world_tiles/2.) - 1
lon = x ... | return lat,lon within a tile given (offsetx,offsety) |
def dict(self):
"""
the python object for rendering json.
It is called dict to be
coherent with the other modules but it actually returns a list
:return: the python object for rendering json
:rtype: list
"""
json_list = []
for step in self.steps... | the python object for rendering json.
It is called dict to be
coherent with the other modules but it actually returns a list
:return: the python object for rendering json
:rtype: list |
def visit_set(self, node):
"""return an astroid.Set node as string"""
return "{%s}" % ", ".join(child.accept(self) for child in node.elts) | return an astroid.Set node as string |
def get_institute_graph_url(start, end):
""" Pie chart comparing institutes usage. """
filename = get_institute_graph_filename(start, end)
urls = {
'graph_url': urlparse.urljoin(GRAPH_URL, filename + ".png"),
'data_url': urlparse.urljoin(GRAPH_URL, filename + ".csv"),
}
return urls | Pie chart comparing institutes usage. |
def ppo_original_world_model():
"""Atari parameters with world model as policy."""
hparams = ppo_original_params()
hparams.policy_network = "next_frame_basic_deterministic"
hparams_keys = hparams.values().keys()
video_hparams = basic_deterministic_params.next_frame_basic_deterministic()
for (name, value) in... | Atari parameters with world model as policy. |
def ConfigureViewTypeChoices( self, event=None ):
"""Configure the set of View types in the toolbar (and menus)"""
self.viewTypeTool.SetItems( getattr( self.loader, 'ROOTS', [] ))
if self.loader and self.viewType in self.loader.ROOTS:
self.viewTypeTool.SetSelection( self.loader.ROOTS... | Configure the set of View types in the toolbar (and menus) |
def _log(self, s):
r"""Log a string. It flushes but doesn't append \n, so do that yourself."""
# TODO(tewalds): Should this be using logging.info instead? How to see them
# outside of google infrastructure?
sys.stderr.write(s)
sys.stderr.flush() | r"""Log a string. It flushes but doesn't append \n, so do that yourself. |
def show(parent=None, targets=[], modal=None, auto_publish=False, auto_validate=False):
"""Attempt to show GUI
Requires install() to have been run first, and
a live instance of Pyblish QML in the background.
Arguments:
parent (None, optional): Deprecated
targets (list, optional): Publi... | Attempt to show GUI
Requires install() to have been run first, and
a live instance of Pyblish QML in the background.
Arguments:
parent (None, optional): Deprecated
targets (list, optional): Publishing targets
modal (bool, optional): Block interactions to parent |
def storage_set(self, key, value):
"""
Store a value for the module.
"""
if not self._module:
return
self._storage_init()
module_name = self._module.module_full_name
return self._storage.storage_set(module_name, key, value) | Store a value for the module. |
def set_iscsi_volume(self, port_id,
initiator_iqn, initiator_dhcp=False,
initiator_ip=None, initiator_netmask=None,
target_dhcp=False, target_iqn=None, target_ip=None,
target_port=3260, target_lun=0, boot_prio=1,
... | Set iSCSI volume information to configuration.
:param port_id: Physical port ID.
:param initiator_iqn: IQN of initiator.
:param initiator_dhcp: True if DHCP is used in the iSCSI network.
:param initiator_ip: IP address of initiator. None if DHCP is used.
:param initiator_netmask... |
def logical_downlinks(self):
"""
Gets the LogicalDownlinks API client.
Returns:
LogicalDownlinks:
"""
if not self.__logical_downlinks:
self.__logical_downlinks = LogicalDownlinks(
self.__connection)
return self.__logical_downlinks | Gets the LogicalDownlinks API client.
Returns:
LogicalDownlinks: |
def mod_repo(repo, saltenv='base', **kwargs):
'''
Modify one or more values for a repo. If the repo does not exist, it will
be created, so long as the definition is well formed. For Ubuntu the
``ppa:<project>/repo`` format is acceptable. ``ppa:`` format can only be
used to create a new repository.... | Modify one or more values for a repo. If the repo does not exist, it will
be created, so long as the definition is well formed. For Ubuntu the
``ppa:<project>/repo`` format is acceptable. ``ppa:`` format can only be
used to create a new repository.
The following options are available to modify a repo... |
def remove(self, key, where=None, start=None, stop=None):
"""
Remove pandas object partially by specifying the where condition
Parameters
----------
key : string
Node to remove or delete rows from
where : list of Term (or convertible) objects, optional
... | Remove pandas object partially by specifying the where condition
Parameters
----------
key : string
Node to remove or delete rows from
where : list of Term (or convertible) objects, optional
start : integer (defaults to None), row number to start selection
st... |
def vtableEqual(a, objectStart, b):
"""vtableEqual compares an unwritten vtable to a written vtable."""
N.enforce_number(objectStart, N.UOffsetTFlags)
if len(a) * N.VOffsetTFlags.bytewidth != len(b):
return False
for i, elem in enumerate(a):
x = encode.Get(packer.voffset, b, i * N.VOf... | vtableEqual compares an unwritten vtable to a written vtable. |
def convert_units(values, source_measure_or_unit_abbreviation, target_measure_or_unit_abbreviation,**kwargs):
"""
Convert a value from one unit to another one.
Example::
>>> cli = PluginLib.connect()
>>> cli.service.convert_units(20.0, 'm', 'km')
0.02
Pa... | Convert a value from one unit to another one.
Example::
>>> cli = PluginLib.connect()
>>> cli.service.convert_units(20.0, 'm', 'km')
0.02
Parameters:
values: single measure or an array of measures
source_measure_or_unit_abbreviation: A measur... |
def exists(self):
""" Check whether the directory exists on the camera. """
if self.name in ("", "/") and self.parent is None:
return True
else:
return self in self.parent.directories | Check whether the directory exists on the camera. |
def clean(self, list_article_candidates):
"""Iterates over each article_candidate and cleans every extracted data.
:param list_article_candidates: A list, the list of ArticleCandidate-Objects which have been extracted
:return: A list, the list with the cleaned ArticleCandidate-Objects
"... | Iterates over each article_candidate and cleans every extracted data.
:param list_article_candidates: A list, the list of ArticleCandidate-Objects which have been extracted
:return: A list, the list with the cleaned ArticleCandidate-Objects |
def face_subset(self, face_index):
"""
Given a mask of face indices, return a sliced version.
Parameters
----------
face_index: (n,) int, mask for faces
(n,) bool, mask for faces
Returns
----------
visual: ColorVisuals object containi... | Given a mask of face indices, return a sliced version.
Parameters
----------
face_index: (n,) int, mask for faces
(n,) bool, mask for faces
Returns
----------
visual: ColorVisuals object containing a subset of faces. |
def _register_options(self, api_interface):
# type: (ApiInterfaceBase) -> None
"""
Register CORS options endpoints.
"""
op_paths = api_interface.op_paths(collate_methods=True)
for path, operations in op_paths.items():
if api.Method.OPTIONS not in operations:
... | Register CORS options endpoints. |
def encode_schedule(schedule):
"""Encodes a schedule tuple into a string.
Args:
schedule: A tuple containing (interpolation, steps, pmfs), where
interpolation is a string specifying the interpolation strategy, steps
is an int array_like of shape [N] specifying the global steps, and pmfs is
an... | Encodes a schedule tuple into a string.
Args:
schedule: A tuple containing (interpolation, steps, pmfs), where
interpolation is a string specifying the interpolation strategy, steps
is an int array_like of shape [N] specifying the global steps, and pmfs is
an array_like of shape [N, M] where pm... |
def create(cls, name, servers=None, time_range='yesterday', all_logs=False,
filter_for_delete=None, comment=None, **kwargs):
"""
Create a new delete log task. Provide True to all_logs to delete
all log types. Otherwise provide kwargs to specify each log by
type of interest... | Create a new delete log task. Provide True to all_logs to delete
all log types. Otherwise provide kwargs to specify each log by
type of interest.
:param str name: name for this task
:param servers: servers to back up. Servers must be instances of
management servers o... |
def _fill_cropping(self, image_size, view_size):
"""
Return a (left, top, right, bottom) 4-tuple containing the cropping
values required to display an image of *image_size* in *view_size*
when stretched proportionately. Each value is a percentage expressed
as a fraction of 1.0, e... | Return a (left, top, right, bottom) 4-tuple containing the cropping
values required to display an image of *image_size* in *view_size*
when stretched proportionately. Each value is a percentage expressed
as a fraction of 1.0, e.g. 0.425 represents 42.5%. *image_size* and
*view_size* are ... |
def editpermissions_user_view(self, request, user_id, forum_id=None):
""" Allows to edit user permissions for the considered forum.
The view displays a form to define which permissions are granted for the given user for the
considered forum.
"""
user_model = get_user_model()
... | Allows to edit user permissions for the considered forum.
The view displays a form to define which permissions are granted for the given user for the
considered forum. |
def article(request, slug):
"""
The main view of the Django-CMS Articles! Takes a request and a slug,
renders the article.
"""
# Get current CMS Page as article tree
tree = request.current_page.get_public_object()
# Check whether it really is a tree.
# It could also be one of its sub-pa... | The main view of the Django-CMS Articles! Takes a request and a slug,
renders the article. |
def recall(self, label=None):
"""
Returns recall or recall for a given label (category) if specified.
"""
if label is None:
return self.call("recall")
else:
return self.call("recall", float(label)) | Returns recall or recall for a given label (category) if specified. |
def estimate_tx_gas_with_safe(self, safe_address: str, to: str, value: int, data: bytes, operation: int,
block_identifier='pending') -> int:
"""
Estimate tx gas using safe `requiredTxGas` method
:return: int: Estimated gas
:raises: CannotEstimateGas: If ... | Estimate tx gas using safe `requiredTxGas` method
:return: int: Estimated gas
:raises: CannotEstimateGas: If gas cannot be estimated
:raises: ValueError: Cannot decode received data |
def decode(self,
dataset_split=None,
decode_from_file=False,
checkpoint_path=None):
"""Decodes from dataset or file."""
if decode_from_file:
decoding.decode_from_file(self._estimator,
self._decode_hparams.decode_from_file,
... | Decodes from dataset or file. |
def dispose(json_str):
"""Clear all comments in json_str.
Clear JS-style comments like // and /**/ in json_str.
Accept a str or unicode as input.
Args:
json_str: A json string of str or unicode to clean up comment
Returns:
str: The str without comments (or unicode if you pass in u... | Clear all comments in json_str.
Clear JS-style comments like // and /**/ in json_str.
Accept a str or unicode as input.
Args:
json_str: A json string of str or unicode to clean up comment
Returns:
str: The str without comments (or unicode if you pass in unicode) |
def get_best_span(span_start_logits: torch.Tensor, span_end_logits: torch.Tensor) -> torch.Tensor:
"""
This acts the same as the static method ``BidirectionalAttentionFlow.get_best_span()``
in ``allennlp/models/reading_comprehension/bidaf.py``. We keep it here so that users can
directly import this func... | This acts the same as the static method ``BidirectionalAttentionFlow.get_best_span()``
in ``allennlp/models/reading_comprehension/bidaf.py``. We keep it here so that users can
directly import this function without the class.
We call the inputs "logits" - they could either be unnormalized logits or normaliz... |
def validateElement(self, ctxt, elem):
"""Try to validate the subtree under an element """
if ctxt is None: ctxt__o = None
else: ctxt__o = ctxt._o
if elem is None: elem__o = None
else: elem__o = elem._o
ret = libxml2mod.xmlValidateElement(ctxt__o, self._o, elem__o)
... | Try to validate the subtree under an element |
async def create(gc: GroupControl, name, slaves):
"""Create new group"""
click.echo("Creating group %s with slaves: %s" % (name, slaves))
click.echo(await gc.create(name, slaves)) | Create new group |
def main(argv=sys.argv, stream=sys.stderr):
"""Entry point for ``tappy`` command."""
args = parse_args(argv)
suite = build_suite(args)
runner = unittest.TextTestRunner(verbosity=args.verbose, stream=stream)
result = runner.run(suite)
return get_status(result) | Entry point for ``tappy`` command. |
def find_next_candidate(self):
"""
Returns the next candidate Node for (potential) evaluation.
The candidate list (really a stack) initially consists of all of
the top-level (command line) targets provided when the Taskmaster
was initialized. While we walk the DAG, visiting Nod... | Returns the next candidate Node for (potential) evaluation.
The candidate list (really a stack) initially consists of all of
the top-level (command line) targets provided when the Taskmaster
was initialized. While we walk the DAG, visiting Nodes, all the
children that haven't finished ... |
def reflect_filter(sources, model, cache=None):
'''Returns the list of reflections of objects in the `source` list to other
class. Objects that are not found in target table are silently discarded.
'''
targets = [reflect(source, model, cache=cache) for source in sources]
# Some objects may not be av... | Returns the list of reflections of objects in the `source` list to other
class. Objects that are not found in target table are silently discarded. |
def upload_headimg(self, account, media_file):
"""
上传客服账号头像
详情请参考
http://mp.weixin.qq.com/wiki/1/70a29afed17f56d537c833f89be979c9.html
:param account: 完整客服账号
:param media_file: 要上传的头像文件,一个 File-Object
:return: 返回的 JSON 数据包
"""
return self._post(
... | 上传客服账号头像
详情请参考
http://mp.weixin.qq.com/wiki/1/70a29afed17f56d537c833f89be979c9.html
:param account: 完整客服账号
:param media_file: 要上传的头像文件,一个 File-Object
:return: 返回的 JSON 数据包 |
def replicate_global_dbs(cloud_url=None, local_url=None):
"""
Set up replication of the global databases from the cloud server to the
local server.
:param str cloud_url: Used to override the cloud url from the global
configuration in case the calling function is in the process of
initializing t... | Set up replication of the global databases from the cloud server to the
local server.
:param str cloud_url: Used to override the cloud url from the global
configuration in case the calling function is in the process of
initializing the cloud server
:param str local_url: Used to override the local u... |
def frozen_stats_from_tree(tree):
"""Restores a statistics from the given flat members tree.
:func:`make_frozen_stats_tree` makes a tree for this function.
"""
if not tree:
raise ValueError('Empty tree')
stats_index = []
for parent_offset, members in tree:
stats = FrozenStatistic... | Restores a statistics from the given flat members tree.
:func:`make_frozen_stats_tree` makes a tree for this function. |
def lock(self, session, lock_type, timeout, requested_key=None):
"""Establishes an access mode to the specified resources.
Corresponds to viLock function of the VISA library.
:param session: Unique logical identifier to a session.
:param lock_type: Specifies the type of lock requested,... | Establishes an access mode to the specified resources.
Corresponds to viLock function of the VISA library.
:param session: Unique logical identifier to a session.
:param lock_type: Specifies the type of lock requested, either Constants.EXCLUSIVE_LOCK or Constants.SHARED_LOCK.
:param ti... |
def to_phalf_from_pfull(arr, val_toa=0, val_sfc=0):
"""Compute data at half pressure levels from values at full levels.
Could be the pressure array itself, but it could also be any other data
defined at pressure levels. Requires specification of values at surface
and top of atmosphere.
"""
pha... | Compute data at half pressure levels from values at full levels.
Could be the pressure array itself, but it could also be any other data
defined at pressure levels. Requires specification of values at surface
and top of atmosphere. |
def list_running_zones(self):
"""
Returns the currently active relay.
:returns: Returns the running relay number or None if no relays are
active.
:rtype: string
"""
self.update_controller_info()
if self.running is None or not self.running:
... | Returns the currently active relay.
:returns: Returns the running relay number or None if no relays are
active.
:rtype: string |
def editors(self, value):
"""Update editors.
DEPRECATED: use ``policy["roles/editors"] = value`` instead."""
warnings.warn(
_ASSIGNMENT_DEPRECATED_MSG.format("editors", EDITOR_ROLE),
DeprecationWarning,
)
self[EDITOR_ROLE] = value | Update editors.
DEPRECATED: use ``policy["roles/editors"] = value`` instead. |
def unnest(c, elem, ignore_whitespace=False):
"""unnest the element from its parent within doc. MUTABLE CHANGES"""
parent = elem.getparent()
gparent = parent.getparent()
index = parent.index(elem)
# put everything up to elem into a new parent element right before the current... | unnest the element from its parent within doc. MUTABLE CHANGES |
def create_venv_with_package(packages):
"""Create a venv with these packages in a temp dir and yielf the env.
packages should be an iterable of pip version instructio (e.g. package~=1.2.3)
"""
with tempfile.TemporaryDirectory() as tempdir:
myenv = create(tempdir, with_pip=True)
pip_call... | Create a venv with these packages in a temp dir and yielf the env.
packages should be an iterable of pip version instructio (e.g. package~=1.2.3) |
def _get_parent(root):
"""Returns root element for a list.
:Args:
root (Element): lxml element of current location
:Returns:
lxml element representing list
"""
elem = root
while True:
elem = elem.getparent()
if elem.tag in ['ul', 'ol']:
return e... | Returns root element for a list.
:Args:
root (Element): lxml element of current location
:Returns:
lxml element representing list |
def _encrypt(self, dec, password=None):
"""
Internal encryption function
Uses either the password argument for the encryption,
or, if not supplied, the password field of the object
:param dec: a byte string representing the to be encrypted data
:rtype: bytes
"""... | Internal encryption function
Uses either the password argument for the encryption,
or, if not supplied, the password field of the object
:param dec: a byte string representing the to be encrypted data
:rtype: bytes |
def _rdumpq(q,size,value,encoding=None):
"""Dump value as a tnetstring, to a deque instance, last chunks first.
This function generates the tnetstring representation of the given value,
pushing chunks of the output onto the given deque instance. It pushes
the last chunk first, then recursively generat... | Dump value as a tnetstring, to a deque instance, last chunks first.
This function generates the tnetstring representation of the given value,
pushing chunks of the output onto the given deque instance. It pushes
the last chunk first, then recursively generates more chunks.
When passed in the current ... |
def get_channel_groups(self, channel_ids):
'''This function returns the group of each channel specifed by
channel_ids
Parameters
----------
channel_ids: array_like
The channel ids (ints) for which the groups will be returned
Returns
----------
... | This function returns the group of each channel specifed by
channel_ids
Parameters
----------
channel_ids: array_like
The channel ids (ints) for which the groups will be returned
Returns
----------
groups: array_like
Returns a list of cor... |
def has_descriptor(self, descriptor):
"""
Return ``True`` if the character has the given descriptor.
:param IPADescriptor descriptor: the descriptor to be checked against
:rtype: bool
"""
for p in self.descriptors:
if p in descriptor:
return T... | Return ``True`` if the character has the given descriptor.
:param IPADescriptor descriptor: the descriptor to be checked against
:rtype: bool |
def makeFrequencyPanel(allFreqs, patientName):
"""
For a title, make a graph showing the frequencies.
@param allFreqs: result from getCompleteFreqs
@param patientName: A C{str}, title for the panel
"""
titles = sorted(
iter(allFreqs.keys()),
key=lambda title: (allFreqs[title]['b... | For a title, make a graph showing the frequencies.
@param allFreqs: result from getCompleteFreqs
@param patientName: A C{str}, title for the panel |
def find_service_by_type(self, service_type):
"""
Get service for a given service type.
:param service_type: Service type, ServiceType
:return: Service
"""
for service in self._services:
if service_type == service.type:
return service
... | Get service for a given service type.
:param service_type: Service type, ServiceType
:return: Service |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.