tab_width = self.directive.state.document.settings.tab_width         return [prepare_docstring(docstring, ignore, tab_width) for docstring in docstrings]     def get_variable_comment(self) -> Optional[List[str]]:        try:            key = ('', '.'.join(self.objpath))            analyzer = ModuleAnalyzer.for_module(self.get_real_modname())            analyzer.analyze()            return list(self.analyzer.attr_docs.get(key, []))        except PycodeError:            return None     def add_content(self, more_content: Optional[StringList], no_docstring: bool = False                     ) -> None:        if self.doc_as_attr:        if self.doc_as_attr and not self.get_variable_comment():             try:                 more_content = StringList([_('alias of %s') % restify(self.object)], source='')             except AttributeError:


# also support syntax like ``:param type name:``             if typedesc.is_typed:                 try:                    argtype, argname = fieldarg.split(None, 1)                    argtype, argname = fieldarg.rsplit(None, 1)                 except ValueError:                     pass                 else:


docsettings.section = section              if self.config.man_make_section_directory:                ensuredir(path.join(self.outdir, str(section)))                targetname = '%s/%s.%s' % (section, name, section)                dirname = 'man%s' % section                ensuredir(path.join(self.outdir, dirname))                targetname = '%s/%s.%s' % (dirname, name, section)             else:                 targetname = '%s.%s' % (name, section)


# add inheritance info, if wanted         if not self.doc_as_attr and self.options.show_inheritance:            sourcename = self.get_sourcename()            self.add_line('', sourcename)             if hasattr(self.object, '__orig_bases__') and len(self.object.__orig_bases__):                 # A subclass of generic types                 # refs: PEP-560 <https://www.python.org/dev/peps/pep-0560/>                bases = [restify(cls) for cls in self.object.__orig_bases__]                self.add_line('   ' + _('Bases: %s') % ', '.join(bases), sourcename)                bases = list(self.object.__orig_bases__)             elif hasattr(self.object, '__bases__') and len(self.object.__bases__):                 # A normal class                bases = [restify(cls) for cls in self.object.__bases__]                self.add_line('   ' + _('Bases: %s') % ', '.join(bases), sourcename)                bases = list(self.object.__bases__)            else:                bases = []            self.env.events.emit('autodoc-process-bases',                                 self.fullname, self.object, self.options, bases)            base_classes = [restify(cls) for cls in bases]            sourcename = self.get_sourcename()            self.add_line('', sourcename)            self.add_line('   ' + _('Bases: %s') % ', '.join(base_classes), sourcename)      def get_object_members(self, want_all: bool) -> Tuple[bool, ObjectMembers]:         members = get_class_members(self.object, self.objpath, self.get_attr)


app.add_event('autodoc-process-docstring')     app.add_event('autodoc-process-signature')     app.add_event('autodoc-skip-member')<ins>    app.add_event('autodoc-process-bases')</ins>      app.connect('config-inited', migrate_autodoc_member_order, priority=800)


except KeyError:                 text, color = ('with unknown code', purple)             linkstat['text'] = text            logger.info(color('redirect  ') + result.uri +                        color(' - ' + text + ' to ' + result.message))            if self.config.linkcheck_allowed_redirects:                logger.warning('redirect  ' + result.uri + ' - ' + text + ' to ' +                               result.message, location=(filename, result.lineno))            else:                logger.info(color('redirect  ') + result.uri +                            color(' - ' + text + ' to ' + result.message))             self.write_entry('redirected ' + text, result.docname, filename,                              result.lineno, result.uri + ' to ' + result.message)         else:


new_url = response.url                 if anchor:                     new_url += '#' + anchor                # history contains any redirects, get last                if response.history:                if allowed_redirect(req_url, new_url):                    return 'working', '', 0                elif response.history:                    # history contains any redirects, get last                     code = response.history[-1].status_code                     return 'redirected', new_url, code                 else:                     return 'redirected', new_url, 0         def allowed_redirect(url: str, new_url: str) -> bool:            for from_url, to_url in self.config.linkcheck_allowed_redirects.items():                if from_url.match(url) and to_url.match(new_url):                    return True            return False         def check(docname: str) -> Tuple[str, str, int]:             # check for various conditions without bothering the network             if len(uri) == 0 or uri.startswith(('#', 'mailto:', 'tel:')):


return None  def compile_linkcheck_allowed_redirects(app: Sphinx, config: Config) -> None:    """Compile patterns in linkcheck_allowed_redirects to the regexp objects."""    for url, pattern in list(app.config.linkcheck_allowed_redirects.items()):        try:            app.config.linkcheck_allowed_redirects[re.compile(url)] = re.compile(pattern)        except re.error as exc:            logger.warning(__('Failed to compile regex in linkcheck_allowed_redirects: %r %s'),                           exc.pattern, exc.msg)        finally:            # Remove the original regexp-string            app.config.linkcheck_allowed_redirects.pop(url) def setup(app: Sphinx) -> Dict[str, Any]:     app.add_builder(CheckExternalLinksBuilder)     app.add_post_transform(HyperlinkCollector)      app.add_config_value('linkcheck_ignore', [], None)    app.add_config_value('linkcheck_allowed_redirects', {}, None)     app.add_config_value('linkcheck_auth', [], None)     app.add_config_value('linkcheck_request_headers', {}, None)     app.add_config_value('linkcheck_retries', 1, None)


app.add_config_value('linkcheck_rate_limit_timeout', 300.0, None)      app.add_event('linkcheck-process-uri')<ins>    app.connect('config-inited', compile_linkcheck_allowed_redirects, priority=800)</ins>     app.connect('linkcheck-process-uri', rewrite_github_anchor)      return {


:license: BSD, see LICENSE for details. """ from typing import Any, Dict, List, Optional, Tuple, Type, castfrom typing import Any, Dict, List, Optional, Sequence, Tuple, Type, cast  from docutils import nodesfrom docutils.nodes import Elementfrom docutils.nodes import Element, Node  from sphinx import addnodes from sphinx.addnodes import pending_xref


logger = logging.getLogger(__name__) <del>if False:    # For type annotation    from docutils.nodes import Node</del>  class SphinxPostTransform(SphinxTransform):     """A base class of post-transforms.


def run(self, **kwargs: Any) -> None:         for node in self.document.traverse(addnodes.pending_xref):            contnode = cast(nodes.TextElement, node[0].deepcopy())            content = self.find_pending_xref_condition(node, ("resolved", "*"))            if content:                contnode = cast(Element, content[0].deepcopy())            else:                contnode = cast(Element, node[0].deepcopy())             newnode = None              typ = node['reftype']


else:                 newnodes = [contnode]                 if newnode is None and isinstance(node[0], addnodes.pending_xref_condition):                    matched = find_pending_xref_condition(node, "*")                    matched = self.find_pending_xref_condition(node, ("*",))                     if matched:                        newnodes = matched.children                        newnodes = matched                     else:                         logger.warning(__('Could not determine the fallback text for the '                                           'cross-reference. Might be a bug.'), location=node)


msg = __('%r reference target not found: %s') % (typ, target)         logger.warning(msg, location=node, type='ref', subtype=typ) <ins>    def find_pending_xref_condition(self, node: pending_xref, conditions: Sequence[str]                                    ) -> Optional[List[Node]]:        for condition in conditions:            matched = find_pending_xref_condition(node, condition)            if matched:                return matched.children        else:            return None</ins>  class OnlyNodeTransform(SphinxPostTransform):     default_priority = 50


def make_xrefs(self, rolename: str, domain: str, target: str,                    innernode: Type[TextlikeNode] = nodes.emphasis,                    contnode: Node = None, env: BuildEnvironment = None) -> List[Node]:        delims = r'(\s*[\[\]\(\),](?:\s*or\s)?\s*|\s+or\s+|\.\.\.)'        delims = r'(\s*[\[\]\(\),](?:\s*or\s)?\s*|\s+or\s+|\s*\|\s*|\.\.\.)'         delims_re = re.compile(delims)         sub_targets = re.split(delims, target)


from threading import Thread from typing import (Any, Dict, Generator, List, NamedTuple, Optional, Pattern, Set, Tuple,                     Union, cast)from urllib.parse import unquote, urlparsefrom urllib.parse import unquote, urlparse, urlunparse  from docutils import nodes from docutils.nodes import Element


if 'refuri' not in refnode:                 continue             uri = refnode['refuri']<ins>            newuri = self.app.emit_firstresult('linkcheck-process-uri', uri)            if newuri:                uri = newuri</ins>             lineno = get_node_line(refnode)             uri_info = Hyperlink(uri, self.env.docname, lineno)             if uri not in hyperlinks:


for imgnode in self.document.traverse(nodes.image):             uri = imgnode['candidates'].get('?')             if uri and '://' in uri:                newuri = self.app.emit_firstresult('linkcheck-process-uri', uri)                if newuri:                    uri = newuri                 lineno = get_node_line(imgnode)                 uri_info = Hyperlink(uri, self.env.docname, lineno)                 if uri not in hyperlinks:                     hyperlinks[uri] = uri_info  def rewrite_github_anchor(app: Sphinx, uri: str) -> Optional[str]:    """Rewrite anchor name of the hyperlink to github.com    The hyperlink anchors in github.com are dynamically generated.  This rewrites    them before checking and makes them comparable.    """    parsed = urlparse(uri)    if parsed.hostname == "github.com" and parsed.fragment:        prefixed = parsed.fragment.startswith('user-content-')        if not prefixed:            fragment = f'user-content-{parsed.fragment}'            return urlunparse(parsed._replace(fragment=fragment))    return None def setup(app: Sphinx) -> Dict[str, Any]:     app.add_builder(CheckExternalLinksBuilder)     app.add_post_transform(HyperlinkCollector)


app.add_config_value('linkcheck_anchors_ignore', ["^!"], None)     app.add_config_value('linkcheck_rate_limit_timeout', 300.0, None) <ins>    app.add_event('linkcheck-process-uri')    app.connect('linkcheck-process-uri', rewrite_github_anchor)</ins>     return {         'version': 'builtin',         'parallel_read_safe': True,


__init__ = self.get_attr(self.object, '__init__', None)             initdocstring = getdoc(__init__, self.get_attr,                                    self.config.autodoc_inherit_docstrings,                                   self.parent, self.object_name)                                   self.object, '__init__')             # for new-style classes, no __init__ means default __init__             if (initdocstring is not None and                 (initdocstring == object.__init__.__doc__ or  # for pypy


__new__ = self.get_attr(self.object, '__new__', None)                 initdocstring = getdoc(__new__, self.get_attr,                                        self.config.autodoc_inherit_docstrings,                                       self.parent, self.object_name)                                       self.object, '__new__')                 # for new-style classes, no __new__ means default __new__                 if (initdocstring is not None and                     (initdocstring == object.__new__.__doc__ or  # for pypydiff --git a/sphinx/util/inspect.py b/sphinx/util/inspect.py-- a/sphinx/util/inspect.py++ b/sphinx/util/inspect.py


