ronantakizawa/codereview-bench huggingface dataset:
Repository: PixiEditor/PixiEditor
File: src/PixiEditor/Exceptions/RecoverableException.cs (C#)

Code before:
﻿using System.Runtime.Serialization;

namespace PixiEditor.Exceptions;

public class RecoverableException : Exception
{
    public RecoverableException() { }

    public RecoverableException(string message) : base(message) { }

    public RecoverableException(string message, Exception innerException) : base(message, innerException) { }

    protected RecoverableException(SerializationInfo info, StreamingContext context) : base(info, context) { }
}


Review comment (suggestion):
Maybe it would be good to add localization key to this, so exception can be in english, but notice dialog would use Exception.LocalizedKey or sth

Code after:
﻿using System.Runtime.Serialization;
using PixiEditor.Localization;

namespace PixiEditor.Exceptions;

public class RecoverableException : Exception
{
    public LocalizedString DisplayMessage { get; set; }

    public RecoverableException() 
    {
        DisplayMessage = "INTERNAL_ERROR";
    }

    public RecoverableException(LocalizedString displayMessage) 
    {
        DisplayMessage = displayMessage;
    }

    public RecoverableException(LocalizedString displayMessage, Exception innerException) : base(null, innerException) 
    {
        DisplayMessage = displayMessage;
    }

    public RecoverableException(LocalizedString displayMessage, string exceptionMessage) : base(exceptionMessage)
    {
        DisplayMessage = displayMessage;
    }

    public RecoverableException(LocalizedString displayMessage, string exceptionMessage, Exception innerException) : base(exceptionMessage, innerException)
    {
Repository: PixiEditor/PixiEditor
File: src/PixiEditor/ViewModels/Document/Nodes/Effects/PosterizationNodeViewModel.cs (C#)

Code before:
﻿using PixiEditor.ChangeableDocument.Changeables.Graph.Nodes.Effects;
using PixiEditor.ViewModels.Nodes;

namespace PixiEditor.ViewModels.Document.Nodes.Effects;

[NodeViewModel("POSTERIZATION_NODE", "EFFECTS", PixiPerfectIcons.ColorPalette)]
internal class PosterizationNodeViewModel : NodeViewModel<PosterizationNode>
{
    
}



Review comment (suggestion):
ColorPalette icon is already used in `Color` node. We are using lucide icons https://lucide.dev/icons/

To add an icon, open icomoon.app, drag [defs.svg](https://github.com/PixiEditor/PixiEditor/blob/master/src/PixiEditor.UI.Common/Fonts/defs.svg) and add your selected icon (you may need to flatten it in some app like Figma)

Give it a name in export, download the font and replace ttf and svg, then run `gen-icons.py` 

Code after:
﻿using PixiEditor.ChangeableDocument.Changeables.Graph.Nodes.Effects;
using PixiEditor.ViewModels.Nodes;

namespace PixiEditor.ViewModels.Document.Nodes.Effects;

[NodeViewModel("POSTERIZATION_NODE", "EFFECTS", PixiPerfectIcons.Swatches)]
internal class PosterizationNodeViewModel : NodeViewModel<PosterizationNode>
{
    
}
Repository: Textualize/rich
File: rich/_emoji_replace.py (Python)

Code before:
from typing import Callable, Match

import re

from ._emoji_codes import EMOJI


_EmojiSub = Callable[[Callable[[Match[str]], str], str], str]


def _emoji_replace(
    text: str, _emoji_sub: _EmojiSub = re.compile(r"(:(\S*?):)").sub
) -> str:
    """Replace emoji code in text."""
    get_emoji = EMOJI.get

    def do_replace(match: Match[str]) -> str:
        """Called by re.sub to do the replacement."""
        emoji_code, emoji_name = match.groups()
        return get_emoji(emoji_name.lower(), emoji_code)

    return _emoji_sub(do_replace, text)


Review comment (suggestion):
This was hard to parse in my head, but I double checked it and it's entirely correct. Bravo.

The thing is that readability has been thrown out for the sake of correctness, which I'm no fan of. Could we break this up a bit to make it more readable? Something along these lines:

```python
_ReStringMatch = Match[str]  # regex match object
_ReSubCallable = Callable[[_ReStringMatch], str] # Callable invoked by re.sub
_EmojiSubMethod = Callable[_ReSubCallable, str]. # Sub method of a compiled re
```

Code after:
from typing import Callable, Match

import re

from ._emoji_codes import EMOJI


_ReStringMatch = Match[str]  # regex match object
_ReSubCallable = Callable[[_ReStringMatch], str]  # Callable invoked by re.sub
_EmojiSubMethod = Callable[[_ReSubCallable, str], str]  # Sub method of a compiled re


def _emoji_replace(
    text: str, _emoji_sub: _EmojiSubMethod = re.compile(r"(:(\S*?):)").sub
) -> str:
    """Replace emoji code in text."""
    get_emoji = EMOJI.get

    def do_replace(match: Match[str]) -> str:
        """Called by re.sub to do the replacement."""
        emoji_code, emoji_name = match.groups()
        return get_emoji(emoji_name.lower(), emoji_code)

    return _emoji_sub(do_replace, text)
Repository: Textualize/rich
File: rich/diagnose.py (Python)

Code before:

def report() -> None:  # pragma: no cover
    """Print a report to the terminal with debugging information"""
    console = Console()
    inspect(console)
    features = get_windows_console_features()
    inspect(features)

    if console.is_jupyter:
        jpy_parent_pid = os.getenv("JPY_PARENT_PID")
        vs_code_verbose = os.getenv("VSCODE_VERBOSE_LOGGING")
        console.print(
            Panel(
                title="Jupyter Environment Hints",
                renderable=Text(
                    f"JPY_PARENT_PID = {jpy_parent_pid}\n"
                    f"VSCODE_VERBOSE_LOGGING = {vs_code_verbose}"
                ),
            ),
        )

    console.print(f'platform="{platform.system()}"')


if __name__ == "__main__":  # pragma: no cover
    console = Console()
    inspect(console)


Review comment (suggestion):
Maybe also in invoke the report from the ``__main__`` block so that `python -m rich.diagnose` give the same info.

Code after:

def report() -> None:  # pragma: no cover
    """Print a report to the terminal with debugging information"""
    console = Console()
    inspect(console)
    features = get_windows_console_features()
    inspect(features)

    env_names = (
        "TERM",
        "COLORTERM",
        "CLICOLOR",
        "NO_COLOR",
        "TERM_PROGRAM",
        "COLUMNS",
        "LINES",
        "JPY_PARENT_PID",
        "VSCODE_VERBOSE_LOGGING",
    )
    env = {name: os.getenv(name) for name in env_names}
    console.print(Panel.fit((Pretty(env)), title="[b]Environment Variables"))

    console.print(f'platform="{platform.system()}"')


if __name__ == "__main__":  # pragma: no cover
    report()
Repository: Textualize/rich
File: rich/diagnose.py (Python)

Code before:
import os
import platform

from rich import inspect
from rich.console import Console, get_windows_console_features
from rich.panel import Panel
from rich.text import Text


def report() -> None:  # pragma: no cover
    """Print a report to the terminal with debugging information"""
    console = Console()
    inspect(console)
    features = get_windows_console_features()
    inspect(features)

    if console.is_jupyter:
        jpy_parent_pid = os.getenv("JPY_PARENT_PID")
        vs_code_verbose = os.getenv("VSCODE_VERBOSE_LOGGING")
        console.print(
            Panel(
                title="Jupyter Environment Hints",
                renderable=Text(
                    f"JPY_PARENT_PID = {jpy_parent_pid}\n"
                    f"VSCODE_VERBOSE_LOGGING = {vs_code_verbose}"
                ),
            ),
        )

    console.print(f'platform="{platform.system()}"')


if __name__ == "__main__":  # pragma: no cover
    console = Console()
    inspect(console)


Review comment (suggestion):
Can you add `panel.fit` to remove superfluous characters.

Code after:
import os
import platform

from rich import inspect
from rich.console import Console, get_windows_console_features
from rich.panel import Panel
from rich.pretty import Pretty


def report() -> None:  # pragma: no cover
    """Print a report to the terminal with debugging information"""
    console = Console()
    inspect(console)
    features = get_windows_console_features()
    inspect(features)

    env_names = (
        "TERM",
        "COLORTERM",
        "CLICOLOR",
        "NO_COLOR",
        "TERM_PROGRAM",
        "COLUMNS",
        "LINES",
        "JPY_PARENT_PID",
        "VSCODE_VERBOSE_LOGGING",
    )
    env = {name: os.getenv(name) for name in env_names}
    console.print(Panel.fit((Pretty(env)), title="[b]Environment Variables"))

    console.print(f'platform="{platform.system()}"')


if __name__ == "__main__":  # pragma: no cover
    report()
Repository: Textualize/rich
File: rich/markdown.py (Python)

Code before:
        dest="page",
        action="store_true",
        help="use pager to scroll output",
    )
    args = parser.parse_args()

    from rich.console import Console

    if args.path == "-":
        markdown_body = sys.stdin.read()
    else:
        with open(args.path, "rt", encoding="utf-8") as markdown_file:
            markdown_body = markdown_file.read()
    markdown = Markdown(
        markdown_body,
        justify="full" if args.justify else "left",
        code_theme=args.code_theme,
        hyperlinks=args.hyperlinks,
        inline_code_lexer=args.inline_code_lexer,
    )
    if args.page:
        import pydoc
        import io

        console = Console(
            file=io.StringIO(), force_terminal=args.force_color, width=args.width
        )
        console.print(markdown)
        pydoc.pager(console.file.getvalue())  # type: ignore

    else:
        console = Console(force_terminal=args.force_color, width=args.width)
        console.print(markdown)


Review comment (suggestion):
`Console` hides the exact type of `file=`. Instead of making it Generic, the original object can be used here, which mypy does know the exact type of.

Code after:
        dest="page",
        action="store_true",
        help="use pager to scroll output",
    )
    args = parser.parse_args()

    from rich.console import Console

    if args.path == "-":
        markdown_body = sys.stdin.read()
    else:
        with open(args.path, "rt", encoding="utf-8") as markdown_file:
            markdown_body = markdown_file.read()
    markdown = Markdown(
        markdown_body,
        justify="full" if args.justify else "left",
        code_theme=args.code_theme,
        hyperlinks=args.hyperlinks,
        inline_code_lexer=args.inline_code_lexer,
    )
    if args.page:
        import pydoc
        import io

        fileio = io.StringIO()
        console = Console(
            file=fileio, force_terminal=args.force_color, width=args.width
        )
        console.print(markdown)
        pydoc.pager(fileio.getvalue())

    else:
        console = Console(force_terminal=args.force_color, width=args.width)
        console.print(markdown)
Repository: Textualize/rich
File: rich/progress.py (Python)

Code before:
    progress_renderables = [
        "Text may be printed while the progress bars are rendering.",
        Panel("In fact, [i]any[/i] renderable will work"),
        "Such as [magenta]tables[/]...",
        table,
        "Pretty printed structures...",
        {"type": "example", "text": "Pretty printed"},
        "Syntax...",
        syntax,
        Rule("Give it a try!"),
    ]

    from itertools import cycle

    examples = cycle(progress_renderables)

    console = Console(record=True)

    with Progress(
        SpinnerColumn(),
        *Progress.get_default_columns(),
        TimeElapsedColumn(),
        console=console,
        transient=False,
    ) as progress:

        # task1 = progress.add_task("[red]Downloading", total=1000)
        # task2 = progress.add_task("[green]Processing", total=1000)
        task3 = progress.add_task("[yellow]A progress with a `None` total", total=None)

        while not progress.finished:
            # progress.update(task1, advance=0.5)
            # progress.update(task2, advance=0.3)
            time.sleep(1)
            # if random.randint(0, 100) < 1:
            #     progress.log(next(examples))


Review comment (suggestion):
I'm assuming the code below was for testing. Can you restore this so that `progress -m rich.progress` show a demonstration of multiple progress bars.

Code after:
    table.add_row("1", "2", "3")

    progress_renderables = [
        "Text may be printed while the progress bars are rendering.",
        Panel("In fact, [i]any[/i] renderable will work"),
        "Such as [magenta]tables[/]...",
        table,
        "Pretty printed structures...",
        {"type": "example", "text": "Pretty printed"},
        "Syntax...",
        syntax,
        Rule("Give it a try!"),
    ]

    from itertools import cycle

    examples = cycle(progress_renderables)

    console = Console(record=True)

    with Progress(
        SpinnerColumn(),
        *Progress.get_default_columns(),
        TimeElapsedColumn(),
        console=console,
        transient=False,
    ) as progress:

        task1 = progress.add_task("[red]Downloading", total=1000)
        task2 = progress.add_task("[green]Processing", total=1000)
        task3 = progress.add_task("[yellow]Thinking", total=None)

        while not progress.finished:
            progress.update(task1, advance=0.5)
            progress.update(task2, advance=0.3)
            time.sleep(0.01)
            if random.randint(0, 100) < 1:
                progress.log(next(examples))
Repository: Textualize/rich
File: rich/__init__.py (Python)

Code before:
"""Rich text and beautiful formatting in the terminal."""

import os
from typing import IO, TYPE_CHECKING, Any, Callable, Optional, Union

from ._extension import load_ipython_extension  # noqa: F401

__all__ = ["get_console", "reconfigure", "print", "inspect"]

if TYPE_CHECKING:
    from .console import Console

# Global console used by alternative print
_console_default_singleton: Optional["Console"] = None

_IMPORT_CWD = os.path.abspath(os.getcwd())


def get_console() -> "Console":
    """Get a global :class:`~rich.console.Console` instance. This function is used when Rich requires a Console,
    and hasn't been explicitly given one.

    Returns:
        Console: A console instance.
    """
    global _console_default_singleton
    if _console_default_singleton is None:
        from .console import Console

        _console_default_singleton = Console()

    return _console_default_singleton


def reconfigure(*args: Any, **kwargs: Any) -> None:
    """Reconfigures the global console by replacing it with another.

    Args:
        console (Console): Replacement console instance.

Review comment (suggestion):
I stumbled across that Python behaviour I was not aware of: it seems that in this `__init__.py` file the fact that we have a variable named `_console` conflicts with a `_console.py` module if there is one.
So `global _console` will actually refer to the `_console` **module**, rather than this variable! :open_mouth: 

Renaming it avoids the problem.

Screenshot of the issue:
(not caused by the fact that the local variable is also named `_console` , but by the fact that `get_console()` will return the `_console.py` module instead of the global `_console` variable)
![Screenshot from 2022-04-05 15-37-56](https://user-images.githubusercontent.com/722388/161779207-195099be-4e87-4441-98bd-ec77910c99d5.png)


Code after:
"""Rich text and beautiful formatting in the terminal."""

import os
from typing import IO, TYPE_CHECKING, Any, Callable, Optional, Union

from ._extension import load_ipython_extension  # noqa: F401

__all__ = ["get_console", "reconfigure", "print", "inspect"]

if TYPE_CHECKING:
    from .console import Console

# Global console used by alternative print
_console: Optional["Console"] = None

_IMPORT_CWD = os.path.abspath(os.getcwd())


def get_console() -> "Console":
    """Get a global :class:`~rich.console.Console` instance. This function is used when Rich requires a Console,
    and hasn't been explicitly given one.

    Returns:
        Console: A console instance.
    """
    global _console
    if _console is None:
        from .console import Console

        _console = Console()

    return _console


def reconfigure(*args: Any, **kwargs: Any) -> None:
    """Reconfigures the global console by replacing it with another.

    Args:
        console (Console): Replacement console instance.
Repository: Textualize/rich
File: rich/control.py (Python)

Code before:

    def __str__(self) -> str:
        return self.segment.text

    def __rich_console__(
        self, console: "Console", options: "ConsoleOptions"
    ) -> "RenderResult":
        if self.segment.text:
            yield self.segment


def strip_control_codes(
    text: str, _translate_table: Dict[int, None] = _CONTROL_STRIP_TRANSLATE
) -> str:
    """Remove control codes from text.

    Args:
        text (str): A string possibly contain control codes.

    Returns:
        str: String with control codes removed.
    """
    return text.translate(_translate_table)


def make_control_codes_readable(
    text: str,
    _translate_table: Dict[int, str] = _CONTROL_MAKE_READABLE_TRANSLATE,
) -> str:
    """Replace control codes with their "readable" equivalent in the given text.
    (e.g. "\b" becomes "\\b")

    Args:
        text (str): A string possibly contain control codes.

    Returns:
        str: String with control codes replaced with a readable version.
    """
    return text.translate(_translate_table)


if __name__ == "__main__":  # pragma: no cover
    from rich.console import Console

    console = Console()
    console.print("Look at the title of your terminal window ^")
    # console.print(Control((ControlType.SET_WINDOW_TITLE, "Hello, world!")))
    for i in range(10):
        console.set_window_title("🚀 Loading" + "." * i)
        time.sleep(0.5)


Review comment (security):
I'd prefer `escape_control_code`. Would you mind changing the terminology from "make readable" elsewhere?

Code after:

    def __str__(self) -> str:
        return self.segment.text

    def __rich_console__(
        self, console: "Console", options: "ConsoleOptions"
    ) -> "RenderResult":
        if self.segment.text:
            yield self.segment


def strip_control_codes(
    text: str, _translate_table: Dict[int, None] = _CONTROL_STRIP_TRANSLATE
) -> str:
    """Remove control codes from text.

    Args:
        text (str): A string possibly contain control codes.

    Returns:
        str: String with control codes removed.
    """
    return text.translate(_translate_table)


def escape_control_codes(
    text: str,
    _translate_table: Dict[int, str] = CONTROL_ESCAPE,
) -> str:
    """Replace control codes with their "escaped" equivalent in the given text.
    (e.g. "\b" becomes "\\b")

    Args:
        text (str): A string possibly containing control codes.

    Returns:
        str: String with control codes replaced with their escaped version.
    """
    return text.translate(_translate_table)


if __name__ == "__main__":  # pragma: no cover
    from rich.console import Console

    console = Console()
    console.print("Look at the title of your terminal window ^")
    # console.print(Control((ControlType.SET_WINDOW_TITLE, "Hello, world!")))
    for i in range(10):
        console.set_window_title("🚀 Loading" + "." * i)
        time.sleep(0.5)
Repository: Textualize/rich
File: tests/test_syntax.py (Python)

Code before:
import io
import os
import sys
import tempfile

import pytest
from pygments.lexers import PythonLexer

from rich.panel import Panel
from rich.style import Style
from rich.syntax import (
    ANSISyntaxTheme,
    Color,
    Console,
    PygmentsSyntaxTheme,
    Syntax,
    SyntaxHighlightRange,
    SyntaxPosition,
)

from .render import render

CODE = '''\
def loop_first_last(values: Iterable[T]) -> Iterable[Tuple[bool, bool, T]]:
    """Iterate and generate a tuple with a flag for first and last value."""
    iter_values = iter(values)

Review comment (bug):
I've never used Python 2, but if I'm not wrong this type of pragma is only for Python 2?

Code after:
import io
import os
import sys
import tempfile

import pytest
from pygments.lexers import PythonLexer

from rich.panel import Panel
from rich.style import Style
from rich.syntax import (
    ANSISyntaxTheme,
    Color,
    Console,
    PygmentsSyntaxTheme,
    Syntax,
    _SyntaxHighlightRange,
)

from .render import render

CODE = '''\
def loop_first_last(values: Iterable[T]) -> Iterable[Tuple[bool, bool, T]]:
    """Iterate and generate a tuple with a flag for first and last value."""
    iter_values = iter(values)
    try:
Repository: Textualize/rich
File: rich/jupyter.py (Python)

Code before:
from typing import TYPE_CHECKING, Any, Dict, Iterable, List, Sequence

if TYPE_CHECKING:
    from rich.console import ConsoleRenderable

from . import get_console
from .segment import Segment
from .terminal_theme import DEFAULT_TERMINAL_THEME

if TYPE_CHECKING:
    from rich.console import ConsoleRenderable

JUPYTER_HTML_FORMAT = """\
<pre style="white-space:pre;overflow-x:auto;line-height:normal;font-family:Menlo,'DejaVu Sans Mono',consolas,'Courier New',monospace">{code}</pre>
"""

JUPYTER_CLASSES_TO_NOT_RENDER = {
    # Matplotlib "Artists" manage their own rendering in a Jupyter notebook, and we should not try to render them too.
    # "Typically, all [Matplotlib] visible elements in a figure are subclasses of Artist."
    "matplotlib.artist.Artist",
}


class JupyterRenderable:
    """A shim to write html to Jupyter notebook."""

    def __init__(self, html: str, text: str) -> None:
        self.html = html
        self.text = text

    def _repr_mimebundle_(
        self, include: Sequence[str], exclude: Sequence[str], **kwargs: Any
    ) -> Dict[str, str]:
        data = {"text/plain": self.text, "text/html": self.html}
        if include:
            data = {k: v for (k, v) in data.items() if k in include}
        if exclude:
            data = {k: v for (k, v) in data.items() if k not in exclude}
        return data


class JupyterMixin:

Review comment (suggestion):
AFAICT this is only used in a single context. It doesn't need to be publicly exposed so we could move it to the file where it is referenced.

Code after:
from typing import TYPE_CHECKING, Any, Dict, Iterable, List, Sequence

if TYPE_CHECKING:
    from rich.console import ConsoleRenderable

from . import get_console
from .segment import Segment
from .terminal_theme import DEFAULT_TERMINAL_THEME

if TYPE_CHECKING:
    from rich.console import ConsoleRenderable

JUPYTER_HTML_FORMAT = """\
<pre style="white-space:pre;overflow-x:auto;line-height:normal;font-family:Menlo,'DejaVu Sans Mono',consolas,'Courier New',monospace">{code}</pre>
"""


class JupyterRenderable:
    """A shim to write html to Jupyter notebook."""

    def __init__(self, html: str, text: str) -> None:
        self.html = html
        self.text = text

    def _repr_mimebundle_(
        self, include: Sequence[str], exclude: Sequence[str], **kwargs: Any
    ) -> Dict[str, str]:
        data = {"text/plain": self.text, "text/html": self.html}
        if include:
            data = {k: v for (k, v) in data.items() if k in include}
        if exclude:
            data = {k: v for (k, v) in data.items() if k not in exclude}
        return data


class JupyterMixin:
    """Add to an Rich renderable to make it render in Jupyter notebook."""

    __slots__ = ()

    def _repr_mimebundle_(
        self: "ConsoleRenderable",