




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        _SCREAMING_SNAKE_CASE      (		snake_case			,     snake_case=False       )						->				str:

						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(_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


a													=			parse_flag_from_env("RUN_SLOW", default=False)
a													=			parse_flag_from_env("RUN_REMOTE", default=False)
a													=			parse_flag_from_env("RUN_LOCAL", default=True)
a													=			parse_flag_from_env("RUN_PACKAGED", default=True)

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

# Audio
a													=			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													=			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													=			pytest.mark.skipif(
    config.DILL_VERSION <= version.parse("0.3.2"),
    reason="test requires dill>0.3.2 for cloudpickle compatibility",
)

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




def        _SCREAMING_SNAKE_CASE      (		snake_case       )						->				str:

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




def        _SCREAMING_SNAKE_CASE      (		snake_case       )						->				Any:

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




def        _SCREAMING_SNAKE_CASE      (		snake_case       )						->				Union[str, Any]:

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




def        _SCREAMING_SNAKE_CASE      (		snake_case       )						->				Dict:

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




def        _SCREAMING_SNAKE_CASE      (		snake_case       )						->				Union[str, Any]:

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




def        _SCREAMING_SNAKE_CASE      (		snake_case       )						->				Optional[Any]:

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




def        _SCREAMING_SNAKE_CASE      (		snake_case       )						->				str:

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




def        _SCREAMING_SNAKE_CASE      (		snake_case       )						->				Dict:

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




def        _SCREAMING_SNAKE_CASE      (		snake_case       )						->				str:

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




def        _SCREAMING_SNAKE_CASE      (		snake_case       )						->				List[Any]:

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




def        _SCREAMING_SNAKE_CASE      (		snake_case       )						->				Optional[int]:

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




def        _SCREAMING_SNAKE_CASE      (		snake_case       )						->				int:

						def _require_spacy_model(snake_case       ):
												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        _SCREAMING_SNAKE_CASE      (		snake_case       )						->				Optional[int]:

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




def        _SCREAMING_SNAKE_CASE      (		snake_case       )						->				List[Any]:

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




def        _SCREAMING_SNAKE_CASE      (		snake_case       )						->				Any:

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




def        _SCREAMING_SNAKE_CASE      (		snake_case       )						->				Any:

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




def        _SCREAMING_SNAKE_CASE      (		snake_case       )						->				Optional[int]:

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




def        _SCREAMING_SNAKE_CASE      (		snake_case       )						->				Dict:

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




def        _SCREAMING_SNAKE_CASE      (		*snake_case       )						->				Dict:

						def decorate(cls       ):
												for name, fn in cls.__dict__.items():
																		if callable(_A       ) and name.startswith("""test"""       ):
																								for decorator in decorators:
																														_UpperCAmelCase      =			decorator(_A       )
																								setattr(cls			,     _A			,     _A       )
												return cls

						return decorate




class       _A				(		_UpperCAmelCase     ):
			pass




class       _A				(		_UpperCAmelCase     ):
			__a					    =       0
			__a					    =       1
			__a					    =       2




@contextmanager
def        _SCREAMING_SNAKE_CASE      (		snake_case=OfflineSimulationMode.CONNECTION_FAILS			,     snake_case=1E-16       )						->				List[Any]:
						_UpperCAmelCase      =			requests.Session().request

						def timeout_request(snake_case			,     snake_case			,     snake_case			,     **snake_case       ):
												# Change the url to an invalid url so that the connection hangs
												_UpperCAmelCase      =			"""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."       )
												_UpperCAmelCase      =			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
																		_UpperCAmelCase      =			url
																		_UpperCAmelCase      =			e.args[0]
																		_UpperCAmelCase      =			(max_retry_error.args[0].replace("""10.255.255.1"""			,     f"OfflineMock[{url}]"       ),)
																		_UpperCAmelCase      =			(max_retry_error,)
																		raise

						def raise_connection_error(snake_case			,     snake_case			,     **snake_case       ):
												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        _SCREAMING_SNAKE_CASE      (		*snake_case			,     **snake_case       )						->				str:
						_UpperCAmelCase      =			str(Path().resolve()       )
						with tempfile.TemporaryDirectory(*_A			,     **_A       ) as tmp_dir:
												try:
																		os.chdir(_A       )
																		yield
												finally:
																		os.chdir(_A       )




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

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




@contextmanager
def        _SCREAMING_SNAKE_CASE      (		)						->				Union[str, Any]:
						import gc

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




def        _SCREAMING_SNAKE_CASE      (		snake_case			,     snake_case       )						->				str:
						return deepcopy(_A       ).integers(0			,     1_0_0			,     1_0       ).tolist() == deepcopy(_A       ).integers(0			,     1_0_0			,     1_0       ).tolist()




def        _SCREAMING_SNAKE_CASE      (		snake_case       )						->				Tuple:
						import decorator
						from requests.exceptions import HTTPError

						def _wrapper(snake_case			,     *snake_case			,     **snake_case       ):
												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       _A				:






			def __init__(    self						,		_SCREAMING_SNAKE_CASE						,		_SCREAMING_SNAKE_CASE						,		_SCREAMING_SNAKE_CASE			):
									_UpperCAmelCase      =			returncode
									_UpperCAmelCase      =			stdout
									_UpperCAmelCase      =			stderr




async def        _SCREAMING_SNAKE_CASE      (		snake_case			,     snake_case       )						->				Union[str, Any]:

						while True:
												_UpperCAmelCase      =			await stream.readline()
												if line:
																		callback(_A       )
												else:
																		break




async def        _SCREAMING_SNAKE_CASE      (		snake_case			,     snake_case=None			,     snake_case=None			,     snake_case=None			,     snake_case=False			,     snake_case=False       )						->				_RunOutput:

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

						_UpperCAmelCase      =			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)

						_UpperCAmelCase      =			[]
						_UpperCAmelCase      =			[]

						def tee(snake_case			,     snake_case			,     snake_case			,     snake_case=""       ):
												_UpperCAmelCase      =			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 snake_case       : tee(_A			,     _A			,     sys.stdout			,     label="""stdout:"""       )       ),
						        _read_stream(p.stderr			,     lambda snake_case       : tee(_A			,     _A			,     sys.stderr			,     label="""stderr:"""       )       ),
						    ]			,     timeout=_A			,     )
						return _RunOutput(await p.wait()			,     _A			,     _A       )




def        _SCREAMING_SNAKE_CASE      (		snake_case			,     snake_case=None			,     snake_case=None			,     snake_case=1_8_0			,     snake_case=False			,     snake_case=True       )						->				_RunOutput:
						_UpperCAmelCase      =			asyncio.get_event_loop()
						_UpperCAmelCase      =			loop.run_until_complete(
						    _stream_subprocess(_A			,     env=_A			,     stdin=_A			,     timeout=_A			,     quiet=_A			,     echo=_A       )       )

						_UpperCAmelCase      =			""" """.join(_A       )
						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}"       )

						# 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        _SCREAMING_SNAKE_CASE      (		)						->				Tuple:
						_UpperCAmelCase      =			os.environ.get("""PYTEST_XDIST_WORKER"""			,     """gw0"""       )
						_UpperCAmelCase      =			re.sub(R"""^gw"""			,     """"""			,     _A			,     0			,     re.M       )
						return int(_A       )




def        _SCREAMING_SNAKE_CASE      (		)						->				Tuple:
						_UpperCAmelCase      =			2_9_5_0_0
						_UpperCAmelCase      =			pytest_xdist_worker_id()
						return port + uniq_delta





import unittest

import numpy as np




def        _SCREAMING_SNAKE_CASE      (		snake_case			,     snake_case			,     snake_case			,     snake_case = None			,     )						->				np.ndarray:
						_UpperCAmelCase      =			np.shape(snake_case       )
						_UpperCAmelCase      =			np.shape(snake_case       )
						_UpperCAmelCase      =			np.shape(snake_case       )

						if shape_a[0] != shape_b[0]:
												_UpperCAmelCase      =			(
												    """Expected the same number of rows for A and B. """
												    f"Instead found A of size {shape_a} and B of size {shape_b}"
												)
												raise ValueError(snake_case       )

						if shape_b[1] != shape_c[1]:
												_UpperCAmelCase      =			(
												    """Expected the same number of columns for B and C. """
												    f"Instead found B of size {shape_b} and C of size {shape_c}"
												)
												raise ValueError(snake_case       )

						_UpperCAmelCase      =			pseudo_inv
						if a_inv is None:
												try:
																		_UpperCAmelCase      =			np.linalg.inv(snake_case       )
												except np.linalg.LinAlgError:
																		raise ValueError(
																		    """Input matrix A is not invertible. Cannot compute Schur complement."""       )

						return mat_c - mat_b.T @ a_inv @ mat_b




class       _A				(		unittest.TestCase     ):






		def 				UpperCAmelCase (    self			):
								_UpperCAmelCase      =			np.array([[1, 2, 1], [2, 1, 2], [3, 2, 4]]			)
								_UpperCAmelCase      =			np.array([[0, 3], [3, 0], [2, 3]]			)
								_UpperCAmelCase      =			np.array([[2, 1], [6, 3]]			)

								_UpperCAmelCase      =			schur_complement(_SCREAMING_SNAKE_CASE						,		_SCREAMING_SNAKE_CASE						,		_SCREAMING_SNAKE_CASE			)

								_UpperCAmelCase      =			np.block([[a, b], [b.T, c]]			)

								_UpperCAmelCase      =			np.linalg.det(_SCREAMING_SNAKE_CASE			)
								_UpperCAmelCase      =			np.linalg.det(_SCREAMING_SNAKE_CASE			)
								_UpperCAmelCase      =			np.linalg.det(_SCREAMING_SNAKE_CASE			)

								self.assertAlmostEqual(_SCREAMING_SNAKE_CASE						,		det_a * det_s			)






		def 				UpperCAmelCase (    self			):
								_UpperCAmelCase      =			np.array([[1, 2, 1], [2, 1, 2], [3, 2, 4]]			)
								_UpperCAmelCase      =			np.array([[0, 3], [3, 0], [2, 3]]			)
								_UpperCAmelCase      =			np.array([[2, 1], [6, 3]]			)

								with self.assertRaises(_SCREAMING_SNAKE_CASE			):
														schur_complement(_SCREAMING_SNAKE_CASE						,		_SCREAMING_SNAKE_CASE						,		_SCREAMING_SNAKE_CASE			)






		def 				UpperCAmelCase (    self			):
								_UpperCAmelCase      =			np.array([[1, 2, 1], [2, 1, 2], [3, 2, 4]]			)
								_UpperCAmelCase      =			np.array([[0, 3], [3, 0], [2, 3]]			)
								_UpperCAmelCase      =			np.array([[2, 1, 3], [6, 3, 5]]			)

								with self.assertRaises(_SCREAMING_SNAKE_CASE			):
														schur_complement(_SCREAMING_SNAKE_CASE						,		_SCREAMING_SNAKE_CASE						,		_SCREAMING_SNAKE_CASE			)


if __name__ == "__main__":
				import doctest

				doctest.testmod()
				unittest.main()