





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 	UpperCamelCase__(       UpperCamelCase__			:       Any ,     UpperCamelCase__			:       List[str]=False  )->str:
       try:
              A__											=						os.environ[key]
       except KeyError:
              # KEY isn't set, default to `default`.
              A__											=						default
       else:
              # KEY is set, convert it to True or False.
              try:
                     A__											=						strtobool(_lowerCamelCase  )
              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__:      Any									=		parse_flag_from_env('RUN_SLOW', default=False)
a__:      List[Any]									=		parse_flag_from_env('RUN_REMOTE', default=False)
a__:      Optional[int]									=		parse_flag_from_env('RUN_LOCAL', default=True)
a__:      str									=		parse_flag_from_env('RUN_PACKAGED', default=True)

# Compression
a__:      Optional[int]									=		pytest.mark.skipif(not config.LZ4_AVAILABLE, reason='test requires lz4')
a__:      Union[str, Any]									=		pytest.mark.skipif(not config.PY7ZR_AVAILABLE, reason='test requires py7zr')
a__:      Optional[int]									=		pytest.mark.skipif(not config.ZSTANDARD_AVAILABLE, reason='test requires zstandard')

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

# Windows
a__:      List[str]									=		pytest.mark.skipif(
    sys.platform == 'win32',
    reason='test should not be run on Windows',
)


def 	UpperCamelCase__(       UpperCamelCase__			:       int  )->str:
       try:
              import faiss  # noqa
       except ImportError:
              A__											=						unittest.skip('''test requires faiss'''  )(_lowerCamelCase  )
       return test_case


def 	UpperCamelCase__(       UpperCamelCase__			:       int  )->Optional[Any]:
       try:
              import regex  # noqa
       except ImportError:
              A__											=						unittest.skip('''test requires regex'''  )(_lowerCamelCase  )
       return test_case


def 	UpperCamelCase__(       UpperCamelCase__			:       int  )->Tuple:
       try:
              import elasticsearch  # noqa
       except ImportError:
              A__											=						unittest.skip('''test requires elasticsearch'''  )(_lowerCamelCase  )
       return test_case


def 	UpperCamelCase__(       UpperCamelCase__			:       Union[str, Any]  )->Tuple:
       try:
              import sqlalchemy  # noqa
       except ImportError:
              A__											=						unittest.skip('''test requires sqlalchemy'''  )(_lowerCamelCase  )
       return test_case


def 	UpperCamelCase__(       UpperCamelCase__			:       int  )->Any:
       if not config.TORCH_AVAILABLE:
              A__											=						unittest.skip('''test requires PyTorch'''  )(_lowerCamelCase  )
       return test_case


def 	UpperCamelCase__(       UpperCamelCase__			:       Tuple  )->Tuple:
       if not config.TF_AVAILABLE:
              A__											=						unittest.skip('''test requires TensorFlow'''  )(_lowerCamelCase  )
       return test_case


def 	UpperCamelCase__(       UpperCamelCase__			:       Dict  )->Union[str, Any]:
       if not config.JAX_AVAILABLE:
              A__											=						unittest.skip('''test requires JAX'''  )(_lowerCamelCase  )
       return test_case


def 	UpperCamelCase__(       UpperCamelCase__			:       int  )->Optional[int]:
       if not config.PIL_AVAILABLE:
              A__											=						unittest.skip('''test requires Pillow'''  )(_lowerCamelCase  )
       return test_case


def 	UpperCamelCase__(       UpperCamelCase__			:       Tuple  )->Optional[int]:
       try:
              import transformers  # noqa F401
       except ImportError:
              return unittest.skip('''test requires transformers'''  )(_lowerCamelCase  )
       else:
              return test_case


def 	UpperCamelCase__(       UpperCamelCase__			:       Optional[Any]  )->List[str]:
       try:
              import tiktoken  # noqa F401
       except ImportError:
              return unittest.skip('''test requires tiktoken'''  )(_lowerCamelCase  )
       else:
              return test_case


def 	UpperCamelCase__(       UpperCamelCase__			:       Dict  )->Any:
       try:
              import spacy  # noqa F401
       except ImportError:
              return unittest.skip('''test requires spacy'''  )(_lowerCamelCase  )
       else:
              return test_case


