


import os
import socket
from contextlib import contextmanager

import torch

from ..commands.config.default import write_basic_config  # noqa: F401
from ..state import PartialState
from .dataclasses import DistributedType
from .imports import is_deepspeed_available, is_tpu_available
from .transformer_engine import convert_model
from .versions import is_torch_version


if is_deepspeed_available():
  from deepspeed import DeepSpeedEngine

if is_tpu_available(check_device=False):
  import torch_xla.core.xla_model as xm



def     __lowerCAmelCase						(							snake_case	:    Optional[int] )       ->							Dict:







   if is_torch_version("""<"""						,      """2.0.0""" ) or not hasattr(_lowercase						,      """_dynamo""" ):
      return False
   return isinstance(_lowercase						,      torch._dynamo.eval_frame.OptimizedModule )



def     __lowerCAmelCase						(							snake_case	:    Dict						,      snake_case	:    str = True )       ->							List[Any]:
   __lowerCamelCase:				Tuple     =	(torch.nn.parallel.DistributedDataParallel, torch.nn.DataParallel)

   __lowerCamelCase:				Optional[Any]     =	is_compiled_module(_lowercase )
   if is_compiled:
      __lowerCamelCase:				Union[str, Any]     =	model
      __lowerCamelCase:				Optional[int]     =	model._orig_mod

   if is_deepspeed_available():
      options += (DeepSpeedEngine,)

   while isinstance(_lowercase						,      _lowercase ):
      __lowerCamelCase:				Dict     =	model.module

   if not keep_fpaa_wrapper:
      __lowerCamelCase:				Dict     =	getattr(_lowercase						,      """forward""" )
      __lowerCamelCase:				str     =	model.__dict__.pop("""_original_forward"""						,      _lowercase )
      if original_forward is not None:
         while hasattr(_lowercase						,      """__wrapped__""" ):
            __lowerCamelCase:				List[str]     =	forward.__wrapped__
            if forward == original_forward:
               break
         __lowerCamelCase:				Optional[int]     =	forward
      if getattr(_lowercase						,      """_converted_to_transformer_engine"""						,      _lowercase ):
         convert_model(_lowercase						,      to_transformer_engine=_lowercase )

   if is_compiled:
      __lowerCamelCase:				str     =	model
      __lowerCamelCase:				Any     =	compiled_model

   return model



def     __lowerCAmelCase						(							)       ->							List[str]:
   PartialState().wait_for_everyone()



def     __lowerCAmelCase						(							snake_case	:    Dict						,      snake_case	:    Union[str, Any] )       ->							str:







   if PartialState().distributed_type == DistributedType.TPU:
      xm.save(_lowercase						,      _lowercase )
   elif PartialState().local_process_index == 0:
      torch.save(_lowercase						,      _lowercase )



@contextmanager
def     __lowerCAmelCase						(							**snake_case	:    Any )       ->							Optional[Any]:







   for key, value in kwargs.items():
      __lowerCamelCase:				Dict     =	str(_lowercase )

   yield

   for key in kwargs:
      if key.upper() in os.environ:
         del os.environ[key.upper()]



def     __lowerCAmelCase						(							snake_case	:    List[Any] )       ->							Dict:







   if not hasattr(_lowercase						,      """__qualname__""" ) and not hasattr(_lowercase						,      """__name__""" ):
      __lowerCamelCase:				List[Any]     =	getattr(_lowercase						,      """__class__"""						,      _lowercase )
   if hasattr(_lowercase						,      """__qualname__""" ):
      return obj.__qualname__
   if hasattr(_lowercase						,      """__name__""" ):
      return obj.__name__
   return str(_lowercase )



def     __lowerCAmelCase						(							snake_case	:    Any						,      snake_case	:    Optional[Any] )       ->							str:







   for key, value in source.items():
      if isinstance(_lowercase						,      _lowercase ):
         __lowerCamelCase:				Union[str, Any]     =	destination.setdefault(_lowercase						,      {} )
         merge_dicts(_lowercase						,      _lowercase )
      else:
         __lowerCamelCase:				Any     =	value

   return destination







def     __lowerCAmelCase						(							snake_case	:    Optional[Any] = None )       ->							Union[str, Any]:







   if port is None:
      __lowerCamelCase:				Optional[int]     =	29500
   with socket.socket(socket.AF_INET						,      socket.SOCK_STREAM ) as s:
      return s.connect_ex(("""localhost""", port) ) == 0






_A		:				Tuple									=       '''ABCDEFGHIJKLMNOPQRSTUVWXYZ'''



def     __lowerCAmelCase						(							)       ->							None:
   __lowerCamelCase:				Optional[int]     =	input("""Enter message: """ )
   __lowerCamelCase:				Dict     =	input("""Enter key [alphanumeric]: """ )
   __lowerCamelCase:				List[Any]     =	input("""Encrypt/Decrypt [e/d]: """ )

   if mode.lower().startswith("""e""" ):
      __lowerCamelCase:				Optional[int]     =	"""encrypt"""
      __lowerCamelCase:				Optional[int]     =	encrypt_message(snake_case						,      snake_case )
   elif mode.lower().startswith("""d""" ):
      __lowerCamelCase:				Union[str, Any]     =	"""decrypt"""
      __lowerCamelCase:				Optional[Any]     =	decrypt_message(snake_case						,      snake_case )

   print(f'\n{mode.title()}ed message:' )
   print(snake_case )



def     __lowerCAmelCase						(							snake_case	:    str						,      snake_case	:    str )       ->							str:
   return translate_message(snake_case						,      snake_case						,      """encrypt""" )



def     __lowerCAmelCase						(							snake_case	:    str						,      snake_case	:    str )       ->							str:
   return translate_message(snake_case						,      snake_case						,      """decrypt""" )



def     __lowerCAmelCase						(							snake_case	:    str						,      snake_case	:    str						,      snake_case	:    str )       ->							str:
   __lowerCamelCase:				Any     =	[]
   __lowerCamelCase:				Optional[int]     =	0
   __lowerCamelCase:				Any     =	key.upper()

   for symbol in message:
      __lowerCamelCase:				int     =	LETTERS.find(symbol.upper() )
      if num != -1:
         if mode == "encrypt":
            num += LETTERS.find(key[key_index] )
         elif mode == "decrypt":
            num -= LETTERS.find(key[key_index] )

         num %= len(snake_case )

         if symbol.isupper():
            translated.append(LETTERS[num] )
         elif symbol.islower():
            translated.append(LETTERS[num].lower() )

         key_index += 1
         if key_index == len(snake_case ):
            __lowerCamelCase:				Union[str, Any]     =	0
      else:
         translated.append(snake_case )
   return "".join(snake_case )


if __name__ == "__main__":
   main()