if ispartial(obj) and doc == obj.__class__.__doc__:         return getdoc(obj.func)     elif doc is None and allow_inherited:        doc = inspect.getdoc(obj)        if doc is None and cls and name:            # inspect.getdoc() does not support some kind of inherited and decorated methods.            # This tries to obtain the docstring from super classes.            for basecls in getattr(cls, '__mro__', []):        if cls and name:            # Check a docstring of the attribute or method from super classes.            for basecls in getmro(cls):                 meth = safe_getattr(basecls, name, None)                 if meth is not None:                    doc = inspect.getdoc(meth)                    if doc:                    doc = attrgetter(meth, '__doc__', None)                    if doc is not None:                         break             if doc is None:                # retry using `inspect.getdoc()`                for basecls in getmro(cls):                    meth = safe_getattr(basecls, name, None)                    if meth is not None:                        doc = inspect.getdoc(meth)                        if doc is not None:                            break        if doc is None:            doc = inspect.getdoc(obj)     return doc


(object_description(key), object_description(object[key]))                      for key in sorted_keys)             return "{%s}" % ", ".join(items)    if isinstance(object, set):    elif isinstance(object, set):         try:             sorted_values = sorted(object)         except TypeError:             pass  # Cannot sort set values, fall back to generic repr         else:             return "{%s}" % ", ".join(object_description(x) for x in sorted_values)    if isinstance(object, frozenset):    elif isinstance(object, frozenset):         try:             sorted_values = sorted(object)         except TypeError:


else:             return "frozenset({%s})" % ", ".join(object_description(x)                                                  for x in sorted_values)<ins>    elif isinstance(object, enum.Enum):        return "%s.%s" % (object.__class__.__name__, object.name)</ins>     try:         s = repr(object)     except Exception as exc:


for node in result.traverse(nodes.Text):                 node.parent[node.parent.index(node)] = nodes.Text(text)                 break<ins>        elif isinstance(result, pending_xref) and env.config.python_use_unqualified_type_names:            children = result.children            result.clear()            shortname = target.split('.')[-1]            textnode = innernode('', shortname)            contnodes = [pending_xref_condition('', '', textnode, condition='resolved'),                         pending_xref_condition('', '', *children, condition='*')]            result.extend(contnodes)</ins>         return result      def make_xrefs(self, rolename: str, domain: str, target: str,


from docutils import nodes from docutils.nodes import Element from requests import Responsefrom requests.exceptions import HTTPError, TooManyRedirectsfrom requests.exceptions import ConnectionError, HTTPError, TooManyRedirects  from sphinx.application import Sphinx from sphinx.builders.dummy import DummyBuilder


config=self.config, auth=auth_info,                                                  **kwargs)                         response.raise_for_status()                    except (HTTPError, TooManyRedirects) as err:                    # Servers drop the connection on HEAD requests, causing                    # ConnectionError.                    except (ConnectionError, HTTPError, TooManyRedirects) as err:                         if isinstance(err, HTTPError) and err.response.status_code == 429:                             raise                         # retry with GET request if that fails, some servers


return x  <ins>def is_path_or_empty(x: str) -> str:    if x == '':        return x    return is_path(x)</ins> def allow_empty(x: str) -> str:     return x


print(__('sphinx-quickstart will not overwrite existing Sphinx projects.'))         print()         d['path'] = do_prompt(__('Please enter a new root path (or just Enter to exit)'),                              '', is_path)                              '', is_path_or_empty)         if not d['path']:             sys.exit(1)


for node in self.document.traverse(matcher):  # type: TextElement             if any(matcher(subnode) for subnode in node):                 pos = node.parent.index(node)                for subnode in reversed(node[1:]):                for subnode in reversed(list(node)):                     node.remove(subnode)                     if matcher(subnode):                         node.parent.insert(pos + 1, subnode)                     else:                         newnode = node.__class__('', '', subnode, **node.attributes)                         node.parent.insert(pos + 1, newnode)                # move node if all children became siblings of the node                if not len(node):                    node.parent.remove(node)   class ManualPageTranslator(SphinxTranslator, BaseTranslator):


return "%s %s" % (self.visit(node.op), self.visit(node.operand))      def visit_Tuple(self, node: ast.Tuple) -> str:        if node.elts:            return "(" + ", ".join(self.visit(e) for e in node.elts) + ")"        else:        if len(node.elts) == 0:             return "()"        elif len(node.elts) == 1:            return "(%s,)" % self.visit(node.elts[0])        else:            return "(" + ", ".join(self.visit(e) for e in node.elts) + ")"      if sys.version_info < (3, 8):         # these ast nodes were deprecated in python 3.8


self.add_line('   :annotation: %s' % self.options.annotation,                           sourcename)         else:            # obtain annotation for this data            annotations = get_type_hints(self.parent, None, self.config.autodoc_type_aliases)            if self.objpath[-1] in annotations:                objrepr = stringify_typehint(annotations.get(self.objpath[-1]))                self.add_line('   :type: ' + objrepr, sourcename)            if self.config.autodoc_typehints != 'none':                # obtain annotation for this data                annotations = get_type_hints(self.parent, None,                                             self.config.autodoc_type_aliases)                if self.objpath[-1] in annotations:                    objrepr = stringify_typehint(annotations.get(self.objpath[-1]))                    self.add_line('   :type: ' + objrepr, sourcename)              try:                 if self.options.no_value or self.should_suppress_value_header():


elif self.options.annotation:             self.add_line('   :annotation: %s' % self.options.annotation, sourcename)         else:            # obtain type annotation for this attribute            annotations = get_type_hints(self.parent, None, self.config.autodoc_type_aliases)            if self.objpath[-1] in annotations:                objrepr = stringify_typehint(annotations.get(self.objpath[-1]))                self.add_line('   :type: ' + objrepr, sourcename)            if self.config.autodoc_typehints != 'none':                # obtain type annotation for this attribute                annotations = get_type_hints(self.parent, None,                                             self.config.autodoc_type_aliases)                if self.objpath[-1] in annotations:                    objrepr = stringify_typehint(annotations.get(self.objpath[-1]))                    self.add_line('   :type: ' + objrepr, sourcename)              try:                 if self.options.no_value or self.should_suppress_value_header():


if inspect.isabstractmethod(self.object):             self.add_line('   :abstractmethod:', sourcename)         if safe_getattr(self.object, 'fget', None):        if safe_getattr(self.object, 'fget', None) and self.config.autodoc_typehints != 'none':             try:                 signature = inspect.signature(self.object.fget,                                               type_aliases=self.config.autodoc_type_aliases)


import sys import time from os import pathfrom typing import IO, Any, Dict, List, Tuplefrom typing import IO, Any, Dict, List, Optional, Tuple from urllib.parse import urlsplit, urlunsplit  from docutils import nodesfrom docutils.nodes import TextElementfrom docutils.nodes import Element, TextElement from docutils.utils import relative_path  import sphinx


from sphinx.application import Sphinx from sphinx.builders.html import INVENTORY_FILENAME from sphinx.config import Configfrom sphinx.domains import Domain from sphinx.environment import BuildEnvironment from sphinx.locale import _, __ from sphinx.util import logging, requests from sphinx.util.inventory import InventoryFilefrom sphinx.util.typing import Inventoryfrom sphinx.util.typing import Inventory, InventoryItem  logger = logging.getLogger(__name__)


