





'''simple docstring'''

import time
from dataclasses import dataclass
from multiprocessing import Pool
from unittest import TestCase
from unittest.mock import patch

import multiprocess
import numpy as np
import pytest

from datasets.utils.py_utils import (
    NestedDataStructure,
    asdict,
    iflatmap_unordered,
    map_nested,
    temp_seed,
    temporary_assignment,
    zip_dict,
)

from .utils import require_tf, require_torch





def 						UpperCamelCase    (							_lowerCamelCase : Any	):  # picklable for multiprocessing
    return x.sum()





def 						UpperCamelCase    (							_lowerCamelCase : Union[str, Any]	):  # picklable for multiprocessing
    return i + 1






@dataclass
class        UpperCAmelCase     :
 __lowercase       		=    42
 __lowercase       		=    42






class        UpperCAmelCase     (	UpperCamelCase__    ):
 def 					UpperCAmelCase_							(    self				:List[Any]							)->							Any:
     A__    =      {}
     A__    =      []
     A__    =      1
     A__    =      [1, 2]
     A__    =      {"a": 1, "b": 2}
     A__    =      {"a": [1, 2], "b": [3, 4]}
     A__    =      {"a": {"1": 1}, "b": 2}
     A__    =      {"a": 1, "b": 2, "c": 3, "d": 4}
     A__    =      {}
     A__    =      []
     A__    =      2
     A__    =      [2, 3]
     A__    =      {"a": 2, "b": 3}
     A__    =      {"a": [2, 3], "b": [4, 5]}
     A__    =      {"a": {"1": 2}, "b": 3}
     A__    =      {"a": 2, "b": 3, "c": 4, "d": 5}
     self.assertEqual(map_nested(lowercase_						,	lowercase_							)						,	lowercase_							)
     self.assertEqual(map_nested(lowercase_						,	lowercase_							)						,	lowercase_							)
     self.assertEqual(map_nested(lowercase_						,	lowercase_							)						,	lowercase_							)
     self.assertEqual(map_nested(lowercase_						,	lowercase_							)						,	lowercase_							)
     self.assertEqual(map_nested(lowercase_						,	lowercase_							)						,	lowercase_							)
     self.assertEqual(map_nested(lowercase_						,	lowercase_							)						,	lowercase_							)
     self.assertEqual(map_nested(lowercase_						,	lowercase_							)						,	lowercase_							)
     self.assertEqual(map_nested(lowercase_						,	lowercase_							)						,	lowercase_							)

     A__    =      2
     self.assertEqual(map_nested(lowercase_						,	lowercase_						,	num_proc=lowercase_							)						,	lowercase_							)
     self.assertEqual(map_nested(lowercase_						,	lowercase_						,	num_proc=lowercase_							)						,	lowercase_							)
     self.assertEqual(map_nested(lowercase_						,	lowercase_						,	num_proc=lowercase_							)						,	lowercase_							)
     self.assertEqual(map_nested(lowercase_						,	lowercase_						,	num_proc=lowercase_							)						,	lowercase_							)
     self.assertEqual(map_nested(lowercase_						,	lowercase_						,	num_proc=lowercase_							)						,	lowercase_							)
     self.assertEqual(map_nested(lowercase_						,	lowercase_						,	num_proc=lowercase_							)						,	lowercase_							)
     self.assertEqual(map_nested(lowercase_						,	lowercase_						,	num_proc=lowercase_							)						,	lowercase_							)
     self.assertEqual(map_nested(lowercase_						,	lowercase_						,	num_proc=lowercase_							)						,	lowercase_							)

     A__    =      {"a": np.eye(2							), "b": np.zeros(3							), "c": np.ones(2							)}
     A__    =      {"a": 2, "b": 0, "c": 2}
     A__    =      {
         "a": np.eye(2							).astype(lowercase_							),
         "b": np.zeros(3							).astype(lowercase_							),
         "c": np.ones(2							).astype(lowercase_							),
     }
     self.assertEqual(map_nested(lowercase_						,	lowercase_						,	map_numpy=lowercase_							)						,	lowercase_							)
     self.assertEqual(
         {k: v.tolist() for k, v in map_nested(lowercase_						,	lowercase_						,	map_numpy=lowercase_							).items()}						,	{k: v.tolist() for k, v in expected_map_nested_sna_int.items()}						,	)
     self.assertEqual(map_nested(lowercase_						,	lowercase_						,	map_numpy=lowercase_						,	num_proc=lowercase_							)						,	lowercase_							)
     self.assertEqual(
         {k: v.tolist() for k, v in map_nested(lowercase_						,	lowercase_						,	map_numpy=lowercase_						,	num_proc=lowercase_							).items()}						,	{k: v.tolist() for k, v in expected_map_nested_sna_int.items()}						,	)
     with self.assertRaises(lowercase_							):  # can't pickle a local lambda
         map_nested(lambda lowercase_							: x + 1						,	lowercase_						,	num_proc=lowercase_							)
 def 					UpperCAmelCase_							(    self				:int							)->							Union[str, Any]:
     A__    =      {"a": 1, "b": 2}
     A__    =      {"a": 3, "b": 4}
     A__    =      {"a": 5, "b": 6}
     A__    =      sorted([("a", (1, 3, 5)), ("b", (2, 4, 6))]							)
     self.assertEqual(sorted(zip_dict(lowercase_						,	lowercase_						,	lowercase_							)							)						,	lowercase_							)



 def 					UpperCAmelCase_							(    self				:Any							)->							Dict:






     class        UpperCAmelCase     :
      __lowercase       		=    """bar"""

     A__    =      Foo()
     self.assertEqual(foo.my_attr						,	"bar"							)
     with temporary_assignment(lowercase_						,	"my_attr"						,	"BAR"							):
         self.assertEqual(foo.my_attr						,	"BAR"							)
     self.assertEqual(foo.my_attr						,	"bar"							)





@pytest.mark.parametrize(
    "iterable_length, num_proc, expected_num_proc"						,	[
        (1, None, 1),
        (1, 1, 1),
        (2, None, 1),
        (2, 1, 1),
        (2, 2, 1),
        (2, 3, 1),
        (3, 2, 1),
        (16, 16, 16),
        (16, 17, 16),
        (17, 16, 16),
    ]						,	)
def 						UpperCamelCase    (							_lowerCamelCase : Dict						,	_lowerCamelCase : Optional[Any]						,	_lowerCamelCase : List[Any]	):
    with patch("datasets.utils.py_utils._single_map_nested"	) as mock_single_map_nested, patch(
        "datasets.parallel.parallel.Pool"	) as mock_multiprocessing_pool:
        A__    =      {F"{i}": i for i in range(_lowerCamelCase	)}
        A__    =      map_nested(lambda _lowerCamelCase	: x + 10						,	_lowerCamelCase						,	num_proc=_lowerCamelCase						,	parallel_min_length=16	)
        if expected_num_proc == 1:
            assert mock_single_map_nested.called
            assert not mock_multiprocessing_pool.called
        else:
            assert not mock_single_map_nested.called
            assert mock_multiprocessing_pool.called
            assert mock_multiprocessing_pool.call_args[0][0] == expected_num_proc






class        UpperCAmelCase     (	UpperCamelCase__    ):
 @require_tf
 def 					UpperCAmelCase_							(    self				:Optional[int]							)->							List[str]:
     import tensorflow as tf
     from tensorflow.keras import layers

     A__    =      layers.Dense(2							)

     def gen_random_output():
         A__    =      tf.random.uniform((1, 3)							)
         return model(lowercase_							).numpy()

     with temp_seed(42						,	set_tensorflow=lowercase_							):
         A__    =      gen_random_output()
     with temp_seed(42						,	set_tensorflow=lowercase_							):
         A__    =      gen_random_output()
     A__    =      gen_random_output()

     np.testing.assert_equal(lowercase_						,	lowercase_							)
     self.assertGreater(np.abs(outa - outa							).sum()						,	0							)
 @require_torch
 def 					UpperCAmelCase_							(    self				:List[Any]							)->							Optional[Any]:
     import torch

     def gen_random_output():
         A__    =      torch.nn.Linear(3						,	2							)
         A__    =      torch.rand(1						,	3							)
         return model(lowercase_							).detach().numpy()

     with temp_seed(42						,	set_pytorch=lowercase_							):
         A__    =      gen_random_output()
     with temp_seed(42						,	set_pytorch=lowercase_							):
         A__    =      gen_random_output()
     A__    =      gen_random_output()

     np.testing.assert_equal(lowercase_						,	lowercase_							)
     self.assertGreater(np.abs(outa - outa							).sum()						,	0							)



 def 					UpperCAmelCase_							(    self				:int							)->							str:
     def gen_random_output():
         return np.random.rand(1						,	3							)

     with temp_seed(42							):
         A__    =      gen_random_output()
     with temp_seed(42							):
         A__    =      gen_random_output()
     A__    =      gen_random_output()

     np.testing.assert_equal(lowercase_						,	lowercase_							)
     self.assertGreater(np.abs(outa - outa							).sum()						,	0							)





@pytest.mark.parametrize("input_data"						,	[{}]	)
def 						UpperCamelCase    (							_lowerCamelCase : int	):
    A__    =      NestedDataStructure(_lowerCamelCase	).data
    assert output_data == input_data





@pytest.mark.parametrize(
    "data, expected_output"						,	[
        ({}, []),
        ([], []),
        ("foo", ["foo"]),
        (["foo", "bar"], ["foo", "bar"]),
        ([["foo", "bar"]], ["foo", "bar"]),
        ([[["foo"], ["bar"]]], ["foo", "bar"]),
        ([[["foo"], "bar"]], ["foo", "bar"]),
        ({"a": 1, "b": 2}, [1, 2]),
        ({"a": [1, 2], "b": [3, 4]}, [1, 2, 3, 4]),
        ({"a": [[1, 2]], "b": [[3, 4]]}, [1, 2, 3, 4]),
        ({"a": [[1, 2]], "b": [3, 4]}, [1, 2, 3, 4]),
        ({"a": [[[1], [2]]], "b": [[[3], [4]]]}, [1, 2, 3, 4]),
        ({"a": [[[1], [2]]], "b": [[3, 4]]}, [1, 2, 3, 4]),
        ({"a": [[[1], [2]]], "b": [3, 4]}, [1, 2, 3, 4]),
        ({"a": [[[1], [2]]], "b": [3, [4]]}, [1, 2, 3, 4]),
        ({"a": {"1": 1}, "b": 2}, [1, 2]),
        ({"a": {"1": [1]}, "b": 2}, [1, 2]),
        ({"a": {"1": [1]}, "b": [2]}, [1, 2]),
    ]						,	)
def 						UpperCamelCase    (							_lowerCamelCase : List[str]						,	_lowerCamelCase : Dict	):
    A__    =      NestedDataStructure(_lowerCamelCase	).flatten()
    assert output == expected_output





def 						UpperCamelCase    (							):
    A__    =      A(x=1						,	y="foobar"	)
    A__    =      {"x": 1, "y": "foobar"}
    assert asdict(_lowerCamelCase	) == expected_output

    A__    =      {"a": {"b": A(x=10						,	y="foo"	)}, "c": [A(x=20						,	y="bar"	)]}
    A__    =      {"a": {"b": {"x": 10, "y": "foo"}}, "c": [{"x": 20, "y": "bar"}]}
    assert asdict(_lowerCamelCase	) == expected_output

    with pytest.raises(_lowerCamelCase	):
        asdict([1, A(x=10						,	y="foo"	)]	)





def 						UpperCamelCase    (							_lowerCamelCase : str	):
    return text.split()





def 						UpperCamelCase    (							_lowerCamelCase : Dict	):
    yield (time.time(), content)
    time.sleep(2	)
    yield (time.time(), content)





def 						UpperCamelCase    (							):
    with Pool(2	) as pool:
        A__    =      list(iflatmap_unordered(_lowerCamelCase						,	_split_text						,	kwargs_iterable=[{"text": "hello there"}] * 10	)	)
        assert out.count("hello"	) == 10
        assert out.count("there"	) == 10
        assert len(_lowerCamelCase	) == 20

    # check multiprocess from pathos (uses dill for pickling)
    with multiprocess.Pool(2	) as pool:
        A__    =      list(iflatmap_unordered(_lowerCamelCase						,	_split_text						,	kwargs_iterable=[{"text": "hello there"}] * 10	)	)
        assert out.count("hello"	) == 10
        assert out.count("there"	) == 10
        assert len(_lowerCamelCase	) == 20

    # check that we get items as fast as possible
    with Pool(2	) as pool:
        A__    =      []
        for yield_time, content in iflatmap_unordered(
            _lowerCamelCase						,	_aseconds_generator_of_aitems_with_timing						,	kwargs_iterable=[{"content": "a"}, {"content": "b"}]	):
            assert yield_time < time.time() + 0.1, "we should each item directly after it was yielded"
            out.append(_lowerCamelCase	)
        assert out.count("a"	) == 2
        assert out.count("b"	) == 2
        assert len(_lowerCamelCase	) == 4










'''simple docstring'''

import os
import random
import sys

from . import cryptomath_module as cryptoMath  # noqa: N812
from . import rabin_miller as rabinMiller  # noqa: N812





def 						UpperCamelCase    (							):
    print("Making key files..."	)
    make_key_files("rsa"						,	10_24	)
    print("Key files generation successful."	)





def 						UpperCamelCase    (							_lowerCamelCase : int	):
    print("Generating prime p..."	)
    A__    =      rabinMiller.generate_large_prime(_lowerCamelCase	)
    print("Generating prime q..."	)
    A__    =      rabinMiller.generate_large_prime(_lowerCamelCase	)
    A__    =      p * q

    print("Generating e that is relatively prime to (p - 1) * (q - 1)..."	)
    while True:
        A__    =      random.randrange(2 ** (key_size - 1)						,	2 ** (key_size)	)
        if cryptoMath.gcd(_lowerCamelCase						,	(p - 1) * (q - 1)	) == 1:
            break

    print("Calculating d that is mod inverse of e..."	)
    A__    =      cryptoMath.find_mod_inverse(_lowerCamelCase						,	(p - 1) * (q - 1)	)

    A__    =      (n, e)
    A__    =      (n, d)
    return (public_key, private_key)





def 						UpperCamelCase    (							_lowerCamelCase : str						,	_lowerCamelCase : int	):
    if os.path.exists(F"{name}_pubkey.txt"	) or os.path.exists(F"{name}_privkey.txt"	):
        print("\nWARNING:"	)
        print(
            F"\"{name}_pubkey.txt\" or \"{name}_privkey.txt\" already exists. \n"
            "Use a different name or delete these files and re-run this program."	)
        sys.exit()

    A__,     A__    =      generate_key(_lowerCamelCase	)
    print(F"\nWriting public key to file {name}_pubkey.txt..."	)
    with open(F"{name}_pubkey.txt"						,	"w"	) as out_file:
        out_file.write(F"{key_size},{public_key[0]},{public_key[1]}"	)

    print(F"Writing private key to file {name}_privkey.txt..."	)
    with open(F"{name}_privkey.txt"						,	"w"	) as out_file:
        out_file.write(F"{key_size},{private_key[0]},{private_key[1]}"	)


if __name__ == "__main__":
  main()



