sentence1 stringlengths 52 3.87M | sentence2 stringlengths 1 47.2k | label stringclasses 1
value |
|---|---|---|
def serialize(self, obj, fields):
"""
Serializes a single model instance to a Python dict, based on the specified list of fields.
"""
data = {}
remaining_fields = []
for field in fields:
if callable(field): # Callable
data[field.__name__] = f... | Serializes a single model instance to a Python dict, based on the specified list of fields. | entailment |
def json_dumps(self, data, **options):
"""
Wrapper around `json.dumps` that uses a special JSON encoder.
"""
params = {'sort_keys': True, 'indent': 2}
params.update(options)
# This code is based off django's built in JSON serializer
if json.__version__.split('.') ... | Wrapper around `json.dumps` that uses a special JSON encoder. | entailment |
def dir(cls, label, children):
"""Return ``FSEntry`` directory object."""
return FSEntry(label=label, children=children, type=u"Directory", use=None) | Return ``FSEntry`` directory object. | entailment |
def from_fptr(cls, label, type_, fptr):
"""Return ``FSEntry`` object."""
return FSEntry(
label=label,
type=type_,
path=fptr.path,
use=fptr.use,
file_uuid=fptr.file_uuid,
derived_from=fptr.derived_from,
checksum=fptr.chec... | Return ``FSEntry`` object. | entailment |
def file_id(self):
""" Returns the fptr @FILEID if this is not a Directory. """
if self.type.lower() == "directory":
return None
if self.file_uuid is None:
raise exceptions.MetsError(
"No FILEID: File %s does not have file_uuid set" % self.path
... | Returns the fptr @FILEID if this is not a Directory. | entailment |
def group_id(self):
"""
Returns the @GROUPID.
If derived_from is set, returns that group_id.
"""
if self.derived_from is not None:
return self.derived_from.group_id()
if self.file_uuid is None:
return None
return utils.GROUP_ID_PREFIX + se... | Returns the @GROUPID.
If derived_from is set, returns that group_id. | entailment |
def _add_metadata_element(self, md, subsection, mdtype, mode="mdwrap", **kwargs):
"""
:param md: Value to pass to the MDWrap/MDRef
:param str subsection: Metadata tag to create. See :const:`SubSection.ALLOWED_SUBSECTIONS`
:param str mdtype: Value for mdWrap/mdRef @MDTYPE
:param ... | :param md: Value to pass to the MDWrap/MDRef
:param str subsection: Metadata tag to create. See :const:`SubSection.ALLOWED_SUBSECTIONS`
:param str mdtype: Value for mdWrap/mdRef @MDTYPE
:param str mode: 'mdwrap' or 'mdref'
:param str loctype: Required if mode is 'mdref'. LOCTYPE of a md... | entailment |
def serialize_md_inst(self, md_inst, md_class):
"""Serialize object ``md_inst`` by transforming it into an
``lxml.etree._ElementTree``. If it already is such, return it. If not,
make sure it is the correct type and return the output of calling
``seriaize()`` on it.
"""
va... | Serialize object ``md_inst`` by transforming it into an
``lxml.etree._ElementTree``. If it already is such, return it. If not,
make sure it is the correct type and return the output of calling
``seriaize()`` on it. | entailment |
def add_child(self, child):
"""Add a child FSEntry to this FSEntry.
Only FSEntrys with a type of 'directory' can have children.
This does not detect cyclic parent/child relationships, but that will
cause problems.
:param metsrw.fsentry.FSEntry child: FSEntry to add as a child
... | Add a child FSEntry to this FSEntry.
Only FSEntrys with a type of 'directory' can have children.
This does not detect cyclic parent/child relationships, but that will
cause problems.
:param metsrw.fsentry.FSEntry child: FSEntry to add as a child
:return: The newly added child
... | entailment |
def remove_child(self, child):
"""
Remove a child from this FSEntry
If `child` is not actually a child of this entry, nothing happens.
:param child: Child to remove
"""
try:
self._children.remove(child)
except ValueError: # Child may not be in list
... | Remove a child from this FSEntry
If `child` is not actually a child of this entry, nothing happens.
:param child: Child to remove | entailment |
def serialize_filesec(self):
"""
Return the file Element for this file, appropriate for use in a fileSec.
If this is not an Item or has no use, return None.
:return: fileSec element for this FSEntry
"""
if (
self.type.lower() not in ("item", "archival inform... | Return the file Element for this file, appropriate for use in a fileSec.
If this is not an Item or has no use, return None.
:return: fileSec element for this FSEntry | entailment |
def is_empty_dir(self):
"""Returns ``True`` if this fs item is a directory with no children or
a directory with only other empty directories as children.
"""
if self.mets_div_type == "Directory":
children = self._children
if children:
if all(child.... | Returns ``True`` if this fs item is a directory with no children or
a directory with only other empty directories as children. | entailment |
def serialize_structmap(self, recurse=True, normative=False):
"""Return the div Element for this file, appropriate for use in a
structMap.
If this FSEntry represents a directory, its children will be
recursively appended to itself. If this FSEntry represents a file, it
will cont... | Return the div Element for this file, appropriate for use in a
structMap.
If this FSEntry represents a directory, its children will be
recursively appended to itself. If this FSEntry represents a file, it
will contain a <fptr> element.
:param bool recurse: If true, serialize an... | entailment |
def check_secret(self, secret):
"""Checks if the secret string used in the authentication attempt
matches the "known" secret string. Some mechanisms will override this
method to control how this comparison is made.
Args:
secret: The secret string to compare against what was ... | Checks if the secret string used in the authentication attempt
matches the "known" secret string. Some mechanisms will override this
method to control how this comparison is made.
Args:
secret: The secret string to compare against what was used in the
authentication ... | entailment |
def secure(cls):
"""Uses only authentication mechanisms that are secure for use in
non-encrypted sessions.
Returns:
A new :class:`SASLAuth` object.
"""
builtin_mechs = cls._get_builtin_mechanisms()
secure_mechs = [mech for _, mech in builtin_mechs.items()
... | Uses only authentication mechanisms that are secure for use in
non-encrypted sessions.
Returns:
A new :class:`SASLAuth` object. | entailment |
def plaintext(cls):
"""Uses only authentication mechanisms that provide the credentials in
un-hashed form, typically meaning
:attr:`~pysasl.AuthenticationCredentials.has_secret` is True.
Returns:
A new :class:`SASLAuth` object.
"""
builtin_mechs = cls._get_b... | Uses only authentication mechanisms that provide the credentials in
un-hashed form, typically meaning
:attr:`~pysasl.AuthenticationCredentials.has_secret` is True.
Returns:
A new :class:`SASLAuth` object. | entailment |
def server_mechanisms(self):
"""List of available :class:`ServerMechanism` objects."""
return [mech for mech in self.mechs.values()
if isinstance(mech, ServerMechanism)] | List of available :class:`ServerMechanism` objects. | entailment |
def client_mechanisms(self):
"""List of available :class:`ClientMechanism` objects."""
return [mech for mech in self.mechs.values()
if isinstance(mech, ClientMechanism)] | List of available :class:`ClientMechanism` objects. | entailment |
def get_server(self, name):
"""Like :meth:`.get`, but only mechanisms inheriting
:class:`ServerMechanism` will be returned.
Args:
name: The SASL mechanism name.
Returns:
The mechanism object or ``None``
"""
mech = self.get(name)
return m... | Like :meth:`.get`, but only mechanisms inheriting
:class:`ServerMechanism` will be returned.
Args:
name: The SASL mechanism name.
Returns:
The mechanism object or ``None`` | entailment |
def get_client(self, name):
"""Like :meth:`.get`, but only mechanisms inheriting
:class:`ClientMechanism` will be returned.
Args:
name: The SASL mechanism name.
Returns:
The mechanism object or ``None``
"""
mech = self.get(name)
return m... | Like :meth:`.get`, but only mechanisms inheriting
:class:`ClientMechanism` will be returned.
Args:
name: The SASL mechanism name.
Returns:
The mechanism object or ``None`` | entailment |
def read(cls, source):
"""Read ``source`` into a ``METSDocument`` instance. This is an
instance constructor. The ``source`` may be a path to a METS file, a
file-like object, or a string of XML.
"""
if hasattr(source, "read"):
return cls.fromfile(source)
if os.... | Read ``source`` into a ``METSDocument`` instance. This is an
instance constructor. The ``source`` may be a path to a METS file, a
file-like object, or a string of XML. | entailment |
def _collect_all_files(self, files=None):
"""
Collect all FSEntrys into a set, including all descendants.
:param list files: List of :class:`FSEntry` to traverse.
:returns: Set of FSEntry
"""
if files is None:
files = self._root_elements
collected = s... | Collect all FSEntrys into a set, including all descendants.
:param list files: List of :class:`FSEntry` to traverse.
:returns: Set of FSEntry | entailment |
def get_file(self, **kwargs):
"""
Return the FSEntry that matches parameters.
:param str file_uuid: UUID of the target FSEntry.
:param str label: structMap LABEL of the target FSEntry.
:param str type: structMap TYPE of the target FSEntry.
:returns: :class:`FSEntry` that... | Return the FSEntry that matches parameters.
:param str file_uuid: UUID of the target FSEntry.
:param str label: structMap LABEL of the target FSEntry.
:param str type: structMap TYPE of the target FSEntry.
:returns: :class:`FSEntry` that matches parameters, or None. | entailment |
def append_file(self, fs_entry):
"""
Adds an FSEntry object to this METS document's tree. Any of the
represented object's children will also be added to the document.
A given FSEntry object can only be included in a document once,
and any attempt to add an object the second time... | Adds an FSEntry object to this METS document's tree. Any of the
represented object's children will also be added to the document.
A given FSEntry object can only be included in a document once,
and any attempt to add an object the second time will be ignored.
:param metsrw.mets.FSEntry... | entailment |
def remove_entry(self, fs_entry):
"""Removes an FSEntry object from this METS document.
Any children of this FSEntry will also be removed. This will be removed
as a child of it's parent, if any.
:param metsrw.mets.FSEntry fs_entry: FSEntry to remove from the METS
"""
tr... | Removes an FSEntry object from this METS document.
Any children of this FSEntry will also be removed. This will be removed
as a child of it's parent, if any.
:param metsrw.mets.FSEntry fs_entry: FSEntry to remove from the METS | entailment |
def _document_root(self, fully_qualified=True):
"""
Return the mets Element for the document root.
"""
nsmap = {"xsi": utils.NAMESPACES["xsi"], "xlink": utils.NAMESPACES["xlink"]}
if fully_qualified:
nsmap["mets"] = utils.NAMESPACES["mets"]
else:
n... | Return the mets Element for the document root. | entailment |
def _mets_header(self, now):
"""
Return the metsHdr Element.
"""
header_tag = etree.QName(utils.NAMESPACES[u"mets"], u"metsHdr")
header_attrs = {}
if self.createdate is None:
header_attrs[u"CREATEDATE"] = now
else:
header_attrs[u"CREATEDAT... | Return the metsHdr Element. | entailment |
def _collect_mdsec_elements(files):
"""
Return all dmdSec and amdSec classes associated with the files.
Returns all dmdSecs, then all amdSecs, so they only need to be
serialized before being appended to the METS document.
:param List files: List of :class:`FSEntry` to collect M... | Return all dmdSec and amdSec classes associated with the files.
Returns all dmdSecs, then all amdSecs, so they only need to be
serialized before being appended to the METS document.
:param List files: List of :class:`FSEntry` to collect MDSecs for.
:returns: List of AMDSecs and SubSect... | entailment |
def _structmap(self):
"""
Returns structMap element for all files.
"""
structmap = etree.Element(
utils.lxmlns("mets") + "structMap",
TYPE="physical",
# TODO Add ability for multiple structMaps
ID="structMap_1",
# TODO don't har... | Returns structMap element for all files. | entailment |
def _filesec(self, files=None):
"""
Returns fileSec Element containing all files grouped by use.
"""
if files is None:
files = self.all_files()
filesec = etree.Element(utils.lxmlns("mets") + "fileSec")
filegrps = {}
for file_ in files:
if ... | Returns fileSec Element containing all files grouped by use. | entailment |
def serialize(self, fully_qualified=True):
"""
Returns this document serialized to an xml Element.
:return: Element for this document
"""
now = datetime.utcnow().replace(microsecond=0).isoformat("T")
files = self.all_files()
mdsecs = self._collect_mdsec_elements(... | Returns this document serialized to an xml Element.
:return: Element for this document | entailment |
def tostring(self, fully_qualified=True, pretty_print=True, encoding="UTF-8"):
"""
Serialize and return a string of this METS document.
To write to file, see :meth:`write`.
The default encoding is ``UTF-8``. This method will return a unicode
string when ``encoding`` is set to `... | Serialize and return a string of this METS document.
To write to file, see :meth:`write`.
The default encoding is ``UTF-8``. This method will return a unicode
string when ``encoding`` is set to ``unicode``.
:return: String of this document | entailment |
def write(
self, filepath, fully_qualified=True, pretty_print=False, encoding="UTF-8"
):
"""Serialize and write this METS document to `filepath`.
The default encoding is ``UTF-8``. This method will return a unicode
string when ``encoding`` is set to ``unicode``.
:param str ... | Serialize and write this METS document to `filepath`.
The default encoding is ``UTF-8``. This method will return a unicode
string when ``encoding`` is set to ``unicode``.
:param str filepath: Path to write the METS document to | entailment |
def _parse_tree_structmap(self, tree, parent_elem, normative_parent_elem=None):
"""Recursively parse all the children of parent_elem, including amdSecs
and dmdSecs.
:param lxml._ElementTree tree: encodes the entire METS file.
:param lxml._Element parent_elem: the element whose children w... | Recursively parse all the children of parent_elem, including amdSecs
and dmdSecs.
:param lxml._ElementTree tree: encodes the entire METS file.
:param lxml._Element parent_elem: the element whose children we are
parsing.
:param lxml._Element normative_parent_elem: the normativ... | entailment |
def _get_el_to_normative(parent_elem, normative_parent_elem):
"""Return ordered dict ``el_to_normative``, which maps children of
``parent_elem`` to their normative counterparts in the children of
``normative_parent_elem`` or to ``None`` if there is no normative
parent. If there is a norm... | Return ordered dict ``el_to_normative``, which maps children of
``parent_elem`` to their normative counterparts in the children of
``normative_parent_elem`` or to ``None`` if there is no normative
parent. If there is a normative div element with no non-normative
counterpart, that element... | entailment |
def fromfile(cls, path):
"""
Creates a METS by parsing a file.
:param str path: Path to a METS document.
"""
parser = etree.XMLParser(remove_blank_text=True)
return cls.fromtree(etree.parse(path, parser=parser)) | Creates a METS by parsing a file.
:param str path: Path to a METS document. | entailment |
def fromstring(cls, string):
"""
Create a METS by parsing a string.
:param str string: String containing a METS document.
"""
parser = etree.XMLParser(remove_blank_text=True)
root = etree.fromstring(string, parser)
tree = root.getroottree()
return cls.fr... | Create a METS by parsing a string.
:param str string: String containing a METS document. | entailment |
def fromtree(cls, tree):
"""
Create a METS from an ElementTree or Element.
:param ElementTree tree: ElementTree to build a METS document from.
"""
mets = cls()
mets.tree = tree
mets._parse_tree(tree)
return mets | Create a METS from an ElementTree or Element.
:param ElementTree tree: ElementTree to build a METS document from. | entailment |
def get_schematron(sct_path):
"""Return an lxml ``isoschematron.Schematron()`` instance using the
schematron file at ``sct_path``.
"""
sct_path = _get_file_path(sct_path)
parser = etree.XMLParser(remove_blank_text=True)
sct_doc = etree.parse(sct_path, parser=parser)
return isoschematron.Sche... | Return an lxml ``isoschematron.Schematron()`` instance using the
schematron file at ``sct_path``. | entailment |
def validate(mets_doc, xmlschema=METS_XSD_PATH, schematron=AM_SCT_PATH):
"""Validate a METS file using both an XMLSchema (.xsd) schema and a
schematron schema, the latter of which typically places additional
constraints on what a METS file can look like.
"""
is_xsd_valid, xsd_error_log = xsd_validat... | Validate a METS file using both an XMLSchema (.xsd) schema and a
schematron schema, the latter of which typically places additional
constraints on what a METS file can look like. | entailment |
def get_xmlschema(xmlschema, mets_doc):
"""Return a ``class::lxml.etree.XMLSchema`` instance given the path to the
XMLSchema (.xsd) file in ``xmlschema`` and the
``class::lxml.etree._ElementTree`` instance ``mets_doc`` representing the
METS file being parsed. The complication here is that the METS file ... | Return a ``class::lxml.etree.XMLSchema`` instance given the path to the
XMLSchema (.xsd) file in ``xmlschema`` and the
``class::lxml.etree._ElementTree`` instance ``mets_doc`` representing the
METS file being parsed. The complication here is that the METS file to be
validated via the .xsd file may refer... | entailment |
def schematron_validate(mets_doc, schematron=AM_SCT_PATH):
"""Validate a METS file using a schematron schema. Return a boolean
indicating validity and a report as an ``lxml.ElementTree`` instance.
"""
if isinstance(schematron, six.string_types):
schematron = get_schematron(schematron)
is_val... | Validate a METS file using a schematron schema. Return a boolean
indicating validity and a report as an ``lxml.ElementTree`` instance. | entailment |
def sct_report_string(report):
"""Return a human-readable string representation of the error report
returned by lxml's schematron validator.
"""
ret = []
namespaces = {"svrl": "http://purl.oclc.org/dsdl/svrl"}
for index, failed_assert_el in enumerate(
report.findall("svrl:failed-assert",... | Return a human-readable string representation of the error report
returned by lxml's schematron validator. | entailment |
def xsd_error_log_string(xsd_error_log):
"""Return a human-readable string representation of the error log
returned by lxml's XMLSchema validator.
"""
ret = []
for error in xsd_error_log:
ret.append(
"ERROR ON LINE {}: {}".format(error.line, error.message.encode("utf-8"))
... | Return a human-readable string representation of the error log
returned by lxml's XMLSchema validator. | entailment |
def validate_arguments(self, view_class, kwargs):
"""
view_class : View Class used to render content popup dialog
view_class must be subclass of django.views.generic.View
"""
# Check view_class inherit from django View
if not issubclass(view_class, View):
rai... | view_class : View Class used to render content popup dialog
view_class must be subclass of django.views.generic.View | entailment |
def get_view_url(self):
"""Return url for ajax to view for render dialog content"""
url = reverse("django_popup_view_field:get_popup_view", args=(self.view_class_name,))
return "{url}?{cd}".format(
url=url,
cd=self.callback_data
) | Return url for ajax to view for render dialog content | entailment |
def on_timer(self):
"""Executes flush(). Ignores any errors to make sure one exception
doesn't halt the whole flushing process.
"""
try:
self.flush()
except Exception as e:
log.exception('Error while flushing: %s', e)
self._set_timer() | Executes flush(). Ignores any errors to make sure one exception
doesn't halt the whole flushing process. | entailment |
def timing_since(self, stat, start, sample_rate=1):
"""
Log timing information as the number of microseconds since the provided time float
>>> start = time.time()
>>> # do stuff
>>> statsd_client.timing_since('some.time', start)
"""
self.timing(stat, int((time.tim... | Log timing information as the number of microseconds since the provided time float
>>> start = time.time()
>>> # do stuff
>>> statsd_client.timing_since('some.time', start) | entailment |
def timing(self, stat, time, sample_rate=1):
"""
Log timing information for a single stat
>>> statsd_client.timing('some.time',500)
"""
stats = {stat: "%f|ms" % time}
self.send(stats, sample_rate) | Log timing information for a single stat
>>> statsd_client.timing('some.time',500) | entailment |
def gauge(self, stat, value, sample_rate=1):
"""
Log gauge information for a single stat
>>> statsd_client.gauge('some.gauge',42)
"""
stats = {stat: "%f|g" % value}
self.send(stats, sample_rate) | Log gauge information for a single stat
>>> statsd_client.gauge('some.gauge',42) | entailment |
def update_stats(self, stats, delta, sample_rate=1):
"""
Updates one or more stats counters by arbitrary amounts
>>> statsd_client.update_stats('some.int',10)
"""
if not isinstance(stats, list):
stats = [stats]
data = dict((stat, "%s|c" % delta) for stat in s... | Updates one or more stats counters by arbitrary amounts
>>> statsd_client.update_stats('some.int',10) | entailment |
def send(self, data, sample_rate=1):
"""
Squirt the metrics over UDP
"""
if self.prefix:
data = dict((".".join((self.prefix, stat)), value) for stat, value in data.items())
if sample_rate < 1:
if random.random() > sample_rate:
return
... | Squirt the metrics over UDP | entailment |
def start(self, *args, **kw):
"""Start the daemon."""
pid = None
if os.path.exists(self.pidfile):
with open(self.pidfile, 'r') as fp:
pid = int(fp.read().strip())
if pid:
msg = 'pidfile (%s) exists. Daemon already running?\n'
sys.stder... | Start the daemon. | entailment |
def stop(self):
"""Stop the daemon."""
pid = None
if os.path.exists(self.pidfile):
with open(self.pidfile, 'r') as fp:
pid = int(fp.read().strip())
if not pid:
msg = 'pidfile (%s) does not exist. Daemon not running?\n'
sys.stderr.write... | Stop the daemon. | entailment |
def restart(self, *args, **kw):
"""Restart the daemon."""
self.stop()
self.start(*args, **kw) | Restart the daemon. | entailment |
def get_auth_providers(self, netloc):
"""BIG-IQ specific query for auth providers
BIG-IP doesn't really need this because BIG-IP's multiple auth providers
seem to handle fallthrough just fine. BIG-IQ on the other hand, needs to
have its auth provider specified if you're using one of the... | BIG-IQ specific query for auth providers
BIG-IP doesn't really need this because BIG-IP's multiple auth providers
seem to handle fallthrough just fine. BIG-IQ on the other hand, needs to
have its auth provider specified if you're using one of the non-default
ones.
:param netloc... | entailment |
def get_new_token(self, netloc):
"""Get a new token from BIG-IP and store it internally.
Throws relevant exception if it fails to get a new token.
This method will be called automatically if a request is attempted
but there is no authentication token, or the authentication token
... | Get a new token from BIG-IP and store it internally.
Throws relevant exception if it fails to get a new token.
This method will be called automatically if a request is attempted
but there is no authentication token, or the authentication token
is expired. It is usually not necessary f... | entailment |
def generate_bigip_uri(base_uri, partition, name, sub_path, suffix, **kwargs):
'''(str, str, str) --> str
This function checks the supplied elements to see if each conforms to
the specification for the appropriate part of the URI. These validations
are conducted by the helper function _validate_uri_par... | (str, str, str) --> str
This function checks the supplied elements to see if each conforms to
the specification for the appropriate part of the URI. These validations
are conducted by the helper function _validate_uri_parts.
After validation the parts are assembled into a valid BigIP REST URI
strin... | entailment |
def decorate_HTTP_verb_method(method):
"""Prepare and Post-Process HTTP VERB method for BigIP-RESTServer request.
This function decorates all of the HTTP VERB methods in the
iControlRESTSession class. It provides the core logic for this module.
If necessary it validates and assembles a uri from parts ... | Prepare and Post-Process HTTP VERB method for BigIP-RESTServer request.
This function decorates all of the HTTP VERB methods in the
iControlRESTSession class. It provides the core logic for this module.
If necessary it validates and assembles a uri from parts with a call to
`generate_bigip_uri`.
... | entailment |
def _unique_resource_identifier_from_kwargs(**kwargs):
"""Chooses an identifier given different choices
The unique identifier in BIG-IP's REST API at the time of this writing
is called 'name'. This is in contrast to the unique identifier that is
used by iWorkflow and BIG-IQ which at some times is 'name... | Chooses an identifier given different choices
The unique identifier in BIG-IP's REST API at the time of this writing
is called 'name'. This is in contrast to the unique identifier that is
used by iWorkflow and BIG-IQ which at some times is 'name' and other
times is 'uuid'.
For example, in iWorkflo... | entailment |
def delete(self, uri, **kwargs):
"""Sends a HTTP DELETE command to the BIGIP REST Server.
Use this method to send a DELETE command to the BIGIP. When calling
this method with the optional arguments ``name`` and ``partition``
as part of ``**kwargs`` they will be added to the ``uri`` pas... | Sends a HTTP DELETE command to the BIGIP REST Server.
Use this method to send a DELETE command to the BIGIP. When calling
this method with the optional arguments ``name`` and ``partition``
as part of ``**kwargs`` they will be added to the ``uri`` passed
in separated by ~ to create a pr... | entailment |
def append_user_agent(self, user_agent):
"""Append text to the User-Agent header for the request.
Use this method to update the User-Agent header by appending the
given string to the session's User-Agent header separated by a space.
:param user_agent: A string to append to the User-Age... | Append text to the User-Agent header for the request.
Use this method to update the User-Agent header by appending the
given string to the session's User-Agent header separated by a space.
:param user_agent: A string to append to the User-Agent header
:type user_agent: str | entailment |
def validate_public_key(value):
"""
Check that the given value is a valid RSA Public key in either PEM or OpenSSH format. If it is invalid,
raises ``django.core.exceptions.ValidationError``.
"""
is_valid = False
exc = None
for load in (load_pem_public_key, load_ssh_public_key):
if n... | Check that the given value is a valid RSA Public key in either PEM or OpenSSH format. If it is invalid,
raises ``django.core.exceptions.ValidationError``. | entailment |
def _register_formats(cls):
"""Adds format properties."""
for fmt in cls.OUTPUT_FORMATS:
clean_fmt = fmt.replace('+', '_')
setattr(cls, clean_fmt, property(
(lambda x, fmt=fmt: cls._output(x, fmt)), # fget
(lambda x, y, fmt=fmt: cls._input(x, y, fm... | Adds format properties. | entailment |
def to_file(self, output_filename):
'''Handles pdf and epub format.
Inpute: output_filename should have the proper extension.
Output: The name of the file created, or an IOError if failed'''
temp_file = NamedTemporaryFile(mode="w", suffix=".md", delete=False)
temp_file.write(self... | Handles pdf and epub format.
Inpute: output_filename should have the proper extension.
Output: The name of the file created, or an IOError if failed | entailment |
def sign(username, private_key, generate_nonce=None, iat=None, algorithm=DEFAULT_ALGORITHM):
"""
Create a signed JWT using the given username and RSA private key.
:param username: Username (string) to authenticate as on the remote system.
:param private_key: Private key to use to sign the JWT claim.
... | Create a signed JWT using the given username and RSA private key.
:param username: Username (string) to authenticate as on the remote system.
:param private_key: Private key to use to sign the JWT claim.
:param generate_nonce: Optional. Callable to use to generate a new nonce. Defaults to
`random.r... | entailment |
def get_claimed_username(token):
"""
Given a JWT, get the username that it is claiming to be `without verifying that the signature is valid`.
:param token: JWT claim
:return: Username
"""
unverified_data = jwt.decode(token, options={
'verify_signature': False
})
if 'username' n... | Given a JWT, get the username that it is claiming to be `without verifying that the signature is valid`.
:param token: JWT claim
:return: Username | entailment |
def verify(token, public_key, validate_nonce=None, algorithms=[DEFAULT_ALGORITHM]):
"""
Verify the validity of the given JWT using the given public key.
:param token: JWM claim
:param public_key: Public key to use when verifying the claim's signature.
:param validate_nonce: Callable to use to valid... | Verify the validity of the given JWT using the given public key.
:param token: JWM claim
:param public_key: Public key to use when verifying the claim's signature.
:param validate_nonce: Callable to use to validate the claim's nonce.
:param algorithms: Allowable signing algorithms. Defaults to ['RS512'... | entailment |
def log_used_nonce(self, username, iat, nonce):
"""
Log a nonce as being used, and therefore henceforth invalid.
:param username: Username as a string.
:param iat: Unix timestamp float or integer of when the nonce was used.
:param nonce: Nonce value.
"""
# TODO: ... | Log a nonce as being used, and therefore henceforth invalid.
:param username: Username as a string.
:param iat: Unix timestamp float or integer of when the nonce was used.
:param nonce: Nonce value. | entailment |
def validate_nonce(self, username, iat, nonce):
"""
Confirm that the given nonce hasn't already been used.
:param username: Username as a string.
:param iat: Unix timestamp float or integer of when the nonce was used.
:param nonce: Nonce value.
:return: True if nonce is ... | Confirm that the given nonce hasn't already been used.
:param username: Username as a string.
:param iat: Unix timestamp float or integer of when the nonce was used.
:param nonce: Nonce value.
:return: True if nonce is valid, False if it is invalid. | entailment |
def process_request(self, request):
"""
Process a Django request and authenticate users.
If a JWT authentication header is detected and it is determined to be valid, the user is set as
``request.user`` and CSRF protection is disabled (``request._dont_enforce_csrf_checks = True``) on
... | Process a Django request and authenticate users.
If a JWT authentication header is detected and it is determined to be valid, the user is set as
``request.user`` and CSRF protection is disabled (``request._dont_enforce_csrf_checks = True``) on
the request.
:param request: Django Reques... | entailment |
def generate_key_pair(size=2048, public_exponent=65537, as_string=True):
"""
Generate a public/private key pair.
:param size: Optional. Describes how many bits long the key should be, larger keys provide more security,
currently 1024 and below are considered breakable, and 2048 or 4096 are reasonab... | Generate a public/private key pair.
:param size: Optional. Describes how many bits long the key should be, larger keys provide more security,
currently 1024 and below are considered breakable, and 2048 or 4096 are reasonable default
key sizes for new keys. Defaults to 2048.
:param public_expone... | entailment |
def load_private_key(key_file, key_password=None):
"""
Load a private key from disk.
:param key_file: File path to key file.
:param key_password: Optional. If the key file is encrypted, provide the password to decrypt it. Defaults to None.
:return: PrivateKey<string>
"""
key_file = os.path.... | Load a private key from disk.
:param key_file: File path to key file.
:param key_password: Optional. If the key file is encrypted, provide the password to decrypt it. Defaults to None.
:return: PrivateKey<string> | entailment |
def decrypt_key(key, password):
"""
Decrypt an encrypted private key.
:param key: Encrypted private key as a string.
:param password: Key pass-phrase.
:return: Decrypted private key as a string.
"""
private = serialization.load_pem_private_key(key, password=password, backend=default_backend... | Decrypt an encrypted private key.
:param key: Encrypted private key as a string.
:param password: Key pass-phrase.
:return: Decrypted private key as a string. | entailment |
def create_auth_header(username, key=None, key_file="~/.ssh/id_rsa", key_password=None):
"""
Create an HTTP Authorization header using a private key file.
Either a key or a key_file must be provided.
:param username: The username to authenticate as on the remote system.
:param key: Optional. A pri... | Create an HTTP Authorization header using a private key file.
Either a key or a key_file must be provided.
:param username: The username to authenticate as on the remote system.
:param key: Optional. A private key as either a string or an instance of cryptography.hazmat.primitives.asymmetric.rsa.RSAPrivat... | entailment |
def _config_logs(lvl=None, name=None):
"""
Set up or change logging configuration.
_config_logs() => idempotent setup;
_config_logs(L) => change log level
"""
# print('_config_log', 'from %s' %name if name else '')
FORMAT = '%(message)s'
# maybe better for log files
# FORMAT='[%(lev... | Set up or change logging configuration.
_config_logs() => idempotent setup;
_config_logs(L) => change log level | entailment |
def mk_set_headers(self, data, columns):
""" figure out sizes and create header fmt """
columns = tuple(columns)
lens = []
for key in columns:
value_len = max(len(str(each.get(key, ''))) for each in data)
# account for header lengths
lens.append(max(v... | figure out sizes and create header fmt | entailment |
def _get_name(self, key):
""" get display name for a key, or mangle for display """
if key in self.display_names:
return self.display_names[key]
return key.capitalize() | get display name for a key, or mangle for display | entailment |
def display_set(self, typ, data, columns):
""" display a list of dicts """
self.display_section("%s (%d)" % (self._get_name(typ), len(data)))
headers = tuple(map(self._get_name, columns))
fmt = self.mk_set_headers(data, columns)
self.display_headers(fmt, headers)
for eac... | display a list of dicts | entailment |
def _print(self, *args):
""" internal print to self.fobj """
string = u" ".join(args) + '\n'
self.fobj.write(string) | internal print to self.fobj | entailment |
def display(self, typ, data):
""" display section of typ with data """
if hasattr(self, 'print_' + typ):
getattr(self, 'print_' + typ)(data)
elif not data:
self._print("%s: %s" % (typ, data))
elif isinstance(data, collections.Mapping):
self._print("\... | display section of typ with data | entailment |
def _handler(func):
"Decorate a command handler"
def _wrapped(*a, **k):
r = func(*a, **k)
if r is None: r = 0
return r
return staticmethod(_wrapped) | Decorate a command handler | entailment |
def add_subcommands(parser, commands):
"Add commands to a parser"
subps = parser.add_subparsers()
for cmd, cls in commands:
subp = subps.add_parser(cmd, help=cls.__doc__)
add_args = getattr(cls, 'add_arguments', None)
if add_args:
add_args(subp)
handler = getattr(... | Add commands to a parser | entailment |
def reftag_to_cls(fn):
"""
decorator that checks function arguments for `concrete` and `resource`
and will properly set them to class references if a string (reftag) is
passed as the value
"""
names, _, _, values = inspect.getargspec(fn)
@wraps(fn)
def wrapped(*args, **kwargs):
i... | decorator that checks function arguments for `concrete` and `resource`
and will properly set them to class references if a string (reftag) is
passed as the value | entailment |
def update(self, res, pk, depth=1, since=None):
"""
Try to sync an object to the local database, in case of failure
where a referenced object is not found, attempt to fetch said
object from the REST api
"""
fetch = lambda: self._fetcher.fetch_latest(res, pk, 1, since=sinc... | Try to sync an object to the local database, in case of failure
where a referenced object is not found, attempt to fetch said
object from the REST api | entailment |
def update_where(self, res, depth=0, since=None, **kwargs):
"Like update() but uses WHERE-style args"
fetch = lambda: self._fetcher.fetch_all_latest(res, 0, kwargs, since=since)
self._update(res, fetch, depth) | Like update() but uses WHERE-style args | entailment |
def update_all(self, rs=None, since=None):
"Sync all objects for the relations rs (if None, sync all resources)"
self._log.info("Updating resources: %s", ' '.join(r.tag for r in rs))
if rs is None:
rs = resource.all_resources()
ctx = self._ContextClass(self)
for r in... | Sync all objects for the relations rs (if None, sync all resources) | entailment |
def get_task(self, key):
"""Get a scheduled task, or none"""
res, pk = key
jobs, lock = self._jobs
with lock:
return jobs[res].get(pk) | Get a scheduled task, or none | entailment |
def set_job(self, key, func, args):
"""
Get a scheduled task or set if none exists.
Returns:
- task coroutine/continuation
"""
res, pk = key
jobs, lock = self._jobs
task = _tasks.UpdateTask(func(*args), key)
with lock:
job = jobs[r... | Get a scheduled task or set if none exists.
Returns:
- task coroutine/continuation | entailment |
def pending_tasks(self, res):
"Synchronized access to tasks"
jobs, lock = self._jobs
with lock:
return jobs[res].copy() | Synchronized access to tasks | entailment |
def fetch_and_index(self, fetch_func):
"Fetch data with func, return dict indexed by ID"
data, e = fetch_func()
if e: raise e
yield {row['id']: row for row in data} | Fetch data with func, return dict indexed by ID | entailment |
def clean_helper(B, obj, clean_func):
"""
Clean object, intercepting and collecting any missing-relation or
unique-constraint errors and returning the relevant resource ids/fields.
Returns:
- tuple: (<dict of non-unique fields>, <dict of missing refs>)
"""
try:
clean_func(obj)
... | Clean object, intercepting and collecting any missing-relation or
unique-constraint errors and returning the relevant resource ids/fields.
Returns:
- tuple: (<dict of non-unique fields>, <dict of missing refs>) | entailment |
def initialize_object(B, res, row):
"""
Do a shallow initialization of an object
Arguments:
- row<dict>: dict of data like depth=1, i.e. many_refs are only ids
"""
B = get_backend()
field_groups = FieldGroups(B.get_concrete(res))
try:
obj = B.get_object(B.get_concrete(res),... | Do a shallow initialization of an object
Arguments:
- row<dict>: dict of data like depth=1, i.e. many_refs are only ids | entailment |
def read_config(conf_dir=DEFAULT_CONFIG_DIR):
"Find and read config file for a directory, return None if not found."
conf_path = os.path.expanduser(conf_dir)
if not os.path.exists(conf_path):
# only throw if not default
if conf_dir != DEFAULT_CONFIG_DIR:
raise IOError("Config di... | Find and read config file for a directory, return None if not found. | entailment |
def load_config(conf_dir=DEFAULT_CONFIG_DIR, schema=CLIENT_SCHEMA):
"""
Load config files from the specified directory, using defaults for missing values.
Directory should contain a file named config.<ext> where <ext> is a
supported config file format.
"""
data = default_config(schema)
confi... | Load config files from the specified directory, using defaults for missing values.
Directory should contain a file named config.<ext> where <ext> is a
supported config file format. | entailment |
def detect_old(data):
"Check for a config file with old schema"
if not data:
return False
ok, errors, warnings = _schema.validate(_OLD_SCHEMA, data)
return ok and not (errors or warnings) | Check for a config file with old schema | entailment |
def convert_old(data):
"Convert config data with old schema to new schema"
ret = default_config()
ret['sync'].update(data.get('peeringdb', {}))
ret['orm']['database'].update(data.get('database', {}))
return ret | Convert config data with old schema to new schema | entailment |
def write_config(data, conf_dir=DEFAULT_CONFIG_DIR, codec="yaml",
backup_existing=False):
"""
Write config values to a file.
Arguments:
- conf_dir<str>: path to output directory
- codec<str>: output field format
- backup_existing<bool>: if a config file exists,
... | Write config values to a file.
Arguments:
- conf_dir<str>: path to output directory
- codec<str>: output field format
- backup_existing<bool>: if a config file exists,
make a copy before overwriting | entailment |
def prompt_config(sch, defaults=None, path=None):
"""
Utility function to recursively prompt for config values
Arguments:
- defaults<dict>: default values used for empty inputs
- path<str>: path to prepend to config keys (eg. "path.keyname")
"""
out = {}
for name, attr in sch.at... | Utility function to recursively prompt for config values
Arguments:
- defaults<dict>: default values used for empty inputs
- path<str>: path to prepend to config keys (eg. "path.keyname") | entailment |
def fetch(self, R, pk, depth=1):
"Request object from API"
d, e = self._fetcher.fetch(R, pk, depth)
if e: raise e
return d | Request object from API | entailment |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.