






"""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       _A    (__a					,       __a=False							)				-> Union[str, Any]:
    """simple docstring"""






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


UpperCAmelCase_     :				Optional[Any]         =				parse_flag_from_env("""RUN_SLOW""", default=False)
UpperCAmelCase_     :				Optional[Any]         =				parse_flag_from_env("""RUN_REMOTE""", default=False)
UpperCAmelCase_     :				Dict         =				parse_flag_from_env("""RUN_LOCAL""", default=True)
UpperCAmelCase_     :				Dict         =				parse_flag_from_env("""RUN_PACKAGED""", default=True)

# Compression
UpperCAmelCase_     :				int         =				pytest.mark.skipif(not config.LZ4_AVAILABLE, reason="""test requires lz4""")
UpperCAmelCase_     :				Dict         =				pytest.mark.skipif(not config.PY7ZR_AVAILABLE, reason="""test requires py7zr""")
UpperCAmelCase_     :				List[str]         =				pytest.mark.skipif(not config.ZSTANDARD_AVAILABLE, reason="""test requires zstandard""")

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

# Windows
UpperCAmelCase_     :				Any         =				pytest.mark.skipif(
    sys.platform == """win32""",
    reason="""test should not be run on Windows""",
)



def       _A    (__a							)				-> int:
    """simple docstring"""






    try:
        import faiss  # noqa
    except ImportError:
        SCREAMING_SNAKE_CASE_   :						Any							=	unittest.skip('''test requires faiss'''							)(snake_case__							)
    return test_case



def       _A    (__a							)				-> Optional[Any]:
    """simple docstring"""






    try:
        import regex  # noqa
    except ImportError:
        SCREAMING_SNAKE_CASE_   :						str							=	unittest.skip('''test requires regex'''							)(snake_case__							)
    return test_case



def       _A    (__a							)				-> int:
    """simple docstring"""






    try:
        import elasticsearch  # noqa
    except ImportError:
        SCREAMING_SNAKE_CASE_   :						List[Any]							=	unittest.skip('''test requires elasticsearch'''							)(snake_case__							)
    return test_case



def       _A    (__a							)				-> Tuple:
    """simple docstring"""






    try:
        import sqlalchemy  # noqa
    except ImportError:
        SCREAMING_SNAKE_CASE_   :						Union[str, Any]							=	unittest.skip('''test requires sqlalchemy'''							)(snake_case__							)
    return test_case



def       _A    (__a							)				-> int:
    """simple docstring"""






    if not config.TORCH_AVAILABLE:
        SCREAMING_SNAKE_CASE_   :						Union[str, Any]							=	unittest.skip('''test requires PyTorch'''							)(snake_case__							)
    return test_case



def       _A    (__a							)				-> List[Any]:
    """simple docstring"""






    if not config.TF_AVAILABLE:
        SCREAMING_SNAKE_CASE_   :						List[Any]							=	unittest.skip('''test requires TensorFlow'''							)(snake_case__							)
    return test_case



def       _A    (__a							)				-> List[Any]:
    """simple docstring"""






    if not config.JAX_AVAILABLE:
        SCREAMING_SNAKE_CASE_   :						Optional[Any]							=	unittest.skip('''test requires JAX'''							)(snake_case__							)
    return test_case



def       _A    (__a							)				-> str:
    """simple docstring"""






    if not config.PIL_AVAILABLE:
        SCREAMING_SNAKE_CASE_   :						Dict							=	unittest.skip('''test requires Pillow'''							)(snake_case__							)
    return test_case



def       _A    (__a							)				-> str:
    """simple docstring"""






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



def       _A    (__a							)				-> Optional[int]:
    """simple docstring"""






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



def       _A    (__a							)				-> List[str]:
    """simple docstring"""






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



def       _A    (__a							)				-> Tuple:
    """simple docstring"""






    def _require_spacy_model(__a							):
        try:
            import spacy  # noqa F401

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

    return _require_spacy_model



def       _A    (__a							)				-> List[Any]:
    """simple docstring"""






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



def       _A    (__a							)				-> List[Any]:
    """simple docstring"""






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



def       _A    (__a							)				-> Dict:
    """simple docstring"""






    if not _run_slow_tests or _run_slow_tests == 0:
        SCREAMING_SNAKE_CASE_   :						Union[str, Any]							=	unittest.skip('''test is slow'''							)(snake_case__							)
    return test_case



def       _A    (__a							)				-> List[Any]:
    """simple docstring"""






    if not _run_local_tests or _run_local_tests == 0:
        SCREAMING_SNAKE_CASE_   :						Optional[Any]							=	unittest.skip('''test is local'''							)(snake_case__							)
    return test_case



def       _A    (__a							)				-> Dict:
    """simple docstring"""






    if not _run_packaged_tests or _run_packaged_tests == 0:
        SCREAMING_SNAKE_CASE_   :						Dict							=	unittest.skip('''test is packaged'''							)(snake_case__							)
    return test_case



def       _A    (__a							)				-> Optional[int]:
    """simple docstring"""






    if not _run_remote_tests or _run_remote_tests == 0:
        SCREAMING_SNAKE_CASE_   :						List[Any]							=	unittest.skip('''test requires remote'''							)(snake_case__							)
    return test_case



def       _A    (*__a							)				-> List[Any]:
    """simple docstring"""






    def decorate(cls							):
        for name, fn in cls.__dict__.items():
            if callable(snake_case__							) and name.startswith('''test'''							):
                for decorator in decorators:
                    SCREAMING_SNAKE_CASE_   :						List[Any]							=	decorator(snake_case__							)
                setattr(cls					,       snake_case__					,       snake_case__							)
        return cls

    return decorate




class 							lowerCAmelCase__       (    _lowercase				):






      '''simple docstring'''

      pass




class 							lowerCAmelCase__       (    _lowercase				):






      '''simple docstring'''

      __UpperCamelCase							=						0
      __UpperCamelCase							=						1
      __UpperCamelCase							=						2



@contextmanager
def       _A    (__a=OfflineSimulationMode.CONNECTION_FAILS					,       __a=1e-16							)				-> Optional[Any]:
    """simple docstring"""






    SCREAMING_SNAKE_CASE_   :						Any							=	requests.Session().request

    def timeout_request(__a					,       __a					,       __a					,       **__a							):
        # 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(snake_case__					,       snake_case__					,       **snake_case__							)
        except Exception as e:
            # The following changes in the error are just here to make the offline timeout error prettier
            SCREAMING_SNAKE_CASE_   :						Dict							=	url
            SCREAMING_SNAKE_CASE_   :						int							=	e.args[0]
            SCREAMING_SNAKE_CASE_   :						str							=	(max_retry_error.args[0].replace('''10.255.255.1'''					,       f'OfflineMock[{url}]'							),)
            SCREAMING_SNAKE_CASE_   :						List[Any]							=	(max_retry_error,)
            raise

    def raise_connection_error(__a					,       __a					,       **__a							):
        raise requests.ConnectionError('''Offline mode is enabled.'''					,       request=snake_case__							)

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



@contextmanager
def       _A    (*__a					,       **__a							)				-> Tuple:
    """simple docstring"""






    SCREAMING_SNAKE_CASE_   :						Optional[Any]							=	str(Path().resolve()							)
    with tempfile.TemporaryDirectory(*snake_case__					,       **snake_case__							) as tmp_dir:
        try:
            os.chdir(snake_case__							)
            yield
        finally:
            os.chdir(snake_case__							)



@contextmanager
def       _A    ()				-> List[str]:
    """simple docstring"""






    import gc

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



@contextmanager
def       _A    ()				-> Tuple:
    """simple docstring"""






    import gc

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



def       _A    (__a					,       __a							)				-> List[str]:
    """simple docstring"""






    return deepcopy(snake_case__							).integers(0					,       1_00					,       10							).tolist() == deepcopy(snake_case__							).integers(0					,       1_00					,       10							).tolist()



def       _A    (__a							)				-> Any:
    """simple docstring"""






    import decorator
    from requests.exceptions import HTTPError

    def _wrapper(__a					,       *__a					,       **__a							):
        try:
            return func(*snake_case__					,       **snake_case__							)
        except HTTPError as err:
            if str(snake_case__							).startswith('''500'''							) or str(snake_case__							).startswith('''502'''							):
                pytest.xfail(str(snake_case__							)							)
            raise err

    return decorator.decorator(_wrapper					,       snake_case__							)




class 							lowerCAmelCase__       :






      '''simple docstring'''

      def __init__(		self  :						Tuple		,			lowercase_  :						Union[str, Any]		,			lowercase_  :						int		,			lowercase_  :						List[Any]):




          '''simple docstring'''


          SCREAMING_SNAKE_CASE_   :						Dict							=	returncode
          SCREAMING_SNAKE_CASE_   :						Any							=	stdout
          SCREAMING_SNAKE_CASE_   :						str							=	stderr



async def       _A    (__a					,       __a							)				-> int:
    """simple docstring"""






    while True:
        SCREAMING_SNAKE_CASE_   :						Optional[Any]							=	await stream.readline()
        if line:
            callback(snake_case__							)
        else:
            break



async def       _A    (__a					,       __a=None					,       __a=None					,       __a=None					,       __a=False					,       __a=False							)				-> Tuple:
    """simple docstring"""






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

    SCREAMING_SNAKE_CASE_   :						Union[str, Any]							=	await asyncio.create_subprocess_exec(
        cmd[0]					,       *cmd[1:]					,       stdin=snake_case__					,       stdout=asyncio.subprocess.PIPE					,       stderr=asyncio.subprocess.PIPE					,       env=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)

    SCREAMING_SNAKE_CASE_   :						Any							=	[]
    SCREAMING_SNAKE_CASE_   :						Any							=	[]

    def tee(__a					,       __a					,       __a					,       __a=""							):
        SCREAMING_SNAKE_CASE_   :						Optional[Any]							=	line.decode('''utf-8'''							).rstrip()
        sink.append(snake_case__							)
        if not quiet:
            print(snake_case__					,       snake_case__					,       file=snake_case__							)

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



def       _A    (__a					,       __a=None					,       __a=None					,       __a=1_80					,       __a=False					,       __a=True							)				-> Union[str, Any]:
    """simple docstring"""






    SCREAMING_SNAKE_CASE_   :						List[Any]							=	asyncio.get_event_loop()
    SCREAMING_SNAKE_CASE_   :						Dict							=	loop.run_until_complete(
        _stream_subprocess(snake_case__					,       env=snake_case__					,       stdin=snake_case__					,       timeout=snake_case__					,       quiet=snake_case__					,       echo=snake_case__							)							)

    SCREAMING_SNAKE_CASE_   :						int							=	''' '''.join(snake_case__							)
    if result.returncode > 0:
        SCREAMING_SNAKE_CASE_   :						Union[str, Any]							=	'''\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       _A    ()				-> str:
    """simple docstring"""






    SCREAMING_SNAKE_CASE_   :						int							=	os.environ.get('''PYTEST_XDIST_WORKER'''					,       '''gw0'''							)
    SCREAMING_SNAKE_CASE_   :						str							=	re.sub(R'''^gw'''					,       ''''''					,       snake_case__					,       0					,       re.M							)
    return int(snake_case__							)





def       _A    ()				-> Optional[int]:
    """simple docstring"""






    SCREAMING_SNAKE_CASE_   :						Union[str, Any]							=	2_95_00
    SCREAMING_SNAKE_CASE_   :						Optional[Any]							=	pytest_xdist_worker_id()
    return port + uniq_delta










"""simple docstring"""






from collections import defaultdict

from graphs.minimum_spanning_tree_prims import prisms_algorithm as mst



def       _A    ()				-> Union[str, Any]:
    """simple docstring"""






    SCREAMING_SNAKE_CASE_		,    SCREAMING_SNAKE_CASE_   :						Tuple							=	9, 14  # noqa: F841
    SCREAMING_SNAKE_CASE_   :						Tuple							=	[
        [0, 1, 4],
        [0, 7, 8],
        [1, 2, 8],
        [7, 8, 7],
        [7, 6, 1],
        [2, 8, 2],
        [8, 6, 6],
        [2, 3, 7],
        [2, 5, 4],
        [6, 5, 2],
        [3, 5, 14],
        [3, 4, 9],
        [5, 4, 10],
        [1, 7, 11],
    ]

    SCREAMING_SNAKE_CASE_   :						Dict							=	defaultdict(__a							)
    for nodea, nodea, cost in edges:
        adjancency[nodea].append([nodea, cost]							)
        adjancency[nodea].append([nodea, cost]							)

    SCREAMING_SNAKE_CASE_   :						Any							=	mst(__a							)

    SCREAMING_SNAKE_CASE_   :						Optional[int]							=	[
        [7, 6, 1],
        [2, 8, 2],
        [6, 5, 2],
        [0, 1, 4],
        [2, 5, 4],
        [2, 3, 7],
        [0, 7, 8],
        [3, 4, 9],
    ]

    for answer in expected:
        SCREAMING_SNAKE_CASE_   :						Dict							=	tuple(answer[:2]							)
        SCREAMING_SNAKE_CASE_   :						Optional[int]							=	tuple(edge[::-1]							)
        assert edge in result or reverse in result


