

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        _SCREAMING_SNAKE_CASE	(   _UpperCAmelCase):







						def __init__(       self				)->				Dict:
													lowerCamelCase_				     =[]







						def     _snake_case							(       self			,		_SCREAMING_SNAKE_CASE			,		_SCREAMING_SNAKE_CASE			,		_SCREAMING_SNAKE_CASE			,		**_SCREAMING_SNAKE_CASE				)->				str:
													self.events.append("""on_init_end"""				)







						def     _snake_case							(       self			,		_SCREAMING_SNAKE_CASE			,		_SCREAMING_SNAKE_CASE			,		_SCREAMING_SNAKE_CASE			,		**_SCREAMING_SNAKE_CASE				)->				Any:
													self.events.append("""on_train_begin"""				)







						def     _snake_case							(       self			,		_SCREAMING_SNAKE_CASE			,		_SCREAMING_SNAKE_CASE			,		_SCREAMING_SNAKE_CASE			,		**_SCREAMING_SNAKE_CASE				)->				Any:
													self.events.append("""on_train_end"""				)







						def     _snake_case							(       self			,		_SCREAMING_SNAKE_CASE			,		_SCREAMING_SNAKE_CASE			,		_SCREAMING_SNAKE_CASE			,		**_SCREAMING_SNAKE_CASE				)->				Union[str, Any]:
													self.events.append("""on_epoch_begin"""				)







						def     _snake_case							(       self			,		_SCREAMING_SNAKE_CASE			,		_SCREAMING_SNAKE_CASE			,		_SCREAMING_SNAKE_CASE			,		**_SCREAMING_SNAKE_CASE				)->				Tuple:
													self.events.append("""on_epoch_end"""				)







						def     _snake_case							(       self			,		_SCREAMING_SNAKE_CASE			,		_SCREAMING_SNAKE_CASE			,		_SCREAMING_SNAKE_CASE			,		**_SCREAMING_SNAKE_CASE				)->				Union[str, Any]:
													self.events.append("""on_step_begin"""				)







						def     _snake_case							(       self			,		_SCREAMING_SNAKE_CASE			,		_SCREAMING_SNAKE_CASE			,		_SCREAMING_SNAKE_CASE			,		**_SCREAMING_SNAKE_CASE				)->				Tuple:
													self.events.append("""on_step_end"""				)







						def     _snake_case							(       self			,		_SCREAMING_SNAKE_CASE			,		_SCREAMING_SNAKE_CASE			,		_SCREAMING_SNAKE_CASE			,		**_SCREAMING_SNAKE_CASE				)->				Any:
													self.events.append("""on_evaluate"""				)







						def     _snake_case							(       self			,		_SCREAMING_SNAKE_CASE			,		_SCREAMING_SNAKE_CASE			,		_SCREAMING_SNAKE_CASE			,		**_SCREAMING_SNAKE_CASE				)->				Union[str, Any]:
													self.events.append("""on_predict"""				)







						def     _snake_case							(       self			,		_SCREAMING_SNAKE_CASE			,		_SCREAMING_SNAKE_CASE			,		_SCREAMING_SNAKE_CASE			,		**_SCREAMING_SNAKE_CASE				)->				Optional[int]:
													self.events.append("""on_save"""				)







						def     _snake_case							(       self			,		_SCREAMING_SNAKE_CASE			,		_SCREAMING_SNAKE_CASE			,		_SCREAMING_SNAKE_CASE			,		**_SCREAMING_SNAKE_CASE				)->				Union[str, Any]:
													self.events.append("""on_log"""				)







						def     _snake_case							(       self			,		_SCREAMING_SNAKE_CASE			,		_SCREAMING_SNAKE_CASE			,		_SCREAMING_SNAKE_CASE			,		**_SCREAMING_SNAKE_CASE				)->				Optional[int]:
													self.events.append("""on_prediction_step"""				)


@require_torch
class        _SCREAMING_SNAKE_CASE	(   unittest.TestCase):







						def     _snake_case							(       self				)->				str:
													lowerCamelCase_				     =tempfile.mkdtemp()







						def     _snake_case							(       self				)->				List[Any]:
													shutil.rmtree(self.output_dir				)







						def     _snake_case							(       self			,		_SCREAMING_SNAKE_CASE=0			,		_SCREAMING_SNAKE_CASE=0			,		_SCREAMING_SNAKE_CASE=64			,		_SCREAMING_SNAKE_CASE=64			,		_SCREAMING_SNAKE_CASE=None			,		_SCREAMING_SNAKE_CASE=False			,		**_SCREAMING_SNAKE_CASE				)->				List[Any]:
													lowerCamelCase_				     =RegressionDataset(length=A_				)
													lowerCamelCase_				     =RegressionDataset(length=A_				)
													lowerCamelCase_				     =RegressionModelConfig(a=A_			,		b=A_				)
													lowerCamelCase_				     =RegressionPreTrainedModel(A_				)

													lowerCamelCase_				     =TrainingArguments(self.output_dir			,		disable_tqdm=A_			,		report_to=[]			,		**A_				)
													return Trainer(
													    A_			,		A_			,		train_dataset=A_			,		eval_dataset=A_			,		callbacks=A_			,		)







						def     _snake_case							(       self			,		_SCREAMING_SNAKE_CASE			,		_SCREAMING_SNAKE_CASE				)->				Dict:
													self.assertEqual(len(A_				)			,		len(A_				)				)

													# Order doesn't matter
													lowerCamelCase_				     =sorted(A_			,		key=lambda _SCREAMING_SNAKE_CASE				: cb.__name__ if isinstance(A_			,		A_				) else cb.__class__.__name__				)
													lowerCamelCase_				     =sorted(A_			,		key=lambda _SCREAMING_SNAKE_CASE				: cb.__name__ if isinstance(A_			,		A_				) else cb.__class__.__name__				)

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







						def     _snake_case							(       self			,		_SCREAMING_SNAKE_CASE				)->				int:
													lowerCamelCase_				     =['''on_init_end''', '''on_train_begin''']
													lowerCamelCase_				     =0
													lowerCamelCase_				     =len(trainer.get_eval_dataloader()				)
													lowerCamelCase_				     =['''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(A_				):
																											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     _snake_case							(       self				)->				str:
													lowerCamelCase_				     =self.get_trainer()
													lowerCamelCase_				     =DEFAULT_CALLBACKS.copy() + [ProgressCallback]
													self.check_callbacks_equality(trainer.callback_handler.callbacks			,		A_				)

													# Callbacks passed at init are added to the default callbacks
													lowerCamelCase_				     =self.get_trainer(callbacks=[MyTestTrainerCallback]				)
													expected_callbacks.append(A_				)
													self.check_callbacks_equality(trainer.callback_handler.callbacks			,		A_				)

													# TrainingArguments.disable_tqdm controls if use ProgressCallback or PrinterCallback
													lowerCamelCase_				     =self.get_trainer(disable_tqdm=A_				)
													lowerCamelCase_				     =DEFAULT_CALLBACKS.copy() + [PrinterCallback]
													self.check_callbacks_equality(trainer.callback_handler.callbacks			,		A_				)







						def     _snake_case							(       self				)->				List[Any]:
													lowerCamelCase_				     =DEFAULT_CALLBACKS.copy() + [ProgressCallback]
													lowerCamelCase_				     =self.get_trainer()

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

													lowerCamelCase_				     =self.get_trainer()
													lowerCamelCase_				     =trainer.pop_callback(A_				)
													self.assertEqual(cb.__class__			,		A_				)
													self.check_callbacks_equality(trainer.callback_handler.callbacks			,		A_				)

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

													# We can also add, pop, or remove by instance
													lowerCamelCase_				     =self.get_trainer()
													lowerCamelCase_				     =trainer.callback_handler.callbacks[0]
													trainer.remove_callback(A_				)
													expected_callbacks.remove(A_				)
													self.check_callbacks_equality(trainer.callback_handler.callbacks			,		A_				)

													lowerCamelCase_				     =self.get_trainer()
													lowerCamelCase_				     =trainer.callback_handler.callbacks[0]
													lowerCamelCase_				     =trainer.pop_callback(A_				)
													self.assertEqual(A_			,		A_				)
													self.check_callbacks_equality(trainer.callback_handler.callbacks			,		A_				)

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







						def     _snake_case							(       self				)->				Dict:
													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=A_				)

													lowerCamelCase_				     =self.get_trainer(callbacks=[MyTestTrainerCallback]				)
													trainer.train()
													lowerCamelCase_				     =trainer.callback_handler.callbacks[-2].events
													self.assertEqual(A_			,		self.get_expected_events(A_				)				)

													# Independent log/save/eval
													lowerCamelCase_				     =self.get_trainer(callbacks=[MyTestTrainerCallback]			,		logging_steps=5				)
													trainer.train()
													lowerCamelCase_				     =trainer.callback_handler.callbacks[-2].events
													self.assertEqual(A_			,		self.get_expected_events(A_				)				)

													lowerCamelCase_				     =self.get_trainer(callbacks=[MyTestTrainerCallback]			,		save_steps=5				)
													trainer.train()
													lowerCamelCase_				     =trainer.callback_handler.callbacks[-2].events
													self.assertEqual(A_			,		self.get_expected_events(A_				)				)

													lowerCamelCase_				     =self.get_trainer(callbacks=[MyTestTrainerCallback]			,		eval_steps=5			,		evaluation_strategy="""steps"""				)
													trainer.train()
													lowerCamelCase_				     =trainer.callback_handler.callbacks[-2].events
													self.assertEqual(A_			,		self.get_expected_events(A_				)				)

													lowerCamelCase_				     =self.get_trainer(callbacks=[MyTestTrainerCallback]			,		evaluation_strategy="""epoch"""				)
													trainer.train()
													lowerCamelCase_				     =trainer.callback_handler.callbacks[-2].events
													self.assertEqual(A_			,		self.get_expected_events(A_				)				)

													# A bit of everything
													lowerCamelCase_				     =self.get_trainer(
													    callbacks=[MyTestTrainerCallback]			,		logging_steps=3			,		save_steps=10			,		eval_steps=5			,		evaluation_strategy="""steps"""			,		)
													trainer.train()
													lowerCamelCase_				     =trainer.callback_handler.callbacks[-2].events
													self.assertEqual(A_			,		self.get_expected_events(A_				)				)

													# warning should be emitted for duplicated callbacks
													with patch("""transformers.trainer_callback.logger.warning"""				) as warn_mock:
																				lowerCamelCase_				     =self.get_trainer(
																				    callbacks=[MyTestTrainerCallback, MyTestTrainerCallback]			,		)
																				assert str(A_				) in warn_mock.call_args[0][0]



def 		_lowercase (     lowercase__   ,	lowercase__						):
      return (pointa[0] - pointa[0]) ** 2 + (pointa[1] - pointa[1]) ** 2







def 		_lowercase (     lowercase__   ,	lowercase__=0						):
      return sorted(lowercase__   ,	key=lambda lowercase__						: x[column]						)







def 		_lowercase (     lowercase__   ,	lowercase__   ,	lowercase__=float('''inf'''						)						):

      for i in range(points_counts - 1						):
            for j in range(i + 1   ,	lowercase__						):
                  __lowerCAmelCase					:						List[str]					=					euclidean_distance_sqr(points[i]   ,	points[j]						)
                  if current_dis < min_dis:
                        __lowerCAmelCase					:						Tuple					=					current_dis
      return min_dis







def 		_lowercase (     lowercase__   ,	lowercase__   ,	lowercase__=float('''inf'''						)						):

      for i in range(min(6   ,	points_counts - 1						)   ,	lowercase__						):
            for j in range(max(0   ,	i - 6						)   ,	lowercase__						):
                  __lowerCAmelCase					:						Union[str, Any]					=					euclidean_distance_sqr(points[i]   ,	points[j]						)
                  if current_dis < min_dis:
                        __lowerCAmelCase					:						int					=					current_dis
      return min_dis







def 		_lowercase (     lowercase__   ,	lowercase__   ,	lowercase__						):

      # base case
      if points_counts <= 3:
            return dis_between_closest_pair(lowercase__   ,	lowercase__						)

      # recursion
      __lowerCAmelCase					:						Optional[Any]					=					points_counts // 2
      __lowerCAmelCase					:						Optional[Any]					=					closest_pair_of_points_sqr(
          lowercase__   ,	points_sorted_on_y[:mid]   ,	lowercase__						)
      __lowerCAmelCase					:						str					=					closest_pair_of_points_sqr(
          lowercase__   ,	points_sorted_on_y[mid:]   ,	points_counts - mid						)
      __lowerCAmelCase					:						Optional[int]					=					min(lowercase__   ,	lowercase__						)
      __lowerCAmelCase					:						Tuple					=					[]
      for point in points_sorted_on_x:
            if abs(point[0] - points_sorted_on_x[mid][0]						) < closest_pair_dis:
                  cross_strip.append(lowercase__						)

      __lowerCAmelCase					:						List[Any]					=					dis_between_closest_in_strip(
          lowercase__   ,	len(lowercase__						)   ,	lowercase__						)
      return min(lowercase__   ,	lowercase__						)







def 		_lowercase (     lowercase__   ,	lowercase__						):
      __lowerCAmelCase					:						Union[str, Any]					=					column_based_sort(lowercase__   ,	column=0						)
      __lowerCAmelCase					:						Any					=					column_based_sort(lowercase__   ,	column=1						)
      return (
          closest_pair_of_points_sqr(
              lowercase__   ,	lowercase__   ,	lowercase__						)
      ) ** 0.5


if __name__ == "__main__":
 _UpperCamelCase 			=		[(2, 3), (12, 30), (40, 50), (5, 1), (12, 10), (3, 4)]
 print("Distance:", closest_pair_of_points(points, len(points)))


