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

Issue:
Unnecessary result insertion into ran qobj
When running a qobj in qiskit there is a side effect of adding the results class to the input qobj. If run is called multiple times this happens recursively.

## Expected Behavior

The input qobj to the `QuantumProgram.run` function should not be modified.

## Current Behavior

The qobj is modified by inserting a `'result'` field containing a circular reference to the original qobj with `qobj['result']._qobj`. 

## Possible Solution

I traced this problem to the `_jobprocessor.JobProcessor._job_done_callback` function: Line 106 `self.futures[future]['result'] = result` should be removed. All current tests pass after removing this line.

## Steps to Reproduce (for bugs)

Here is an example

```python
import qiskit as qk
qr = qk.QuantumRegister('qr', 1)
cr = qk.ClassicalRegister('cr', 1)
c = qk.QuantumCircuit(qr, cr)
c.x(qr)
c.measure(qr, cr)
qp = qk.QuantumProgram()
qp.add_circuit('test', c)
```
Executing this example circuit we have
```python
qobj = qp.compile('test', backend='local_qasm_simulator')
result = qp.run(qobj)    
   
# Following prints True
print(qobj['id'] == result._qobj['id'])

# Following prints True, False
print('result' in qobj,
      'result' in result._qobj)
``` 

To see recursion:
```python
qobj = qp.compile('test', backend='local_qasm_simulator')
result = qp.run(qobj)        
result = qp.run(qobj)

# Following prints True, True
print(qobj['id'] == result._qobj['id'], 
      qobj['id'] == result._qobj['result']._qobj['id'])

# Following prints True, True, False
print('result' in qobj, 
      'result' in result._qobj, 
      'result' in result._qobj['result']._qobj)
```


Discussion:

Resolving patch:
diff --git a/qiskit/_jobprocessor.py b/qiskit/_jobprocessor.py
--- a/qiskit/_jobprocessor.py
+++ b/qiskit/_jobprocessor.py
@@ -103,7 +103,6 @@ def _job_done_callback(self, future):
                             future.qobj)
         with self.lock:
             logger.debug("Have a Result: %s", pprint.pformat(result))
-            self.futures[future]['result'] = result
             self.jobs_results.append(result)
             if self.num_jobs != 0:
                 self.num_jobs -= 1


Test patch:
Repository: Qiskit/qiskit

Issue:
JSONBackend expects basis_gates as a list, receives a string
As _openquantumcompiler.dag2json has been reintroduced  by commit https://github.com/QISKit/qiskit-sdk-py/commit/77ffd963798e57b0f0650628048dd2ac19a30a16 it is not compatible with JSONBackend as it expects to get as argument a list of basis gates, not a comma separated string.

A possible solution is to substitute 
https://github.com/QISKit/qiskit-sdk-py/blob/07b2485cb0c05d3649de83ece9be1c50c3aff979/qiskit/_openquantumcompiler.py#L36 
by 
``    return DagUnroller(dag_circuit, JsonBackend(basis_gates.split(",")).execute()``


Discussion:

Resolving patch:
diff --git a/qiskit/_openquantumcompiler.py b/qiskit/_openquantumcompiler.py
--- a/qiskit/_openquantumcompiler.py
+++ b/qiskit/_openquantumcompiler.py
@@ -33,4 +33,4 @@ def dag2json(dag_circuit, basis_gates='u1,u2,u3,cx,id'):
     Returns:
         json: the json version of the dag
     """
-    return DagUnroller(dag_circuit, JsonBackend(basis_gates)).execute()
+    return DagUnroller(dag_circuit, JsonBackend(basis_gates.split(","))).execute()


Test patch:
Repository: Qiskit/qiskit

Issue:
load_qasm_{file, string} converts `t` gate inappropriately
### Informations

- **QISKit (Python SDK) version**: 0.5.3
- **Python version**: 3.6.5
- **Operating system**: macOS 10.13.5

### What is the current behavior?

`load_qasm_file` and `load_qasm_string` converts `t` gate into `tdg`.


### Steps to reproduce the problem

Run the following script.
```
from qiskit.wrapper import load_qasm_string

qasm_string="""
OPENQASM 2.0;
include "qelib1.inc";
qreg q[1];
creg c[1];
t q[0];
"""
circuit = load_qasm_string(qasm_string, name='tmp', basis_gates='t')
print(circuit.qasm())
```

The result is as follows.
```
OPENQASM 2.0;
include "qelib1.inc";
qreg q[1];
creg c[1];
tdg q[0];
```

### What is the expected behavior?

Do not change `t` gate.

### Suggested solutions

I have no idea.



Discussion:

Resolving patch:
diff --git a/qiskit/unroll/_circuitbackend.py b/qiskit/unroll/_circuitbackend.py
--- a/qiskit/unroll/_circuitbackend.py
+++ b/qiskit/unroll/_circuitbackend.py
@@ -235,7 +235,7 @@ def start_gate(self, name, args, qubits, nested_scope=None):
                    "rz": [(1, 1), lambda x: self.circuit.rz(x[0][0], x[1][0])],
                    "s": [(0, 1), lambda x: self.circuit.s(x[1][0])],
                    "sdg": [(0, 1), lambda x: self.circuit.s(x[1][0]).inverse()],
-                   "t": [(0, 1), lambda x: self.circuit.t(x[1][0]).inverse()],
+                   "t": [(0, 1), lambda x: self.circuit.t(x[1][0])],
                    "tdg": [(0, 1), lambda x: self.circuit.t(x[1][0]).inverse()],
                    "u1": [(1, 1), lambda x: self.circuit.u1(x[0][0], x[1][0])],
                    "u2": [(2, 1), lambda x: self.circuit.u2(x[0][0], x[0][1],


Test patch:
Repository: Qiskit/qiskit

Issue:
Inverting a quantum circuit
<!--- Provide a general summary of the issue in the Title above -->
I can create a circuit for generating arbitrary quantum superposition with `initialize()` function. 
I know there is a call to `inverse()` function within the `initialize()`. So, it should be easy to do that (just do not execute that call to `inverse()`). 

But I cannot find a way to inverse a circuit I obtain from the `initialize()` nor for any quantum circuit that I have. 


## Expected Behavior
<!--- If you're describing a bug, tell us what should happen -->
<!--- If you're suggesting a change/improvement, tell us how it should work -->
Access to `inverse()` function, or, at least an example of using `CompositeGate` that supports operation to invert the gate.

## Current Behavior
<!--- If describing a bug, tell us what happens instead of the expected behavior -->
<!--- If suggesting a change/improvement, explain the difference from current behavior -->
There seems to be no test case and examples of using `CompositeGate` from the `initialize()`. 

## Possible Solution
<!--- Not obligatory, but suggest a fix/reason for the bug, -->
<!--- or ideas how to implement the addition or change -->

## Steps to Reproduce (for bugs)
<!--- Provide a link to a live example, or an unambiguous set of steps to -->
<!--- reproduce this bug. Include code to reproduce, if relevant -->
1.
2.
3.
4.

## Context
<!--- How has this issue affected you? What are you trying to accomplish? -->
<!--- Providing context helps us come up with a solution that is most useful in the real world -->

## Your Environment
<!--- Include as many relevant details about the environment you experienced the bug in -->
* Version used: 0.5.2
* Environment name and version (e.g. Python 3.6.1): Python 3.6.x
* Operating System and version: MacOSX


Discussion:

Resolving patch:
diff --git a/qiskit/extensions/quantum_initializer/_initializer.py b/qiskit/extensions/quantum_initializer/_initializer.py
--- a/qiskit/extensions/quantum_initializer/_initializer.py
+++ b/qiskit/extensions/quantum_initializer/_initializer.py
@@ -75,6 +75,9 @@ def __init__(self, param, arg, circ=None):
         # invert the circuit to create the desired vector from zero (assuming
         # the qubits are in the zero state)
         self.inverse()
+        # do not set the inverse flag, as this is the actual initialize gate
+        # we just used inverse() as a method to obtain it
+        self.inverse_flag = False
 
     def nth_qubit_from_least_sig_qubit(self, nth):
         """
@@ -91,7 +94,7 @@ def nth_qubit_from_least_sig_qubit(self, nth):
 
     def reapply(self, circ):
         """Reapply this gate to the corresponding qubits in circ."""
-        circ.initialize(self.param, self.arg)
+        self._modifiers(circ.initialize(self.param, self.arg))
 
     def gates_to_uncompute(self):
         """


Test patch:
Repository: Qiskit/qiskit

Issue:
Gate cswap does not behave as expected
<!-- ⚠️ If you do not respect this template, your issue will be closed -->
<!-- ⚠️ Make sure to browse the opened and closed issues -->

### Informations

- **Qiskit (Python SDK) version**:  0.5.6
- **Python version**: 3.6.5
- **Operating system**: Docker container based on Ubuntu 18.04, host Fedora 28 (Linux 4.17.4)

### What is the current behavior?

The CSWAP gate behaves as a CCX gate

### Steps to reproduce the problem

```python
q = QuantumRegister(3, 'q')
c = ClassicalRegister(3, 'c')
circuit = QuantumCircuit(q, c)
circuit.h(q[0])
circuit.x(q[1])
circuit.cswap(q[0], q[1], q[2])
    
circuit.measure(q, c)
    
job = execute(circuit, 'local_qasm_simulator')
print(job.result().get_counts(circuit))
# {'010': 522, '111': 502}
```

### What is the expected behavior?

The output states of that code snippet should be `010` and `101`.

### Suggested solutions
The issue seems to be [here](https://github.com/Qiskit/qiskit-terra/blob/909728c61d094eaf33a706d513e9a84a53370a5a/qiskit/extensions/standard/cswap.py#L24).



Discussion:

Resolving patch:
diff --git a/qiskit/extensions/standard/cswap.py b/qiskit/extensions/standard/cswap.py
--- a/qiskit/extensions/standard/cswap.py
+++ b/qiskit/extensions/standard/cswap.py
@@ -21,7 +21,7 @@ class FredkinGate(Gate):
 
     def __init__(self, ctl, tgt1, tgt2, circ=None):
         """Create new Fredkin gate."""
-        super().__init__("ccx", [], [ctl, tgt1, tgt2], circ)
+        super().__init__("cswap", [], [ctl, tgt1, tgt2], circ)
 
     def qasm(self):
         """Return OPENQASM string."""


Test patch:
diff --git a/test/python/test_extensions_standard.py b/test/python/test_extensions_standard.py
--- a/test/python/test_extensions_standard.py
+++ b/test/python/test_extensions_standard.py
@@ -169,7 +169,7 @@ def test_crz_invalid(self):
 
     def test_cswap(self):
         self.circuit.cswap(self.q[0], self.q[1], self.q[2])
-        qasm_txt = 'cx q[2],q[1];\nccx q[0],q[1],q[2];\ncx q[2],q[1];'
+        qasm_txt = 'cswap q[0],q[1],q[2];'
         self.assertResult(FredkinGate, qasm_txt, qasm_txt)
 
     def test_cswap_invalid(self):
@@ -733,19 +733,6 @@ def test_rzz(self):
         c.rzz(pi/2, self.q[1], self.q[2])
         self.assertResult(RZZGate, 'rzz(pi/2) q[1],q[2];', 'rzz(-pi/2) q[1],q[2];')
 
-    def assertResult(self, t, qasm_txt, qasm_txt_):
-        """
-        t: type
-        qasm_txt: qasm representation
-        qasm_txt_: qasm representation of inverse
-        """
-        c = self.circuit
-        self.assertRaises(QISKitError, c.z, self.c[0])
-        self.assertRaises(QISKitError, c.z, self.c)
-        self.assertRaises(QISKitError, c.z, (self.q, 3))
-        self.assertRaises(QISKitError, c.z, (self.q, 'a'))
-        self.assertRaises(QISKitError, c.z, 0)
-
     def test_z_reg(self):
         qasm_txt = 'z q[0];\nz q[1];\nz q[2];'
         instruction_set = self.circuit.z(self.q)
Repository: Qiskit/qiskit

Issue:
Can not combine or extend a circuit which is built with CompositeGate
<!-- ⚠️ If you do not respect this template, your issue will be closed -->
<!-- ⚠️ Make sure to browse the opened and closed issues -->

### Informations
Can not use `+` operator to combine or extend a circuit.
- **Qiskit (Python SDK) version**: 0.5.7
- **Python version**: 3.6.5
- **Operating system**: macOS 10.13

### What is the current behavior?
Program crash
```
Traceback (most recent call last):
  File "qiskit_acqua/svm/svm_qkernel.py", line 327, in <module>
    a.run()
  File "qiskit_acqua/svm/svm_qkernel.py", line 306, in run
    self.train(self.training_dataset, self.class_labels)
  File "qiskit_acqua/svm/svm_qkernel.py", line 182, in train
    kernel_matrix = self.construct_kernel_matrix(training_points)
  File "qiskit_acqua/svm/svm_qkernel.py", line 158, in construct_kernel_matrix
    circuit = self.inner_product(self.feature_extraction, self.num_qubits, x1, x2)
  File "qiskit_acqua/svm/svm_qkernel.py", line 124, in inner_product
    trial_circuit += feature_extractor.construct_circuit(x1, q)
  File "/Users/rchen/.pythonVirtualEnv/quantum-dev/lib/python3.6/site-packages/qiskit/_quantumcircuit.py", line 173, in __iadd__
    return self.extend(rhs)
  File "/Users/rchen/.pythonVirtualEnv/quantum-dev/lib/python3.6/site-packages/qiskit/_quantumcircuit.py", line 164, in extend
    gate.reapply(self)
AttributeError: 'CompositeGate' object has no attribute 'reapply'
```

### Steps to reproduce the problem

```python
from qiskit import CompositeGate, QuantumCircuit, QuantumRegister
from qiskit.extensions.standard.u1 import U1Gate

q = QuantumRegister(2)
composite_gate = CompositeGate("second_order_expansion", [], [q[i] for i in range(2)])
composite_gate._attach(U1Gate(0, q[0]))
qc1 = QuantumCircuit(q)
qc1._attach(composite_gate)
qc2 = QuantumCircuit(q)
qc2 = qc2 + qc1
```


### What is the expected behavior?

qc2 is the copy of qc1

### Suggested solutions

add `reapply` method in the CompositeGate.
Like
```python
def reapply(self, circ):
    """Reapply this gate to corresponding qubits in circ."""
    for gate in self.data:
        gate.reapply(circ)
```



Discussion:

Resolving patch:
diff --git a/qiskit/_compositegate.py b/qiskit/_compositegate.py
--- a/qiskit/_compositegate.py
+++ b/qiskit/_compositegate.py
@@ -101,6 +101,11 @@ def inverse(self):
         self.inverse_flag = not self.inverse_flag
         return self
 
+    def reapply(self, circ):
+        """Reapply this gate to corresponding qubits in circ."""
+        for gate in self.data:
+            gate.reapply(circ)
+
     def q_if(self, *qregs):
         """Add controls to this gate."""
         self.data = [gate.q_if(qregs) for gate in self.data]


Test patch:
Repository: Qiskit/qiskit

Issue:
`backend.jobs()` does not show jobs from that particular 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**: 0.5.7
- **Python version**: 3.7
- **Operating system**: MacOS


### Steps to reproduce the problem

```python
from qiskit import *
import Qconfig
register(Qconfig.APItoken)
backend_5 = get_backend('ibmq_5_tenerife')
backend_16 = get_backend('ibmq_16_rueschlikon')
jobs_5 = backend_5.jobs(limit=10)
jobs_16 = backend_16.jobs(limit=10)

for job in jobs_5:
    print(job.id)

for job in jobs_16:
    print(job.id)
```

Both print the same set of jobs.


### What is the expected behavior?
Different backends should report different jobs.

`backend.jobs()` does not show jobs from that particular 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**: 0.5.7
- **Python version**: 3.7
- **Operating system**: MacOS


### Steps to reproduce the problem

```python
from qiskit import *
import Qconfig
register(Qconfig.APItoken)
backend_5 = get_backend('ibmq_5_tenerife')
backend_16 = get_backend('ibmq_16_rueschlikon')
jobs_5 = backend_5.jobs(limit=10)
jobs_16 = backend_16.jobs(limit=10)

for job in jobs_5:
    print(job.id)

for job in jobs_16:
    print(job.id)
```

Both print the same set of jobs.


### What is the expected behavior?
Different backends should report different jobs.



Discussion:

Resolving patch:
diff --git a/qiskit/backends/ibmq/ibmqbackend.py b/qiskit/backends/ibmq/ibmqbackend.py
--- a/qiskit/backends/ibmq/ibmqbackend.py
+++ b/qiskit/backends/ibmq/ibmqbackend.py
@@ -188,7 +188,7 @@ def jobs(self, limit=50, skip=0, status=None, db_filter=None):
             IBMQBackendValueError: status keyword value unrecognized
         """
         backend_name = self.configuration['name']
-        api_filter = {}
+        api_filter = {'backend.name': backend_name}
         if status:
             if isinstance(status, str):
                 status = JobStatus[status]
@@ -209,12 +209,9 @@ def jobs(self, limit=50, skip=0, status=None, db_filter=None):
                                             'in job filter')
             api_filter.update(this_filter)
         if db_filter:
