prompt: We are currently solving the following issue within our repository. Here is the issue text:
  --- BEGIN ISSUE ---
  QubitOrder.explicit fails when given an iterator
  Also affects `QubitOrder.as_qubit_order()`.  I believe the issue is on line 77 of cirq/ops/qubit_order.py.
  
  Example:
  ```
  cirq.QubitOrder.as_qubit_order(reversed(cirq.LineQubit.range(5))).order_for(
      (cirq.LineQubit(3),))
  ```
  
  The example raises `ValueError: Unexpected extra qubits: {cirq.LineQubit(3)}.` because `reversed()` is an iterator and QubitOrder tried to iterate it twice.
  
  --- END ISSUE ---
  
  Below are some code segments, each from a relevant file. One or more of these files may contain bugs.
  --- BEGIN FILES ---
  Path: `cirq/ops/qubit_order.py`
  Content:
  ```
  1 # Copyright 2018 The Cirq Developers
  2 #
  3 # Licensed under the Apache License, Version 2.0 (the "License");
  4 # you may not use this file except in compliance with the License.
  5 # You may obtain a copy of the License at
  6 #
  7 #     https://www.apache.org/licenses/LICENSE-2.0
  8 #
  9 # Unless required by applicable law or agreed to in writing, software
  10 # distributed under the License is distributed on an "AS IS" BASIS,
  11 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12 # See the License for the specific language governing permissions and
  13 # limitations under the License.
  14 
  15 
  16 from typing import (
  17     Any,
  18     Callable,
  19     Iterable,
  20     Optional,
  21     Tuple,
  22     TypeVar,
  23     TYPE_CHECKING,
  24 )
  25 
  26 import collections
  27 
  28 from cirq.ops import raw_types
  29 
  30 if TYPE_CHECKING:
  31     # pylint: disable=unused-import
  32     from cirq.ops import qubit_order_or_list
  33 
  34 
  35 TInternalQubit = TypeVar('TInternalQubit')
  36 TExternalQubit = TypeVar('TExternalQubit')
  37 
  38 
  39 class QubitOrder:
  40     """Defines the kronecker product order of qubits."""
  41 
  42     def __init__(self, explicit_func: Callable[[Iterable[raw_types.Qid]],
  43                                                Tuple[raw_types.Qid, ...]]
  44                  ) -> None:
  45         self._explicit_func = explicit_func
  46 
  47     DEFAULT = None  # type: QubitOrder
  48     """A basis that orders qubits in the same way that calling `sorted` does.
  49 
  50     Specifically, qubits are ordered first by their type name and then by
  51     whatever comparison value qubits of a given type provide (e.g. for LineQubit
  52     it is the x coordinate of the qubit).
  53     """
  54 
  55     @staticmethod
  56     def explicit(fixed_qubits: Iterable[raw_types.Qid],
  57                  fallback: Optional['QubitOrder']=None) -> 'QubitOrder':
  58         """A basis that contains exactly the given qubits in the given order.
  59 
  60         Args:
  61             fixed_qubits: The qubits in basis order.
  62             fallback: A fallback order to use for extra qubits not in the
  63                 fixed_qubits list. Extra qubits will always come after the
  64                 fixed_qubits, but will be ordered based on the fallback. If no
  65                 fallback is specified, a ValueError is raised when extra qubits
  66                 are specified.
  67 
  68         Returns:
  69             A Basis instance that forces the given qubits in the given order.
  70         """
  71         result = tuple(fixed_qubits)
  72         if len(set(result)) < len(result):
  73             raise ValueError(
  74                 'Qubits appear in fixed_order twice: {}.'.format(result))
  75 
  76         def func(qubits):
  77             remaining = set(qubits) - set(fixed_qubits)
  78             if not remaining:
  79                 return result
  80             if not fallback:
  81                 raise ValueError(
  82                     'Unexpected extra qubits: {}.'.format(remaining))
  83             return result + fallback.order_for(remaining)
  84 
  85         return QubitOrder(func)
  86 
  87     @staticmethod
  88     def sorted_by(key: Callable[[raw_types.Qid], Any]) -> 'QubitOrder':
  89         """A basis that orders qubits ascending based on a key function.
  90 
  91         Args:
  92             key: A function that takes a qubit and returns a key value. The
  93                 basis will be ordered ascending according to these key values.
  94 
  95 
  96         Returns:
  97             A basis that orders qubits ascending based on a key function.
  98         """
  99         return QubitOrder(lambda qubits: tuple(sorted(qubits, key=key)))
  100 
  101     def order_for(self, qubits: Iterable[raw_types.Qid]
  102                   ) -> Tuple[raw_types.Qid, ...]:
  103         """Returns a qubit tuple ordered corresponding to the basis.
  104 
  105         Args:
  106             qubits: Qubits that should be included in the basis. (Additional
  107                 qubits may be added into the output by the basis.)
  108 
  109         Returns:
  110             A tuple of qubits in the same order that their single-qubit
  111             matrices would be passed into `np.kron` when producing a matrix for
  112             the entire system.
  113         """
  114         return self._explicit_func(qubits)
  115 
  116     @staticmethod
  117     def as_qubit_order(val: 'qubit_order_or_list.QubitOrderOrList'
  118                        ) -> 'QubitOrder':
  119         """Converts a value into a basis.
  120 
  121         Args:
  122             val: An iterable or a basis.
  123 
  124         Returns:
  125             The basis implied by the value.
  126         """
  127         if isinstance(val, collections.Iterable):
  128             return QubitOrder.explicit(val)
  129         if isinstance(val, QubitOrder):
  130             return val
  131         raise ValueError(
  132             "Don't know how to interpret <{}> as a Basis.".format(val))
  133 
  134     def map(self,
  135             internalize: Callable[[TExternalQubit], TInternalQubit],
  136             externalize: Callable[[TInternalQubit], TExternalQubit]
  137             ) -> 'QubitOrder':
  138         """Transforms the Basis so that it applies to wrapped qubits.
  139 
  140         Args:
  141             externalize: Converts an internal qubit understood by the underlying
  142                 basis into an external qubit understood by the caller.
  143             internalize: Converts an external qubit understood by the caller
  144                 into an internal qubit understood by the underlying basis.
  145 
  146         Returns:
  147             A basis that transforms qubits understood by the caller into qubits
  148             understood by an underlying basis, uses that to order the qubits,
  149             then wraps the ordered qubits back up for the caller.
  150         """
  151 
  152         def func(qubits):
  153             unwrapped_qubits = [internalize(q) for q in qubits]
  154             unwrapped_result = self.order_for(unwrapped_qubits)
  155             return tuple(externalize(q) for q in unwrapped_result)
  156 
  157         return QubitOrder(func)
  158 
  159 
  160 QubitOrder.DEFAULT = QubitOrder.sorted_by(lambda v: v)
  161
  ```
  --- END FILES ---
  
  Please first localize the bug based on the issue statement, and then generate a patch according to the `git diff` format fenced by three backticks.
  
  Here is an example:
  
  ```diff
  diff --git a/examples/server_async.py b/examples/server_async.py
  --- a/examples/server_async.py
  +++ b/examples/server_async.py
  @@ -313,4 +313,4 @@
   
   
   if __name__ == "__main__":
  -    asyncio.run(run_async_server("."), debug=True)
  +    asyncio.run(run_async_server(), debug=True)
  diff --git a/examples/server_sync.py b/examples/server_sync.py
  --- a/examples/server_sync.py
  +++ b/examples/server_sync.py
  @@ -313,5 +313,5 @@
   
   
   if __name__ == "__main__":
  -    server = run_sync_server(".")
  +    server = run_sync_server()
       server.shutdown()
  
  ```
  
golden_diff: diff --git a/cirq/ops/qubit_order.py b/cirq/ops/qubit_order.py
  --- a/cirq/ops/qubit_order.py
  +++ b/cirq/ops/qubit_order.py
  @@ -74,7 +74,7 @@
                   'Qubits appear in fixed_order twice: {}.'.format(result))
   
           def func(qubits):
  -            remaining = set(qubits) - set(fixed_qubits)
  +            remaining = set(qubits) - set(result)
               if not remaining:
                   return result
               if not fallback:
  
verification_info: {"golden_diff": "diff --git a/cirq/ops/qubit_order.py b/cirq/ops/qubit_order.py\n--- a/cirq/ops/qubit_order.py\n+++ b/cirq/ops/qubit_order.py\n@@ -74,7 +74,7 @@\n                 'Qubits appear in fixed_order twice: {}.'.format(result))\n \n         def func(qubits):\n-            remaining = set(qubits) - set(fixed_qubits)\n+            remaining = set(qubits) - set(result)\n             if not remaining:\n                 return result\n             if not fallback:\n", "issue": "QubitOrder.explicit fails when given an iterator\nAlso affects `QubitOrder.as_qubit_order()`.  I believe the issue is on line 77 of cirq/ops/qubit_order.py.\r\n\r\nExample:\r\n```\r\ncirq.QubitOrder.as_qubit_order(reversed(cirq.LineQubit.range(5))).order_for(\r\n    (cirq.LineQubit(3),))\r\n```\r\n\r\nThe example raises `ValueError: Unexpected extra qubits: {cirq.LineQubit(3)}.` because `reversed()` is an iterator and QubitOrder tried to iterate it twice.\n", "before_files": [{"content": "# Copyright 2018 The Cirq Developers\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     https://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\nfrom typing import (\n    Any,\n    Callable,\n    Iterable,\n    Optional,\n    Tuple,\n    TypeVar,\n    TYPE_CHECKING,\n)\n\nimport collections\n\nfrom cirq.ops import raw_types\n\nif TYPE_CHECKING:\n    # pylint: disable=unused-import\n    from cirq.ops import qubit_order_or_list\n\n\nTInternalQubit = TypeVar('TInternalQubit')\nTExternalQubit = TypeVar('TExternalQubit')\n\n\nclass QubitOrder:\n    \"\"\"Defines the kronecker product order of qubits.\"\"\"\n\n    def __init__(self, explicit_func: Callable[[Iterable[raw_types.Qid]],\n                                               Tuple[raw_types.Qid, ...]]\n                 ) -> None:\n        self._explicit_func = explicit_func\n\n    DEFAULT = None  # type: QubitOrder\n    \"\"\"A basis that orders qubits in the same way that calling `sorted` does.\n\n    Specifically, qubits are ordered first by their type name and then by\n    whatever comparison value qubits of a given type provide (e.g. for LineQubit\n    it is the x coordinate of the qubit).\n    \"\"\"\n\n    @staticmethod\n    def explicit(fixed_qubits: Iterable[raw_types.Qid],\n                 fallback: Optional['QubitOrder']=None) -> 'QubitOrder':\n        \"\"\"A basis that contains exactly the given qubits in the given order.\n\n        Args:\n            fixed_qubits: The qubits in basis order.\n            fallback: A fallback order to use for extra qubits not in the\n                fixed_qubits list. Extra qubits will always come after the\n                fixed_qubits, but will be ordered based on the fallback. If no\n                fallback is specified, a ValueError is raised when extra qubits\n                are specified.\n\n        Returns:\n            A Basis instance that forces the given qubits in the given order.\n        \"\"\"\n        result = tuple(fixed_qubits)\n        if len(set(result)) < len(result):\n            raise ValueError(\n                'Qubits appear in fixed_order twice: {}.'.format(result))\n\n        def func(qubits):\n            remaining = set(qubits) - set(fixed_qubits)\n            if not remaining:\n                return result\n            if not fallback:\n                raise ValueError(\n                    'Unexpected extra qubits: {}.'.format(remaining))\n            return result + fallback.order_for(remaining)\n\n        return QubitOrder(func)\n\n    @staticmethod\n    def sorted_by(key: Callable[[raw_types.Qid], Any]) -> 'QubitOrder':\n        \"\"\"A basis that orders qubits ascending based on a key function.\n\n        Args:\n            key: A function that takes a qubit and returns a key value. The\n                basis will be ordered ascending according to these key values.\n\n\n        Returns:\n            A basis that orders qubits ascending based on a key function.\n        \"\"\"\n        return QubitOrder(lambda qubits: tuple(sorted(qubits, key=key)))\n\n    def order_for(self, qubits: Iterable[raw_types.Qid]\n                  ) -> Tuple[raw_types.Qid, ...]:\n        \"\"\"Returns a qubit tuple ordered corresponding to the basis.\n\n        Args:\n            qubits: Qubits that should be included in the basis. (Additional\n                qubits may be added into the output by the basis.)\n\n        Returns:\n            A tuple of qubits in the same order that their single-qubit\n            matrices would be passed into `np.kron` when producing a matrix for\n            the entire system.\n        \"\"\"\n        return self._explicit_func(qubits)\n\n    @staticmethod\n    def as_qubit_order(val: 'qubit_order_or_list.QubitOrderOrList'\n                       ) -> 'QubitOrder':\n        \"\"\"Converts a value into a basis.\n\n        Args:\n            val: An iterable or a basis.\n\n        Returns:\n            The basis implied by the value.\n        \"\"\"\n        if isinstance(val, collections.Iterable):\n            return QubitOrder.explicit(val)\n        if isinstance(val, QubitOrder):\n            return val\n        raise ValueError(\n            \"Don't know how to interpret <{}> as a Basis.\".format(val))\n\n    def map(self,\n            internalize: Callable[[TExternalQubit], TInternalQubit],\n            externalize: Callable[[TInternalQubit], TExternalQubit]\n            ) -> 'QubitOrder':\n        \"\"\"Transforms the Basis so that it applies to wrapped qubits.\n\n        Args:\n            externalize: Converts an internal qubit understood by the underlying\n                basis into an external qubit understood by the caller.\n            internalize: Converts an external qubit understood by the caller\n                into an internal qubit understood by the underlying basis.\n\n        Returns:\n            A basis that transforms qubits understood by the caller into qubits\n            understood by an underlying basis, uses that to order the qubits,\n            then wraps the ordered qubits back up for the caller.\n        \"\"\"\n\n        def func(qubits):\n            unwrapped_qubits = [internalize(q) for q in qubits]\n            unwrapped_result = self.order_for(unwrapped_qubits)\n            return tuple(externalize(q) for q in unwrapped_result)\n\n        return QubitOrder(func)\n\n\nQubitOrder.DEFAULT = QubitOrder.sorted_by(lambda v: v)\n", "path": "cirq/ops/qubit_order.py"}], "after_files": [{"content": "# Copyright 2018 The Cirq Developers\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     https://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\nfrom typing import (\n    Any,\n    Callable,\n    Iterable,\n    Optional,\n    Tuple,\n    TypeVar,\n    TYPE_CHECKING,\n)\n\nimport collections\n\nfrom cirq.ops import raw_types\n\nif TYPE_CHECKING:\n    # pylint: disable=unused-import\n    from cirq.ops import qubit_order_or_list\n\n\nTInternalQubit = TypeVar('TInternalQubit')\nTExternalQubit = TypeVar('TExternalQubit')\n\n\nclass QubitOrder:\n    \"\"\"Defines the kronecker product order of qubits.\"\"\"\n\n    def __init__(self, explicit_func: Callable[[Iterable[raw_types.Qid]],\n                                               Tuple[raw_types.Qid, ...]]\n                 ) -> None:\n        self._explicit_func = explicit_func\n\n    DEFAULT = None  # type: QubitOrder\n    \"\"\"A basis that orders qubits in the same way that calling `sorted` does.\n\n    Specifically, qubits are ordered first by their type name and then by\n    whatever comparison value qubits of a given type provide (e.g. for LineQubit\n    it is the x coordinate of the qubit).\n    \"\"\"\n\n    @staticmethod\n    def explicit(fixed_qubits: Iterable[raw_types.Qid],\n                 fallback: Optional['QubitOrder']=None) -> 'QubitOrder':\n        \"\"\"A basis that contains exactly the given qubits in the given order.\n\n        Args:\n            fixed_qubits: The qubits in basis order.\n            fallback: A fallback order to use for extra qubits not in the\n                fixed_qubits list. Extra qubits will always come after the\n                fixed_qubits, but will be ordered based on the fallback. If no\n                fallback is specified, a ValueError is raised when extra qubits\n                are specified.\n\n        Returns:\n            A Basis instance that forces the given qubits in the given order.\n        \"\"\"\n        result = tuple(fixed_qubits)\n        if len(set(result)) < len(result):\n            raise ValueError(\n                'Qubits appear in fixed_order twice: {}.'.format(result))\n\n        def func(qubits):\n            remaining = set(qubits) - set(result)\n            if not remaining:\n                return result\n            if not fallback:\n                raise ValueError(\n                    'Unexpected extra qubits: {}.'.format(remaining))\n            return result + fallback.order_for(remaining)\n\n        return QubitOrder(func)\n\n    @staticmethod\n    def sorted_by(key: Callable[[raw_types.Qid], Any]) -> 'QubitOrder':\n        \"\"\"A basis that orders qubits ascending based on a key function.\n\n        Args:\n            key: A function that takes a qubit and returns a key value. The\n                basis will be ordered ascending according to these key values.\n\n\n        Returns:\n            A basis that orders qubits ascending based on a key function.\n        \"\"\"\n        return QubitOrder(lambda qubits: tuple(sorted(qubits, key=key)))\n\n    def order_for(self, qubits: Iterable[raw_types.Qid]\n                  ) -> Tuple[raw_types.Qid, ...]:\n        \"\"\"Returns a qubit tuple ordered corresponding to the basis.\n\n        Args:\n            qubits: Qubits that should be included in the basis. (Additional\n                qubits may be added into the output by the basis.)\n\n        Returns:\n            A tuple of qubits in the same order that their single-qubit\n            matrices would be passed into `np.kron` when producing a matrix for\n            the entire system.\n        \"\"\"\n        return self._explicit_func(qubits)\n\n    @staticmethod\n    def as_qubit_order(val: 'qubit_order_or_list.QubitOrderOrList'\n                       ) -> 'QubitOrder':\n        \"\"\"Converts a value into a basis.\n\n        Args:\n            val: An iterable or a basis.\n\n        Returns:\n            The basis implied by the value.\n        \"\"\"\n        if isinstance(val, collections.Iterable):\n            return QubitOrder.explicit(val)\n        if isinstance(val, QubitOrder):\n            return val\n        raise ValueError(\n            \"Don't know how to interpret <{}> as a Basis.\".format(val))\n\n    def map(self,\n            internalize: Callable[[TExternalQubit], TInternalQubit],\n            externalize: Callable[[TInternalQubit], TExternalQubit]\n            ) -> 'QubitOrder':\n        \"\"\"Transforms the Basis so that it applies to wrapped qubits.\n\n        Args:\n            externalize: Converts an internal qubit understood by the underlying\n                basis into an external qubit understood by the caller.\n            internalize: Converts an external qubit understood by the caller\n                into an internal qubit understood by the underlying basis.\n\n        Returns:\n            A basis that transforms qubits understood by the caller into qubits\n            understood by an underlying basis, uses that to order the qubits,\n            then wraps the ordered qubits back up for the caller.\n        \"\"\"\n\n        def func(qubits):\n            unwrapped_qubits = [internalize(q) for q in qubits]\n            unwrapped_result = self.order_for(unwrapped_qubits)\n            return tuple(externalize(q) for q in unwrapped_result)\n\n        return QubitOrder(func)\n\n\nQubitOrder.DEFAULT = QubitOrder.sorted_by(lambda v: v)\n", "path": "cirq/ops/qubit_order.py"}]}