
"""simple docstring"""

import contextlib
import os
import sqlitea

import pytest

from datasets import Dataset, Features, Value
from datasets.io.sql import SqlDatasetReader, SqlDatasetWriter

from ..utils import assert_arrow_memory_doesnt_increase, assert_arrow_memory_increases, require_sqlalchemy






def 							A		(       snake_case   :Any       ,      snake_case   :Dict	)   ->			str:
 assert isinstance(__UpperCamelCase       ,      __UpperCamelCase	)
 assert dataset.num_rows == 4
 assert dataset.num_columns == 3
 assert dataset.column_names == ["col_1", "col_2", "col_3"]
 for feature, expected_dtype in expected_features.items():
  assert dataset.features[feature].dtype == expected_dtype






@require_sqlalchemy
@pytest.mark.parametrize('keep_in_memory'       ,      [False, True]	)
def 							A		(       snake_case   :Optional[Any]       ,      snake_case   :List[Any]       ,      snake_case   :Optional[Any]       ,      snake_case   :Optional[Any]	)   ->			str:
 __UpperCamelCase       						= tmp_path / 'cache'
 __UpperCamelCase       						= {'col_1': 'string', 'col_2': 'int64', 'col_3': 'float64'}
 with assert_arrow_memory_increases() if keep_in_memory else assert_arrow_memory_doesnt_increase():
  __UpperCamelCase       						= SqlDatasetReader(
      'dataset'       ,      'sqlite:///' + sqlite_path       ,      cache_dir=__UpperCamelCase       ,      keep_in_memory=__UpperCamelCase	).read()
 _check_sql_dataset(__UpperCamelCase       ,      __UpperCamelCase	)






@require_sqlalchemy
@pytest.mark.parametrize(
    'features'       ,      [
        None,
        {'col_1': 'string', 'col_2': 'int64', 'col_3': 'float64'},
        {'col_1': 'string', 'col_2': 'string', 'col_3': 'string'},
        {'col_1': 'int32', 'col_2': 'int32', 'col_3': 'int32'},
        {'col_1': 'float32', 'col_2': 'float32', 'col_3': 'float32'},
    ]       ,      )
def 							A		(       snake_case   :Tuple       ,      snake_case   :int       ,      snake_case   :Union[str, Any]       ,      snake_case   :Union[str, Any]	)   ->			Union[str, Any]:
 __UpperCamelCase       						= tmp_path / 'cache'
 __UpperCamelCase       						= {'col_1': 'string', 'col_2': 'int64', 'col_3': 'float64'}
 __UpperCamelCase       						= features.copy() if features else default_expected_features
 __UpperCamelCase       						= (
     Features({feature: Value(__UpperCamelCase	) for feature, dtype in features.items()}	) if features is not None else None
 )
 __UpperCamelCase       						= SqlDatasetReader('dataset'       ,      'sqlite:///' + sqlite_path       ,      features=__UpperCamelCase       ,      cache_dir=__UpperCamelCase	).read()
 _check_sql_dataset(__UpperCamelCase       ,      __UpperCamelCase	)






def 							A		(       snake_case   :Optional[Any]	)   ->			Union[str, Any]:
 with contextlib.closing(sqlitea.connect(__UpperCamelCase	)	) as con:
  __UpperCamelCase       						= con.cursor()
  cur.execute('SELECT * FROM dataset'	)
  for row in cur:
   yield row






@require_sqlalchemy
def 							A		(       snake_case   :Optional[int]       ,      snake_case   :List[Any]       ,      snake_case   :Optional[Any]	)   ->			Any:
 __UpperCamelCase       						= tmp_path / 'cache'
 __UpperCamelCase       						= os.path.join(__UpperCamelCase       ,      'tmp.sql'	)
 __UpperCamelCase       						= SqlDatasetReader('dataset'       ,      'sqlite:///' + sqlite_path       ,      cache_dir=__UpperCamelCase	).read()
 SqlDatasetWriter(__UpperCamelCase       ,      'dataset'       ,      'sqlite:///' + output_sqlite_path       ,      num_proc=1	).write()

 __UpperCamelCase       						= iter_sql_file(__UpperCamelCase	)
 __UpperCamelCase       						= iter_sql_file(__UpperCamelCase	)

 for rowa, rowa in zip(__UpperCamelCase       ,      __UpperCamelCase	):
  assert rowa == rowa






