repo stringlengths 7 55 | path stringlengths 4 127 | func_name stringlengths 1 88 | original_string stringlengths 75 19.8k | language stringclasses 1
value | code stringlengths 75 19.8k | code_tokens listlengths 20 707 | docstring stringlengths 3 17.3k | docstring_tokens listlengths 3 222 | sha stringlengths 40 40 | url stringlengths 87 242 | partition stringclasses 1
value | idx int64 0 252k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
zmathew/django-backbone | backbone/views.py | BackboneAPIView.has_add_permission | def has_add_permission(self, request):
"""
Returns True if the requesting user is allowed to add an object, False otherwise.
"""
perm_string = '%s.add_%s' % (self.model._meta.app_label,
self.model._meta.object_name.lower()
)
return request.user.has_perm(perm_string) | python | def has_add_permission(self, request):
"""
Returns True if the requesting user is allowed to add an object, False otherwise.
"""
perm_string = '%s.add_%s' % (self.model._meta.app_label,
self.model._meta.object_name.lower()
)
return request.user.has_perm(perm_string) | [
"def",
"has_add_permission",
"(",
"self",
",",
"request",
")",
":",
"perm_string",
"=",
"'%s.add_%s'",
"%",
"(",
"self",
".",
"model",
".",
"_meta",
".",
"app_label",
",",
"self",
".",
"model",
".",
"_meta",
".",
"object_name",
".",
"lower",
"(",
")",
... | Returns True if the requesting user is allowed to add an object, False otherwise. | [
"Returns",
"True",
"if",
"the",
"requesting",
"user",
"is",
"allowed",
"to",
"add",
"an",
"object",
"False",
"otherwise",
"."
] | 53505a247fb058e64a103c4f11da66993037bd6b | https://github.com/zmathew/django-backbone/blob/53505a247fb058e64a103c4f11da66993037bd6b/backbone/views.py#L212-L219 | train | 37,400 |
zmathew/django-backbone | backbone/views.py | BackboneAPIView.has_update_permission | def has_update_permission(self, request, obj):
"""
Returns True if the requesting user is allowed to update the given object, False otherwise.
"""
perm_string = '%s.change_%s' % (self.model._meta.app_label,
self.model._meta.object_name.lower()
)
return request.user.has_perm(perm_string) | python | def has_update_permission(self, request, obj):
"""
Returns True if the requesting user is allowed to update the given object, False otherwise.
"""
perm_string = '%s.change_%s' % (self.model._meta.app_label,
self.model._meta.object_name.lower()
)
return request.user.has_perm(perm_string) | [
"def",
"has_update_permission",
"(",
"self",
",",
"request",
",",
"obj",
")",
":",
"perm_string",
"=",
"'%s.change_%s'",
"%",
"(",
"self",
".",
"model",
".",
"_meta",
".",
"app_label",
",",
"self",
".",
"model",
".",
"_meta",
".",
"object_name",
".",
"lo... | Returns True if the requesting user is allowed to update the given object, False otherwise. | [
"Returns",
"True",
"if",
"the",
"requesting",
"user",
"is",
"allowed",
"to",
"update",
"the",
"given",
"object",
"False",
"otherwise",
"."
] | 53505a247fb058e64a103c4f11da66993037bd6b | https://github.com/zmathew/django-backbone/blob/53505a247fb058e64a103c4f11da66993037bd6b/backbone/views.py#L231-L238 | train | 37,401 |
zmathew/django-backbone | backbone/views.py | BackboneAPIView.serialize | def serialize(self, obj, fields):
"""
Serializes a single model instance to a Python dict, based on the specified list of fields.
"""
data = {}
remaining_fields = []
for field in fields:
if callable(field): # Callable
data[field.__name__] = field(obj)
elif hasattr(self, field) and callable(getattr(self, field)): # Method on the view
data[field] = getattr(self, field)(obj)
elif hasattr(obj, field): # Callable/property/field on the model
attr = getattr(obj, field)
if isinstance(attr, Model):
data[field] = attr.pk
elif isinstance(attr, Manager):
data[field] = [item['pk'] for item in attr.values('pk')]
elif callable(attr): # Callable on the model
data[field] = attr()
else:
remaining_fields.append(field)
else:
raise AttributeError('Invalid field: %s' % field)
# Add on db fields
serializer = Serializer()
serializer.serialize([obj], fields=list(remaining_fields))
data.update(serializer.getvalue()[0]['fields'])
# Any remaining fields should be properties on the model
remaining_fields = set(remaining_fields) - set(data.keys())
for field in remaining_fields:
data[field] = getattr(obj, field)
return data | python | def serialize(self, obj, fields):
"""
Serializes a single model instance to a Python dict, based on the specified list of fields.
"""
data = {}
remaining_fields = []
for field in fields:
if callable(field): # Callable
data[field.__name__] = field(obj)
elif hasattr(self, field) and callable(getattr(self, field)): # Method on the view
data[field] = getattr(self, field)(obj)
elif hasattr(obj, field): # Callable/property/field on the model
attr = getattr(obj, field)
if isinstance(attr, Model):
data[field] = attr.pk
elif isinstance(attr, Manager):
data[field] = [item['pk'] for item in attr.values('pk')]
elif callable(attr): # Callable on the model
data[field] = attr()
else:
remaining_fields.append(field)
else:
raise AttributeError('Invalid field: %s' % field)
# Add on db fields
serializer = Serializer()
serializer.serialize([obj], fields=list(remaining_fields))
data.update(serializer.getvalue()[0]['fields'])
# Any remaining fields should be properties on the model
remaining_fields = set(remaining_fields) - set(data.keys())
for field in remaining_fields:
data[field] = getattr(obj, field)
return data | [
"def",
"serialize",
"(",
"self",
",",
"obj",
",",
"fields",
")",
":",
"data",
"=",
"{",
"}",
"remaining_fields",
"=",
"[",
"]",
"for",
"field",
"in",
"fields",
":",
"if",
"callable",
"(",
"field",
")",
":",
"# Callable",
"data",
"[",
"field",
".",
... | Serializes a single model instance to a Python dict, based on the specified list of fields. | [
"Serializes",
"a",
"single",
"model",
"instance",
"to",
"a",
"Python",
"dict",
"based",
"on",
"the",
"specified",
"list",
"of",
"fields",
"."
] | 53505a247fb058e64a103c4f11da66993037bd6b | https://github.com/zmathew/django-backbone/blob/53505a247fb058e64a103c4f11da66993037bd6b/backbone/views.py#L259-L295 | train | 37,402 |
zmathew/django-backbone | backbone/views.py | BackboneAPIView.json_dumps | def json_dumps(self, data, **options):
"""
Wrapper around `json.dumps` that uses a special JSON encoder.
"""
params = {'sort_keys': True, 'indent': 2}
params.update(options)
# This code is based off django's built in JSON serializer
if json.__version__.split('.') >= ['2', '1', '3']:
# Use JS strings to represent Python Decimal instances (ticket #16850)
params.update({'use_decimal': False})
return json.dumps(data, cls=DjangoJSONEncoder, **params) | python | def json_dumps(self, data, **options):
"""
Wrapper around `json.dumps` that uses a special JSON encoder.
"""
params = {'sort_keys': True, 'indent': 2}
params.update(options)
# This code is based off django's built in JSON serializer
if json.__version__.split('.') >= ['2', '1', '3']:
# Use JS strings to represent Python Decimal instances (ticket #16850)
params.update({'use_decimal': False})
return json.dumps(data, cls=DjangoJSONEncoder, **params) | [
"def",
"json_dumps",
"(",
"self",
",",
"data",
",",
"*",
"*",
"options",
")",
":",
"params",
"=",
"{",
"'sort_keys'",
":",
"True",
",",
"'indent'",
":",
"2",
"}",
"params",
".",
"update",
"(",
"options",
")",
"# This code is based off django's built in JSON ... | Wrapper around `json.dumps` that uses a special JSON encoder. | [
"Wrapper",
"around",
"json",
".",
"dumps",
"that",
"uses",
"a",
"special",
"JSON",
"encoder",
"."
] | 53505a247fb058e64a103c4f11da66993037bd6b | https://github.com/zmathew/django-backbone/blob/53505a247fb058e64a103c4f11da66993037bd6b/backbone/views.py#L297-L307 | train | 37,403 |
artefactual-labs/mets-reader-writer | metsrw/fsentry.py | FSEntry.dir | def dir(cls, label, children):
"""Return ``FSEntry`` directory object."""
return FSEntry(label=label, children=children, type=u"Directory", use=None) | python | def dir(cls, label, children):
"""Return ``FSEntry`` directory object."""
return FSEntry(label=label, children=children, type=u"Directory", use=None) | [
"def",
"dir",
"(",
"cls",
",",
"label",
",",
"children",
")",
":",
"return",
"FSEntry",
"(",
"label",
"=",
"label",
",",
"children",
"=",
"children",
",",
"type",
"=",
"u\"Directory\"",
",",
"use",
"=",
"None",
")"
] | Return ``FSEntry`` directory object. | [
"Return",
"FSEntry",
"directory",
"object",
"."
] | d95939cabdfdc25cb1bf67df0c84bd0d6e6a73ff | https://github.com/artefactual-labs/mets-reader-writer/blob/d95939cabdfdc25cb1bf67df0c84bd0d6e6a73ff/metsrw/fsentry.py#L170-L172 | train | 37,404 |
artefactual-labs/mets-reader-writer | metsrw/fsentry.py | FSEntry.from_fptr | def from_fptr(cls, label, type_, fptr):
"""Return ``FSEntry`` object."""
return FSEntry(
label=label,
type=type_,
path=fptr.path,
use=fptr.use,
file_uuid=fptr.file_uuid,
derived_from=fptr.derived_from,
checksum=fptr.checksum,
checksumtype=fptr.checksumtype,
) | python | def from_fptr(cls, label, type_, fptr):
"""Return ``FSEntry`` object."""
return FSEntry(
label=label,
type=type_,
path=fptr.path,
use=fptr.use,
file_uuid=fptr.file_uuid,
derived_from=fptr.derived_from,
checksum=fptr.checksum,
checksumtype=fptr.checksumtype,
) | [
"def",
"from_fptr",
"(",
"cls",
",",
"label",
",",
"type_",
",",
"fptr",
")",
":",
"return",
"FSEntry",
"(",
"label",
"=",
"label",
",",
"type",
"=",
"type_",
",",
"path",
"=",
"fptr",
".",
"path",
",",
"use",
"=",
"fptr",
".",
"use",
",",
"file_... | Return ``FSEntry`` object. | [
"Return",
"FSEntry",
"object",
"."
] | d95939cabdfdc25cb1bf67df0c84bd0d6e6a73ff | https://github.com/artefactual-labs/mets-reader-writer/blob/d95939cabdfdc25cb1bf67df0c84bd0d6e6a73ff/metsrw/fsentry.py#L175-L186 | train | 37,405 |
artefactual-labs/mets-reader-writer | metsrw/fsentry.py | FSEntry.file_id | def file_id(self):
""" Returns the fptr @FILEID if this is not a Directory. """
if self.type.lower() == "directory":
return None
if self.file_uuid is None:
raise exceptions.MetsError(
"No FILEID: File %s does not have file_uuid set" % self.path
)
if self.is_aip:
return os.path.splitext(os.path.basename(self.path))[0]
return utils.FILE_ID_PREFIX + self.file_uuid | python | def file_id(self):
""" Returns the fptr @FILEID if this is not a Directory. """
if self.type.lower() == "directory":
return None
if self.file_uuid is None:
raise exceptions.MetsError(
"No FILEID: File %s does not have file_uuid set" % self.path
)
if self.is_aip:
return os.path.splitext(os.path.basename(self.path))[0]
return utils.FILE_ID_PREFIX + self.file_uuid | [
"def",
"file_id",
"(",
"self",
")",
":",
"if",
"self",
".",
"type",
".",
"lower",
"(",
")",
"==",
"\"directory\"",
":",
"return",
"None",
"if",
"self",
".",
"file_uuid",
"is",
"None",
":",
"raise",
"exceptions",
".",
"MetsError",
"(",
"\"No FILEID: File ... | Returns the fptr @FILEID if this is not a Directory. | [
"Returns",
"the",
"fptr"
] | d95939cabdfdc25cb1bf67df0c84bd0d6e6a73ff | https://github.com/artefactual-labs/mets-reader-writer/blob/d95939cabdfdc25cb1bf67df0c84bd0d6e6a73ff/metsrw/fsentry.py#L198-L208 | train | 37,406 |
artefactual-labs/mets-reader-writer | metsrw/fsentry.py | FSEntry.add_child | def add_child(self, child):
"""Add a child FSEntry to this FSEntry.
Only FSEntrys with a type of 'directory' can have children.
This does not detect cyclic parent/child relationships, but that will
cause problems.
:param metsrw.fsentry.FSEntry child: FSEntry to add as a child
:return: The newly added child
:raises ValueError: If this FSEntry cannot have children.
:raises ValueError: If the child and the parent are the same
"""
if self.type.lower() != "directory":
raise ValueError("Only directory objects can have children")
if child is self:
raise ValueError("Cannot be a child of itself!")
if child not in self._children:
self._children.append(child)
child.parent = self
return child | python | def add_child(self, child):
"""Add a child FSEntry to this FSEntry.
Only FSEntrys with a type of 'directory' can have children.
This does not detect cyclic parent/child relationships, but that will
cause problems.
:param metsrw.fsentry.FSEntry child: FSEntry to add as a child
:return: The newly added child
:raises ValueError: If this FSEntry cannot have children.
:raises ValueError: If the child and the parent are the same
"""
if self.type.lower() != "directory":
raise ValueError("Only directory objects can have children")
if child is self:
raise ValueError("Cannot be a child of itself!")
if child not in self._children:
self._children.append(child)
child.parent = self
return child | [
"def",
"add_child",
"(",
"self",
",",
"child",
")",
":",
"if",
"self",
".",
"type",
".",
"lower",
"(",
")",
"!=",
"\"directory\"",
":",
"raise",
"ValueError",
"(",
"\"Only directory objects can have children\"",
")",
"if",
"child",
"is",
"self",
":",
"raise"... | Add a child FSEntry to this FSEntry.
Only FSEntrys with a type of 'directory' can have children.
This does not detect cyclic parent/child relationships, but that will
cause problems.
:param metsrw.fsentry.FSEntry child: FSEntry to add as a child
:return: The newly added child
:raises ValueError: If this FSEntry cannot have children.
:raises ValueError: If the child and the parent are the same | [
"Add",
"a",
"child",
"FSEntry",
"to",
"this",
"FSEntry",
"."
] | d95939cabdfdc25cb1bf67df0c84bd0d6e6a73ff | https://github.com/artefactual-labs/mets-reader-writer/blob/d95939cabdfdc25cb1bf67df0c84bd0d6e6a73ff/metsrw/fsentry.py#L337-L357 | train | 37,407 |
artefactual-labs/mets-reader-writer | metsrw/fsentry.py | FSEntry.remove_child | def remove_child(self, child):
"""
Remove a child from this FSEntry
If `child` is not actually a child of this entry, nothing happens.
:param child: Child to remove
"""
try:
self._children.remove(child)
except ValueError: # Child may not be in list
pass
else:
child.parent = None | python | def remove_child(self, child):
"""
Remove a child from this FSEntry
If `child` is not actually a child of this entry, nothing happens.
:param child: Child to remove
"""
try:
self._children.remove(child)
except ValueError: # Child may not be in list
pass
else:
child.parent = None | [
"def",
"remove_child",
"(",
"self",
",",
"child",
")",
":",
"try",
":",
"self",
".",
"_children",
".",
"remove",
"(",
"child",
")",
"except",
"ValueError",
":",
"# Child may not be in list",
"pass",
"else",
":",
"child",
".",
"parent",
"=",
"None"
] | Remove a child from this FSEntry
If `child` is not actually a child of this entry, nothing happens.
:param child: Child to remove | [
"Remove",
"a",
"child",
"from",
"this",
"FSEntry"
] | d95939cabdfdc25cb1bf67df0c84bd0d6e6a73ff | https://github.com/artefactual-labs/mets-reader-writer/blob/d95939cabdfdc25cb1bf67df0c84bd0d6e6a73ff/metsrw/fsentry.py#L359-L372 | train | 37,408 |
artefactual-labs/mets-reader-writer | metsrw/fsentry.py | FSEntry.serialize_filesec | def serialize_filesec(self):
"""
Return the file Element for this file, appropriate for use in a fileSec.
If this is not an Item or has no use, return None.
:return: fileSec element for this FSEntry
"""
if (
self.type.lower() not in ("item", "archival information package")
or self.use is None
):
return None
el = etree.Element(utils.lxmlns("mets") + "file", ID=self.file_id())
if self.group_id():
el.attrib["GROUPID"] = self.group_id()
if self.admids:
el.set("ADMID", " ".join(self.admids))
if self.checksum and self.checksumtype:
el.attrib["CHECKSUM"] = self.checksum
el.attrib["CHECKSUMTYPE"] = self.checksumtype
if self.path:
flocat = etree.SubElement(el, utils.lxmlns("mets") + "FLocat")
# Setting manually so order is correct
try:
flocat.set(utils.lxmlns("xlink") + "href", utils.urlencode(self.path))
except ValueError:
raise exceptions.SerializeError(
'Value "{}" (for attribute xlink:href) is not a valid'
" URL.".format(self.path)
)
flocat.set("LOCTYPE", "OTHER")
flocat.set("OTHERLOCTYPE", "SYSTEM")
for transform_file in self.transform_files:
transform_file_el = etree.SubElement(
el, utils.lxmlns("mets") + "transformFile"
)
for key, val in transform_file.items():
attribute = "transform{}".format(key).upper()
transform_file_el.attrib[attribute] = str(val)
return el | python | def serialize_filesec(self):
"""
Return the file Element for this file, appropriate for use in a fileSec.
If this is not an Item or has no use, return None.
:return: fileSec element for this FSEntry
"""
if (
self.type.lower() not in ("item", "archival information package")
or self.use is None
):
return None
el = etree.Element(utils.lxmlns("mets") + "file", ID=self.file_id())
if self.group_id():
el.attrib["GROUPID"] = self.group_id()
if self.admids:
el.set("ADMID", " ".join(self.admids))
if self.checksum and self.checksumtype:
el.attrib["CHECKSUM"] = self.checksum
el.attrib["CHECKSUMTYPE"] = self.checksumtype
if self.path:
flocat = etree.SubElement(el, utils.lxmlns("mets") + "FLocat")
# Setting manually so order is correct
try:
flocat.set(utils.lxmlns("xlink") + "href", utils.urlencode(self.path))
except ValueError:
raise exceptions.SerializeError(
'Value "{}" (for attribute xlink:href) is not a valid'
" URL.".format(self.path)
)
flocat.set("LOCTYPE", "OTHER")
flocat.set("OTHERLOCTYPE", "SYSTEM")
for transform_file in self.transform_files:
transform_file_el = etree.SubElement(
el, utils.lxmlns("mets") + "transformFile"
)
for key, val in transform_file.items():
attribute = "transform{}".format(key).upper()
transform_file_el.attrib[attribute] = str(val)
return el | [
"def",
"serialize_filesec",
"(",
"self",
")",
":",
"if",
"(",
"self",
".",
"type",
".",
"lower",
"(",
")",
"not",
"in",
"(",
"\"item\"",
",",
"\"archival information package\"",
")",
"or",
"self",
".",
"use",
"is",
"None",
")",
":",
"return",
"None",
"... | Return the file Element for this file, appropriate for use in a fileSec.
If this is not an Item or has no use, return None.
:return: fileSec element for this FSEntry | [
"Return",
"the",
"file",
"Element",
"for",
"this",
"file",
"appropriate",
"for",
"use",
"in",
"a",
"fileSec",
"."
] | d95939cabdfdc25cb1bf67df0c84bd0d6e6a73ff | https://github.com/artefactual-labs/mets-reader-writer/blob/d95939cabdfdc25cb1bf67df0c84bd0d6e6a73ff/metsrw/fsentry.py#L376-L416 | train | 37,409 |
artefactual-labs/mets-reader-writer | metsrw/fsentry.py | FSEntry.is_empty_dir | def is_empty_dir(self):
"""Returns ``True`` if this fs item is a directory with no children or
a directory with only other empty directories as children.
"""
if self.mets_div_type == "Directory":
children = self._children
if children:
if all(child.is_empty_dir for child in children):
return True
else:
return False
else:
return True
else:
return False | python | def is_empty_dir(self):
"""Returns ``True`` if this fs item is a directory with no children or
a directory with only other empty directories as children.
"""
if self.mets_div_type == "Directory":
children = self._children
if children:
if all(child.is_empty_dir for child in children):
return True
else:
return False
else:
return True
else:
return False | [
"def",
"is_empty_dir",
"(",
"self",
")",
":",
"if",
"self",
".",
"mets_div_type",
"==",
"\"Directory\"",
":",
"children",
"=",
"self",
".",
"_children",
"if",
"children",
":",
"if",
"all",
"(",
"child",
".",
"is_empty_dir",
"for",
"child",
"in",
"children"... | Returns ``True`` if this fs item is a directory with no children or
a directory with only other empty directories as children. | [
"Returns",
"True",
"if",
"this",
"fs",
"item",
"is",
"a",
"directory",
"with",
"no",
"children",
"or",
"a",
"directory",
"with",
"only",
"other",
"empty",
"directories",
"as",
"children",
"."
] | d95939cabdfdc25cb1bf67df0c84bd0d6e6a73ff | https://github.com/artefactual-labs/mets-reader-writer/blob/d95939cabdfdc25cb1bf67df0c84bd0d6e6a73ff/metsrw/fsentry.py#L419-L433 | train | 37,410 |
artefactual-labs/mets-reader-writer | metsrw/fsentry.py | FSEntry.serialize_structmap | def serialize_structmap(self, recurse=True, normative=False):
"""Return the div Element for this file, appropriate for use in a
structMap.
If this FSEntry represents a directory, its children will be
recursively appended to itself. If this FSEntry represents a file, it
will contain a <fptr> element.
:param bool recurse: If true, serialize and apppend all children.
Otherwise, only serialize this element but not any children.
:param bool normative: If true, we are creating a "Normative Directory
Structure" logical structmap, in which case we add div elements for
empty directories and do not add fptr elements for files.
:return: structMap element for this FSEntry
"""
if not self.label:
return None
# Empty directories are not included in the physical structmap.
if self.is_empty_dir and not normative:
return None
el = etree.Element(utils.lxmlns("mets") + "div", TYPE=self.mets_div_type)
el.attrib["LABEL"] = self.label
if (not normative) and self.file_id():
etree.SubElement(el, utils.lxmlns("mets") + "fptr", FILEID=self.file_id())
if self.dmdids:
if (not normative) or (normative and self.is_empty_dir):
el.set("DMDID", " ".join(self.dmdids))
if recurse and self._children:
for child in self._children:
child_el = child.serialize_structmap(
recurse=recurse, normative=normative
)
if child_el is not None:
el.append(child_el)
return el | python | def serialize_structmap(self, recurse=True, normative=False):
"""Return the div Element for this file, appropriate for use in a
structMap.
If this FSEntry represents a directory, its children will be
recursively appended to itself. If this FSEntry represents a file, it
will contain a <fptr> element.
:param bool recurse: If true, serialize and apppend all children.
Otherwise, only serialize this element but not any children.
:param bool normative: If true, we are creating a "Normative Directory
Structure" logical structmap, in which case we add div elements for
empty directories and do not add fptr elements for files.
:return: structMap element for this FSEntry
"""
if not self.label:
return None
# Empty directories are not included in the physical structmap.
if self.is_empty_dir and not normative:
return None
el = etree.Element(utils.lxmlns("mets") + "div", TYPE=self.mets_div_type)
el.attrib["LABEL"] = self.label
if (not normative) and self.file_id():
etree.SubElement(el, utils.lxmlns("mets") + "fptr", FILEID=self.file_id())
if self.dmdids:
if (not normative) or (normative and self.is_empty_dir):
el.set("DMDID", " ".join(self.dmdids))
if recurse and self._children:
for child in self._children:
child_el = child.serialize_structmap(
recurse=recurse, normative=normative
)
if child_el is not None:
el.append(child_el)
return el | [
"def",
"serialize_structmap",
"(",
"self",
",",
"recurse",
"=",
"True",
",",
"normative",
"=",
"False",
")",
":",
"if",
"not",
"self",
".",
"label",
":",
"return",
"None",
"# Empty directories are not included in the physical structmap.",
"if",
"self",
".",
"is_em... | Return the div Element for this file, appropriate for use in a
structMap.
If this FSEntry represents a directory, its children will be
recursively appended to itself. If this FSEntry represents a file, it
will contain a <fptr> element.
:param bool recurse: If true, serialize and apppend all children.
Otherwise, only serialize this element but not any children.
:param bool normative: If true, we are creating a "Normative Directory
Structure" logical structmap, in which case we add div elements for
empty directories and do not add fptr elements for files.
:return: structMap element for this FSEntry | [
"Return",
"the",
"div",
"Element",
"for",
"this",
"file",
"appropriate",
"for",
"use",
"in",
"a",
"structMap",
"."
] | d95939cabdfdc25cb1bf67df0c84bd0d6e6a73ff | https://github.com/artefactual-labs/mets-reader-writer/blob/d95939cabdfdc25cb1bf67df0c84bd0d6e6a73ff/metsrw/fsentry.py#L435-L469 | train | 37,411 |
icgood/pysasl | pysasl/__init__.py | AuthenticationCredentials.check_secret | def check_secret(self, secret):
"""Checks if the secret string used in the authentication attempt
matches the "known" secret string. Some mechanisms will override this
method to control how this comparison is made.
Args:
secret: The secret string to compare against what was used in the
authentication attempt.
Returns:
True if the given secret matches the authentication attempt.
"""
try:
return hmac.compare_digest(secret, self.secret)
except AttributeError: # pragma: no cover
return secret == self.secret | python | def check_secret(self, secret):
"""Checks if the secret string used in the authentication attempt
matches the "known" secret string. Some mechanisms will override this
method to control how this comparison is made.
Args:
secret: The secret string to compare against what was used in the
authentication attempt.
Returns:
True if the given secret matches the authentication attempt.
"""
try:
return hmac.compare_digest(secret, self.secret)
except AttributeError: # pragma: no cover
return secret == self.secret | [
"def",
"check_secret",
"(",
"self",
",",
"secret",
")",
":",
"try",
":",
"return",
"hmac",
".",
"compare_digest",
"(",
"secret",
",",
"self",
".",
"secret",
")",
"except",
"AttributeError",
":",
"# pragma: no cover",
"return",
"secret",
"==",
"self",
".",
... | Checks if the secret string used in the authentication attempt
matches the "known" secret string. Some mechanisms will override this
method to control how this comparison is made.
Args:
secret: The secret string to compare against what was used in the
authentication attempt.
Returns:
True if the given secret matches the authentication attempt. | [
"Checks",
"if",
"the",
"secret",
"string",
"used",
"in",
"the",
"authentication",
"attempt",
"matches",
"the",
"known",
"secret",
"string",
".",
"Some",
"mechanisms",
"will",
"override",
"this",
"method",
"to",
"control",
"how",
"this",
"comparison",
"is",
"ma... | 241bdd349577cc99f05c4239755c307e6a46018c | https://github.com/icgood/pysasl/blob/241bdd349577cc99f05c4239755c307e6a46018c/pysasl/__init__.py#L107-L123 | train | 37,412 |
icgood/pysasl | pysasl/__init__.py | SASLAuth.secure | def secure(cls):
"""Uses only authentication mechanisms that are secure for use in
non-encrypted sessions.
Returns:
A new :class:`SASLAuth` object.
"""
builtin_mechs = cls._get_builtin_mechanisms()
secure_mechs = [mech for _, mech in builtin_mechs.items()
if not mech.insecure and mech.priority is not None]
return SASLAuth(secure_mechs) | python | def secure(cls):
"""Uses only authentication mechanisms that are secure for use in
non-encrypted sessions.
Returns:
A new :class:`SASLAuth` object.
"""
builtin_mechs = cls._get_builtin_mechanisms()
secure_mechs = [mech for _, mech in builtin_mechs.items()
if not mech.insecure and mech.priority is not None]
return SASLAuth(secure_mechs) | [
"def",
"secure",
"(",
"cls",
")",
":",
"builtin_mechs",
"=",
"cls",
".",
"_get_builtin_mechanisms",
"(",
")",
"secure_mechs",
"=",
"[",
"mech",
"for",
"_",
",",
"mech",
"in",
"builtin_mechs",
".",
"items",
"(",
")",
"if",
"not",
"mech",
".",
"insecure",
... | Uses only authentication mechanisms that are secure for use in
non-encrypted sessions.
Returns:
A new :class:`SASLAuth` object. | [
"Uses",
"only",
"authentication",
"mechanisms",
"that",
"are",
"secure",
"for",
"use",
"in",
"non",
"-",
"encrypted",
"sessions",
"."
] | 241bdd349577cc99f05c4239755c307e6a46018c | https://github.com/icgood/pysasl/blob/241bdd349577cc99f05c4239755c307e6a46018c/pysasl/__init__.py#L312-L323 | train | 37,413 |
artefactual-labs/mets-reader-writer | metsrw/mets.py | METSDocument.read | def read(cls, source):
"""Read ``source`` into a ``METSDocument`` instance. This is an
instance constructor. The ``source`` may be a path to a METS file, a
file-like object, or a string of XML.
"""
if hasattr(source, "read"):
return cls.fromfile(source)
if os.path.exists(source):
return cls.fromfile(source)
if isinstance(source, six.string_types):
source = source.encode("utf8")
return cls.fromstring(source) | python | def read(cls, source):
"""Read ``source`` into a ``METSDocument`` instance. This is an
instance constructor. The ``source`` may be a path to a METS file, a
file-like object, or a string of XML.
"""
if hasattr(source, "read"):
return cls.fromfile(source)
if os.path.exists(source):
return cls.fromfile(source)
if isinstance(source, six.string_types):
source = source.encode("utf8")
return cls.fromstring(source) | [
"def",
"read",
"(",
"cls",
",",
"source",
")",
":",
"if",
"hasattr",
"(",
"source",
",",
"\"read\"",
")",
":",
"return",
"cls",
".",
"fromfile",
"(",
"source",
")",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"source",
")",
":",
"return",
"cls",
... | Read ``source`` into a ``METSDocument`` instance. This is an
instance constructor. The ``source`` may be a path to a METS file, a
file-like object, or a string of XML. | [
"Read",
"source",
"into",
"a",
"METSDocument",
"instance",
".",
"This",
"is",
"an",
"instance",
"constructor",
".",
"The",
"source",
"may",
"be",
"a",
"path",
"to",
"a",
"METS",
"file",
"a",
"file",
"-",
"like",
"object",
"or",
"a",
"string",
"of",
"XM... | d95939cabdfdc25cb1bf67df0c84bd0d6e6a73ff | https://github.com/artefactual-labs/mets-reader-writer/blob/d95939cabdfdc25cb1bf67df0c84bd0d6e6a73ff/metsrw/mets.py#L46-L57 | train | 37,414 |
artefactual-labs/mets-reader-writer | metsrw/mets.py | METSDocument._collect_all_files | def _collect_all_files(self, files=None):
"""
Collect all FSEntrys into a set, including all descendants.
:param list files: List of :class:`FSEntry` to traverse.
:returns: Set of FSEntry
"""
if files is None:
files = self._root_elements
collected = set()
for entry in files:
collected.add(entry)
collected.update(self._collect_all_files(entry.children))
return collected | python | def _collect_all_files(self, files=None):
"""
Collect all FSEntrys into a set, including all descendants.
:param list files: List of :class:`FSEntry` to traverse.
:returns: Set of FSEntry
"""
if files is None:
files = self._root_elements
collected = set()
for entry in files:
collected.add(entry)
collected.update(self._collect_all_files(entry.children))
return collected | [
"def",
"_collect_all_files",
"(",
"self",
",",
"files",
"=",
"None",
")",
":",
"if",
"files",
"is",
"None",
":",
"files",
"=",
"self",
".",
"_root_elements",
"collected",
"=",
"set",
"(",
")",
"for",
"entry",
"in",
"files",
":",
"collected",
".",
"add"... | Collect all FSEntrys into a set, including all descendants.
:param list files: List of :class:`FSEntry` to traverse.
:returns: Set of FSEntry | [
"Collect",
"all",
"FSEntrys",
"into",
"a",
"set",
"including",
"all",
"descendants",
"."
] | d95939cabdfdc25cb1bf67df0c84bd0d6e6a73ff | https://github.com/artefactual-labs/mets-reader-writer/blob/d95939cabdfdc25cb1bf67df0c84bd0d6e6a73ff/metsrw/mets.py#L61-L74 | train | 37,415 |
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 matches parameters, or None.
"""
# 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():
if all(value == getattr(entry, key) for key, value in kwargs.items()):
return entry
return None | 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 matches parameters, or None.
"""
# 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():
if all(value == getattr(entry, key) for key, value in kwargs.items()):
return entry
return None | [
"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",
"."
] | d95939cabdfdc25cb1bf67df0c84bd0d6e6a73ff | https://github.com/artefactual-labs/mets-reader-writer/blob/d95939cabdfdc25cb1bf67df0c84bd0d6e6a73ff/metsrw/mets.py#L87-L102 | train | 37,416 |
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 will be ignored.
:param metsrw.mets.FSEntry fs_entry: FSEntry to add to the METS document
"""
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)
self._all_files = None | 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 will be ignored.
:param metsrw.mets.FSEntry fs_entry: FSEntry to add to the METS document
"""
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)
self._all_files = None | [
"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 fs_entry: FSEntry to add to the METS document | [
"Adds",
"an",
"FSEntry",
"object",
"to",
"this",
"METS",
"document",
"s",
"tree",
".",
"Any",
"of",
"the",
"represented",
"object",
"s",
"children",
"will",
"also",
"be",
"added",
"to",
"the",
"document",
"."
] | d95939cabdfdc25cb1bf67df0c84bd0d6e6a73ff | https://github.com/artefactual-labs/mets-reader-writer/blob/d95939cabdfdc25cb1bf67df0c84bd0d6e6a73ff/metsrw/mets.py#L104-L119 | train | 37,417 |
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
"""
try:
self._root_elements.remove(fs_entry)
except ValueError: # fs_entry may not be in the root elements
pass
if fs_entry.parent:
fs_entry.parent.remove_child(fs_entry)
# Reset file lists so they get regenerated without the removed file(s)
self._all_files = None | 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
"""
try:
self._root_elements.remove(fs_entry)
except ValueError: # fs_entry may not be in the root elements
pass
if fs_entry.parent:
fs_entry.parent.remove_child(fs_entry)
# Reset file lists so they get regenerated without the removed file(s)
self._all_files = None | [
"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",
"."
] | d95939cabdfdc25cb1bf67df0c84bd0d6e6a73ff | https://github.com/artefactual-labs/mets-reader-writer/blob/d95939cabdfdc25cb1bf67df0c84bd0d6e6a73ff/metsrw/mets.py#L123-L138 | train | 37,418 |
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:
nsmap[None] = utils.NAMESPACES["mets"]
attrib = {
"{}schemaLocation".format(utils.lxmlns("xsi")): utils.SCHEMA_LOCATIONS
}
if self.objid:
attrib["OBJID"] = self.objid
return etree.Element(utils.lxmlns("mets") + "mets", nsmap=nsmap, attrib=attrib) | 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:
nsmap[None] = utils.NAMESPACES["mets"]
attrib = {
"{}schemaLocation".format(utils.lxmlns("xsi")): utils.SCHEMA_LOCATIONS
}
if self.objid:
attrib["OBJID"] = self.objid
return etree.Element(utils.lxmlns("mets") + "mets", nsmap=nsmap, attrib=attrib) | [
"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",
"."
] | d95939cabdfdc25cb1bf67df0c84bd0d6e6a73ff | https://github.com/artefactual-labs/mets-reader-writer/blob/d95939cabdfdc25cb1bf67df0c84bd0d6e6a73ff/metsrw/mets.py#L166-L180 | train | 37,419 |
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"CREATEDATE"] = self.createdate
header_attrs[u"LASTMODDATE"] = now
header_element = etree.Element(header_tag, **header_attrs)
for agent in self.agents:
header_element.append(agent.serialize())
for alternate_id in self.alternate_ids:
header_element.append(alternate_id.serialize())
return header_element | 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"CREATEDATE"] = self.createdate
header_attrs[u"LASTMODDATE"] = now
header_element = etree.Element(header_tag, **header_attrs)
for agent in self.agents:
header_element.append(agent.serialize())
for alternate_id in self.alternate_ids:
header_element.append(alternate_id.serialize())
return header_element | [
"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",
"."
] | d95939cabdfdc25cb1bf67df0c84bd0d6e6a73ff | https://github.com/artefactual-labs/mets-reader-writer/blob/d95939cabdfdc25cb1bf67df0c84bd0d6e6a73ff/metsrw/mets.py#L182-L201 | train | 37,420 |
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 MDSecs for.
:returns: List of AMDSecs and SubSections
"""
dmdsecs = []
amdsecs = []
for f in files:
for d in f.dmdsecs:
dmdsecs.append(d)
for a in f.amdsecs:
amdsecs.append(a)
dmdsecs.sort(key=lambda x: x.id_string)
amdsecs.sort(key=lambda x: x.id_string)
return dmdsecs + amdsecs | 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 MDSecs for.
:returns: List of AMDSecs and SubSections
"""
dmdsecs = []
amdsecs = []
for f in files:
for d in f.dmdsecs:
dmdsecs.append(d)
for a in f.amdsecs:
amdsecs.append(a)
dmdsecs.sort(key=lambda x: x.id_string)
amdsecs.sort(key=lambda x: x.id_string)
return dmdsecs + amdsecs | [
"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 SubSections | [
"Return",
"all",
"dmdSec",
"and",
"amdSec",
"classes",
"associated",
"with",
"the",
"files",
"."
] | d95939cabdfdc25cb1bf67df0c84bd0d6e6a73ff | https://github.com/artefactual-labs/mets-reader-writer/blob/d95939cabdfdc25cb1bf67df0c84bd0d6e6a73ff/metsrw/mets.py#L204-L224 | train | 37,421 |
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 hardcode this
LABEL="Archivematica default",
)
for item in self._root_elements:
child = item.serialize_structmap(recurse=True)
if child is not None:
structmap.append(child)
return structmap | 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 hardcode this
LABEL="Archivematica default",
)
for item in self._root_elements:
child = item.serialize_structmap(recurse=True)
if child is not None:
structmap.append(child)
return structmap | [
"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",
"."
] | d95939cabdfdc25cb1bf67df0c84bd0d6e6a73ff | https://github.com/artefactual-labs/mets-reader-writer/blob/d95939cabdfdc25cb1bf67df0c84bd0d6e6a73ff/metsrw/mets.py#L226-L243 | train | 37,422 |
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 file_.type.lower() not in ("item", AIP_ENTRY_TYPE):
continue
# Get fileGrp, or create if not exist
filegrp = filegrps.get(file_.use)
if filegrp is None:
filegrp = etree.SubElement(
filesec, utils.lxmlns("mets") + "fileGrp", USE=file_.use
)
filegrps[file_.use] = filegrp
file_el = file_.serialize_filesec()
if file_el is not None:
filegrp.append(file_el)
return filesec | 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 file_.type.lower() not in ("item", AIP_ENTRY_TYPE):
continue
# Get fileGrp, or create if not exist
filegrp = filegrps.get(file_.use)
if filegrp is None:
filegrp = etree.SubElement(
filesec, utils.lxmlns("mets") + "fileGrp", USE=file_.use
)
filegrps[file_.use] = filegrp
file_el = file_.serialize_filesec()
if file_el is not None:
filegrp.append(file_el)
return filesec | [
"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",
"."
] | d95939cabdfdc25cb1bf67df0c84bd0d6e6a73ff | https://github.com/artefactual-labs/mets-reader-writer/blob/d95939cabdfdc25cb1bf67df0c84bd0d6e6a73ff/metsrw/mets.py#L262-L286 | train | 37,423 |
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(files)
root = self._document_root(fully_qualified=fully_qualified)
root.append(self._mets_header(now=now))
for section in mdsecs:
root.append(section.serialize(now=now))
root.append(self._filesec(files))
root.append(self._structmap())
root.append(self._normative_structmap())
return root | 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(files)
root = self._document_root(fully_qualified=fully_qualified)
root.append(self._mets_header(now=now))
for section in mdsecs:
root.append(section.serialize(now=now))
root.append(self._filesec(files))
root.append(self._structmap())
root.append(self._normative_structmap())
return root | [
"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",
"."
] | d95939cabdfdc25cb1bf67df0c84bd0d6e6a73ff | https://github.com/artefactual-labs/mets-reader-writer/blob/d95939cabdfdc25cb1bf67df0c84bd0d6e6a73ff/metsrw/mets.py#L288-L304 | train | 37,424 |
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 ``unicode``.
:return: String of this document
"""
root = self.serialize(fully_qualified=fully_qualified)
kwargs = {"pretty_print": pretty_print, "encoding": encoding}
if encoding != "unicode":
kwargs["xml_declaration"] = True
return etree.tostring(root, **kwargs) | 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 ``unicode``.
:return: String of this document
"""
root = self.serialize(fully_qualified=fully_qualified)
kwargs = {"pretty_print": pretty_print, "encoding": encoding}
if encoding != "unicode":
kwargs["xml_declaration"] = True
return etree.tostring(root, **kwargs) | [
"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",
"."
] | d95939cabdfdc25cb1bf67df0c84bd0d6e6a73ff | https://github.com/artefactual-labs/mets-reader-writer/blob/d95939cabdfdc25cb1bf67df0c84bd0d6e6a73ff/metsrw/mets.py#L306-L321 | train | 37,425 |
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 filepath: Path to write the METS document to
"""
root = self.serialize(fully_qualified=fully_qualified)
tree = root.getroottree()
kwargs = {"pretty_print": pretty_print, "encoding": encoding}
if encoding != "unicode":
kwargs["xml_declaration"] = True
tree.write(filepath, **kwargs) | 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 filepath: Path to write the METS document to
"""
root = self.serialize(fully_qualified=fully_qualified)
tree = root.getroottree()
kwargs = {"pretty_print": pretty_print, "encoding": encoding}
if encoding != "unicode":
kwargs["xml_declaration"] = True
tree.write(filepath, **kwargs) | [
"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",
"."
] | d95939cabdfdc25cb1bf67df0c84bd0d6e6a73ff | https://github.com/artefactual-labs/mets-reader-writer/blob/d95939cabdfdc25cb1bf67df0c84bd0d6e6a73ff/metsrw/mets.py#L323-L338 | train | 37,426 |
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 normative div element with no non-normative
counterpart, that element is treated as a key with value ``None``.
This allows us to create ``FSEntry`` instances for empty directory div
elements, which are only documented in a normative logical structmap.
"""
el_to_normative = OrderedDict()
if normative_parent_elem is None:
for el in parent_elem:
el_to_normative[el] = None
else:
for norm_el in normative_parent_elem:
matches = [
el
for el in parent_elem
if el.get("TYPE") == norm_el.get("TYPE")
and el.get("LABEL") == norm_el.get("LABEL")
]
if matches:
el_to_normative[matches[0]] = norm_el
else:
el_to_normative[norm_el] = None
return el_to_normative | 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 normative div element with no non-normative
counterpart, that element is treated as a key with value ``None``.
This allows us to create ``FSEntry`` instances for empty directory div
elements, which are only documented in a normative logical structmap.
"""
el_to_normative = OrderedDict()
if normative_parent_elem is None:
for el in parent_elem:
el_to_normative[el] = None
else:
for norm_el in normative_parent_elem:
matches = [
el
for el in parent_elem
if el.get("TYPE") == norm_el.get("TYPE")
and el.get("LABEL") == norm_el.get("LABEL")
]
if matches:
el_to_normative[matches[0]] = norm_el
else:
el_to_normative[norm_el] = None
return el_to_normative | [
"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 is treated as a key with value ``None``.
This allows us to create ``FSEntry`` instances for empty directory div
elements, which are only documented in a normative logical structmap. | [
"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... | d95939cabdfdc25cb1bf67df0c84bd0d6e6a73ff | https://github.com/artefactual-labs/mets-reader-writer/blob/d95939cabdfdc25cb1bf67df0c84bd0d6e6a73ff/metsrw/mets.py#L388-L413 | train | 37,427 |
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",
"."
] | d95939cabdfdc25cb1bf67df0c84bd0d6e6a73ff | https://github.com/artefactual-labs/mets-reader-writer/blob/d95939cabdfdc25cb1bf67df0c84bd0d6e6a73ff/metsrw/mets.py#L555-L563 | train | 37,428 |
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.fromtree(tree) | 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.fromtree(tree) | [
"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",
"."
] | d95939cabdfdc25cb1bf67df0c84bd0d6e6a73ff | https://github.com/artefactual-labs/mets-reader-writer/blob/d95939cabdfdc25cb1bf67df0c84bd0d6e6a73ff/metsrw/mets.py#L566-L576 | train | 37,429 |
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",
"."
] | d95939cabdfdc25cb1bf67df0c84bd0d6e6a73ff | https://github.com/artefactual-labs/mets-reader-writer/blob/d95939cabdfdc25cb1bf67df0c84bd0d6e6a73ff/metsrw/mets.py#L579-L589 | train | 37,430 |
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_valid = schematron.validate(mets_doc)
report = schematron.validation_report
return is_valid, report | 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_valid = schematron.validate(mets_doc)
report = schematron.validation_report
return is_valid, report | [
"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",
"."
] | d95939cabdfdc25cb1bf67df0c84bd0d6e6a73ff | https://github.com/artefactual-labs/mets-reader-writer/blob/d95939cabdfdc25cb1bf67df0c84bd0d6e6a73ff/metsrw/validate.py#L98-L106 | train | 37,431 |
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", namespaces=namespaces)
):
ret.append(
"{}. {}".format(
index + 1,
failed_assert_el.find("svrl:text", namespaces=namespaces).text,
)
)
ret.append(" test: {}".format(failed_assert_el.attrib["test"]))
ret.append(" location: {}".format(failed_assert_el.attrib["location"]))
ret.append("\n")
return "\n".join(ret) | 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", namespaces=namespaces)
):
ret.append(
"{}. {}".format(
index + 1,
failed_assert_el.find("svrl:text", namespaces=namespaces).text,
)
)
ret.append(" test: {}".format(failed_assert_el.attrib["test"]))
ret.append(" location: {}".format(failed_assert_el.attrib["location"]))
ret.append("\n")
return "\n".join(ret) | [
"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",
"."
] | d95939cabdfdc25cb1bf67df0c84bd0d6e6a73ff | https://github.com/artefactual-labs/mets-reader-writer/blob/d95939cabdfdc25cb1bf67df0c84bd0d6e6a73ff/metsrw/validate.py#L109-L127 | train | 37,432 |
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"))
)
return "\n".join(ret) | 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"))
)
return "\n".join(ret) | [
"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",
"."
] | d95939cabdfdc25cb1bf67df0c84bd0d6e6a73ff | https://github.com/artefactual-labs/mets-reader-writer/blob/d95939cabdfdc25cb1bf67df0c84bd0d6e6a73ff/metsrw/validate.py#L130-L139 | train | 37,433 |
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"
] | f144e7acd221fab2a7f4867dd1430a8b1c941f90 | https://github.com/djk2/django-popup-view-field/blob/f144e7acd221fab2a7f4867dd1430a8b1c941f90/django_popup_view_field/widgets.py#L34-L40 | train | 37,434 |
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
sampled_data = dict((stat, "%s|@%s" % (value, sample_rate))
for stat, value in data.items())
else:
sampled_data = data
try:
[self.udp_sock.sendto(bytes(bytearray("%s:%s" % (stat, value),
"utf-8")), self.addr)
for stat, value in sampled_data.items()]
except:
self.log.exception("unexpected error") | 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
sampled_data = dict((stat, "%s|@%s" % (value, sample_rate))
for stat, value in data.items())
else:
sampled_data = data
try:
[self.udp_sock.sendto(bytes(bytearray("%s:%s" % (stat, value),
"utf-8")), self.addr)
for stat, value in sampled_data.items()]
except:
self.log.exception("unexpected error") | [
"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"
] | 69e362654c37df28582b12b964901334326620a7 | https://github.com/sivy/pystatsd/blob/69e362654c37df28582b12b964901334326620a7/pystatsd/statsd.py#L89-L110 | train | 37,435 |
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",
"."
] | 69e362654c37df28582b12b964901334326620a7 | https://github.com/sivy/pystatsd/blob/69e362654c37df28582b12b964901334326620a7/pystatsd/daemon.py#L108-L111 | train | 37,436 |
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 non-default
ones.
:param netloc:
:return:
"""
url = "https://%s/info/system?null" % (netloc)
response = requests.get(url, verify=self.verify)
if not response.ok or not hasattr(response, "json"):
error_message = '%s Unexpected Error: %s for uri: %s\nText: %r' %\
(response.status_code,
response.reason,
response.url,
response.text)
raise iControlUnexpectedHTTPError(error_message, response=response)
respJson = response.json()
result = respJson['providers']
return result | 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 non-default
ones.
:param netloc:
:return:
"""
url = "https://%s/info/system?null" % (netloc)
response = requests.get(url, verify=self.verify)
if not response.ok or not hasattr(response, "json"):
error_message = '%s Unexpected Error: %s for uri: %s\nText: %r' %\
(response.status_code,
response.reason,
response.url,
response.text)
raise iControlUnexpectedHTTPError(error_message, response=response)
respJson = response.json()
result = respJson['providers']
return result | [
"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:
:return: | [
"BIG",
"-",
"IQ",
"specific",
"query",
"for",
"auth",
"providers"
] | 34bb916299f4a00829352e7eb9818589408fa35a | https://github.com/F5Networks/f5-icontrol-rest-python/blob/34bb916299f4a00829352e7eb9818589408fa35a/icontrol/authtoken.py#L85-L108 | train | 37,437 |
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
is expired. It is usually not necessary for users to call it, but
it can be called if it is known that the authentication token has
been invalidated by other means.
"""
login_body = {
'username': self.username,
'password': self.password,
}
if self.auth_provider:
if self.auth_provider == 'local':
login_body['loginProviderName'] = 'local'
elif self.auth_provider == 'tmos':
login_body['loginProviderName'] = 'tmos'
elif self.auth_provider not in ['none', 'default']:
providers = self.get_auth_providers(netloc)
for provider in providers:
if self.auth_provider in provider['link']:
login_body['loginProviderName'] = provider['name']
break
elif self.auth_provider == provider['name']:
login_body['loginProviderName'] = provider['name']
break
else:
if self.login_provider_name == 'tmos':
login_body['loginProviderName'] = self.login_provider_name
login_url = "https://%s/mgmt/shared/authn/login" % (netloc)
response = requests.post(
login_url,
json=login_body,
verify=self.verify,
auth=HTTPBasicAuth(self.username, self.password)
)
self.attempts += 1
if not response.ok or not hasattr(response, "json"):
error_message = '%s Unexpected Error: %s for uri: %s\nText: %r' %\
(response.status_code,
response.reason,
response.url,
response.text)
raise iControlUnexpectedHTTPError(error_message,
response=response)
respJson = response.json()
token = self._get_token_from_response(respJson)
created_bigip = self._get_last_update_micros(token)
try:
expiration_bigip = self._get_expiration_micros(
token, created_bigip
)
except (KeyError, ValueError):
error_message = \
'%s Unparseable Response: %s for uri: %s\nText: %r' %\
(response.status_code,
response.reason,
response.url,
response.text)
raise iControlUnexpectedHTTPError(error_message,
response=response)
try:
self.expiration = self._get_token_expiration_time(
created_bigip, expiration_bigip
)
except iControlUnexpectedHTTPError:
error_message = \
'%s Token already expired: %s for uri: %s\nText: %r' % \
(response.status_code,
time.ctime(expiration_bigip),
response.url,
response.text)
raise iControlUnexpectedHTTPError(error_message,
response=response) | 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
is expired. It is usually not necessary for users to call it, but
it can be called if it is known that the authentication token has
been invalidated by other means.
"""
login_body = {
'username': self.username,
'password': self.password,
}
if self.auth_provider:
if self.auth_provider == 'local':
login_body['loginProviderName'] = 'local'
elif self.auth_provider == 'tmos':
login_body['loginProviderName'] = 'tmos'
elif self.auth_provider not in ['none', 'default']:
providers = self.get_auth_providers(netloc)
for provider in providers:
if self.auth_provider in provider['link']:
login_body['loginProviderName'] = provider['name']
break
elif self.auth_provider == provider['name']:
login_body['loginProviderName'] = provider['name']
break
else:
if self.login_provider_name == 'tmos':
login_body['loginProviderName'] = self.login_provider_name
login_url = "https://%s/mgmt/shared/authn/login" % (netloc)
response = requests.post(
login_url,
json=login_body,
verify=self.verify,
auth=HTTPBasicAuth(self.username, self.password)
)
self.attempts += 1
if not response.ok or not hasattr(response, "json"):
error_message = '%s Unexpected Error: %s for uri: %s\nText: %r' %\
(response.status_code,
response.reason,
response.url,
response.text)
raise iControlUnexpectedHTTPError(error_message,
response=response)
respJson = response.json()
token = self._get_token_from_response(respJson)
created_bigip = self._get_last_update_micros(token)
try:
expiration_bigip = self._get_expiration_micros(
token, created_bigip
)
except (KeyError, ValueError):
error_message = \
'%s Unparseable Response: %s for uri: %s\nText: %r' %\
(response.status_code,
response.reason,
response.url,
response.text)
raise iControlUnexpectedHTTPError(error_message,
response=response)
try:
self.expiration = self._get_token_expiration_time(
created_bigip, expiration_bigip
)
except iControlUnexpectedHTTPError:
error_message = \
'%s Token already expired: %s for uri: %s\nText: %r' % \
(response.status_code,
time.ctime(expiration_bigip),
response.url,
response.text)
raise iControlUnexpectedHTTPError(error_message,
response=response) | [
"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 for users to call it, but
it can be called if it is known that the authentication token has
been invalidated by other means. | [
"Get",
"a",
"new",
"token",
"from",
"BIG",
"-",
"IP",
"and",
"store",
"it",
"internally",
"."
] | 34bb916299f4a00829352e7eb9818589408fa35a | https://github.com/F5Networks/f5-icontrol-rest-python/blob/34bb916299f4a00829352e7eb9818589408fa35a/icontrol/authtoken.py#L110-L192 | train | 37,438 |
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 with a call to
`generate_bigip_uri`.
Then it:
1. pre-logs the details of the request
2. submits the request
3. logs the response, included expected status codes
4. raises exceptions for unexpected status codes. (i.e. not doc'd as BigIP
RESTServer codes.)
"""
@functools.wraps(method)
def wrapper(self, RIC_base_uri, **kwargs):
partition = kwargs.pop('partition', '')
sub_path = kwargs.pop('subPath', '')
suffix = kwargs.pop('suffix', '')
identifier, kwargs = _unique_resource_identifier_from_kwargs(**kwargs)
uri_as_parts = kwargs.pop('uri_as_parts', False)
transform_name = kwargs.pop('transform_name', False)
transform_subpath = kwargs.pop('transform_subpath', False)
if uri_as_parts:
REST_uri = generate_bigip_uri(RIC_base_uri, partition, identifier,
sub_path, suffix,
transform_name=transform_name,
transform_subpath=transform_subpath,
**kwargs)
else:
REST_uri = RIC_base_uri
pre_message = "%s WITH uri: %s AND suffix: %s AND kwargs: %s" %\
(method.__name__, REST_uri, suffix, kwargs)
logger = logging.getLogger(__name__)
logger.debug(pre_message)
response = method(self, REST_uri, **kwargs)
post_message =\
"RESPONSE::STATUS: %s Content-Type: %s Content-Encoding:"\
" %s\nText: %r" % (response.status_code,
response.headers.get('Content-Type', None),
response.headers.get('Content-Encoding', None),
response.text)
logger.debug(post_message)
if response.status_code not in range(200, 207):
error_message = '%s Unexpected Error: %s for uri: %s\nText: %r' %\
(response.status_code,
response.reason,
response.url,
response.text)
raise iControlUnexpectedHTTPError(error_message, response=response)
return response
return wrapper | 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 with a call to
`generate_bigip_uri`.
Then it:
1. pre-logs the details of the request
2. submits the request
3. logs the response, included expected status codes
4. raises exceptions for unexpected status codes. (i.e. not doc'd as BigIP
RESTServer codes.)
"""
@functools.wraps(method)
def wrapper(self, RIC_base_uri, **kwargs):
partition = kwargs.pop('partition', '')
sub_path = kwargs.pop('subPath', '')
suffix = kwargs.pop('suffix', '')
identifier, kwargs = _unique_resource_identifier_from_kwargs(**kwargs)
uri_as_parts = kwargs.pop('uri_as_parts', False)
transform_name = kwargs.pop('transform_name', False)
transform_subpath = kwargs.pop('transform_subpath', False)
if uri_as_parts:
REST_uri = generate_bigip_uri(RIC_base_uri, partition, identifier,
sub_path, suffix,
transform_name=transform_name,
transform_subpath=transform_subpath,
**kwargs)
else:
REST_uri = RIC_base_uri
pre_message = "%s WITH uri: %s AND suffix: %s AND kwargs: %s" %\
(method.__name__, REST_uri, suffix, kwargs)
logger = logging.getLogger(__name__)
logger.debug(pre_message)
response = method(self, REST_uri, **kwargs)
post_message =\
"RESPONSE::STATUS: %s Content-Type: %s Content-Encoding:"\
" %s\nText: %r" % (response.status_code,
response.headers.get('Content-Type', None),
response.headers.get('Content-Encoding', None),
response.text)
logger.debug(post_message)
if response.status_code not in range(200, 207):
error_message = '%s Unexpected Error: %s for uri: %s\nText: %r' %\
(response.status_code,
response.reason,
response.url,
response.text)
raise iControlUnexpectedHTTPError(error_message, response=response)
return response
return wrapper | [
"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`.
Then it:
1. pre-logs the details of the request
2. submits the request
3. logs the response, included expected status codes
4. raises exceptions for unexpected status codes. (i.e. not doc'd as BigIP
RESTServer codes.) | [
"Prepare",
"and",
"Post",
"-",
"Process",
"HTTP",
"VERB",
"method",
"for",
"BigIP",
"-",
"RESTServer",
"request",
"."
] | 34bb916299f4a00829352e7eb9818589408fa35a | https://github.com/F5Networks/f5-icontrol-rest-python/blob/34bb916299f4a00829352e7eb9818589408fa35a/icontrol/session.py#L243-L297 | train | 37,439 |
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' and other
times is 'uuid'.
For example, in iWorkflow, there consider this URI
* https://10.2.2.3/mgmt/cm/cloud/tenants/{0}/services/iapp
Then consider this iWorkflow URI
* https://localhost/mgmt/cm/cloud/connectors/local/{0}
In the first example, the identifier, {0}, is what we would normally
consider a name. For example, "tenant1". In the second example though,
the value is expected to be what we would normally consider to be a
UUID. For example, '244bd478-374e-4eb2-8c73-6e46d7112604'.
This method only tries to rectify the problem of which to use.
I believe there might be some change that the two can appear together,
although I have not yet experienced it. If it is possible, I believe it
would happen in BIG-IQ/iWorkflow land where the UUID and Name both have
significance. That's why I deliberately prefer the UUID when it exists
in the parameters sent to the URL.
:param kwargs:
:return:
"""
name = kwargs.pop('name', '')
uuid = kwargs.pop('uuid', '')
id = kwargs.pop('id', '')
if uuid:
return uuid, kwargs
elif id:
# Used for /mgmt/cm/system/authn/providers/tmos on BIG-IP
return id, kwargs
else:
return name, kwargs | 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' and other
times is 'uuid'.
For example, in iWorkflow, there consider this URI
* https://10.2.2.3/mgmt/cm/cloud/tenants/{0}/services/iapp
Then consider this iWorkflow URI
* https://localhost/mgmt/cm/cloud/connectors/local/{0}
In the first example, the identifier, {0}, is what we would normally
consider a name. For example, "tenant1". In the second example though,
the value is expected to be what we would normally consider to be a
UUID. For example, '244bd478-374e-4eb2-8c73-6e46d7112604'.
This method only tries to rectify the problem of which to use.
I believe there might be some change that the two can appear together,
although I have not yet experienced it. If it is possible, I believe it
would happen in BIG-IQ/iWorkflow land where the UUID and Name both have
significance. That's why I deliberately prefer the UUID when it exists
in the parameters sent to the URL.
:param kwargs:
:return:
"""
name = kwargs.pop('name', '')
uuid = kwargs.pop('uuid', '')
id = kwargs.pop('id', '')
if uuid:
return uuid, kwargs
elif id:
# Used for /mgmt/cm/system/authn/providers/tmos on BIG-IP
return id, kwargs
else:
return name, kwargs | [
"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 iWorkflow, there consider this URI
* https://10.2.2.3/mgmt/cm/cloud/tenants/{0}/services/iapp
Then consider this iWorkflow URI
* https://localhost/mgmt/cm/cloud/connectors/local/{0}
In the first example, the identifier, {0}, is what we would normally
consider a name. For example, "tenant1". In the second example though,
the value is expected to be what we would normally consider to be a
UUID. For example, '244bd478-374e-4eb2-8c73-6e46d7112604'.
This method only tries to rectify the problem of which to use.
I believe there might be some change that the two can appear together,
although I have not yet experienced it. If it is possible, I believe it
would happen in BIG-IQ/iWorkflow land where the UUID and Name both have
significance. That's why I deliberately prefer the UUID when it exists
in the parameters sent to the URL.
:param kwargs:
:return: | [
"Chooses",
"an",
"identifier",
"given",
"different",
"choices"
] | 34bb916299f4a00829352e7eb9818589408fa35a | https://github.com/F5Networks/f5-icontrol-rest-python/blob/34bb916299f4a00829352e7eb9818589408fa35a/icontrol/session.py#L300-L341 | train | 37,440 |
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`` passed
in separated by ~ to create a proper BIGIP REST API URL for objects.
All other parameters passed in as ``**kwargs`` are passed directly
to the :meth:`requests.Session.delete`
:param uri: A HTTP URI
:type uri: str
:param name: The object name that will be appended to the uri
:type name: str
:arg partition: The partition name that will be appened to the uri
:type partition: str
:param \**kwargs: The :meth:`reqeusts.Session.delete` optional params
"""
args1 = get_request_args(kwargs)
args2 = get_send_args(kwargs)
req = requests.Request('DELETE', uri, **args1)
prepared = self.session.prepare_request(req)
if self.debug:
self._debug_output.append(debug_prepared_request(prepared))
return self.session.send(prepared, **args2) | 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`` passed
in separated by ~ to create a proper BIGIP REST API URL for objects.
All other parameters passed in as ``**kwargs`` are passed directly
to the :meth:`requests.Session.delete`
:param uri: A HTTP URI
:type uri: str
:param name: The object name that will be appended to the uri
:type name: str
:arg partition: The partition name that will be appened to the uri
:type partition: str
:param \**kwargs: The :meth:`reqeusts.Session.delete` optional params
"""
args1 = get_request_args(kwargs)
args2 = get_send_args(kwargs)
req = requests.Request('DELETE', uri, **args1)
prepared = self.session.prepare_request(req)
if self.debug:
self._debug_output.append(debug_prepared_request(prepared))
return self.session.send(prepared, **args2) | [
"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 proper BIGIP REST API URL for objects.
All other parameters passed in as ``**kwargs`` are passed directly
to the :meth:`requests.Session.delete`
:param uri: A HTTP URI
:type uri: str
:param name: The object name that will be appended to the uri
:type name: str
:arg partition: The partition name that will be appened to the uri
:type partition: str
:param \**kwargs: The :meth:`reqeusts.Session.delete` optional params | [
"Sends",
"a",
"HTTP",
"DELETE",
"command",
"to",
"the",
"BIGIP",
"REST",
"Server",
"."
] | 34bb916299f4a00829352e7eb9818589408fa35a | https://github.com/F5Networks/f5-icontrol-rest-python/blob/34bb916299f4a00829352e7eb9818589408fa35a/icontrol/session.py#L474-L499 | train | 37,441 |
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-Agent header
:type user_agent: str
"""
old_ua = self.session.headers.get('User-Agent', '')
ua = old_ua + ' ' + user_agent
self.session.headers['User-Agent'] = ua.strip() | 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-Agent header
:type user_agent: str
"""
old_ua = self.session.headers.get('User-Agent', '')
ua = old_ua + ' ' + user_agent
self.session.headers['User-Agent'] = ua.strip() | [
"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",
"."
] | 34bb916299f4a00829352e7eb9818589408fa35a | https://github.com/F5Networks/f5-icontrol-rest-python/blob/34bb916299f4a00829352e7eb9818589408fa35a/icontrol/session.py#L623-L634 | train | 37,442 |
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 not is_valid:
try:
load(value.encode('utf-8'), default_backend())
is_valid = True
except Exception as e:
exc = e
if not is_valid:
raise ValidationError('Public key is invalid: %s' % exc) | 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 not is_valid:
try:
load(value.encode('utf-8'), default_backend())
is_valid = True
except Exception as e:
exc = e
if not is_valid:
raise ValidationError('Public key is invalid: %s' % exc) | [
"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",
"."
] | eae1a6474b6141edce4d6be2dc1746e18bbf5318 | https://github.com/crgwbr/asymmetric-jwt-auth/blob/eae1a6474b6141edce4d6be2dc1746e18bbf5318/src/asymmetric_jwt_auth/models.py#L8-L25 | train | 37,443 |
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, fmt)))) | 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, fmt)))) | [
"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",
"."
] | 4417ee34e85c88c874f0a5ae93bc54b0f5d93af0 | https://github.com/kenneth-reitz/pyandoc/blob/4417ee34e85c88c874f0a5ae93bc54b0f5d93af0/pandoc/core.py#L73-L79 | train | 37,444 |
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.
:param generate_nonce: Optional. Callable to use to generate a new nonce. Defaults to
`random.random <https://docs.python.org/3/library/random.html#random.random>`_.
:param iat: Optional. Timestamp to include in the JWT claim. Defaults to
`time.time <https://docs.python.org/3/library/time.html#time.time>`_.
:param algorithm: Optional. Algorithm to use to sign the JWT claim. Default to ``RS512``.
See `pyjwt.readthedocs.io <https://pyjwt.readthedocs.io/en/latest/algorithms.html>`_ for other possible algorithms.
:return: JWT claim as a string.
"""
iat = iat if iat else time.time()
if not generate_nonce:
generate_nonce = lambda username, iat: random.random() # NOQA
token_data = {
'username': username,
'time': iat,
'nonce': generate_nonce(username, iat),
}
token = jwt.encode(token_data, private_key, algorithm=algorithm)
return token | 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.
:param generate_nonce: Optional. Callable to use to generate a new nonce. Defaults to
`random.random <https://docs.python.org/3/library/random.html#random.random>`_.
:param iat: Optional. Timestamp to include in the JWT claim. Defaults to
`time.time <https://docs.python.org/3/library/time.html#time.time>`_.
:param algorithm: Optional. Algorithm to use to sign the JWT claim. Default to ``RS512``.
See `pyjwt.readthedocs.io <https://pyjwt.readthedocs.io/en/latest/algorithms.html>`_ for other possible algorithms.
:return: JWT claim as a string.
"""
iat = iat if iat else time.time()
if not generate_nonce:
generate_nonce = lambda username, iat: random.random() # NOQA
token_data = {
'username': username,
'time': iat,
'nonce': generate_nonce(username, iat),
}
token = jwt.encode(token_data, private_key, algorithm=algorithm)
return token | [
"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.random <https://docs.python.org/3/library/random.html#random.random>`_.
:param iat: Optional. Timestamp to include in the JWT claim. Defaults to
`time.time <https://docs.python.org/3/library/time.html#time.time>`_.
:param algorithm: Optional. Algorithm to use to sign the JWT claim. Default to ``RS512``.
See `pyjwt.readthedocs.io <https://pyjwt.readthedocs.io/en/latest/algorithms.html>`_ for other possible algorithms.
:return: JWT claim as a string. | [
"Create",
"a",
"signed",
"JWT",
"using",
"the",
"given",
"username",
"and",
"RSA",
"private",
"key",
"."
] | eae1a6474b6141edce4d6be2dc1746e18bbf5318 | https://github.com/crgwbr/asymmetric-jwt-auth/blob/eae1a6474b6141edce4d6be2dc1746e18bbf5318/src/asymmetric_jwt_auth/token.py#L16-L41 | train | 37,445 |
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' not in unverified_data:
return None
return unverified_data['username'] | 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' not in unverified_data:
return None
return unverified_data['username'] | [
"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",
"."
] | eae1a6474b6141edce4d6be2dc1746e18bbf5318 | https://github.com/crgwbr/asymmetric-jwt-auth/blob/eae1a6474b6141edce4d6be2dc1746e18bbf5318/src/asymmetric_jwt_auth/token.py#L44-L57 | train | 37,446 |
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 validate the claim's nonce.
:param algorithms: Allowable signing algorithms. Defaults to ['RS512'].
:return: False if the token is determined to be invalid or a dictionary of the token data if it is valid.
"""
try:
token_data = jwt.decode(token, public_key, algorithms=algorithms)
except jwt.InvalidTokenError:
logger.debug('JWT failed verification')
return False
claimed_username = token_data.get('username')
claimed_time = token_data.get('time', 0)
claimed_nonce = token_data.get('nonce')
# Ensure time is within acceptable bounds
current_time = time.time()
min_time, max_time = (current_time - TIMESTAMP_TOLERANCE, current_time + TIMESTAMP_TOLERANCE)
if claimed_time < min_time or claimed_time > max_time:
logger.debug('Claimed time is outside of allowable tolerances')
return False
# Ensure nonce is unique
if validate_nonce:
if not validate_nonce(claimed_username, claimed_time, claimed_nonce):
logger.debug('Claimed nonce failed to validate')
return False
else:
logger.warning('validate_nonce function was not supplied!')
# If we've gotten this far, the token is valid
return token_data | 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 validate the claim's nonce.
:param algorithms: Allowable signing algorithms. Defaults to ['RS512'].
:return: False if the token is determined to be invalid or a dictionary of the token data if it is valid.
"""
try:
token_data = jwt.decode(token, public_key, algorithms=algorithms)
except jwt.InvalidTokenError:
logger.debug('JWT failed verification')
return False
claimed_username = token_data.get('username')
claimed_time = token_data.get('time', 0)
claimed_nonce = token_data.get('nonce')
# Ensure time is within acceptable bounds
current_time = time.time()
min_time, max_time = (current_time - TIMESTAMP_TOLERANCE, current_time + TIMESTAMP_TOLERANCE)
if claimed_time < min_time or claimed_time > max_time:
logger.debug('Claimed time is outside of allowable tolerances')
return False
# Ensure nonce is unique
if validate_nonce:
if not validate_nonce(claimed_username, claimed_time, claimed_nonce):
logger.debug('Claimed nonce failed to validate')
return False
else:
logger.warning('validate_nonce function was not supplied!')
# If we've gotten this far, the token is valid
return token_data | [
"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'].
:return: False if the token is determined to be invalid or a dictionary of the token data if it is valid. | [
"Verify",
"the",
"validity",
"of",
"the",
"given",
"JWT",
"using",
"the",
"given",
"public",
"key",
"."
] | eae1a6474b6141edce4d6be2dc1746e18bbf5318 | https://github.com/crgwbr/asymmetric-jwt-auth/blob/eae1a6474b6141edce4d6be2dc1746e18bbf5318/src/asymmetric_jwt_auth/token.py#L60-L96 | train | 37,447 |
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: 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 not everyone uses it.
key = self.create_nonce_key(username, iat)
used = cache.get(key, [])
used.append(nonce)
cache.set(key, set(used), token.TIMESTAMP_TOLERANCE * 2) | 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: 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 not everyone uses it.
key = self.create_nonce_key(username, iat)
used = cache.get(key, [])
used.append(nonce)
cache.set(key, set(used), token.TIMESTAMP_TOLERANCE * 2) | [
"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",
"."
] | eae1a6474b6141edce4d6be2dc1746e18bbf5318 | https://github.com/crgwbr/asymmetric-jwt-auth/blob/eae1a6474b6141edce4d6be2dc1746e18bbf5318/src/asymmetric_jwt_auth/middleware.py#L29-L43 | train | 37,448 |
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 valid, False if it is invalid.
"""
key = self.create_nonce_key(username, iat)
used = cache.get(key, [])
return nonce not in used | 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 valid, False if it is invalid.
"""
key = self.create_nonce_key(username, iat)
used = cache.get(key, [])
return nonce not in used | [
"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",
"."
] | eae1a6474b6141edce4d6be2dc1746e18bbf5318 | https://github.com/crgwbr/asymmetric-jwt-auth/blob/eae1a6474b6141edce4d6be2dc1746e18bbf5318/src/asymmetric_jwt_auth/middleware.py#L46-L57 | train | 37,449 |
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
the request.
:param request: Django Request instance
"""
if 'HTTP_AUTHORIZATION' not in request.META:
return
try:
method, claim = request.META['HTTP_AUTHORIZATION'].split(' ', 1)
except ValueError:
return
if method.upper() != AUTH_METHOD:
return
username = token.get_claimed_username(claim)
if not username:
return
User = get_user_model()
try:
user = User.objects.get(username=username)
except User.DoesNotExist:
return
claim_data = None
for public in user.public_keys.all():
claim_data = token.verify(claim, public.key, validate_nonce=self.validate_nonce)
if claim_data:
break
if not claim_data:
return
logger.debug('Successfully authenticated %s using JWT', user.username)
request._dont_enforce_csrf_checks = True
request.user = user | 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
the request.
:param request: Django Request instance
"""
if 'HTTP_AUTHORIZATION' not in request.META:
return
try:
method, claim = request.META['HTTP_AUTHORIZATION'].split(' ', 1)
except ValueError:
return
if method.upper() != AUTH_METHOD:
return
username = token.get_claimed_username(claim)
if not username:
return
User = get_user_model()
try:
user = User.objects.get(username=username)
except User.DoesNotExist:
return
claim_data = None
for public in user.public_keys.all():
claim_data = token.verify(claim, public.key, validate_nonce=self.validate_nonce)
if claim_data:
break
if not claim_data:
return
logger.debug('Successfully authenticated %s using JWT', user.username)
request._dont_enforce_csrf_checks = True
request.user = user | [
"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 Request instance | [
"Process",
"a",
"Django",
"request",
"and",
"authenticate",
"users",
"."
] | eae1a6474b6141edce4d6be2dc1746e18bbf5318 | https://github.com/crgwbr/asymmetric-jwt-auth/blob/eae1a6474b6141edce4d6be2dc1746e18bbf5318/src/asymmetric_jwt_auth/middleware.py#L60-L101 | train | 37,450 |
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.expanduser(key_file)
key_file = os.path.abspath(key_file)
if not key_password:
with open(key_file, 'r') as key:
return key.read()
with open(key_file, 'rb') as key:
key_bytes = key.read()
return decrypt_key(key_bytes, key_password).decode(ENCODING) | 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.expanduser(key_file)
key_file = os.path.abspath(key_file)
if not key_password:
with open(key_file, 'r') as key:
return key.read()
with open(key_file, 'rb') as key:
key_bytes = key.read()
return decrypt_key(key_bytes, key_password).decode(ENCODING) | [
"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",
"."
] | eae1a6474b6141edce4d6be2dc1746e18bbf5318 | https://github.com/crgwbr/asymmetric-jwt-auth/blob/eae1a6474b6141edce4d6be2dc1746e18bbf5318/src/asymmetric_jwt_auth/__init__.py#L52-L69 | train | 37,451 |
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())
return private.private_bytes(Encoding.PEM, PrivateFormat.PKCS8, NoEncryption()) | 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())
return private.private_bytes(Encoding.PEM, PrivateFormat.PKCS8, NoEncryption()) | [
"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",
"."
] | eae1a6474b6141edce4d6be2dc1746e18bbf5318 | https://github.com/crgwbr/asymmetric-jwt-auth/blob/eae1a6474b6141edce4d6be2dc1746e18bbf5318/src/asymmetric_jwt_auth/__init__.py#L72-L81 | train | 37,452 |
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 private key as either a string or an instance of cryptography.hazmat.primitives.asymmetric.rsa.RSAPrivateKey.
:param key_file: Optional. Path to a file containing the user's private key. Defaults to ~/.ssh/id_rsa. Should be in PEM format.
:param key_password: Optional. Password to decrypt key_file. If set, should be a bytes object.
:return: Authentication header value as a string.
"""
if not key:
key = load_private_key(key_file, key_password)
claim = token.sign(username, key)
return "%s %s" % (AUTH_METHOD, claim.decode(ENCODING)) | 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 private key as either a string or an instance of cryptography.hazmat.primitives.asymmetric.rsa.RSAPrivateKey.
:param key_file: Optional. Path to a file containing the user's private key. Defaults to ~/.ssh/id_rsa. Should be in PEM format.
:param key_password: Optional. Password to decrypt key_file. If set, should be a bytes object.
:return: Authentication header value as a string.
"""
if not key:
key = load_private_key(key_file, key_password)
claim = token.sign(username, key)
return "%s %s" % (AUTH_METHOD, claim.decode(ENCODING)) | [
"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.RSAPrivateKey.
:param key_file: Optional. Path to a file containing the user's private key. Defaults to ~/.ssh/id_rsa. Should be in PEM format.
:param key_password: Optional. Password to decrypt key_file. If set, should be a bytes object.
:return: Authentication header value as a string. | [
"Create",
"an",
"HTTP",
"Authorization",
"header",
"using",
"a",
"private",
"key",
"file",
"."
] | eae1a6474b6141edce4d6be2dc1746e18bbf5318 | https://github.com/crgwbr/asymmetric-jwt-auth/blob/eae1a6474b6141edce4d6be2dc1746e18bbf5318/src/asymmetric_jwt_auth/__init__.py#L84-L99 | train | 37,453 |
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='[%(levelname)s]:%(message)s',
# Reset handlers
for h in list(logging.root.handlers):
logging.root.removeHandler(h)
global _log_level
if lvl: _log_level = lvl
logging.basicConfig(level=_log_level, format=FORMAT, stream=sys.stdout)
_log = logging.getLogger(__name__)
_log.setLevel(_log_level)
# external
for log in ['urllib3', 'asyncio']:
logging.getLogger(log).setLevel(_log_level) | 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='[%(levelname)s]:%(message)s',
# Reset handlers
for h in list(logging.root.handlers):
logging.root.removeHandler(h)
global _log_level
if lvl: _log_level = lvl
logging.basicConfig(level=_log_level, format=FORMAT, stream=sys.stdout)
_log = logging.getLogger(__name__)
_log.setLevel(_log_level)
# external
for log in ['urllib3', 'asyncio']:
logging.getLogger(log).setLevel(_log_level) | [
"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",
"."
] | cf2060a1d5ef879a01cf849e54b7756909ab2661 | https://github.com/peeringdb/peeringdb-py/blob/cf2060a1d5ef879a01cf849e54b7756909ab2661/peeringdb/__init__.py#L12-L37 | train | 37,454 |
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(value_len, len(self._get_name(key))))
fmt = self.mk_fmt(*lens)
return fmt | 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(value_len, len(self._get_name(key))))
fmt = self.mk_fmt(*lens)
return fmt | [
"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"
] | cf2060a1d5ef879a01cf849e54b7756909ab2661 | https://github.com/peeringdb/peeringdb-py/blob/cf2060a1d5ef879a01cf849e54b7756909ab2661/peeringdb/whois.py#L19-L30 | train | 37,455 |
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"
] | cf2060a1d5ef879a01cf849e54b7756909ab2661 | https://github.com/peeringdb/peeringdb-py/blob/cf2060a1d5ef879a01cf849e54b7756909ab2661/peeringdb/whois.py#L32-L37 | train | 37,456 |
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 each in data:
row = tuple(self._get_val(each, k) for k, v in each.items())
self._print(fmt % row)
self._print("\n") | 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 each in data:
row = tuple(self._get_val(each, k) for k, v in each.items())
self._print(fmt % row)
self._print("\n") | [
"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"
] | cf2060a1d5ef879a01cf849e54b7756909ab2661 | https://github.com/peeringdb/peeringdb-py/blob/cf2060a1d5ef879a01cf849e54b7756909ab2661/peeringdb/whois.py#L56-L67 | train | 37,457 |
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"
] | cf2060a1d5ef879a01cf849e54b7756909ab2661 | https://github.com/peeringdb/peeringdb-py/blob/cf2060a1d5ef879a01cf849e54b7756909ab2661/peeringdb/whois.py#L152-L155 | train | 37,458 |
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("\n", typ)
for k, v in data.items():
self.print(k, v)
elif isinstance(data, (list, tuple)):
# tabular data layout for lists of dicts
if isinstance(data[0], collections.Mapping):
self.display_set(typ, data, self._get_columns(data[0]))
else:
for each in data:
self.print(typ, each)
else:
self._print("%s: %s" % (typ, data))
self.fobj.flush() | 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("\n", typ)
for k, v in data.items():
self.print(k, v)
elif isinstance(data, (list, tuple)):
# tabular data layout for lists of dicts
if isinstance(data[0], collections.Mapping):
self.display_set(typ, data, self._get_columns(data[0]))
else:
for each in data:
self.print(typ, each)
else:
self._print("%s: %s" % (typ, data))
self.fobj.flush() | [
"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"
] | cf2060a1d5ef879a01cf849e54b7756909ab2661 | https://github.com/peeringdb/peeringdb-py/blob/cf2060a1d5ef879a01cf849e54b7756909ab2661/peeringdb/whois.py#L161-L184 | train | 37,459 |
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"
] | cf2060a1d5ef879a01cf849e54b7756909ab2661 | https://github.com/peeringdb/peeringdb-py/blob/cf2060a1d5ef879a01cf849e54b7756909ab2661/peeringdb/commands.py#L16-L24 | train | 37,460 |
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(cls, 'handle', None)
if handler:
subp.set_defaults(handler=handler) | 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(cls, 'handle', None)
if handler:
subp.set_defaults(handler=handler) | [
"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"
] | cf2060a1d5ef879a01cf849e54b7756909ab2661 | https://github.com/peeringdb/peeringdb-py/blob/cf2060a1d5ef879a01cf849e54b7756909ab2661/peeringdb/commands.py#L27-L37 | train | 37,461 |
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=since)
self._update(res, fetch, depth) | 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=since)
self._update(res, fetch, depth) | [
"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"
] | cf2060a1d5ef879a01cf849e54b7756909ab2661 | https://github.com/peeringdb/peeringdb-py/blob/cf2060a1d5ef879a01cf849e54b7756909ab2661/peeringdb/_update.py#L44-L51 | train | 37,462 |
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"
] | cf2060a1d5ef879a01cf849e54b7756909ab2661 | https://github.com/peeringdb/peeringdb-py/blob/cf2060a1d5ef879a01cf849e54b7756909ab2661/peeringdb/_update.py#L121-L126 | train | 37,463 |
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[res].get(pk)
had = bool(job)
if not job:
job = task
jobs[res][pk] = job
else:
task.cancel()
self._log.debug('Scheduling: %s-%s (%s)', res.tag, pk,
'new task' if not had else 'dup')
return job | 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[res].get(pk)
had = bool(job)
if not job:
job = task
jobs[res][pk] = job
else:
task.cancel()
self._log.debug('Scheduling: %s-%s (%s)', res.tag, pk,
'new task' if not had else 'dup')
return job | [
"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",
"."
] | cf2060a1d5ef879a01cf849e54b7756909ab2661 | https://github.com/peeringdb/peeringdb-py/blob/cf2060a1d5ef879a01cf849e54b7756909ab2661/peeringdb/_update.py#L128-L148 | train | 37,464 |
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"
] | cf2060a1d5ef879a01cf849e54b7756909ab2661 | https://github.com/peeringdb/peeringdb-py/blob/cf2060a1d5ef879a01cf849e54b7756909ab2661/peeringdb/_update.py#L150-L154 | train | 37,465 |
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"
] | cf2060a1d5ef879a01cf849e54b7756909ab2661 | https://github.com/peeringdb/peeringdb-py/blob/cf2060a1d5ef879a01cf849e54b7756909ab2661/peeringdb/_update.py#L157-L161 | train | 37,466 |
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), row['id'])
except B.object_missing_error(B.get_concrete(res)):
tbl = B.get_concrete(res)
obj = tbl()
# Set attributes, refs
for fname, field in field_groups['scalars'].items():
value = row.get(fname, getattr(obj, fname, None))
value = B.convert_field(obj.__class__, fname, value)
setattr(obj, fname, value)
# _debug('res, row: %s, %s', res, row)
# Already-fetched, and id-only refs
fetched, dangling = defaultdict(dict), defaultdict(set)
# To handle subrows that might be shallow (id) or deep (dict)
def _handle_subrow(R, subrow):
if isinstance(subrow, dict):
pk = subrow['id']
fetched[R][pk] = subrow
else:
pk = subrow
dangling[R].add(pk)
return pk
for fname, field in field_groups['one_refs'].items():
fieldres = _field_resource(B, B.get_concrete(res), fname)
key = field.column
subrow = row.get(key)
if subrow is None: # e.g. use "org" if "org_id" is missing
key = fname
subrow = row[key]
pk = _handle_subrow(fieldres, subrow)
setattr(obj, key, pk)
for fname, field in field_groups['many_refs'].items():
fieldres = _field_resource(B, B.get_concrete(res), fname)
pks = [
_handle_subrow(fieldres, subrow) for subrow in row.get(fname, [])
]
return obj, fetched, dangling | 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), row['id'])
except B.object_missing_error(B.get_concrete(res)):
tbl = B.get_concrete(res)
obj = tbl()
# Set attributes, refs
for fname, field in field_groups['scalars'].items():
value = row.get(fname, getattr(obj, fname, None))
value = B.convert_field(obj.__class__, fname, value)
setattr(obj, fname, value)
# _debug('res, row: %s, %s', res, row)
# Already-fetched, and id-only refs
fetched, dangling = defaultdict(dict), defaultdict(set)
# To handle subrows that might be shallow (id) or deep (dict)
def _handle_subrow(R, subrow):
if isinstance(subrow, dict):
pk = subrow['id']
fetched[R][pk] = subrow
else:
pk = subrow
dangling[R].add(pk)
return pk
for fname, field in field_groups['one_refs'].items():
fieldres = _field_resource(B, B.get_concrete(res), fname)
key = field.column
subrow = row.get(key)
if subrow is None: # e.g. use "org" if "org_id" is missing
key = fname
subrow = row[key]
pk = _handle_subrow(fieldres, subrow)
setattr(obj, key, pk)
for fname, field in field_groups['many_refs'].items():
fieldres = _field_resource(B, B.get_concrete(res), fname)
pks = [
_handle_subrow(fieldres, subrow) for subrow in row.get(fname, [])
]
return obj, fetched, dangling | [
"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"
] | cf2060a1d5ef879a01cf849e54b7756909ab2661 | https://github.com/peeringdb/peeringdb-py/blob/cf2060a1d5ef879a01cf849e54b7756909ab2661/peeringdb/_sync.py#L36-L88 | train | 37,467 |
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 directory not found at %s" % (conf_path, ))
return munge.load_datafile('config', conf_path, default=None) | 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 directory not found at %s" % (conf_path, ))
return munge.load_datafile('config', conf_path, default=None) | [
"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",
"."
] | cf2060a1d5ef879a01cf849e54b7756909ab2661 | https://github.com/peeringdb/peeringdb-py/blob/cf2060a1d5ef879a01cf849e54b7756909ab2661/peeringdb/config.py#L59-L68 | train | 37,468 |
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"
] | cf2060a1d5ef879a01cf849e54b7756909ab2661 | https://github.com/peeringdb/peeringdb-py/blob/cf2060a1d5ef879a01cf849e54b7756909ab2661/peeringdb/config.py#L107-L112 | train | 37,469 |
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"
] | cf2060a1d5ef879a01cf849e54b7756909ab2661 | https://github.com/peeringdb/peeringdb-py/blob/cf2060a1d5ef879a01cf849e54b7756909ab2661/peeringdb/config.py#L115-L120 | train | 37,470 |
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,
make a copy before overwriting
"""
if not codec:
codec = 'yaml'
codec = munge.get_codec(codec)()
conf_dir = os.path.expanduser(conf_dir)
if not os.path.exists(conf_dir):
os.mkdir(conf_dir)
# Check for existing file, back up if necessary
outpath = os.path.join(conf_dir, 'config.' + codec.extensions[0])
if backup_existing and os.path.exists(outpath):
os.rename(outpath, outpath + '.bak')
codec.dump(data, open(outpath, 'w')) | 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,
make a copy before overwriting
"""
if not codec:
codec = 'yaml'
codec = munge.get_codec(codec)()
conf_dir = os.path.expanduser(conf_dir)
if not os.path.exists(conf_dir):
os.mkdir(conf_dir)
# Check for existing file, back up if necessary
outpath = os.path.join(conf_dir, 'config.' + codec.extensions[0])
if backup_existing and os.path.exists(outpath):
os.rename(outpath, outpath + '.bak')
codec.dump(data, open(outpath, 'w')) | [
"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",
"."
] | cf2060a1d5ef879a01cf849e54b7756909ab2661 | https://github.com/peeringdb/peeringdb-py/blob/cf2060a1d5ef879a01cf849e54b7756909ab2661/peeringdb/config.py#L123-L145 | train | 37,471 |
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.attributes():
fullpath = name
if path:
fullpath = '{}.{}'.format(path, name)
if defaults is None:
defaults = {}
default = defaults.get(name)
if isinstance(attr, _schema.Schema):
# recurse on sub-schema
value = prompt_config(attr, defaults=default, path=fullpath)
else:
if default is None:
default = attr.default
if default is None:
default = ''
value = prompt(fullpath, default)
out[name] = value
return sch.validate(out) | 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.attributes():
fullpath = name
if path:
fullpath = '{}.{}'.format(path, name)
if defaults is None:
defaults = {}
default = defaults.get(name)
if isinstance(attr, _schema.Schema):
# recurse on sub-schema
value = prompt_config(attr, defaults=default, path=fullpath)
else:
if default is None:
default = attr.default
if default is None:
default = ''
value = prompt(fullpath, default)
out[name] = value
return sch.validate(out) | [
"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"
] | cf2060a1d5ef879a01cf849e54b7756909ab2661 | https://github.com/peeringdb/peeringdb-py/blob/cf2060a1d5ef879a01cf849e54b7756909ab2661/peeringdb/config.py#L148-L175 | train | 37,472 |
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"
] | cf2060a1d5ef879a01cf849e54b7756909ab2661 | https://github.com/peeringdb/peeringdb-py/blob/cf2060a1d5ef879a01cf849e54b7756909ab2661/peeringdb/client.py#L64-L68 | train | 37,473 |
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"
] | cf2060a1d5ef879a01cf849e54b7756909ab2661 | https://github.com/peeringdb/peeringdb-py/blob/cf2060a1d5ef879a01cf849e54b7756909ab2661/peeringdb/client.py#L70-L74 | train | 37,474 |
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"
] | cf2060a1d5ef879a01cf849e54b7756909ab2661 | https://github.com/peeringdb/peeringdb-py/blob/cf2060a1d5ef879a01cf849e54b7756909ab2661/peeringdb/client.py#L81-L84 | train | 37,475 |
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"
] | cf2060a1d5ef879a01cf849e54b7756909ab2661 | https://github.com/peeringdb/peeringdb-py/blob/cf2060a1d5ef879a01cf849e54b7756909ab2661/peeringdb/_tasks_sequential.py#L69-L79 | train | 37,476 |
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"
] | cf2060a1d5ef879a01cf849e54b7756909ab2661 | https://github.com/peeringdb/peeringdb-py/blob/cf2060a1d5ef879a01cf849e54b7756909ab2661/peeringdb/_fetch.py#L83-L87 | train | 37,477 |
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:
try:
item = gen.send(r)
except StopIteration:
break
if inspect.isawaitable(item):
r = await item
else:
r = item
ret.append(r)
if len(ret) == 1:
return ret.pop()
return ret
return _wrapped | 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:
try:
item = gen.send(r)
except StopIteration:
break
if inspect.isawaitable(item):
r = await item
else:
r = item
ret.append(r)
if len(ret) == 1:
return ret.pop()
return ret
return _wrapped | [
"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"
] | cf2060a1d5ef879a01cf849e54b7756909ab2661 | https://github.com/peeringdb/peeringdb-py/blob/cf2060a1d5ef879a01cf849e54b7756909ab2661/peeringdb/_tasks_async.py#L30-L54 | train | 37,478 |
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",
"."
] | cf2060a1d5ef879a01cf849e54b7756909ab2661 | https://github.com/peeringdb/peeringdb-py/blob/cf2060a1d5ef879a01cf849e54b7756909ab2661/peeringdb/_tasks_async.py#L57-L67 | train | 37,479 |
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 s | 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 s | [
"def",
"prompt",
"(",
"msg",
",",
"default",
"=",
"None",
")",
":",
"if",
"default",
"is",
"not",
"None",
":",
"msg",
"=",
"'{} ({})'",
".",
"format",
"(",
"msg",
",",
"repr",
"(",
"default",
")",
")",
"msg",
"=",
"'{}: '",
".",
"format",
"(",
"m... | Prompt for input | [
"Prompt",
"for",
"input"
] | cf2060a1d5ef879a01cf849e54b7756909ab2661 | https://github.com/peeringdb/peeringdb-py/blob/cf2060a1d5ef879a01cf849e54b7756909ab2661/peeringdb/util.py#L37-L50 | train | 37,480 |
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 soft memory limit: %s => %s', soft, softnew) | 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 soft memory limit: %s => %s', soft, softnew) | [
"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"
] | cf2060a1d5ef879a01cf849e54b7756909ab2661 | https://github.com/peeringdb/peeringdb-py/blob/cf2060a1d5ef879a01cf849e54b7756909ab2661/peeringdb/util.py#L86-L95 | train | 37,481 |
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(),
'inits': '\n'.join(inits),
'inputs': inputs,
'calls': '\n'.join(calls),
'outputs': outputs,
})
if dst_dir is not None:
import os
import errno
try:
os.makedirs(dst_dir)
except OSError as e:
if e.errno != errno.EEXIST:
raise
with open(os.path.join(dst_dir, pytorch_module_name.lower() + '.py'), 'w+') as f:
f.write(output)
f.close()
torch.save(pytorch_dict, os.path.join(dst_dir, pytorch_module_name.lower() + '.pt'))
return output | 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(),
'inits': '\n'.join(inits),
'inputs': inputs,
'calls': '\n'.join(calls),
'outputs': outputs,
})
if dst_dir is not None:
import os
import errno
try:
os.makedirs(dst_dir)
except OSError as e:
if e.errno != errno.EEXIST:
raise
with open(os.path.join(dst_dir, pytorch_module_name.lower() + '.py'), 'w+') as f:
f.write(output)
f.close()
torch.save(pytorch_dict, os.path.join(dst_dir, pytorch_module_name.lower() + '.pt'))
return output | [
"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",
"."
] | 4fad7fc3a0a478d68bd509e239d4b7f1e0748ffa | https://github.com/nerox8664/gluon2pytorch/blob/4fad7fc3a0a478d68bd509e239d4b7f1e0748ffa/gluon2pytorch/gluon2pytorch.py#L31-L63 | train | 37,482 |
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]) + "\n"
counter += 1
if self.printOutput:
logger.info(outputMsg)
return self.ftpList | 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]) + "\n"
counter += 1
if self.printOutput:
logger.info(outputMsg)
return self.ftpList | [
"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",
"."
] | 90794be0a12af489ac98e8ae3b4ff450c83e2f3d | https://github.com/kowalpy/Robot-Framework-FTP-Library/blob/90794be0a12af489ac98e8ae3b4ff450c83e2f3d/FtpLibrary.py#L105-L117 | train | 37,483 |
Robpol86/sphinxcontrib-versioning | sphinxcontrib/versioning/setup_logging.py | setup_logging | def setup_logging(verbose=0, colors=False, name=None):
"""Configure console logging. Info and below go to stdout, others go to stderr.
:param int verbose: Verbosity level. > 0 print debug statements. > 1 passed to sphinx-build.
:param bool colors: Print color text in non-verbose mode.
:param str name: Which logger name to set handlers to. Used for testing.
"""
root_logger = logging.getLogger(name)
root_logger.setLevel(logging.DEBUG if verbose > 0 else logging.INFO)
formatter = ColorFormatter(verbose > 0, colors)
if colors:
colorclass.Windows.enable()
handler_stdout = logging.StreamHandler(sys.stdout)
handler_stdout.setFormatter(formatter)
handler_stdout.setLevel(logging.DEBUG)
handler_stdout.addFilter(type('', (logging.Filter,), {'filter': staticmethod(lambda r: r.levelno <= logging.INFO)}))
root_logger.addHandler(handler_stdout)
handler_stderr = logging.StreamHandler(sys.stderr)
handler_stderr.setFormatter(formatter)
handler_stderr.setLevel(logging.WARNING)
root_logger.addHandler(handler_stderr) | python | def setup_logging(verbose=0, colors=False, name=None):
"""Configure console logging. Info and below go to stdout, others go to stderr.
:param int verbose: Verbosity level. > 0 print debug statements. > 1 passed to sphinx-build.
:param bool colors: Print color text in non-verbose mode.
:param str name: Which logger name to set handlers to. Used for testing.
"""
root_logger = logging.getLogger(name)
root_logger.setLevel(logging.DEBUG if verbose > 0 else logging.INFO)
formatter = ColorFormatter(verbose > 0, colors)
if colors:
colorclass.Windows.enable()
handler_stdout = logging.StreamHandler(sys.stdout)
handler_stdout.setFormatter(formatter)
handler_stdout.setLevel(logging.DEBUG)
handler_stdout.addFilter(type('', (logging.Filter,), {'filter': staticmethod(lambda r: r.levelno <= logging.INFO)}))
root_logger.addHandler(handler_stdout)
handler_stderr = logging.StreamHandler(sys.stderr)
handler_stderr.setFormatter(formatter)
handler_stderr.setLevel(logging.WARNING)
root_logger.addHandler(handler_stderr) | [
"def",
"setup_logging",
"(",
"verbose",
"=",
"0",
",",
"colors",
"=",
"False",
",",
"name",
"=",
"None",
")",
":",
"root_logger",
"=",
"logging",
".",
"getLogger",
"(",
"name",
")",
"root_logger",
".",
"setLevel",
"(",
"logging",
".",
"DEBUG",
"if",
"v... | Configure console logging. Info and below go to stdout, others go to stderr.
:param int verbose: Verbosity level. > 0 print debug statements. > 1 passed to sphinx-build.
:param bool colors: Print color text in non-verbose mode.
:param str name: Which logger name to set handlers to. Used for testing. | [
"Configure",
"console",
"logging",
".",
"Info",
"and",
"below",
"go",
"to",
"stdout",
"others",
"go",
"to",
"stderr",
"."
] | 920edec0ac764081b583a2ecf4e6952762b9dbf2 | https://github.com/Robpol86/sphinxcontrib-versioning/blob/920edec0ac764081b583a2ecf4e6952762b9dbf2/sphinxcontrib/versioning/setup_logging.py#L55-L77 | train | 37,484 |
Robpol86/sphinxcontrib-versioning | sphinxcontrib/versioning/setup_logging.py | ColorFormatter.format | def format(self, record):
"""Apply little arrow and colors to the record.
Arrow and colors are only applied to sphinxcontrib.versioning log statements.
:param logging.LogRecord record: The log record object to log.
"""
formatted = super(ColorFormatter, self).format(record)
if self.verbose or not record.name.startswith(self.SPECIAL_SCOPE):
return formatted
# Arrow.
formatted = '=> ' + formatted
# Colors.
if not self.colors:
return formatted
if record.levelno >= logging.ERROR:
formatted = str(colorclass.Color.red(formatted))
elif record.levelno >= logging.WARNING:
formatted = str(colorclass.Color.yellow(formatted))
else:
formatted = str(colorclass.Color.cyan(formatted))
return formatted | python | def format(self, record):
"""Apply little arrow and colors to the record.
Arrow and colors are only applied to sphinxcontrib.versioning log statements.
:param logging.LogRecord record: The log record object to log.
"""
formatted = super(ColorFormatter, self).format(record)
if self.verbose or not record.name.startswith(self.SPECIAL_SCOPE):
return formatted
# Arrow.
formatted = '=> ' + formatted
# Colors.
if not self.colors:
return formatted
if record.levelno >= logging.ERROR:
formatted = str(colorclass.Color.red(formatted))
elif record.levelno >= logging.WARNING:
formatted = str(colorclass.Color.yellow(formatted))
else:
formatted = str(colorclass.Color.cyan(formatted))
return formatted | [
"def",
"format",
"(",
"self",
",",
"record",
")",
":",
"formatted",
"=",
"super",
"(",
"ColorFormatter",
",",
"self",
")",
".",
"format",
"(",
"record",
")",
"if",
"self",
".",
"verbose",
"or",
"not",
"record",
".",
"name",
".",
"startswith",
"(",
"s... | Apply little arrow and colors to the record.
Arrow and colors are only applied to sphinxcontrib.versioning log statements.
:param logging.LogRecord record: The log record object to log. | [
"Apply",
"little",
"arrow",
"and",
"colors",
"to",
"the",
"record",
"."
] | 920edec0ac764081b583a2ecf4e6952762b9dbf2 | https://github.com/Robpol86/sphinxcontrib-versioning/blob/920edec0ac764081b583a2ecf4e6952762b9dbf2/sphinxcontrib/versioning/setup_logging.py#L29-L52 | train | 37,485 |
Robpol86/sphinxcontrib-versioning | sphinxcontrib/versioning/git.py | get_root | def get_root(directory):
"""Get root directory of the local git repo from any subdirectory within it.
:raise GitError: If git command fails (dir not a git repo?).
:param str directory: Subdirectory in the local repo.
:return: Root directory of repository.
:rtype: str
"""
command = ['git', 'rev-parse', '--show-toplevel']
try:
output = run_command(directory, command, env_var=False)
except CalledProcessError as exc:
raise GitError('Failed to find local git repository root in {}.'.format(repr(directory)), exc.output)
if IS_WINDOWS:
output = output.replace('/', '\\')
return output.strip() | python | def get_root(directory):
"""Get root directory of the local git repo from any subdirectory within it.
:raise GitError: If git command fails (dir not a git repo?).
:param str directory: Subdirectory in the local repo.
:return: Root directory of repository.
:rtype: str
"""
command = ['git', 'rev-parse', '--show-toplevel']
try:
output = run_command(directory, command, env_var=False)
except CalledProcessError as exc:
raise GitError('Failed to find local git repository root in {}.'.format(repr(directory)), exc.output)
if IS_WINDOWS:
output = output.replace('/', '\\')
return output.strip() | [
"def",
"get_root",
"(",
"directory",
")",
":",
"command",
"=",
"[",
"'git'",
",",
"'rev-parse'",
",",
"'--show-toplevel'",
"]",
"try",
":",
"output",
"=",
"run_command",
"(",
"directory",
",",
"command",
",",
"env_var",
"=",
"False",
")",
"except",
"Called... | Get root directory of the local git repo from any subdirectory within it.
:raise GitError: If git command fails (dir not a git repo?).
:param str directory: Subdirectory in the local repo.
:return: Root directory of repository.
:rtype: str | [
"Get",
"root",
"directory",
"of",
"the",
"local",
"git",
"repo",
"from",
"any",
"subdirectory",
"within",
"it",
"."
] | 920edec0ac764081b583a2ecf4e6952762b9dbf2 | https://github.com/Robpol86/sphinxcontrib-versioning/blob/920edec0ac764081b583a2ecf4e6952762b9dbf2/sphinxcontrib/versioning/git.py#L161-L178 | train | 37,486 |
Robpol86/sphinxcontrib-versioning | sphinxcontrib/versioning/git.py | filter_and_date | def filter_and_date(local_root, conf_rel_paths, commits):
"""Get commit Unix timestamps and first matching conf.py path. Exclude commits with no conf.py file.
:raise CalledProcessError: Unhandled git command failure.
:raise GitError: A commit SHA has not been fetched.
:param str local_root: Local path to git root directory.
:param iter conf_rel_paths: List of possible relative paths (to git root) of Sphinx conf.py (e.g. docs/conf.py).
:param iter commits: List of commit SHAs.
:return: Commit time (seconds since Unix epoch) for each commit and conf.py path. SHA keys and [int, str] values.
:rtype: dict
"""
dates_paths = dict()
# Filter without docs.
for commit in commits:
if commit in dates_paths:
continue
command = ['git', 'ls-tree', '--name-only', '-r', commit] + conf_rel_paths
try:
output = run_command(local_root, command)
except CalledProcessError as exc:
raise GitError('Git ls-tree failed on {0}'.format(commit), exc.output)
if output:
dates_paths[commit] = [None, output.splitlines()[0].strip()]
# Get timestamps by groups of 50.
command_prefix = ['git', 'show', '--no-patch', '--pretty=format:%ct']
for commits_group in chunk(dates_paths, 50):
command = command_prefix + commits_group
output = run_command(local_root, command)
timestamps = [int(i) for i in RE_UNIX_TIME.findall(output)]
for i, commit in enumerate(commits_group):
dates_paths[commit][0] = timestamps[i]
# Done.
return dates_paths | python | def filter_and_date(local_root, conf_rel_paths, commits):
"""Get commit Unix timestamps and first matching conf.py path. Exclude commits with no conf.py file.
:raise CalledProcessError: Unhandled git command failure.
:raise GitError: A commit SHA has not been fetched.
:param str local_root: Local path to git root directory.
:param iter conf_rel_paths: List of possible relative paths (to git root) of Sphinx conf.py (e.g. docs/conf.py).
:param iter commits: List of commit SHAs.
:return: Commit time (seconds since Unix epoch) for each commit and conf.py path. SHA keys and [int, str] values.
:rtype: dict
"""
dates_paths = dict()
# Filter without docs.
for commit in commits:
if commit in dates_paths:
continue
command = ['git', 'ls-tree', '--name-only', '-r', commit] + conf_rel_paths
try:
output = run_command(local_root, command)
except CalledProcessError as exc:
raise GitError('Git ls-tree failed on {0}'.format(commit), exc.output)
if output:
dates_paths[commit] = [None, output.splitlines()[0].strip()]
# Get timestamps by groups of 50.
command_prefix = ['git', 'show', '--no-patch', '--pretty=format:%ct']
for commits_group in chunk(dates_paths, 50):
command = command_prefix + commits_group
output = run_command(local_root, command)
timestamps = [int(i) for i in RE_UNIX_TIME.findall(output)]
for i, commit in enumerate(commits_group):
dates_paths[commit][0] = timestamps[i]
# Done.
return dates_paths | [
"def",
"filter_and_date",
"(",
"local_root",
",",
"conf_rel_paths",
",",
"commits",
")",
":",
"dates_paths",
"=",
"dict",
"(",
")",
"# Filter without docs.",
"for",
"commit",
"in",
"commits",
":",
"if",
"commit",
"in",
"dates_paths",
":",
"continue",
"command",
... | Get commit Unix timestamps and first matching conf.py path. Exclude commits with no conf.py file.
:raise CalledProcessError: Unhandled git command failure.
:raise GitError: A commit SHA has not been fetched.
:param str local_root: Local path to git root directory.
:param iter conf_rel_paths: List of possible relative paths (to git root) of Sphinx conf.py (e.g. docs/conf.py).
:param iter commits: List of commit SHAs.
:return: Commit time (seconds since Unix epoch) for each commit and conf.py path. SHA keys and [int, str] values.
:rtype: dict | [
"Get",
"commit",
"Unix",
"timestamps",
"and",
"first",
"matching",
"conf",
".",
"py",
"path",
".",
"Exclude",
"commits",
"with",
"no",
"conf",
".",
"py",
"file",
"."
] | 920edec0ac764081b583a2ecf4e6952762b9dbf2 | https://github.com/Robpol86/sphinxcontrib-versioning/blob/920edec0ac764081b583a2ecf4e6952762b9dbf2/sphinxcontrib/versioning/git.py#L212-L249 | train | 37,487 |
Robpol86/sphinxcontrib-versioning | sphinxcontrib/versioning/git.py | fetch_commits | def fetch_commits(local_root, remotes):
"""Fetch from origin.
:raise CalledProcessError: Unhandled git command failure.
:param str local_root: Local path to git root directory.
:param iter remotes: Output of list_remote().
"""
# Fetch all known branches.
command = ['git', 'fetch', 'origin']
run_command(local_root, command)
# Fetch new branches/tags.
for sha, name, kind in remotes:
try:
run_command(local_root, ['git', 'reflog', sha])
except CalledProcessError:
run_command(local_root, command + ['refs/{0}/{1}'.format(kind, name)])
run_command(local_root, ['git', 'reflog', sha]) | python | def fetch_commits(local_root, remotes):
"""Fetch from origin.
:raise CalledProcessError: Unhandled git command failure.
:param str local_root: Local path to git root directory.
:param iter remotes: Output of list_remote().
"""
# Fetch all known branches.
command = ['git', 'fetch', 'origin']
run_command(local_root, command)
# Fetch new branches/tags.
for sha, name, kind in remotes:
try:
run_command(local_root, ['git', 'reflog', sha])
except CalledProcessError:
run_command(local_root, command + ['refs/{0}/{1}'.format(kind, name)])
run_command(local_root, ['git', 'reflog', sha]) | [
"def",
"fetch_commits",
"(",
"local_root",
",",
"remotes",
")",
":",
"# Fetch all known branches.",
"command",
"=",
"[",
"'git'",
",",
"'fetch'",
",",
"'origin'",
"]",
"run_command",
"(",
"local_root",
",",
"command",
")",
"# Fetch new branches/tags.",
"for",
"sha... | Fetch from origin.
:raise CalledProcessError: Unhandled git command failure.
:param str local_root: Local path to git root directory.
:param iter remotes: Output of list_remote(). | [
"Fetch",
"from",
"origin",
"."
] | 920edec0ac764081b583a2ecf4e6952762b9dbf2 | https://github.com/Robpol86/sphinxcontrib-versioning/blob/920edec0ac764081b583a2ecf4e6952762b9dbf2/sphinxcontrib/versioning/git.py#L252-L270 | train | 37,488 |
Robpol86/sphinxcontrib-versioning | sphinxcontrib/versioning/git.py | export | def export(local_root, commit, target):
"""Export git commit to directory. "Extracts" all files at the commit to the target directory.
Set mtime of RST files to last commit date.
:raise CalledProcessError: Unhandled git command failure.
:param str local_root: Local path to git root directory.
:param str commit: Git commit SHA to export.
:param str target: Directory to export to.
"""
log = logging.getLogger(__name__)
target = os.path.realpath(target)
mtimes = list()
# Define extract function.
def extract(stdout):
"""Extract tar archive from "git archive" stdout.
:param file stdout: Handle to git's stdout pipe.
"""
queued_links = list()
try:
with tarfile.open(fileobj=stdout, mode='r|') as tar:
for info in tar:
log.debug('name: %s; mode: %d; size: %s; type: %s', info.name, info.mode, info.size, info.type)
path = os.path.realpath(os.path.join(target, info.name))
if not path.startswith(target): # Handle bad paths.
log.warning('Ignoring tar object path %s outside of target directory.', info.name)
elif info.isdir(): # Handle directories.
if not os.path.exists(path):
os.makedirs(path, mode=info.mode)
elif info.issym() or info.islnk(): # Queue links.
queued_links.append(info)
else: # Handle files.
tar.extract(member=info, path=target)
if os.path.splitext(info.name)[1].lower() == '.rst':
mtimes.append(info.name)
for info in (i for i in queued_links if os.path.exists(os.path.join(target, i.linkname))):
tar.extract(member=info, path=target)
except tarfile.TarError as exc:
log.debug('Failed to extract output from "git archive" command: %s', str(exc))
# Run command.
run_command(local_root, ['git', 'archive', '--format=tar', commit], pipeto=extract)
# Set mtime.
for file_path in mtimes:
last_committed = int(run_command(local_root, ['git', 'log', '-n1', '--format=%at', commit, '--', file_path]))
os.utime(os.path.join(target, file_path), (last_committed, last_committed)) | python | def export(local_root, commit, target):
"""Export git commit to directory. "Extracts" all files at the commit to the target directory.
Set mtime of RST files to last commit date.
:raise CalledProcessError: Unhandled git command failure.
:param str local_root: Local path to git root directory.
:param str commit: Git commit SHA to export.
:param str target: Directory to export to.
"""
log = logging.getLogger(__name__)
target = os.path.realpath(target)
mtimes = list()
# Define extract function.
def extract(stdout):
"""Extract tar archive from "git archive" stdout.
:param file stdout: Handle to git's stdout pipe.
"""
queued_links = list()
try:
with tarfile.open(fileobj=stdout, mode='r|') as tar:
for info in tar:
log.debug('name: %s; mode: %d; size: %s; type: %s', info.name, info.mode, info.size, info.type)
path = os.path.realpath(os.path.join(target, info.name))
if not path.startswith(target): # Handle bad paths.
log.warning('Ignoring tar object path %s outside of target directory.', info.name)
elif info.isdir(): # Handle directories.
if not os.path.exists(path):
os.makedirs(path, mode=info.mode)
elif info.issym() or info.islnk(): # Queue links.
queued_links.append(info)
else: # Handle files.
tar.extract(member=info, path=target)
if os.path.splitext(info.name)[1].lower() == '.rst':
mtimes.append(info.name)
for info in (i for i in queued_links if os.path.exists(os.path.join(target, i.linkname))):
tar.extract(member=info, path=target)
except tarfile.TarError as exc:
log.debug('Failed to extract output from "git archive" command: %s', str(exc))
# Run command.
run_command(local_root, ['git', 'archive', '--format=tar', commit], pipeto=extract)
# Set mtime.
for file_path in mtimes:
last_committed = int(run_command(local_root, ['git', 'log', '-n1', '--format=%at', commit, '--', file_path]))
os.utime(os.path.join(target, file_path), (last_committed, last_committed)) | [
"def",
"export",
"(",
"local_root",
",",
"commit",
",",
"target",
")",
":",
"log",
"=",
"logging",
".",
"getLogger",
"(",
"__name__",
")",
"target",
"=",
"os",
".",
"path",
".",
"realpath",
"(",
"target",
")",
"mtimes",
"=",
"list",
"(",
")",
"# Defi... | Export git commit to directory. "Extracts" all files at the commit to the target directory.
Set mtime of RST files to last commit date.
:raise CalledProcessError: Unhandled git command failure.
:param str local_root: Local path to git root directory.
:param str commit: Git commit SHA to export.
:param str target: Directory to export to. | [
"Export",
"git",
"commit",
"to",
"directory",
".",
"Extracts",
"all",
"files",
"at",
"the",
"commit",
"to",
"the",
"target",
"directory",
"."
] | 920edec0ac764081b583a2ecf4e6952762b9dbf2 | https://github.com/Robpol86/sphinxcontrib-versioning/blob/920edec0ac764081b583a2ecf4e6952762b9dbf2/sphinxcontrib/versioning/git.py#L273-L322 | train | 37,489 |
Robpol86/sphinxcontrib-versioning | sphinxcontrib/versioning/git.py | clone | def clone(local_root, new_root, remote, branch, rel_dest, exclude):
"""Clone "local_root" origin into a new directory and check out a specific branch. Optionally run "git rm".
:raise CalledProcessError: Unhandled git command failure.
:raise GitError: Handled git failures.
:param str local_root: Local path to git root directory.
:param str new_root: Local path empty directory in which branch will be cloned into.
:param str remote: The git remote to clone from to.
:param str branch: Checkout this branch.
:param str rel_dest: Run "git rm" on this directory if exclude is truthy.
:param iter exclude: List of strings representing relative file paths to exclude from "git rm".
"""
log = logging.getLogger(__name__)
output = run_command(local_root, ['git', 'remote', '-v'])
remotes = dict()
for match in RE_ALL_REMOTES.findall(output):
remotes.setdefault(match[0], [None, None])
if match[2] == 'fetch':
remotes[match[0]][0] = match[1]
else:
remotes[match[0]][1] = match[1]
if not remotes:
raise GitError('Git repo has no remotes.', output)
if remote not in remotes:
raise GitError('Git repo missing remote "{}".'.format(remote), output)
# Clone.
try:
run_command(new_root, ['git', 'clone', remotes[remote][0], '--depth=1', '--branch', branch, '.'])
except CalledProcessError as exc:
raise GitError('Failed to clone from remote repo URL.', exc.output)
# Make sure user didn't select a tag as their DEST_BRANCH.
try:
run_command(new_root, ['git', 'symbolic-ref', 'HEAD'])
except CalledProcessError as exc:
raise GitError('Specified branch is not a real branch.', exc.output)
# Copy all remotes from original repo.
for name, (fetch, push) in remotes.items():
try:
run_command(new_root, ['git', 'remote', 'set-url' if name == 'origin' else 'add', name, fetch], retry=3)
run_command(new_root, ['git', 'remote', 'set-url', '--push', name, push], retry=3)
except CalledProcessError as exc:
raise GitError('Failed to set git remote URL.', exc.output)
# Done if no exclude.
if not exclude:
return
# Resolve exclude paths.
exclude_joined = [
os.path.relpath(p, new_root) for e in exclude for p in glob.glob(os.path.join(new_root, rel_dest, e))
]
log.debug('Expanded %s to %s', repr(exclude), repr(exclude_joined))
# Do "git rm".
try:
run_command(new_root, ['git', 'rm', '-rf', rel_dest])
except CalledProcessError as exc:
raise GitError('"git rm" failed to remove ' + rel_dest, exc.output)
# Restore files in exclude.
run_command(new_root, ['git', 'reset', 'HEAD'] + exclude_joined)
run_command(new_root, ['git', 'checkout', '--'] + exclude_joined) | python | def clone(local_root, new_root, remote, branch, rel_dest, exclude):
"""Clone "local_root" origin into a new directory and check out a specific branch. Optionally run "git rm".
:raise CalledProcessError: Unhandled git command failure.
:raise GitError: Handled git failures.
:param str local_root: Local path to git root directory.
:param str new_root: Local path empty directory in which branch will be cloned into.
:param str remote: The git remote to clone from to.
:param str branch: Checkout this branch.
:param str rel_dest: Run "git rm" on this directory if exclude is truthy.
:param iter exclude: List of strings representing relative file paths to exclude from "git rm".
"""
log = logging.getLogger(__name__)
output = run_command(local_root, ['git', 'remote', '-v'])
remotes = dict()
for match in RE_ALL_REMOTES.findall(output):
remotes.setdefault(match[0], [None, None])
if match[2] == 'fetch':
remotes[match[0]][0] = match[1]
else:
remotes[match[0]][1] = match[1]
if not remotes:
raise GitError('Git repo has no remotes.', output)
if remote not in remotes:
raise GitError('Git repo missing remote "{}".'.format(remote), output)
# Clone.
try:
run_command(new_root, ['git', 'clone', remotes[remote][0], '--depth=1', '--branch', branch, '.'])
except CalledProcessError as exc:
raise GitError('Failed to clone from remote repo URL.', exc.output)
# Make sure user didn't select a tag as their DEST_BRANCH.
try:
run_command(new_root, ['git', 'symbolic-ref', 'HEAD'])
except CalledProcessError as exc:
raise GitError('Specified branch is not a real branch.', exc.output)
# Copy all remotes from original repo.
for name, (fetch, push) in remotes.items():
try:
run_command(new_root, ['git', 'remote', 'set-url' if name == 'origin' else 'add', name, fetch], retry=3)
run_command(new_root, ['git', 'remote', 'set-url', '--push', name, push], retry=3)
except CalledProcessError as exc:
raise GitError('Failed to set git remote URL.', exc.output)
# Done if no exclude.
if not exclude:
return
# Resolve exclude paths.
exclude_joined = [
os.path.relpath(p, new_root) for e in exclude for p in glob.glob(os.path.join(new_root, rel_dest, e))
]
log.debug('Expanded %s to %s', repr(exclude), repr(exclude_joined))
# Do "git rm".
try:
run_command(new_root, ['git', 'rm', '-rf', rel_dest])
except CalledProcessError as exc:
raise GitError('"git rm" failed to remove ' + rel_dest, exc.output)
# Restore files in exclude.
run_command(new_root, ['git', 'reset', 'HEAD'] + exclude_joined)
run_command(new_root, ['git', 'checkout', '--'] + exclude_joined) | [
"def",
"clone",
"(",
"local_root",
",",
"new_root",
",",
"remote",
",",
"branch",
",",
"rel_dest",
",",
"exclude",
")",
":",
"log",
"=",
"logging",
".",
"getLogger",
"(",
"__name__",
")",
"output",
"=",
"run_command",
"(",
"local_root",
",",
"[",
"'git'"... | Clone "local_root" origin into a new directory and check out a specific branch. Optionally run "git rm".
:raise CalledProcessError: Unhandled git command failure.
:raise GitError: Handled git failures.
:param str local_root: Local path to git root directory.
:param str new_root: Local path empty directory in which branch will be cloned into.
:param str remote: The git remote to clone from to.
:param str branch: Checkout this branch.
:param str rel_dest: Run "git rm" on this directory if exclude is truthy.
:param iter exclude: List of strings representing relative file paths to exclude from "git rm". | [
"Clone",
"local_root",
"origin",
"into",
"a",
"new",
"directory",
"and",
"check",
"out",
"a",
"specific",
"branch",
".",
"Optionally",
"run",
"git",
"rm",
"."
] | 920edec0ac764081b583a2ecf4e6952762b9dbf2 | https://github.com/Robpol86/sphinxcontrib-versioning/blob/920edec0ac764081b583a2ecf4e6952762b9dbf2/sphinxcontrib/versioning/git.py#L325-L390 | train | 37,490 |
Robpol86/sphinxcontrib-versioning | sphinxcontrib/versioning/git.py | commit_and_push | def commit_and_push(local_root, remote, versions):
"""Commit changed, new, and deleted files in the repo and attempt to push the branch to the remote repository.
:raise CalledProcessError: Unhandled git command failure.
:raise GitError: Conflicting changes made in remote by other client and bad git config for commits.
:param str local_root: Local path to git root directory.
:param str remote: The git remote to push to.
:param sphinxcontrib.versioning.versions.Versions versions: Versions class instance.
:return: If push succeeded.
:rtype: bool
"""
log = logging.getLogger(__name__)
current_branch = run_command(local_root, ['git', 'rev-parse', '--abbrev-ref', 'HEAD']).strip()
run_command(local_root, ['git', 'add', '.'])
# Check if there are no changes.
try:
run_command(local_root, ['git', 'diff', 'HEAD', '--no-ext-diff', '--quiet', '--exit-code'])
except CalledProcessError:
pass # Repo is dirty, something has changed.
else:
log.info('No changes to commit.')
return True
# Check if there are changes excluding those files that always change.
output = run_command(local_root, ['git', 'diff', 'HEAD', '--no-ext-diff', '--name-status'])
for status, name in (l.split('\t', 1) for l in output.splitlines()):
if status != 'M':
break # Only looking for modified files.
components = name.split('/')
if '.doctrees' not in components and components[-1] != 'searchindex.js':
break # Something other than those two dirs/files has changed.
else:
log.info('No significant changes to commit.')
return True
# Commit.
latest_commit = sorted(versions.remotes, key=lambda v: v['date'])[-1]
commit_message_file = os.path.join(local_root, '_scv_commit_message.txt')
with open(commit_message_file, 'w') as handle:
handle.write('AUTO sphinxcontrib-versioning {} {}\n\n'.format(
datetime.utcfromtimestamp(latest_commit['date']).strftime('%Y%m%d'),
latest_commit['sha'][:11],
))
for line in ('{}: {}\n'.format(v, os.environ[v]) for v in WHITELIST_ENV_VARS if v in os.environ):
handle.write(line)
try:
run_command(local_root, ['git', 'commit', '-F', commit_message_file])
except CalledProcessError as exc:
raise GitError('Failed to commit locally.', exc.output)
os.remove(commit_message_file)
# Push.
try:
run_command(local_root, ['git', 'push', remote, current_branch])
except CalledProcessError as exc:
if '[rejected]' in exc.output and '(fetch first)' in exc.output:
log.debug('Remote has changed since cloning the repo. Must retry.')
return False
raise GitError('Failed to push to remote.', exc.output)
log.info('Successfully pushed to remote repository.')
return True | python | def commit_and_push(local_root, remote, versions):
"""Commit changed, new, and deleted files in the repo and attempt to push the branch to the remote repository.
:raise CalledProcessError: Unhandled git command failure.
:raise GitError: Conflicting changes made in remote by other client and bad git config for commits.
:param str local_root: Local path to git root directory.
:param str remote: The git remote to push to.
:param sphinxcontrib.versioning.versions.Versions versions: Versions class instance.
:return: If push succeeded.
:rtype: bool
"""
log = logging.getLogger(__name__)
current_branch = run_command(local_root, ['git', 'rev-parse', '--abbrev-ref', 'HEAD']).strip()
run_command(local_root, ['git', 'add', '.'])
# Check if there are no changes.
try:
run_command(local_root, ['git', 'diff', 'HEAD', '--no-ext-diff', '--quiet', '--exit-code'])
except CalledProcessError:
pass # Repo is dirty, something has changed.
else:
log.info('No changes to commit.')
return True
# Check if there are changes excluding those files that always change.
output = run_command(local_root, ['git', 'diff', 'HEAD', '--no-ext-diff', '--name-status'])
for status, name in (l.split('\t', 1) for l in output.splitlines()):
if status != 'M':
break # Only looking for modified files.
components = name.split('/')
if '.doctrees' not in components and components[-1] != 'searchindex.js':
break # Something other than those two dirs/files has changed.
else:
log.info('No significant changes to commit.')
return True
# Commit.
latest_commit = sorted(versions.remotes, key=lambda v: v['date'])[-1]
commit_message_file = os.path.join(local_root, '_scv_commit_message.txt')
with open(commit_message_file, 'w') as handle:
handle.write('AUTO sphinxcontrib-versioning {} {}\n\n'.format(
datetime.utcfromtimestamp(latest_commit['date']).strftime('%Y%m%d'),
latest_commit['sha'][:11],
))
for line in ('{}: {}\n'.format(v, os.environ[v]) for v in WHITELIST_ENV_VARS if v in os.environ):
handle.write(line)
try:
run_command(local_root, ['git', 'commit', '-F', commit_message_file])
except CalledProcessError as exc:
raise GitError('Failed to commit locally.', exc.output)
os.remove(commit_message_file)
# Push.
try:
run_command(local_root, ['git', 'push', remote, current_branch])
except CalledProcessError as exc:
if '[rejected]' in exc.output and '(fetch first)' in exc.output:
log.debug('Remote has changed since cloning the repo. Must retry.')
return False
raise GitError('Failed to push to remote.', exc.output)
log.info('Successfully pushed to remote repository.')
return True | [
"def",
"commit_and_push",
"(",
"local_root",
",",
"remote",
",",
"versions",
")",
":",
"log",
"=",
"logging",
".",
"getLogger",
"(",
"__name__",
")",
"current_branch",
"=",
"run_command",
"(",
"local_root",
",",
"[",
"'git'",
",",
"'rev-parse'",
",",
"'--abb... | Commit changed, new, and deleted files in the repo and attempt to push the branch to the remote repository.
:raise CalledProcessError: Unhandled git command failure.
:raise GitError: Conflicting changes made in remote by other client and bad git config for commits.
:param str local_root: Local path to git root directory.
:param str remote: The git remote to push to.
:param sphinxcontrib.versioning.versions.Versions versions: Versions class instance.
:return: If push succeeded.
:rtype: bool | [
"Commit",
"changed",
"new",
"and",
"deleted",
"files",
"in",
"the",
"repo",
"and",
"attempt",
"to",
"push",
"the",
"branch",
"to",
"the",
"remote",
"repository",
"."
] | 920edec0ac764081b583a2ecf4e6952762b9dbf2 | https://github.com/Robpol86/sphinxcontrib-versioning/blob/920edec0ac764081b583a2ecf4e6952762b9dbf2/sphinxcontrib/versioning/git.py#L393-L457 | train | 37,491 |
Robpol86/sphinxcontrib-versioning | sphinxcontrib/versioning/versions.py | multi_sort | def multi_sort(remotes, sort):
"""Sort `remotes` in place. Allows sorting by multiple conditions.
This is needed because Python 3 no longer supports sorting lists of multiple types. Sort keys must all be of the
same type.
Problem: the user expects versions to be sorted latest first and timelogical to be most recent first (when viewing
the HTML documentation), yet expects alphabetical sorting to be A before Z.
Solution: invert integers (dates and parsed versions).
:param iter remotes: List of dicts from Versions().remotes.
:param iter sort: What to sort by. May be one or more of: alpha, time, semver
"""
exploded_alpha = list()
exploded_semver = list()
# Convert name to int if alpha is in sort.
if 'alpha' in sort:
alpha_max_len = max(len(r['name']) for r in remotes)
for name in (r['name'] for r in remotes):
exploded_alpha.append([ord(i) for i in name] + [0] * (alpha_max_len - len(name)))
# Parse versions if semver is in sort.
if 'semver' in sort:
exploded_semver = semvers(r['name'] for r in remotes)
# Build sort_mapping dict.
sort_mapping = dict()
for i, remote in enumerate(remotes):
key = list()
for sort_by in sort:
if sort_by == 'alpha':
key.extend(exploded_alpha[i])
elif sort_by == 'time':
key.append(-remote['date'])
elif sort_by == 'semver':
key.extend(exploded_semver[i])
sort_mapping[id(remote)] = key
# Sort.
remotes.sort(key=lambda k: sort_mapping.get(id(k))) | python | def multi_sort(remotes, sort):
"""Sort `remotes` in place. Allows sorting by multiple conditions.
This is needed because Python 3 no longer supports sorting lists of multiple types. Sort keys must all be of the
same type.
Problem: the user expects versions to be sorted latest first and timelogical to be most recent first (when viewing
the HTML documentation), yet expects alphabetical sorting to be A before Z.
Solution: invert integers (dates and parsed versions).
:param iter remotes: List of dicts from Versions().remotes.
:param iter sort: What to sort by. May be one or more of: alpha, time, semver
"""
exploded_alpha = list()
exploded_semver = list()
# Convert name to int if alpha is in sort.
if 'alpha' in sort:
alpha_max_len = max(len(r['name']) for r in remotes)
for name in (r['name'] for r in remotes):
exploded_alpha.append([ord(i) for i in name] + [0] * (alpha_max_len - len(name)))
# Parse versions if semver is in sort.
if 'semver' in sort:
exploded_semver = semvers(r['name'] for r in remotes)
# Build sort_mapping dict.
sort_mapping = dict()
for i, remote in enumerate(remotes):
key = list()
for sort_by in sort:
if sort_by == 'alpha':
key.extend(exploded_alpha[i])
elif sort_by == 'time':
key.append(-remote['date'])
elif sort_by == 'semver':
key.extend(exploded_semver[i])
sort_mapping[id(remote)] = key
# Sort.
remotes.sort(key=lambda k: sort_mapping.get(id(k))) | [
"def",
"multi_sort",
"(",
"remotes",
",",
"sort",
")",
":",
"exploded_alpha",
"=",
"list",
"(",
")",
"exploded_semver",
"=",
"list",
"(",
")",
"# Convert name to int if alpha is in sort.",
"if",
"'alpha'",
"in",
"sort",
":",
"alpha_max_len",
"=",
"max",
"(",
"... | Sort `remotes` in place. Allows sorting by multiple conditions.
This is needed because Python 3 no longer supports sorting lists of multiple types. Sort keys must all be of the
same type.
Problem: the user expects versions to be sorted latest first and timelogical to be most recent first (when viewing
the HTML documentation), yet expects alphabetical sorting to be A before Z.
Solution: invert integers (dates and parsed versions).
:param iter remotes: List of dicts from Versions().remotes.
:param iter sort: What to sort by. May be one or more of: alpha, time, semver | [
"Sort",
"remotes",
"in",
"place",
".",
"Allows",
"sorting",
"by",
"multiple",
"conditions",
"."
] | 920edec0ac764081b583a2ecf4e6952762b9dbf2 | https://github.com/Robpol86/sphinxcontrib-versioning/blob/920edec0ac764081b583a2ecf4e6952762b9dbf2/sphinxcontrib/versioning/versions.py#L47-L87 | train | 37,492 |
Robpol86/sphinxcontrib-versioning | sphinxcontrib/versioning/routines.py | read_local_conf | def read_local_conf(local_conf):
"""Search for conf.py in any rel_source directory in CWD and if found read it and return.
:param str local_conf: Path to conf.py to read.
:return: Loaded conf.py.
:rtype: dict
"""
log = logging.getLogger(__name__)
# Attempt to read.
log.info('Reading config from %s...', local_conf)
try:
config = read_config(os.path.dirname(local_conf), '<local>')
except HandledError:
log.warning('Unable to read file, continuing with only CLI args.')
return dict()
# Filter and return.
return {k[4:]: v for k, v in config.items() if k.startswith('scv_') and not k[4:].startswith('_')} | python | def read_local_conf(local_conf):
"""Search for conf.py in any rel_source directory in CWD and if found read it and return.
:param str local_conf: Path to conf.py to read.
:return: Loaded conf.py.
:rtype: dict
"""
log = logging.getLogger(__name__)
# Attempt to read.
log.info('Reading config from %s...', local_conf)
try:
config = read_config(os.path.dirname(local_conf), '<local>')
except HandledError:
log.warning('Unable to read file, continuing with only CLI args.')
return dict()
# Filter and return.
return {k[4:]: v for k, v in config.items() if k.startswith('scv_') and not k[4:].startswith('_')} | [
"def",
"read_local_conf",
"(",
"local_conf",
")",
":",
"log",
"=",
"logging",
".",
"getLogger",
"(",
"__name__",
")",
"# Attempt to read.",
"log",
".",
"info",
"(",
"'Reading config from %s...'",
",",
"local_conf",
")",
"try",
":",
"config",
"=",
"read_config",
... | Search for conf.py in any rel_source directory in CWD and if found read it and return.
:param str local_conf: Path to conf.py to read.
:return: Loaded conf.py.
:rtype: dict | [
"Search",
"for",
"conf",
".",
"py",
"in",
"any",
"rel_source",
"directory",
"in",
"CWD",
"and",
"if",
"found",
"read",
"it",
"and",
"return",
"."
] | 920edec0ac764081b583a2ecf4e6952762b9dbf2 | https://github.com/Robpol86/sphinxcontrib-versioning/blob/920edec0ac764081b583a2ecf4e6952762b9dbf2/sphinxcontrib/versioning/routines.py#L16-L35 | train | 37,493 |
Robpol86/sphinxcontrib-versioning | sphinxcontrib/versioning/routines.py | gather_git_info | def gather_git_info(root, conf_rel_paths, whitelist_branches, whitelist_tags):
"""Gather info about the remote git repository. Get list of refs.
:raise HandledError: If function fails with a handled error. Will be logged before raising.
:param str root: Root directory of repository.
:param iter conf_rel_paths: List of possible relative paths (to git root) of Sphinx conf.py (e.g. docs/conf.py).
:param iter whitelist_branches: Optional list of patterns to filter branches by.
:param iter whitelist_tags: Optional list of patterns to filter tags by.
:return: Commits with docs. A list of tuples: (sha, name, kind, date, conf_rel_path).
:rtype: list
"""
log = logging.getLogger(__name__)
# List remote.
log.info('Getting list of all remote branches/tags...')
try:
remotes = list_remote(root)
except GitError as exc:
log.error(exc.message)
log.error(exc.output)
raise HandledError
log.info('Found: %s', ' '.join(i[1] for i in remotes))
# Filter and date.
try:
try:
dates_paths = filter_and_date(root, conf_rel_paths, (i[0] for i in remotes))
except GitError:
log.info('Need to fetch from remote...')
fetch_commits(root, remotes)
try:
dates_paths = filter_and_date(root, conf_rel_paths, (i[0] for i in remotes))
except GitError as exc:
log.error(exc.message)
log.error(exc.output)
raise HandledError
except subprocess.CalledProcessError as exc:
log.debug(json.dumps(dict(command=exc.cmd, cwd=root, code=exc.returncode, output=exc.output)))
log.error('Failed to get dates for all remote commits.')
raise HandledError
filtered_remotes = [[i[0], i[1], i[2], ] + dates_paths[i[0]] for i in remotes if i[0] in dates_paths]
log.info('With docs: %s', ' '.join(i[1] for i in filtered_remotes))
if not whitelist_branches and not whitelist_tags:
return filtered_remotes
# Apply whitelist.
whitelisted_remotes = list()
for remote in filtered_remotes:
if remote[2] == 'heads' and whitelist_branches:
if not any(re.search(p, remote[1]) for p in whitelist_branches):
continue
if remote[2] == 'tags' and whitelist_tags:
if not any(re.search(p, remote[1]) for p in whitelist_tags):
continue
whitelisted_remotes.append(remote)
log.info('Passed whitelisting: %s', ' '.join(i[1] for i in whitelisted_remotes))
return whitelisted_remotes | python | def gather_git_info(root, conf_rel_paths, whitelist_branches, whitelist_tags):
"""Gather info about the remote git repository. Get list of refs.
:raise HandledError: If function fails with a handled error. Will be logged before raising.
:param str root: Root directory of repository.
:param iter conf_rel_paths: List of possible relative paths (to git root) of Sphinx conf.py (e.g. docs/conf.py).
:param iter whitelist_branches: Optional list of patterns to filter branches by.
:param iter whitelist_tags: Optional list of patterns to filter tags by.
:return: Commits with docs. A list of tuples: (sha, name, kind, date, conf_rel_path).
:rtype: list
"""
log = logging.getLogger(__name__)
# List remote.
log.info('Getting list of all remote branches/tags...')
try:
remotes = list_remote(root)
except GitError as exc:
log.error(exc.message)
log.error(exc.output)
raise HandledError
log.info('Found: %s', ' '.join(i[1] for i in remotes))
# Filter and date.
try:
try:
dates_paths = filter_and_date(root, conf_rel_paths, (i[0] for i in remotes))
except GitError:
log.info('Need to fetch from remote...')
fetch_commits(root, remotes)
try:
dates_paths = filter_and_date(root, conf_rel_paths, (i[0] for i in remotes))
except GitError as exc:
log.error(exc.message)
log.error(exc.output)
raise HandledError
except subprocess.CalledProcessError as exc:
log.debug(json.dumps(dict(command=exc.cmd, cwd=root, code=exc.returncode, output=exc.output)))
log.error('Failed to get dates for all remote commits.')
raise HandledError
filtered_remotes = [[i[0], i[1], i[2], ] + dates_paths[i[0]] for i in remotes if i[0] in dates_paths]
log.info('With docs: %s', ' '.join(i[1] for i in filtered_remotes))
if not whitelist_branches and not whitelist_tags:
return filtered_remotes
# Apply whitelist.
whitelisted_remotes = list()
for remote in filtered_remotes:
if remote[2] == 'heads' and whitelist_branches:
if not any(re.search(p, remote[1]) for p in whitelist_branches):
continue
if remote[2] == 'tags' and whitelist_tags:
if not any(re.search(p, remote[1]) for p in whitelist_tags):
continue
whitelisted_remotes.append(remote)
log.info('Passed whitelisting: %s', ' '.join(i[1] for i in whitelisted_remotes))
return whitelisted_remotes | [
"def",
"gather_git_info",
"(",
"root",
",",
"conf_rel_paths",
",",
"whitelist_branches",
",",
"whitelist_tags",
")",
":",
"log",
"=",
"logging",
".",
"getLogger",
"(",
"__name__",
")",
"# List remote.",
"log",
".",
"info",
"(",
"'Getting list of all remote branches/... | Gather info about the remote git repository. Get list of refs.
:raise HandledError: If function fails with a handled error. Will be logged before raising.
:param str root: Root directory of repository.
:param iter conf_rel_paths: List of possible relative paths (to git root) of Sphinx conf.py (e.g. docs/conf.py).
:param iter whitelist_branches: Optional list of patterns to filter branches by.
:param iter whitelist_tags: Optional list of patterns to filter tags by.
:return: Commits with docs. A list of tuples: (sha, name, kind, date, conf_rel_path).
:rtype: list | [
"Gather",
"info",
"about",
"the",
"remote",
"git",
"repository",
".",
"Get",
"list",
"of",
"refs",
"."
] | 920edec0ac764081b583a2ecf4e6952762b9dbf2 | https://github.com/Robpol86/sphinxcontrib-versioning/blob/920edec0ac764081b583a2ecf4e6952762b9dbf2/sphinxcontrib/versioning/routines.py#L38-L97 | train | 37,494 |
Robpol86/sphinxcontrib-versioning | sphinxcontrib/versioning/routines.py | pre_build | def pre_build(local_root, versions):
"""Build docs for all versions to determine root directory and master_doc names.
Need to build docs to (a) avoid filename collision with files from root_ref and branch/tag names and (b) determine
master_doc config values for all versions (in case master_doc changes from e.g. contents.rst to index.rst between
versions).
Exports all commits into a temporary directory and returns the path to avoid re-exporting during the final build.
:param str local_root: Local path to git root directory.
:param sphinxcontrib.versioning.versions.Versions versions: Versions class instance.
:return: Tempdir path with exported commits as subdirectories.
:rtype: str
"""
log = logging.getLogger(__name__)
exported_root = TempDir(True).name
# Extract all.
for sha in {r['sha'] for r in versions.remotes}:
target = os.path.join(exported_root, sha)
log.debug('Exporting %s to temporary directory.', sha)
export(local_root, sha, target)
# Build root.
remote = versions[Config.from_context().root_ref]
with TempDir() as temp_dir:
log.debug('Building root (before setting root_dirs) in temporary directory: %s', temp_dir)
source = os.path.dirname(os.path.join(exported_root, remote['sha'], remote['conf_rel_path']))
build(source, temp_dir, versions, remote['name'], True)
existing = os.listdir(temp_dir)
# Define root_dir for all versions to avoid file name collisions.
for remote in versions.remotes:
root_dir = RE_INVALID_FILENAME.sub('_', remote['name'])
while root_dir in existing:
root_dir += '_'
remote['root_dir'] = root_dir
log.debug('%s root directory is %s', remote['name'], root_dir)
existing.append(root_dir)
# Get found_docs and master_doc values for all versions.
for remote in list(versions.remotes):
log.debug('Partially running sphinx-build to read configuration for: %s', remote['name'])
source = os.path.dirname(os.path.join(exported_root, remote['sha'], remote['conf_rel_path']))
try:
config = read_config(source, remote['name'])
except HandledError:
log.warning('Skipping. Will not be building: %s', remote['name'])
versions.remotes.pop(versions.remotes.index(remote))
continue
remote['found_docs'] = config['found_docs']
remote['master_doc'] = config['master_doc']
return exported_root | python | def pre_build(local_root, versions):
"""Build docs for all versions to determine root directory and master_doc names.
Need to build docs to (a) avoid filename collision with files from root_ref and branch/tag names and (b) determine
master_doc config values for all versions (in case master_doc changes from e.g. contents.rst to index.rst between
versions).
Exports all commits into a temporary directory and returns the path to avoid re-exporting during the final build.
:param str local_root: Local path to git root directory.
:param sphinxcontrib.versioning.versions.Versions versions: Versions class instance.
:return: Tempdir path with exported commits as subdirectories.
:rtype: str
"""
log = logging.getLogger(__name__)
exported_root = TempDir(True).name
# Extract all.
for sha in {r['sha'] for r in versions.remotes}:
target = os.path.join(exported_root, sha)
log.debug('Exporting %s to temporary directory.', sha)
export(local_root, sha, target)
# Build root.
remote = versions[Config.from_context().root_ref]
with TempDir() as temp_dir:
log.debug('Building root (before setting root_dirs) in temporary directory: %s', temp_dir)
source = os.path.dirname(os.path.join(exported_root, remote['sha'], remote['conf_rel_path']))
build(source, temp_dir, versions, remote['name'], True)
existing = os.listdir(temp_dir)
# Define root_dir for all versions to avoid file name collisions.
for remote in versions.remotes:
root_dir = RE_INVALID_FILENAME.sub('_', remote['name'])
while root_dir in existing:
root_dir += '_'
remote['root_dir'] = root_dir
log.debug('%s root directory is %s', remote['name'], root_dir)
existing.append(root_dir)
# Get found_docs and master_doc values for all versions.
for remote in list(versions.remotes):
log.debug('Partially running sphinx-build to read configuration for: %s', remote['name'])
source = os.path.dirname(os.path.join(exported_root, remote['sha'], remote['conf_rel_path']))
try:
config = read_config(source, remote['name'])
except HandledError:
log.warning('Skipping. Will not be building: %s', remote['name'])
versions.remotes.pop(versions.remotes.index(remote))
continue
remote['found_docs'] = config['found_docs']
remote['master_doc'] = config['master_doc']
return exported_root | [
"def",
"pre_build",
"(",
"local_root",
",",
"versions",
")",
":",
"log",
"=",
"logging",
".",
"getLogger",
"(",
"__name__",
")",
"exported_root",
"=",
"TempDir",
"(",
"True",
")",
".",
"name",
"# Extract all.",
"for",
"sha",
"in",
"{",
"r",
"[",
"'sha'",... | Build docs for all versions to determine root directory and master_doc names.
Need to build docs to (a) avoid filename collision with files from root_ref and branch/tag names and (b) determine
master_doc config values for all versions (in case master_doc changes from e.g. contents.rst to index.rst between
versions).
Exports all commits into a temporary directory and returns the path to avoid re-exporting during the final build.
:param str local_root: Local path to git root directory.
:param sphinxcontrib.versioning.versions.Versions versions: Versions class instance.
:return: Tempdir path with exported commits as subdirectories.
:rtype: str | [
"Build",
"docs",
"for",
"all",
"versions",
"to",
"determine",
"root",
"directory",
"and",
"master_doc",
"names",
"."
] | 920edec0ac764081b583a2ecf4e6952762b9dbf2 | https://github.com/Robpol86/sphinxcontrib-versioning/blob/920edec0ac764081b583a2ecf4e6952762b9dbf2/sphinxcontrib/versioning/routines.py#L100-L154 | train | 37,495 |
Robpol86/sphinxcontrib-versioning | sphinxcontrib/versioning/routines.py | build_all | def build_all(exported_root, destination, versions):
"""Build all versions.
:param str exported_root: Tempdir path with exported commits as subdirectories.
:param str destination: Destination directory to copy/overwrite built docs to. Does not delete old files.
:param sphinxcontrib.versioning.versions.Versions versions: Versions class instance.
"""
log = logging.getLogger(__name__)
while True:
# Build root.
remote = versions[Config.from_context().root_ref]
log.info('Building root: %s', remote['name'])
source = os.path.dirname(os.path.join(exported_root, remote['sha'], remote['conf_rel_path']))
build(source, destination, versions, remote['name'], True)
# Build all refs.
for remote in list(versions.remotes):
log.info('Building ref: %s', remote['name'])
source = os.path.dirname(os.path.join(exported_root, remote['sha'], remote['conf_rel_path']))
target = os.path.join(destination, remote['root_dir'])
try:
build(source, target, versions, remote['name'], False)
except HandledError:
log.warning('Skipping. Will not be building %s. Rebuilding everything.', remote['name'])
versions.remotes.pop(versions.remotes.index(remote))
break # Break out of for loop.
else:
break | python | def build_all(exported_root, destination, versions):
"""Build all versions.
:param str exported_root: Tempdir path with exported commits as subdirectories.
:param str destination: Destination directory to copy/overwrite built docs to. Does not delete old files.
:param sphinxcontrib.versioning.versions.Versions versions: Versions class instance.
"""
log = logging.getLogger(__name__)
while True:
# Build root.
remote = versions[Config.from_context().root_ref]
log.info('Building root: %s', remote['name'])
source = os.path.dirname(os.path.join(exported_root, remote['sha'], remote['conf_rel_path']))
build(source, destination, versions, remote['name'], True)
# Build all refs.
for remote in list(versions.remotes):
log.info('Building ref: %s', remote['name'])
source = os.path.dirname(os.path.join(exported_root, remote['sha'], remote['conf_rel_path']))
target = os.path.join(destination, remote['root_dir'])
try:
build(source, target, versions, remote['name'], False)
except HandledError:
log.warning('Skipping. Will not be building %s. Rebuilding everything.', remote['name'])
versions.remotes.pop(versions.remotes.index(remote))
break # Break out of for loop.
else:
break | [
"def",
"build_all",
"(",
"exported_root",
",",
"destination",
",",
"versions",
")",
":",
"log",
"=",
"logging",
".",
"getLogger",
"(",
"__name__",
")",
"while",
"True",
":",
"# Build root.",
"remote",
"=",
"versions",
"[",
"Config",
".",
"from_context",
"(",... | Build all versions.
:param str exported_root: Tempdir path with exported commits as subdirectories.
:param str destination: Destination directory to copy/overwrite built docs to. Does not delete old files.
:param sphinxcontrib.versioning.versions.Versions versions: Versions class instance. | [
"Build",
"all",
"versions",
"."
] | 920edec0ac764081b583a2ecf4e6952762b9dbf2 | https://github.com/Robpol86/sphinxcontrib-versioning/blob/920edec0ac764081b583a2ecf4e6952762b9dbf2/sphinxcontrib/versioning/routines.py#L157-L185 | train | 37,496 |
Robpol86/sphinxcontrib-versioning | sphinxcontrib/versioning/sphinx_.py | _build | def _build(argv, config, versions, current_name, is_root):
"""Build Sphinx docs via multiprocessing for isolation.
:param tuple argv: Arguments to pass to Sphinx.
:param sphinxcontrib.versioning.lib.Config config: Runtime configuration.
:param sphinxcontrib.versioning.versions.Versions versions: Versions class instance.
:param str current_name: The ref name of the current version being built.
:param bool is_root: Is this build in the web root?
"""
# Patch.
application.Config = ConfigInject
if config.show_banner:
EventHandlers.BANNER_GREATEST_TAG = config.banner_greatest_tag
EventHandlers.BANNER_MAIN_VERSION = config.banner_main_ref
EventHandlers.BANNER_RECENT_TAG = config.banner_recent_tag
EventHandlers.SHOW_BANNER = True
EventHandlers.CURRENT_VERSION = current_name
EventHandlers.IS_ROOT = is_root
EventHandlers.VERSIONS = versions
SC_VERSIONING_VERSIONS[:] = [p for r in versions.remotes for p in sorted(r.items()) if p[0] not in ('sha', 'date')]
# Update argv.
if config.verbose > 1:
argv += ('-v',) * (config.verbose - 1)
if config.no_colors:
argv += ('-N',)
if config.overflow:
argv += config.overflow
# Build.
result = build_main(argv)
if result != 0:
raise SphinxError | python | def _build(argv, config, versions, current_name, is_root):
"""Build Sphinx docs via multiprocessing for isolation.
:param tuple argv: Arguments to pass to Sphinx.
:param sphinxcontrib.versioning.lib.Config config: Runtime configuration.
:param sphinxcontrib.versioning.versions.Versions versions: Versions class instance.
:param str current_name: The ref name of the current version being built.
:param bool is_root: Is this build in the web root?
"""
# Patch.
application.Config = ConfigInject
if config.show_banner:
EventHandlers.BANNER_GREATEST_TAG = config.banner_greatest_tag
EventHandlers.BANNER_MAIN_VERSION = config.banner_main_ref
EventHandlers.BANNER_RECENT_TAG = config.banner_recent_tag
EventHandlers.SHOW_BANNER = True
EventHandlers.CURRENT_VERSION = current_name
EventHandlers.IS_ROOT = is_root
EventHandlers.VERSIONS = versions
SC_VERSIONING_VERSIONS[:] = [p for r in versions.remotes for p in sorted(r.items()) if p[0] not in ('sha', 'date')]
# Update argv.
if config.verbose > 1:
argv += ('-v',) * (config.verbose - 1)
if config.no_colors:
argv += ('-N',)
if config.overflow:
argv += config.overflow
# Build.
result = build_main(argv)
if result != 0:
raise SphinxError | [
"def",
"_build",
"(",
"argv",
",",
"config",
",",
"versions",
",",
"current_name",
",",
"is_root",
")",
":",
"# Patch.",
"application",
".",
"Config",
"=",
"ConfigInject",
"if",
"config",
".",
"show_banner",
":",
"EventHandlers",
".",
"BANNER_GREATEST_TAG",
"=... | Build Sphinx docs via multiprocessing for isolation.
:param tuple argv: Arguments to pass to Sphinx.
:param sphinxcontrib.versioning.lib.Config config: Runtime configuration.
:param sphinxcontrib.versioning.versions.Versions versions: Versions class instance.
:param str current_name: The ref name of the current version being built.
:param bool is_root: Is this build in the web root? | [
"Build",
"Sphinx",
"docs",
"via",
"multiprocessing",
"for",
"isolation",
"."
] | 920edec0ac764081b583a2ecf4e6952762b9dbf2 | https://github.com/Robpol86/sphinxcontrib-versioning/blob/920edec0ac764081b583a2ecf4e6952762b9dbf2/sphinxcontrib/versioning/sphinx_.py#L172-L204 | train | 37,497 |
Robpol86/sphinxcontrib-versioning | sphinxcontrib/versioning/sphinx_.py | _read_config | def _read_config(argv, config, current_name, queue):
"""Read the Sphinx config via multiprocessing for isolation.
:param tuple argv: Arguments to pass to Sphinx.
:param sphinxcontrib.versioning.lib.Config config: Runtime configuration.
:param str current_name: The ref name of the current version being built.
:param multiprocessing.queues.Queue queue: Communication channel to parent process.
"""
# Patch.
EventHandlers.ABORT_AFTER_READ = queue
# Run.
_build(argv, config, Versions(list()), current_name, False) | python | def _read_config(argv, config, current_name, queue):
"""Read the Sphinx config via multiprocessing for isolation.
:param tuple argv: Arguments to pass to Sphinx.
:param sphinxcontrib.versioning.lib.Config config: Runtime configuration.
:param str current_name: The ref name of the current version being built.
:param multiprocessing.queues.Queue queue: Communication channel to parent process.
"""
# Patch.
EventHandlers.ABORT_AFTER_READ = queue
# Run.
_build(argv, config, Versions(list()), current_name, False) | [
"def",
"_read_config",
"(",
"argv",
",",
"config",
",",
"current_name",
",",
"queue",
")",
":",
"# Patch.",
"EventHandlers",
".",
"ABORT_AFTER_READ",
"=",
"queue",
"# Run.",
"_build",
"(",
"argv",
",",
"config",
",",
"Versions",
"(",
"list",
"(",
")",
")",... | Read the Sphinx config via multiprocessing for isolation.
:param tuple argv: Arguments to pass to Sphinx.
:param sphinxcontrib.versioning.lib.Config config: Runtime configuration.
:param str current_name: The ref name of the current version being built.
:param multiprocessing.queues.Queue queue: Communication channel to parent process. | [
"Read",
"the",
"Sphinx",
"config",
"via",
"multiprocessing",
"for",
"isolation",
"."
] | 920edec0ac764081b583a2ecf4e6952762b9dbf2 | https://github.com/Robpol86/sphinxcontrib-versioning/blob/920edec0ac764081b583a2ecf4e6952762b9dbf2/sphinxcontrib/versioning/sphinx_.py#L207-L219 | train | 37,498 |
Robpol86/sphinxcontrib-versioning | sphinxcontrib/versioning/sphinx_.py | read_config | def read_config(source, current_name):
"""Read the Sphinx config for one version.
:raise HandledError: If sphinx-build fails. Will be logged before raising.
:param str source: Source directory to pass to sphinx-build.
:param str current_name: The ref name of the current version being built.
:return: Specific Sphinx config values.
:rtype: dict
"""
log = logging.getLogger(__name__)
queue = multiprocessing.Queue()
config = Config.from_context()
with TempDir() as temp_dir:
argv = ('sphinx-build', source, temp_dir)
log.debug('Running sphinx-build for config values with args: %s', str(argv))
child = multiprocessing.Process(target=_read_config, args=(argv, config, current_name, queue))
child.start()
child.join() # Block.
if child.exitcode != 0:
log.error('sphinx-build failed for branch/tag while reading config: %s', current_name)
raise HandledError
config = queue.get()
return config | python | def read_config(source, current_name):
"""Read the Sphinx config for one version.
:raise HandledError: If sphinx-build fails. Will be logged before raising.
:param str source: Source directory to pass to sphinx-build.
:param str current_name: The ref name of the current version being built.
:return: Specific Sphinx config values.
:rtype: dict
"""
log = logging.getLogger(__name__)
queue = multiprocessing.Queue()
config = Config.from_context()
with TempDir() as temp_dir:
argv = ('sphinx-build', source, temp_dir)
log.debug('Running sphinx-build for config values with args: %s', str(argv))
child = multiprocessing.Process(target=_read_config, args=(argv, config, current_name, queue))
child.start()
child.join() # Block.
if child.exitcode != 0:
log.error('sphinx-build failed for branch/tag while reading config: %s', current_name)
raise HandledError
config = queue.get()
return config | [
"def",
"read_config",
"(",
"source",
",",
"current_name",
")",
":",
"log",
"=",
"logging",
".",
"getLogger",
"(",
"__name__",
")",
"queue",
"=",
"multiprocessing",
".",
"Queue",
"(",
")",
"config",
"=",
"Config",
".",
"from_context",
"(",
")",
"with",
"T... | Read the Sphinx config for one version.
:raise HandledError: If sphinx-build fails. Will be logged before raising.
:param str source: Source directory to pass to sphinx-build.
:param str current_name: The ref name of the current version being built.
:return: Specific Sphinx config values.
:rtype: dict | [
"Read",
"the",
"Sphinx",
"config",
"for",
"one",
"version",
"."
] | 920edec0ac764081b583a2ecf4e6952762b9dbf2 | https://github.com/Robpol86/sphinxcontrib-versioning/blob/920edec0ac764081b583a2ecf4e6952762b9dbf2/sphinxcontrib/versioning/sphinx_.py#L246-L272 | train | 37,499 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.