ronantakizawa/codereview-bench huggingface dataset:
Repository: symfony/symfony
File: src/Symfony/Component/Cache/DependencyInjection/CachePoolPass.php (PHP)

Code before:
    {
        return substr(str_replace('/', '-', base64_encode(hash('xxh128', $id.$seed, true))), 0, 10);
    }

    /**
     * @internal
     */
    public static function getServiceProvider(ContainerBuilder $container, string $name): string
    {
        $container->resolveEnvPlaceholders($name, null, $usedEnvs);

        if ($usedEnvs || preg_match('#^[a-z]++:#', $name)) {
            $dsn = $name;

            if (!$container->hasDefinition($name = '.cache_connection.'.ContainerBuilder::hash($dsn))) {
                $definition = new Definition(AbstractAdapter::class);
                $definition->setFactory([AbstractAdapter::class, 'createConnection']);
                $definition->setArguments([$dsn, ['lazy' => true]]);
                $container->setDefinition($name, $definition);
            }
        }

        return $name;
    }

    private function findDefaultMarshallerArgumentIndex(Definition $definition): ?int
    {
        foreach ($definition->getArguments() as $index => $argument) {
            if ($argument instanceof Reference && 'cache.default_marshaller' === (string) $argument) {
                return \is_int($index) ? $index : (int) substr($index, 6); // handle 'index_N' format
            }
        }

        return null;
    }
}


Review comment (suggestion):
```suggestion
    private function findDefaultMarshallerArgumentIndex(Definition $definition): int|string|null
```

Code after:
    }

    /**
     * @internal
     */
    public static function getServiceProvider(ContainerBuilder $container, string $name): string
    {
        $container->resolveEnvPlaceholders($name, null, $usedEnvs);

        if ($usedEnvs || preg_match('#^[a-z]++:#', $name)) {
            $dsn = $name;

            if (!$container->hasDefinition($name = '.cache_connection.'.ContainerBuilder::hash($dsn))) {
                $definition = new Definition(AbstractAdapter::class);
                $definition->setFactory([AbstractAdapter::class, 'createConnection']);
                $definition->setArguments([$dsn, ['lazy' => true]]);
                $container->setDefinition($name, $definition);
            }
        }

        return $name;
    }

    private function findDefaultMarshallerArgumentIndex(Definition $definition): int|string|null
    {
        foreach ($definition->getArguments() as $index => $argument) {
            if ($argument instanceof Reference && 'cache.default_marshaller' === (string) $argument) {
                return \is_int($index) ? $index : (str_starts_with($index, 'index_') ? (int) substr($index, 6) : $index);
            }
        }

        return null;
    }
}
Repository: symfony/symfony
File: src/Symfony/Component/HttpFoundation/BinaryFileResponse.php (PHP)

Code before:
    {
        return false;
    }

    /**
     * Trust X-Sendfile-Type header.
     */
    public static function trustXSendfileTypeHeader(): void
    {
        self::$trustXSendfileTypeHeader = true;
    }

    /**
     * If this is set to true, the file will be unlinked after the request is sent
     * Note: If the X-Sendfile header is used, the deleteFileAfterSend setting will not be used.
     *
     * @return $this
     */
    public function deleteFileAfterSend(bool $shouldDelete = true): static
    {
        $this->deleteFileAfterSend = $shouldDelete;

        return $this;
    }

    public function isDeleteFileAfterSend(): bool
    {
        return $this->deleteFileAfterSend;
    }
}


Review comment (suggestion):
maybe a bit better?
```suggestion
    public function shouldDeleteFileAfterSend(): bool
```

Code after:
    {
        return false;
    }

    /**
     * Trust X-Sendfile-Type header.
     */
    public static function trustXSendfileTypeHeader(): void
    {
        self::$trustXSendfileTypeHeader = true;
    }

    /**
     * If this is set to true, the file will be unlinked after the request is sent
     * Note: If the X-Sendfile header is used, the deleteFileAfterSend setting will not be used.
     *
     * @return $this
     */
    public function deleteFileAfterSend(bool $shouldDelete = true): static
    {
        $this->deleteFileAfterSend = $shouldDelete;

        return $this;
    }

    public function shouldDeleteFileAfterSend(): bool
    {
        return $this->deleteFileAfterSend;
    }
}
Repository: symfony/symfony
File: src/Symfony/Component/Console/Command/TraceableCommand.php (PHP)

Code before:
        }

        $event = $this->stopwatch->start($this->getName().'.interact', 'command');

        $this->command->interact($input, $output);

        $event->stop();
    }

    protected function execute(InputInterface $input, OutputInterface $output): int
    {
        $event = $this->stopwatch->start($this->getName().'.execute', 'command');

        $exitCode = $this->command->execute($input, $output);

        $event->stop();

        return $exitCode;
    }

    private function extractInteractiveInputs(array $initialArguments, array $initialOptions): void
    {
        $nativeDefinition = $this->command->getNativeDefinition();

        foreach ($nativeDefinition->getArguments() as $argName => $argument) {
            // skip applicaton-level opts/args e.g. 'command' or '--help'
            if (\array_key_exists($argName, $initialArguments) && $initialArguments[$argName] === $this->arguments[$argName]) {
                continue;
            }

            $this->interactiveInputs[$argName] = $this->arguments[$argName];
        }

        foreach ($nativeDefinition->getOptions() as $optName => $option) {
            if (\array_key_exists($optName, $initialOptions) && $initialOptions[$optName] === $this->options[$optName]) {
                continue;
            }

            $this->interactiveInputs['--'.$optName] = $this->options[$optName];
        }
    }
}


Review comment (suggestion):
this comment is misleading IMO. Any argument that was part of the initial arguments is skipped (unless the comments refers to the usage of `$nativeDefinition->getArguments()` for the loop, but then it should be above it)

Code after:
        }

        $event = $this->stopwatch->start($this->getName().'.interact', 'command');

        $this->command->interact($input, $output);

        $event->stop();
    }

    protected function execute(InputInterface $input, OutputInterface $output): int
    {
        $event = $this->stopwatch->start($this->getName().'.execute', 'command');

        $exitCode = $this->command->execute($input, $output);

        $event->stop();

        return $exitCode;
    }

    private function extractInteractiveInputs(array $initialArguments, array $initialOptions): void
    {
        $nativeDefinition = $this->command->getNativeDefinition();

        foreach ($nativeDefinition->getArguments() as $argName => $argument) {
            if (\array_key_exists($argName, $initialArguments) && $initialArguments[$argName] === $this->arguments[$argName]) {
                continue;
            }

            $this->interactiveInputs[$argName] = $this->arguments[$argName];
        }

        foreach ($nativeDefinition->getOptions() as $optName => $option) {
            if (\array_key_exists($optName, $initialOptions) && $initialOptions[$optName] === $this->options[$optName]) {
                continue;
            }

            $this->interactiveInputs['--'.$optName] = $this->options[$optName];
        }
    }
}
Repository: symfony/symfony
File: src/Symfony/Component/Translation/Bridge/Crowdin/CrowdinProviderFactory.php (PHP)

Code before:
        private readonly XliffFileDumper $xliffFileDumper,
    ) {
    }

    public function create(Dsn $dsn): CrowdinProvider
    {
        if ('crowdin' !== $dsn->getScheme()) {
            throw new UnsupportedSchemeException($dsn, 'crowdin', $this->getSupportedSchemes());
        }

        $endpoint = preg_replace('/(^|\.)default$/', '\1'.self::HOST, $dsn->getHost());
        $endpoint .= $dsn->getPort() ? ':'.$dsn->getPort() : '';

        $client = ScopingHttpClient::forBaseUri(
            new RetryableHttpClient(
                $this->client,
                new GenericRetryStrategy([429]),
                3,
                $this->logger
            ),
            \sprintf('https://%s/api/v2/projects/%d/', $endpoint, $this->getUser($dsn)),
            [
                'auth_bearer' => $this->getPassword($dsn),
            ],
            preg_quote('https://'.$endpoint.'/api/v2/')
        );

        return new CrowdinProvider($client, $this->loader, $this->logger, $this->xliffFileDumper, $this->defaultLocale, $endpoint);
    }

    protected function getSupportedSchemes(): array
    {
        return ['crowdin'];
    }
}


Review comment (security):
```suggestion
        $client = new RetryableHttpClient($this->client, new GenericRetryStrategy([429]), 3, $this->logger);
        $client = ScopingHttpClient::forBaseUri($client, \sprintf('https://%s/api/v2/projects/%d/', $endpoint, $this->getUser($dsn)), [
            'auth_bearer' => $this->getPassword($dsn),
        ], preg_quote('https://'.$endpoint.'/api/v2/'));
```

Code after:
        private readonly XliffFileDumper $xliffFileDumper,
    ) {
    }

    public function create(Dsn $dsn): CrowdinProvider
    {
        if ('crowdin' !== $dsn->getScheme()) {
            throw new UnsupportedSchemeException($dsn, 'crowdin', $this->getSupportedSchemes());
        }

        $endpoint = preg_replace('/(^|\.)default$/', '\1'.self::HOST, $dsn->getHost());
        $endpoint .= $dsn->getPort() ? ':'.$dsn->getPort() : '';

        $client = new RetryableHttpClient($this->client, new GenericRetryStrategy([429]), 3, $this->logger);
        $client = ScopingHttpClient::forBaseUri($client, \sprintf('https://%s/api/v2/projects/%d/', $endpoint, $this->getUser($dsn)), [
            'auth_bearer' => $this->getPassword($dsn),
        ], preg_quote('https://'.$endpoint.'/api/v2/'));

        return new CrowdinProvider($client, $this->loader, $this->logger, $this->xliffFileDumper, $this->defaultLocale, $endpoint);
    }

    protected function getSupportedSchemes(): array
    {
        return ['crowdin'];
    }
}
Repository: symfony/symfony
File: src/Symfony/Bundle/FrameworkBundle/Tests/Functional/RunCommandTest.php (PHP)

Code before:
<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Bundle\FrameworkBundle\Tests\Functional;

use PHPUnit\Framework\Attributes\Group;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Tester\ExecutionResult;

#[Group('functional')]
class RunCommandTest extends AbstractWebTestCase
{
    protected function setUp(): void
    {
        static::bootKernel(['test_case' => 'RunCommand', 'root_config' => 'config.yml']);
    }

    public function testRunCommandReturnsExecutionResult(): void
    {
        $result = static::runCommand('list');

        $this->assertInstanceOf(ExecutionResult::class, $result);
        $this->assertSame(Command::SUCCESS, $result->statusCode);
        $this->assertStringContainsString('Available commands:', $result->getOutput());
    }

    public function testRunCommandIsSuccessful(): void
    {
        $result = static::runCommand('list');

        $this->assertIsSuccessful($result);
    }

    public function testRunCommandWithArguments(): void
    {
        $result = static::runCommand('list', ['namespace' => 'debug']);

        $this->assertIsSuccessful($result);
        $this->assertStringContainsString('debug', $result->getOutput());
    }
}


Review comment (suggestion):
See fabbot
```suggestion
    public function testRunCommandReturnsExecutionResult()
```

Code after:
<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Bundle\FrameworkBundle\Tests\Functional;

use PHPUnit\Framework\Attributes\Group;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Tester\ExecutionResult;

#[Group('functional')]
class RunCommandTest extends AbstractWebTestCase
{
    protected function setUp(): void
    {
        static::bootKernel(['test_case' => 'RunCommand', 'root_config' => 'config.yml']);
    }

    public function testRunCommandReturnsExecutionResult()
    {
        $result = static::runCommand('list');

        $this->assertInstanceOf(ExecutionResult::class, $result);
        $this->assertSame(Command::SUCCESS, $result->statusCode);
        $this->assertStringContainsString('Available commands:', $result->getOutput());
    }

    public function testRunCommandIsSuccessful()
    {
        $result = static::runCommand('list');

        $this->assertIsSuccessful($result);
    }

    public function testRunCommandWithArguments()
    {
        $result = static::runCommand('list', ['namespace' => 'debug']);

        $this->assertIsSuccessful($result);
        $this->assertStringContainsString('debug', $result->getOutput());
    }
}
Repository: sympy/sympy
File: sympy/tensor/array/expressions/arrayexpr_derivatives.py (Python)

Code before:
    rank_x = len(get_shape(x))
    diag_indices = [[j + rank_x for j in i] for i in expr.diagonal_indices]
    return _array_diagonal(dsubexpr, *diag_indices)


@array_derive.register(ArrayAdd)
def _(expr: ArrayAdd, x: Expr):
    return _array_add(*[array_derive(arg, x) for arg in expr.args])


@array_derive.register(PermuteDims)
def _(expr: PermuteDims, x: Expr):
    de = array_derive(expr.expr, x)
    perm = [0, 1] + [i + 2 for i in expr.permutation.array_form]
    return _permute_dims(de, perm)


@array_derive.register(Reshape)
def _(expr: Reshape, x: Expr):
    de = array_derive(expr.expr, x)
    return Reshape(de, get_shape(x) + expr.shape)


@array_derive.register(MatrixBase)
def _(expr: MatrixBase, x):
    if len(set.intersection(expr.free_symbols, x.free_symbols)) == 0:
        return ZeroArray(*x.shape, *expr.shape)
    if isinstance(x, MatrixExpr) and all(isinstance(i, (int, Integer)) for i in x.shape):
        x = x.as_explicit()
    if isinstance(x, MatrixBase):
        return derive_by_array(expr, x)
    raise NotImplementedError("could not determine derivative")


def matrix_derive(expr, x):
    from sympy.tensor.array.expressions.from_array_to_matrix import convert_array_to_matrix
    ce = convert_matrix_to_array(expr)
    dce = array_derive(ce, x)
    return convert_array_to_matrix(dce).doit()


Review comment (suggestion):
```suggestion
    if not set.intersection(expr.free_symbols, x.free_symbols):
```

Code after:
@array_derive.register(ArrayDiagonal)
def _(expr: ArrayDiagonal, x: Expr):
    dsubexpr = array_derive(expr.expr, x)
    rank_x = len(get_shape(x))
    diag_indices = [[j + rank_x for j in i] for i in expr.diagonal_indices]
    return _array_diagonal(dsubexpr, *diag_indices)


@array_derive.register(ArrayAdd)
def _(expr: ArrayAdd, x: Expr):
    return _array_add(*[array_derive(arg, x) for arg in expr.args])


@array_derive.register(PermuteDims)
def _(expr: PermuteDims, x: Expr):
    de = array_derive(expr.expr, x)
    perm = [0, 1] + [i + 2 for i in expr.permutation.array_form]
    return _permute_dims(de, perm)


@array_derive.register(Reshape)
def _(expr: Reshape, x: Expr):
    de = array_derive(expr.expr, x)
    return Reshape(de, get_shape(x) + expr.shape)


@array_derive.register(MatrixBase)
def _(expr: MatrixBase, x):
    if not set.intersection(expr.free_symbols, x.free_symbols):
        return ZeroArray(*x.shape, *expr.shape)
    if isinstance(x, MatrixExpr) and all(isinstance(i, (int, Integer)) for i in x.shape):
        x = x.as_explicit()
    if isinstance(x, MatrixBase):
        return derive_by_array(expr, x)
    raise NotImplementedError("could not determine derivative")


@array_derive.register(NDimArray)
def _(expr: NDimArray, x):
    derive_by_array(expr, x)


def matrix_derive(expr, x):
    from sympy.tensor.array.expressions.from_array_to_matrix import convert_array_to_matrix
    ce = convert_matrix_to_array(expr)
    dce = array_derive(ce, x)
    return convert_array_to_matrix(dce).doit()
Repository: sympy/sympy
File: sympy/matrices/expressions/special.py (Python)

Code before:
        condition = self._is_1x1()
        if condition == True:
            return Identity(1)
        elif condition == False:
            raise NonInvertibleMatrixError("Matrix det == 0; not invertible.")
        else:
            from .inverse import Inverse
            return Inverse(self)

    def _eval_as_real_imag(self):
        return self, ZeroMatrix(*self.shape)

    def _eval_conjugate(self):
        return self

    def _entry(self, i, j, **kwargs):
        return S.One


class MatrixUnit(MatrixExpr):
    """
    Matrix with only one nonzero entry with value 1.

    https://en.wikipedia.org/wiki/Matrix_unit
    """
    def __new__(cls, i, j, shape):
        obj = MatrixExpr.__new__(cls, i, j, shape)
        obj._i = i
        obj._j = j
        obj._shape = shape
        return obj

    @property
    def shape(self):
        return self._shape

    @property
    def rows(self):
        return self._shape[0]

    @property
    def cols(self):
        return self._shape[1]

    @property
    def is_square(self):
        return Eq(self.rows, self.cols)

    def _eval_transpose(self):
        return MatrixUnit(self._j, self._i, self.shape)


Review comment (suggestion):
I'm not sure if these are the best parameters
because other matrix symbols are used to take rows and cols as separate parameters than shape.

Code after:
        condition = self._is_1x1()
        if condition == True:
            return Identity(1)
        elif condition == False:
            raise NonInvertibleMatrixError("Matrix det == 0; not invertible.")
        else:
            from .inverse import Inverse
            return Inverse(self)

    def _eval_as_real_imag(self):
        return self, ZeroMatrix(*self.shape)

    def _eval_conjugate(self):
        return self

    def _entry(self, i, j, **kwargs):
        return S.One


class MatrixUnit(MatrixExpr):
    """
    Matrix with only one nonzero entry with value 1.

    https://en.wikipedia.org/wiki/Matrix_unit
    """
    def __new__(cls, rows, cols, i, j):
        obj = MatrixExpr.__new__(cls, rows, cols, i, j)
        obj._i = i
        obj._j = j
        return obj

    @property
    def shape(self):
        return self._args[0], self._args[1]

    @property
    def rows(self):
        return self._args[0]

    @property
    def cols(self):
        return self._args[1]

    @property
    def is_square(self):
        return Eq(self.rows, self.cols)

    def _eval_transpose(self):
        return MatrixUnit(self.cols, self.rows, self._j, self._i)

    def _eval_trace(self):
Repository: sympy/sympy
File: sympy/matrices/expressions/special.py (Python)

Code before:
    @property
    def is_square(self):
        return Eq(self.rows, self.cols)

    def _eval_transpose(self):
        return MatrixUnit(self._j, self._i, self.shape)

    def _eval_trace(self):
        if (self.rows == self.cols) == True:
            if self.shape == (1, 1):
                return S.One
            return S.Zero

    def _eval_inverse(self):
        if self.shape == (1, 1):
            return self
        raise NonInvertibleMatrixError("Cannot invert this MatrixUnit")

    def _eval_as_real_imag(self):
        return self, ZeroMatrix(*self.shape)

    def _eval_conjugate(self):
        return MatrixUnit(self._j, self._i, self.shape)

    def _eval_adjoint(self):
        return self._eval_conjugate()

    def _entry(self, i, j, **kwargs):
        return KroneckerDelta(i, self._i, (0, self.rows-1)) * KroneckerDelta(j, self._j, (0, self.cols-1))


Review comment (suggestion):
`_eval_conjugate` does not seem right:
```python
In [8]: from sympy.matrices.expressions.special import MatrixUnit

In [9]: M = MatrixUnit(0, 1, (2, 2))

In [10]: M
Out[10]: MatrixUnit(0, 1, (2, 2))

In [11]: M.conjugate()
Out[11]: MatrixUnit(1, 0, (2, 2))

In [12]: M.as_explicit()
Out[12]: 
⎡0  1⎤
⎢    ⎥
⎣0  0⎦

In [13]: M.as_explicit().conjugate()
Out[13]: 
⎡0  1⎤
⎢    ⎥
⎣0  0⎦

In [14]: M.conjugate().as_explicit()
Out[14]: 
⎡0  0⎤
⎢    ⎥
⎣1  0⎦
```

Code after:
    def is_square(self):
        return Eq(self.rows, self.cols)

    def _eval_transpose(self):
        return MatrixUnit(self.cols, self.rows, self._j, self._i)

    def _eval_trace(self):
        if (self.rows == self.cols) == True:
            if self.shape == (1, 1):
                return S.One
            return S.Zero

    def _eval_inverse(self):
        if self.shape == (1, 1):
            return self
        raise NonInvertibleMatrixError("Cannot invert this MatrixUnit")

    def _eval_as_real_imag(self):
        return self, ZeroMatrix(*self.shape)

    def _eval_conjugate(self):
        return self

    def _eval_adjoint(self):
        return self._eval_conjugate()._eval_transpose()

    def _entry(self, i, j, **kwargs):
        return KroneckerDelta(i, self._i, (0, self.rows-1)) * KroneckerDelta(j, self._j, (0, self.cols-1))
Repository: sympy/sympy
File: sympy/functions/elementary/complexes.py (Python)

Code before:
    See Also
    ========

    sign, Abs

    References
    ==========

    .. [1] https://en.wikipedia.org/wiki/Complex_conjugation
    """
    _singularities = True  # non-holomorphic

    @classmethod
    def eval(cls, arg):
        obj = arg._eval_conjugate()
        if obj is not None:
            return obj

    def inverse(self):
        return conjugate

    def _eval_Abs(self):
        return Abs(self.args[0], evaluate=True)

    def _eval_adjoint(self):
        return transpose(self.args[0])

    def _eval_conjugate(self):
        return self.args[0]

    def _eval_derivative(self, x):
        if x.is_real:
            return conjugate(Derivative(self.args[0], x, evaluate=True))
        elif x.is_imaginary:
            return -conjugate(Derivative(self.args[0], x, evaluate=True))

    def _eval_transpose(self):
        return adjoint(self.args[0])

    def _eval_is_algebraic(self):
        return self.args[0].is_algebraic


class transpose(DefinedFunction):
    """
    Linear map transposition.

    Examples
    ========

    >>> from sympy import transpose, Matrix, MatrixSymbol

Review comment (suggestion):
The type:ignore here are needed because of: https://github.com/python/mypy/issues/15182

Code after:
    =======

    arg : Expr
        Complex conjugate of arg as real, imaginary or mixed expression.

    See Also
    ========

    sign, Abs

    References
    ==========

    .. [1] https://en.wikipedia.org/wiki/Complex_conjugation
    """
    _singularities = True  # non-holomorphic

    if TYPE_CHECKING:

        @overload
        def __new__(cls, arg: Quaternion) -> Quaternion: ... # type: ignore
        @overload
        def __new__(cls, arg: Expr) -> Expr: ... # type: ignore

        def __new__(cls, arg: Basic) -> Basic: ... # type: ignore

    @classmethod
    def eval(cls, arg):
        obj = arg._eval_conjugate()
        if obj is not None:
            return obj

    def inverse(self):
        return conjugate

    def _eval_Abs(self):
        return Abs(self.args[0], evaluate=True)

    def _eval_adjoint(self):
        return transpose(self.args[0])

    def _eval_conjugate(self):
        return self.args[0]

    def _eval_derivative(self, x):
        if x.is_real:
            return conjugate(Derivative(self.args[0], x, evaluate=True))
        elif x.is_imaginary:
            return -conjugate(Derivative(self.args[0], x, evaluate=True))

    def _eval_transpose(self):