-            # filter ignores backend_name filter so we need to set it
-            api_filter['backend.name'] = backend_name
             # status takes precendence over db_filter for same keys
             api_filter = {**db_filter, **api_filter}
         job_info_list = self._api.get_jobs(limit=limit, skip=skip,
-                                           backend=backend_name,
                                            filter=api_filter)
         job_list = []
         for job_info in job_info_list:


Test patch:
Repository: Qiskit/qiskit

Issue:
hidden exception during job submission
<!-- ⚠️ 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?
If the API encounters an exception during job submission before a job is actually submitted to the server IBMQJob._future.result() returns None but self._future_captured_exception is not raised. Instead 'error' is checked for in None which raises a different exception and hides the root one inside IBMQuantumExperience.


### Steps to reproduce the problem



### What is the expected behavior?



### Suggested solutions
raise self._future_captured_exception for this case




Discussion:

Resolving patch:
diff --git a/qiskit/backends/ibmq/ibmqjob.py b/qiskit/backends/ibmq/ibmqjob.py
--- a/qiskit/backends/ibmq/ibmqjob.py
+++ b/qiskit/backends/ibmq/ibmqjob.py
@@ -421,11 +421,14 @@ def _wait_for_submission(self, timeout=60):
                 raise JobError("You have to submit before asking for status or results!")
             try:
                 submit_info = self._future.result(timeout=timeout)