@require_sqlalchemy
def 							A		(       snake_case   :Dict       ,      snake_case   :int       ,      snake_case   :int	)   ->			Union[str, Any]:
 __UpperCamelCase       						= tmp_path / 'cache'
 __UpperCamelCase       						= os.path.join(__UpperCamelCase       ,      'tmp.sql'	)
 __UpperCamelCase       						= SqlDatasetReader('dataset'       ,      'sqlite:///' + sqlite_path       ,      cache_dir=__UpperCamelCase	).read()
 SqlDatasetWriter(__UpperCamelCase       ,      'dataset'       ,      'sqlite:///' + output_sqlite_path       ,      num_proc=2	).write()

 __UpperCamelCase       						= iter_sql_file(__UpperCamelCase	)
 __UpperCamelCase       						= iter_sql_file(__UpperCamelCase	)

 for rowa, rowa in zip(__UpperCamelCase       ,      __UpperCamelCase	):
  assert rowa == rowa






@require_sqlalchemy
def 							A		(       snake_case   :List[str]       ,      snake_case   :Union[str, Any]       ,      snake_case   :Any	)   ->			str:
 __UpperCamelCase       						= tmp_path / 'cache'
 __UpperCamelCase       						= os.path.join(__UpperCamelCase       ,      'tmp.sql'	)
 __UpperCamelCase       						= SqlDatasetReader('dataset'       ,      'sqlite:///' + sqlite_path       ,      cache_dir=__UpperCamelCase	).read()
 with pytest.raises(__UpperCamelCase	):
  SqlDatasetWriter(__UpperCamelCase       ,      'dataset'       ,      'sqlite:///' + output_sqlite_path       ,      num_proc=0	).write()





"""simple docstring"""

import string

import numpy






def 							A		(       snake_case   :int       ,      snake_case   :int	)   ->			int:
 return b if a == 0 else greatest_common_divisor(b % a       ,      snake_case	)

class __lowerCAmelCase	:
     lowercase		     =		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)
     lowercase		     =		numpy.vectorize(lambda __SCREAMING_SNAKE_CASE    : x % 36    )

     lowercase		     =		numpy.vectorize(__SCREAMING_SNAKE_CASE    )





     def __init__(			self			,  __UpperCAmelCase   ):

      '''simple docstring'''




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





     def 		UpperCAmelCase      (			self			,  __UpperCAmelCase   ):

      '''simple docstring'''




      return self.key_string.index(__UpperCAmelCase   )





     def 		UpperCAmelCase      (			self			,  __UpperCAmelCase   ):

      '''simple docstring'''




      return self.key_string[round(__UpperCAmelCase   )]





     def 		UpperCAmelCase      (			self   ):

      '''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(__UpperCAmelCase			,  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(__UpperCAmelCase   )





     def 		UpperCAmelCase      (			self			,  __UpperCAmelCase   ):

      '''simple docstring'''




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

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

      return "".join(__UpperCAmelCase   )





     def 		UpperCAmelCase      (			self			,  __UpperCAmelCase   ):

      '''simple docstring'''




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

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

      return encrypted





     def 		UpperCAmelCase      (			self   ):

      '''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(__UpperCAmelCase   )   )







     def 		UpperCAmelCase      (			self			,  __UpperCAmelCase   ):

      '''simple docstring'''




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

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

      return decrypted






def 							A		(       )   ->			None:
 __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(snake_case	):
  __UpperCamelCase       						= [int(snake_case	) for x in input().split()]
  hill_matrix.append(snake_case	)

 __UpperCamelCase       						= HillCipher(numpy.array(snake_case	)	)

 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(snake_case	)	)
 elif option == "2":
  __UpperCamelCase       						= input('What text would you like to decrypt?: '	)
  print('Your decrypted text is:'	)
  print(hc.decrypt(snake_case	)	)


if __name__ == "__main__":
      import doctest

      doctest.testmod()

      main()



