






'''simple docstring'''



import shutil
import tempfile
import unittest
from unittest.mock import patch

from transformers import (
    DefaultFlowCallback,
    IntervalStrategy,
    PrinterCallback,
    ProgressCallback,
    Trainer,
    TrainerCallback,
    TrainingArguments,
    is_torch_available,
)
from transformers.testing_utils import require_torch


if is_torch_available():
      from transformers.trainer import DEFAULT_CALLBACKS

      from .test_trainer import RegressionDataset, RegressionModelConfig, RegressionPreTrainedModel
class UpperCAmelCase_       (     __A					):




      """simple docstring"""




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


       '''simple docstring'''

       lowercase       : Union[str, Any]						=[]






      def 					A__   (			self      :		Optional[int]  ,   UpperCAmelCase      :		List[Any]  ,   UpperCAmelCase      :		str  ,   UpperCAmelCase      :		Any  ,   **UpperCAmelCase      :		Tuple		)	->	Optional[Any]:


       '''simple docstring'''

       self.events.append('''on_init_end'''		)






      def 					A__   (			self      :		Union[str, Any]  ,   UpperCAmelCase      :		List[Any]  ,   UpperCAmelCase      :		Any  ,   UpperCAmelCase      :		Any  ,   **UpperCAmelCase      :		Dict		)	->	int:


       '''simple docstring'''

       self.events.append('''on_train_begin'''		)






      def 					A__   (			self      :		Dict  ,   UpperCAmelCase      :		Optional[Any]  ,   UpperCAmelCase      :		Tuple  ,   UpperCAmelCase      :		Union[str, Any]  ,   **UpperCAmelCase      :		Tuple		)	->	Optional[Any]:


       '''simple docstring'''

       self.events.append('''on_train_end'''		)






      def 					A__   (			self      :		Any  ,   UpperCAmelCase      :		str  ,   UpperCAmelCase      :		Tuple  ,   UpperCAmelCase      :		Dict  ,   **UpperCAmelCase      :		Any		)	->	Dict:


       '''simple docstring'''

       self.events.append('''on_epoch_begin'''		)






      def 					A__   (			self      :		Optional[int]  ,   UpperCAmelCase      :		List[Any]  ,   UpperCAmelCase      :		Union[str, Any]  ,   UpperCAmelCase      :		List[str]  ,   **UpperCAmelCase      :		List[Any]		)	->	List[str]:


       '''simple docstring'''

       self.events.append('''on_epoch_end'''		)






      def 					A__   (			self      :		str  ,   UpperCAmelCase      :		Union[str, Any]  ,   UpperCAmelCase      :		List[str]  ,   UpperCAmelCase      :		Optional[Any]  ,   **UpperCAmelCase      :		Optional[int]		)	->	int:


       '''simple docstring'''

       self.events.append('''on_step_begin'''		)






      def 					A__   (			self      :		List[Any]  ,   UpperCAmelCase      :		Union[str, Any]  ,   UpperCAmelCase      :		List[Any]  ,   UpperCAmelCase      :		Tuple  ,   **UpperCAmelCase      :		List[Any]		)	->	Any:


       '''simple docstring'''

       self.events.append('''on_step_end'''		)






      def 					A__   (			self      :		Optional[int]  ,   UpperCAmelCase      :		Tuple  ,   UpperCAmelCase      :		Optional[Any]  ,   UpperCAmelCase      :		Union[str, Any]  ,   **UpperCAmelCase      :		Tuple		)	->	Dict:


       '''simple docstring'''

       self.events.append('''on_evaluate'''		)






      def 					A__   (			self      :		int  ,   UpperCAmelCase      :		Any  ,   UpperCAmelCase      :		Union[str, Any]  ,   UpperCAmelCase      :		List[str]  ,   **UpperCAmelCase      :		str		)	->	List[str]:


       '''simple docstring'''

       self.events.append('''on_predict'''		)






      def 					A__   (			self      :		Optional[Any]  ,   UpperCAmelCase      :		Tuple  ,   UpperCAmelCase      :		Optional[int]  ,   UpperCAmelCase      :		int  ,   **UpperCAmelCase      :		Dict		)	->	Union[str, Any]:


       '''simple docstring'''

       self.events.append('''on_save'''		)






      def 					A__   (			self      :		int  ,   UpperCAmelCase      :		List[str]  ,   UpperCAmelCase      :		int  ,   UpperCAmelCase      :		Any  ,   **UpperCAmelCase      :		int		)	->	str:


       '''simple docstring'''

       self.events.append('''on_log'''		)






      def 					A__   (			self      :		str  ,   UpperCAmelCase      :		List[str]  ,   UpperCAmelCase      :		List[str]  ,   UpperCAmelCase      :		str  ,   **UpperCAmelCase      :		Any		)	->	Tuple:


       '''simple docstring'''

       self.events.append('''on_prediction_step'''		)





@require_torch
class UpperCAmelCase_       (     unittest.TestCase					):




      """simple docstring"""




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


       '''simple docstring'''

       lowercase       : Optional[int]						=tempfile.mkdtemp()






      def 					A__   (			self      :		Optional[int]		)	->	Union[str, Any]:


       '''simple docstring'''

       shutil.rmtree(self.output_dir		)






      def 					A__   (			self      :		str  ,   UpperCAmelCase      :		List[Any]=0  ,   UpperCAmelCase      :		Tuple=0  ,   UpperCAmelCase      :		Dict=64  ,   UpperCAmelCase      :		List[Any]=64  ,   UpperCAmelCase      :		Optional[int]=None  ,   UpperCAmelCase      :		Optional[Any]=False  ,   **UpperCAmelCase      :		Optional[int]		)	->	Union[str, Any]:


       '''simple docstring'''

       lowercase       : Union[str, Any]						=RegressionDataset(length=UpperCAmelCase		)
       lowercase       : Any						=RegressionDataset(length=UpperCAmelCase		)
       lowercase       : Optional[int]						=RegressionModelConfig(a=UpperCAmelCase  ,   b=UpperCAmelCase		)
       lowercase       : Any						=RegressionPreTrainedModel(UpperCAmelCase		)

       lowercase       : Dict						=TrainingArguments(self.output_dir  ,   disable_tqdm=UpperCAmelCase  ,   report_to=[]  ,   **UpperCAmelCase		)
       return Trainer(
           UpperCAmelCase  ,   UpperCAmelCase  ,   train_dataset=UpperCAmelCase  ,   eval_dataset=UpperCAmelCase  ,   callbacks=UpperCAmelCase  ,   )






      def 					A__   (			self      :		Tuple  ,   UpperCAmelCase      :		Union[str, Any]  ,   UpperCAmelCase      :		List[str]		)	->	Tuple:


       '''simple docstring'''

       self.assertEqual(len(UpperCAmelCase		)  ,   len(UpperCAmelCase		)		)

       # Order doesn't matter
       lowercase       : Tuple						=sorted(UpperCAmelCase  ,   key=lambda UpperCAmelCase		: cb.__name__ if isinstance(UpperCAmelCase  ,   UpperCAmelCase		) else cb.__class__.__name__		)
       lowercase       : Any						=sorted(UpperCAmelCase  ,   key=lambda UpperCAmelCase		: cb.__name__ if isinstance(UpperCAmelCase  ,   UpperCAmelCase		) else cb.__class__.__name__		)

       for cba, cba in zip(UpperCAmelCase  ,   UpperCAmelCase		):
        if isinstance(UpperCAmelCase  ,   UpperCAmelCase		) and isinstance(UpperCAmelCase  ,   UpperCAmelCase		):
         self.assertEqual(UpperCAmelCase  ,   UpperCAmelCase		)
        elif isinstance(UpperCAmelCase  ,   UpperCAmelCase		) and not isinstance(UpperCAmelCase  ,   UpperCAmelCase		):
         self.assertEqual(UpperCAmelCase  ,   cba.__class__		)
        elif not isinstance(UpperCAmelCase  ,   UpperCAmelCase		) and isinstance(UpperCAmelCase  ,   UpperCAmelCase		):
         self.assertEqual(cba.__class__  ,   UpperCAmelCase		)
        else:
         self.assertEqual(UpperCAmelCase  ,   UpperCAmelCase		)






      def 					A__   (			self      :		Dict  ,   UpperCAmelCase      :		Optional[Any]		)	->	Any:


       '''simple docstring'''

       lowercase       : Tuple						=['''on_init_end''', '''on_train_begin''']
       lowercase       : List[str]						=0
       lowercase       : Union[str, Any]						=len(trainer.get_eval_dataloader()		)
       lowercase       : Optional[Any]						=['''on_prediction_step'''] * len(trainer.get_eval_dataloader()		) + ['''on_log''', '''on_evaluate''']
       for _ in range(trainer.state.num_train_epochs		):
        expected_events.append('''on_epoch_begin'''		)
        for _ in range(UpperCAmelCase		):
         step += 1
         expected_events += ["on_step_begin", "on_step_end"]
         if step % trainer.args.logging_steps == 0:
          expected_events.append('''on_log'''		)
         if trainer.args.evaluation_strategy == IntervalStrategy.STEPS and step % trainer.args.eval_steps == 0:
          expected_events += evaluation_events.copy()
         if step % trainer.args.save_steps == 0:
          expected_events.append('''on_save'''		)
        expected_events.append('''on_epoch_end'''		)
        if trainer.args.evaluation_strategy == IntervalStrategy.EPOCH:
         expected_events += evaluation_events.copy()
       expected_events += ["on_log", "on_train_end"]
       return expected_events






      def 					A__   (			self      :		Any		)	->	List[Any]:


       '''simple docstring'''

       lowercase       : List[str]						=self.get_trainer()
       lowercase       : Dict						=DEFAULT_CALLBACKS.copy() + [ProgressCallback]
       self.check_callbacks_equality(trainer.callback_handler.callbacks  ,   UpperCAmelCase		)

       # Callbacks passed at init are added to the default callbacks
       lowercase       : List[Any]						=self.get_trainer(callbacks=[MyTestTrainerCallback]		)
       expected_callbacks.append(UpperCAmelCase		)
       self.check_callbacks_equality(trainer.callback_handler.callbacks  ,   UpperCAmelCase		)

       # TrainingArguments.disable_tqdm controls if use ProgressCallback or PrinterCallback
       lowercase       : Tuple						=self.get_trainer(disable_tqdm=UpperCAmelCase		)
       lowercase       : str						=DEFAULT_CALLBACKS.copy() + [PrinterCallback]
       self.check_callbacks_equality(trainer.callback_handler.callbacks  ,   UpperCAmelCase		)






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


       '''simple docstring'''

       lowercase       : Any						=DEFAULT_CALLBACKS.copy() + [ProgressCallback]
       lowercase       : Optional[int]						=self.get_trainer()

       # We can add, pop, or remove by class name
       trainer.remove_callback(UpperCAmelCase		)
       expected_callbacks.remove(UpperCAmelCase		)
       self.check_callbacks_equality(trainer.callback_handler.callbacks  ,   UpperCAmelCase		)

       lowercase       : Union[str, Any]						=self.get_trainer()
       lowercase       : Union[str, Any]						=trainer.pop_callback(UpperCAmelCase		)
       self.assertEqual(cb.__class__  ,   UpperCAmelCase		)
       self.check_callbacks_equality(trainer.callback_handler.callbacks  ,   UpperCAmelCase		)

       trainer.add_callback(UpperCAmelCase		)
       expected_callbacks.insert(0  ,   UpperCAmelCase		)
       self.check_callbacks_equality(trainer.callback_handler.callbacks  ,   UpperCAmelCase		)

       # We can also add, pop, or remove by instance
       lowercase       : Optional[int]						=self.get_trainer()
       lowercase       : str						=trainer.callback_handler.callbacks[0]
       trainer.remove_callback(UpperCAmelCase		)
       expected_callbacks.remove(UpperCAmelCase		)
       self.check_callbacks_equality(trainer.callback_handler.callbacks  ,   UpperCAmelCase		)

       lowercase       : Union[str, Any]						=self.get_trainer()
       lowercase       : List[Any]						=trainer.callback_handler.callbacks[0]
       lowercase       : Optional[int]						=trainer.pop_callback(UpperCAmelCase		)
       self.assertEqual(UpperCAmelCase  ,   UpperCAmelCase		)
       self.check_callbacks_equality(trainer.callback_handler.callbacks  ,   UpperCAmelCase		)

       trainer.add_callback(UpperCAmelCase		)
       expected_callbacks.insert(0  ,   UpperCAmelCase		)
       self.check_callbacks_equality(trainer.callback_handler.callbacks  ,   UpperCAmelCase		)






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


       '''simple docstring'''

       import warnings

       # XXX: for now ignore scatter_gather warnings in this test since it's not relevant to what's being tested
       warnings.simplefilter(action='''ignore'''  ,   category=UpperCAmelCase		)

       lowercase       : List[Any]						=self.get_trainer(callbacks=[MyTestTrainerCallback]		)
       trainer.train()
       lowercase       : List[Any]						=trainer.callback_handler.callbacks[-2].events
       self.assertEqual(UpperCAmelCase  ,   self.get_expected_events(UpperCAmelCase		)		)

       # Independent log/save/eval
       lowercase       : int						=self.get_trainer(callbacks=[MyTestTrainerCallback]  ,   logging_steps=5		)
       trainer.train()
       lowercase       : List[str]						=trainer.callback_handler.callbacks[-2].events
       self.assertEqual(UpperCAmelCase  ,   self.get_expected_events(UpperCAmelCase		)		)

       lowercase       : Dict						=self.get_trainer(callbacks=[MyTestTrainerCallback]  ,   save_steps=5		)
       trainer.train()
       lowercase       : Union[str, Any]						=trainer.callback_handler.callbacks[-2].events
       self.assertEqual(UpperCAmelCase  ,   self.get_expected_events(UpperCAmelCase		)		)

       lowercase       : int						=self.get_trainer(callbacks=[MyTestTrainerCallback]  ,   eval_steps=5  ,   evaluation_strategy='''steps'''		)
       trainer.train()
       lowercase       : List[str]						=trainer.callback_handler.callbacks[-2].events
       self.assertEqual(UpperCAmelCase  ,   self.get_expected_events(UpperCAmelCase		)		)

       lowercase       : Optional[Any]						=self.get_trainer(callbacks=[MyTestTrainerCallback]  ,   evaluation_strategy='''epoch'''		)
       trainer.train()
       lowercase       : Optional[int]						=trainer.callback_handler.callbacks[-2].events
       self.assertEqual(UpperCAmelCase  ,   self.get_expected_events(UpperCAmelCase		)		)

       # A bit of everything
       lowercase       : Dict						=self.get_trainer(
           callbacks=[MyTestTrainerCallback]  ,   logging_steps=3  ,   save_steps=10  ,   eval_steps=5  ,   evaluation_strategy='''steps'''  ,   )
       trainer.train()
       lowercase       : Optional[Any]						=trainer.callback_handler.callbacks[-2].events
       self.assertEqual(UpperCAmelCase  ,   self.get_expected_events(UpperCAmelCase		)		)

       # warning should be emitted for duplicated callbacks
       with patch('''transformers.trainer_callback.logger.warning'''		) as warn_mock:
        lowercase       : Optional[Any]						=self.get_trainer(
            callbacks=[MyTestTrainerCallback, MyTestTrainerCallback]  ,   )
        assert str(UpperCAmelCase		) in warn_mock.call_args[0][0]






from sympy import diff, lambdify, symbols
from sympy.functions import *  # noqa: F403






def        snake_case__		(    lowerCamelCase_     ,				lowerCamelCase_     ,				lowerCamelCase_ = "x"     ,				lowerCamelCase_ = 10**-10     ,				lowerCamelCase_ = 1     ,				):
							A      :					int      		=					symbols(lowerCamelCase_		)
							A      :					List[str]      		=					lambdify(lowerCamelCase_     ,				lowerCamelCase_		)
							A      :					Tuple      		=					lambdify(lowerCamelCase_     ,				diff(lowerCamelCase_     ,				lowerCamelCase_		)		)

							A      :					Optional[int]      		=					starting_point

							while True:
														if diff_function(lowerCamelCase_		) != 0:
																					A      :					Union[str, Any]      		=					prev_guess - multiplicity * func(lowerCamelCase_		) / diff_function(
																					    lowerCamelCase_		)
														else:
																					raise ZeroDivisionError('''Could not find root'''		) from None

														# Precision is checked by comparing the difference of consecutive guesses
														if abs(next_guess - prev_guess		) < precision:
																					return next_guess

														A      :					Tuple      		=					next_guess


# Let's Execute
if __name__ == "__main__":
		# Find root of trigonometric function
		# Find value of pi
		print(F"The root of sin(x) = 0 is {newton_raphson('sin(x)', 2)}")

		# Find root of polynomial
		# Find fourth Root of 5
		print(F"The root of x**4 - 5 = 0 is {newton_raphson('x**4 -5', 0.4 +5J)}")

		# Find value of e
		print(
		    "The root of log(y) - 1 = 0 is ",
		    F"{newton_raphson('log(y) - 1', 2, variable='y')}",
		)

		# Exponential Roots
		print(
		    "The root of exp(x) - 1 = 0 is",
		    F"{newton_raphson('exp(x) - 1', 10, precision=0.0_05)}",
		)

		# Find root of cos(x)
		print(F"The root of cos(x) = 0 is {newton_raphson('cos(x)', 0)}")






