repository_name stringlengths 7 55 | func_path_in_repository stringlengths 4 223 | func_name stringlengths 1 134 | whole_func_string stringlengths 75 104k | language stringclasses 1
value | func_code_string stringlengths 75 104k | func_code_tokens listlengths 19 28.4k | func_documentation_string stringlengths 1 46.9k | func_documentation_tokens listlengths 1 1.97k | split_name stringclasses 1
value | func_code_url stringlengths 87 315 |
|---|---|---|---|---|---|---|---|---|---|---|
artefactual-labs/mets-reader-writer | metsrw/mets.py | METSDocument.get_file | 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... | python | 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... | [
"def",
"get_file",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"# TODO put this in a sqlite DB so it can be queried efficiently",
"# TODO handle multiple matches (with DB?)",
"# TODO check that kwargs are actual attrs",
"for",
"entry",
"in",
"self",
".",
"all_files",
"(",
... | 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. | [
"Return",
"the",
"FSEntry",
"that",
"matches",
"parameters",
"."
] | train | https://github.com/artefactual-labs/mets-reader-writer/blob/d95939cabdfdc25cb1bf67df0c84bd0d6e6a73ff/metsrw/mets.py#L87-L102 |
artefactual-labs/mets-reader-writer | metsrw/mets.py | METSDocument.append_file | 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... | python | 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... | [
"def",
"append_file",
"(",
"self",
",",
"fs_entry",
")",
":",
"if",
"fs_entry",
"in",
"self",
".",
"_root_elements",
":",
"return",
"self",
".",
"_root_elements",
".",
"append",
"(",
"fs_entry",
")",
"# Reset file lists so they get regenerated with the new files(s)",
... | 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... | [
"Adds",
"an",
"FSEntry",
"object",
"to",
"this",
"METS",
"document",
"s",
"tree",
".",
"Any",
"of",
"the",
"represented",
"object",
"s",
"children",
"will",
"also",
"be",
"added",
"to",
"the",
"document",
"."
] | train | https://github.com/artefactual-labs/mets-reader-writer/blob/d95939cabdfdc25cb1bf67df0c84bd0d6e6a73ff/metsrw/mets.py#L104-L119 |
artefactual-labs/mets-reader-writer | metsrw/mets.py | METSDocument.remove_entry | 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... | python | 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... | [
"def",
"remove_entry",
"(",
"self",
",",
"fs_entry",
")",
":",
"try",
":",
"self",
".",
"_root_elements",
".",
"remove",
"(",
"fs_entry",
")",
"except",
"ValueError",
":",
"# fs_entry may not be in the root elements",
"pass",
"if",
"fs_entry",
".",
"parent",
":"... | 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 | [
"Removes",
"an",
"FSEntry",
"object",
"from",
"this",
"METS",
"document",
"."
] | train | https://github.com/artefactual-labs/mets-reader-writer/blob/d95939cabdfdc25cb1bf67df0c84bd0d6e6a73ff/metsrw/mets.py#L123-L138 |
artefactual-labs/mets-reader-writer | metsrw/mets.py | METSDocument._document_root | 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... | python | 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... | [
"def",
"_document_root",
"(",
"self",
",",
"fully_qualified",
"=",
"True",
")",
":",
"nsmap",
"=",
"{",
"\"xsi\"",
":",
"utils",
".",
"NAMESPACES",
"[",
"\"xsi\"",
"]",
",",
"\"xlink\"",
":",
"utils",
".",
"NAMESPACES",
"[",
"\"xlink\"",
"]",
"}",
"if",
... | Return the mets Element for the document root. | [
"Return",
"the",
"mets",
"Element",
"for",
"the",
"document",
"root",
"."
] | train | https://github.com/artefactual-labs/mets-reader-writer/blob/d95939cabdfdc25cb1bf67df0c84bd0d6e6a73ff/metsrw/mets.py#L166-L180 |
artefactual-labs/mets-reader-writer | metsrw/mets.py | METSDocument._mets_header | 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... | python | 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... | [
"def",
"_mets_header",
"(",
"self",
",",
"now",
")",
":",
"header_tag",
"=",
"etree",
".",
"QName",
"(",
"utils",
".",
"NAMESPACES",
"[",
"u\"mets\"",
"]",
",",
"u\"metsHdr\"",
")",
"header_attrs",
"=",
"{",
"}",
"if",
"self",
".",
"createdate",
"is",
... | Return the metsHdr Element. | [
"Return",
"the",
"metsHdr",
"Element",
"."
] | train | https://github.com/artefactual-labs/mets-reader-writer/blob/d95939cabdfdc25cb1bf67df0c84bd0d6e6a73ff/metsrw/mets.py#L182-L201 |
artefactual-labs/mets-reader-writer | metsrw/mets.py | METSDocument._collect_mdsec_elements | 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... | python | 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... | [
"def",
"_collect_mdsec_elements",
"(",
"files",
")",
":",
"dmdsecs",
"=",
"[",
"]",
"amdsecs",
"=",
"[",
"]",
"for",
"f",
"in",
"files",
":",
"for",
"d",
"in",
"f",
".",
"dmdsecs",
":",
"dmdsecs",
".",
"append",
"(",
"d",
")",
"for",
"a",
"in",
"... | 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... | [
"Return",
"all",
"dmdSec",
"and",
"amdSec",
"classes",
"associated",
"with",
"the",
"files",
"."
] | train | https://github.com/artefactual-labs/mets-reader-writer/blob/d95939cabdfdc25cb1bf67df0c84bd0d6e6a73ff/metsrw/mets.py#L204-L224 |
artefactual-labs/mets-reader-writer | metsrw/mets.py | METSDocument._structmap | 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... | python | 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... | [
"def",
"_structmap",
"(",
"self",
")",
":",
"structmap",
"=",
"etree",
".",
"Element",
"(",
"utils",
".",
"lxmlns",
"(",
"\"mets\"",
")",
"+",
"\"structMap\"",
",",
"TYPE",
"=",
"\"physical\"",
",",
"# TODO Add ability for multiple structMaps",
"ID",
"=",
"\"s... | Returns structMap element for all files. | [
"Returns",
"structMap",
"element",
"for",
"all",
"files",
"."
] | train | https://github.com/artefactual-labs/mets-reader-writer/blob/d95939cabdfdc25cb1bf67df0c84bd0d6e6a73ff/metsrw/mets.py#L226-L243 |
artefactual-labs/mets-reader-writer | metsrw/mets.py | METSDocument._filesec | 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 ... | python | 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 ... | [
"def",
"_filesec",
"(",
"self",
",",
"files",
"=",
"None",
")",
":",
"if",
"files",
"is",
"None",
":",
"files",
"=",
"self",
".",
"all_files",
"(",
")",
"filesec",
"=",
"etree",
".",
"Element",
"(",
"utils",
".",
"lxmlns",
"(",
"\"mets\"",
")",
"+"... | Returns fileSec Element containing all files grouped by use. | [
"Returns",
"fileSec",
"Element",
"containing",
"all",
"files",
"grouped",
"by",
"use",
"."
] | train | https://github.com/artefactual-labs/mets-reader-writer/blob/d95939cabdfdc25cb1bf67df0c84bd0d6e6a73ff/metsrw/mets.py#L262-L286 |
artefactual-labs/mets-reader-writer | metsrw/mets.py | METSDocument.serialize | 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(... | python | 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(... | [
"def",
"serialize",
"(",
"self",
",",
"fully_qualified",
"=",
"True",
")",
":",
"now",
"=",
"datetime",
".",
"utcnow",
"(",
")",
".",
"replace",
"(",
"microsecond",
"=",
"0",
")",
".",
"isoformat",
"(",
"\"T\"",
")",
"files",
"=",
"self",
".",
"all_f... | Returns this document serialized to an xml Element.
:return: Element for this document | [
"Returns",
"this",
"document",
"serialized",
"to",
"an",
"xml",
"Element",
"."
] | train | https://github.com/artefactual-labs/mets-reader-writer/blob/d95939cabdfdc25cb1bf67df0c84bd0d6e6a73ff/metsrw/mets.py#L288-L304 |
artefactual-labs/mets-reader-writer | metsrw/mets.py | METSDocument.tostring | 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 `... | python | 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 `... | [
"def",
"tostring",
"(",
"self",
",",
"fully_qualified",
"=",
"True",
",",
"pretty_print",
"=",
"True",
",",
"encoding",
"=",
"\"UTF-8\"",
")",
":",
"root",
"=",
"self",
".",
"serialize",
"(",
"fully_qualified",
"=",
"fully_qualified",
")",
"kwargs",
"=",
"... | 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 | [
"Serialize",
"and",
"return",
"a",
"string",
"of",
"this",
"METS",
"document",
"."
] | train | https://github.com/artefactual-labs/mets-reader-writer/blob/d95939cabdfdc25cb1bf67df0c84bd0d6e6a73ff/metsrw/mets.py#L306-L321 |
artefactual-labs/mets-reader-writer | metsrw/mets.py | METSDocument.write | 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 ... | python | 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 ... | [
"def",
"write",
"(",
"self",
",",
"filepath",
",",
"fully_qualified",
"=",
"True",
",",
"pretty_print",
"=",
"False",
",",
"encoding",
"=",
"\"UTF-8\"",
")",
":",
"root",
"=",
"self",
".",
"serialize",
"(",
"fully_qualified",
"=",
"fully_qualified",
")",
"... | 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 | [
"Serialize",
"and",
"write",
"this",
"METS",
"document",
"to",
"filepath",
"."
] | train | https://github.com/artefactual-labs/mets-reader-writer/blob/d95939cabdfdc25cb1bf67df0c84bd0d6e6a73ff/metsrw/mets.py#L323-L338 |
artefactual-labs/mets-reader-writer | metsrw/mets.py | METSDocument._parse_tree_structmap | 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... | python | 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... | [
"def",
"_parse_tree_structmap",
"(",
"self",
",",
"tree",
",",
"parent_elem",
",",
"normative_parent_elem",
"=",
"None",
")",
":",
"siblings",
"=",
"[",
"]",
"el_to_normative",
"=",
"self",
".",
"_get_el_to_normative",
"(",
"parent_elem",
",",
"normative_parent_el... | 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... | [
"Recursively",
"parse",
"all",
"the",
"children",
"of",
"parent_elem",
"including",
"amdSecs",
"and",
"dmdSecs",
".",
":",
"param",
"lxml",
".",
"_ElementTree",
"tree",
":",
"encodes",
"the",
"entire",
"METS",
"file",
".",
":",
"param",
"lxml",
".",
"_Elemen... | train | https://github.com/artefactual-labs/mets-reader-writer/blob/d95939cabdfdc25cb1bf67df0c84bd0d6e6a73ff/metsrw/mets.py#L342-L385 |
artefactual-labs/mets-reader-writer | metsrw/mets.py | METSDocument._get_el_to_normative | 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... | python | 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... | [
"def",
"_get_el_to_normative",
"(",
"parent_elem",
",",
"normative_parent_elem",
")",
":",
"el_to_normative",
"=",
"OrderedDict",
"(",
")",
"if",
"normative_parent_elem",
"is",
"None",
":",
"for",
"el",
"in",
"parent_elem",
":",
"el_to_normative",
"[",
"el",
"]",
... | 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... | [
"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",
"paren... | train | https://github.com/artefactual-labs/mets-reader-writer/blob/d95939cabdfdc25cb1bf67df0c84bd0d6e6a73ff/metsrw/mets.py#L388-L413 |
artefactual-labs/mets-reader-writer | metsrw/mets.py | METSDocument.fromfile | 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)) | python | 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)) | [
"def",
"fromfile",
"(",
"cls",
",",
"path",
")",
":",
"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. | [
"Creates",
"a",
"METS",
"by",
"parsing",
"a",
"file",
"."
] | train | https://github.com/artefactual-labs/mets-reader-writer/blob/d95939cabdfdc25cb1bf67df0c84bd0d6e6a73ff/metsrw/mets.py#L555-L563 |
artefactual-labs/mets-reader-writer | metsrw/mets.py | METSDocument.fromstring | 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... | python | 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... | [
"def",
"fromstring",
"(",
"cls",
",",
"string",
")",
":",
"parser",
"=",
"etree",
".",
"XMLParser",
"(",
"remove_blank_text",
"=",
"True",
")",
"root",
"=",
"etree",
".",
"fromstring",
"(",
"string",
",",
"parser",
")",
"tree",
"=",
"root",
".",
"getro... | Create a METS by parsing a string.
:param str string: String containing a METS document. | [
"Create",
"a",
"METS",
"by",
"parsing",
"a",
"string",
"."
] | train | https://github.com/artefactual-labs/mets-reader-writer/blob/d95939cabdfdc25cb1bf67df0c84bd0d6e6a73ff/metsrw/mets.py#L566-L576 |
artefactual-labs/mets-reader-writer | metsrw/mets.py | METSDocument.fromtree | 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 | python | 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 | [
"def",
"fromtree",
"(",
"cls",
",",
"tree",
")",
":",
"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. | [
"Create",
"a",
"METS",
"from",
"an",
"ElementTree",
"or",
"Element",
"."
] | train | https://github.com/artefactual-labs/mets-reader-writer/blob/d95939cabdfdc25cb1bf67df0c84bd0d6e6a73ff/metsrw/mets.py#L579-L589 |
artefactual-labs/mets-reader-writer | metsrw/validate.py | get_schematron | 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... | python | 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... | [
"def",
"get_schematron",
"(",
"sct_path",
")",
":",
"sct_path",
"=",
"_get_file_path",
"(",
"sct_path",
")",
"parser",
"=",
"etree",
".",
"XMLParser",
"(",
"remove_blank_text",
"=",
"True",
")",
"sct_doc",
"=",
"etree",
".",
"parse",
"(",
"sct_path",
",",
... | Return an lxml ``isoschematron.Schematron()`` instance using the
schematron file at ``sct_path``. | [
"Return",
"an",
"lxml",
"isoschematron",
".",
"Schematron",
"()",
"instance",
"using",
"the",
"schematron",
"file",
"at",
"sct_path",
"."
] | train | https://github.com/artefactual-labs/mets-reader-writer/blob/d95939cabdfdc25cb1bf67df0c84bd0d6e6a73ff/metsrw/validate.py#L29-L36 |
artefactual-labs/mets-reader-writer | metsrw/validate.py | validate | 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... | python | 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... | [
"def",
"validate",
"(",
"mets_doc",
",",
"xmlschema",
"=",
"METS_XSD_PATH",
",",
"schematron",
"=",
"AM_SCT_PATH",
")",
":",
"is_xsd_valid",
",",
"xsd_error_log",
"=",
"xsd_validate",
"(",
"mets_doc",
",",
"xmlschema",
"=",
"xmlschema",
")",
"is_sct_valid",
",",... | 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. | [
"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",
... | train | https://github.com/artefactual-labs/mets-reader-writer/blob/d95939cabdfdc25cb1bf67df0c84bd0d6e6a73ff/metsrw/validate.py#L39-L54 |
artefactual-labs/mets-reader-writer | metsrw/validate.py | get_xmlschema | 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 ... | python | 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 ... | [
"def",
"get_xmlschema",
"(",
"xmlschema",
",",
"mets_doc",
")",
":",
"xsd_path",
"=",
"_get_file_path",
"(",
"xmlschema",
")",
"xmlschema",
"=",
"etree",
".",
"parse",
"(",
"xsd_path",
")",
"schema_locations",
"=",
"set",
"(",
"mets_doc",
".",
"xpath",
"(",
... | 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... | [
"Return",
"a",
"class",
"::",
"lxml",
".",
"etree",
".",
"XMLSchema",
"instance",
"given",
"the",
"path",
"to",
"the",
"XMLSchema",
"(",
".",
"xsd",
")",
"file",
"in",
"xmlschema",
"and",
"the",
"class",
"::",
"lxml",
".",
"etree",
".",
"_ElementTree",
... | train | https://github.com/artefactual-labs/mets-reader-writer/blob/d95939cabdfdc25cb1bf67df0c84bd0d6e6a73ff/metsrw/validate.py#L57-L88 |
artefactual-labs/mets-reader-writer | metsrw/validate.py | schematron_validate | 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... | python | 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... | [
"def",
"schematron_validate",
"(",
"mets_doc",
",",
"schematron",
"=",
"AM_SCT_PATH",
")",
":",
"if",
"isinstance",
"(",
"schematron",
",",
"six",
".",
"string_types",
")",
":",
"schematron",
"=",
"get_schematron",
"(",
"schematron",
")",
"is_valid",
"=",
"sch... | Validate a METS file using a schematron schema. Return a boolean
indicating validity and a report as an ``lxml.ElementTree`` instance. | [
"Validate",
"a",
"METS",
"file",
"using",
"a",
"schematron",
"schema",
".",
"Return",
"a",
"boolean",
"indicating",
"validity",
"and",
"a",
"report",
"as",
"an",
"lxml",
".",
"ElementTree",
"instance",
"."
] | train | https://github.com/artefactual-labs/mets-reader-writer/blob/d95939cabdfdc25cb1bf67df0c84bd0d6e6a73ff/metsrw/validate.py#L98-L106 |
artefactual-labs/mets-reader-writer | metsrw/validate.py | sct_report_string | 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",... | python | 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",... | [
"def",
"sct_report_string",
"(",
"report",
")",
":",
"ret",
"=",
"[",
"]",
"namespaces",
"=",
"{",
"\"svrl\"",
":",
"\"http://purl.oclc.org/dsdl/svrl\"",
"}",
"for",
"index",
",",
"failed_assert_el",
"in",
"enumerate",
"(",
"report",
".",
"findall",
"(",
"\"sv... | Return a human-readable string representation of the error report
returned by lxml's schematron validator. | [
"Return",
"a",
"human",
"-",
"readable",
"string",
"representation",
"of",
"the",
"error",
"report",
"returned",
"by",
"lxml",
"s",
"schematron",
"validator",
"."
] | train | https://github.com/artefactual-labs/mets-reader-writer/blob/d95939cabdfdc25cb1bf67df0c84bd0d6e6a73ff/metsrw/validate.py#L109-L127 |
artefactual-labs/mets-reader-writer | metsrw/validate.py | xsd_error_log_string | 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"))
... | python | 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"))
... | [
"def",
"xsd_error_log_string",
"(",
"xsd_error_log",
")",
":",
"ret",
"=",
"[",
"]",
"for",
"error",
"in",
"xsd_error_log",
":",
"ret",
".",
"append",
"(",
"\"ERROR ON LINE {}: {}\"",
".",
"format",
"(",
"error",
".",
"line",
",",
"error",
".",
"message",
... | Return a human-readable string representation of the error log
returned by lxml's XMLSchema validator. | [
"Return",
"a",
"human",
"-",
"readable",
"string",
"representation",
"of",
"the",
"error",
"log",
"returned",
"by",
"lxml",
"s",
"XMLSchema",
"validator",
"."
] | train | https://github.com/artefactual-labs/mets-reader-writer/blob/d95939cabdfdc25cb1bf67df0c84bd0d6e6a73ff/metsrw/validate.py#L130-L139 |
djk2/django-popup-view-field | django_popup_view_field/fields.py | PopupViewFieldMixin.validate_arguments | 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... | python | 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... | [
"def",
"validate_arguments",
"(",
"self",
",",
"view_class",
",",
"kwargs",
")",
":",
"# Check view_class inherit from django View",
"if",
"not",
"issubclass",
"(",
"view_class",
",",
"View",
")",
":",
"raise",
"PopupViewIsNotSubclassView",
"(",
")",
"self",
".",
... | view_class : View Class used to render content popup dialog
view_class must be subclass of django.views.generic.View | [
"view_class",
":",
"View",
"Class",
"used",
"to",
"render",
"content",
"popup",
"dialog",
"view_class",
"must",
"be",
"subclass",
"of",
"django",
".",
"views",
".",
"generic",
".",
"View"
] | train | https://github.com/djk2/django-popup-view-field/blob/f144e7acd221fab2a7f4867dd1430a8b1c941f90/django_popup_view_field/fields.py#L17-L36 |
djk2/django-popup-view-field | django_popup_view_field/widgets.py | PopupViewWidget.get_view_url | 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
) | python | 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
) | [
"def",
"get_view_url",
"(",
"self",
")",
":",
"url",
"=",
"reverse",
"(",
"\"django_popup_view_field:get_popup_view\"",
",",
"args",
"=",
"(",
"self",
".",
"view_class_name",
",",
")",
")",
"return",
"\"{url}?{cd}\"",
".",
"format",
"(",
"url",
"=",
"url",
"... | Return url for ajax to view for render dialog content | [
"Return",
"url",
"for",
"ajax",
"to",
"view",
"for",
"render",
"dialog",
"content"
] | train | https://github.com/djk2/django-popup-view-field/blob/f144e7acd221fab2a7f4867dd1430a8b1c941f90/django_popup_view_field/widgets.py#L34-L40 |
sivy/pystatsd | pystatsd/server.py | Server.on_timer | 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() | python | 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() | [
"def",
"on_timer",
"(",
"self",
")",
":",
"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. | [
"Executes",
"flush",
"()",
".",
"Ignores",
"any",
"errors",
"to",
"make",
"sure",
"one",
"exception",
"doesn",
"t",
"halt",
"the",
"whole",
"flushing",
"process",
"."
] | train | https://github.com/sivy/pystatsd/blob/69e362654c37df28582b12b964901334326620a7/pystatsd/server.py#L148-L156 |
sivy/pystatsd | pystatsd/statsd.py | Client.timing_since | 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... | python | 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... | [
"def",
"timing_since",
"(",
"self",
",",
"stat",
",",
"start",
",",
"sample_rate",
"=",
"1",
")",
":",
"self",
".",
"timing",
"(",
"stat",
",",
"int",
"(",
"(",
"time",
".",
"time",
"(",
")",
"-",
"start",
")",
"*",
"1000000",
")",
",",
"sample_r... | 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) | [
"Log",
"timing",
"information",
"as",
"the",
"number",
"of",
"microseconds",
"since",
"the",
"provided",
"time",
"float",
">>>",
"start",
"=",
"time",
".",
"time",
"()",
">>>",
"#",
"do",
"stuff",
">>>",
"statsd_client",
".",
"timing_since",
"(",
"some",
"... | train | https://github.com/sivy/pystatsd/blob/69e362654c37df28582b12b964901334326620a7/pystatsd/statsd.py#L32-L39 |
sivy/pystatsd | pystatsd/statsd.py | Client.timing | 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) | python | 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) | [
"def",
"timing",
"(",
"self",
",",
"stat",
",",
"time",
",",
"sample_rate",
"=",
"1",
")",
":",
"stats",
"=",
"{",
"stat",
":",
"\"%f|ms\"",
"%",
"time",
"}",
"self",
".",
"send",
"(",
"stats",
",",
"sample_rate",
")"
] | Log timing information for a single stat
>>> statsd_client.timing('some.time',500) | [
"Log",
"timing",
"information",
"for",
"a",
"single",
"stat",
">>>",
"statsd_client",
".",
"timing",
"(",
"some",
".",
"time",
"500",
")"
] | train | https://github.com/sivy/pystatsd/blob/69e362654c37df28582b12b964901334326620a7/pystatsd/statsd.py#L41-L47 |
sivy/pystatsd | pystatsd/statsd.py | Client.gauge | 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) | python | 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) | [
"def",
"gauge",
"(",
"self",
",",
"stat",
",",
"value",
",",
"sample_rate",
"=",
"1",
")",
":",
"stats",
"=",
"{",
"stat",
":",
"\"%f|g\"",
"%",
"value",
"}",
"self",
".",
"send",
"(",
"stats",
",",
"sample_rate",
")"
] | Log gauge information for a single stat
>>> statsd_client.gauge('some.gauge',42) | [
"Log",
"gauge",
"information",
"for",
"a",
"single",
"stat",
">>>",
"statsd_client",
".",
"gauge",
"(",
"some",
".",
"gauge",
"42",
")"
] | train | https://github.com/sivy/pystatsd/blob/69e362654c37df28582b12b964901334326620a7/pystatsd/statsd.py#L49-L55 |
sivy/pystatsd | pystatsd/statsd.py | Client.update_stats | 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... | python | 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... | [
"def",
"update_stats",
"(",
"self",
",",
"stats",
",",
"delta",
",",
"sample_rate",
"=",
"1",
")",
":",
"if",
"not",
"isinstance",
"(",
"stats",
",",
"list",
")",
":",
"stats",
"=",
"[",
"stats",
"]",
"data",
"=",
"dict",
"(",
"(",
"stat",
",",
"... | Updates one or more stats counters by arbitrary amounts
>>> statsd_client.update_stats('some.int',10) | [
"Updates",
"one",
"or",
"more",
"stats",
"counters",
"by",
"arbitrary",
"amounts",
">>>",
"statsd_client",
".",
"update_stats",
"(",
"some",
".",
"int",
"10",
")"
] | train | https://github.com/sivy/pystatsd/blob/69e362654c37df28582b12b964901334326620a7/pystatsd/statsd.py#L78-L87 |
sivy/pystatsd | pystatsd/statsd.py | Client.send | 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
... | python | 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
... | [
"def",
"send",
"(",
"self",
",",
"data",
",",
"sample_rate",
"=",
"1",
")",
":",
"if",
"self",
".",
"prefix",
":",
"data",
"=",
"dict",
"(",
"(",
"\".\"",
".",
"join",
"(",
"(",
"self",
".",
"prefix",
",",
"stat",
")",
")",
",",
"value",
")",
... | Squirt the metrics over UDP | [
"Squirt",
"the",
"metrics",
"over",
"UDP"
] | train | https://github.com/sivy/pystatsd/blob/69e362654c37df28582b12b964901334326620a7/pystatsd/statsd.py#L89-L110 |
sivy/pystatsd | pystatsd/daemon.py | Daemon.start | 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... | python | 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... | [
"def",
"start",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kw",
")",
":",
"pid",
"=",
"None",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"self",
".",
"pidfile",
")",
":",
"with",
"open",
"(",
"self",
".",
"pidfile",
",",
"'r'",
")",
"as... | Start the daemon. | [
"Start",
"the",
"daemon",
"."
] | train | https://github.com/sivy/pystatsd/blob/69e362654c37df28582b12b964901334326620a7/pystatsd/daemon.py#L68-L81 |
sivy/pystatsd | pystatsd/daemon.py | Daemon.stop | 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... | python | 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... | [
"def",
"stop",
"(",
"self",
")",
":",
"pid",
"=",
"None",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"self",
".",
"pidfile",
")",
":",
"with",
"open",
"(",
"self",
".",
"pidfile",
",",
"'r'",
")",
"as",
"fp",
":",
"pid",
"=",
"int",
"(",
"f... | Stop the daemon. | [
"Stop",
"the",
"daemon",
"."
] | train | https://github.com/sivy/pystatsd/blob/69e362654c37df28582b12b964901334326620a7/pystatsd/daemon.py#L83-L106 |
sivy/pystatsd | pystatsd/daemon.py | Daemon.restart | def restart(self, *args, **kw):
"""Restart the daemon."""
self.stop()
self.start(*args, **kw) | python | def restart(self, *args, **kw):
"""Restart the daemon."""
self.stop()
self.start(*args, **kw) | [
"def",
"restart",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kw",
")",
":",
"self",
".",
"stop",
"(",
")",
"self",
".",
"start",
"(",
"*",
"args",
",",
"*",
"*",
"kw",
")"
] | Restart the daemon. | [
"Restart",
"the",
"daemon",
"."
] | train | https://github.com/sivy/pystatsd/blob/69e362654c37df28582b12b964901334326620a7/pystatsd/daemon.py#L108-L111 |
F5Networks/f5-icontrol-rest-python | icontrol/authtoken.py | iControlRESTTokenAuth.get_auth_providers | 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... | python | 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... | [
"def",
"get_auth_providers",
"(",
"self",
",",
"netloc",
")",
":",
"url",
"=",
"\"https://%s/info/system?null\"",
"%",
"(",
"netloc",
")",
"response",
"=",
"requests",
".",
"get",
"(",
"url",
",",
"verify",
"=",
"self",
".",
"verify",
")",
"if",
"not",
"... | 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... | [
"BIG",
"-",
"IQ",
"specific",
"query",
"for",
"auth",
"providers"
] | train | https://github.com/F5Networks/f5-icontrol-rest-python/blob/34bb916299f4a00829352e7eb9818589408fa35a/icontrol/authtoken.py#L85-L108 |
F5Networks/f5-icontrol-rest-python | icontrol/authtoken.py | iControlRESTTokenAuth.get_new_token | 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
... | python | 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
... | [
"def",
"get_new_token",
"(",
"self",
",",
"netloc",
")",
":",
"login_body",
"=",
"{",
"'username'",
":",
"self",
".",
"username",
",",
"'password'",
":",
"self",
".",
"password",
",",
"}",
"if",
"self",
".",
"auth_provider",
":",
"if",
"self",
".",
"au... | 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... | [
"Get",
"a",
"new",
"token",
"from",
"BIG",
"-",
"IP",
"and",
"store",
"it",
"internally",
"."
] | train | https://github.com/F5Networks/f5-icontrol-rest-python/blob/34bb916299f4a00829352e7eb9818589408fa35a/icontrol/authtoken.py#L110-L192 |
F5Networks/f5-icontrol-rest-python | icontrol/session.py | generate_bigip_uri | 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... | python | 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... | [
"def",
"generate_bigip_uri",
"(",
"base_uri",
",",
"partition",
",",
"name",
",",
"sub_path",
",",
"suffix",
",",
"*",
"*",
"kwargs",
")",
":",
"_validate_uri_parts",
"(",
"base_uri",
",",
"partition",
",",
"name",
",",
"sub_path",
",",
"suffix",
",",
"*",... | (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... | [
"(",
"str",
"str",
"str",
")",
"--",
">",
"str"
] | train | https://github.com/F5Networks/f5-icontrol-rest-python/blob/34bb916299f4a00829352e7eb9818589408fa35a/icontrol/session.py#L191-L240 |
F5Networks/f5-icontrol-rest-python | icontrol/session.py | decorate_HTTP_verb_method | 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 ... | python | 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 ... | [
"def",
"decorate_HTTP_verb_method",
"(",
"method",
")",
":",
"@",
"functools",
".",
"wraps",
"(",
"method",
")",
"def",
"wrapper",
"(",
"self",
",",
"RIC_base_uri",
",",
"*",
"*",
"kwargs",
")",
":",
"partition",
"=",
"kwargs",
".",
"pop",
"(",
"'partiti... | 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`.
... | [
"Prepare",
"and",
"Post",
"-",
"Process",
"HTTP",
"VERB",
"method",
"for",
"BigIP",
"-",
"RESTServer",
"request",
"."
] | train | https://github.com/F5Networks/f5-icontrol-rest-python/blob/34bb916299f4a00829352e7eb9818589408fa35a/icontrol/session.py#L243-L297 |
F5Networks/f5-icontrol-rest-python | icontrol/session.py | _unique_resource_identifier_from_kwargs | 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... | python | 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... | [
"def",
"_unique_resource_identifier_from_kwargs",
"(",
"*",
"*",
"kwargs",
")",
":",
"name",
"=",
"kwargs",
".",
"pop",
"(",
"'name'",
",",
"''",
")",
"uuid",
"=",
"kwargs",
".",
"pop",
"(",
"'uuid'",
",",
"''",
")",
"id",
"=",
"kwargs",
".",
"pop",
... | 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... | [
"Chooses",
"an",
"identifier",
"given",
"different",
"choices"
] | train | https://github.com/F5Networks/f5-icontrol-rest-python/blob/34bb916299f4a00829352e7eb9818589408fa35a/icontrol/session.py#L300-L341 |
F5Networks/f5-icontrol-rest-python | icontrol/session.py | iControlRESTSession.delete | 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... | python | 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... | [
"def",
"delete",
"(",
"self",
",",
"uri",
",",
"*",
"*",
"kwargs",
")",
":",
"args1",
"=",
"get_request_args",
"(",
"kwargs",
")",
"args2",
"=",
"get_send_args",
"(",
"kwargs",
")",
"req",
"=",
"requests",
".",
"Request",
"(",
"'DELETE'",
",",
"uri",
... | 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... | [
"Sends",
"a",
"HTTP",
"DELETE",
"command",
"to",
"the",
"BIGIP",
"REST",
"Server",
"."
] | train | https://github.com/F5Networks/f5-icontrol-rest-python/blob/34bb916299f4a00829352e7eb9818589408fa35a/icontrol/session.py#L474-L499 |
F5Networks/f5-icontrol-rest-python | icontrol/session.py | iControlRESTSession.append_user_agent | 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... | python | 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... | [
"def",
"append_user_agent",
"(",
"self",
",",
"user_agent",
")",
":",
"old_ua",
"=",
"self",
".",
"session",
".",
"headers",
".",
"get",
"(",
"'User-Agent'",
",",
"''",
")",
"ua",
"=",
"old_ua",
"+",
"' '",
"+",
"user_agent",
"self",
".",
"session",
".... | 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 | [
"Append",
"text",
"to",
"the",
"User",
"-",
"Agent",
"header",
"for",
"the",
"request",
"."
] | train | https://github.com/F5Networks/f5-icontrol-rest-python/blob/34bb916299f4a00829352e7eb9818589408fa35a/icontrol/session.py#L623-L634 |
crgwbr/asymmetric-jwt-auth | src/asymmetric_jwt_auth/models.py | validate_public_key | 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... | python | 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... | [
"def",
"validate_public_key",
"(",
"value",
")",
":",
"is_valid",
"=",
"False",
"exc",
"=",
"None",
"for",
"load",
"in",
"(",
"load_pem_public_key",
",",
"load_ssh_public_key",
")",
":",
"if",
"not",
"is_valid",
":",
"try",
":",
"load",
"(",
"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``. | [
"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",
"."
] | train | https://github.com/crgwbr/asymmetric-jwt-auth/blob/eae1a6474b6141edce4d6be2dc1746e18bbf5318/src/asymmetric_jwt_auth/models.py#L8-L25 |
kenneth-reitz/pyandoc | pandoc/core.py | Document._register_formats | 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... | python | 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... | [
"def",
"_register_formats",
"(",
"cls",
")",
":",
"for",
"fmt",
"in",
"cls",
".",
"OUTPUT_FORMATS",
":",
"clean_fmt",
"=",
"fmt",
".",
"replace",
"(",
"'+'",
",",
"'_'",
")",
"setattr",
"(",
"cls",
",",
"clean_fmt",
",",
"property",
"(",
"(",
"lambda",... | Adds format properties. | [
"Adds",
"format",
"properties",
"."
] | train | https://github.com/kenneth-reitz/pyandoc/blob/4417ee34e85c88c874f0a5ae93bc54b0f5d93af0/pandoc/core.py#L73-L79 |
kenneth-reitz/pyandoc | pandoc/core.py | Document.to_file | 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... | python | 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... | [
"def",
"to_file",
"(",
"self",
",",
"output_filename",
")",
":",
"temp_file",
"=",
"NamedTemporaryFile",
"(",
"mode",
"=",
"\"w\"",
",",
"suffix",
"=",
"\".md\"",
",",
"delete",
"=",
"False",
")",
"temp_file",
".",
"write",
"(",
"self",
".",
"_content",
... | 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 | [
"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"
] | train | https://github.com/kenneth-reitz/pyandoc/blob/4417ee34e85c88c874f0a5ae93bc54b0f5d93af0/pandoc/core.py#L100-L123 |
crgwbr/asymmetric-jwt-auth | src/asymmetric_jwt_auth/token.py | sign | 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.
... | python | 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.
... | [
"def",
"sign",
"(",
"username",
",",
"private_key",
",",
"generate_nonce",
"=",
"None",
",",
"iat",
"=",
"None",
",",
"algorithm",
"=",
"DEFAULT_ALGORITHM",
")",
":",
"iat",
"=",
"iat",
"if",
"iat",
"else",
"time",
".",
"time",
"(",
")",
"if",
"not",
... | 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... | [
"Create",
"a",
"signed",
"JWT",
"using",
"the",
"given",
"username",
"and",
"RSA",
"private",
"key",
"."
] | train | https://github.com/crgwbr/asymmetric-jwt-auth/blob/eae1a6474b6141edce4d6be2dc1746e18bbf5318/src/asymmetric_jwt_auth/token.py#L16-L41 |
crgwbr/asymmetric-jwt-auth | src/asymmetric_jwt_auth/token.py | get_claimed_username | 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... | python | 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... | [
"def",
"get_claimed_username",
"(",
"token",
")",
":",
"unverified_data",
"=",
"jwt",
".",
"decode",
"(",
"token",
",",
"options",
"=",
"{",
"'verify_signature'",
":",
"False",
"}",
")",
"if",
"'username'",
"not",
"in",
"unverified_data",
":",
"return",
"Non... | 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 | [
"Given",
"a",
"JWT",
"get",
"the",
"username",
"that",
"it",
"is",
"claiming",
"to",
"be",
"without",
"verifying",
"that",
"the",
"signature",
"is",
"valid",
"."
] | train | https://github.com/crgwbr/asymmetric-jwt-auth/blob/eae1a6474b6141edce4d6be2dc1746e18bbf5318/src/asymmetric_jwt_auth/token.py#L44-L57 |
crgwbr/asymmetric-jwt-auth | src/asymmetric_jwt_auth/token.py | verify | 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... | python | 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... | [
"def",
"verify",
"(",
"token",
",",
"public_key",
",",
"validate_nonce",
"=",
"None",
",",
"algorithms",
"=",
"[",
"DEFAULT_ALGORITHM",
"]",
")",
":",
"try",
":",
"token_data",
"=",
"jwt",
".",
"decode",
"(",
"token",
",",
"public_key",
",",
"algorithms",
... | 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'... | [
"Verify",
"the",
"validity",
"of",
"the",
"given",
"JWT",
"using",
"the",
"given",
"public",
"key",
"."
] | train | https://github.com/crgwbr/asymmetric-jwt-auth/blob/eae1a6474b6141edce4d6be2dc1746e18bbf5318/src/asymmetric_jwt_auth/token.py#L60-L96 |
crgwbr/asymmetric-jwt-auth | src/asymmetric_jwt_auth/middleware.py | JWTAuthMiddleware.log_used_nonce | 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: ... | python | 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: ... | [
"def",
"log_used_nonce",
"(",
"self",
",",
"username",
",",
"iat",
",",
"nonce",
")",
":",
"# TODO: Figure out some way to do this in a thread-safe manner. It'd be better to use",
"# a Redis Set or something, but we don't necessarily want to be tightly coupled to",
"# Redis either since ... | 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. | [
"Log",
"a",
"nonce",
"as",
"being",
"used",
"and",
"therefore",
"henceforth",
"invalid",
"."
] | train | https://github.com/crgwbr/asymmetric-jwt-auth/blob/eae1a6474b6141edce4d6be2dc1746e18bbf5318/src/asymmetric_jwt_auth/middleware.py#L29-L43 |
crgwbr/asymmetric-jwt-auth | src/asymmetric_jwt_auth/middleware.py | JWTAuthMiddleware.validate_nonce | 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 ... | python | 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 ... | [
"def",
"validate_nonce",
"(",
"self",
",",
"username",
",",
"iat",
",",
"nonce",
")",
":",
"key",
"=",
"self",
".",
"create_nonce_key",
"(",
"username",
",",
"iat",
")",
"used",
"=",
"cache",
".",
"get",
"(",
"key",
",",
"[",
"]",
")",
"return",
"n... | 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. | [
"Confirm",
"that",
"the",
"given",
"nonce",
"hasn",
"t",
"already",
"been",
"used",
"."
] | train | https://github.com/crgwbr/asymmetric-jwt-auth/blob/eae1a6474b6141edce4d6be2dc1746e18bbf5318/src/asymmetric_jwt_auth/middleware.py#L46-L57 |
crgwbr/asymmetric-jwt-auth | src/asymmetric_jwt_auth/middleware.py | JWTAuthMiddleware.process_request | 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
... | python | 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
... | [
"def",
"process_request",
"(",
"self",
",",
"request",
")",
":",
"if",
"'HTTP_AUTHORIZATION'",
"not",
"in",
"request",
".",
"META",
":",
"return",
"try",
":",
"method",
",",
"claim",
"=",
"request",
".",
"META",
"[",
"'HTTP_AUTHORIZATION'",
"]",
".",
"spli... | 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... | [
"Process",
"a",
"Django",
"request",
"and",
"authenticate",
"users",
"."
] | train | https://github.com/crgwbr/asymmetric-jwt-auth/blob/eae1a6474b6141edce4d6be2dc1746e18bbf5318/src/asymmetric_jwt_auth/middleware.py#L60-L101 |
crgwbr/asymmetric-jwt-auth | src/asymmetric_jwt_auth/__init__.py | generate_key_pair | 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... | python | 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... | [
"def",
"generate_key_pair",
"(",
"size",
"=",
"2048",
",",
"public_exponent",
"=",
"65537",
",",
"as_string",
"=",
"True",
")",
":",
"private",
"=",
"rsa",
".",
"generate_private_key",
"(",
"public_exponent",
"=",
"public_exponent",
",",
"key_size",
"=",
"size... | 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... | [
"Generate",
"a",
"public",
"/",
"private",
"key",
"pair",
"."
] | train | https://github.com/crgwbr/asymmetric-jwt-auth/blob/eae1a6474b6141edce4d6be2dc1746e18bbf5318/src/asymmetric_jwt_auth/__init__.py#L21-L49 |
crgwbr/asymmetric-jwt-auth | src/asymmetric_jwt_auth/__init__.py | load_private_key | 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.... | python | 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.... | [
"def",
"load_private_key",
"(",
"key_file",
",",
"key_password",
"=",
"None",
")",
":",
"key_file",
"=",
"os",
".",
"path",
".",
"expanduser",
"(",
"key_file",
")",
"key_file",
"=",
"os",
".",
"path",
".",
"abspath",
"(",
"key_file",
")",
"if",
"not",
... | 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> | [
"Load",
"a",
"private",
"key",
"from",
"disk",
"."
] | train | https://github.com/crgwbr/asymmetric-jwt-auth/blob/eae1a6474b6141edce4d6be2dc1746e18bbf5318/src/asymmetric_jwt_auth/__init__.py#L52-L69 |
crgwbr/asymmetric-jwt-auth | src/asymmetric_jwt_auth/__init__.py | decrypt_key | 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... | python | 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... | [
"def",
"decrypt_key",
"(",
"key",
",",
"password",
")",
":",
"private",
"=",
"serialization",
".",
"load_pem_private_key",
"(",
"key",
",",
"password",
"=",
"password",
",",
"backend",
"=",
"default_backend",
"(",
")",
")",
"return",
"private",
".",
"private... | 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. | [
"Decrypt",
"an",
"encrypted",
"private",
"key",
"."
] | train | https://github.com/crgwbr/asymmetric-jwt-auth/blob/eae1a6474b6141edce4d6be2dc1746e18bbf5318/src/asymmetric_jwt_auth/__init__.py#L72-L81 |
crgwbr/asymmetric-jwt-auth | src/asymmetric_jwt_auth/__init__.py | create_auth_header | 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... | python | 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... | [
"def",
"create_auth_header",
"(",
"username",
",",
"key",
"=",
"None",
",",
"key_file",
"=",
"\"~/.ssh/id_rsa\"",
",",
"key_password",
"=",
"None",
")",
":",
"if",
"not",
"key",
":",
"key",
"=",
"load_private_key",
"(",
"key_file",
",",
"key_password",
")",
... | 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... | [
"Create",
"an",
"HTTP",
"Authorization",
"header",
"using",
"a",
"private",
"key",
"file",
"."
] | train | https://github.com/crgwbr/asymmetric-jwt-auth/blob/eae1a6474b6141edce4d6be2dc1746e18bbf5318/src/asymmetric_jwt_auth/__init__.py#L84-L99 |
peeringdb/peeringdb-py | peeringdb/__init__.py | _config_logs | 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... | python | 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... | [
"def",
"_config_logs",
"(",
"lvl",
"=",
"None",
",",
"name",
"=",
"None",
")",
":",
"# print('_config_log', 'from %s' %name if name else '')",
"FORMAT",
"=",
"'%(message)s'",
"# maybe better for log files",
"# FORMAT='[%(levelname)s]:%(message)s',",
"# Reset handlers",
"for",
... | Set up or change logging configuration.
_config_logs() => idempotent setup;
_config_logs(L) => change log level | [
"Set",
"up",
"or",
"change",
"logging",
"configuration",
"."
] | train | https://github.com/peeringdb/peeringdb-py/blob/cf2060a1d5ef879a01cf849e54b7756909ab2661/peeringdb/__init__.py#L12-L37 |
peeringdb/peeringdb-py | peeringdb/whois.py | WhoisFormat.mk_set_headers | 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... | python | 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... | [
"def",
"mk_set_headers",
"(",
"self",
",",
"data",
",",
"columns",
")",
":",
"columns",
"=",
"tuple",
"(",
"columns",
")",
"lens",
"=",
"[",
"]",
"for",
"key",
"in",
"columns",
":",
"value_len",
"=",
"max",
"(",
"len",
"(",
"str",
"(",
"each",
".",... | figure out sizes and create header fmt | [
"figure",
"out",
"sizes",
"and",
"create",
"header",
"fmt"
] | train | https://github.com/peeringdb/peeringdb-py/blob/cf2060a1d5ef879a01cf849e54b7756909ab2661/peeringdb/whois.py#L19-L30 |
peeringdb/peeringdb-py | peeringdb/whois.py | WhoisFormat._get_name | 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() | python | 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() | [
"def",
"_get_name",
"(",
"self",
",",
"key",
")",
":",
"if",
"key",
"in",
"self",
".",
"display_names",
":",
"return",
"self",
".",
"display_names",
"[",
"key",
"]",
"return",
"key",
".",
"capitalize",
"(",
")"
] | get display name for a key, or mangle for display | [
"get",
"display",
"name",
"for",
"a",
"key",
"or",
"mangle",
"for",
"display"
] | train | https://github.com/peeringdb/peeringdb-py/blob/cf2060a1d5ef879a01cf849e54b7756909ab2661/peeringdb/whois.py#L32-L37 |
peeringdb/peeringdb-py | peeringdb/whois.py | WhoisFormat.display_set | 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... | python | 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... | [
"def",
"display_set",
"(",
"self",
",",
"typ",
",",
"data",
",",
"columns",
")",
":",
"self",
".",
"display_section",
"(",
"\"%s (%d)\"",
"%",
"(",
"self",
".",
"_get_name",
"(",
"typ",
")",
",",
"len",
"(",
"data",
")",
")",
")",
"headers",
"=",
"... | display a list of dicts | [
"display",
"a",
"list",
"of",
"dicts"
] | train | https://github.com/peeringdb/peeringdb-py/blob/cf2060a1d5ef879a01cf849e54b7756909ab2661/peeringdb/whois.py#L56-L67 |
peeringdb/peeringdb-py | peeringdb/whois.py | WhoisFormat._print | def _print(self, *args):
""" internal print to self.fobj """
string = u" ".join(args) + '\n'
self.fobj.write(string) | python | def _print(self, *args):
""" internal print to self.fobj """
string = u" ".join(args) + '\n'
self.fobj.write(string) | [
"def",
"_print",
"(",
"self",
",",
"*",
"args",
")",
":",
"string",
"=",
"u\" \"",
".",
"join",
"(",
"args",
")",
"+",
"'\\n'",
"self",
".",
"fobj",
".",
"write",
"(",
"string",
")"
] | internal print to self.fobj | [
"internal",
"print",
"to",
"self",
".",
"fobj"
] | train | https://github.com/peeringdb/peeringdb-py/blob/cf2060a1d5ef879a01cf849e54b7756909ab2661/peeringdb/whois.py#L152-L155 |
peeringdb/peeringdb-py | peeringdb/whois.py | WhoisFormat.display | 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("\... | python | 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("\... | [
"def",
"display",
"(",
"self",
",",
"typ",
",",
"data",
")",
":",
"if",
"hasattr",
"(",
"self",
",",
"'print_'",
"+",
"typ",
")",
":",
"getattr",
"(",
"self",
",",
"'print_'",
"+",
"typ",
")",
"(",
"data",
")",
"elif",
"not",
"data",
":",
"self",... | display section of typ with data | [
"display",
"section",
"of",
"typ",
"with",
"data"
] | train | https://github.com/peeringdb/peeringdb-py/blob/cf2060a1d5ef879a01cf849e54b7756909ab2661/peeringdb/whois.py#L161-L184 |
peeringdb/peeringdb-py | peeringdb/commands.py | _handler | 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) | python | 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) | [
"def",
"_handler",
"(",
"func",
")",
":",
"def",
"_wrapped",
"(",
"*",
"a",
",",
"*",
"*",
"k",
")",
":",
"r",
"=",
"func",
"(",
"*",
"a",
",",
"*",
"*",
"k",
")",
"if",
"r",
"is",
"None",
":",
"r",
"=",
"0",
"return",
"r",
"return",
"sta... | Decorate a command handler | [
"Decorate",
"a",
"command",
"handler"
] | train | https://github.com/peeringdb/peeringdb-py/blob/cf2060a1d5ef879a01cf849e54b7756909ab2661/peeringdb/commands.py#L16-L24 |
peeringdb/peeringdb-py | peeringdb/commands.py | add_subcommands | 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(... | python | 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(... | [
"def",
"add_subcommands",
"(",
"parser",
",",
"commands",
")",
":",
"subps",
"=",
"parser",
".",
"add_subparsers",
"(",
")",
"for",
"cmd",
",",
"cls",
"in",
"commands",
":",
"subp",
"=",
"subps",
".",
"add_parser",
"(",
"cmd",
",",
"help",
"=",
"cls",
... | Add commands to a parser | [
"Add",
"commands",
"to",
"a",
"parser"
] | train | https://github.com/peeringdb/peeringdb-py/blob/cf2060a1d5ef879a01cf849e54b7756909ab2661/peeringdb/commands.py#L27-L37 |
peeringdb/peeringdb-py | peeringdb/backend.py | reftag_to_cls | 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... | python | 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... | [
"def",
"reftag_to_cls",
"(",
"fn",
")",
":",
"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 | [
"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"
] | train | https://github.com/peeringdb/peeringdb-py/blob/cf2060a1d5ef879a01cf849e54b7756909ab2661/peeringdb/backend.py#L8-L27 |
peeringdb/peeringdb-py | peeringdb/_update.py | Updater.update | 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... | python | 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... | [
"def",
"update",
"(",
"self",
",",
"res",
",",
"pk",
",",
"depth",
"=",
"1",
",",
"since",
"=",
"None",
")",
":",
"fetch",
"=",
"lambda",
":",
"self",
".",
"_fetcher",
".",
"fetch_latest",
"(",
"res",
",",
"pk",
",",
"1",
",",
"since",
"=",
"si... | 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 | [
"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"
] | train | https://github.com/peeringdb/peeringdb-py/blob/cf2060a1d5ef879a01cf849e54b7756909ab2661/peeringdb/_update.py#L44-L51 |
peeringdb/peeringdb-py | peeringdb/_update.py | Updater.update_where | 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) | python | 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) | [
"def",
"update_where",
"(",
"self",
",",
"res",
",",
"depth",
"=",
"0",
",",
"since",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"fetch",
"=",
"lambda",
":",
"self",
".",
"_fetcher",
".",
"fetch_all_latest",
"(",
"res",
",",
"0",
",",
"kwargs"... | Like update() but uses WHERE-style args | [
"Like",
"update",
"()",
"but",
"uses",
"WHERE",
"-",
"style",
"args"
] | train | https://github.com/peeringdb/peeringdb-py/blob/cf2060a1d5ef879a01cf849e54b7756909ab2661/peeringdb/_update.py#L53-L56 |
peeringdb/peeringdb-py | peeringdb/_update.py | Updater.update_all | 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... | python | 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... | [
"def",
"update_all",
"(",
"self",
",",
"rs",
"=",
"None",
",",
"since",
"=",
"None",
")",
":",
"self",
".",
"_log",
".",
"info",
"(",
"\"Updating resources: %s\"",
",",
"' '",
".",
"join",
"(",
"r",
".",
"tag",
"for",
"r",
"in",
"rs",
")",
")",
"... | Sync all objects for the relations rs (if None, sync all resources) | [
"Sync",
"all",
"objects",
"for",
"the",
"relations",
"rs",
"(",
"if",
"None",
"sync",
"all",
"resources",
")"
] | train | https://github.com/peeringdb/peeringdb-py/blob/cf2060a1d5ef879a01cf849e54b7756909ab2661/peeringdb/_update.py#L58-L66 |
peeringdb/peeringdb-py | peeringdb/_update.py | UpdateContext.get_task | 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) | python | 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) | [
"def",
"get_task",
"(",
"self",
",",
"key",
")",
":",
"res",
",",
"pk",
"=",
"key",
"jobs",
",",
"lock",
"=",
"self",
".",
"_jobs",
"with",
"lock",
":",
"return",
"jobs",
"[",
"res",
"]",
".",
"get",
"(",
"pk",
")"
] | Get a scheduled task, or none | [
"Get",
"a",
"scheduled",
"task",
"or",
"none"
] | train | https://github.com/peeringdb/peeringdb-py/blob/cf2060a1d5ef879a01cf849e54b7756909ab2661/peeringdb/_update.py#L121-L126 |
peeringdb/peeringdb-py | peeringdb/_update.py | UpdateContext.set_job | 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... | python | 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... | [
"def",
"set_job",
"(",
"self",
",",
"key",
",",
"func",
",",
"args",
")",
":",
"res",
",",
"pk",
"=",
"key",
"jobs",
",",
"lock",
"=",
"self",
".",
"_jobs",
"task",
"=",
"_tasks",
".",
"UpdateTask",
"(",
"func",
"(",
"*",
"args",
")",
",",
"key... | Get a scheduled task or set if none exists.
Returns:
- task coroutine/continuation | [
"Get",
"a",
"scheduled",
"task",
"or",
"set",
"if",
"none",
"exists",
"."
] | train | https://github.com/peeringdb/peeringdb-py/blob/cf2060a1d5ef879a01cf849e54b7756909ab2661/peeringdb/_update.py#L128-L148 |
peeringdb/peeringdb-py | peeringdb/_update.py | UpdateContext.pending_tasks | def pending_tasks(self, res):
"Synchronized access to tasks"
jobs, lock = self._jobs
with lock:
return jobs[res].copy() | python | def pending_tasks(self, res):
"Synchronized access to tasks"
jobs, lock = self._jobs
with lock:
return jobs[res].copy() | [
"def",
"pending_tasks",
"(",
"self",
",",
"res",
")",
":",
"jobs",
",",
"lock",
"=",
"self",
".",
"_jobs",
"with",
"lock",
":",
"return",
"jobs",
"[",
"res",
"]",
".",
"copy",
"(",
")"
] | Synchronized access to tasks | [
"Synchronized",
"access",
"to",
"tasks"
] | train | https://github.com/peeringdb/peeringdb-py/blob/cf2060a1d5ef879a01cf849e54b7756909ab2661/peeringdb/_update.py#L150-L154 |
peeringdb/peeringdb-py | peeringdb/_update.py | UpdateContext.fetch_and_index | 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} | python | 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} | [
"def",
"fetch_and_index",
"(",
"self",
",",
"fetch_func",
")",
":",
"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 | [
"Fetch",
"data",
"with",
"func",
"return",
"dict",
"indexed",
"by",
"ID"
] | train | https://github.com/peeringdb/peeringdb-py/blob/cf2060a1d5ef879a01cf849e54b7756909ab2661/peeringdb/_update.py#L157-L161 |
peeringdb/peeringdb-py | peeringdb/_sync.py | clean_helper | 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)
... | python | 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)
... | [
"def",
"clean_helper",
"(",
"B",
",",
"obj",
",",
"clean_func",
")",
":",
"try",
":",
"clean_func",
"(",
"obj",
")",
"except",
"B",
".",
"validation_error",
"(",
")",
"as",
"e",
":",
"# _debug.log_validation_errors(B, e, obj, k)",
"# Check if it's a uniqueness or ... | 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>) | [
"Clean",
"object",
"intercepting",
"and",
"collecting",
"any",
"missing",
"-",
"relation",
"or",
"unique",
"-",
"constraint",
"errors",
"and",
"returning",
"the",
"relevant",
"resource",
"ids",
"/",
"fields",
"."
] | train | https://github.com/peeringdb/peeringdb-py/blob/cf2060a1d5ef879a01cf849e54b7756909ab2661/peeringdb/_sync.py#L16-L33 |
peeringdb/peeringdb-py | peeringdb/_sync.py | initialize_object | 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),... | python | 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),... | [
"def",
"initialize_object",
"(",
"B",
",",
"res",
",",
"row",
")",
":",
"B",
"=",
"get_backend",
"(",
")",
"field_groups",
"=",
"FieldGroups",
"(",
"B",
".",
"get_concrete",
"(",
"res",
")",
")",
"try",
":",
"obj",
"=",
"B",
".",
"get_object",
"(",
... | Do a shallow initialization of an object
Arguments:
- row<dict>: dict of data like depth=1, i.e. many_refs are only ids | [
"Do",
"a",
"shallow",
"initialization",
"of",
"an",
"object"
] | train | https://github.com/peeringdb/peeringdb-py/blob/cf2060a1d5ef879a01cf849e54b7756909ab2661/peeringdb/_sync.py#L36-L88 |
peeringdb/peeringdb-py | peeringdb/config.py | read_config | 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... | python | 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... | [
"def",
"read_config",
"(",
"conf_dir",
"=",
"DEFAULT_CONFIG_DIR",
")",
":",
"conf_path",
"=",
"os",
".",
"path",
".",
"expanduser",
"(",
"conf_dir",
")",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"conf_path",
")",
":",
"# only throw if not default"... | Find and read config file for a directory, return None if not found. | [
"Find",
"and",
"read",
"config",
"file",
"for",
"a",
"directory",
"return",
"None",
"if",
"not",
"found",
"."
] | train | https://github.com/peeringdb/peeringdb-py/blob/cf2060a1d5ef879a01cf849e54b7756909ab2661/peeringdb/config.py#L59-L68 |
peeringdb/peeringdb-py | peeringdb/config.py | load_config | 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... | python | 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... | [
"def",
"load_config",
"(",
"conf_dir",
"=",
"DEFAULT_CONFIG_DIR",
",",
"schema",
"=",
"CLIENT_SCHEMA",
")",
":",
"data",
"=",
"default_config",
"(",
"schema",
")",
"config",
"=",
"read_config",
"(",
"conf_dir",
")",
"if",
"config",
":",
"recursive_update",
"("... | 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. | [
"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",
"confi... | train | https://github.com/peeringdb/peeringdb-py/blob/cf2060a1d5ef879a01cf849e54b7756909ab2661/peeringdb/config.py#L71-L81 |
peeringdb/peeringdb-py | peeringdb/config.py | detect_old | 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) | python | 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) | [
"def",
"detect_old",
"(",
"data",
")",
":",
"if",
"not",
"data",
":",
"return",
"False",
"ok",
",",
"errors",
",",
"warnings",
"=",
"_schema",
".",
"validate",
"(",
"_OLD_SCHEMA",
",",
"data",
")",
"return",
"ok",
"and",
"not",
"(",
"errors",
"or",
"... | Check for a config file with old schema | [
"Check",
"for",
"a",
"config",
"file",
"with",
"old",
"schema"
] | train | https://github.com/peeringdb/peeringdb-py/blob/cf2060a1d5ef879a01cf849e54b7756909ab2661/peeringdb/config.py#L107-L112 |
peeringdb/peeringdb-py | peeringdb/config.py | convert_old | 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 | python | 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 | [
"def",
"convert_old",
"(",
"data",
")",
":",
"ret",
"=",
"default_config",
"(",
")",
"ret",
"[",
"'sync'",
"]",
".",
"update",
"(",
"data",
".",
"get",
"(",
"'peeringdb'",
",",
"{",
"}",
")",
")",
"ret",
"[",
"'orm'",
"]",
"[",
"'database'",
"]",
... | Convert config data with old schema to new schema | [
"Convert",
"config",
"data",
"with",
"old",
"schema",
"to",
"new",
"schema"
] | train | https://github.com/peeringdb/peeringdb-py/blob/cf2060a1d5ef879a01cf849e54b7756909ab2661/peeringdb/config.py#L115-L120 |
peeringdb/peeringdb-py | peeringdb/config.py | write_config | 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,
... | python | 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,
... | [
"def",
"write_config",
"(",
"data",
",",
"conf_dir",
"=",
"DEFAULT_CONFIG_DIR",
",",
"codec",
"=",
"\"yaml\"",
",",
"backup_existing",
"=",
"False",
")",
":",
"if",
"not",
"codec",
":",
"codec",
"=",
"'yaml'",
"codec",
"=",
"munge",
".",
"get_codec",
"(",
... | 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 | [
"Write",
"config",
"values",
"to",
"a",
"file",
"."
] | train | https://github.com/peeringdb/peeringdb-py/blob/cf2060a1d5ef879a01cf849e54b7756909ab2661/peeringdb/config.py#L123-L145 |
peeringdb/peeringdb-py | peeringdb/config.py | prompt_config | 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... | python | 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... | [
"def",
"prompt_config",
"(",
"sch",
",",
"defaults",
"=",
"None",
",",
"path",
"=",
"None",
")",
":",
"out",
"=",
"{",
"}",
"for",
"name",
",",
"attr",
"in",
"sch",
".",
"attributes",
"(",
")",
":",
"fullpath",
"=",
"name",
"if",
"path",
":",
"fu... | 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") | [
"Utility",
"function",
"to",
"recursively",
"prompt",
"for",
"config",
"values"
] | train | https://github.com/peeringdb/peeringdb-py/blob/cf2060a1d5ef879a01cf849e54b7756909ab2661/peeringdb/config.py#L148-L175 |
peeringdb/peeringdb-py | peeringdb/client.py | Client.fetch | 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 | python | 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 | [
"def",
"fetch",
"(",
"self",
",",
"R",
",",
"pk",
",",
"depth",
"=",
"1",
")",
":",
"d",
",",
"e",
"=",
"self",
".",
"_fetcher",
".",
"fetch",
"(",
"R",
",",
"pk",
",",
"depth",
")",
"if",
"e",
":",
"raise",
"e",
"return",
"d"
] | Request object from API | [
"Request",
"object",
"from",
"API"
] | train | https://github.com/peeringdb/peeringdb-py/blob/cf2060a1d5ef879a01cf849e54b7756909ab2661/peeringdb/client.py#L64-L68 |
peeringdb/peeringdb-py | peeringdb/client.py | Client.fetch_all | def fetch_all(self, R, depth=1, **kwargs):
"Request multiple objects from API"
d, e = self._fetcher.fetch_all(R, depth, kwargs)
if e: raise e
return d | python | def fetch_all(self, R, depth=1, **kwargs):
"Request multiple objects from API"
d, e = self._fetcher.fetch_all(R, depth, kwargs)
if e: raise e
return d | [
"def",
"fetch_all",
"(",
"self",
",",
"R",
",",
"depth",
"=",
"1",
",",
"*",
"*",
"kwargs",
")",
":",
"d",
",",
"e",
"=",
"self",
".",
"_fetcher",
".",
"fetch_all",
"(",
"R",
",",
"depth",
",",
"kwargs",
")",
"if",
"e",
":",
"raise",
"e",
"re... | Request multiple objects from API | [
"Request",
"multiple",
"objects",
"from",
"API"
] | train | https://github.com/peeringdb/peeringdb-py/blob/cf2060a1d5ef879a01cf849e54b7756909ab2661/peeringdb/client.py#L70-L74 |
peeringdb/peeringdb-py | peeringdb/client.py | Client.get | def get(self, res, pk):
"Get a resource instance by primary key (id)"
B = get_backend()
return B.get_object(B.get_concrete(res), pk) | python | def get(self, res, pk):
"Get a resource instance by primary key (id)"
B = get_backend()
return B.get_object(B.get_concrete(res), pk) | [
"def",
"get",
"(",
"self",
",",
"res",
",",
"pk",
")",
":",
"B",
"=",
"get_backend",
"(",
")",
"return",
"B",
".",
"get_object",
"(",
"B",
".",
"get_concrete",
"(",
"res",
")",
",",
"pk",
")"
] | Get a resource instance by primary key (id) | [
"Get",
"a",
"resource",
"instance",
"by",
"primary",
"key",
"(",
"id",
")"
] | train | https://github.com/peeringdb/peeringdb-py/blob/cf2060a1d5ef879a01cf849e54b7756909ab2661/peeringdb/client.py#L76-L79 |
peeringdb/peeringdb-py | peeringdb/client.py | Client.all | def all(self, res):
"Get resources using a filter condition"
B = get_backend()
return B.get_objects(B.get_concrete(res)) | python | def all(self, res):
"Get resources using a filter condition"
B = get_backend()
return B.get_objects(B.get_concrete(res)) | [
"def",
"all",
"(",
"self",
",",
"res",
")",
":",
"B",
"=",
"get_backend",
"(",
")",
"return",
"B",
".",
"get_objects",
"(",
"B",
".",
"get_concrete",
"(",
"res",
")",
")"
] | Get resources using a filter condition | [
"Get",
"resources",
"using",
"a",
"filter",
"condition"
] | train | https://github.com/peeringdb/peeringdb-py/blob/cf2060a1d5ef879a01cf849e54b7756909ab2661/peeringdb/client.py#L81-L84 |
peeringdb/peeringdb-py | peeringdb/_tasks_sequential.py | run_task | def run_task(func):
"""
Decorator to collect and return generator results, returning a list
if there are multiple results
"""
def _wrapped(*a, **k):
gen = func(*a, **k)
return _consume_task(gen)
return _wrapped | python | def run_task(func):
"""
Decorator to collect and return generator results, returning a list
if there are multiple results
"""
def _wrapped(*a, **k):
gen = func(*a, **k)
return _consume_task(gen)
return _wrapped | [
"def",
"run_task",
"(",
"func",
")",
":",
"def",
"_wrapped",
"(",
"*",
"a",
",",
"*",
"*",
"k",
")",
":",
"gen",
"=",
"func",
"(",
"*",
"a",
",",
"*",
"*",
"k",
")",
"return",
"_consume_task",
"(",
"gen",
")",
"return",
"_wrapped"
] | Decorator to collect and return generator results, returning a list
if there are multiple results | [
"Decorator",
"to",
"collect",
"and",
"return",
"generator",
"results",
"returning",
"a",
"list",
"if",
"there",
"are",
"multiple",
"results"
] | train | https://github.com/peeringdb/peeringdb-py/blob/cf2060a1d5ef879a01cf849e54b7756909ab2661/peeringdb/_tasks_sequential.py#L69-L79 |
peeringdb/peeringdb-py | peeringdb/_fetch.py | Fetcher.get | def get(self, typ, id, **kwargs):
"""
Load type by id
"""
return self._load(self._request(typ, id=id, params=kwargs)) | python | def get(self, typ, id, **kwargs):
"""
Load type by id
"""
return self._load(self._request(typ, id=id, params=kwargs)) | [
"def",
"get",
"(",
"self",
",",
"typ",
",",
"id",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"self",
".",
"_load",
"(",
"self",
".",
"_request",
"(",
"typ",
",",
"id",
"=",
"id",
",",
"params",
"=",
"kwargs",
")",
")"
] | Load type by id | [
"Load",
"type",
"by",
"id"
] | train | https://github.com/peeringdb/peeringdb-py/blob/cf2060a1d5ef879a01cf849e54b7756909ab2661/peeringdb/_fetch.py#L83-L87 |
peeringdb/peeringdb-py | peeringdb/_fetch.py | Fetcher._request | def _request(self, typ, id=0, method='GET', params=None, data=None,
url=None):
"""
send the request, return response obj
"""
backend, backend_version = peeringdb.get_backend_info()
user_agent = 'PeeringDB/{} {}/{}'.format(peeringdb.__version__,
... | python | def _request(self, typ, id=0, method='GET', params=None, data=None,
url=None):
"""
send the request, return response obj
"""
backend, backend_version = peeringdb.get_backend_info()
user_agent = 'PeeringDB/{} {}/{}'.format(peeringdb.__version__,
... | [
"def",
"_request",
"(",
"self",
",",
"typ",
",",
"id",
"=",
"0",
",",
"method",
"=",
"'GET'",
",",
"params",
"=",
"None",
",",
"data",
"=",
"None",
",",
"url",
"=",
"None",
")",
":",
"backend",
",",
"backend_version",
"=",
"peeringdb",
".",
"get_ba... | send the request, return response obj | [
"send",
"the",
"request",
"return",
"response",
"obj"
] | train | https://github.com/peeringdb/peeringdb-py/blob/cf2060a1d5ef879a01cf849e54b7756909ab2661/peeringdb/_fetch.py#L89-L112 |
peeringdb/peeringdb-py | peeringdb/_tasks_async.py | wrap_generator | def wrap_generator(func):
"""
Decorator to convert a generator function to an async function which collects
and returns generator results, returning a list if there are multiple results
"""
async def _wrapped(*a, **k):
r, ret = None, []
gen = func(*a, **k)
while True:
... | python | def wrap_generator(func):
"""
Decorator to convert a generator function to an async function which collects
and returns generator results, returning a list if there are multiple results
"""
async def _wrapped(*a, **k):
r, ret = None, []
gen = func(*a, **k)
while True:
... | [
"def",
"wrap_generator",
"(",
"func",
")",
":",
"async",
"def",
"_wrapped",
"(",
"*",
"a",
",",
"*",
"*",
"k",
")",
":",
"r",
",",
"ret",
"=",
"None",
",",
"[",
"]",
"gen",
"=",
"func",
"(",
"*",
"a",
",",
"*",
"*",
"k",
")",
"while",
"True... | Decorator to convert a generator function to an async function which collects
and returns generator results, returning a list if there are multiple results | [
"Decorator",
"to",
"convert",
"a",
"generator",
"function",
"to",
"an",
"async",
"function",
"which",
"collects",
"and",
"returns",
"generator",
"results",
"returning",
"a",
"list",
"if",
"there",
"are",
"multiple",
"results"
] | train | https://github.com/peeringdb/peeringdb-py/blob/cf2060a1d5ef879a01cf849e54b7756909ab2661/peeringdb/_tasks_async.py#L30-L54 |
peeringdb/peeringdb-py | peeringdb/_tasks_async.py | run_task | def run_task(func):
"""
Decorator to wrap an async function in an event loop.
Use for main sync interface methods.
"""
def _wrapped(*a, **k):
loop = asyncio.get_event_loop()
return loop.run_until_complete(func(*a, **k))
return _wrapped | python | def run_task(func):
"""
Decorator to wrap an async function in an event loop.
Use for main sync interface methods.
"""
def _wrapped(*a, **k):
loop = asyncio.get_event_loop()
return loop.run_until_complete(func(*a, **k))
return _wrapped | [
"def",
"run_task",
"(",
"func",
")",
":",
"def",
"_wrapped",
"(",
"*",
"a",
",",
"*",
"*",
"k",
")",
":",
"loop",
"=",
"asyncio",
".",
"get_event_loop",
"(",
")",
"return",
"loop",
".",
"run_until_complete",
"(",
"func",
"(",
"*",
"a",
",",
"*",
... | Decorator to wrap an async function in an event loop.
Use for main sync interface methods. | [
"Decorator",
"to",
"wrap",
"an",
"async",
"function",
"in",
"an",
"event",
"loop",
".",
"Use",
"for",
"main",
"sync",
"interface",
"methods",
"."
] | train | https://github.com/peeringdb/peeringdb-py/blob/cf2060a1d5ef879a01cf849e54b7756909ab2661/peeringdb/_tasks_async.py#L57-L67 |
peeringdb/peeringdb-py | peeringdb/util.py | split_ref | def split_ref(string):
""" splits a string into (tag, id) """
re_tag = re.compile('^(?P<tag>[a-zA-Z]+)[\s-]*(?P<pk>\d+)$')
m = re_tag.search(string)
if not m:
raise ValueError("unable to split string '%s'" % (string, ))
return (m.group('tag').lower(), int(m.group('pk'))) | python | def split_ref(string):
""" splits a string into (tag, id) """
re_tag = re.compile('^(?P<tag>[a-zA-Z]+)[\s-]*(?P<pk>\d+)$')
m = re_tag.search(string)
if not m:
raise ValueError("unable to split string '%s'" % (string, ))
return (m.group('tag').lower(), int(m.group('pk'))) | [
"def",
"split_ref",
"(",
"string",
")",
":",
"re_tag",
"=",
"re",
".",
"compile",
"(",
"'^(?P<tag>[a-zA-Z]+)[\\s-]*(?P<pk>\\d+)$'",
")",
"m",
"=",
"re_tag",
".",
"search",
"(",
"string",
")",
"if",
"not",
"m",
":",
"raise",
"ValueError",
"(",
"\"unable to sp... | splits a string into (tag, id) | [
"splits",
"a",
"string",
"into",
"(",
"tag",
"id",
")"
] | train | https://github.com/peeringdb/peeringdb-py/blob/cf2060a1d5ef879a01cf849e54b7756909ab2661/peeringdb/util.py#L12-L19 |
peeringdb/peeringdb-py | peeringdb/util.py | prompt | def prompt(msg, default=None):
"Prompt for input"
if default is not None:
msg = '{} ({})'.format(msg, repr(default))
msg = '{}: '.format(msg)
try:
s = input(msg)
except KeyboardInterrupt:
exit(1)
except EOFError:
s = ''
if not s:
s = default
return... | python | def prompt(msg, default=None):
"Prompt for input"
if default is not None:
msg = '{} ({})'.format(msg, repr(default))
msg = '{}: '.format(msg)
try:
s = input(msg)
except KeyboardInterrupt:
exit(1)
except EOFError:
s = ''
if not s:
s = default
return... | [
"def",
"prompt",
"(",
"msg",
",",
"default",
"=",
"None",
")",
":",
"if",
"default",
"is",
"not",
"None",
":",
"msg",
"=",
"'{} ({})'",
".",
"format",
"(",
"msg",
",",
"repr",
"(",
"default",
")",
")",
"msg",
"=",
"'{}: '",
".",
"format",
"(",
"m... | Prompt for input | [
"Prompt",
"for",
"input"
] | train | https://github.com/peeringdb/peeringdb-py/blob/cf2060a1d5ef879a01cf849e54b7756909ab2661/peeringdb/util.py#L37-L50 |
peeringdb/peeringdb-py | peeringdb/util.py | limit_mem | def limit_mem(limit=(4 * 1024**3)):
"Set soft memory limit"
rsrc = resource.RLIMIT_DATA
soft, hard = resource.getrlimit(rsrc)
resource.setrlimit(rsrc, (limit, hard)) # 4GB
softnew, _ = resource.getrlimit(rsrc)
assert softnew == limit
_log = logging.getLogger(__name__)
_log.debug('Set s... | python | def limit_mem(limit=(4 * 1024**3)):
"Set soft memory limit"
rsrc = resource.RLIMIT_DATA
soft, hard = resource.getrlimit(rsrc)
resource.setrlimit(rsrc, (limit, hard)) # 4GB
softnew, _ = resource.getrlimit(rsrc)
assert softnew == limit
_log = logging.getLogger(__name__)
_log.debug('Set s... | [
"def",
"limit_mem",
"(",
"limit",
"=",
"(",
"4",
"*",
"1024",
"**",
"3",
")",
")",
":",
"rsrc",
"=",
"resource",
".",
"RLIMIT_DATA",
"soft",
",",
"hard",
"=",
"resource",
".",
"getrlimit",
"(",
"rsrc",
")",
"resource",
".",
"setrlimit",
"(",
"rsrc",
... | Set soft memory limit | [
"Set",
"soft",
"memory",
"limit"
] | train | https://github.com/peeringdb/peeringdb-py/blob/cf2060a1d5ef879a01cf849e54b7756909ab2661/peeringdb/util.py#L86-L95 |
nerox8664/gluon2pytorch | gluon2pytorch/gluon2pytorch.py | render_module | def render_module(inits, calls, inputs, outputs, dst_dir, pytorch_dict, pytorch_module_name):
"""
Render model.
"""
inits = [i for i in inits if len(i) > 0]
output = pytorch_model_template.format(**{
'module_name': pytorch_module_name,
'module_name_lower': pytorch_module_name.lower... | python | def render_module(inits, calls, inputs, outputs, dst_dir, pytorch_dict, pytorch_module_name):
"""
Render model.
"""
inits = [i for i in inits if len(i) > 0]
output = pytorch_model_template.format(**{
'module_name': pytorch_module_name,
'module_name_lower': pytorch_module_name.lower... | [
"def",
"render_module",
"(",
"inits",
",",
"calls",
",",
"inputs",
",",
"outputs",
",",
"dst_dir",
",",
"pytorch_dict",
",",
"pytorch_module_name",
")",
":",
"inits",
"=",
"[",
"i",
"for",
"i",
"in",
"inits",
"if",
"len",
"(",
"i",
")",
">",
"0",
"]"... | Render model. | [
"Render",
"model",
"."
] | train | https://github.com/nerox8664/gluon2pytorch/blob/4fad7fc3a0a478d68bd509e239d4b7f1e0748ffa/gluon2pytorch/gluon2pytorch.py#L31-L63 |
nerox8664/gluon2pytorch | gluon2pytorch/gluon2pytorch.py | gluon2pytorch | def gluon2pytorch(net, args, dst_dir, pytorch_module_name, debug=True, keep_names=False):
"""
Function to convert a model.
"""
x = [mx.nd.array(np.ones(i)) for i in args]
x = net(*x)
# Get network params
params = net.collect_params()
# Create a symbol to trace net
x = [mx.sym.var(... | python | def gluon2pytorch(net, args, dst_dir, pytorch_module_name, debug=True, keep_names=False):
"""
Function to convert a model.
"""
x = [mx.nd.array(np.ones(i)) for i in args]
x = net(*x)
# Get network params
params = net.collect_params()
# Create a symbol to trace net
x = [mx.sym.var(... | [
"def",
"gluon2pytorch",
"(",
"net",
",",
"args",
",",
"dst_dir",
",",
"pytorch_module_name",
",",
"debug",
"=",
"True",
",",
"keep_names",
"=",
"False",
")",
":",
"x",
"=",
"[",
"mx",
".",
"nd",
".",
"array",
"(",
"np",
".",
"ones",
"(",
"i",
")",
... | Function to convert a model. | [
"Function",
"to",
"convert",
"a",
"model",
"."
] | train | https://github.com/nerox8664/gluon2pytorch/blob/4fad7fc3a0a478d68bd509e239d4b7f1e0748ffa/gluon2pytorch/gluon2pytorch.py#L66-L163 |
acsone/odoo-autodiscover | odoo_autodiscover/post_import_hook.py | hook_odoo | def hook_odoo(package):
""" work around Odoo 10 issue
https://github.com/acsone/setuptools-odoo/issues/10
# This hook should runs after all *-nspkg.pth files because it is named
# zzz_ and .pth file run in alphabetical order.
"""
if sys.version_info.major != 2:
return
if package.__n... | python | def hook_odoo(package):
""" work around Odoo 10 issue
https://github.com/acsone/setuptools-odoo/issues/10
# This hook should runs after all *-nspkg.pth files because it is named
# zzz_ and .pth file run in alphabetical order.
"""
if sys.version_info.major != 2:
return
if package.__n... | [
"def",
"hook_odoo",
"(",
"package",
")",
":",
"if",
"sys",
".",
"version_info",
".",
"major",
"!=",
"2",
":",
"return",
"if",
"package",
".",
"__name__",
"==",
"'odoo'",
":",
"if",
"not",
"hasattr",
"(",
"package",
",",
"'release'",
")",
":",
"# Since ... | work around Odoo 10 issue
https://github.com/acsone/setuptools-odoo/issues/10
# This hook should runs after all *-nspkg.pth files because it is named
# zzz_ and .pth file run in alphabetical order. | [
"work",
"around",
"Odoo",
"10",
"issue",
"https",
":",
"//",
"github",
".",
"com",
"/",
"acsone",
"/",
"setuptools",
"-",
"odoo",
"/",
"issues",
"/",
"10"
] | train | https://github.com/acsone/odoo-autodiscover/blob/b7c6869ec34a7c141b207abc0971eadccd3a0316/odoo_autodiscover/post_import_hook.py#L9-L28 |
kowalpy/Robot-Framework-FTP-Library | FtpLibrary.py | FtpLibrary.getAllFtpConnections | def getAllFtpConnections(self):
"""
Returns a dictionary containing active ftp connections.
"""
outputMsg = "Current ftp connections:\n"
counter = 1
for k in self.ftpList:
outputMsg += str(counter) + ". " + k + " "
outputMsg += str(self.ftpList[k])... | python | def getAllFtpConnections(self):
"""
Returns a dictionary containing active ftp connections.
"""
outputMsg = "Current ftp connections:\n"
counter = 1
for k in self.ftpList:
outputMsg += str(counter) + ". " + k + " "
outputMsg += str(self.ftpList[k])... | [
"def",
"getAllFtpConnections",
"(",
"self",
")",
":",
"outputMsg",
"=",
"\"Current ftp connections:\\n\"",
"counter",
"=",
"1",
"for",
"k",
"in",
"self",
".",
"ftpList",
":",
"outputMsg",
"+=",
"str",
"(",
"counter",
")",
"+",
"\". \"",
"+",
"k",
"+",
"\" ... | Returns a dictionary containing active ftp connections. | [
"Returns",
"a",
"dictionary",
"containing",
"active",
"ftp",
"connections",
"."
] | train | https://github.com/kowalpy/Robot-Framework-FTP-Library/blob/90794be0a12af489ac98e8ae3b4ff450c83e2f3d/FtpLibrary.py#L105-L117 |
kowalpy/Robot-Framework-FTP-Library | FtpLibrary.py | FtpLibrary.ftp_connect | def ftp_connect(self, host, user='anonymous', password='anonymous@', port=21, timeout=30, connId='default'):
"""
Constructs FTP object, opens a connection and login.
Call this function before any other (otherwise raises exception).
Returns server output.
Parameters:
-... | python | def ftp_connect(self, host, user='anonymous', password='anonymous@', port=21, timeout=30, connId='default'):
"""
Constructs FTP object, opens a connection and login.
Call this function before any other (otherwise raises exception).
Returns server output.
Parameters:
-... | [
"def",
"ftp_connect",
"(",
"self",
",",
"host",
",",
"user",
"=",
"'anonymous'",
",",
"password",
"=",
"'anonymous@'",
",",
"port",
"=",
"21",
",",
"timeout",
"=",
"30",
",",
"connId",
"=",
"'default'",
")",
":",
"if",
"connId",
"in",
"self",
".",
"f... | Constructs FTP object, opens a connection and login.
Call this function before any other (otherwise raises exception).
Returns server output.
Parameters:
- host - server host address
- user(optional) - FTP user name. If not given, 'anonymous' is used.
- passwo... | [
"Constructs",
"FTP",
"object",
"opens",
"a",
"connection",
"and",
"login",
".",
"Call",
"this",
"function",
"before",
"any",
"other",
"(",
"otherwise",
"raises",
"exception",
")",
".",
"Returns",
"server",
"output",
".",
"Parameters",
":",
"-",
"host",
"-",
... | train | https://github.com/kowalpy/Robot-Framework-FTP-Library/blob/90794be0a12af489ac98e8ae3b4ff450c83e2f3d/FtpLibrary.py#L119-L160 |
kowalpy/Robot-Framework-FTP-Library | FtpLibrary.py | FtpLibrary.get_welcome | def get_welcome(self, connId='default'):
"""
Returns wlecome message of FTP server.
Parameters:
- connId(optional) - connection identifier. By default equals 'default'
"""
thisConn = self.__getConnection(connId)
outputMsg = ""
try:
outputMsg +=... | python | def get_welcome(self, connId='default'):
"""
Returns wlecome message of FTP server.
Parameters:
- connId(optional) - connection identifier. By default equals 'default'
"""
thisConn = self.__getConnection(connId)
outputMsg = ""
try:
outputMsg +=... | [
"def",
"get_welcome",
"(",
"self",
",",
"connId",
"=",
"'default'",
")",
":",
"thisConn",
"=",
"self",
".",
"__getConnection",
"(",
"connId",
")",
"outputMsg",
"=",
"\"\"",
"try",
":",
"outputMsg",
"+=",
"thisConn",
".",
"getwelcome",
"(",
")",
"except",
... | Returns wlecome message of FTP server.
Parameters:
- connId(optional) - connection identifier. By default equals 'default' | [
"Returns",
"wlecome",
"message",
"of",
"FTP",
"server",
".",
"Parameters",
":",
"-",
"connId",
"(",
"optional",
")",
"-",
"connection",
"identifier",
".",
"By",
"default",
"equals",
"default"
] | train | https://github.com/kowalpy/Robot-Framework-FTP-Library/blob/90794be0a12af489ac98e8ae3b4ff450c83e2f3d/FtpLibrary.py#L162-L176 |
kowalpy/Robot-Framework-FTP-Library | FtpLibrary.py | FtpLibrary.dir | def dir(self, connId='default'):
"""
Returns list of raw lines returned as contens of current directory.
Parameters:
- connId(optional) - connection identifier. By default equals 'default'
"""
dirList = []
thisConn = self.__getConnection(connId)
outputMsg ... | python | def dir(self, connId='default'):
"""
Returns list of raw lines returned as contens of current directory.
Parameters:
- connId(optional) - connection identifier. By default equals 'default'
"""
dirList = []
thisConn = self.__getConnection(connId)
outputMsg ... | [
"def",
"dir",
"(",
"self",
",",
"connId",
"=",
"'default'",
")",
":",
"dirList",
"=",
"[",
"]",
"thisConn",
"=",
"self",
".",
"__getConnection",
"(",
"connId",
")",
"outputMsg",
"=",
"\"\"",
"try",
":",
"thisConn",
".",
"dir",
"(",
"dirList",
".",
"a... | Returns list of raw lines returned as contens of current directory.
Parameters:
- connId(optional) - connection identifier. By default equals 'default' | [
"Returns",
"list",
"of",
"raw",
"lines",
"returned",
"as",
"contens",
"of",
"current",
"directory",
".",
"Parameters",
":",
"-",
"connId",
"(",
"optional",
")",
"-",
"connection",
"identifier",
".",
"By",
"default",
"equals",
"default"
] | train | https://github.com/kowalpy/Robot-Framework-FTP-Library/blob/90794be0a12af489ac98e8ae3b4ff450c83e2f3d/FtpLibrary.py#L213-L230 |
kowalpy/Robot-Framework-FTP-Library | FtpLibrary.py | FtpLibrary.dir_names | def dir_names(self, connId='default'):
"""
Returns list of files (and/or directories) of current directory.
Parameters:
- connId(optional) - connection identifier. By default equals 'default'
"""
files_list = []
thisConn = self.__getConnection(connId)
try:... | python | def dir_names(self, connId='default'):
"""
Returns list of files (and/or directories) of current directory.
Parameters:
- connId(optional) - connection identifier. By default equals 'default'
"""
files_list = []
thisConn = self.__getConnection(connId)
try:... | [
"def",
"dir_names",
"(",
"self",
",",
"connId",
"=",
"'default'",
")",
":",
"files_list",
"=",
"[",
"]",
"thisConn",
"=",
"self",
".",
"__getConnection",
"(",
"connId",
")",
"try",
":",
"files_list",
"=",
"thisConn",
".",
"nlst",
"(",
")",
"except",
":... | Returns list of files (and/or directories) of current directory.
Parameters:
- connId(optional) - connection identifier. By default equals 'default' | [
"Returns",
"list",
"of",
"files",
"(",
"and",
"/",
"or",
"directories",
")",
"of",
"current",
"directory",
".",
"Parameters",
":",
"-",
"connId",
"(",
"optional",
")",
"-",
"connection",
"identifier",
".",
"By",
"default",
"equals",
"default"
] | train | https://github.com/kowalpy/Robot-Framework-FTP-Library/blob/90794be0a12af489ac98e8ae3b4ff450c83e2f3d/FtpLibrary.py#L232-L244 |
kowalpy/Robot-Framework-FTP-Library | FtpLibrary.py | FtpLibrary.download_file | def download_file(self, remoteFileName, localFilePath=None, connId='default'):
"""
Downloads file from current directory on FTP server in binary mode. If
localFilePath is not given, file is saved in current local directory (by
default folder containing robot framework project file) with ... | python | def download_file(self, remoteFileName, localFilePath=None, connId='default'):
"""
Downloads file from current directory on FTP server in binary mode. If
localFilePath is not given, file is saved in current local directory (by
default folder containing robot framework project file) with ... | [
"def",
"download_file",
"(",
"self",
",",
"remoteFileName",
",",
"localFilePath",
"=",
"None",
",",
"connId",
"=",
"'default'",
")",
":",
"thisConn",
"=",
"self",
".",
"__getConnection",
"(",
"connId",
")",
"outputMsg",
"=",
"\"\"",
"localPath",
"=",
"\"\"",... | Downloads file from current directory on FTP server in binary mode. If
localFilePath is not given, file is saved in current local directory (by
default folder containing robot framework project file) with the same name
as source file. Returns server output
Parameters:
- remoteFil... | [
"Downloads",
"file",
"from",
"current",
"directory",
"on",
"FTP",
"server",
"in",
"binary",
"mode",
".",
"If",
"localFilePath",
"is",
"not",
"given",
"file",
"is",
"saved",
"in",
"current",
"local",
"directory",
"(",
"by",
"default",
"folder",
"containing",
... | train | https://github.com/kowalpy/Robot-Framework-FTP-Library/blob/90794be0a12af489ac98e8ae3b4ff450c83e2f3d/FtpLibrary.py#L280-L317 |
kowalpy/Robot-Framework-FTP-Library | FtpLibrary.py | FtpLibrary.upload_file | def upload_file(self, localFileName, remoteFileName=None, connId='default'):
"""
Sends file from local drive to current directory on FTP server in binary mode.
Returns server output.
Parameters:
- localFileName - file name or path to a file on a local drive.
- remoteFileN... | python | def upload_file(self, localFileName, remoteFileName=None, connId='default'):
"""
Sends file from local drive to current directory on FTP server in binary mode.
Returns server output.
Parameters:
- localFileName - file name or path to a file on a local drive.
- remoteFileN... | [
"def",
"upload_file",
"(",
"self",
",",
"localFileName",
",",
"remoteFileName",
"=",
"None",
",",
"connId",
"=",
"'default'",
")",
":",
"thisConn",
"=",
"self",
".",
"__getConnection",
"(",
"connId",
")",
"outputMsg",
"=",
"\"\"",
"remoteFileName_",
"=",
"\"... | Sends file from local drive to current directory on FTP server in binary mode.
Returns server output.
Parameters:
- localFileName - file name or path to a file on a local drive.
- remoteFileName (optional) - a name or path containing name under which file should be saved.
- connI... | [
"Sends",
"file",
"from",
"local",
"drive",
"to",
"current",
"directory",
"on",
"FTP",
"server",
"in",
"binary",
"mode",
".",
"Returns",
"server",
"output",
".",
"Parameters",
":",
"-",
"localFileName",
"-",
"file",
"name",
"or",
"path",
"to",
"a",
"file",
... | train | https://github.com/kowalpy/Robot-Framework-FTP-Library/blob/90794be0a12af489ac98e8ae3b4ff450c83e2f3d/FtpLibrary.py#L319-L356 |
kowalpy/Robot-Framework-FTP-Library | FtpLibrary.py | FtpLibrary.size | def size(self, fileToCheck, connId='default'):
"""
Checks size of a file on FTP server. Returns size of a file in bytes (integer).
Parameters:
- fileToCheck - file name or path to a file on FTP server
- connId(optional) - connection identifier. By default equals 'default'
... | python | def size(self, fileToCheck, connId='default'):
"""
Checks size of a file on FTP server. Returns size of a file in bytes (integer).
Parameters:
- fileToCheck - file name or path to a file on FTP server
- connId(optional) - connection identifier. By default equals 'default'
... | [
"def",
"size",
"(",
"self",
",",
"fileToCheck",
",",
"connId",
"=",
"'default'",
")",
":",
"thisConn",
"=",
"self",
".",
"__getConnection",
"(",
"connId",
")",
"outputMsg",
"=",
"\"\"",
"try",
":",
"tmpSize",
"=",
"thisConn",
".",
"size",
"(",
"fileToChe... | Checks size of a file on FTP server. Returns size of a file in bytes (integer).
Parameters:
- fileToCheck - file name or path to a file on FTP server
- connId(optional) - connection identifier. By default equals 'default'
Example:
| ${file1size} = | size | /home/myname/tmp/uu.txt... | [
"Checks",
"size",
"of",
"a",
"file",
"on",
"FTP",
"server",
".",
"Returns",
"size",
"of",
"a",
"file",
"in",
"bytes",
"(",
"integer",
")",
".",
"Parameters",
":",
"-",
"fileToCheck",
"-",
"file",
"name",
"or",
"path",
"to",
"a",
"file",
"on",
"FTP",
... | train | https://github.com/kowalpy/Robot-Framework-FTP-Library/blob/90794be0a12af489ac98e8ae3b4ff450c83e2f3d/FtpLibrary.py#L358-L380 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.