inventories.main_inventory.setdefault(type, {}).update(objects)  def missing_reference(app: Sphinx, env: BuildEnvironment, node: pending_xref,                      contnode: TextElement) -> nodes.reference:    """Attempt to resolve a missing reference via intersphinx references."""    target = node['reftarget']    inventories = InventoryAdapter(env)    objtypes: List[str] = None    if node['reftype'] == 'any':        # we search anything!        objtypes = ['%s:%s' % (domain.name, objtype)                    for domain in env.domains.values()                    for objtype in domain.object_types]        domain = Nonedef _create_element_from_result(domain: Domain, inv_name: Optional[str],                                data: InventoryItem,                                node: pending_xref, contnode: TextElement) -> Element:    proj, version, uri, dispname = data    if '://' not in uri and node.get('refdoc'):        # get correct path in case of subdirectories        uri = path.join(relative_path(node['refdoc'], '.'), uri)    if version:        reftitle = _('(in %s v%s)') % (proj, version)     else:        domain = node.get('refdomain')        if not domain:        reftitle = _('(in %s)') % (proj,)    newnode = nodes.reference('', '', internal=False, refuri=uri, reftitle=reftitle)    if node.get('refexplicit'):        # use whatever title was given        newnode.append(contnode)    elif dispname == '-' or \            (domain.name == 'std' and node['reftype'] == 'keyword'):        # use whatever title was given, but strip prefix        title = contnode.astext()        if inv_name is not None and title.startswith(inv_name + ':'):            newnode.append(contnode.__class__(title[len(inv_name) + 1:],                                              title[len(inv_name) + 1:]))        else:            newnode.append(contnode)    else:        # else use the given display name (used for :ref:)        newnode.append(contnode.__class__(dispname, dispname))    return newnodedef _resolve_reference_in_domain_by_target(        inv_name: Optional[str], inventory: Inventory,        domain: Domain, objtypes: List[str],        target: str,        node: pending_xref, contnode: TextElement) -> Optional[Element]:    for objtype in objtypes:        if objtype not in inventory:            # Continue if there's nothing of this kind in the inventory            continue        if target in inventory[objtype]:            # Case sensitive match, use it            data = inventory[objtype][target]        elif objtype == 'std:term':            # Check for potential case insensitive matches for terms only            target_lower = target.lower()            insensitive_matches = list(filter(lambda k: k.lower() == target_lower,                                              inventory[objtype].keys()))            if insensitive_matches:                data = inventory[objtype][insensitive_matches[0]]            else:                # No case insensitive match either, continue to the next candidate                continue        else:            # Could reach here if we're not a term but have a case insensitive match.            # This is a fix for terms specifically, but potentially should apply to            # other types.            continue        return _create_element_from_result(domain, inv_name, data, node, contnode)    return Nonedef _resolve_reference_in_domain(env: BuildEnvironment,                                 inv_name: Optional[str], inventory: Inventory,                                 honor_disabled_refs: bool,                                 domain: Domain, objtypes: List[str],                                 node: pending_xref, contnode: TextElement                                 ) -> Optional[Element]:    # we adjust the object types for backwards compatibility    if domain.name == 'std' and 'cmdoption' in objtypes:        # until Sphinx-1.6, cmdoptions are stored as std:option        objtypes.append('option')    if domain.name == 'py' and 'attribute' in objtypes:        # Since Sphinx-2.1, properties are stored as py:method        objtypes.append('method')    # the inventory contains domain:type as objtype    objtypes = ["{}:{}".format(domain.name, t) for t in objtypes]    # now that the objtypes list is complete we can remove the disabled ones    if honor_disabled_refs:        disabled = env.config.intersphinx_disabled_reftypes        objtypes = [o for o in objtypes if o not in disabled]    # without qualification    res = _resolve_reference_in_domain_by_target(inv_name, inventory, domain, objtypes,                                                 node['reftarget'], node, contnode)    if res is not None:        return res    # try with qualification of the current scope instead    full_qualified_name = domain.get_full_qualified_name(node)    if full_qualified_name is None:        return None    return _resolve_reference_in_domain_by_target(inv_name, inventory, domain, objtypes,                                                  full_qualified_name, node, contnode)def _resolve_reference(env: BuildEnvironment, inv_name: Optional[str], inventory: Inventory,                       honor_disabled_refs: bool,                       node: pending_xref, contnode: TextElement) -> Optional[Element]:    # disabling should only be done if no inventory is given    honor_disabled_refs = honor_disabled_refs and inv_name is None    if honor_disabled_refs and '*' in env.config.intersphinx_disabled_reftypes:        return None    typ = node['reftype']    if typ == 'any':        for domain_name, domain in env.domains.items():            if honor_disabled_refs \                    and (domain_name + ":*") in env.config.intersphinx_disabled_reftypes:                continue            objtypes = list(domain.object_types)            res = _resolve_reference_in_domain(env, inv_name, inventory,                                               honor_disabled_refs,                                               domain, objtypes,                                               node, contnode)            if res is not None:                return res        return None    else:        domain_name = node.get('refdomain')        if not domain_name:             # only objects in domains are in the inventory             return None        objtypes = env.get_domain(domain).objtypes_for_role(node['reftype'])        if honor_disabled_refs \                and (domain_name + ":*") in env.config.intersphinx_disabled_reftypes:            return None        domain = env.get_domain(domain_name)        objtypes = domain.objtypes_for_role(typ)         if not objtypes:             return None        objtypes = ['%s:%s' % (domain, objtype) for objtype in objtypes]    if 'std:cmdoption' in objtypes:        # until Sphinx-1.6, cmdoptions are stored as std:option        objtypes.append('std:option')    if 'py:attribute' in objtypes:        # Since Sphinx-2.1, properties are stored as py:method        objtypes.append('py:method')    to_try = [(inventories.main_inventory, target)]    if domain:        full_qualified_name = env.get_domain(domain).get_full_qualified_name(node)        if full_qualified_name:            to_try.append((inventories.main_inventory, full_qualified_name))    in_set = None    if ':' in target:        # first part may be the foreign doc set name        setname, newtarget = target.split(':', 1)        if setname in inventories.named_inventory:            in_set = setname            to_try.append((inventories.named_inventory[setname], newtarget))            if domain:                node['reftarget'] = newtarget                full_qualified_name = env.get_domain(domain).get_full_qualified_name(node)                if full_qualified_name:                    to_try.append((inventories.named_inventory[setname], full_qualified_name))    for inventory, target in to_try:        for objtype in objtypes:            if objtype not in inventory:                # Continue if there's nothing of this kind in the inventory                continue            if target in inventory[objtype]:                # Case sensitive match, use it                proj, version, uri, dispname = inventory[objtype][target]            elif objtype == 'std:term':                # Check for potential case insensitive matches for terms only                target_lower = target.lower()                insensitive_matches = list(filter(lambda k: k.lower() == target_lower,                                                  inventory[objtype].keys()))                if insensitive_matches:                    proj, version, uri, dispname = inventory[objtype][insensitive_matches[0]]                else:                    # No case insensitive match either, continue to the next candidate                    continue            else:                # Could reach here if we're not a term but have a case insensitive match.                # This is a fix for terms specifically, but potentially should apply to                # other types.                continue        return _resolve_reference_in_domain(env, inv_name, inventory,                                            honor_disabled_refs,                                            domain, objtypes,                                            node, contnode)             if '://' not in uri and node.get('refdoc'):                # get correct path in case of subdirectories                uri = path.join(relative_path(node['refdoc'], '.'), uri)            if version:                reftitle = _('(in %s v%s)') % (proj, version)            else:                reftitle = _('(in %s)') % (proj,)            newnode = nodes.reference('', '', internal=False, refuri=uri, reftitle=reftitle)            if node.get('refexplicit'):                # use whatever title was given                newnode.append(contnode)            elif dispname == '-' or \                    (domain == 'std' and node['reftype'] == 'keyword'):                # use whatever title was given, but strip prefix                title = contnode.astext()                if in_set and title.startswith(in_set + ':'):                    newnode.append(contnode.__class__(title[len(in_set) + 1:],                                                      title[len(in_set) + 1:]))                else:                    newnode.append(contnode)            else:                # else use the given display name (used for :ref:)                newnode.append(contnode.__class__(dispname, dispname))            return newnode    # at least get rid of the ':' in the target if no explicit title given    if in_set is not None and not node.get('refexplicit', True):        if len(contnode) and isinstance(contnode[0], nodes.Text):            contnode[0] = nodes.Text(newtarget, contnode[0].rawsource)     return Nonedef inventory_exists(env: BuildEnvironment, inv_name: str) -> bool:    return inv_name in InventoryAdapter(env).named_inventorydef resolve_reference_in_inventory(env: BuildEnvironment,                                   inv_name: str,                                   node: pending_xref, contnode: TextElement                                   ) -> Optional[Element]:    """Attempt to resolve a missing reference via intersphinx references.    Resolution is tried in the given inventory with the target as is.    Requires ``inventory_exists(env, inv_name)``.    """    assert inventory_exists(env, inv_name)    return _resolve_reference(env, inv_name, InventoryAdapter(env).named_inventory[inv_name],                              False, node, contnode)def resolve_reference_any_inventory(env: BuildEnvironment,                                    honor_disabled_refs: bool,                                    node: pending_xref, contnode: TextElement                                    ) -> Optional[Element]:    """Attempt to resolve a missing reference via intersphinx references.    Resolution is tried with the target as is in any inventory.    """    return _resolve_reference(env, None, InventoryAdapter(env).main_inventory,                              honor_disabled_refs,                              node, contnode)def resolve_reference_detect_inventory(env: BuildEnvironment,                                       node: pending_xref, contnode: TextElement                                       ) -> Optional[Element]:    """Attempt to resolve a missing reference via intersphinx references.    Resolution is tried first with the target as is in any inventory.    If this does not succeed, then the target is split by the first ``:``,    to form ``inv_name:newtarget``. If ``inv_name`` is a named inventory, then resolution    is tried in that inventory with the new target.    """    # ordinary direct lookup, use data as is    res = resolve_reference_any_inventory(env, True, node, contnode)    if res is not None:        return res    # try splitting the target into 'inv_name:target'    target = node['reftarget']    if ':' not in target:        return None    inv_name, newtarget = target.split(':', 1)    if not inventory_exists(env, inv_name):        return None    node['reftarget'] = newtarget    res_inv = resolve_reference_in_inventory(env, inv_name, node, contnode)    node['reftarget'] = target    return res_invdef missing_reference(app: Sphinx, env: BuildEnvironment, node: pending_xref,                      contnode: TextElement) -> Optional[Element]:    """Attempt to resolve a missing reference via intersphinx references."""    return resolve_reference_detect_inventory(env, node, contnode)   def normalize_intersphinx_mapping(app: Sphinx, config: Config) -> None:


app.add_config_value('intersphinx_mapping', {}, True)     app.add_config_value('intersphinx_cache_limit', 5, False)     app.add_config_value('intersphinx_timeout', None, False)    app.add_config_value('intersphinx_disabled_reftypes', [], True)     app.connect('config-inited', normalize_intersphinx_mapping, priority=800)     app.connect('builder-inited', load_mappings)     app.connect('missing-reference', missing_reference)diff --git a/sphinx/util/typing.py b/sphinx/util/typing.py-- a/sphinx/util/typing.py++ b/sphinx/util/typing.py


TitleGetter = Callable[[nodes.Node], str]  # inventory data on memoryInventory = Dict[str, Dict[str, Tuple[str, str, str, str]]]InventoryItem = Tuple[str, str, str, str]Inventory = Dict[str, Dict[str, InventoryItem]]   def get_type_hints(obj: Any, globalns: Dict = None, localns: Dict = None) -> Dict[str, Any]:


option_spec = PyObject.option_spec.copy()     option_spec.update({         'abstractmethod': directives.flag,<ins>        'classmethod': directives.flag,</ins>         'type': directives.unchanged,     })


return fullname, prefix      def get_signature_prefix(self, sig: str) -> str:        prefix = ['property']        prefix = []         if 'abstractmethod' in self.options:            prefix.insert(0, 'abstract')            prefix.append('abstract')        if 'classmethod' in self.options:            prefix.append('class')         prefix.append('property')         return ' '.join(prefix) + ' '      def get_index_text(self, modname: str, name_cls: Tuple[str, str]) -> str:diff --git a/sphinx/ext/autodoc/__init__.py b/sphinx/ext/autodoc/__init__.py-- a/sphinx/ext/autodoc/__init__.py++ b/sphinx/ext/autodoc/__init__.py


isattr = False              doc = getdoc(member, self.get_attr, self.config.autodoc_inherit_docstrings,                         self.parent, self.object_name)                         self.object, membername)             if not isinstance(doc, str):                 # Ignore non-string __doc__                 doc = None


@classmethod     def can_document_member(cls, member: Any, membername: str, isattr: bool, parent: Any                             ) -> bool:        return inspect.isproperty(member) and isinstance(parent, ClassDocumenter)        if isinstance(parent, ClassDocumenter):            if inspect.isproperty(member):                return True            else:                __dict__ = safe_getattr(parent.object, '__dict__', {})                obj = __dict__.get(membername)                return isinstance(obj, classmethod) and inspect.isproperty(obj.__func__)        else:            return False    def import_object(self, raiseerror: bool = False) -> bool:        """Check the exisitence of uninitialized instance attribute when failed to import        the attribute."""        ret = super().import_object(raiseerror)        if ret and not inspect.isproperty(self.object):            __dict__ = safe_getattr(self.parent, '__dict__', {})            obj = __dict__.get(self.objpath[-1])            if isinstance(obj, classmethod) and inspect.isproperty(obj.__func__):                self.object = obj.__func__                self.isclassmethod = True                return True            else:                return False        self.isclassmethod = False        return ret      def document_members(self, all_members: bool = False) -> None:         pass


sourcename = self.get_sourcename()         if inspect.isabstractmethod(self.object):             self.add_line('   :abstractmethod:', sourcename)        if self.isclassmethod:            self.add_line('   :classmethod:', sourcename)          if safe_getattr(self.object, 'fget', None) and self.config.autodoc_typehints != 'none':             try:diff --git a/sphinx/util/inspect.py b/sphinx/util/inspect.py-- a/sphinx/util/inspect.py++ b/sphinx/util/inspect.py


return isinstance(obj, (partial, partialmethod))  def isclassmethod(obj: Any) -> bool:def isclassmethod(obj: Any, cls: Any = None, name: str = None) -> bool:     """Check if the object is classmethod."""     if isinstance(obj, classmethod):         return True     elif inspect.ismethod(obj) and obj.__self__ is not None and isclass(obj.__self__):         return True    elif cls and name:        for basecls in getmro(cls):            meth = basecls.__dict__.get(name)            if meth:                return isclassmethod(meth)      return False


* inherited docstring     * inherited decorated methods     """<ins>    if cls and name and isclassmethod(obj, cls, name):        for basecls in getmro(cls):            meth = basecls.__dict__.get(name)            if meth:                return getdoc(meth.__func__)</ins>     doc = attrgetter(obj, '__doc__', None)     if ispartial(obj) and doc == obj.__class__.__doc__:         return getdoc(obj.func)


return INVALID_BUILTIN_CLASSES[annotation]     elif (getattr(annotation, '__module__', None) == 'builtins' and           hasattr(annotation, '__qualname__')):        return annotation.__qualname__        if hasattr(annotation, '__args__'):  # PEP 585 generic            return repr(annotation)        else:            return annotation.__qualname__     elif annotation is Ellipsis:         return '...'


app.add_event('linkcheck-process-uri')      app.connect('config-inited', compile_linkcheck_allowed_redirects, priority=800)    app.connect('linkcheck-process-uri', rewrite_github_anchor)    # FIXME: Disable URL rewrite handler for github.com temporarily.    # ref: https://github.com/sphinx-doc/sphinx/issues/9435    # app.connect('linkcheck-process-uri', rewrite_github_anchor)      return {         'version': 'builtin',


_string_re = re.compile(r"[LuU8]?('([^'\\]*(?:\\.[^'\\]*)*)'"                         r'|"([^"\\]*(?:\\.[^"\\]*)*)")', re.S) <ins>_simple_type_sepcifiers_re = re.compile(r"""(?x)    \b(    void|_Bool|bool    # Integer    # -------    |((signed|unsigned)\s+)?(char|(        ((long\s+long|long|short)\s+)?int    ))    |__uint128|__int128    # extensions    |((signed|unsigned)\s+)?__int(8|16|32|64|128)    # Floating-point    # --------------    |(float|double|long\s+double)(\s+(_Complex|complex|_Imaginary|imaginary))?    |(_Complex|complex|_Imaginary|imaginary)\s+(float|double|long\s+double)    |_Decimal(32|64|128)    # extensions    |__float80|_Float64x|__float128|_Float128|__ibm128    |__fp16    # Fixed-point, extension    |(_Sat\s+)?((signed|unsigned)\s+)?((short|long|long\s+long)\s+)?(_Fract|fract|_Accum|accum)    # Integer types that could be prefixes of the previous ones    # ---------------------------------------------------------    |((signed|unsigned)\s+)?(long\s+long|long|short)    |signed|unsigned    )\b""")</ins>  class _DuplicateSymbolError(Exception):     def __init__(self, symbol: "Symbol", declaration: "ASTDeclaration") -> None:


class ASTTrailingTypeSpecFundamental(ASTTrailingTypeSpec):     def __init__(self, name: str) -> None:        self.name = name        self.names = name.split()      def _stringify(self, transform: StringifyTransform) -> str:        return self.name        return ' '.join(self.names)      def describe_signature(self, signode: TextElement, mode: str,                            env: "BuildEnvironment", symbol: "Symbol") -> None:        signode += addnodes.desc_sig_keyword_type(self.name, self.name)        first = True        for n in self.names:            if not first:                signode += addnodes.desc_sig_space()            else:                first = False            signode += addnodes.desc_sig_keyword_type(n, n)   class ASTTrailingTypeSpecName(ASTTrailingTypeSpec):


class DefinitionParser(BaseParser):<del>    # those without signedness and size modifiers    # see https://en.cppreference.com/w/cpp/language/types    _simple_fundamental_types = (        'void', '_Bool', 'bool', 'char', 'int', 'float', 'double',        '__int64',    )    _prefix_keys = ('struct', 'enum', 'union')</del>     @property     def language(self) -> str:         return 'C'


return ASTNestedName(names, rooted)      def _parse_trailing_type_spec(self) -> ASTTrailingTypeSpec:        # fundamental types        # fundamental types, https://en.cppreference.com/w/c/language/type        # and extensions         self.skip_ws()        for t in self._simple_fundamental_types:            if self.skip_word(t):                return ASTTrailingTypeSpecFundamental(t)        # TODO: this could/should be more strict        elements = []        if self.skip_word_and_ws('signed'):            elements.append('signed')        elif self.skip_word_and_ws('unsigned'):            elements.append('unsigned')        while 1:            if self.skip_word_and_ws('short'):                elements.append('short')            elif self.skip_word_and_ws('long'):                elements.append('long')            else:                break        if self.skip_word_and_ws('char'):            elements.append('char')        elif self.skip_word_and_ws('int'):            elements.append('int')        elif self.skip_word_and_ws('double'):            elements.append('double')        elif self.skip_word_and_ws('__int64'):            elements.append('__int64')        if len(elements) > 0:            return ASTTrailingTypeSpecFundamental(' '.join(elements))        if self.match(_simple_type_sepcifiers_re):            return ASTTrailingTypeSpecFundamental(self.matched_text)          # prefixed         prefix = None         self.skip_ws()        for k in self._prefix_keys:        for k in ('struct', 'enum', 'union'):             if self.skip_word_and_ws(k):                 prefix = k                 breakdiff --git a/sphinx/domains/cpp.py b/sphinx/domains/cpp.py-- a/sphinx/domains/cpp.py++ b/sphinx/domains/cpp.py


'while', 'xor', 'xor_eq' ] <ins>_simple_type_sepcifiers_re = re.compile(r"""(?x)    \b(    auto|void|bool    # Integer    # -------    |((signed|unsigned)\s+)?(char|__int128|(        ((long\s+long|long|short)\s+)?int    ))    |wchar_t|char(8|16|32)_t    # extensions    |((signed|unsigned)\s+)?__int(64|128)    # Floating-point    # --------------    |(float|double|long\s+double)(\s+(_Complex|_Imaginary))?    |(_Complex|_Imaginary)\s+(float|double|long\s+double)    # extensions    |__float80|_Float64x|__float128|_Float128    # Integer types that could be prefixes of the previous ones    # ---------------------------------------------------------    |((signed|unsigned)\s+)?(long\s+long|long|short)    |signed|unsigned    )\b""")</ins> _max_id = 4 _id_prefix = [None, '', '_CPPv2', '_CPPv3', '_CPPv4'] # Ids are used in lookup keys which are used across pickled files,


'long long int': 'x',     'signed long long': 'x',     'signed long long int': 'x',    '__int64': 'x',     'unsigned long long': 'y',     'unsigned long long int': 'y',    '__int128': 'n',    'signed __int128': 'n',    'unsigned __int128': 'o',     'float': 'f',     'double': 'd',     'long double': 'e',    '__float80': 'e', '_Float64x': 'e',    '__float128': 'g', '_Float128': 'g',    'float _Complex': 'Cf', '_Complex float': 'Cf',    'double _Complex': 'Cd', '_Complex double': 'Cd',    'long double _Complex': 'Ce', '_Complex long double': 'Ce',    'float _Imaginary': 'f', '_Imaginary float': 'f',    'double _Imaginary': 'd', '_Imaginary double': 'd',    'long double _Imaginary': 'e', '_Imaginary long double': 'e',     'auto': 'Da',     'decltype(auto)': 'Dc',     'std::nullptr_t': 'Dn'


class ASTTrailingTypeSpecFundamental(ASTTrailingTypeSpec):     def __init__(self, name: str) -> None:        self.name = name        self.names = name.split()      def _stringify(self, transform: StringifyTransform) -> str:        return self.name        return ' '.join(self.names)      def get_id(self, version: int) -> str:         if version == 1:             res = []            for a in self.name.split(' '):            for a in self.names:                 if a in _id_fundamental_v1:                     res.append(_id_fundamental_v1[a])                 else:                     res.append(a)             return '-'.join(res)         if self.name not in _id_fundamental_v2:        txt = str(self)        if txt not in _id_fundamental_v2:             raise Exception(                 'Semi-internal error: Fundamental type "%s" can not be mapped '                'to an id. Is it a true fundamental type? If not so, the '                'parser should have rejected it.' % self.name)        return _id_fundamental_v2[self.name]                'to an ID. Is it a true fundamental type? If not so, the '                'parser should have rejected it.' % txt)        return _id_fundamental_v2[txt]      def describe_signature(self, signode: TextElement, mode: str,                            env: "BuildEnvironment", symbol: "Symbol") -> None:        signode += addnodes.desc_sig_keyword_type(self.name, self.name)        first = True        for n in self.names:            if not first:                signode += addnodes.desc_sig_space()            else:                first = False            signode += addnodes.desc_sig_keyword_type(n, n)   class ASTTrailingTypeSpecDecltypeAuto(ASTTrailingTypeSpec):


class DefinitionParser(BaseParser):<del>    # those without signedness and size modifiers    # see https://en.cppreference.com/w/cpp/language/types    _simple_fundemental_types = (        'void', 'bool', 'char', 'wchar_t', 'char8_t', 'char16_t', 'char32_t',        'int', 'float', 'double', 'auto'    )    _prefix_keys = ('class', 'struct', 'enum', 'union', 'typename')</del>     @property     def language(self) -> str:         return 'C++'


# ==========================================================================      def _parse_trailing_type_spec(self) -> ASTTrailingTypeSpec:        # fundemental types        # fundamental types, https://en.cppreference.com/w/cpp/language/type        # and extensions         self.skip_ws()        for t in self._simple_fundemental_types:            if self.skip_word(t):                return ASTTrailingTypeSpecFundamental(t)        # TODO: this could/should be more strict        elements = []        if self.skip_word_and_ws('signed'):            elements.append('signed')        elif self.skip_word_and_ws('unsigned'):            elements.append('unsigned')        while 1:            if self.skip_word_and_ws('short'):                elements.append('short')            elif self.skip_word_and_ws('long'):                elements.append('long')            else:                break        if self.skip_word_and_ws('char'):            elements.append('char')        elif self.skip_word_and_ws('int'):            elements.append('int')        elif self.skip_word_and_ws('double'):            elements.append('double')        if len(elements) > 0:            return ASTTrailingTypeSpecFundamental(' '.join(elements))        if self.match(_simple_type_sepcifiers_re):            return ASTTrailingTypeSpecFundamental(self.matched_text)          # decltype         self.skip_ws()


# prefixed         prefix = None         self.skip_ws()        for k in self._prefix_keys:        for k in ('class', 'struct', 'enum', 'union', 'typename'):             if self.skip_word_and_ws(k):                 prefix = k                 break


typ = self.options.get('type')         if typ:            signode += addnodes.desc_annotation(typ, ': ' + typ)            annotations = _parse_annotation(typ, self.env)            signode += addnodes.desc_annotation(typ, '', nodes.Text(': '), *annotations)          return fullname, prefix


if node.value is Ellipsis:                 return [addnodes.desc_sig_punctuation('', "...")]             else:                return [nodes.Text(node.value)]                return [nodes.Text(repr(node.value))]         elif isinstance(node, ast.Expr):             return unparse(node.value)         elif isinstance(node, ast.Index):


result.append(addnodes.desc_sig_punctuation('', '['))             result.extend(unparse(node.slice))             result.append(addnodes.desc_sig_punctuation('', ']'))<ins>            # Wrap the Text nodes inside brackets by literal node if the subscript is a Literal            if result[0] in ('Literal', 'typing.Literal'):                for i, subnode in enumerate(result[1:], start=1):                    if isinstance(subnode, nodes.Text):                        result[i] = nodes.literal('', '', subnode)</ins>             return result         elif isinstance(node, ast.Tuple):             if node.elts:


tree = ast_parse(annotation)         result = unparse(tree)         for i, node in enumerate(result):            if isinstance(node, nodes.Text) and node.strip():            if isinstance(node, nodes.literal):                result[i] = node[0]            elif isinstance(node, nodes.Text) and node.strip():                 result[i] = type_to_xref(str(node), env)         return result     except SyntaxError:


# add inheritance info, if wanted         if not self.doc_as_attr and self.options.show_inheritance:            if hasattr(self.object, '__orig_bases__') and len(self.object.__orig_bases__):            if inspect.getorigbases(self.object):                 # A subclass of generic types                 # refs: PEP-560 <https://www.python.org/dev/peps/pep-0560/>                 bases = list(self.object.__orig_bases__)diff --git a/sphinx/util/inspect.py b/sphinx/util/inspect.py-- a/sphinx/util/inspect.py++ b/sphinx/util/inspect.py


return tuple()  <ins>def getorigbases(obj: Any) -> Optional[Tuple[Any, ...]]:    """Get __orig_bases__ from *obj* safely."""    if not inspect.isclass(obj):        return None    # Get __orig_bases__ from obj.__dict__ to avoid accessing the parent's __orig_bases__.    # refs: https://github.com/sphinx-doc/sphinx/issues/9607    __dict__ = safe_getattr(obj, '__dict__', {})    __orig_bases__ = __dict__.get('__orig_bases__')    if isinstance(__orig_bases__, tuple) and len(__orig_bases__) > 0:        return __orig_bases__    else:        return None</ins> def getslots(obj: Any) -> Optional[Dict]:     """Get __slots__ attribute of the class as dict.


"""Used by autodoc_mock_imports."""      __display_name__ = '_MockObject'<ins>    __name__ = ''</ins>     __sphinx_mock__ = True     __sphinx_decorator_args__: Tuple[Any, ...] = ()


return super().__new__(cls)      def __init__(self, *args: Any, **kwargs: Any) -> None:        self.__qualname__ = ''        self.__qualname__ = self.__name__      def __len__(self) -> int:         return 0


attributes: Any = None, decorator_args: Tuple = ()) -> Any:     attrs = {'__module__': module,              '__display_name__': module + '.' + name,<ins>             '__name__': name,</ins>              '__sphinx_decorator_args__': decorator_args}     attrs.update(attributes or {})


return ':py:obj:`None`'         elif cls is Ellipsis:             return '...'<ins>        elif isinstance(cls, str):            return cls</ins>         elif cls in INVALID_BUILTIN_CLASSES:             return ':py:class:`%s`' % INVALID_BUILTIN_CLASSES[cls]         elif inspect.isNewType(cls):


elif parts[0] == 'type':             name = ' '.join(parts[1:])             has_type.add(name)        elif parts[0] == 'return':        elif parts[0] in ('return', 'returns'):             has_description.add('return')         elif parts[0] == 'rtype':             has_type.add('return')      # Add 'type' for parameters with a description but no declared type.     for name in annotations:        if name == 'return':        if name in ('return', 'returns'):             continue         if name in has_description and name not in has_type:             field = nodes.field()


if 'classmethod' in self.options:             return _('%s() (%s class method)') % (methname, clsname)         elif 'property' in self.options:            return _('%s() (%s property)') % (methname, clsname)            return _('%s (%s property)') % (methname, clsname)         elif 'staticmethod' in self.options:             return _('%s() (%s static method)') % (methname, clsname)         else:


from typing import TYPE_CHECKING, Any, Dict <ins>from packaging.version import InvalidVersion, Version</ins> from sphinx.config import Config from sphinx.errors import VersionRequirementError from sphinx.locale import __


'but it is not loaded.'), extname)             continue         if extension.version == 'unknown version' or reqversion > extension.version:        fulfilled = True        if extension.version == 'unknown version':            fulfilled = False        else:            try:                if Version(reqversion) > Version(extension.version):                    fulfilled = False            except InvalidVersion:                if reqversion > extension.version:                    fulfilled = False        if not fulfilled:             raise VersionRequirementError(__('This project needs the extension %s at least in '                                              'version %s and therefore cannot be built with '                                              'the loaded version (%s).') %


for basecls in getmro(cls):             meth = basecls.__dict__.get(name)             if meth and hasattr(meth, '__func__'):                return getdoc(meth.__func__)                doc = getdoc(meth.__func__)                if doc is not None or not allow_inherited:                    return doc      doc = attrgetter(obj, '__doc__', None)     if ispartial(obj) and doc == obj.__class__.__doc__:


split_contnode = bool(contnode and contnode.astext() == target)         in_literal = False         results = []         for sub_target in filter(None, sub_targets):             if split_contnode:                 contnode = nodes.Text(sub_target)             if delims_re.match(sub_target):            if in_literal or delims_re.match(sub_target):                 results.append(contnode or innernode(sub_target, sub_target))             else:                 results.append(self.make_xref(rolename, domain, sub_target,                                               innernode, contnode, env, inliner, location))             if sub_target in ('Literal', 'typing.Literal'):                in_literal = True         return results


import ast import inspectfrom typing import Any, Dictimport sysfrom typing import Any, Dict, List, Optional  from sphinx.application import Sphinx from sphinx.locale import __


return None  def get_default_value(lines: List[str], position: ast.AST) -> Optional[str]:    try:        if sys.version_info < (3, 8):  # only for py38+            return None        elif position.lineno == position.end_lineno:            line = lines[position.lineno - 1]            return line[position.col_offset:position.end_col_offset]        else:            # multiline value is not supported now            return None    except (AttributeError, IndexError):        return None def update_defvalue(app: Sphinx, obj: Any, bound_method: bool) -> None:     """Update defvalue info of *obj* using type_comments."""     if not app.config.autodoc_preserve_defaults:         return     try:        lines = inspect.getsource(obj).splitlines()        if lines[0].startswith((' ', r'\t')):            lines.insert(0, '')  # insert a dummy line to follow what get_function_def() does.    except OSError:        lines = []     try:         function = get_function_def(obj)         if function.args.defaults or function.args.kw_defaults:


for i, param in enumerate(parameters):                 if param.default is not param.empty:                     if param.kind in (param.POSITIONAL_ONLY, param.POSITIONAL_OR_KEYWORD):                        value = DefaultValue(ast_unparse(defaults.pop(0)))  # type: ignore                        parameters[i] = param.replace(default=value)                        default = defaults.pop(0)                        value = get_default_value(lines, default)                        if value is None:                            value = ast_unparse(default)  # type: ignore                        parameters[i] = param.replace(default=DefaultValue(value))                     else:                        value = DefaultValue(ast_unparse(kw_defaults.pop(0)))  # type: ignore                        parameters[i] = param.replace(default=value)                        default = kw_defaults.pop(0)                        value = get_default_value(lines, default)                        if value is None:                            value = ast_unparse(default)  # type: ignore                        parameters[i] = param.replace(default=DefaultValue(value))             sig = sig.replace(parameters=parameters)             obj.__signature__ = sig     except (AttributeError, TypeError):


self.config.language, self.config.source_encoding)             for catalog in repo.catalogs:                 if catalog.domain == 'sphinx' and catalog.is_outdated():                    catalog.write_mo(self.config.language)                    catalog.write_mo(self.config.language,                                     self.config.gettext_allow_fuzzy_translations)              locale_dirs: List[Optional[str]] = list(repo.locale_dirs)             locale_dirs += [None]diff --git a/sphinx/builders/__init__.py b/sphinx/builders/__init__.py-- a/sphinx/builders/__init__.py++ b/sphinx/builders/__init__.py


for catalog in status_iterator(catalogs, __('writing output... '), "darkgreen",                                        len(catalogs), self.app.verbosity,                                        stringify_func=cat2relpath):            catalog.write_mo(self.config.language)            catalog.write_mo(self.config.language,                             self.config.gettext_allow_fuzzy_translations)      def compile_all_catalogs(self) -> None:         repo = CatalogRepository(self.srcdir, self.config.locale_dirs,diff --git a/sphinx/config.py b/sphinx/config.py-- a/sphinx/config.py++ b/sphinx/config.py


'language': (None, 'env', [str]),         'locale_dirs': (['locales'], 'env', []),         'figure_language_filename': ('{root}.{language}{ext}', 'env', [str]),        'gettext_allow_fuzzy_translations': (False, 'gettext', []),          'master_doc': ('index', 'env', []),         'root_doc': (lambda config: config.master_doc, 'env', []),diff --git a/sphinx/util/i18n.py b/sphinx/util/i18n.py-- a/sphinx/util/i18n.py++ b/sphinx/util/i18n.py


not path.exists(self.mo_path) or             path.getmtime(self.mo_path) < path.getmtime(self.po_path))     def write_mo(self, locale: str) -> None:    def write_mo(self, locale: str, use_fuzzy: bool = False) -> None:         with open(self.po_path, encoding=self.charset) as file_po:             try:                 po = read_po(file_po, locale)


with open(self.mo_path, 'wb') as file_mo:             try:                write_mo(file_mo, po)                write_mo(file_mo, po, use_fuzzy)             except Exception as exc:                 logger.warning(__('writing error: %s, %s'), self.mo_path, exc)


domain = cast(MathDomain, app.env.get_domain('math'))     if app.registry.html_assets_policy == 'always' or domain.has_equations(pagename):         # Enable mathjax only if equations exists        options = {'async': 'async'}        options = {'defer': 'defer'}         if app.config.mathjax_options:             options.update(app.config.mathjax_options)         app.add_js_file(app.config.mathjax_path, **options)  # type: ignore


deprecated: bool  def type_to_xref(text: str, env: BuildEnvironment = None) -> addnodes.pending_xref:def type_to_xref(target: str, env: BuildEnvironment = None) -> addnodes.pending_xref:     """Convert a type string to a cross reference node."""    if text == 'None':    if target == 'None':         reftype = 'obj'     else:         reftype = 'class'


else:         kwargs = {} <ins>    refspecific = False    if target.startswith('.'):        target = target[1:]        text = target        refspecific = True    elif target.startswith('~'):        target = target[1:]        text = target.split('.')[-1]    else:        text = target</ins>     if env.config.python_use_unqualified_type_names:         # Note: It would be better to use qualname to describe the object to support support         # nested classes.  But python domain can't access the real python object because this


contnodes = [nodes.Text(text)]      return pending_xref('', *contnodes,                        refdomain='py', reftype=reftype, reftarget=text, **kwargs)                        refdomain='py', reftype=reftype, reftarget=target,                        refspecific=refspecific, **kwargs)   def _parse_annotation(annotation: str, env: BuildEnvironment = None) -> List[Node]:


class SphinxWarningLogRecord(SphinxLogRecord):     """Warning log record class supporting location"""    prefix = 'WARNING: '    @property    def prefix(self) -> str:  # type: ignore        if self.levelno >= logging.CRITICAL:            return 'CRITICAL: '        elif self.levelno >= logging.ERROR:            return 'ERROR: '        else:            return 'WARNING: '   class SphinxLoggerAdapter(logging.LoggerAdapter):


"""Returns the name of the first argument if in a function."""         if self.current_function and self.current_function.args.args:             return self.current_function.args.args[0]<ins>        elif (self.current_function and              getattr(self.current_function.args, 'posonlyargs', None)):            # for py38+            return self.current_function.args.posonlyargs[0]  # type: ignore</ins>         else:             return None


ctx = r'\phantomsection'             for node_id in node['ids']:                 ctx += self.hypertarget(node_id, anchor=False)        ctx += r'}] \leavevmode'        self.body.append(r'\item[{')        ctx += r'}'        self.body.append(r'\sphinxlineitem{')         self.context.append(ctx)      def depart_term(self, node: Element) -> None:


return self._print_Add(s.truncate()) + self._print(' + \ldots')      def _print_FormalPowerSeries(self, s):        return self._print_Add(s.truncate())        return self._print_Add(s.infinite)      def _print_FiniteField(self, expr):         return r"\mathbb{F}_{%s}" % expr.moddiff --git a/sympy/printing/pretty/pretty.py b/sympy/printing/pretty/pretty.py-- a/sympy/printing/pretty/pretty.py++ b/sympy/printing/pretty/pretty.py


return self._print_Add(s.truncate()) + self._print(dots)      def _print_FormalPowerSeries(self, s):        return self._print_Add(s.truncate())        return self._print_Add(s.infinite)      def _print_SeqFormula(self, s):         if self._use_unicode:


else:             return name <ins>    def _print_Relational(self, expr):        lhs_code = self._print(expr.lhs)        rhs_code = self._print(expr.rhs)        op = expr.rel_op        return ("{0} {1} {2}").format(lhs_code, op, rhs_code)    def _print_sinc(self, expr):        from sympy.functions.elementary.trigonometric import sin        from sympy.core.relational import Ne        from sympy.functions import Piecewise        _piecewise = Piecewise(            (sin(expr.args[0]) / expr.args[0], Ne(expr.args[0], 0)), (1, True))        return self._print(_piecewise)</ins>     def _print_AugmentedAssignment(self, expr):         lhs_code = self._print(expr.lhs)         op = expr.rel_op


diop_type = "cubic_thue"      elif (total_degree > 3 and total_degree % 2 == 0 and            all(k.is_Pow for k in coeff if k != 1)):            all(k.is_Pow and k.exp == total_degree for k in coeff if k != 1)):         if all(coeff[k] == 1 for k in coeff if k != 1):             diop_type = 'general_sum_of_even_powers'


sqrt(x**2 + y**2)          """<ins>        if type(p) is not type(self):            if len(p) == len(self):                return sqrt(sum([(a - b)**2 for a, b in zip(                    self.args, p.args if isinstance(p, Point) else p)]))            else:                p1 = [0] * max(len(p), len(self))                p2 = p.args if len(p.args) > len(self.args) else self.args                for i in range(min(len(p), len(self))):                    p1[i] = p.args[i] if len(p) < len(self) else self.args[i]                return sqrt(sum([(a - b)**2 for a, b in zip(                    p1, p2)]))</ins>         return sqrt(sum([(a - b)**2 for a, b in zip(             self.args, p.args if isinstance(p, Point) else p)]))


>>> cos(_)     0.73908513321516064165531208767387340401341175890076     mpmath.findroot is used, you can find there more extensive documentation,    especially concerning keyword parameters and available solvers. Note,    however, that this routine works only with the numerator of the function    in the one-dimensional case, and for very steep functions near the root    this may lead to a failure in the verification of the root. In this case    you should use the flag `verify=False` and independently verify the    solution.    mpmath.findroot is used and you can find there more extensive    documentation, especially concerning keyword parameters and    available solvers. Note, however, that functions which are very    steep near the root the verification of the solution may fail. In    this case you should use the flag `verify=False` and    independently verify the solution.      >>> from sympy import cos, cosh     >>> from sympy.abc import i


>>> bounds = lambda i: (3.14*i, 3.14*(i + 1))     >>> nsolve(f, bounds(100), solver='bisect', verify=False)     315.730061685774<ins>    Alternatively, a function may be better behaved when the    denominator is ignored. Since this is not always the case, however,    the decision of what function to use is left to the discretion of    the user.    >>> eq = x**2/(1 - x)/(1 - 2*x)**2 - 100    >>> nsolve(eq, 0.46)    Traceback (most recent call last):    ...    ValueError: Could not find root within given tolerance. (10000 > 2.1684e-19)    Try another starting point or tweak arguments.    >>> nsolve(eq.as_numer_denom()[0], 0.46)    0.46792545969349058</ins>     """     # there are several other SymPy functions that use method= so     # guard against that here


expected a one-dimensional and numerical function'''))          # the function is much better behaved if there is no denominator        f = f.as_numer_denom()[0]        # but sending the numerator is left to the user since sometimes        # the function is better behaved when the denominator is present        # e.g., issue 11768          f = lambdify(fargs, f, modules)         return Float(findroot(f, x0, **kwargs))


pform = base**n             return pform         else:            return self._print_Function(e)            n = self._print(e.args[2])            shift = self._print(e.args[0]-e.args[1])            base = self._print_seq(shift, "<", ">", ' ')            return base**n      def _print_gamma(self, e):         if self._use_unicode:


if end == start and (left_open or right_open):             return S.EmptySet         if end == start and not (left_open or right_open):<ins>            if start == S.Infinity or start == S.NegativeInfinity:                return S.EmptySet</ins>             return FiniteSet(end)          # Make sure infinite interval end points are open.


"""         return self.sets._measure <ins>    @classmethod    def from_real(cls, sets):        """        Converts given subset of real numbers to a complex region.        Examples        ========        >>> from sympy import Interval, ComplexRegion        >>> unit = Interval(0,1)        >>> ComplexRegion.from_real(unit)        ComplexRegion([0, 1] x {0}, False)        """        if not sets.is_subset(S.Reals):            raise ValueError("sets must be a subset of the real line")        return cls(sets * FiniteSet(0))</ins>     def _contains(self, other):         from sympy.functions import arg, Abs         from sympy.core.containers import Tuple


return ComplexRegion(new_r_interval*new_theta_interval,                                     polar=True) <del>        if other is S.Reals:            return other</del>          if other.is_subset(S.Reals):             new_interval = []


def _union(self, other): <ins>        if other.is_subset(S.Reals):            # treat a subset of reals as a complex region            other = ComplexRegion.from_real(other)</ins>         if other.is_ComplexRegion:              # self in rectangular form


elif self.polar and other.polar:                 return ComplexRegion(Union(self.sets, other.sets), polar=True)         if self == S.Complexes:            return self         return None  diff --git a/sympy/sets/sets.py b/sympy/sets/sets.py-- a/sympy/sets/sets.py++ b/sympy/sets/sets.py


for a, b in zip(self.sets, other.sets))      def _union(self, other):<ins>        if other.is_subset(self):            return self</ins>         if not other.is_ProductSet:             return None         if len(other.args) != len(self.args):


('var', ['sup'], ['sub1', 'sub2'])      """<ins>    if len(text) == 0:        return text, [], []</ins>     pos = 0     name = None     supers = []


def __len__(self):         return Mul(*[len(s) for s in self.args]) <ins>    def __bool__(self):        return all([bool(s) for s in self.args])    __nonzero__ = __bool__</ins>  class Interval(Set, EvalfMixin):     """


# don't change anything; this should already             # be a well formed mpf tuple             return mpf    rv = mpf_normalize(sign, man, expt, bc, prec, rnd)    # Necessary if mpmath is using the gmpy backend    from mpmath.libmp.backend import MPZ    rv = mpf_normalize(sign, MPZ(man), expt, bc, prec, rnd)     return rv  # TODO: we should use the warnings module


elif num is S.NegativeInfinity:             num = '-inf'         elif isinstance(num, mpmath.mpf):<ins>            if prec == None:                prec = num.context.dps</ins>             num = num._mpf_          if prec is None:


num[1] = long(num[1], 16)                 _mpf_ = tuple(num)             else:                if not num[1] and len(num) == 4:                if len(num) == 4:                     # handle normalization hack                     return Float._new(num, prec)                 else:                    _mpf_ = mpmath.mpf(                        S.NegativeOne**num[0]*num[1]*2**num[2])._mpf_                    return (S.NegativeOne**num[0]*num[1]*S(2)**num[2]).evalf(prec)         elif isinstance(num, Float):             _mpf_ = num._mpf_             if prec < num._prec:                 _mpf_ = mpf_norm(_mpf_, prec)         else:            # XXX: We lose precision here.             _mpf_ = mpmath.mpf(num)._mpf_          # special cases


obj = Expr.__new__(cls)         obj._mpf_ = mpf_norm(_mpf_, _prec)        # XXX: Should this be obj._prec = obj._mpf_[3]?         obj._prec = _prec         return obj diff --git a/sympy/printing/lambdarepr.py b/sympy/printing/lambdarepr.py-- a/sympy/printing/lambdarepr.py++ b/sympy/printing/lambdarepr.py


lstr = super(NumExprPrinter, self).doprint(expr)         return "evaluate('%s', truediv=True)" % lstr class MpmathPrinter(LambdaPrinter):    """    Lambda printer for mpmath which maintains precision for floats    """    def _print_Float(self, e):        # XXX: This does not handle setting mpmath.mp.dps. It is assumed that        # the caller of the lambdified function will have set it to sufficient        # precision to match the Floats in the expression.        # Remove 'mpz' if gmpy is installed.        args = str(tuple(map(int, e._mpf_)))        return 'mpf(%s)' % args def lambdarepr(expr, **settings):     """     Returns a string usable for lambdifying.diff --git a/sympy/solvers/solvers.py b/sympy/solvers/solvers.py-- a/sympy/solvers/solvers.py++ b/sympy/solvers/solvers.py


# assume it's a sympy expression         if isinstance(f, Equality):             f = f.lhs - f.rhs        f = f.evalf()         syms = f.free_symbols         if fargs is None:             fargs = syms.copy().pop()diff --git a/sympy/utilities/decorator.py b/sympy/utilities/decorator.py-- a/sympy/utilities/decorator.py++ b/sympy/utilities/decorator.py


import functools     import mpmath     def func_wrapper():    def func_wrapper(*args, **kwargs):         dps = mpmath.mp.dps         try:            func()            return func(*args, **kwargs)         finally:             mpmath.mp.dps = dps diff --git a/sympy/utilities/lambdify.py b/sympy/utilities/lambdify.py-- a/sympy/utilities/lambdify.py++ b/sympy/utilities/lambdify.py


for term in syms:             namespace.update({str(term): term})     if _module_present('mpmath',namespaces) and printer is None:        #XXX: This has to be done here because of circular imports        from sympy.printing.lambdarepr import MpmathPrinter as printer     if _module_present('numpy',namespaces) and printer is None:         #XXX: This has to be done here because of circular imports         from sympy.printing.lambdarepr import NumPyPrinter as printerdiff --git a/sympy/utilities/runtests.py b/sympy/utilities/runtests.py-- a/sympy/utilities/runtests.py++ b/sympy/utilities/runtests.py


clear_cache()             self._count += 1             random.seed(self._seed)            pytestfile = ""            if "XFAIL" in gl:                pytestfile = inspect.getsourcefile(gl["XFAIL"])            pytestfile2 = ""            if "slow" in gl:                pytestfile2 = inspect.getsourcefile(gl["slow"])             disabled = gl.get("disabled", False)             if not disabled:                 # we need to filter only those functions that begin with 'test_'                # that are defined in the testing file or in the file where                # is defined the XFAIL decorator                funcs = [gl[f] for f in gl.keys() if f.startswith("test_") and                    (inspect.isfunction(gl[f]) or inspect.ismethod(gl[f])) and                    (inspect.getsourcefile(gl[f]) == filename or                     inspect.getsourcefile(gl[f]) == pytestfile or                     inspect.getsourcefile(gl[f]) == pytestfile2)]                # We have to be careful about decorated functions. As long as                # the decorator uses functools.wraps, we can detect it.                funcs = []                for f in gl:                    if (f.startswith("test_") and (inspect.isfunction(gl[f])                        or inspect.ismethod(gl[f]))):                        func = gl[f]                        # Handle multiple decorators                        while hasattr(func, '__wrapped__'):                            func = func.__wrapped__                        if inspect.getsourcefile(func) == filename:                            funcs.append(gl[f])                 if slow:                     funcs = [f for f in funcs if getattr(f, '_slow', False)]                 # Sorting of XFAILed functions isn't fixed yet :-(


from sympy.sets.sets import FiniteSet from sympy.utilities.iterables import numbered_symbols from sympy.core.compatibility import range<ins>from sympy.core.relational import Nefrom sympy.functions.elementary.piecewise import Piecewise</ins>  ############################################################################### ########################## TRIGONOMETRIC FUNCTIONS ############################


def _eval_rewrite_as_sec(self, arg):         return 1 / sec(arg - S.Pi / 2, evaluate=False) <ins>    def _eval_rewrite_as_sinc(self, arg):        return arg*sinc(arg)</ins>     def _eval_conjugate(self):         return self.func(self.args[0].conjugate())


return jn(0, arg)      def _eval_rewrite_as_sin(self, arg):        return sin(arg) / arg        return Piecewise((sin(arg)/arg, Ne(arg, 0)), (1, True))   ###############################################################################


elif expr.is_Mul:             if not first and _coeff_isneg(expr):                 return True        if expr.is_Piecewise:            return True         if any([expr.has(x) for x in (Mod,)]):             return True         if (not last and            any([expr.has(x) for x in (Integral, Piecewise, Product, Sum)])):            any([expr.has(x) for x in (Integral, Product, Sum)])):             return True          return False


>>> diop_solve(x + 3*y - 4*z + w - 6)     (t_0, t_0 + t_1, 6*t_0 + 5*t_1 + 4*t_2 - 6, 5*t_0 + 4*t_1 + 3*t_2 - 6)     >>> diop_solve(x**2 + y**2 - 5)    {(-1, 2), (1, 2)}    {(-2, -1), (-2, 1), (-1, -2), (-1, 2), (1, -2), (1, 2), (2, -1), (2, 1)}      See Also     ========


This method is generalised for many variables, below.      '''<del></del>     solutions = []     for i in range(len(B)):         tot_x, tot_y = [], []


solns_pell = diop_DN(D, N)          if D < 0:            for solution in solns_pell:                s1 = P*Matrix([solution[0], solution[1]]) + Q                s2 = P*Matrix([-solution[0], solution[1]]) + Q                try:                    sol.add(tuple([as_int(_) for _ in s1]))                    sol.add(tuple([as_int(_) for _ in s2]))                except ValueError:                    pass            for x0, y0 in solns_pell:                for x in [-x0, x0]:                    for y in [-y0, y0]:                        s = P*Matrix([x, y]) + Q                        try:                            sol.add(tuple([as_int(_) for _ in s]))                        except ValueError:                            pass         else:             # In this case equation can be transformed into a Pell equation


if sols:                     for x, y in sols:                         sol.append((d*x, d*y))                        if D == -1:                            sol.append((d*y, d*x))             return sol      elif D == 0:


>>> cornacchia(2, 3, 35) # equation 2x**2 + 3y**2 = 35     {(2, 3), (4, 1)}     >>> cornacchia(1, 1, 25) # equation x**2 + y**2 = 25    {(3, 4)}    {(4, 3)}      References     ===========


m1 = m1 // b             s, _exact = integer_nthroot(m1, 2)             if _exact:                if a == b and r > s:                if a == b and r < s:                     r, s = s, r                 sols.add((int(r), int(s)))


func = getattr(mpmath, fname)         except (AttributeError, KeyError):             try:                return Float(self._imp_(*self.args), prec)                return Float(self._imp_(*[i.evalf(prec) for i in self.args]), prec)             except (AttributeError, TypeError, ValueError):                 return


else:                 return Derivative(self, self.args[argindex - 1], evaluate=False)         # See issue 4624 and issue 4719 and issue 5600        arg_dummy = Dummy('xi_%i' % argindex)        arg_dummy.dummy_index = hash(self.args[argindex - 1])        arg_dummy = Dummy('xi_%i' % argindex, dummy_index=hash(self.args[argindex - 1]))         new_args = [arg for arg in self.args]         new_args[argindex-1] = arg_dummy         return Subs(Derivative(self.func(*new_args), arg_dummy),


obj = None             else:                 if not is_symbol:                    new_v = Dummy('xi_%i' % i)                    new_v.dummy_index = hash(v)                    new_v = Dummy('xi_%i' % i, dummy_index=hash(v))                     expr = expr.xreplace({v: new_v})                     old_v = v                     v = new_vdiff --git a/sympy/core/symbol.py b/sympy/core/symbol.py-- a/sympy/core/symbol.py++ b/sympy/core/symbol.py


import string import re as _re<ins>import random</ins>   class Symbol(AtomicExpr, Boolean):


class Dummy(Symbol):    """Dummy symbols are each unique, identified by an internal count index:    """Dummy symbols are each unique, even if they have the same name:      >>> from sympy import Dummy     >>> bool(Dummy("x") == Dummy("x")) == True     False     If a name is not supplied then a string value of the count index will be    If a name is not supplied then a string value of an internal count will be     used. This is useful when a temporary variable is needed and the name     of the variable used in the expression is not important.


"""     # In the rare event that a Dummy object needs to be recreated, both the    # `name` and `dummy_index` should be passed.  This is used by `srepr` for    # example:    # >>> d1 = Dummy()    # >>> d2 = eval(srepr(d1))    # >>> d2 == d1    # True    #    # If a new session is started between `srepr` and `eval`, there is a very    # small chance that `d2` will be equal to a previously-created Dummy.     _count = 0    _dummyorder = {}    _prng = random.Random()      __slots__ = ['dummy_index']      is_Dummy = True     def __new__(cls, name=None, **assumptions):    def __new__(cls, name=None, dummy_index=None, **assumptions):        if dummy_index is not None:            assert name is not None, "If you specify a dummy_index, you must also provide a name"         if name is None:             name = "Dummy_" + str(Dummy._count)          cls._sanitize(assumptions, cls)         obj = Symbol.__xnew__(cls, name, **assumptions)         while dummy_index is None:            # The dummy_index that *we* generate will be a smallish positive            # integers (at least Codeprinter assumes this).  But we do not            # impose this if dummy_index was passed in.            dummy_index = Dummy._prng.randint(10**6, 10**7-1)            if dummy_index in Dummy._dummyorder:                dummy_index = None        # Store count but don't update it if we already made this Dummy        Dummy._dummyorder.setdefault(dummy_index, Dummy._count)        obj.dummy_index = dummy_index         Dummy._count += 1        obj.dummy_index = Dummy._count         return obj      def __getstate__(self):


@cacheit     def sort_key(self, order=None):        # some tests depend on order of creation of Dummys         return self.class_key(), (            2, (str(self), self.dummy_index)), S.One.sort_key(), S.One            2, (str(self), Dummy._dummyorder[self.dummy_index])), S.One.sort_key(), S.One      def _hashable_content(self):         return Symbol._hashable_content(self) + (self.dummy_index,)diff --git a/sympy/printing/repr.py b/sympy/printing/repr.py-- a/sympy/printing/repr.py++ b/sympy/printing/repr.py


def _print_Symbol(self, expr):         d = expr._assumptions.generator<ins>        # print the dummy_index like it was an assumption        if expr.is_Dummy:            d['dummy_index'] = expr.dummy_index</ins>         if d == {}:             return "%s(%s)" % (expr.__class__.__name__, self._print(expr.name))         else:


def _print_Sum(self, expr):         return "Hold[Sum[" + ', '.join(self.doprint(a) for a in expr.args) + "]]" <ins>    def _print_Derivative(self, expr):        return "Hold[D[" + ', '.join(self.doprint(a) for a in expr.args) + "]]"</ins>  def mathematica_code(expr, **settings):     r"""Converts an expr to a string of the Wolfram Mathematica code


args = flatten(args)          if len(args) == 0:            return S.EmptySet            return S.UniversalSet          # args can't be ordered for Partition see issue #9608         if 'Partition' not in [type(a).__name__ for a in args]:


def factorint(n, limit=None, use_trial=True, use_rho=True, use_pm1=True,              verbose=False, visual=None):              verbose=False, visual=None, multiple=False):     r"""     Given a positive integer ``n``, ``factorint(n)`` returns a dict containing     the prime factors of ``n`` as keys and their respective multiplicities


>>> factorint(3*101**7, limit=5)     {3: 1, 101: 7} <ins>    List of Factors:    If ``multiple`` is set to ``True`` then a list containing the    prime factors including multiplicities is returned.    >>> factorint(24, multiple=True)    [2, 2, 2, 3]</ins>     Visual Factorization:      If ``visual`` is set to ``True``, then it will return a visual


smoothness, smoothness_p, divisors      """<ins>    if multiple:        fac = factorint(n, limit=limit, use_trial=use_trial,                           use_rho=use_rho, use_pm1=use_pm1,                           verbose=verbose, visual=False, multiple=False)        factorlist = sum(([p] * fac[p] if fac[p] > 0 else [S(1)/p]*(-1*fac[p])                               for p in sorted(fac)), [])        return factorlist</ins>     factordict = {}     if visual and not isinstance(n, Mul) and not isinstance(n, dict):         factordict = factorint(n, limit=limit, use_trial=use_trial,


def factorrat(rat, limit=None, use_trial=True, use_rho=True, use_pm1=True,              verbose=False, visual=None):              verbose=False, visual=None, multiple=False):     r"""     Given a Rational ``r``, ``factorrat(r)`` returns a dict containing     the prime factors of ``r`` as keys and their respective multiplicities


- ``use_rho``: Toggle use of Pollard's rho method         - ``use_pm1``: Toggle use of Pollard's p-1 method         - ``verbose``: Toggle detailed printing of progress        - ``multiple``: Toggle returning a list of factors or dict         - ``visual``: Toggle product form of output     """     from collections import defaultdict    if multiple:        fac = factorrat(rat, limit=limit, use_trial=use_trial,                  use_rho=use_rho, use_pm1=use_pm1,                  verbose=verbose, visual=False,multiple=False)        factorlist = sum(([p] * fac[p] if fac[p] > 0 else [S(1)/p]*(-1*fac[p])                               for p, _ in sorted(fac.items(),                                                        key=lambda elem: elem[0]                                                        if elem[1] > 0                                                        else 1/elem[0])), [])        return factorlist     f = factorint(rat.p, limit=limit, use_trial=use_trial,                   use_rho=use_rho, use_pm1=use_pm1,                   verbose=verbose).copy()


new_args = []         n_intervals = len(b1.args)         if n_intervals != len(b2.args):            raise ValueError("Args of b1 and b2 are not equal")        new_args.append((c*b1.args[0].expr, b1.args[0].cond))        for i in range(1, n_intervals - 1):            new_args.append((                c*b1.args[i].expr + d*b2.args[i - 1].expr,                b1.args[i].cond            ))        new_args.append((d*b2.args[-2].expr, b2.args[-2].cond))        new_args.append(b2.args[-1])            # Args of b1 and b2 are not equal. Just combining the Piecewise without any fancy optimisation            p1 = piecewise_fold(c*b1)            p2 = piecewise_fold(d*b2)            # Search all Piecewise arguments except (0, True)            p2args = list(p2.args[:-1])            # This merging algorithm assume the conditions in p1 and p2 are sorted            for arg in p1.args[:-1]:                # Conditional of Piecewise are And objects                # the args of the And object is a tuple of two Relational objects                # the numerical value is in the .rhs of the Relational object                expr = arg.expr                cond = arg.cond                lower = cond.args[0].rhs                # Check p2 for matching conditions that can be merged                for i, arg2 in enumerate(p2args):                    expr2 = arg2.expr                    cond2 = arg2.cond                    lower_2 = cond2.args[0].rhs                    upper_2 = cond2.args[1].rhs                    if cond2 == cond:                        # Conditions match, join expressions                        expr += expr2                        # Remove matching element                        del p2args[i]                        # No need to check the rest                        break                    elif lower_2 < lower and upper_2 <= lower:                        # Check if arg2 condition smaller than arg1, add to new_args by itself (no match expected in p1)                        new_args.append(arg2)                        del p2args[i]                        break                # Checked all, add expr and cond                new_args.append((expr, cond))            # Add remaining items from p2args            new_args.extend(p2args)            # Add final (0, True)            new_args.append((0, True))        else:            new_args.append((c*b1.args[0].expr, b1.args[0].cond))            for i in range(1, n_intervals - 1):                new_args.append((                    c*b1.args[i].expr + d*b2.args[i - 1].expr,                    b1.args[i].cond                ))            new_args.append((d*b2.args[-2].expr, b2.args[-2].cond))            new_args.append(b2.args[-1])         rv = Piecewise(*new_args)      return rv.expand()  def bspline_basis(d, knots, n, x, close=True):def bspline_basis(d, knots, n, x):     """The `n`-th B-spline at `x` of degree `d` with knots.      B-Splines are piecewise polynomials of degree `d` [1]_.  They are defined on


Here is an example of a cubic B-spline:          >>> bspline_basis(3, range(5), 0, x)        Piecewise((x**3/6, (x >= 0) & (x < 1)),        Piecewise((x**3/6, (x >= 0) & (x <= 1)),                   (-x**3/2 + 2*x**2 - 2*x + 2/3,                  (x >= 1) & (x < 2)),                  (x >= 1) & (x <= 2)),                   (x**3/2 - 4*x**2 + 10*x - 22/3,                  (x >= 2) & (x < 3)),                  (x >= 2) & (x <= 3)),                   (-x**3/6 + 2*x**2 - 8*x + 32/3,                   (x >= 3) & (x <= 4)),                   (0, True))


raise ValueError('n + d + 1 must not exceed len(knots) - 1')     if d == 0:         result = Piecewise(            (S.One, Interval(knots[n], knots[n + 1], False,             not close).contains(x)),            (S.One, Interval(knots[n], knots[n + 1]).contains(x)),             (0, True)         )     elif d > 0:         denom = knots[n + d + 1] - knots[n + 1]         if denom != S.Zero:             B = (knots[n + d + 1] - x)/denom            b2 = bspline_basis(d - 1, knots, n + 1, x, close)            b2 = bspline_basis(d - 1, knots, n + 1, x)         else:             b2 = B = S.Zero          denom = knots[n + d] - knots[n]         if denom != S.Zero:             A = (x - knots[n])/denom            b1 = bspline_basis(                d - 1, knots, n, x, close and (B == S.Zero or b2 == S.Zero))            b1 = bspline_basis(d - 1, knots, n, x)         else:             b1 = A = S.Zero


>>> knots = range(5)     >>> splines = bspline_basis_set(d, knots, x)     >>> splines    [Piecewise((x**2/2, (x >= 0) & (x < 1)),               (-x**2 + 3*x - 3/2, (x >= 1) & (x < 2)),    [Piecewise((x**2/2, (x >= 0) & (x <= 1)),               (-x**2 + 3*x - 3/2, (x >= 1) & (x <= 2)),                (x**2/2 - 3*x + 9/2, (x >= 2) & (x <= 3)),                (0, True)),    Piecewise((x**2/2 - x + 1/2, (x >= 1) & (x < 2)),              (-x**2 + 5*x - 11/2, (x >= 2) & (x < 3)),    Piecewise((x**2/2 - x + 1/2, (x >= 1) & (x <= 2)),              (-x**2 + 5*x - 11/2, (x >= 2) & (x <= 3)),               (x**2/2 - 4*x + 8, (x >= 3) & (x <= 4)),               (0, True))]


import decimal import fractions import math<ins>import warnings</ins> import re as regex from collections import defaultdict


from sympy.utilities.misc import debug, filldedent from .evaluate import global_evaluate <ins>from sympy.utilities.exceptions import SymPyDeprecationWarning</ins> rnd = mlib.round_nearest  _LOG2 = math.log(2)


is_Float = True     def __new__(cls, num, prec=None):    def __new__(cls, num, dps=None, prec=None, precision=None):        if prec is not None:            SymPyDeprecationWarning(                            feature="Using 'prec=XX' to denote decimal precision",                            useinstead="'dps=XX' to denote decimal and 'precision=XX' "\                                              "for binary precision",                            value="This is an effort to improve functionality "\                                       "of Float class. ").warn()            dps = prec        if dps is not None and precision is not None:            raise ValueError('Both decimal and binary precision supplied. '                             'Supply only one. ')         if isinstance(num, string_types):             num = num.replace(' ', '')             if num.startswith('.') and len(num) > 1:


elif num is S.NegativeInfinity:             num = '-inf'         elif isinstance(num, mpmath.mpf):            if prec == None:                prec = num.context.dps            if precision is None:                if dps is None:                    precision = num.context.prec             num = num._mpf_         if prec is None:        if dps is None and precision is None:             dps = 15             if isinstance(num, Float):                 return num


if num.is_Integer and isint:                         dps = max(dps, len(str(num).lstrip('-')))                     dps = max(15, dps)        elif prec == '':                    precision = mlib.libmpf.dps_to_prec(dps)        elif precision == '' and dps is None or precision is None and dps == '':             if not isinstance(num, string_types):                 raise ValueError('The null string can only be used when '                 'the number to Float is passed as a string or an integer.')


num, dps = _decimal_to_Rational_prec(Num)                     if num.is_Integer and isint:                         dps = max(dps, len(str(num).lstrip('-')))                        precision = mlib.libmpf.dps_to_prec(dps)                     ok = True             if ok is None:                 raise ValueError('string-float not recognized: %s' % num)        else:            dps = prec         prec = mlib.libmpf.dps_to_prec(dps)        # decimal precision(dps) is set and maybe binary precision(precision)        # as well.From here on binary precision is used to compute the Float.        # Hence, if supplied use binary precision else translate from decimal        # precision.        if precision is None or precision == '':            precision = mlib.libmpf.dps_to_prec(dps)         if isinstance(num, float):            _mpf_ = mlib.from_float(num, prec, rnd)            _mpf_ = mlib.from_float(num, precision, rnd)         elif isinstance(num, string_types):            _mpf_ = mlib.from_str(num, prec, rnd)            _mpf_ = mlib.from_str(num, precision, rnd)         elif isinstance(num, decimal.Decimal):             if num.is_finite():                _mpf_ = mlib.from_str(str(num), prec, rnd)                _mpf_ = mlib.from_str(str(num), precision, rnd)             elif num.is_nan():                 _mpf_ = _mpf_nan             elif num.is_infinite():


else:                 raise ValueError("unexpected decimal value %s" % str(num))         elif isinstance(num, Rational):            _mpf_ = mlib.from_rational(num.p, num.q, prec, rnd)            _mpf_ = mlib.from_rational(num.p, num.q, precision, rnd)         elif isinstance(num, tuple) and len(num) in (3, 4):             if type(num[1]) is str:                 # it's a hexadecimal (coming from a pickled object)


else:                 if len(num) == 4:                     # handle normalization hack                    return Float._new(num, prec)                    return Float._new(num, precision)                 else:                    return (S.NegativeOne**num[0]*num[1]*S(2)**num[2]).evalf(prec)                    return (S.NegativeOne**num[0]*num[1]*S(2)**num[2]).evalf(precision)         elif isinstance(num, Float):             _mpf_ = num._mpf_            if prec < num._prec:                _mpf_ = mpf_norm(_mpf_, prec)            if precision < num._prec:                _mpf_ = mpf_norm(_mpf_, precision)         else:             # XXX: We lose precision here.             _mpf_ = mpmath.mpf(num)._mpf_


obj = Expr.__new__(cls)         obj._mpf_ = _mpf_        obj._prec = prec        obj._prec = precision         return obj      @classmethoddiff --git a/sympy/printing/repr.py b/sympy/printing/repr.py-- a/sympy/printing/repr.py++ b/sympy/printing/repr.py


return 'Fraction(%s, %s)' % (self._print(expr.numerator), self._print(expr.denominator))      def _print_Float(self, expr):        dps = prec_to_dps(expr._prec)         r = mlib.to_str(expr._mpf_, repr_dps(expr._prec))        return "%s('%s', prec=%i)" % (expr.__class__.__name__, r, dps)        return "%s('%s', precision=%i)" % (expr.__class__.__name__, r, expr._prec)      def _print_Sum2(self, expr):         return "Sum2(%s, (%s, %s, %s))" % (self._print(expr.f), self._print(expr.i),


from collections import defaultdict <del></del> class Expr(Basic, EvalfMixin):     """     Base class for algebraic expressions.


x/6          """<ins>        from .function import _coeff_isneg</ins>         c = sympify(c)         if self is S.NaN:             return None


return self         elif c == self:             return S.One         if c.is_Add:             cc, pc = c.primitive()             if cc is not S.One:                 c = Mul(cc, pc, evaluate=False)         if c.is_Mul:             a, b = c.as_two_terms()             x = self.extract_multiplicatively(a)             if x is not None:                 return x.extract_multiplicatively(b)         quotient = self / c         if self.is_Number:             if self is S.Infinity: