ronantakizawa/codereview-bench huggingface dataset:
Repository: Textualize/textual
File: src/textual/message_pump.py (Python)

Code before:
    TypeVar,
    cast,
)
from weakref import WeakSet

from . import Logger, events, log, messages
from ._callback import invoke
from ._context import NoActiveAppError, active_app, active_message_pump
from ._context import message_hook as message_hook_context_var
from ._context import prevent_message_types_stack
from ._on import OnNoWidget
from ._time import time
from .css.match import match
from .events import Event
from .message import Message
from .reactive import Reactive, TooManyComputesError
from .signal import Signal
from .timer import Timer, TimerCallback

if TYPE_CHECKING:
    from typing_extensions import TypeAlias

    from .app import App
    from .css.model import SelectorSet

SLOW_THRESHOLD_MS = int(os.getenv('TEXTUAL_SLOW_THRESHOLD_MS', 500))

Callback: TypeAlias = "Callable[..., Any] | Callable[..., Awaitable[Any]]"


class CallbackError(Exception):
    pass


class MessagePumpClosed(Exception):
    pass


_MessagePumpMetaSub = TypeVar("_MessagePumpMetaSub", bound="_MessagePumpMeta")


class _MessagePumpMeta(type):
    """Metaclass for message pump. This exists to populate a Message inner class of a Widget with the
    parent classes' name.
    """

    def __new__(
        cls: Type[_MessagePumpMetaSub],
        name: str,
        bases: tuple[type, ...],
        class_dict: dict[str, Any],

Review comment (suggestion):
Can you put this in constants.py

Probably no need for the `_MS` suffix, as I think any time related constants should me in milliseconds.

Code after:
    TypeVar,
    cast,
)
from weakref import WeakSet

from . import Logger, events, log, messages
from ._callback import invoke
from ._context import NoActiveAppError, active_app, active_message_pump
from ._context import message_hook as message_hook_context_var
from ._context import prevent_message_types_stack
from ._on import OnNoWidget
from ._time import time
from .constants import SLOW_THRESHOLD
from .css.match import match
from .events import Event
from .message import Message
from .reactive import Reactive, TooManyComputesError
from .signal import Signal
from .timer import Timer, TimerCallback

if TYPE_CHECKING:
    from typing_extensions import TypeAlias

    from .app import App
    from .css.model import SelectorSet


Callback: TypeAlias = "Callable[..., Any] | Callable[..., Awaitable[Any]]"


class CallbackError(Exception):
    pass


class MessagePumpClosed(Exception):
    pass


_MessagePumpMetaSub = TypeVar("_MessagePumpMetaSub", bound="_MessagePumpMeta")


class _MessagePumpMeta(type):
    """Metaclass for message pump. This exists to populate a Message inner class of a Widget with the
    parent classes' name.
    """

    def __new__(
        cls: Type[_MessagePumpMetaSub],
        name: str,
        bases: tuple[type, ...],
        class_dict: dict[str, Any],
Repository: Textualize/textual
File: src/textual/walk.py (Python)

Code before:

    Returns:
        An iterable of DOMNodes, or the type specified in ``filter_type``.
    """
    from textual.dom import DOMNode

    stack: list[Iterator[DOMNode]] = [iter(root.children)]
    pop = stack.pop
    push = stack.append
    check_type = filter_type or DOMNode

    if with_root and isinstance(root, check_type):
        yield root
    while stack:
        if (node := next(stack[-1], None)) is None:
            pop()
        else:
            if isinstance(node, check_type):
                yield node
            if children := node._nodes:
                push(iter(children))


if TYPE_CHECKING:

    @overload
    def walk_breadth_first(
        root: DOMNode,
        *,
        with_root: bool = True,
    ) -> Iterable[DOMNode]: ...

    @overload
    def walk_breadth_first(
        root: WalkType,
        filter_type: type[WalkType],
        *,
        with_root: bool = True,
    ) -> Iterable[WalkType]: ...


def walk_breadth_first(
    root: DOMNode,
    filter_type: type[WalkType] | None = None,
    *,
    with_root: bool = True,
) -> Iterable[DOMNode] | Iterable[WalkType]:
    """Walk the tree breadth first (children first).

    !!! note


Review comment (suggestion):
I feel like writing 'if filter_type and isinstance(...)' here would have the same overall result and would only be a single check of a Boolean value, but would allow us to keep the single loop.

Code after:

    Returns:
        An iterable of DOMNodes, or the type specified in `filter_type`.
    """
    stack: list[Iterator[DOMNode]] = [iter(root.children)]
    pop = stack.pop
    push = stack.append

    if filter_type is None:
        if with_root:
            yield root
        while stack:
            if (node := next(stack[-1], None)) is None:
                pop()
            else:
                yield node
                if children := node._nodes:
                    push(iter(children))
    else:
        if with_root and isinstance(root, filter_type):
            yield root
        while stack:
            if (node := next(stack[-1], None)) is None:
                pop()
            else:
                if isinstance(node, filter_type):
                    yield node
                if children := node._nodes:
                    push(iter(children))


if TYPE_CHECKING:

    @overload
    def walk_breadth_first(
        root: DOMNode,
        *,
        with_root: bool = True,
    ) -> Iterable[DOMNode]: ...

    @overload
    def walk_breadth_first(
        root: WalkType,
        filter_type: type[WalkType],
        *,
        with_root: bool = True,
    ) -> Iterable[WalkType]: ...


def walk_breadth_first(
    root: DOMNode,
Repository: Textualize/textual
File: tests/test_compositor.py (Python)

Code before:
from textual.app import App, ComposeResult
from textual.containers import Container
from textual.widgets import Static


async def test_compositor_scroll_placements():
    """Regression test for https://github.com/Textualize/textual/issues/5249"""

    class ScrollApp(App):
        CSS = """
        Screen {
            overflow: scroll;
        }
        Container {
            width: 200vw;
        }
        #hello {
            width: 20;
            height: 10;
            offset: 50 10;
            background: blue;
            color: white;
        }
        """

        def compose(self) -> ComposeResult:
            with Container():
                yield Static("Hello", id="hello")

        def on_mount(self) -> None:
            self.query_one("Screen").scroll_to(20, 0, animate=False)


Review comment (suggestion):
```suggestion
    """Regression test for https://github.com/Textualize/textual/issues/5249
    The Static should remain visible.
    """
```

Code after:
from textual.app import App, ComposeResult
from textual.containers import Container
from textual.widgets import Static


async def test_compositor_scroll_placements():
    """Regression test for https://github.com/Textualize/textual/issues/5249
    The Static should remain visible.
    """

    class ScrollApp(App):
        CSS = """
        Screen {
            overflow: scroll;
        }
        Container {
            width: 200vw;
        }
        #hello {
            width: 20;
            height: 10;
            offset: 50 10;
            background: blue;
            color: white;
        }
        """

        def compose(self) -> ComposeResult:
            with Container():
                yield Static("Hello", id="hello")

        def on_mount(self) -> None:
Repository: Textualize/textual
File: src/textual/getters.py (Python)

Code before:
        else:
            self.expect_type = expect_type
        self.child_id = child_id

    @overload
    def __get__(
        self: "child_by_id[QueryType]", obj: DOMNode, obj_type: type[DOMNode]
    ) -> QueryType: ...

    @overload
    def __get__(
        self: "child_by_id[QueryType]", obj: None, obj_type: type[DOMNode]
    ) -> "child_by_id[QueryType]": ...

    def __get__(
        self: "child_by_id[QueryType]", obj: DOMNode | None, obj_type: type[DOMNode]
    ) -> QueryType | Widget | "child_by_id":
        """Get the widget matching the selector and/or type."""
        if obj is None:
            return self
        child = obj._get_dom_base()._nodes._get_by_id(self.child_id)
        if child is None:
            raise NoMatches(f"No child found with id={self.child_id!r}")
        if not isinstance(child, self.expect_type):
            raise WrongType(
                f"Child with id={id!r} is the wrong type; expected type {self.expect_type.__name__!r}, found {child}"
            )
        return child


Review comment (bug):
```suggestion
                f"Child with id={self.child_id!r} is the wrong type; expected type {self.expect_type.__name__!r}, found {child}"
```

Code after:
        else:
            self.expect_type = expect_type
        self.child_id = child_id

    @overload
    def __get__(
        self: "child_by_id[QueryType]", obj: DOMNode, obj_type: type[DOMNode]
    ) -> QueryType: ...

    @overload
    def __get__(
        self: "child_by_id[QueryType]", obj: None, obj_type: type[DOMNode]
    ) -> "child_by_id[QueryType]": ...

    def __get__(
        self: "child_by_id[QueryType]", obj: DOMNode | None, obj_type: type[DOMNode]
    ) -> QueryType | Widget | "child_by_id":
        """Get the widget matching the selector and/or type."""
        if obj is None:
            return self
        child = obj._get_dom_base()._nodes._get_by_id(self.child_id)
        if child is None:
            raise NoMatches(f"No child found with id={self.child_id!r}")
        if not isinstance(child, self.expect_type):
            raise WrongType(
                f"Child with id={self.child_id!r} is the wrong type; expected type {self.expect_type.__name__!r}, found {child}"
            )
        return child
Repository: Textualize/textual
File: src/textual/widgets/_select.py (Python)

Code before:
from __future__ import annotations

from dataclasses import dataclass
from typing import TYPE_CHECKING, Generic, Iterable, TypeVar, Union

import rich.repr
from rich.console import RenderableType
from rich.text import Text

from textual import events, on
from textual.binding import Binding
from textual.containers import Horizontal, Vertical
from textual.css.query import NoMatches
from textual.message import Message
from textual.reactive import reactive, var
from textual.timer import Timer
from textual.widgets import Static
from textual.widgets._option_list import Option, OptionList

if TYPE_CHECKING:
    from typing_extensions import TypeAlias

    from textual.app import ComposeResult


class NoSelection:
    """Used by the `Select` widget to flag the unselected state. See [`Select.BLANK`][textual.widgets.Select.BLANK]."""

    def __repr__(self) -> str:

Review comment (suggestion):
Usually you want to import `Hashable` from `collections.abc` and hide the import behind a `TYPE_CHECKING` block and quote `Hashable` inside the type variable. 

Prevents unnecessary imports and this import path was deprecated in 3.12.

https://docs.python.org/3/library/typing.html#typing.Hashable

Code after:
from __future__ import annotations

from dataclasses import dataclass
from typing import TYPE_CHECKING, Generic, Hashable, Iterable, TypeVar, Union

import rich.repr
from rich.console import RenderableType
from rich.text import Text

from textual import events, on
from textual.binding import Binding
from textual.containers import Horizontal, Vertical
from textual.css.query import NoMatches
from textual.message import Message
from textual.reactive import reactive, var
from textual.timer import Timer
from textual.widgets import Static
from textual.widgets._option_list import Option, OptionList

if TYPE_CHECKING:
    from typing_extensions import TypeAlias

    from textual.app import ComposeResult


class NoSelection:
    """Used by the `Select` widget to flag the unselected state. See [`Select.BLANK`][textual.widgets.Select.BLANK]."""

    def __repr__(self) -> str:
Repository: ai16z/eliza
File: packages/cli/src/utils/get-config.ts (TypeScript)

Code before:
    console.log('BYPASS: Using postgres URL from environment variable');
    return process.env.POSTGRES_URL;
  }

  // If we already have PGLITE_DATA_DIR set in env and not reconfiguring, use PGLite
  if (pgliteDataDir && !reconfigure) {
    logger.debug(`Using existing PGLite configuration: ${pgliteDataDir}`);

    // Ensure the directory exists
    await ensureDir(pgliteDataDir);

    return null;
  }

  // BYPASS ADDED: Default to pglite if no configuration is provided
  console.log('BYPASS: No database configuration found, defaulting to pglite');
  await setupPgLite(elizaDbDir, envFilePath);
  return null;
}

// Main config schema
/**
 * Schema definition for the raw configuration object.
 *
 * @type {z.ZodType<RawConfig>}
 */
export const rawConfigSchema = z
  .object({
    $schema: z.string().optional(),
    database: z.discriminatedUnion('type', [postgresConfigSchema, pgliteConfigSchema]),
    plugins: z.object({
      registry: z.string().url(),
      installed: z.array(z.string()),
    }),
    paths: z.object({
      knowledge: z.string(),
    }),
  })
  .strict();

/**
 * Type definition for the inferred type of the raw config schema.
 */
export type RawConfig = z.infer<typeof rawConfigSchema>;

export const configSchema = rawConfigSchema.extend({
  resolvedPaths: z.object({
    knowledge: z.string(),
  }),
});


Review comment (suggestion):
we could make some `updateEnv` re-usable config for this, used many places, I did make a `mergeEnvs` function but new task later

Code after:
  config: { endpoint: string; model: string },
  envFilePath: string
): Promise<void> {
  if (!config.endpoint || !config.model) return;

  try {
    // Read existing content first to avoid duplicates
    let content = '';
    if (existsSync(envFilePath)) {
      content = await fs.readFile(envFilePath, 'utf8');
    }

    // Remove existing Ollama lines if present
    const lines = content
      .split('\n')
      .filter(
        (line) =>
          !line.startsWith('OLLAMA_API_ENDPOINT=') &&
          !line.startsWith('OLLAMA_MODEL=') &&
          !line.startsWith('USE_OLLAMA_TEXT_MODELS=')
      );

    // Add new Ollama configuration
    lines.push(`OLLAMA_API_ENDPOINT=${config.endpoint}`);
    lines.push(`OLLAMA_MODEL=${config.model}`);
    lines.push('USE_OLLAMA_TEXT_MODELS=true');

    await fs.writeFile(envFilePath, lines.join('\n'), 'utf8');

    // Update process.env
    process.env.OLLAMA_API_ENDPOINT = config.endpoint;
    process.env.OLLAMA_MODEL = config.model;
    process.env.USE_OLLAMA_TEXT_MODELS = 'true';

    logger.success('Ollama configuration saved to configuration');
  } catch (error) {
    logger.error('Error saving Ollama configuration:', error);
    throw error;
  }
}

/**
 * Prompts the user for Ollama configuration, validates it, and stores it
 * @param envFilePath Path to the .env file
 * @returns The configured Ollama settings or null if user cancels
 */
export async function promptAndStoreOllamaConfig(
  envFilePath: string
): Promise<{ endpoint: string; model: string } | null> {
  clack.intro('🦙 Ollama Configuration');
Repository: andrewyng/aisuite
File: aimodels/providers/ollama_interface.py (Python)

Code before:
"""The interface to the Ollama API."""

from aimodels.framework import ProviderInterface, ChatCompletionResponse
from httpx import ConnectError


class OllamaInterface(ProviderInterface):
    """Implements the ProviderInterface for interacting with the Ollama API."""

    _OLLAMA_STATUS_ERROR_MESSAGE = "Ollama is likely not running. Start Ollama by running `ollama serve` on your host."

    def __init__(self, server_url="http://localhost:11434"):
        """Set up the Ollama API client with the key from the user's environment."""
        from ollama import Client

        self.ollama_client = Client(host=server_url)

    def chat_completion_create(self, messages=None, model=None, temperature=0):
        """Request chat completions from Ollama.

        Args:
        ----
            model (str): Identifies the specific provider/model to use.
            messages (list of dict): A list of message objects in chat history.
            temperature (float): The temperature to use in the completion.

        Raises:
        ------
            RuntimeError: If the Ollama server is not reachable,
                we catch the ConnectError from the underlying httpx library
                used by the Ollama client.

        Returns:
        -------
            The ChatCompletionResponse with the completion result.

        """

Review comment (suggestion):
We should make this an env with that as the default.

`os.getenv("OLLAMA_API_URL", "http://localhost:11434")` and then add this to the `.env.sample

Code after:
"""The interface to the Ollama API."""

from aimodels.framework import ProviderInterface, ChatCompletionResponse
from httpx import ConnectError
import os


class OllamaInterface(ProviderInterface):
    """Implements the ProviderInterface for interacting with the Ollama API."""

    _OLLAMA_STATUS_ERROR_MESSAGE = "Ollama is likely not running. Start Ollama by running `ollama serve` on your host."

    def __init__(
        self, server_url=os.getenv("OLLAMA_API_URL", "http://localhost:11434")
    ):
        """Set up the Ollama API client with the key from the user's environment."""
        from ollama import Client

        self.ollama_client = Client(host=server_url)

    def chat_completion_create(self, messages=None, model=None, temperature=0):
        """Request chat completions from Ollama.

        Args:
        ----
            model (str): Identifies the specific provider/model to use.
            messages (list of dict): A list of message objects in chat history.
            temperature (float): The temperature to use in the completion.

        Raises:
        ------
            RuntimeError: If the Ollama server is not reachable,
                we catch the ConnectError from the underlying httpx library
                used by the Ollama client.

        Returns:
        -------
Repository: andrewyng/aisuite
File: aimodels/providers/replicate_interface.py (Python)

Code before:
"""The interface to the Replicate API."""

import os

from ..framework.provider_interface import ProviderInterface

class ReplicateInterface(ProviderInterface):
    """Implements the ProviderInterface for interacting with Replicate's APIs."""

    def __init__(self):
        """Set up the Replicate client using the API key obtained from the user's environment."""
        from openai import OpenAI

        self.replicate_client = OpenAI(api_key=os.getenv("REPLICATE_API_KEY"), base_url="https://openai-proxy.replicate.com/v1")

    def chat_completion_create(self, messages=None, model=None, temperature=0):
        """Request chat completions from the Replicate API.

        Args:
        ----
            model (str): Identifies the specific provider/model to use.
            messages (list of dict): A list of message objects in chat history.
            temperature (float): The temperature to use in the completion.

        Returns:
        -------
            The API response with the completion result.

        """
        return self.replicate_client.chat.completions.create(
            model=model,
            messages=messages,
            temperature=temperature,
        )


Review comment (suggestion):
Can you make the url here an ENV variable and set the hardcoded value as a fallback? This will need to be added to the `.env.sample` as well. Something like

`REPLICATE_BASE_URL=""` in the .env.sampel

Then in client initialization use:

`os.getenv("REPLICATE_BASE_URL", "https://openai-proxy.replicate.com/v1")`

Code after:
"""The interface to the Replicate API."""

import os

from ..framework.provider_interface import ProviderInterface

_REPLICATE_BASE_URL = "https://openai-proxy.replicate.com/v1"


class ReplicateInterface(ProviderInterface):
    """Implements the ProviderInterface for interacting with Replicate's APIs."""

    def __init__(self):
        """Set up the Replicate client using the API key obtained from the user's environment."""
        from openai import OpenAI

        self.replicate_client = OpenAI(
            api_key=os.getenv("REPLICATE_API_KEY"),
            base_url=_REPLICATE_BASE_URL,
        )

    def chat_completion_create(self, messages=None, model=None, temperature=0):
        """Request chat completions from the Replicate API.

        Args:
        ----
            model (str): Identifies the specific provider/model to use.
            messages (list of dict): A list of message objects in chat history.
            temperature (float): The temperature to use in the completion.

        Returns:
        -------
            The API response with the completion result.

        """
        return self.replicate_client.chat.completions.create(
            model=model,
            messages=messages,
            temperature=temperature,
Repository: andrewyng/aisuite
File: aimodels/providers/together_interface.py (Python)

Code before:
"""The interface to the Groq API."""

import os

from ..framework.provider_interface import ProviderInterface

_TOGETHER_BASE_URL = "https://api.together.xyz/v1"

class TogetherInterface(ProviderInterface):
    """Implements the ProviderInterface for interacting with Together's APIs."""

    def __init__(self):
        """Set up the Together client using the API key obtained from the user's environment."""
        from openai import OpenAI

        self.together_client = OpenAI(
            api_key=os.getenv("TOGETHER_API_KEY"),
            base_url=_TOGETHER_BASE_URL,
        )
    def chat_completion_create(self, messages=None, model=None, temperature=0):
        """Request chat completions from the Together API.

        Args:
        ----
            model (str): Identifies the specific provider/model to use.
            messages (list of dict): A list of message objects in chat history.

Review comment (suggestion):
```suggestion
"""The interface to the Together API."""
```

Code after:
"""The interface to the Together API."""

import os

from ..framework.provider_interface import ProviderInterface

_TOGETHER_BASE_URL = "https://api.together.xyz/v1"


class TogetherInterface(ProviderInterface):
    """Implements the ProviderInterface for interacting with Together's APIs."""

    def __init__(self):
        """Set up the Together client using the API key obtained from the user's environment."""
        from openai import OpenAI

        self.together_client = OpenAI(
            api_key=os.getenv("TOGETHER_API_KEY"),
            base_url=_TOGETHER_BASE_URL,
        )

    def chat_completion_create(self, messages=None, model=None, temperature=0):
        """Request chat completions from the Together API.

        Args:
        ----