




'''simple docstring'''







import asyncio
import os
import shutil
import subprocess
import sys
import tempfile
import unittest
from distutils.util import strtobool
from functools import partial
from pathlib import Path
from typing import List, Union
from unittest import mock

import torch

from ..state import AcceleratorState, PartialState
from ..utils import (
    gather,
    is_bnb_available,
    is_comet_ml_available,
    is_datasets_available,
    is_deepspeed_available,
    is_mps_available,
    is_safetensors_available,
    is_tensorboard_available,
    is_torch_version,
    is_tpu_available,
    is_transformers_available,
    is_wandb_available,
    is_xpu_available,
)





def 		snake_case_							(_a			:							str					,     _a			:							List[Any]=False  ):






    try:
        UpperCAmelCase     =	os.environ[key]
    except KeyError:
        # KEY isn't set, default to `default`.
        UpperCAmelCase     =	default
    else:
        # KEY is set, convert it to True or False.
        try:
            UpperCAmelCase     =	strtobool(__SCREAMING_SNAKE_CASE  )
        except ValueError:
            # More values are supported, but let's keep the message simple.
            raise ValueError(F"If set, {key} must be yes or no."  )
    return _value


A     :   Tuple									=parse_flag_from_env('RUN_SLOW', default=False)





def 		snake_case_							(_a			:							int  ):
    return unittest.skip('''Test was skipped'''  )(__SCREAMING_SNAKE_CASE  )





def 		snake_case_							(_a			:							Any  ):
    return unittest.skipUnless(_run_slow_tests					,     '''test is slow'''  )(__SCREAMING_SNAKE_CASE  )





def 		snake_case_							(_a			:							Any  ):
    return unittest.skipUnless(not torch.cuda.is_available()					,     '''test requires only a CPU'''  )(__SCREAMING_SNAKE_CASE  )





def 		snake_case_							(_a			:							List[Any]  ):
    return unittest.skipUnless(torch.cuda.is_available()					,     '''test requires a GPU'''  )(__SCREAMING_SNAKE_CASE  )





def 		snake_case_							(_a			:							Optional[int]  ):
    return unittest.skipUnless(is_xpu_available()					,     '''test requires a XPU'''  )(__SCREAMING_SNAKE_CASE  )





def 		snake_case_							(_a			:							Tuple  ):
    return unittest.skipUnless(is_mps_available()					,     '''test requires a `mps` backend support in `torch`'''  )(__SCREAMING_SNAKE_CASE  )





def 		snake_case_							(_a			:							Optional[int]  ):
    return unittest.skipUnless(
        is_transformers_available() and is_datasets_available()					,     '''test requires the Hugging Face suite'''  )(__SCREAMING_SNAKE_CASE  )





def 		snake_case_							(_a			:							Optional[Any]  ):
    return unittest.skipUnless(is_bnb_available()					,     '''test requires the bitsandbytes library'''  )(__SCREAMING_SNAKE_CASE  )





def 		snake_case_							(_a			:							str  ):
    return unittest.skipUnless(is_tpu_available()					,     '''test requires TPU'''  )(__SCREAMING_SNAKE_CASE  )





def 		snake_case_							(_a			:							Tuple  ):
    return unittest.skipUnless(torch.cuda.device_count() == 1					,     '''test requires a GPU'''  )(__SCREAMING_SNAKE_CASE  )





def 		snake_case_							(_a			:							List[str]  ):
    return unittest.skipUnless(torch.xpu.device_count() == 1					,     '''test requires a XPU'''  )(__SCREAMING_SNAKE_CASE  )





def 		snake_case_							(_a			:							Optional[Any]  ):
    return unittest.skipUnless(torch.cuda.device_count() > 1					,     '''test requires multiple GPUs'''  )(__SCREAMING_SNAKE_CASE  )





def 		snake_case_							(_a			:							List[Any]  ):
    return unittest.skipUnless(torch.xpu.device_count() > 1					,     '''test requires multiple XPUs'''  )(__SCREAMING_SNAKE_CASE  )





def 		snake_case_							(_a			:							Union[str, Any]  ):
    return unittest.skipUnless(is_safetensors_available()					,     '''test requires safetensors'''  )(__SCREAMING_SNAKE_CASE  )





def 		snake_case_							(_a			:							Any  ):
    return unittest.skipUnless(is_deepspeed_available()					,     '''test requires DeepSpeed'''  )(__SCREAMING_SNAKE_CASE  )





def 		snake_case_							(_a			:							Dict  ):
    return unittest.skipUnless(is_torch_version('''>='''					,     '''1.12.0'''  )					,     '''test requires torch version >= 1.12.0'''  )(__SCREAMING_SNAKE_CASE  )





def 		snake_case_							(_a			:							Dict=None					,     _a			:							Union[str, Any]=None  ):






    if test_case is None:
        return partial(__SCREAMING_SNAKE_CASE					,     version=__SCREAMING_SNAKE_CASE  )
    return unittest.skipUnless(is_torch_version('''>='''					,     __SCREAMING_SNAKE_CASE  )					,     F"test requires torch version >= {version}"  )(__SCREAMING_SNAKE_CASE  )





def 		snake_case_							(_a			:							List[Any]  ):
    return unittest.skipUnless(is_tensorboard_available()					,     '''test requires Tensorboard'''  )(__SCREAMING_SNAKE_CASE  )





def 		snake_case_							(_a			:							str  ):
    return unittest.skipUnless(is_wandb_available()					,     '''test requires wandb'''  )(__SCREAMING_SNAKE_CASE  )





def 		snake_case_							(_a			:							Tuple  ):
    return unittest.skipUnless(is_comet_ml_available()					,     '''test requires comet_ml'''  )(__SCREAMING_SNAKE_CASE  )


A     :   Any									=(
    any([is_wandb_available(), is_tensorboard_available()]) and not is_comet_ml_available()
)





def 		snake_case_							(_a			:							Any  ):
    return unittest.skipUnless(
        _atleast_one_tracker_available					,     '''test requires at least one tracker to be available and for `comet_ml` to not be installed'''					,     )(__SCREAMING_SNAKE_CASE  )


class     _a						(			unittest.TestCase				):
       __a       :  List[Any]            =      True
       @classmethod
       def 					A   (			cls		:			Union[str, Any]       ):



           '''simple docstring'''

           UpperCAmelCase     =	tempfile.mkdtemp()
       @classmethod
       def 					A   (			cls		:			Tuple       ):



           '''simple docstring'''

           if os.path.exists(cls.tmpdir       ):
               shutil.rmtree(cls.tmpdir       )







       def 					A   (			self		:			Union[str, Any]       ):



           '''simple docstring'''

           if self.clear_on_setup:
               for path in Path(self.tmpdir       ).glob('''**/*'''       ):
                   if path.is_file():
                       path.unlink()
                   elif path.is_dir():
                       shutil.rmtree(lowercase_       )






class     _a						(			unittest.TestCase				):
       def 					A   (			self		:			Dict       ):



           '''simple docstring'''

           super().tearDown()
           # Reset the state of the AcceleratorState singleton.
           AcceleratorState._reset_state()
           PartialState._reset_state()






class     _a						(			unittest.TestCase				):
       def 					A   (			self		:			Any     ,       lowercase		:			str       ):



           '''simple docstring'''

           UpperCAmelCase     =	mocks if isinstance(lowercase_     ,       (tuple, list)       ) else [mocks]
           for m in self.mocks:
               m.start()
               self.addCleanup(m.stop       )






def 		snake_case_							(_a			:							str  ):
    UpperCAmelCase     =	AcceleratorState()
    UpperCAmelCase     =	tensor[None].clone().to(state.device  )
    UpperCAmelCase     =	gather(__SCREAMING_SNAKE_CASE  ).cpu()
    UpperCAmelCase     =	tensor[0].cpu()
    for i in range(tensors.shape[0]  ):
        if not torch.equal(tensors[i]					,     __SCREAMING_SNAKE_CASE  ):
            return False
    return True


class     _a						:
       def __init__(			self		:			Optional[Any]     ,       lowercase		:			Tuple     ,       lowercase		:			Optional[Any]     ,       lowercase		:			str       ):



           '''simple docstring'''

           UpperCAmelCase     =	returncode
           UpperCAmelCase     =	stdout
           UpperCAmelCase     =	stderr






async def 		snake_case_							(_a			:							Tuple					,     _a			:							str  ):






    while True:
        UpperCAmelCase     =	await stream.readline()
        if line:
            callback(__SCREAMING_SNAKE_CASE  )
        else:
            break





async def 		snake_case_							(_a			:							Any					,     _a			:							int=None					,     _a			:							Optional[Any]=None					,     _a			:							int=None					,     _a			:							Union[str, Any]=False					,     _a			:							Optional[int]=False  ):






    if echo:
        print('''\nRunning: '''					,     ''' '''.join(__SCREAMING_SNAKE_CASE  )  )

    UpperCAmelCase     =	await asyncio.create_subprocess_exec(
        cmd[0]					,     *cmd[1:]					,     stdin=__SCREAMING_SNAKE_CASE					,     stdout=asyncio.subprocess.PIPE					,     stderr=asyncio.subprocess.PIPE					,     env=__SCREAMING_SNAKE_CASE					,     )

    # note: there is a warning for a possible deadlock when using `wait` with huge amounts of data in the pipe
    # https://docs.python.org/3/library/asyncio-subprocess.html#asyncio.asyncio.subprocess.Process.wait
    #
    # If it starts hanging, will need to switch to the following code. The problem is that no data
    # will be seen until it's done and if it hangs for example there will be no debug info.
    # out, err = await p.communicate()
    # return _RunOutput(p.returncode, out, err)

    UpperCAmelCase     =	[]
    UpperCAmelCase     =	[]

    def tee(_a			:							Union[str, Any]					,     _a			:							str					,     _a			:							Optional[Any]					,     _a			:							List[Any]=""  ):
        UpperCAmelCase     =	line.decode('''utf-8'''  ).rstrip()
        sink.append(__SCREAMING_SNAKE_CASE  )
        if not quiet:
            print(__SCREAMING_SNAKE_CASE					,     __SCREAMING_SNAKE_CASE					,     file=__SCREAMING_SNAKE_CASE  )

    # XXX: the timeout doesn't seem to make any difference here
    await asyncio.wait(
        [
            asyncio.create_task(_read_stream(p.stdout					,     lambda _a  : tee(__SCREAMING_SNAKE_CASE					,     __SCREAMING_SNAKE_CASE					,     sys.stdout					,     label='''stdout:'''  )  )  ),
            asyncio.create_task(_read_stream(p.stderr					,     lambda _a  : tee(__SCREAMING_SNAKE_CASE					,     __SCREAMING_SNAKE_CASE					,     sys.stderr					,     label='''stderr:'''  )  )  ),
        ]					,     timeout=__SCREAMING_SNAKE_CASE					,     )
    return _RunOutput(await p.wait()					,     __SCREAMING_SNAKE_CASE					,     __SCREAMING_SNAKE_CASE  )





def 		snake_case_							(_a			:							Optional[Any]					,     _a			:							List[str]=None					,     _a			:							Optional[int]=None					,     _a			:							int=1_8_0					,     _a			:							Optional[int]=False					,     _a			:							str=True  ):
    UpperCAmelCase     =	asyncio.get_event_loop()
    UpperCAmelCase     =	loop.run_until_complete(
        _stream_subprocess(__SCREAMING_SNAKE_CASE					,     env=__SCREAMING_SNAKE_CASE					,     stdin=__SCREAMING_SNAKE_CASE					,     timeout=__SCREAMING_SNAKE_CASE					,     quiet=__SCREAMING_SNAKE_CASE					,     echo=__SCREAMING_SNAKE_CASE  )  )

    UpperCAmelCase     =	" ".join(__SCREAMING_SNAKE_CASE  )
    if result.returncode > 0:
        UpperCAmelCase     =	"\n".join(result.stderr  )
        raise RuntimeError(
            F"\'{cmd_str}\' failed with returncode {result.returncode}\n\n"
            F"The combined stderr from workers follows:\n{stderr}"  )

    return result


class     _a						(			snake_case__				):
       pass






def 		snake_case_							(_a			:							Tuple					,     _a			:							Union[str, Any]=False  ):






    try:
        UpperCAmelCase     =	subprocess.check_output(__SCREAMING_SNAKE_CASE					,     stderr=subprocess.STDOUT  )
        if return_stdout:
            if hasattr(__SCREAMING_SNAKE_CASE					,     '''decode'''  ):
                UpperCAmelCase     =	output.decode('''utf-8'''  )
            return output
    except subprocess.CalledProcessError as e:
        raise SubprocessCallException(
            F"Command `{' '.join(__SCREAMING_SNAKE_CASE  )}` failed with the following error:\n\n{e.output.decode()}"  ) from e










'''simple docstring'''







from typing import Any


class     _a						:
       def __init__(			self		:			int     ,       lowercase		:			Any       ):



           '''simple docstring'''

           UpperCAmelCase     =	data
           UpperCAmelCase     =	None






class     _a						:
       def __init__(			self		:			int       ):



           '''simple docstring'''

           UpperCAmelCase     =	None
       def 					A   (			self		:			int       ):



           '''simple docstring'''

           UpperCAmelCase     =	self.head
           while temp is not None:
               print(temp.data     ,       end=''' '''       )
               UpperCAmelCase     =	temp.next
           print()
       def 					A   (			self		:			List[str]     ,       lowercase		:			Any       ):



           '''simple docstring'''

           UpperCAmelCase     =	Node(lowercase       )
           UpperCAmelCase     =	self.head
           UpperCAmelCase     =	new_node







       def 					A   (			self		:			List[Any]     ,       lowercase		:			List[Any]     ,       lowercase		:			str       ):



           '''simple docstring'''

           if node_data_a == node_data_a:
               return
           else:
               UpperCAmelCase     =	self.head
               while node_a is not None and node_a.data != node_data_a:
                   UpperCAmelCase     =	node_a.next

               UpperCAmelCase     =	self.head
               while node_a is not None and node_a.data != node_data_a:
                   UpperCAmelCase     =	node_a.next

               if node_a is None or node_a is None:
                   return

               UpperCAmelCase ,  UpperCAmelCase     =	node_a.data, node_a.data


if __name__ == "__main__":
   A									=LinkedList()
   for i in range(5, 0, -1):
      ll.push(i)

   ll.print_list()

   ll.swap_nodes(1, 4)
   print('After swapping')
   ll.print_list()




