



'''simple docstring'''




import numpy as np
import qiskit



def       a     (					lowerCamelCase__ = 8		, lowerCamelCase__ = None       ):
			'''simple docstring'''





			A_      :		Tuple      =	np.random.default_rng(seed=_UpperCAmelCase       )

			# Roughly 25% of the qubits will contribute to the key.
			# So we take more than we need.
			A_      :		int      =	6 * key_len
			# Measurement basis for Alice's qubits.
			A_      :		str      =	rng.integers(2		, size=_UpperCAmelCase       )
			# The set of states Alice will prepare.
			A_      :		Optional[int]      =	rng.integers(2		, size=_UpperCAmelCase       )
			# Measurement basis for Bob's qubits.
			A_      :		List[Any]      =	rng.integers(2		, size=_UpperCAmelCase       )

			# Quantum Circuit to simulate BB84
			A_      :		Optional[int]      =	qiskit.QuantumCircuit(_UpperCAmelCase		, name="""BB84"""       )

			# Alice prepares her qubits according to rules above.
			for index, _ in enumerate(_UpperCAmelCase       ):
						if alice_state[index] == 1:
									bbaa_circ.x(_UpperCAmelCase       )
						if alice_basis[index] == 1:
									bbaa_circ.h(_UpperCAmelCase       )
			bbaa_circ.barrier()

			# Bob measures the received qubits according to rules above.
			for index, _ in enumerate(_UpperCAmelCase       ):
						if bob_basis[index] == 1:
									bbaa_circ.h(_UpperCAmelCase       )

			bbaa_circ.barrier()
			bbaa_circ.measure_all()

			# Simulate the quantum circuit.
			A_      :		Optional[Any]      =	qiskit.Aer.get_backend("""aer_simulator"""       )
			# We only need to run one shot because the key is unique.
			# Multiple shots will produce the same key.
			A_      :		Optional[int]      =	qiskit.execute(_UpperCAmelCase		, _UpperCAmelCase		, shots=1		, seed_simulator=_UpperCAmelCase       )
			# Returns the result of measurement.
			A_      :		Any      =	job.result().get_counts(_UpperCAmelCase       ).most_frequent()

			# Extracting the generated key from the simulation results.
			# Only keep measurement results where Alice and Bob chose the same basis.
			A_      :		str      =	''.join(
			    [
			        result_bit
			        for alice_basis_bit, bob_basis_bit, result_bit in zip(
			            _UpperCAmelCase		, _UpperCAmelCase		, _UpperCAmelCase       )
			        if alice_basis_bit == bob_basis_bit
			    ]       )

			# Get final key. Pad with 0 if too short, otherwise truncate.
			A_      :		List[Any]      =	gen_key[:key_len] if len(_UpperCAmelCase       ) >= key_len else gen_key.ljust(_UpperCAmelCase		, """0"""       )
			return key


if __name__ == "__main__":
						print(F"The generated key is : {bbaa(8, seed=0)}")
						from doctest import testmod

						testmod()




'''simple docstring'''





import json
import logging
import os
import sys
from time import time
from unittest.mock import patch

from transformers.testing_utils import TestCasePlus, require_torch_tpu


logging.basicConfig(level=logging.DEBUG)

A__    :   List[str]           =					logging.getLogger()





def   a_   (		_UpperCAmelCase    :      int				)    ->  Optional[int]:
      __snake_case :   List[str]													=    {}
      __snake_case :   List[str]													=    os.path.join(_UpperCAmelCase ,'all_results.json'				)
      if os.path.exists(_UpperCAmelCase				):
            with open(_UpperCAmelCase ,'r'				) as f:
                  __snake_case :   Dict													=    json.load(_UpperCAmelCase				)
      else:
            raise ValueError(f'''can\'t find {path}'''				)
      return results


A__    :   Dict           =					logging.StreamHandler(sys.stdout)
logger.addHandler(stream_handler)





@require_torch_tpu
class  snake_case__						(    SCREAMING_SNAKE_CASE_				):
 def A_   (   self						:							Optional[Any]  )      ->   List[str]:







       '''simple docstring'''
       import xla_spawn

       __snake_case :   int													=    self.get_auto_remove_tmp_dir()
       __snake_case :   Tuple													=    f'''
            ./examples/pytorch/text-classification/run_glue.py
            --num_cores=8
            ./examples/pytorch/text-classification/run_glue.py
            --model_name_or_path distilbert-base-uncased
            --output_dir {tmp_dir}
            --overwrite_output_dir
            --train_file ./tests/fixtures/tests_samples/MRPC/train.csv
            --validation_file ./tests/fixtures/tests_samples/MRPC/dev.csv
            --do_train
            --do_eval
            --debug tpu_metrics_debug
            --per_device_train_batch_size=2
            --per_device_eval_batch_size=1
            --learning_rate=1e-4
            --max_steps=10
            --warmup_steps=2
            --seed=42
            --max_seq_length=128
            '''.split()

       with patch.object(__a      ,     'argv'      ,     __a  ):
             __snake_case :   Tuple													=    time()
             xla_spawn.main()
             __snake_case :   Optional[int]													=    time()

             __snake_case :   List[Any]													=    get_results(__a  )
             self.assertGreaterEqual(result['eval_accuracy']      ,     0.7_5  )

             # Assert that the script takes less than 500 seconds to make sure it doesn't hang.
             self.assertLess(end - start      ,     500  )





 def A_   (   self						:							List[str]  )      ->   Optional[int]:







       '''simple docstring'''
       import xla_spawn

       __snake_case :   Optional[Any]													=    '\n            ./tests/test_trainer_tpu.py\n            --num_cores=8\n            ./tests/test_trainer_tpu.py\n            '.split()
       with patch.object(__a      ,     'argv'      ,     __a  ):
             xla_spawn.main()