+                if self._future_captured_exception is not None:
+                    # pylint can't see if catch of None type
+                    # pylint: disable=raising-bad-type
+                    raise self._future_captured_exception
             except TimeoutError as ex:
                 raise JobTimeoutError(
                     "Timeout waiting for the job being submitted: {}".format(ex)
                 )
-
             if 'error' in submit_info:
                 self._status = JobStatus.ERROR
                 self._api_error_msg = str(submit_info['error'])


Test patch:
Repository: Qiskit/qiskit

Issue:
Interactive Qsphere shows black vectors
<!-- ⚠️ If you do not respect this template, your issue will be closed -->
<!-- ⚠️ Make sure to browse the opened and closed issues -->

### What is the current behavior?
The Qsphere vectors can be black becuse phase angle is negative

### What is the expected behavior?
All vectors must be on a range of colors according next image:
![image](https://user-images.githubusercontent.com/1753426/44908490-f28f4d00-ad1b-11e8-9173-73a3ab25290f.png)


### Suggested solutions
Modify phase formula to get (always) positive angles.




Discussion:

Resolving patch:
diff --git a/qiskit/tools/visualization/interactive/_iplot_qsphere.py b/qiskit/tools/visualization/interactive/_iplot_qsphere.py
--- a/qiskit/tools/visualization/interactive/_iplot_qsphere.py
+++ b/qiskit/tools/visualization/interactive/_iplot_qsphere.py
@@ -113,7 +113,7 @@ def iplot_qsphere(rho, options=None):
 
                 # get prob and angle - prob will be shade and angle color
                 prob = np.real(np.dot(state[i], state[i].conj()))
-                angles = np.angle(state[i])
+                angles = (np.angle(state[i]) + 2 * np.pi) % (2 * np.pi)
                 qpoint = {
                     'x': xvalue,
                     'y': yvalue,


Test patch:
Repository: Qiskit/qiskit

Issue:
Make interactive visualizations default for Jupyter
<!-- ⚠️ 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?
The interactive visualizations contributed in PR #765 are much better than the static ones, and should be default when the environment is a Jupyter notebook. This is related to Epic #707 for providing better jupyter tools.

Several issues must be solved first:
- These visualizations need internet connection. Can we eliminate that?
- The interface of the static and interactive visualizations are all the same, except for `plot_histogram` vs `iplot_histogram`. These should be made similar for consistency. But the interactive visualization is able to plot multiple histograms in one plot.
- How "heavy" is it to run these interactive visualizations? I hear my laptop fan.


Discussion:
1. Commented on #805, the visual library must be online due Jupyter limitations. 
2. All visualizations (except histogram) are working in the same way than the static visualizations.
3. Next week a new version of the JS library will be released (it will require less CPU/GPU usage).
I am closing this Issue as it seems there is no way to run the interactive visualizations offline, thus making it impossible to have them as default.
Reopening this to rethink for 0.6 release:
1. Can we default to interactive visualizations if the environment is Jupyter AND there is internet connection?
2. We have to rework the static histogram plot to show multiple histograms in one graph. This way we can make its signature consistent with the interactive one.

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
@@ -7,7 +7,18 @@
 
 """Main QISKit visualization methods."""
 
+import sys
+
 from ._circuit_visualization import circuit_drawer, plot_circuit, generate_latex_source,\
     latex_circuit_drawer, matplotlib_circuit_drawer, qx_color_scheme
-from ._state_visualization import plot_state
 from ._counts_visualization import plot_histogram
+
+if ('ipykernel' in sys.modules) and ('spyder' not in sys.modules):
+    import requests
+    if requests.get(
+            'https://qvisualization.mybluemix.net/').status_code == 200:
+        from .interactive._iplot_state import iplot_state as plot_state
+    else:
+        from ._state_visualization import plot_state
+else:
+    from ._state_visualization import plot_state


Test patch: