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

Issue:
Remove `deepcopy` from `circuit_to_dag`
<!-- ⚠️ 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?

It's very slow.



Discussion:

Resolving patch:
diff --git a/qiskit/converters/circuit_to_dag.py b/qiskit/converters/circuit_to_dag.py
--- a/qiskit/converters/circuit_to_dag.py
+++ b/qiskit/converters/circuit_to_dag.py
@@ -7,7 +7,6 @@
 
 """Helper function for converting a circuit to a dag"""
 
-import copy
 
 from qiskit.circuit.compositegate import CompositeGate
 from qiskit.dagcircuit._dagcircuit import DAGCircuit
@@ -22,8 +21,6 @@ def circuit_to_dag(circuit):
     Return:
         DAGCircuit: the DAG representing the input circuit.
     """
-    circuit = copy.deepcopy(circuit)
-
     dagcircuit = DAGCircuit()
     dagcircuit.name = circuit.name
     for register in circuit.qregs:
@@ -72,7 +69,19 @@ def circuit_to_dag(circuit):
             else:
                 control = (instruction.control[0], instruction.control[1])
 
-            dagcircuit.apply_operation_back(instruction, instruction.qargs,
-                                            instruction.cargs, control)
+            def duplicate_instruction(inst):
+                """Create a fresh instruction from an input instruction."""
+                if inst.name == 'barrier':
+                    params = [inst.qargs]
+                elif inst.name in simulator_instructions.keys():
+                    params = inst.param + [inst.qargs] + [inst.circuit]
+                else:
+                    params = inst.param + inst.qargs + inst.cargs
+                new_inst = inst.__class__(*params)
+                return new_inst
+
+            inst = duplicate_instruction(instruction)
+            dagcircuit.apply_operation_back(inst, inst.qargs,
+                                            inst.cargs, control)
 
     return dagcircuit


Test patch:
Repository: Qiskit/qiskit

Issue:
timeout setting is not passed to job submission [remote backend]
<!-- ⚠️ 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**: the newest master branch
- **Python version**: 3.6.5
- **Operating system**: macOS 10.13

### What is the current behavior?

`timeout` setting only used for `_wait_for_result` but not `_wait_for_submission`.
So, Qiskit raises `the Timeout error` after 60 seconds regardless of the setting of `timeout`.

related codes:
`_wait_for_result`
https://github.com/Qiskit/qiskit-terra/blob/master/qiskit/backends/ibmq/ibmqjob.py#L190
`_wait_for_submission`
https://github.com/Qiskit/qiskit-terra/blob/master/qiskit/backends/ibmq/ibmqjob.py#L400

### Steps to reproduce the problem



### What is the expected behavior?

`timeout` setting should be passed to `_wait_for_submission` as well.

### Suggested solutions

pass the `timeout`  in `_wait_for_result` to  `_wait_for_submission`.



Discussion:
@delapuente can we link this to the epic on the redo of backends. 
I don't think this belongs to the authentication effort but we can discuss it in the next review if you want.

Resolving patch:
diff --git a/qiskit/providers/ibmq/ibmqjob.py b/qiskit/providers/ibmq/ibmqjob.py
--- a/qiskit/providers/ibmq/ibmqjob.py
+++ b/qiskit/providers/ibmq/ibmqjob.py
@@ -204,7 +204,7 @@ def result(self, timeout=None, wait=5):
         return self._result_from_job_response(job_response)
 
     def _wait_for_result(self, timeout=None, wait=5):
-        self._wait_for_submission()
+        self._wait_for_submission(timeout)
 
         try:
             job_response = self._wait_for_job(timeout=timeout, wait=wait)


Test patch:
Repository: Qiskit/qiskit

Issue:
IBMQjob Seed
<!-- ⚠️ 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.6.6
- **Operating system**: OSX

### What is the current behavior?
[IBMQJob `_job_data` tries to directly access seed] (https://github.com/Qiskit/qiskit-terra/blob/37e4f3540e2fc1c9ab4b37c6cc5a449c82fb2391/qiskit/providers/ibmq/ibmqjob.py#L150). 


### Steps to reproduce the problem



### What is the expected behaviour?
It should not fail on pulse qobj's missing this seed.

### Suggested solutions
`seed': old_qobj['circuits'][0]['config'].get('seed')`





Discussion:

Resolving patch:
diff --git a/qiskit/providers/ibmq/ibmqjob.py b/qiskit/providers/ibmq/ibmqjob.py
--- a/qiskit/providers/ibmq/ibmqjob.py
+++ b/qiskit/providers/ibmq/ibmqjob.py
@@ -147,7 +147,7 @@ def __init__(self, backend, job_id, api, is_device, qobj=None,
             self._job_data = {
                 'circuits': old_qobj['circuits'],
                 'hpc':  old_qobj['config'].get('hpc'),
-                'seed': old_qobj['circuits'][0]['config']['seed'],
+                'seed': old_qobj['circuits'][0]['config'].get('seed'),
                 'shots': old_qobj['config']['shots'],
                 'max_credits': old_qobj['config']['max_credits']
             }


Test patch:
Repository: Qiskit/qiskit

Issue:
remove ghpages_documentation_deploy.sh
<!-- ⚠️ 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?
since all the documentation is now in qiskit/qiskit we should remove this script. 




Discussion:

Resolving patch:
diff --git a/setup.py b/setup.py
--- a/setup.py
+++ b/setup.py
@@ -13,7 +13,7 @@
     "marshmallow>=2.17.0,<3",
     "marshmallow_polyfield>=3.2,<4",
     "networkx>=2.2",
-    "numpy>=1.13",
+    "numpy>=1.13,<1.16",
     "pillow>=4.2.1",
     "ply>=3.10",
     "psutil>=5",


Test patch:
Repository: Qiskit/qiskit

Issue:
Bug in drawing barriers in matplotlib 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**: master
- **Python version**: 3.6
- **Operating system**: mac

### What is the current behavior?
Drawing barriers (or barrier like instructions such as snapshot) sometimes fails in matplotlib drawer.


### Steps to reproduce the problem
```python
from qiskit import QuantumCircuit
qasm = """
OPENQASM 2.0;
include "qelib1.inc";
qreg q[1];
qreg r[1];
creg c[1];
cz q, r;
barrier q, r;
x q;
y q;
measure q -> c;
z q;
if (c==1) z r;
"""
circ = QuantumCircuit.from_qasm_str(qasm)
circ.draw(output='mpl')
```

![image](https://user-images.githubusercontent.com/8622381/51454284-f72bc080-1d11-11e9-8a12-cdb4e8558aa4.png)


### What is the expected behavior?
Barrier should extend across all qubits.







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
@@ -592,10 +592,15 @@ def _draw_ops(self, verbose=False):
                 self._measure(q_xy[0], c_xy[0], vv)
             elif op['name'] in ['barrier', 'snapshot', 'load', 'save',
                                 'noise']:
-                q_group = self._qreg_dict[q_idxs[0]]['group']
-                if q_group not in _barriers['group']:
-                    _barriers['group'].append(q_group)
-                _barriers['coord'].append(q_xy[0])
+
+                # Go over all indices to add barriers across
+                for index, qbit in enumerate(q_idxs):
+                    q_group = self._qreg_dict[qbit]['group']
+
+                    if q_group not in _barriers['group']:
+                        _barriers['group'].append(q_group)
+                    _barriers['coord'].append(q_xy[index])
+
                 if op_next and op_next['name'] == 'barrier':
                     continue
                 else:


Test patch:
Repository: Qiskit/qiskit

Issue:
BackendConfiguration fails validation if backend supports pulse
<!-- ⚠️ 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**:0.8.0
- **Python version**3.6.6
- **Operating system**:OSX

### What is the current behavior?
If a backend sets `open_pulse=true` in its configuration Qiskit will raise a validation error when creating a `BackendConfigurationSchema`


### Steps to reproduce the problem
Create a backend with `open_pulse=true` set in its configuration.


### What is the expected behavior?
Should not fail.


### Suggested solutions
Allow `open_pulse=true` to be valid.




Discussion:

Resolving patch:
diff --git a/qiskit/providers/models/backendconfiguration.py b/qiskit/providers/models/backendconfiguration.py
--- a/qiskit/providers/models/backendconfiguration.py
+++ b/qiskit/providers/models/backendconfiguration.py
@@ -7,7 +7,7 @@
 
 """Model and schema for backend configuration."""
 
-from marshmallow.validate import Equal, Length, OneOf, Range, Regexp
+from marshmallow.validate import Length, OneOf, Range, Regexp
 
 from qiskit.validation import BaseModel, BaseSchema, bind_schema
 from qiskit.validation.fields import Boolean, DateTime, Integer, List, Nested, String
@@ -47,7 +47,7 @@ class BackendConfigurationSchema(BaseSchema):
     local = Boolean(required=True)
     simulator = Boolean(required=True)
     conditional = Boolean(required=True)
-    open_pulse = Boolean(required=True, validate=Equal(False))
+    open_pulse = Boolean(required=True)
     memory = Boolean(required=True)
     max_shots = Integer(required=True, validate=Range(min=1))
 


Test patch:
Repository: Qiskit/qiskit

Issue:
Include a copy method for 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 enhancement?
This code is often repeated a lot:
```
import copy
qc_copy = copy.deepcopy(qc)
```
It would be nice if there was a `copy()` method for `QuantumCircuit` that did this for you.



Discussion:

Resolving patch:
diff --git a/qiskit/circuit/quantumcircuit.py b/qiskit/circuit/quantumcircuit.py
--- a/qiskit/circuit/quantumcircuit.py
+++ b/qiskit/circuit/quantumcircuit.py
@@ -377,6 +377,10 @@ def num_tensor_factors(self):
         dag = circuit_to_dag(self)
         return dag.num_tensor_factors()
 
+    def copy(self):
+        """ Returns a deepcopy of the circuit"""
+        return deepcopy(self)
+
     @staticmethod
     def from_qasm_file(path):
         """Take in a QASM file and generate a QuantumCircuit object.


