

"""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   snake_case__     (	__lowerCamelCase       :					Optional[int]							,	__lowerCamelCase       :					Any=False			):
			"""simple docstring"""






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

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

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

# Windows
_lowercase				:				Union[str, Any]   		=		pytest.mark.skipif(
    sys.platform == "win32",
    reason="test should not be run on Windows",
)






def   snake_case__     (	__lowerCamelCase       :					str			):
			"""simple docstring"""






			try:
						import faiss  # noqa
			except ImportError:
						lowerCamelCase__	:	int				=unittest.skip('''test requires faiss'''			)(__UpperCamelCase			)
			return test_case






def   snake_case__     (	__lowerCamelCase       :					Union[str, Any]			):
			"""simple docstring"""






			try:
						import regex  # noqa
			except ImportError:
						lowerCamelCase__	:	Dict				=unittest.skip('''test requires regex'''			)(__UpperCamelCase			)
			return test_case






def   snake_case__     (	__lowerCamelCase       :					List[str]			):
			"""simple docstring"""






			try:
						import elasticsearch  # noqa
			except ImportError:
						lowerCamelCase__	:	str				=unittest.skip('''test requires elasticsearch'''			)(__UpperCamelCase			)
			return test_case






def   snake_case__     (	__lowerCamelCase       :					str			):
			"""simple docstring"""






			try:
						import sqlalchemy  # noqa
			except ImportError:
						lowerCamelCase__	:	Tuple				=unittest.skip('''test requires sqlalchemy'''			)(__UpperCamelCase			)
			return test_case






def   snake_case__     (	__lowerCamelCase       :					Dict			):
			"""simple docstring"""






			if not config.TORCH_AVAILABLE:
						lowerCamelCase__	:	Any				=unittest.skip('''test requires PyTorch'''			)(__UpperCamelCase			)
			return test_case






def   snake_case__     (	__lowerCamelCase       :					Tuple			):
			"""simple docstring"""






			if not config.TF_AVAILABLE:
						lowerCamelCase__	:	Tuple				=unittest.skip('''test requires TensorFlow'''			)(__UpperCamelCase			)
			return test_case






def   snake_case__     (	__lowerCamelCase       :					Tuple			):
			"""simple docstring"""






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






def   snake_case__     (	__lowerCamelCase       :					int			):
			"""simple docstring"""






			if not config.PIL_AVAILABLE:
						lowerCamelCase__	:	Optional[Any]				=unittest.skip('''test requires Pillow'''			)(__UpperCamelCase			)
			return test_case






def   snake_case__     (	__lowerCamelCase       :					Optional[Any]			):
			"""simple docstring"""






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






def   snake_case__     (	__lowerCamelCase       :					int			):
			"""simple docstring"""






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






def   snake_case__     (	__lowerCamelCase       :					Optional[Any]			):
			"""simple docstring"""






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






def   snake_case__     (	__lowerCamelCase       :					Tuple			):
			"""simple docstring"""






			def _require_spacy_model(__lowerCamelCase       :					Optional[Any]			):
						try:
									import spacy  # noqa F401

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

			return _require_spacy_model






def   snake_case__     (	__lowerCamelCase       :					str			):
			"""simple docstring"""






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






def   snake_case__     (	__lowerCamelCase       :					List[str]			):
			"""simple docstring"""






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






def   snake_case__     (	__lowerCamelCase       :					Optional[Any]			):
			"""simple docstring"""






			if not _run_slow_tests or _run_slow_tests == 0:
						lowerCamelCase__	:	Any				=unittest.skip('''test is slow'''			)(__UpperCamelCase			)
			return test_case






def   snake_case__     (	__lowerCamelCase       :					int			):
			"""simple docstring"""






			if not _run_local_tests or _run_local_tests == 0:
						lowerCamelCase__	:	Optional[int]				=unittest.skip('''test is local'''			)(__UpperCamelCase			)
			return test_case






def   snake_case__     (	__lowerCamelCase       :					str			):
			"""simple docstring"""






			if not _run_packaged_tests or _run_packaged_tests == 0:
						lowerCamelCase__	:	Union[str, Any]				=unittest.skip('''test is packaged'''			)(__UpperCamelCase			)
			return test_case






def   snake_case__     (	__lowerCamelCase       :					Optional[int]			):
			"""simple docstring"""






			if not _run_remote_tests or _run_remote_tests == 0:
						lowerCamelCase__	:	List[str]				=unittest.skip('''test requires remote'''			)(__UpperCamelCase			)
			return test_case






def   snake_case__     (	*__lowerCamelCase       :					List[str]			):
			"""simple docstring"""






			def decorate(cls       :					Union[str, Any]			):
						for name, fn in cls.__dict__.items():
									if callable(__UpperCamelCase			) and name.startswith('''test'''			):
												for decorator in decorators:
															lowerCamelCase__	:	Optional[int]				=decorator(__UpperCamelCase			)
												setattr(cls							,	__UpperCamelCase							,	__UpperCamelCase			)
						return cls

			return decorate

class  __SCREAMING_SNAKE_CASE			(   SCREAMING_SNAKE_CASE__     ):


					'''simple docstring'''





					pass





class  __SCREAMING_SNAKE_CASE			(   SCREAMING_SNAKE_CASE__     ):


					'''simple docstring'''





					_a         =							0
					_a         =							1
					_a         =							2






@contextmanager
def   snake_case__     (	__lowerCamelCase       :					Union[str, Any]=OfflineSimulationMode.CONNECTION_FAILS							,	__lowerCamelCase       :					Optional[int]=1e-1_6			):
			"""simple docstring"""
			lowerCamelCase__	:	Dict				=requests.Session().request

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

			def raise_connection_error(__lowerCamelCase       :					List[str]							,	__lowerCamelCase       :					List[str]							,	**__lowerCamelCase       :					int			):
						raise requests.ConnectionError('''Offline mode is enabled.'''							,	request=__UpperCamelCase			)

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






@contextmanager
def   snake_case__     (	*__lowerCamelCase       :					Optional[int]							,	**__lowerCamelCase       :					Dict			):
			"""simple docstring"""
			lowerCamelCase__	:	Optional[Any]				=str(Path().resolve()			)
			with tempfile.TemporaryDirectory(*__UpperCamelCase							,	**__UpperCamelCase			) as tmp_dir:
						try:
									os.chdir(__UpperCamelCase			)
									yield
						finally:
									os.chdir(__UpperCamelCase			)






@contextmanager
def   snake_case__     (	):
			"""simple docstring"""
			import gc

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






@contextmanager
def   snake_case__     (	):
			"""simple docstring"""
			import gc

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






def   snake_case__     (	__lowerCamelCase       :					Any							,	__lowerCamelCase       :					Union[str, Any]			):
			"""simple docstring"""
			return deepcopy(__UpperCamelCase			).integers(0							,	100							,	10			).tolist() == deepcopy(__UpperCamelCase			).integers(0							,	100							,	10			).tolist()






def   snake_case__     (	__lowerCamelCase       :					Optional[int]			):
			"""simple docstring"""
			import decorator
			from requests.exceptions import HTTPError

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

			return decorator.decorator(_wrapper							,	__UpperCamelCase			)

class  __SCREAMING_SNAKE_CASE			:


					'''simple docstring'''





					def __init__( self							:						Any,						lowerCamelCase							:						int,						lowerCamelCase							:						List[str],						lowerCamelCase							:						Union[str, Any]  )->      Dict:
								lowerCamelCase__	:	List[str]				=returncode
								lowerCamelCase__	:	Dict				=stdout
								lowerCamelCase__	:	Union[str, Any]				=stderr






async def   snake_case__     (	__lowerCamelCase       :					List[str]							,	__lowerCamelCase       :					List[str]			):
			"""simple docstring"""






			while True:
						lowerCamelCase__	:	int				=await stream.readline()
						if line:
									callback(__UpperCamelCase			)
						else:
									break






async def   snake_case__     (	__lowerCamelCase       :					List[str]							,	__lowerCamelCase       :					Dict=None							,	__lowerCamelCase       :					Union[str, Any]=None							,	__lowerCamelCase       :					int=None							,	__lowerCamelCase       :					List[str]=False							,	__lowerCamelCase       :					Dict=False			):
			"""simple docstring"""






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

			lowerCamelCase__	:	Union[str, Any]				=await asyncio.create_subprocess_exec(
			    cmd[0]							,	*cmd[1:]							,	stdin=__UpperCamelCase							,	stdout=asyncio.subprocess.PIPE							,	stderr=asyncio.subprocess.PIPE							,	env=__UpperCamelCase							,	)

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

			lowerCamelCase__	:	Union[str, Any]				=[]
			lowerCamelCase__	:	Dict				=[]

			def tee(__lowerCamelCase       :					List[str]							,	__lowerCamelCase       :					int							,	__lowerCamelCase       :					Dict							,	__lowerCamelCase       :					List[str]=""			):
						lowerCamelCase__	:	Any				=line.decode('''utf-8'''			).rstrip()
						sink.append(__UpperCamelCase			)
						if not quiet:
									print(__UpperCamelCase							,	__UpperCamelCase							,	file=__UpperCamelCase			)

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






def   snake_case__     (	__lowerCamelCase       :					Optional[Any]							,	__lowerCamelCase       :					Optional[int]=None							,	__lowerCamelCase       :					Tuple=None							,	__lowerCamelCase       :					str=180							,	__lowerCamelCase       :					Any=False							,	__lowerCamelCase       :					List[str]=True			):
			"""simple docstring"""
			lowerCamelCase__	:	Union[str, Any]				=asyncio.get_event_loop()
			lowerCamelCase__	:	List[Any]				=loop.run_until_complete(
			    _stream_subprocess(__UpperCamelCase							,	env=__UpperCamelCase							,	stdin=__UpperCamelCase							,	timeout=__UpperCamelCase							,	quiet=__UpperCamelCase							,	echo=__UpperCamelCase			)			)

			lowerCamelCase__	:	int				=""" """.join(__UpperCamelCase			)
			if result.returncode > 0:
						lowerCamelCase__	:	Tuple				="""\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   snake_case__     (	):
			"""simple docstring"""
			lowerCamelCase__	:	Union[str, Any]				=os.environ.get('''PYTEST_XDIST_WORKER'''							,	'''gw0'''			)
			lowerCamelCase__	:	List[Any]				=re.sub(R'''^gw'''							,	''''''							,	__UpperCamelCase							,	0							,	re.M			)
			return int(__UpperCamelCase			)






def   snake_case__     (	):
			"""simple docstring"""
			lowerCamelCase__	:	List[Any]				=29500
			lowerCamelCase__	:	Optional[Any]				=pytest_xdist_worker_id()
			return port + uniq_delta









"""simple docstring"""






def   snake_case__     (	__lowerCamelCase       :					int = 10							,	__lowerCamelCase       :					int = 22			):
			"""simple docstring"""
			lowerCamelCase__	:	Optional[Any]				=range(1							,	__lowerCamelCase			)
			lowerCamelCase__	:	str				=range(1							,	__lowerCamelCase			)
			return sum(
			    1 for power in powers for base in bases if len(str(base**power			)			) == power			)


if __name__ == "__main__":
		print(f'{solution(1_0, 2_2) = }')




