




"""simple docstring"""


from importlib import import_module

from .logging import get_logger


A_         =							get_logger(__name__)






class    lowercase:







 '''simple docstring'''





 def __init__(							self:						List[Any], a_:						str, a_:						Union[str, Any]=None						):




   '''simple docstring'''



   _snake_case				:						Optional[int]								=    attrs or []
   if module is not None:
     for key in module.__dict__:
       if key in attrs or not key.startswith("""__"""						):
         setattr(self, lowercase_, getattr(lowercase_, lowercase_						)						)
   _snake_case				:						Tuple								=    module._original_module if isinstance(lowercase_, _PatchedModuleObj						) else module







class    lowercase:







 '''simple docstring'''





 lowercase__					   =   []


 def __init__(							self:						Optional[int], a_:						Optional[int], a_:						str, a_:						Optional[int], a_:						List[str]=None						):




   '''simple docstring'''



   _snake_case				:						Any								=    obj
   _snake_case				:						Tuple								=    target
   _snake_case				:						Dict								=    new
   _snake_case				:						str								=    target.split("""."""						)[0]
   _snake_case				:						str								=    {}
   _snake_case				:						Optional[Any]								=    attrs or []


 def __enter__(							self:						List[str]						):




   '''simple docstring'''



   *_snake_case						,   _snake_case				:						Dict								=    self.target.split("""."""						)

   # Patch modules:
   # it's used to patch attributes of submodules like "os.path.join";
   # in this case we need to patch "os" and "os.path"

   for i in range(len(lowercase_						)						):
     try:
       _snake_case				:						Union[str, Any]								=    import_module(""".""".join(submodules[: i + 1]						)						)
     except ModuleNotFoundError:
       continue
     # We iterate over all the globals in self.obj in case we find "os" or "os.path"
     for attr in self.obj.__dir__():
       _snake_case				:						Any								=    getattr(self.obj, lowercase_						)
       # We don't check for the name of the global, but rather if its value *is* "os" or "os.path".
       # This allows to patch renamed modules like "from os import path as ospath".
       if obj_attr is submodule or (
           (isinstance(lowercase_, _PatchedModuleObj						) and obj_attr._original_module is submodule)
       ):
         _snake_case				:						str								=    obj_attr
         # patch at top level
         setattr(self.obj, lowercase_, _PatchedModuleObj(lowercase_, attrs=self.attrs						)						)
         _snake_case				:						Any								=    getattr(self.obj, lowercase_						)
         # construct lower levels patches
         for key in submodules[i + 1 :]:
           setattr(lowercase_, lowercase_, _PatchedModuleObj(getattr(lowercase_, lowercase_, lowercase_						), attrs=self.attrs						)						)
           _snake_case				:						Optional[Any]								=    getattr(lowercase_, lowercase_						)
         # finally set the target attribute
         setattr(lowercase_, lowercase_, self.new						)

        # Patch attribute itself:
        # it's used for builtins like "open",
        # and also to patch "os.path.join" we may also need to patch "join"
        # itself if it was imported as "from os.path import join".

   if submodules:  # if it's an attribute of a submodule like "os.path.join"
     try:
       _snake_case				:						Union[str, Any]								=    getattr(import_module(""".""".join(lowercase_						)						), lowercase_						)
     except (AttributeError, ModuleNotFoundError):
       return
     # We iterate over all the globals in self.obj in case we find "os.path.join"
     for attr in self.obj.__dir__():
       # We don't check for the name of the global, but rather if its value *is* "os.path.join".
       # This allows to patch renamed attributes like "from os.path import join as pjoin".
       if getattr(self.obj, lowercase_						) is attr_value:
         _snake_case				:						Dict								=    getattr(self.obj, lowercase_						)
         setattr(self.obj, lowercase_, self.new						)
   elif target_attr in globals()["__builtins__"]:  # if it'a s builtin like "open"
     _snake_case				:						Optional[Any]								=    globals()["""__builtins__"""][target_attr]
     setattr(self.obj, lowercase_, self.new						)
   else:
     raise RuntimeError(f"Tried to patch attribute {target_attr} instead of a submodule."						)


 def __exit__(							self:						Tuple, *a_:						Any						):




   '''simple docstring'''



   for attr in list(self.original						):
     setattr(self.obj, lowercase_, self.original.pop(lowercase_						)						)


 def 					UpperCamelCase_  (							self:						Union[str, Any]						):




   '''simple docstring'''



   self.__enter__()
   self._active_patches.append(self						)


 def 					UpperCamelCase_  (							self:						List[Any]						):




   '''simple docstring'''



   try:
     self._active_patches.remove(self						)
   except ValueError:
     # If the patch hasn't been started this will fail
     return None

   return self.__exit__()



# This code is adapted from OpenAI's release
# https://github.com/openai/human-eval/blob/master/human_eval/execution.py

import contextlib
import faulthandler
import io
import multiprocessing
import os
import platform
import signal
import tempfile


def 				lowerCAmelCase__       (			a__    ,     a__    ,     a__    ,     a__ )      ->str:




  '''simple docstring'''

  _UpperCamelCase           =    multiprocessing.Manager()
  _UpperCamelCase           =    manager.list()

  _UpperCamelCase           =    multiprocessing.Process(target=a__    ,     args=(check_program, result, timeout) )
  p.start()
  p.join(timeout=timeout + 1 )
  if p.is_alive():
    p.kill()

  if not result:
    result.append("timed out" )

  return {
      "task_id": task_id,
      "passed": result[0] == "passed",
      "result": result[0],
      "completion_id": completion_id,
  }


def 				lowerCAmelCase__       (			a__    ,     a__    ,     a__ )      ->Union[str, Any]:




  '''simple docstring'''

  with create_tempdir():
    # These system calls are needed when cleaning up tempdir.
    import os
    import shutil

    _UpperCamelCase           =    shutil.rmtree
    _UpperCamelCase           =    os.rmdir
    _UpperCamelCase           =    os.chdir

    # Disable functionalities that can make destructive changes to the test.
    reliability_guard()

    # Run program.
    try:
      _UpperCamelCase           =    {}
      with swallow_io():
        with time_limit(a__ ):
          exec(a__    ,     a__ )
      result.append("passed" )
    except TimeoutException:
      result.append("timed out" )
    except BaseException as e:
      result.append(f'failed: {e}' )

    # Needed for cleaning up.
    _UpperCamelCase           =    rmtree
    _UpperCamelCase           =    rmdir
    _UpperCamelCase           =    chdir


@contextlib.contextmanager
def 				lowerCAmelCase__       (			a__ )      ->Optional[Any]:




  '''simple docstring'''

  def signal_handler(a__    ,     a__ ):
    raise TimeoutException("Timed out!" )

  signal.setitimer(signal.ITIMER_REAL    ,     a__ )
  signal.signal(signal.SIGALRM    ,     a__ )
  try:
    yield
  finally:
    signal.setitimer(signal.ITIMER_REAL    ,     0 )


@contextlib.contextmanager
def 				lowerCAmelCase__       (			)      ->Optional[int]:




  '''simple docstring'''

  _UpperCamelCase           =    WriteOnlyStringIO()
  with contextlib.redirect_stdout(a__ ):
    with contextlib.redirect_stderr(a__ ):
      with redirect_stdin(a__ ):
        yield


@contextlib.contextmanager
def 				lowerCAmelCase__       (			)      ->Optional[int]:




  '''simple docstring'''

  with tempfile.TemporaryDirectory() as dirname:
    with chdir(a__ ):
      yield dirname




class 					_UpperCAmelCase			(     lowerCAmelCase  ):



 '''simple docstring'''




 pass




class 					_UpperCAmelCase			(     io.StringIO  ):



 '''simple docstring'''




 def 		__UpperCAmelCase				(		self				:   List[str]							, *lowercase_				:   str							, **lowercase_				:   List[str])						->	Optional[Any]:


   """simple docstring"""







   raise OSError







 def 		__UpperCAmelCase				(		self				:   Any							, *lowercase_				:   List[Any]							, **lowercase_				:   Optional[int])						->	Optional[int]:


   """simple docstring"""







   raise OSError







 def 		__UpperCAmelCase				(		self				:   int							, *lowercase_				:   int							, **lowercase_				:   str)						->	int:


   """simple docstring"""







   raise OSError







 def 		__UpperCAmelCase				(		self				:   List[Any]							, *lowercase_				:   Tuple							, **lowercase_				:   Tuple)						->	Tuple:


   """simple docstring"""







   return False




class 					_UpperCAmelCase			(     contextlib._RedirectStream  ):  # type: ignore



 '''simple docstring'''




 __A			       =					'''stdin'''


@contextlib.contextmanager
def 				lowerCAmelCase__       (			a__ )      ->str:




  '''simple docstring'''

  if root == ".":
    yield
    return
  _UpperCamelCase           =    os.getcwd()
  os.chdir(a__ )
  try:
    yield
  except BaseException as exc:
    raise exc
  finally:
    os.chdir(a__ )







def 				lowerCAmelCase__       (			a__=None )      ->Optional[int]:




  '''simple docstring'''

  if maximum_memory_bytes is not None:
    import resource

    resource.setrlimit(resource.RLIMIT_AS    ,     (maximum_memory_bytes, maximum_memory_bytes) )
    resource.setrlimit(resource.RLIMIT_DATA    ,     (maximum_memory_bytes, maximum_memory_bytes) )
    if not platform.uname().system == "Darwin":
      resource.setrlimit(resource.RLIMIT_STACK    ,     (maximum_memory_bytes, maximum_memory_bytes) )

  faulthandler.disable()

  import builtins

  _UpperCamelCase           =    None
  _UpperCamelCase           =    None

  import os

  _UpperCamelCase           =    "1"

  _UpperCamelCase           =    None
  _UpperCamelCase           =    None
  _UpperCamelCase           =    None
  _UpperCamelCase           =    None
  _UpperCamelCase           =    None
  _UpperCamelCase           =    None
  _UpperCamelCase           =    None
  _UpperCamelCase           =    None
  _UpperCamelCase           =    None
  _UpperCamelCase           =    None
  _UpperCamelCase           =    None
  _UpperCamelCase           =    None
  _UpperCamelCase           =    None
  _UpperCamelCase           =    None
  _UpperCamelCase           =    None
  _UpperCamelCase           =    None
  _UpperCamelCase           =    None
  _UpperCamelCase           =    None
  _UpperCamelCase           =    None
  _UpperCamelCase           =    None
  _UpperCamelCase           =    None
  _UpperCamelCase           =    None
  _UpperCamelCase           =    None
  _UpperCamelCase           =    None
  _UpperCamelCase           =    None
  _UpperCamelCase           =    None
  _UpperCamelCase           =    None

  import shutil

  _UpperCamelCase           =    None
  _UpperCamelCase           =    None
  _UpperCamelCase           =    None

  import subprocess

  _UpperCamelCase           =    None  # type: ignore

  _UpperCamelCase           =    None

  import sys

  _UpperCamelCase           =    None
  _UpperCamelCase           =    None
  _UpperCamelCase           =    None
  _UpperCamelCase           =    None
  _UpperCamelCase           =    None




