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





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


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

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

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

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


def 							a__					(							snake_case							):





  """simple docstring"""
  try:
    import faiss  # noqa
  except ImportError:
    __SCREAMING_SNAKE_CASE      :	List[Any]					=		unittest.skip('''test requires faiss'''							)(snake_case							)
  return test_case


def 							a__					(							snake_case							):





  """simple docstring"""
  try:
    import regex  # noqa
  except ImportError:
    __SCREAMING_SNAKE_CASE      :	List[str]					=		unittest.skip('''test requires regex'''							)(snake_case							)
  return test_case


def 							a__					(							snake_case							):





  """simple docstring"""
  try:
    import elasticsearch  # noqa
  except ImportError:
    __SCREAMING_SNAKE_CASE      :	Dict					=		unittest.skip('''test requires elasticsearch'''							)(snake_case							)
  return test_case


def 							a__					(							snake_case							):





  """simple docstring"""
  try:
    import sqlalchemy  # noqa
  except ImportError:
    __SCREAMING_SNAKE_CASE      :	Any					=		unittest.skip('''test requires sqlalchemy'''							)(snake_case							)
  return test_case


def 							a__					(							snake_case							):





  """simple docstring"""
  if not config.TORCH_AVAILABLE:
    __SCREAMING_SNAKE_CASE      :	Optional[Any]					=		unittest.skip('''test requires PyTorch'''							)(snake_case							)
  return test_case


def 							a__					(							snake_case							):





  """simple docstring"""
  if not config.TF_AVAILABLE:
    __SCREAMING_SNAKE_CASE      :	Dict					=		unittest.skip('''test requires TensorFlow'''							)(snake_case							)
  return test_case


def 							a__					(							snake_case							):





  """simple docstring"""
  if not config.JAX_AVAILABLE:
    __SCREAMING_SNAKE_CASE      :	Tuple					=		unittest.skip('''test requires JAX'''							)(snake_case							)
  return test_case


def 							a__					(							snake_case							):





  """simple docstring"""
  if not config.PIL_AVAILABLE:
    __SCREAMING_SNAKE_CASE      :	Union[str, Any]					=		unittest.skip('''test requires Pillow'''							)(snake_case							)
  return test_case


def 							a__					(							snake_case							):





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


def 							a__					(							snake_case							):





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


def 							a__					(							snake_case							):





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


def 							a__					(							snake_case							):





  """simple docstring"""

  def _require_spacy_model(snake_case							):
    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__					(							snake_case							):





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


def 							a__					(							snake_case							):





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


def 							a__					(							snake_case							):





  """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__					(							snake_case							):





  """simple docstring"""
  if not _run_local_tests or _run_local_tests == 0:
    __SCREAMING_SNAKE_CASE      :	int					=		unittest.skip('''test is local'''							)(snake_case							)
  return test_case


def 							a__					(							snake_case							):





  """simple docstring"""
  if not _run_packaged_tests or _run_packaged_tests == 0:
    __SCREAMING_SNAKE_CASE      :	Optional[Any]					=		unittest.skip('''test is packaged'''							)(snake_case							)
  return test_case


def 							a__					(							snake_case							):





  """simple docstring"""
  if not _run_remote_tests or _run_remote_tests == 0:
    __SCREAMING_SNAKE_CASE      :	Tuple					=		unittest.skip('''test requires remote'''							)(snake_case							)
  return test_case


def 							a__					(							*snake_case							):





  """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      :	Optional[Any]					=		decorator(snake_case							)
        setattr(cls       ,			snake_case       ,			snake_case							)
    return cls

  return decorate





class     __UpperCamelCase (							lowerCAmelCase__       ):






     """simple docstring"""







     pass






class     __UpperCamelCase (							lowerCAmelCase__       ):






     """simple docstring"""







     lowerCAmelCase_							   =			0
     lowerCAmelCase_							   =			1
     lowerCAmelCase_							   =			2






@contextmanager
def 							a__					(							snake_case=OfflineSimulationMode.CONNECTION_FAILS       ,			snake_case=1E-16							):





  """simple docstring"""
  __SCREAMING_SNAKE_CASE      :	Tuple					=		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
    __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      :	Optional[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      :	Union[str, Any]					=		e.args[0]
      __SCREAMING_SNAKE_CASE      :	Optional[Any]					=		(max_retry_error.args[0].replace('''10.255.255.1'''       ,			F'''OfflineMock[{url}]'''							),)
      __SCREAMING_SNAKE_CASE      :	Optional[int]					=		(max_retry_error,)
      raise

  def raise_connection_error(snake_case       ,			snake_case       ,			**snake_case							):
    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__					(							*snake_case       ,			**snake_case							):





  """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__					(							):





  """simple docstring"""
  import gc

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


@contextmanager
def 							a__					(							):





  """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__					(							snake_case       ,			snake_case							):





  """simple docstring"""
  return deepcopy(snake_case							).integers(0       ,			100       ,			10							).tolist() == deepcopy(snake_case							).integers(0       ,			100       ,			10							).tolist()


def 							a__					(							snake_case							):





  """simple docstring"""
  import decorator
  from requests.exceptions import HTTPError

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






     """simple docstring"""







     def __init__(				self							:							Optional[Any]     ,						_A							:							int     ,						_A							:							str     ,						_A							:							Dict ):







       """simple docstring"""




       __SCREAMING_SNAKE_CASE      :	Optional[int]					=		returncode
       __SCREAMING_SNAKE_CASE      :	List[Any]					=		stdout
       __SCREAMING_SNAKE_CASE      :	Union[str, Any]					=		stderr






async def 							a__					(							snake_case       ,			snake_case							):





  """simple docstring"""
  while True:
    __SCREAMING_SNAKE_CASE      :	Optional[int]					=		await stream.readline()
    if line:
      callback(snake_case							)
    else:
      break


async def 							a__					(							snake_case       ,			snake_case=None       ,			snake_case=None       ,			snake_case=None       ,			snake_case=False       ,			snake_case=False							):





  """simple docstring"""
  if echo:
    print('''\nRunning: '''       ,			''' '''.join(snake_case							)							)

  __SCREAMING_SNAKE_CASE      :	List[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      :	Optional[int]					=		[]
  __SCREAMING_SNAKE_CASE      :	int					=		[]

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


def 							a__					(							snake_case       ,			snake_case=None       ,			snake_case=None       ,			snake_case=180       ,			snake_case=False       ,			snake_case=True							):





  """simple docstring"""
  __SCREAMING_SNAKE_CASE      :	Tuple					=		asyncio.get_event_loop()
  __SCREAMING_SNAKE_CASE      :	Optional[Any]					=		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      :	Union[str, Any]					=		''' '''.join(snake_case							)
  if result.returncode > 0:
    __SCREAMING_SNAKE_CASE      :	Optional[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__					(							):





  """simple docstring"""
  __SCREAMING_SNAKE_CASE      :	Union[str, Any]					=		os.environ.get('''PYTEST_XDIST_WORKER'''       ,			'''gw0'''							)
  __SCREAMING_SNAKE_CASE      :	List[Any]					=		re.sub(R'''^gw'''       ,			''''''       ,			snake_case       ,			0       ,			re.M							)
  return int(snake_case							)


def 							a__					(							):





  """simple docstring"""
  __SCREAMING_SNAKE_CASE      :	List[Any]					=		29_500
  __SCREAMING_SNAKE_CASE      :	Tuple					=		pytest_xdist_worker_id()
  return port + uniq_delta


"""simple docstring"""

from math import ceil, sqrt




def      lowercase__    (       lowerCAmelCase					:       int = 1_000_000			)			->   int:






    """simple docstring"""




    UpperCAmelCase          =       0

    for outer_width in range(3			,					(limit // 4) + 2			):
        if outer_width**2 > limit:
            UpperCAmelCase          =       max(ceil(sqrt(outer_width**2 - limit			)			)			,					1			)
        else:
            UpperCAmelCase          =       1
        if (outer_width - hole_width_lower_bound) % 2:
            hole_width_lower_bound += 1

        answer += (outer_width - hole_width_lower_bound - 2) // 2 + 1

    return answer


if __name__ == "__main__":
   print(F'{solution() = }')



