
'''simple docstring'''

import inspect
import unittest

from transformers import DataaVecVisionConfig
from transformers.models.auto import get_values
from transformers.testing_utils import require_torch, require_torch_multi_gpu, require_vision, slow, torch_device
from transformers.utils import cached_property, is_torch_available, is_vision_available

from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, _config_zero_init, floats_tensor, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin


if is_torch_available():
   import torch
   from torch import nn

   from transformers import (
       MODEL_MAPPING,
       DataaVecVisionForImageClassification,
       DataaVecVisionForSemanticSegmentation,
       DataaVecVisionModel,
   )
   from transformers.models.dataavec.modeling_dataavec_vision import DATA2VEC_VISION_PRETRAINED_MODEL_ARCHIVE_LIST


if is_vision_available():
   from PIL import Image

   from transformers import BeitImageProcessor


class 		_a     :







   """simple docstring"""




   def __init__(       self    ,__SCREAMING_SNAKE_CASE    ,__SCREAMING_SNAKE_CASE=100    ,__SCREAMING_SNAKE_CASE=13    ,__SCREAMING_SNAKE_CASE=30    ,__SCREAMING_SNAKE_CASE=2    ,__SCREAMING_SNAKE_CASE=3    ,__SCREAMING_SNAKE_CASE=True    ,__SCREAMING_SNAKE_CASE=True    ,__SCREAMING_SNAKE_CASE=32    ,__SCREAMING_SNAKE_CASE=4    ,__SCREAMING_SNAKE_CASE=4    ,__SCREAMING_SNAKE_CASE=37    ,__SCREAMING_SNAKE_CASE="gelu"    ,__SCREAMING_SNAKE_CASE=0.1    ,__SCREAMING_SNAKE_CASE=0.1    ,__SCREAMING_SNAKE_CASE=10    ,__SCREAMING_SNAKE_CASE=0.02    ,__SCREAMING_SNAKE_CASE=3    ,__SCREAMING_SNAKE_CASE=None    ,__SCREAMING_SNAKE_CASE=[0, 1, 2, 3]    ,):
    SCREAMING_SNAKE_CASE  :  List[Any]								=		parent
    SCREAMING_SNAKE_CASE  :  List[Any]								=		100
    SCREAMING_SNAKE_CASE  :  Tuple								=		batch_size
    SCREAMING_SNAKE_CASE  :  Union[str, Any]								=		image_size
    SCREAMING_SNAKE_CASE  :  int								=		patch_size
    SCREAMING_SNAKE_CASE  :  str								=		num_channels
    SCREAMING_SNAKE_CASE  :  int								=		is_training
    SCREAMING_SNAKE_CASE  :  Tuple								=		use_labels
    SCREAMING_SNAKE_CASE  :  Union[str, Any]								=		hidden_size
    SCREAMING_SNAKE_CASE  :  List[Any]								=		num_hidden_layers
    SCREAMING_SNAKE_CASE  :  Optional[Any]								=		num_attention_heads
    SCREAMING_SNAKE_CASE  :  Tuple								=		intermediate_size
    SCREAMING_SNAKE_CASE  :  Optional[Any]								=		hidden_act
    SCREAMING_SNAKE_CASE  :  Dict								=		hidden_dropout_prob
    SCREAMING_SNAKE_CASE  :  List[str]								=		attention_probs_dropout_prob
    SCREAMING_SNAKE_CASE  :  int								=		type_sequence_label_size
    SCREAMING_SNAKE_CASE  :  Dict								=		initializer_range
    SCREAMING_SNAKE_CASE  :  Tuple								=		scope
    SCREAMING_SNAKE_CASE  :  List[str]								=		out_indices
    SCREAMING_SNAKE_CASE  :  Tuple								=		num_labels

    # in BeiT, the seq length equals the number of patches + 1 (we add 1 for the [CLS] token)
    SCREAMING_SNAKE_CASE  :  Optional[Any]								=		(image_size // patch_size) ** 2
    SCREAMING_SNAKE_CASE  :  List[Any]								=		num_patches + 1






   def 					__a			(       self      ):
    SCREAMING_SNAKE_CASE  :  Union[str, Any]								=		floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]      )

    SCREAMING_SNAKE_CASE  :  Tuple								=		None
    SCREAMING_SNAKE_CASE  :  Optional[Any]								=		None
    if self.use_labels:
     SCREAMING_SNAKE_CASE  :  Tuple								=		ids_tensor([self.batch_size]    ,self.type_sequence_label_size      )
     SCREAMING_SNAKE_CASE  :  Any								=		ids_tensor([self.batch_size, self.image_size, self.image_size]    ,self.num_labels      )

    SCREAMING_SNAKE_CASE  :  str								=		self.get_config()

    return config, pixel_values, labels, pixel_labels






   def 					__a			(       self      ):
    return DataaVecVisionConfig(
        vocab_size=self.vocab_size    ,image_size=self.image_size    ,patch_size=self.patch_size    ,num_channels=self.num_channels    ,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    ,is_decoder=lowerCAmelCase_    ,initializer_range=self.initializer_range    ,out_indices=self.out_indices    ,)






   def 					__a			(       self    ,__SCREAMING_SNAKE_CASE    ,__SCREAMING_SNAKE_CASE    ,__SCREAMING_SNAKE_CASE    ,__SCREAMING_SNAKE_CASE      ):
    SCREAMING_SNAKE_CASE  :  str								=		DataaVecVisionModel(config=lowerCAmelCase_      )
    model.to(lowerCAmelCase_      )
    model.eval()
    SCREAMING_SNAKE_CASE  :  Union[str, Any]								=		model(lowerCAmelCase_      )
    # expected sequence length = num_patches + 1 (we add 1 for the [CLS] token)
    SCREAMING_SNAKE_CASE  :  Union[str, Any]								=		(self.image_size // self.patch_size) ** 2
    self.parent.assertEqual(result.last_hidden_state.shape    ,(self.batch_size, num_patches + 1, self.hidden_size)      )






   def 					__a			(       self    ,__SCREAMING_SNAKE_CASE    ,__SCREAMING_SNAKE_CASE    ,__SCREAMING_SNAKE_CASE    ,__SCREAMING_SNAKE_CASE      ):
    SCREAMING_SNAKE_CASE  :  Dict								=		self.type_sequence_label_size
    SCREAMING_SNAKE_CASE  :  Any								=		DataaVecVisionForImageClassification(lowerCAmelCase_      )
    model.to(lowerCAmelCase_      )
    model.eval()
    SCREAMING_SNAKE_CASE  :  Dict								=		model(lowerCAmelCase_    ,labels=lowerCAmelCase_      )
    self.parent.assertEqual(result.logits.shape    ,(self.batch_size, self.type_sequence_label_size)      )






   def 					__a			(       self    ,__SCREAMING_SNAKE_CASE    ,__SCREAMING_SNAKE_CASE    ,__SCREAMING_SNAKE_CASE    ,__SCREAMING_SNAKE_CASE      ):
    SCREAMING_SNAKE_CASE  :  Union[str, Any]								=		self.num_labels
    SCREAMING_SNAKE_CASE  :  Optional[Any]								=		DataaVecVisionForSemanticSegmentation(lowerCAmelCase_      )
    model.to(lowerCAmelCase_      )
    model.eval()
    SCREAMING_SNAKE_CASE  :  Union[str, Any]								=		model(lowerCAmelCase_      )
    self.parent.assertEqual(
        result.logits.shape    ,(self.batch_size, self.num_labels, self.image_size * 2, self.image_size * 2)      )
    SCREAMING_SNAKE_CASE  :  Optional[int]								=		model(lowerCAmelCase_    ,labels=lowerCAmelCase_      )
    self.parent.assertEqual(
        result.logits.shape    ,(self.batch_size, self.num_labels, self.image_size * 2, self.image_size * 2)      )






   def 					__a			(       self      ):
    SCREAMING_SNAKE_CASE  :  Any								=		self.prepare_config_and_inputs()
    SCREAMING_SNAKE_CASE  :  Optional[int]								=		config_and_inputs
    SCREAMING_SNAKE_CASE  :  Any								=		{'''pixel_values''': pixel_values}
    return config, inputs_dict



@require_torch
class 		_a     (							SCREAMING_SNAKE_CASE__			,    SCREAMING_SNAKE_CASE__			,    unittest.TestCase  ):







   """simple docstring"""




   A		= (
       (DataaVecVisionModel, DataaVecVisionForImageClassification, DataaVecVisionForSemanticSegmentation)
       if is_torch_available()
       else ()
   )
   A		= (
       {
           '''feature-extraction''': DataaVecVisionModel,
           '''image-classification''': DataaVecVisionForImageClassification,
           '''image-segmentation''': DataaVecVisionForSemanticSegmentation,
       }
       if is_torch_available()
       else {}
   )

   A		= False
   A		= False
   A		= False






   def 					__a			(       self      ):
    SCREAMING_SNAKE_CASE  :  int								=		DataaVecVisionModelTester(self      )
    SCREAMING_SNAKE_CASE  :  Dict								=		ConfigTester(
        self    ,config_class=lowerCAmelCase_    ,has_text_modality=lowerCAmelCase_    ,hidden_size=37      )






   def 					__a			(       self      ):
    self.config_tester.run_common_tests()






   def 					__a			(       self      ):
    pass






   @require_torch_multi_gpu
   @unittest.skip(
       reason='Data2VecVision has some layers using `add_module` which doesn\'t work well with `nn.DataParallel`'      )
   def 					__a			(       self      ):
    pass






   def 					__a			(       self      ):
    SCREAMING_SNAKE_CASE  :  Union[str, Any]								=		self.model_tester.prepare_config_and_inputs_for_common()

    for model_class in self.all_model_classes:
     SCREAMING_SNAKE_CASE  :  Any								=		model_class(lowerCAmelCase_      )
     self.assertIsInstance(model.get_input_embeddings()    ,(nn.Module)      )
     SCREAMING_SNAKE_CASE  :  str								=		model.get_output_embeddings()
     self.assertTrue(x is None or isinstance(lowerCAmelCase_    ,nn.Linear      )      )






   def 					__a			(       self      ):
    SCREAMING_SNAKE_CASE  :  Any								=		self.model_tester.prepare_config_and_inputs_for_common()

    for model_class in self.all_model_classes:
     SCREAMING_SNAKE_CASE  :  int								=		model_class(lowerCAmelCase_      )
     SCREAMING_SNAKE_CASE  :  Dict								=		inspect.signature(model.forward      )
     # signature.parameters is an OrderedDict => so arg_names order is deterministic
     SCREAMING_SNAKE_CASE  :  Any								=		[*signature.parameters.keys()]

     SCREAMING_SNAKE_CASE  :  Any								=		['''pixel_values''']
     self.assertListEqual(arg_names[:1]    ,lowerCAmelCase_      )






   def 					__a			(       self      ):
    SCREAMING_SNAKE_CASE  :  List[str]								=		self.model_tester.prepare_config_and_inputs()
    self.model_tester.create_and_check_model(*lowerCAmelCase_      )






   def 					__a			(       self      ):
    SCREAMING_SNAKE_CASE  :  List[str]								=		self.model_tester.prepare_config_and_inputs()
    self.model_tester.create_and_check_for_image_segmentation(*lowerCAmelCase_      )






   def 					__a			(       self      ):
    if not self.model_tester.is_training:
     return

    SCREAMING_SNAKE_CASE  :  str								=		self.model_tester.prepare_config_and_inputs_for_common()
    SCREAMING_SNAKE_CASE  :  Optional[Any]								=		True

    for model_class in self.all_model_classes:
     if model_class in [*get_values(lowerCAmelCase_      )]:
      continue

     SCREAMING_SNAKE_CASE  :  Optional[int]								=		model_class(lowerCAmelCase_      )
     model.to(lowerCAmelCase_      )
     model.train()
     SCREAMING_SNAKE_CASE  :  List[Any]								=		self._prepare_for_class(lowerCAmelCase_    ,lowerCAmelCase_    ,return_labels=lowerCAmelCase_      )
     SCREAMING_SNAKE_CASE  :  Dict								=		model(**lowerCAmelCase_      ).loss
     loss.backward()






   def 					__a			(       self      ):
    SCREAMING_SNAKE_CASE  :  List[str]								=		self.model_tester.prepare_config_and_inputs_for_common()
    if not self.model_tester.is_training:
     return

    SCREAMING_SNAKE_CASE  :  Optional[int]								=		False
    SCREAMING_SNAKE_CASE  :  int								=		True

    for model_class in self.all_model_classes:
     if model_class in [*get_values(lowerCAmelCase_      )] or not model_class.supports_gradient_checkpointing:
      continue
     # TODO: remove the following 3 lines once we have a MODEL_FOR_SEMANTIC_SEGMENTATION_MAPPING
     # this can then be incorporated into _prepare_for_class in test_modeling_common.py
     elif model_class.__name__ == "Data2VecVisionForSemanticSegmentation":
      SCREAMING_SNAKE_CASE  :  Dict								=		inputs_dict['''pixel_values'''].shape
      SCREAMING_SNAKE_CASE  :  Dict								=		torch.zeros(
          [self.model_tester.batch_size, height, width]    ,device=lowerCAmelCase_      ).long()
     SCREAMING_SNAKE_CASE  :  Optional[int]								=		model_class(lowerCAmelCase_      )
     model.gradient_checkpointing_enable()
     model.to(lowerCAmelCase_      )
     model.train()
     SCREAMING_SNAKE_CASE  :  Union[str, Any]								=		self._prepare_for_class(lowerCAmelCase_    ,lowerCAmelCase_    ,return_labels=lowerCAmelCase_      )
     SCREAMING_SNAKE_CASE  :  List[Any]								=		model(**lowerCAmelCase_      ).loss
     loss.backward()






   def 					__a			(       self      ):
    SCREAMING_SNAKE_CASE  :  List[str]								=		self.model_tester.prepare_config_and_inputs_for_common()

    SCREAMING_SNAKE_CASE  :  List[str]								=		_config_zero_init(lowerCAmelCase_      )
    for model_class in self.all_model_classes:
     SCREAMING_SNAKE_CASE  :  int								=		model_class(config=lowerCAmelCase_      )
     for name, param in model.named_parameters():
      # we skip lambda parameters as these require special initial values
      # determined by config.layer_scale_init_value
      if "lambda" in name:
       continue
      if param.requires_grad:
       self.assertIn(
           ((param.data.mean() * 1e9).round() / 1e9).item()    ,[0.0, 1.0]    ,msg=f"""Parameter {name} of model {model_class} seems not properly initialized"""    ,)






   def 					__a			(       self    ,__SCREAMING_SNAKE_CASE    ,__SCREAMING_SNAKE_CASE    ,__SCREAMING_SNAKE_CASE    ,__SCREAMING_SNAKE_CASE=2e-4    ,__SCREAMING_SNAKE_CASE="outputs"    ,__SCREAMING_SNAKE_CASE=None      ):
    super().check_pt_tf_outputs(lowerCAmelCase_    ,lowerCAmelCase_    ,lowerCAmelCase_    ,lowerCAmelCase_    ,lowerCAmelCase_    ,lowerCAmelCase_      )






   def 					__a			(       self      ):
    SCREAMING_SNAKE_CASE  :  Dict								=		self.model_tester.prepare_config_and_inputs()
    self.model_tester.create_and_check_for_image_classification(*lowerCAmelCase_      )






   @slow
   def 					__a			(       self      ):
    for model_name in DATA2VEC_VISION_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
     SCREAMING_SNAKE_CASE  :  Any								=		DataaVecVisionModel.from_pretrained(lowerCAmelCase_      )
     self.assertIsNotNone(lowerCAmelCase_      )



def        SCREAMING_SNAKE_CASE_  (	)       ->	Any:
 SCREAMING_SNAKE_CASE  :  Optional[int]								=		Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png'							)
 return image





@require_torch
@require_vision
class 		_a     (							unittest.TestCase  ):







   """simple docstring"""




   @cached_property
   def 					__a			(       self      ):
    return (
        BeitImageProcessor.from_pretrained('facebook/data2vec-vision-base-ft1k'      ) if is_vision_available() else None
    )






   @slow
   def 					__a			(       self      ):
    SCREAMING_SNAKE_CASE  :  List[Any]								=		DataaVecVisionForImageClassification.from_pretrained('facebook/data2vec-vision-base-ft1k'      ).to(
        lowerCAmelCase_      )

    SCREAMING_SNAKE_CASE  :  int								=		self.default_image_processor
    SCREAMING_SNAKE_CASE  :  List[str]								=		prepare_img()
    SCREAMING_SNAKE_CASE  :  List[Any]								=		image_processor(images=lowerCAmelCase_    ,return_tensors='pt'      ).to(lowerCAmelCase_      )

    # forward pass
    with torch.no_grad():
     SCREAMING_SNAKE_CASE  :  str								=		model(**lowerCAmelCase_      )
    SCREAMING_SNAKE_CASE  :  Any								=		outputs.logits

    # verify the logits
    SCREAMING_SNAKE_CASE  :  List[str]								=		torch.Size((1, 1000)      )
    self.assertEqual(logits.shape    ,lowerCAmelCase_      )

    SCREAMING_SNAKE_CASE  :  Optional[Any]								=		torch.tensor([0.3277, -0.1395, 0.0911]      ).to(lowerCAmelCase_      )

    self.assertTrue(torch.allclose(logits[0, :3]    ,lowerCAmelCase_    ,atol=1e-4      )      )

    SCREAMING_SNAKE_CASE  :  Union[str, Any]								=		[model.config.labelaid[i] for i in ['''remote control, remote''', '''tabby, tabby cat''']]
    self.assertEqual(logits[0].topk(2      ).indices.cpu().tolist()    ,lowerCAmelCase_      )




from __future__ import annotations






def     lowerCamelCase__				(   a ) ->  Union[str, Any]:
   global graph, reversed_graph, scc, component, visit, stack
   if visit[u]:
      return
   _A:    Optional[Any]						     =			True
   for v in graph[u]:
      dfs(a )
   stack.append(a )






def     lowerCamelCase__				(   a ) ->  List[Any]:
   global graph, reversed_graph, scc, component, visit, stack
   if visit[u]:
      return
   _A:    str						     =			True
   component.append(a )
   for v in reversed_graph[u]:
      dfsa(a )






def     lowerCamelCase__				(   ) ->  str:
   global graph, reversed_graph, scc, component, visit, stack
   for i in range(a ):
      dfs(a )
   _A:    Optional[Any]						     =			[False] * n
   for i in stack[::-1]:
      if visit[i]:
         continue
      _A:    Optional[Any]						     =			[]
      dfsa(a )
      scc.append(a )
   return scc


if __name__ == "__main__":
   # n - no of nodes, m - no of edges
   UpperCAmelCase__     ,UpperCAmelCase__						:	Any	     = list(map(int, input().strip().split()))

   UpperCAmelCase__						:	list[list[int]]	     = [[] for _ in range(n)]  # graph
   UpperCAmelCase__						:	list[list[int]]	     = [[] for i in range(n)]  # reversed graph
   # input graph data (edges)
   for _ in range(m):
      UpperCAmelCase__     ,UpperCAmelCase__						:	str	     = list(map(int, input().strip().split()))
      graph[u].append(v)
      reversed_graph[v].append(u)

   UpperCAmelCase__						:	list[int]	     = []
   UpperCAmelCase__						:	list[bool]	     = [False] * n
   UpperCAmelCase__						:	list[int]	     = []
   UpperCAmelCase__						:	list[int]	     = []
   print(kosaraju())



