ronantakizawa/codereview-bench huggingface dataset:
Repository: ManimCommunity/manim
File: manim/utils/space_ops.py (Python)

Code before:
    Union[float, np.ndarray]
        The midpoint of the points
    """
    return center_of_mass([point1, point2])


def line_intersection(line1: Sequence[float], line2: Sequence[float]) -> np.ndarray:
    """Returns intersection point of two lines, each defined with
    a pair of vectors determining the end points.

    Parameters
    ----------
    line1
        The first line.
    line2
        The second line.

    Returns
    -------
    np.ndarray
        The intersection points of the two lines which are intersecting.

    Raises
    ------
    ValueError
        Error is produced if the two line don't intersect with each other
    """
    x_diff = (line1[0][0] - line1[1][0], line2[0][0] - line2[1][0])
    y_diff = (line1[0][1] - line1[1][1], line2[0][1] - line2[1][1])

    def det(a, b):
        return a[0] * b[1] - a[1] * b[0]

    div = det(x_diff, y_diff)
    if div == 0:
        raise ValueError("Lines do not intersect")
    d = (det(*line1), det(*line2))
    x = det(d, x_diff) / div
    y = det(d, y_diff) / div
    return np.array([x, y, 0])


def find_intersection(p0, v0, p1, v1, threshold=1e-5) -> np.ndarray:
    """
    Return the intersection of a line passing through p0 in direction v0
    with one passing through p1 in direction v1.  (Or array of intersections
    from arrays of such points/directions).
    For 3d values, it returns the point on the ray p0 + v0 * t closest to the
    ray p1 + v1 * t
    """
    p0 = np.array(p0, ndmin=2)

Review comment (suggestion):
```suggestion
        Error is produced if the two lines don't intersect with each other
```

Code after:
    Union[float, np.ndarray]
        The midpoint of the points
    """
    return center_of_mass([point1, point2])


def line_intersection(line1: Sequence[float], line2: Sequence[float]) -> np.ndarray:
    """Returns intersection point of two lines, each defined with
    a pair of vectors determining the end points.

    Parameters
    ----------
    line1
        The first line.
    line2
        The second line.

    Returns
    -------
    np.ndarray
        The intersection points of the two lines which are intersecting.

    Raises
    ------
    ValueError
        Error is produced if the two lines don't intersect with each other
    """
    x_diff = (line1[0][0] - line1[1][0], line2[0][0] - line2[1][0])
    y_diff = (line1[0][1] - line1[1][1], line2[0][1] - line2[1][1])

    def det(a, b):
        return a[0] * b[1] - a[1] * b[0]

    div = det(x_diff, y_diff)
    if div == 0:
        raise ValueError("Lines do not intersect")
    d = (det(*line1), det(*line2))
    x = det(d, x_diff) / div
    y = det(d, y_diff) / div
    return np.array([x, y, 0])


def find_intersection(p0, v0, p1, v1, threshold=1e-5) -> np.ndarray:
    """
    Return the intersection of a line passing through p0 in direction v0
    with one passing through p1 in direction v1.  (Or array of intersections
    from arrays of such points/directions).
    For 3d values, it returns the point on the ray p0 + v0 * t closest to the
    ray p1 + v1 * t
    """
    p0 = np.array(p0, ndmin=2)
Repository: ManimCommunity/manim
File: manim/cli/init/commands.py (Python)

Code before:
"""Manim's init subcommand.

Manim's init subcommand is accessed in the command-line interface via ``manim
init``. Here you can specify options, subcommands, and subgroups for the init
group.

"""
from pathlib import Path

import click

from ...constants import CONTEXT_SETTINGS, EPILOG
from ...utils.file_ops import copy_template_files


@click.command(
    context_settings=CONTEXT_SETTINGS,
    no_args_is_help=False,
    epilog=EPILOG,
    help="Quickly setup a project",
)
def init():
    """The init subcommand is a quick and easy way to initialize a project. It copies files from templates directory and pastes them in the current working dir."""
    cfg = Path("manim.cfg")
    if cfg.exists():
        raise FileExistsError(f"\t{cfg} exists\n")
    else:
        copy_template_files()


Review comment (suggestion):
Nitpick. I'm pretty sure the default for this is false so this is not needed.
```suggestion
```

Code after:
"""Manim's init subcommand.

Manim's init subcommand is accessed in the command-line interface via ``manim
init``. Here you can specify options, subcommands, and subgroups for the init
group.

"""
from pathlib import Path

import click

from ...constants import CONTEXT_SETTINGS, EPILOG
from ...utils.file_ops import copy_template_files


@click.command(
    context_settings=CONTEXT_SETTINGS,
    epilog=EPILOG,
)
def init():
    """Sets up a project in current working directory with default settings.

    It copies files from templates directory and pastes them in the current working dir.

    The new project is set up with default settings.
    """
    cfg = Path("manim.cfg")
    if cfg.exists():
        raise FileExistsError(f"\t{cfg} exists\n")
    else:
        copy_template_files()
Repository: ManimCommunity/manim
File: manim/cli/new/group.py (Python)

Code before:
import configparser
from pathlib import Path

import click

from ... import console
from ...constants import CONTEXT_SETTINGS, EPILOG, QUALITIES
from ...utils.file_ops import (
    add_import_statement,
    copy_template_files,
    get_template_names,
    get_template_path,
)

CFG_DEFAULTS = {
    "frame_rate": 30,
    "background_color": "BLACK",
    "background_opacity": 1,
    "scene_names": "Default",
    "resolution": (854, 480),
}


# select_resolution() called inside project command
def select_resolution():
    """Prompts input of type click.Choice from user. Presents options from QUALITIES constant.

    Returns
    -------
        :class:`tuple`
            Tuple containing height and width.
    """
    resolution_options = []
    for quality in QUALITIES.items():
        resolution_options.append(
            (quality[1]["pixel_height"], quality[1]["pixel_width"])
        )
    resolution_options.pop()
    choice = click.prompt(
        "\nSelect resolution:\n",
        type=click.Choice([f"{i[0]}p" for i in resolution_options]),
        show_default=False,
        default="480p",
    )
    return [res for res in resolution_options if f"{res[0]}p" == choice][0]


def update_cfg(cfg_dict, project_cfg_path):
    """Updates the manim.cfg file after reading it from the project_cfg_path.

Review comment (suggestion):
We can figure this out ourselves via search if we're curious
```suggestion
```

Code after:
import configparser
from pathlib import Path

import click

from ... import console
from ...constants import CONTEXT_SETTINGS, EPILOG, QUALITIES
from ...utils.file_ops import (
    add_import_statement,
    copy_template_files,
    get_template_names,
    get_template_path,
)

CFG_DEFAULTS = {
    "frame_rate": 30,
    "background_color": "BLACK",
    "background_opacity": 1,
    "scene_names": "Default",
    "resolution": (854, 480),
}


def select_resolution():
    """Prompts input of type click.Choice from user. Presents options from QUALITIES constant.

    Returns
    -------
        :class:`tuple`
            Tuple containing height and width.
    """
    resolution_options = []
    for quality in QUALITIES.items():
        resolution_options.append(
            (quality[1]["pixel_height"], quality[1]["pixel_width"])
        )
    resolution_options.pop()
    choice = click.prompt(
        "\nSelect resolution:\n",
        type=click.Choice([f"{i[0]}p" for i in resolution_options]),
        show_default=False,
        default="480p",
    )
    return [res for res in resolution_options if f"{res[0]}p" == choice][0]


def update_cfg(cfg_dict, project_cfg_path):
    """Updates the manim.cfg file after reading it from the project_cfg_path.
Repository: ManimCommunity/manim
File: manim/cli/init/commands.py (Python)

Code before:
"""Manim's init subcommand.

Manim's init subcommand is accessed in the command-line interface via ``manim
init``. Here you can specify options, subcommands, and subgroups for the init
group.

"""
from pathlib import Path

import click

from ...constants import CONTEXT_SETTINGS, EPILOG
from ...utils.file_ops import copy_template_files


@click.command(
    context_settings=CONTEXT_SETTINGS,
    no_args_is_help=False,
    epilog=EPILOG,
    help="Sets up a project in current working directory with default settings.",
)
def init():
    """The init subcommand is a quick and easy way to initialize a project. It copies files from templates directory and pastes them in the current working dir."""
    cfg = Path("manim.cfg")
    if cfg.exists():
        raise FileExistsError(f"\t{cfg} exists\n")
    else:
        copy_template_files()


Review comment (suggestion):
Using this `help` option overwrites the content of the docstring down below. You should prefer the docstring down below so that you can be more descriptive in the help message.

Code after:
"""Manim's init subcommand.

Manim's init subcommand is accessed in the command-line interface via ``manim
init``. Here you can specify options, subcommands, and subgroups for the init
group.

"""
from pathlib import Path

import click

from ...constants import CONTEXT_SETTINGS, EPILOG
from ...utils.file_ops import copy_template_files


@click.command(
    context_settings=CONTEXT_SETTINGS,
    epilog=EPILOG,
)
def init():
    """Sets up a project in current working directory with default settings.

    It copies files from templates directory and pastes them in the current working dir.

    The new project is set up with default settings.
    """
    cfg = Path("manim.cfg")
    if cfg.exists():
        raise FileExistsError(f"\t{cfg} exists\n")
    else:
        copy_template_files()
Repository: ManimCommunity/manim
File: manim/cli/init/commands.py (Python)

Code before:
"""Manim's init subcommand.

Manim's init subcommand is accessed in the command-line interface via ``manim
init``. Here you can specify options, subcommands, and subgroups for the init
group.

"""
from pathlib import Path

import click

from ...constants import CONTEXT_SETTINGS, EPILOG
from ...utils.file_ops import copy_template_files


@click.command(
    context_settings=CONTEXT_SETTINGS,
    epilog=EPILOG,
)
def init():
    """Sets up a project in currenct working directory.

    It copies files from templates directory and pastes them in the current working dir.

    The new project is set up with default settings.
    """
    cfg = Path("manim.cfg")
    if cfg.exists():
        raise FileExistsError(f"\t{cfg} exists\n")
    else:
        copy_template_files()


Review comment (suggestion):
```suggestion
    """Sets up a project in current working directory.
```

Code after:
"""Manim's init subcommand.

Manim's init subcommand is accessed in the command-line interface via ``manim
init``. Here you can specify options, subcommands, and subgroups for the init
group.

"""
from pathlib import Path

import click

from ...constants import CONTEXT_SETTINGS, EPILOG
from ...utils.file_ops import copy_template_files


@click.command(
    context_settings=CONTEXT_SETTINGS,
    epilog=EPILOG,
)
def init():
    """Sets up a project in current working directory with default settings.

    It copies files from templates directory and pastes them in the current working dir.

    The new project is set up with default settings.
    """
    cfg = Path("manim.cfg")
    if cfg.exists():
        raise FileExistsError(f"\t{cfg} exists\n")
    else:
        copy_template_files()
Repository: ManimCommunity/manim
File: manim/cli/init/commands.py (Python)

Code before:
"""Manim's init subcommand.

Manim's init subcommand is accessed in the command-line interface via ``manim
init``. Here you can specify options, subcommands, and subgroups for the init
group.

"""
from pathlib import Path

import click

from ...constants import CONTEXT_SETTINGS, EPILOG
from ...utils.file_ops import copy_template_files


@click.command(
    context_settings=CONTEXT_SETTINGS,
    epilog=EPILOG,
)
def init():
    """Sets up a project in current working directory.

    It copies files from templates directory and pastes them in the current working dir.

    The new project is set up with default settings.
    """
    cfg = Path("manim.cfg")
    if cfg.exists():
        raise FileExistsError(f"\t{cfg} exists\n")
    else:
        copy_template_files()


Review comment (suggestion):
Since this also appears to be the help string for this command, maybe it'd be better to specify that the project is created with default settings?
```suggestion
    """Sets up a project in current working directory with default settings.
```

another option might be to explicitly add a `help` argument to the decorator (like with `new`)

Code after:
"""Manim's init subcommand.

Manim's init subcommand is accessed in the command-line interface via ``manim
init``. Here you can specify options, subcommands, and subgroups for the init
group.

"""
from pathlib import Path

import click

from ...constants import CONTEXT_SETTINGS, EPILOG
from ...utils.file_ops import copy_template_files


@click.command(
    context_settings=CONTEXT_SETTINGS,
    epilog=EPILOG,
)
def init():
    """Sets up a project in current working directory with default settings.

    It copies files from templates directory and pastes them in the current working dir.

    The new project is set up with default settings.
    """
    cfg = Path("manim.cfg")
    if cfg.exists():
        raise FileExistsError(f"\t{cfg} exists\n")
    else:
        copy_template_files()
Repository: ManimCommunity/manim
File: manim/mobject/mobject.py (Python)

Code before:
    from ..animation.animation import Animation


class Mobject(Container):
    """Mathematical Object: base class for objects that can be displayed on screen.

    There is a compatibility layer that allows for
    getting and setting generic attributes with ``get_*``
    and ``set_*`` methods. See :meth:`set` for more details.

    Attributes
    ----------
    submobjects : List[:class:`Mobject`]
        The contained objects.
    points : :class:`numpy.ndarray`
        The points of the objects.

        .. seealso::

            :class:`~.VMobject`

    """

    animation_overrides: Dict[
        Type["Animation"], Callable[["Mobject"], "Animation"]
    ] = {}

    def __init_subclass__(cls):
        cls.animation_overrides = {}
        cls._add_intrinsic_animation_overrides()

    def __init__(self, color=WHITE, name=None, dim=3, target=None, z_index=0, **kwargs):
        self.color = Color(color)
        self.name = self.__class__.__name__ if name is None else name
        self.dim = dim
        self.target = target
        self.z_index = z_index
        self.point_hash = None
        self.submobjects = []
        self.updaters = []
        self.updating_suspended = False
        self.reset_points()
        self.generate_points()
        self.init_colors()

        # OpenGL data.
        self.data = {}
        self.depth_test = False
        self.is_fixed_in_frame = False
        self.gloss = 0.0
        self.shadow = 0.0

Review comment (suggestion):
Don't think this should be here now that classes store their own overrides.
```suggestion
```

Code after:
    from ..animation.animation import Animation


class Mobject(Container):
    """Mathematical Object: base class for objects that can be displayed on screen.

    There is a compatibility layer that allows for
    getting and setting generic attributes with ``get_*``
    and ``set_*`` methods. See :meth:`set` for more details.

    Attributes
    ----------
    submobjects : List[:class:`Mobject`]
        The contained objects.
    points : :class:`numpy.ndarray`
        The points of the objects.

        .. seealso::

            :class:`~.VMobject`

    """

    animation_overrides = {}

    @classmethod
    def __init_subclass__(cls, **kwargs):
        super().__init_subclass__(**kwargs)

        cls.animation_overrides: Dict[
            Type["Animation"], Callable[["Mobject"], "Animation"]
        ] = {}
        cls._add_intrinsic_animation_overrides()

    def __init__(self, color=WHITE, name=None, dim=3, target=None, z_index=0, **kwargs):
        self.color = Color(color)
        self.name = self.__class__.__name__ if name is None else name
        self.dim = dim
        self.target = target
        self.z_index = z_index
        self.point_hash = None
        self.submobjects = []
        self.updaters = []
        self.updating_suspended = False
        self.reset_points()
        self.generate_points()
        self.init_colors()

        # OpenGL data.
        self.data = {}
        self.depth_test = False
Repository: ManimCommunity/manim
File: manim/animation/animation.py (Python)

Code before:
        self.duration: float = run_time
        self.stop_condition = stop_condition
        self.is_static_wait: bool = False
        super().__init__(None, run_time=run_time, **kwargs)
        # quick fix to work in opengl setting:
        self.mobject.shader_wrapper_list = []

    def begin(self) -> None:
        pass

    def finish(self) -> None:
        pass

    def clean_up_from_scene(self, scene: "Scene") -> None:
        pass

    def update_mobjects(self, dt: float) -> None:
        pass

    def interpolate(self, alpha: float) -> None:
        pass


def override_animation(
    animation_class: Type["Animation"],
) -> Callable[[Callable], Callable]:
    """Decorator used to mark methods as overrides for specific :class:`~.Animation` types.

    Should only be used to decorate methods of classes derived from :class:`~.Mobject`.
    ``Animation`` overrides get inherited to subclasses of the ``Mobject`` who defined
    them. They don't override subclasses of the ``Animation`` they override.

    Parameters
    ----------
    animation_class
        The animation to be overridden.

    Returns
    -------
    Callable[[Callable], Callable]
        The actual decorator. This marks the method as overriding an animation.

    Examples
    --------

    .. manim:: OverrideAnimationExample

        class MySquare(Square):
            @override_animation(FadeIn)
            def _fade_in_override(self, **kwargs):
                return Create(self, **kwargs)

Review comment (suggestion):
```suggestion

    See Also
    --------
    :meth:`~.Mobject.add_animation_override`

```

Code after:

    def begin(self) -> None:
        pass

    def finish(self) -> None:
        pass

    def clean_up_from_scene(self, scene: "Scene") -> None:
        pass

    def update_mobjects(self, dt: float) -> None:
        pass

    def interpolate(self, alpha: float) -> None:
        pass


def override_animation(
    animation_class: Type["Animation"],
) -> Callable[[Callable], Callable]:
    """Decorator used to mark methods as overrides for specific :class:`~.Animation` types.

    Should only be used to decorate methods of classes derived from :class:`~.Mobject`.
    ``Animation`` overrides get inherited to subclasses of the ``Mobject`` who defined
    them. They don't override subclasses of the ``Animation`` they override.

    See Also
    --------
    :meth:`~.Mobject.add_animation_override`

    Parameters
    ----------
    animation_class
        The animation to be overridden.

    Returns
    -------
    Callable[[Callable], Callable]
        The actual decorator. This marks the method as overriding an animation.

    Examples
    --------

    .. manim:: OverrideAnimationExample

        class MySquare(Square):
            @override_animation(FadeIn)
            def _fade_in_override(self, **kwargs):
                return Create(self, **kwargs)

        class OverrideAnimationExample(Scene):
Repository: ManimCommunity/manim
File: manim/animation/animation.py (Python)

Code before:
        super().__init__(None, run_time=run_time, **kwargs)
        # quick fix to work in opengl setting:
        self.mobject.shader_wrapper_list = []

    def begin(self) -> None:
        pass

    def finish(self) -> None:
        pass

    def clean_up_from_scene(self, scene: "Scene") -> None:
        pass

    def update_mobjects(self, dt: float) -> None:
        pass

    def interpolate(self, alpha: float) -> None:
        pass


def override_animation(
    animation_class: Type["Animation"],
) -> Callable[[Callable], Callable]:
    """Decorator used to mark methods as overrides for specific :class:`~.Animation` types.

    Should only be used to decorate methods of classes derived from :class:`~.Mobject`.
    ``Animation`` overrides get inherited to subclasses of the ``Mobject`` who defined
    them. They don't override subclasses of the ``Animation`` they override.

    See Also
    --------
    :meth:`~.Mobject.add_animation_override`

    Parameters
    ----------
    animation_class
        The animation to be overridden.

    Returns
    -------
    Callable[[Callable], Callable]
        The actual decorator. This marks the method as overriding an animation.

    Examples
    --------

    .. manim:: OverrideAnimationExample

        class MySquare(Square):
            @override_animation(FadeIn)
            def _fade_in_override(self, **kwargs):

Review comment (suggestion):
This is my fault
```suggestion
    :meth:`.Mobject.add_animation_override`
```

Code after:

    def finish(self) -> None:
        pass

    def clean_up_from_scene(self, scene: "Scene") -> None:
        pass

    def update_mobjects(self, dt: float) -> None:
        pass

    def interpolate(self, alpha: float) -> None:
        pass


def override_animation(
    animation_class: Type["Animation"],
) -> Callable[[Callable], Callable]:
    """Decorator used to mark methods as overrides for specific :class:`~.Animation` types.

    Should only be used to decorate methods of classes derived from :class:`~.Mobject`.
    ``Animation`` overrides get inherited to subclasses of the ``Mobject`` who defined
    them. They don't override subclasses of the ``Animation`` they override.

    See Also
    --------
    :meth:`~.Mobject.add_animation_override`

    Parameters
    ----------
    animation_class
        The animation to be overridden.

    Returns
    -------
    Callable[[Callable], Callable]
        The actual decorator. This marks the method as overriding an animation.

    Examples
    --------

    .. manim:: OverrideAnimationExample

        class MySquare(Square):
            @override_animation(FadeIn)
            def _fade_in_override(self, **kwargs):
                return Create(self, **kwargs)

        class OverrideAnimationExample(Scene):
            def construct(self):
                self.play(FadeIn(MySquare()))