INSTRUCTION stringlengths 1 46.3k | RESPONSE stringlengths 75 80.2k |
|---|---|
Creates a :class:`~argparse.ArgumentParser` instances to work with VSGSuite classes.
:param kwargs: List of additional keyworded arguments to be passed into the :class:`~argparse.ArgumentParser`.
:return: A :class:`~argparse.ArgumentParser` instance. | def make_parser(cls, **kwargs):
"""
Creates a :class:`~argparse.ArgumentParser` instances to work with VSGSuite classes.
:param kwargs: List of additional keyworded arguments to be passed into the :class:`~argparse.ArgumentParser`.
:return: A :class:`~argparse.ArgumentParser` instance... |
Generates one or more VSGSuite instances from command line arguments.
:param kwargs: List of additional keyworded arguments to be passed into the VSGSuite defined in the :meth:`~VSGSuite.make_parser` method. | def from_args(cls, **kwargs):
"""
Generates one or more VSGSuite instances from command line arguments.
:param kwargs: List of additional keyworded arguments to be passed into the VSGSuite defined in the :meth:`~VSGSuite.make_parser` method.
"""
# Create a VSGSuite for each fil... |
Creates an VSGSuite instance from a filename.
:param str filename: The fully qualified path to the VSG configuration file.
:param str type: The configuration type to generate.
:param kwargs: List of additional keyworded arguments to be passed into the VSGSuite. | def from_directory(cls, directory, type, **kwargs):
"""
Creates an VSGSuite instance from a filename.
:param str filename: The fully qualified path to the VSG configuration file.
:param str type: The configuration type to generate.
:param kwargs: List of additional keyworded ... |
Writes the configuration to disk. | def write(self, parallel=True):
"""
Writes the configuration to disk.
"""
# Write the Solution files
solutions = sorted(self._solutions, key=lambda x: x.Name)
with VSGWriteCommand('Writing VSG Solution', solutions, parallel) as command:
command.execute()
... |
Return a plaintext representation of a bibitem from the ``.bbl`` file.
.. note::
This plaintext representation can be super ugly, contain URLs and so \
on.
.. note::
You need to have ``delatex`` installed system-wide, or to build it in \
this repo, according to the ``... | def bibitem_as_plaintext(bibitem):
"""
Return a plaintext representation of a bibitem from the ``.bbl`` file.
.. note::
This plaintext representation can be super ugly, contain URLs and so \
on.
.. note::
You need to have ``delatex`` installed system-wide, or to build it in \... |
Parse a ``*.bbl`` file to get a clean list of plaintext citations.
:param bbl: Either the path to the .bbl file or the content of a ``.bbl`` \
file.
:returns: A list of cleaned plaintext citations. | def get_plaintext_citations(bbl):
"""
Parse a ``*.bbl`` file to get a clean list of plaintext citations.
:param bbl: Either the path to the .bbl file or the content of a ``.bbl`` \
file.
:returns: A list of cleaned plaintext citations.
"""
# Handle path or content
if os.path.is... |
Get ScaleIO ProtectionDomain object by its name
:param name: Name of ProtectionDomain
:return: ScaleIO ProtectionDomain object
:raise KeyError: No ProtetionDomain with specified name found
:rtype: ProtectionDomain object | def get_pd_by_name(self, name):
"""
Get ScaleIO ProtectionDomain object by its name
:param name: Name of ProtectionDomain
:return: ScaleIO ProtectionDomain object
:raise KeyError: No ProtetionDomain with specified name found
:rtype: ProtectionDomain object
"""
... |
Get ScaleIO ProtectionDomain object by its id
:param name: ID of ProtectionDomain
:return: ScaleIO ProctectionDomain object
:raise KeyError: No ProtectionDomain with specified name found
:rtype: ProtectionDomain object | def get_pd_by_id(self, id):
"""
Get ScaleIO ProtectionDomain object by its id
:param name: ID of ProtectionDomain
:return: ScaleIO ProctectionDomain object
:raise KeyError: No ProtectionDomain with specified name found
:rtype: ProtectionDomain object
"""
f... |
:param pdObj: ID of ProtectionDomain
type: POST
Required:
Protection Domain Object
Return: | def delete_potection_domain(self, pdObj):
"""
:param pdObj: ID of ProtectionDomain
type: POST
Required:
Protection Domain Object
Return:
"""
self.conn.connection._check_login()
response = self.conn.connection._do_post("{}/{}{}/{}".form... |
Split type of a type name with CardinalityField suffix into its parts.
:param type_name: Type name (as string).
:return: Tuple (type_basename, cardinality) | def split_type(cls, type_name):
"""Split type of a type name with CardinalityField suffix into its parts.
:param type_name: Type name (as string).
:return: Tuple (type_basename, cardinality)
"""
if cls.matches_type(type_name):
basename = type_name[:-1]
c... |
Build new type name according to CardinalityField naming scheme.
:param basename: Type basename of primary type (as string).
:param cardinality: Cardinality of the new type (as Cardinality item).
:return: Type name with CardinalityField suffix (if needed) | def make_type(cls, basename, cardinality):
"""Build new type name according to CardinalityField naming scheme.
:param basename: Type basename of primary type (as string).
:param cardinality: Cardinality of the new type (as Cardinality item).
:return: Type name with CardinalityField suf... |
Create type variants for types with a cardinality field.
The new type converters are based on the type converter with
cardinality=1.
.. code-block:: python
import parse
@parse.with_pattern(r'\d+')
def parse_number(text):
return int(text)
... | def create_type_variant(cls, type_name, type_converter):
"""
Create type variants for types with a cardinality field.
The new type converters are based on the type converter with
cardinality=1.
.. code-block:: python
import parse
@parse.with_pattern(r'\... |
Create type variants for types with a cardinality field.
The new type converters are based on the type converter with
cardinality=1.
.. code-block:: python
# -- USE: parse_number() type converter function.
new_types = CardinalityFieldTypeBuilder.create_type_variants(
... | def create_type_variants(cls, type_names, type_dict):
"""
Create type variants for types with a cardinality field.
The new type converters are based on the type converter with
cardinality=1.
.. code-block:: python
# -- USE: parse_number() type converter function.
... |
Create missing type variants for types with a cardinality field.
:param type_names: List of type names with cardinality field suffix.
:param type_dict: Type dictionary with named type converters.
:return: Type dictionary with missing type converter variants. | def create_missing_type_variants(cls, type_names, type_dict):
"""
Create missing type variants for types with a cardinality field.
:param type_names: List of type names with cardinality field suffix.
:param type_dict: Type dictionary with named type converters.
:return: Type di... |
small static method to get logging level
:param str level: string of the level e.g. "INFO"
:returns logging.<LEVEL>: appropriate debug level | def _get_log_level(level):
"""
small static method to get logging level
:param str level: string of the level e.g. "INFO"
:returns logging.<LEVEL>: appropriate debug level
"""
# default to DEBUG
if level is None or level == "DEBUG":
return logging.DEBU... |
Returns a `list` of all the `System` objects to the cluster. Updates every time - no caching.
:return: a `list` of all the `System` objects known to the cluster.
:rtype: list | def system(self):
"""
Returns a `list` of all the `System` objects to the cluster. Updates every time - no caching.
:return: a `list` of all the `System` objects known to the cluster.
:rtype: list
"""
self.connection._check_login()
response = self.connection._do_... |
Returns a `list` of all the `System` objects to the cluster. Updates every time - no caching.
:return: a `list` of all the `System` objects known to the cluster.
:rtype: list | def storage_pools(self):
"""
Returns a `list` of all the `System` objects to the cluster. Updates every time - no caching.
:return: a `list` of all the `System` objects known to the cluster.
:rtype: list
"""
self.connection._check_login()
response = self.connecti... |
Returns a `list` of all the `ScaleIO_SDC` known to the cluster. Updates every time - no caching.
:return: a `list` of all the `ScaleIO_SDC` known to the cluster.
:rtype: list | def sdc(self):
"""
Returns a `list` of all the `ScaleIO_SDC` known to the cluster. Updates every time - no caching.
:return: a `list` of all the `ScaleIO_SDC` known to the cluster.
:rtype: list
"""
self.connection._check_login()
response = self.connection._do_get... |
Returns a `list` of all the `Volume` known to the cluster. Updates every time - no caching.
:return: a `list` of all the `Volume` known to the cluster.
:rtype: list | def volumes(self):
"""
Returns a `list` of all the `Volume` known to the cluster. Updates every time - no caching.
:return: a `list` of all the `Volume` known to the cluster.
:rtype: list
"""
self.connection._check_login()
response = self.connection._do_get("{}/{... |
Returns a `list` of all the `ScaleIO_SDS` known to the cluster. Updates every time - no caching.
:return: a `list` of all the `ScaleIO_SDS` known to the cluster.
:rtype: list | def sds(self):
"""
Returns a `list` of all the `ScaleIO_SDS` known to the cluster. Updates every time - no caching.
:return: a `list` of all the `ScaleIO_SDS` known to the cluster.
:rtype: list
"""
self.connection._check_login()
response = self.connection._do_get... |
Get all Volumes of type Snapshot. Updates every time - no caching.
:return: a `list` of all the `ScaleIO_Volume` that have a are of type Snapshot.
:rtype: list | def snapshots(self):
"""
Get all Volumes of type Snapshot. Updates every time - no caching.
:return: a `list` of all the `ScaleIO_Volume` that have a are of type Snapshot.
:rtype: list
"""
self.connection._check_login()
response = self.connection._do_get("{}/{}".... |
:rtype: list of Protection Domains | def protection_domains(self):
"""
:rtype: list of Protection Domains
"""
self.connection._check_login()
response = self.connection._do_get("{}/{}".format(self.connection._api_url, "types/ProtectionDomain/instances")).json()
all_pds = []
for pd in response:
... |
You can only create and configure Fault Sets before adding SDSs to the system, and configuring them incorrectly
may prevent the creation of volumes. An SDS can only be added to a Fault Set during the creation of the SDS.
:rtype: list of Faultset objects | def fault_sets(self):
"""
You can only create and configure Fault Sets before adding SDSs to the system, and configuring them incorrectly
may prevent the creation of volumes. An SDS can only be added to a Fault Set during the creation of the SDS.
:rtype: list of Faultset objects
... |
Get list of VTrees from ScaleIO cluster
:return: List of VTree objects - Can be empty of no VTrees exist
:rtype: VTree object | def vtrees(self):
"""
Get list of VTrees from ScaleIO cluster
:return: List of VTree objects - Can be empty of no VTrees exist
:rtype: VTree object
"""
self.connection._check_login()
response = self.connection._do_get("{}/{}".format(self.connection._api_url, "type... |
Convenience method to verify if string is an IP addr?
:param ipstr: Stinrg containing IP address
:rtype True if string is a valid IP address | def is_ip_addr(self, ipstr):
"""
Convenience method to verify if string is an IP addr?
:param ipstr: Stinrg containing IP address
:rtype True if string is a valid IP address
"""
ipstr_chunks = ipstr.split('.')
if len(ipstr_chunks) != 4:
return False
... |
Put an ops only if not already there, otherwise it's a no op. | def put_ops(self, key, time, ops):
''' Put an ops only if not already there, otherwise it's a no op.
'''
if self._store.get(key) is None:
self._store[key] = ops |
Returns ops from the key if found otherwise raises a KeyError. | def get_ops(self, key):
''' Returns ops from the key if found otherwise raises a KeyError.
'''
ops = self._store.get(key)
if ops is None:
raise KeyError(
'cannot get operations for {}'.format(key))
return ops |
Parse a local caveat location as generated by LocalThirdPartyCaveat.
This is of the form:
local <version> <pubkey>
where <version> is the bakery version of the client that we're
adding the local caveat for.
It returns None if the location does not represent a local
caveat location.
@... | def _parse_local_location(loc):
'''Parse a local caveat location as generated by LocalThirdPartyCaveat.
This is of the form:
local <version> <pubkey>
where <version> is the bakery version of the client that we're
adding the local caveat for.
It returns None if the location does not repre... |
Add a caveat to the macaroon.
It encrypts it using the given key pair
and by looking up the location using the given locator.
As a special case, if the caveat's Location field has the prefix
"local " the caveat is added as a client self-discharge caveat using
the public key base... | def add_caveat(self, cav, key=None, loc=None):
'''Add a caveat to the macaroon.
It encrypts it using the given key pair
and by looking up the location using the given locator.
As a special case, if the caveat's Location field has the prefix
"local " the caveat is added as a clie... |
Add an array of caveats to the macaroon.
This method does not mutate the current object.
@param cavs arrary of caveats.
@param key the PublicKey to encrypt third party caveat.
@param loc locator to find the location object that has a method
third_party_info. | def add_caveats(self, cavs, key, loc):
'''Add an array of caveats to the macaroon.
This method does not mutate the current object.
@param cavs arrary of caveats.
@param key the PublicKey to encrypt third party caveat.
@param loc locator to find the location object that has a met... |
Return a dict representation of the macaroon data in JSON format.
@return a dict | def to_dict(self):
'''Return a dict representation of the macaroon data in JSON format.
@return a dict
'''
if self.version < VERSION_3:
if len(self._caveat_data) > 0:
raise ValueError('cannot serialize pre-version3 macaroon with '
... |
Return a macaroon obtained from the given dictionary as
deserialized from JSON.
@param json_dict The deserialized JSON object. | def from_dict(cls, json_dict):
'''Return a macaroon obtained from the given dictionary as
deserialized from JSON.
@param json_dict The deserialized JSON object.
'''
json_macaroon = json_dict.get('m')
if json_macaroon is None:
# Try the v1 format if we don't ha... |
Return a macaroon deserialized from a string
@param serialized_json The string to decode {str}
@return {Macaroon} | def deserialize_json(cls, serialized_json):
'''Return a macaroon deserialized from a string
@param serialized_json The string to decode {str}
@return {Macaroon}
'''
serialized = json.loads(serialized_json)
return Macaroon.from_dict(serialized) |
Return a third party caveat id
This does not duplicate any third party caveat ids already inside
macaroon. If base is non-empty, it is used as the id prefix.
@param base bytes
@return bytes | def _new_caveat_id(self, base):
'''Return a third party caveat id
This does not duplicate any third party caveat ids already inside
macaroon. If base is non-empty, it is used as the id prefix.
@param base bytes
@return bytes
'''
id = bytearray()
if len(b... |
Returns a copy of the macaroon. Note that the the new
macaroon's namespace still points to the same underlying Namespace -
copying the macaroon does not make a copy of the namespace.
:return a Macaroon | def copy(self):
''' Returns a copy of the macaroon. Note that the the new
macaroon's namespace still points to the same underlying Namespace -
copying the macaroon does not make a copy of the namespace.
:return a Macaroon
'''
m1 = Macaroon(None, None, version=self._versio... |
Return the hook function (called when the response is received.)
This allows us to intercept the response and do any necessary
macaroon discharge before returning. | def _prepare_discharge_hook(req, client):
''' Return the hook function (called when the response is received.)
This allows us to intercept the response and do any necessary
macaroon discharge before returning.
'''
class Retry:
# Define a local class so that we can use its class variable as
... |
Returns an array of any macaroons found in the given slice of cookies.
If the argument implements a get_header method, that will be used
instead of the get method to retrieve headers.
@param headers_or_request: dict of headers or a
urllib.request.Request-like object.
@return: A list of list of mpy m... | def extract_macaroons(headers_or_request):
''' Returns an array of any macaroons found in the given slice of cookies.
If the argument implements a get_header method, that will be used
instead of the get method to retrieve headers.
@param headers_or_request: dict of headers or a
urllib.request.Reques... |
Set the given field to the given val (bytes) in the serialized
dictionary.
If the value isn't valid utf-8, we base64 encode it and use field+"64"
as the field name. | def _add_json_binary_field(b, serialized, field):
'''' Set the given field to the given val (bytes) in the serialized
dictionary.
If the value isn't valid utf-8, we base64 encode it and use field+"64"
as the field name.
'''
try:
val = b.decode('utf-8')
serialized[field] = val
... |
Returns a macaroon from a legacy wait endpoint. | def _wait_for_macaroon(wait_url):
''' Returns a macaroon from a legacy wait endpoint.
'''
headers = {
BAKERY_PROTOCOL_HEADER: str(bakery.LATEST_VERSION)
}
resp = requests.get(url=wait_url, headers=headers)
if resp.status_code != 200:
raise InteractionError('cannot get {}'.format(... |
Queries a URL as found in an ErrInteractionRequired VisitURL field to
find available interaction methods.
It does this by sending a GET request to the URL with the Accept
header set to "application/json" and parsing the resulting
response as a dict. | def _legacy_get_interaction_methods(u):
''' Queries a URL as found in an ErrInteractionRequired VisitURL field to
find available interaction methods.
It does this by sending a GET request to the URL with the Accept
header set to "application/json" and parsing the resulting
response as a dict.
''... |
Use the requests library to make a request.
Using this method is like doing:
requests.request(method, url, auth=client.auth()) | def request(self, method, url, **kwargs):
'''Use the requests library to make a request.
Using this method is like doing:
requests.request(method, url, auth=client.auth())
'''
# TODO should we raise an exception if auth or cookies are explicitly
# mentioned in kwargs... |
Try to resolve the given error, which should be a response
to the given URL, by discharging any macaroon contained in
it. That is, if error.code is ERR_DISCHARGE_REQUIRED
then it will try to discharge err.info.macaroon. If the discharge
succeeds, the discharged macaroon will be saved to ... | def handle_error(self, error, url):
'''Try to resolve the given error, which should be a response
to the given URL, by discharging any macaroon contained in
it. That is, if error.code is ERR_DISCHARGE_REQUIRED
then it will try to discharge err.info.macaroon. If the discharge
succ... |
Request a discharge macaroon from the caveat location
as an HTTP URL.
@param cav Third party {pymacaroons.Caveat} to be discharged.
@param payload External caveat data {bytes}.
@return The acquired macaroon {macaroonbakery.Macaroon} | def acquire_discharge(self, cav, payload):
''' Request a discharge macaroon from the caveat location
as an HTTP URL.
@param cav Third party {pymacaroons.Caveat} to be discharged.
@param payload External caveat data {bytes}.
@return The acquired macaroon {macaroonbakery.Macaroon}
... |
Gathers a macaroon by directing the user to interact with a
web page. The error_info argument holds the interaction-required
error response.
@return DischargeToken, bakery.Macaroon | def _interact(self, location, error_info, payload):
'''Gathers a macaroon by directing the user to interact with a
web page. The error_info argument holds the interaction-required
error response.
@return DischargeToken, bakery.Macaroon
'''
if (self._interaction_methods is... |
Generates a random secret exponent. | def random_secret_exponent(curve_order):
""" Generates a random secret exponent. """
# run a rejection sampling algorithm to ensure the random int is less
# than the curve order
while True:
# generate a random 256 bit hex string
random_hex = hexlify(dev_urandom_entropy(32))
rando... |
Convert a single BibTeX entry dict to a BibTeX string.
:param data: A dict representing BibTeX entry, as the ones from \
``bibtexparser.BibDatabase.entries`` output.
:return: A formatted BibTeX string. | def dict2bibtex(data):
"""
Convert a single BibTeX entry dict to a BibTeX string.
:param data: A dict representing BibTeX entry, as the ones from \
``bibtexparser.BibDatabase.entries`` output.
:return: A formatted BibTeX string.
"""
bibtex = '@' + data['ENTRYTYPE'] + '{' + data['ID'... |
Create a new BibTeX file.
:param filename: The name of the BibTeX file to write.
:param data: A ``bibtexparser.BibDatabase`` object. | def write(filename, data):
"""
Create a new BibTeX file.
:param filename: The name of the BibTeX file to write.
:param data: A ``bibtexparser.BibDatabase`` object.
"""
with open(filename, 'w') as fh:
fh.write(bibdatabase2bibtex(data)) |
Update an entry in a BibTeX file.
:param filename: The name of the BibTeX file to edit.
:param identifier: The id of the entry to update, in the BibTeX file.
:param data: A dict associating fields and updated values. Fields present \
in the BibTeX file but not in this dict will be kept as is. | def edit(filename, identifier, data):
"""
Update an entry in a BibTeX file.
:param filename: The name of the BibTeX file to edit.
:param identifier: The id of the entry to update, in the BibTeX file.
:param data: A dict associating fields and updated values. Fields present \
in the BibT... |
Delete an entry in a BibTeX file.
:param filename: The name of the BibTeX file to edit.
:param identifier: The id of the entry to delete, in the BibTeX file. | def delete(filename, identifier):
"""
Delete an entry in a BibTeX file.
:param filename: The name of the BibTeX file to edit.
:param identifier: The id of the entry to delete, in the BibTeX file.
"""
# Get current bibtex
with open(filename, 'r') as fh:
bibtex = bibtexparser.load(fh)... |
Get all entries from a BibTeX file.
:param filename: The name of the BibTeX file.
:param ignore_fields: An optional list of fields to strip from the BibTeX \
file.
:returns: A ``bibtexparser.BibDatabase`` object representing the fetched \
entries. | def get(filename, ignore_fields=None):
"""
Get all entries from a BibTeX file.
:param filename: The name of the BibTeX file.
:param ignore_fields: An optional list of fields to strip from the BibTeX \
file.
:returns: A ``bibtexparser.BibDatabase`` object representing the fetched \
... |
Get an entry from a BibTeX file.
.. note ::
Returns the first matching entry.
:param filename: The name of the BibTeX file.
:param filter_function: A function returning ``True`` or ``False`` \
whether the entry should be included or not.
:param ignore_fields: An optional list of f... | def get_entry_by_filter(filename, filter_function, ignore_fields=None):
"""
Get an entry from a BibTeX file.
.. note ::
Returns the first matching entry.
:param filename: The name of the BibTeX file.
:param filter_function: A function returning ``True`` or ``False`` \
whether ... |
Get an entry from a BibTeX file.
:param filename: The name of the BibTeX file.
:param identifier: An id of the entry to fetch, in the BibTeX file.
:param ignore_fields: An optional list of fields to strip from the BibTeX \
file.
:returns: A ``bibtexparser.BibDatabase`` object representing ... | def get_entry(filename, identifier, ignore_fields=None):
"""
Get an entry from a BibTeX file.
:param filename: The name of the BibTeX file.
:param identifier: An id of the entry to fetch, in the BibTeX file.
:param ignore_fields: An optional list of fields to strip from the BibTeX \
fil... |
Convert a bibtex entry to a formatted filename according to a given mask.
.. note ::
Available formatters out of the box are:
- ``journal``
- ``title``
- ``year``
- ``first`` for the first author
- ``last`` for the last author
- ``aut... | def to_filename(data,
mask=DEFAULT_PAPERS_FILENAME_MASK,
extra_formatters=None):
"""
Convert a bibtex entry to a formatted filename according to a given mask.
.. note ::
Available formatters out of the box are:
- ``journal``
- ``title``
... |
Constant-width integer serialization
:param reader:
:param width:
:return: | async def load_uint(reader, width):
"""
Constant-width integer serialization
:param reader:
:param width:
:return:
"""
buffer = _UINT_BUFFER
result = 0
shift = 0
for _ in range(width):
await reader.areadinto(buffer)
result += buffer[0] << shift
shift += 8
... |
Constant-width integer serialization
:param writer:
:param n:
:param width:
:return: | async def dump_uint(writer, n, width):
"""
Constant-width integer serialization
:param writer:
:param n:
:param width:
:return:
"""
buffer = _UINT_BUFFER
for _ in range(width):
buffer[0] = n & 0xff
await writer.awrite(buffer)
n >>= 8 |
Variable int deserialization, synchronous from buffer.
:param buffer:
:return: | def load_uvarint_b(buffer):
"""
Variable int deserialization, synchronous from buffer.
:param buffer:
:return:
"""
result = 0
idx = 0
byte = 0x80
while byte & 0x80:
byte = buffer[idx]
result += (byte & 0x7F) << (7 * idx)
idx += 1
return result |
Serializes n as variable size integer to the provided buffer.
Buffer has to ha
:param n:
:param buffer:
:param offset:
:return: | def dump_uvarint_b_into(n, buffer, offset=0):
"""
Serializes n as variable size integer to the provided buffer.
Buffer has to ha
:param n:
:param buffer:
:param offset:
:return:
"""
shifted = True
while shifted:
shifted = n >> 7
buffer[offset] = (n & 0x7F) | (0x80... |
Loads fixed size integer from the buffer
:param buffer:
:return: | def load_uint_b(buffer, width):
"""
Loads fixed size integer from the buffer
:param buffer:
:return:
"""
result = 0
for idx in range(width):
result += buffer[idx] << (8 * idx)
return result |
Serializes fixed size integer to the buffer
:param n:
:param width:
:return: | def dump_uint_b_into(n, width, buffer, offset=0):
"""
Serializes fixed size integer to the buffer
:param n:
:param width:
:return:
"""
for idx in range(width):
buffer[idx + offset] = n & 0xff
n >>= 8
return buffer |
Bind field to its name in model class. | def bind_name(self, name):
"""Bind field to its name in model class."""
if self.name:
raise errors.Error('Already bound "{0}" with name "{1}" could not '
'be rebound'.format(self, self.name))
self.name = name
self.storage_name = ''.join(('_', se... |
Bind field to model class. | def bind_model_cls(self, model_cls):
"""Bind field to model class."""
if self.model_cls:
raise errors.Error('"{0}" has been already bound to "{1}" and '
'could not be rebound to "{2}"'.format(
self, self.model_cls, model_cls))... |
Init model with field.
:param DomainModel model:
:param object value: | def init_model(self, model, value):
"""Init model with field.
:param DomainModel model:
:param object value:
"""
if value is None and self.default is not None:
value = self.default() if callable(self.default) else self.default
self.set_value(model, value) |
Return field's value.
:param DomainModel model:
:param object default:
:rtype object: | def get_value(self, model, default=None):
"""Return field's value.
:param DomainModel model:
:param object default:
:rtype object:
"""
if default is not None:
default = self._converter(default)
value = getattr(model, self.storage_name)
return... |
Set field's value.
:param DomainModel model:
:param object value: | def set_value(self, model, value):
"""Set field's value.
:param DomainModel model:
:param object value:
"""
if value is None and self.required:
raise AttributeError("This field is required.")
if value is not None:
value = self._converter(value)
... |
Convert raw input value of the field. | def _converter(self, value):
"""Convert raw input value of the field."""
if not isinstance(value, datetime.date):
raise TypeError('{0} is not valid date'.format(value))
return value |
Convert raw input value of the field.
:param object value:
:rtype object: | def _converter(self, value):
"""Convert raw input value of the field.
:param object value:
:rtype object:
"""
if type(value) is not self.related_model_cls.Collection:
value = self.related_model_cls.Collection([
self._get_model_instance(self.related_mo... |
Return built-in type representation of Collection.
:param DomainModel model:
:rtype list: | def get_builtin_type(self, model):
"""Return built-in type representation of Collection.
:param DomainModel model:
:rtype list:
"""
return [item.get_data() if isinstance(item, self.related_model_cls)
else item for item in self.get_value(model)] |
Parse the docstring into its components.
:returns: parsed docstring | def parse(text):
"""
Parse the docstring into its components.
:returns: parsed docstring
"""
ret = Docstring()
if not text:
return ret
text = inspect.cleandoc(text)
match = re.search('^:', text, flags=re.M)
if match:
desc_chunk = text[:match.start()]
meta_ch... |
Copy DocstringMeta from another instance. | def from_meta(cls, meta, meta_all=None):
"""Copy DocstringMeta from another instance."""
if len(meta.args) == 2:
name = meta.args[1]
meta_type = None
for x in meta_all:
if x.args[1] == name and x.args[0] == 'type':
meta_type = x.des... |
Return argument name associated with given param. | def arg_name(self):
"""Return argument name associated with given param."""
if len(self.args) > 2:
return self.args[2]
elif len(self.args) > 1:
return self.args[1]
return None |
Return list of :param meta. | def params(self):
"""Return list of :param meta."""
return [
DocstringParam.from_meta(meta, self.meta)
for meta in self.meta
if meta.args[0] in {
'param', 'parameter', 'arg', 'argument', 'key', 'keyword'
}
] |
Return list of :raises meta. | def raises(self):
"""Return list of :raises meta."""
return [
DocstringRaises.from_meta(meta)
for meta in self.meta
if meta.args[0] in {'raises', 'raise', 'except', 'exception'}
] |
Getter function to retrieve objects from a given object dictionary.
Used mainly to provide get() inside patterns.
:param object_dict: objects, which must have 'name' and 'plugin' as attribute
:type object_dict: dictionary
:param name: name of the object
:type name: str
:param plugin: plugin na... | def gw_get(object_dict, name=None, plugin=None):
"""
Getter function to retrieve objects from a given object dictionary.
Used mainly to provide get() inside patterns.
:param object_dict: objects, which must have 'name' and 'plugin' as attribute
:type object_dict: dictionary
:param name: name o... |
Handles a discharge request as received by the /discharge
endpoint.
@param ctx The context passed to the checker {checkers.AuthContext}
@param content URL and form parameters {dict}
@param locator Locator used to add third party caveats returned by
the checker {macaroonbakery.ThirdPartyLocator}
... | def discharge(ctx, content, key, locator, checker):
'''Handles a discharge request as received by the /discharge
endpoint.
@param ctx The context passed to the checker {checkers.AuthContext}
@param content URL and form parameters {dict}
@param locator Locator used to add third party caveats returned... |
Handle 404 errors returned by the API server | def http_error_handler(f):
"""Handle 404 errors returned by the API server
"""
def hrefs_to_resources(hrefs):
for href in hrefs.replace(',', '').split():
type, uuid = href.split('/')[-2:]
yield Resource(type, uuid=uuid)
def hrefs_list_to_resources(hrefs_list):
f... |
Return URL of the resource
:rtype: str | def href(self):
"""Return URL of the resource
:rtype: str
"""
url = self.session.base_url + str(self.path)
if self.path.is_collection and not self.path.is_root:
return url + 's'
return url |
Add permanent filter on the collection
:param field_name: name of the field to filter on
:type field_name: str
:param field_value: value to filter on
:rtype: Collection | def filter(self, field_name, field_value):
"""Add permanent filter on the collection
:param field_name: name of the field to filter on
:type field_name: str
:param field_value: value to filter on
:rtype: Collection
"""
self.filters.append((field_name, field_valu... |
Fetch collection from API server
:param recursive: level of recursion
:type recursive: int
:param fields: fetch only listed fields.
contrail 3.0 required
:type fields: [str]
:param detail: fetch all fields
:type detail: bool
:param filters:... | def fetch(self, recursive=1, fields=None, detail=None,
filters=None, parent_uuid=None, back_refs_uuid=None):
"""
Fetch collection from API server
:param recursive: level of recursion
:type recursive: int
:param fields: fetch only listed fields.
... |
Check that the resource exists.
:raises ResourceNotFound: if the resource doesn't exists | def check(self):
"""Check that the resource exists.
:raises ResourceNotFound: if the resource doesn't exists
"""
if self.fq_name:
self['uuid'] = self._check_fq_name(self.fq_name)
elif self.uuid:
self['fq_name'] = self._check_uuid(self.uuid)
return... |
Return FQDN of the resource
:rtype: FQName | def fq_name(self):
"""Return FQDN of the resource
:rtype: FQName
"""
return self.get('fq_name', self.get('to', super(Resource, self).fq_name)) |
Return parent resource
:rtype: Resource
:raises ResourceNotFound: parent resource doesn't exists
:raises ResourceMissing: parent resource is not defined | def parent(self):
"""Return parent resource
:rtype: Resource
:raises ResourceNotFound: parent resource doesn't exists
:raises ResourceMissing: parent resource is not defined
"""
try:
return Resource(self['parent_type'], uuid=self['parent_uuid'], check=True)
... |
Set parent resource
:param resource: parent resource
:type resource: Resource
:raises ResourceNotFound: resource not found on the API | def parent(self, resource):
"""Set parent resource
:param resource: parent resource
:type resource: Resource
:raises ResourceNotFound: resource not found on the API
"""
resource.check()
self['parent_type'] = resource.type
self['parent_uuid'] = resource.u... |
Return creation date
:rtype: datetime
:raises ResourceNotFound: resource not found on the API | def created(self):
"""Return creation date
:rtype: datetime
:raises ResourceNotFound: resource not found on the API
"""
if 'id_perms' not in self:
self.fetch()
created = self['id_perms']['created']
return datetime.strptime(created, '%Y-%m-%dT%H:%M:%S.... |
Save the resource to the API server
If the resource doesn't have a uuid the resource will be created.
If uuid is present the resource is updated.
:rtype: Resource | def save(self):
"""Save the resource to the API server
If the resource doesn't have a uuid the resource will be created.
If uuid is present the resource is updated.
:rtype: Resource
"""
if self.path.is_collection:
self.session.post_json(self.href,
... |
Delete resource from the API server | def delete(self):
"""Delete resource from the API server
"""
res = self.session.delete(self.href)
self.emit('deleted', self)
return res |
Fetch resource from the API server
:param recursive: level of recursion for fetching resources
:type recursive: int
:param exclude_children: don't get children references
:type exclude_children: bool
:param exclude_back_refs: don't get back_refs references
:type exclude_... | def fetch(self, recursive=1, exclude_children=False, exclude_back_refs=False):
"""Fetch resource from the API server
:param recursive: level of recursion for fetching resources
:type recursive: int
:param exclude_children: don't get children references
:type exclude_children: bo... |
Populate the resource from a python dict
:param recursive: level of recursion for fetching resources
:type recursive: int | def from_dict(self, data, recursive=1):
"""Populate the resource from a python dict
:param recursive: level of recursion for fetching resources
:type recursive: int
"""
# Find other linked resources
data = self._encode_resource(data, recursive=recursive)
self.dat... |
Remove reference from self to ref
>>> iip = Resource('instance-ip',
uuid='30213cf9-4b03-4afc-b8f9-c9971a216978',
fetch=True)
>>> for vmi in iip['virtual_machine_interface_refs']:
iip.remove_ref(vmi)
>>> iip['virtual_machine_i... | def remove_ref(self, ref):
"""Remove reference from self to ref
>>> iip = Resource('instance-ip',
uuid='30213cf9-4b03-4afc-b8f9-c9971a216978',
fetch=True)
>>> for vmi in iip['virtual_machine_interface_refs']:
iip.remove_ref(v... |
Set reference to resource
Can be used to set references on a resource
that is not already created.
:param ref: reference to add
:type ref: Resource
:rtype: Resource | def set_ref(self, ref, attr=None):
"""Set reference to resource
Can be used to set references on a resource
that is not already created.
:param ref: reference to add
:type ref: Resource
:rtype: Resource
"""
ref_attr = '%s_refs' % ref.type.replace('-', '... |
Add reference to resource
:param ref: reference to add
:type ref: Resource
:rtype: Resource | def add_ref(self, ref, attr=None):
"""Add reference to resource
:param ref: reference to add
:type ref: Resource
:rtype: Resource
"""
self.session.add_ref(self, ref, attr)
return self.fetch() |
Add reference from back_ref to self
:param back_ref: back_ref to add
:type back_ref: Resource
:rtype: Resource | def add_back_ref(self, back_ref, attr=None):
"""Add reference from back_ref to self
:param back_ref: back_ref to add
:type back_ref: Resource
:rtype: Resource
"""
back_ref.add_ref(self, attr)
return self.fetch() |
Search in cache
:param strings: list of strings to get from the cache
:type strings: str list
:param limit: limit search results
:type limit: int
:rtype: [Resource | Collection] | def _search(self, trie, strings, limit=None):
"""Search in cache
:param strings: list of strings to get from the cache
:type strings: str list
:param limit: limit search results
:type limit: int
:rtype: [Resource | Collection]
"""
results = [trie.has_key... |
Registers a new signal.
:param signal: Unique name of the signal
:param plugin: Plugin, which registers the new signal
:param description: Description of the reason or use case, why this signal is needed.
Used for documentation. | def register(self, signal, plugin, description=""):
"""
Registers a new signal.
:param signal: Unique name of the signal
:param plugin: Plugin, which registers the new signal
:param description: Description of the reason or use case, why this signal is needed.
... |
Unregisters an existing signal
:param signal: Name of the signal | def unregister(self, signal):
"""
Unregisters an existing signal
:param signal: Name of the signal
"""
if signal in self.signals.keys():
del(self.signals[signal])
self.__log.debug("Signal %s unregisterd" % signal)
else:
self.__log.debu... |
Connect a receiver to a signal
:param receiver: Name of the receiver
:type receiver: str
:param signal: Name of the signal. Must already be registered!
:type signal: str
:param function: Callable functions, which shall be executed, of signal is send.
:param plugin: The p... | def connect(self, receiver, signal, function, plugin, description="", sender=None):
"""
Connect a receiver to a signal
:param receiver: Name of the receiver
:type receiver: str
:param signal: Name of the signal. Must already be registered!
:type signal: str
:para... |
Disconnect a receiver from a signal.
Signal and receiver must exist, otherwise an exception is thrown.
:param receiver: Name of the receiver | def disconnect(self, receiver):
"""
Disconnect a receiver from a signal.
Signal and receiver must exist, otherwise an exception is thrown.
:param receiver: Name of the receiver
"""
if receiver not in self.receivers.keys():
raise Exception("No receiver %s was ... |
Sends a signal for the given plugin.
:param signal: Name of the signal
:type signal: str
:param plugin: Plugin object, under which the signals where registered
:type plugin: GwBasePattern | def send(self, signal, plugin, **kwargs):
"""
Sends a signal for the given plugin.
:param signal: Name of the signal
:type signal: str
:param plugin: Plugin object, under which the signals where registered
:type plugin: GwBasePattern
"""
if signal not in ... |
Get one or more signals.
:param signal: Name of the signal
:type signal: str
:param plugin: Plugin object, under which the signals where registered
:type plugin: GwBasePattern | def get(self, signal=None, plugin=None):
"""
Get one or more signals.
:param signal: Name of the signal
:type signal: str
:param plugin: Plugin object, under which the signals where registered
:type plugin: GwBasePattern
"""
if plugin is not None:
... |
Get one or more receivers.
:param receiver: Name of the signal
:type receiver: str
:param plugin: Plugin object, under which the signals where registered
:type plugin: GwBasePattern | def get_receiver(self, receiver=None, plugin=None):
"""
Get one or more receivers.
:param receiver: Name of the signal
:type receiver: str
:param plugin: Plugin object, under which the signals where registered
:type plugin: GwBasePattern
"""
if plugin is ... |
Starts the listener with incoming and outgoing queues. | def start(inqueue, outqueue=None):
"""Starts the listener with incoming and outgoing queues."""
conf.init(), db.init(conf.DbPath)
Listener(inqueue, outqueue).run() |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.