



import unittest

import numpy as np

from transformers import BertConfig, is_flax_available
from transformers.testing_utils import require_flax, slow

from ...test_modeling_flax_common import FlaxModelTesterMixin, floats_tensor, ids_tensor, random_attention_mask


if is_flax_available():
						from transformers.models.bert.modeling_flax_bert import (
						    FlaxBertForMaskedLM,
						    FlaxBertForMultipleChoice,
						    FlaxBertForNextSentencePrediction,
						    FlaxBertForPreTraining,
						    FlaxBertForQuestionAnswering,
						    FlaxBertForSequenceClassification,
						    FlaxBertForTokenClassification,
						    FlaxBertModel,
						)







class       __lowerCAmelCase   (      unittest.TestCase						):



			def __init__(						self       :  Tuple			,		A       :  Union[str, Any]			,		A       :  Union[str, Any]=13			,		A       :  List[Any]=7			,		A       :  int=True			,		A       :  List[str]=True			,		A       :  Dict=True			,		A       :  Union[str, Any]=True			,		A       :  Tuple=99			,		A       :  Tuple=32			,		A       :  Tuple=5			,		A       :  int=4			,		A       :  List[str]=37			,		A       :  Tuple="gelu"			,		A       :  int=0.1			,		A       :  Tuple=0.1			,		A       :  Any=5_12			,		A       :  int=16			,		A       :  Dict=2			,		A       :  Tuple=0.0_2			,		A       :  Dict=4			,		)       ->   Any:



						"""simple docstring"""






						_UpperCAmelCase			=       parent
						_UpperCAmelCase			=       batch_size
						_UpperCAmelCase			=       seq_length
						_UpperCAmelCase			=       is_training
						_UpperCAmelCase			=       use_attention_mask
						_UpperCAmelCase			=       use_token_type_ids
						_UpperCAmelCase			=       use_labels
						_UpperCAmelCase			=       vocab_size
						_UpperCAmelCase			=       hidden_size
						_UpperCAmelCase			=       num_hidden_layers
						_UpperCAmelCase			=       num_attention_heads
						_UpperCAmelCase			=       intermediate_size
						_UpperCAmelCase			=       hidden_act
						_UpperCAmelCase			=       hidden_dropout_prob
						_UpperCAmelCase			=       attention_probs_dropout_prob
						_UpperCAmelCase			=       max_position_embeddings
						_UpperCAmelCase			=       type_vocab_size
						_UpperCAmelCase			=       type_sequence_label_size
						_UpperCAmelCase			=       initializer_range
						_UpperCAmelCase			=       num_choices



			def    _lowerCamelCase	(						self       :  List[Any])       ->   Optional[int]:



						"""simple docstring"""






						_UpperCAmelCase			=       ids_tensor([self.batch_size, self.seq_length]			,		self.vocab_size)

						_UpperCAmelCase			=       None
						if self.use_attention_mask:
									_UpperCAmelCase			=       random_attention_mask([self.batch_size, self.seq_length])

						_UpperCAmelCase			=       None
						if self.use_token_type_ids:
									_UpperCAmelCase			=       ids_tensor([self.batch_size, self.seq_length]			,		self.type_vocab_size)

						_UpperCAmelCase			=       BertConfig(
						    vocab_size=self.vocab_size			,		hidden_size=self.hidden_size			,		num_hidden_layers=self.num_hidden_layers			,		num_attention_heads=self.num_attention_heads			,		intermediate_size=self.intermediate_size			,		hidden_act=self.hidden_act			,		hidden_dropout_prob=self.hidden_dropout_prob			,		attention_probs_dropout_prob=self.attention_probs_dropout_prob			,		max_position_embeddings=self.max_position_embeddings			,		type_vocab_size=self.type_vocab_size			,		is_decoder=A			,		initializer_range=self.initializer_range			,		)

						return config, input_ids, token_type_ids, attention_mask



			def    _lowerCamelCase	(						self       :  int)       ->   str:



						"""simple docstring"""






						_UpperCAmelCase			=       self.prepare_config_and_inputs()
						_UpperCAmelCase	,					_UpperCAmelCase	,					_UpperCAmelCase	,					_UpperCAmelCase			=       config_and_inputs
						_UpperCAmelCase			=       {'input_ids': input_ids, 'token_type_ids': token_type_ids, 'attention_mask': attention_mask}
						return config, inputs_dict



			def    _lowerCamelCase	(						self       :  Tuple)       ->   List[str]:



						"""simple docstring"""






						_UpperCAmelCase			=       self.prepare_config_and_inputs()
						_UpperCAmelCase	,					_UpperCAmelCase	,					_UpperCAmelCase	,					_UpperCAmelCase			=       config_and_inputs

						_UpperCAmelCase			=       True
						_UpperCAmelCase			=       floats_tensor([self.batch_size, self.seq_length, self.hidden_size])
						_UpperCAmelCase			=       ids_tensor([self.batch_size, self.seq_length]			,		vocab_size=2)

						return (
						    config,
						    input_ids,
						    attention_mask,
						    encoder_hidden_states,
						    encoder_attention_mask,
						)







@require_flax
class       __lowerCAmelCase   (      A    ,						unittest.TestCase						):
			UpperCamelCase        =					True

			UpperCamelCase        =					(
			    (
			        FlaxBertModel,
			        FlaxBertForPreTraining,
			        FlaxBertForMaskedLM,
			        FlaxBertForMultipleChoice,
			        FlaxBertForQuestionAnswering,
			        FlaxBertForNextSentencePrediction,
			        FlaxBertForSequenceClassification,
			        FlaxBertForTokenClassification,
			        FlaxBertForQuestionAnswering,
			    )
			    if is_flax_available()
			    else ()
			)



			def    _lowerCamelCase	(						self       :  str)       ->   Dict:



						"""simple docstring"""






						_UpperCAmelCase			=       FlaxBertModelTester(self)



			@slow
			def    _lowerCamelCase	(						self       :  Optional[Any])       ->   Optional[int]:



						"""simple docstring"""






						_UpperCAmelCase			=       FlaxBertModel.from_pretrained('bert-base-cased')
						_UpperCAmelCase			=       model(np.ones((1, 1)))
						self.assertIsNotNone(A)





import string

import numpy





def 							A     (					_UpperCAmelCase    :       int							,       _UpperCAmelCase    :       int   )    ->			int:







			'''simple docstring'''
			return b if a == 0 else greatest_common_divisor(b % a							,       _UpperCAmelCase   )







class       __lowerCAmelCase   :
			UpperCamelCase        =					string.ascii_uppercase + string.digits
			# This cipher takes alphanumerics into account
			# i.e. a total of 36 characters

			# take x and return x % len(key_string)
			UpperCamelCase        =					numpy.vectorize(lambda A						: x % 3_6						)

			UpperCamelCase        =					numpy.vectorize(A						)



			def __init__(						self       :  Tuple			,		A       :  numpy.ndarray)       ->   None:



						"""simple docstring"""






						_UpperCAmelCase			=       self.modulus(A)  # mod36 calc's on the encrypt key
						self.check_determinant()  # validate the determinant of the encryption key
						_UpperCAmelCase			=       encrypt_key.shape[0]



			def    _lowerCamelCase	(						self       :  str			,		A       :  str)       ->   int:



						"""simple docstring"""






						return self.key_string.index(A)



			def    _lowerCamelCase	(						self       :  Any			,		A       :  int)       ->   str:



						"""simple docstring"""






						return self.key_string[round(A)]



			def    _lowerCamelCase	(						self       :  Union[str, Any])       ->   None:



						"""simple docstring"""






						_UpperCAmelCase			=       round(numpy.linalg.det(self.encrypt_key))

						if det < 0:
									_UpperCAmelCase			=       det % len(self.key_string)

						_UpperCAmelCase			=       len(self.key_string)
						if greatest_common_divisor(A			,		len(self.key_string)) != 1:
									_UpperCAmelCase			=       (
									    F"determinant modular {req_l} of encryption key({det}) "
									    F"is not co prime w.r.t {req_l}.\nTry another key."
									)
									raise ValueError(A)



			def    _lowerCamelCase	(						self       :  Union[str, Any]			,		A       :  str)       ->   str:



						"""simple docstring"""






						_UpperCAmelCase			=       [char for char in text.upper() if char in self.key_string]

						_UpperCAmelCase			=       chars[-1]
						while len(A) % self.break_key != 0:
									chars.append(A)

						return "".join(A)



			def    _lowerCamelCase	(						self       :  Union[str, Any]			,		A       :  str)       ->   str:



						"""simple docstring"""






						_UpperCAmelCase			=       self.process_text(text.upper())
						_UpperCAmelCase			=       ''

						for i in range(0			,		len(A) - self.break_key + 1			,		self.break_key):
									_UpperCAmelCase			=       text[i : i + self.break_key]
									_UpperCAmelCase			=       [self.replace_letters(A) for char in batch]
									_UpperCAmelCase			=       numpy.array([vec]).T
									_UpperCAmelCase			=       self.modulus(self.encrypt_key.dot(A)).T.tolist()[
									    0
									]
									_UpperCAmelCase			=       ''.join(
									    self.replace_digits(A) for num in batch_encrypted)
									encrypted += encrypted_batch

						return encrypted



			def    _lowerCamelCase	(						self       :  Optional[Any])       ->   numpy.ndarray:



						"""simple docstring"""






						_UpperCAmelCase			=       round(numpy.linalg.det(self.encrypt_key))

						if det < 0:
									_UpperCAmelCase			=       det % len(self.key_string)
						_UpperCAmelCase			=       None
						for i in range(len(self.key_string)):
									if (det * i) % len(self.key_string) == 1:
												_UpperCAmelCase			=       i
												break

						_UpperCAmelCase			=       (
						    det_inv
						    * numpy.linalg.det(self.encrypt_key)
						    * numpy.linalg.inv(self.encrypt_key)
						)

						return self.to_int(self.modulus(A))



			def    _lowerCamelCase	(						self       :  Tuple			,		A       :  str)       ->   str:



						"""simple docstring"""






						_UpperCAmelCase			=       self.make_decrypt_key()
						_UpperCAmelCase			=       self.process_text(text.upper())
						_UpperCAmelCase			=       ''

						for i in range(0			,		len(A) - self.break_key + 1			,		self.break_key):
									_UpperCAmelCase			=       text[i : i + self.break_key]
									_UpperCAmelCase			=       [self.replace_letters(A) for char in batch]
									_UpperCAmelCase			=       numpy.array([vec]).T
									_UpperCAmelCase			=       self.modulus(decrypt_key.dot(A)).T.tolist()[0]
									_UpperCAmelCase			=       ''.join(
									    self.replace_digits(A) for num in batch_decrypted)
									decrypted += decrypted_batch

						return decrypted





def 							A     (					)    ->			None:







			'''simple docstring'''
			_UpperCAmelCase			=       int(input('Enter the order of the encryption key: '   )   )
			_UpperCAmelCase			=       []

			print('Enter each row of the encryption key with space separated integers'   )
			for _ in range(_UpperCAmelCase   ):
						_UpperCAmelCase			=       [int(_UpperCAmelCase   ) for x in input().split()]
						hill_matrix.append(_UpperCAmelCase   )

			_UpperCAmelCase			=       HillCipher(numpy.array(_UpperCAmelCase   )   )

			print('Would you like to encrypt or decrypt some text? (1 or 2)'   )
			_UpperCAmelCase			=       input('\n1. Encrypt\n2. Decrypt\n'   )
			if option == "1":
						_UpperCAmelCase			=       input('What text would you like to encrypt?: '   )
						print('Your encrypted text is:'   )
						print(hc.encrypt(_UpperCAmelCase   )   )
			elif option == "2":
						_UpperCAmelCase			=       input('What text would you like to decrypt?: '   )
						print('Your decrypted text is:'   )
						print(hc.decrypt(_UpperCAmelCase   )   )


if __name__ == "__main__":
							import doctest

							doctest.testmod()

							main()
