ronantakizawa/codereview-bench huggingface dataset:
Repository: unoplatform/uno
File: src/Uno.UWP/Globalization/DateTimeFormatting/DateTimeFormatter.cs (C#)

Code before:
			{
				return string.Empty;
			}

			char singleQuoteChar = '\'';
			var builder = new StringBuilder();
			int i = 0;
			int len = str.Length;

			while (i < len)
			{
				char currentChar = str[i];

				// Handle quoted section (literals) "MMMM 'de' yyyy"
				if (currentChar == singleQuoteChar)
				{
					i++;
					var literal = new StringBuilder();

					while (i < len)
					{
						if (str[i] == singleQuoteChar)
						{
							if (i + 1 < len && str[i + 1] == singleQuoteChar)
							{
								literal.Append(singleQuoteChar);
								i += 2;
							}
							else
							{
								// End of quoted section
								i++;
								break;
							}
						}
						else
						{
							literal.Append(str[i]);
							i++;
						}
					}

					builder.Append(literal);
				}
				else
				{
					char lastChar = currentChar;
					int count = 1;
					i++;

					while (i < len && str[i] == lastChar && str[i] != '\'')

Review comment (security):
here we have the case for triple `'''` in a row, which you add as a `'`, this doesnt sound right
according to https://learn.microsoft.com/en-us/dotnet/standard/base-types/custom-date-and-time-format-strings, it would be open-close-empty-literal and open-literal...
the only way to insert quote (both single or double) would be to use `\`-escape or weave in another different quote-sign literal (`'"'` or `"'"` d-quote between s-quote or vise-versa)

just test with `DateTime.Now.ToString("MMMM '''''''''de' yyyy")` it should produces `December de 2025`
but this formatter produces the intermediate value of: `{month.full} ''''de {year.full}`

Code after:
			{
				return string.Empty;
			}

			var builder = new StringBuilder();

			foreach (var part in StringLiteralRegex().Split(str))
			{
				// skip empty block
				if (part.Length == 0)
				{
					continue;
				}
				// add quoted literal as is, without the quotes
				else if (part.StartsWith('\''))
				{
					if (part.Length > 2)
					{
						builder.Append(part[1..^1]);
					}
				}
				// for non-quoted parts, further segment them by grouping repeated character(s)
				else
				{
					foreach (var segment in RepeatedCharactersRegex().EnumerateMatches(part))
					{
						AddToBuilder(builder, part[segment.Index], segment.Length);
					}
				}
			}

			return builder.ToString();
		}
	}

	[GeneratedRegex(@"('[^']+')")]
	private static partial Regex StringLiteralRegex();

	[GeneratedRegex(@"(.)(\1+)?")]
	private static partial Regex RepeatedCharactersRegex();
}
Repository: unoplatform/uno
File: src/Uno.UWP/Globalization/DateTimeFormatting/DateTimeFormatter.cs (C#)

Code before:
					}

					while (count >= 1)
					{
						builder.Append("{timezone.abbreviated(1)}");
						count -= 1;
					}

					break;

				default:
					builder.Append(lastChar, count);
					break;
			}
		}

		string ConstructPattern(string str)
		{
			if (string.IsNullOrEmpty(str))
			{
				return string.Empty;
			}

			var builder = new StringBuilder();

			foreach (var part in IsWithinSingleQuotesRegex().Split(str))
			{
				// skip empty block
				if (part.Length == 0)
				{
					continue;
				}
				// add quoted literal as is, without the quotes
				else if (part.StartsWith('\''))
				{
					if (part.Length > 2)
					{
						builder.Append(part[1..^1]);
					}
				}
				// for non-quoted parts, further segment them by grouping repeated character(s)
				else
				{
					foreach (var segment in DateTimeFormatPartsRegex().EnumerateMatches(part))
					{
						AddToBuilder(builder, part[segment.Index], segment.Length);
					}
				}
			}

			return builder.ToString();

Review comment (suggestion):
If I get it correctly, this can be done much more easily without regex.
i.e, keep a track of boolean variable e.g, `bool isInLiteral = false`
Then when looping, if `isInLiteral` is true, just append directly to the builder without calling `AddToBuilder`.

And when you encounter a `'`, flip the `isInLiteral`.

Code after:
					}

					while (count >= 1)
					{
						builder.Append("{timezone.abbreviated(1)}");
						count -= 1;
					}

					break;

				default:
					builder.Append(lastChar, count);
					break;
			}
		}

		string ConstructPattern(string str)
		{
			if (string.IsNullOrEmpty(str))
			{
				return string.Empty;
			}

			var builder = new StringBuilder();

			foreach (var part in StringLiteralRegex().Split(str))
			{
				// skip empty block
				if (part.Length == 0)
				{
					continue;
				}
				// add quoted literal as is, without the quotes
				else if (part.StartsWith('\''))
				{
					if (part.Length > 2)
					{
						builder.Append(part[1..^1]);
					}
				}
				// for non-quoted parts, further segment them by grouping repeated character(s)
				else
				{
					foreach (var segment in RepeatedCharactersRegex().EnumerateMatches(part))
					{
						AddToBuilder(builder, part[segment.Index], segment.Length);
					}
				}
			}

			return builder.ToString();
Repository: unoplatform/uno
File: src/Uno.UI/UI/Xaml/Controls/ToolTip/ToolTipService.cs (C#)

Code before:
		}
	}

	private static void OnPointerEntered(object sender, PointerRoutedEventArgs e)
	{
		// Multiple elements can all receive the same PointerEntered at once (from inner-most to outer-most).
		// In this case, the inner-most one is the only one that should be shown,
		// so we are dropping any subsequent events from this frame-id.
		if (e.FrameId == m_LastEnteredFrameId) return;

		if (sender is FrameworkElement owner && GetActualToolTipObject(owner) is { } toolTip)
		{
			if (toolTip.IsOpen) return;

			if (m_OpenTimer is null)
			{
				m_OpenTimer = new DispatcherTimer();
				m_OpenTimer.Interval = TimeSpan.FromMilliseconds(FeatureConfiguration.ToolTip.ShowDelay);
				m_OpenTimer.Tick += OnOpenTimerTick;
			}
			m_LastEnteredFrameId = e.FrameId;
			OpenToolTipImpl(toolTip);
		}
	}

	private static void OnPointerExitedOrCanceledOrCaptureLostOrLostFocus(object sender, object e)
	{
		if (sender is FrameworkElement owner && GetActualToolTipObject(owner) is { } toolTip)
		{
			CloseToolTipImpl(toolTip);
		}
	}

	private static void OnKeyDown(object sender, KeyRoutedEventArgs args)
	{
		if (sender is FrameworkElement owner && GetActualToolTipObject(owner) is { } toolTip)
		{
			switch (args.Key)
			{
				case VirtualKey.Up:
				case VirtualKey.Down:
				case VirtualKey.Left:
				case VirtualKey.Right:
					return;
			}

			CloseToolTipImpl(toolTip);
		}
	}

	private static void OnPointerPressed(object sender, PointerRoutedEventArgs e)

Review comment (suggestion):
```suggestion
	private static void CloseToolTipImpl(object sender, object e)
```

Code after:
		{
			if (toolTip.IsOpen) return;

			EnsureOpenTimer();
			OpenToolTipImpl(toolTip);
		}
	}

	private static void OnPointerEntered(object sender, PointerRoutedEventArgs e)
	{
		// Multiple elements can all receive the same PointerEntered at once (from inner-most to outer-most).
		// In this case, the inner-most one is the only one that should be shown,
		// so we are dropping any subsequent events from this frame-id.
		if (e.FrameId == m_LastEnteredFrameId) return;

		if (sender is FrameworkElement owner && GetActualToolTipObject(owner) is { } toolTip)
		{
			if (toolTip.IsOpen) return;

			EnsureOpenTimer();
			m_LastEnteredFrameId = e.FrameId;
			OpenToolTipImpl(toolTip);
		}
	}

	private static void OnPointerOutOrLostFocus(object sender, object e)
	{
		if (sender is FrameworkElement owner && GetActualToolTipObject(owner) is { } toolTip)
		{
			CloseToolTipImpl(toolTip);
		}
	}

	private static void OnKeyDown(object sender, KeyRoutedEventArgs args)
	{
		if (sender is FrameworkElement owner && GetActualToolTipObject(owner) is { } toolTip)
		{
			switch (args.Key)
			{
				case VirtualKey.Up:
				case VirtualKey.Down:
				case VirtualKey.Left:
				case VirtualKey.Right:
					return;
			}

			CloseToolTipImpl(toolTip);
		}
	}

	private static void OnPointerPressed(object sender, PointerRoutedEventArgs e)
Repository: unoplatform/uno
File: src/Uno.UI.RuntimeTests/Tests/Windows_System/Given_BrowserVirtualKeyHelper.cs (C#)

Code before:
using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Windows.System;

#if __WASM__
using Uno.UI.RuntimeTests.Helpers;
#endif

namespace Uno.UI.RuntimeTests.Tests.Windows_System
{
	[TestClass]
	public class Given_BrowserVirtualKeyHelper
	{
#if __WASM__
		[TestMethod]
		[RunsOnUIThread]
		public void When_FromCode_ControlLeft_Returns_Control()
		{
			var result = BrowserVirtualKeyHelper.FromCode("ControlLeft");
			Assert.AreEqual(VirtualKey.Control, result, "ControlLeft should map to VirtualKey.Control");
		}

		[TestMethod]
		[RunsOnUIThread]
		public void When_FromCode_ControlRight_Returns_Control()
		{
			var result = BrowserVirtualKeyHelper.FromCode("ControlRight");
			Assert.AreEqual(VirtualKey.Control, result, "ControlRight should map to VirtualKey.Control");
		}

		[TestMethod]
		[RunsOnUIThread]
		public void When_FromCode_ShiftLeft_Returns_Shift()
		{
			var result = BrowserVirtualKeyHelper.FromCode("ShiftLeft");
			Assert.AreEqual(VirtualKey.Shift, result, "ShiftLeft should map to VirtualKey.Shift");
		}

		[TestMethod]

Review comment (suggestion):
@copilot Actually the class is available generally, so drop the #if, but you can still use `PlatformCondition` for WASM native + skia on the test class itself

Code after:
using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Uno.UI.RuntimeTests.Helpers;
using Windows.System;

#if HAS_UNO
namespace Uno.UI.RuntimeTests.Tests.Windows_System
{
	[TestClass]
	[PlatformCondition(ConditionMode.Include, RuntimeTestPlatforms.Wasm)]
	public class Given_BrowserVirtualKeyHelper
	{
		[TestMethod]
		[RunsOnUIThread]
		public void When_FromCode_ControlLeft_Returns_Control()
		{
			var result = BrowserVirtualKeyHelper.FromCode("ControlLeft");
			Assert.AreEqual(VirtualKey.Control, result, "ControlLeft should map to VirtualKey.Control");
		}

		[TestMethod]
		[RunsOnUIThread]
		public void When_FromCode_ControlRight_Returns_Control()
		{
			var result = BrowserVirtualKeyHelper.FromCode("ControlRight");
			Assert.AreEqual(VirtualKey.Control, result, "ControlRight should map to VirtualKey.Control");
		}

		[TestMethod]
		[RunsOnUIThread]
		public void When_FromCode_ShiftLeft_Returns_Shift()
		{
			var result = BrowserVirtualKeyHelper.FromCode("ShiftLeft");
			Assert.AreEqual(VirtualKey.Shift, result, "ShiftLeft should map to VirtualKey.Shift");
		}

		[TestMethod]
		[RunsOnUIThread]
		public void When_FromCode_ShiftRight_Returns_Shift()
Repository: unoplatform/uno
File: src/Uno.UI/UI/Xaml/Controls/TextBlock/TextBlock.skia.cs (C#)

Code before:
			RecalculateSubscribeToPointerEvents();
			UpdateSelectionRendering();
		}

		private void UpdateSelectionRendering()
		{
			if (OwningTextBox is null) // TextBox manages RenderSelection itself
			{
				RenderSelection = IsTextSelectionEnabled && (IsFocused || (_contextMenu?.IsOpen ?? false));
			}
		}

		protected override Size ArrangeOverride(Size finalSize)
		{
			Visual.Compositor.InvalidateRender(Visual);
			var padding = Padding;
			var availableSizeWithoutPadding = finalSize.Subtract(padding);
			ParsedText = new UnicodeText(
				availableSizeWithoutPadding,
				Inlines.TraversedTree.leafTree,
				GetDefaultFontDetails(),
				MaxLines,
				(float)LineHeight,
				LineStackingStrategy,
				FlowDirection,
				(OwningTextBox as IDependencyObjectStoreProvider)?.Store.GetCurrentHighestValuePrecedence(TextBox.TextAlignmentProperty) is DependencyPropertyValuePrecedences.DefaultValue ? null : TextAlignment,
				TextWrapping,
				out var arrangedSize);
			_lastInlinesArrangeWithPadding = arrangedSize.Add(padding);

			var result = base.ArrangeOverride(finalSize);
			UpdateIsTextTrimmed();

			return result;
		}

		internal bool RenderSelection
		{
			set
			{
				if (_renderSelection != value)
				{
					_renderSelection = value;
					InvalidateInlineAndRequireRepaint();
				}
			}
		}

		internal (int index, CompositionBrush brush)? RenderCaret
		{
			set

Review comment (suggestion):
```suggestion
				(OwningTextBox as IDependencyObjectStoreProvider)
					?.Store.GetCurrentHighestValuePrecedence(TextBox.TextAlignmentProperty)
					is DependencyPropertyValuePrecedences.DefaultValue
					? null : TextAlignment,
```

Code after:
			var success = Matrix3x2.Invert(transform, out var inverted);
			return success && inverted.Transform(LayoutSlotWithMarginsAndAlignments).Contains(point);
		}

		partial void OnIsTextSelectionEnabledChangedPartial()
		{
			RecalculateSubscribeToPointerEvents();
			UpdateSelectionRendering();
		}

		private void UpdateSelectionRendering()
		{
			if (OwningTextBox is null) // TextBox manages RenderSelection itself
			{
				RenderSelection = IsTextSelectionEnabled && (IsFocused || (_contextMenu?.IsOpen ?? false));
			}
		}

		protected override Size ArrangeOverride(Size finalSize)
		{
			Visual.Compositor.InvalidateRender(Visual);
			var padding = Padding;
			var availableSizeWithoutPadding = finalSize.Subtract(padding);
			ParsedText = ParseText(availableSizeWithoutPadding, out var arrangedSize);

			_lastInlinesArrangeWithPadding = arrangedSize.Add(padding);

			var result = base.ArrangeOverride(finalSize);
			UpdateIsTextTrimmed();

			return result;
		}

		internal bool RenderSelection
		{
			set
			{
				if (_renderSelection != value)
				{
					_renderSelection = value;
					InvalidateInlineAndRequireRepaint();
				}
			}
		}

		internal (int index, CompositionBrush brush)? RenderCaret
		{
			set
			{
				if (_caretPaint != value)
				{
Repository: unoplatform/uno
File: src/Uno.UI.Runtime.Skia.AppleUIKit/UI/Xaml/Controls/TextBox/MultilineInvisibleTextBoxDelegate.cs (C#)

Code before:
	{
		return true;
	}

	/// <summary>
	/// Corresponds to a gain of focus
	/// </summary>
	public override void EditingStarted(UITextView textView)
	{
		if (_textBoxViewExtension.GetTarget()?.Owner.TextBox is TextBox textBox && textBox.FocusState == FocusState.Unfocused)
		{
			textBox.Focus(FocusState.Pointer);
		}
	}

	/// <summary>
	/// Corresponds to a loss of focus
	/// </summary>
	public override void EditingEnded(UITextView textView)
	{
		var bindableTextView = textView as MultilineInvisibleTextBoxView;
		bindableTextView?.OnTextChanged();

		if (_textBoxViewExtension.GetTarget()?.Owner.TextBox is TextBox { FocusState: not FocusState.Unfocused } textBox)
		{
			textBox.Unfocus();
		}
	}
}


Review comment (suggestion):
I'm wondering if we can get the "directionality" of the selection as well? i.e. whether end of the selection is at the left or right of the selection. If so, we can use TextBox.SelectInternal instead of TextBox.Select, which can handle "negative directions".

Code after:
			{
				// When replacing text from pasting (multiple characters at once)
				// we should only allow it (return true) when the new text length
				// is lower or equal to the allowed length (TextBox.MaxLength)
				var newLength = (textBoxView.Text?.Length ?? 0) + replacementString.Length - range.Length;
				return newLength <= textBox.MaxLength;
			}
		}

		return true;
	}

	public override void SelectionChanged(UITextView textView)
	{
		SyncSelectionToTextView(textView);
	}

	private void SyncSelectionToTextView(UITextView textView)
	{
		if (_textBoxViewExtension.GetTarget()?.Owner.TextBox is { } textBox &&
		textView.SelectedTextRange is { } selectedRange)
		{
			var selectionStart = (int)textView.GetOffsetFromPosition(textView.BeginningOfDocument, selectedRange.Start);
			var selectionEnd = (int)textView.GetOffsetFromPosition(textView.BeginningOfDocument, selectedRange.End);
			textBox.Select(selectionStart, selectionEnd - selectionStart);
		}
	}

	public override bool ShouldEndEditing(UITextView textView)
	{
		return true;
	}

	/// <summary>
	/// Corresponds to a gain of focus
	/// </summary>
	public override void EditingStarted(UITextView textView)
	{
		if (_textBoxViewExtension.GetTarget()?.Owner.TextBox is TextBox textBox && textBox.FocusState == FocusState.Unfocused)
		{
			textBox.Focus(FocusState.Pointer);
		}
	}

	/// <summary>
	/// Corresponds to a loss of focus
	/// </summary>
	public override void EditingEnded(UITextView textView)
	{
		var bindableTextView = textView as MultilineInvisibleTextBoxView;
		bindableTextView?.OnTextChanged();
Repository: unslothai/unsloth
File: unsloth/models/_utils.py (Python)

Code before:

    return loftq_config


def _prepare_model_for_qat(model: torch.nn.Module, qat_scheme: str) -> torch.nn.Module:
    """
    Transform a model for Quantization-Aware Training (QAT) during fine-tuning.

    On a high level, this means fake quantizing the base (frozen) model during training.
    Fake quantization refers to simulating quantization numerics in high precision (e.g. bf16).
    This helps mitigate quantization degradations when the model is quantized after training.

    QAT can be optionally combined with LoRA fine-tuning to for additional throughput improvement.
    For more details: https://dev-discuss.pytorch.org/t/speeding-up-qat-by-1-89x-with-lora/2700
    """
    filter_fn = None
    if qat_scheme == "fp8-int4":
        group_size = 128
        base_config = Float8DynamicActivationInt4WeightConfig()
        filter_fn = lambda m, _: isinstance(m, torch.nn.Linear) and m.in_features >= group_size
    elif qat_scheme == "fp8-fp8":
        base_config = Float8DynamicActivationFloat8WeightConfig(granularity=PerRow())
    else:
        raise ValueError(f"Unexpected QAT scheme {qat_scheme}")
    pass
    quantize_(model, QATConfig(base_config, step="prepare"), filter_fn=filter_fn)
    return model
pass


Review comment (suggestion):
Wait does this need an import:
```python
 from torchao.quantization import ( ...
        )
```

Code after:

    return loftq_config


def _prepare_model_for_qat(model: torch.nn.Module, qat_scheme: str) -> torch.nn.Module:
    """
    Transform a model for Quantization-Aware Training (QAT) during fine-tuning.

    On a high level, this means fake quantizing the base (frozen) model during training.
    Fake quantization refers to simulating quantization numerics in high precision (e.g. bf16).
    This helps mitigate quantization degradations when the model is quantized after training.

    QAT can be optionally combined with LoRA fine-tuning to for additional throughput improvement.
    For more details: https://dev-discuss.pytorch.org/t/speeding-up-qat-by-1-89x-with-lora/2700
    """
    from torchao.quantization import (
        Float8DynamicActivationInt4WeightConfig,
        Float8DynamicActivationFloat8WeightConfig,
        PerRow,
        quantize_,
    )
    from torchao.quantization.qat import QATConfig
    filter_fn = None
    if qat_scheme == "fp8-int4":
        group_size = 128
        base_config = Float8DynamicActivationInt4WeightConfig()
        filter_fn = lambda m, _: isinstance(m, torch.nn.Linear) and m.in_features >= group_size
    elif qat_scheme == "fp8-fp8":
        base_config = Float8DynamicActivationFloat8WeightConfig(granularity=PerRow())
    else:
        raise ValueError(f"Unexpected QAT scheme {qat_scheme}")
    pass
    quantize_(model, QATConfig(base_config, step="prepare"), filter_fn=filter_fn)
    return model
pass
Repository: veler/DevToys
File: src/dev/impl/DevToys/ViewModels/Tools/Text/StringUtilities/StringUtilitiesToolViewModel.cs (C#)

Code before:
                    }
                }
            }


            lock (_lockObject)
            {
                _forbidBackup = true;
                Text = snakeCaseStringBuilder.ToString();
                _forbidBackup = false;
            }
        }

        #endregion

        #region AlternatingCaseCommand

        public IRelayCommand AlternatingCaseCommand { get; }

        private void ExecuteAlternatingCaseCommand()
        {
            char[]? titleCaseString = _textBackup?.ToCharArray();
            if (titleCaseString is null)
            {
                return;
            }

            bool lowerCase = true;
            for (int i = 0; i < titleCaseString.Length; i++)
            {
                if (lowerCase)
                {
                    titleCaseString[i] = char.ToLowerInvariant(titleCaseString[i]);
                }
                else
                {
                    titleCaseString[i] = char.ToUpperInvariant(titleCaseString[i]);
                }

                lowerCase = !lowerCase;
            }

            lock (_lockObject)
            {
                _forbidBackup = true;
                Text = new string(titleCaseString);
                _forbidBackup = false;
            }
        }

        #endregion

Review comment (suggestion):
Please use `string.IsNullOrEmpty(text)` instead, since `"" != null`.

Code after:
            {
                if (lowerCase)
                {
                    titleCaseString[i] = char.ToLowerInvariant(titleCaseString[i]);
                }
                else
                {
                    titleCaseString[i] = char.ToUpperInvariant(titleCaseString[i]);
                }

                lowerCase = !lowerCase;
            }

            SetTextWithoutBackup(new string(titleCaseString));
        }

        #endregion

        #region AlphabetizeCommand

        public IRelayCommand AlphabetizeCommand { get; }

        private void ExecuteAlphabetizeCommand()
        {
            string? text = _textBackup;
            if (text is null)
            {
                return;
            }

            IOrderedEnumerable<string> lines = text.Split('\r').OrderBy(line => line, StringComparer.CurrentCulture);
            text = string.Join('\r', lines);

            SetTextWithoutBackup(text);
        }

        #endregion

        #region ReverseAlphabetizeCommand

        public IRelayCommand ReverseAlphabetizeCommand { get; }

        private void ExecuteReverseAlphabetizeCommand()
        {
            string? text = _textBackup;
            if (text is null)
            {
                return;
            }

            IOrderedEnumerable<string> lines = text.Split('\r').OrderByDescending(line => line, StringComparer.CurrentCulture);