ronantakizawa/codereview-bench huggingface dataset:
Repository: PowerShell/PowerShell
File: src/Microsoft.PowerShell.Commands.Utility/commands/utility/NewGuidCommand.cs (C#)

Code before:
        [Parameter(ParameterSetName = "Empty")]
        public SwitchParameter Empty { get; set; }

        /// <summary>
        /// Converts a string to a Guid.
        /// </summary>
        [Parameter(ParameterSetName = "FromString")]
        [ValidateNotNullOrWhiteSpace]
        public string? FromString { get; set; }

        /// <summary>
        /// Returns a Guid.
        /// </summary>
        protected override void EndProcessing()
        {
            Guid guid = Empty.IsPresent ? Guid.Empty : Guid.NewGuid();

            if (FromString is not null)
            {
                try
                {
                    guid = new(FromString);
                }
                catch (Exception ex)
                {
                    ErrorRecord error = new(ex, "StringNotRecognizedAsGuid", ErrorCategory.InvalidOperation, null);
                    ThrowTerminatingError(error);
                }  
            }

            WriteObject(guid);
        }
    }
}


Review comment (suggestion):
this should probably be InvalidArgument
```suggestion
                    ErrorRecord error = new(ex, "StringNotRecognizedAsGuid", ErrorCategory.InvalidArgument, null);
```

Code after:
        [Parameter(ParameterSetName = "Empty")]
        public SwitchParameter Empty { get; set; }

        /// <summary>
        /// Gets or sets the value to be converted to a Guid.
        /// </summary>
        [Parameter(Position = 0, ValueFromPipeline = true, ParameterSetName = "InputObject")]
        [System.Diagnostics.CodeAnalysis.AllowNull]
        public string InputObject { get; set; }

        /// <summary>
        /// Returns a Guid.
        /// </summary>
        protected override void ProcessRecord()
        {
            Guid? guid = null;

            if (ParameterSetName is "InputObject")
            {
                try
                {
                    guid = new(InputObject);
                }
                catch (Exception ex)
                {
                    ErrorRecord error = new(ex, "StringNotRecognizedAsGuid", ErrorCategory.InvalidArgument, null);
                    WriteError(error);
                }  
            }
            else
            {
                guid = ParameterSetName is "Empty" ? Guid.Empty : Guid.NewGuid();
            }

            WriteObject(guid);
        }
    }
}
Repository: PowerShell/PowerShell
File: test/powershell/Modules/Microsoft.PowerShell.Utility/New-Guid.Tests.ps1 (PowerShell)

Code before:
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT License.
Describe "New-Guid" -Tags "CI" {

    It "Returns a new guid" {
        $guid = New-Guid
        $guid | Should -BeOfType System.Guid
    }

    It "Should not be all zeros" {
        $guid = New-Guid
        $guid.ToString() | Should -Not -BeExactly "00000000-0000-0000-0000-000000000000"
    }

    It "Should be all zeros" {
        $guid = New-Guid -Empty
        $guid.ToString() | Should -BeExactly "00000000-0000-0000-0000-000000000000"
    }

    It "Should convert a string to a guid" {
        $guid1 = New-Guid
        $guid2 = New-Guid -FromString $guid1.ToString()
        $guid2 | Should -BeOfType System.Guid
        $guid1.ToString() | Should -BeExactly $guid2.ToString()
    }

    It "Should return different guids with each call" {
        $guid1 = New-Guid
        $guid2 = New-Guid
        $guid1.ToString() | Should -Not -Be $guid2.ToString()
    }
}



Review comment (suggestion):
here's an additional test we should probably do:
```powershell
It "Should accept pipeline input" {
   $guids = 1..10 | foreach-object { [guid]::newguid() }
   $observed = $guids.Foreach({$_.ToString()}) | New-Guid
   $observed | Should -Be $guids
}
```

Code after:
    }

    It "Should convert a string to a guid" {
        $guid1 = New-Guid
        $guid2 = New-Guid -InputObject $guid1.ToString()
        $guid3 = New-Guid $guid1.ToString()
        $guid2 | Should -BeOfType System.Guid
        $guid1.ToString() | Should -BeExactly $guid2.ToString()
        $guid1.ToString() | Should -BeExactly $guid3.ToString()
    }

    It "Should convert a string to a guid, value from pipeline" {
        $guids = '11c43ee8-b9d3-4e51-b73f-bd9dda66e29c','0f8fad5bd9cb469fa16570867728950e' | New-Guid
        $guids[0].ToString() | Should -BeExactly '11c43ee8-b9d3-4e51-b73f-bd9dda66e29c'
        $guids[1].ToString() | Should -BeExactly '0f8fad5b-d9cb-469f-a165-70867728950e'
    }

    It "Should accept pipeline input" {
        $guids = 1..10 | foreach-object { [guid]::newguid() }
        $observed = $guids.Foreach({$_.ToString()}) | New-Guid
        $observed | Should -Be $guids
    }

    It "Should return different guids with each call" {
        $guid1 = New-Guid
        $guid2 = New-Guid
        $guid1.ToString() | Should -Not -Be $guid2.ToString()
    }
}
Repository: PowerShell/PowerShell
File: src/Microsoft.PowerShell.Commands.Utility/commands/utility/NewGuidCommand.cs (C#)

Code before:
        public SwitchParameter Empty { get; set; }

        /// <summary>
        /// Converts a string to a Guid.
        /// </summary>
        [Parameter(ParameterSetName = "FromString")]
        [ValidateNotNullOrWhiteSpace]
        public string? FromString { get; set; }

        /// <summary>
        /// Returns a Guid.
        /// </summary>
        protected override void EndProcessing()
        {
            Guid guid = Empty.IsPresent ? Guid.Empty : Guid.NewGuid();

            if (FromString is not null)
            {
                try
                {
                    guid = new(FromString);
                }
                catch (Exception ex)
                {
                    ErrorRecord error = new(ex, "StringNotRecognizedAsGuid", ErrorCategory.InvalidOperation, null);
                    ThrowTerminatingError(error);
                }  
            }

            WriteObject(guid);
        }
    }
}


Review comment (bug):
I'm not sure this should be a terminating error. I think `WriteError` is more appropriate here, especially now that you accept pipeline input. A single failure of converting a string into a guid shouldn't keep conversions happening to other acceptable strings.

Code after:
        public SwitchParameter Empty { get; set; }

        /// <summary>
        /// Gets or sets the value to be converted to a Guid.
        /// </summary>
        [Parameter(Position = 0, ValueFromPipeline = true, ParameterSetName = "InputObject")]
        [System.Diagnostics.CodeAnalysis.AllowNull]
        public string InputObject { get; set; }

        /// <summary>
        /// Returns a Guid.
        /// </summary>
        protected override void ProcessRecord()
        {
            Guid? guid = null;

            if (ParameterSetName is "InputObject")
            {
                try
                {
                    guid = new(InputObject);
                }
                catch (Exception ex)
                {
                    ErrorRecord error = new(ex, "StringNotRecognizedAsGuid", ErrorCategory.InvalidArgument, null);
                    WriteError(error);
                }  
            }
            else
            {
                guid = ParameterSetName is "Empty" ? Guid.Empty : Guid.NewGuid();
            }

            WriteObject(guid);
        }
    }
}
Repository: PowerShell/PowerShell
File: src/Microsoft.PowerShell.Commands.Utility/commands/utility/NewGuidCommand.cs (C#)

Code before:
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.

#nullable enable

using System;
using System.Management.Automation;

namespace Microsoft.PowerShell.Commands
{
    /// <summary>
    /// The implementation of the "new-guid" cmdlet.
    /// </summary>
    [Cmdlet(VerbsCommon.New, "Guid", DefaultParameterSetName = "Default", HelpUri = "https://go.microsoft.com/fwlink/?LinkId=2097130")]
    [OutputType(typeof(Guid))]
    public class NewGuidCommand : PSCmdlet
    {
        /// <summary>
        /// Generates an instance of the Guid structure whose value is all zeros.
        /// </summary>
        [Parameter(ParameterSetName = "Empty")]
        public SwitchParameter Empty { get; set; }

        /// <summary>
        /// Converts a string to a Guid.
        /// </summary>
        [Parameter(Position = 0, ValueFromPipeline = true, ParameterSetName = "InputObject")]
        [System.Diagnostics.CodeAnalysis.AllowNull]
        public string InputObject { get; set; }

        /// <summary>
        /// Returns a Guid.
        /// </summary>
        protected override void ProcessRecord()
        {
            Guid? guid = null;

            if (ParameterSetName is "InputObject")
            {
                try
                {
                    guid = new(InputObject);
                }
                catch (Exception ex)

Review comment (suggestion):
```suggestion
        /// Gets or sets a value indicating that the cmdlet should return a Guid structure whose value is all zeros.
```

Code after:
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.

#nullable enable

using System;
using System.Management.Automation;

namespace Microsoft.PowerShell.Commands
{
    /// <summary>
    /// The implementation of the "new-guid" cmdlet.
    /// </summary>
    [Cmdlet(VerbsCommon.New, "Guid", DefaultParameterSetName = "Default", HelpUri = "https://go.microsoft.com/fwlink/?LinkId=2097130")]
    [OutputType(typeof(Guid))]
    public class NewGuidCommand : PSCmdlet
    {
        /// <summary>
        /// Gets or sets a value indicating that the cmdlet should return a Guid structure whose value is all zeros.
        /// </summary>
        [Parameter(ParameterSetName = "Empty")]
        public SwitchParameter Empty { get; set; }

        /// <summary>
        /// Gets or sets the value to be converted to a Guid.
        /// </summary>
        [Parameter(Position = 0, ValueFromPipeline = true, ParameterSetName = "InputObject")]
        [System.Diagnostics.CodeAnalysis.AllowNull]
        public string InputObject { get; set; }

        /// <summary>
        /// Returns a Guid.
        /// </summary>
        protected override void ProcessRecord()
        {
            Guid? guid = null;

            if (ParameterSetName is "InputObject")
            {
                try
                {
                    guid = new(InputObject);
                }
                catch (Exception ex)
Repository: PowerShell/PowerShell
File: src/Microsoft.PowerShell.Commands.Utility/commands/utility/NewGuidCommand.cs (C#)

Code before:
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.

using System;
using System.Management.Automation;

namespace Microsoft.PowerShell.Commands
{
    /// <summary>
    /// The implementation of the "new-guid" cmdlet.
    /// </summary>
    [Cmdlet(VerbsCommon.New, "Guid", HelpUri = "https://go.microsoft.com/fwlink/?LinkId=2097130")]
    [OutputType(typeof(Guid))]
    public class NewGuidCommand : Cmdlet
    {
        /// <summary>
        /// Returns a guid.
        /// </summary>
        protected override void EndProcessing()
        {
            WriteObject(Guid.NewGuid());
        }
    }
}


Review comment (suggestion):
Should InputObject be object type to follow PowerShell best practice? And here:
```
guid = new(InputObject.ToString());
```

Code after:
    {
        /// <summary>
        /// Gets or sets a value indicating that the cmdlet should return a Guid structure whose value is all zeros.
        /// </summary>
        [Parameter(ParameterSetName = "Empty")]
        public SwitchParameter Empty { get; set; }

        /// <summary>
        /// Gets or sets the value to be converted to a Guid.
        /// </summary>
        [Parameter(Position = 0, ValueFromPipeline = true, ParameterSetName = "InputObject")]
        [System.Diagnostics.CodeAnalysis.AllowNull]
        public string InputObject { get; set; }

        /// <summary>
        /// Returns a Guid.
        /// </summary>
        protected override void ProcessRecord()
        {
            Guid? guid = null;

            if (ParameterSetName is "InputObject")
            {
                try
                {
                    guid = new(InputObject);
                }
                catch (Exception ex)
                {
                    ErrorRecord error = new(ex, "StringNotRecognizedAsGuid", ErrorCategory.InvalidArgument, null);
                    WriteError(error);
                }  
            }
            else
            {
                guid = ParameterSetName is "Empty" ? Guid.Empty : Guid.NewGuid();
            }

            WriteObject(guid);
        }
    }
}
Repository: PowerShell/PowerShell
File: src/System.Management.Automation/engine/BytePipe.cs (C#)

Code before:
                fileName,
                resolvedEncoding: null,
                defaultEncoding: false,
                append,
                Force: true,
                NoClobber: false,
                out fileStream,
                streamWriter: out _,
                readOnlyFileInfo: out _,
                isLiteralPath: true);
        }
        catch (Exception e) when (e.Data.Contains(typeof(ErrorRecord)))
        {
            // The error record is attached to the exception when thrown to preserve
            // the call stack.
            ErrorRecord? errorRecord = e.Data[typeof(ErrorRecord)] as ErrorRecord;
            if (errorRecord is null)
            {
                throw;
            }

            e.Data.Remove(typeof(ErrorRecord));
            throw new RuntimeException(null, e, errorRecord);
        }

        ApplicationInsightsTelemetry.SendExperimentalUseData(
            ExperimentalFeature.PSNativeCommandPreserveBytePipe,
            "f");

        return new FileBytePipe(fileStream);
    }

    public override Task<Stream> GetStream(CancellationToken cancellationToken) => Task.FromResult(_stream);
}


Review comment (suggestion):
`PSNativeCommandPreserveBytePipe` is no longer an experimental feature, so this telemetry call should be removed.

Code after:
                fileName,
                resolvedEncoding: null,
                defaultEncoding: false,
                append,
                Force: true,
                NoClobber: false,
                out fileStream,
                streamWriter: out _,
                readOnlyFileInfo: out _,
                isLiteralPath: true);
        }
        catch (Exception e) when (e.Data.Contains(typeof(ErrorRecord)))
        {
            // The error record is attached to the exception when thrown to preserve
            // the call stack.
            ErrorRecord? errorRecord = e.Data[typeof(ErrorRecord)] as ErrorRecord;
            if (errorRecord is null)
            {
                throw;
            }

            e.Data.Remove(typeof(ErrorRecord));
            throw new RuntimeException(null, e, errorRecord);
        }

        ApplicationInsightsTelemetry.SendExperimentalUseData("PSNativeCommandPreserveBytePipe", "f");

        return new FileBytePipe(fileStream);
    }

    public override Task<Stream> GetStream(CancellationToken cancellationToken) => Task.FromResult(_stream);
}
Repository: PowerShell/PowerShell
File: src/Microsoft.PowerShell.Commands.Utility/commands/utility/Var.cs (C#)

Code before:
                _visibility = value;
            }
        }

        private SessionStateEntryVisibility? _visibility;

        /// <summary>
        /// The variable object should be passed down the pipeline.
        /// </summary>
        [Parameter]
        public SwitchParameter PassThru
        {
            get
            {
                return _passThru;
            }

            set
            {
                _passThru = value;
            }
        }

        private bool _passThru;

        private bool _nameIsFormalParameter;
        private bool _valueIsFormalParameter;
        #endregion parameters

        /// <summary>
        /// Checks to see if the name and value parameters were bound as formal parameters.
        /// </summary>
        protected override void BeginProcessing()
        {
            if (Name != null && Name.Length > 0)
            {
                _nameIsFormalParameter = true;
            }

            if (Value != AutomationNull.Value)
            {
                _valueIsFormalParameter = true;
            }
        }

        /// <summary>
        /// If name and value are both specified as a formal parameters, then
        /// just ignore the incoming objects in ProcessRecord.
        /// If name is a formal parameter but the value is coming from the pipeline,
        /// then accumulate the values in the valueList and set the variable during
        /// EndProcessing().

Review comment (suggestion):
```suggestion
        /// Append to the variable if it exists.
```

Code after:
                _visibility = value;
            }
        }

        private SessionStateEntryVisibility? _visibility;

        /// <summary>
        /// The variable object should be passed down the pipeline.
        /// </summary>
        [Parameter]
        public SwitchParameter PassThru
        {
            get
            {
                return _passThru;
            }

            set
            {
                _passThru = value;
            }
        }

        private bool _passThru;

        /// <summary>
        /// Gets whether we will append to the variable if it exists.
        /// </summary>
        [Parameter]
        [Experimental(ExperimentalFeature.PSRedirectToVariable, ExperimentAction.Show)]
        public SwitchParameter Append { get; set; }

        private bool _nameIsFormalParameter;
        private bool _valueIsFormalParameter;
        #endregion parameters

        /// <summary>
        /// Checks to see if the name and value parameters were bound as formal parameters.
        /// </summary>
        protected override void BeginProcessing()
        {
            if (Name != null && Name.Length > 0)
            {
                _nameIsFormalParameter = true;
            }

            if (Value != AutomationNull.Value)
            {
                _valueIsFormalParameter = true;
            }
Repository: PowerShell/PowerShell
File: test/powershell/engine/Basic/RegisterAssemblyResolverEarly.ps1 (PowerShell)

Code before:
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT License.

Describe "Assembly resolvers should be registered early at startup" -Tags "CI" {

    ## The PKI module requires loading an assembly from GAC, and thus depends on the PowerShell assembly resolver to work.
    It "Can load the PKI module with 'pwsh -ExecutionPolicy bypass -NoProfile -c `"Import-Module PKI`"'" -Skip:(!$IsWindows) {
        $pwsh = Join-Path $PSHOME "pwsh.exe"
        $out = & $pwsh -ExecutionPolicy bypass -NoProfile -c "Import-Module PKI; Get-Module | % name"
        $out | Should -BeExactly "PKI"
    }
}


Review comment (suggestion):
This shouldn't be necessary since I believe we had a change so that $PSHOME is prepended to the path so that `pwsh` always starts an instance of the current pwsh

Code after:
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT License.

Describe "Assembly resolvers should be registered early at startup" -Tags "CI" {

    ## The PKI module requires loading an assembly from GAC, and thus depends on the PowerShell assembly resolver to work.
    It "Can load the PKI module with 'pwsh -ExecutionPolicy bypass -NoProfile -c `"Import-Module PKI`"'" -Skip:(!$IsWindows) {
        ## Use 'Bypass' execution policy so that it doesn't trigger 'AuthorizationManager' which would trigger 'ClrFacade' initialization.
        ## We want to make sure even if 'ClrFacade' is not hit during startup, the resolvers are still registered early enough.
        $out = pwsh -ExecutionPolicy bypass -NoProfile -c "Import-Module PKI; Get-Module | % name"
        $out | Should -BeExactly "PKI"
    }
}
Repository: PowerShell/PowerShell
File: src/System.Management.Automation/engine/runtime/Operations/ArrayOps.cs (C#)

Code before:
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.

// ReSharper disable UnusedMember.Global

using System.Collections.Generic;
using System.Globalization;
using System.Management.Automation.Internal;
using System.Management.Automation.Runspaces;

namespace System.Management.Automation
{
    internal static class ArrayOps
    {
        internal static object[] SlicingIndex(object target, object[] indexes, Func<object, object, object> indexer)
        {
            var result = new object[indexes.Length];
            int j = 0;
            foreach (object t in indexes)
            {
                var value = indexer(target, t);
                if (value != AutomationNull.Value)
                {
                    result[j++] = value;
                }
            }

            if (j != indexes.Length)
            {
                var shortResult = new object[j];
                Array.Copy(result, shortResult, j);
                return shortResult;
            }

            return result;
        }

        /// <summary>
        /// Efficiently multiplies collection by integer.
        /// </summary>
        /// <param name="array">Collection to multiply.</param>
        /// <param name="times">Number of times the collection is to be multiplied/copied.</param>
        /// <returns>Collection multiplied by integer.</returns>

Review comment (performance):
If we look original issue the performance problem is only with _loops_. In the case it would be better to increase the size on an empirical value more than one - 4, 8, 16. This will significantly reduce the number of unnecessary array copies.

Code after:
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.

// ReSharper disable UnusedMember.Global

using System.Collections.Generic;
using System.Globalization;
using System.Management.Automation.Internal;
using System.Management.Automation.Runspaces;

namespace System.Management.Automation
{
    internal static class ArrayOps
    {
        internal static object AddObjectArray(object[] lhs, object rhs)
        {
            int newIdx = lhs.Length;
            Array.Resize(ref lhs, newIdx + 1);
            lhs[newIdx] = rhs;

            return lhs;
        }

        internal static object[] SlicingIndex(object target, object[] indexes, Func<object, object, object> indexer)
        {
            var result = new object[indexes.Length];
            int j = 0;
            foreach (object t in indexes)
            {
                var value = indexer(target, t);
                if (value != AutomationNull.Value)
                {
                    result[j++] = value;
                }
            }

            if (j != indexes.Length)
            {
                var shortResult = new object[j];
                Array.Copy(result, shortResult, j);
                return shortResult;
            }