internlm/SWE-Fixer-Train-110K huggingface dataset:
Repository: numba/numba

Issue:
Not compatible with onetbb-2021.6.0
## Reporting a bug

```
numba/np/ufunc/tbbpool.cpp:238:45: error: call to non-static member function without an object argument
                tbb::task_scheduler_handle::release(tsh);
                ~~~~~~~~~~~~~~~~~~~~~~~~~~~~^~~~~~~
numba/np/ufunc/tbbpool.cpp:263:43: error: no member named 'get' in 'tbb::detail::d1::task_scheduler_handle'
        tsh = tbb::task_scheduler_handle::get();
              ~~~~~~~~~~~~~~~~~~~~~~~~~~~~^
numba/np/ufunc/tbbpool.cpp:301:39: error: no member named 'get' in 'tbb::detail::d1::task_scheduler_handle'
    tsh = tbb::task_scheduler_handle::get();
          ~~~~~~~~~~~~~~~~~~~~~~~~~~~~^
3 errors generated.
```

- [x] I have tried using the latest released version of Numba (most recent is
 visible in the change log (https://github.com/numba/numba/blob/main/CHANGE_LOG).
- [ ] I have included a self contained code sample to reproduce the problem.
  i.e. it's possible to run as 'python bug.py'.



Discussion:

Resolving patch:
diff --git a/numba/np/ufunc/parallel.py b/numba/np/ufunc/parallel.py
--- a/numba/np/ufunc/parallel.py
+++ b/numba/np/ufunc/parallel.py
@@ -361,10 +361,10 @@ def _check_tbb_version_compatible():
         version_func.argtypes = []
         version_func.restype = c_int
         tbb_iface_ver = version_func()
-        if tbb_iface_ver < 12010: # magic number from TBB
+        if tbb_iface_ver < 12060: # magic number from TBB
             msg = ("The TBB threading layer requires TBB "
-                   "version 2021 update 1 or later i.e., "
-                   "TBB_INTERFACE_VERSION >= 12010. Found "
+                   "version 2021 update 6 or later i.e., "
+                   "TBB_INTERFACE_VERSION >= 12060. Found "
                    "TBB_INTERFACE_VERSION = %s. The TBB "
                    "threading layer is disabled.") % tbb_iface_ver
             problem = errors.NumbaWarning(msg)


Test patch:
diff --git a/buildscripts/condarecipe.local/run_test.bat b/buildscripts/condarecipe.local/run_test.bat
--- a/buildscripts/condarecipe.local/run_test.bat
+++ b/buildscripts/condarecipe.local/run_test.bat
@@ -3,6 +3,11 @@ set NUMBA_DISABLE_ERROR_MESSAGE_HIGHLIGHTING=1
 set NUMBA_CAPTURED_ERRORS=new_style
 set PYTHONFAULTHANDLER=1
 
+@rem no parallel target support for 32 bit windows and no TBB packages
+if "%ARCH%"=="32" (
+    set NUMBA_DISABLE_TBB=1
+)
+
 @rem Check Numba executable is there
 numba -h
Repository: numba/numba

Issue:
`isinstance` check produces wrong output
Mutating a variable inside an `isinstance` produces the wrong output

```python
from numba import njit

@njit
def foo(a):
    x = 0
    if isinstance(a, int):
        # renaming variable fixes the issue: "b = (a, a)"
        a = (a, a)

    for i in range(len(a)):
        x += i
    return x

a = 3
print(foo(a))  # 0
print(foo.py_func(a))  # 1
```

------------

*  Using a while loop fixes the issue
```python
@njit
def foo(a):
    x = 0
    if isinstance(a, int):
        a = (a, a)
    i = 0
    while i < len(a):
        x += i
        i += 1
    return x

a = 3
print(foo(a))  # 1
print(foo.py_func(a))  # 1
```

------------

* Renaming `b = (a, a)` fixes it as well

```python
@njit
def foo(a):
    x = 0
    if isinstance(a, int):
        b = (a, a)
    for i in range(len(b)):
        x += i
    return x

a = 3
print(foo(a))  # 1
print(foo.py_func(a))  # 1
```


Discussion:

Resolving patch:
diff --git a/numba/core/untyped_passes.py b/numba/core/untyped_passes.py
--- a/numba/core/untyped_passes.py
+++ b/numba/core/untyped_passes.py
@@ -1574,6 +1574,15 @@ def run_pass(self, state):
                                    'due to a branch.')
                             raise errors.NumbaTypeError(msg, loc=assign.loc)
 
+                # Only propagate a PHI node if all arguments are the same
+                # constant
+                if isinstance(value, ir.Expr) and value.op == 'phi':
+                    # typemap will return None in case `inc.name` not in typemap
+                    v = [typemap.get(inc.name) for inc in value.incoming_values]
+                    # stop if the elements in `v` do not hold the same value
+                    if v[0] is not None and any([v[0] != vi for vi in v]):
+                        continue
+
                 lit = typemap.get(target.name, None)
                 if lit and isinstance(lit, types.Literal):
                     # replace assign instruction by ir.Const(lit) iff


Test patch:
diff --git a/numba/tests/test_builtins.py b/numba/tests/test_builtins.py
--- a/numba/tests/test_builtins.py
+++ b/numba/tests/test_builtins.py
@@ -309,6 +309,17 @@ def invalid_isinstance_usecase_phi_nopropagate(x):
         return False
 
 
+def invalid_isinstance_usecase_phi_nopropagate2(a):
+    # Numba issue #9125
+    x = 0
+    if isinstance(a, int):
+        a = (a, a)
+
+    for i in range(len(a)):
+        x += i
+    return x
+
+
 def invalid_isinstance_optional_usecase(x):
     if x > 4:
         z = 10
@@ -1246,6 +1257,11 @@ def test_isinstance_dict(self):
         cfunc = jit(nopython=True)(pyfunc)
         self.assertEqual(pyfunc(), cfunc())
 
+    def test_isinstance_issue9125(self):
+        pyfunc = invalid_isinstance_usecase_phi_nopropagate2
+        cfunc = jit(nopython=True)(pyfunc)
+        self.assertEqual(pyfunc(3), cfunc(3))
+
     def test_isinstance_numba_types(self):
         # This makes use of type aliasing between python scalars and NumPy
         # scalars, see also test_numba_types()
Repository: numba/numba

Issue:
refcount error in test_np_randomgen.py
This seems to be caught only by a debug build of python. I followed these steps to reproduce, using pyenv:

```
pyenv install -g 3.10.4 
pyenv virtualenv 3.10.4-debug numba-57-debug
pyenv activate numba-57-debug
git clone https://github.com/numba/numba.git
cd numba
git checkout 0.57.1
pip install -e .
python runtests.py numba.tests.test_np_randomgen.TestRandomGenerators.test_npgen_boxing_unboxing
```

Which causes a failure similar to the following:

```
================================================================================
Modules/gcmodule.c:113: gc_decref: Assertion "gc_get_refs(g) > 0" failed: refcount is too small
Enable tracemalloc to get the memory block allocation traceback

object address  : 0x5602c139b1c0
object refcount : 59
object type     : 0x7fc4484fd4c0
object type name: _ctypes.PyCSimpleType
object repr     : <class 'ctypes.c_void_p'>

Fatal Python error: _PyObject_AssertFailed: _PyObject_AssertFailed
Python runtime state: initialized

```

system info:

```
Linux umibozu 6.3.7-1rodete2-amd64 #1 SMP PREEMPT_DYNAMIC Debian 6.3.7-1rodete2 (2023-07-14) x86_64 GNU/Linux
model name      : Intel(R) Xeon(R) Gold 6154 CPU @ 3.00GHz                                                                                                                                          
```


Discussion:
[debuglog.txt](https://github.com/numba/numba/files/12384123/debuglog.txt)


Resolving patch:
diff --git a/numba/core/boxing.py b/numba/core/boxing.py
--- a/numba/core/boxing.py
+++ b/numba/core/boxing.py
@@ -1230,11 +1230,9 @@ def wire_in_fnptrs(name):
 
             # Want to do ctypes.cast(CFunctionType, ctypes.c_void_p), create an
             # args tuple for that.
-            extra_refs.append(ct_voidptr_ty)
             args = c.pyapi.tuple_pack([interface_next_fn, ct_voidptr_ty])
             with cgutils.early_exit_if_null(c.builder, stack, args):
                 handle_failure()
-            extra_refs.append(ct_voidptr_ty)
 
             # Call ctypes.cast()
             interface_next_fn_casted = c.pyapi.call(ct_cast, args)


Test patch:
Repository: google/openhtf

Issue:
Add ability to pass in dut_serial via command line config
Add ability to pass in dut_serial via command line.  This would be a useful feature when doing loop test



Discussion:

Resolving patch:
diff --git a/openhtf/exe/triggers.py b/openhtf/exe/triggers.py
--- a/openhtf/exe/triggers.py
+++ b/openhtf/exe/triggers.py
@@ -38,14 +38,20 @@
 import logging
 import time
 
+import gflags
+
 from openhtf.io import user_input
 
-_LOG = logging.getLogger(__name__)
+gflags.DEFINE_string('dut_serial', 'UNKNOWN_DUT_ID',
+                     'DUT serial to start the test with. '
+                     'Only use if using the AutoStart trigger.')
 
+FLAGS = gflags.FLAGS
+_LOG = logging.getLogger(__name__)
 
 def AutoStart():  # pylint: disable=invalid-name
   """Start the test immediately with a dummy DUT ID."""
-  return 'UNKNOWN_DUT_ID'
+  return FLAGS.dut_serial
 
 
 def AutoStop(dummy_dut_id):  # pylint: disable=invalid-name


Test patch:
Repository: google/openhtf

Issue:
Start Test Prompt is timing out and raising PromptUnansweredError
Start Test Prompt appears to be using same timeout as user prompts.  When using this in loop mode we shouldn't have a timeout



Discussion:
Hmm, good point. I'll wire up a way for the test start trigger to override the global prompt timeout.

Amy is working on this now. The plan we discussed:
- Add a timeout_s= keyword arg to DisplayPrompt with a default taken from FLAGS.
- Change the _cond.wait() call to use the new kwarg.
- In PromptForTestStart, provide an exceedingly long timeout via the timeout_ms kwarg.


Resolving patch:
diff --git a/openhtf/exe/triggers.py b/openhtf/exe/triggers.py
--- a/openhtf/exe/triggers.py
+++ b/openhtf/exe/triggers.py
@@ -61,18 +61,20 @@ def AutoStop(dummy_dut_id):  # pylint: disable=invalid-name
 
 # pylint: disable=invalid-name
 def PromptForTestStart(message='Provide a DUT ID in order to start the test.',
-                       text_input=True):
+                       text_input=False, timeout_s=60*60*24):
   """Make a test start trigger based on prompting the user for input."""
   def trigger():  # pylint: disable=missing-docstring
     prompt_manager = user_input.get_prompt_manager()
-    return prompt_manager.DisplayPrompt(message, text_input=text_input)
+    return prompt_manager.DisplayPrompt(
+        message, text_input=text_input, timeout_s=timeout_s)
   return trigger
 
 
 def PromptForTestStop(message='Hit ENTER to complete the test.',
-                      text_input=False):
+                      text_input=False, timeout_s=60*60*24):
   """Make a test stop trigger based on prompting the user for a response."""
   def trigger(dummy_dut_id):  # pylint: disable=missing-docstring
     prompt_manager = user_input.get_prompt_manager()
-    return prompt_manager.DisplayPrompt(message, text_input=text_input)
+    return prompt_manager.DisplayPrompt(
+        message, text_input=text_input, timeout_s=timeout_s)
   return trigger


Test patch:
Repository: google/openhtf

Issue:
Error Attaching Wav Files
using test.AttachFromFile(path_to_wav) results in UnicodeDecodeError: 'utf8' codec can't decode byte 0xa4 in position 5: invalid start byte



Discussion:

Resolving patch:
diff --git a/openhtf/exe/phase_data.py b/openhtf/exe/phase_data.py
--- a/openhtf/exe/phase_data.py
+++ b/openhtf/exe/phase_data.py
@@ -110,7 +110,7 @@ def AttachFromFile(self, filename, name=None, mimetype=None):
         the given name.
       IOError: Raised if the given filename couldn't be opened.
     """
-    with open(filename, 'r') as f:  # pylint: disable=invalid-name
+    with open(filename, 'rb') as f:  # pylint: disable=invalid-name
       self.Attach(
           name if name is not None else filename, f.read(),
           mimetype=mimetype if mimetype is not None else mimetypes.guess_type(


Test patch:
Repository: google/openhtf

Issue:
Remove Werkzeug from setup.py
Remove Werkzeug from setup.py.  This is a Flask dependency which was removed



Discussion:

Resolving patch:
diff --git a/setup.py b/setup.py
--- a/setup.py
+++ b/setup.py
@@ -116,7 +116,6 @@ def run(self):
     'PyYAML==3.11',
     'singledispatch==3.4.0.3',
     'tornado==4.3',
-    'Werkzeug==0.10.4',
 ]
 
 


Test patch:
Repository: google/openhtf

Issue:
remove MarkupSafe from setup.py
remove MarkupSafe from setup.py.  I don't see this being used anywhere



Discussion:
same with singledispatch?

(trying to reduce dependencies I have to add to virtual env)

N/M looks like tornado is using singledispatch

I'm down with it. Let's try to get them all in one fell swoop.


Resolving patch:
diff --git a/setup.py b/setup.py
--- a/setup.py
+++ b/setup.py
@@ -107,14 +107,11 @@ def run(self):
 INSTALL_REQUIRES = [
     'contextlib2==0.5.1',
     'enum34==1.1.2',
-    'MarkupSafe==0.23',
     'mutablerecords==0.2.9',
     'oauth2client==1.5.2',
     'protobuf==2.6.1',
     'pyaml==15.3.1',
     'pyOpenSSL==0.15.1',
-    'PyYAML==3.11',
-    'singledispatch==3.4.0.3',
     'tornado==4.3',
 ]
 


Test patch:
Repository: google/openhtf

Issue:
"Provide a DUT ID in order to start the test" does not reliably print to stdout
Cloned repo from head, hello world hangs, CTRL+C shows:

python hello_world.py 
^C2016-05-16 16:25:54,533 - ERROR - Received SIGINT.
2016-05-16 16:25:54,534 - ERROR - Stopping Test due to SIGINT: None
Traceback (most recent call last):
  File "hello_world.py", line 87, in <module>
    test.Execute(test_start=triggers.PromptForTestStart())
  File "/home/source/openhtf/openhtf/**init**.py", line 181, in Execute
    record = self._executor.GetState().GetFinishedRecord()
AttributeError: 'NoneType' object has no attribute 'GetFinishedRecord'



Discussion:
The error message here is a red herring that occurs if you ctrl+c before test state is created. The bigger concern is why hello_world.py is hanging for you. I just cloned from head and was able to run hello_world.py without the hang.

Can you tell me your exact steps to repro?

I deleted my virtualenv and repo and followed the steps in CONTRIBUTING.md.  Found that the issue is that I do not see the prompt "Provide a DUT ID in order to start the test." which created confusion.

(venv)laptop:~/source/openhtf/examples$ python hello_world.py 
test
Hello World!
Finishing test execution with outcome PASS.
(venv)laptop:~/source/openhtf/examples$ python hello_world.py 
test
Hello World!
Finishing test execution with outcome PASS.

Able to reproduce.  Through some trial and error I found I can get it to reliably print out by removing  termios.tcflush or adding a delay before termios.tcflush in ConsolePrompt.

 print self._message
 time.sleep(.01)
 # Before reading, clear any lingering buffered terminal input.
 termios.tcflush(sys.stdin, termios.TCIOFLUSH)

I also tried doing sys.stdout.flush() instead of the delay and that didn't appear to help.

Thanks, I'll check it out.

Any objections to merging any of the following?
1. comment out:
   
   # termios.tcflush(sys.stdin, termios.TCIOFLUSH)
2. add delay?
3. Switch to sys.stdin.flush()?

I'd rather understand what's going on here a little better, and potentially switch to using readline (i believe that's what we had talked about?) as a more cross-platform solution.  Specifically, https://pypi.python.org/pypi/pyreadline is a pure-python implementation that is suggested as a Windows-friendly alternative at https://pypi.python.org/pypi/gnureadline


Resolving patch:
diff --git a/openhtf/io/user_input.py b/openhtf/io/user_input.py
--- a/openhtf/io/user_input.py
+++ b/openhtf/io/user_input.py
@@ -157,7 +157,7 @@ def run(self):
         print self._message
 
         # Before reading, clear any lingering buffered terminal input.
-        termios.tcflush(sys.stdin, termios.TCIOFLUSH)
+        termios.tcflush(sys.stdin, termios.TCIFLUSH)
 
         while not self._stopped:
           inputs, _, _ = select.select([sys.stdin], [], [], 0.001)


Test patch:
Repository: google/openhtf

Issue:
setup.py isn't locating protoc on OSX
setup.py isn't locating protoc on OSX

Homebrew default on OSX /usr/local



Discussion:
what does `pkg-config --variable prefix protobuf` output on OSX?


Resolving patch:
diff --git a/setup.py b/setup.py
--- a/setup.py
+++ b/setup.py
@@ -54,10 +54,13 @@ def initialize_options(self):
     try:
       prefix = subprocess.check_output(
           'pkg-config --variable prefix protobuf'.split()).strip()
-    except subprocess.CalledProcessError:
-      if platform.system() in {'Linux', 'Mac'}:
+    except (subprocess.CalledProcessError, OSError):
+      if platform.system() == 'Linux':
         # Default to /usr?
         prefix = '/usr'
+      elif platform.system() == 'Mac':
+        # Default to /usr/local for Homebrew
+        prefix = '/usr/local'
       else:
         raise NotImplementedError(
             'Windows support in-progress. Help us by submitting an issue! '


Test patch:
Repository: google/openhtf

Issue:
mfg_inspector output broken.
Traceback (most recent call last):
  File "C:\Users\CameraLab02\venv\lib\site-packages\openhtf__init__.py", line 110, in OutputTestRecord
    output_cb(record)
  File "C:\Users\CameraLab02\venv\lib\site-packages\openhtf\io\output\mfg_inspector.py", line 469, in **call**
    testrun = _TestRunFromTestRecord(test_record)
  File "C:\Users\CameraLab02\venv\lib\site-packages\openhtf\io\output\mfg_inspector.py", line 334, in _TestRunFromTestRe
cord
    mangled_parameters = _ExtractParameters(record, testrun, used_parameter_names)
  File "C:\Users\CameraLab02\venv\lib\site-packages\openhtf\io\output\mfg_inspector.py", line 260, in _ExtractParameters

```
for d in measurement.dimensions]
```

AttributeError: 'NoneType' object has no attribute 'encode'



Discussion:

Resolving patch:
diff --git a/openhtf/io/output/mfg_inspector.py b/openhtf/io/output/mfg_inspector.py
--- a/openhtf/io/output/mfg_inspector.py
+++ b/openhtf/io/output/mfg_inspector.py
@@ -256,7 +256,8 @@ def _ExtractParameters(record, testrun, used_parameter_names):
         attachment = testrun.info_parameters.add()
         attachment.name = 'multidim_%s' % name
         dims = [{
-            'uom_suffix': d.uom_suffix.encode('utf8'), 'uom_code': d.uom_code}
+            'uom_suffix': d.uom_suffix and d.uom_suffix.encode('utf8'),
+            'uom_code': d.uom_code}
             for d in measurement.dimensions]
         # Refer to the module docstring for the expected schema.
         attachment.value_binary = json.dumps({


Test patch:
Repository: google/openhtf

Issue:
Nicer failure mode for misuse of StoreInModule.
See #389.

> ...it's nonsensical to have no dots, but something one might accidentally do if you forget to do the %s/name business, maybe throw in a quick format check on the inputs of add_argument() to fail-fast rather than raise an obscure error here?
> @grybmadsci

Document util/argv.py
There are no docs on how to use this module.



Discussion:

Resolving patch:
diff --git a/openhtf/util/argv.py b/openhtf/util/argv.py
--- a/openhtf/util/argv.py
+++ b/openhtf/util/argv.py
@@ -35,7 +35,10 @@ def __init__(self, *args, **kwargs):
     def __call__(self, parser, namespace, values, option_string=None):
         if hasattr(self, '_proxy'):
             values = self._proxy(parser, namespace, values)
-        base, mod = self._tgt_mod.rsplit('.', 1)
-        module = getattr(__import__(base, fromlist=[mod]), mod)
+        if '.' in self._tgt_mod:
+          base, mod = self._tgt_mod.rsplit('.', 1)
+          module = getattr(__import__(base, fromlist=[mod]), mod)
+        else:
+          module = __import__(self._tgt_mod)
         setattr(module, self._tgt_attr, values)
 


Test patch:
Repository: google/openhtf

Issue:
Frontend broken
Exception in thread Thread-4:
Traceback (most recent call last):
  File "/usr/lib/python2.7/threading.py", line 810, in **bootstrap_inner
    self.run()
  File "openhtf/io/frontend/__init**.py", line 119, in run
    self._test.wait_for_update(timeout_s=self._wait_timeout_s))
  File "openhtf/io/station_api.py", line 283, in wait_for_update
    cached_state, summary_dict = self.cached_state_summary
  File "openhtf/io/station_api.py", line 266, in cached_state_summary
    phases=len(test_record.phases),
UnboundLocalError: local variable 'test_record' referenced before assignment



Discussion:

Resolving patch:
diff --git a/openhtf/io/station_api.py b/openhtf/io/station_api.py
--- a/openhtf/io/station_api.py
+++ b/openhtf/io/station_api.py
@@ -263,8 +263,8 @@ def cached_state_summary(self):
 
     test_record = mutablerecords.CopyRecord(
         cached_state.test_record,
-        phases=len(test_record.phases),
-        log_records=len(test_record.log_records))
+        phases=len(cached_state.test_record.phases),
+        log_records=len(cached_state.test_record.log_records))
 
     return cached_state, {
         'status': cached_state.status.name,
@@ -632,10 +632,9 @@ def wait_for_plug(self, test_id, plug_type_name, current_state, timeout_s):
     return test_state.plug_manager.wait_for_plug_update(
         plug_type_name, current_state, timeout_s)
 
-  def _summary_for_state(self, state):
+  @staticmethod
+  def _summary_for_state_dict(cls, state_dict):
     """Return a dict for state with counts swapped in for phase/log records."""
-    state_dict, event = state.asdict_with_event()
-    
     state_dict_summary = {
         k: v for k, v in state_dict.iteritems() if k != 'plugs'}
     state_dict_summary['test_record'] = mutablerecords.CopyRecord(
@@ -699,7 +698,8 @@ def wait_for_update(self, test_uid, remote_state_dict, timeout_s):
           'RPC:wait_for_update() -> short-circuited wait (local was blank)')
       return self._serialize_state_dict(state._asdict())
 
-    state_dict_summary = self._summary_for_state(state)
+    state_dict, update_event = state.asdict_with_event()
+    state_dict_summary = self._summary_for_state_dict(state_dict)
 
     # Deserialize the RemoteState fields for comparison.
     remote_state_dict = remote_state_dict and {
@@ -726,7 +726,7 @@ def wait_for_update(self, test_uid, remote_state_dict, timeout_s):
     # If we get here, then the remote side is already up-to-date, so we wait
     # for there to be new information available.  We rely on the TestState
     # object itself to notify us when this is the case.
-    if not event.wait(timeout_s):
+    if not update_event.wait(timeout_s):
       _LOG.debug('RPC:wait_for_update() -> timeout after %s seconds', timeout_s)
       raise UpdateTimeout('No new information before timeout.', timeout_s)
 


Test patch:
Repository: google/openhtf

Issue:
Web gui broken in pypi package.
The web gui doesn't work from PyPI install because I forgot to update the `package_data` path in `setup.py` when restructuring the package.



Discussion:

Resolving patch:
diff --git a/setup.py b/setup.py
--- a/setup.py
+++ b/setup.py
@@ -158,14 +158,15 @@ def run_tests(self):
 
 setup(
     name='openhtf',
-    version='1.0.0',
+    version='1.0.1',
     description='OpenHTF, the open hardware testing framework.',
     author='John Hawley',
     author_email='madsci@google.com',
     maintainer='Joe Ethier',
     maintainer_email='jethier@google.com',
     packages=find_packages(exclude='examples'),
-    package_data={'openhtf': ['io/frontend/prebuilt/**/*.*']},
+    package_data={'openhtf': ['output/web_gui/prebuilt/**/*.*',
+                              'output/web_gui/prebuilt/*.*']},
     cmdclass={
         'build_proto': BuildProtoCommand,
         'clean': CleanCommand,


Test patch: