

import asyncio
import os
import re
import sys
import tempfile
import unittest
from contextlib import contextmanager
from copy import deepcopy
from distutils.util import strtobool
from enum import Enum
from importlib.util import find_spec
from pathlib import Path
from unittest.mock import patch

import pyarrow as pa
import pytest
import requests
from packaging import version

from datasets import config


if config.PY_VERSION < version.parse('''3.8'''):
    import importlib_metadata
else:
    import importlib.metadata as importlib_metadata







def 						lowerCamelCase__      ( __A    :Optional[Any]	,__A    :List[str]=False		):


       """simple docstring"""




       try:
              __snake_case       	=							os.environ[key]
       except KeyError:
              # KEY isn't set, default to `default`.
              __snake_case       	=							default
       else:
              # KEY is set, convert it to True or False.
              try:
                     __snake_case       	=							strtobool(__A		)
              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


UpperCamelCase__		 =     parse_flag_from_env('''RUN_SLOW''', default=False)
UpperCamelCase__		 =     parse_flag_from_env('''RUN_REMOTE''', default=False)
UpperCamelCase__		 =     parse_flag_from_env('''RUN_LOCAL''', default=True)
UpperCamelCase__		 =     parse_flag_from_env('''RUN_PACKAGED''', default=True)

# Compression
UpperCamelCase__		 =     pytest.mark.skipif(not config.LZ4_AVAILABLE, reason='''test requires lz4''')
UpperCamelCase__		 =     pytest.mark.skipif(not config.PY7ZR_AVAILABLE, reason='''test requires py7zr''')
UpperCamelCase__		 =     pytest.mark.skipif(not config.ZSTANDARD_AVAILABLE, reason='''test requires zstandard''')

# Audio
UpperCamelCase__		 =     pytest.mark.skipif(
    # On Windows and OS X, soundfile installs sndfile
    find_spec('''soundfile''') is None or version.parse(importlib_metadata.version('''soundfile''')) < version.parse('''0.12.0'''),
    reason='''test requires sndfile>=0.12.1: \'pip install \"soundfile>=0.12.1\"\'; ''',
)

# Beam
UpperCamelCase__		 =     pytest.mark.skipif(
    not config.BEAM_AVAILABLE or config.DILL_VERSION >= version.parse('''0.3.2'''),
    reason='''test requires apache-beam and a compatible dill version''',
)

# Dill-cloudpickle compatibility
UpperCamelCase__		 =     pytest.mark.skipif(
    config.DILL_VERSION <= version.parse('''0.3.2'''),
    reason='''test requires dill>0.3.2 for cloudpickle compatibility''',
)

# Windows
UpperCamelCase__		 =     pytest.mark.skipif(
    sys.platform == '''win32''',
    reason='''test should not be run on Windows''',
)







def 						lowerCamelCase__      ( __A    :Optional[int]		):


       """simple docstring"""




       try:
              import faiss  # noqa
       except ImportError:
              __snake_case       	=							unittest.skip("""test requires faiss"""		)(__A		)
       return test_case







def 						lowerCamelCase__      ( __A    :Tuple		):


       """simple docstring"""




       try:
              import regex  # noqa
       except ImportError:
              __snake_case       	=							unittest.skip("""test requires regex"""		)(__A		)
       return test_case







def 						lowerCamelCase__      ( __A    :Optional[int]		):


       """simple docstring"""




       try:
              import elasticsearch  # noqa
       except ImportError:
              __snake_case       	=							unittest.skip("""test requires elasticsearch"""		)(__A		)
       return test_case







def 						lowerCamelCase__      ( __A    :Union[str, Any]		):


       """simple docstring"""




       try:
              import sqlalchemy  # noqa
       except ImportError:
              __snake_case       	=							unittest.skip("""test requires sqlalchemy"""		)(__A		)
       return test_case







def 						lowerCamelCase__      ( __A    :Dict		):


       """simple docstring"""




       if not config.TORCH_AVAILABLE:
              __snake_case       	=							unittest.skip("""test requires PyTorch"""		)(__A		)
       return test_case







def 						lowerCamelCase__      ( __A    :str		):


       """simple docstring"""




       if not config.TF_AVAILABLE:
              __snake_case       	=							unittest.skip("""test requires TensorFlow"""		)(__A		)
       return test_case







def 						lowerCamelCase__      ( __A    :List[str]		):


       """simple docstring"""




       if not config.JAX_AVAILABLE:
              __snake_case       	=							unittest.skip("""test requires JAX"""		)(__A		)
       return test_case







def 						lowerCamelCase__      ( __A    :Dict		):


       """simple docstring"""




       if not config.PIL_AVAILABLE:
              __snake_case       	=							unittest.skip("""test requires Pillow"""		)(__A		)
       return test_case







def 						lowerCamelCase__      ( __A    :str		):


       """simple docstring"""




       try:
              import transformers  # noqa F401
       except ImportError:
              return unittest.skip("""test requires transformers"""		)(__A		)
       else:
              return test_case







def 						lowerCamelCase__      ( __A    :Tuple		):


       """simple docstring"""




       try:
              import tiktoken  # noqa F401
       except ImportError:
              return unittest.skip("""test requires tiktoken"""		)(__A		)
       else:
              return test_case







def 						lowerCamelCase__      ( __A    :List[Any]		):


       """simple docstring"""




       try:
              import spacy  # noqa F401
       except ImportError:
              return unittest.skip("""test requires spacy"""		)(__A		)
       else:
              return test_case







def 						lowerCamelCase__      ( __A    :Optional[int]		):


       """simple docstring"""




       def _require_spacy_model(__A    :List[str]		):
              try:
                     import spacy  # noqa F401

                     spacy.load(__A		)
              except ImportError:
                     return unittest.skip("""test requires spacy"""		)(__A		)
              except OSError:
                     return unittest.skip("""test requires spacy model '{}'""".format(__A		)		)(__A		)
              else:
                     return test_case

       return _require_spacy_model







def 						lowerCamelCase__      ( __A    :int		):


       """simple docstring"""




       try:
              import pyspark  # noqa F401
       except ImportError:
              return unittest.skip("""test requires pyspark"""		)(__A		)
       else:
              return test_case







def 						lowerCamelCase__      ( __A    :Any		):


       """simple docstring"""




       try:
              import joblibspark  # noqa F401
       except ImportError:
              return unittest.skip("""test requires joblibspark"""		)(__A		)
       else:
              return test_case







def 						lowerCamelCase__      ( __A    :Optional[Any]		):


       """simple docstring"""




       if not _run_slow_tests or _run_slow_tests == 0:
              __snake_case       	=							unittest.skip("""test is slow"""		)(__A		)
       return test_case







def 						lowerCamelCase__      ( __A    :Tuple		):


       """simple docstring"""




       if not _run_local_tests or _run_local_tests == 0:
              __snake_case       	=							unittest.skip("""test is local"""		)(__A		)
       return test_case







def 						lowerCamelCase__      ( __A    :List[Any]		):


       """simple docstring"""




       if not _run_packaged_tests or _run_packaged_tests == 0:
              __snake_case       	=							unittest.skip("""test is packaged"""		)(__A		)
       return test_case







def 						lowerCamelCase__      ( __A    :Union[str, Any]		):


       """simple docstring"""




       if not _run_remote_tests or _run_remote_tests == 0:
              __snake_case       	=							unittest.skip("""test requires remote"""		)(__A		)
       return test_case







def 						lowerCamelCase__      ( *__A    :Any		):


       """simple docstring"""




       def decorate(cls    :Union[str, Any]		):
              for name, fn in cls.__dict__.items():
                     if callable(__A		) and name.startswith("""test"""		):
                            for decorator in decorators:
                                   __snake_case       	=							decorator(__A		)
                            setattr(cls	,__A	,__A		)
              return cls

       return decorate

class     __snake_case    (				snake_case__  ):
       """simple docstring"""







       pass






class     __snake_case    (				snake_case__  ):
       """simple docstring"""







       __SCREAMING_SNAKE_CASE				    =							0
       __SCREAMING_SNAKE_CASE				    =							1
       __SCREAMING_SNAKE_CASE				    =							2







@contextmanager
def 						lowerCamelCase__      ( __A    :Tuple=OfflineSimulationMode.CONNECTION_FAILS	,__A    :int=1e-1_6		):


       """simple docstring"""




       __snake_case       	=							requests.Session().request

       def timeout_request(__A    :List[str]	,__A    :Tuple	,__A    :List[str]	,**__A    :str		):
              # Change the url to an invalid url so that the connection hangs
              __snake_case       	=							"""https://10.255.255.1"""
              if kwargs.get("""timeout"""		) is None:
                     raise RequestWouldHangIndefinitelyError(
                         F'Tried a call to {url} in offline mode with no timeout set. Please set a timeout.'		)
              __snake_case       	=							timeout
              try:
                     return online_request(__A	,__A	,**__A		)
              except Exception as e:
                     # The following changes in the error are just here to make the offline timeout error prettier
                     __snake_case       	=							url
                     __snake_case       	=							e.args[0]
                     __snake_case       	=							(max_retry_error.args[0].replace("""10.255.255.1"""	,F'OfflineMock[{url}]'		),)
                     __snake_case       	=							(max_retry_error,)
                     raise

       def raise_connection_error(__A    :Dict	,__A    :List[str]	,**__A    :List[str]		):
              raise requests.ConnectionError("""Offline mode is enabled."""	,request=__A		)

       if mode is OfflineSimulationMode.CONNECTION_FAILS:
              with patch("""requests.Session.send"""	,__A		):
                     yield
       elif mode is OfflineSimulationMode.CONNECTION_TIMES_OUT:
              # inspired from https://stackoverflow.com/a/904609
              with patch("""requests.Session.request"""	,__A		):
                     yield
       elif mode is OfflineSimulationMode.HF_DATASETS_OFFLINE_SET_TO_1:
              with patch("""datasets.config.HF_DATASETS_OFFLINE"""	,__A		):
                     yield
       else:
              raise ValueError("""Please use a value from the OfflineSimulationMode enum."""		)







@contextmanager
def 						lowerCamelCase__      ( *__A    :Any	,**__A    :Optional[int]		):


       """simple docstring"""




       __snake_case       	=							str(Path().resolve()		)
       with tempfile.TemporaryDirectory(*__A	,**__A		) as tmp_dir:
              try:
                     os.chdir(__A		)
                     yield
              finally:
                     os.chdir(__A		)







@contextmanager
def 						lowerCamelCase__      ( ):


       """simple docstring"""




       import gc

       gc.collect()
       __snake_case       	=							pa.total_allocated_bytes()
       yield
       assert pa.total_allocated_bytes() - previous_allocated_memory > 0, "Arrow memory didn't increase."







@contextmanager
def 						lowerCamelCase__      ( ):


       """simple docstring"""




       import gc

       gc.collect()
       __snake_case       	=							pa.total_allocated_bytes()
       yield
       assert pa.total_allocated_bytes() - previous_allocated_memory <= 0, "Arrow memory wasn't expected to increase."







def 						lowerCamelCase__      ( __A    :List[str]	,__A    :str		):


       """simple docstring"""




       return deepcopy(__A		).integers(0	,1_0_0	,1_0		).tolist() == deepcopy(__A		).integers(0	,1_0_0	,1_0		).tolist()







def 						lowerCamelCase__      ( __A    :List[str]		):


       """simple docstring"""




       import decorator
       from requests.exceptions import HTTPError

       def _wrapper(__A    :str	,*__A    :Optional[int]	,**__A    :Any		):
              try:
                     return func(*__A	,**__A		)
              except HTTPError as err:
                     if str(__A		).startswith("""500"""		) or str(__A		).startswith("""502"""		):
                            pytest.xfail(str(__A		)		)
                     raise err

       return decorator.decorator(_wrapper	,__A		)

class     __snake_case    :
       """simple docstring"""







       def __init__(		self      , _UpperCamelCase      , _UpperCamelCase      , _UpperCamelCase   )      ->							Any:






              """simple docstring"""


              __snake_case       	=							returncode
              __snake_case       	=							stdout
              __snake_case       	=							stderr







async def 						lowerCamelCase__      ( __A    :Dict	,__A    :Optional[Any]		):


       """simple docstring"""




       while True:
              __snake_case       	=							await stream.readline()
              if line:
                     callback(__A		)
              else:
                     break







async def 						lowerCamelCase__      ( __A    :Any	,__A    :Tuple=None	,__A    :Tuple=None	,__A    :Optional[int]=None	,__A    :Optional[int]=False	,__A    :int=False		):


       """simple docstring"""




       if echo:
              print("""\nRunning: """	,""" """.join(__A		)		)

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

       # 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)

       __snake_case       	=							[]
       __snake_case       	=							[]

       def tee(__A    :Any	,__A    :Any	,__A    :Optional[int]	,__A    :Optional[Any]=""		):
              __snake_case       	=							line.decode("""utf-8"""		).rstrip()
              sink.append(__A		)
              if not quiet:
                     print(__A	,__A	,file=__A		)

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







def 						lowerCamelCase__      ( __A    :Union[str, Any]	,__A    :str=None	,__A    :Any=None	,__A    :Tuple=1_8_0	,__A    :List[Any]=False	,__A    :str=True		):


       """simple docstring"""




       __snake_case       	=							asyncio.get_event_loop()
       __snake_case       	=							loop.run_until_complete(
           _stream_subprocess(__A	,env=__A	,stdin=__A	,timeout=__A	,quiet=__A	,echo=__A		)		)

       __snake_case       	=							""" """.join(__A		)
       if result.returncode > 0:
              __snake_case       	=							"""\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}'		)

       # check that the subprocess actually did run and produced some output, should the test rely on
       # the remote side to do the testing
       if not result.stdout and not result.stderr:
              raise RuntimeError(F'\'{cmd_str}\' produced no output.'		)

       return result







def 						lowerCamelCase__      ( ):


       """simple docstring"""




       __snake_case       	=							os.environ.get("""PYTEST_XDIST_WORKER"""	,"""gw0"""		)
       __snake_case       	=							re.sub(r"""^gw"""	,""""""	,__A	,0	,re.M		)
       return int(__A		)







def 						lowerCamelCase__      ( ):


       """simple docstring"""




       __snake_case       	=							2_9_5_0_0
       __snake_case       	=							pytest_xdist_worker_id()
       return port + uniq_delta




from __future__ import annotations







def 						lowerCamelCase__      ( __A    :list[float]	,__A    :Union[str, Any]		):


       """simple docstring"""




       print(F'Vertex\tShortest Distance from vertex {src}'		)
       for i, d in enumerate(__A		):
              print(F'{i}\t\t{d}'		)







def 						lowerCamelCase__      ( __A    :list[dict[str, int]]	,__A    :list[float]	,__A    :int		):


       """simple docstring"""




       for j in range(__A		):
              __snake_case	,    __snake_case	,    __snake_case       	=							(graph[j][k] for k in ["""src""", """dst""", """weight"""])
              if distance[u] != float("""inf"""		) and distance[u] + w < distance[v]:
                     return True
       return False







def 						lowerCamelCase__      ( __A    :list[dict[str, int]]	,__A    :int	,__A    :int	,__A    :int		):


       """simple docstring"""




       __snake_case       	=							[float("""inf"""		)] * vertex_count
       __snake_case       	=							0.0

       for _ in range(vertex_count - 1		):
              for j in range(__A		):
                     __snake_case	,    __snake_case	,    __snake_case       	=							(graph[j][k] for k in ["""src""", """dst""", """weight"""])

                     if distance[u] != float("""inf"""		) and distance[u] + w < distance[v]:
                            __snake_case       	=							distance[u] + w

       __snake_case       	=							check_negative_cycle(__A	,__A	,__A		)
       if negative_cycle_exists:
              raise Exception("""Negative cycle found"""		)

       return distance


if __name__ == "__main__":
    import doctest

    doctest.testmod()

    UpperCamelCase__		 =     int(input('''Enter number of vertices: ''').strip())
    UpperCamelCase__		 =     int(input('''Enter number of edges: ''').strip())

    UpperCamelCase__		 =     [{} for _ in range(E)]

    for i in range(E):
        print('''Edge ''', i + 1)
        UpperCamelCase__ ,UpperCamelCase__ ,UpperCamelCase__		 =     (
            int(x)
            for x in input('''Enter source, destination, weight: ''').strip().split(''' ''')
        )
        UpperCamelCase__		 =     {'''src''': src, '''dst''': dest, '''weight''': weight}

    UpperCamelCase__		 =     int(input('''\nEnter shortest path source:''').strip())
    UpperCamelCase__		 =     bellman_ford(graph, V, E, source)
    print_distance(shortest_distance, 0)