def 	UpperCamelCase__(       UpperCamelCase__			:       Optional[int]  )->Optional[int]:

       def _require_spacy_model(UpperCamelCase__			:       Optional[int]  ):
              try:
                     import spacy  # noqa F401

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

       return _require_spacy_model


def 	UpperCamelCase__(       UpperCamelCase__			:       Dict  )->Dict:
       try:
              import pyspark  # noqa F401
       except ImportError:
              return unittest.skip('''test requires pyspark'''  )(_lowerCamelCase  )
       else:
              return test_case


def 	UpperCamelCase__(       UpperCamelCase__			:       List[str]  )->Any:
       try:
              import joblibspark  # noqa F401
       except ImportError:
              return unittest.skip('''test requires joblibspark'''  )(_lowerCamelCase  )
       else:
              return test_case


def 	UpperCamelCase__(       UpperCamelCase__			:       Dict  )->str:
       if not _run_slow_tests or _run_slow_tests == 0:
              A__											=						unittest.skip('''test is slow'''  )(_lowerCamelCase  )
       return test_case


def 	UpperCamelCase__(       UpperCamelCase__			:       int  )->List[str]:
       if not _run_local_tests or _run_local_tests == 0:
              A__											=						unittest.skip('''test is local'''  )(_lowerCamelCase  )
       return test_case


def 	UpperCamelCase__(       UpperCamelCase__			:       Optional[int]  )->Union[str, Any]:
       if not _run_packaged_tests or _run_packaged_tests == 0:
              A__											=						unittest.skip('''test is packaged'''  )(_lowerCamelCase  )
       return test_case


def 	UpperCamelCase__(       UpperCamelCase__			:       Tuple  )->str:
       if not _run_remote_tests or _run_remote_tests == 0:
              A__											=						unittest.skip('''test requires remote'''  )(_lowerCamelCase  )
       return test_case


def 	UpperCamelCase__(       *UpperCamelCase__			:       str  )->str:
       def decorate(cls			:       str  ):
              for name, fn in cls.__dict__.items():
                     if callable(_lowerCamelCase  ) and name.startswith('''test'''  ):
                            for decorator in decorators:
                                   A__											=						decorator(_lowerCamelCase  )
                            setattr(cls ,     _lowerCamelCase ,     _lowerCamelCase  )
              return cls

       return decorate




class     SCREAMING_SNAKE_CASE__ (						__A      ):
 pass




class     SCREAMING_SNAKE_CASE__ (						__A      ):
 __SCREAMING_SNAKE_CASE							       =	0
 __SCREAMING_SNAKE_CASE							       =	1
 __SCREAMING_SNAKE_CASE							       =	2


@contextmanager
def 	UpperCamelCase__(       UpperCamelCase__			:       List[str]=OfflineSimulationMode.CONNECTION_FAILS ,     UpperCamelCase__			:       int=1e-1_6  )->Tuple:
       A__											=						requests.Session().request

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

       def raise_connection_error(UpperCamelCase__			:       Union[str, Any] ,     UpperCamelCase__			:       Optional[Any] ,     **UpperCamelCase__			:       Tuple  ):
              raise requests.ConnectionError('''Offline mode is enabled.''' ,     request=_lowerCamelCase  )

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


@contextmanager
def 	UpperCamelCase__(       *UpperCamelCase__			:       str ,     **UpperCamelCase__			:       Tuple  )->List[Any]:
       A__											=						str(Path().resolve()  )
       with tempfile.TemporaryDirectory(*_lowerCamelCase ,     **_lowerCamelCase  ) as tmp_dir:
              try:
                     os.chdir(_lowerCamelCase  )
                     yield
              finally:
                     os.chdir(_lowerCamelCase  )


@contextmanager
def 	UpperCamelCase__(       )->Tuple:
       import gc

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


@contextmanager
def 	UpperCamelCase__(       )->Any:
       import gc

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


def 	UpperCamelCase__(       UpperCamelCase__			:       Optional[Any] ,     UpperCamelCase__			:       Optional[Any]  )->Optional[int]:
       return deepcopy(_lowerCamelCase  ).integers(0 ,     1_00 ,     10  ).tolist() == deepcopy(_lowerCamelCase  ).integers(0 ,     1_00 ,     10  ).tolist()


def 	UpperCamelCase__(       UpperCamelCase__			:       str  )->Tuple:
       import decorator
       from requests.exceptions import HTTPError

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

       return decorator.decorator(_wrapper ,     _lowerCamelCase  )




