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

Issue:
Make random seed accessible by cocotb tests
I use the numpy package in my cocotb tests. I want to seed the numpy random generator to make numpy's randomization predictable.
Cocotb does this for python's `random ` package in the [`__init__.py`](https://github.com/potentialventures/cocotb/blob/master/cocotb/__init__.py#L138) using `seed` variable. By making `seed` `global` type it can be accessed in `cocotb.test` as `cocotb.seed`. 
This allows the following: `numpy.random.seed(cocotb.seed)` which solves the problem.

I know that this is a one-liner but I don't know if this is the correct approach. Please review my proposal, thanks.
Make random seed accessible by cocotb tests
I use the numpy package in my cocotb tests. I want to seed the numpy random generator to make numpy's randomization predictable.
Cocotb does this for python's `random ` package in the [`__init__.py`](https://github.com/potentialventures/cocotb/blob/master/cocotb/__init__.py#L138) using `seed` variable. By making `seed` `global` type it can be accessed in `cocotb.test` as `cocotb.seed`. 
This allows the following: `numpy.random.seed(cocotb.seed)` which solves the problem.

I know that this is a one-liner but I don't know if this is the correct approach. Please review my proposal, thanks.


Discussion:

Resolving patch:
diff --git a/cocotb/__init__.py b/cocotb/__init__.py
--- a/cocotb/__init__.py
+++ b/cocotb/__init__.py
@@ -135,20 +135,21 @@ def _initialise_testbench(root_name):
     process_plusargs()
 
     # Seed the Python random number generator to make this repeatable
-    seed = os.getenv('RANDOM_SEED')
+    global RANDOM_SEED
+    RANDOM_SEED = os.getenv('RANDOM_SEED')
 
-    if seed is None:
+    if RANDOM_SEED is None:
         if 'ntb_random_seed' in plusargs:
-            seed = eval(plusargs['ntb_random_seed'])
+            RANDOM_SEED = eval(plusargs['ntb_random_seed'])
         elif 'seed' in plusargs:
-            seed = eval(plusargs['seed'])
+            RANDOM_SEED = eval(plusargs['seed'])
         else:
-            seed = int(time.time())
-        log.info("Seeding Python random module with %d" % (seed))
+            RANDOM_SEED = int(time.time())
+        log.info("Seeding Python random module with %d" % (RANDOM_SEED))
     else:
-        seed = int(seed)
-        log.info("Seeding Python random module with supplied seed %d" % (seed))
-    random.seed(seed)
+        RANDOM_SEED = int(RANDOM_SEED)
+        log.info("Seeding Python random module with supplied seed %d" % (RANDOM_SEED))
+    random.seed(RANDOM_SEED)
 
     module_str = os.getenv('MODULE')
     test_str = os.getenv('TESTCASE')
@@ -163,7 +164,7 @@ def _initialise_testbench(root_name):
 
     global regression_manager
 
-    regression_manager = RegressionManager(root_name, modules, tests=test_str, seed=seed, hooks=hooks)
+    regression_manager = RegressionManager(root_name, modules, tests=test_str, seed=RANDOM_SEED, hooks=hooks)
     regression_manager.initialise()
     regression_manager.execute()
 


Test patch:
Repository: cocotb/cocotb

Issue:
Profiling bug
When i enable the profiling i got the following traceback:

```make COCOTB_ENABLE_PROFILING=true
...
Traceback (most recent call last):
  File "/home/ademski/Documents/satellogic/hdlteam/cocotb/cocotb/__init__.py", line 41, in <module>
    from cocotb.scheduler import Scheduler
  File "/home/ademski/Documents/satellogic/hdlteam/cocotb/cocotb/scheduler.py", line 51, in <module>
    import cProfile, StringIO, pstats
ModuleNotFoundError: No module named 'StringIO
```

StringIO is not used in `scheduler.py`. I solved the problem removing that import.

Python version: 3.7.3


Discussion:

Resolving patch:
diff --git a/cocotb/scheduler.py b/cocotb/scheduler.py
--- a/cocotb/scheduler.py
+++ b/cocotb/scheduler.py
@@ -48,7 +48,7 @@
 
 # Debug mode controlled by environment variables
 if "COCOTB_ENABLE_PROFILING" in os.environ:
-    import cProfile, StringIO, pstats
+    import cProfile, pstats
     _profile = cProfile.Profile()
     _profiling = True
 else:


Test patch:
Repository: cocotb/cocotb

Issue:
XGMII interface issue in 8 byte width without interleaving
XGMII interface is 32 bit with 4 bit control or 2 words in a 64 bit word (and 8 bit control). Currently the XGMII monitor doesnt support if the XGMII_START is offset to the second 32:40 bit position. I have made an update which works for me locally.

             if ctrl[4] and bytes[4] == _XGMII_START:

                ctrl, bytes = ctrl[5:], bytes[5:]

                while self._add_payload(ctrl, bytes):
                    yield clk
                    ctrl, bytes = self._get_bytes()

located at line 136 in xgmii.py in monitors


Discussion:

Resolving patch:
diff --git a/cocotb/monitors/xgmii.py b/cocotb/monitors/xgmii.py
--- a/cocotb/monitors/xgmii.py
+++ b/cocotb/monitors/xgmii.py
@@ -133,6 +133,15 @@ def _monitor_recv(self):
                     yield clk
                     ctrl, bytes = self._get_bytes()
 
+            elif self.bytes == 8 :
+                if ctrl[4] and bytes[4] == _XGMII_START:
+
+                    ctrl, bytes = ctrl[5:], bytes[5:]
+
+                    while self._add_payload(ctrl, bytes):
+                        yield clk
+                        ctrl, bytes = self._get_bytes()
+
             if self._pkt:
 
                 self.log.debug("Received:\n%s" % (hexdump(self._pkt)))


Test patch:
Repository: cocotb/cocotb

Issue:
COCOTB_ANSI_OUTPUT=1 broken
@Matthewar https://github.com/potentialventures/cocotb/commit/5c399d9a7a2fe092e8ee9a3fe92e4daa6b34afd9 has broken usage of ``COCOTB_ANSI_OUTPUT=1``.
I have suggested a fix there as a comment.


Discussion:
Related: https://bixense.com/clicolors/

Resolving patch:
diff --git a/cocotb/log.py b/cocotb/log.py
--- a/cocotb/log.py
+++ b/cocotb/log.py
@@ -34,7 +34,7 @@
 import logging
 import warnings
 
-from cocotb.utils import get_sim_time
+from cocotb.utils import get_sim_time, want_color_output
 
 import cocotb.ANSI as ANSI
 
@@ -57,12 +57,8 @@ def __init__(self, name):
 
         # customizations of the defaults
         hdlr = logging.StreamHandler(sys.stdout)
-        want_ansi = os.getenv("COCOTB_ANSI_OUTPUT") and not os.getenv("GUI")
-        if want_ansi is None:
-            want_ansi = sys.stdout.isatty()  # default to ANSI for TTYs
-        else:
-            want_ansi = want_ansi == '1'
-        if want_ansi:
+
+        if want_color_output():
             hdlr.setFormatter(SimColourLogFormatter())
             self.colour = True
         else:
@@ -164,8 +160,8 @@ def format(self, record):
 
 
 class SimColourLogFormatter(SimLogFormatter):
-
     """Log formatter to provide consistent log message handling."""
+    
     loglevel2colour = {
         logging.DEBUG   :       "%s",
         logging.INFO    :       ANSI.COLOR_INFO + "%s" + ANSI.COLOR_DEFAULT,
diff --git a/cocotb/utils.py b/cocotb/utils.py
--- a/cocotb/utils.py
+++ b/cocotb/utils.py
@@ -280,15 +280,9 @@ def sane(x):
         return r
 
     def highlight(string, colour=ANSI.COLOR_HILITE_HEXDIFF_DEFAULT):
-        """Highlight only with ANSI output if it's requested and we are not in a GUI."""
+        """Highlight with ANSI colors if possible/requested and not running in GUI."""
         
-        want_ansi = os.getenv("COCOTB_ANSI_OUTPUT") and not os.getenv("GUI")
-        if want_ansi is None:
-            want_ansi = sys.stdout.isatty()  # default to ANSI for TTYs
-        else:
-            want_ansi = want_ansi == '1'
-
-        if want_ansi:
+        if want_color_output():
             return colour + string + ANSI.COLOR_DEFAULT
         else:
             return string
@@ -542,7 +536,7 @@ def __exit__(self, *excinfo):
 
 def reject_remaining_kwargs(name, kwargs):
     """
-    Helper function to emulate python 3 keyword-only arguments.
+    Helper function to emulate Python 3 keyword-only arguments.
 
     Use as::
 
@@ -590,6 +584,16 @@ def __get__(self, obj, cls):
         return value
 
 
+def want_color_output():
+    """Return ``True`` if colored output is possible/requested and not running in GUI."""
+    want_color = sys.stdout.isatty()  # default to color for TTYs
+    if os.getenv("COCOTB_ANSI_OUTPUT", default='0') == '1':
+        want_color = True
+    if os.getenv("GUI", default='0') == '1':
+        want_color = False
+    return want_color
+        
+    
 if __name__ == "__main__":
     import random
     a = ""


Test patch:
Repository: cocotb/cocotb

Issue:
[docs] Fix API docs in Bus()
The arguments of the cocotb.bus.Bus() class don't get rendered properly at the moment. See https://cocotb.readthedocs.io/en/latest/library_reference.html#cocotb.bus.Bus


Discussion:

Resolving patch:
diff --git a/cocotb/binary.py b/cocotb/binary.py
--- a/cocotb/binary.py
+++ b/cocotb/binary.py
@@ -99,7 +99,8 @@ class BinaryValue(object):
     def __init__(self, value=None, n_bits=None, bigEndian=True,
                  binaryRepresentation=BinaryRepresentation.UNSIGNED,
                  bits=None):
-        """Args:
+        """
+        Args:
             value (str or int or long, optional): Value to assign to the bus.
             n_bits (int, optional): Number of bits to use for the underlying
                 binary representation.
diff --git a/cocotb/bus.py b/cocotb/bus.py
--- a/cocotb/bus.py
+++ b/cocotb/bus.py
@@ -55,7 +55,8 @@ class Bus(object):
         Support for struct/record ports where signals are member names.
     """
     def __init__(self, entity, name, signals, optional_signals=[], bus_separator="_", array_idx=None):
-        """Args:
+        """
+        Args:
             entity (SimHandle): SimHandle instance to the entity containing the bus.
             name (str): Name of the bus. ``None`` for nameless bus, e.g. bus-signals
                 in an interface or a modport (untested on struct/record, 


Test patch:
Repository: cocotb/cocotb

Issue:
Packaging: Add python_requires to manifest
Define our Python version requirements in our package manifest, as described here: https://packaging.python.org/guides/distributing-packages-using-setuptools/#python-requires


Discussion:

Resolving patch:
diff --git a/setup.py b/setup.py
old mode 100644
new mode 100755
--- a/setup.py
+++ b/setup.py
@@ -55,6 +55,7 @@ def package_files(directory):
     author='Chris Higgs, Stuart Hodgson',
     author_email='cocotb@potentialventures.com',
     install_requires=[],
+    python_requires='>=2.7, !=3.0.*, !=3.1.*, !=3.2.*, !=3.3.*, !=3.4.*',
     packages=find_packages(),
     include_package_data=True,
     package_data={'cocotb': package_files('cocotb/share')},


Test patch:
Repository: cocotb/cocotb

Issue:
Py_Finalize() is never called
`Py_Finalize()` runs a number of very important cleanup routines, like flushing `stderr` and `stdout` (how I figured this out) and running `__del__` on living objects in Python 3.


Discussion:

Resolving patch:
diff --git a/cocotb/scheduler.py b/cocotb/scheduler.py
--- a/cocotb/scheduler.py
+++ b/cocotb/scheduler.py
@@ -775,9 +775,13 @@ def finish_scheduler(self, exc):
         """Directly call into the regression manager and end test
            once we return the sim will close us so no cleanup is needed.
         """
-        self.log.debug("Issue sim closedown result to regression object")
-        self._test.abort(exc)
-        cocotb.regression_manager.handle_result(self._test)
+        # If there is an error during cocotb initialization, self._test may not
+        # have been set yet. Don't cause another Python exception here.
+
+        if self._test:
+            self.log.debug("Issue sim closedown result to regression object")
+            self._test.abort(exc)
+            cocotb.regression_manager.handle_result(self._test)
 
     def cleanup(self):
         """Clear up all our state.


Test patch:
Repository: cocotb/cocotb

Issue:
Add Scheduler to Library Reference
The scheduler module is not at all listed in the Library Reference.


Discussion:

Resolving patch:
diff --git a/cocotb/__init__.py b/cocotb/__init__.py
--- a/cocotb/__init__.py
+++ b/cocotb/__init__.py
@@ -85,6 +85,8 @@
 
 
 scheduler = Scheduler()
+"""The global scheduler instance."""
+
 regression_manager = None
 
 plusargs = {}


Test patch:
Repository: cocotb/cocotb

Issue:
Change setup.py to list the version as 1.x-dev for versions installed from github
As suggested by @themperek, it would be neat if cocotb behaved like this:
```
> pip install git+https://github.com/cocotb/cocotb
> python -c "import cocotb; print(cocotb.__version__)"
1.4.0-dev
```


Discussion:

Resolving patch:
diff --git a/cocotb/_version.py b/cocotb/_version.py
--- a/cocotb/_version.py
+++ b/cocotb/_version.py
@@ -5,4 +5,4 @@
 # 1) we don't load dependencies by storing it in __init__.py
 # 2) we can import it in setup.py for the same reason
 # 3) we can import it into your module
-__version__ = '1.3.0'
+__version__ = '1.4.0.dev0'


Test patch:
Repository: cocotb/cocotb

Issue:
Document run order of tests
With #1380 merged, tests are now defined to run in the order they are listed in the source file. Document this fact somewhere in the docs, and the change in the release notes.


Discussion:
I assume you meant to merge the linked issue?

Resolving patch:
diff --git a/cocotb/decorators.py b/cocotb/decorators.py
--- a/cocotb/decorators.py
+++ b/cocotb/decorators.py
@@ -421,6 +421,8 @@ class test(_py_compat.with_metaclass(_decorator_helper, coroutine)):
     some common reporting etc., a test timeout and allows
     us to mark tests as expected failures.
 
+    Tests are evaluated in the order they are defined in a test module.
+
     Used as ``@cocotb.test(...)``.
 
     Args:


Test patch:
Repository: cocotb/cocotb

Issue:
Logging non-string messages leads to AttributeError
Test code:

```
dut._log.info(dut.empty.value)
# dut.empty is a signal in the DUT, .value gets its BinaryValue object
```

This worked fine in older versions of cocotb, haven't attempted to find exact regression range yet. Now I get this trace:

```
Traceback (most recent call last):
  File "/usr/lib64/python3.7/logging/__init__.py", line 1034, in emit
    msg = self.format(record)
  File "/usr/lib64/python3.7/logging/__init__.py", line 880, in format
    return fmt.format(record)
  File "/home/philipp/.local/lib/python3.7/site-packages/cocotb/log.py", line 201, in format
    msg = '\n'.join([SimColourLogFormatter.loglevel2colour[record.levelno] % line for line in msg.split('\n')])
AttributeError: 'BinaryValue' object has no attribute 'split'
Call stack:
  File "/home/philipp/.local/lib/python3.7/site-packages/cocotb/scheduler.py", line 355, in react
    self._event_loop(trigger)
  File "/home/philipp/.local/lib/python3.7/site-packages/cocotb/scheduler.py", line 448, in _event_loop
    self.schedule(coro, trigger=trigger)
  File "/home/philipp/.local/lib/python3.7/site-packages/cocotb/scheduler.py", line 758, in schedule
    result = coroutine._advance(send_outcome)
  File "/home/philipp/.local/lib/python3.7/site-packages/cocotb/decorators.py", line 264, in _advance
    return super(RunningTest, self)._advance(outcome)
  File "/home/philipp/.local/lib/python3.7/site-packages/cocotb/decorators.py", line 146, in _advance
    return outcome.send(self._coro)
  File "/home/philipp/.local/lib/python3.7/site-packages/cocotb/outcomes.py", line 38, in send
    return gen.send(self.value)
  File "path/to/test_fifo.py", line 45, in test_fifo_manual
    dut._log.info(dut.empty.value)
```

I'll try to come up with a test and a fix soon-ish.


Discussion:
Correct fix to me looks to be to call `str(msg)` before splitting, which is essentially what the default builtin formatter does (strictly that does `'stuff %s stuff' % msg`, but that's equivalent).

Resolving patch:
diff --git a/cocotb/log.py b/cocotb/log.py
--- a/cocotb/log.py
+++ b/cocotb/log.py
@@ -167,12 +167,8 @@ def _format(self, level, record, msg, coloured=False):
 
     def format(self, record):
         """Prettify the log output, annotate with simulation time"""
-        if record.args:
-            msg = record.msg % record.args
-        else:
-            msg = record.msg
 
-        msg = str(msg)
+        msg = record.getMessage()
         level = record.levelname.ljust(_LEVEL_CHARS)
 
         return self._format(level, record, msg)
@@ -192,10 +188,7 @@ class SimColourLogFormatter(SimLogFormatter):
     def format(self, record):
         """Prettify the log output, annotate with simulation time"""
 
-        if record.args:
-            msg = record.msg % record.args
-        else:
-            msg = record.msg
+        msg = record.getMessage()
 
         # Need to colour each line in case coloring is applied in the message
         msg = '\n'.join([SimColourLogFormatter.loglevel2colour[record.levelno] % line for line in msg.split('\n')])


Test patch:
Repository: cocotb/cocotb

Issue:
Simulator timestamps are broken in logs
Looks like gh-1411 didn't work properly. I'll try and find the fix shortly, but if we want to do a release before I do we should revert it.


Discussion:

Resolving patch:
diff --git a/cocotb/log.py b/cocotb/log.py
--- a/cocotb/log.py
+++ b/cocotb/log.py
@@ -72,17 +72,16 @@ def default_config():
     """
     # construct an appropriate handler
     hdlr = logging.StreamHandler(sys.stdout)
+    hdlr.addFilter(SimTimeContextFilter())
     if want_color_output():
         hdlr.setFormatter(SimColourLogFormatter())
     else:
         hdlr.setFormatter(SimLogFormatter())
 
-    filter = SimTimeContextFilter()
 
     logging.setLoggerClass(SimBaseLog)  # For backwards compatibility
     logging.basicConfig()
     logging.getLogger().handlers = [hdlr]  # overwrite default handlers
-    logging.getLogger().filters = [filter]
 
     # apply level settings for cocotb
     log = logging.getLogger('cocotb')
@@ -139,9 +138,9 @@ class SimTimeContextFilter(logging.Filter):
     """
 
     # needed to make our docs render well
-    def __init__(self, *args, **kwargs):
-        """ See :class:`logging.Filter` for argument descriptions """
-        super().__init__(*args, **kwargs)
+    def __init__(self):
+        """ Takes no arguments """
+        super().__init__()
 
     def filter(self, record):
         try:
@@ -156,9 +155,9 @@ def filter(self, record):
 class SimLogFormatter(logging.Formatter):
     """Log formatter to provide consistent log message handling.
 
-    This will only add simulator timestamps if the logger object has a
-    :class:`SimTimeContextFilter` filter attached, which cocotb ensures by
-    default.
+    This will only add simulator timestamps if the handler object this
+    formatter is attached to has a :class:`SimTimeContextFilter` filter
+    attached, which cocotb ensures by default.
     """
 
     # Removes the arguments from the base class. Docstring needed to make


Test patch:
Repository: cocotb/cocotb

Issue:
Honor NO_COLOR to disable colored output
The NO_COLOR environment variable is proposed as a way to disable all colored output, and more and more projects are using it now. (https://no-color.org/) We should support this variable, and deprecate  COCOTB_ANSI_OUTPUT (don't remove it just yet).


Discussion:
Interesting - there was a related proposal in https://bixense.com/clicolors/.
Also, FWIW, most (but not all) makefiles use ``| tee <logfile>`` which makes terminal auto-detection (``isatty``) fail.

Resolving patch:
diff --git a/cocotb/utils.py b/cocotb/utils.py
--- a/cocotb/utils.py
+++ b/cocotb/utils.py
@@ -524,6 +524,8 @@ def want_color_output():
     Colored output can be explicitly requested by setting :envvar:`COCOTB_ANSI_OUTPUT` to  ``1``.
     """
     want_color = sys.stdout.isatty()  # default to color for TTYs
+    if os.getenv("NO_COLOR") is not None:
+        want_color = False
     if os.getenv("COCOTB_ANSI_OUTPUT", default='0') == '1':
         want_color = True
     if os.getenv("GUI", default='0') == '1':


Test patch:
Repository: cocotb/cocotb

Issue:
Documentation building: "WARNING: duplicate label"
With ``sphinx.ext.autosectionlabel`` (in use since https://github.com/cocotb/cocotb/commit/862012b3c01f90ea1fb715c206b4eb785119f964), we got quite some new "duplicate label" warnings.

To fix some of those warnings, we could set ``autosectionlabel_prefix_document = True`` which prefixes each automatically generated section label with the name of the document it is in, followed by a colon.

A drawback is that we would now hardcode the file name of the document into the reference,
so that we are not as free with renaming documents anymore. Also, we cannot catch all those duplicates that way, e.g. in the release notes, there are multiple "new features" subsections.

The alternative is to remove ``sphinx.ext.autosectionlabel`` and set our own reference anchors.
I would prefer this.

Ping @Martoni 


Discussion:
Hi Colin,

> 
> The alternative is to remove ``sphinx.ext.autosectionlabel`` and set our own reference anchors.
> I would prefer this.

If I remember, I added this dependency just to be able to reference
«chapter». Then yes I think we can remove the dependency and add an
anchors (i'm a sphinx beginner ;).

Do you want me to do it ?

Regards,
Martoni
http//www.fabienm.eu/flf/


Hi Fabien,

Thanks for the quick reply, I can do it as part of some other changes, I just wanted to get your opinion on it. 

Resolving patch:
diff --git a/documentation/source/conf.py b/documentation/source/conf.py
--- a/documentation/source/conf.py
+++ b/documentation/source/conf.py
@@ -42,7 +42,6 @@
     'sphinx.ext.napoleon',
     'sphinx.ext.intersphinx',
     'sphinxcontrib.makedomain',
-    'sphinx.ext.autosectionlabel',
     'sphinx.ext.inheritance_diagram',
     'cairosvgconverter',
     'breathe',


Test patch:
Repository: cocotb/cocotb

Issue:
"Running tests with cocotb ... from Unknown"
In e.g. https://asciinema.org/a/316949, we can see the line
```
0.00ns INFO  cocotb  __init__.py:144  in _initialise_testbench  Running tests with cocotb v1.4.0.dev0 from Unknown
```

@themperek suggested using ``__file__`` in https://github.com/cocotb/cocotb/blob/09effc69f914820d4aa50217b9fad6ba29c4248f/cocotb/__init__.py#L139-L144 instead of ``export``ing ``COCOTB_PY_DIR`` in https://github.com/cocotb/cocotb/blob/67bf79b997b630416b1f98742fbeab09d9e90fef/cocotb/share/makefiles/Makefile.inc#L33


Discussion:
How did it end up as unknown in the first place? Is that variable just not used any more?
@eric-wieser https://github.com/cocotb/cocotb/pull/1445

Should add `export` or use`__file__` ?
Using `__file__` sounds like a good idea to me.

Hadn't noticed the lack of `export`, wasn't reading that properly.

Resolving patch:
diff --git a/cocotb/__init__.py b/cocotb/__init__.py
--- a/cocotb/__init__.py
+++ b/cocotb/__init__.py
@@ -136,12 +136,8 @@ def _initialise_testbench(root_name):
     if memcheck_port is not None:
         mem_debug(int(memcheck_port))
 
-    exec_path = os.getenv('COCOTB_PY_DIR')
-    if exec_path is None:
-        exec_path = 'Unknown'
-
     log.info("Running tests with cocotb v%s from %s" %
-             (__version__, exec_path))
+             (__version__, os.path.dirname(__file__)))
 
     # Create the base handle type
 


Test patch: