internlm/SWE-Fixer-Train-110K huggingface dataset:
Repository: Qiskit/qiskit

Issue:
Default circuit names are not zero-based
<!-- ⚠️ If you do not respect this template, your issue will be closed -->
<!-- ⚠️ Make sure to browse the opened and closed issues -->

### Informations

- **Qiskit Terra version**: latest
- **Python version**: 3.7
- **Operating system**: OSX

### What is the current behavior?
When creating a quantum circuit with no name, the default name is set to `circuitX`.  Currently, `X` starts from `1` rather than `0`, and can cause some confusion when trying to index circuits by name.


### Steps to reproduce the problem
```python
from qiskit import *
q = QuantumRegister(2, "q")
c = ClassicalRegister(2, "c")
# Create measurement subcircuit
qc = QuantumCircuit(q,c)
qc.name
```
gives `'circuit1'` for the initial circuit created.  It should be `'circuit0'` to coincide with the the indexing in Python.

### What is the expected behavior?



### Suggested solutions





Discussion:

Resolving patch:
diff --git a/qiskit/_quantumcircuit.py b/qiskit/_quantumcircuit.py
--- a/qiskit/_quantumcircuit.py
+++ b/qiskit/_quantumcircuit.py
@@ -51,9 +51,9 @@ def __init__(self, *regs, name=None):
         Raises:
             QISKitError: if the circuit name, if given, is not valid.
         """
-        self._increment_instances()
         if name is None:
             name = self.cls_prefix() + str(self.cls_instances())
+        self._increment_instances()
 
         if not isinstance(name, str):
             raise QISKitError("The circuit name should be a string "


Test patch:
Repository: Qiskit/qiskit

Issue:
DAG visualization dependence on graphviz is not mentioned
<!-- ⚠️ If you do not respect this template, your issue will be closed -->
<!-- ⚠️ Make sure to browse the opened and closed issues -->

### Informations

- **Qiskit Terra version**: latest
- **Python version**: 3.7
- **Operating system**: OSX

### What is the current behavior?
Calling `dag_drawer(dag)` gives the error:
```python
InvocationException: GraphViz's executables not found
```
indicating that `GraphViz` is a requirement for this function, but it is not listed anywhere.

### Steps to reproduce the problem



### What is the expected behavior?



### Suggested solutions





Discussion:

Resolving patch:
diff --git a/qiskit/tools/visualization/_dag_visualization.py b/qiskit/tools/visualization/_dag_visualization.py
--- a/qiskit/tools/visualization/_dag_visualization.py
+++ b/qiskit/tools/visualization/_dag_visualization.py
@@ -21,6 +21,12 @@ def dag_drawer(dag, scale=0.7, filename=None, style='color'):
     """Plot the directed acyclic graph (dag) to represent operation dependencies
     in a quantum circuit.
 
+    Note this function leverages
+    `pydot <https://github.com/erocarrera/pydot>`_ (via
+    `nxpd <https://github.com/chebee7i/nxpd`_) to generate the graph, which
+    means that having `Graphviz <https://www.graphviz.org/>`_ installed on your
+    system is required for this to work.
+
     Args:
         dag (DAGCircuit): The dag to draw.
         scale (float): scaling factor


Test patch:
Repository: Qiskit/qiskit

Issue:
Barrier when reversebits circuit drawer
<!-- ⚠️ If you do not respect this template, your issue will be closed -->
<!-- ⚠️ Make sure to browse the opened and closed issues -->

### Informations

- **Qiskit Terra version**:
- **Python version**:
- **Operating system**:

### What is the current behavior?
I saw two problems when using barriers in the latex drawer.
1. When using `'reversebits': True` in the style, the barriers get messed up. The following should have barriers on quantum registers q and v:
![image](https://user-images.githubusercontent.com/8622381/46925091-21296480-cff8-11e8-943f-d35e4d9feb56.png)

2. The style `'plotbarrier': False` is introduced by the mpl drawer, but the latex drawer ignores it. It would be nice if this style affected both drawers.


### Steps to reproduce the problem
```
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit
from qiskit.tools.visualization import circuit_drawer
q = QuantumRegister(3, 'q')
v = QuantumRegister(2, 'v')
c = ClassicalRegister(4, 'c')
d = ClassicalRegister(3, 'd')
circ = QuantumCircuit(q, v, c, d)
circ.x(q[0])
circ.x(q[2])
circ.x(v[1])
circ.barrier(q)
circ.barrier(v)
circ.measure(q[0], c[1])
circ.measure(q[2], d[2])
circ.measure(v[1], c[0])
circuit_drawer(circ, output='latex', scale=0.5, style={'reversebits': True, 'plotbarrier': False})
```


### What is the expected behavior?
Barrier on registers `q` and `v`






Discussion:

Resolving patch:
diff --git a/qiskit/tools/visualization/_circuit_visualization.py b/qiskit/tools/visualization/_circuit_visualization.py
--- a/qiskit/tools/visualization/_circuit_visualization.py
+++ b/qiskit/tools/visualization/_circuit_visualization.py
@@ -1435,6 +1435,8 @@ def _build_latex_array(self, aliases=None):
                                       str(e))
             elif op['name'] == "barrier":
                 qarglist = [self.qubit_list[i] for i in op['qubits']]
+                if self._style.reverse:
+                    qarglist = list(reversed(qarglist))
                 if aliases is not None:
                     qarglist = map(lambda x: aliases[x], qarglist)
                 start = self.img_regs[(qarglist[0][0],


Test patch:
Repository: Qiskit/qiskit

Issue:
Running on statevector_simulator alters the qobj
<!-- ⚠️ If you do not respect this template, your issue will be closed -->
<!-- ⚠️ Make sure to browse the opened and closed issues -->

### Informations

- **Qiskit Terra version**:
- **Python version**:
- **Operating system**:

### What is the current behavior?
When a qobj is run on a statevector_simulator, it implicitly inserts a snapshot at the end, sets `shots=1`, then runs it on the qasm_simulator.

The added instruction makes the qobj not pass validation if run again.

```python
statevector_simulator = Aer.get_backend('statevector_simulator')
qobj = compile(circ, statevector_simulator, shots=1)
statevector_simulator.run(qobj).result().get_statevector()  # this works fine
statevector_simulator.run(qobj).result().get_statevector()  # the second time, SchemaValidationError is raised
```

### Suggested solution:
Move this logic to the transpiler, and make Qobj immutable.


Discussion:

Resolving patch:
diff --git a/qiskit/backends/aer/statevector_simulator.py b/qiskit/backends/aer/statevector_simulator.py
--- a/qiskit/backends/aer/statevector_simulator.py
+++ b/qiskit/backends/aer/statevector_simulator.py
@@ -57,6 +57,9 @@ def _run_job(self, job_id, qobj):
                                 label='MISSING', type='MISSING')
             )
         result = super()._run_job(job_id, qobj)
+        # Remove added snapshot from qobj
+        for experiment in qobj.experiments:
+            del experiment.instructions[-1]
         # Extract final state snapshot and move to 'statevector' data field
         for experiment_result in result.results.values():
             snapshots = experiment_result.snapshots
diff --git a/qiskit/backends/aer/statevector_simulator_py.py b/qiskit/backends/aer/statevector_simulator_py.py
--- a/qiskit/backends/aer/statevector_simulator_py.py
+++ b/qiskit/backends/aer/statevector_simulator_py.py
@@ -71,6 +71,9 @@ def _run_job(self, job_id, qobj):
                                 label='MISSING', type='MISSING')
             )
         result = super()._run_job(job_id, qobj)
+        # Remove added snapshot from qobj
+        for experiment in qobj.experiments:
+            del experiment.instructions[-1]
         # Extract final state snapshot and move to 'statevector' data field
         for experiment_result in result.results.values():
             snapshots = experiment_result.snapshots


Test patch:
Repository: Qiskit/qiskit

Issue:
test_compiler breaks AerJob status check
<!-- ⚠️ If you do not respect this template, your issue will be closed -->
<!-- ⚠️ Make sure to browse the opened and closed issues -->

### Informations

- **Qiskit Terra version**: master
- **Python version**:
- **Operating system**:

### What is the current behavior?
When running the tests, the following does not work when run *after* the `test_compiler` module:

```python
backend = Aer.get_backend('qasm_simulator')
job_sim = execute(qc, backend)
job_sim.status()
```

```
Traceback (most recent call last):
  File "/Users/paul/Desktop/Github_repos/qiskit-core/test/python/test_cpp.py", line 34, in test_aer_status
    job_sim.status()
  File "/Users/paul/Desktop/Github_repos/qiskit-core/qiskit/backends/aer/aerjob.py", line 37, in _wrapper
    return func(self, *args, **kwargs)
  File "/Users/paul/Desktop/Github_repos/qiskit-core/qiskit/backends/aer/aerjob.py", line 118, in status
    self.__class__.__name__))
qiskit.backends.joberror.JobError: 'Unexpected behavior of AerJob'
```

However, if run *before* that module, it works fine.  This is true both when running locally and on Travis.  This is blocking #975.

### Steps to reproduce the problem



### What is the expected behavior?



### Suggested solutions





Discussion:
I'm taking over this one

Resolving patch:
diff --git a/qiskit/backends/aer/aerjob.py b/qiskit/backends/aer/aerjob.py
--- a/qiskit/backends/aer/aerjob.py
+++ b/qiskit/backends/aer/aerjob.py
@@ -114,8 +114,12 @@ def status(self):
         elif self._future.done():
             _status = JobStatus.DONE if self._future.exception() is None else JobStatus.ERROR
         else:
-            raise JobError('Unexpected behavior of {0}'.format(
-                self.__class__.__name__))
+            # Note: There is an undocumented Future state: PENDING, that seems to show up when
+            # the job is enqueued, waiting for someone to pick it up. We need to deal with this
+            # state but there's no public API for it, so we are assuming that if the job is not
+            # in any of the previous states, is PENDING, ergo INITIALIZING for us.
+            _status = JobStatus.INITIALIZING
+
         return _status
 
     def backend_name(self):


Test patch:
Repository: Qiskit/qiskit

Issue:
test.python.quantum_info.test_states.TestStates.test_random_state fails by returning nan 
<!-- ⚠️ If you do not respect this template, your issue will be closed -->
<!-- ⚠️ Make sure to browse the opened and closed issues -->

### Informations

- **Qiskit Terra version**: master
- **Python version**: any
- **Operating system**: any

### What is the current behavior?

Occasionally in CI we're encountering failures caused by `test.python.quantum_info.test_states.TestStates.test_random_state` generating `nan` instead of a value converged to `1/8`. For example see:

https://ci.appveyor.com/project/QISKit/qiskit-sdk-py/builds/20165445/job/r5t0rtgv445hcuqt#L927

```
test.python.quantum_info.test_states.TestStates.test_random_state
-----------------------------------------------------------------
Captured traceback:
~~~~~~~~~~~~~~~~~~~
    b'Traceback (most recent call last):'
    b'  File "C:\\projects\\qiskit-sdk-py\\test\\python\\quantum_info\\test_states.py", line 90, in test_random_state'
    b'    self.assertAlmostEqual(E_P0, 1/8, places=2)'
    b'  File "C:\\Python35\\lib\\unittest\\case.py", line 877, in assertAlmostEqual'
    b'    raise self.failureException(msg)'
    b'AssertionError: nan != 0.125 within 2 places'
    b''
======
```

### Steps to reproduce the problem

It's occurring in CI occasionally, see the referenced failures.


### What is the expected behavior?

The test passes 100% of the time.

### Suggested solutions

Figure out the source of the failure (likely something with calling randint in the test) and fix it so that it always passes.


Discussion:
I had a look at this. I'm not sure what I found is the bug that is causing the CI failures but I believe it to be _a_ bug at least!

I can't see an issue with the use of `randint` (other than the issues raised in #205). However the `random_state` function which is called has the line `x = np.random.random(1 << num)+0.00000001` followed by some numpy array manipulations. It's quite rare but I believe that line can give arrays with elements greater than 1 which result in a `nan` value being returned and hence the `AssertionError`.
This test can't be deterministic but it converges to a known value. 

I agree with you lets make sure that this is not greater than one. 
Ill open a PR later on.
great -- when you have done just ping me and i will look. 

Resolving patch:
diff --git a/qiskit/quantum_info/states/_states.py b/qiskit/quantum_info/states/_states.py
--- a/qiskit/quantum_info/states/_states.py
+++ b/qiskit/quantum_info/states/_states.py
@@ -48,7 +48,9 @@ def random_state(num):
     Returns:
         ndarray:  state(2**num) a random quantum state.
     """
-    x = np.random.random(1 << num)+0.00000001
+    # Random array over interval (0, 1]
+    x = np.random.random(1 << num)
+    x += x == 0
     x = -np.log(x)
     sumx = sum(x)
     phases = np.random.random(1 << num)*2.0*np.pi


Test patch:
Repository: Qiskit/qiskit

Issue:
update example visualizing_circuits
<!-- ⚠️ If you do not respect this template, your issue will be closed -->
<!-- ⚠️ Make sure to browse the opened and closed issues to confirm this idea does not exist. -->

### What is the expected behavior?
when the ascii drawer is in place update the `visualizing_circuits.py` example and show it using circuit.draw()

as for me on a mac I cant user matplotlib with just python. Need to use the pythonw. 




Discussion:
This is blocked until issue #1004 is fixed. This issue is fixed by PR #911, which is on hold. Therefore, this is on hold.

Resolving patch:
diff --git a/examples/python/visualizing_circuits.py b/examples/python/circuit_draw.py
similarity index 69%
rename from examples/python/visualizing_circuits.py
rename to examples/python/circuit_draw.py
--- a/examples/python/visualizing_circuits.py
+++ b/examples/python/circuit_draw.py
@@ -11,7 +11,6 @@
 """
 
 from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister
-from qiskit.tools.visualization import circuit_drawer
 
 
 def build_bell_circuit():
@@ -27,9 +26,5 @@ def build_bell_circuit():
 # Create the circuit
 bell_circuit = build_bell_circuit()
 
-# Provide a name to write the diagram to the filesystem
-circuit_drawer(bell_circuit, filename='./bell_circuit.png')
-
-# Use the return value with show() to display the diagram
-diagram = circuit_drawer(bell_circuit)
-diagram.show()
+# Use the internal .draw() to print the circuit
+print(bell_circuit)
diff --git a/examples/python/qft.py b/examples/python/qft.py
--- a/examples/python/qft.py
+++ b/examples/python/qft.py
@@ -63,9 +63,9 @@ def qft(circ, q, n):
 for j in range(5):
     qft5.measure(q[j], c[j])
 
-print(qft3.qasm())
-print(qft4.qasm())
-print(qft5.qasm())
+print(qft3)
+print(qft4)
+print(qft5)
 
 ###############################################################
 # Set up the API and execute the program.


Test patch:
Repository: Qiskit/qiskit

Issue:
load_qasm example should use the quantumcircuit
<!-- ⚠️ If you do not respect this template, your issue will be closed -->
<!-- ⚠️ Make sure to browse the opened and closed issues to confirm this idea does not exist. -->

### What is the expected behavior?

Need to update the load_qasm with the new from file qasm load. 



Discussion:

Resolving patch:
diff --git a/examples/python/load_qasm.py b/examples/python/load_qasm.py
--- a/examples/python/load_qasm.py
+++ b/examples/python/load_qasm.py
@@ -1,25 +1,25 @@
 """
-Example on how to use: load_qasm_file
+Example on how to load a file into a QuantumCircuit
 
 """
-from qiskit.wrapper import load_qasm_file
+from qiskit import QuantumCircuit
 from qiskit import QISKitError, execute, Aer
 
 try:
-    qc = load_qasm_file("examples/qasm/entangled_registers.qasm")
+    circ = QuantumCircuit.from_qasm_file("examples/qasm/entangled_registers.qasm")
+    print(circ.draw())
 
-    # See a list of available local simulators
-    print("Aer backends: ", Aer.backends())
+    # See the backend
     sim_backend = Aer.get_backend('qasm_simulator')
 
 
     # Compile and run the Quantum circuit on a local simulator backend
-    job_sim = execute(qc, sim_backend)
+    job_sim = execute(circ, sim_backend)
     sim_result = job_sim.result()
 
     # Show the results
     print("simulation: ", sim_result)
-    print(sim_result.get_counts(qc))
+    print(sim_result.get_counts(circ))
 
 except QISKitError as ex:
     print('There was an internal Qiskit error. Error = {}'.format(ex))


Test patch:
Repository: Qiskit/qiskit

Issue:
_has_connection('https://qvisualization.mybluemix.net/', port=443) returns False
<!-- ⚠️ If you do not respect this template, your issue will be closed -->
<!-- ⚠️ Make sure to browse the opened and closed issues -->

### Information

- **Qiskit Terra version**: master
- **Python version**: 3.7
- **Operating system**: OSX

### What is the current behavior?
Interactive visualizations do not work because `_has_connection('https://qvisualization.mybluemix.net/', port=443)` is returning `False`.


### Steps to reproduce the problem
Try it.


### What is the expected behavior?

### Suggested solutions




Discussion:
@filemaster 

Resolving patch:
diff --git a/qiskit/tools/visualization/__init__.py b/qiskit/tools/visualization/__init__.py
--- a/qiskit/tools/visualization/__init__.py
+++ b/qiskit/tools/visualization/__init__.py
@@ -26,7 +26,7 @@
 
 INTERACTIVE = False
 if ('ipykernel' in sys.modules) and ('spyder' not in sys.modules):
-    if _has_connection('https://qvisualization.mybluemix.net/', 443):
+    if _has_connection('qvisualization.mybluemix.net', 443):
         INTERACTIVE = True
 
 


Test patch:
Repository: Qiskit/qiskit

Issue:
Revise the documentation TOC subsection handling
<!-- ⚠️ If you do not respect this template, your issue will be closed -->
<!-- ⚠️ Make sure to browse the opened and closed issues to confirm this idea does not exist. -->

### What is the expected enhancement?

An issue raised during #1254:

> Also Is it possible in the template to show the subsection when that section is viewed.

The new fancy design currently does not show subsections in the left-side TOC pane (except for the autodocs). Ideally it should show the subsections, allowing collapsing with sensible defaults and usability.



Discussion:

Resolving patch:
diff --git a/doc/conf.py b/doc/conf.py
--- a/doc/conf.py
+++ b/doc/conf.py
@@ -117,6 +117,11 @@
 # html_theme = 'bizstyle'
 # html_theme = agogo
 
+html_sidebars = {
+   '**': ['globaltoc.html']
+}
+
+
 html_theme = 'sphinx_materialdesign_theme' # use the theme in subdir 'theme'
 html_theme_path = ['./']  # make sphinx search for themes in current dir
 


Test patch:
Repository: Qiskit/qiskit

Issue:
Memory-related spec changes for 0.7
<!-- ⚠️ If you do not respect this template, your issue will be closed -->
<!-- ⚠️ Make sure to browse the opened and closed issues to confirm this idea does not exist. -->

### What is the expected enhancement?

After recent discussion, the specs needs further tweaks before 0.7:

* `BackendConfiguration`:
   * `BackendConfiguration.memory` (boolean): new **required** field, indicates if the backend supports `memory`
   * `BackendConfiguration.max_shots` (int): new **required** field, contains the maximum number of shots supported
* `Qobj`:
   * `config.memory` (boolean): new **optional** field, indicates if the job is going to use `memory`

This changes need to be reflected as well in #1047, for tracking purposes.



Discussion:
Updating as there is one more change left in the specs:

* `BackendConfiguration.max_experiments` (int): new optional field, contains the maximum number of experiments supported.

Resolving patch:
diff --git a/qiskit/backends/models/backendconfiguration.py b/qiskit/backends/models/backendconfiguration.py
--- a/qiskit/backends/models/backendconfiguration.py
+++ b/qiskit/backends/models/backendconfiguration.py
@@ -52,6 +52,7 @@ class BackendConfigurationSchema(BaseSchema):
     max_shots = Integer(required=True, validate=Range(min=1))
 
     # Optional properties.
+    max_experiments = Integer(validate=Range(min=1))
     sample_name = String()
     coupling_map = List(List(Integer(),
                              validate=Length(min=1)),


Test patch:
Repository: Qiskit/qiskit

Issue:
circuit.draw(output='mpl) does not draw qubit labels correctly.
<!-- ⚠️ If you do not respect this template, your issue will be closed -->
<!-- ⚠️ Make sure to browse the opened and closed issues -->

### Informations

- **Qiskit Terra version**: master
- **Python version**: 3.7
- **Operating system**: osx

### What is the current behavior?
Using Latex:
<img width="603" alt="screen shot 2018-12-07 at 11 49 43 am" src="https://user-images.githubusercontent.com/1249193/49661112-39c16400-fa16-11e8-8610-70a1d89474e6.png">
Using MPL:
<img width="496" alt="screen shot 2018-12-07 at 11 50 21 am" src="https://user-images.githubusercontent.com/1249193/49661148-4fcf2480-fa16-11e8-8f52-ad065c35d815.png">



### Steps to reproduce the problem



### What is the expected behavior?



### Suggested solutions





Discussion:

Resolving patch:
diff --git a/qiskit/tools/visualization/_matplotlib.py b/qiskit/tools/visualization/_matplotlib.py
--- a/qiskit/tools/visualization/_matplotlib.py
+++ b/qiskit/tools/visualization/_matplotlib.py
@@ -363,9 +363,9 @@ def _draw_regs(self):
         # quantum register
         for ii, reg in enumerate(self._qreg):
             if len(self._qreg) > 1:
-                label = '${}_{{{}}}$'.format(reg.name, reg.index)
+                label = '${}_{{{}}}$'.format(reg.name.name, reg.index)
             else:
-                label = '${}$'.format(reg.name)
+                label = '${}$'.format(reg.name.name)
             pos = -ii
             self._qreg_dict[ii] = {
                 'y': pos,
@@ -384,7 +384,7 @@ def _draw_regs(self):
                     self._creg, n_creg)):
                 pos = y_off - idx
                 if self._style.bundle:
-                    label = '${}$'.format(reg.name)
+                    label = '${}$'.format(reg.name.name)
                     self._creg_dict[ii] = {
                         'y': pos,
                         'label': label,
@@ -394,7 +394,7 @@ def _draw_regs(self):
                     if not (not nreg or reg.name != nreg.name):
                         continue
                 else:
-                    label = '${}_{{{}}}$'.format(reg.name, reg.index)
+                    label = '${}_{{{}}}$'.format(reg.name.name, reg.index)
                     self._creg_dict[ii] = {
                         'y': pos,
                         'label': label,


Test patch: