
"""simple docstring"""
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    (     lowerCamelCase__							:							List[Any],						lowerCamelCase__							:							List[str]=False				)  ->    str:
  try:
    _SCREAMING_SNAKE_CASE   :				Optional[Any]							    = os.environ[key]
  except KeyError:
    # KEY isn't set, default to `default`.
    _SCREAMING_SNAKE_CASE   :				Union[str, Any]							    = default
  else:
    # KEY is set, convert it to True or False.
    try:
      _SCREAMING_SNAKE_CASE   :				int							    = strtobool(_lowercase				)
    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


lowercase_       :						Optional[int]     					=	parse_flag_from_env('''RUN_SLOW''', default=False)
lowercase_       :						Dict     					=	parse_flag_from_env('''RUN_REMOTE''', default=False)
lowercase_       :						Optional[int]     					=	parse_flag_from_env('''RUN_LOCAL''', default=True)
lowercase_       :						Optional[Any]     					=	parse_flag_from_env('''RUN_PACKAGED''', default=True)

# Compression
lowercase_       :						Tuple     					=	pytest.mark.skipif(not config.LZ4_AVAILABLE, reason='''test requires lz4''')
lowercase_       :						Any     					=	pytest.mark.skipif(not config.PY7ZR_AVAILABLE, reason='''test requires py7zr''')
lowercase_       :						str     					=	pytest.mark.skipif(not config.ZSTANDARD_AVAILABLE, reason='''test requires zstandard''')

# Audio
lowercase_       :						str     					=	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
lowercase_       :						List[str]     					=	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
lowercase_       :						List[str]     					=	pytest.mark.skipif(
    config.DILL_VERSION <= version.parse('''0.3.2'''),
    reason='''test requires dill>0.3.2 for cloudpickle compatibility''',
)

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





def    _lowerCAmelCase    (     lowerCamelCase__							:							List[Any]				)  ->    Dict:
  try:
    import faiss  # noqa
  except ImportError:
    _SCREAMING_SNAKE_CASE   :				Optional[Any]							    = unittest.skip("test requires faiss"				)(_lowercase				)
  return test_case





def    _lowerCAmelCase    (     lowerCamelCase__							:							str				)  ->    List[Any]:
  try:
    import regex  # noqa
  except ImportError:
    _SCREAMING_SNAKE_CASE   :				Tuple							    = unittest.skip("test requires regex"				)(_lowercase				)
  return test_case





def    _lowerCAmelCase    (     lowerCamelCase__							:							List[str]				)  ->    List[Any]:
  try:
    import elasticsearch  # noqa
  except ImportError:
    _SCREAMING_SNAKE_CASE   :				str							    = unittest.skip("test requires elasticsearch"				)(_lowercase				)
  return test_case





def    _lowerCAmelCase    (     lowerCamelCase__							:							int				)  ->    Dict:
  try:
    import sqlalchemy  # noqa
  except ImportError:
    _SCREAMING_SNAKE_CASE   :				Tuple							    = unittest.skip("test requires sqlalchemy"				)(_lowercase				)
  return test_case





def    _lowerCAmelCase    (     lowerCamelCase__							:							Optional[int]				)  ->    int:
  if not config.TORCH_AVAILABLE:
    _SCREAMING_SNAKE_CASE   :				Dict							    = unittest.skip("test requires PyTorch"				)(_lowercase				)
  return test_case





def    _lowerCAmelCase    (     lowerCamelCase__							:							Optional[Any]				)  ->    List[str]:
  if not config.TF_AVAILABLE:
    _SCREAMING_SNAKE_CASE   :				int							    = unittest.skip("test requires TensorFlow"				)(_lowercase				)
  return test_case





def    _lowerCAmelCase    (     lowerCamelCase__							:							List[str]				)  ->    List[Any]:
  if not config.JAX_AVAILABLE:
    _SCREAMING_SNAKE_CASE   :				Optional[int]							    = unittest.skip("test requires JAX"				)(_lowercase				)
  return test_case





def    _lowerCAmelCase    (     lowerCamelCase__							:							Tuple				)  ->    str:
  if not config.PIL_AVAILABLE:
    _SCREAMING_SNAKE_CASE   :				Optional[int]							    = unittest.skip("test requires Pillow"				)(_lowercase				)
  return test_case





def    _lowerCAmelCase    (     lowerCamelCase__							:							int				)  ->    Optional[Any]:
  try:
    import transformers  # noqa F401
  except ImportError:
    return unittest.skip("test requires transformers"				)(_lowercase				)
  else:
    return test_case





def    _lowerCAmelCase    (     lowerCamelCase__							:							str				)  ->    Tuple:
  try:
    import tiktoken  # noqa F401
  except ImportError:
    return unittest.skip("test requires tiktoken"				)(_lowercase				)
  else:
    return test_case





def    _lowerCAmelCase    (     lowerCamelCase__							:							Optional[Any]				)  ->    Dict:
  try:
    import spacy  # noqa F401
  except ImportError:
    return unittest.skip("test requires spacy"				)(_lowercase				)
  else:
    return test_case





def    _lowerCAmelCase    (     lowerCamelCase__							:							int				)  ->    Tuple:

  def _require_spacy_model(lowerCamelCase__							:							Dict				):
    try:
      import spacy  # noqa F401

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

  return _require_spacy_model





def    _lowerCAmelCase    (     lowerCamelCase__							:							Any				)  ->    int:
  try:
    import pyspark  # noqa F401
  except ImportError:
    return unittest.skip("test requires pyspark"				)(_lowercase				)
  else:
    return test_case





def    _lowerCAmelCase    (     lowerCamelCase__							:							List[Any]				)  ->    List[Any]:
  try:
    import joblibspark  # noqa F401
  except ImportError:
    return unittest.skip("test requires joblibspark"				)(_lowercase				)
  else:
    return test_case





def    _lowerCAmelCase    (     lowerCamelCase__							:							int				)  ->    Tuple:
  if not _run_slow_tests or _run_slow_tests == 0:
    _SCREAMING_SNAKE_CASE   :				List[str]							    = unittest.skip("test is slow"				)(_lowercase				)
  return test_case





def    _lowerCAmelCase    (     lowerCamelCase__							:							List[Any]				)  ->    List[str]:
  if not _run_local_tests or _run_local_tests == 0:
    _SCREAMING_SNAKE_CASE   :				int							    = unittest.skip("test is local"				)(_lowercase				)
  return test_case





def    _lowerCAmelCase    (     lowerCamelCase__							:							Optional[int]				)  ->    List[Any]:
  if not _run_packaged_tests or _run_packaged_tests == 0:
    _SCREAMING_SNAKE_CASE   :				Optional[int]							    = unittest.skip("test is packaged"				)(_lowercase				)
  return test_case





def    _lowerCAmelCase    (     lowerCamelCase__							:							Any				)  ->    Optional[int]:
  if not _run_remote_tests or _run_remote_tests == 0:
    _SCREAMING_SNAKE_CASE   :				Dict							    = unittest.skip("test requires remote"				)(_lowercase				)
  return test_case





def    _lowerCAmelCase    (     *lowerCamelCase__							:							Dict				)  ->    List[Any]:
  def decorate(cls							:							str				):
    for name, fn in cls.__dict__.items():
      if callable(_lowercase				) and name.startswith("test"				):
        for decorator in decorators:
          _SCREAMING_SNAKE_CASE   :				Any							    = decorator(_lowercase				)
        setattr(cls,						_lowercase,						_lowercase				)
    return cls

  return decorate
class 			UpperCamelCase      (							UpperCamelCase_  ):
     pass
class 			UpperCamelCase      (							UpperCamelCase_  ):
     A__      =			0
     A__      =			1
     A__      =			2





@contextmanager
def    _lowerCAmelCase    (     lowerCamelCase__							:							Dict=OfflineSimulationMode.CONNECTION_FAILS,						lowerCamelCase__							:							Union[str, Any]=1E-16				)  ->    Optional[Any]:
  _SCREAMING_SNAKE_CASE   :				Optional[int]							    = requests.Session().request

  def timeout_request(lowerCamelCase__							:							List[str],						lowerCamelCase__							:							Tuple,						lowerCamelCase__							:							int,						**lowerCamelCase__							:							str				):
    # Change the url to an invalid url so that the connection hangs
    _SCREAMING_SNAKE_CASE   :				str							    = '''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.'''				)
    _SCREAMING_SNAKE_CASE   :				int							    = timeout
    try:
      return online_request(_lowercase,						_lowercase,						**_lowercase				)
    except Exception as e:
      # The following changes in the error are just here to make the offline timeout error prettier
      _SCREAMING_SNAKE_CASE   :				str							    = url
      _SCREAMING_SNAKE_CASE   :				Optional[int]							    = e.args[0]
      _SCREAMING_SNAKE_CASE   :				Optional[int]							    = (max_retry_error.args[0].replace("10.255.255.1",						f'''OfflineMock[{url}]'''				),)
      _SCREAMING_SNAKE_CASE   :				Optional[int]							    = (max_retry_error,)
      raise

  def raise_connection_error(lowerCamelCase__							:							Optional[Any],						lowerCamelCase__							:							Union[str, Any],						**lowerCamelCase__							:							Any				):
    raise requests.ConnectionError("Offline mode is enabled.",						request=_lowercase				)

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





@contextmanager
def    _lowerCAmelCase    (     *lowerCamelCase__							:							Dict,						**lowerCamelCase__							:							int				)  ->    List[str]:
  _SCREAMING_SNAKE_CASE   :				Optional[int]							    = str(Path().resolve()				)
  with tempfile.TemporaryDirectory(*_lowercase,						**_lowercase				) as tmp_dir:
    try:
      os.chdir(_lowercase				)
      yield
    finally:
      os.chdir(_lowercase				)





@contextmanager
def    _lowerCAmelCase    (     )  ->    Dict:
  import gc

  gc.collect()
  _SCREAMING_SNAKE_CASE   :				Optional[int]							    = pa.total_allocated_bytes()
  yield
  assert pa.total_allocated_bytes() - previous_allocated_memory > 0, "Arrow memory didn't increase."





@contextmanager
def    _lowerCAmelCase    (     )  ->    Dict:
  import gc

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





def    _lowerCAmelCase    (     lowerCamelCase__							:							int,						lowerCamelCase__							:							Dict				)  ->    Optional[Any]:
  return deepcopy(_lowercase				).integers(0,						1_0_0,						1_0				).tolist() == deepcopy(_lowercase				).integers(0,						1_0_0,						1_0				).tolist()





def    _lowerCAmelCase    (     lowerCamelCase__							:							Any				)  ->    str:
  import decorator
  from requests.exceptions import HTTPError

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

  return decorator.decorator(_wrapper,						_lowercase				)
class 			UpperCamelCase      :
     def __init__(     self  ,     snake_case__  ,     snake_case__  ,     snake_case__				):




       """simple docstring"""


       _SCREAMING_SNAKE_CASE   :				Tuple							    = returncode
       _SCREAMING_SNAKE_CASE   :				Any							    = stdout
       _SCREAMING_SNAKE_CASE   :				List[Any]							    = stderr





async def    _lowerCAmelCase    (     lowerCamelCase__							:							Union[str, Any],						lowerCamelCase__							:							Union[str, Any]				)  ->    Union[str, Any]:
  while True:
    _SCREAMING_SNAKE_CASE   :				Any							    = await stream.readline()
    if line:
      callback(_lowercase				)
    else:
      break





async def    _lowerCAmelCase    (     lowerCamelCase__							:							Dict,						lowerCamelCase__							:							Optional[Any]=None,						lowerCamelCase__							:							Optional[int]=None,						lowerCamelCase__							:							Dict=None,						lowerCamelCase__							:							Any=False,						lowerCamelCase__							:							Optional[int]=False				)  ->    int:
  if echo:
    print("\nRunning: ",						" ".join(_lowercase				)				)

  _SCREAMING_SNAKE_CASE   :				List[Any]							    = await asyncio.create_subprocess_exec(
      cmd[0],						*cmd[1:],						stdin=_lowercase,						stdout=asyncio.subprocess.PIPE,						stderr=asyncio.subprocess.PIPE,						env=_lowercase,						)

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

  _SCREAMING_SNAKE_CASE   :				List[str]							    = []
  _SCREAMING_SNAKE_CASE   :				List[str]							    = []

  def tee(lowerCamelCase__							:							str,						lowerCamelCase__							:							Optional[Any],						lowerCamelCase__							:							Union[str, Any],						lowerCamelCase__							:							int=""				):
    _SCREAMING_SNAKE_CASE   :				List[str]							    = line.decode("utf-8"				).rstrip()
    sink.append(_lowercase				)
    if not quiet:
      print(_lowercase,						_lowercase,						file=_lowercase				)

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





def    _lowerCAmelCase    (     lowerCamelCase__							:							Optional[Any],						lowerCamelCase__							:							Union[str, Any]=None,						lowerCamelCase__							:							Union[str, Any]=None,						lowerCamelCase__							:							Tuple=1_8_0,						lowerCamelCase__							:							Any=False,						lowerCamelCase__							:							Optional[int]=True				)  ->    Any:
  _SCREAMING_SNAKE_CASE   :				Dict							    = asyncio.get_event_loop()
  _SCREAMING_SNAKE_CASE   :				List[str]							    = loop.run_until_complete(
      _stream_subprocess(_lowercase,						env=_lowercase,						stdin=_lowercase,						timeout=_lowercase,						quiet=_lowercase,						echo=_lowercase				)				)

  _SCREAMING_SNAKE_CASE   :				Optional[int]							    = ''' '''.join(_lowercase				)
  if result.returncode > 0:
    _SCREAMING_SNAKE_CASE   :				List[str]							    = '''\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    (     )  ->    Dict:
  _SCREAMING_SNAKE_CASE   :				Tuple							    = os.environ.get("PYTEST_XDIST_WORKER",						"gw0"				)
  _SCREAMING_SNAKE_CASE   :				int							    = re.sub(R"^gw",						"",						_lowercase,						0,						re.M				)
  return int(_lowercase				)





def    _lowerCAmelCase    (     )  ->    Any:
  _SCREAMING_SNAKE_CASE   :				Any							    = 2_9_5_0_0
  _SCREAMING_SNAKE_CASE   :				List[Any]							    = pytest_xdist_worker_id()
  return port + uniq_delta





"""simple docstring"""
def    _lowerCAmelCase    (     lowerCamelCase__							:							str,						lowerCamelCase__							:							str				)  ->    Union[str, Any]:
  print("\nThe shortest path matrix using Floyd Warshall algorithm\n"				)
  for i in range(lowerCamelCase__				):
    for j in range(lowerCamelCase__				):
      if dist[i][j] != float("inf"				):
        print(int(dist[i][j]				),						end="\t"				)
      else:
        print("INF",						end="\t"				)
    print()





def    _lowerCAmelCase    (     lowerCamelCase__							:							Dict,						lowerCamelCase__							:							Any				)  ->    List[str]:
  _SCREAMING_SNAKE_CASE   :				List[Any]							    = [[float("inf"				) for _ in range(lowerCamelCase__				)] for _ in range(lowerCamelCase__				)]

  for i in range(lowerCamelCase__				):
    for j in range(lowerCamelCase__				):
      _SCREAMING_SNAKE_CASE   :				List[Any]							    = graph[i][j]

      # check vertex k against all other vertices (i, j)
  for k in range(lowerCamelCase__				):
    # looping through rows of graph array
    for i in range(lowerCamelCase__				):
      # looping through columns of graph array
      for j in range(lowerCamelCase__				):
        if (
            dist[i][k] != float("inf"				)
            and dist[k][j] != float("inf"				)
            and dist[i][k] + dist[k][j] < dist[i][j]
        ):
          _SCREAMING_SNAKE_CASE   :				List[Any]							    = dist[i][k] + dist[k][j]

  _print_dist(lowerCamelCase__,						lowerCamelCase__				)
  return dist, v


if __name__ == "__main__":
      lowercase_       :						Tuple     					=	int(input('''Enter number of vertices: '''))
      lowercase_       :						List[Any]     					=	int(input('''Enter number of edges: '''))

      lowercase_       :						Optional[Any]     					=	[[float('''inf''') for i in range(v)] for j in range(v)]

      for i in range(v):
            lowercase_       :						Tuple     					=	0.0

            # src and dst are indices that must be within the array size graph[e][v]
            # failure to follow this will result in an error
      for i in range(e):
            print('''\nEdge ''', i + 1)
            lowercase_       :						str     					=	int(input('''Enter source:'''))
            lowercase_       :						Optional[Any]     					=	int(input('''Enter destination:'''))
            lowercase_       :						Union[str, Any]     					=	float(input('''Enter weight:'''))
            lowercase_       :						str     					=	weight

      floyd_warshall(graph, v)

      # Example Input
      # Enter number of vertices: 3
      # Enter number of edges: 2

      # # generated graph from vertex and edge inputs
      # [[inf, inf, inf], [inf, inf, inf], [inf, inf, inf]]
      # [[0.0, inf, inf], [inf, 0.0, inf], [inf, inf, 0.0]]

      # specify source, destination and weight for edge #1
      # Edge  1
      # Enter source:1
      # Enter destination:2
      # Enter weight:2

      # specify source, destination and weight for edge #2
      # Edge  2
      # Enter source:2
      # Enter destination:1
      # Enter weight:1

      # # Expected Output from the vertice, edge and src, dst, weight inputs!!
      # 0		INF	INF
      # INF	0	2
      # INF	1	0



