ronantakizawa/codereview-bench huggingface dataset:
Repository: Rapptz/discord.py
File: discord/integrations.py (Python)

Code before:
        'guild',
        '_state',
        'id',
        'type',
        'name',
        'account',
        'application_id',
    )

    def __init__(self, *, data: PartialIntegrationPayload, guild: Guild):
        self.guild: Guild = guild
        self._state: ConnectionState = guild._state
        self._from_data(data)

    def __repr__(self) -> str:
        return f"<{self.__class__.__name__} id={self.id} name={self.name!r}>"

    def _from_data(self, data: PartialIntegrationPayload) -> None:
        self.id: int = int(data['id'])
        self.type: IntegrationType = data['type']
        self.name: str = data['name']
        self.account: IntegrationAccount = IntegrationAccount(data['account'])
        application_id = data.get('application_id')
        self.application_id: Optional[int] = None
        if application_id is not None:
            self.application_id = int(application_id)


def _integration_factory(value: str) -> Tuple[Type[Integration], str]:
    if value == 'discord':
        return BotIntegration, value
    elif value in ('twitch', 'youtube'):
        return StreamIntegration, value
    else:
        return Integration, value


Review comment (suggestion):
```suggestion
        self.application_id: Optional[int] = _get_as_snowflake(data, 'application_id')
```

Code after:
        'guild',
        '_state',
        'id',
        'type',
        'name',
        'account',
        'application_id',
    )

    def __init__(self, *, data: PartialIntegrationPayload, guild: Guild):
        self.guild: Guild = guild
        self._state: ConnectionState = guild._state
        self._from_data(data)

    def __repr__(self) -> str:
        return f'<{self.__class__.__name__} id={self.id} name={self.name!r}>'

    def _from_data(self, data: PartialIntegrationPayload) -> None:
        self.id: int = int(data['id'])
        self.type: IntegrationType = data['type']
        self.name: str = data['name']
        self.account: IntegrationAccount = IntegrationAccount(data['account'])
        self.application_id: Optional[int] = _get_as_snowflake(data, 'application_id')


def _integration_factory(value: str) -> Tuple[Type[Integration], str]:
    if value == 'discord':
        return BotIntegration, value
    elif value in ('twitch', 'youtube'):
        return StreamIntegration, value
    else:
        return Integration, value
Repository: Rapptz/discord.py
File: discord/appinfo.py (Python)

Code before:
    def flags(self) -> ApplicationFlags:
        """:class:`ApplicationFlags`: The application's flags.

        .. versionadded:: 2.0
        """
        return ApplicationFlags._from_value(self._flags)


class AppInstallParams:
    """Represents the settings for custom authorization URL of an application.

    .. versionadded:: 2.0

    Attributes
    ----------
    scopes: List[:class:`str`]
        The list of `OAuth2 scopes <https://discord.com/developers/docs/topics/oauth2#shared-resources-oauth2-scopes>`_
        to add the application to a guild with.
    permissions: :class:`Permissions`
        The permissions to give to application in the guild.
    """

    __slots__ = (
        "scopes",
        "permissions",
    )

    def __init__(self, data: InstallParamsPayload) -> None:
        self.scopes: List[str] = data.get("scopes", [])
        self.permissions: Permissions = Permissions._from_value(int(data["permissions"]))


Review comment (security):
```suggestion
    __slots__ = ('scopes', 'permissions')
```

Code after:
        return Asset._from_icon(self._state, self.id, self._icon, path='app')

    @property
    def flags(self) -> ApplicationFlags:
        """:class:`ApplicationFlags`: The application's flags.

        .. versionadded:: 2.0
        """
        return ApplicationFlags._from_value(self._flags)


class AppInstallParams:
    """Represents the settings for custom authorization URL of an application.

    .. versionadded:: 2.0

    Attributes
    ----------
    scopes: List[:class:`str`]
        The list of `OAuth2 scopes <https://discord.com/developers/docs/topics/oauth2#shared-resources-oauth2-scopes>`_
        to add the application to a guild with.
    permissions: :class:`Permissions`
        The permissions to give to application in the guild.
    """

    __slots__ = ('scopes', 'permissions')

    def __init__(self, data: InstallParamsPayload) -> None:
        self.scopes: List[str] = data.get('scopes', [])
        self.permissions: Permissions = Permissions(int(data['permissions']))
Repository: Rapptz/discord.py
File: discord/appinfo.py (Python)

Code before:
        .. versionadded:: 2.0
        """
        return ApplicationFlags._from_value(self._flags)


class AppInstallParams:
    """Represents the settings for custom authorization URL of an application.

    .. versionadded:: 2.0

    Attributes
    ----------
    scopes: List[:class:`str`]
        The list of `OAuth2 scopes <https://discord.com/developers/docs/topics/oauth2#shared-resources-oauth2-scopes>`_
        to add the application to a guild with.
    permissions: :class:`Permissions`
        The permissions to give to application in the guild.
    """

    __slots__ = (
        "scopes",
        "permissions",
    )

    def __init__(self, data: InstallParamsPayload) -> None:
        self.scopes: List[str] = data.get("scopes", [])
        self.permissions: Permissions = Permissions._from_value(int(data["permissions"]))


Review comment (suggestion):
```suggestion
        self.scopes: List[str] = data.get('scopes', [])
```

Code after:
    def flags(self) -> ApplicationFlags:
        """:class:`ApplicationFlags`: The application's flags.

        .. versionadded:: 2.0
        """
        return ApplicationFlags._from_value(self._flags)


class AppInstallParams:
    """Represents the settings for custom authorization URL of an application.

    .. versionadded:: 2.0

    Attributes
    ----------
    scopes: List[:class:`str`]
        The list of `OAuth2 scopes <https://discord.com/developers/docs/topics/oauth2#shared-resources-oauth2-scopes>`_
        to add the application to a guild with.
    permissions: :class:`Permissions`
        The permissions to give to application in the guild.
    """

    __slots__ = ('scopes', 'permissions')

    def __init__(self, data: InstallParamsPayload) -> None:
        self.scopes: List[str] = data.get('scopes', [])
        self.permissions: Permissions = Permissions(int(data['permissions']))
Repository: Rapptz/discord.py
File: discord/appinfo.py (Python)

Code before:
        """
        return ApplicationFlags._from_value(self._flags)


class AppInstallParams:
    """Represents the settings for custom authorization URL of an application.

    .. versionadded:: 2.0

    Attributes
    ----------
    scopes: List[:class:`str`]
        The list of `OAuth2 scopes <https://discord.com/developers/docs/topics/oauth2#shared-resources-oauth2-scopes>`_
        to add the application to a guild with.
    permissions: :class:`Permissions`
        The permissions to give to application in the guild.
    """

    __slots__ = (
        "scopes",
        "permissions",
    )

    def __init__(self, data: InstallParamsPayload) -> None:
        self.scopes: List[str] = data.get("scopes", [])
        self.permissions: Permissions = Permissions._from_value(int(data["permissions"]))


Review comment (security):
```suggestion
        self.permissions: Permissions = Permissions(int(data['permissions']))
```

Code after:
        """:class:`ApplicationFlags`: The application's flags.

        .. versionadded:: 2.0
        """
        return ApplicationFlags._from_value(self._flags)


class AppInstallParams:
    """Represents the settings for custom authorization URL of an application.

    .. versionadded:: 2.0

    Attributes
    ----------
    scopes: List[:class:`str`]
        The list of `OAuth2 scopes <https://discord.com/developers/docs/topics/oauth2#shared-resources-oauth2-scopes>`_
        to add the application to a guild with.
    permissions: :class:`Permissions`
        The permissions to give to application in the guild.
    """

    __slots__ = ('scopes', 'permissions')

    def __init__(self, data: InstallParamsPayload) -> None:
        self.scopes: List[str] = data.get('scopes', [])
        self.permissions: Permissions = Permissions(int(data['permissions']))
Repository: Rapptz/discord.py
File: discord/ext/commands/errors.py (Python)

Code before:
    """An exception raised when a flag failed to convert a value.

    This inherits from :exc:`FlagError`

    .. versionadded:: 2.0

    Attributes
    -----------
    flag: :class:`~discord.ext.commands.Flag`
        The flag that failed to convert.
    argument: :class:`str`
        The argument supplied by the caller that was not able to be converted.
    original: :class:`Exception`
        The original exception that was raised. You can also get this via
        the ``__cause__`` attribute.
    """

    def __init__(self, flag: Flag, argument: str, original: Exception) -> None:
        self.flag: Flag = flag
        try:
            name = flag.annotation.__name__
        except AttributeError:
            name = flag.annotation.__class__.__name__

        self.argument = argument
        self.original = original

        super().__init__(f'Could not convert to {name!r} for flag {flag.name!r}')


class MissingRequiredFlag(FlagError):
    """An exception raised when a required flag was not given.

    This inherits from :exc:`FlagError`

    .. versionadded:: 2.0

    Attributes
    -----------
    flag: :class:`~discord.ext.commands.Flag`
        The required flag that was not found.
    """

    def __init__(self, flag: Flag) -> None:
        self.flag: Flag = flag
        super().__init__(f'Flag {flag.name!r} is required and missing')


class MissingFlagArgument(FlagError):
    """An exception raised when a flag did not get a value.


Review comment (suggestion):
```suggestion
        self.argument: str = argument
        self.original: Exception = original
```

Code after:
    """An exception raised when a flag failed to convert a value.

    This inherits from :exc:`FlagError`

    .. versionadded:: 2.0

    Attributes
    -----------
    flag: :class:`~discord.ext.commands.Flag`
        The flag that failed to convert.
    argument: :class:`str`
        The argument supplied by the caller that was not able to be converted.
    original: :class:`Exception`
        The original exception that was raised. You can also get this via
        the ``__cause__`` attribute.
    """

    def __init__(self, flag: Flag, argument: str, original: Exception) -> None:
        self.flag: Flag = flag
        try:
            name = flag.annotation.__name__
        except AttributeError:
            name = flag.annotation.__class__.__name__

        self.argument: str = argument
        self.original: Exception = original

        super().__init__(f'Could not convert to {name!r} for flag {flag.name!r}')


class MissingRequiredFlag(FlagError):
    """An exception raised when a required flag was not given.

    This inherits from :exc:`FlagError`

    .. versionadded:: 2.0

    Attributes
    -----------
    flag: :class:`~discord.ext.commands.Flag`
        The required flag that was not found.
    """

    def __init__(self, flag: Flag) -> None:
        self.flag: Flag = flag
        super().__init__(f'Flag {flag.name!r} is required and missing')


class MissingFlagArgument(FlagError):
    """An exception raised when a flag did not get a value.
Repository: Rapptz/discord.py
File: discord/ext/commands/flags.py (Python)

Code before:
                
                if case_insensitive:
                    name = last_flag.name.casefold()
                else:
                    name = last_flag.name

                try:
                    values = result[name]
                except KeyError:
                    result[name] = [value]
                else:
                    values.append(value)

            last_position = end
            last_flag = flag

        # Add the remaining string to the last available flag
        if last_position and last_flag is not None:
            value = argument[last_position:].strip()
            if not value:
                raise MissingFlagArgument(last_flag)

            if case_insensitive:
                name = last_flag.name.casefold()
            else:
                name = last_flag.name

            try:
                values = result[name]
            except KeyError:
                result[name] = [value]
            else:
                values.append(value)

        # Verification of values will come at a later stage
        return result

    @classmethod
    async def convert(cls, ctx: Context[BotT], argument: str) -> Self:
        """|coro|

        The method that actually converters an argument to the flag mapping.

        Parameters
        ----------
        ctx: :class:`Context`
            The invocation context.
        argument: :class:`str`
            The argument to convert from.

        Raises

Review comment (security):
```suggestion
            name = last_flag.name.casefold() if case_insensitive else last_flag.name
```

Code after:

                name = last_flag.name.casefold() if case_insensitive else last_flag.name

                try:
                    values = result[name]
                except KeyError:
                    result[name] = [value]
                else:
                    values.append(value)

            last_position = end
            last_flag = flag

        # Add the remaining string to the last available flag
        if last_position and last_flag is not None:
            value = argument[last_position:].strip()
            if not value:
                raise MissingFlagArgument(last_flag)

            name = last_flag.name.casefold() if case_insensitive else last_flag.name

            try:
                values = result[name]
            except KeyError:
                result[name] = [value]
            else:
                values.append(value)

        # Verification of values will come at a later stage
        return result

    @classmethod
    async def convert(cls, ctx: Context[BotT], argument: str) -> Self:
        """|coro|

        The method that actually converters an argument to the flag mapping.

        Parameters
        ----------
        ctx: :class:`Context`
            The invocation context.
        argument: :class:`str`
            The argument to convert from.

        Raises
        --------
        FlagError
            A flag related parsing error.

        Returns
        --------
Repository: Rapptz/discord.py
File: examples/advanced_startup.py (Python)

Code before:
# This example covers advanced startup options and uses some real world examples for why you may need them.

import asyncio
import logging
import os

from typing import Optional

import asyncpg  # asyncpg is not a dependency of the discord.py, and is only included here for illustrative purposes.
import discord
from discord.ext import commands
from aiohttp import ClientSession


class CustomBot(commands.Bot):
    def __init__(
        self,
        *args,
        initial_extensions: list,
        db_pool: asyncpg.Pool,
        web_client: ClientSession,
        testing_guild_id: Optional[int] = None,
        **kwargs,
    ):
        super().__init__(*args, **kwargs)
        self.db_pool = db_pool
        self.web_client = web_client
        self.testing_guild_id = testing_guild_id
        self.initial_extensions = initial_extensions

    async def setup_hook(self) -> None:


Review comment (suggestion):
```suggestion
from typing import Optional, List
```

Code after:
# This example covers advanced startup options and uses some real world examples for why you may need them.

import asyncio
import logging
import logging.handlers
import os

from typing import List, Optional

import asyncpg  # asyncpg is not a dependency of the discord.py, and is only included here for illustrative purposes.
import discord
from discord.ext import commands
from aiohttp import ClientSession


class CustomBot(commands.Bot):
    def __init__(
        self,
        *args,
        initial_extensions: List[str],
        db_pool: asyncpg.Pool,
        web_client: ClientSession,
        testing_guild_id: Optional[int] = None,
        **kwargs,
    ):
        super().__init__(*args, **kwargs)
        self.db_pool = db_pool
        self.web_client = web_client
        self.testing_guild_id = testing_guild_id
        self.initial_extensions = initial_extensions

    async def setup_hook(self) -> None:
Repository: Rapptz/discord.py
File: discord/types/command.py (Python)

Code before:


class _SubCommandCommandOption(_BaseApplicationCommandOption):
    type: Literal[1]
    options: List[_ValueApplicationCommandOption]


class _SubCommandGroupCommandOption(_BaseApplicationCommandOption):
    type: Literal[2]
    options: List[_SubCommandCommandOption]


class _BaseValueApplicationCommandOption(_BaseApplicationCommandOption, total=False):
    required: bool


class _StringApplicationCommandOptionChoice(TypedDict):
    name: str
    value: str


class _StringApplicationCommandOption(_BaseApplicationCommandOption):
    type: Literal[3]
    choices: NotRequired[List[_StringApplicationCommandOptionChoice]]
    min_length: int
    max_length: int
    autocomplete: NotRequired[bool]


class _IntegerApplicationCommandOptionChoice(TypedDict):
    name: str
    value: int


class _IntegerApplicationCommandOption(_BaseApplicationCommandOption, total=False):
    type: Required[Literal[4]]
    min_value: int
    max_value: int
    choices: List[_IntegerApplicationCommandOptionChoice]
    autocomplete: bool


class _BooleanApplicationCommandOption(_BaseValueApplicationCommandOption):
    type: Literal[5]


class _ChannelApplicationCommandOptionChoice(_BaseApplicationCommandOption):
    type: Literal[7]
    channel_types: NotRequired[List[ChannelType]]



Review comment (suggestion):
```suggestion
    min_length: NotRequired[int]
    max_length: NotRequired[int]
```

Code after:


class _SubCommandCommandOption(_BaseApplicationCommandOption):
    type: Literal[1]
    options: List[_ValueApplicationCommandOption]


class _SubCommandGroupCommandOption(_BaseApplicationCommandOption):
    type: Literal[2]
    options: List[_SubCommandCommandOption]


class _BaseValueApplicationCommandOption(_BaseApplicationCommandOption, total=False):
    required: bool


class _StringApplicationCommandOptionChoice(TypedDict):
    name: str
    value: str


class _StringApplicationCommandOption(_BaseApplicationCommandOption):
    type: Literal[3]
    choices: NotRequired[List[_StringApplicationCommandOptionChoice]]
    min_length: NotRequired[int]
    max_length: NotRequired[int]
    autocomplete: NotRequired[bool]


class _IntegerApplicationCommandOptionChoice(TypedDict):
    name: str
    value: int


class _IntegerApplicationCommandOption(_BaseApplicationCommandOption, total=False):
    type: Required[Literal[4]]
    min_value: int
    max_value: int
    choices: List[_IntegerApplicationCommandOptionChoice]
    autocomplete: bool


class _BooleanApplicationCommandOption(_BaseValueApplicationCommandOption):
    type: Literal[5]


class _ChannelApplicationCommandOptionChoice(_BaseApplicationCommandOption):
    type: Literal[7]
    channel_types: NotRequired[List[ChannelType]]
Repository: Rapptz/discord.py
File: discord/flags.py (Python)

Code before:
        """A factory method that creates a :class:`AutoModPresets` with everything enabled."""
        bits = max(cls.VALID_FLAGS.values()).bit_length()
        value = (1 << bits) - 1
        self = cls.__new__(cls)
        self.value = value
        return self

    @classmethod
    def none(cls: Type[Self]) -> Self:
        """A factory method that creates a :class:`AutoModPresets` with everything disabled."""
        self = cls.__new__(cls)
        self.value = self.DEFAULT_VALUE
        return self


@fill_with_flags()
class MemberFlags(BaseFlags):
    r"""Wraps up the Discord Guild Member flags

    .. container:: operations

        .. describe:: x == y

            Checks if two MemberFlags are equal.
        .. describe:: x != y

            Checks if two MemberFlags are not equal.

        .. describe:: x | y, x |= y

            Returns a MemberFlags instance with all enabled flags from
            both x and y.

        .. describe:: x & y, x &= y

            Returns a MemberFlags instance with only flags enabled on
            both x and y.

        .. describe:: x ^ y, x ^= y

            Returns a MemberFlags instance with only flags enabled on
            only one of x or y, not on both.

        .. describe:: ~x

            Returns a MemberFlags instance with all flags inverted from x.

        .. describe:: hash(x)

            Return the flag's hash.
        .. describe:: iter(x)

Review comment (suggestion):
```suggestion
            Checks if two MemberFlags are equal.

```

Code after:
        """A factory method that creates a :class:`AutoModPresets` with everything enabled."""
        bits = max(cls.VALID_FLAGS.values()).bit_length()
        value = (1 << bits) - 1
        self = cls.__new__(cls)
        self.value = value
        return self

    @classmethod
    def none(cls: Type[Self]) -> Self:
        """A factory method that creates a :class:`AutoModPresets` with everything disabled."""
        self = cls.__new__(cls)
        self.value = self.DEFAULT_VALUE
        return self


@fill_with_flags()
class MemberFlags(BaseFlags):
    r"""Wraps up the Discord Guild Member flags

    .. versionadded:: 2.2

    .. container:: operations

        .. describe:: x == y

            Checks if two MemberFlags are equal.

        .. describe:: x != y

            Checks if two MemberFlags are not equal.

        .. describe:: x | y, x |= y

            Returns a MemberFlags instance with all enabled flags from
            both x and y.

        .. describe:: x & y, x &= y

            Returns a MemberFlags instance with only flags enabled on
            both x and y.

        .. describe:: x ^ y, x ^= y

            Returns a MemberFlags instance with only flags enabled on
            only one of x or y, not on both.

        .. describe:: ~x

            Returns a MemberFlags instance with all flags inverted from x.

        .. describe:: hash(x)