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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
NiklasRosenstein/pydoc-markdown | pydocmd/imp.py | import_object_with_scope | def import_object_with_scope(name):
"""
Imports a Python object by an absolute identifier.
# Arguments
name (str): The name of the Python object to import.
# Returns
(any, Module): The object and the module that contains it. Note that
for plain modules loaded with this function, both elements of the
tuple may be the same object.
"""
# Import modules until we can no longer import them. Prefer existing
# attributes over importing modules at each step.
parts = name.split('.')
current_name = parts[0]
obj = import_module(current_name)
scope = None
for part in parts[1:]:
current_name += '.' + part
try:
if hasattr(obj, '__dict__'):
# Using directly __dict__ for descriptors, where we want to get the descriptor's instance
# and not calling the descriptor's __get__ method.
sub_obj = obj.__dict__[part]
else:
sub_obj = getattr(obj, part)
scope, obj = obj, sub_obj
except (AttributeError, KeyError):
try:
obj = scope = import_module(current_name)
except ImportError as exc:
if 'named {}'.format(part) in str(exc):
raise ImportError(current_name)
raise
return obj, scope | python | def import_object_with_scope(name):
"""
Imports a Python object by an absolute identifier.
# Arguments
name (str): The name of the Python object to import.
# Returns
(any, Module): The object and the module that contains it. Note that
for plain modules loaded with this function, both elements of the
tuple may be the same object.
"""
# Import modules until we can no longer import them. Prefer existing
# attributes over importing modules at each step.
parts = name.split('.')
current_name = parts[0]
obj = import_module(current_name)
scope = None
for part in parts[1:]:
current_name += '.' + part
try:
if hasattr(obj, '__dict__'):
# Using directly __dict__ for descriptors, where we want to get the descriptor's instance
# and not calling the descriptor's __get__ method.
sub_obj = obj.__dict__[part]
else:
sub_obj = getattr(obj, part)
scope, obj = obj, sub_obj
except (AttributeError, KeyError):
try:
obj = scope = import_module(current_name)
except ImportError as exc:
if 'named {}'.format(part) in str(exc):
raise ImportError(current_name)
raise
return obj, scope | [
"def",
"import_object_with_scope",
"(",
"name",
")",
":",
"# Import modules until we can no longer import them. Prefer existing",
"# attributes over importing modules at each step.",
"parts",
"=",
"name",
".",
"split",
"(",
"'.'",
")",
"current_name",
"=",
"parts",
"[",
"0",
... | Imports a Python object by an absolute identifier.
# Arguments
name (str): The name of the Python object to import.
# Returns
(any, Module): The object and the module that contains it. Note that
for plain modules loaded with this function, both elements of the
tuple may be the same object. | [
"Imports",
"a",
"Python",
"object",
"by",
"an",
"absolute",
"identifier",
"."
] | e7e93b2bf7f7535e0de4cd275058fc9865dff21b | https://github.com/NiklasRosenstein/pydoc-markdown/blob/e7e93b2bf7f7535e0de4cd275058fc9865dff21b/pydocmd/imp.py#L47-L84 | train | 199,200 |
NiklasRosenstein/pydoc-markdown | pydocmd/imp.py | force_lazy_import | def force_lazy_import(name):
"""
Import any modules off of "name" by iterating a new list rather than a generator so that this
library works with lazy imports.
"""
obj = import_object(name)
module_items = list(getattr(obj, '__dict__', {}).items())
for key, value in module_items:
if getattr(value, '__module__', None):
import_object(name + '.' + key) | python | def force_lazy_import(name):
"""
Import any modules off of "name" by iterating a new list rather than a generator so that this
library works with lazy imports.
"""
obj = import_object(name)
module_items = list(getattr(obj, '__dict__', {}).items())
for key, value in module_items:
if getattr(value, '__module__', None):
import_object(name + '.' + key) | [
"def",
"force_lazy_import",
"(",
"name",
")",
":",
"obj",
"=",
"import_object",
"(",
"name",
")",
"module_items",
"=",
"list",
"(",
"getattr",
"(",
"obj",
",",
"'__dict__'",
",",
"{",
"}",
")",
".",
"items",
"(",
")",
")",
"for",
"key",
",",
"value",... | Import any modules off of "name" by iterating a new list rather than a generator so that this
library works with lazy imports. | [
"Import",
"any",
"modules",
"off",
"of",
"name",
"by",
"iterating",
"a",
"new",
"list",
"rather",
"than",
"a",
"generator",
"so",
"that",
"this",
"library",
"works",
"with",
"lazy",
"imports",
"."
] | e7e93b2bf7f7535e0de4cd275058fc9865dff21b | https://github.com/NiklasRosenstein/pydoc-markdown/blob/e7e93b2bf7f7535e0de4cd275058fc9865dff21b/pydocmd/imp.py#L87-L96 | train | 199,201 |
NiklasRosenstein/pydoc-markdown | pydocmd/restructuredtext.py | Preprocessor.preprocess_section | def preprocess_section(self, section):
"""
Preprocessors a given section into it's components.
"""
lines = []
in_codeblock = False
keyword = None
components = {}
for line in section.content.split('\n'):
line = line.strip()
if line.startswith("```"):
in_codeblock = not in_codeblock
if not in_codeblock:
match = re.match(r':(?:param|parameter)\s+(\w+)\s*:(.*)?$', line)
if match:
keyword = 'Arguments'
param = match.group(1)
text = match.group(2)
text = text.strip()
component = components.get(keyword, [])
component.append('- `{}`: {}'.format(param, text))
components[keyword] = component
continue
match = re.match(r':(?:return|returns)\s*:(.*)?$', line)
if match:
keyword = 'Returns'
text = match.group(1)
text = text.strip()
component = components.get(keyword, [])
component.append(text)
components[keyword] = component
continue
match = re.match(':(?:raises|raise)\s+(\w+)\s*:(.*)?$', line)
if match:
keyword = 'Raises'
exception = match.group(1)
text = match.group(2)
text = text.strip()
component = components.get(keyword, [])
component.append('- `{}`: {}'.format(exception, text))
components[keyword] = component
continue
if keyword is not None:
components[keyword].append(line)
else:
lines.append(line)
for key in components:
self._append_section(lines, key, components)
section.content = '\n'.join(lines) | python | def preprocess_section(self, section):
"""
Preprocessors a given section into it's components.
"""
lines = []
in_codeblock = False
keyword = None
components = {}
for line in section.content.split('\n'):
line = line.strip()
if line.startswith("```"):
in_codeblock = not in_codeblock
if not in_codeblock:
match = re.match(r':(?:param|parameter)\s+(\w+)\s*:(.*)?$', line)
if match:
keyword = 'Arguments'
param = match.group(1)
text = match.group(2)
text = text.strip()
component = components.get(keyword, [])
component.append('- `{}`: {}'.format(param, text))
components[keyword] = component
continue
match = re.match(r':(?:return|returns)\s*:(.*)?$', line)
if match:
keyword = 'Returns'
text = match.group(1)
text = text.strip()
component = components.get(keyword, [])
component.append(text)
components[keyword] = component
continue
match = re.match(':(?:raises|raise)\s+(\w+)\s*:(.*)?$', line)
if match:
keyword = 'Raises'
exception = match.group(1)
text = match.group(2)
text = text.strip()
component = components.get(keyword, [])
component.append('- `{}`: {}'.format(exception, text))
components[keyword] = component
continue
if keyword is not None:
components[keyword].append(line)
else:
lines.append(line)
for key in components:
self._append_section(lines, key, components)
section.content = '\n'.join(lines) | [
"def",
"preprocess_section",
"(",
"self",
",",
"section",
")",
":",
"lines",
"=",
"[",
"]",
"in_codeblock",
"=",
"False",
"keyword",
"=",
"None",
"components",
"=",
"{",
"}",
"for",
"line",
"in",
"section",
".",
"content",
".",
"split",
"(",
"'\\n'",
"... | Preprocessors a given section into it's components. | [
"Preprocessors",
"a",
"given",
"section",
"into",
"it",
"s",
"components",
"."
] | e7e93b2bf7f7535e0de4cd275058fc9865dff21b | https://github.com/NiklasRosenstein/pydoc-markdown/blob/e7e93b2bf7f7535e0de4cd275058fc9865dff21b/pydocmd/restructuredtext.py#L35-L93 | train | 199,202 |
rtfd/sphinx-autoapi | autoapi/mappers/go.py | GoSphinxMapper.create_class | def create_class(self, data, options=None, **kwargs):
"""Return instance of class based on Go data
Data keys handled here:
_type
Set the object class
consts, types, vars, funcs
Recurse into :py:meth:`create_class` to create child object
instances
:param data: dictionary data from godocjson output
"""
_type = kwargs.get("_type")
obj_map = dict((cls.type, cls) for cls in ALL_CLASSES)
try:
# Contextual type data from children recursion
if _type:
LOGGER.debug("Forcing Go Type %s" % _type)
cls = obj_map[_type]
else:
cls = obj_map[data["type"]]
except KeyError:
LOGGER.warning("Unknown Type: %s" % data)
else:
if cls.inverted_names and "names" in data:
# Handle types that have reversed names parameter
for name in data["names"]:
data_inv = {}
data_inv.update(data)
data_inv["name"] = name
if "names" in data_inv:
del data_inv["names"]
for obj in self.create_class(data_inv):
yield obj
else:
# Recurse for children
obj = cls(data, jinja_env=self.jinja_env)
for child_type in ["consts", "types", "vars", "funcs"]:
for child_data in data.get(child_type, []):
obj.children += list(
self.create_class(
child_data,
_type=child_type.replace("consts", "const")
.replace("types", "type")
.replace("vars", "variable")
.replace("funcs", "func"),
)
)
yield obj | python | def create_class(self, data, options=None, **kwargs):
"""Return instance of class based on Go data
Data keys handled here:
_type
Set the object class
consts, types, vars, funcs
Recurse into :py:meth:`create_class` to create child object
instances
:param data: dictionary data from godocjson output
"""
_type = kwargs.get("_type")
obj_map = dict((cls.type, cls) for cls in ALL_CLASSES)
try:
# Contextual type data from children recursion
if _type:
LOGGER.debug("Forcing Go Type %s" % _type)
cls = obj_map[_type]
else:
cls = obj_map[data["type"]]
except KeyError:
LOGGER.warning("Unknown Type: %s" % data)
else:
if cls.inverted_names and "names" in data:
# Handle types that have reversed names parameter
for name in data["names"]:
data_inv = {}
data_inv.update(data)
data_inv["name"] = name
if "names" in data_inv:
del data_inv["names"]
for obj in self.create_class(data_inv):
yield obj
else:
# Recurse for children
obj = cls(data, jinja_env=self.jinja_env)
for child_type in ["consts", "types", "vars", "funcs"]:
for child_data in data.get(child_type, []):
obj.children += list(
self.create_class(
child_data,
_type=child_type.replace("consts", "const")
.replace("types", "type")
.replace("vars", "variable")
.replace("funcs", "func"),
)
)
yield obj | [
"def",
"create_class",
"(",
"self",
",",
"data",
",",
"options",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"_type",
"=",
"kwargs",
".",
"get",
"(",
"\"_type\"",
")",
"obj_map",
"=",
"dict",
"(",
"(",
"cls",
".",
"type",
",",
"cls",
")",
"fo... | Return instance of class based on Go data
Data keys handled here:
_type
Set the object class
consts, types, vars, funcs
Recurse into :py:meth:`create_class` to create child object
instances
:param data: dictionary data from godocjson output | [
"Return",
"instance",
"of",
"class",
"based",
"on",
"Go",
"data"
] | 9735f43a8d9ff4620c7bcbd177fd1bb7608052e9 | https://github.com/rtfd/sphinx-autoapi/blob/9735f43a8d9ff4620c7bcbd177fd1bb7608052e9/autoapi/mappers/go.py#L57-L107 | train | 199,203 |
rtfd/sphinx-autoapi | autoapi/mappers/base.py | PythonMapperBase.pathname | def pathname(self):
"""Sluggified path for filenames
Slugs to a filename using the follow steps
* Decode unicode to approximate ascii
* Remove existing hypens
* Substitute hyphens for non-word characters
* Break up the string as paths
"""
slug = self.name
slug = unidecode.unidecode(slug)
slug = slug.replace("-", "")
slug = re.sub(r"[^\w\.]+", "-", slug).strip("-")
return os.path.join(*slug.split(".")) | python | def pathname(self):
"""Sluggified path for filenames
Slugs to a filename using the follow steps
* Decode unicode to approximate ascii
* Remove existing hypens
* Substitute hyphens for non-word characters
* Break up the string as paths
"""
slug = self.name
slug = unidecode.unidecode(slug)
slug = slug.replace("-", "")
slug = re.sub(r"[^\w\.]+", "-", slug).strip("-")
return os.path.join(*slug.split(".")) | [
"def",
"pathname",
"(",
"self",
")",
":",
"slug",
"=",
"self",
".",
"name",
"slug",
"=",
"unidecode",
".",
"unidecode",
"(",
"slug",
")",
"slug",
"=",
"slug",
".",
"replace",
"(",
"\"-\"",
",",
"\"\"",
")",
"slug",
"=",
"re",
".",
"sub",
"(",
"r\... | Sluggified path for filenames
Slugs to a filename using the follow steps
* Decode unicode to approximate ascii
* Remove existing hypens
* Substitute hyphens for non-word characters
* Break up the string as paths | [
"Sluggified",
"path",
"for",
"filenames"
] | 9735f43a8d9ff4620c7bcbd177fd1bb7608052e9 | https://github.com/rtfd/sphinx-autoapi/blob/9735f43a8d9ff4620c7bcbd177fd1bb7608052e9/autoapi/mappers/base.py#L107-L121 | train | 199,204 |
rtfd/sphinx-autoapi | autoapi/mappers/base.py | PythonMapperBase.include_dir | def include_dir(self, root):
"""Return directory of file"""
parts = [root]
parts.extend(self.pathname.split(os.path.sep))
return "/".join(parts) | python | def include_dir(self, root):
"""Return directory of file"""
parts = [root]
parts.extend(self.pathname.split(os.path.sep))
return "/".join(parts) | [
"def",
"include_dir",
"(",
"self",
",",
"root",
")",
":",
"parts",
"=",
"[",
"root",
"]",
"parts",
".",
"extend",
"(",
"self",
".",
"pathname",
".",
"split",
"(",
"os",
".",
"path",
".",
"sep",
")",
")",
"return",
"\"/\"",
".",
"join",
"(",
"part... | Return directory of file | [
"Return",
"directory",
"of",
"file"
] | 9735f43a8d9ff4620c7bcbd177fd1bb7608052e9 | https://github.com/rtfd/sphinx-autoapi/blob/9735f43a8d9ff4620c7bcbd177fd1bb7608052e9/autoapi/mappers/base.py#L123-L127 | train | 199,205 |
rtfd/sphinx-autoapi | autoapi/mappers/base.py | PythonMapperBase.include_path | def include_path(self):
"""Return 'absolute' path without regarding OS path separator
This is used in ``toctree`` directives, as Sphinx always expects Unix
path separators
"""
parts = [self.include_dir(root=self.url_root)]
parts.append("index")
return "/".join(parts) | python | def include_path(self):
"""Return 'absolute' path without regarding OS path separator
This is used in ``toctree`` directives, as Sphinx always expects Unix
path separators
"""
parts = [self.include_dir(root=self.url_root)]
parts.append("index")
return "/".join(parts) | [
"def",
"include_path",
"(",
"self",
")",
":",
"parts",
"=",
"[",
"self",
".",
"include_dir",
"(",
"root",
"=",
"self",
".",
"url_root",
")",
"]",
"parts",
".",
"append",
"(",
"\"index\"",
")",
"return",
"\"/\"",
".",
"join",
"(",
"parts",
")"
] | Return 'absolute' path without regarding OS path separator
This is used in ``toctree`` directives, as Sphinx always expects Unix
path separators | [
"Return",
"absolute",
"path",
"without",
"regarding",
"OS",
"path",
"separator"
] | 9735f43a8d9ff4620c7bcbd177fd1bb7608052e9 | https://github.com/rtfd/sphinx-autoapi/blob/9735f43a8d9ff4620c7bcbd177fd1bb7608052e9/autoapi/mappers/base.py#L130-L138 | train | 199,206 |
rtfd/sphinx-autoapi | autoapi/mappers/javascript.py | JavaScriptSphinxMapper.create_class | def create_class(self, data, options=None, **kwargs):
"""Return instance of class based on Javascript data
Data keys handled here:
type
Set the object class
consts, types, vars, funcs
Recurse into :py:meth:`create_class` to create child object
instances
:param data: dictionary data from godocjson output
"""
obj_map = dict((cls.type, cls) for cls in ALL_CLASSES)
try:
cls = obj_map[data["kind"]]
except (KeyError, TypeError):
LOGGER.warning("Unknown Type: %s" % data)
else:
# Recurse for children
obj = cls(data, jinja_env=self.jinja_env)
if "children" in data:
for child_data in data["children"]:
for child_obj in self.create_class(child_data, options=options):
obj.children.append(child_obj)
yield obj | python | def create_class(self, data, options=None, **kwargs):
"""Return instance of class based on Javascript data
Data keys handled here:
type
Set the object class
consts, types, vars, funcs
Recurse into :py:meth:`create_class` to create child object
instances
:param data: dictionary data from godocjson output
"""
obj_map = dict((cls.type, cls) for cls in ALL_CLASSES)
try:
cls = obj_map[data["kind"]]
except (KeyError, TypeError):
LOGGER.warning("Unknown Type: %s" % data)
else:
# Recurse for children
obj = cls(data, jinja_env=self.jinja_env)
if "children" in data:
for child_data in data["children"]:
for child_obj in self.create_class(child_data, options=options):
obj.children.append(child_obj)
yield obj | [
"def",
"create_class",
"(",
"self",
",",
"data",
",",
"options",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"obj_map",
"=",
"dict",
"(",
"(",
"cls",
".",
"type",
",",
"cls",
")",
"for",
"cls",
"in",
"ALL_CLASSES",
")",
"try",
":",
"cls",
"="... | Return instance of class based on Javascript data
Data keys handled here:
type
Set the object class
consts, types, vars, funcs
Recurse into :py:meth:`create_class` to create child object
instances
:param data: dictionary data from godocjson output | [
"Return",
"instance",
"of",
"class",
"based",
"on",
"Javascript",
"data"
] | 9735f43a8d9ff4620c7bcbd177fd1bb7608052e9 | https://github.com/rtfd/sphinx-autoapi/blob/9735f43a8d9ff4620c7bcbd177fd1bb7608052e9/autoapi/mappers/javascript.py#L50-L76 | train | 199,207 |
rtfd/sphinx-autoapi | autoapi/mappers/dotnet.py | DotNetSphinxMapper.create_class | def create_class(self, data, options=None, path=None, **kwargs):
"""
Return instance of class based on Roslyn type property
Data keys handled here:
type
Set the object class
items
Recurse into :py:meth:`create_class` to create child object
instances
:param data: dictionary data from Roslyn output artifact
"""
obj_map = dict((cls.type, cls) for cls in ALL_CLASSES)
try:
cls = obj_map[data["type"].lower()]
except KeyError:
LOGGER.warning("Unknown type: %s" % data)
else:
obj = cls(
data,
jinja_env=self.jinja_env,
options=options,
url_root=self.url_root,
**kwargs
)
# Append child objects
# TODO this should recurse in the case we're getting back more
# complex argument listings
yield obj | python | def create_class(self, data, options=None, path=None, **kwargs):
"""
Return instance of class based on Roslyn type property
Data keys handled here:
type
Set the object class
items
Recurse into :py:meth:`create_class` to create child object
instances
:param data: dictionary data from Roslyn output artifact
"""
obj_map = dict((cls.type, cls) for cls in ALL_CLASSES)
try:
cls = obj_map[data["type"].lower()]
except KeyError:
LOGGER.warning("Unknown type: %s" % data)
else:
obj = cls(
data,
jinja_env=self.jinja_env,
options=options,
url_root=self.url_root,
**kwargs
)
# Append child objects
# TODO this should recurse in the case we're getting back more
# complex argument listings
yield obj | [
"def",
"create_class",
"(",
"self",
",",
"data",
",",
"options",
"=",
"None",
",",
"path",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"obj_map",
"=",
"dict",
"(",
"(",
"cls",
".",
"type",
",",
"cls",
")",
"for",
"cls",
"in",
"ALL_CLASSES",
"... | Return instance of class based on Roslyn type property
Data keys handled here:
type
Set the object class
items
Recurse into :py:meth:`create_class` to create child object
instances
:param data: dictionary data from Roslyn output artifact | [
"Return",
"instance",
"of",
"class",
"based",
"on",
"Roslyn",
"type",
"property"
] | 9735f43a8d9ff4620c7bcbd177fd1bb7608052e9 | https://github.com/rtfd/sphinx-autoapi/blob/9735f43a8d9ff4620c7bcbd177fd1bb7608052e9/autoapi/mappers/dotnet.py#L147-L181 | train | 199,208 |
rtfd/sphinx-autoapi | autoapi/mappers/dotnet.py | DotNetSphinxMapper.organize_objects | def organize_objects(self):
"""Organize objects and namespaces"""
def _render_children(obj):
for child in obj.children_strings:
child_object = self.objects.get(child)
if child_object:
obj.item_map[child_object.plural].append(child_object)
obj.children.append(child_object)
for key in obj.item_map:
obj.item_map[key].sort()
def _recurse_ns(obj):
if not obj:
return
namespace = obj.top_namespace
if namespace is not None:
ns_obj = self.top_namespaces.get(namespace)
if ns_obj is None or not isinstance(ns_obj, DotNetNamespace):
for ns_obj in self.create_class(
{"uid": namespace, "type": "namespace"}
):
self.top_namespaces[ns_obj.id] = ns_obj
if obj not in ns_obj.children and namespace != obj.id:
ns_obj.children.append(obj)
for obj in self.objects.values():
_render_children(obj)
_recurse_ns(obj)
# Clean out dead namespaces
for key, ns in self.top_namespaces.copy().items():
if not ns.children:
del self.top_namespaces[key]
for key, ns in self.namespaces.items():
if not ns.children:
del self.namespaces[key] | python | def organize_objects(self):
"""Organize objects and namespaces"""
def _render_children(obj):
for child in obj.children_strings:
child_object = self.objects.get(child)
if child_object:
obj.item_map[child_object.plural].append(child_object)
obj.children.append(child_object)
for key in obj.item_map:
obj.item_map[key].sort()
def _recurse_ns(obj):
if not obj:
return
namespace = obj.top_namespace
if namespace is not None:
ns_obj = self.top_namespaces.get(namespace)
if ns_obj is None or not isinstance(ns_obj, DotNetNamespace):
for ns_obj in self.create_class(
{"uid": namespace, "type": "namespace"}
):
self.top_namespaces[ns_obj.id] = ns_obj
if obj not in ns_obj.children and namespace != obj.id:
ns_obj.children.append(obj)
for obj in self.objects.values():
_render_children(obj)
_recurse_ns(obj)
# Clean out dead namespaces
for key, ns in self.top_namespaces.copy().items():
if not ns.children:
del self.top_namespaces[key]
for key, ns in self.namespaces.items():
if not ns.children:
del self.namespaces[key] | [
"def",
"organize_objects",
"(",
"self",
")",
":",
"def",
"_render_children",
"(",
"obj",
")",
":",
"for",
"child",
"in",
"obj",
".",
"children_strings",
":",
"child_object",
"=",
"self",
".",
"objects",
".",
"get",
"(",
"child",
")",
"if",
"child_object",
... | Organize objects and namespaces | [
"Organize",
"objects",
"and",
"namespaces"
] | 9735f43a8d9ff4620c7bcbd177fd1bb7608052e9 | https://github.com/rtfd/sphinx-autoapi/blob/9735f43a8d9ff4620c7bcbd177fd1bb7608052e9/autoapi/mappers/dotnet.py#L193-L231 | train | 199,209 |
rtfd/sphinx-autoapi | autoapi/mappers/dotnet.py | DotNetPythonMapper.transform_doc_comments | def transform_doc_comments(text):
"""
Parse XML content for references and other syntax.
This avoids an LXML dependency, we only need to parse out a small subset
of elements here. Iterate over string to reduce regex pattern complexity
and make substitutions easier
.. seealso::
`Doc comment reference <https://msdn.microsoft.com/en-us/library/5ast78ax.aspx>`
Reference on XML documentation comment syntax
"""
try:
while True:
found = DOC_COMMENT_SEE_PATTERN.search(text)
if found is None:
break
ref = found.group("attr_value").replace("<", "\<").replace("`", "\`")
reftype = "any"
replacement = ""
# Given the pattern of `\w:\w+`, inspect first letter of
# reference for identity type
if ref[1] == ":" and ref[0] in DOC_COMMENT_IDENTITIES:
reftype = DOC_COMMENT_IDENTITIES[ref[:1]]
ref = ref[2:]
replacement = ":{reftype}:`{ref}`".format(reftype=reftype, ref=ref)
elif ref[:2] == "!:":
replacement = ref[2:]
else:
replacement = ":any:`{ref}`".format(ref=ref)
# Escape following text
text_end = text[found.end() :]
text_start = text[: found.start()]
text_end = re.sub(r"^(\S)", r"\\\1", text_end)
text_start = re.sub(r"(\S)$", r"\1 ", text_start)
text = "".join([text_start, replacement, text_end])
while True:
found = DOC_COMMENT_PARAM_PATTERN.search(text)
if found is None:
break
# Escape following text
text_end = text[found.end() :]
text_start = text[: found.start()]
text_end = re.sub(r"^(\S)", r"\\\1", text_end)
text_start = re.sub(r"(\S)$", r"\1 ", text_start)
text = "".join(
[text_start, "``", found.group("attr_value"), "``", text_end]
)
except TypeError:
pass
return text | python | def transform_doc_comments(text):
"""
Parse XML content for references and other syntax.
This avoids an LXML dependency, we only need to parse out a small subset
of elements here. Iterate over string to reduce regex pattern complexity
and make substitutions easier
.. seealso::
`Doc comment reference <https://msdn.microsoft.com/en-us/library/5ast78ax.aspx>`
Reference on XML documentation comment syntax
"""
try:
while True:
found = DOC_COMMENT_SEE_PATTERN.search(text)
if found is None:
break
ref = found.group("attr_value").replace("<", "\<").replace("`", "\`")
reftype = "any"
replacement = ""
# Given the pattern of `\w:\w+`, inspect first letter of
# reference for identity type
if ref[1] == ":" and ref[0] in DOC_COMMENT_IDENTITIES:
reftype = DOC_COMMENT_IDENTITIES[ref[:1]]
ref = ref[2:]
replacement = ":{reftype}:`{ref}`".format(reftype=reftype, ref=ref)
elif ref[:2] == "!:":
replacement = ref[2:]
else:
replacement = ":any:`{ref}`".format(ref=ref)
# Escape following text
text_end = text[found.end() :]
text_start = text[: found.start()]
text_end = re.sub(r"^(\S)", r"\\\1", text_end)
text_start = re.sub(r"(\S)$", r"\1 ", text_start)
text = "".join([text_start, replacement, text_end])
while True:
found = DOC_COMMENT_PARAM_PATTERN.search(text)
if found is None:
break
# Escape following text
text_end = text[found.end() :]
text_start = text[: found.start()]
text_end = re.sub(r"^(\S)", r"\\\1", text_end)
text_start = re.sub(r"(\S)$", r"\1 ", text_start)
text = "".join(
[text_start, "``", found.group("attr_value"), "``", text_end]
)
except TypeError:
pass
return text | [
"def",
"transform_doc_comments",
"(",
"text",
")",
":",
"try",
":",
"while",
"True",
":",
"found",
"=",
"DOC_COMMENT_SEE_PATTERN",
".",
"search",
"(",
"text",
")",
"if",
"found",
"is",
"None",
":",
"break",
"ref",
"=",
"found",
".",
"group",
"(",
"\"attr... | Parse XML content for references and other syntax.
This avoids an LXML dependency, we only need to parse out a small subset
of elements here. Iterate over string to reduce regex pattern complexity
and make substitutions easier
.. seealso::
`Doc comment reference <https://msdn.microsoft.com/en-us/library/5ast78ax.aspx>`
Reference on XML documentation comment syntax | [
"Parse",
"XML",
"content",
"for",
"references",
"and",
"other",
"syntax",
"."
] | 9735f43a8d9ff4620c7bcbd177fd1bb7608052e9 | https://github.com/rtfd/sphinx-autoapi/blob/9735f43a8d9ff4620c7bcbd177fd1bb7608052e9/autoapi/mappers/dotnet.py#L429-L485 | train | 199,210 |
rtfd/sphinx-autoapi | autoapi/mappers/dotnet.py | DotNetPythonMapper.resolve_spec_identifier | def resolve_spec_identifier(self, obj_name):
"""Find reference name based on spec identifier
Spec identifiers are used in parameter and return type definitions, but
should be a user-friendly version instead. Use docfx ``references``
lookup mapping for resolution.
If the spec identifier reference has a ``spec.csharp`` key, this implies
a compound reference that should be linked in a special way. Resolve to
a nested reference, with the corrected nodes.
.. note::
This uses a special format that is interpreted by the domain for
parameter type and return type fields.
:param obj_name: spec identifier to resolve to a correct reference
:returns: resolved string with one or more references
:rtype: str
"""
ref = self.references.get(obj_name)
if ref is None:
return obj_name
resolved = ref.get("fullName", obj_name)
spec = ref.get("spec.csharp", [])
parts = []
for part in spec:
if part.get("name") == "<":
parts.append("{")
elif part.get("name") == ">":
parts.append("}")
elif "fullName" in part and "uid" in part:
parts.append("{fullName}<{uid}>".format(**part))
elif "uid" in part:
parts.append(part["uid"])
elif "fullName" in part:
parts.append(part["fullName"])
if parts:
resolved = "".join(parts)
return resolved | python | def resolve_spec_identifier(self, obj_name):
"""Find reference name based on spec identifier
Spec identifiers are used in parameter and return type definitions, but
should be a user-friendly version instead. Use docfx ``references``
lookup mapping for resolution.
If the spec identifier reference has a ``spec.csharp`` key, this implies
a compound reference that should be linked in a special way. Resolve to
a nested reference, with the corrected nodes.
.. note::
This uses a special format that is interpreted by the domain for
parameter type and return type fields.
:param obj_name: spec identifier to resolve to a correct reference
:returns: resolved string with one or more references
:rtype: str
"""
ref = self.references.get(obj_name)
if ref is None:
return obj_name
resolved = ref.get("fullName", obj_name)
spec = ref.get("spec.csharp", [])
parts = []
for part in spec:
if part.get("name") == "<":
parts.append("{")
elif part.get("name") == ">":
parts.append("}")
elif "fullName" in part and "uid" in part:
parts.append("{fullName}<{uid}>".format(**part))
elif "uid" in part:
parts.append(part["uid"])
elif "fullName" in part:
parts.append(part["fullName"])
if parts:
resolved = "".join(parts)
return resolved | [
"def",
"resolve_spec_identifier",
"(",
"self",
",",
"obj_name",
")",
":",
"ref",
"=",
"self",
".",
"references",
".",
"get",
"(",
"obj_name",
")",
"if",
"ref",
"is",
"None",
":",
"return",
"obj_name",
"resolved",
"=",
"ref",
".",
"get",
"(",
"\"fullName\... | Find reference name based on spec identifier
Spec identifiers are used in parameter and return type definitions, but
should be a user-friendly version instead. Use docfx ``references``
lookup mapping for resolution.
If the spec identifier reference has a ``spec.csharp`` key, this implies
a compound reference that should be linked in a special way. Resolve to
a nested reference, with the corrected nodes.
.. note::
This uses a special format that is interpreted by the domain for
parameter type and return type fields.
:param obj_name: spec identifier to resolve to a correct reference
:returns: resolved string with one or more references
:rtype: str | [
"Find",
"reference",
"name",
"based",
"on",
"spec",
"identifier"
] | 9735f43a8d9ff4620c7bcbd177fd1bb7608052e9 | https://github.com/rtfd/sphinx-autoapi/blob/9735f43a8d9ff4620c7bcbd177fd1bb7608052e9/autoapi/mappers/dotnet.py#L487-L526 | train | 199,211 |
rtfd/sphinx-autoapi | autoapi/mappers/python/objects.py | PythonPythonMapper.display | def display(self):
"""Whether this object should be displayed in documentation.
This attribute depends on the configuration options given in
:confval:`autoapi_options`.
:type: bool
"""
if self.is_undoc_member and "undoc-members" not in self.options:
return False
if self.is_private_member and "private-members" not in self.options:
return False
if self.is_special_member and "special-members" not in self.options:
return False
return True | python | def display(self):
"""Whether this object should be displayed in documentation.
This attribute depends on the configuration options given in
:confval:`autoapi_options`.
:type: bool
"""
if self.is_undoc_member and "undoc-members" not in self.options:
return False
if self.is_private_member and "private-members" not in self.options:
return False
if self.is_special_member and "special-members" not in self.options:
return False
return True | [
"def",
"display",
"(",
"self",
")",
":",
"if",
"self",
".",
"is_undoc_member",
"and",
"\"undoc-members\"",
"not",
"in",
"self",
".",
"options",
":",
"return",
"False",
"if",
"self",
".",
"is_private_member",
"and",
"\"private-members\"",
"not",
"in",
"self",
... | Whether this object should be displayed in documentation.
This attribute depends on the configuration options given in
:confval:`autoapi_options`.
:type: bool | [
"Whether",
"this",
"object",
"should",
"be",
"displayed",
"in",
"documentation",
"."
] | 9735f43a8d9ff4620c7bcbd177fd1bb7608052e9 | https://github.com/rtfd/sphinx-autoapi/blob/9735f43a8d9ff4620c7bcbd177fd1bb7608052e9/autoapi/mappers/python/objects.py#L92-L106 | train | 199,212 |
rtfd/sphinx-autoapi | autoapi/mappers/python/objects.py | PythonPythonMapper.summary | def summary(self):
"""The summary line of the docstring.
The summary line is the first non-empty line, as-per :pep:`257`.
This will be the empty string if the object does not have a docstring.
:type: str
"""
for line in self.docstring.splitlines():
line = line.strip()
if line:
return line
return "" | python | def summary(self):
"""The summary line of the docstring.
The summary line is the first non-empty line, as-per :pep:`257`.
This will be the empty string if the object does not have a docstring.
:type: str
"""
for line in self.docstring.splitlines():
line = line.strip()
if line:
return line
return "" | [
"def",
"summary",
"(",
"self",
")",
":",
"for",
"line",
"in",
"self",
".",
"docstring",
".",
"splitlines",
"(",
")",
":",
"line",
"=",
"line",
".",
"strip",
"(",
")",
"if",
"line",
":",
"return",
"line",
"return",
"\"\""
] | The summary line of the docstring.
The summary line is the first non-empty line, as-per :pep:`257`.
This will be the empty string if the object does not have a docstring.
:type: str | [
"The",
"summary",
"line",
"of",
"the",
"docstring",
"."
] | 9735f43a8d9ff4620c7bcbd177fd1bb7608052e9 | https://github.com/rtfd/sphinx-autoapi/blob/9735f43a8d9ff4620c7bcbd177fd1bb7608052e9/autoapi/mappers/python/objects.py#L109-L122 | train | 199,213 |
rtfd/sphinx-autoapi | autoapi/mappers/python/astroid_utils.py | resolve_import_alias | def resolve_import_alias(name, import_names):
"""Resolve a name from an aliased import to its original name.
:param name: The potentially aliased name to resolve.
:type name: str
:param import_names: The pairs of original names and aliases
from the import.
:type import_names: iterable(tuple(str, str or None))
:returns: The original name.
:rtype: str
"""
resolved_name = name
for import_name, imported_as in import_names:
if import_name == name:
break
if imported_as == name:
resolved_name = import_name
break
return resolved_name | python | def resolve_import_alias(name, import_names):
"""Resolve a name from an aliased import to its original name.
:param name: The potentially aliased name to resolve.
:type name: str
:param import_names: The pairs of original names and aliases
from the import.
:type import_names: iterable(tuple(str, str or None))
:returns: The original name.
:rtype: str
"""
resolved_name = name
for import_name, imported_as in import_names:
if import_name == name:
break
if imported_as == name:
resolved_name = import_name
break
return resolved_name | [
"def",
"resolve_import_alias",
"(",
"name",
",",
"import_names",
")",
":",
"resolved_name",
"=",
"name",
"for",
"import_name",
",",
"imported_as",
"in",
"import_names",
":",
"if",
"import_name",
"==",
"name",
":",
"break",
"if",
"imported_as",
"==",
"name",
":... | Resolve a name from an aliased import to its original name.
:param name: The potentially aliased name to resolve.
:type name: str
:param import_names: The pairs of original names and aliases
from the import.
:type import_names: iterable(tuple(str, str or None))
:returns: The original name.
:rtype: str | [
"Resolve",
"a",
"name",
"from",
"an",
"aliased",
"import",
"to",
"its",
"original",
"name",
"."
] | 9735f43a8d9ff4620c7bcbd177fd1bb7608052e9 | https://github.com/rtfd/sphinx-autoapi/blob/9735f43a8d9ff4620c7bcbd177fd1bb7608052e9/autoapi/mappers/python/astroid_utils.py#L21-L42 | train | 199,214 |
rtfd/sphinx-autoapi | autoapi/mappers/python/astroid_utils.py | get_full_import_name | def get_full_import_name(import_from, name):
"""Get the full path of a name from a ``from x import y`` statement.
:param import_from: The astroid node to resolve the name of.
:type import_from: astroid.nodes.ImportFrom
:param name:
:type name: str
:returns: The full import path of the name.
:rtype: str
"""
partial_basename = resolve_import_alias(name, import_from.names)
module_name = import_from.modname
if import_from.level:
module = import_from.root()
assert isinstance(module, astroid.nodes.Module)
module_name = module.relative_to_absolute_name(
import_from.modname, level=import_from.level
)
return "{}.{}".format(module_name, partial_basename) | python | def get_full_import_name(import_from, name):
"""Get the full path of a name from a ``from x import y`` statement.
:param import_from: The astroid node to resolve the name of.
:type import_from: astroid.nodes.ImportFrom
:param name:
:type name: str
:returns: The full import path of the name.
:rtype: str
"""
partial_basename = resolve_import_alias(name, import_from.names)
module_name = import_from.modname
if import_from.level:
module = import_from.root()
assert isinstance(module, astroid.nodes.Module)
module_name = module.relative_to_absolute_name(
import_from.modname, level=import_from.level
)
return "{}.{}".format(module_name, partial_basename) | [
"def",
"get_full_import_name",
"(",
"import_from",
",",
"name",
")",
":",
"partial_basename",
"=",
"resolve_import_alias",
"(",
"name",
",",
"import_from",
".",
"names",
")",
"module_name",
"=",
"import_from",
".",
"modname",
"if",
"import_from",
".",
"level",
"... | Get the full path of a name from a ``from x import y`` statement.
:param import_from: The astroid node to resolve the name of.
:type import_from: astroid.nodes.ImportFrom
:param name:
:type name: str
:returns: The full import path of the name.
:rtype: str | [
"Get",
"the",
"full",
"path",
"of",
"a",
"name",
"from",
"a",
"from",
"x",
"import",
"y",
"statement",
"."
] | 9735f43a8d9ff4620c7bcbd177fd1bb7608052e9 | https://github.com/rtfd/sphinx-autoapi/blob/9735f43a8d9ff4620c7bcbd177fd1bb7608052e9/autoapi/mappers/python/astroid_utils.py#L45-L66 | train | 199,215 |
rtfd/sphinx-autoapi | autoapi/mappers/python/astroid_utils.py | get_full_basename | def get_full_basename(node, basename):
"""Resolve a partial base name to the full path.
:param node: The node representing the base name.
:type node: astroid.NodeNG
:param basename: The partial base name to resolve.
:type basename: str
:returns: The fully resolved base name.
:rtype: str
"""
full_basename = basename
top_level_name = re.sub(r"\(.*\)", "", basename).split(".", 1)[0]
lookup_node = node
while not hasattr(lookup_node, "lookup"):
lookup_node = lookup_node.parent
assigns = lookup_node.lookup(top_level_name)[1]
for assignment in assigns:
if isinstance(assignment, astroid.nodes.ImportFrom):
import_name = get_full_import_name(assignment, top_level_name)
full_basename = basename.replace(top_level_name, import_name, 1)
break
elif isinstance(assignment, astroid.nodes.Import):
import_name = resolve_import_alias(top_level_name, assignment.names)
full_basename = basename.replace(top_level_name, import_name, 1)
break
elif isinstance(assignment, astroid.nodes.ClassDef):
full_basename = "{}.{}".format(assignment.root().name, assignment.name)
break
if isinstance(node, astroid.nodes.Call):
full_basename = re.sub(r"\(.*\)", "()", full_basename)
if full_basename.startswith("builtins."):
return full_basename[len("builtins.") :]
if full_basename.startswith("__builtin__."):
return full_basename[len("__builtin__.") :]
return full_basename | python | def get_full_basename(node, basename):
"""Resolve a partial base name to the full path.
:param node: The node representing the base name.
:type node: astroid.NodeNG
:param basename: The partial base name to resolve.
:type basename: str
:returns: The fully resolved base name.
:rtype: str
"""
full_basename = basename
top_level_name = re.sub(r"\(.*\)", "", basename).split(".", 1)[0]
lookup_node = node
while not hasattr(lookup_node, "lookup"):
lookup_node = lookup_node.parent
assigns = lookup_node.lookup(top_level_name)[1]
for assignment in assigns:
if isinstance(assignment, astroid.nodes.ImportFrom):
import_name = get_full_import_name(assignment, top_level_name)
full_basename = basename.replace(top_level_name, import_name, 1)
break
elif isinstance(assignment, astroid.nodes.Import):
import_name = resolve_import_alias(top_level_name, assignment.names)
full_basename = basename.replace(top_level_name, import_name, 1)
break
elif isinstance(assignment, astroid.nodes.ClassDef):
full_basename = "{}.{}".format(assignment.root().name, assignment.name)
break
if isinstance(node, astroid.nodes.Call):
full_basename = re.sub(r"\(.*\)", "()", full_basename)
if full_basename.startswith("builtins."):
return full_basename[len("builtins.") :]
if full_basename.startswith("__builtin__."):
return full_basename[len("__builtin__.") :]
return full_basename | [
"def",
"get_full_basename",
"(",
"node",
",",
"basename",
")",
":",
"full_basename",
"=",
"basename",
"top_level_name",
"=",
"re",
".",
"sub",
"(",
"r\"\\(.*\\)\"",
",",
"\"\"",
",",
"basename",
")",
".",
"split",
"(",
"\".\"",
",",
"1",
")",
"[",
"0",
... | Resolve a partial base name to the full path.
:param node: The node representing the base name.
:type node: astroid.NodeNG
:param basename: The partial base name to resolve.
:type basename: str
:returns: The fully resolved base name.
:rtype: str | [
"Resolve",
"a",
"partial",
"base",
"name",
"to",
"the",
"full",
"path",
"."
] | 9735f43a8d9ff4620c7bcbd177fd1bb7608052e9 | https://github.com/rtfd/sphinx-autoapi/blob/9735f43a8d9ff4620c7bcbd177fd1bb7608052e9/autoapi/mappers/python/astroid_utils.py#L69-L109 | train | 199,216 |
rtfd/sphinx-autoapi | autoapi/mappers/python/astroid_utils.py | get_full_basenames | def get_full_basenames(bases, basenames):
"""Resolve the base nodes and partial names of a class to full names.
:param bases: The astroid node representing something that a class
inherits from.
:type bases: iterable(astroid.NodeNG)
:param basenames: The partial name of something that a class inherits from.
:type basenames: iterable(str)
:returns: The full names.
:rtype: iterable(str)
"""
for base, basename in zip(bases, basenames):
yield get_full_basename(base, basename) | python | def get_full_basenames(bases, basenames):
"""Resolve the base nodes and partial names of a class to full names.
:param bases: The astroid node representing something that a class
inherits from.
:type bases: iterable(astroid.NodeNG)
:param basenames: The partial name of something that a class inherits from.
:type basenames: iterable(str)
:returns: The full names.
:rtype: iterable(str)
"""
for base, basename in zip(bases, basenames):
yield get_full_basename(base, basename) | [
"def",
"get_full_basenames",
"(",
"bases",
",",
"basenames",
")",
":",
"for",
"base",
",",
"basename",
"in",
"zip",
"(",
"bases",
",",
"basenames",
")",
":",
"yield",
"get_full_basename",
"(",
"base",
",",
"basename",
")"
] | Resolve the base nodes and partial names of a class to full names.
:param bases: The astroid node representing something that a class
inherits from.
:type bases: iterable(astroid.NodeNG)
:param basenames: The partial name of something that a class inherits from.
:type basenames: iterable(str)
:returns: The full names.
:rtype: iterable(str) | [
"Resolve",
"the",
"base",
"nodes",
"and",
"partial",
"names",
"of",
"a",
"class",
"to",
"full",
"names",
"."
] | 9735f43a8d9ff4620c7bcbd177fd1bb7608052e9 | https://github.com/rtfd/sphinx-autoapi/blob/9735f43a8d9ff4620c7bcbd177fd1bb7608052e9/autoapi/mappers/python/astroid_utils.py#L112-L125 | train | 199,217 |
rtfd/sphinx-autoapi | autoapi/mappers/python/astroid_utils.py | get_assign_value | def get_assign_value(node):
"""Get the name and value of the assignment of the given node.
Assignments to multiple names are ignored, as per PEP 257.
:param node: The node to get the assignment value from.
:type node: astroid.nodes.Assign or astroid.nodes.AnnAssign
:returns: The name that is assigned to,
and the value assigned to the name (if it can be converted).
:rtype: tuple(str, object or None) or None
"""
try:
targets = node.targets
except AttributeError:
targets = [node.target]
if len(targets) == 1:
target = targets[0]
if isinstance(target, astroid.nodes.AssignName):
name = target.name
elif isinstance(target, astroid.nodes.AssignAttr):
name = target.attrname
else:
return None
return (name, _get_const_values(node.value))
return None | python | def get_assign_value(node):
"""Get the name and value of the assignment of the given node.
Assignments to multiple names are ignored, as per PEP 257.
:param node: The node to get the assignment value from.
:type node: astroid.nodes.Assign or astroid.nodes.AnnAssign
:returns: The name that is assigned to,
and the value assigned to the name (if it can be converted).
:rtype: tuple(str, object or None) or None
"""
try:
targets = node.targets
except AttributeError:
targets = [node.target]
if len(targets) == 1:
target = targets[0]
if isinstance(target, astroid.nodes.AssignName):
name = target.name
elif isinstance(target, astroid.nodes.AssignAttr):
name = target.attrname
else:
return None
return (name, _get_const_values(node.value))
return None | [
"def",
"get_assign_value",
"(",
"node",
")",
":",
"try",
":",
"targets",
"=",
"node",
".",
"targets",
"except",
"AttributeError",
":",
"targets",
"=",
"[",
"node",
".",
"target",
"]",
"if",
"len",
"(",
"targets",
")",
"==",
"1",
":",
"target",
"=",
"... | Get the name and value of the assignment of the given node.
Assignments to multiple names are ignored, as per PEP 257.
:param node: The node to get the assignment value from.
:type node: astroid.nodes.Assign or astroid.nodes.AnnAssign
:returns: The name that is assigned to,
and the value assigned to the name (if it can be converted).
:rtype: tuple(str, object or None) or None | [
"Get",
"the",
"name",
"and",
"value",
"of",
"the",
"assignment",
"of",
"the",
"given",
"node",
"."
] | 9735f43a8d9ff4620c7bcbd177fd1bb7608052e9 | https://github.com/rtfd/sphinx-autoapi/blob/9735f43a8d9ff4620c7bcbd177fd1bb7608052e9/autoapi/mappers/python/astroid_utils.py#L148-L175 | train | 199,218 |
rtfd/sphinx-autoapi | autoapi/mappers/python/astroid_utils.py | get_assign_annotation | def get_assign_annotation(node):
"""Get the type annotation of the assignment of the given node.
:param node: The node to get the annotation for.
:type node: astroid.nodes.Assign or astroid.nodes.AnnAssign
:returns: The type annotation as a string, or None if one does not exist.
:type: str or None
"""
annotation = None
annotation_node = None
try:
annotation_node = node.annotation
except AttributeError:
# Python 2 has no support for type annotations, so use getattr
annotation_node = getattr(node, "type_annotation", None)
if annotation_node:
if isinstance(annotation_node, astroid.nodes.Const):
annotation = node.value
else:
annotation = annotation_node.as_string()
return annotation | python | def get_assign_annotation(node):
"""Get the type annotation of the assignment of the given node.
:param node: The node to get the annotation for.
:type node: astroid.nodes.Assign or astroid.nodes.AnnAssign
:returns: The type annotation as a string, or None if one does not exist.
:type: str or None
"""
annotation = None
annotation_node = None
try:
annotation_node = node.annotation
except AttributeError:
# Python 2 has no support for type annotations, so use getattr
annotation_node = getattr(node, "type_annotation", None)
if annotation_node:
if isinstance(annotation_node, astroid.nodes.Const):
annotation = node.value
else:
annotation = annotation_node.as_string()
return annotation | [
"def",
"get_assign_annotation",
"(",
"node",
")",
":",
"annotation",
"=",
"None",
"annotation_node",
"=",
"None",
"try",
":",
"annotation_node",
"=",
"node",
".",
"annotation",
"except",
"AttributeError",
":",
"# Python 2 has no support for type annotations, so use getatt... | Get the type annotation of the assignment of the given node.
:param node: The node to get the annotation for.
:type node: astroid.nodes.Assign or astroid.nodes.AnnAssign
:returns: The type annotation as a string, or None if one does not exist.
:type: str or None | [
"Get",
"the",
"type",
"annotation",
"of",
"the",
"assignment",
"of",
"the",
"given",
"node",
"."
] | 9735f43a8d9ff4620c7bcbd177fd1bb7608052e9 | https://github.com/rtfd/sphinx-autoapi/blob/9735f43a8d9ff4620c7bcbd177fd1bb7608052e9/autoapi/mappers/python/astroid_utils.py#L178-L202 | train | 199,219 |
rtfd/sphinx-autoapi | autoapi/mappers/python/astroid_utils.py | is_decorated_with_property | def is_decorated_with_property(node):
"""Check if the function is decorated as a property.
:param node: The node to check.
:type node: astroid.nodes.FunctionDef
:returns: True if the function is a property, False otherwise.
:rtype: bool
"""
if not node.decorators:
return False
for decorator in node.decorators.nodes:
if not isinstance(decorator, astroid.Name):
continue
try:
if _is_property_decorator(decorator):
return True
except astroid.InferenceError:
pass
return False | python | def is_decorated_with_property(node):
"""Check if the function is decorated as a property.
:param node: The node to check.
:type node: astroid.nodes.FunctionDef
:returns: True if the function is a property, False otherwise.
:rtype: bool
"""
if not node.decorators:
return False
for decorator in node.decorators.nodes:
if not isinstance(decorator, astroid.Name):
continue
try:
if _is_property_decorator(decorator):
return True
except astroid.InferenceError:
pass
return False | [
"def",
"is_decorated_with_property",
"(",
"node",
")",
":",
"if",
"not",
"node",
".",
"decorators",
":",
"return",
"False",
"for",
"decorator",
"in",
"node",
".",
"decorators",
".",
"nodes",
":",
"if",
"not",
"isinstance",
"(",
"decorator",
",",
"astroid",
... | Check if the function is decorated as a property.
:param node: The node to check.
:type node: astroid.nodes.FunctionDef
:returns: True if the function is a property, False otherwise.
:rtype: bool | [
"Check",
"if",
"the",
"function",
"is",
"decorated",
"as",
"a",
"property",
"."
] | 9735f43a8d9ff4620c7bcbd177fd1bb7608052e9 | https://github.com/rtfd/sphinx-autoapi/blob/9735f43a8d9ff4620c7bcbd177fd1bb7608052e9/autoapi/mappers/python/astroid_utils.py#L205-L227 | train | 199,220 |
rtfd/sphinx-autoapi | autoapi/mappers/python/astroid_utils.py | is_decorated_with_property_setter | def is_decorated_with_property_setter(node):
"""Check if the function is decorated as a property setter.
:param node: The node to check.
:type node: astroid.nodes.FunctionDef
:returns: True if the function is a property setter, False otherwise.
:rtype: bool
"""
if not node.decorators:
return False
for decorator in node.decorators.nodes:
if (
isinstance(decorator, astroid.nodes.Attribute)
and decorator.attrname == "setter"
):
return True
return False | python | def is_decorated_with_property_setter(node):
"""Check if the function is decorated as a property setter.
:param node: The node to check.
:type node: astroid.nodes.FunctionDef
:returns: True if the function is a property setter, False otherwise.
:rtype: bool
"""
if not node.decorators:
return False
for decorator in node.decorators.nodes:
if (
isinstance(decorator, astroid.nodes.Attribute)
and decorator.attrname == "setter"
):
return True
return False | [
"def",
"is_decorated_with_property_setter",
"(",
"node",
")",
":",
"if",
"not",
"node",
".",
"decorators",
":",
"return",
"False",
"for",
"decorator",
"in",
"node",
".",
"decorators",
".",
"nodes",
":",
"if",
"(",
"isinstance",
"(",
"decorator",
",",
"astroi... | Check if the function is decorated as a property setter.
:param node: The node to check.
:type node: astroid.nodes.FunctionDef
:returns: True if the function is a property setter, False otherwise.
:rtype: bool | [
"Check",
"if",
"the",
"function",
"is",
"decorated",
"as",
"a",
"property",
"setter",
"."
] | 9735f43a8d9ff4620c7bcbd177fd1bb7608052e9 | https://github.com/rtfd/sphinx-autoapi/blob/9735f43a8d9ff4620c7bcbd177fd1bb7608052e9/autoapi/mappers/python/astroid_utils.py#L250-L269 | train | 199,221 |
rtfd/sphinx-autoapi | autoapi/mappers/python/astroid_utils.py | is_constructor | def is_constructor(node):
"""Check if the function is a constructor.
:param node: The node to check.
:type node: astroid.nodes.FunctionDef
:returns: True if the function is a contructor, False otherwise.
:rtype: bool
"""
return (
node.parent
and isinstance(node.parent.scope(), astroid.nodes.ClassDef)
and node.name == "__init__"
) | python | def is_constructor(node):
"""Check if the function is a constructor.
:param node: The node to check.
:type node: astroid.nodes.FunctionDef
:returns: True if the function is a contructor, False otherwise.
:rtype: bool
"""
return (
node.parent
and isinstance(node.parent.scope(), astroid.nodes.ClassDef)
and node.name == "__init__"
) | [
"def",
"is_constructor",
"(",
"node",
")",
":",
"return",
"(",
"node",
".",
"parent",
"and",
"isinstance",
"(",
"node",
".",
"parent",
".",
"scope",
"(",
")",
",",
"astroid",
".",
"nodes",
".",
"ClassDef",
")",
"and",
"node",
".",
"name",
"==",
"\"__... | Check if the function is a constructor.
:param node: The node to check.
:type node: astroid.nodes.FunctionDef
:returns: True if the function is a contructor, False otherwise.
:rtype: bool | [
"Check",
"if",
"the",
"function",
"is",
"a",
"constructor",
"."
] | 9735f43a8d9ff4620c7bcbd177fd1bb7608052e9 | https://github.com/rtfd/sphinx-autoapi/blob/9735f43a8d9ff4620c7bcbd177fd1bb7608052e9/autoapi/mappers/python/astroid_utils.py#L272-L285 | train | 199,222 |
rtfd/sphinx-autoapi | autoapi/mappers/python/astroid_utils.py | is_exception | def is_exception(node):
"""Check if a class is an exception.
:param node: The node to check.
:type node: astroid.nodes.ClassDef
:returns: True if the class is an exception, False otherwise.
:rtype: bool
"""
if (
node.name in ("Exception", "BaseException")
and node.root().name == _EXCEPTIONS_MODULE
):
return True
if not hasattr(node, "ancestors"):
return False
return any(is_exception(parent) for parent in node.ancestors(recurs=True)) | python | def is_exception(node):
"""Check if a class is an exception.
:param node: The node to check.
:type node: astroid.nodes.ClassDef
:returns: True if the class is an exception, False otherwise.
:rtype: bool
"""
if (
node.name in ("Exception", "BaseException")
and node.root().name == _EXCEPTIONS_MODULE
):
return True
if not hasattr(node, "ancestors"):
return False
return any(is_exception(parent) for parent in node.ancestors(recurs=True)) | [
"def",
"is_exception",
"(",
"node",
")",
":",
"if",
"(",
"node",
".",
"name",
"in",
"(",
"\"Exception\"",
",",
"\"BaseException\"",
")",
"and",
"node",
".",
"root",
"(",
")",
".",
"name",
"==",
"_EXCEPTIONS_MODULE",
")",
":",
"return",
"True",
"if",
"n... | Check if a class is an exception.
:param node: The node to check.
:type node: astroid.nodes.ClassDef
:returns: True if the class is an exception, False otherwise.
:rtype: bool | [
"Check",
"if",
"a",
"class",
"is",
"an",
"exception",
"."
] | 9735f43a8d9ff4620c7bcbd177fd1bb7608052e9 | https://github.com/rtfd/sphinx-autoapi/blob/9735f43a8d9ff4620c7bcbd177fd1bb7608052e9/autoapi/mappers/python/astroid_utils.py#L288-L306 | train | 199,223 |
rtfd/sphinx-autoapi | autoapi/mappers/python/astroid_utils.py | is_local_import_from | def is_local_import_from(node, package_name):
"""Check if a node is an import from the local package.
:param node: The node to check.
:type node: astroid.node.NodeNG
:param package_name: The name of the local package.
:type package_name: str
:returns: True if the node is an import from the local package,
False otherwise.
:rtype: bool
"""
if not isinstance(node, astroid.ImportFrom):
return False
return (
node.level
or node.modname == package_name
or node.modname.startswith(package_name + ".")
) | python | def is_local_import_from(node, package_name):
"""Check if a node is an import from the local package.
:param node: The node to check.
:type node: astroid.node.NodeNG
:param package_name: The name of the local package.
:type package_name: str
:returns: True if the node is an import from the local package,
False otherwise.
:rtype: bool
"""
if not isinstance(node, astroid.ImportFrom):
return False
return (
node.level
or node.modname == package_name
or node.modname.startswith(package_name + ".")
) | [
"def",
"is_local_import_from",
"(",
"node",
",",
"package_name",
")",
":",
"if",
"not",
"isinstance",
"(",
"node",
",",
"astroid",
".",
"ImportFrom",
")",
":",
"return",
"False",
"return",
"(",
"node",
".",
"level",
"or",
"node",
".",
"modname",
"==",
"p... | Check if a node is an import from the local package.
:param node: The node to check.
:type node: astroid.node.NodeNG
:param package_name: The name of the local package.
:type package_name: str
:returns: True if the node is an import from the local package,
False otherwise.
:rtype: bool | [
"Check",
"if",
"a",
"node",
"is",
"an",
"import",
"from",
"the",
"local",
"package",
"."
] | 9735f43a8d9ff4620c7bcbd177fd1bb7608052e9 | https://github.com/rtfd/sphinx-autoapi/blob/9735f43a8d9ff4620c7bcbd177fd1bb7608052e9/autoapi/mappers/python/astroid_utils.py#L309-L329 | train | 199,224 |
rtfd/sphinx-autoapi | autoapi/extension.py | run_autoapi | def run_autoapi(app):
"""
Load AutoAPI data from the filesystem.
"""
if not app.config.autoapi_dirs:
raise ExtensionError("You must configure an autoapi_dirs setting")
# Make sure the paths are full
normalized_dirs = []
autoapi_dirs = app.config.autoapi_dirs
if isinstance(autoapi_dirs, str):
autoapi_dirs = [autoapi_dirs]
for path in autoapi_dirs:
if os.path.isabs(path):
normalized_dirs.append(path)
else:
normalized_dirs.append(os.path.normpath(os.path.join(app.confdir, path)))
for _dir in normalized_dirs:
if not os.path.exists(_dir):
raise ExtensionError(
"AutoAPI Directory `{dir}` not found. "
"Please check your `autoapi_dirs` setting.".format(dir=_dir)
)
normalized_root = os.path.normpath(
os.path.join(app.confdir, app.config.autoapi_root)
)
url_root = os.path.join("/", app.config.autoapi_root)
sphinx_mapper = default_backend_mapping[app.config.autoapi_type]
sphinx_mapper_obj = sphinx_mapper(
app, template_dir=app.config.autoapi_template_dir, url_root=url_root
)
app.env.autoapi_mapper = sphinx_mapper_obj
if app.config.autoapi_file_patterns:
file_patterns = app.config.autoapi_file_patterns
else:
file_patterns = default_file_mapping.get(app.config.autoapi_type, [])
if app.config.autoapi_ignore:
ignore_patterns = app.config.autoapi_ignore
else:
ignore_patterns = default_ignore_patterns.get(app.config.autoapi_type, [])
if ".rst" in app.config.source_suffix:
out_suffix = ".rst"
elif ".txt" in app.config.source_suffix:
out_suffix = ".txt"
else:
# Fallback to first suffix listed
out_suffix = app.config.source_suffix[0]
# Actual meat of the run.
LOGGER.info(bold("[AutoAPI] ") + darkgreen("Loading Data"))
sphinx_mapper_obj.load(
patterns=file_patterns, dirs=normalized_dirs, ignore=ignore_patterns
)
LOGGER.info(bold("[AutoAPI] ") + darkgreen("Mapping Data"))
sphinx_mapper_obj.map(options=app.config.autoapi_options)
if app.config.autoapi_generate_api_docs:
LOGGER.info(bold("[AutoAPI] ") + darkgreen("Rendering Data"))
sphinx_mapper_obj.output_rst(root=normalized_root, source_suffix=out_suffix) | python | def run_autoapi(app):
"""
Load AutoAPI data from the filesystem.
"""
if not app.config.autoapi_dirs:
raise ExtensionError("You must configure an autoapi_dirs setting")
# Make sure the paths are full
normalized_dirs = []
autoapi_dirs = app.config.autoapi_dirs
if isinstance(autoapi_dirs, str):
autoapi_dirs = [autoapi_dirs]
for path in autoapi_dirs:
if os.path.isabs(path):
normalized_dirs.append(path)
else:
normalized_dirs.append(os.path.normpath(os.path.join(app.confdir, path)))
for _dir in normalized_dirs:
if not os.path.exists(_dir):
raise ExtensionError(
"AutoAPI Directory `{dir}` not found. "
"Please check your `autoapi_dirs` setting.".format(dir=_dir)
)
normalized_root = os.path.normpath(
os.path.join(app.confdir, app.config.autoapi_root)
)
url_root = os.path.join("/", app.config.autoapi_root)
sphinx_mapper = default_backend_mapping[app.config.autoapi_type]
sphinx_mapper_obj = sphinx_mapper(
app, template_dir=app.config.autoapi_template_dir, url_root=url_root
)
app.env.autoapi_mapper = sphinx_mapper_obj
if app.config.autoapi_file_patterns:
file_patterns = app.config.autoapi_file_patterns
else:
file_patterns = default_file_mapping.get(app.config.autoapi_type, [])
if app.config.autoapi_ignore:
ignore_patterns = app.config.autoapi_ignore
else:
ignore_patterns = default_ignore_patterns.get(app.config.autoapi_type, [])
if ".rst" in app.config.source_suffix:
out_suffix = ".rst"
elif ".txt" in app.config.source_suffix:
out_suffix = ".txt"
else:
# Fallback to first suffix listed
out_suffix = app.config.source_suffix[0]
# Actual meat of the run.
LOGGER.info(bold("[AutoAPI] ") + darkgreen("Loading Data"))
sphinx_mapper_obj.load(
patterns=file_patterns, dirs=normalized_dirs, ignore=ignore_patterns
)
LOGGER.info(bold("[AutoAPI] ") + darkgreen("Mapping Data"))
sphinx_mapper_obj.map(options=app.config.autoapi_options)
if app.config.autoapi_generate_api_docs:
LOGGER.info(bold("[AutoAPI] ") + darkgreen("Rendering Data"))
sphinx_mapper_obj.output_rst(root=normalized_root, source_suffix=out_suffix) | [
"def",
"run_autoapi",
"(",
"app",
")",
":",
"if",
"not",
"app",
".",
"config",
".",
"autoapi_dirs",
":",
"raise",
"ExtensionError",
"(",
"\"You must configure an autoapi_dirs setting\"",
")",
"# Make sure the paths are full",
"normalized_dirs",
"=",
"[",
"]",
"autoapi... | Load AutoAPI data from the filesystem. | [
"Load",
"AutoAPI",
"data",
"from",
"the",
"filesystem",
"."
] | 9735f43a8d9ff4620c7bcbd177fd1bb7608052e9 | https://github.com/rtfd/sphinx-autoapi/blob/9735f43a8d9ff4620c7bcbd177fd1bb7608052e9/autoapi/extension.py#L39-L105 | train | 199,225 |
rtfd/sphinx-autoapi | autoapi/extension.py | doctree_read | def doctree_read(app, doctree):
"""
Inject AutoAPI into the TOC Tree dynamically.
"""
if app.env.docname == "index":
all_docs = set()
insert = True
nodes = doctree.traverse(toctree)
toc_entry = "%s/index" % app.config.autoapi_root
add_entry = (
nodes
and app.config.autoapi_generate_api_docs
and app.config.autoapi_add_toctree_entry
)
if not add_entry:
return
# Capture all existing toctree entries
for node in nodes:
for entry in node["entries"]:
all_docs.add(entry[1])
# Don't insert autoapi it's already present
for doc in all_docs:
if doc.find(app.config.autoapi_root) != -1:
insert = False
if insert and app.config.autoapi_add_toctree_entry:
# Insert AutoAPI index
nodes[-1]["entries"].append((None, u"%s/index" % app.config.autoapi_root))
nodes[-1]["includefiles"].append(u"%s/index" % app.config.autoapi_root)
message_prefix = bold("[AutoAPI] ")
message = darkgreen(
"Adding AutoAPI TOCTree [{0}] to index.rst".format(toc_entry)
)
LOGGER.info(message_prefix + message) | python | def doctree_read(app, doctree):
"""
Inject AutoAPI into the TOC Tree dynamically.
"""
if app.env.docname == "index":
all_docs = set()
insert = True
nodes = doctree.traverse(toctree)
toc_entry = "%s/index" % app.config.autoapi_root
add_entry = (
nodes
and app.config.autoapi_generate_api_docs
and app.config.autoapi_add_toctree_entry
)
if not add_entry:
return
# Capture all existing toctree entries
for node in nodes:
for entry in node["entries"]:
all_docs.add(entry[1])
# Don't insert autoapi it's already present
for doc in all_docs:
if doc.find(app.config.autoapi_root) != -1:
insert = False
if insert and app.config.autoapi_add_toctree_entry:
# Insert AutoAPI index
nodes[-1]["entries"].append((None, u"%s/index" % app.config.autoapi_root))
nodes[-1]["includefiles"].append(u"%s/index" % app.config.autoapi_root)
message_prefix = bold("[AutoAPI] ")
message = darkgreen(
"Adding AutoAPI TOCTree [{0}] to index.rst".format(toc_entry)
)
LOGGER.info(message_prefix + message) | [
"def",
"doctree_read",
"(",
"app",
",",
"doctree",
")",
":",
"if",
"app",
".",
"env",
".",
"docname",
"==",
"\"index\"",
":",
"all_docs",
"=",
"set",
"(",
")",
"insert",
"=",
"True",
"nodes",
"=",
"doctree",
".",
"traverse",
"(",
"toctree",
")",
"toc... | Inject AutoAPI into the TOC Tree dynamically. | [
"Inject",
"AutoAPI",
"into",
"the",
"TOC",
"Tree",
"dynamically",
"."
] | 9735f43a8d9ff4620c7bcbd177fd1bb7608052e9 | https://github.com/rtfd/sphinx-autoapi/blob/9735f43a8d9ff4620c7bcbd177fd1bb7608052e9/autoapi/extension.py#L122-L154 | train | 199,226 |
rtfd/sphinx-autoapi | autoapi/mappers/python/mapper.py | _expand_wildcard_placeholder | def _expand_wildcard_placeholder(original_module, originals_map, placeholder):
"""Expand a wildcard placeholder to a sequence of named placeholders.
:param original_module: The data dictionary of the module
that the placeholder is imported from.
:type original_module: dict
:param originals_map: A map of the names of children under the module
to their data dictionaries.
:type originals_map: dict(str, dict)
:param placeholder: The wildcard placeholder to expand.
:type placeholder: dict
:returns: The placeholders that the wildcard placeholder represents.
:rtype: list(dict)
"""
originals = originals_map.values()
if original_module["all"] is not None:
originals = []
for name in original_module["all"]:
if name == "__all__":
continue
if name not in originals_map:
msg = "Invalid __all__ entry {0} in {1}".format(
name, original_module["name"]
)
LOGGER.warning(msg)
continue
originals.append(originals_map[name])
placeholders = []
for original in originals:
new_full_name = placeholder["full_name"].replace("*", original["name"])
new_original_path = placeholder["original_path"].replace("*", original["name"])
if "original_path" in original:
new_original_path = original["original_path"]
new_placeholder = dict(
placeholder,
name=original["name"],
full_name=new_full_name,
original_path=new_original_path,
)
placeholders.append(new_placeholder)
return placeholders | python | def _expand_wildcard_placeholder(original_module, originals_map, placeholder):
"""Expand a wildcard placeholder to a sequence of named placeholders.
:param original_module: The data dictionary of the module
that the placeholder is imported from.
:type original_module: dict
:param originals_map: A map of the names of children under the module
to their data dictionaries.
:type originals_map: dict(str, dict)
:param placeholder: The wildcard placeholder to expand.
:type placeholder: dict
:returns: The placeholders that the wildcard placeholder represents.
:rtype: list(dict)
"""
originals = originals_map.values()
if original_module["all"] is not None:
originals = []
for name in original_module["all"]:
if name == "__all__":
continue
if name not in originals_map:
msg = "Invalid __all__ entry {0} in {1}".format(
name, original_module["name"]
)
LOGGER.warning(msg)
continue
originals.append(originals_map[name])
placeholders = []
for original in originals:
new_full_name = placeholder["full_name"].replace("*", original["name"])
new_original_path = placeholder["original_path"].replace("*", original["name"])
if "original_path" in original:
new_original_path = original["original_path"]
new_placeholder = dict(
placeholder,
name=original["name"],
full_name=new_full_name,
original_path=new_original_path,
)
placeholders.append(new_placeholder)
return placeholders | [
"def",
"_expand_wildcard_placeholder",
"(",
"original_module",
",",
"originals_map",
",",
"placeholder",
")",
":",
"originals",
"=",
"originals_map",
".",
"values",
"(",
")",
"if",
"original_module",
"[",
"\"all\"",
"]",
"is",
"not",
"None",
":",
"originals",
"=... | Expand a wildcard placeholder to a sequence of named placeholders.
:param original_module: The data dictionary of the module
that the placeholder is imported from.
:type original_module: dict
:param originals_map: A map of the names of children under the module
to their data dictionaries.
:type originals_map: dict(str, dict)
:param placeholder: The wildcard placeholder to expand.
:type placeholder: dict
:returns: The placeholders that the wildcard placeholder represents.
:rtype: list(dict) | [
"Expand",
"a",
"wildcard",
"placeholder",
"to",
"a",
"sequence",
"of",
"named",
"placeholders",
"."
] | 9735f43a8d9ff4620c7bcbd177fd1bb7608052e9 | https://github.com/rtfd/sphinx-autoapi/blob/9735f43a8d9ff4620c7bcbd177fd1bb7608052e9/autoapi/mappers/python/mapper.py#L24-L69 | train | 199,227 |
rtfd/sphinx-autoapi | autoapi/mappers/python/mapper.py | _resolve_module_placeholders | def _resolve_module_placeholders(modules, module_name, visit_path, resolved):
"""Resolve all placeholder children under a module.
:param modules: A mapping of module names to their data dictionary.
Placeholders are resolved in place.
:type modules: dict(str, dict)
:param module_name: The name of the module to resolve.
:type module_name: str
:param visit_path: An ordered set of visited module names.
:type visited: collections.OrderedDict
:param resolved: A set of already resolved module names.
:type resolved: set(str)
"""
if module_name in resolved:
return
visit_path[module_name] = True
module, children = modules[module_name]
for child in list(children.values()):
if child["type"] != "placeholder":
continue
if child["original_path"] in modules:
module["children"].remove(child)
children.pop(child["name"])
continue
imported_from, original_name = child["original_path"].rsplit(".", 1)
if imported_from in visit_path:
msg = "Cannot resolve cyclic import: {0}, {1}".format(
", ".join(visit_path), imported_from
)
LOGGER.warning(msg)
module["children"].remove(child)
children.pop(child["name"])
continue
if imported_from not in modules:
msg = "Cannot resolve import of unknown module {0} in {1}".format(
imported_from, module_name
)
LOGGER.warning(msg)
module["children"].remove(child)
children.pop(child["name"])
continue
_resolve_module_placeholders(modules, imported_from, visit_path, resolved)
if original_name == "*":
original_module, originals_map = modules[imported_from]
# Replace the wildcard placeholder
# with a list of named placeholders.
new_placeholders = _expand_wildcard_placeholder(
original_module, originals_map, child
)
child_index = module["children"].index(child)
module["children"][child_index : child_index + 1] = new_placeholders
children.pop(child["name"])
for new_placeholder in new_placeholders:
if new_placeholder["name"] not in children:
children[new_placeholder["name"]] = new_placeholder
original = originals_map[new_placeholder["name"]]
_resolve_placeholder(new_placeholder, original)
elif original_name not in modules[imported_from][1]:
msg = "Cannot resolve import of {0} in {1}".format(
child["original_path"], module_name
)
LOGGER.warning(msg)
module["children"].remove(child)
children.pop(child["name"])
continue
else:
original = modules[imported_from][1][original_name]
_resolve_placeholder(child, original)
del visit_path[module_name]
resolved.add(module_name) | python | def _resolve_module_placeholders(modules, module_name, visit_path, resolved):
"""Resolve all placeholder children under a module.
:param modules: A mapping of module names to their data dictionary.
Placeholders are resolved in place.
:type modules: dict(str, dict)
:param module_name: The name of the module to resolve.
:type module_name: str
:param visit_path: An ordered set of visited module names.
:type visited: collections.OrderedDict
:param resolved: A set of already resolved module names.
:type resolved: set(str)
"""
if module_name in resolved:
return
visit_path[module_name] = True
module, children = modules[module_name]
for child in list(children.values()):
if child["type"] != "placeholder":
continue
if child["original_path"] in modules:
module["children"].remove(child)
children.pop(child["name"])
continue
imported_from, original_name = child["original_path"].rsplit(".", 1)
if imported_from in visit_path:
msg = "Cannot resolve cyclic import: {0}, {1}".format(
", ".join(visit_path), imported_from
)
LOGGER.warning(msg)
module["children"].remove(child)
children.pop(child["name"])
continue
if imported_from not in modules:
msg = "Cannot resolve import of unknown module {0} in {1}".format(
imported_from, module_name
)
LOGGER.warning(msg)
module["children"].remove(child)
children.pop(child["name"])
continue
_resolve_module_placeholders(modules, imported_from, visit_path, resolved)
if original_name == "*":
original_module, originals_map = modules[imported_from]
# Replace the wildcard placeholder
# with a list of named placeholders.
new_placeholders = _expand_wildcard_placeholder(
original_module, originals_map, child
)
child_index = module["children"].index(child)
module["children"][child_index : child_index + 1] = new_placeholders
children.pop(child["name"])
for new_placeholder in new_placeholders:
if new_placeholder["name"] not in children:
children[new_placeholder["name"]] = new_placeholder
original = originals_map[new_placeholder["name"]]
_resolve_placeholder(new_placeholder, original)
elif original_name not in modules[imported_from][1]:
msg = "Cannot resolve import of {0} in {1}".format(
child["original_path"], module_name
)
LOGGER.warning(msg)
module["children"].remove(child)
children.pop(child["name"])
continue
else:
original = modules[imported_from][1][original_name]
_resolve_placeholder(child, original)
del visit_path[module_name]
resolved.add(module_name) | [
"def",
"_resolve_module_placeholders",
"(",
"modules",
",",
"module_name",
",",
"visit_path",
",",
"resolved",
")",
":",
"if",
"module_name",
"in",
"resolved",
":",
"return",
"visit_path",
"[",
"module_name",
"]",
"=",
"True",
"module",
",",
"children",
"=",
"... | Resolve all placeholder children under a module.
:param modules: A mapping of module names to their data dictionary.
Placeholders are resolved in place.
:type modules: dict(str, dict)
:param module_name: The name of the module to resolve.
:type module_name: str
:param visit_path: An ordered set of visited module names.
:type visited: collections.OrderedDict
:param resolved: A set of already resolved module names.
:type resolved: set(str) | [
"Resolve",
"all",
"placeholder",
"children",
"under",
"a",
"module",
"."
] | 9735f43a8d9ff4620c7bcbd177fd1bb7608052e9 | https://github.com/rtfd/sphinx-autoapi/blob/9735f43a8d9ff4620c7bcbd177fd1bb7608052e9/autoapi/mappers/python/mapper.py#L72-L151 | train | 199,228 |
rtfd/sphinx-autoapi | autoapi/mappers/python/mapper.py | _resolve_placeholder | def _resolve_placeholder(placeholder, original):
"""Resolve a placeholder to the given original object.
:param placeholder: The placeholder to resolve, in place.
:type placeholder: dict
:param original: The object that the placeholder represents.
:type original: dict
"""
new = copy.deepcopy(original)
# The name remains the same.
new["name"] = placeholder["name"]
new["full_name"] = placeholder["full_name"]
# Record where the placeholder originally came from.
new["original_path"] = original["full_name"]
# The source lines for this placeholder do not exist in this file.
# The keys might not exist if original is a resolved placeholder.
new.pop("from_line_no", None)
new.pop("to_line_no", None)
# Resolve the children
stack = list(new.get("children", ()))
while stack:
child = stack.pop()
# Relocate the child to the new location
assert child["full_name"].startswith(original["full_name"])
suffix = child["full_name"][len(original["full_name"]) :]
child["full_name"] = new["full_name"] + suffix
# The source lines for this placeholder do not exist in this file.
# The keys might not exist if original is a resolved placeholder.
child.pop("from_line_no", None)
child.pop("to_line_no", None)
# Resolve the remaining children
stack.extend(child.get("children", ()))
placeholder.clear()
placeholder.update(new) | python | def _resolve_placeholder(placeholder, original):
"""Resolve a placeholder to the given original object.
:param placeholder: The placeholder to resolve, in place.
:type placeholder: dict
:param original: The object that the placeholder represents.
:type original: dict
"""
new = copy.deepcopy(original)
# The name remains the same.
new["name"] = placeholder["name"]
new["full_name"] = placeholder["full_name"]
# Record where the placeholder originally came from.
new["original_path"] = original["full_name"]
# The source lines for this placeholder do not exist in this file.
# The keys might not exist if original is a resolved placeholder.
new.pop("from_line_no", None)
new.pop("to_line_no", None)
# Resolve the children
stack = list(new.get("children", ()))
while stack:
child = stack.pop()
# Relocate the child to the new location
assert child["full_name"].startswith(original["full_name"])
suffix = child["full_name"][len(original["full_name"]) :]
child["full_name"] = new["full_name"] + suffix
# The source lines for this placeholder do not exist in this file.
# The keys might not exist if original is a resolved placeholder.
child.pop("from_line_no", None)
child.pop("to_line_no", None)
# Resolve the remaining children
stack.extend(child.get("children", ()))
placeholder.clear()
placeholder.update(new) | [
"def",
"_resolve_placeholder",
"(",
"placeholder",
",",
"original",
")",
":",
"new",
"=",
"copy",
".",
"deepcopy",
"(",
"original",
")",
"# The name remains the same.",
"new",
"[",
"\"name\"",
"]",
"=",
"placeholder",
"[",
"\"name\"",
"]",
"new",
"[",
"\"full_... | Resolve a placeholder to the given original object.
:param placeholder: The placeholder to resolve, in place.
:type placeholder: dict
:param original: The object that the placeholder represents.
:type original: dict | [
"Resolve",
"a",
"placeholder",
"to",
"the",
"given",
"original",
"object",
"."
] | 9735f43a8d9ff4620c7bcbd177fd1bb7608052e9 | https://github.com/rtfd/sphinx-autoapi/blob/9735f43a8d9ff4620c7bcbd177fd1bb7608052e9/autoapi/mappers/python/mapper.py#L154-L189 | train | 199,229 |
rtfd/sphinx-autoapi | autoapi/mappers/python/mapper.py | PythonSphinxMapper.load | def load(self, patterns, dirs, ignore=None):
"""Load objects from the filesystem into the ``paths`` dictionary
Also include an attribute on the object, ``relative_path`` which is the
shortened, relative path the package/module
"""
for dir_ in dirs:
dir_root = dir_
if os.path.exists(os.path.join(dir_, "__init__.py")):
dir_root = os.path.abspath(os.path.join(dir_, os.pardir))
for path in self.find_files(patterns=patterns, dirs=[dir_], ignore=ignore):
data = self.read_file(path=path)
if data:
data["relative_path"] = os.path.relpath(path, dir_root)
self.paths[path] = data | python | def load(self, patterns, dirs, ignore=None):
"""Load objects from the filesystem into the ``paths`` dictionary
Also include an attribute on the object, ``relative_path`` which is the
shortened, relative path the package/module
"""
for dir_ in dirs:
dir_root = dir_
if os.path.exists(os.path.join(dir_, "__init__.py")):
dir_root = os.path.abspath(os.path.join(dir_, os.pardir))
for path in self.find_files(patterns=patterns, dirs=[dir_], ignore=ignore):
data = self.read_file(path=path)
if data:
data["relative_path"] = os.path.relpath(path, dir_root)
self.paths[path] = data | [
"def",
"load",
"(",
"self",
",",
"patterns",
",",
"dirs",
",",
"ignore",
"=",
"None",
")",
":",
"for",
"dir_",
"in",
"dirs",
":",
"dir_root",
"=",
"dir_",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"os",
".",
"path",
".",
"join",
"(",
"dir_",
... | Load objects from the filesystem into the ``paths`` dictionary
Also include an attribute on the object, ``relative_path`` which is the
shortened, relative path the package/module | [
"Load",
"objects",
"from",
"the",
"filesystem",
"into",
"the",
"paths",
"dictionary"
] | 9735f43a8d9ff4620c7bcbd177fd1bb7608052e9 | https://github.com/rtfd/sphinx-autoapi/blob/9735f43a8d9ff4620c7bcbd177fd1bb7608052e9/autoapi/mappers/python/mapper.py#L201-L216 | train | 199,230 |
rtfd/sphinx-autoapi | autoapi/mappers/python/mapper.py | PythonSphinxMapper._resolve_placeholders | def _resolve_placeholders(self):
"""Resolve objects that have been imported from elsewhere."""
modules = {}
for module in self.paths.values():
children = {child["name"]: child for child in module["children"]}
modules[module["name"]] = (module, children)
resolved = set()
for module_name in modules:
visit_path = collections.OrderedDict()
_resolve_module_placeholders(modules, module_name, visit_path, resolved) | python | def _resolve_placeholders(self):
"""Resolve objects that have been imported from elsewhere."""
modules = {}
for module in self.paths.values():
children = {child["name"]: child for child in module["children"]}
modules[module["name"]] = (module, children)
resolved = set()
for module_name in modules:
visit_path = collections.OrderedDict()
_resolve_module_placeholders(modules, module_name, visit_path, resolved) | [
"def",
"_resolve_placeholders",
"(",
"self",
")",
":",
"modules",
"=",
"{",
"}",
"for",
"module",
"in",
"self",
".",
"paths",
".",
"values",
"(",
")",
":",
"children",
"=",
"{",
"child",
"[",
"\"name\"",
"]",
":",
"child",
"for",
"child",
"in",
"modu... | Resolve objects that have been imported from elsewhere. | [
"Resolve",
"objects",
"that",
"have",
"been",
"imported",
"from",
"elsewhere",
"."
] | 9735f43a8d9ff4620c7bcbd177fd1bb7608052e9 | https://github.com/rtfd/sphinx-autoapi/blob/9735f43a8d9ff4620c7bcbd177fd1bb7608052e9/autoapi/mappers/python/mapper.py#L230-L240 | train | 199,231 |
rtfd/sphinx-autoapi | autoapi/mappers/python/mapper.py | PythonSphinxMapper.create_class | def create_class(self, data, options=None, **kwargs):
"""Create a class from the passed in data
:param data: dictionary data of parser output
"""
obj_map = dict(
(cls.type, cls)
for cls in [
PythonClass,
PythonFunction,
PythonModule,
PythonMethod,
PythonPackage,
PythonAttribute,
PythonData,
PythonException,
]
)
try:
cls = obj_map[data["type"]]
except KeyError:
LOGGER.warning("Unknown type: %s" % data["type"])
else:
obj = cls(
data,
class_content=self.app.config.autoapi_python_class_content,
options=self.app.config.autoapi_options,
jinja_env=self.jinja_env,
url_root=self.url_root,
**kwargs
)
lines = sphinx.util.docstrings.prepare_docstring(obj.docstring)
if lines and "autodoc-process-docstring" in self.app.events.events:
self.app.emit(
"autodoc-process-docstring",
cls.type,
obj.name,
None, # object
None, # options
lines,
)
obj.docstring = "\n".join(lines)
for child_data in data.get("children", []):
for child_obj in self.create_class(
child_data, options=options, **kwargs
):
obj.children.append(child_obj)
yield obj | python | def create_class(self, data, options=None, **kwargs):
"""Create a class from the passed in data
:param data: dictionary data of parser output
"""
obj_map = dict(
(cls.type, cls)
for cls in [
PythonClass,
PythonFunction,
PythonModule,
PythonMethod,
PythonPackage,
PythonAttribute,
PythonData,
PythonException,
]
)
try:
cls = obj_map[data["type"]]
except KeyError:
LOGGER.warning("Unknown type: %s" % data["type"])
else:
obj = cls(
data,
class_content=self.app.config.autoapi_python_class_content,
options=self.app.config.autoapi_options,
jinja_env=self.jinja_env,
url_root=self.url_root,
**kwargs
)
lines = sphinx.util.docstrings.prepare_docstring(obj.docstring)
if lines and "autodoc-process-docstring" in self.app.events.events:
self.app.emit(
"autodoc-process-docstring",
cls.type,
obj.name,
None, # object
None, # options
lines,
)
obj.docstring = "\n".join(lines)
for child_data in data.get("children", []):
for child_obj in self.create_class(
child_data, options=options, **kwargs
):
obj.children.append(child_obj)
yield obj | [
"def",
"create_class",
"(",
"self",
",",
"data",
",",
"options",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"obj_map",
"=",
"dict",
"(",
"(",
"cls",
".",
"type",
",",
"cls",
")",
"for",
"cls",
"in",
"[",
"PythonClass",
",",
"PythonFunction",
"... | Create a class from the passed in data
:param data: dictionary data of parser output | [
"Create",
"a",
"class",
"from",
"the",
"passed",
"in",
"data"
] | 9735f43a8d9ff4620c7bcbd177fd1bb7608052e9 | https://github.com/rtfd/sphinx-autoapi/blob/9735f43a8d9ff4620c7bcbd177fd1bb7608052e9/autoapi/mappers/python/mapper.py#L259-L308 | train | 199,232 |
rtfd/sphinx-autoapi | autoapi/toctree.py | _build_toc_node | def _build_toc_node(docname, anchor="anchor", text="test text", bullet=False):
"""
Create the node structure that Sphinx expects for TOC Tree entries.
The ``bullet`` argument wraps it in a ``nodes.bullet_list``,
which is how you nest TOC Tree entries.
"""
reference = nodes.reference(
"",
"",
internal=True,
refuri=docname,
anchorname="#" + anchor,
*[nodes.Text(text, text)]
)
para = addnodes.compact_paragraph("", "", reference)
ret_list = nodes.list_item("", para)
return nodes.bullet_list("", ret_list) if bullet else ret_list | python | def _build_toc_node(docname, anchor="anchor", text="test text", bullet=False):
"""
Create the node structure that Sphinx expects for TOC Tree entries.
The ``bullet`` argument wraps it in a ``nodes.bullet_list``,
which is how you nest TOC Tree entries.
"""
reference = nodes.reference(
"",
"",
internal=True,
refuri=docname,
anchorname="#" + anchor,
*[nodes.Text(text, text)]
)
para = addnodes.compact_paragraph("", "", reference)
ret_list = nodes.list_item("", para)
return nodes.bullet_list("", ret_list) if bullet else ret_list | [
"def",
"_build_toc_node",
"(",
"docname",
",",
"anchor",
"=",
"\"anchor\"",
",",
"text",
"=",
"\"test text\"",
",",
"bullet",
"=",
"False",
")",
":",
"reference",
"=",
"nodes",
".",
"reference",
"(",
"\"\"",
",",
"\"\"",
",",
"internal",
"=",
"True",
","... | Create the node structure that Sphinx expects for TOC Tree entries.
The ``bullet`` argument wraps it in a ``nodes.bullet_list``,
which is how you nest TOC Tree entries. | [
"Create",
"the",
"node",
"structure",
"that",
"Sphinx",
"expects",
"for",
"TOC",
"Tree",
"entries",
"."
] | 9735f43a8d9ff4620c7bcbd177fd1bb7608052e9 | https://github.com/rtfd/sphinx-autoapi/blob/9735f43a8d9ff4620c7bcbd177fd1bb7608052e9/autoapi/toctree.py#L16-L33 | train | 199,233 |
rtfd/sphinx-autoapi | autoapi/toctree.py | _traverse_parent | def _traverse_parent(node, objtypes):
"""
Traverse up the node's parents until you hit the ``objtypes`` referenced.
Can either be a single type,
or a tuple of types.
"""
curr_node = node.parent
while curr_node is not None:
if isinstance(curr_node, objtypes):
return curr_node
curr_node = curr_node.parent
return None | python | def _traverse_parent(node, objtypes):
"""
Traverse up the node's parents until you hit the ``objtypes`` referenced.
Can either be a single type,
or a tuple of types.
"""
curr_node = node.parent
while curr_node is not None:
if isinstance(curr_node, objtypes):
return curr_node
curr_node = curr_node.parent
return None | [
"def",
"_traverse_parent",
"(",
"node",
",",
"objtypes",
")",
":",
"curr_node",
"=",
"node",
".",
"parent",
"while",
"curr_node",
"is",
"not",
"None",
":",
"if",
"isinstance",
"(",
"curr_node",
",",
"objtypes",
")",
":",
"return",
"curr_node",
"curr_node",
... | Traverse up the node's parents until you hit the ``objtypes`` referenced.
Can either be a single type,
or a tuple of types. | [
"Traverse",
"up",
"the",
"node",
"s",
"parents",
"until",
"you",
"hit",
"the",
"objtypes",
"referenced",
"."
] | 9735f43a8d9ff4620c7bcbd177fd1bb7608052e9 | https://github.com/rtfd/sphinx-autoapi/blob/9735f43a8d9ff4620c7bcbd177fd1bb7608052e9/autoapi/toctree.py#L36-L48 | train | 199,234 |
rtfd/sphinx-autoapi | autoapi/toctree.py | _find_toc_node | def _find_toc_node(toc, ref_id, objtype):
"""
Find the actual TOC node for a ref_id.
Depends on the object type:
* Section - First section (refuri) or 2nd+ level section (anchorname)
* Desc - Just use the anchor name
"""
for check_node in toc.traverse(nodes.reference):
if objtype == nodes.section and (
check_node.attributes["refuri"] == ref_id
or check_node.attributes["anchorname"] == "#" + ref_id
):
return check_node
if (
objtype == addnodes.desc
and check_node.attributes["anchorname"] == "#" + ref_id
):
return check_node
return None | python | def _find_toc_node(toc, ref_id, objtype):
"""
Find the actual TOC node for a ref_id.
Depends on the object type:
* Section - First section (refuri) or 2nd+ level section (anchorname)
* Desc - Just use the anchor name
"""
for check_node in toc.traverse(nodes.reference):
if objtype == nodes.section and (
check_node.attributes["refuri"] == ref_id
or check_node.attributes["anchorname"] == "#" + ref_id
):
return check_node
if (
objtype == addnodes.desc
and check_node.attributes["anchorname"] == "#" + ref_id
):
return check_node
return None | [
"def",
"_find_toc_node",
"(",
"toc",
",",
"ref_id",
",",
"objtype",
")",
":",
"for",
"check_node",
"in",
"toc",
".",
"traverse",
"(",
"nodes",
".",
"reference",
")",
":",
"if",
"objtype",
"==",
"nodes",
".",
"section",
"and",
"(",
"check_node",
".",
"a... | Find the actual TOC node for a ref_id.
Depends on the object type:
* Section - First section (refuri) or 2nd+ level section (anchorname)
* Desc - Just use the anchor name | [
"Find",
"the",
"actual",
"TOC",
"node",
"for",
"a",
"ref_id",
"."
] | 9735f43a8d9ff4620c7bcbd177fd1bb7608052e9 | https://github.com/rtfd/sphinx-autoapi/blob/9735f43a8d9ff4620c7bcbd177fd1bb7608052e9/autoapi/toctree.py#L51-L70 | train | 199,235 |
rtfd/sphinx-autoapi | autoapi/toctree.py | _get_toc_reference | def _get_toc_reference(app, node, toc, docname):
"""
Logic that understands maps a specific node to it's part of the toctree.
It takes a specific incoming ``node``,
and returns the actual TOC Tree node that is said reference.
"""
if isinstance(node, nodes.section) and isinstance(node.parent, nodes.document):
# Top Level Section header
ref_id = docname
toc_reference = _find_toc_node(toc, ref_id, nodes.section)
elif isinstance(node, nodes.section):
# Nested Section header
ref_id = node.attributes["ids"][0]
toc_reference = _find_toc_node(toc, ref_id, nodes.section)
else:
# Desc node
try:
ref_id = node.children[0].attributes["ids"][0]
toc_reference = _find_toc_node(toc, ref_id, addnodes.desc)
except (KeyError, IndexError) as e:
LOGGER.warning("Invalid desc node: %s" % e)
toc_reference = None
return toc_reference | python | def _get_toc_reference(app, node, toc, docname):
"""
Logic that understands maps a specific node to it's part of the toctree.
It takes a specific incoming ``node``,
and returns the actual TOC Tree node that is said reference.
"""
if isinstance(node, nodes.section) and isinstance(node.parent, nodes.document):
# Top Level Section header
ref_id = docname
toc_reference = _find_toc_node(toc, ref_id, nodes.section)
elif isinstance(node, nodes.section):
# Nested Section header
ref_id = node.attributes["ids"][0]
toc_reference = _find_toc_node(toc, ref_id, nodes.section)
else:
# Desc node
try:
ref_id = node.children[0].attributes["ids"][0]
toc_reference = _find_toc_node(toc, ref_id, addnodes.desc)
except (KeyError, IndexError) as e:
LOGGER.warning("Invalid desc node: %s" % e)
toc_reference = None
return toc_reference | [
"def",
"_get_toc_reference",
"(",
"app",
",",
"node",
",",
"toc",
",",
"docname",
")",
":",
"if",
"isinstance",
"(",
"node",
",",
"nodes",
".",
"section",
")",
"and",
"isinstance",
"(",
"node",
".",
"parent",
",",
"nodes",
".",
"document",
")",
":",
... | Logic that understands maps a specific node to it's part of the toctree.
It takes a specific incoming ``node``,
and returns the actual TOC Tree node that is said reference. | [
"Logic",
"that",
"understands",
"maps",
"a",
"specific",
"node",
"to",
"it",
"s",
"part",
"of",
"the",
"toctree",
"."
] | 9735f43a8d9ff4620c7bcbd177fd1bb7608052e9 | https://github.com/rtfd/sphinx-autoapi/blob/9735f43a8d9ff4620c7bcbd177fd1bb7608052e9/autoapi/toctree.py#L73-L97 | train | 199,236 |
rtfd/sphinx-autoapi | autoapi/toctree.py | add_domain_to_toctree | def add_domain_to_toctree(app, doctree, docname):
"""
Add domain objects to the toctree dynamically.
This should be attached to the ``doctree-resolved`` event.
This works by:
* Finding each domain node (addnodes.desc)
* Figuring out it's parent that will be in the toctree
(nodes.section, or a previously added addnodes.desc)
* Finding that parent in the TOC Tree based on it's ID
* Taking that element in the TOC Tree,
and finding it's parent that is a TOC Listing (nodes.bullet_list)
* Adding the new TOC element for our specific node as a child of that nodes.bullet_list
* This checks that bullet_list's last child,
and checks that it is also a nodes.bullet_list,
effectively nesting it under that element
"""
toc = app.env.tocs[docname]
for desc_node in doctree.traverse(addnodes.desc):
try:
ref_id = desc_node.children[0].attributes["ids"][0]
except (KeyError, IndexError) as e:
LOGGER.warning("Invalid desc node: %s" % e)
continue
try:
# Python domain object
ref_text = desc_node[0].attributes["fullname"].split(".")[-1].split("(")[0]
except (KeyError, IndexError):
# TODO[eric]: Support other Domains and ways of accessing this data
# Use `astext` for other types of domain objects
ref_text = desc_node[0].astext().split(".")[-1].split("(")[0]
# This is the actual object that will exist in the TOC Tree
# Sections by default, and other Desc nodes that we've previously placed.
parent_node = _traverse_parent(
node=desc_node, objtypes=(addnodes.desc, nodes.section)
)
if parent_node:
toc_reference = _get_toc_reference(app, parent_node, toc, docname)
if toc_reference:
# Get the last child of our parent's bullet list, this is where "we" live.
toc_insertion_point = _traverse_parent(
toc_reference, nodes.bullet_list
)[-1]
# Ensure we're added another bullet list so that we nest inside the parent,
# not next to it
if toc_insertion_point and isinstance(
toc_insertion_point[0], nodes.bullet_list
):
new_insert = toc_insertion_point[0]
to_add = _build_toc_node(docname, anchor=ref_id, text=ref_text)
new_insert.append(to_add)
else:
to_add = _build_toc_node(
docname, anchor=ref_id, text=ref_text, bullet=True
)
toc_insertion_point.append(to_add) | python | def add_domain_to_toctree(app, doctree, docname):
"""
Add domain objects to the toctree dynamically.
This should be attached to the ``doctree-resolved`` event.
This works by:
* Finding each domain node (addnodes.desc)
* Figuring out it's parent that will be in the toctree
(nodes.section, or a previously added addnodes.desc)
* Finding that parent in the TOC Tree based on it's ID
* Taking that element in the TOC Tree,
and finding it's parent that is a TOC Listing (nodes.bullet_list)
* Adding the new TOC element for our specific node as a child of that nodes.bullet_list
* This checks that bullet_list's last child,
and checks that it is also a nodes.bullet_list,
effectively nesting it under that element
"""
toc = app.env.tocs[docname]
for desc_node in doctree.traverse(addnodes.desc):
try:
ref_id = desc_node.children[0].attributes["ids"][0]
except (KeyError, IndexError) as e:
LOGGER.warning("Invalid desc node: %s" % e)
continue
try:
# Python domain object
ref_text = desc_node[0].attributes["fullname"].split(".")[-1].split("(")[0]
except (KeyError, IndexError):
# TODO[eric]: Support other Domains and ways of accessing this data
# Use `astext` for other types of domain objects
ref_text = desc_node[0].astext().split(".")[-1].split("(")[0]
# This is the actual object that will exist in the TOC Tree
# Sections by default, and other Desc nodes that we've previously placed.
parent_node = _traverse_parent(
node=desc_node, objtypes=(addnodes.desc, nodes.section)
)
if parent_node:
toc_reference = _get_toc_reference(app, parent_node, toc, docname)
if toc_reference:
# Get the last child of our parent's bullet list, this is where "we" live.
toc_insertion_point = _traverse_parent(
toc_reference, nodes.bullet_list
)[-1]
# Ensure we're added another bullet list so that we nest inside the parent,
# not next to it
if toc_insertion_point and isinstance(
toc_insertion_point[0], nodes.bullet_list
):
new_insert = toc_insertion_point[0]
to_add = _build_toc_node(docname, anchor=ref_id, text=ref_text)
new_insert.append(to_add)
else:
to_add = _build_toc_node(
docname, anchor=ref_id, text=ref_text, bullet=True
)
toc_insertion_point.append(to_add) | [
"def",
"add_domain_to_toctree",
"(",
"app",
",",
"doctree",
",",
"docname",
")",
":",
"toc",
"=",
"app",
".",
"env",
".",
"tocs",
"[",
"docname",
"]",
"for",
"desc_node",
"in",
"doctree",
".",
"traverse",
"(",
"addnodes",
".",
"desc",
")",
":",
"try",
... | Add domain objects to the toctree dynamically.
This should be attached to the ``doctree-resolved`` event.
This works by:
* Finding each domain node (addnodes.desc)
* Figuring out it's parent that will be in the toctree
(nodes.section, or a previously added addnodes.desc)
* Finding that parent in the TOC Tree based on it's ID
* Taking that element in the TOC Tree,
and finding it's parent that is a TOC Listing (nodes.bullet_list)
* Adding the new TOC element for our specific node as a child of that nodes.bullet_list
* This checks that bullet_list's last child,
and checks that it is also a nodes.bullet_list,
effectively nesting it under that element | [
"Add",
"domain",
"objects",
"to",
"the",
"toctree",
"dynamically",
"."
] | 9735f43a8d9ff4620c7bcbd177fd1bb7608052e9 | https://github.com/rtfd/sphinx-autoapi/blob/9735f43a8d9ff4620c7bcbd177fd1bb7608052e9/autoapi/toctree.py#L100-L157 | train | 199,237 |
rtfd/sphinx-autoapi | autoapi/directives.py | AutoapiSummary.warn | def warn(self, msg):
"""Add a warning message.
:param msg: The warning message to add.
:type msg: str
"""
self.warnings.append(
self.state.document.reporter.warning(msg, line=self.lineno)
) | python | def warn(self, msg):
"""Add a warning message.
:param msg: The warning message to add.
:type msg: str
"""
self.warnings.append(
self.state.document.reporter.warning(msg, line=self.lineno)
) | [
"def",
"warn",
"(",
"self",
",",
"msg",
")",
":",
"self",
".",
"warnings",
".",
"append",
"(",
"self",
".",
"state",
".",
"document",
".",
"reporter",
".",
"warning",
"(",
"msg",
",",
"line",
"=",
"self",
".",
"lineno",
")",
")"
] | Add a warning message.
:param msg: The warning message to add.
:type msg: str | [
"Add",
"a",
"warning",
"message",
"."
] | 9735f43a8d9ff4620c7bcbd177fd1bb7608052e9 | https://github.com/rtfd/sphinx-autoapi/blob/9735f43a8d9ff4620c7bcbd177fd1bb7608052e9/autoapi/directives.py#L29-L37 | train | 199,238 |
rtfd/sphinx-autoapi | autoapi/directives.py | AutoapiSummary._get_names | def _get_names(self):
"""Get the names of the objects to include in the table.
:returns: The names of the objects to include.
:rtype: generator(str)
"""
for line in self.content:
line = line.strip()
if line and re.search("^[a-zA-Z0-9]", line):
yield line | python | def _get_names(self):
"""Get the names of the objects to include in the table.
:returns: The names of the objects to include.
:rtype: generator(str)
"""
for line in self.content:
line = line.strip()
if line and re.search("^[a-zA-Z0-9]", line):
yield line | [
"def",
"_get_names",
"(",
"self",
")",
":",
"for",
"line",
"in",
"self",
".",
"content",
":",
"line",
"=",
"line",
".",
"strip",
"(",
")",
"if",
"line",
"and",
"re",
".",
"search",
"(",
"\"^[a-zA-Z0-9]\"",
",",
"line",
")",
":",
"yield",
"line"
] | Get the names of the objects to include in the table.
:returns: The names of the objects to include.
:rtype: generator(str) | [
"Get",
"the",
"names",
"of",
"the",
"objects",
"to",
"include",
"in",
"the",
"table",
"."
] | 9735f43a8d9ff4620c7bcbd177fd1bb7608052e9 | https://github.com/rtfd/sphinx-autoapi/blob/9735f43a8d9ff4620c7bcbd177fd1bb7608052e9/autoapi/directives.py#L39-L48 | train | 199,239 |
Tivix/django-cron | django_cron/helpers.py | humanize_duration | def humanize_duration(duration):
"""
Returns a humanized string representing time difference
For example: 2 days 1 hour 25 minutes 10 seconds
"""
days = duration.days
hours = int(duration.seconds / 3600)
minutes = int(duration.seconds % 3600 / 60)
seconds = int(duration.seconds % 3600 % 60)
parts = []
if days > 0:
parts.append(u'%s %s' % (days, pluralize(days, _('day,days'))))
if hours > 0:
parts.append(u'%s %s' % (hours, pluralize(hours, _('hour,hours'))))
if minutes > 0:
parts.append(u'%s %s' % (minutes, pluralize(minutes, _('minute,minutes'))))
if seconds > 0:
parts.append(u'%s %s' % (seconds, pluralize(seconds, _('second,seconds'))))
return ', '.join(parts) if len(parts) != 0 else _('< 1 second') | python | def humanize_duration(duration):
"""
Returns a humanized string representing time difference
For example: 2 days 1 hour 25 minutes 10 seconds
"""
days = duration.days
hours = int(duration.seconds / 3600)
minutes = int(duration.seconds % 3600 / 60)
seconds = int(duration.seconds % 3600 % 60)
parts = []
if days > 0:
parts.append(u'%s %s' % (days, pluralize(days, _('day,days'))))
if hours > 0:
parts.append(u'%s %s' % (hours, pluralize(hours, _('hour,hours'))))
if minutes > 0:
parts.append(u'%s %s' % (minutes, pluralize(minutes, _('minute,minutes'))))
if seconds > 0:
parts.append(u'%s %s' % (seconds, pluralize(seconds, _('second,seconds'))))
return ', '.join(parts) if len(parts) != 0 else _('< 1 second') | [
"def",
"humanize_duration",
"(",
"duration",
")",
":",
"days",
"=",
"duration",
".",
"days",
"hours",
"=",
"int",
"(",
"duration",
".",
"seconds",
"/",
"3600",
")",
"minutes",
"=",
"int",
"(",
"duration",
".",
"seconds",
"%",
"3600",
"/",
"60",
")",
... | Returns a humanized string representing time difference
For example: 2 days 1 hour 25 minutes 10 seconds | [
"Returns",
"a",
"humanized",
"string",
"representing",
"time",
"difference"
] | 7fa5c2d2835520d8c920f3c103937ab292d9e545 | https://github.com/Tivix/django-cron/blob/7fa5c2d2835520d8c920f3c103937ab292d9e545/django_cron/helpers.py#L5-L29 | train | 199,240 |
Tivix/django-cron | django_cron/management/commands/runcrons.py | run_cron_with_cache_check | def run_cron_with_cache_check(cron_class, force=False, silent=False):
"""
Checks the cache and runs the cron or not.
@cron_class - cron class to run.
@force - run job even if not scheduled
@silent - suppress notifications
"""
with CronJobManager(cron_class, silent) as manager:
manager.run(force) | python | def run_cron_with_cache_check(cron_class, force=False, silent=False):
"""
Checks the cache and runs the cron or not.
@cron_class - cron class to run.
@force - run job even if not scheduled
@silent - suppress notifications
"""
with CronJobManager(cron_class, silent) as manager:
manager.run(force) | [
"def",
"run_cron_with_cache_check",
"(",
"cron_class",
",",
"force",
"=",
"False",
",",
"silent",
"=",
"False",
")",
":",
"with",
"CronJobManager",
"(",
"cron_class",
",",
"silent",
")",
"as",
"manager",
":",
"manager",
".",
"run",
"(",
"force",
")"
] | Checks the cache and runs the cron or not.
@cron_class - cron class to run.
@force - run job even if not scheduled
@silent - suppress notifications | [
"Checks",
"the",
"cache",
"and",
"runs",
"the",
"cron",
"or",
"not",
"."
] | 7fa5c2d2835520d8c920f3c103937ab292d9e545 | https://github.com/Tivix/django-cron/blob/7fa5c2d2835520d8c920f3c103937ab292d9e545/django_cron/management/commands/runcrons.py#L61-L71 | train | 199,241 |
Tivix/django-cron | django_cron/management/commands/runcrons.py | clear_old_log_entries | def clear_old_log_entries():
"""
Removes older log entries, if the appropriate setting has been set
"""
if hasattr(settings, 'DJANGO_CRON_DELETE_LOGS_OLDER_THAN'):
delta = timedelta(days=settings.DJANGO_CRON_DELETE_LOGS_OLDER_THAN)
CronJobLog.objects.filter(end_time__lt=get_current_time() - delta).delete() | python | def clear_old_log_entries():
"""
Removes older log entries, if the appropriate setting has been set
"""
if hasattr(settings, 'DJANGO_CRON_DELETE_LOGS_OLDER_THAN'):
delta = timedelta(days=settings.DJANGO_CRON_DELETE_LOGS_OLDER_THAN)
CronJobLog.objects.filter(end_time__lt=get_current_time() - delta).delete() | [
"def",
"clear_old_log_entries",
"(",
")",
":",
"if",
"hasattr",
"(",
"settings",
",",
"'DJANGO_CRON_DELETE_LOGS_OLDER_THAN'",
")",
":",
"delta",
"=",
"timedelta",
"(",
"days",
"=",
"settings",
".",
"DJANGO_CRON_DELETE_LOGS_OLDER_THAN",
")",
"CronJobLog",
".",
"objec... | Removes older log entries, if the appropriate setting has been set | [
"Removes",
"older",
"log",
"entries",
"if",
"the",
"appropriate",
"setting",
"has",
"been",
"set"
] | 7fa5c2d2835520d8c920f3c103937ab292d9e545 | https://github.com/Tivix/django-cron/blob/7fa5c2d2835520d8c920f3c103937ab292d9e545/django_cron/management/commands/runcrons.py#L74-L80 | train | 199,242 |
Tivix/django-cron | django_cron/__init__.py | CronJobManager.should_run_now | def should_run_now(self, force=False):
from django_cron.models import CronJobLog
cron_job = self.cron_job
"""
Returns a boolean determining whether this cron should run now or not!
"""
self.user_time = None
self.previously_ran_successful_cron = None
# If we pass --force options, we force cron run
if force:
return True
if cron_job.schedule.run_every_mins is not None:
# We check last job - success or not
last_job = None
try:
last_job = CronJobLog.objects.filter(code=cron_job.code).latest('start_time')
except CronJobLog.DoesNotExist:
pass
if last_job:
if not last_job.is_success and cron_job.schedule.retry_after_failure_mins:
if get_current_time() > last_job.start_time + timedelta(minutes=cron_job.schedule.retry_after_failure_mins):
return True
else:
return False
try:
self.previously_ran_successful_cron = CronJobLog.objects.filter(
code=cron_job.code,
is_success=True,
ran_at_time__isnull=True
).latest('start_time')
except CronJobLog.DoesNotExist:
pass
if self.previously_ran_successful_cron:
if get_current_time() > self.previously_ran_successful_cron.start_time + timedelta(minutes=cron_job.schedule.run_every_mins):
return True
else:
return True
if cron_job.schedule.run_at_times:
for time_data in cron_job.schedule.run_at_times:
user_time = time.strptime(time_data, "%H:%M")
now = get_current_time()
actual_time = time.strptime("%s:%s" % (now.hour, now.minute), "%H:%M")
if actual_time >= user_time:
qset = CronJobLog.objects.filter(
code=cron_job.code,
ran_at_time=time_data,
is_success=True
).filter(
Q(start_time__gt=now) | Q(end_time__gte=now.replace(hour=0, minute=0, second=0, microsecond=0))
)
if not qset:
self.user_time = time_data
return True
return False | python | def should_run_now(self, force=False):
from django_cron.models import CronJobLog
cron_job = self.cron_job
"""
Returns a boolean determining whether this cron should run now or not!
"""
self.user_time = None
self.previously_ran_successful_cron = None
# If we pass --force options, we force cron run
if force:
return True
if cron_job.schedule.run_every_mins is not None:
# We check last job - success or not
last_job = None
try:
last_job = CronJobLog.objects.filter(code=cron_job.code).latest('start_time')
except CronJobLog.DoesNotExist:
pass
if last_job:
if not last_job.is_success and cron_job.schedule.retry_after_failure_mins:
if get_current_time() > last_job.start_time + timedelta(minutes=cron_job.schedule.retry_after_failure_mins):
return True
else:
return False
try:
self.previously_ran_successful_cron = CronJobLog.objects.filter(
code=cron_job.code,
is_success=True,
ran_at_time__isnull=True
).latest('start_time')
except CronJobLog.DoesNotExist:
pass
if self.previously_ran_successful_cron:
if get_current_time() > self.previously_ran_successful_cron.start_time + timedelta(minutes=cron_job.schedule.run_every_mins):
return True
else:
return True
if cron_job.schedule.run_at_times:
for time_data in cron_job.schedule.run_at_times:
user_time = time.strptime(time_data, "%H:%M")
now = get_current_time()
actual_time = time.strptime("%s:%s" % (now.hour, now.minute), "%H:%M")
if actual_time >= user_time:
qset = CronJobLog.objects.filter(
code=cron_job.code,
ran_at_time=time_data,
is_success=True
).filter(
Q(start_time__gt=now) | Q(end_time__gte=now.replace(hour=0, minute=0, second=0, microsecond=0))
)
if not qset:
self.user_time = time_data
return True
return False | [
"def",
"should_run_now",
"(",
"self",
",",
"force",
"=",
"False",
")",
":",
"from",
"django_cron",
".",
"models",
"import",
"CronJobLog",
"cron_job",
"=",
"self",
".",
"cron_job",
"self",
".",
"user_time",
"=",
"None",
"self",
".",
"previously_ran_successful_c... | Returns a boolean determining whether this cron should run now or not! | [
"Returns",
"a",
"boolean",
"determining",
"whether",
"this",
"cron",
"should",
"run",
"now",
"or",
"not!"
] | 7fa5c2d2835520d8c920f3c103937ab292d9e545 | https://github.com/Tivix/django-cron/blob/7fa5c2d2835520d8c920f3c103937ab292d9e545/django_cron/__init__.py#L89-L149 | train | 199,243 |
Tivix/django-cron | django_cron/backends/lock/cache.py | CacheLock.lock | def lock(self):
"""
This method sets a cache variable to mark current job as "already running".
"""
if self.cache.get(self.lock_name):
return False
else:
self.cache.set(self.lock_name, timezone.now(), self.timeout)
return True | python | def lock(self):
"""
This method sets a cache variable to mark current job as "already running".
"""
if self.cache.get(self.lock_name):
return False
else:
self.cache.set(self.lock_name, timezone.now(), self.timeout)
return True | [
"def",
"lock",
"(",
"self",
")",
":",
"if",
"self",
".",
"cache",
".",
"get",
"(",
"self",
".",
"lock_name",
")",
":",
"return",
"False",
"else",
":",
"self",
".",
"cache",
".",
"set",
"(",
"self",
".",
"lock_name",
",",
"timezone",
".",
"now",
"... | This method sets a cache variable to mark current job as "already running". | [
"This",
"method",
"sets",
"a",
"cache",
"variable",
"to",
"mark",
"current",
"job",
"as",
"already",
"running",
"."
] | 7fa5c2d2835520d8c920f3c103937ab292d9e545 | https://github.com/Tivix/django-cron/blob/7fa5c2d2835520d8c920f3c103937ab292d9e545/django_cron/backends/lock/cache.py#L22-L30 | train | 199,244 |
bee-keeper/django-invitations | invitations/utils.py | get_invitation_model | def get_invitation_model():
"""
Returns the Invitation model that is active in this project.
"""
path = app_settings.INVITATION_MODEL
try:
return django_apps.get_model(path)
except ValueError:
raise ImproperlyConfigured(
"path must be of the form 'app_label.model_name'"
)
except LookupError:
raise ImproperlyConfigured(
"path refers to model '%s' that\
has not been installed" % app_settings.INVITATION_MODEL
) | python | def get_invitation_model():
"""
Returns the Invitation model that is active in this project.
"""
path = app_settings.INVITATION_MODEL
try:
return django_apps.get_model(path)
except ValueError:
raise ImproperlyConfigured(
"path must be of the form 'app_label.model_name'"
)
except LookupError:
raise ImproperlyConfigured(
"path refers to model '%s' that\
has not been installed" % app_settings.INVITATION_MODEL
) | [
"def",
"get_invitation_model",
"(",
")",
":",
"path",
"=",
"app_settings",
".",
"INVITATION_MODEL",
"try",
":",
"return",
"django_apps",
".",
"get_model",
"(",
"path",
")",
"except",
"ValueError",
":",
"raise",
"ImproperlyConfigured",
"(",
"\"path must be of the for... | Returns the Invitation model that is active in this project. | [
"Returns",
"the",
"Invitation",
"model",
"that",
"is",
"active",
"in",
"this",
"project",
"."
] | 9802e24504f877dd6d67dd81274daead99a7ef76 | https://github.com/bee-keeper/django-invitations/blob/9802e24504f877dd6d67dd81274daead99a7ef76/invitations/utils.py#L32-L47 | train | 199,245 |
aio-libs/aiodocker | aiodocker/images.py | DockerImages.list | async def list(self, **params) -> Mapping:
"""
List of images
"""
response = await self.docker._query_json("images/json", "GET", params=params)
return response | python | async def list(self, **params) -> Mapping:
"""
List of images
"""
response = await self.docker._query_json("images/json", "GET", params=params)
return response | [
"async",
"def",
"list",
"(",
"self",
",",
"*",
"*",
"params",
")",
"->",
"Mapping",
":",
"response",
"=",
"await",
"self",
".",
"docker",
".",
"_query_json",
"(",
"\"images/json\"",
",",
"\"GET\"",
",",
"params",
"=",
"params",
")",
"return",
"response"
... | List of images | [
"List",
"of",
"images"
] | 88d0285ddba8e606ff684278e0a831347209189c | https://github.com/aio-libs/aiodocker/blob/88d0285ddba8e606ff684278e0a831347209189c/aiodocker/images.py#L12-L17 | train | 199,246 |
aio-libs/aiodocker | aiodocker/images.py | DockerImages.inspect | async def inspect(self, name: str) -> Mapping:
"""
Return low-level information about an image
Args:
name: name of the image
"""
response = await self.docker._query_json("images/{name}/json".format(name=name))
return response | python | async def inspect(self, name: str) -> Mapping:
"""
Return low-level information about an image
Args:
name: name of the image
"""
response = await self.docker._query_json("images/{name}/json".format(name=name))
return response | [
"async",
"def",
"inspect",
"(",
"self",
",",
"name",
":",
"str",
")",
"->",
"Mapping",
":",
"response",
"=",
"await",
"self",
".",
"docker",
".",
"_query_json",
"(",
"\"images/{name}/json\"",
".",
"format",
"(",
"name",
"=",
"name",
")",
")",
"return",
... | Return low-level information about an image
Args:
name: name of the image | [
"Return",
"low",
"-",
"level",
"information",
"about",
"an",
"image"
] | 88d0285ddba8e606ff684278e0a831347209189c | https://github.com/aio-libs/aiodocker/blob/88d0285ddba8e606ff684278e0a831347209189c/aiodocker/images.py#L19-L27 | train | 199,247 |
aio-libs/aiodocker | aiodocker/images.py | DockerImages.pull | async def pull(
self,
from_image: str,
*,
auth: Optional[Union[MutableMapping, str, bytes]] = None,
tag: str = None,
repo: str = None,
stream: bool = False
) -> Mapping:
"""
Similar to `docker pull`, pull an image locally
Args:
fromImage: name of the image to pull
repo: repository name given to an image when it is imported
tag: if empty when pulling an image all tags
for the given image to be pulled
auth: special {'auth': base64} pull private repo
"""
image = from_image # TODO: clean up
params = {"fromImage": image}
headers = {}
if repo:
params["repo"] = repo
if tag:
params["tag"] = tag
if auth is not None:
registry, has_registry_host, _ = image.partition("/")
if not has_registry_host:
raise ValueError(
"Image should have registry host "
"when auth information is provided"
)
# TODO: assert registry == repo?
headers["X-Registry-Auth"] = compose_auth_header(auth, registry)
response = await self.docker._query(
"images/create", "POST", params=params, headers=headers
)
return await json_stream_result(response, stream=stream) | python | async def pull(
self,
from_image: str,
*,
auth: Optional[Union[MutableMapping, str, bytes]] = None,
tag: str = None,
repo: str = None,
stream: bool = False
) -> Mapping:
"""
Similar to `docker pull`, pull an image locally
Args:
fromImage: name of the image to pull
repo: repository name given to an image when it is imported
tag: if empty when pulling an image all tags
for the given image to be pulled
auth: special {'auth': base64} pull private repo
"""
image = from_image # TODO: clean up
params = {"fromImage": image}
headers = {}
if repo:
params["repo"] = repo
if tag:
params["tag"] = tag
if auth is not None:
registry, has_registry_host, _ = image.partition("/")
if not has_registry_host:
raise ValueError(
"Image should have registry host "
"when auth information is provided"
)
# TODO: assert registry == repo?
headers["X-Registry-Auth"] = compose_auth_header(auth, registry)
response = await self.docker._query(
"images/create", "POST", params=params, headers=headers
)
return await json_stream_result(response, stream=stream) | [
"async",
"def",
"pull",
"(",
"self",
",",
"from_image",
":",
"str",
",",
"*",
",",
"auth",
":",
"Optional",
"[",
"Union",
"[",
"MutableMapping",
",",
"str",
",",
"bytes",
"]",
"]",
"=",
"None",
",",
"tag",
":",
"str",
"=",
"None",
",",
"repo",
":... | Similar to `docker pull`, pull an image locally
Args:
fromImage: name of the image to pull
repo: repository name given to an image when it is imported
tag: if empty when pulling an image all tags
for the given image to be pulled
auth: special {'auth': base64} pull private repo | [
"Similar",
"to",
"docker",
"pull",
"pull",
"an",
"image",
"locally"
] | 88d0285ddba8e606ff684278e0a831347209189c | https://github.com/aio-libs/aiodocker/blob/88d0285ddba8e606ff684278e0a831347209189c/aiodocker/images.py#L44-L82 | train | 199,248 |
aio-libs/aiodocker | aiodocker/images.py | DockerImages.tag | async def tag(self, name: str, repo: str, *, tag: str = None) -> bool:
"""
Tag the given image so that it becomes part of a repository.
Args:
repo: the repository to tag in
tag: the name for the new tag
"""
params = {"repo": repo}
if tag:
params["tag"] = tag
await self.docker._query(
"images/{name}/tag".format(name=name),
"POST",
params=params,
headers={"content-type": "application/json"},
)
return True | python | async def tag(self, name: str, repo: str, *, tag: str = None) -> bool:
"""
Tag the given image so that it becomes part of a repository.
Args:
repo: the repository to tag in
tag: the name for the new tag
"""
params = {"repo": repo}
if tag:
params["tag"] = tag
await self.docker._query(
"images/{name}/tag".format(name=name),
"POST",
params=params,
headers={"content-type": "application/json"},
)
return True | [
"async",
"def",
"tag",
"(",
"self",
",",
"name",
":",
"str",
",",
"repo",
":",
"str",
",",
"*",
",",
"tag",
":",
"str",
"=",
"None",
")",
"->",
"bool",
":",
"params",
"=",
"{",
"\"repo\"",
":",
"repo",
"}",
"if",
"tag",
":",
"params",
"[",
"\... | Tag the given image so that it becomes part of a repository.
Args:
repo: the repository to tag in
tag: the name for the new tag | [
"Tag",
"the",
"given",
"image",
"so",
"that",
"it",
"becomes",
"part",
"of",
"a",
"repository",
"."
] | 88d0285ddba8e606ff684278e0a831347209189c | https://github.com/aio-libs/aiodocker/blob/88d0285ddba8e606ff684278e0a831347209189c/aiodocker/images.py#L115-L134 | train | 199,249 |
aio-libs/aiodocker | aiodocker/images.py | DockerImages.delete | async def delete(
self, name: str, *, force: bool = False, noprune: bool = False
) -> List:
"""
Remove an image along with any untagged parent
images that were referenced by that image
Args:
name: name/id of the image to delete
force: remove the image even if it is being used
by stopped containers or has other tags
noprune: don't delete untagged parent images
Returns:
List of deleted images
"""
params = {"force": force, "noprune": noprune}
response = await self.docker._query_json(
"images/{name}".format(name=name), "DELETE", params=params
)
return response | python | async def delete(
self, name: str, *, force: bool = False, noprune: bool = False
) -> List:
"""
Remove an image along with any untagged parent
images that were referenced by that image
Args:
name: name/id of the image to delete
force: remove the image even if it is being used
by stopped containers or has other tags
noprune: don't delete untagged parent images
Returns:
List of deleted images
"""
params = {"force": force, "noprune": noprune}
response = await self.docker._query_json(
"images/{name}".format(name=name), "DELETE", params=params
)
return response | [
"async",
"def",
"delete",
"(",
"self",
",",
"name",
":",
"str",
",",
"*",
",",
"force",
":",
"bool",
"=",
"False",
",",
"noprune",
":",
"bool",
"=",
"False",
")",
"->",
"List",
":",
"params",
"=",
"{",
"\"force\"",
":",
"force",
",",
"\"noprune\"",... | Remove an image along with any untagged parent
images that were referenced by that image
Args:
name: name/id of the image to delete
force: remove the image even if it is being used
by stopped containers or has other tags
noprune: don't delete untagged parent images
Returns:
List of deleted images | [
"Remove",
"an",
"image",
"along",
"with",
"any",
"untagged",
"parent",
"images",
"that",
"were",
"referenced",
"by",
"that",
"image"
] | 88d0285ddba8e606ff684278e0a831347209189c | https://github.com/aio-libs/aiodocker/blob/88d0285ddba8e606ff684278e0a831347209189c/aiodocker/images.py#L136-L156 | train | 199,250 |
aio-libs/aiodocker | aiodocker/images.py | DockerImages.build | async def build(
self,
*,
remote: str = None,
fileobj: BinaryIO = None,
path_dockerfile: str = None,
tag: str = None,
quiet: bool = False,
nocache: bool = False,
buildargs: Mapping = None,
pull: bool = False,
rm: bool = True,
forcerm: bool = False,
labels: Mapping = None,
stream: bool = False,
encoding: str = None
) -> Mapping:
"""
Build an image given a remote Dockerfile
or a file object with a Dockerfile inside
Args:
path_dockerfile: path within the build context to the Dockerfile
remote: a Git repository URI or HTTP/HTTPS context URI
quiet: suppress verbose build output
nocache: do not use the cache when building the image
rm: remove intermediate containers after a successful build
pull: downloads any updates to the FROM image in Dockerfiles
encoding: set `Content-Encoding` for the file object your send
forcerm: always remove intermediate containers, even upon failure
labels: arbitrary key/value labels to set on the image
fileobj: a tar archive compressed or not
"""
local_context = None
headers = {}
params = {
"t": tag,
"rm": rm,
"q": quiet,
"pull": pull,
"remote": remote,
"nocache": nocache,
"forcerm": forcerm,
"dockerfile": path_dockerfile,
}
if remote is None and fileobj is None:
raise ValueError("You need to specify either remote or fileobj")
if fileobj and remote:
raise ValueError("You cannot specify both fileobj and remote")
if fileobj and not encoding:
raise ValueError("You need to specify an encoding")
if remote is None and fileobj is None:
raise ValueError("Either remote or fileobj needs to be provided.")
if fileobj:
local_context = fileobj.read()
headers["content-type"] = "application/x-tar"
if fileobj and encoding:
headers["Content-Encoding"] = encoding
if buildargs:
params.update({"buildargs": json.dumps(buildargs)})
if labels:
params.update({"labels": json.dumps(labels)})
response = await self.docker._query(
"build",
"POST",
params=clean_map(params),
headers=headers,
data=local_context,
)
return await json_stream_result(response, stream=stream) | python | async def build(
self,
*,
remote: str = None,
fileobj: BinaryIO = None,
path_dockerfile: str = None,
tag: str = None,
quiet: bool = False,
nocache: bool = False,
buildargs: Mapping = None,
pull: bool = False,
rm: bool = True,
forcerm: bool = False,
labels: Mapping = None,
stream: bool = False,
encoding: str = None
) -> Mapping:
"""
Build an image given a remote Dockerfile
or a file object with a Dockerfile inside
Args:
path_dockerfile: path within the build context to the Dockerfile
remote: a Git repository URI or HTTP/HTTPS context URI
quiet: suppress verbose build output
nocache: do not use the cache when building the image
rm: remove intermediate containers after a successful build
pull: downloads any updates to the FROM image in Dockerfiles
encoding: set `Content-Encoding` for the file object your send
forcerm: always remove intermediate containers, even upon failure
labels: arbitrary key/value labels to set on the image
fileobj: a tar archive compressed or not
"""
local_context = None
headers = {}
params = {
"t": tag,
"rm": rm,
"q": quiet,
"pull": pull,
"remote": remote,
"nocache": nocache,
"forcerm": forcerm,
"dockerfile": path_dockerfile,
}
if remote is None and fileobj is None:
raise ValueError("You need to specify either remote or fileobj")
if fileobj and remote:
raise ValueError("You cannot specify both fileobj and remote")
if fileobj and not encoding:
raise ValueError("You need to specify an encoding")
if remote is None and fileobj is None:
raise ValueError("Either remote or fileobj needs to be provided.")
if fileobj:
local_context = fileobj.read()
headers["content-type"] = "application/x-tar"
if fileobj and encoding:
headers["Content-Encoding"] = encoding
if buildargs:
params.update({"buildargs": json.dumps(buildargs)})
if labels:
params.update({"labels": json.dumps(labels)})
response = await self.docker._query(
"build",
"POST",
params=clean_map(params),
headers=headers,
data=local_context,
)
return await json_stream_result(response, stream=stream) | [
"async",
"def",
"build",
"(",
"self",
",",
"*",
",",
"remote",
":",
"str",
"=",
"None",
",",
"fileobj",
":",
"BinaryIO",
"=",
"None",
",",
"path_dockerfile",
":",
"str",
"=",
"None",
",",
"tag",
":",
"str",
"=",
"None",
",",
"quiet",
":",
"bool",
... | Build an image given a remote Dockerfile
or a file object with a Dockerfile inside
Args:
path_dockerfile: path within the build context to the Dockerfile
remote: a Git repository URI or HTTP/HTTPS context URI
quiet: suppress verbose build output
nocache: do not use the cache when building the image
rm: remove intermediate containers after a successful build
pull: downloads any updates to the FROM image in Dockerfiles
encoding: set `Content-Encoding` for the file object your send
forcerm: always remove intermediate containers, even upon failure
labels: arbitrary key/value labels to set on the image
fileobj: a tar archive compressed or not | [
"Build",
"an",
"image",
"given",
"a",
"remote",
"Dockerfile",
"or",
"a",
"file",
"object",
"with",
"a",
"Dockerfile",
"inside"
] | 88d0285ddba8e606ff684278e0a831347209189c | https://github.com/aio-libs/aiodocker/blob/88d0285ddba8e606ff684278e0a831347209189c/aiodocker/images.py#L158-L240 | train | 199,251 |
aio-libs/aiodocker | aiodocker/images.py | DockerImages.export_image | async def export_image(self, name: str):
"""
Get a tarball of an image by name or id.
Args:
name: name/id of the image to be exported
Returns:
Streamreader of tarball image
"""
response = await self.docker._query(
"images/{name}/get".format(name=name), "GET"
)
return response.content | python | async def export_image(self, name: str):
"""
Get a tarball of an image by name or id.
Args:
name: name/id of the image to be exported
Returns:
Streamreader of tarball image
"""
response = await self.docker._query(
"images/{name}/get".format(name=name), "GET"
)
return response.content | [
"async",
"def",
"export_image",
"(",
"self",
",",
"name",
":",
"str",
")",
":",
"response",
"=",
"await",
"self",
".",
"docker",
".",
"_query",
"(",
"\"images/{name}/get\"",
".",
"format",
"(",
"name",
"=",
"name",
")",
",",
"\"GET\"",
")",
"return",
"... | Get a tarball of an image by name or id.
Args:
name: name/id of the image to be exported
Returns:
Streamreader of tarball image | [
"Get",
"a",
"tarball",
"of",
"an",
"image",
"by",
"name",
"or",
"id",
"."
] | 88d0285ddba8e606ff684278e0a831347209189c | https://github.com/aio-libs/aiodocker/blob/88d0285ddba8e606ff684278e0a831347209189c/aiodocker/images.py#L242-L255 | train | 199,252 |
aio-libs/aiodocker | aiodocker/images.py | DockerImages.import_image | async def import_image(self, data, stream: bool = False):
"""
Import tarball of image to docker.
Args:
data: tarball data of image to be imported
Returns:
Tarball of the image
"""
headers = {"Content-Type": "application/x-tar"}
response = await self.docker._query_chunked_post(
"images/load", "POST", data=data, headers=headers
)
return await json_stream_result(response, stream=stream) | python | async def import_image(self, data, stream: bool = False):
"""
Import tarball of image to docker.
Args:
data: tarball data of image to be imported
Returns:
Tarball of the image
"""
headers = {"Content-Type": "application/x-tar"}
response = await self.docker._query_chunked_post(
"images/load", "POST", data=data, headers=headers
)
return await json_stream_result(response, stream=stream) | [
"async",
"def",
"import_image",
"(",
"self",
",",
"data",
",",
"stream",
":",
"bool",
"=",
"False",
")",
":",
"headers",
"=",
"{",
"\"Content-Type\"",
":",
"\"application/x-tar\"",
"}",
"response",
"=",
"await",
"self",
".",
"docker",
".",
"_query_chunked_po... | Import tarball of image to docker.
Args:
data: tarball data of image to be imported
Returns:
Tarball of the image | [
"Import",
"tarball",
"of",
"image",
"to",
"docker",
"."
] | 88d0285ddba8e606ff684278e0a831347209189c | https://github.com/aio-libs/aiodocker/blob/88d0285ddba8e606ff684278e0a831347209189c/aiodocker/images.py#L257-L271 | train | 199,253 |
aio-libs/aiodocker | aiodocker/utils.py | parse_result | async def parse_result(response, response_type=None, *, encoding="utf-8"):
"""
Convert the response to native objects by the given response type
or the auto-detected HTTP content-type.
It also ensures release of the response object.
"""
if response_type is None:
ct = response.headers.get("content-type")
if ct is None:
cl = response.headers.get("content-length")
if cl is None or cl == "0":
return ""
raise TypeError(
"Cannot auto-detect response type "
"due to missing Content-Type header."
)
main_type, sub_type, extras = parse_content_type(ct)
if sub_type == "json":
response_type = "json"
elif sub_type == "x-tar":
response_type = "tar"
elif (main_type, sub_type) == ("text", "plain"):
response_type = "text"
encoding = extras.get("charset", encoding)
else:
raise TypeError("Unrecognized response type: {ct}".format(ct=ct))
if "tar" == response_type:
what = await response.read()
return tarfile.open(mode="r", fileobj=BytesIO(what))
if "json" == response_type:
data = await response.json(encoding=encoding)
elif "text" == response_type:
data = await response.text(encoding=encoding)
else:
data = await response.read()
return data | python | async def parse_result(response, response_type=None, *, encoding="utf-8"):
"""
Convert the response to native objects by the given response type
or the auto-detected HTTP content-type.
It also ensures release of the response object.
"""
if response_type is None:
ct = response.headers.get("content-type")
if ct is None:
cl = response.headers.get("content-length")
if cl is None or cl == "0":
return ""
raise TypeError(
"Cannot auto-detect response type "
"due to missing Content-Type header."
)
main_type, sub_type, extras = parse_content_type(ct)
if sub_type == "json":
response_type = "json"
elif sub_type == "x-tar":
response_type = "tar"
elif (main_type, sub_type) == ("text", "plain"):
response_type = "text"
encoding = extras.get("charset", encoding)
else:
raise TypeError("Unrecognized response type: {ct}".format(ct=ct))
if "tar" == response_type:
what = await response.read()
return tarfile.open(mode="r", fileobj=BytesIO(what))
if "json" == response_type:
data = await response.json(encoding=encoding)
elif "text" == response_type:
data = await response.text(encoding=encoding)
else:
data = await response.read()
return data | [
"async",
"def",
"parse_result",
"(",
"response",
",",
"response_type",
"=",
"None",
",",
"*",
",",
"encoding",
"=",
"\"utf-8\"",
")",
":",
"if",
"response_type",
"is",
"None",
":",
"ct",
"=",
"response",
".",
"headers",
".",
"get",
"(",
"\"content-type\"",... | Convert the response to native objects by the given response type
or the auto-detected HTTP content-type.
It also ensures release of the response object. | [
"Convert",
"the",
"response",
"to",
"native",
"objects",
"by",
"the",
"given",
"response",
"type",
"or",
"the",
"auto",
"-",
"detected",
"HTTP",
"content",
"-",
"type",
".",
"It",
"also",
"ensures",
"release",
"of",
"the",
"response",
"object",
"."
] | 88d0285ddba8e606ff684278e0a831347209189c | https://github.com/aio-libs/aiodocker/blob/88d0285ddba8e606ff684278e0a831347209189c/aiodocker/utils.py#L22-L57 | train | 199,254 |
aio-libs/aiodocker | aiodocker/utils.py | clean_map | def clean_map(obj: Mapping[Any, Any]) -> Mapping[Any, Any]:
"""
Return a new copied dictionary without the keys with ``None`` values from
the given Mapping object.
"""
return {k: v for k, v in obj.items() if v is not None} | python | def clean_map(obj: Mapping[Any, Any]) -> Mapping[Any, Any]:
"""
Return a new copied dictionary without the keys with ``None`` values from
the given Mapping object.
"""
return {k: v for k, v in obj.items() if v is not None} | [
"def",
"clean_map",
"(",
"obj",
":",
"Mapping",
"[",
"Any",
",",
"Any",
"]",
")",
"->",
"Mapping",
"[",
"Any",
",",
"Any",
"]",
":",
"return",
"{",
"k",
":",
"v",
"for",
"k",
",",
"v",
"in",
"obj",
".",
"items",
"(",
")",
"if",
"v",
"is",
"... | Return a new copied dictionary without the keys with ``None`` values from
the given Mapping object. | [
"Return",
"a",
"new",
"copied",
"dictionary",
"without",
"the",
"keys",
"with",
"None",
"values",
"from",
"the",
"given",
"Mapping",
"object",
"."
] | 88d0285ddba8e606ff684278e0a831347209189c | https://github.com/aio-libs/aiodocker/blob/88d0285ddba8e606ff684278e0a831347209189c/aiodocker/utils.py#L176-L181 | train | 199,255 |
aio-libs/aiodocker | aiodocker/utils.py | clean_networks | def clean_networks(networks: Iterable[str] = None) -> Optional[Iterable[str]]:
"""
Cleans the values inside `networks`
Returns a new list
"""
if not networks:
return networks
if not isinstance(networks, list):
raise TypeError("networks parameter must be a list.")
result = []
for n in networks:
if isinstance(n, str):
n = {"Target": n}
result.append(n)
return result | python | def clean_networks(networks: Iterable[str] = None) -> Optional[Iterable[str]]:
"""
Cleans the values inside `networks`
Returns a new list
"""
if not networks:
return networks
if not isinstance(networks, list):
raise TypeError("networks parameter must be a list.")
result = []
for n in networks:
if isinstance(n, str):
n = {"Target": n}
result.append(n)
return result | [
"def",
"clean_networks",
"(",
"networks",
":",
"Iterable",
"[",
"str",
"]",
"=",
"None",
")",
"->",
"Optional",
"[",
"Iterable",
"[",
"str",
"]",
"]",
":",
"if",
"not",
"networks",
":",
"return",
"networks",
"if",
"not",
"isinstance",
"(",
"networks",
... | Cleans the values inside `networks`
Returns a new list | [
"Cleans",
"the",
"values",
"inside",
"networks",
"Returns",
"a",
"new",
"list"
] | 88d0285ddba8e606ff684278e0a831347209189c | https://github.com/aio-libs/aiodocker/blob/88d0285ddba8e606ff684278e0a831347209189c/aiodocker/utils.py#L196-L211 | train | 199,256 |
aio-libs/aiodocker | aiodocker/tasks.py | DockerTasks.inspect | async def inspect(self, task_id: str) -> Mapping[str, Any]:
"""
Return info about a task
Args:
task_id: is ID of the task
"""
response = await self.docker._query_json(
"tasks/{task_id}".format(task_id=task_id), method="GET"
)
return response | python | async def inspect(self, task_id: str) -> Mapping[str, Any]:
"""
Return info about a task
Args:
task_id: is ID of the task
"""
response = await self.docker._query_json(
"tasks/{task_id}".format(task_id=task_id), method="GET"
)
return response | [
"async",
"def",
"inspect",
"(",
"self",
",",
"task_id",
":",
"str",
")",
"->",
"Mapping",
"[",
"str",
",",
"Any",
"]",
":",
"response",
"=",
"await",
"self",
".",
"docker",
".",
"_query_json",
"(",
"\"tasks/{task_id}\"",
".",
"format",
"(",
"task_id",
... | Return info about a task
Args:
task_id: is ID of the task | [
"Return",
"info",
"about",
"a",
"task"
] | 88d0285ddba8e606ff684278e0a831347209189c | https://github.com/aio-libs/aiodocker/blob/88d0285ddba8e606ff684278e0a831347209189c/aiodocker/tasks.py#L31-L43 | train | 199,257 |
aio-libs/aiodocker | aiodocker/containers.py | DockerContainers.run | async def run(self, config, *, name=None):
"""
Create and start a container.
If container.start() will raise an error the exception will contain
a `container_id` attribute with the id of the container.
"""
try:
container = await self.create(config, name=name)
except DockerError as err:
# image not find, try pull it
if err.status == 404 and "Image" in config:
await self.docker.pull(config["Image"])
container = await self.create(config, name=name)
else:
raise err
try:
await container.start()
except DockerError as err:
raise DockerContainerError(
err.status, {"message": err.message}, container["id"]
)
return container | python | async def run(self, config, *, name=None):
"""
Create and start a container.
If container.start() will raise an error the exception will contain
a `container_id` attribute with the id of the container.
"""
try:
container = await self.create(config, name=name)
except DockerError as err:
# image not find, try pull it
if err.status == 404 and "Image" in config:
await self.docker.pull(config["Image"])
container = await self.create(config, name=name)
else:
raise err
try:
await container.start()
except DockerError as err:
raise DockerContainerError(
err.status, {"message": err.message}, container["id"]
)
return container | [
"async",
"def",
"run",
"(",
"self",
",",
"config",
",",
"*",
",",
"name",
"=",
"None",
")",
":",
"try",
":",
"container",
"=",
"await",
"self",
".",
"create",
"(",
"config",
",",
"name",
"=",
"name",
")",
"except",
"DockerError",
"as",
"err",
":",
... | Create and start a container.
If container.start() will raise an error the exception will contain
a `container_id` attribute with the id of the container. | [
"Create",
"and",
"start",
"a",
"container",
"."
] | 88d0285ddba8e606ff684278e0a831347209189c | https://github.com/aio-libs/aiodocker/blob/88d0285ddba8e606ff684278e0a831347209189c/aiodocker/containers.py#L53-L77 | train | 199,258 |
aio-libs/aiodocker | aiodocker/events.py | DockerEvents.subscribe | def subscribe(self, *, create_task=True, **params):
"""Subscribes to the Docker events channel. Use the keyword argument
create_task=False to prevent automatically spawning the background
tasks that listen to the events.
This function returns a ChannelSubscriber object.
"""
if create_task and not self.task:
self.task = asyncio.ensure_future(self.run(**params))
return self.channel.subscribe() | python | def subscribe(self, *, create_task=True, **params):
"""Subscribes to the Docker events channel. Use the keyword argument
create_task=False to prevent automatically spawning the background
tasks that listen to the events.
This function returns a ChannelSubscriber object.
"""
if create_task and not self.task:
self.task = asyncio.ensure_future(self.run(**params))
return self.channel.subscribe() | [
"def",
"subscribe",
"(",
"self",
",",
"*",
",",
"create_task",
"=",
"True",
",",
"*",
"*",
"params",
")",
":",
"if",
"create_task",
"and",
"not",
"self",
".",
"task",
":",
"self",
".",
"task",
"=",
"asyncio",
".",
"ensure_future",
"(",
"self",
".",
... | Subscribes to the Docker events channel. Use the keyword argument
create_task=False to prevent automatically spawning the background
tasks that listen to the events.
This function returns a ChannelSubscriber object. | [
"Subscribes",
"to",
"the",
"Docker",
"events",
"channel",
".",
"Use",
"the",
"keyword",
"argument",
"create_task",
"=",
"False",
"to",
"prevent",
"automatically",
"spawning",
"the",
"background",
"tasks",
"that",
"listen",
"to",
"the",
"events",
"."
] | 88d0285ddba8e606ff684278e0a831347209189c | https://github.com/aio-libs/aiodocker/blob/88d0285ddba8e606ff684278e0a831347209189c/aiodocker/events.py#L24-L33 | train | 199,259 |
aio-libs/aiodocker | aiodocker/events.py | DockerEvents.run | async def run(self, **params):
"""
Query the events endpoint of the Docker daemon.
Publish messages inside the asyncio queue.
"""
if self.json_stream:
warnings.warn("already running", RuntimeWarning, stackelevel=2)
return
forced_params = {"stream": True}
params = ChainMap(forced_params, params)
try:
# timeout has to be set to 0, None is not passed
# Otherwise after 5 minutes the client
# will close the connection
# http://aiohttp.readthedocs.io/en/stable/client_reference.html#aiohttp.ClientSession.request
response = await self.docker._query(
"events", method="GET", params=params, timeout=0
)
self.json_stream = await json_stream_result(
response, self._transform_event, human_bool(params["stream"])
)
try:
async for data in self.json_stream:
await self.channel.publish(data)
finally:
if self.json_stream is not None:
await self.json_stream._close()
self.json_stream = None
finally:
# signal termination to subscribers
await self.channel.publish(None) | python | async def run(self, **params):
"""
Query the events endpoint of the Docker daemon.
Publish messages inside the asyncio queue.
"""
if self.json_stream:
warnings.warn("already running", RuntimeWarning, stackelevel=2)
return
forced_params = {"stream": True}
params = ChainMap(forced_params, params)
try:
# timeout has to be set to 0, None is not passed
# Otherwise after 5 minutes the client
# will close the connection
# http://aiohttp.readthedocs.io/en/stable/client_reference.html#aiohttp.ClientSession.request
response = await self.docker._query(
"events", method="GET", params=params, timeout=0
)
self.json_stream = await json_stream_result(
response, self._transform_event, human_bool(params["stream"])
)
try:
async for data in self.json_stream:
await self.channel.publish(data)
finally:
if self.json_stream is not None:
await self.json_stream._close()
self.json_stream = None
finally:
# signal termination to subscribers
await self.channel.publish(None) | [
"async",
"def",
"run",
"(",
"self",
",",
"*",
"*",
"params",
")",
":",
"if",
"self",
".",
"json_stream",
":",
"warnings",
".",
"warn",
"(",
"\"already running\"",
",",
"RuntimeWarning",
",",
"stackelevel",
"=",
"2",
")",
"return",
"forced_params",
"=",
"... | Query the events endpoint of the Docker daemon.
Publish messages inside the asyncio queue. | [
"Query",
"the",
"events",
"endpoint",
"of",
"the",
"Docker",
"daemon",
"."
] | 88d0285ddba8e606ff684278e0a831347209189c | https://github.com/aio-libs/aiodocker/blob/88d0285ddba8e606ff684278e0a831347209189c/aiodocker/events.py#L40-L71 | train | 199,260 |
aio-libs/aiodocker | aiodocker/nodes.py | DockerSwarmNodes.inspect | async def inspect(self, *, node_id: str) -> Mapping[str, Any]:
"""
Inspect a node
Args:
node_id: The ID or name of the node
"""
response = await self.docker._query_json(
"nodes/{node_id}".format(node_id=node_id), method="GET"
)
return response | python | async def inspect(self, *, node_id: str) -> Mapping[str, Any]:
"""
Inspect a node
Args:
node_id: The ID or name of the node
"""
response = await self.docker._query_json(
"nodes/{node_id}".format(node_id=node_id), method="GET"
)
return response | [
"async",
"def",
"inspect",
"(",
"self",
",",
"*",
",",
"node_id",
":",
"str",
")",
"->",
"Mapping",
"[",
"str",
",",
"Any",
"]",
":",
"response",
"=",
"await",
"self",
".",
"docker",
".",
"_query_json",
"(",
"\"nodes/{node_id}\"",
".",
"format",
"(",
... | Inspect a node
Args:
node_id: The ID or name of the node | [
"Inspect",
"a",
"node"
] | 88d0285ddba8e606ff684278e0a831347209189c | https://github.com/aio-libs/aiodocker/blob/88d0285ddba8e606ff684278e0a831347209189c/aiodocker/nodes.py#L30-L41 | train | 199,261 |
aio-libs/aiodocker | aiodocker/nodes.py | DockerSwarmNodes.update | async def update(
self, *, node_id: str, version: int, spec: Mapping[str, Any]
) -> Mapping[str, Any]:
"""
Update the spec of a node.
Args:
node_id: The ID or name of the node
version: version number of the node being updated
spec: fields to be updated
"""
params = {"version": version}
if "Role" in spec:
assert spec["Role"] in {"worker", "manager"}
if "Availability" in spec:
assert spec["Availability"] in {"active", "pause", "drain"}
response = await self.docker._query_json(
"nodes/{node_id}/update".format(node_id=node_id),
method="POST",
params=params,
data=spec,
)
return response | python | async def update(
self, *, node_id: str, version: int, spec: Mapping[str, Any]
) -> Mapping[str, Any]:
"""
Update the spec of a node.
Args:
node_id: The ID or name of the node
version: version number of the node being updated
spec: fields to be updated
"""
params = {"version": version}
if "Role" in spec:
assert spec["Role"] in {"worker", "manager"}
if "Availability" in spec:
assert spec["Availability"] in {"active", "pause", "drain"}
response = await self.docker._query_json(
"nodes/{node_id}/update".format(node_id=node_id),
method="POST",
params=params,
data=spec,
)
return response | [
"async",
"def",
"update",
"(",
"self",
",",
"*",
",",
"node_id",
":",
"str",
",",
"version",
":",
"int",
",",
"spec",
":",
"Mapping",
"[",
"str",
",",
"Any",
"]",
")",
"->",
"Mapping",
"[",
"str",
",",
"Any",
"]",
":",
"params",
"=",
"{",
"\"ve... | Update the spec of a node.
Args:
node_id: The ID or name of the node
version: version number of the node being updated
spec: fields to be updated | [
"Update",
"the",
"spec",
"of",
"a",
"node",
"."
] | 88d0285ddba8e606ff684278e0a831347209189c | https://github.com/aio-libs/aiodocker/blob/88d0285ddba8e606ff684278e0a831347209189c/aiodocker/nodes.py#L43-L69 | train | 199,262 |
aio-libs/aiodocker | aiodocker/nodes.py | DockerSwarmNodes.remove | async def remove(self, *, node_id: str, force: bool = False) -> Mapping[str, Any]:
"""
Remove a node from a swarm.
Args:
node_id: The ID or name of the node
"""
params = {"force": force}
response = await self.docker._query_json(
"nodes/{node_id}".format(node_id=node_id), method="DELETE", params=params
)
return response | python | async def remove(self, *, node_id: str, force: bool = False) -> Mapping[str, Any]:
"""
Remove a node from a swarm.
Args:
node_id: The ID or name of the node
"""
params = {"force": force}
response = await self.docker._query_json(
"nodes/{node_id}".format(node_id=node_id), method="DELETE", params=params
)
return response | [
"async",
"def",
"remove",
"(",
"self",
",",
"*",
",",
"node_id",
":",
"str",
",",
"force",
":",
"bool",
"=",
"False",
")",
"->",
"Mapping",
"[",
"str",
",",
"Any",
"]",
":",
"params",
"=",
"{",
"\"force\"",
":",
"force",
"}",
"response",
"=",
"aw... | Remove a node from a swarm.
Args:
node_id: The ID or name of the node | [
"Remove",
"a",
"node",
"from",
"a",
"swarm",
"."
] | 88d0285ddba8e606ff684278e0a831347209189c | https://github.com/aio-libs/aiodocker/blob/88d0285ddba8e606ff684278e0a831347209189c/aiodocker/nodes.py#L71-L84 | train | 199,263 |
aio-libs/aiodocker | aiodocker/docker.py | Docker._query | async def _query(
self,
path,
method="GET",
*,
params=None,
data=None,
headers=None,
timeout=None,
chunked=None
):
"""
Get the response object by performing the HTTP request.
The caller is responsible to finalize the response object.
"""
url = self._canonicalize_url(path)
if headers and "content-type" not in headers:
headers["content-type"] = "application/json"
try:
response = await self.session.request(
method,
url,
params=httpize(params),
headers=headers,
data=data,
timeout=timeout,
chunked=chunked,
)
except asyncio.TimeoutError:
raise
if (response.status // 100) in [4, 5]:
what = await response.read()
content_type = response.headers.get("content-type", "")
response.close()
if content_type == "application/json":
raise DockerError(response.status, json.loads(what.decode("utf8")))
else:
raise DockerError(response.status, {"message": what.decode("utf8")})
return response | python | async def _query(
self,
path,
method="GET",
*,
params=None,
data=None,
headers=None,
timeout=None,
chunked=None
):
"""
Get the response object by performing the HTTP request.
The caller is responsible to finalize the response object.
"""
url = self._canonicalize_url(path)
if headers and "content-type" not in headers:
headers["content-type"] = "application/json"
try:
response = await self.session.request(
method,
url,
params=httpize(params),
headers=headers,
data=data,
timeout=timeout,
chunked=chunked,
)
except asyncio.TimeoutError:
raise
if (response.status // 100) in [4, 5]:
what = await response.read()
content_type = response.headers.get("content-type", "")
response.close()
if content_type == "application/json":
raise DockerError(response.status, json.loads(what.decode("utf8")))
else:
raise DockerError(response.status, {"message": what.decode("utf8")})
return response | [
"async",
"def",
"_query",
"(",
"self",
",",
"path",
",",
"method",
"=",
"\"GET\"",
",",
"*",
",",
"params",
"=",
"None",
",",
"data",
"=",
"None",
",",
"headers",
"=",
"None",
",",
"timeout",
"=",
"None",
",",
"chunked",
"=",
"None",
")",
":",
"u... | Get the response object by performing the HTTP request.
The caller is responsible to finalize the response object. | [
"Get",
"the",
"response",
"object",
"by",
"performing",
"the",
"HTTP",
"request",
".",
"The",
"caller",
"is",
"responsible",
"to",
"finalize",
"the",
"response",
"object",
"."
] | 88d0285ddba8e606ff684278e0a831347209189c | https://github.com/aio-libs/aiodocker/blob/88d0285ddba8e606ff684278e0a831347209189c/aiodocker/docker.py#L136-L174 | train | 199,264 |
aio-libs/aiodocker | aiodocker/docker.py | Docker._query_chunked_post | async def _query_chunked_post(
self, path, method="POST", *, params=None, data=None, headers=None, timeout=None
):
"""
A shorthand for uploading data by chunks
"""
if headers is None:
headers = {}
if headers and "content-type" not in headers:
headers["content-type"] = "application/octet-stream"
response = await self._query(
path,
method,
params=params,
data=data,
headers=headers,
timeout=timeout,
chunked=True,
)
return response | python | async def _query_chunked_post(
self, path, method="POST", *, params=None, data=None, headers=None, timeout=None
):
"""
A shorthand for uploading data by chunks
"""
if headers is None:
headers = {}
if headers and "content-type" not in headers:
headers["content-type"] = "application/octet-stream"
response = await self._query(
path,
method,
params=params,
data=data,
headers=headers,
timeout=timeout,
chunked=True,
)
return response | [
"async",
"def",
"_query_chunked_post",
"(",
"self",
",",
"path",
",",
"method",
"=",
"\"POST\"",
",",
"*",
",",
"params",
"=",
"None",
",",
"data",
"=",
"None",
",",
"headers",
"=",
"None",
",",
"timeout",
"=",
"None",
")",
":",
"if",
"headers",
"is"... | A shorthand for uploading data by chunks | [
"A",
"shorthand",
"for",
"uploading",
"data",
"by",
"chunks"
] | 88d0285ddba8e606ff684278e0a831347209189c | https://github.com/aio-libs/aiodocker/blob/88d0285ddba8e606ff684278e0a831347209189c/aiodocker/docker.py#L193-L212 | train | 199,265 |
aio-libs/aiodocker | aiodocker/swarm.py | DockerSwarm.init | async def init(
self,
*,
advertise_addr: str = None,
listen_addr: str = "0.0.0.0:2377",
force_new_cluster: bool = False,
swarm_spec: Mapping = None
) -> str:
"""
Initialize a new swarm.
Args:
ListenAddr: listen address used for inter-manager communication
AdvertiseAddr: address advertised to other nodes.
ForceNewCluster: Force creation of a new swarm.
SwarmSpec: User modifiable swarm configuration.
Returns:
id of the swarm node
"""
data = {
"AdvertiseAddr": advertise_addr,
"ListenAddr": listen_addr,
"ForceNewCluster": force_new_cluster,
"Spec": swarm_spec,
}
response = await self.docker._query_json("swarm/init", method="POST", data=data)
return response | python | async def init(
self,
*,
advertise_addr: str = None,
listen_addr: str = "0.0.0.0:2377",
force_new_cluster: bool = False,
swarm_spec: Mapping = None
) -> str:
"""
Initialize a new swarm.
Args:
ListenAddr: listen address used for inter-manager communication
AdvertiseAddr: address advertised to other nodes.
ForceNewCluster: Force creation of a new swarm.
SwarmSpec: User modifiable swarm configuration.
Returns:
id of the swarm node
"""
data = {
"AdvertiseAddr": advertise_addr,
"ListenAddr": listen_addr,
"ForceNewCluster": force_new_cluster,
"Spec": swarm_spec,
}
response = await self.docker._query_json("swarm/init", method="POST", data=data)
return response | [
"async",
"def",
"init",
"(",
"self",
",",
"*",
",",
"advertise_addr",
":",
"str",
"=",
"None",
",",
"listen_addr",
":",
"str",
"=",
"\"0.0.0.0:2377\"",
",",
"force_new_cluster",
":",
"bool",
"=",
"False",
",",
"swarm_spec",
":",
"Mapping",
"=",
"None",
"... | Initialize a new swarm.
Args:
ListenAddr: listen address used for inter-manager communication
AdvertiseAddr: address advertised to other nodes.
ForceNewCluster: Force creation of a new swarm.
SwarmSpec: User modifiable swarm configuration.
Returns:
id of the swarm node | [
"Initialize",
"a",
"new",
"swarm",
"."
] | 88d0285ddba8e606ff684278e0a831347209189c | https://github.com/aio-libs/aiodocker/blob/88d0285ddba8e606ff684278e0a831347209189c/aiodocker/swarm.py#L10-L40 | train | 199,266 |
aio-libs/aiodocker | aiodocker/swarm.py | DockerSwarm.join | async def join(
self,
*,
remote_addrs: Iterable[str],
listen_addr: str = "0.0.0.0:2377",
join_token: str,
advertise_addr: str = None,
data_path_addr: str = None
) -> bool:
"""
Join a swarm.
Args:
listen_addr
Used for inter-manager communication
advertise_addr
Externally reachable address advertised to other nodes.
data_path_addr
Address or interface to use for data path traffic.
remote_addrs
Addresses of manager nodes already participating in the swarm.
join_token
Secret token for joining this swarm.
"""
data = {
"RemoteAddrs": list(remote_addrs),
"JoinToken": join_token,
"ListenAddr": listen_addr,
"AdvertiseAddr": advertise_addr,
"DataPathAddr": data_path_addr,
}
await self.docker._query("swarm/join", method="POST", data=clean_map(data))
return True | python | async def join(
self,
*,
remote_addrs: Iterable[str],
listen_addr: str = "0.0.0.0:2377",
join_token: str,
advertise_addr: str = None,
data_path_addr: str = None
) -> bool:
"""
Join a swarm.
Args:
listen_addr
Used for inter-manager communication
advertise_addr
Externally reachable address advertised to other nodes.
data_path_addr
Address or interface to use for data path traffic.
remote_addrs
Addresses of manager nodes already participating in the swarm.
join_token
Secret token for joining this swarm.
"""
data = {
"RemoteAddrs": list(remote_addrs),
"JoinToken": join_token,
"ListenAddr": listen_addr,
"AdvertiseAddr": advertise_addr,
"DataPathAddr": data_path_addr,
}
await self.docker._query("swarm/join", method="POST", data=clean_map(data))
return True | [
"async",
"def",
"join",
"(",
"self",
",",
"*",
",",
"remote_addrs",
":",
"Iterable",
"[",
"str",
"]",
",",
"listen_addr",
":",
"str",
"=",
"\"0.0.0.0:2377\"",
",",
"join_token",
":",
"str",
",",
"advertise_addr",
":",
"str",
"=",
"None",
",",
"data_path_... | Join a swarm.
Args:
listen_addr
Used for inter-manager communication
advertise_addr
Externally reachable address advertised to other nodes.
data_path_addr
Address or interface to use for data path traffic.
remote_addrs
Addresses of manager nodes already participating in the swarm.
join_token
Secret token for joining this swarm. | [
"Join",
"a",
"swarm",
"."
] | 88d0285ddba8e606ff684278e0a831347209189c | https://github.com/aio-libs/aiodocker/blob/88d0285ddba8e606ff684278e0a831347209189c/aiodocker/swarm.py#L54-L93 | train | 199,267 |
aio-libs/aiodocker | aiodocker/services.py | DockerServices.list | async def list(self, *, filters: Mapping = None) -> List[Mapping]:
"""
Return a list of services
Args:
filters: a dict with a list of filters
Available filters:
id=<service id>
label=<service label>
mode=["replicated"|"global"]
name=<service name>
"""
params = {"filters": clean_filters(filters)}
response = await self.docker._query_json(
"services", method="GET", params=params
)
return response | python | async def list(self, *, filters: Mapping = None) -> List[Mapping]:
"""
Return a list of services
Args:
filters: a dict with a list of filters
Available filters:
id=<service id>
label=<service label>
mode=["replicated"|"global"]
name=<service name>
"""
params = {"filters": clean_filters(filters)}
response = await self.docker._query_json(
"services", method="GET", params=params
)
return response | [
"async",
"def",
"list",
"(",
"self",
",",
"*",
",",
"filters",
":",
"Mapping",
"=",
"None",
")",
"->",
"List",
"[",
"Mapping",
"]",
":",
"params",
"=",
"{",
"\"filters\"",
":",
"clean_filters",
"(",
"filters",
")",
"}",
"response",
"=",
"await",
"sel... | Return a list of services
Args:
filters: a dict with a list of filters
Available filters:
id=<service id>
label=<service label>
mode=["replicated"|"global"]
name=<service name> | [
"Return",
"a",
"list",
"of",
"services"
] | 88d0285ddba8e606ff684278e0a831347209189c | https://github.com/aio-libs/aiodocker/blob/88d0285ddba8e606ff684278e0a831347209189c/aiodocker/services.py#L17-L36 | train | 199,268 |
aio-libs/aiodocker | aiodocker/services.py | DockerServices.update | async def update(
self,
service_id: str,
version: str,
*,
image: str = None,
rollback: bool = False
) -> bool:
"""
Update a service.
If rollback is True image will be ignored.
Args:
service_id: ID or name of the service.
version: Version of the service that you want to update.
rollback: Rollback the service to the previous service spec.
Returns:
True if successful.
"""
if image is None and rollback is False:
raise ValueError("You need to specify an image.")
inspect_service = await self.inspect(service_id)
spec = inspect_service["Spec"]
if image is not None:
spec["TaskTemplate"]["ContainerSpec"]["Image"] = image
params = {"version": version}
if rollback is True:
params["rollback"] = "previous"
data = json.dumps(clean_map(spec))
await self.docker._query_json(
"services/{service_id}/update".format(service_id=service_id),
method="POST",
data=data,
params=params,
)
return True | python | async def update(
self,
service_id: str,
version: str,
*,
image: str = None,
rollback: bool = False
) -> bool:
"""
Update a service.
If rollback is True image will be ignored.
Args:
service_id: ID or name of the service.
version: Version of the service that you want to update.
rollback: Rollback the service to the previous service spec.
Returns:
True if successful.
"""
if image is None and rollback is False:
raise ValueError("You need to specify an image.")
inspect_service = await self.inspect(service_id)
spec = inspect_service["Spec"]
if image is not None:
spec["TaskTemplate"]["ContainerSpec"]["Image"] = image
params = {"version": version}
if rollback is True:
params["rollback"] = "previous"
data = json.dumps(clean_map(spec))
await self.docker._query_json(
"services/{service_id}/update".format(service_id=service_id),
method="POST",
data=data,
params=params,
)
return True | [
"async",
"def",
"update",
"(",
"self",
",",
"service_id",
":",
"str",
",",
"version",
":",
"str",
",",
"*",
",",
"image",
":",
"str",
"=",
"None",
",",
"rollback",
":",
"bool",
"=",
"False",
")",
"->",
"bool",
":",
"if",
"image",
"is",
"None",
"a... | Update a service.
If rollback is True image will be ignored.
Args:
service_id: ID or name of the service.
version: Version of the service that you want to update.
rollback: Rollback the service to the previous service spec.
Returns:
True if successful. | [
"Update",
"a",
"service",
".",
"If",
"rollback",
"is",
"True",
"image",
"will",
"be",
"ignored",
"."
] | 88d0285ddba8e606ff684278e0a831347209189c | https://github.com/aio-libs/aiodocker/blob/88d0285ddba8e606ff684278e0a831347209189c/aiodocker/services.py#L109-L150 | train | 199,269 |
aio-libs/aiodocker | aiodocker/services.py | DockerServices.delete | async def delete(self, service_id: str) -> bool:
"""
Remove a service
Args:
service_id: ID or name of the service
Returns:
True if successful
"""
await self.docker._query(
"services/{service_id}".format(service_id=service_id), method="DELETE"
)
return True | python | async def delete(self, service_id: str) -> bool:
"""
Remove a service
Args:
service_id: ID or name of the service
Returns:
True if successful
"""
await self.docker._query(
"services/{service_id}".format(service_id=service_id), method="DELETE"
)
return True | [
"async",
"def",
"delete",
"(",
"self",
",",
"service_id",
":",
"str",
")",
"->",
"bool",
":",
"await",
"self",
".",
"docker",
".",
"_query",
"(",
"\"services/{service_id}\"",
".",
"format",
"(",
"service_id",
"=",
"service_id",
")",
",",
"method",
"=",
"... | Remove a service
Args:
service_id: ID or name of the service
Returns:
True if successful | [
"Remove",
"a",
"service"
] | 88d0285ddba8e606ff684278e0a831347209189c | https://github.com/aio-libs/aiodocker/blob/88d0285ddba8e606ff684278e0a831347209189c/aiodocker/services.py#L152-L166 | train | 199,270 |
aio-libs/aiodocker | aiodocker/services.py | DockerServices.inspect | async def inspect(self, service_id: str) -> Mapping[str, Any]:
"""
Inspect a service
Args:
service_id: ID or name of the service
Returns:
a dict with info about a service
"""
response = await self.docker._query_json(
"services/{service_id}".format(service_id=service_id), method="GET"
)
return response | python | async def inspect(self, service_id: str) -> Mapping[str, Any]:
"""
Inspect a service
Args:
service_id: ID or name of the service
Returns:
a dict with info about a service
"""
response = await self.docker._query_json(
"services/{service_id}".format(service_id=service_id), method="GET"
)
return response | [
"async",
"def",
"inspect",
"(",
"self",
",",
"service_id",
":",
"str",
")",
"->",
"Mapping",
"[",
"str",
",",
"Any",
"]",
":",
"response",
"=",
"await",
"self",
".",
"docker",
".",
"_query_json",
"(",
"\"services/{service_id}\"",
".",
"format",
"(",
"ser... | Inspect a service
Args:
service_id: ID or name of the service
Returns:
a dict with info about a service | [
"Inspect",
"a",
"service"
] | 88d0285ddba8e606ff684278e0a831347209189c | https://github.com/aio-libs/aiodocker/blob/88d0285ddba8e606ff684278e0a831347209189c/aiodocker/services.py#L168-L182 | train | 199,271 |
aio-libs/aiodocker | aiodocker/services.py | DockerServices.logs | async def logs(
self,
service_id: str,
*,
details: bool = False,
follow: bool = False,
stdout: bool = False,
stderr: bool = False,
since: int = 0,
timestamps: bool = False,
is_tty: bool = False,
tail: str = "all"
) -> Union[str, AsyncIterator[str]]:
"""
Retrieve logs of the given service
Args:
details: show service context and extra details provided to logs
follow: return the logs as a stream.
stdout: return logs from stdout
stderr: return logs from stderr
since: return logs since this time, as a UNIX timestamp
timestamps: add timestamps to every log line
is_tty: the service has a pseudo-TTY allocated
tail: only return this number of log lines
from the end of the logs, specify as an integer
or `all` to output all log lines.
"""
if stdout is False and stderr is False:
raise TypeError("Need one of stdout or stderr")
params = {
"details": details,
"follow": follow,
"stdout": stdout,
"stderr": stderr,
"since": since,
"timestamps": timestamps,
"tail": tail,
}
response = await self.docker._query(
"services/{service_id}/logs".format(service_id=service_id),
method="GET",
params=params,
)
return await multiplexed_result(response, follow, is_tty=is_tty) | python | async def logs(
self,
service_id: str,
*,
details: bool = False,
follow: bool = False,
stdout: bool = False,
stderr: bool = False,
since: int = 0,
timestamps: bool = False,
is_tty: bool = False,
tail: str = "all"
) -> Union[str, AsyncIterator[str]]:
"""
Retrieve logs of the given service
Args:
details: show service context and extra details provided to logs
follow: return the logs as a stream.
stdout: return logs from stdout
stderr: return logs from stderr
since: return logs since this time, as a UNIX timestamp
timestamps: add timestamps to every log line
is_tty: the service has a pseudo-TTY allocated
tail: only return this number of log lines
from the end of the logs, specify as an integer
or `all` to output all log lines.
"""
if stdout is False and stderr is False:
raise TypeError("Need one of stdout or stderr")
params = {
"details": details,
"follow": follow,
"stdout": stdout,
"stderr": stderr,
"since": since,
"timestamps": timestamps,
"tail": tail,
}
response = await self.docker._query(
"services/{service_id}/logs".format(service_id=service_id),
method="GET",
params=params,
)
return await multiplexed_result(response, follow, is_tty=is_tty) | [
"async",
"def",
"logs",
"(",
"self",
",",
"service_id",
":",
"str",
",",
"*",
",",
"details",
":",
"bool",
"=",
"False",
",",
"follow",
":",
"bool",
"=",
"False",
",",
"stdout",
":",
"bool",
"=",
"False",
",",
"stderr",
":",
"bool",
"=",
"False",
... | Retrieve logs of the given service
Args:
details: show service context and extra details provided to logs
follow: return the logs as a stream.
stdout: return logs from stdout
stderr: return logs from stderr
since: return logs since this time, as a UNIX timestamp
timestamps: add timestamps to every log line
is_tty: the service has a pseudo-TTY allocated
tail: only return this number of log lines
from the end of the logs, specify as an integer
or `all` to output all log lines. | [
"Retrieve",
"logs",
"of",
"the",
"given",
"service"
] | 88d0285ddba8e606ff684278e0a831347209189c | https://github.com/aio-libs/aiodocker/blob/88d0285ddba8e606ff684278e0a831347209189c/aiodocker/services.py#L184-L232 | train | 199,272 |
pixelogik/NearPy | nearpy/storage/storage_memory.py | MemoryStorage.store_many_vectors | def store_many_vectors(self, hash_name, bucket_keys, vs, data):
"""
Store a batch of vectors.
Stores vector and JSON-serializable data in bucket with specified key.
"""
if data is None:
data = itertools.repeat(data)
for v, k, d in zip(vs, bucket_keys, data):
self.store_vector(hash_name, k, v, d) | python | def store_many_vectors(self, hash_name, bucket_keys, vs, data):
"""
Store a batch of vectors.
Stores vector and JSON-serializable data in bucket with specified key.
"""
if data is None:
data = itertools.repeat(data)
for v, k, d in zip(vs, bucket_keys, data):
self.store_vector(hash_name, k, v, d) | [
"def",
"store_many_vectors",
"(",
"self",
",",
"hash_name",
",",
"bucket_keys",
",",
"vs",
",",
"data",
")",
":",
"if",
"data",
"is",
"None",
":",
"data",
"=",
"itertools",
".",
"repeat",
"(",
"data",
")",
"for",
"v",
",",
"k",
",",
"d",
"in",
"zip... | Store a batch of vectors.
Stores vector and JSON-serializable data in bucket with specified key. | [
"Store",
"a",
"batch",
"of",
"vectors",
".",
"Stores",
"vector",
"and",
"JSON",
"-",
"serializable",
"data",
"in",
"bucket",
"with",
"specified",
"key",
"."
] | 1b534b864d320d875508e95cd2b76b6d8c07a90b | https://github.com/pixelogik/NearPy/blob/1b534b864d320d875508e95cd2b76b6d8c07a90b/nearpy/storage/storage_memory.py#L55-L63 | train | 199,273 |
pixelogik/NearPy | nearpy/hashes/randombinaryprojectiontree.py | RandomBinaryProjectionTreeNode.collect_all_bucket_keys | def collect_all_bucket_keys(self):
"""
Just collects all buckets keys from subtree
"""
if len(self.childs) == 0:
# This is a leaf so just return the bucket key (we reached the bucket leaf)
#print 'Returning (collect) leaf bucket key %s with %d vectors' % (self.bucket_key, self.vector_count)
return [self.bucket_key]
# Not leaf, return results of childs
result = []
for child in self.childs.values():
result = result + child.collect_all_bucket_keys()
return result | python | def collect_all_bucket_keys(self):
"""
Just collects all buckets keys from subtree
"""
if len(self.childs) == 0:
# This is a leaf so just return the bucket key (we reached the bucket leaf)
#print 'Returning (collect) leaf bucket key %s with %d vectors' % (self.bucket_key, self.vector_count)
return [self.bucket_key]
# Not leaf, return results of childs
result = []
for child in self.childs.values():
result = result + child.collect_all_bucket_keys()
return result | [
"def",
"collect_all_bucket_keys",
"(",
"self",
")",
":",
"if",
"len",
"(",
"self",
".",
"childs",
")",
"==",
"0",
":",
"# This is a leaf so just return the bucket key (we reached the bucket leaf)",
"#print 'Returning (collect) leaf bucket key %s with %d vectors' % (self.bucket_key,... | Just collects all buckets keys from subtree | [
"Just",
"collects",
"all",
"buckets",
"keys",
"from",
"subtree"
] | 1b534b864d320d875508e95cd2b76b6d8c07a90b | https://github.com/pixelogik/NearPy/blob/1b534b864d320d875508e95cd2b76b6d8c07a90b/nearpy/hashes/randombinaryprojectiontree.py#L70-L84 | train | 199,274 |
pixelogik/NearPy | nearpy/hashes/randombinaryprojectiontree.py | RandomBinaryProjectionTreeNode.bucket_keys_to_guarantee_result_set_size | def bucket_keys_to_guarantee_result_set_size(self, bucket_key, N, tree_depth):
"""
Returns list of bucket keys based on the specified bucket key
and minimum result size N.
"""
if tree_depth == len(bucket_key):
#print 'Returning leaf bucket key %s with %d vectors' % (self.bucket_key, self.vector_count)
# This is a leaf so just return the bucket key (we reached the bucket leaf)
return [self.bucket_key]
# If not leaf, this is a subtree node.
hash_char = bucket_key[tree_depth]
if hash_char == '0':
other_hash_char = '1'
else:
other_hash_char = '0'
# Check if child has enough results
if hash_char in self.childs:
if self.childs[hash_char].vector_count < N:
# If not combine buckets of both child subtrees
listA = self.childs[hash_char].collect_all_bucket_keys()
listB = self.childs[other_hash_char].collect_all_bucket_keys()
return listA + listB
else:
# Child subtree has enough results, so call method on child
return self.childs[hash_char].bucket_keys_to_guarantee_result_set_size(bucket_key, N, tree_depth+1)
else:
# That subtree is not existing, so just follow the other side
return self.childs[other_hash_char].bucket_keys_to_guarantee_result_set_size(bucket_key, N, tree_depth+1) | python | def bucket_keys_to_guarantee_result_set_size(self, bucket_key, N, tree_depth):
"""
Returns list of bucket keys based on the specified bucket key
and minimum result size N.
"""
if tree_depth == len(bucket_key):
#print 'Returning leaf bucket key %s with %d vectors' % (self.bucket_key, self.vector_count)
# This is a leaf so just return the bucket key (we reached the bucket leaf)
return [self.bucket_key]
# If not leaf, this is a subtree node.
hash_char = bucket_key[tree_depth]
if hash_char == '0':
other_hash_char = '1'
else:
other_hash_char = '0'
# Check if child has enough results
if hash_char in self.childs:
if self.childs[hash_char].vector_count < N:
# If not combine buckets of both child subtrees
listA = self.childs[hash_char].collect_all_bucket_keys()
listB = self.childs[other_hash_char].collect_all_bucket_keys()
return listA + listB
else:
# Child subtree has enough results, so call method on child
return self.childs[hash_char].bucket_keys_to_guarantee_result_set_size(bucket_key, N, tree_depth+1)
else:
# That subtree is not existing, so just follow the other side
return self.childs[other_hash_char].bucket_keys_to_guarantee_result_set_size(bucket_key, N, tree_depth+1) | [
"def",
"bucket_keys_to_guarantee_result_set_size",
"(",
"self",
",",
"bucket_key",
",",
"N",
",",
"tree_depth",
")",
":",
"if",
"tree_depth",
"==",
"len",
"(",
"bucket_key",
")",
":",
"#print 'Returning leaf bucket key %s with %d vectors' % (self.bucket_key, self.vector_count... | Returns list of bucket keys based on the specified bucket key
and minimum result size N. | [
"Returns",
"list",
"of",
"bucket",
"keys",
"based",
"on",
"the",
"specified",
"bucket",
"key",
"and",
"minimum",
"result",
"size",
"N",
"."
] | 1b534b864d320d875508e95cd2b76b6d8c07a90b | https://github.com/pixelogik/NearPy/blob/1b534b864d320d875508e95cd2b76b6d8c07a90b/nearpy/hashes/randombinaryprojectiontree.py#L86-L117 | train | 199,275 |
pixelogik/NearPy | nearpy/storage/storage_mongo.py | MongoStorage.store_vector | def store_vector(self, hash_name, bucket_key, v, data):
"""
Stores vector and JSON-serializable data in MongoDB with specified key.
"""
mongo_key = self._format_mongo_key(hash_name, bucket_key)
val_dict = {}
val_dict['lsh'] = mongo_key
# Depending on type (sparse or not) fill value dict
if scipy.sparse.issparse(v):
# Make sure that we are using COO format (easy to handle)
if not scipy.sparse.isspmatrix_coo(v):
v = scipy.sparse.coo_matrix(v)
# Construct list of [index, value] items,
# one for each non-zero element of the sparse vector
encoded_values = []
for k in range(v.data.size):
row_index = v.row[k]
value = v.data[k]
encoded_values.append([int(row_index), value])
val_dict['sparse'] = 1
val_dict['nonzeros'] = encoded_values
val_dict['dim'] = v.shape[0]
else:
# Make sure it is a 1d vector
v = numpy.reshape(v, v.shape[0])
val_dict['vector'] = v.tostring()
val_dict['dtype'] = v.dtype.name
# Add data if set
if data is not None:
val_dict['data'] = data
# Push JSON representation of dict to end of bucket list
self.mongo_object.insert_one(val_dict) | python | def store_vector(self, hash_name, bucket_key, v, data):
"""
Stores vector and JSON-serializable data in MongoDB with specified key.
"""
mongo_key = self._format_mongo_key(hash_name, bucket_key)
val_dict = {}
val_dict['lsh'] = mongo_key
# Depending on type (sparse or not) fill value dict
if scipy.sparse.issparse(v):
# Make sure that we are using COO format (easy to handle)
if not scipy.sparse.isspmatrix_coo(v):
v = scipy.sparse.coo_matrix(v)
# Construct list of [index, value] items,
# one for each non-zero element of the sparse vector
encoded_values = []
for k in range(v.data.size):
row_index = v.row[k]
value = v.data[k]
encoded_values.append([int(row_index), value])
val_dict['sparse'] = 1
val_dict['nonzeros'] = encoded_values
val_dict['dim'] = v.shape[0]
else:
# Make sure it is a 1d vector
v = numpy.reshape(v, v.shape[0])
val_dict['vector'] = v.tostring()
val_dict['dtype'] = v.dtype.name
# Add data if set
if data is not None:
val_dict['data'] = data
# Push JSON representation of dict to end of bucket list
self.mongo_object.insert_one(val_dict) | [
"def",
"store_vector",
"(",
"self",
",",
"hash_name",
",",
"bucket_key",
",",
"v",
",",
"data",
")",
":",
"mongo_key",
"=",
"self",
".",
"_format_mongo_key",
"(",
"hash_name",
",",
"bucket_key",
")",
"val_dict",
"=",
"{",
"}",
"val_dict",
"[",
"'lsh'",
"... | Stores vector and JSON-serializable data in MongoDB with specified key. | [
"Stores",
"vector",
"and",
"JSON",
"-",
"serializable",
"data",
"in",
"MongoDB",
"with",
"specified",
"key",
"."
] | 1b534b864d320d875508e95cd2b76b6d8c07a90b | https://github.com/pixelogik/NearPy/blob/1b534b864d320d875508e95cd2b76b6d8c07a90b/nearpy/storage/storage_mongo.py#L48-L87 | train | 199,276 |
pixelogik/NearPy | nearpy/utils/utils.py | numpy_array_from_list_or_numpy_array | def numpy_array_from_list_or_numpy_array(vectors):
"""
Returns numpy array representation of argument.
Argument maybe numpy array (input is returned)
or a list of numpy vectors.
"""
# If vectors is not a numpy matrix, create one
if not isinstance(vectors, numpy.ndarray):
V = numpy.zeros((vectors[0].shape[0], len(vectors)))
for index in range(len(vectors)):
vector = vectors[index]
V[:, index] = vector
return V
return vectors | python | def numpy_array_from_list_or_numpy_array(vectors):
"""
Returns numpy array representation of argument.
Argument maybe numpy array (input is returned)
or a list of numpy vectors.
"""
# If vectors is not a numpy matrix, create one
if not isinstance(vectors, numpy.ndarray):
V = numpy.zeros((vectors[0].shape[0], len(vectors)))
for index in range(len(vectors)):
vector = vectors[index]
V[:, index] = vector
return V
return vectors | [
"def",
"numpy_array_from_list_or_numpy_array",
"(",
"vectors",
")",
":",
"# If vectors is not a numpy matrix, create one",
"if",
"not",
"isinstance",
"(",
"vectors",
",",
"numpy",
".",
"ndarray",
")",
":",
"V",
"=",
"numpy",
".",
"zeros",
"(",
"(",
"vectors",
"[",... | Returns numpy array representation of argument.
Argument maybe numpy array (input is returned)
or a list of numpy vectors. | [
"Returns",
"numpy",
"array",
"representation",
"of",
"argument",
"."
] | 1b534b864d320d875508e95cd2b76b6d8c07a90b | https://github.com/pixelogik/NearPy/blob/1b534b864d320d875508e95cd2b76b6d8c07a90b/nearpy/utils/utils.py#L28-L43 | train | 199,277 |
pixelogik/NearPy | nearpy/utils/utils.py | unitvec | def unitvec(vec):
"""
Scale a vector to unit length. The only exception is the zero vector, which
is returned back unchanged.
"""
if scipy.sparse.issparse(vec): # convert scipy.sparse to standard numpy array
vec = vec.tocsr()
veclen = numpy.sqrt(numpy.sum(vec.data ** 2))
if veclen > 0.0:
return vec / veclen
else:
return vec
if isinstance(vec, numpy.ndarray):
vec = numpy.asarray(vec, dtype=float)
veclen = numpy.linalg.norm(vec)
if veclen > 0.0:
return vec / veclen
else:
return vec | python | def unitvec(vec):
"""
Scale a vector to unit length. The only exception is the zero vector, which
is returned back unchanged.
"""
if scipy.sparse.issparse(vec): # convert scipy.sparse to standard numpy array
vec = vec.tocsr()
veclen = numpy.sqrt(numpy.sum(vec.data ** 2))
if veclen > 0.0:
return vec / veclen
else:
return vec
if isinstance(vec, numpy.ndarray):
vec = numpy.asarray(vec, dtype=float)
veclen = numpy.linalg.norm(vec)
if veclen > 0.0:
return vec / veclen
else:
return vec | [
"def",
"unitvec",
"(",
"vec",
")",
":",
"if",
"scipy",
".",
"sparse",
".",
"issparse",
"(",
"vec",
")",
":",
"# convert scipy.sparse to standard numpy array",
"vec",
"=",
"vec",
".",
"tocsr",
"(",
")",
"veclen",
"=",
"numpy",
".",
"sqrt",
"(",
"numpy",
"... | Scale a vector to unit length. The only exception is the zero vector, which
is returned back unchanged. | [
"Scale",
"a",
"vector",
"to",
"unit",
"length",
".",
"The",
"only",
"exception",
"is",
"the",
"zero",
"vector",
"which",
"is",
"returned",
"back",
"unchanged",
"."
] | 1b534b864d320d875508e95cd2b76b6d8c07a90b | https://github.com/pixelogik/NearPy/blob/1b534b864d320d875508e95cd2b76b6d8c07a90b/nearpy/utils/utils.py#L46-L65 | train | 199,278 |
pixelogik/NearPy | nearpy/utils/utils.py | perform_pca | def perform_pca(A):
"""
Computes eigenvalues and eigenvectors of covariance matrix of A.
The rows of a correspond to observations, the columns to variables.
"""
# First subtract the mean
M = (A-numpy.mean(A.T, axis=1)).T
# Get eigenvectors and values of covariance matrix
return numpy.linalg.eig(numpy.cov(M)) | python | def perform_pca(A):
"""
Computes eigenvalues and eigenvectors of covariance matrix of A.
The rows of a correspond to observations, the columns to variables.
"""
# First subtract the mean
M = (A-numpy.mean(A.T, axis=1)).T
# Get eigenvectors and values of covariance matrix
return numpy.linalg.eig(numpy.cov(M)) | [
"def",
"perform_pca",
"(",
"A",
")",
":",
"# First subtract the mean",
"M",
"=",
"(",
"A",
"-",
"numpy",
".",
"mean",
"(",
"A",
".",
"T",
",",
"axis",
"=",
"1",
")",
")",
".",
"T",
"# Get eigenvectors and values of covariance matrix",
"return",
"numpy",
".... | Computes eigenvalues and eigenvectors of covariance matrix of A.
The rows of a correspond to observations, the columns to variables. | [
"Computes",
"eigenvalues",
"and",
"eigenvectors",
"of",
"covariance",
"matrix",
"of",
"A",
".",
"The",
"rows",
"of",
"a",
"correspond",
"to",
"observations",
"the",
"columns",
"to",
"variables",
"."
] | 1b534b864d320d875508e95cd2b76b6d8c07a90b | https://github.com/pixelogik/NearPy/blob/1b534b864d320d875508e95cd2b76b6d8c07a90b/nearpy/utils/utils.py#L68-L76 | train | 199,279 |
pixelogik/NearPy | nearpy/hashes/permutation/permute.py | Permute.permute | def permute(self, ba):
"""
Permute the bitarray ba inplace.
"""
c = ba.copy()
for i in xrange(len(self.mapping)):
ba[i] = c[self.mapping[i]]
return ba | python | def permute(self, ba):
"""
Permute the bitarray ba inplace.
"""
c = ba.copy()
for i in xrange(len(self.mapping)):
ba[i] = c[self.mapping[i]]
return ba | [
"def",
"permute",
"(",
"self",
",",
"ba",
")",
":",
"c",
"=",
"ba",
".",
"copy",
"(",
")",
"for",
"i",
"in",
"xrange",
"(",
"len",
"(",
"self",
".",
"mapping",
")",
")",
":",
"ba",
"[",
"i",
"]",
"=",
"c",
"[",
"self",
".",
"mapping",
"[",
... | Permute the bitarray ba inplace. | [
"Permute",
"the",
"bitarray",
"ba",
"inplace",
"."
] | 1b534b864d320d875508e95cd2b76b6d8c07a90b | https://github.com/pixelogik/NearPy/blob/1b534b864d320d875508e95cd2b76b6d8c07a90b/nearpy/hashes/permutation/permute.py#L53-L60 | train | 199,280 |
pixelogik/NearPy | nearpy/engine.py | Engine.store_vector | def store_vector(self, v, data=None):
"""
Hashes vector v and stores it in all matching buckets in the storage.
The data argument must be JSON-serializable. It is stored with the
vector and will be returned in search results.
"""
# We will store the normalized vector (used during retrieval)
nv = unitvec(v)
# Store vector in each bucket of all hashes
for lshash in self.lshashes:
for bucket_key in lshash.hash_vector(v):
#print 'Storying in bucket %s one vector' % bucket_key
self.storage.store_vector(lshash.hash_name, bucket_key,
nv, data) | python | def store_vector(self, v, data=None):
"""
Hashes vector v and stores it in all matching buckets in the storage.
The data argument must be JSON-serializable. It is stored with the
vector and will be returned in search results.
"""
# We will store the normalized vector (used during retrieval)
nv = unitvec(v)
# Store vector in each bucket of all hashes
for lshash in self.lshashes:
for bucket_key in lshash.hash_vector(v):
#print 'Storying in bucket %s one vector' % bucket_key
self.storage.store_vector(lshash.hash_name, bucket_key,
nv, data) | [
"def",
"store_vector",
"(",
"self",
",",
"v",
",",
"data",
"=",
"None",
")",
":",
"# We will store the normalized vector (used during retrieval)",
"nv",
"=",
"unitvec",
"(",
"v",
")",
"# Store vector in each bucket of all hashes",
"for",
"lshash",
"in",
"self",
".",
... | Hashes vector v and stores it in all matching buckets in the storage.
The data argument must be JSON-serializable. It is stored with the
vector and will be returned in search results. | [
"Hashes",
"vector",
"v",
"and",
"stores",
"it",
"in",
"all",
"matching",
"buckets",
"in",
"the",
"storage",
".",
"The",
"data",
"argument",
"must",
"be",
"JSON",
"-",
"serializable",
".",
"It",
"is",
"stored",
"with",
"the",
"vector",
"and",
"will",
"be"... | 1b534b864d320d875508e95cd2b76b6d8c07a90b | https://github.com/pixelogik/NearPy/blob/1b534b864d320d875508e95cd2b76b6d8c07a90b/nearpy/engine.py#L84-L97 | train | 199,281 |
pixelogik/NearPy | nearpy/engine.py | Engine.store_many_vectors | def store_many_vectors(self, vs, data=None):
"""
Store a batch of vectors.
Hashes vector vs and stores them in all matching buckets in the storage.
The data argument must be either None or a list of JSON-serializable
object. It is stored with the vector and will be returned in search
results.
"""
# We will store the normalized vector (used during retrieval)
nvs = [unitvec(i) for i in vs]
# Store vector in each bucket of all hashes
for lshash in self.lshashes:
bucket_keys = [lshash.hash_vector(i)[0] for i in vs]
self.storage.store_many_vectors(lshash.hash_name, bucket_keys,
nvs, data) | python | def store_many_vectors(self, vs, data=None):
"""
Store a batch of vectors.
Hashes vector vs and stores them in all matching buckets in the storage.
The data argument must be either None or a list of JSON-serializable
object. It is stored with the vector and will be returned in search
results.
"""
# We will store the normalized vector (used during retrieval)
nvs = [unitvec(i) for i in vs]
# Store vector in each bucket of all hashes
for lshash in self.lshashes:
bucket_keys = [lshash.hash_vector(i)[0] for i in vs]
self.storage.store_many_vectors(lshash.hash_name, bucket_keys,
nvs, data) | [
"def",
"store_many_vectors",
"(",
"self",
",",
"vs",
",",
"data",
"=",
"None",
")",
":",
"# We will store the normalized vector (used during retrieval)",
"nvs",
"=",
"[",
"unitvec",
"(",
"i",
")",
"for",
"i",
"in",
"vs",
"]",
"# Store vector in each bucket of all ha... | Store a batch of vectors.
Hashes vector vs and stores them in all matching buckets in the storage.
The data argument must be either None or a list of JSON-serializable
object. It is stored with the vector and will be returned in search
results. | [
"Store",
"a",
"batch",
"of",
"vectors",
".",
"Hashes",
"vector",
"vs",
"and",
"stores",
"them",
"in",
"all",
"matching",
"buckets",
"in",
"the",
"storage",
".",
"The",
"data",
"argument",
"must",
"be",
"either",
"None",
"or",
"a",
"list",
"of",
"JSON",
... | 1b534b864d320d875508e95cd2b76b6d8c07a90b | https://github.com/pixelogik/NearPy/blob/1b534b864d320d875508e95cd2b76b6d8c07a90b/nearpy/engine.py#L99-L113 | train | 199,282 |
pixelogik/NearPy | nearpy/engine.py | Engine._get_candidates | def _get_candidates(self, v):
""" Collect candidates from all buckets from all hashes """
candidates = []
for lshash in self.lshashes:
for bucket_key in lshash.hash_vector(v, querying=True):
bucket_content = self.storage.get_bucket(
lshash.hash_name,
bucket_key,
)
#print 'Bucket %s size %d' % (bucket_key, len(bucket_content))
candidates.extend(bucket_content)
return candidates | python | def _get_candidates(self, v):
""" Collect candidates from all buckets from all hashes """
candidates = []
for lshash in self.lshashes:
for bucket_key in lshash.hash_vector(v, querying=True):
bucket_content = self.storage.get_bucket(
lshash.hash_name,
bucket_key,
)
#print 'Bucket %s size %d' % (bucket_key, len(bucket_content))
candidates.extend(bucket_content)
return candidates | [
"def",
"_get_candidates",
"(",
"self",
",",
"v",
")",
":",
"candidates",
"=",
"[",
"]",
"for",
"lshash",
"in",
"self",
".",
"lshashes",
":",
"for",
"bucket_key",
"in",
"lshash",
".",
"hash_vector",
"(",
"v",
",",
"querying",
"=",
"True",
")",
":",
"b... | Collect candidates from all buckets from all hashes | [
"Collect",
"candidates",
"from",
"all",
"buckets",
"from",
"all",
"hashes"
] | 1b534b864d320d875508e95cd2b76b6d8c07a90b | https://github.com/pixelogik/NearPy/blob/1b534b864d320d875508e95cd2b76b6d8c07a90b/nearpy/engine.py#L180-L191 | train | 199,283 |
pixelogik/NearPy | nearpy/engine.py | Engine._apply_filter | def _apply_filter(self, filters, candidates):
""" Apply vector filters if specified and return filtered list """
if filters:
filter_input = candidates
for fetch_vector_filter in filters:
filter_input = fetch_vector_filter.filter_vectors(filter_input)
return filter_input
else:
return candidates | python | def _apply_filter(self, filters, candidates):
""" Apply vector filters if specified and return filtered list """
if filters:
filter_input = candidates
for fetch_vector_filter in filters:
filter_input = fetch_vector_filter.filter_vectors(filter_input)
return filter_input
else:
return candidates | [
"def",
"_apply_filter",
"(",
"self",
",",
"filters",
",",
"candidates",
")",
":",
"if",
"filters",
":",
"filter_input",
"=",
"candidates",
"for",
"fetch_vector_filter",
"in",
"filters",
":",
"filter_input",
"=",
"fetch_vector_filter",
".",
"filter_vectors",
"(",
... | Apply vector filters if specified and return filtered list | [
"Apply",
"vector",
"filters",
"if",
"specified",
"and",
"return",
"filtered",
"list"
] | 1b534b864d320d875508e95cd2b76b6d8c07a90b | https://github.com/pixelogik/NearPy/blob/1b534b864d320d875508e95cd2b76b6d8c07a90b/nearpy/engine.py#L194-L203 | train | 199,284 |
pixelogik/NearPy | nearpy/engine.py | Engine._append_distances | def _append_distances(self, v, distance, candidates):
""" Apply distance implementation if specified """
if distance:
# Normalize vector (stored vectors are normalized)
nv = unitvec(v)
candidates = [(x[0], x[1], self.distance.distance(x[0], nv)) for x
in candidates]
return candidates | python | def _append_distances(self, v, distance, candidates):
""" Apply distance implementation if specified """
if distance:
# Normalize vector (stored vectors are normalized)
nv = unitvec(v)
candidates = [(x[0], x[1], self.distance.distance(x[0], nv)) for x
in candidates]
return candidates | [
"def",
"_append_distances",
"(",
"self",
",",
"v",
",",
"distance",
",",
"candidates",
")",
":",
"if",
"distance",
":",
"# Normalize vector (stored vectors are normalized)",
"nv",
"=",
"unitvec",
"(",
"v",
")",
"candidates",
"=",
"[",
"(",
"x",
"[",
"0",
"]"... | Apply distance implementation if specified | [
"Apply",
"distance",
"implementation",
"if",
"specified"
] | 1b534b864d320d875508e95cd2b76b6d8c07a90b | https://github.com/pixelogik/NearPy/blob/1b534b864d320d875508e95cd2b76b6d8c07a90b/nearpy/engine.py#L205-L213 | train | 199,285 |
pixelogik/NearPy | nearpy/experiments/recallprecisionexperiment.py | RecallPrecisionExperiment.perform_experiment | def perform_experiment(self, engine_list):
"""
Performs nearest neighbour recall experiments with custom vector data
for all engines in the specified list.
Returns self.result contains list of (recall, precision, search_time)
tuple. All are the averaged values over all request vectors.
search_time is the average retrieval/search time compared to the
average exact search time.
"""
# We will fill this array with measures for all the engines.
result = []
# For each engine, first index vectors and then retrieve neighbours
for endine_idx, engine in enumerate(engine_list):
print('Engine %d / %d' % (endine_idx, len(engine_list)))
# Clean storage
engine.clean_all_buckets()
# Use this to compute average recall
avg_recall = 0.0
# Use this to compute average precision
avg_precision = 0.0
# Use this to compute average search time
avg_search_time = 0.0
# Index all vectors and store them
for index, v in enumerate(self.vectors):
engine.store_vector(v, 'data_%d' % index)
# Look for N nearest neighbours for query vectors
for index in self.query_indices:
# Get indices of the real nearest as set
real_nearest = set(self.closest[index])
# We have to time the search
search_time_start = time.time()
# Get nearest N according to engine
nearest = engine.neighbours(self.vectors[index])
# Get search time
search_time = time.time() - search_time_start
# For comparance we need their indices (as set)
nearest = set([self.__index_of_vector(x[0]) for x in nearest])
# Remove query index from search result to make sure that
# recall and precision make sense in terms of "neighbours".
# If ONLY the query vector is retrieved, we want recall to be
# zero!
nearest.remove(index)
# If the result list is empty, recall and precision are 0.0
if len(nearest) == 0:
recall = 0.0
precision = 0.0
else:
# Get intersection count
inter_count = float(len(real_nearest & nearest))
# Normalize recall for this vector
recall = inter_count/float(len(real_nearest))
# Normalize precision for this vector
precision = inter_count/float(len(nearest))
# Add to accumulator
avg_recall += recall
# Add to accumulator
avg_precision += precision
# Add to accumulator
avg_search_time += search_time
# Normalize recall over query set
avg_recall /= float(len(self.query_indices))
# Normalize precision over query set
avg_precision /= float(len(self.query_indices))
# Normalize search time over query set
avg_search_time = avg_search_time / float(len(self.query_indices))
# Normalize search time with respect to exact search
avg_search_time /= self.exact_search_time_per_vector
print(' recall=%f, precision=%f, time=%f' % (avg_recall,
avg_precision,
avg_search_time))
result.append((avg_recall, avg_precision, avg_search_time))
# Return (recall, precision, search_time) tuple
return result | python | def perform_experiment(self, engine_list):
"""
Performs nearest neighbour recall experiments with custom vector data
for all engines in the specified list.
Returns self.result contains list of (recall, precision, search_time)
tuple. All are the averaged values over all request vectors.
search_time is the average retrieval/search time compared to the
average exact search time.
"""
# We will fill this array with measures for all the engines.
result = []
# For each engine, first index vectors and then retrieve neighbours
for endine_idx, engine in enumerate(engine_list):
print('Engine %d / %d' % (endine_idx, len(engine_list)))
# Clean storage
engine.clean_all_buckets()
# Use this to compute average recall
avg_recall = 0.0
# Use this to compute average precision
avg_precision = 0.0
# Use this to compute average search time
avg_search_time = 0.0
# Index all vectors and store them
for index, v in enumerate(self.vectors):
engine.store_vector(v, 'data_%d' % index)
# Look for N nearest neighbours for query vectors
for index in self.query_indices:
# Get indices of the real nearest as set
real_nearest = set(self.closest[index])
# We have to time the search
search_time_start = time.time()
# Get nearest N according to engine
nearest = engine.neighbours(self.vectors[index])
# Get search time
search_time = time.time() - search_time_start
# For comparance we need their indices (as set)
nearest = set([self.__index_of_vector(x[0]) for x in nearest])
# Remove query index from search result to make sure that
# recall and precision make sense in terms of "neighbours".
# If ONLY the query vector is retrieved, we want recall to be
# zero!
nearest.remove(index)
# If the result list is empty, recall and precision are 0.0
if len(nearest) == 0:
recall = 0.0
precision = 0.0
else:
# Get intersection count
inter_count = float(len(real_nearest & nearest))
# Normalize recall for this vector
recall = inter_count/float(len(real_nearest))
# Normalize precision for this vector
precision = inter_count/float(len(nearest))
# Add to accumulator
avg_recall += recall
# Add to accumulator
avg_precision += precision
# Add to accumulator
avg_search_time += search_time
# Normalize recall over query set
avg_recall /= float(len(self.query_indices))
# Normalize precision over query set
avg_precision /= float(len(self.query_indices))
# Normalize search time over query set
avg_search_time = avg_search_time / float(len(self.query_indices))
# Normalize search time with respect to exact search
avg_search_time /= self.exact_search_time_per_vector
print(' recall=%f, precision=%f, time=%f' % (avg_recall,
avg_precision,
avg_search_time))
result.append((avg_recall, avg_precision, avg_search_time))
# Return (recall, precision, search_time) tuple
return result | [
"def",
"perform_experiment",
"(",
"self",
",",
"engine_list",
")",
":",
"# We will fill this array with measures for all the engines.",
"result",
"=",
"[",
"]",
"# For each engine, first index vectors and then retrieve neighbours",
"for",
"endine_idx",
",",
"engine",
"in",
"enu... | Performs nearest neighbour recall experiments with custom vector data
for all engines in the specified list.
Returns self.result contains list of (recall, precision, search_time)
tuple. All are the averaged values over all request vectors.
search_time is the average retrieval/search time compared to the
average exact search time. | [
"Performs",
"nearest",
"neighbour",
"recall",
"experiments",
"with",
"custom",
"vector",
"data",
"for",
"all",
"engines",
"in",
"the",
"specified",
"list",
"."
] | 1b534b864d320d875508e95cd2b76b6d8c07a90b | https://github.com/pixelogik/NearPy/blob/1b534b864d320d875508e95cd2b76b6d8c07a90b/nearpy/experiments/recallprecisionexperiment.py#L105-L200 | train | 199,286 |
pixelogik/NearPy | nearpy/experiments/recallprecisionexperiment.py | RecallPrecisionExperiment.__vector_to_string | def __vector_to_string(self, vector):
""" Returns string representation of vector. """
return numpy.array_str(numpy.round(unitvec(vector), decimals=3)) | python | def __vector_to_string(self, vector):
""" Returns string representation of vector. """
return numpy.array_str(numpy.round(unitvec(vector), decimals=3)) | [
"def",
"__vector_to_string",
"(",
"self",
",",
"vector",
")",
":",
"return",
"numpy",
".",
"array_str",
"(",
"numpy",
".",
"round",
"(",
"unitvec",
"(",
"vector",
")",
",",
"decimals",
"=",
"3",
")",
")"
] | Returns string representation of vector. | [
"Returns",
"string",
"representation",
"of",
"vector",
"."
] | 1b534b864d320d875508e95cd2b76b6d8c07a90b | https://github.com/pixelogik/NearPy/blob/1b534b864d320d875508e95cd2b76b6d8c07a90b/nearpy/experiments/recallprecisionexperiment.py#L202-L204 | train | 199,287 |
pixelogik/NearPy | nearpy/distances/manhattan.py | ManhattanDistance.distance | def distance(self, x, y):
"""
Computes the Manhattan distance between vectors x and y. Returns float.
"""
if scipy.sparse.issparse(x):
return numpy.sum(numpy.absolute((x-y).toarray().ravel()))
else:
return numpy.sum(numpy.absolute(x-y)) | python | def distance(self, x, y):
"""
Computes the Manhattan distance between vectors x and y. Returns float.
"""
if scipy.sparse.issparse(x):
return numpy.sum(numpy.absolute((x-y).toarray().ravel()))
else:
return numpy.sum(numpy.absolute(x-y)) | [
"def",
"distance",
"(",
"self",
",",
"x",
",",
"y",
")",
":",
"if",
"scipy",
".",
"sparse",
".",
"issparse",
"(",
"x",
")",
":",
"return",
"numpy",
".",
"sum",
"(",
"numpy",
".",
"absolute",
"(",
"(",
"x",
"-",
"y",
")",
".",
"toarray",
"(",
... | Computes the Manhattan distance between vectors x and y. Returns float. | [
"Computes",
"the",
"Manhattan",
"distance",
"between",
"vectors",
"x",
"and",
"y",
".",
"Returns",
"float",
"."
] | 1b534b864d320d875508e95cd2b76b6d8c07a90b | https://github.com/pixelogik/NearPy/blob/1b534b864d320d875508e95cd2b76b6d8c07a90b/nearpy/distances/manhattan.py#L32-L39 | train | 199,288 |
pixelogik/NearPy | nearpy/storage/storage_redis.py | RedisStorage.store_many_vectors | def store_many_vectors(self, hash_name, bucket_keys, vs, data):
"""
Store a batch of vectors in Redis.
Stores vector and JSON-serializable data in bucket with specified key.
"""
with self.redis_object.pipeline() as pipeline:
if data is None:
data = [None] * len(vs)
for bucket_key, data, v in zip(bucket_keys, data, vs):
self._add_vector(hash_name, bucket_key, v, data, pipeline)
pipeline.execute() | python | def store_many_vectors(self, hash_name, bucket_keys, vs, data):
"""
Store a batch of vectors in Redis.
Stores vector and JSON-serializable data in bucket with specified key.
"""
with self.redis_object.pipeline() as pipeline:
if data is None:
data = [None] * len(vs)
for bucket_key, data, v in zip(bucket_keys, data, vs):
self._add_vector(hash_name, bucket_key, v, data, pipeline)
pipeline.execute() | [
"def",
"store_many_vectors",
"(",
"self",
",",
"hash_name",
",",
"bucket_keys",
",",
"vs",
",",
"data",
")",
":",
"with",
"self",
".",
"redis_object",
".",
"pipeline",
"(",
")",
"as",
"pipeline",
":",
"if",
"data",
"is",
"None",
":",
"data",
"=",
"[",
... | Store a batch of vectors in Redis.
Stores vector and JSON-serializable data in bucket with specified key. | [
"Store",
"a",
"batch",
"of",
"vectors",
"in",
"Redis",
".",
"Stores",
"vector",
"and",
"JSON",
"-",
"serializable",
"data",
"in",
"bucket",
"with",
"specified",
"key",
"."
] | 1b534b864d320d875508e95cd2b76b6d8c07a90b | https://github.com/pixelogik/NearPy/blob/1b534b864d320d875508e95cd2b76b6d8c07a90b/nearpy/storage/storage_redis.py#L55-L65 | train | 199,289 |
pixelogik/NearPy | nearpy/storage/storage_redis.py | RedisStorage._add_vector | def _add_vector(self, hash_name, bucket_key, v, data, redis_object):
'''
Store vector and JSON-serializable data in bucket with specified key.
'''
redis_key = self._format_redis_key(hash_name, bucket_key)
val_dict = {}
# Depending on type (sparse or not) fill value dict
if scipy.sparse.issparse(v):
# Make sure that we are using COO format (easy to handle)
if not scipy.sparse.isspmatrix_coo(v):
v = scipy.sparse.coo_matrix(v)
# Construct list of [index, value] items,
# one for each non-zero element of the sparse vector
encoded_values = []
for k in range(v.data.size):
row_index = v.row[k]
value = v.data[k]
encoded_values.append([int(row_index), value])
val_dict['sparse'] = 1
val_dict['nonzeros'] = encoded_values
val_dict['dim'] = v.shape[0]
else:
# Make sure it is a 1d vector
v = numpy.reshape(v, v.shape[0])
val_dict['vector'] = v.tostring()
val_dict['dtype'] = v.dtype.name
# Add data if set
if data is not None:
val_dict['data'] = data
# Push JSON representation of dict to end of bucket list
self.redis_object.rpush(redis_key, pickle.dumps(val_dict, protocol=2)) | python | def _add_vector(self, hash_name, bucket_key, v, data, redis_object):
'''
Store vector and JSON-serializable data in bucket with specified key.
'''
redis_key = self._format_redis_key(hash_name, bucket_key)
val_dict = {}
# Depending on type (sparse or not) fill value dict
if scipy.sparse.issparse(v):
# Make sure that we are using COO format (easy to handle)
if not scipy.sparse.isspmatrix_coo(v):
v = scipy.sparse.coo_matrix(v)
# Construct list of [index, value] items,
# one for each non-zero element of the sparse vector
encoded_values = []
for k in range(v.data.size):
row_index = v.row[k]
value = v.data[k]
encoded_values.append([int(row_index), value])
val_dict['sparse'] = 1
val_dict['nonzeros'] = encoded_values
val_dict['dim'] = v.shape[0]
else:
# Make sure it is a 1d vector
v = numpy.reshape(v, v.shape[0])
val_dict['vector'] = v.tostring()
val_dict['dtype'] = v.dtype.name
# Add data if set
if data is not None:
val_dict['data'] = data
# Push JSON representation of dict to end of bucket list
self.redis_object.rpush(redis_key, pickle.dumps(val_dict, protocol=2)) | [
"def",
"_add_vector",
"(",
"self",
",",
"hash_name",
",",
"bucket_key",
",",
"v",
",",
"data",
",",
"redis_object",
")",
":",
"redis_key",
"=",
"self",
".",
"_format_redis_key",
"(",
"hash_name",
",",
"bucket_key",
")",
"val_dict",
"=",
"{",
"}",
"# Depend... | Store vector and JSON-serializable data in bucket with specified key. | [
"Store",
"vector",
"and",
"JSON",
"-",
"serializable",
"data",
"in",
"bucket",
"with",
"specified",
"key",
"."
] | 1b534b864d320d875508e95cd2b76b6d8c07a90b | https://github.com/pixelogik/NearPy/blob/1b534b864d320d875508e95cd2b76b6d8c07a90b/nearpy/storage/storage_redis.py#L67-L105 | train | 199,290 |
pixelogik/NearPy | nearpy/storage/storage_redis.py | RedisStorage.clean_buckets | def clean_buckets(self, hash_name):
"""
Removes all buckets and their content for specified hash.
"""
bucket_keys = self._iter_bucket_keys(hash_name)
self.redis_object.delete(*bucket_keys) | python | def clean_buckets(self, hash_name):
"""
Removes all buckets and their content for specified hash.
"""
bucket_keys = self._iter_bucket_keys(hash_name)
self.redis_object.delete(*bucket_keys) | [
"def",
"clean_buckets",
"(",
"self",
",",
"hash_name",
")",
":",
"bucket_keys",
"=",
"self",
".",
"_iter_bucket_keys",
"(",
"hash_name",
")",
"self",
".",
"redis_object",
".",
"delete",
"(",
"*",
"bucket_keys",
")"
] | Removes all buckets and their content for specified hash. | [
"Removes",
"all",
"buckets",
"and",
"their",
"content",
"for",
"specified",
"hash",
"."
] | 1b534b864d320d875508e95cd2b76b6d8c07a90b | https://github.com/pixelogik/NearPy/blob/1b534b864d320d875508e95cd2b76b6d8c07a90b/nearpy/storage/storage_redis.py#L184-L189 | train | 199,291 |
pixelogik/NearPy | nearpy/storage/storage_redis.py | RedisStorage.clean_all_buckets | def clean_all_buckets(self):
"""
Removes all buckets from all hashes and their content.
"""
bucket_keys = self.redis_object.keys(pattern='nearpy_*')
if len(bucket_keys) > 0:
self.redis_object.delete(*bucket_keys) | python | def clean_all_buckets(self):
"""
Removes all buckets from all hashes and their content.
"""
bucket_keys = self.redis_object.keys(pattern='nearpy_*')
if len(bucket_keys) > 0:
self.redis_object.delete(*bucket_keys) | [
"def",
"clean_all_buckets",
"(",
"self",
")",
":",
"bucket_keys",
"=",
"self",
".",
"redis_object",
".",
"keys",
"(",
"pattern",
"=",
"'nearpy_*'",
")",
"if",
"len",
"(",
"bucket_keys",
")",
">",
"0",
":",
"self",
".",
"redis_object",
".",
"delete",
"(",... | Removes all buckets from all hashes and their content. | [
"Removes",
"all",
"buckets",
"from",
"all",
"hashes",
"and",
"their",
"content",
"."
] | 1b534b864d320d875508e95cd2b76b6d8c07a90b | https://github.com/pixelogik/NearPy/blob/1b534b864d320d875508e95cd2b76b6d8c07a90b/nearpy/storage/storage_redis.py#L191-L197 | train | 199,292 |
pixelogik/NearPy | nearpy/hashes/permutation/hashpermutationmapper.py | HashPermutationMapper.add_child_hash | def add_child_hash(self, child_hash):
"""
Adds specified child hash.
The hash must be one of the binary types.
"""
# Hash must generate binary keys
if not (isinstance(child_hash,PCABinaryProjections) or isinstance(child_hash,RandomBinaryProjections) or isinstance(child_hash,RandomBinaryProjectionTree)):
raise ValueError('Child hashes must generate binary keys')
# Add both hash and config to array of child hashes. Also we are going to
# accumulate used bucket keys for every hash in order to build the permuted index
self.child_hashes.append(child_hash) | python | def add_child_hash(self, child_hash):
"""
Adds specified child hash.
The hash must be one of the binary types.
"""
# Hash must generate binary keys
if not (isinstance(child_hash,PCABinaryProjections) or isinstance(child_hash,RandomBinaryProjections) or isinstance(child_hash,RandomBinaryProjectionTree)):
raise ValueError('Child hashes must generate binary keys')
# Add both hash and config to array of child hashes. Also we are going to
# accumulate used bucket keys for every hash in order to build the permuted index
self.child_hashes.append(child_hash) | [
"def",
"add_child_hash",
"(",
"self",
",",
"child_hash",
")",
":",
"# Hash must generate binary keys",
"if",
"not",
"(",
"isinstance",
"(",
"child_hash",
",",
"PCABinaryProjections",
")",
"or",
"isinstance",
"(",
"child_hash",
",",
"RandomBinaryProjections",
")",
"o... | Adds specified child hash.
The hash must be one of the binary types. | [
"Adds",
"specified",
"child",
"hash",
"."
] | 1b534b864d320d875508e95cd2b76b6d8c07a90b | https://github.com/pixelogik/NearPy/blob/1b534b864d320d875508e95cd2b76b6d8c07a90b/nearpy/hashes/permutation/hashpermutationmapper.py#L130-L143 | train | 199,293 |
pixelogik/NearPy | nearpy/experiments/distanceratioexperiment.py | DistanceRatioExperiment.perform_experiment | def perform_experiment(self, engine_list):
"""
Performs nearest neighbour experiments with custom vector data
for all engines in the specified list.
Returns self.result contains list of (distance_ratio, search_time)
tuple. All are the averaged values over all request vectors.
search_time is the average retrieval/search time compared to the
average exact search time.
"""
# We will fill this array with measures for all the engines.
result = []
# For each engine, first index vectors and then retrieve neighbours
for engine in engine_list:
print('Engine %d / %d' % (engine_list.index(engine),
len(engine_list)))
# Clean storage
engine.clean_all_buckets()
# Use this to compute average distance_ratio
avg_distance_ratio = 0.0
# Use this to compute average result set size
avg_result_size = 0.0
# Use this to compute average search time
avg_search_time = 0.0
# Index all vectors and store them
for index in range(self.vectors.shape[1]):
engine.store_vector(self.vectors[:, index],
'data_%d' % index)
# Look for N nearest neighbours for query vectors
for index in self.query_indices:
# We have to time the search
search_time_start = time.time()
# Get nearest N according to engine
nearest = engine.neighbours(self.vectors[:, index])
# Get search time
search_time = time.time() - search_time_start
# Get average distance ratio (with respect to radius
# of real N closest neighbours)
distance_ratio = 0.0
for n in nearest:
# If the vector is outside the real neighbour radius
if n[2] > self.nearest_radius[index]:
# Compute distance to real neighbour radius
d = (n[2] - self.nearest_radius[index])
# And normalize it. 1.0 means: distance to
# real neighbour radius is identical to radius
d /= self.nearest_radius[index]
# If all neighbours are in the radius, the
# distance ratio is 0.0
distance_ratio += d
# Normalize distance ratio over all neighbours
distance_ratio /= len(nearest)
# Add to accumulator
avg_distance_ratio += distance_ratio
# Add to accumulator
avg_result_size += len(nearest)
# Add to accumulator
avg_search_time += search_time
# Normalize distance ratio over query set
avg_distance_ratio /= float(len(self.query_indices))
# Normalize avg result size
avg_result_size /= float(len(self.query_indices))
# Normalize search time over query set
avg_search_time = avg_search_time / float(len(self.query_indices))
# Normalize search time with respect to exact search
avg_search_time /= self.exact_search_time_per_vector
print(' distance_ratio=%f, result_size=%f, time=%f' % (avg_distance_ratio,
avg_result_size,
avg_search_time))
result.append((avg_distance_ratio, avg_result_size, avg_search_time))
return result | python | def perform_experiment(self, engine_list):
"""
Performs nearest neighbour experiments with custom vector data
for all engines in the specified list.
Returns self.result contains list of (distance_ratio, search_time)
tuple. All are the averaged values over all request vectors.
search_time is the average retrieval/search time compared to the
average exact search time.
"""
# We will fill this array with measures for all the engines.
result = []
# For each engine, first index vectors and then retrieve neighbours
for engine in engine_list:
print('Engine %d / %d' % (engine_list.index(engine),
len(engine_list)))
# Clean storage
engine.clean_all_buckets()
# Use this to compute average distance_ratio
avg_distance_ratio = 0.0
# Use this to compute average result set size
avg_result_size = 0.0
# Use this to compute average search time
avg_search_time = 0.0
# Index all vectors and store them
for index in range(self.vectors.shape[1]):
engine.store_vector(self.vectors[:, index],
'data_%d' % index)
# Look for N nearest neighbours for query vectors
for index in self.query_indices:
# We have to time the search
search_time_start = time.time()
# Get nearest N according to engine
nearest = engine.neighbours(self.vectors[:, index])
# Get search time
search_time = time.time() - search_time_start
# Get average distance ratio (with respect to radius
# of real N closest neighbours)
distance_ratio = 0.0
for n in nearest:
# If the vector is outside the real neighbour radius
if n[2] > self.nearest_radius[index]:
# Compute distance to real neighbour radius
d = (n[2] - self.nearest_radius[index])
# And normalize it. 1.0 means: distance to
# real neighbour radius is identical to radius
d /= self.nearest_radius[index]
# If all neighbours are in the radius, the
# distance ratio is 0.0
distance_ratio += d
# Normalize distance ratio over all neighbours
distance_ratio /= len(nearest)
# Add to accumulator
avg_distance_ratio += distance_ratio
# Add to accumulator
avg_result_size += len(nearest)
# Add to accumulator
avg_search_time += search_time
# Normalize distance ratio over query set
avg_distance_ratio /= float(len(self.query_indices))
# Normalize avg result size
avg_result_size /= float(len(self.query_indices))
# Normalize search time over query set
avg_search_time = avg_search_time / float(len(self.query_indices))
# Normalize search time with respect to exact search
avg_search_time /= self.exact_search_time_per_vector
print(' distance_ratio=%f, result_size=%f, time=%f' % (avg_distance_ratio,
avg_result_size,
avg_search_time))
result.append((avg_distance_ratio, avg_result_size, avg_search_time))
return result | [
"def",
"perform_experiment",
"(",
"self",
",",
"engine_list",
")",
":",
"# We will fill this array with measures for all the engines.",
"result",
"=",
"[",
"]",
"# For each engine, first index vectors and then retrieve neighbours",
"for",
"engine",
"in",
"engine_list",
":",
"pr... | Performs nearest neighbour experiments with custom vector data
for all engines in the specified list.
Returns self.result contains list of (distance_ratio, search_time)
tuple. All are the averaged values over all request vectors.
search_time is the average retrieval/search time compared to the
average exact search time. | [
"Performs",
"nearest",
"neighbour",
"experiments",
"with",
"custom",
"vector",
"data",
"for",
"all",
"engines",
"in",
"the",
"specified",
"list",
"."
] | 1b534b864d320d875508e95cd2b76b6d8c07a90b | https://github.com/pixelogik/NearPy/blob/1b534b864d320d875508e95cd2b76b6d8c07a90b/nearpy/experiments/distanceratioexperiment.py#L127-L214 | train | 199,294 |
pixelogik/NearPy | nearpy/hashes/permutation/permutation.py | Permutation.get_neighbour_keys | def get_neighbour_keys(self, hash_name, bucket_key):
"""
Return the neighbour buckets given hash_name and query bucket key.
"""
# get the permutedIndex given hash_name
permutedIndex = self.permutedIndexs[hash_name]
# return neighbour bucket keys of query bucket key
return permutedIndex.get_neighbour_keys(
bucket_key,
permutedIndex.num_neighbour) | python | def get_neighbour_keys(self, hash_name, bucket_key):
"""
Return the neighbour buckets given hash_name and query bucket key.
"""
# get the permutedIndex given hash_name
permutedIndex = self.permutedIndexs[hash_name]
# return neighbour bucket keys of query bucket key
return permutedIndex.get_neighbour_keys(
bucket_key,
permutedIndex.num_neighbour) | [
"def",
"get_neighbour_keys",
"(",
"self",
",",
"hash_name",
",",
"bucket_key",
")",
":",
"# get the permutedIndex given hash_name",
"permutedIndex",
"=",
"self",
".",
"permutedIndexs",
"[",
"hash_name",
"]",
"# return neighbour bucket keys of query bucket key",
"return",
"p... | Return the neighbour buckets given hash_name and query bucket key. | [
"Return",
"the",
"neighbour",
"buckets",
"given",
"hash_name",
"and",
"query",
"bucket",
"key",
"."
] | 1b534b864d320d875508e95cd2b76b6d8c07a90b | https://github.com/pixelogik/NearPy/blob/1b534b864d320d875508e95cd2b76b6d8c07a90b/nearpy/hashes/permutation/permutation.py#L67-L76 | train | 199,295 |
prompt-toolkit/pyvim | pyvim/rc_file.py | run_rc_file | def run_rc_file(editor, rc_file):
"""
Run rc file.
"""
assert isinstance(editor, Editor)
assert isinstance(rc_file, six.string_types)
# Expand tildes.
rc_file = os.path.expanduser(rc_file)
# Check whether this file exists.
if not os.path.exists(rc_file):
print('Impossible to read %r' % rc_file)
_press_enter_to_continue()
return
# Run the rc file in an empty namespace.
try:
namespace = {}
with open(rc_file, 'r') as f:
code = compile(f.read(), rc_file, 'exec')
six.exec_(code, namespace, namespace)
# Now we should have a 'configure' method in this namespace. We call this
# method with editor as an argument.
if 'configure' in namespace:
namespace['configure'](editor)
except Exception as e:
# Handle possible exceptions in rc file.
traceback.print_exc()
_press_enter_to_continue() | python | def run_rc_file(editor, rc_file):
"""
Run rc file.
"""
assert isinstance(editor, Editor)
assert isinstance(rc_file, six.string_types)
# Expand tildes.
rc_file = os.path.expanduser(rc_file)
# Check whether this file exists.
if not os.path.exists(rc_file):
print('Impossible to read %r' % rc_file)
_press_enter_to_continue()
return
# Run the rc file in an empty namespace.
try:
namespace = {}
with open(rc_file, 'r') as f:
code = compile(f.read(), rc_file, 'exec')
six.exec_(code, namespace, namespace)
# Now we should have a 'configure' method in this namespace. We call this
# method with editor as an argument.
if 'configure' in namespace:
namespace['configure'](editor)
except Exception as e:
# Handle possible exceptions in rc file.
traceback.print_exc()
_press_enter_to_continue() | [
"def",
"run_rc_file",
"(",
"editor",
",",
"rc_file",
")",
":",
"assert",
"isinstance",
"(",
"editor",
",",
"Editor",
")",
"assert",
"isinstance",
"(",
"rc_file",
",",
"six",
".",
"string_types",
")",
"# Expand tildes.",
"rc_file",
"=",
"os",
".",
"path",
"... | Run rc file. | [
"Run",
"rc",
"file",
"."
] | 5928b53b9d700863c1a06d2181a034a955f94594 | https://github.com/prompt-toolkit/pyvim/blob/5928b53b9d700863c1a06d2181a034a955f94594/pyvim/rc_file.py#L25-L57 | train | 199,296 |
prompt-toolkit/pyvim | pyvim/layout.py | _try_char | def _try_char(character, backup, encoding=sys.stdout.encoding):
"""
Return `character` if it can be encoded using sys.stdout, else return the
backup character.
"""
if character.encode(encoding, 'replace') == b'?':
return backup
else:
return character | python | def _try_char(character, backup, encoding=sys.stdout.encoding):
"""
Return `character` if it can be encoded using sys.stdout, else return the
backup character.
"""
if character.encode(encoding, 'replace') == b'?':
return backup
else:
return character | [
"def",
"_try_char",
"(",
"character",
",",
"backup",
",",
"encoding",
"=",
"sys",
".",
"stdout",
".",
"encoding",
")",
":",
"if",
"character",
".",
"encode",
"(",
"encoding",
",",
"'replace'",
")",
"==",
"b'?'",
":",
"return",
"backup",
"else",
":",
"r... | Return `character` if it can be encoded using sys.stdout, else return the
backup character. | [
"Return",
"character",
"if",
"it",
"can",
"be",
"encoded",
"using",
"sys",
".",
"stdout",
"else",
"return",
"the",
"backup",
"character",
"."
] | 5928b53b9d700863c1a06d2181a034a955f94594 | https://github.com/prompt-toolkit/pyvim/blob/5928b53b9d700863c1a06d2181a034a955f94594/pyvim/layout.py#L36-L44 | train | 199,297 |
prompt-toolkit/pyvim | pyvim/layout.py | EditorLayout.update | def update(self):
"""
Update layout to match the layout as described in the
WindowArrangement.
"""
# Start with an empty frames list everytime, to avoid memory leaks.
existing_frames = self._frames
self._frames = {}
def create_layout_from_node(node):
if isinstance(node, window_arrangement.Window):
# Create frame for Window, or reuse it, if we had one already.
key = (node, node.editor_buffer)
frame = existing_frames.get(key)
if frame is None:
frame, pt_window = self._create_window_frame(node.editor_buffer)
# Link layout Window to arrangement.
node.pt_window = pt_window
self._frames[key] = frame
return frame
elif isinstance(node, window_arrangement.VSplit):
return VSplit(
[create_layout_from_node(n) for n in node],
padding=1,
padding_char=self.get_vertical_border_char(),
padding_style='class:frameborder')
if isinstance(node, window_arrangement.HSplit):
return HSplit([create_layout_from_node(n) for n in node])
layout = create_layout_from_node(self.window_arrangement.active_tab.root)
self._fc.content = layout | python | def update(self):
"""
Update layout to match the layout as described in the
WindowArrangement.
"""
# Start with an empty frames list everytime, to avoid memory leaks.
existing_frames = self._frames
self._frames = {}
def create_layout_from_node(node):
if isinstance(node, window_arrangement.Window):
# Create frame for Window, or reuse it, if we had one already.
key = (node, node.editor_buffer)
frame = existing_frames.get(key)
if frame is None:
frame, pt_window = self._create_window_frame(node.editor_buffer)
# Link layout Window to arrangement.
node.pt_window = pt_window
self._frames[key] = frame
return frame
elif isinstance(node, window_arrangement.VSplit):
return VSplit(
[create_layout_from_node(n) for n in node],
padding=1,
padding_char=self.get_vertical_border_char(),
padding_style='class:frameborder')
if isinstance(node, window_arrangement.HSplit):
return HSplit([create_layout_from_node(n) for n in node])
layout = create_layout_from_node(self.window_arrangement.active_tab.root)
self._fc.content = layout | [
"def",
"update",
"(",
"self",
")",
":",
"# Start with an empty frames list everytime, to avoid memory leaks.",
"existing_frames",
"=",
"self",
".",
"_frames",
"self",
".",
"_frames",
"=",
"{",
"}",
"def",
"create_layout_from_node",
"(",
"node",
")",
":",
"if",
"isin... | Update layout to match the layout as described in the
WindowArrangement. | [
"Update",
"layout",
"to",
"match",
"the",
"layout",
"as",
"described",
"in",
"the",
"WindowArrangement",
"."
] | 5928b53b9d700863c1a06d2181a034a955f94594 | https://github.com/prompt-toolkit/pyvim/blob/5928b53b9d700863c1a06d2181a034a955f94594/pyvim/layout.py#L493-L527 | train | 199,298 |
prompt-toolkit/pyvim | pyvim/layout.py | EditorLayout._create_window_frame | def _create_window_frame(self, editor_buffer):
"""
Create a Window for the buffer, with underneat a status bar.
"""
@Condition
def wrap_lines():
return self.editor.wrap_lines
window = Window(
self._create_buffer_control(editor_buffer),
allow_scroll_beyond_bottom=True,
scroll_offsets=ScrollOffsets(
left=0, right=0,
top=(lambda: self.editor.scroll_offset),
bottom=(lambda: self.editor.scroll_offset)),
wrap_lines=wrap_lines,
left_margins=[ConditionalMargin(
margin=NumberedMargin(
display_tildes=True,
relative=Condition(lambda: self.editor.relative_number)),
filter=Condition(lambda: self.editor.show_line_numbers))],
cursorline=Condition(lambda: self.editor.cursorline),
cursorcolumn=Condition(lambda: self.editor.cursorcolumn),
colorcolumns=(
lambda: [ColorColumn(pos) for pos in self.editor.colorcolumn]),
ignore_content_width=True,
ignore_content_height=True,
get_line_prefix=partial(self._get_line_prefix, editor_buffer.buffer))
return HSplit([
window,
VSplit([
WindowStatusBar(self.editor, editor_buffer),
WindowStatusBarRuler(self.editor, window, editor_buffer.buffer),
], width=Dimension()), # Ignore actual status bar width.
]), window | python | def _create_window_frame(self, editor_buffer):
"""
Create a Window for the buffer, with underneat a status bar.
"""
@Condition
def wrap_lines():
return self.editor.wrap_lines
window = Window(
self._create_buffer_control(editor_buffer),
allow_scroll_beyond_bottom=True,
scroll_offsets=ScrollOffsets(
left=0, right=0,
top=(lambda: self.editor.scroll_offset),
bottom=(lambda: self.editor.scroll_offset)),
wrap_lines=wrap_lines,
left_margins=[ConditionalMargin(
margin=NumberedMargin(
display_tildes=True,
relative=Condition(lambda: self.editor.relative_number)),
filter=Condition(lambda: self.editor.show_line_numbers))],
cursorline=Condition(lambda: self.editor.cursorline),
cursorcolumn=Condition(lambda: self.editor.cursorcolumn),
colorcolumns=(
lambda: [ColorColumn(pos) for pos in self.editor.colorcolumn]),
ignore_content_width=True,
ignore_content_height=True,
get_line_prefix=partial(self._get_line_prefix, editor_buffer.buffer))
return HSplit([
window,
VSplit([
WindowStatusBar(self.editor, editor_buffer),
WindowStatusBarRuler(self.editor, window, editor_buffer.buffer),
], width=Dimension()), # Ignore actual status bar width.
]), window | [
"def",
"_create_window_frame",
"(",
"self",
",",
"editor_buffer",
")",
":",
"@",
"Condition",
"def",
"wrap_lines",
"(",
")",
":",
"return",
"self",
".",
"editor",
".",
"wrap_lines",
"window",
"=",
"Window",
"(",
"self",
".",
"_create_buffer_control",
"(",
"e... | Create a Window for the buffer, with underneat a status bar. | [
"Create",
"a",
"Window",
"for",
"the",
"buffer",
"with",
"underneat",
"a",
"status",
"bar",
"."
] | 5928b53b9d700863c1a06d2181a034a955f94594 | https://github.com/prompt-toolkit/pyvim/blob/5928b53b9d700863c1a06d2181a034a955f94594/pyvim/layout.py#L529-L564 | train | 199,299 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.