class     SCREAMING_SNAKE_CASE__ :



 def __init__(							self,__lowerCamelCase,__lowerCamelCase,__lowerCamelCase ):
        A__											=						returncode
        A__											=						stdout
        A__											=						stderr


async def 	UpperCamelCase__(       UpperCamelCase__			:       List[str] ,     UpperCamelCase__			:       Dict  )->Union[str, Any]:
       while True:
              A__											=						await stream.readline()
              if line:
                     callback(_lowerCamelCase  )
              else:
                     break


async def 	UpperCamelCase__(       UpperCamelCase__			:       Optional[int] ,     UpperCamelCase__			:       Union[str, Any]=None ,     UpperCamelCase__			:       Optional[Any]=None ,     UpperCamelCase__			:       int=None ,     UpperCamelCase__			:       Optional[Any]=False ,     UpperCamelCase__			:       Tuple=False  )->Any:
       if echo:
              print('''\nRunning: ''' ,     ''' '''.join(_lowerCamelCase  )  )

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

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

       A__											=						[]
       A__											=						[]

       def tee(UpperCamelCase__			:       str ,     UpperCamelCase__			:       Optional[Any] ,     UpperCamelCase__			:       Union[str, Any] ,     UpperCamelCase__			:       Optional[int]=""  ):
              A__											=						line.decode('''utf-8'''  ).rstrip()
              sink.append(_lowerCamelCase  )
              if not quiet:
                     print(_lowerCamelCase ,     _lowerCamelCase ,     file=_lowerCamelCase  )

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


def 	UpperCamelCase__(       UpperCamelCase__			:       Optional[int] ,     UpperCamelCase__			:       List[str]=None ,     UpperCamelCase__			:       Dict=None ,     UpperCamelCase__			:       int=1_80 ,     UpperCamelCase__			:       Union[str, Any]=False ,     UpperCamelCase__			:       Optional[Any]=True  )->Optional[Any]:
       A__											=						asyncio.get_event_loop()
       A__											=						loop.run_until_complete(
           _stream_subprocess(_lowerCamelCase ,     env=_lowerCamelCase ,     stdin=_lowerCamelCase ,     timeout=_lowerCamelCase ,     quiet=_lowerCamelCase ,     echo=_lowerCamelCase  )  )

       A__											=						" ".join(_lowerCamelCase  )
       if result.returncode > 0:
              A__											=						"\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 	UpperCamelCase__(       )->List[Any]:
       A__											=						os.environ.get('''PYTEST_XDIST_WORKER''' ,     '''gw0'''  )
       A__											=						re.sub(r'''^gw''' ,     '''''' ,     _lowerCamelCase ,     0 ,     re.M  )
       return int(_lowerCamelCase  )


def 	UpperCamelCase__(       )->Optional[Any]:
       A__											=						2_95_00
       A__											=						pytest_xdist_worker_id()
       return port + uniq_delta






import operator

def 			lowercase_				(			_lowerCamelCase							:       list		,	_lowerCamelCase							:       bool = False		,	_lowerCamelCase							:       list | None = None):
    lowercase__ :   int    					=				operator.lt if reverse else operator.gt
    lowercase__ :   str    					=				solution or []

    if not arr:
        return solution

    lowercase__ :   List[str]    					=				[arr.pop(0)]
    for i, item in enumerate(_lowerCamelCase):
        if _operator(_lowerCamelCase		,	sublist[-1]):
            sublist.append(_lowerCamelCase)
            arr.pop(_lowerCamelCase)

    #  merging sublist into solution list
    if not solution:
        solution.extend(_lowerCamelCase)
    else:
        while sublist:
            lowercase__ :   str    					=				sublist.pop(0)
            for i, xx in enumerate(_lowerCamelCase):
                if not _operator(_lowerCamelCase		,	_lowerCamelCase):
                    solution.insert(_lowerCamelCase		,	_lowerCamelCase)
                    break
            else:
                solution.append(_lowerCamelCase)

    strand_sort(_lowerCamelCase		,	_lowerCamelCase		,	_lowerCamelCase)
    return solution


if __name__ == "__main__":
      assert strand_sort([4, 3, 5, 1, 2]) == [1, 2, 3, 4, 5]
      assert strand_sort([4, 3, 5, 1, 2], reverse=True) == [5, 4, 3, 2, 1]



