import sys, time, getpass
try:
    sys.path.append("../../") # go to parent dir
    import Qconfig
    qx_config = {
        "APItoken": Qconfig.APItoken,
        "url": Qconfig.config['url']}
    print('Qconfig loaded from %s.' % Qconfig.__file__)
except:
    APItoken = getpass.getpass('Please input your token and hit enter: ')
    qx_config = {
        "APItoken": APItoken,
        "url":"https://quantumexperience.ng.bluemix.net/api"}
    print('Qconfig.py not found in qiskit-tutorial directory; Qconfig loaded using user input.')

from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister, QISKitError
from qiskit import available_backends, execute, register, get_backend, compile

from qiskit.tools.visualization import plot_histogram
from pprint import pprint

available_backends()

available_backends(compact=False)

register(qx_config['APItoken'], qx_config['url'])
available_backends()

available_backends({'local': False})

available_backends({'local': True})

available_backends({'simulator': True})

available_backends({'simulator': False})

available_backends({'local': False, 'simulator': True})

available_backends({'operational': True, 'simulator': False})

available_backends(lambda x: x.configuration['n_qubits'] > 10 and not x.configuration['simulator'])

from qiskit import least_busy
least_busy(available_backends({'simulator': False}))

backends = []
for backend in available_backends():
    backends.append(get_backend(backend))
backends

for backend in backends:
    pprint(backend.status)

for backend in backends:
    pprint(backend.configuration)

for backend in backends:
    pprint(backend.parameters)

for backend in backends:
    pprint(backend.calibration)

qr = QuantumRegister(3)
cr = ClassicalRegister(3)
circuit = QuantumCircuit(qr, cr)
circuit.x(qr[0])
circuit.x(qr[1])
circuit.ccx(qr[0], qr[1], qr[2])
circuit.cx(qr[0], qr[1])
circuit.measure(qr, cr)

my_backend = get_backend('local_qasm_simulator')

qobj = compile(circuit, backend=my_backend, shots=1024)
job = my_backend.run(qobj)

job.status

job.done

result = job.result()
counts = result.get_counts()
print(counts)

device_name = least_busy(available_backends({'simulator': False}))
my_backend = get_backend(device_name)

qobj = compile(circuit, backend=my_backend, shots=1024)
job = my_backend.run(qobj)

lapse = 0
interval = 10
while not job.done:
    print('Status @ {} seconds'.format(interval * lapse))
    print(job.status)
    time.sleep(interval)
    lapse += 1
print(job.status)

job.id

result = job.result()
counts = result.get_counts()
print(counts)

plot_histogram(counts)