Test patch:
diff --git a/test/python/circuit/test_circuit_operations.py b/test/python/circuit/test_circuit_operations.py
--- a/test/python/circuit/test_circuit_operations.py
+++ b/test/python/circuit/test_circuit_operations.py
@@ -135,3 +135,14 @@ def test_measure_args_type_cohesion(self):
             quantum_circuit.measure(quantum_reg, classical_reg_1)
         self.assertEqual(ctx.exception.message,
                          'qubit and cbit should have the same length if lists')
+
+    def test_copy_circuit(self):
+        """ Test copy method makes a copy"""
+        qr = QuantumRegister(2)
+        cr = ClassicalRegister(2)
+        qc = QuantumCircuit(qr, cr)
+        qc.h(qr[0])
+        qc.measure(qr[0], cr[0])
+        qc.measure(qr[1], cr[1])
+
+        self.assertEqual(qc, qc.copy())
Repository: Qiskit/qiskit

Issue:
[ENH] reverse order of operations when loading OpenQASM 
<!-- ⚠️ 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?
When applying an operation to a quantum register in OpenQASM code, the operations get loaded in an order where the last qubit is first. It would be nice to have this reversed. 

Currently:
```python
qasm = """OPENQASM 2.0;
include "qelib1.inc";
qreg q[3];
h q;"""

from qiskit import QuantumCircuit
circuit = QuantumCircuit.from_qasm_str(qasm)

print(circuit.qasm())
```
 Yields H on q[2] first, then q[1], then q[0]
```
OPENQASM 2.0;
include "qelib1.inc";
qreg q[3];
h q[2];
h q[1];
h q[0];         
```


Discussion:

Resolving patch:
diff --git a/qiskit/converters/dag_to_circuit.py b/qiskit/converters/dag_to_circuit.py
--- a/qiskit/converters/dag_to_circuit.py
+++ b/qiskit/converters/dag_to_circuit.py
@@ -7,7 +7,6 @@
 
 """Helper function for converting a dag to a circuit"""
 import collections
-import networkx as nx
 
 from qiskit.circuit import QuantumCircuit
 from qiskit.circuit import ClassicalRegister
@@ -36,7 +35,7 @@ def dag_to_circuit(dag):
     circuit = QuantumCircuit(*qregs.values(), *cregs.values(), name=name)
 
     graph = dag.multi_graph
-    for node in nx.topological_sort(graph):
+    for node in dag.node_nums_in_topological_order():
         n = graph.nodes[node]
         if n['type'] == 'op':
             if n['op'].name == 'U':


Test patch:
diff --git a/test/python/circuit/test_circuit_load_from_qasm.py b/test/python/circuit/test_circuit_load_from_qasm.py
--- a/test/python/circuit/test_circuit_load_from_qasm.py
+++ b/test/python/circuit/test_circuit_load_from_qasm.py
@@ -145,3 +145,19 @@ def test_qasm_example_file(self):
         self.assertEqual(q_circuit, expected_circuit)
         self.assertEqual(len(q_circuit.cregs), 2)
         self.assertEqual(len(q_circuit.qregs), 2)
+
+    def test_qasm_qas_string_order(self):
+        """ Test that gates are returned in qasm in ascending order"""
+        expected_qasm = '\n'.join(["OPENQASM 2.0;",
+                                   "include \"qelib1.inc\";",
+                                   "qreg q[3];",
+                                   "h q[0];",
+                                   "h q[1];",
+                                   "h q[2];"]) + '\n'
+        qasm_string = """OPENQASM 2.0;
+        include "qelib1.inc";
+        qreg q[3];
+        h q;"""
+        q_circuit = QuantumCircuit.from_qasm_str(qasm_string)
+
+        self.assertEqual(q_circuit.qasm(), expected_qasm)
Repository: Qiskit/qiskit

Issue:
Support the progress bar to another stream handler
<!-- ⚠️ 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?
ProgressBar is a good visualization tool when you have tons of jobs running in the background. 

Now, the progress bar will be printed in `sys.stdout`, I wonder that is it possible to add an argument to `TextProgressBar` to print the progress on `sys.stderr` or the other handler? 
Then, users can control when the progress bar is displayed. (I know that users can always write the wrapper to wrap `sys.stdout` to the logger but it seems to be a workaround.)

Thanks.



Discussion:

Resolving patch:
diff --git a/qiskit/tools/events/progressbar.py b/qiskit/tools/events/progressbar.py
--- a/qiskit/tools/events/progressbar.py
+++ b/qiskit/tools/events/progressbar.py
@@ -109,12 +109,17 @@ def finished(self):
 class TextProgressBar(BaseProgressBar):
     """
     A simple text-based progress bar.
+
+    output_handler : the handler the progress bar should be written to, default
+                     is sys.stdout, another option is sys.stderr
     """
 
-    def __init__(self):
+    def __init__(self, output_handler=None):
         super().__init__()
         self._init_subscriber()
 
+        self.output_handler = output_handler if output_handler else sys.stdout
+
     def _init_subscriber(self):
         def _initialize_progress_bar(num_tasks):
             """ """
@@ -139,14 +144,14 @@ def start(self, iterations):
         self.iter = int(iterations)
         self.t_start = time.time()
         pbar = '-' * 50
-        sys.stdout.write('\r|%s| %s%s%s [%s]' %
-                         (pbar, 0, '/', self.iter, ''))
+        self.output_handler.write('\r|%s| %s%s%s [%s]' %
+                                  (pbar, 0, '/', self.iter, ''))
 
     def update(self, n):
         filled_length = int(round(50 * n / self.iter))
         pbar = u'█' * filled_length + '-' * (50 - filled_length)
         time_left = self.time_remaining_est(n)
-        sys.stdout.write('\r|%s| %s%s%s [%s]' % (pbar, n, '/', self.iter, time_left))
+        self.output_handler.write('\r|%s| %s%s%s [%s]' % (pbar, n, '/', self.iter, time_left))
         if n == self.iter:
-            sys.stdout.write('\n')
-        sys.stdout.flush()
+            self.output_handler.write('\n')
+        self.output_handler.flush()


Test patch:
Repository: Qiskit/qiskit

Issue:
center labels on histogram
<!-- ⚠️ 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?
can we center the x labels on the histogram when plotting more than one data set. 

<img width="692" alt="image" src="https://user-images.githubusercontent.com/15731369/52830969-c6d10b00-30a0-11e9-926d-bc2b9042c1c7.png">





Discussion:

Resolving patch:
diff --git a/qiskit/tools/visualization/_counts_visualization.py b/qiskit/tools/visualization/_counts_visualization.py
--- a/qiskit/tools/visualization/_counts_visualization.py
+++ b/qiskit/tools/visualization/_counts_visualization.py
@@ -74,6 +74,7 @@ def plot_histogram(data, figsize=(7, 5), color=None, number_to_keep=None,
         color = [color]
 
     all_pvalues = []
+    length = len(data)
     for item, execution in enumerate(data):
         if number_to_keep is not None:
             data_temp = dict(Counter(execution).most_common(number_to_keep))
@@ -107,7 +108,8 @@ def plot_histogram(data, figsize=(7, 5), color=None, number_to_keep=None,
                 rects.append(ax.bar(idx+item*width, val, width, label=label,
                                     color=color[item % len(color)],
                                     zorder=2))
-        ax.set_xticks(ind)
+        bar_center = (width / 2) * (length - 1)
+        ax.set_xticks(ind + bar_center)
         ax.set_xticklabels(labels_dict.keys(), fontsize=14, rotation=70)
         # attach some text labels
         if bar_labels:


Test patch:
Repository: Qiskit/qiskit

Issue:
Matplotlib circuit drawer raises IndexError if there is no gate in QuantumCircuit
<!-- ⚠️ 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**: 0.7.3
- **Python version**: 3.6.8
- **Operating system**: macOS HighSierra

### What is the current behavior?

If I try to draw a quantum circuit without any gate, the mpl drawer raises IndexError. The text drawer does not have this issue.

### Steps to reproduce the problem

```
# sample.py
from qiskit import QuantumCircuit, QuantumRegister
qr = QuantumRegister(1)
qc = QuantumCircuit(qr)
print(qc)
qc.draw(filename='output.pdf', output='mpl')
```

```
$ python sample.py
         
q0_0: |0>
         
Traceback (most recent call last):
  File "c.py", line 5, in <module>
    qc.draw(filename='output.pdf', output='mpl')
  File "/Users/ima/envs/vqe2/lib/python3.6/site-packages/qiskit/circuit/quantumcircuit.py", line 353, in draw
    reverse_bits=reverse_bits)
  File "/Users/ima/envs/vqe2/lib/python3.6/site-packages/qiskit/tools/visualization/_circuit_visualization.py", line 237, in circuit_drawer
    reverse_bits=reverse_bits)
  File "/Users/ima/envs/vqe2/lib/python3.6/site-packages/qiskit/tools/visualization/_circuit_visualization.py", line 577, in _matplotlib_circuit_drawer
    return qcd.draw(filename)
  File "/Users/ima/envs/vqe2/lib/python3.6/site-packages/qiskit/tools/visualization/_matplotlib.py", line 343, in draw
    self._draw_ops(verbose)
  File "/Users/ima/envs/vqe2/lib/python3.6/site-packages/qiskit/tools/visualization/_matplotlib.py", line 466, in _draw_ops
    next_ops.pop(0)
IndexError: pop from empty list
```

### What is the expected behavior?

No IndexError.

### Suggested solutions

Check whether `next_ops` is empty or not.



Discussion:
@nkanazawa1989 Can you check it?

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
@@ -462,7 +462,8 @@ def _draw_ops(self, verbose=False):
         _wide_gate = 'u2 u3 cu2 cu3'.split()
         _barriers = {'coord': [], 'group': []}
         next_ops = self._ops.copy()
-        next_ops.pop(0)
+        if next_ops:
+            next_ops.pop(0)
         this_anc = 0
 
         #
@@ -682,8 +683,12 @@ def _draw_ops(self, verbose=False):
         #
         # adjust window size and draw horizontal lines
         #
-        max_anc = max([q_anchors[ii].get_index() for ii in self._qreg_dict])
-        n_fold = (max_anc - 1) // self._style.fold
+        anchors = [q_anchors[ii].get_index() for ii in self._qreg_dict]
+        if anchors:
+            max_anc = max(anchors)
+        else:
+            max_anc = 0
+        n_fold = max(0, max_anc - 1) // self._style.fold
         # window size
         if max_anc > self._style.fold > 0:
             self._cond['xmax'] = self._style.fold + 1


Test patch:
Repository: Qiskit/qiskit

Issue:
Registers cannot be index with negative integers or slices
<!-- ⚠️ 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?

It would be nice if the behavior mimicked python lists more. e.g.

```python
q = QuantumRegister(5)
q[-1]
q[-3:-1]
etc.
```


Discussion:
I support this issue. Probably the getitem method needs to be enhanced to support negative indices.

Resolving patch:
diff --git a/qiskit/circuit/register.py b/qiskit/circuit/register.py
--- a/qiskit/circuit/register.py
+++ b/qiskit/circuit/register.py
@@ -80,6 +80,8 @@ def __getitem__(self, key):
         """
         if not isinstance(key, (int, slice, list)):
             raise QiskitError("expected integer or slice index into register")
+        if isinstance(key, int) and key < 0:
+            key = self.size + key
         self.check_range(key)
         if isinstance(key, slice):
             return [(self, ind) for ind in range(*key.indices(len(self)))]


Test patch:
diff --git a/test/python/circuit/test_circuit_registers.py b/test/python/circuit/test_circuit_registers.py
--- a/test/python/circuit/test_circuit_registers.py
+++ b/test/python/circuit/test_circuit_registers.py
@@ -41,6 +41,15 @@ def test_cregs(self):
         self.assertEqual(cr1.size, 10)
         self.assertEqual(type(cr1), ClassicalRegister)
 
+    def test_negative_index(self):
+        """Test indexing from the back
+        """
+        qr1 = QuantumRegister(10, "q")
+        cr1 = ClassicalRegister(10, "c")
+        self.assertEqual(qr1[-1], (qr1, 9))
+        self.assertEqual(qr1[-3:-1], [(qr1, 7), (qr1, 8)])
+        self.assertEqual(len(cr1[0:-2]), 8)
+
     def test_reg_equal(self):
         """Test getting quantum registers from circuit.
         """