{"instance_id": "django__django-15569", "model_name_or_path": "cain-anthropic-e124", "model_patch": "diff --git a/django/db/models/query_utils.py b/django/db/models/query_utils.py\nindex 0caa165e15..6917820604 100644\n--- a/django/db/models/query_utils.py\n+++ b/django/db/models/query_utils.py\n@@ -217,6 +217,7 @@ class RegisterLookupMixin:\n         if lookup_name is None:\n             lookup_name = lookup.lookup_name\n         del cls.class_lookups[lookup_name]\n+        cls._clear_cached_lookups()\n \n \n def select_related_descend(field, restricted, requested, load_fields, reverse=False):\n", "model": "claude-sonnet-5-5", "steps": 4, "finished": true, "patch_lines": 12, "candidates": [{"compile_ok": 0, "loc_hits": 0, "files": 1, "diff_lines": 12, "steps": 4}], "ms": 7123}
{"instance_id": "psf__requests-5414", "model_name_or_path": "cain-anthropic-e124", "model_patch": "diff --git a/requests/models.py b/requests/models.py\nindex e7d292d5..d8638818 100644\n--- a/requests/models.py\n+++ b/requests/models.py\n@@ -403,7 +403,7 @@ class PreparedRequest(RequestEncodingMixin, RequestHooksMixin):\n                 host = self._get_idna_encoded_host(host)\n             except UnicodeError:\n                 raise InvalidURL('URL has an invalid label.')\n-        elif host.startswith(u'*'):\n+        elif host.startswith((u'*', u'.')):\n             raise InvalidURL('URL has an invalid label.')\n \n         # Carefully reconstruct the network location\n", "model": "claude-sonnet-5-5", "steps": 6, "finished": true, "patch_lines": 13, "candidates": [{"compile_ok": 0, "loc_hits": 1, "files": 1, "diff_lines": 13, "steps": 6}], "ms": 11191}
{"instance_id": "astropy__astropy-13579", "model_name_or_path": "cain-anthropic-e124", "model_patch": "diff --git a/astropy/wcs/wcsapi/wrappers/sliced_wcs.py b/astropy/wcs/wcsapi/wrappers/sliced_wcs.py\nindex d7605b078c..349422d9eb 100644\n--- a/astropy/wcs/wcsapi/wrappers/sliced_wcs.py\n+++ b/astropy/wcs/wcsapi/wrappers/sliced_wcs.py\n@@ -244,6 +244,8 @@ class SlicedLowLevelWCS(BaseWCSWrapper):\n \n     def world_to_pixel_values(self, *world_arrays):\n         world_arrays = tuple(map(np.asanyarray, world_arrays))\n+        sliced_out_world_coords = self._pixel_to_world_values_all(*[0]*len(self._pixel_keep))\n+\n         world_arrays_new = []\n         iworld_curr = -1\n         for iworld in range(self._wcs.world_n_dim):\n@@ -251,7 +253,7 @@ class SlicedLowLevelWCS(BaseWCSWrapper):\n                 iworld_curr += 1\n                 world_arrays_new.append(world_arrays[iworld_curr])\n             else:\n-                world_arrays_new.append(1.)\n+                world_arrays_new.append(sliced_out_world_coords[iworld])\n \n         world_arrays_new = np.broadcast_arrays(*world_arrays_new)\n         pixel_arrays = list(self._wcs.world_to_pixel_values(*world_arrays_new))\n", "model": "claude-sonnet-5-5", "steps": 5, "finished": true, "patch_lines": 22, "candidates": [{"compile_ok": 0, "loc_hits": 0, "files": 1, "diff_lines": 22, "steps": 5}], "ms": 16518}
{"instance_id": "django__django-13195", "model_name_or_path": "cain-anthropic-e124", "model_patch": "diff --git a/django/contrib/messages/storage/cookie.py b/django/contrib/messages/storage/cookie.py\nindex 78256ca3b2..b51e292aa0 100644\n--- a/django/contrib/messages/storage/cookie.py\n+++ b/django/contrib/messages/storage/cookie.py\n@@ -92,7 +92,11 @@ class CookieStorage(BaseStorage):\n                 samesite=settings.SESSION_COOKIE_SAMESITE,\n             )\n         else:\n-            response.delete_cookie(self.cookie_name, domain=settings.SESSION_COOKIE_DOMAIN)\n+            response.delete_cookie(\n+                self.cookie_name,\n+                domain=settings.SESSION_COOKIE_DOMAIN,\n+                samesite=settings.SESSION_COOKIE_SAMESITE,\n+            )\n \n     def _store(self, messages, response, remove_oldest=True, *args, **kwargs):\n         \"\"\"\ndiff --git a/django/contrib/sessions/middleware.py b/django/contrib/sessions/middleware.py\nindex 63013eef7a..95ad30ce7f 100644\n--- a/django/contrib/sessions/middleware.py\n+++ b/django/contrib/sessions/middleware.py\n@@ -42,6 +42,7 @@ class SessionMiddleware(MiddlewareMixin):\n                 settings.SESSION_COOKIE_NAME,\n                 path=settings.SESSION_COOKIE_PATH,\n                 domain=settings.SESSION_COOKIE_DOMAIN,\n+                samesite=settings.SESSION_COOKIE_SAMESITE,\n             )\n             patch_vary_headers(response, ('Cookie',))\n         else:\ndiff --git a/django/http/response.py b/django/http/response.py\nindex e00bcacefb..cca175f8eb 100644\n--- a/django/http/response.py\n+++ b/django/http/response.py\n@@ -210,13 +210,16 @@ class HttpResponseBase:\n         value = signing.get_cookie_signer(salt=key + salt).sign(value)\n         return self.set_cookie(key, value, **kwargs)\n \n-    def delete_cookie(self, key, path='/', domain=None):\n+    def delete_cookie(self, key, path='/', domain=None, samesite=None):\n         # Most browsers ignore the Set-Cookie header if the cookie name starts\n         # with __Host- or __Secure- and the cookie doesn't use the secure flag.\n-        secure = key.startswith(('__Secure-', '__Host-'))\n+        secure = (\n+            key.startswith(('__Secure-', '__Host-')) or\n+            (samesite and samesite.lower() == 'none')\n+        )\n         self.set_cookie(\n             key, max_age=0, path=path, domain=domain, secure=secure,\n-            expires='Thu, 01 Jan 1970 00:00:00 GMT',\n+            expires='Thu, 01 Jan 1970 00:00:00 GMT', samesite=samesite,\n         )\n \n     # Common methods used by subclasses\n", "model": "claude-sonnet-5-5", "steps": 7, "finished": true, "patch_lines": 53, "candidates": [{"compile_ok": 0, "loc_hits": 1, "files": 3, "diff_lines": 53, "steps": 7}], "ms": 21533}
{"instance_id": "sympy__sympy-23413", "model_name_or_path": "cain-anthropic-e124", "model_patch": "diff --git a/sympy/polys/matrices/normalforms.py b/sympy/polys/matrices/normalforms.py\nindex 30f5534b08..286b411726 100644\n--- a/sympy/polys/matrices/normalforms.py\n+++ b/sympy/polys/matrices/normalforms.py\n@@ -205,16 +205,17 @@ def _hermite_normal_form(A):\n     if not A.domain.is_ZZ:\n         raise DMDomainError('Matrix must be over domain ZZ.')\n     # We work one row at a time, starting from the bottom row, and working our\n-    # way up. The total number of rows we will consider is min(m, n), where\n-    # A is an m x n matrix.\n+    # way up. We stop once every column has a pivot, but zero rows do not use\n+    # up a pivot column, so we may need to look at more than min(m, n) rows.\n     m, n = A.shape\n-    rows = min(m, n)\n     A = A.to_dense().rep.copy()\n     # Our goal is to put pivot entries in the rightmost columns.\n     # Invariant: Before processing each row, k should be the index of the\n     # leftmost column in which we have so far put a pivot.\n     k = n\n-    for i in range(m - 1, m - 1 - rows, -1):\n+    for i in range(m - 1, -1, -1):\n+        if k == 0:\n+            break\n         k -= 1\n         # k now points to the column in which we want to put a pivot.\n         # We want zeros in all entries to the left of the pivot column.\n", "model": "claude-sonnet-5-5", "steps": 9, "finished": true, "patch_lines": 26, "candidates": [{"compile_ok": 0, "loc_hits": 0, "files": 1, "diff_lines": 26, "steps": 9}], "ms": 19045}
{"instance_id": "astropy__astropy-12907", "model_name_or_path": "cain-anthropic-e124", "model_patch": "diff --git a/astropy/modeling/separable.py b/astropy/modeling/separable.py\nindex a308e27297..e69de29bb2 100644\n--- a/astropy/modeling/separable.py\n+++ b/astropy/modeling/separable.py\n@@ -1,317 +0,0 @@\n-# Licensed under a 3-clause BSD style license - see LICENSE.rst\n-\n-\"\"\"\n-Functions to determine if a model is separable, i.e.\n-if the model outputs are independent.\n-\n-It analyzes ``n_inputs``, ``n_outputs`` and the operators\n-in a compound model by stepping through the transforms\n-and creating a ``coord_matrix`` of shape (``n_outputs``, ``n_inputs``).\n-\n-\n-Each modeling operator is represented by a function which\n-takes two simple models (or two ``coord_matrix`` arrays) and\n-returns an array of shape (``n_outputs``, ``n_inputs``).\n-\n-\"\"\"\n-\n-import numpy as np\n-\n-from .core import Model, ModelDefinitionError, CompoundModel\n-from .mappings import Mapping\n-\n-\n-__all__ = [\"is_separable\", \"separability_matrix\"]\n-\n-\n-def is_separable(transform):\n-    \"\"\"\n-    A separability test for the outputs of a transform.\n-\n-    Parameters\n-    ----------\n-    transform : `~astropy.modeling.core.Model`\n-        A (compound) model.\n-\n-    Returns\n-    -------\n-    is_separable : ndarray\n-        A boolean array with size ``transform.n_outputs`` where\n-        each element indicates whether the output is independent\n-        and the result of a separable transform.\n-\n-    Examples\n-    --------\n-    >>> from astropy.modeling.models import Shift, Scale, Rotation2D, Polynomial2D\n-    >>> is_separable(Shift(1) & Shift(2) | Scale(1) & Scale(2))\n-        array([ True,  True]...)\n-    >>> is_separable(Shift(1) & Shift(2) | Rotation2D(2))\n-        array([False, False]...)\n-    >>> is_separable(Shift(1) & Shift(2) | Mapping([0, 1, 0, 1]) | \\\n-        Polynomial2D(1) & Polynomial2D(2))\n-        array([False, False]...)\n-    >>> is_separable(Shift(1) & Shift(2) | Mapping([0, 1, 0, 1]))\n-        array([ True,  True,  True,  True]...)\n-\n-    \"\"\"\n-    if transform.n_inputs == 1 and transform.n_outputs > 1:\n-        is_separable = np.array([False] * transform.n_outputs).T\n-        return is_separable\n-    separable_matrix = _separable(transform)\n-    is_separable = separable_matrix.sum(1)\n-    is_separable = np.where(is_separable != 1, False, True)\n-    return is_separable\n-\n-\n-def separability_matrix(transform):\n-    \"\"\"\n-    Compute the correlation between outputs and inputs.\n-\n-    Parameters\n-    ----------\n-    transform : `~astropy.modeling.core.Model`\n-        A (compound) model.\n-\n-    Returns\n-    -------\n-    separable_matrix : ndarray\n-        A boolean correlation matrix of shape (n_outputs, n_inputs).\n-        Indicates the dependence of outputs on inputs. For completely\n-        independent outputs, the diagonal elements are True and\n-        off-diagonal elements are False.\n-\n-    Examples\n-    --------\n-    >>> from astropy.modeling.models import Shift, Scale, Rotation2D, Polynomial2D\n-    >>> separability_matrix(Shift(1) & Shift(2) | Scale(1) & Scale(2))\n-        array([[ True, False], [False,  True]]...)\n-    >>> separability_matrix(Shift(1) & Shift(2) | Rotation2D(2))\n-        array([[ True,  True], [ True,  True]]...)\n-    >>> separability_matrix(Shift(1) & Shift(2) | Mapping([0, 1, 0, 1]) | \\\n-        Polynomial2D(1) & Polynomial2D(2))\n-        array([[ True,  True], [ True,  True]]...)\n-    >>> separability_matrix(Shift(1) & Shift(2) | Mapping([0, 1, 0, 1]))\n-        array([[ True, False], [False,  True], [ True, False], [False,  True]]...)\n-\n-    \"\"\"\n-    if transform.n_inputs == 1 and transform.n_outputs > 1:\n-        return np.ones((transform.n_outputs, transform.n_inputs),\n-                       dtype=np.bool_)\n-    separable_matrix = _separable(transform)\n-    separable_matrix = np.where(separable_matrix != 0, True, False)\n-    return separable_matrix\n-\n-\n-def _compute_n_outputs(left, right):\n-    \"\"\"\n-    Compute the number of outputs of two models.\n-\n-    The two models are the left and right model to an operation in\n-    the expression tree of a compound model.\n-\n-    Parameters\n-    ----------\n-    left, right : `astropy.modeling.Model` or ndarray\n-        If input is of an array, it is the output of `coord_matrix`.\n-\n-    \"\"\"\n-    if isinstance(left, Model):\n-        lnout = left.n_outputs\n-    else:\n-        lnout = left.shape[0]\n-    if isinstance(right, Model):\n-        rnout = right.n_outputs\n-    else:\n-        rnout = right.shape[0]\n-    noutp = lnout + rnout\n-    return noutp\n-\n-\n-def _arith_oper(left, right):\n-    \"\"\"\n-    Function corresponding to one of the arithmetic operators\n-    ['+', '-'. '*', '/', '**'].\n-\n-    This always returns a nonseparable output.\n-\n-\n-    Parameters\n-    ----------\n-    left, right : `astropy.modeling.Model` or ndarray\n-        If input is of an array, it is the output of `coord_matrix`.\n-\n-    Returns\n-    -------\n-    result : ndarray\n-        Result from this operation.\n-    \"\"\"\n-    # models have the same number of inputs and outputs\n-    def _n_inputs_outputs(input):\n-        if isinstance(input, Model):\n-            n_outputs, n_inputs = input.n_outputs, input.n_inputs\n-        else:\n-            n_outputs, n_inputs = input.shape\n-        return n_inputs, n_outputs\n-\n-    left_inputs, left_outputs = _n_inputs_outputs(left)\n-    right_inputs, right_outputs = _n_inputs_outputs(right)\n-\n-    if left_inputs != right_inputs or left_outputs != right_outputs:\n-        raise ModelDefinitionError(\n-            \"Unsupported operands for arithmetic operator: left (n_inputs={}, \"\n-            \"n_outputs={}) and right (n_inputs={}, n_outputs={}); \"\n-            \"models must have the same n_inputs and the same \"\n-            \"n_outputs for this operator.\".format(\n-                left_inputs, left_outputs, right_inputs, right_outputs))\n-\n-    result = np.ones((left_outputs, left_inputs))\n-    return result\n-\n-\n-def _coord_matrix(model, pos, noutp):\n-    \"\"\"\n-    Create an array representing inputs and outputs of a simple model.\n-\n-    The array has a shape (noutp, model.n_inputs).\n-\n-    Parameters\n-    ----------\n-    model : `astropy.modeling.Model`\n-        model\n-    pos : str\n-        Position of this model in the expression tree.\n-        One of ['left', 'right'].\n-    noutp : int\n-        Number of outputs of the compound model of which the input model\n-        is a left or right child.\n-\n-    \"\"\"\n-    if isinstance(model, Mapping):\n-        axes = []\n-        for i in model.mapping:\n-            axis = np.zeros((model.n_inputs,))\n-            axis[i] = 1\n-            axes.append(axis)\n-        m = np.vstack(axes)\n-        mat = np.zeros((noutp, model.n_inputs))\n-        if pos == 'left':\n-            mat[: model.n_outputs, :model.n_inputs] = m\n-        else:\n-            mat[-model.n_outputs:, -model.n_inputs:] = m\n-        return mat\n-    if not model.separable:\n-        # this does not work for more than 2 coordinates\n-        mat = np.zeros((noutp, model.n_inputs))\n-        if pos == 'left':\n-            mat[:model.n_outputs, : model.n_inputs] = 1\n-        else:\n-            mat[-model.n_outputs:, -model.n_inputs:] = 1\n-    else:\n-        mat = np.zeros((noutp, model.n_inputs))\n-\n-        for i in range(model.n_inputs):\n-            mat[i, i] = 1\n-        if pos == 'right':\n-            mat = np.roll(mat, (noutp - model.n_outputs))\n-    return mat\n-\n-\n-def _cstack(left, right):\n-    \"\"\"\n-    Function corresponding to '&' operation.\n-\n-    Parameters\n-    ----------\n-    left, right : `astropy.modeling.Model` or ndarray\n-        If input is of an array, it is the output of `coord_matrix`.\n-\n-    Returns\n-    -------\n-    result : ndarray\n-        Result from this operation.\n-\n-    \"\"\"\n-    noutp = _compute_n_outputs(left, right)\n-\n-    if isinstance(left, Model):\n-        cleft = _coord_matrix(left, 'left', noutp)\n-    else:\n-        cleft = np.zeros((noutp, left.shape[1]))\n-        cleft[: left.shape[0], : left.shape[1]] = left\n-    if isinstance(right, Model):\n-        cright = _coord_matrix(right, 'right', noutp)\n-    else:\n-        cright = np.zeros((noutp, right.shape[1]))\n-        cright[-right.shape[0]:, -right.shape[1]:] = 1\n-\n-    return np.hstack([cleft, cright])\n-\n-\n-def _cdot(left, right):\n-    \"\"\"\n-    Function corresponding to \"|\" operation.\n-\n-    Parameters\n-    ----------\n-    left, right : `astropy.modeling.Model` or ndarray\n-        If input is of an array, it is the output of `coord_matrix`.\n-\n-    Returns\n-    -------\n-    result : ndarray\n-        Result from this operation.\n-    \"\"\"\n-\n-    left, right = right, left\n-\n-    def _n_inputs_outputs(input, position):\n-        \"\"\"\n-        Return ``n_inputs``, ``n_outputs`` for a model or coord_matrix.\n-        \"\"\"\n-        if isinstance(input, Model):\n-            coords = _coord_matrix(input, position, input.n_outputs)\n-        else:\n-            coords = input\n-        return coords\n-\n-    cleft = _n_inputs_outputs(left, 'left')\n-    cright = _n_inputs_outputs(right, 'right')\n-\n-    try:\n-        result = np.dot(cleft, cright)\n-    except ValueError:\n-        raise ModelDefinitionError(\n-            'Models cannot be combined with the \"|\" operator; '\n-            'left coord_matrix is {}, right coord_matrix is {}'.format(\n-                cright, cleft))\n-    return result\n-\n-\n-def _separable(transform):\n-    \"\"\"\n-    Calculate the separability of outputs.\n-\n-    Parameters\n-    ----------\n-    transform : `astropy.modeling.Model`\n-        A transform (usually a compound model).\n-\n-    Returns :\n-    is_separable : ndarray of dtype np.bool\n-        An array of shape (transform.n_outputs,) of boolean type\n-        Each element represents the separablity of the corresponding output.\n-    \"\"\"\n-    if (transform_matrix := transform._calculate_separability_matrix()) is not NotImplemented:\n-        return transform_matrix\n-    elif isinstance(transform, CompoundModel):\n-        sepleft = _separable(transform.left)\n-        sepright = _separable(transform.right)\n-        return _operators[transform.op](sepleft, sepright)\n-    elif isinstance(transform, Model):\n-        return _coord_matrix(transform, 'left', transform.n_outputs)\n-\n-\n-# Maps modeling operators to a function computing and represents the\n-# relationship of axes as an array of 0-es and 1-s\n-_operators = {'&': _cstack, '|': _cdot, '+': _arith_oper, '-': _arith_oper,\n-              '*': _arith_oper, '/': _arith_oper, '**': _arith_oper}\n", "model": "claude-haiku-5-5", "steps": 15, "finished": true, "patch_lines": 322, "candidates": [{"compile_ok": 0, "loc_hits": 0, "files": 1, "diff_lines": 322, "steps": 15}], "ms": 54077}
{"instance_id": "astropy__astropy-14365", "model_name_or_path": "cain-70b-e124", "model_patch": "diff --git a/astropy/io/ascii/qdp.py b/astropy/io/ascii/qdp.py\nindex 83a4f004aa..e7bc241e54 100644\n--- a/astropy/io/ascii/qdp.py\n+++ b/astropy/io/ascii/qdp.py\n@@ -1,642 +1,5 @@\n-# Licensed under a 3-clause BSD style license - see LICENSE.rst\n-\"\"\"\n-This package contains functions for reading and writing QDP tables that are\n-not meant to be used directly, but instead are available as readers/writers in\n-`astropy.table`. See :ref:`astropy:table_io` for more details.\n-\"\"\"\n-import copy\n-import re\n-import warnings\n-from collections.abc import Iterable\n-\n-import numpy as np\n-\n-from astropy.table import Table\n-from astropy.utils.exceptions import AstropyUserWarning\n-\n-from . import basic, core\n-\n-\n-def _line_type(line, delimiter=None):\n-    \"\"\"Interpret a QDP file line.\n-\n-    Parameters\n-    ----------\n-    line : str\n-        a single line of the file\n-\n-    Returns\n-    -------\n-    type : str\n-        Line type: \"comment\", \"command\", or \"data\"\n-\n-    Examples\n-    --------\n-    >>> _line_type(\"READ SERR 3\")\n-    'command'\n-    >>> _line_type(\" \\\\n    !some gibberish\")\n-    'comment'\n-    >>> _line_type(\"   \")\n-    'comment'\n-    >>> _line_type(\" 21345.45\")\n-    'data,1'\n-    >>> _line_type(\" 21345.45 1.53e-3 1e-3 .04 NO nan\")\n-    'data,6'\n-    >>> _line_type(\" 21345.45,1.53e-3,1e-3,.04,NO,nan\", delimiter=',')\n-    'data,6'\n-    >>> _line_type(\" 21345.45 ! a comment to disturb\")\n-    'data,1'\n-    >>> _line_type(\"NO NO NO NO NO\")\n-    'new'\n-    >>> _line_type(\"NO,NO,NO,NO,NO\", delimiter=',')\n-    'new'\n-    >>> _line_type(\"N O N NOON OON O\")\n-    Traceback (most recent call last):\n-        ...\n-    ValueError: Unrecognized QDP line...\n-    >>> _line_type(\" some non-comment gibberish\")\n-    Traceback (most recent call last):\n-        ...\n-    ValueError: Unrecognized QDP line...\n-    \"\"\"\n-    _decimal_re = r\"[+-]?(\\d+(\\.\\d*)?|\\.\\d+)([eE][+-]?\\d+)?\"\n-    _command_re = r\"READ [TS]ERR(\\s+[0-9]+)+\"\n-\n-    sep = delimiter\n-    if delimiter is None:\n-        sep = r\"\\s+\"\n-    _new_re = rf\"NO({sep}NO)+\"\n-    _data_re = rf\"({_decimal_re}|NO|[-+]?nan)({sep}({_decimal_re}|NO|[-+]?nan))*)\"\n-    _type_re = rf\"^\\s*((?P<command>{_command_re})|(?P<new>{_new_re})|(?P<data>{_data_re})?\\s*(\\!(?P<comment>.*))?\\s*$\"\n-    _line_type_re = re.compile(_type_re)\n-    line = line.strip()\n-    if not line:\n-        return \"comment\"\n-    match = _line_type_re.match(line)\n-\n-    if match is None:\n-        raise ValueError(f\"Unrecognized QDP line: {line}\")\n-    for type_, val in match.groupdict().items():\n-        if val is None:\n-            continue\n-        if type_ == \"data\":\n-            return f\"data,{len(val.split(sep=delimiter))}\"\n-        else:\n-            return type_\n-\n-\n-def _get_type_from_list_of_lines(lines, delimiter=None):\n-    \"\"\"Read through the list of QDP file lines and label each line by type.\n-\n-    Parameters\n-    ----------\n-    lines : list\n-        List containing one file line in each entry\n-\n-    Returns\n-    -------\n-    contents : list\n-        List containing the type for each line (see `line_type_and_data`)\n-    ncol : int\n-        The number of columns in the data lines. Must be the same throughout\n-        the file\n-\n-    Examples\n-    --------\n-    >>> line0 = \"! A comment\"\n-    >>> line1 = \"543 12 456.0\"\n-    >>> lines = [line0, line1]\n-    >>> types, ncol = _get_type_from_list_of_lines(lines)\n-    >>> types[0]\n-    'comment'\n-    >>> types[1]\n-    'data,3'\n-    >>> ncol\n-    3\n-    >>> lines.append(\"23\")\n-    >>> _get_type_from_list_of_lines(lines)\n-    Traceback (most recent call last):\n-        ...\n-    ValueError: Inconsistent number of columns\n-    \"\"\"\n-    types = [_line_type(line, delimiter=delimiter) for line in lines]\n-    current_ncol = None\n-    for type_ in types:\n-        if type_.startswith(\"data,\"):\n-            ncol = int(type_[5:])\n-            if current_ncol is None:\n-                current_ncol = ncol\n-            elif ncol != current_ncol:\n-                raise ValueError(\"Inconsistent number of columns\")\n-\n-    return types, current_ncol\n-\n-\n-def _get_lines_from_file(qdp_file):\n-    if \"\\n\" in qdp_file:\n-        lines = qdp_file.split(\"\\n\")\n-    elif isinstance(qdp_file, str):\n-        with open(qdp_file) as fobj:\n-            lines = [line.strip() for line in fobj.readlines()]\n-    elif isinstance(qdp_file, Iterable):\n-        lines = qdp_file\n-    else:\n-        raise ValueError(\"invalid value of qdb_file\")\n-\n-    return lines\n-\n-\n-def _interpret_err_lines(err_specs, ncols, names=None):\n-    \"\"\"Give list of column names from the READ SERR and TERR commands.\n-\n-    Parameters\n-    ----------\n-    err_specs : dict\n-        ``{'serr': [n0, n1, ...], 'terr': [n2, n3, ...]}``\n-        Error specifications for symmetric and two-sided errors\n-    ncols : int\n-        Number of data columns\n-\n-    Other Parameters\n-    ----------------\n-    names : list of str\n-        Name of data columns (defaults to ['col1', 'col2', ...]), _not_\n-        including error columns.\n-\n-    Returns\n-    -------\n-    colnames : list\n-        List containing the column names. Error columns will have the name\n-        of the main column plus ``_err`` for symmetric errors, and ``_perr``\n-        and ``_nerr`` for positive and negative errors respectively\n-\n-    Examples\n-    --------\n-    >>> col_in = ['MJD', 'Rate']\n-    >>> cols = _interpret_err_lines(None, 2, names=col_in)\n-    >>> cols[0]\n-    'MJD'\n-    >>> err_specs = {'terr': [1], 'serr': [2]}\n-    >>> ncols = 5\n-    >>> cols = _interpret_err_lines(err_specs, ncols, names=col_in)\n-    >>> cols[0]\n-    'MJD'\n-    >>> cols[2]\n-    'MJD_nerr'\n-    >>> cols[4]\n-    'Rate_err'\n-    >>> _interpret_err_lines(err_specs, 6, names=col_in)\n-    Traceback (most recent call last):\n-        ...\n-    ValueError: Inconsistent number of input colnames\n-    \"\"\"\n-    colnames = [\"\" for i in range(ncols)]\n-    if err_specs is None:\n-        serr_cols = terr_cols = []\n-\n-    else:\n-        # I don't want to empty the original one when using `pop` below\n-        err_specs = copy.deepcopy(err_specs)\n-\n-        serr_cols = err_specs.pop(\"serr\", [])\n-        terr_cols = err_specs.pop(\"terr\", [])\n-\n-    if names is not None:\n-        all_error_cols = len(serr_cols) + len(terr_cols) * 2\n-        if all_error_cols + len(names) != ncols:\n-            raise ValueError(\"Inconsistent number of input colnames\")\n-\n-    shift = 0\n-    for i in range(ncols):\n-        col_num = i + 1 - shift\n-        if colnames[i] != \"\":\n-            continue\n-\n-        colname_root = f\"col{col_num}\"\n-\n-        if names is not None:\n-            colname_root = names[col_num - 1]\n-\n-        colnames[i] = f\"{colname_root}\"\n-        if col_num in serr_cols:\n-            colnames[i + 1] = f\"{colname_root}_err\"\n-            shift += 1\n-            continue\n-\n-        if col_num in terr_cols:\n-            colnames[i + 1] = f\"{colname_root}_perr\"\n-            colnames[i + 2] = f\"{colname_root}_nerr\"\n-            shift += 2\n-            continue\n-\n-    assert not np.any([c == \"\" for c in colnames])\n-\n-    return colnames\n-\n-\n-def _get_tables_from_qdp_file(qdp_file, input_colnames=None, delimiter=None):\n-    \"\"\"Get all tables from a QDP file.\n-\n-    Parameters\n-    ----------\n-    qdp_file : str\n-        Input QDP file name\n-\n-    Other Parameters\n-    ----------------\n-    input_colnames : list of str\n-        Name of data columns (defaults to ['col1', 'col2', ...]), _not_\n-        including error columns.\n-    delimiter : str\n-        Delimiter for the values in the table.\n-\n-    Returns\n-    -------\n-    list of `~astropy.table.Table`\n-        List containing all the tables present inside the QDP file\n-    \"\"\"\n-    lines = _get_lines_from_file(qdp_file)\n-    contents, ncol = _get_type_from_list_of_lines(lines, delimiter=delimiter)\n-\n-    table_list = []\n-    err_specs = {}\n-    colnames = None\n-\n-    comment_text = \"\"\n-    initial_comments = \"\"\n-    command_lines = \"\"\n-    current_rows = None\n-\n-    for line, datatype in zip(lines, contents):\n-        line = line.strip().lstrip(\"!\")\n-        # Is this a comment?\n-        if datatype == \"comment\":\n-            comment_text += line + \"\\n\"\n-            continue\n-\n-        if datatype == \"command\":\n-            # The first time I find commands, I save whatever comments into\n-            # The initial comments.\n-            if command_lines == \"\":\n-                initial_comments = comment_text\n-                comment_text = \"\"\n-\n-            if err_specs != {}:\n-                warnings.warn(\n-                    \"This file contains multiple command blocks. Please verify\",\n-                    AstropyUserWarning,\n-                )\n-            command_lines += line + \"\\n\"\n-            continue\n-\n-        if datatype.startswith(\"data\"):\n-            # The first time I find data, I define err_specs\n-            if err_specs == {} and command_lines != \"\":\n-                for cline in command_lines.strip().split(\"\\n\"):\n-                    command = cline.strip().split()\n-                    # This should never happen, but just in case.\n-                    if len(command) < 3:\n-                        continue\n-                    err_specs[command[1].lower()] = [int(c) for c in command[2:]]\n-            if colnames is None:\n-                colnames = _interpret_err_lines(err_specs, ncol, names=input_colnames)\n-\n-            if current_rows is None:\n-                current_rows = []\n-\n-            values = []\n-            for v in line.split(delimiter):\n-                if v == \"NO\":\n-                    values.append(np.ma.masked)\n-                else:\n-                    # Understand if number is int or float\n-                    try:\n-                        values.append(int(v))\n-                    except ValueError:\n-                        values.append(float(v))\n-            current_rows.append(values)\n-            continue\n-\n-        if datatype == \"new\":\n-            # Save table to table_list and reset\n-            if current_rows is not None:\n-                new_table = Table(names=colnames, rows=current_rows)\n-                new_table.meta[\"initial_comments\"] = initial_comments.strip().split(\n-                    \"\\n\"\n-                )\n-                new_table.meta[\"comments\"] = comment_text.strip().split(\"\\n\")\n-                # Reset comments\n-                comment_text = \"\"\n-                table_list.append(new_table)\n-                current_rows = None\n-            continue\n-\n-    # At the very end, if there is still a table being written, let's save\n-    # it to the table_list\n-    if current_rows is not None:\n-        new_table = Table(names=colnames, rows=current_rows)\n-        new_table.meta[\"initial_comments\"] = initial_comments.strip().split(\"\\n\")\n-        new_table.meta[\"comments\"] = comment_text.strip().split(\"\\n\")\n-        table_list.append(new_table)\n-\n-    return table_list\n-\n-\n-def _understand_err_col(colnames):\n-    \"\"\"Get which column names are error columns.\n-\n-    Examples\n-    --------\n-    >>> colnames = ['a', 'a_err', 'b', 'b_perr', 'b_nerr']\n-    >>> serr, terr = _understand_err_col(colnames)\n-    >>> np.allclose(serr, [1])\n-    True\n-    >>> np.allclose(terr, [2])\n-    True\n-    >>> serr, terr = _understand_err_col(['a', 'a_nerr'])\n-    Traceback (most recent call last):\n-    ...\n-    ValueError: Missing positive error...\n-    >>> serr, terr = _understand_err_col(['a', 'a_perr'])\n-    Traceback (most recent call last):\n-    ...\n-    ValueError: Missing negative error...\n-    \"\"\"\n-    shift = 0\n-    serr = []\n-    terr = []\n-\n-    for i, col in enumerate(colnames):\n-        if col.endswith(\"_err\"):\n-            # The previous column, but they're numbered from 1!\n-            # Plus, take shift into account\n-            serr.append(i - shift)\n-            shift += 1\n-        elif col.endswith(\"_perr\"):\n-            terr.append(i - shift)\n-            if len(colnames) == i + 1 or not colnames[i + 1].endswith(\"_nerr\"):\n-                raise ValueError(\"Missing negative error\")\n-            shift += 2\n-        elif col.endswith(\"_nerr\") and not colnames[i - 1].endswith(\"_perr\"):\n-            raise ValueError(\"Missing positive error\")\n-    return serr, terr\n-\n-\n-def _read_table_qdp(qdp_file, names=None, table_id=None, delimiter=None):\n-    \"\"\"Read a table from a QDP file.\n-\n-    Parameters\n-    ----------\n-    qdp_file : str\n-        Input QDP file name\n-\n-    Other Parameters\n-    ----------------\n-    names : list of str\n-        Name of data columns (defaults to ['col1', 'col2', ...]), _not_\n-        including error columns.\n-\n-    table_id : int, default 0\n-        Number of the table to be read from the QDP file. This is useful\n-        when multiple tables present in the file. By default, the first is read.\n-\n-    delimiter : str\n-        Any delimiter accepted by the `sep` argument of str.split()\n-\n-    Returns\n-    -------\n-    tables : list of `~astropy.table.Table`\n-        List containing all the tables present inside the QDP file\n-    \"\"\"\n-    if table_id is None:\n-        warnings.warn(\n-            \"table_id not specified. Reading the first available table\",\n-            AstropyUserWarning,\n-        )\n-        table_id = 0\n-\n-    tables = _get_tables_from_qdp_file(\n-        qdp_file, input_colnames=names, delimiter=delimiter\n-    )\n-\n-    return tables[table_id]\n-\n-\n-def _write_table_qdp(table, filename=None, err_specs=None):\n-    \"\"\"Write a table to a QDP file.\n-\n-    Parameters\n-    ----------\n-    table : :class:`~astropy.table.Table`\n-        Input table to be written\n-    filename : str\n-        Output QDP file name\n-\n-    Other Parameters\n-    ----------------\n-    err_specs : dict\n-        Dictionary of the format {'serr': [1], 'terr': [2, 3]}, specifying\n-        which columns have symmetric and two-sided errors (see QDP format\n-        specification)\n-    \"\"\"\n-    import io\n-\n-    fobj = io.StringIO()\n-\n-    if \"initial_comments\" in table.meta and table.meta[\"initial_comments\"] != []:\n-        for line in table.meta[\"initial_comments\"]:\n-            line = line.strip()\n-            if not line.startswith(\"!\"):\n-                line = \"!\" + line\n-            print(line, file=fobj)\n-\n-    if err_specs is None:\n-        serr_cols, terr_cols = _understand_err_col(table.colnames)\n-    else:\n-        serr_cols = err_specs.pop(\"serr\", [])\n-        terr_cols = err_specs.pop(\"terr\", [])\n-    if serr_cols != []:\n-        col_string = \" \".join([str(val) for val in serr_cols])\n-        print(f\"READ SERR {col_string}\", file=fobj)\n-    if terr_cols != []:\n-        col_string = \" \".join([str(val) for val in terr_cols])\n-        print(f\"READ TERR {col_string}\", file=fobj)\n-\n-    if \"comments\" in table.meta and table.meta[\"comments\"] != []:\n-        for line in table.meta[\"comments\"]:\n-            line = line.strip()\n-            if not line.startswith(\"!\"):\n-                line = \"!\" + line\n-            print(line, file=fobj)\n-\n-    colnames = table.colnames\n-    print(\"!\" + \" \".join(colnames), file=fobj)\n-    for row in table:\n-        values = []\n-        for val in row:\n-            if not np.ma.is_masked(val):\n-                rep = str(val)\n-            else:\n-                rep = \"NO\"\n-            values.append(rep)\n-        print(\" \".join(values), file=fobj)\n-\n-    full_string = fobj.getvalue()\n-    fobj.close()\n-\n-    if filename is not None:\n-        with open(filename, \"w\") as fobj:\n-            print(full_string, file=fobj)\n-\n-    return full_string.split(\"\\n\")\n-\n-\n-class QDPSplitter(core.DefaultSplitter):\n-    \"\"\"\n-    Split on space for QDP tables.\n-    \"\"\"\n-\n-    delimiter = \" \"\n-\n-\n-class QDPHeader(basic.CommentedHeaderHeader):\n-    \"\"\"\n-    Header that uses the :class:`astropy.io.ascii.basic.QDPSplitter`.\n-    \"\"\"\n-\n-    splitter_class = QDPSplitter\n-    comment = \"!\"\n-    write_comment = \"!\"\n-\n-\n-class QDPData(basic.BasicData):\n-    \"\"\"\n-    Data that uses the :class:`astropy.io.ascii.basic.CsvSplitter`.\n-    \"\"\"\n-\n-    splitter_class = QDPSplitter\n-    fill_values = [(core.masked, \"NO\")]\n-    comment = \"!\"\n-    write_comment = None\n-\n-\n-class QDP(basic.Basic):\n-    \"\"\"Quick and Dandy Plot table.\n-\n-    Example::\n-\n-        ! Initial comment line 1\n-        ! Initial comment line 2\n-        READ TERR 1\n-        READ SERR 3\n-        ! Table 0 comment\n-        !a a(pos) a(neg) b be c d\n-        53000.5   0.25  -0.5   1  1.5  3.5 2\n-        54000.5   1.25  -1.5   2  2.5  4.5 3\n-        NO NO NO NO NO\n-        ! Table 1 comment\n-        !a a(pos) a(neg) b be c d\n-        54000.5   2.25  -2.5   NO  3.5  5.5 5\n-        55000.5   3.25  -3.5   4  4.5  6.5 nan\n-\n-    The input table above contains some initial comments, the error commands,\n-    then two tables.\n-    This file format can contain multiple tables, separated by a line full\n-    of ``NO``s. Comments are exclamation marks, and missing values are single\n-    ``NO`` entries. The delimiter is usually whitespace, more rarely a comma.\n-    The QDP format differentiates between data and error columns. The table\n-    above has commands::\n-\n-        READ TERR 1\n-        READ SERR 3\n-\n-    which mean that after data column 1 there will be two error columns\n-    containing its positive and engative error bars, then data column 2 without\n-    error bars, then column 3, then a column with the symmetric error of column\n-    3, then the remaining data columns.\n-\n-    As explained below, table headers are highly inconsistent. Possible\n-    comments containing column names will be ignored and columns will be called\n-    ``col1``, ``col2``, etc. unless the user specifies their names with the\n-    ``names=`` keyword argument,\n-    When passing column names, pass **only the names of the data columns, not\n-    the error columns.**\n-    Error information will be encoded in the names of the table columns.\n-    (e.g. ``a_perr`` and ``a_nerr`` for the positive and negative error of\n-    column ``a``, ``b_err`` the symmetric error of column ``b``.)\n-\n-    When writing tables to this format, users can pass an ``err_specs`` keyword\n-    passing a dictionary ``{'serr': [3], 'terr': [1, 2]}``, meaning that data\n-    columns 1 and two will have two additional columns each with their positive\n-    and negative errors, and data column 3 will have an additional column with\n-    a symmetric error (just like the ``READ SERR`` and ``READ TERR`` commands\n-    above)\n-\n-    Headers are just comments, and tables distributed by various missions\n-    can differ greatly in their use of conventions. For example, light curves\n-    distributed by the Swift-Gehrels mission have an extra space in one header\n-    entry that makes the number of labels inconsistent with the number of cols.\n-    For this reason, we ignore the comments that might encode the column names\n-    and leave the name specification to the user.\n-\n-    Example::\n-\n-        >               Extra space\n-        >                   |\n-        >                   v\n-        >!     MJD       Err (pos)       Err(neg)        Rate            Error\n-        >53000.123456   2.378e-05     -2.378472e-05     NO             0.212439\n-\n-    These readers and writer classes will strive to understand which of the\n-    comments belong to all the tables, and which ones to each single table.\n-    General comments will be stored in the ``initial_comments`` meta of each\n-    table. The comments of each table will be stored in the ``comments`` meta.\n-\n-    Example::\n-\n-        t = Table.read(example_qdp, format='ascii.qdp', table_id=1, names=['a', 'b', 'c', 'd'])\n-\n-    reads the second table (``table_id=1``) in file ``example.qdp`` containing\n-    the table above. There are four column names but seven data columns, why?\n-    Because the ``READ SERR`` and ``READ TERR`` commands say that there are\n-    three error columns.\n-    ``t.meta['initial_comments']`` will contain the initial two comment lines\n-    in the file, while ``t.meta['comments']`` will contain ``Table 1 comment``\n-\n-    The table can be written to another file, preserving the same information,\n-    as::\n-\n-        t.write(test_file, err_specs={'terr': [1], 'serr': [3]})\n-\n-    Note how the ``terr`` and ``serr`` commands are passed to the writer.\n-\n-    \"\"\"\n-\n-    _format_name = \"qdp\"\n-    _io_registry_can_write = True\n-    _io_registry_suffix = \".qdp\"\n-    _description = \"Quick and Dandy Plotter\"\n-\n-    header_class = QDPHeader\n-    data_class = QDPData\n-\n-    def __init__(self, table_id=None, names=None, err_specs=None, sep=None):\n-        super().__init__()\n-        self.table_id = table_id\n-        self.names = names\n-        self.err_specs = err_specs\n-        self.delimiter = sep\n-\n-    def read(self, table):\n-        self.lines = self.inputter.get_lines(table, newline=\"\\n\")\n-        return _read_table_qdp(\n-            self.lines,\n-            table_id=self.table_id,\n-            names=self.names,\n-            delimiter=self.delimiter,\n-        )\n-\n-    def write(self, table):\n-        self._check_multidim_table(table)\n-        lines = _write_table_qdp(table, err_specs=self.err_specs)\n-        return lines\n+class QDPCommand:\n+    def __init__(self, line):\n+        self.line = line.strip()\n+        self.cmd = self.line.split()[0].lower()  # <--- Change here\n+        self.args = self.line.split()[1:]\n\\ No newline at end of file\n"}
{"instance_id": "astropy__astropy-7606", "model_name_or_path": "cain-70b-e124", "model_patch": "diff --git a/astropy/units/core.py b/astropy/units/core.py\nindex e9bd986d33..03d16fa9f1 100644\n--- a/astropy/units/core.py\n+++ b/astropy/units/core.py\n@@ -1,2316 +1,5 @@\n-# -*- coding: utf-8 -*-\n-# Licensed under a 3-clause BSD style license - see LICENSE.rst\n-\n-\"\"\"\n-Core units classes and functions\n-\"\"\"\n-\n-\n-import inspect\n-import operator\n-import textwrap\n-import warnings\n-\n-import numpy as np\n-\n-from ..utils.decorators import lazyproperty\n-from ..utils.exceptions import AstropyWarning\n-from ..utils.misc import isiterable, InheritDocstrings\n-from .utils import (is_effectively_unity, sanitize_scale, validate_power,\n-                    resolve_fractions)\n-from . import format as unit_format\n-\n-\n-__all__ = [\n-    'UnitsError', 'UnitsWarning', 'UnitConversionError', 'UnitTypeError',\n-    'UnitBase', 'NamedUnit', 'IrreducibleUnit', 'Unit', 'CompositeUnit',\n-    'PrefixUnit', 'UnrecognizedUnit', 'def_unit', 'get_current_unit_registry',\n-    'set_enabled_units', 'add_enabled_units',\n-    'set_enabled_equivalencies', 'add_enabled_equivalencies',\n-    'dimensionless_unscaled', 'one']\n-\n-UNITY = 1.0\n-\n-\n-def _flatten_units_collection(items):\n-    \"\"\"\n-    Given a list of sequences, modules or dictionaries of units, or\n-    single units, return a flat set of all the units found.\n-    \"\"\"\n-    if not isinstance(items, list):\n-        items = [items]\n-\n-    result = set()\n-    for item in items:\n-        if isinstance(item, UnitBase):\n-            result.add(item)\n-        else:\n-            if isinstance(item, dict):\n-                units = item.values()\n-            elif inspect.ismodule(item):\n-                units = vars(item).values()\n-            elif isiterable(item):\n-                units = item\n-            else:\n-                continue\n-\n-            for unit in units:\n-                if isinstance(unit, UnitBase):\n-                    result.add(unit)\n-\n-    return result\n-\n-\n-def _normalize_equivalencies(equivalencies):\n-    \"\"\"\n-    Normalizes equivalencies, ensuring each is a 4-tuple of the form::\n-\n-    (from_unit, to_unit, forward_func, backward_func)\n-\n-    Parameters\n-    ----------\n-    equivalencies : list of equivalency pairs\n-\n-    Raises\n-    ------\n-    ValueError if an equivalency cannot be interpreted\n-    \"\"\"\n-    if equivalencies is None:\n-        return []\n-\n-    normalized = []\n-\n-    for i, equiv in enumerate(equivalencies):\n-        if len(equiv) == 2:\n-            funit, tunit = equiv\n-            a = b = lambda x: x\n-        elif len(equiv) == 3:\n-            funit, tunit, a = equiv\n-            b = a\n-        elif len(equiv) == 4:\n-            funit, tunit, a, b = equiv\n-        else:\n-            raise ValueError(\n-                \"Invalid equivalence entry {0}: {1!r}\".format(i, equiv))\n-        if not (funit is Unit(funit) and\n-                (tunit is None or tunit is Unit(tunit)) and\n-                callable(a) and\n-                callable(b)):\n-            raise ValueError(\n-                \"Invalid equivalence entry {0}: {1!r}\".format(i, equiv))\n-        normalized.append((funit, tunit, a, b))\n-\n-    return normalized\n-\n-\n-class _UnitRegistry:\n-    \"\"\"\n-    Manages a registry of the enabled units.\n-    \"\"\"\n-\n-    def __init__(self, init=[], equivalencies=[]):\n-\n-        if isinstance(init, _UnitRegistry):\n-            # If passed another registry we don't need to rebuild everything.\n-            # but because these are mutable types we don't want to create\n-            # conflicts so everything needs to be copied.\n-            self._equivalencies = init._equivalencies.copy()\n-            self._all_units = init._all_units.copy()\n-            self._registry = init._registry.copy()\n-            self._non_prefix_units = init._non_prefix_units.copy()\n-            # The physical type is a dictionary containing sets as values.\n-            # All of these must be copied otherwise we could alter the old\n-            # registry.\n-            self._by_physical_type = {k: v.copy() for k, v in\n-                                      init._by_physical_type.items()}\n-\n-        else:\n-            self._reset_units()\n-            self._reset_equivalencies()\n-            self.add_enabled_units(init)\n-            self.add_enabled_equivalencies(equivalencies)\n-\n-    def _reset_units(self):\n-        self._all_units = set()\n-        self._non_prefix_units = set()\n-        self._registry = {}\n-        self._by_physical_type = {}\n-\n-    def _reset_equivalencies(self):\n-        self._equivalencies = set()\n-\n-    @property\n-    def registry(self):\n-        return self._registry\n-\n-    @property\n-    def all_units(self):\n-        return self._all_units\n-\n-    @property\n-    def non_prefix_units(self):\n-        return self._non_prefix_units\n-\n-    def set_enabled_units(self, units):\n-        \"\"\"\n-        Sets the units enabled in the unit registry.\n-\n-        These units are searched when using\n-        `UnitBase.find_equivalent_units`, for example.\n-\n-        Parameters\n-        ----------\n-        units : list of sequences, dicts, or modules containing units, or units\n-            This is a list of things in which units may be found\n-            (sequences, dicts or modules), or units themselves.  The\n-            entire set will be \"enabled\" for searching through by\n-            methods like `UnitBase.find_equivalent_units` and\n-            `UnitBase.compose`.\n-        \"\"\"\n-        self._reset_units()\n-        return self.add_enabled_units(units)\n-\n-    def add_enabled_units(self, units):\n-        \"\"\"\n-        Adds to the set of units enabled in the unit registry.\n-\n-        These units are searched when using\n-        `UnitBase.find_equivalent_units`, for example.\n-\n-        Parameters\n-        ----------\n-        units : list of sequences, dicts, or modules containing units, or units\n-            This is a list of things in which units may be found\n-            (sequences, dicts or modules), or units themselves.  The\n-            entire set will be added to the \"enabled\" set for\n-            searching through by methods like\n-            `UnitBase.find_equivalent_units` and `UnitBase.compose`.\n-        \"\"\"\n-        units = _flatten_units_collection(units)\n-\n-        for unit in units:\n-            # Loop through all of the names first, to ensure all of them\n-            # are new, then add them all as a single \"transaction\" below.\n-            for st in unit._names:\n-                if (st in self._registry and unit != self._registry[st]):\n-                    raise ValueError(\n-                        \"Object with name {0!r} already exists in namespace. \"\n-                        \"Filter the set of units to avoid name clashes before \"\n-                        \"enabling them.\".format(st))\n-\n-            for st in unit._names:\n-                self._registry[st] = unit\n-\n-            self._all_units.add(unit)\n-            if not isinstance(unit, PrefixUnit):\n-                self._non_prefix_units.add(unit)\n-\n-            hash = unit._get_physical_type_id()\n-            self._by_physical_type.setdefault(hash, set()).add(unit)\n-\n-    def get_units_with_physical_type(self, unit):\n-        \"\"\"\n-        Get all units in the registry with the same physical type as\n-        the given unit.\n-\n-        Parameters\n-        ----------\n-        unit : UnitBase instance\n-        \"\"\"\n-        return self._by_physical_type.get(unit._get_physical_type_id(), set())\n-\n-    @property\n-    def equivalencies(self):\n-        return list(self._equivalencies)\n-\n-    def set_enabled_equivalencies(self, equivalencies):\n-        \"\"\"\n-        Sets the equivalencies enabled in the unit registry.\n-\n-        These equivalencies are used if no explicit equivalencies are given,\n-        both in unit conversion and in finding equivalent units.\n-\n-        This is meant in particular for allowing angles to be dimensionless.\n-        Use with care.\n-\n-        Parameters\n-        ----------\n-        equivalencies : list of equivalent pairs\n-            E.g., as returned by\n-            `~astropy.units.equivalencies.dimensionless_angles`.\n-        \"\"\"\n-        self._reset_equivalencies()\n-        return self.add_enabled_equivalencies(equivalencies)\n-\n-    def add_enabled_equivalencies(self, equivalencies):\n-        \"\"\"\n-        Adds to the set of equivalencies enabled in the unit registry.\n-\n-        These equivalencies are used if no explicit equivalencies are given,\n-        both in unit conversion and in finding equivalent units.\n-\n-        This is meant in particular for allowing angles to be dimensionless.\n-        Use with care.\n-\n-        Parameters\n-        ----------\n-        equivalencies : list of equivalent pairs\n-            E.g., as returned by\n-            `~astropy.units.equivalencies.dimensionless_angles`.\n-        \"\"\"\n-        # pre-normalize list to help catch mistakes\n-        equivalencies = _normalize_equivalencies(equivalencies)\n-        self._equivalencies |= set(equivalencies)\n-\n-\n-class _UnitContext:\n-    def __init__(self, init=[], equivalencies=[]):\n-        _unit_registries.append(\n-            _UnitRegistry(init=init, equivalencies=equivalencies))\n-\n-    def __enter__(self):\n-        pass\n-\n-    def __exit__(self, type, value, tb):\n-        _unit_registries.pop()\n-\n-\n-_unit_registries = [_UnitRegistry()]\n-\n-\n-def get_current_unit_registry():\n-    return _unit_registries[-1]\n-\n-\n-def set_enabled_units(units):\n-    \"\"\"\n-    Sets the units enabled in the unit registry.\n-\n-    These units are searched when using\n-    `UnitBase.find_equivalent_units`, for example.\n-\n-    This may be used either permanently, or as a context manager using\n-    the ``with`` statement (see example below).\n-\n-    Parameters\n-    ----------\n-    units : list of sequences, dicts, or modules containing units, or units\n-        This is a list of things in which units may be found\n-        (sequences, dicts or modules), or units themselves.  The\n-        entire set will be \"enabled\" for searching through by methods\n-        like `UnitBase.find_equivalent_units` and `UnitBase.compose`.\n-\n-    Examples\n-    --------\n-\n-    >>> from astropy import units as u\n-    >>> with u.set_enabled_units([u.pc]):\n-    ...     u.m.find_equivalent_units()\n-    ...\n-      Primary name | Unit definition | Aliases\n-    [\n-      pc           | 3.08568e+16 m   | parsec  ,\n-    ]\n-    >>> u.m.find_equivalent_units()\n-      Primary name | Unit definition | Aliases\n-    [\n-      AU           | 1.49598e+11 m   | au, astronomical_unit ,\n-      Angstrom     | 1e-10 m         | AA, angstrom          ,\n-      cm           | 0.01 m          | centimeter            ,\n-      earthRad     | 6.3781e+06 m    | R_earth, Rearth       ,\n-      jupiterRad   | 7.1492e+07 m    | R_jup, Rjup, R_jupiter, Rjupiter ,\n-      lyr          | 9.46073e+15 m   | lightyear             ,\n-      m            | irreducible     | meter                 ,\n-      micron       | 1e-06 m         |                       ,\n-      pc           | 3.08568e+16 m   | parsec                ,\n-      solRad       | 6.957e+08 m     | R_sun, Rsun           ,\n-    ]\n-    \"\"\"\n-    # get a context with a new registry, using equivalencies of the current one\n-    context = _UnitContext(\n-        equivalencies=get_current_unit_registry().equivalencies)\n-    # in this new current registry, enable the units requested\n-    get_current_unit_registry().set_enabled_units(units)\n-    return context\n-\n-\n-def add_enabled_units(units):\n-    \"\"\"\n-    Adds to the set of units enabled in the unit registry.\n-\n-    These units are searched when using\n-    `UnitBase.find_equivalent_units`, for example.\n-\n-    This may be used either permanently, or as a context manager using\n-    the ``with`` statement (see example below).\n-\n-    Parameters\n-    ----------\n-    units : list of sequences, dicts, or modules containing units, or units\n-        This is a list of things in which units may be found\n-        (sequences, dicts or modules), or units themselves.  The\n-        entire set will be added to the \"enabled\" set for searching\n-        through by methods like `UnitBase.find_equivalent_units` and\n-        `UnitBase.compose`.\n-\n-    Examples\n-    --------\n-\n-    >>> from astropy import units as u\n-    >>> from astropy.units import imperial\n-    >>> with u.add_enabled_units(imperial):\n-    ...     u.m.find_equivalent_units()\n-    ...\n-      Primary name | Unit definition | Aliases\n-    [\n-      AU           | 1.49598e+11 m   | au, astronomical_unit ,\n-      Angstrom     | 1e-10 m         | AA, angstrom          ,\n-      cm           | 0.01 m          | centimeter            ,\n-      earthRad     | 6.3781e+06 m    | R_earth, Rearth       ,\n-      ft           | 0.3048 m        | foot                  ,\n-      fur          | 201.168 m       | furlong               ,\n-      inch         | 0.0254 m        |                       ,\n-      jupiterRad   | 7.1492e+07 m    | R_jup, Rjup, R_jupiter, Rjupiter ,\n-      lyr          | 9.46073e+15 m   | lightyear             ,\n-      m            | irreducible     | meter                 ,\n-      mi           | 1609.34 m       | mile                  ,\n-      micron       | 1e-06 m         |                       ,\n-      mil          | 2.54e-05 m      | thou                  ,\n-      nmi          | 1852 m          | nauticalmile, NM      ,\n-      pc           | 3.08568e+16 m   | parsec                ,\n-      solRad       | 6.957e+08 m     | R_sun, Rsun           ,\n-      yd           | 0.9144 m        | yard                  ,\n-    ]\n-    \"\"\"\n-    # get a context with a new registry, which is a copy of the current one\n-    context = _UnitContext(get_current_unit_registry())\n-    # in this new current registry, enable the further units requested\n-    get_current_unit_registry().add_enabled_units(units)\n-    return context\n-\n-\n-def set_enabled_equivalencies(equivalencies):\n-    \"\"\"\n-    Sets the equivalencies enabled in the unit registry.\n-\n-    These equivalencies are used if no explicit equivalencies are given,\n-    both in unit conversion and in finding equivalent units.\n-\n-    This is meant in particular for allowing angles to be dimensionless.\n-    Use with care.\n-\n-    Parameters\n-    ----------\n-    equivalencies : list of equivalent pairs\n-        E.g., as returned by\n-        `~astropy.units.equivalencies.dimensionless_angles`.\n-\n-    Examples\n-    --------\n-    Exponentiation normally requires dimensionless quantities.  To avoid\n-    problems with complex phases::\n-\n-        >>> from astropy import units as u\n-        >>> with u.set_enabled_equivalencies(u.dimensionless_angles()):\n-        ...     phase = 0.5 * u.cycle\n-        ...     np.exp(1j*phase)  # doctest: +SKIP\n-        <Quantity  -1. +1.22464680e-16j>\n-    \"\"\"\n-    # doctest skipped as the complex number formatting changed in numpy 1.14.\n-    #\n-    # get a context with a new registry, using all units of the current one\n-    context = _UnitContext(get_current_unit_registry())\n-    # in this new current registry, enable the equivalencies requested\n-    get_current_unit_registry().set_enabled_equivalencies(equivalencies)\n-    return context\n-\n-\n-def add_enabled_equivalencies(equivalencies):\n-    \"\"\"\n-    Adds to the equivalencies enabled in the unit registry.\n-\n-    These equivalencies are used if no explicit equivalencies are given,\n-    both in unit conversion and in finding equivalent units.\n-\n-    This is meant in particular for allowing angles to be dimensionless.\n-    Since no equivalencies are enabled by default, generally it is recommended\n-    to use `set_enabled_equivalencies`.\n-\n-    Parameters\n-    ----------\n-    equivalencies : list of equivalent pairs\n-        E.g., as returned by\n-        `~astropy.units.equivalencies.dimensionless_angles`.\n-    \"\"\"\n-    # get a context with a new registry, which is a copy of the current one\n-    context = _UnitContext(get_current_unit_registry())\n-    # in this new current registry, enable the further equivalencies requested\n-    get_current_unit_registry().add_enabled_equivalencies(equivalencies)\n-    return context\n-\n-\n-class UnitsError(Exception):\n-    \"\"\"\n-    The base class for unit-specific exceptions.\n-    \"\"\"\n-\n-\n-class UnitScaleError(UnitsError, ValueError):\n-    \"\"\"\n-    Used to catch the errors involving scaled units,\n-    which are not recognized by FITS format.\n-    \"\"\"\n-    pass\n-\n-\n-class UnitConversionError(UnitsError, ValueError):\n-    \"\"\"\n-    Used specifically for errors related to converting between units or\n-    interpreting units in terms of other units.\n-    \"\"\"\n-\n-\n-class UnitTypeError(UnitsError, TypeError):\n-    \"\"\"\n-    Used specifically for errors in setting to units not allowed by a class.\n-\n-    E.g., would be raised if the unit of an `~astropy.coordinates.Angle`\n-    instances were set to a non-angular unit.\n-    \"\"\"\n-\n-\n-class UnitsWarning(AstropyWarning):\n-    \"\"\"\n-    The base class for unit-specific warnings.\n-    \"\"\"\n-\n-\n-class UnitBase(metaclass=InheritDocstrings):\n-    \"\"\"\n-    Abstract base class for units.\n-\n-    Most of the arithmetic operations on units are defined in this\n-    base class.\n-\n-    Should not be instantiated by users directly.\n-    \"\"\"\n-    # Make sure that __rmul__ of units gets called over the __mul__ of Numpy\n-    # arrays to avoid element-wise multiplication.\n-    __array_priority__ = 1000\n-\n-    def __deepcopy__(self, memo):\n-        # This may look odd, but the units conversion will be very\n-        # broken after deep-copying if we don't guarantee that a given\n-        # physical unit corresponds to only one instance\n-        return self\n-\n-    def _repr_latex_(self):\n-        \"\"\"\n-        Generate latex representation of unit name.  This is used by\n-        the IPython notebook to print a unit with a nice layout.\n-\n-        Returns\n-        -------\n-        Latex string\n-        \"\"\"\n-        return unit_format.Latex.to_string(self)\n-\n-    def __bytes__(self):\n-        \"\"\"Return string representation for unit\"\"\"\n-        return unit_format.Generic.to_string(self).encode('unicode_escape')\n-\n-    def __str__(self):\n-        \"\"\"Return string representation for unit\"\"\"\n-        return unit_format.Generic.to_string(self)\n-\n-    def __repr__(self):\n-        string = unit_format.Generic.to_string(self)\n-\n-        return 'Unit(\"{0}\")'.format(string)\n-\n-    def _get_physical_type_id(self):\n-        \"\"\"\n-        Returns an identifier that uniquely identifies the physical\n-        type of this unit.  It is comprised of the bases and powers of\n-        this unit, without the scale.  Since it is hashable, it is\n-        useful as a dictionary key.\n-        \"\"\"\n-        unit = self.decompose()\n-        r = zip([x.name for x in unit.bases], unit.powers)\n-        # bases and powers are already sorted in a unique way\n-        # r.sort()\n-        r = tuple(r)\n-        return r\n-\n-    @property\n-    def names(self):\n-        \"\"\"\n-        Returns all of the names associated with this unit.\n-        \"\"\"\n-        raise AttributeError(\n-            \"Can not get names from unnamed units. \"\n-            \"Perhaps you meant to_string()?\")\n-\n-    @property\n-    def name(self):\n-        \"\"\"\n-        Returns the canonical (short) name associated with this unit.\n-        \"\"\"\n-        raise AttributeError(\n-            \"Can not get names from unnamed units. \"\n-            \"Perhaps you meant to_string()?\")\n-\n-    @property\n-    def aliases(self):\n-        \"\"\"\n-        Returns the alias (long) names for this unit.\n-        \"\"\"\n-        raise AttributeError(\n-            \"Can not get aliases from unnamed units. \"\n-            \"Perhaps you meant to_string()?\")\n-\n-    @property\n-    def scale(self):\n-        \"\"\"\n-        Return the scale of the unit.\n-        \"\"\"\n-        return 1.0\n-\n-    @property\n-    def bases(self):\n-        \"\"\"\n-        Return the bases of the unit.\n-        \"\"\"\n-        return [self]\n-\n-    @property\n-    def powers(self):\n-        \"\"\"\n-        Return the powers of the unit.\n-        \"\"\"\n-        return [1]\n-\n-    def to_string(self, format=unit_format.Generic):\n-        \"\"\"\n-        Output the unit in the given format as a string.\n-\n-        Parameters\n-        ----------\n-        format : `astropy.units.format.Base` instance or str\n-            The name of a format or a formatter object.  If not\n-            provided, defaults to the generic format.\n-        \"\"\"\n-\n-        f = unit_format.get_format(format)\n-        return f.to_string(self)\n-\n-    def __format__(self, format_spec):\n-        \"\"\"Try to format units using a formatter.\"\"\"\n-        try:\n-            return self.to_string(format=format_spec)\n-        except ValueError:\n-            return format(str(self), format_spec)\n-\n-    @staticmethod\n-    def _normalize_equivalencies(equivalencies):\n-        \"\"\"\n-        Normalizes equivalencies, ensuring each is a 4-tuple of the form::\n-\n-        (from_unit, to_unit, forward_func, backward_func)\n-\n-        Parameters\n-        ----------\n-        equivalencies : list of equivalency pairs, or `None`\n-\n-        Returns\n-        -------\n-        A normalized list, including possible global defaults set by, e.g.,\n-        `set_enabled_equivalencies`, except when `equivalencies`=`None`,\n-        in which case the returned list is always empty.\n-\n-        Raises\n-        ------\n-        ValueError if an equivalency cannot be interpreted\n-        \"\"\"\n-        normalized = _normalize_equivalencies(equivalencies)\n-        if equivalencies is not None:\n-            normalized += get_current_unit_registry().equivalencies\n-\n-        return normalized\n-\n-    def __pow__(self, p):\n-        p = validate_power(p)\n-        return CompositeUnit(1, [self], [p], _error_check=False)\n-\n-    def __div__(self, m):\n-        if isinstance(m, (bytes, str)):\n-            m = Unit(m)\n-\n-        if isinstance(m, UnitBase):\n-            if m.is_unity():\n-                return self\n-            return CompositeUnit(1, [self, m], [1, -1], _error_check=False)\n-\n-        try:\n-            # Cannot handle this as Unit, re-try as Quantity\n-            from .quantity import Quantity\n-            return Quantity(1, self) / m\n-        except TypeError:\n-            return NotImplemented\n-\n-    def __rdiv__(self, m):\n-        if isinstance(m, (bytes, str)):\n-            return Unit(m) / self\n-\n-        try:\n-            # Cannot handle this as Unit.  Here, m cannot be a Quantity,\n-            # so we make it into one, fasttracking when it does not have a\n-            # unit, for the common case of <array> / <unit>.\n-            from .quantity import Quantity\n-            if hasattr(m, 'unit'):\n-                result = Quantity(m)\n-                result /= self\n-                return result\n-            else:\n-                return Quantity(m, self**(-1))\n-        except TypeError:\n-            return NotImplemented\n-\n-    __truediv__ = __div__\n-\n-    __rtruediv__ = __rdiv__\n-\n-    def __mul__(self, m):\n-        if isinstance(m, (bytes, str)):\n-            m = Unit(m)\n-\n-        if isinstance(m, UnitBase):\n-            if m.is_unity():\n-                return self\n-            elif self.is_unity():\n-                return m\n-            return CompositeUnit(1, [self, m], [1, 1], _error_check=False)\n-\n-        # Cannot handle this as Unit, re-try as Quantity.\n-        try:\n-            from .quantity import Quantity\n-            return Quantity(1, self) * m\n-        except TypeError:\n-            return NotImplemented\n-\n-    def __rmul__(self, m):\n-        if isinstance(m, (bytes, str)):\n-            return Unit(m) * self\n-\n-        # Cannot handle this as Unit.  Here, m cannot be a Quantity,\n-        # so we make it into one, fasttracking when it does not have a unit\n-        # for the common case of <array> * <unit>.\n-        try:\n-            from .quantity import Quantity\n-            if hasattr(m, 'unit'):\n-                result = Quantity(m)\n-                result *= self\n-                return result\n-            else:\n-                return Quantity(m, self)\n-        except TypeError:\n-            return NotImplemented\n-\n-    def __hash__(self):\n-        # This must match the hash used in CompositeUnit for a unit\n-        # with only one base and no scale or power.\n-        return hash((str(self.scale), self.name, str('1')))\n-\n-    def __eq__(self, other):\n-        if self is other:\n-            return True\n-\n-        try:\n-            other = Unit(other, parse_strict='silent')\n-        except (ValueError, UnitsError, TypeError):\n-            return False\n-\n-        # Other is Unit-like, but the test below requires it is a UnitBase\n-        # instance; if it is not, give up (so that other can try).\n-        if not isinstance(other, UnitBase):\n-            return NotImplemented\n-\n-        try:\n-            return is_effectively_unity(self._to(other))\n-        except UnitsError:\n-            return False\n-\n-    def __ne__(self, other):\n-        return not (self == other)\n-\n-    def __le__(self, other):\n-        scale = self._to(Unit(other))\n-        return scale <= 1. or is_effectively_unity(scale)\n-\n-    def __ge__(self, other):\n-        scale = self._to(Unit(other))\n-        return scale >= 1. or is_effectively_unity(scale)\n-\n-    def __lt__(self, other):\n-        return not (self >= other)\n-\n-    def __gt__(self, other):\n-        return not (self <= other)\n-\n-    def __neg__(self):\n-        return self * -1.\n-\n-    def is_equivalent(self, other, equivalencies=[]):\n-        \"\"\"\n-        Returns `True` if this unit is equivalent to ``other``.\n-\n-        Parameters\n-        ----------\n-        other : unit object or string or tuple\n-            The unit to convert to. If a tuple of units is specified, this\n-            method returns true if the unit matches any of those in the tuple.\n-\n-        equivalencies : list of equivalence pairs, optional\n-            A list of equivalence pairs to try if the units are not\n-            directly convertible.  See :ref:`unit_equivalencies`.\n-            This list is in addition to possible global defaults set by, e.g.,\n-            `set_enabled_equivalencies`.\n-            Use `None` to turn off all equivalencies.\n-\n-        Returns\n-        -------\n-        bool\n-        \"\"\"\n-        equivalencies = self._normalize_equivalencies(equivalencies)\n-\n-        if isinstance(other, tuple):\n-            return any(self.is_equivalent(u, equivalencies=equivalencies)\n-                       for u in other)\n-\n-        other = Unit(other, parse_strict='silent')\n-\n-        return self._is_equivalent(other, equivalencies)\n-\n-    def _is_equivalent(self, other, equivalencies=[]):\n-        \"\"\"Returns `True` if this unit is equivalent to `other`.\n-        See `is_equivalent`, except that a proper Unit object should be\n-        given (i.e., no string) and that the equivalency list should be\n-        normalized using `_normalize_equivalencies`.\n-        \"\"\"\n-        if isinstance(other, UnrecognizedUnit):\n-            return False\n-\n-        if (self._get_physical_type_id() ==\n-                other._get_physical_type_id()):\n-            return True\n-        elif len(equivalencies):\n-            unit = self.decompose()\n-            other = other.decompose()\n-            for a, b, forward, backward in equivalencies:\n-                if b is None:\n-                    # after canceling, is what's left convertible\n-                    # to dimensionless (according to the equivalency)?\n-                    try:\n-                        (other/unit).decompose([a])\n-                        return True\n-                    except Exception:\n-                        pass\n-                else:\n-                    if(a._is_equivalent(unit) and b._is_equivalent(other) or\n-                       b._is_equivalent(unit) and a._is_equivalent(other)):\n-                        return True\n-\n+def __eq__(self, other):\n+    if other is None:\n         return False\n-\n-    def _apply_equivalencies(self, unit, other, equivalencies):\n-        \"\"\"\n-        Internal function (used from `_get_converter`) to apply\n-        equivalence pairs.\n-        \"\"\"\n-        def make_converter(scale1, func, scale2):\n-            def convert(v):\n-                return func(_condition_arg(v) / scale1) * scale2\n-            return convert\n-\n-        for funit, tunit, a, b in equivalencies:\n-            if tunit is None:\n-                try:\n-                    ratio_in_funit = (other.decompose() /\n-                                      unit.decompose()).decompose([funit])\n-                    return make_converter(ratio_in_funit.scale, a, 1.)\n-                except UnitsError:\n-                    pass\n-            else:\n-                try:\n-                    scale1 = funit._to(unit)\n-                    scale2 = tunit._to(other)\n-                    return make_converter(scale1, a, scale2)\n-                except UnitsError:\n-                    pass\n-                try:\n-                    scale1 = tunit._to(unit)\n-                    scale2 = funit._to(other)\n-                    return make_converter(scale1, b, scale2)\n-                except UnitsError:\n-                    pass\n-\n-        def get_err_str(unit):\n-            unit_str = unit.to_string('unscaled')\n-            physical_type = unit.physical_type\n-            if physical_type != 'unknown':\n-                unit_str = \"'{0}' ({1})\".format(\n-                    unit_str, physical_type)\n-            else:\n-                unit_str = \"'{0}'\".format(unit_str)\n-            return unit_str\n-\n-        unit_str = get_err_str(unit)\n-        other_str = get_err_str(other)\n-\n-        raise UnitConversionError(\n-            \"{0} and {1} are not convertible\".format(\n-                unit_str, other_str))\n-\n-    def _get_converter(self, other, equivalencies=[]):\n-        other = Unit(other)\n-\n-        # First see if it is just a scaling.\n-        try:\n-            scale = self._to(other)\n-        except UnitsError:\n-            pass\n-        else:\n-            return lambda val: scale * _condition_arg(val)\n-\n-        # if that doesn't work, maybe we can do it with equivalencies?\n-        try:\n-            return self._apply_equivalencies(\n-                self, other, self._normalize_equivalencies(equivalencies))\n-        except UnitsError as exc:\n-            # Last hope: maybe other knows how to do it?\n-            # We assume the equivalencies have the unit itself as first item.\n-            # TODO: maybe better for other to have a `_back_converter` method?\n-            if hasattr(other, 'equivalencies'):\n-                for funit, tunit, a, b in other.equivalencies:\n-                    if other is funit:\n-                        try:\n-                            return lambda v: b(self._get_converter(\n-                                tunit, equivalencies=equivalencies)(v))\n-                        except Exception:\n-                            pass\n-\n-            raise exc\n-\n-    def _to(self, other):\n-        \"\"\"\n-        Returns the scale to the specified unit.\n-\n-        See `to`, except that a Unit object should be given (i.e., no\n-        string), and that all defaults are used, i.e., no\n-        equivalencies and value=1.\n-        \"\"\"\n-        # There are many cases where we just want to ensure a Quantity is\n-        # of a particular unit, without checking whether it's already in\n-        # a particular unit.  If we're being asked to convert from a unit\n-        # to itself, we can short-circuit all of this.\n-        if self is other:\n-            return 1.0\n-\n-        # Don't presume decomposition is possible; e.g.,\n-        # conversion to function units is through equivalencies.\n-        if isinstance(other, UnitBase):\n-            self_decomposed = self.decompose()\n-            other_decomposed = other.decompose()\n-\n-            # Check quickly whether equivalent.  This is faster than\n-            # `is_equivalent`, because it doesn't generate the entire\n-            # physical type list of both units.  In other words it \"fails\n-            # fast\".\n-            if(self_decomposed.powers == other_decomposed.powers and\n-               all(self_base is other_base for (self_base, other_base)\n-                   in zip(self_decomposed.bases, other_decomposed.bases))):\n-                return self_decomposed.scale / other_decomposed.scale\n-\n-        raise UnitConversionError(\n-            \"'{0!r}' is not a scaled version of '{1!r}'\".format(self, other))\n-\n-    def to(self, other, value=UNITY, equivalencies=[]):\n-        \"\"\"\n-        Return the converted values in the specified unit.\n-\n-        Parameters\n-        ----------\n-        other : unit object or string\n-            The unit to convert to.\n-\n-        value : scalar int or float, or sequence convertible to array, optional\n-            Value(s) in the current unit to be converted to the\n-            specified unit.  If not provided, defaults to 1.0\n-\n-        equivalencies : list of equivalence pairs, optional\n-            A list of equivalence pairs to try if the units are not\n-            directly convertible.  See :ref:`unit_equivalencies`.\n-            This list is in addition to possible global defaults set by, e.g.,\n-            `set_enabled_equivalencies`.\n-            Use `None` to turn off all equivalencies.\n-\n-        Returns\n-        -------\n-        values : scalar or array\n-            Converted value(s). Input value sequences are returned as\n-            numpy arrays.\n-\n-        Raises\n-        ------\n-        UnitsError\n-            If units are inconsistent\n-        \"\"\"\n-        if other is self and value is UNITY:\n-            return UNITY\n-        else:\n-            return self._get_converter(other, equivalencies=equivalencies)(value)\n-\n-    def in_units(self, other, value=1.0, equivalencies=[]):\n-        \"\"\"\n-        Alias for `to` for backward compatibility with pynbody.\n-        \"\"\"\n-        return self.to(\n-            other, value=value, equivalencies=equivalencies)\n-\n-    def decompose(self, bases=set()):\n-        \"\"\"\n-        Return a unit object composed of only irreducible units.\n-\n-        Parameters\n-        ----------\n-        bases : sequence of UnitBase, optional\n-            The bases to decompose into.  When not provided,\n-            decomposes down to any irreducible units.  When provided,\n-            the decomposed result will only contain the given units.\n-            This will raises a `UnitsError` if it's not possible\n-            to do so.\n-\n-        Returns\n-        -------\n-        unit : CompositeUnit object\n-            New object containing only irreducible unit objects.\n-        \"\"\"\n-        raise NotImplementedError()\n-\n-    def _compose(self, equivalencies=[], namespace=[], max_depth=2, depth=0,\n-                 cached_results=None):\n-        def is_final_result(unit):\n-            # Returns True if this result contains only the expected\n-            # units\n-            for base in unit.bases:\n-                if base not in namespace:\n-                    return False\n-            return True\n-\n-        unit = self.decompose()\n-        key = hash(unit)\n-\n-        cached = cached_results.get(key)\n-        if cached is not None:\n-            if isinstance(cached, Exception):\n-                raise cached\n-            return cached\n-\n-        # Prevent too many levels of recursion\n-        # And special case for dimensionless unit\n-        if depth >= max_depth:\n-            cached_results[key] = [unit]\n-            return [unit]\n-\n-        # Make a list including all of the equivalent units\n-        units = [unit]\n-        for funit, tunit, a, b in equivalencies:\n-            if tunit is not None:\n-                if self._is_equivalent(funit):\n-                    scale = funit.decompose().scale / unit.scale\n-                    units.append(Unit(a(1.0 / scale) * tunit).decompose())\n-                elif self._is_equivalent(tunit):\n-                    scale = tunit.decompose().scale / unit.scale\n-                    units.append(Unit(b(1.0 / scale) * funit).decompose())\n-            else:\n-                if self._is_equivalent(funit):\n-                    units.append(Unit(unit.scale))\n-\n-        # Store partial results\n-        partial_results = []\n-        # Store final results that reduce to a single unit or pair of\n-        # units\n-        if len(unit.bases) == 0:\n-            final_results = [set([unit]), set()]\n-        else:\n-            final_results = [set(), set()]\n-\n-        for tunit in namespace:\n-            tunit_decomposed = tunit.decompose()\n-            for u in units:\n-                # If the unit is a base unit, look for an exact match\n-                # to one of the bases of the target unit.  If found,\n-                # factor by the same power as the target unit's base.\n-                # This allows us to factor out fractional powers\n-                # without needing to do an exhaustive search.\n-                if len(tunit_decomposed.bases) == 1:\n-                    for base, power in zip(u.bases, u.powers):\n-                        if tunit_decomposed._is_equivalent(base):\n-                            tunit = tunit ** power\n-                            tunit_decomposed = tunit_decomposed ** power\n-                            break\n-\n-                composed = (u / tunit_decomposed).decompose()\n-                factored = composed * tunit\n-                len_bases = len(composed.bases)\n-                if is_final_result(factored) and len_bases <= 1:\n-                    final_results[len_bases].add(factored)\n-                else:\n-                    partial_results.append(\n-                        (len_bases, composed, tunit))\n-\n-        # Do we have any minimal results?\n-        for final_result in final_results:\n-            if len(final_result):\n-                results = final_results[0].union(final_results[1])\n-                cached_results[key] = results\n-                return results\n-\n-        partial_results.sort(key=operator.itemgetter(0))\n-\n-        # ...we have to recurse and try to further compose\n-        results = []\n-        for len_bases, composed, tunit in partial_results:\n-            try:\n-                composed_list = composed._compose(\n-                    equivalencies=equivalencies,\n-                    namespace=namespace,\n-                    max_depth=max_depth, depth=depth + 1,\n-                    cached_results=cached_results)\n-            except UnitsError:\n-                composed_list = []\n-            for subcomposed in composed_list:\n-                results.append(\n-                    (len(subcomposed.bases), subcomposed, tunit))\n-\n-        if len(results):\n-            results.sort(key=operator.itemgetter(0))\n-\n-            min_length = results[0][0]\n-            subresults = set()\n-            for len_bases, composed, tunit in results:\n-                if len_bases > min_length:\n-                    break\n-                else:\n-                    factored = composed * tunit\n-                    if is_final_result(factored):\n-                        subresults.add(factored)\n-\n-            if len(subresults):\n-                cached_results[key] = subresults\n-                return subresults\n-\n-        if not is_final_result(self):\n-            result = UnitsError(\n-                \"Cannot represent unit {0} in terms of the given \"\n-                \"units\".format(self))\n-            cached_results[key] = result\n-            raise result\n-\n-        cached_results[key] = [self]\n-        return [self]\n-\n-    def compose(self, equivalencies=[], units=None, max_depth=2,\n-                include_prefix_units=None):\n-        \"\"\"\n-        Return the simplest possible composite unit(s) that represent\n-        the given unit.  Since there may be multiple equally simple\n-        compositions of the unit, a list of units is always returned.\n-\n-        Parameters\n-        ----------\n-        equivalencies : list of equivalence pairs, optional\n-            A list of equivalence pairs to also list.  See\n-            :ref:`unit_equivalencies`.\n-            This list is in addition to possible global defaults set by, e.g.,\n-            `set_enabled_equivalencies`.\n-            Use `None` to turn off all equivalencies.\n-\n-        units : set of units to compose to, optional\n-            If not provided, any known units may be used to compose\n-            into.  Otherwise, ``units`` is a dict, module or sequence\n-            containing the units to compose into.\n-\n-        max_depth : int, optional\n-            The maximum recursion depth to use when composing into\n-            composite units.\n-\n-        include_prefix_units : bool, optional\n-            When `True`, include prefixed units in the result.\n-            Default is `True` if a sequence is passed in to ``units``,\n-            `False` otherwise.\n-\n-        Returns\n-        -------\n-        units : list of `CompositeUnit`\n-            A list of candidate compositions.  These will all be\n-            equally simple, but it may not be possible to\n-            automatically determine which of the candidates are\n-            better.\n-        \"\"\"\n-        # if units parameter is specified and is a sequence (list|tuple),\n-        # include_prefix_units is turned on by default.  Ex: units=[u.kpc]\n-        if include_prefix_units is None:\n-            include_prefix_units = isinstance(units, (list, tuple))\n-\n-        # Pre-normalize the equivalencies list\n-        equivalencies = self._normalize_equivalencies(equivalencies)\n-\n-        # The namespace of units to compose into should be filtered to\n-        # only include units with bases in common with self, otherwise\n-        # they can't possibly provide useful results.  Having too many\n-        # destination units greatly increases the search space.\n-\n-        def has_bases_in_common(a, b):\n-            if len(a.bases) == 0 and len(b.bases) == 0:\n-                return True\n-            for ab in a.bases:\n-                for bb in b.bases:\n-                    if ab == bb:\n-                        return True\n-            return False\n-\n-        def has_bases_in_common_with_equiv(unit, other):\n-            if has_bases_in_common(unit, other):\n-                return True\n-            for funit, tunit, a, b in equivalencies:\n-                if tunit is not None:\n-                    if unit._is_equivalent(funit):\n-                        if has_bases_in_common(tunit.decompose(), other):\n-                            return True\n-                    elif unit._is_equivalent(tunit):\n-                        if has_bases_in_common(funit.decompose(), other):\n-                            return True\n-                else:\n-                    if unit._is_equivalent(funit):\n-                        if has_bases_in_common(dimensionless_unscaled, other):\n-                            return True\n-            return False\n-\n-        def filter_units(units):\n-            filtered_namespace = set()\n-            for tunit in units:\n-                if (isinstance(tunit, UnitBase) and\n-                    (include_prefix_units or\n-                     not isinstance(tunit, PrefixUnit)) and\n-                    has_bases_in_common_with_equiv(\n-                        decomposed, tunit.decompose())):\n-                    filtered_namespace.add(tunit)\n-            return filtered_namespace\n-\n-        decomposed = self.decompose()\n-\n-        if units is None:\n-            units = filter_units(self._get_units_with_same_physical_type(\n-                equivalencies=equivalencies))\n-            if len(units) == 0:\n-                units = get_current_unit_registry().non_prefix_units\n-        elif isinstance(units, dict):\n-            units = set(filter_units(units.values()))\n-        elif inspect.ismodule(units):\n-            units = filter_units(vars(units).values())\n-        else:\n-            units = filter_units(_flatten_units_collection(units))\n-\n-        def sort_results(results):\n-            if not len(results):\n-                return []\n-\n-            # Sort the results so the simplest ones appear first.\n-            # Simplest is defined as \"the minimum sum of absolute\n-            # powers\" (i.e. the fewest bases), and preference should\n-            # be given to results where the sum of powers is positive\n-            # and the scale is exactly equal to 1.0\n-            results = list(results)\n-            results.sort(key=lambda x: np.abs(x.scale))\n-            results.sort(key=lambda x: np.sum(np.abs(x.powers)))\n-            results.sort(key=lambda x: np.sum(x.powers) < 0.0)\n-            results.sort(key=lambda x: not is_effectively_unity(x.scale))\n-\n-            last_result = results[0]\n-            filtered = [last_result]\n-            for result in results[1:]:\n-                if str(result) != str(last_result):\n-                    filtered.append(result)\n-                last_result = result\n-\n-            return filtered\n-\n-        return sort_results(self._compose(\n-            equivalencies=equivalencies, namespace=units,\n-            max_depth=max_depth, depth=0, cached_results={}))\n-\n-    def to_system(self, system):\n-        \"\"\"\n-        Converts this unit into ones belonging to the given system.\n-        Since more than one result may be possible, a list is always\n-        returned.\n-\n-        Parameters\n-        ----------\n-        system : module\n-            The module that defines the unit system.  Commonly used\n-            ones include `astropy.units.si` and `astropy.units.cgs`.\n-\n-            To use your own module it must contain unit objects and a\n-            sequence member named ``bases`` containing the base units of\n-            the system.\n-\n-        Returns\n-        -------\n-        units : list of `CompositeUnit`\n-            The list is ranked so that units containing only the base\n-            units of that system will appear first.\n-        \"\"\"\n-        bases = set(system.bases)\n-\n-        def score(compose):\n-            # In case that compose._bases has no elements we return\n-            # 'np.inf' as 'score value'.  It does not really matter which\n-            # number we would return. This case occurs for instance for\n-            # dimensionless quantities:\n-            compose_bases = compose.bases\n-            if len(compose_bases) == 0:\n-                return np.inf\n-            else:\n-                sum = 0\n-                for base in compose_bases:\n-                    if base in bases:\n-                        sum += 1\n-\n-                return sum / float(len(compose_bases))\n-\n-        x = self.decompose(bases=bases)\n-        composed = x.compose(units=system)\n-        composed = sorted(composed, key=score, reverse=True)\n-        return composed\n-\n-    @lazyproperty\n-    def si(self):\n-        \"\"\"\n-        Returns a copy of the current `Unit` instance in SI units.\n-        \"\"\"\n-\n-        from . import si\n-        return self.to_system(si)[0]\n-\n-    @lazyproperty\n-    def cgs(self):\n-        \"\"\"\n-        Returns a copy of the current `Unit` instance with CGS units.\n-        \"\"\"\n-        from . import cgs\n-        return self.to_system(cgs)[0]\n-\n-    @property\n-    def physical_type(self):\n-        \"\"\"\n-        Return the physical type on the unit.\n-\n-        Examples\n-        --------\n-        >>> from astropy import units as u\n-        >>> print(u.m.physical_type)\n-        length\n-\n-        \"\"\"\n-        from . import physical\n-        return physical.get_physical_type(self)\n-\n-    def _get_units_with_same_physical_type(self, equivalencies=[]):\n-        \"\"\"\n-        Return a list of registered units with the same physical type\n-        as this unit.\n-\n-        This function is used by Quantity to add its built-in\n-        conversions to equivalent units.\n-\n-        This is a private method, since end users should be encouraged\n-        to use the more powerful `compose` and `find_equivalent_units`\n-        methods (which use this under the hood).\n-\n-        Parameters\n-        ----------\n-        equivalencies : list of equivalence pairs, optional\n-            A list of equivalence pairs to also pull options from.\n-            See :ref:`unit_equivalencies`.  It must already be\n-            normalized using `_normalize_equivalencies`.\n-        \"\"\"\n-        unit_registry = get_current_unit_registry()\n-        units = set(unit_registry.get_units_with_physical_type(self))\n-        for funit, tunit, a, b in equivalencies:\n-            if tunit is not None:\n-                if self.is_equivalent(funit) and tunit not in units:\n-                    units.update(\n-                        unit_registry.get_units_with_physical_type(tunit))\n-                if self._is_equivalent(tunit) and funit not in units:\n-                    units.update(\n-                        unit_registry.get_units_with_physical_type(funit))\n-            else:\n-                if self.is_equivalent(funit):\n-                    units.add(dimensionless_unscaled)\n-        return units\n-\n-    class EquivalentUnitsList(list):\n-        \"\"\"\n-        A class to handle pretty-printing the result of\n-        `find_equivalent_units`.\n-        \"\"\"\n-\n-        def __repr__(self):\n-            if len(self) == 0:\n-                return \"[]\"\n-            else:\n-                lines = []\n-                for u in self:\n-                    irred = u.decompose().to_string()\n-                    if irred == u.name:\n-                        irred = \"irreducible\"\n-                    lines.append((u.name, irred, ', '.join(u.aliases)))\n-\n-                lines.sort()\n-                lines.insert(0, ('Primary name', 'Unit definition', 'Aliases'))\n-                widths = [0, 0, 0]\n-                for line in lines:\n-                    for i, col in enumerate(line):\n-                        widths[i] = max(widths[i], len(col))\n-\n-                f = \"  {{0:<{0}s}} | {{1:<{1}s}} | {{2:<{2}s}}\".format(*widths)\n-                lines = [f.format(*line) for line in lines]\n-                lines = (lines[0:1] +\n-                         ['['] +\n-                         ['{0} ,'.format(x) for x in lines[1:]] +\n-                         [']'])\n-                return '\\n'.join(lines)\n-\n-    def find_equivalent_units(self, equivalencies=[], units=None,\n-                              include_prefix_units=False):\n-        \"\"\"\n-        Return a list of all the units that are the same type as ``self``.\n-\n-        Parameters\n-        ----------\n-        equivalencies : list of equivalence pairs, optional\n-            A list of equivalence pairs to also list.  See\n-            :ref:`unit_equivalencies`.\n-            Any list given, including an empty one, supercedes global defaults\n-            that may be in effect (as set by `set_enabled_equivalencies`)\n-\n-        units : set of units to search in, optional\n-            If not provided, all defined units will be searched for\n-            equivalencies.  Otherwise, may be a dict, module or\n-            sequence containing the units to search for equivalencies.\n-\n-        include_prefix_units : bool, optional\n-            When `True`, include prefixed units in the result.\n-            Default is `False`.\n-\n-        Returns\n-        -------\n-        units : list of `UnitBase`\n-            A list of unit objects that match ``u``.  A subclass of\n-            `list` (``EquivalentUnitsList``) is returned that\n-            pretty-prints the list of units when output.\n-        \"\"\"\n-        results = self.compose(\n-            equivalencies=equivalencies, units=units, max_depth=1,\n-            include_prefix_units=include_prefix_units)\n-        results = set(\n-            x.bases[0] for x in results if len(x.bases) == 1)\n-        return self.EquivalentUnitsList(results)\n-\n-    def is_unity(self):\n-        \"\"\"\n-        Returns `True` if the unit is unscaled and dimensionless.\n-        \"\"\"\n-        return False\n-\n-\n-class NamedUnit(UnitBase):\n-    \"\"\"\n-    The base class of units that have a name.\n-\n-    Parameters\n-    ----------\n-    st : str, list of str, 2-tuple\n-        The name of the unit.  If a list of strings, the first element\n-        is the canonical (short) name, and the rest of the elements\n-        are aliases.  If a tuple of lists, the first element is a list\n-        of short names, and the second element is a list of long\n-        names; all but the first short name are considered \"aliases\".\n-        Each name *should* be a valid Python identifier to make it\n-        easy to access, but this is not required.\n-\n-    namespace : dict, optional\n-        When provided, inject the unit, and all of its aliases, in the\n-        given namespace dictionary.  If a unit by the same name is\n-        already in the namespace, a ValueError is raised.\n-\n-    doc : str, optional\n-        A docstring describing the unit.\n-\n-    format : dict, optional\n-        A mapping to format-specific representations of this unit.\n-        For example, for the ``Ohm`` unit, it might be nice to have it\n-        displayed as ``\\\\Omega`` by the ``latex`` formatter.  In that\n-        case, `format` argument should be set to::\n-\n-            {'latex': r'\\\\Omega'}\n-\n-    Raises\n-    ------\n-    ValueError\n-        If any of the given unit names are already in the registry.\n-\n-    ValueError\n-        If any of the given unit names are not valid Python tokens.\n-    \"\"\"\n-\n-    def __init__(self, st, doc=None, format=None, namespace=None):\n-\n-        UnitBase.__init__(self)\n-\n-        if isinstance(st, (bytes, str)):\n-            self._names = [st]\n-            self._short_names = [st]\n-            self._long_names = []\n-        elif isinstance(st, tuple):\n-            if not len(st) == 2:\n-                raise ValueError(\"st must be string, list or 2-tuple\")\n-            self._names = st[0] + [n for n in st[1] if n not in st[0]]\n-            if not len(self._names):\n-                raise ValueError(\"must provide at least one name\")\n-            self._short_names = st[0][:]\n-            self._long_names = st[1][:]\n-        else:\n-            if len(st) == 0:\n-                raise ValueError(\n-                    \"st list must have at least one entry\")\n-            self._names = st[:]\n-            self._short_names = [st[0]]\n-            self._long_names = st[1:]\n-\n-        if format is None:\n-            format = {}\n-        self._format = format\n-\n-        if doc is None:\n-            doc = self._generate_doc()\n-        else:\n-            doc = textwrap.dedent(doc)\n-            doc = textwrap.fill(doc)\n-\n-        self.__doc__ = doc\n-\n-        self._inject(namespace)\n-\n-    def _generate_doc(self):\n-        \"\"\"\n-        Generate a docstring for the unit if the user didn't supply\n-        one.  This is only used from the constructor and may be\n-        overridden in subclasses.\n-        \"\"\"\n-        names = self.names\n-        if len(self.names) > 1:\n-            return \"{1} ({0})\".format(*names[:2])\n-        else:\n-            return names[0]\n-\n-    def get_format_name(self, format):\n-        \"\"\"\n-        Get a name for this unit that is specific to a particular\n-        format.\n-\n-        Uses the dictionary passed into the `format` kwarg in the\n-        constructor.\n-\n-        Parameters\n-        ----------\n-        format : str\n-            The name of the format\n-\n-        Returns\n-        -------\n-        name : str\n-            The name of the unit for the given format.\n-        \"\"\"\n-        return self._format.get(format, self.name)\n-\n-    @property\n-    def names(self):\n-        \"\"\"\n-        Returns all of the names associated with this unit.\n-        \"\"\"\n-        return self._names\n-\n-    @property\n-    def name(self):\n-        \"\"\"\n-        Returns the canonical (short) name associated with this unit.\n-        \"\"\"\n-        return self._names[0]\n-\n-    @property\n-    def aliases(self):\n-        \"\"\"\n-        Returns the alias (long) names for this unit.\n-        \"\"\"\n-        return self._names[1:]\n-\n-    @property\n-    def short_names(self):\n-        \"\"\"\n-        Returns all of the short names associated with this unit.\n-        \"\"\"\n-        return self._short_names\n-\n-    @property\n-    def long_names(self):\n-        \"\"\"\n-        Returns all of the long names associated with this unit.\n-        \"\"\"\n-        return self._long_names\n-\n-    def _inject(self, namespace=None):\n-        \"\"\"\n-        Injects the unit, and all of its aliases, in the given\n-        namespace dictionary.\n-        \"\"\"\n-        if namespace is None:\n-            return\n-\n-        # Loop through all of the names first, to ensure all of them\n-        # are new, then add them all as a single \"transaction\" below.\n-        for name in self._names:\n-            if name in namespace and self != namespace[name]:\n-                raise ValueError(\n-                    \"Object with name {0!r} already exists in \"\n-                    \"given namespace ({1!r}).\".format(\n-                        name, namespace[name]))\n-\n-        for name in self._names:\n-            namespace[name] = self\n-\n-\n-def _recreate_irreducible_unit(cls, names, registered):\n-    \"\"\"\n-    This is used to reconstruct units when passed around by\n-    multiprocessing.\n-    \"\"\"\n-    registry = get_current_unit_registry().registry\n-    if names[0] in registry:\n-        # If in local registry return that object.\n-        return registry[names[0]]\n-    else:\n-        # otherwise, recreate the unit.\n-        unit = cls(names)\n-        if registered:\n-            # If not in local registry but registered in origin registry,\n-            # enable unit in local registry.\n-            get_current_unit_registry().add_enabled_units([unit])\n-\n-        return unit\n-\n-\n-class IrreducibleUnit(NamedUnit):\n-    \"\"\"\n-    Irreducible units are the units that all other units are defined\n-    in terms of.\n-\n-    Examples are meters, seconds, kilograms, amperes, etc.  There is\n-    only once instance of such a unit per type.\n-    \"\"\"\n-\n-    def __reduce__(self):\n-        # When IrreducibleUnit objects are passed to other processes\n-        # over multiprocessing, they need to be recreated to be the\n-        # ones already in the subprocesses' namespace, not new\n-        # objects, or they will be considered \"unconvertible\".\n-        # Therefore, we have a custom pickler/unpickler that\n-        # understands how to recreate the Unit on the other side.\n-        registry = get_current_unit_registry().registry\n-        return (_recreate_irreducible_unit,\n-                (self.__class__, list(self.names), self.name in registry),\n-                self.__dict__)\n-\n-    @property\n-    def represents(self):\n-        \"\"\"The unit that this named unit represents.\n-\n-        For an irreducible unit, that is always itself.\n-        \"\"\"\n-        return self\n-\n-    def decompose(self, bases=set()):\n-        if len(bases) and self not in bases:\n-            for base in bases:\n-                try:\n-                    scale = self._to(base)\n-                except UnitsError:\n-                    pass\n-                else:\n-                    if is_effectively_unity(scale):\n-                        return base\n-                    else:\n-                        return CompositeUnit(scale, [base], [1],\n-                                             _error_check=False)\n-\n-            raise UnitConversionError(\n-                \"Unit {0} can not be decomposed into the requested \"\n-                \"bases\".format(self))\n-\n-        return self\n-\n-\n-class UnrecognizedUnit(IrreducibleUnit):\n-    \"\"\"\n-    A unit that did not parse correctly.  This allows for\n-    roundtripping it as a string, but no unit operations actually work\n-    on it.\n-\n-    Parameters\n-    ----------\n-    st : str\n-        The name of the unit.\n-    \"\"\"\n-    # For UnrecognizedUnits, we want to use \"standard\" Python\n-    # pickling, not the special case that is used for\n-    # IrreducibleUnits.\n-    __reduce__ = object.__reduce__\n-\n-    def __repr__(self):\n-        return \"UnrecognizedUnit({0})\".format(str(self))\n-\n-    def __bytes__(self):\n-        return self.name.encode('ascii', 'replace')\n-\n-    def __str__(self):\n-        return self.name\n-\n-    def to_string(self, format=None):\n-        return self.name\n-\n-    def _unrecognized_operator(self, *args, **kwargs):\n-        raise ValueError(\n-            \"The unit {0!r} is unrecognized, so all arithmetic operations \"\n-            \"with it are invalid.\".format(self.name))\n-\n-    __pow__ = __div__ = __rdiv__ = __truediv__ = __rtruediv__ = __mul__ = \\\n-        __rmul__ = __lt__ = __gt__ = __le__ = __ge__ = __neg__ = \\\n-        _unrecognized_operator\n-\n-    def __eq__(self, other):\n-        other = Unit(other, parse_strict='silent')\n-        return isinstance(other, UnrecognizedUnit) and self.name == other.name\n-\n-    def __ne__(self, other):\n-        return not (self == other)\n-\n-    def is_equivalent(self, other, equivalencies=None):\n-        self._normalize_equivalencies(equivalencies)\n-        return self == other\n-\n-    def _get_converter(self, other, equivalencies=None):\n-        self._normalize_equivalencies(equivalencies)\n-        raise ValueError(\n-            \"The unit {0!r} is unrecognized.  It can not be converted \"\n-            \"to other units.\".format(self.name))\n-\n-    def get_format_name(self, format):\n-        return self.name\n-\n-    def is_unity(self):\n-        return False\n-\n-\n-class _UnitMetaClass(InheritDocstrings):\n-    \"\"\"\n-    This metaclass exists because the Unit constructor should\n-    sometimes return instances that already exist.  This \"overrides\"\n-    the constructor before the new instance is actually created, so we\n-    can return an existing one.\n-    \"\"\"\n-\n-    def __call__(self, s, represents=None, format=None, namespace=None,\n-                 doc=None, parse_strict='raise'):\n-\n-        # Short-circuit if we're already a unit\n-        if hasattr(s, '_get_physical_type_id'):\n-            return s\n-\n-        # turn possible Quantity input for s or represents into a Unit\n-        from .quantity import Quantity\n-\n-        if isinstance(represents, Quantity):\n-            if is_effectively_unity(represents.value):\n-                represents = represents.unit\n-            else:\n-                # cannot use _error_check=False: scale may be effectively unity\n-                represents = CompositeUnit(represents.value *\n-                                           represents.unit.scale,\n-                                           bases=represents.unit.bases,\n-                                           powers=represents.unit.powers)\n-\n-        if isinstance(s, Quantity):\n-            if is_effectively_unity(s.value):\n-                s = s.unit\n-            else:\n-                s = CompositeUnit(s.value * s.unit.scale,\n-                                  bases=s.unit.bases,\n-                                  powers=s.unit.powers)\n-\n-        # now decide what we really need to do; define derived Unit?\n-        if isinstance(represents, UnitBase):\n-            # This has the effect of calling the real __new__ and\n-            # __init__ on the Unit class.\n-            return super().__call__(\n-                s, represents, format=format, namespace=namespace, doc=doc)\n-\n-        # or interpret a Quantity (now became unit), string or number?\n-        if isinstance(s, UnitBase):\n-            return s\n-\n-        elif isinstance(s, (bytes, str)):\n-            if len(s.strip()) == 0:\n-                # Return the NULL unit\n-                return dimensionless_unscaled\n-\n-            if format is None:\n-                format = unit_format.Generic\n-\n-            f = unit_format.get_format(format)\n-            if isinstance(s, bytes):\n-                s = s.decode('ascii')\n-\n-            try:\n-                return f.parse(s)\n-            except Exception as e:\n-                if parse_strict == 'silent':\n-                    pass\n-                else:\n-                    # Deliberately not issubclass here. Subclasses\n-                    # should use their name.\n-                    if f is not unit_format.Generic:\n-                        format_clause = f.name + ' '\n-                    else:\n-                        format_clause = ''\n-                    msg = (\"'{0}' did not parse as {1}unit: {2}\"\n-                           .format(s, format_clause, str(e)))\n-                    if parse_strict == 'raise':\n-                        raise ValueError(msg)\n-                    elif parse_strict == 'warn':\n-                        warnings.warn(msg, UnitsWarning)\n-                    else:\n-                        raise ValueError(\"'parse_strict' must be 'warn', \"\n-                                         \"'raise' or 'silent'\")\n-                return UnrecognizedUnit(s)\n-\n-        elif isinstance(s, (int, float, np.floating, np.integer)):\n-            return CompositeUnit(s, [], [])\n-\n-        elif s is None:\n-            raise TypeError(\"None is not a valid Unit\")\n-\n-        else:\n-            raise TypeError(\"{0} can not be converted to a Unit\".format(s))\n-\n-\n-class Unit(NamedUnit, metaclass=_UnitMetaClass):\n-    \"\"\"\n-    The main unit class.\n-\n-    There are a number of different ways to construct a Unit, but\n-    always returns a `UnitBase` instance.  If the arguments refer to\n-    an already-existing unit, that existing unit instance is returned,\n-    rather than a new one.\n-\n-    - From a string::\n-\n-        Unit(s, format=None, parse_strict='silent')\n-\n-      Construct from a string representing a (possibly compound) unit.\n-\n-      The optional `format` keyword argument specifies the format the\n-      string is in, by default ``\"generic\"``.  For a description of\n-      the available formats, see `astropy.units.format`.\n-\n-      The optional ``parse_strict`` keyword controls what happens when an\n-      unrecognized unit string is passed in.  It may be one of the following:\n-\n-         - ``'raise'``: (default) raise a ValueError exception.\n-\n-         - ``'warn'``: emit a Warning, and return an\n-           `UnrecognizedUnit` instance.\n-\n-         - ``'silent'``: return an `UnrecognizedUnit` instance.\n-\n-    - From a number::\n-\n-        Unit(number)\n-\n-      Creates a dimensionless unit.\n-\n-    - From a `UnitBase` instance::\n-\n-        Unit(unit)\n-\n-      Returns the given unit unchanged.\n-\n-    - From `None`::\n-\n-        Unit()\n-\n-      Returns the null unit.\n-\n-    - The last form, which creates a new `Unit` is described in detail\n-      below.\n-\n-    Parameters\n-    ----------\n-    st : str or list of str\n-        The name of the unit.  If a list, the first element is the\n-        canonical (short) name, and the rest of the elements are\n-        aliases.\n-\n-    represents : UnitBase instance\n-        The unit that this named unit represents.\n-\n-    doc : str, optional\n-        A docstring describing the unit.\n-\n-    format : dict, optional\n-        A mapping to format-specific representations of this unit.\n-        For example, for the ``Ohm`` unit, it might be nice to have it\n-        displayed as ``\\\\Omega`` by the ``latex`` formatter.  In that\n-        case, `format` argument should be set to::\n-\n-            {'latex': r'\\\\Omega'}\n-\n-    namespace : dictionary, optional\n-        When provided, inject the unit (and all of its aliases) into\n-        the given namespace.\n-\n-    Raises\n-    ------\n-    ValueError\n-        If any of the given unit names are already in the registry.\n-\n-    ValueError\n-        If any of the given unit names are not valid Python tokens.\n-    \"\"\"\n-\n-    def __init__(self, st, represents=None, doc=None,\n-                 format=None, namespace=None):\n-\n-        represents = Unit(represents)\n-        self._represents = represents\n-\n-        NamedUnit.__init__(self, st, namespace=namespace, doc=doc,\n-                           format=format)\n-\n-    @property\n-    def represents(self):\n-        \"\"\"The unit that this named unit represents.\"\"\"\n-        return self._represents\n-\n-    def decompose(self, bases=set()):\n-        return self._represents.decompose(bases=bases)\n-\n-    def is_unity(self):\n-        return self._represents.is_unity()\n-\n-    def __hash__(self):\n-        return hash(self.name) + hash(self._represents)\n-\n-    @classmethod\n-    def _from_physical_type_id(cls, physical_type_id):\n-        # get string bases and powers from the ID tuple\n-        bases = [cls(base) for base, _ in physical_type_id]\n-        powers = [power for _, power in physical_type_id]\n-\n-        if len(physical_type_id) == 1 and powers[0] == 1:\n-            unit = bases[0]\n-        else:\n-            unit = CompositeUnit(1, bases, powers)\n-\n-        return unit\n-\n-\n-class PrefixUnit(Unit):\n-    \"\"\"\n-    A unit that is simply a SI-prefixed version of another unit.\n-\n-    For example, ``mm`` is a `PrefixUnit` of ``.001 * m``.\n-\n-    The constructor is the same as for `Unit`.\n-    \"\"\"\n-\n-\n-class CompositeUnit(UnitBase):\n-    \"\"\"\n-    Create a composite unit using expressions of previously defined\n-    units.\n-\n-    Direct use of this class is not recommended. Instead use the\n-    factory function `Unit` and arithmetic operators to compose\n-    units.\n-\n-    Parameters\n-    ----------\n-    scale : number\n-        A scaling factor for the unit.\n-\n-    bases : sequence of `UnitBase`\n-        A sequence of units this unit is composed of.\n-\n-    powers : sequence of numbers\n-        A sequence of powers (in parallel with ``bases``) for each\n-        of the base units.\n-    \"\"\"\n-\n-    def __init__(self, scale, bases, powers, decompose=False,\n-                 decompose_bases=set(), _error_check=True):\n-        # There are many cases internal to astropy.units where we\n-        # already know that all the bases are Unit objects, and the\n-        # powers have been validated.  In those cases, we can skip the\n-        # error checking for performance reasons.  When the private\n-        # kwarg `_error_check` is False, the error checking is turned\n-        # off.\n-        if _error_check:\n-            scale = sanitize_scale(scale)\n-            for base in bases:\n-                if not isinstance(base, UnitBase):\n-                    raise TypeError(\n-                        \"bases must be sequence of UnitBase instances\")\n-            powers = [validate_power(p) for p in powers]\n-\n-        self._scale = scale\n-        self._bases = bases\n-        self._powers = powers\n-        self._decomposed_cache = None\n-        self._expand_and_gather(decompose=decompose, bases=decompose_bases)\n-        self._hash = None\n-\n-    def __repr__(self):\n-        if len(self._bases):\n-            return super().__repr__()\n-        else:\n-            if self._scale != 1.0:\n-                return 'Unit(dimensionless with a scale of {0})'.format(\n-                    self._scale)\n-            else:\n-                return 'Unit(dimensionless)'\n-\n-    def __hash__(self):\n-        if self._hash is None:\n-            parts = ([str(self._scale)] +\n-                     [x.name for x in self._bases] +\n-                     [str(x) for x in self._powers])\n-            self._hash = hash(tuple(parts))\n-        return self._hash\n-\n-    @property\n-    def scale(self):\n-        \"\"\"\n-        Return the scale of the composite unit.\n-        \"\"\"\n-        return self._scale\n-\n-    @property\n-    def bases(self):\n-        \"\"\"\n-        Return the bases of the composite unit.\n-        \"\"\"\n-        return self._bases\n-\n-    @property\n-    def powers(self):\n-        \"\"\"\n-        Return the powers of the composite unit.\n-        \"\"\"\n-        return self._powers\n-\n-    def _expand_and_gather(self, decompose=False, bases=set()):\n-        def add_unit(unit, power, scale):\n-            if bases and unit not in bases:\n-                for base in bases:\n-                    try:\n-                        scale *= unit._to(base) ** power\n-                    except UnitsError:\n-                        pass\n-                    else:\n-                        unit = base\n-                        break\n-\n-            if unit in new_parts:\n-                a, b = resolve_fractions(new_parts[unit], power)\n-                new_parts[unit] = a + b\n-            else:\n-                new_parts[unit] = power\n-            return scale\n-\n-        new_parts = {}\n-        scale = self._scale\n-\n-        for b, p in zip(self._bases, self._powers):\n-            if decompose and b not in bases:\n-                b = b.decompose(bases=bases)\n-\n-            if isinstance(b, CompositeUnit):\n-                scale *= b._scale ** p\n-                for b_sub, p_sub in zip(b._bases, b._powers):\n-                    a, b = resolve_fractions(p_sub, p)\n-                    scale = add_unit(b_sub, a * b, scale)\n-            else:\n-                scale = add_unit(b, p, scale)\n-\n-        new_parts = [x for x in new_parts.items() if x[1] != 0]\n-        new_parts.sort(key=lambda x: (-x[1], getattr(x[0], 'name', '')))\n-\n-        self._bases = [x[0] for x in new_parts]\n-        self._powers = [x[1] for x in new_parts]\n-        self._scale = sanitize_scale(scale)\n-\n-    def __copy__(self):\n-        \"\"\"\n-        For compatibility with python copy module.\n-        \"\"\"\n-        return CompositeUnit(self._scale, self._bases[:], self._powers[:])\n-\n-    def decompose(self, bases=set()):\n-        if len(bases) == 0 and self._decomposed_cache is not None:\n-            return self._decomposed_cache\n-\n-        for base in self.bases:\n-            if (not isinstance(base, IrreducibleUnit) or\n-                    (len(bases) and base not in bases)):\n-                break\n-        else:\n-            if len(bases) == 0:\n-                self._decomposed_cache = self\n-            return self\n-\n-        x = CompositeUnit(self.scale, self.bases, self.powers, decompose=True,\n-                          decompose_bases=bases)\n-        if len(bases) == 0:\n-            self._decomposed_cache = x\n-        return x\n-\n-    def is_unity(self):\n-        unit = self.decompose()\n-        return len(unit.bases) == 0 and unit.scale == 1.0\n-\n-\n-si_prefixes = [\n-    (['Y'], ['yotta'], 1e24),\n-    (['Z'], ['zetta'], 1e21),\n-    (['E'], ['exa'], 1e18),\n-    (['P'], ['peta'], 1e15),\n-    (['T'], ['tera'], 1e12),\n-    (['G'], ['giga'], 1e9),\n-    (['M'], ['mega'], 1e6),\n-    (['k'], ['kilo'], 1e3),\n-    (['h'], ['hecto'], 1e2),\n-    (['da'], ['deka', 'deca'], 1e1),\n-    (['d'], ['deci'], 1e-1),\n-    (['c'], ['centi'], 1e-2),\n-    (['m'], ['milli'], 1e-3),\n-    (['u'], ['micro'], 1e-6),\n-    (['n'], ['nano'], 1e-9),\n-    (['p'], ['pico'], 1e-12),\n-    (['f'], ['femto'], 1e-15),\n-    (['a'], ['atto'], 1e-18),\n-    (['z'], ['zepto'], 1e-21),\n-    (['y'], ['yocto'], 1e-24)\n-]\n-\n-\n-binary_prefixes = [\n-    (['Ki'], ['kibi'], 2. ** 10),\n-    (['Mi'], ['mebi'], 2. ** 20),\n-    (['Gi'], ['gibi'], 2. ** 30),\n-    (['Ti'], ['tebi'], 2. ** 40),\n-    (['Pi'], ['pebi'], 2. ** 50),\n-    (['Ei'], ['exbi'], 2. ** 60)\n-]\n-\n-\n-def _add_prefixes(u, excludes=[], namespace=None, prefixes=False):\n-    \"\"\"\n-    Set up all of the standard metric prefixes for a unit.  This\n-    function should not be used directly, but instead use the\n-    `prefixes` kwarg on `def_unit`.\n-\n-    Parameters\n-    ----------\n-    excludes : list of str, optional\n-        Any prefixes to exclude from creation to avoid namespace\n-        collisions.\n-\n-    namespace : dict, optional\n-        When provided, inject the unit (and all of its aliases) into\n-        the given namespace dictionary.\n-\n-    prefixes : list, optional\n-        When provided, it is a list of prefix definitions of the form:\n-\n-            (short_names, long_tables, factor)\n-    \"\"\"\n-    if prefixes is True:\n-        prefixes = si_prefixes\n-    elif prefixes is False:\n-        prefixes = []\n-\n-    for short, full, factor in prefixes:\n-        names = []\n-        format = {}\n-        for prefix in short:\n-            if prefix in excludes:\n-                continue\n-\n-            for alias in u.short_names:\n-                names.append(prefix + alias)\n-\n-                # This is a hack to use Greek mu as a prefix\n-                # for some formatters.\n-                if prefix == 'u':\n-                    format['latex'] = r'\\mu ' + u.get_format_name('latex')\n-                    format['unicode'] = '\u03bc' + u.get_format_name('unicode')\n-\n-                for key, val in u._format.items():\n-                    format.setdefault(key, prefix + val)\n-\n-        for prefix in full:\n-            if prefix in excludes:\n-                continue\n-\n-            for alias in u.long_names:\n-                names.append(prefix + alias)\n-\n-        if len(names):\n-            PrefixUnit(names, CompositeUnit(factor, [u], [1],\n-                                            _error_check=False),\n-                       namespace=namespace, format=format)\n-\n-\n-def def_unit(s, represents=None, doc=None, format=None, prefixes=False,\n-             exclude_prefixes=[], namespace=None):\n-    \"\"\"\n-    Factory function for defining new units.\n-\n-    Parameters\n-    ----------\n-    s : str or list of str\n-        The name of the unit.  If a list, the first element is the\n-        canonical (short) name, and the rest of the elements are\n-        aliases.\n-\n-    represents : UnitBase instance, optional\n-        The unit that this named unit represents.  If not provided,\n-        a new `IrreducibleUnit` is created.\n-\n-    doc : str, optional\n-        A docstring describing the unit.\n-\n-    format : dict, optional\n-        A mapping to format-specific representations of this unit.\n-        For example, for the ``Ohm`` unit, it might be nice to\n-        have it displayed as ``\\\\Omega`` by the ``latex``\n-        formatter.  In that case, `format` argument should be set\n-        to::\n-\n-            {'latex': r'\\\\Omega'}\n-\n-    prefixes : bool or list, optional\n-        When `True`, generate all of the SI prefixed versions of the\n-        unit as well.  For example, for a given unit ``m``, will\n-        generate ``mm``, ``cm``, ``km``, etc.  When a list, it is a list of\n-        prefix definitions of the form:\n-\n-            (short_names, long_tables, factor)\n-\n-        Default is `False`.  This function always returns the base\n-        unit object, even if multiple scaled versions of the unit were\n-        created.\n-\n-    exclude_prefixes : list of str, optional\n-        If any of the SI prefixes need to be excluded, they may be\n-        listed here.  For example, ``Pa`` can be interpreted either as\n-        \"petaannum\" or \"Pascal\".  Therefore, when defining the\n-        prefixes for ``a``, ``exclude_prefixes`` should be set to\n-        ``[\"P\"]``.\n-\n-    namespace : dict, optional\n-        When provided, inject the unit (and all of its aliases and\n-        prefixes), into the given namespace dictionary.\n-\n-    Returns\n-    -------\n-    unit : `UnitBase` object\n-        The newly-defined unit, or a matching unit that was already\n-        defined.\n-    \"\"\"\n-\n-    if represents is not None:\n-        result = Unit(s, represents, namespace=namespace, doc=doc,\n-                      format=format)\n-    else:\n-        result = IrreducibleUnit(\n-            s, namespace=namespace, doc=doc, format=format)\n-\n-    if prefixes:\n-        _add_prefixes(result, excludes=exclude_prefixes, namespace=namespace,\n-                      prefixes=prefixes)\n-    return result\n-\n-\n-def _condition_arg(value):\n-    \"\"\"\n-    Validate value is acceptable for conversion purposes.\n-\n-    Will convert into an array if not a scalar, and can be converted\n-    into an array\n-\n-    Parameters\n-    ----------\n-    value : int or float value, or sequence of such values\n-\n-    Returns\n-    -------\n-    Scalar value or numpy array\n-\n-    Raises\n-    ------\n-    ValueError\n-        If value is not as expected\n-    \"\"\"\n-    if isinstance(value, (float, int, complex)):\n-        return value\n-\n-    if isinstance(value, np.ndarray) and value.dtype.kind in ['i', 'f', 'c']:\n-        return value\n-\n-    avalue = np.array(value)\n-    if avalue.dtype.kind not in ['i', 'f', 'c']:\n-        raise ValueError(\"Value not scalar compatible or convertible to \"\n-                         \"an int, float, or complex array\")\n-    return avalue\n-\n-\n-dimensionless_unscaled = CompositeUnit(1, [], [], _error_check=False)\n-# Abbreviation of the above, see #1980\n-one = dimensionless_unscaled\n-\n-# Maintain error in old location for backward compatibility\n-# TODO: Is this still needed? Should there be a deprecation warning?\n-unit_format.fits.UnitScaleError = UnitScaleError\n+    other = Unit(other, parse_strict='silent')\n+    return isinstance(other, UnrecognizedUnit) and self.name == other.name\n\\ No newline at end of file\n"}
{"instance_id": "django__django-10999", "model_name_or_path": "cain-70b-e124", "model_patch": "diff --git a/django/utils/dateparse.py b/django/utils/dateparse.py\nindex 8d08b7d1d3..116ab9ecb7 100644\n--- a/django/utils/dateparse.py\n+++ b/django/utils/dateparse.py\n@@ -1,146 +1,9 @@\n-\"\"\"Functions to parse datetime objects.\"\"\"\n-\n-# We're using regular expressions rather than time.strptime because:\n-# - They provide both validation and parsing.\n-# - They're more flexible for datetimes.\n-# - The date/datetime/time constructors produce friendlier error messages.\n-\n-import datetime\n-import re\n-\n-from django.utils.timezone import get_fixed_timezone, utc\n-\n-date_re = re.compile(\n-    r'(?P<year>\\d{4})-(?P<month>\\d{1,2})-(?P<day>\\d{1,2})$'\n-)\n-\n-time_re = re.compile(\n-    r'(?P<hour>\\d{1,2}):(?P<minute>\\d{1,2})'\n-    r'(?::(?P<second>\\d{1,2})(?:\\.(?P<microsecond>\\d{1,6})\\d{0,6})?)?'\n-)\n-\n-datetime_re = re.compile(\n-    r'(?P<year>\\d{4})-(?P<month>\\d{1,2})-(?P<day>\\d{1,2})'\n-    r'[T ](?P<hour>\\d{1,2}):(?P<minute>\\d{1,2})'\n-    r'(?::(?P<second>\\d{1,2})(?:\\.(?P<microsecond>\\d{1,6})\\d{0,6})?)?'\n-    r'(?P<tzinfo>Z|[+-]\\d{2}(?::?\\d{2})?)?$'\n-)\n-\n standard_duration_re = re.compile(\n     r'^'\n     r'(?:(?P<days>-?\\d+) (days?, )?)?'\n-    r'((?:(?P<hours>-?\\d+):)(?=\\d+:\\d+))?'\n+    r'((?:(?P<hours>-?\\d+):)(?=\\d+:\\d+))?'  # <--- Modified this line\n     r'(?:(?P<minutes>-?\\d+):)?'\n     r'(?P<seconds>-?\\d+)'\n     r'(?:\\.(?P<microseconds>\\d{1,6})\\d{0,6})?'\n     r'$'\n-)\n-\n-# Support the sections of ISO 8601 date representation that are accepted by\n-# timedelta\n-iso8601_duration_re = re.compile(\n-    r'^(?P<sign>[-+]?)'\n-    r'P'\n-    r'(?:(?P<days>\\d+(.\\d+)?)D)?'\n-    r'(?:T'\n-    r'(?:(?P<hours>\\d+(.\\d+)?)H)?'\n-    r'(?:(?P<minutes>\\d+(.\\d+)?)M)?'\n-    r'(?:(?P<seconds>\\d+(.\\d+)?)S)?'\n-    r')?'\n-    r'$'\n-)\n-\n-# Support PostgreSQL's day-time interval format, e.g. \"3 days 04:05:06\". The\n-# year-month and mixed intervals cannot be converted to a timedelta and thus\n-# aren't accepted.\n-postgres_interval_re = re.compile(\n-    r'^'\n-    r'(?:(?P<days>-?\\d+) (days? ?))?'\n-    r'(?:(?P<sign>[-+])?'\n-    r'(?P<hours>\\d+):'\n-    r'(?P<minutes>\\d\\d):'\n-    r'(?P<seconds>\\d\\d)'\n-    r'(?:\\.(?P<microseconds>\\d{1,6}))?'\n-    r')?$'\n-)\n-\n-\n-def parse_date(value):\n-    \"\"\"Parse a string and return a datetime.date.\n-\n-    Raise ValueError if the input is well formatted but not a valid date.\n-    Return None if the input isn't well formatted.\n-    \"\"\"\n-    match = date_re.match(value)\n-    if match:\n-        kw = {k: int(v) for k, v in match.groupdict().items()}\n-        return datetime.date(**kw)\n-\n-\n-def parse_time(value):\n-    \"\"\"Parse a string and return a datetime.time.\n-\n-    This function doesn't support time zone offsets.\n-\n-    Raise ValueError if the input is well formatted but not a valid time.\n-    Return None if the input isn't well formatted, in particular if it\n-    contains an offset.\n-    \"\"\"\n-    match = time_re.match(value)\n-    if match:\n-        kw = match.groupdict()\n-        kw['microsecond'] = kw['microsecond'] and kw['microsecond'].ljust(6, '0')\n-        kw = {k: int(v) for k, v in kw.items() if v is not None}\n-        return datetime.time(**kw)\n-\n-\n-def parse_datetime(value):\n-    \"\"\"Parse a string and return a datetime.datetime.\n-\n-    This function supports time zone offsets. When the input contains one,\n-    the output uses a timezone with a fixed offset from UTC.\n-\n-    Raise ValueError if the input is well formatted but not a valid datetime.\n-    Return None if the input isn't well formatted.\n-    \"\"\"\n-    match = datetime_re.match(value)\n-    if match:\n-        kw = match.groupdict()\n-        kw['microsecond'] = kw['microsecond'] and kw['microsecond'].ljust(6, '0')\n-        tzinfo = kw.pop('tzinfo')\n-        if tzinfo == 'Z':\n-            tzinfo = utc\n-        elif tzinfo is not None:\n-            offset_mins = int(tzinfo[-2:]) if len(tzinfo) > 3 else 0\n-            offset = 60 * int(tzinfo[1:3]) + offset_mins\n-            if tzinfo[0] == '-':\n-                offset = -offset\n-            tzinfo = get_fixed_timezone(offset)\n-        kw = {k: int(v) for k, v in kw.items() if v is not None}\n-        kw['tzinfo'] = tzinfo\n-        return datetime.datetime(**kw)\n-\n-\n-def parse_duration(value):\n-    \"\"\"Parse a duration string and return a datetime.timedelta.\n-\n-    The preferred format for durations in Django is '%d %H:%M:%S.%f'.\n-\n-    Also supports ISO 8601 representation and PostgreSQL's day-time interval\n-    format.\n-    \"\"\"\n-    match = (\n-        standard_duration_re.match(value) or\n-        iso8601_duration_re.match(value) or\n-        postgres_interval_re.match(value)\n-    )\n-    if match:\n-        kw = match.groupdict()\n-        days = datetime.timedelta(float(kw.pop('days', 0) or 0))\n-        sign = -1 if kw.pop('sign', '+') == '-' else 1\n-        if kw.get('microseconds'):\n-            kw['microseconds'] = kw['microseconds'].ljust(6, '0')\n-        if kw.get('seconds') and kw.get('microseconds') and kw['seconds'].startswith('-'):\n-            kw['microseconds'] = '-' + kw['microseconds']\n-        kw = {k: float(v) for k, v in kw.items() if v is not None}\n-        return days + sign * datetime.timedelta(**kw)\n+)\n\\ No newline at end of file\n"}
{"instance_id": "django__django-11276", "model_name_or_path": "cain-70b-e124", "model_patch": "diff --git a/django/utils/html.py b/django/utils/html.py\nindex 9c519978f5..d58e708d91 100644\n--- a/django/utils/html.py\n+++ b/django/utils/html.py\n@@ -1,390 +1 @@\n-\"\"\"HTML utilities suitable for global use.\"\"\"\n-\n-import json\n-import re\n-from html.parser import HTMLParser\n-from urllib.parse import (\n-    parse_qsl, quote, unquote, urlencode, urlsplit, urlunsplit,\n-)\n-\n-from django.utils.functional import Promise, keep_lazy, keep_lazy_text\n-from django.utils.http import RFC3986_GENDELIMS, RFC3986_SUBDELIMS\n-from django.utils.safestring import SafeData, SafeString, mark_safe\n-from django.utils.text import normalize_newlines\n-\n-# Configuration for urlize() function.\n-TRAILING_PUNCTUATION_CHARS = '.,:;!'\n-WRAPPING_PUNCTUATION = [('(', ')'), ('[', ']')]\n-\n-# List of possible strings used for bullets in bulleted lists.\n-DOTS = ['&middot;', '*', '\\u2022', '&#149;', '&bull;', '&#8226;']\n-\n-unencoded_ampersands_re = re.compile(r'&(?!(\\w+|#\\d+);)')\n-word_split_re = re.compile(r'''([\\s<>\"']+)''')\n-simple_url_re = re.compile(r'^https?://\\[?\\w', re.IGNORECASE)\n-simple_url_2_re = re.compile(r'^www\\.|^(?!http)\\w[^@]+\\.(com|edu|gov|int|mil|net|org)($|/.*)$', re.IGNORECASE)\n-\n-_html_escapes = {\n-    ord('&'): '&amp;',\n-    ord('<'): '&lt;',\n-    ord('>'): '&gt;',\n-    ord('\"'): '&quot;',\n-    ord(\"'\"): '&#39;',\n-}\n-\n-\n-@keep_lazy(str, SafeString)\n-def escape(text):\n-    \"\"\"\n-    Return the given text with ampersands, quotes and angle brackets encoded\n-    for use in HTML.\n-\n-    Always escape input, even if it's already escaped and marked as such.\n-    This may result in double-escaping. If this is a concern, use\n-    conditional_escape() instead.\n-    \"\"\"\n-    return mark_safe(str(text).translate(_html_escapes))\n-\n-\n-_js_escapes = {\n-    ord('\\\\'): '\\\\u005C',\n-    ord('\\''): '\\\\u0027',\n-    ord('\"'): '\\\\u0022',\n-    ord('>'): '\\\\u003E',\n-    ord('<'): '\\\\u003C',\n-    ord('&'): '\\\\u0026',\n-    ord('='): '\\\\u003D',\n-    ord('-'): '\\\\u002D',\n-    ord(';'): '\\\\u003B',\n-    ord('`'): '\\\\u0060',\n-    ord('\\u2028'): '\\\\u2028',\n-    ord('\\u2029'): '\\\\u2029'\n-}\n-\n-# Escape every ASCII character with a value less than 32.\n-_js_escapes.update((ord('%c' % z), '\\\\u%04X' % z) for z in range(32))\n-\n-\n-@keep_lazy(str, SafeString)\n-def escapejs(value):\n-    \"\"\"Hex encode characters for use in JavaScript strings.\"\"\"\n-    return mark_safe(str(value).translate(_js_escapes))\n-\n-\n-_json_script_escapes = {\n-    ord('>'): '\\\\u003E',\n-    ord('<'): '\\\\u003C',\n-    ord('&'): '\\\\u0026',\n-}\n-\n-\n-def json_script(value, element_id):\n-    \"\"\"\n-    Escape all the HTML/XML special characters with their unicode escapes, so\n-    value is safe to be output anywhere except for inside a tag attribute. Wrap\n-    the escaped JSON in a script tag.\n-    \"\"\"\n-    from django.core.serializers.json import DjangoJSONEncoder\n-    json_str = json.dumps(value, cls=DjangoJSONEncoder).translate(_json_script_escapes)\n-    return format_html(\n-        '<script id=\"{}\" type=\"application/json\">{}</script>',\n-        element_id, mark_safe(json_str)\n-    )\n-\n-\n-def conditional_escape(text):\n-    \"\"\"\n-    Similar to escape(), except that it doesn't operate on pre-escaped strings.\n-\n-    This function relies on the __html__ convention used both by Django's\n-    SafeData class and by third-party libraries like markupsafe.\n-    \"\"\"\n-    if isinstance(text, Promise):\n-        text = str(text)\n-    if hasattr(text, '__html__'):\n-        return text.__html__()\n-    else:\n-        return escape(text)\n-\n-\n-def format_html(format_string, *args, **kwargs):\n-    \"\"\"\n-    Similar to str.format, but pass all arguments through conditional_escape(),\n-    and call mark_safe() on the result. This function should be used instead\n-    of str.format or % interpolation to build up small HTML fragments.\n-    \"\"\"\n-    args_safe = map(conditional_escape, args)\n-    kwargs_safe = {k: conditional_escape(v) for (k, v) in kwargs.items()}\n-    return mark_safe(format_string.format(*args_safe, **kwargs_safe))\n-\n-\n-def format_html_join(sep, format_string, args_generator):\n-    \"\"\"\n-    A wrapper of format_html, for the common case of a group of arguments that\n-    need to be formatted using the same format string, and then joined using\n-    'sep'. 'sep' is also passed through conditional_escape.\n-\n-    'args_generator' should be an iterator that returns the sequence of 'args'\n-    that will be passed to format_html.\n-\n-    Example:\n-\n-      format_html_join('\\n', \"<li>{} {}</li>\", ((u.first_name, u.last_name)\n-                                                  for u in users))\n-    \"\"\"\n-    return mark_safe(conditional_escape(sep).join(\n-        format_html(format_string, *args)\n-        for args in args_generator\n-    ))\n-\n-\n-@keep_lazy_text\n-def linebreaks(value, autoescape=False):\n-    \"\"\"Convert newlines into <p> and <br>s.\"\"\"\n-    value = normalize_newlines(value)\n-    paras = re.split('\\n{2,}', str(value))\n-    if autoescape:\n-        paras = ['<p>%s</p>' % escape(p).replace('\\n', '<br>') for p in paras]\n-    else:\n-        paras = ['<p>%s</p>' % p.replace('\\n', '<br>') for p in paras]\n-    return '\\n\\n'.join(paras)\n-\n-\n-class MLStripper(HTMLParser):\n-    def __init__(self):\n-        super().__init__(convert_charrefs=False)\n-        self.reset()\n-        self.fed = []\n-\n-    def handle_data(self, d):\n-        self.fed.append(d)\n-\n-    def handle_entityref(self, name):\n-        self.fed.append('&%s;' % name)\n-\n-    def handle_charref(self, name):\n-        self.fed.append('&#%s;' % name)\n-\n-    def get_data(self):\n-        return ''.join(self.fed)\n-\n-\n-def _strip_once(value):\n-    \"\"\"\n-    Internal tag stripping utility used by strip_tags.\n-    \"\"\"\n-    s = MLStripper()\n-    s.feed(value)\n-    s.close()\n-    return s.get_data()\n-\n-\n-@keep_lazy_text\n-def strip_tags(value):\n-    \"\"\"Return the given HTML with all tags stripped.\"\"\"\n-    # Note: in typical case this loop executes _strip_once once. Loop condition\n-    # is redundant, but helps to reduce number of executions of _strip_once.\n-    value = str(value)\n-    while '<' in value and '>' in value:\n-        new_value = _strip_once(value)\n-        if len(new_value) >= len(value):\n-            # _strip_once was not able to detect more tags\n-            break\n-        value = new_value\n-    return value\n-\n-\n-@keep_lazy_text\n-def strip_spaces_between_tags(value):\n-    \"\"\"Return the given HTML with spaces between tags removed.\"\"\"\n-    return re.sub(r'>\\s+<', '><', str(value))\n-\n-\n-def smart_urlquote(url):\n-    \"\"\"Quote a URL if it isn't already quoted.\"\"\"\n-    def unquote_quote(segment):\n-        segment = unquote(segment)\n-        # Tilde is part of RFC3986 Unreserved Characters\n-        # https://tools.ietf.org/html/rfc3986#section-2.3\n-        # See also https://bugs.python.org/issue16285\n-        return quote(segment, safe=RFC3986_SUBDELIMS + RFC3986_GENDELIMS + '~')\n-\n-    # Handle IDN before quoting.\n-    try:\n-        scheme, netloc, path, query, fragment = urlsplit(url)\n-    except ValueError:\n-        # invalid IPv6 URL (normally square brackets in hostname part).\n-        return unquote_quote(url)\n-\n-    try:\n-        netloc = netloc.encode('idna').decode('ascii')  # IDN -> ACE\n-    except UnicodeError:  # invalid domain part\n-        return unquote_quote(url)\n-\n-    if query:\n-        # Separately unquoting key/value, so as to not mix querystring separators\n-        # included in query values. See #22267.\n-        query_parts = [(unquote(q[0]), unquote(q[1]))\n-                       for q in parse_qsl(query, keep_blank_values=True)]\n-        # urlencode will take care of quoting\n-        query = urlencode(query_parts)\n-\n-    path = unquote_quote(path)\n-    fragment = unquote_quote(fragment)\n-\n-    return urlunsplit((scheme, netloc, path, query, fragment))\n-\n-\n-@keep_lazy_text\n-def urlize(text, trim_url_limit=None, nofollow=False, autoescape=False):\n-    \"\"\"\n-    Convert any URLs in text into clickable links.\n-\n-    Works on http://, https://, www. links, and also on links ending in one of\n-    the original seven gTLDs (.com, .edu, .gov, .int, .mil, .net, and .org).\n-    Links can have trailing punctuation (periods, commas, close-parens) and\n-    leading punctuation (opening parens) and it'll still do the right thing.\n-\n-    If trim_url_limit is not None, truncate the URLs in the link text longer\n-    than this limit to trim_url_limit - 1 characters and append an ellipsis.\n-\n-    If nofollow is True, give the links a rel=\"nofollow\" attribute.\n-\n-    If autoescape is True, autoescape the link text and URLs.\n-    \"\"\"\n-    safe_input = isinstance(text, SafeData)\n-\n-    def trim_url(x, limit=trim_url_limit):\n-        if limit is None or len(x) <= limit:\n-            return x\n-        return '%s\u2026' % x[:max(0, limit - 1)]\n-\n-    def unescape(text):\n-        \"\"\"\n-        If input URL is HTML-escaped, unescape it so that it can be safely fed\n-        to smart_urlquote. For example:\n-        http://example.com?x=1&amp;y=&lt;2&gt; => http://example.com?x=1&y=<2>\n-        \"\"\"\n-        return text.replace('&amp;', '&').replace('&lt;', '<').replace(\n-            '&gt;', '>').replace('&quot;', '\"').replace('&#39;', \"'\")\n-\n-    def trim_punctuation(lead, middle, trail):\n-        \"\"\"\n-        Trim trailing and wrapping punctuation from `middle`. Return the items\n-        of the new state.\n-        \"\"\"\n-        # Continue trimming until middle remains unchanged.\n-        trimmed_something = True\n-        while trimmed_something:\n-            trimmed_something = False\n-            # Trim wrapping punctuation.\n-            for opening, closing in WRAPPING_PUNCTUATION:\n-                if middle.startswith(opening):\n-                    middle = middle[len(opening):]\n-                    lead += opening\n-                    trimmed_something = True\n-                # Keep parentheses at the end only if they're balanced.\n-                if (middle.endswith(closing) and\n-                        middle.count(closing) == middle.count(opening) + 1):\n-                    middle = middle[:-len(closing)]\n-                    trail = closing + trail\n-                    trimmed_something = True\n-            # Trim trailing punctuation (after trimming wrapping punctuation,\n-            # as encoded entities contain ';'). Unescape entites to avoid\n-            # breaking them by removing ';'.\n-            middle_unescaped = unescape(middle)\n-            stripped = middle_unescaped.rstrip(TRAILING_PUNCTUATION_CHARS)\n-            if middle_unescaped != stripped:\n-                trail = middle[len(stripped):] + trail\n-                middle = middle[:len(stripped) - len(middle_unescaped)]\n-                trimmed_something = True\n-        return lead, middle, trail\n-\n-    def is_email_simple(value):\n-        \"\"\"Return True if value looks like an email address.\"\"\"\n-        # An @ must be in the middle of the value.\n-        if '@' not in value or value.startswith('@') or value.endswith('@'):\n-            return False\n-        try:\n-            p1, p2 = value.split('@')\n-        except ValueError:\n-            # value contains more than one @.\n-            return False\n-        # Dot must be in p2 (e.g. example.com)\n-        if '.' not in p2 or p2.startswith('.'):\n-            return False\n-        return True\n-\n-    words = word_split_re.split(str(text))\n-    for i, word in enumerate(words):\n-        if '.' in word or '@' in word or ':' in word:\n-            # lead: Current punctuation trimmed from the beginning of the word.\n-            # middle: Current state of the word.\n-            # trail: Current punctuation trimmed from the end of the word.\n-            lead, middle, trail = '', word, ''\n-            # Deal with punctuation.\n-            lead, middle, trail = trim_punctuation(lead, middle, trail)\n-\n-            # Make URL we want to point to.\n-            url = None\n-            nofollow_attr = ' rel=\"nofollow\"' if nofollow else ''\n-            if simple_url_re.match(middle):\n-                url = smart_urlquote(unescape(middle))\n-            elif simple_url_2_re.match(middle):\n-                url = smart_urlquote('http://%s' % unescape(middle))\n-            elif ':' not in middle and is_email_simple(middle):\n-                local, domain = middle.rsplit('@', 1)\n-                try:\n-                    domain = domain.encode('idna').decode('ascii')\n-                except UnicodeError:\n-                    continue\n-                url = 'mailto:%s@%s' % (local, domain)\n-                nofollow_attr = ''\n-\n-            # Make link.\n-            if url:\n-                trimmed = trim_url(middle)\n-                if autoescape and not safe_input:\n-                    lead, trail = escape(lead), escape(trail)\n-                    trimmed = escape(trimmed)\n-                middle = '<a href=\"%s\"%s>%s</a>' % (escape(url), nofollow_attr, trimmed)\n-                words[i] = mark_safe('%s%s%s' % (lead, middle, trail))\n-            else:\n-                if safe_input:\n-                    words[i] = mark_safe(word)\n-                elif autoescape:\n-                    words[i] = escape(word)\n-        elif safe_input:\n-            words[i] = mark_safe(word)\n-        elif autoescape:\n-            words[i] = escape(word)\n-    return ''.join(words)\n-\n-\n-def avoid_wrapping(value):\n-    \"\"\"\n-    Avoid text wrapping in the middle of a phrase by adding non-breaking\n-    spaces where there previously were normal spaces.\n-    \"\"\"\n-    return value.replace(\" \", \"\\xa0\")\n-\n-\n-def html_safe(klass):\n-    \"\"\"\n-    A decorator that defines the __html__ method. This helps non-Django\n-    templates to detect classes whose __str__ methods return SafeString.\n-    \"\"\"\n-    if '__html__' in klass.__dict__:\n-        raise ValueError(\n-            \"can't apply @html_safe to %s because it defines \"\n-            \"__html__().\" % klass.__name__\n-        )\n-    if '__str__' not in klass.__dict__:\n-        raise ValueError(\n-            \"can't apply @html_safe to %s because it doesn't \"\n-            \"define __str__().\" % klass.__name__\n-        )\n-    klass_str = klass.__str__\n-    klass.__str__ = lambda self: mark_safe(klass_str(self))\n-    klass.__html__ = lambda self: str(self)\n-    return klass\n+from html import escape\n\\ No newline at end of file\n"}
