





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


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

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

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

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



def 					__lowerCamelCase       (							a_					:		List[Any]							)      ->				int:
      try:
            import faiss  # noqa
      except ImportError:
            __SCREAMING_SNAKE_CASE       :List[Any]		    =  unittest.skip('''test requires faiss'''							)(a_							)
      return test_case



def 					__lowerCamelCase       (							a_					:		int							)      ->				Optional[Any]:
      try:
            import regex  # noqa
      except ImportError:
            __SCREAMING_SNAKE_CASE       :Tuple		    =  unittest.skip('''test requires regex'''							)(a_							)
      return test_case



def 					__lowerCamelCase       (							a_					:		Optional[int]							)      ->				Any:
      try:
            import elasticsearch  # noqa
      except ImportError:
            __SCREAMING_SNAKE_CASE       :Dict		    =  unittest.skip('''test requires elasticsearch'''							)(a_							)
      return test_case



def 					__lowerCamelCase       (							a_					:		Dict							)      ->				List[Any]:
      try:
            import sqlalchemy  # noqa
      except ImportError:
            __SCREAMING_SNAKE_CASE       :Optional[Any]		    =  unittest.skip('''test requires sqlalchemy'''							)(a_							)
      return test_case



def 					__lowerCamelCase       (							a_					:		List[Any]							)      ->				int:
      if not config.TORCH_AVAILABLE:
            __SCREAMING_SNAKE_CASE       :int		    =  unittest.skip('''test requires PyTorch'''							)(a_							)
      return test_case



def 					__lowerCamelCase       (							a_					:		Any							)      ->				int:
      if not config.TF_AVAILABLE:
            __SCREAMING_SNAKE_CASE       :Optional[int]		    =  unittest.skip('''test requires TensorFlow'''							)(a_							)
      return test_case



def 					__lowerCamelCase       (							a_					:		int							)      ->				str:
      if not config.JAX_AVAILABLE:
            __SCREAMING_SNAKE_CASE       :Optional[int]		    =  unittest.skip('''test requires JAX'''							)(a_							)
      return test_case



def 					__lowerCamelCase       (							a_					:		Union[str, Any]							)      ->				Optional[Any]:
      if not config.PIL_AVAILABLE:
            __SCREAMING_SNAKE_CASE       :Tuple		    =  unittest.skip('''test requires Pillow'''							)(a_							)
      return test_case



def 					__lowerCamelCase       (							a_					:		Union[str, Any]							)      ->				Dict:
      try:
            import transformers  # noqa F401
      except ImportError:
            return unittest.skip('''test requires transformers'''							)(a_							)
      else:
            return test_case



def 					__lowerCamelCase       (							a_					:		Optional[int]							)      ->				Union[str, Any]:
      try:
            import tiktoken  # noqa F401
      except ImportError:
            return unittest.skip('''test requires tiktoken'''							)(a_							)
      else:
            return test_case



def 					__lowerCamelCase       (							a_					:		Union[str, Any]							)      ->				Tuple:
      try:
            import spacy  # noqa F401
      except ImportError:
            return unittest.skip('''test requires spacy'''							)(a_							)
      else:
            return test_case



def 					__lowerCamelCase       (							a_					:		Optional[Any]							)      ->				Union[str, Any]:

      def _require_spacy_model(a_					:		Dict							):
            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 					__lowerCamelCase       (							a_					:		Optional[Any]							)      ->				Optional[int]:
      try:
            import pyspark  # noqa F401
      except ImportError:
            return unittest.skip('''test requires pyspark'''							)(a_							)
      else:
            return test_case



def 					__lowerCamelCase       (							a_					:		Union[str, Any]							)      ->				Union[str, Any]:
      try:
            import joblibspark  # noqa F401
      except ImportError:
            return unittest.skip('''test requires joblibspark'''							)(a_							)
      else:
            return test_case



def 					__lowerCamelCase       (							a_					:		int							)      ->				Dict:
      if not _run_slow_tests or _run_slow_tests == 0:
            __SCREAMING_SNAKE_CASE       :Union[str, Any]		    =  unittest.skip('''test is slow'''							)(a_							)
      return test_case



def 					__lowerCamelCase       (							a_					:		Any							)      ->				int:
      if not _run_local_tests or _run_local_tests == 0:
            __SCREAMING_SNAKE_CASE       :str		    =  unittest.skip('''test is local'''							)(a_							)
      return test_case



def 					__lowerCamelCase       (							a_					:		List[str]							)      ->				str:
      if not _run_packaged_tests or _run_packaged_tests == 0:
            __SCREAMING_SNAKE_CASE       :List[str]		    =  unittest.skip('''test is packaged'''							)(a_							)
      return test_case



def 					__lowerCamelCase       (							a_					:		str							)      ->				Dict:
      if not _run_remote_tests or _run_remote_tests == 0:
            __SCREAMING_SNAKE_CASE       :List[Any]		    =  unittest.skip('''test requires remote'''							)(a_							)
      return test_case



def 					__lowerCamelCase       (							*a_					:		int							)      ->				Optional[int]:
      def decorate(cls					:		Optional[int]							):
            for name, fn in cls.__dict__.items():
                  if callable(a_							) and name.startswith('''test'''							):
                        for decorator in decorators:
                              __SCREAMING_SNAKE_CASE       :Tuple		    =  decorator(a_							)
                        setattr(cls			,       a_			,       a_							)
            return cls

      return decorate






class  _SCREAMING_SNAKE_CASE(       A  ):
       pass






class  _SCREAMING_SNAKE_CASE(       A  ):
       SCREAMING_SNAKE_CASE_       :				List[str]     						=  0
       SCREAMING_SNAKE_CASE_       :				Dict     						=  1
       SCREAMING_SNAKE_CASE_       :				Optional[Any]     						=  2




@contextmanager
def 					__lowerCamelCase       (							a_					:		int=OfflineSimulationMode.CONNECTION_FAILS			,       a_					:		Any=1e-16							)      ->				Tuple:
      __SCREAMING_SNAKE_CASE       :Union[str, Any]		    =  requests.Session().request

      def timeout_request(a_					:		Optional[Any]			,       a_					:		Dict			,       a_					:		int			,       **a_					:		Optional[Any]							):
            # Change the url to an invalid url so that the connection hangs
            __SCREAMING_SNAKE_CASE       :Dict		    =  '''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       :List[Any]		    =  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
                  __SCREAMING_SNAKE_CASE       :str		    =  url
                  __SCREAMING_SNAKE_CASE       :Optional[Any]		    =  e.args[0]
                  __SCREAMING_SNAKE_CASE       :Dict		    =  (max_retry_error.args[0].replace('''10.255.255.1'''			,       f'''OfflineMock[{url}]'''							),)
                  __SCREAMING_SNAKE_CASE       :Dict		    =  (max_retry_error,)
                  raise

      def raise_connection_error(a_					:		List[Any]			,       a_					:		Union[str, Any]			,       **a_					:		List[Any]							):
            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 					__lowerCamelCase       (							*a_					:		int			,       **a_					:		List[Any]							)      ->				str:
      __SCREAMING_SNAKE_CASE       :Optional[int]		    =  str(Path().resolve()							)
      with tempfile.TemporaryDirectory(*a_			,       **a_							) as tmp_dir:
            try:
                  os.chdir(a_							)
                  yield
            finally:
                  os.chdir(a_							)



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

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



@contextmanager
def 					__lowerCamelCase       (							)      ->				int:
      import gc

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



def 					__lowerCamelCase       (							a_					:		List[str]			,       a_					:		str							)      ->				Dict:
      return deepcopy(a_							).integers(0			,       1_00			,       10							).tolist() == deepcopy(a_							).integers(0			,       1_00			,       10							).tolist()



def 					__lowerCamelCase       (							a_					:		Tuple							)      ->				List[Any]:
      import decorator
      from requests.exceptions import HTTPError

      def _wrapper(a_					:		List[str]			,       *a_					:		Any			,       **a_					:		int							):
            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  _SCREAMING_SNAKE_CASE:




       def __init__(						self		,SCREAMING_SNAKE_CASE__		,SCREAMING_SNAKE_CASE__		,SCREAMING_SNAKE_CASE__							)      ->				List[Any]:





             """simple docstring"""






             __SCREAMING_SNAKE_CASE       :Tuple		    =  returncode
             __SCREAMING_SNAKE_CASE       :Optional[Any]		    =  stdout
             __SCREAMING_SNAKE_CASE       :Tuple		    =  stderr




async def 					__lowerCamelCase       (							a_					:		Optional[int]			,       a_					:		List[str]							)      ->				Tuple:
      while True:
            __SCREAMING_SNAKE_CASE       :str		    =  await stream.readline()
            if line:
                  callback(a_							)
            else:
                  break



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

      __SCREAMING_SNAKE_CASE       :str		    =  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)

      __SCREAMING_SNAKE_CASE       :List[Any]		    =  []
      __SCREAMING_SNAKE_CASE       :Union[str, Any]		    =  []

      def tee(a_					:		List[str]			,       a_					:		List[str]			,       a_					:		Any			,       a_					:		int=""							):
            __SCREAMING_SNAKE_CASE       :Tuple		    =  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 a_							: tee(a_			,       a_			,       sys.stdout			,       label='''stdout:'''							)							),
              _read_stream(p.stderr			,       lambda a_							: tee(a_			,       a_			,       sys.stderr			,       label='''stderr:'''							)							),
          ]			,       timeout=a_			,       )
      return _RunOutput(await p.wait()			,       a_			,       a_							)



def 					__lowerCamelCase       (							a_					:		Optional[Any]			,       a_					:		Optional[int]=None			,       a_					:		int=None			,       a_					:		Any=1_80			,       a_					:		Optional[Any]=False			,       a_					:		int=True							)      ->				_RunOutput:
      __SCREAMING_SNAKE_CASE       :Tuple		    =  asyncio.get_event_loop()
      __SCREAMING_SNAKE_CASE       :Tuple		    =  loop.run_until_complete(
          _stream_subprocess(a_			,       env=a_			,       stdin=a_			,       timeout=a_			,       quiet=a_			,       echo=a_							)							)

      __SCREAMING_SNAKE_CASE       :Optional[int]		    =  ''' '''.join(a_							)
      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 					__lowerCamelCase       (							)      ->				Tuple:
      __SCREAMING_SNAKE_CASE       :List[Any]		    =  os.environ.get('''PYTEST_XDIST_WORKER'''			,       '''gw0'''							)
      __SCREAMING_SNAKE_CASE       :Dict		    =  re.sub(r'''^gw'''			,       ''''''			,       a_			,       0			,       re.M							)
      return int(a_							)







def 					__lowerCamelCase       (							)      ->				Any:
      __SCREAMING_SNAKE_CASE       :Tuple		    =  2_95_00
      __SCREAMING_SNAKE_CASE       :int		    =  pytest_xdist_worker_id()
      return port + uniq_delta






"""simple docstring"""
import colorsys

from PIL import Image  # type: ignore



def 					__lowerCamelCase       (							a_					:		float			,       a_					:		float			,       a_					:		int							)      ->				float:
      __SCREAMING_SNAKE_CASE       :List[Any]		    =  x
      __SCREAMING_SNAKE_CASE       :List[Any]		    =  y
      for step in range(a_							):  # noqa: B007
            __SCREAMING_SNAKE_CASE       :Dict		    =  a * a - b * b + x
            __SCREAMING_SNAKE_CASE       :Tuple		    =  2 * a * b + y
            __SCREAMING_SNAKE_CASE       :Dict		    =  a_new

            # divergence happens for all complex number with an absolute value
            # greater than 4
            if a * a + b * b > 4:
                  break
      return step / (max_step - 1)



def 					__lowerCamelCase       (							a_					:		float							)      ->				tuple:
      if distance == 1:
            return (0, 0, 0)
      else:
            return (2_55, 2_55, 2_55)



def 					__lowerCamelCase       (							a_					:		float							)      ->				tuple:
      if distance == 1:
            return (0, 0, 0)
      else:
            return tuple(round(i * 2_55							) for i in colorsys.hsv_to_rgb(a_			,       1			,       1							)							)



def 					__lowerCamelCase       (							a_					:		int = 8_00			,       a_					:		int = 6_00			,       a_					:		float = -0.6			,       a_					:		float = 0			,       a_					:		float = 3.2			,       a_					:		int = 50			,       a_					:		bool = True			,       )      ->				Image.Image:
      __SCREAMING_SNAKE_CASE       :Optional[int]		    =  Image.new('''RGB'''			,       (image_width, image_height)							)
      __SCREAMING_SNAKE_CASE       :Tuple		    =  img.load()

      # loop through the image-coordinates
      for image_x in range(a_							):
            for image_y in range(a_							):
                  # determine the figure-coordinates based on the image-coordinates
                  __SCREAMING_SNAKE_CASE       :Dict		    =  figure_width / image_width * image_height
                  __SCREAMING_SNAKE_CASE       :str		    =  figure_center_x + (image_x / image_width - 0.5) * figure_width
                  __SCREAMING_SNAKE_CASE       :Tuple		    =  figure_center_y + (image_y / image_height - 0.5) * figure_height

                  __SCREAMING_SNAKE_CASE       :List[Any]		    =  get_distance(a_			,       a_			,       a_							)

                  # color the corresponding pixel based on the selected coloring-function
                  if use_distance_color_coding:
                        __SCREAMING_SNAKE_CASE       :Optional[int]		    =  get_color_coded_rgb(a_							)
                  else:
                        __SCREAMING_SNAKE_CASE       :Optional[Any]		    =  get_black_and_white_rgb(a_							)

      return img


if __name__ == "__main__":
  import doctest

  doctest.testmod()

  # colored version, full figure
  lowerCamelCase_       =		get_image()

  # uncomment for colored version, different section, zoomed in
  # img = get_image(figure_center_x = -0.6, figure_center_y = -0.4,
  # figure_width = 0.8)

  # uncomment for black and white version, full figure
  # img = get_image(use_distance_color_coding = False)

  # uncomment to save the image
  # img.save("mandelbrot.png")

  img.show()