language
stringclasses
1 value
repo
stringclasses
133 values
path
stringlengths
13
229
class_span
dict
source
stringlengths
14
2.92M
target
stringlengths
1
153
csharp
ServiceStack__ServiceStack
ServiceStack/src/ServiceStack.Interfaces/Redis/ItemRef.cs
{ "start": 31, "end": 127 }
public class ____ { public string Id { get; set; } public string Item { get; set; } }
ItemRef
csharp
dotnet__aspnetcore
src/Http/Routing/src/Matching/EndpointComparer.cs
{ "start": 3990, "end": 4789 }
private sealed class ____ : IComparer<Endpoint> { public static readonly IComparer<Endpoint> Instance = new PrecedenceComparer(); public int Compare(Endpoint? x, Endpoint? y) { var routeEndpointX = x as RouteEndpoint; var routeEndpointY = y as RouteEndpoint; if (routeEndpointX != null) { if (routeEndpointY != null) { return routeEndpointX.RoutePattern.InboundPrecedence .CompareTo(routeEndpointY.RoutePattern.InboundPrecedence); } return 1; } else if (routeEndpointY != null) { return -1; } return 0; } } }
PrecedenceComparer
csharp
xunit__xunit
src/xunit.v3.core.tests/Runners/XunitTestClassRunnerTests.cs
{ "start": 22408, "end": 23686 }
public class ____ { [Fact] public static async ValueTask UsesCustomTestOrderer() { var testCase = TestData.XunitTestCase<ClassUnderTest>(nameof(ClassUnderTest.Passing)); var runner = new TestableXunitTestClassRunner(testCase); await runner.RunAsync(); Assert.IsType<CustomTestCaseOrderer>(runner.RunTestMethodsAsync_TestCaseOrderer); } [Fact] public static async ValueTask SettingTestCaseOrdererWithThrowingConstructorLogsDiagnosticMessage() { var spy = SpyMessageSink.Capture(); TestContextInternal.Current.DiagnosticMessageSink = spy; var testCase = TestData.XunitTestCase<TestClassWithCtorThrowingTestCaseOrder>(nameof(ClassUnderTest.Passing)); var runner = new TestableXunitTestClassRunner(testCase); await runner.RunAsync(); var diagnosticMessage = Assert.Single(spy.Messages.Cast<IDiagnosticMessage>()); Assert.StartsWith("Class-level test case orderer 'XunitTestClassRunnerTests+TestCaseOrderer+MyCtorThrowingTestCaseOrderer' for test class 'XunitTestClassRunnerTests+TestCaseOrderer+TestClassWithCtorThrowingTestCaseOrder' threw 'System.DivideByZeroException' during construction: Attempted to divide by zero.", diagnosticMessage.Message); } [TestCaseOrderer(typeof(MyCtorThrowingTestCaseOrderer))]
TestCaseOrderer
csharp
icsharpcode__ILSpy
ILSpy.BamlDecompiler.Tests/Mocks/AvalonDock.cs
{ "start": 3247, "end": 3369 }
public enum ____ { DockablePane, DocumentPane, DockableFloatingWindow, DocumentFloatingWindow } }
ContextMenuElement
csharp
AvaloniaUI__Avalonia
src/Browser/Avalonia.Browser/BrowserDataTransferHelper.cs
{ "start": 265, "end": 2521 }
internal static class ____ { public static DataFormat[] GetReadableItemFormats(JSObject readableDataItem /* JS type: ReadableDataItem */) { var formatStrings = InputHelper.GetReadableDataItemFormats(readableDataItem); var formats = new DataFormat[formatStrings.Length]; var hasSupportedImage = false; for (var i = 0; i < formatStrings.Length; ++i) { var formatString = formatStrings[i]; hasSupportedImage = formatString is "image/png"; formats[i] = BrowserDataFormatHelper.ToDataFormat(formatString); } if (hasSupportedImage) formats = [..formats, DataFormat.Bitmap]; return formats; } public static object? TryGetValue(JSObject? readableDataValue /* JS type: ReadableDataValue */, DataFormat format) { object? data = readableDataValue?.GetPropertyAsString("type") switch { "string" => readableDataValue.GetPropertyAsString("value"), "bytes" => readableDataValue.GetPropertyAsByteArray("value"), "file" => readableDataValue.GetPropertyAsJSObject("value") is { } jsFile ? new JSStorageFile(jsFile) : null, _ => null }; if (data is null) return null; if (DataFormat.Text.Equals(format)) return data as string; if (DataFormat.File.Equals(format)) return data as IStorageItem; if (format is DataFormat<string>) { return data switch { string text => text, byte[] bytes => Encoding.UTF8.GetString(bytes), _ => null }; } if (DataFormat.Bitmap.Equals(format)) { if (data is byte[] bytes) { using var stream = new MemoryStream(bytes); return new Bitmap(stream); } return null; } if (format is DataFormat<byte[]>) { return data switch { byte[] bytes => bytes, string text => Encoding.UTF8.GetBytes(text), _ => null }; } return null; } }
BrowserDataTransferHelper
csharp
dotnet__aspnetcore
src/SignalR/server/SignalR/test/Microsoft.AspNetCore.SignalR.Tests/Internal/TypedClientBuilderTests.cs
{ "start": 11120, "end": 11269 }
public interface ____ { [HubMethodName("Method")] Task MethodAsync(string arg1, int arg2, object arg3); }
IRenamedTestClient
csharp
ChilliCream__graphql-platform
src/GreenDonut/src/GreenDonut/PromiseCacheOwner.cs
{ "start": 266, "end": 1512 }
public sealed class ____ : IDisposable { private readonly ObjectPool<PromiseCache> _pool; private readonly PromiseCache _cache; private bool _disposed; /// <summary> /// Rents a new cache from <see cref="PromiseCachePool.Shared"/>. /// </summary> public PromiseCacheOwner(IPromiseCacheInterceptor? interceptor = null) { _pool = PromiseCachePool.Shared; _cache = PromiseCachePool.Shared.Get(); _cache.Interceptor = interceptor; } /// <summary> /// Rents a new cache from the given <paramref name="pool"/>. /// </summary> public PromiseCacheOwner(ObjectPool<PromiseCache> pool, IPromiseCacheInterceptor? interceptor = null) { _pool = pool ?? throw new ArgumentNullException(nameof(pool)); _cache = pool.Get(); _cache.Interceptor = interceptor; } /// <summary> /// Gets the rented cache. /// </summary> public IPromiseCache Cache => _cache; /// <summary> /// Returns the rented cache back to the <see cref="ObjectPool{TaskCache}"/>. /// </summary> public void Dispose() { if (!_disposed) { _pool.Return(_cache); _disposed = true; } } }
PromiseCacheOwner
csharp
dotnet__efcore
src/EFCore.Design/Scaffolding/Internal/CSharpDbContextGenerator.cs
{ "start": 23488, "end": 31410 }
public class ____ { #region Fields private global::System.Text.StringBuilder generationEnvironmentField; private global::System.CodeDom.Compiler.CompilerErrorCollection errorsField; private global::System.Collections.Generic.List<int> indentLengthsField; private string currentIndentField = ""; private bool endsWithNewline; private global::System.Collections.Generic.IDictionary<string, object> sessionField; #endregion #region Properties /// <summary> /// The string builder that generation-time code is using to assemble generated output /// </summary> public System.Text.StringBuilder GenerationEnvironment { get { if ((this.generationEnvironmentField == null)) { this.generationEnvironmentField = new global::System.Text.StringBuilder(); } return this.generationEnvironmentField; } set { this.generationEnvironmentField = value; } } /// <summary> /// The error collection for the generation process /// </summary> public System.CodeDom.Compiler.CompilerErrorCollection Errors { get { if ((this.errorsField == null)) { this.errorsField = new global::System.CodeDom.Compiler.CompilerErrorCollection(); } return this.errorsField; } } /// <summary> /// A list of the lengths of each indent that was added with PushIndent /// </summary> private System.Collections.Generic.List<int> indentLengths { get { if ((this.indentLengthsField == null)) { this.indentLengthsField = new global::System.Collections.Generic.List<int>(); } return this.indentLengthsField; } } /// <summary> /// Gets the current indent we use when adding lines to the output /// </summary> public string CurrentIndent { get { return this.currentIndentField; } } /// <summary> /// Current transformation session /// </summary> public virtual global::System.Collections.Generic.IDictionary<string, object> Session { get { return this.sessionField; } set { this.sessionField = value; } } #endregion #region Transform-time helpers /// <summary> /// Write text directly into the generated output /// </summary> public void Write(string textToAppend) { if (string.IsNullOrEmpty(textToAppend)) { return; } // If we're starting off, or if the previous text ended with a newline, // we have to append the current indent first. if (((this.GenerationEnvironment.Length == 0) || this.endsWithNewline)) { this.GenerationEnvironment.Append(this.currentIndentField); this.endsWithNewline = false; } // Check if the current text ends with a newline if (textToAppend.EndsWith(global::System.Environment.NewLine, global::System.StringComparison.CurrentCulture)) { this.endsWithNewline = true; } // This is an optimization. If the current indent is "", then we don't have to do any // of the more complex stuff further down. if ((this.currentIndentField.Length == 0)) { this.GenerationEnvironment.Append(textToAppend); return; } // Everywhere there is a newline in the text, add an indent after it textToAppend = textToAppend.Replace(global::System.Environment.NewLine, (global::System.Environment.NewLine + this.currentIndentField)); // If the text ends with a newline, then we should strip off the indent added at the very end // because the appropriate indent will be added when the next time Write() is called if (this.endsWithNewline) { this.GenerationEnvironment.Append(textToAppend, 0, (textToAppend.Length - this.currentIndentField.Length)); } else { this.GenerationEnvironment.Append(textToAppend); } } /// <summary> /// Write text directly into the generated output /// </summary> public void WriteLine(string textToAppend) { this.Write(textToAppend); this.GenerationEnvironment.AppendLine(); this.endsWithNewline = true; } /// <summary> /// Write formatted text directly into the generated output /// </summary> public void Write(string format, params object[] args) { this.Write(string.Format(global::System.Globalization.CultureInfo.CurrentCulture, format, args)); } /// <summary> /// Write formatted text directly into the generated output /// </summary> public void WriteLine(string format, params object[] args) { this.WriteLine(string.Format(global::System.Globalization.CultureInfo.CurrentCulture, format, args)); } /// <summary> /// Raise an error /// </summary> public void Error(string message) { System.CodeDom.Compiler.CompilerError error = new global::System.CodeDom.Compiler.CompilerError(); error.ErrorText = message; this.Errors.Add(error); } /// <summary> /// Raise a warning /// </summary> public void Warning(string message) { System.CodeDom.Compiler.CompilerError error = new global::System.CodeDom.Compiler.CompilerError(); error.ErrorText = message; error.IsWarning = true; this.Errors.Add(error); } /// <summary> /// Increase the indent /// </summary> public void PushIndent(string indent) { if ((indent == null)) { throw new global::System.ArgumentNullException("indent"); } this.currentIndentField = (this.currentIndentField + indent); this.indentLengths.Add(indent.Length); } /// <summary> /// Remove the last indent that was added with PushIndent /// </summary> public string PopIndent() { string returnValue = ""; if ((this.indentLengths.Count > 0)) { int indentLength = this.indentLengths[(this.indentLengths.Count - 1)]; this.indentLengths.RemoveAt((this.indentLengths.Count - 1)); if ((indentLength > 0)) { returnValue = this.currentIndentField.Substring((this.currentIndentField.Length - indentLength)); this.currentIndentField = this.currentIndentField.Remove((this.currentIndentField.Length - indentLength)); } } return returnValue; } /// <summary> /// Remove any indentation /// </summary> public void ClearIndent() { this.indentLengths.Clear(); this.currentIndentField = ""; } #endregion #region ToString Helpers /// <summary> /// Utility
CSharpDbContextGeneratorBase
csharp
CommunityToolkit__WindowsCommunityToolkit
Microsoft.Toolkit.Uwp.UI/Triggers/UserInteractionModeStateTrigger.cs
{ "start": 491, "end": 2952 }
public sealed class ____ : StateTriggerBase { /// <summary> /// Initializes a new instance of the <see cref="UserInteractionModeStateTrigger"/> class. /// </summary> public UserInteractionModeStateTrigger() { if (!Windows.ApplicationModel.DesignMode.DesignModeEnabled) { var weakEvent = new WeakEventListener<UserInteractionModeStateTrigger, object, WindowSizeChangedEventArgs>(this) { OnEventAction = static (instance, source, eventArgs) => instance.UserInteractionModeTrigger_SizeChanged(source, eventArgs), OnDetachAction = (weakEventListener) => Window.Current.SizeChanged -= weakEventListener.OnEvent }; Window.Current.SizeChanged += weakEvent.OnEvent; UpdateTrigger(InteractionMode); } } /// <summary> /// Gets or sets the InteractionMode to trigger on. /// </summary> public UserInteractionMode InteractionMode { get { return (UserInteractionMode)GetValue(InteractionModeProperty); } set { SetValue(InteractionModeProperty, value); } } /// <summary> /// Identifies the <see cref="InteractionMode"/> parameter. /// </summary> public static readonly DependencyProperty InteractionModeProperty = DependencyProperty.Register(nameof(InteractionMode), typeof(UserInteractionMode), typeof(UserInteractionModeStateTrigger), new PropertyMetadata(UserInteractionMode.Mouse, OnInteractionModeChanged)); private static void OnInteractionModeChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { var obj = (UserInteractionModeStateTrigger)d; if (!Windows.ApplicationModel.DesignMode.DesignModeEnabled) { var orientation = (UserInteractionMode)e.NewValue; obj.UpdateTrigger(orientation); } } private void UpdateTrigger(UserInteractionMode interactionMode) { SetActive(interactionMode == UIViewSettings.GetForCurrentView().UserInteractionMode); } private void UserInteractionModeTrigger_SizeChanged(object sender, WindowSizeChangedEventArgs e) { UpdateTrigger(InteractionMode); } } }
UserInteractionModeStateTrigger
csharp
CommunityToolkit__dotnet
tests/CommunityToolkit.Mvvm.SourceGenerators.UnitTests/Test_SourceGeneratorsDiagnostics.cs
{ "start": 22205, "end": 22820 }
public partial class ____ : ObservableObject { [ObservableProperty] [NotifyPropertyChangedFor(null)] private string name; } } """; VerifyGeneratedDiagnostics<ObservablePropertyGenerator>(source, "MVVMTK0015"); } [TestMethod] public void NotifyPropertyChangedForInvalidTargetError_SamePropertyAsGeneratedOneFromSelf() { string source = """ using CommunityToolkit.Mvvm.ComponentModel; namespace MyApp {
SampleViewModel
csharp
smartstore__Smartstore
src/Smartstore.Modules/Smartstore.Google.MerchantCenter/Migrations/20250829153000_MediaFileIds.cs
{ "start": 256, "end": 965 }
internal class ____ : Migration { const string GmcProductTable = nameof(GoogleProduct); const string MediaFileIdsColumn = nameof(GoogleProduct.MediaFileIds); public override void Up() { if (!Schema.Table(GmcProductTable).Column(MediaFileIdsColumn).Exists()) { Create.Column(MediaFileIdsColumn).OnTable(GmcProductTable).AsString(1000).Nullable(); } } public override void Down() { if (Schema.Table(GmcProductTable).Column(MediaFileIdsColumn).Exists()) { Delete.Column(MediaFileIdsColumn).FromTable(GmcProductTable); } } } }
MediaFileIds
csharp
unoplatform__uno
src/Uno.UI/Generated/3.0.0.0/Microsoft.UI.Xaml.Automation.Provider/IStylesProvider.cs
{ "start": 272, "end": 1398 }
public partial interface ____ { // Skipping already declared property ExtendedProperties // Skipping already declared property FillColor // Skipping already declared property FillPatternColor // Skipping already declared property FillPatternStyle // Skipping already declared property Shape // Skipping already declared property StyleId // Skipping already declared property StyleName // Forced skipping of method Microsoft.UI.Xaml.Automation.Provider.IStylesProvider.ExtendedProperties.get // Forced skipping of method Microsoft.UI.Xaml.Automation.Provider.IStylesProvider.FillColor.get // Forced skipping of method Microsoft.UI.Xaml.Automation.Provider.IStylesProvider.FillPatternColor.get // Forced skipping of method Microsoft.UI.Xaml.Automation.Provider.IStylesProvider.FillPatternStyle.get // Forced skipping of method Microsoft.UI.Xaml.Automation.Provider.IStylesProvider.Shape.get // Forced skipping of method Microsoft.UI.Xaml.Automation.Provider.IStylesProvider.StyleId.get // Forced skipping of method Microsoft.UI.Xaml.Automation.Provider.IStylesProvider.StyleName.get } }
IStylesProvider
csharp
ChilliCream__graphql-platform
src/Nitro/CommandLine/src/CommandLine.Cloud/Generated/ApiClient.Client.cs
{ "start": 1777881, "end": 1780646 }
public partial class ____ : global::System.IEquatable<OnSchemaVersionPublishUpdated_OnSchemaVersionPublishingUpdate_Deployment_Errors_Changes_Changes_UnionMemberAdded>, IOnSchemaVersionPublishUpdated_OnSchemaVersionPublishingUpdate_Deployment_Errors_Changes_Changes_UnionMemberAdded { public OnSchemaVersionPublishUpdated_OnSchemaVersionPublishingUpdate_Deployment_Errors_Changes_Changes_UnionMemberAdded(global::System.String __typename, global::ChilliCream.Nitro.CommandLine.Cloud.Client.SchemaChangeSeverity severity, global::System.String typeName) { this.__typename = __typename; Severity = severity; TypeName = typeName; } /// <summary> /// The name of the current Object type at runtime. /// </summary> public global::System.String __typename { get; } public global::ChilliCream.Nitro.CommandLine.Cloud.Client.SchemaChangeSeverity Severity { get; } public global::System.String TypeName { get; } public virtual global::System.Boolean Equals(OnSchemaVersionPublishUpdated_OnSchemaVersionPublishingUpdate_Deployment_Errors_Changes_Changes_UnionMemberAdded? other) { if (ReferenceEquals(null, other)) { return false; } if (ReferenceEquals(this, other)) { return true; } if (other.GetType() != GetType()) { return false; } return (__typename.Equals(other.__typename)) && Severity.Equals(other.Severity) && TypeName.Equals(other.TypeName); } public override global::System.Boolean Equals(global::System.Object? obj) { if (ReferenceEquals(null, obj)) { return false; } if (ReferenceEquals(this, obj)) { return true; } if (obj.GetType() != GetType()) { return false; } return Equals((OnSchemaVersionPublishUpdated_OnSchemaVersionPublishingUpdate_Deployment_Errors_Changes_Changes_UnionMemberAdded)obj); } public override global::System.Int32 GetHashCode() { unchecked { int hash = 5; hash ^= 397 * __typename.GetHashCode(); hash ^= 397 * Severity.GetHashCode(); hash ^= 397 * TypeName.GetHashCode(); return hash; } } } [global::System.CodeDom.Compiler.GeneratedCode("StrawberryShake", "15.1.8.0")]
OnSchemaVersionPublishUpdated_OnSchemaVersionPublishingUpdate_Deployment_Errors_Changes_Changes_UnionMemberAdded
csharp
icsharpcode__ILSpy
ILSpy/Controls/TreeView/SharpTreeViewItem.cs
{ "start": 1337, "end": 4507 }
public class ____ : ListViewItem { static SharpTreeViewItem() { DefaultStyleKeyProperty.OverrideMetadata(typeof(SharpTreeViewItem), new FrameworkPropertyMetadata(typeof(SharpTreeViewItem))); } public SharpTreeNode Node { get { return DataContext as SharpTreeNode; } } public SharpTreeNodeView NodeView { get; internal set; } public SharpTreeView ParentTreeView { get; internal set; } protected override void OnKeyDown(KeyEventArgs e) { switch (e.Key) { case Key.F2: if (Node.IsEditable && ParentTreeView != null && ParentTreeView.SelectedItems.Count == 1 && ParentTreeView.SelectedItems[0] == Node) { Node.IsEditing = true; e.Handled = true; } break; case Key.Escape: if (Node.IsEditing) { Node.IsEditing = false; e.Handled = true; } break; } } protected override System.Windows.Automation.Peers.AutomationPeer OnCreateAutomationPeer() { return new SharpTreeViewItemAutomationPeer(this); } #region Mouse Point startPoint; bool wasSelected; bool wasDoubleClick; protected override void OnMouseLeftButtonDown(MouseButtonEventArgs e) { wasSelected = IsSelected; if (!IsSelected) { base.OnMouseLeftButtonDown(e); } if (Mouse.LeftButton == MouseButtonState.Pressed) { startPoint = e.GetPosition(null); CaptureMouse(); if (e.ClickCount == 2) { wasDoubleClick = true; } } } protected override void OnMouseMove(MouseEventArgs e) { if (IsMouseCaptured) { var currentPoint = e.GetPosition(null); if (Math.Abs(currentPoint.X - startPoint.X) >= SystemParameters.MinimumHorizontalDragDistance || Math.Abs(currentPoint.Y - startPoint.Y) >= SystemParameters.MinimumVerticalDragDistance) { var selection = ParentTreeView.GetTopLevelSelection().ToArray(); if (Node.CanDrag(selection)) { Node.StartDrag(this, selection, new WpfWindowsDragDropManager()); } } } } protected override void OnMouseLeftButtonUp(MouseButtonEventArgs e) { if (wasDoubleClick) { wasDoubleClick = false; Node.ActivateItem(new WpfWindowsRoutedEventArgs(e)); if (!e.Handled) { if (!Node.IsRoot || ParentTreeView.ShowRootExpander) { Node.IsExpanded = !Node.IsExpanded; } } } ReleaseMouseCapture(); if (wasSelected) { base.OnMouseLeftButtonDown(e); } } protected override void OnMouseUp(MouseButtonEventArgs e) { if (e.ChangedButton == MouseButton.Middle) { Node.ActivateItemSecondary(new WpfWindowsRoutedEventArgs(e)); } else { base.OnMouseUp(e); } } #endregion #region Drag and Drop protected override void OnDragEnter(DragEventArgs e) { ParentTreeView.HandleDragEnter(this, e); } protected override void OnDragOver(DragEventArgs e) { ParentTreeView.HandleDragOver(this, e); } protected override void OnDrop(DragEventArgs e) { ParentTreeView.HandleDrop(this, e); } protected override void OnDragLeave(DragEventArgs e) { ParentTreeView.HandleDragLeave(this, e); } #endregion } }
SharpTreeViewItem
csharp
dotnet__machinelearning
src/Microsoft.Data.Analysis/PrimitiveDataFrameColumn.BinaryOperators.cs
{ "start": 211718, "end": 215227 }
public partial class ____ { public static Int32DataFrameColumn operator /(SByteDataFrameColumn left, byte right) { return left.Divide(right); } public static Int32DataFrameColumn operator /(byte left, SByteDataFrameColumn right) { return right.ReverseDivide(left); } public static DecimalDataFrameColumn operator /(SByteDataFrameColumn left, decimal right) { return left.Divide(right); } public static DecimalDataFrameColumn operator /(decimal left, SByteDataFrameColumn right) { return right.ReverseDivide(left); } public static DoubleDataFrameColumn operator /(SByteDataFrameColumn left, double right) { return left.Divide(right); } public static DoubleDataFrameColumn operator /(double left, SByteDataFrameColumn right) { return right.ReverseDivide(left); } public static SingleDataFrameColumn operator /(SByteDataFrameColumn left, float right) { return left.Divide(right); } public static SingleDataFrameColumn operator /(float left, SByteDataFrameColumn right) { return right.ReverseDivide(left); } public static Int32DataFrameColumn operator /(SByteDataFrameColumn left, int right) { return left.Divide(right); } public static Int32DataFrameColumn operator /(int left, SByteDataFrameColumn right) { return right.ReverseDivide(left); } public static Int64DataFrameColumn operator /(SByteDataFrameColumn left, long right) { return left.Divide(right); } public static Int64DataFrameColumn operator /(long left, SByteDataFrameColumn right) { return right.ReverseDivide(left); } public static Int32DataFrameColumn operator /(SByteDataFrameColumn left, sbyte right) { return left.Divide(right); } public static Int32DataFrameColumn operator /(sbyte left, SByteDataFrameColumn right) { return right.ReverseDivide(left); } public static Int32DataFrameColumn operator /(SByteDataFrameColumn left, short right) { return left.Divide(right); } public static Int32DataFrameColumn operator /(short left, SByteDataFrameColumn right) { return right.ReverseDivide(left); } public static Int64DataFrameColumn operator /(SByteDataFrameColumn left, uint right) { return left.Divide(right); } public static Int64DataFrameColumn operator /(uint left, SByteDataFrameColumn right) { return right.ReverseDivide(left); } public static SingleDataFrameColumn operator /(SByteDataFrameColumn left, ulong right) { return left.Divide(right); } public static SingleDataFrameColumn operator /(ulong left, SByteDataFrameColumn right) { return right.ReverseDivide(left); } public static Int32DataFrameColumn operator /(SByteDataFrameColumn left, ushort right) { return left.Divide(right); } public static Int32DataFrameColumn operator /(ushort left, SByteDataFrameColumn right) { return right.ReverseDivide(left); } }
SByteDataFrameColumn
csharp
CommunityToolkit__WindowsCommunityToolkit
Microsoft.Toolkit.Uwp/Helpers/BackgroundTaskHelper.cs
{ "start": 1182, "end": 4560 }
class ____ to implement IBackgroundTask</param> /// <returns><c>true</c> if a background task was registered; otherwise, <c>false</c>.</returns> public static bool IsBackgroundTaskRegistered(Type backgroundTaskType) { return IsBackgroundTaskRegistered(backgroundTaskType.Name); } /// <summary> /// Registers a background task with conditions. /// If the task is already registered, return null. /// Or set <paramref name="forceRegister"/> to true to un-register the old one and then re-register. /// </summary> /// <param name="backgroundTaskName">Name of the background task class</param> /// <param name="backgroundTaskEntryPoint">Entry point of the background task.</param> /// <param name="trigger">Trigger that indicate when the background task should be invoked</param> /// <param name="forceRegister">Indicate if the background task will be force installed in the case of being already registered</param> /// <param name="enforceConditions">Indicate if the background task should quit if condition is no longer valid</param> /// <param name="conditions">Optional conditions for the background task to run with</param> /// <returns>Background Task that was registered with the system</returns> public static BackgroundTaskRegistration Register(string backgroundTaskName, string backgroundTaskEntryPoint, IBackgroundTrigger trigger, bool forceRegister = false, bool enforceConditions = true, params IBackgroundCondition[] conditions) { // Check if the task is already registered. if (IsBackgroundTaskRegistered(backgroundTaskName)) { BackgroundTaskRegistration previouslyRegistered = GetBackgroundTask(backgroundTaskName) as BackgroundTaskRegistration; if (forceRegister) { Unregister(previouslyRegistered); } else { return null; } } // build the background task BackgroundTaskBuilder builder = new BackgroundTaskBuilder { Name = backgroundTaskName }; // check if we are registering in SPM mode if (backgroundTaskEntryPoint != string.Empty) { builder.TaskEntryPoint = backgroundTaskEntryPoint; } builder.CancelOnConditionLoss = enforceConditions; // add the conditions if we have them. conditions?.ToList().ForEach(builder.AddCondition); builder.SetTrigger(trigger); // Register it BackgroundTaskRegistration registered = builder.Register(); return registered; } /// <summary> /// Registers a background task with conditions. /// If the task is already registered and has the same trigger, returns the existing registration if it has the same trigger. /// If the task is already registered but has different trigger, return null by default. /// Or set <paramref name="forceRegister"/> to true to un-register the old one and then re-register. /// </summary> /// <param name="backgroundTaskType">The type of the background task. This
has
csharp
dotnet__efcore
src/EFCore/Metadata/Conventions/TimestampAttributeConvention.cs
{ "start": 566, "end": 1441 }
public class ____ : PropertyAttributeConventionBase<TimestampAttribute> { /// <summary> /// Creates a new instance of <see cref="TimestampAttributeConvention" />. /// </summary> /// <param name="dependencies">Parameter object containing dependencies for this convention.</param> public TimestampAttributeConvention(ProviderConventionSetBuilderDependencies dependencies) : base(dependencies) { } /// <inheritdoc /> protected override void ProcessPropertyAdded( IConventionPropertyBuilder propertyBuilder, TimestampAttribute attribute, MemberInfo clrMember, IConventionContext context) { propertyBuilder.ValueGenerated(ValueGenerated.OnAddOrUpdate, fromDataAnnotation: true); propertyBuilder.IsConcurrencyToken(true, fromDataAnnotation: true); } }
TimestampAttributeConvention
csharp
dotnet__aspnetcore
src/Http/Routing/src/Template/TemplateMatcher.cs
{ "start": 349, "end": 3140 }
public class ____ { // Perf: This is a cache to avoid looking things up in 'Defaults' each request. private readonly bool[] _hasDefaultValue; private readonly object?[] _defaultValues; private readonly RoutePatternMatcher _routePatternMatcher; /// <summary> /// Creates a new <see cref="TemplateMatcher"/> instance given a <paramref name="template"/> and <paramref name="defaults"/>. /// </summary> /// <param name="template">The <see cref="RouteTemplate"/> to compare against.</param> /// <param name="defaults">The default values for parameters in the <paramref name="template"/>.</param> public TemplateMatcher( RouteTemplate template, RouteValueDictionary defaults) { ArgumentNullException.ThrowIfNull(template); Template = template; Defaults = defaults ?? new RouteValueDictionary(); // Perf: cache the default value for each parameter (other than complex segments). _hasDefaultValue = new bool[Template.Segments.Count]; _defaultValues = new object[Template.Segments.Count]; for (var i = 0; i < Template.Segments.Count; i++) { var segment = Template.Segments[i]; if (!segment.IsSimple) { continue; } var part = segment.Parts[0]; if (!part.IsParameter) { continue; } if (Defaults.TryGetValue(part.Name!, out var value)) { _hasDefaultValue[i] = true; _defaultValues[i] = value; } } var routePattern = Template.ToRoutePattern(); _routePatternMatcher = new RoutePatternMatcher(routePattern, Defaults); } /// <summary> /// Gets the default values for parameters in the <see cref="Template"/>. /// </summary> public RouteValueDictionary Defaults { get; } /// <summary> /// Gets the <see cref="RouteTemplate"/> to match against. /// </summary> public RouteTemplate Template { get; } /// <summary> /// Evaluates if the provided <paramref name="path"/> matches the <see cref="Template"/>. Populates /// <paramref name="values"/> with parameter values. /// </summary> /// <param name="path">A <see cref="PathString"/> representing the route to match.</param> /// <param name="values">A <see cref="RouteValueDictionary"/> to populate with parameter values.</param> /// <returns><see langword="true"/> if <paramref name="path"/> matches <see cref="Template"/>.</returns> public bool TryMatch(PathString path, RouteValueDictionary values) { ArgumentNullException.ThrowIfNull(values); return _routePatternMatcher.TryMatch(path, values); } }
TemplateMatcher
csharp
microsoft__PowerToys
src/settings-ui/Settings.UI/SettingsXAML/Views/WorkspacesPage.xaml.cs
{ "start": 431, "end": 1141 }
partial class ____ : NavigablePage, IRefreshablePage { private WorkspacesViewModel ViewModel { get; set; } public WorkspacesPage() { var settingsUtils = new SettingsUtils(); ViewModel = new WorkspacesViewModel(settingsUtils, SettingsRepository<GeneralSettings>.GetInstance(settingsUtils), SettingsRepository<WorkspacesSettings>.GetInstance(settingsUtils), ShellPage.SendDefaultIPCMessage); DataContext = ViewModel; InitializeComponent(); Loaded += (s, e) => ViewModel.OnPageLoaded(); } public void RefreshEnabledState() { ViewModel.RefreshEnabledState(); } } }
WorkspacesPage
csharp
CommunityToolkit__WindowsCommunityToolkit
UnitTests/UnitTests.UWP/UI/Controls/Test_ListDetailsView.cs
{ "start": 474, "end": 4755 }
public class ____ { [TestCategory("ListDetailsView")] [UITestMethod] public void Test_SelectedIndex_Default() { var items = Enumerable.Range(1, 10).ToArray(); var listDetailsView = new ListDetailsView { ItemsSource = items }; Assert.AreEqual(-1, listDetailsView.SelectedIndex); } [TestCategory("ListDetailsView")] [UITestMethod] public void Test_SelectedItem_Default() { var items = Enumerable.Range(1, 10).ToArray(); var listDetailsView = new ListDetailsView { ItemsSource = items }; Assert.IsNull(listDetailsView.SelectedItem); } [TestCategory("ListDetailsView")] [UITestMethod] public void Test_SelectedIndex_Syncs_SelectedItem() { var items = Enumerable.Range(1, 10).ToArray(); var listDetailsView = new ListDetailsView { ItemsSource = items, SelectedIndex = 6 }; Assert.AreEqual(items[6], listDetailsView.SelectedItem); } [TestCategory("ListDetailsView")] [UITestMethod] public void Test_UnselectUsingIndex() { var items = Enumerable.Range(1, 10).ToArray(); var listDetailsView = new ListDetailsView { ItemsSource = items, SelectedIndex = 5 }; listDetailsView.SelectedIndex = -1; Assert.IsNull(listDetailsView.SelectedItem); } [TestCategory("ListDetailsView")] [UITestMethod] public void Test_UnselectUsingItem() { var items = Enumerable.Range(1, 10).ToArray(); var listDetailsView = new ListDetailsView { ItemsSource = items, SelectedItem = items[5] }; listDetailsView.SelectedItem = null; Assert.AreEqual(-1, listDetailsView.SelectedIndex); } [TestCategory("ListDetailsView")] [UITestMethod] public void Test_SelectedItem_Syncs_SelectedIndex() { var items = Enumerable.Range(0, 10).ToArray(); var listDetailsView = new ListDetailsView { ItemsSource = items, SelectedItem = items[3] }; Assert.AreEqual(3, listDetailsView.SelectedIndex); } [TestCategory("ListDetailsView")] [UITestMethod] public void Test_Sorting_Keeps_SelectedIndex() { var items = Enumerable.Range(0, 10).ToArray(); var listDetailsView = new ListDetailsView { ItemsSource = items, SelectedItem = items[3] }; Assert.AreEqual(3, listDetailsView.SelectedIndex); } [TestCategory("ListDetailsView")] [UITestMethod] public void Test_Sorting_Keeps_SelectedItem() { var items = new ObservableCollection<int>(Enumerable.Range(0, 10)); var listDetailsView = new ListDetailsView { ItemsSource = items, SelectedIndex = 3 }; var item = listDetailsView.SelectedItem; listDetailsView.ItemsSource = new ObservableCollection<int>(items.OrderByDescending(i => i)); Assert.AreEqual(item, listDetailsView.SelectedItem); listDetailsView.ItemsSource = new ObservableCollection<int>(items.OrderBy(i => i)); Assert.AreEqual(item, listDetailsView.SelectedItem); } [TestCategory("ListDetailsView")] [UITestMethod] public void Test_ItemsRemoved() { var items = new ObservableCollection<int>(Enumerable.Range(0, 10)); var listDetailsView = new ListDetailsView { ItemsSource = items, SelectedIndex = 3 }; listDetailsView.ItemsSource = null; Assert.AreEqual(null, listDetailsView.SelectedItem); Assert.AreEqual(-1, listDetailsView.SelectedIndex); } } }
Test_ListDetailsView
csharp
dotnet__aspnetcore
src/Razor/Razor.Runtime/test/Runtime/TagHelpers/TestTagHelpers/TagHelperDescriptorFactoryTagHelpers.cs
{ "start": 471, "end": 572 }
public class ____ : EnumTagHelper { } [HtmlTargetElement("input", ParentTag = "div")]
MultiEnumTagHelper
csharp
dotnet__maui
src/SingleProject/Resizetizer/src/AsyncTaskExtensions.cs
{ "start": 334, "end": 1650 }
public static class ____ { /// <summary> /// Calls Parallel.ForEach() with appropriate ParallelOptions and exception handling. /// </summary> public static ParallelLoopResult ParallelForEach<TSource>(this MauiAsyncTask asyncTask, IEnumerable<TSource> source, Action<TSource> body) { return Parallel.ForEach(source, ParallelOptions(asyncTask), s => { try { body(s); } catch (Exception ex) { asyncTask.LogCodedError(ErrorCodes.ImageProcessingCode, ErrorMessages.ImageProcessing, string.Format(ErrorMessages.ImageProcessingError, ex.ToString())); asyncTask.Cancel(); } }); } static ParallelOptions ParallelOptions(MauiAsyncTask asyncTask) => new ParallelOptions { CancellationToken = asyncTask.CancellationToken, TaskScheduler = TaskScheduler.Default, }; /// <summary> /// Calls Task.Run() with a proper CancellationToken. /// </summary> public static Task RunTask(this MauiAsyncTask asyncTask, Action body) => Task.Run(body, asyncTask.CancellationToken); /// <summary> /// Calls Task.Run<T>() with a proper CancellationToken. /// </summary> public static Task<TSource> RunTask<TSource>(this MauiAsyncTask asyncTask, Func<TSource> body) => Task.Run(body, asyncTask.CancellationToken); } }
AsyncTaskExtensions
csharp
AutoMapper__AutoMapper
src/IntegrationTests/NullCheckCollections.cs
{ "start": 218, "end": 382 }
public class ____ { public int Id { get; set; } public ICollection<Parameter> Parameters { get; set; } = new List<Parameter>(); }
SourceType
csharp
xunit__xunit
src/xunit.v2.tests/Sdk/Reflection/ReflectorTests.cs
{ "start": 6193, "end": 6682 }
class ____ : Grandparent { } [Fact] public void Parent_ReturnsOnlyParent() { var results = Reflector .Wrap(typeof(Parent)) .GetCustomAttributes(typeof(AttributeUnderTest)); var result = Assert.Single(results); var reflectionResult = Assert.IsAssignableFrom<IReflectionAttributeInfo>(result); var attributeUnderTest = Assert.IsType<AttributeUnderTest>(reflectionResult.Attribute); Assert.Equal("Parent", attributeUnderTest.Level); }
Parent
csharp
MassTransit__MassTransit
tests/MassTransit.RabbitMqTransport.Tests/PublishTopology_Specs.cs
{ "start": 646, "end": 1135 }
public class ____ : RabbitMqTestFixture { [Test] [Explicit] public void Should_create_the_exchanges() { } protected override void ConfigureRabbitMqBus(IRabbitMqBusFactoryConfigurator configurator) { configurator.DeployPublishTopology = true; configurator.Publish<OrderSubmitted>(); configurator.Publish<PackageShipped>(); } }
Configuring_the_publish_topology_at_startup
csharp
MassTransit__MassTransit
tests/MassTransit.Azure.Cosmos.Tests/AzureCosmosTestAccountKeyConfigurator.cs
{ "start": 47, "end": 413 }
public class ____ : IAzureCosmosTestAuthenticationConfigurator { public void Configure(ICosmosSagaRepositoryConfigurator configurator) { configurator.AccountEndpoint = Configuration.AccountEndpoint; configurator.AuthKeyOrResourceToken = Configuration.AccountKey; } } }
AzureCosmosTestAccountKeyConfigurator
csharp
OrchardCMS__OrchardCore
src/OrchardCore.Modules/OrchardCore.Workflows/Http/Activities/HttpRequestEvent.cs
{ "start": 250, "end": 3241 }
public class ____ : EventActivity { public static string EventName => nameof(HttpRequestEvent); private readonly IHttpContextAccessor _httpContextAccessor; protected readonly IStringLocalizer S; public HttpRequestEvent( IStringLocalizer<HttpRequestEvent> localizer, IHttpContextAccessor httpContextAccessor ) { S = localizer; _httpContextAccessor = httpContextAccessor; } public override string Name => EventName; public override LocalizedString DisplayText => S["Http Request Event"]; public override LocalizedString Category => S["HTTP"]; public string HttpMethod { get => GetProperty<string>(); set => SetProperty(value); } public string Url { get => GetProperty<string>(); set => SetProperty(value); } public bool ValidateAntiforgeryToken { get => GetProperty(() => true); set => SetProperty(value); } public int TokenLifeSpan { get => GetProperty(() => 0); set => SetProperty(value); } public string FormLocationKey { get => GetProperty(() => string.Empty); set => SetProperty(value ?? string.Empty); } public override bool CanExecute(WorkflowExecutionContext workflowContext, ActivityContext activityContext) { var httpContext = _httpContextAccessor.HttpContext; var httpRequest = httpContext.Request; var isMatch = string.Equals(HttpMethod, httpRequest.Method, StringComparison.OrdinalIgnoreCase); return isMatch; } public override Task<ActivityExecutionResult> ExecuteAsync(WorkflowExecutionContext workflowContext, ActivityContext activityContext) { if (_httpContextAccessor.HttpContext.Request.HasFormContentType && _httpContextAccessor.HttpContext.Request.Form.TryGetValue(WorkflowConstants.FormLocationKeyInputName, out var value) && !string.IsNullOrWhiteSpace(value)) { if (!workflowContext.Output.TryGetValue(WorkflowConstants.HttpFormLocationOutputKeyName, out var obj) || obj is not Dictionary<string, string> formLocation) { formLocation = []; } formLocation[FormLocationKey] = GetLocationUrl(value); workflowContext.Output[WorkflowConstants.HttpFormLocationOutputKeyName] = formLocation; } return Task.FromResult(Outcomes("Done")); } public override IEnumerable<Outcome> GetPossibleOutcomes(WorkflowExecutionContext workflowContext, ActivityContext activityContext) => Outcomes(S["Done"]); public override ActivityExecutionResult Resume(WorkflowExecutionContext workflowContext, ActivityContext activityContext) => Outcomes("Done"); private static string GetLocationUrl(string value) { if (value.StartsWith('/')) { return "~" + value; } return value; } }
HttpRequestEvent
csharp
microsoft__PowerToys
src/modules/previewpane/common/cominterop/LOGFONT.cs
{ "start": 403, "end": 3970 }
public struct ____ { /// <summary> /// Gets or sets value of type INT that specifies the height, in logical units, of the font's character cell or character. /// </summary> public int LfHeight { get; set; } /// <summary> /// Gets or sets value of type INT that specifies the width, in logical units, of characters in the font. /// </summary> public int LfWidth { get; set; } /// <summary> /// Gets or sets value of type INT that contains the angle, in tenths of degrees, between the escapement vector and the x-axis of the device. The escapement /// vector is parallel to the base line of a row of text. /// </summary> public int LfEscapement { get; set; } /// <summary> /// Gets or sets value of type INT that specifies the angle, in tenths of degrees, between each character's base line and the x-axis of the device. /// </summary> public int LfOrientation { get; set; } /// <summary> /// Gets or sets value of type INT that specifies the weight of the font in the range from 0 through 1000. /// </summary> public int LfWeight { get; set; } /// <summary> /// Gets or sets value of type BYTE that specifies an italic font if set to TRUE. /// </summary> public byte LfItalic { get; set; } /// <summary> /// Gets or sets value of type BYTE that specifies an underlined font if set to TRUE. /// </summary> public byte LfUnderline { get; set; } /// <summary> /// Gets or sets value of type BYTE that specifies a strikeout font if set to TRUE. /// </summary> public byte LfStrikeOut { get; set; } /// <summary> /// Gets or sets value of type BYTE that specifies the character set. /// </summary> public byte LfCharSet { get; set; } /// <summary> /// Gets or sets value of type BYTE that specifies the output precision. The output precision defines how closely the output must match the requested /// font's height, width, character orientation, escapement, pitch, and font type. /// </summary> public byte LfOutPrecision { get; set; } /// <summary> /// Gets or sets value of type BYTE that specifies the clipping precision. The clipping precision defines how to clip characters that are partially outside the clipping region. /// </summary> public byte LfClipPrecision { get; set; } /// <summary> /// Gets or sets value of type BYTE that specifies the output quality. The output quality defines how carefully the GDI must attempt to match the logical-font attributes to those of an actual physical font. /// </summary> public byte LfQuality { get; set; } /// <summary> /// Gets or sets value of type BYTE that specifies the pitch and family of the font. /// </summary> public byte LfPitchAndFamily { get; set; } /// <summary> /// Gets or sets array of wide characters that contains a null-terminated string that specifies the typeface name of the font. The length of the string must not exceed 32 characters, including the NULL terminator. /// </summary> public string LfFaceName { get { return _lfFaceName; } set { _lfFaceName = value; } } [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 32)] private string _lfFaceName; } }
LOGFONT
csharp
dotnet__orleans
test/Analyzers.Tests/AliasClashAttributeAnalyzerTest.cs
{ "start": 3311, "end": 3486 }
public struct ____ { public SA() { } [Id(0)] public string P { get; set; } } [Alias("Struct")]
SA
csharp
NLog__NLog
src/NLog/Internal/IAppEnvironment.cs
{ "start": 1832, "end": 2720 }
internal interface ____ : IFileSystem { string AppDomainBaseDirectory { get; } string AppDomainConfigurationFile { get; } string AppDomainFriendlyName { get; } int AppDomainId { get; } IEnumerable<string> AppDomainPrivateBinPath { get; } IEnumerable<System.Reflection.Assembly> GetAppDomainRuntimeAssemblies(); string CurrentProcessFilePath { get; } /// <summary> /// Gets current process name (excluding filename extension, if any). /// </summary> string CurrentProcessBaseName { get; } int CurrentProcessId { get; } string EntryAssemblyLocation { get; } string EntryAssemblyFileName { get; } string UserTempFilePath { get; } /// <summary> /// Process exit event. /// </summary> event EventHandler ProcessExit; } }
IAppEnvironment
csharp
icsharpcode__AvalonEdit
ICSharpCode.AvalonEdit.Tests/Editing/ChangeDocumentTests.cs
{ "start": 1343, "end": 3116 }
public class ____ { [Test] public void ClearCaretAndSelectionOnDocumentChange() { TextArea textArea = new TextArea(); textArea.Document = new TextDocument("1\n2\n3\n4th line"); textArea.Caret.Offset = 6; textArea.Selection = Selection.Create(textArea, 3, 6); textArea.Document = new TextDocument("1\n2nd"); Assert.That(textArea.Caret.Offset, Is.EqualTo(0)); Assert.That(textArea.Caret.Location, Is.EqualTo(new TextLocation(1, 1))); Assert.That(textArea.Selection.IsEmpty, Is.True); } [Test] public void SetDocumentToNull() { TextArea textArea = new TextArea(); textArea.Document = new TextDocument("1\n2\n3\n4th line"); textArea.Caret.Offset = 6; textArea.Selection = Selection.Create(textArea, 3, 6); textArea.Document = null; Assert.That(textArea.Caret.Offset, Is.EqualTo(0)); Assert.That(textArea.Caret.Location, Is.EqualTo(new TextLocation(1, 1))); Assert.That(textArea.Selection.IsEmpty, Is.True); } [Test] public void CheckEventOrderOnDocumentChange() { TextArea textArea = new TextArea(); TextDocument newDocument = new TextDocument(); StringBuilder b = new StringBuilder(); textArea.TextView.DocumentChanged += delegate { b.Append("TextView.DocumentChanged;"); Assert.That(textArea.TextView.Document, Is.SameAs(newDocument)); Assert.That(textArea.Document, Is.SameAs(newDocument)); }; textArea.DocumentChanged += delegate { b.Append("TextArea.DocumentChanged;"); Assert.That(textArea.TextView.Document, Is.SameAs(newDocument)); Assert.That(textArea.Document, Is.SameAs(newDocument)); }; textArea.Document = newDocument; Assert.That(b.ToString(), Is.EqualTo("TextView.DocumentChanged;TextArea.DocumentChanged;")); } } }
ChangeDocumentTests
csharp
Cysharp__UniTask
src/UniTask/Assets/Plugins/UniTask/Runtime/Triggers/MonoBehaviourMessagesTriggers.cs
{ "start": 674, "end": 1155 }
partial class ____ { public static AsyncFixedUpdateTrigger GetAsyncFixedUpdateTrigger(this GameObject gameObject) { return GetOrAddComponent<AsyncFixedUpdateTrigger>(gameObject); } public static AsyncFixedUpdateTrigger GetAsyncFixedUpdateTrigger(this Component component) { return component.gameObject.GetAsyncFixedUpdateTrigger(); } } [DisallowMultipleComponent]
AsyncTriggerExtensions
csharp
GtkSharp__GtkSharp
Source/Libs/GtkSharp/ComboBox.cs
{ "start": 933, "end": 2051 }
public partial class ____ { public ComboBox (string[] entries) : this (new ListStore (typeof (string))) { ListStore store = Model as ListStore; CellRendererText cell = new CellRendererText (); PackStart (cell, true); SetAttributes (cell, "text", 0); foreach (string entry in entries) store.AppendValues (entry); } protected ComboBox (bool with_entry) : base (IntPtr.Zero) { if (GetType () != typeof (ComboBox)) { CreateNativeObject (new string[] { "has-entry" }, new GLib.Value[] { new GLib.Value (with_entry) }); return; } if (with_entry) { Raw = gtk_combo_box_new_with_entry (); } else { Raw = gtk_combo_box_new (); } } public Gtk.Entry Entry { get { return Child as Gtk.Entry; } } public void SetAttributes (CellRenderer cell, params object[] attrs) { if (attrs.Length % 2 != 0) throw new ArgumentException ("attrs should contain pairs of attribute/col"); ClearAttributes (cell); for (int i = 0; i < attrs.Length - 1; i += 2) { AddAttribute (cell, (string) attrs [i], (int) attrs [i + 1]); } } } }
ComboBox
csharp
unoplatform__uno
src/Uno.UWP/Devices/Sensors/SimpleOrientationSensor.Android.cs
{ "start": 10932, "end": 11965 }
private sealed class ____ : Java.Lang.Object, ISensorEventListener { private readonly SimpleOrientationSensor _simpleOrientationSensor; public OrientationListener(SimpleOrientationSensor simpleOrientationSensor) { _simpleOrientationSensor = simpleOrientationSensor; } public void OnAccuracyChanged(Sensor? sensor, [GeneratedEnum] SensorStatus accuracy) { } public void OnSensorChanged(SensorEvent? e) { if (e?.Sensor?.Type != _gravitySensorType || e?.Values == null) { return; } // All units are negatives compared to iOS : https://developer.android.com/reference/android/hardware/SensorEvent#values var gravityX = -(double)e.Values[0]; var gravityY = -(double)e.Values[1]; var gravityZ = -(double)e.Values[2]; var simpleOrientation = ToSimpleOrientation(gravityX, gravityY, gravityZ, _threshold, _simpleOrientationSensor._currentOrientation); _simpleOrientationSensor.SetCurrentOrientation(simpleOrientation); } } #endregion } }
OrientationListener
csharp
OrchardCMS__OrchardCore
src/OrchardCore.Modules/OrchardCore.OpenId/Deployment/OpenIdServerDeploymentStep.cs
{ "start": 169, "end": 314 }
public class ____ : DeploymentStep { public OpenIdServerDeploymentStep() { Name = "OpenID Server"; } }
OpenIdServerDeploymentStep
csharp
dotnetcore__WTM
demo/WalkingTec.Mvvm.BlazorDemo/WalkingTec.Mvvm.BlazorDemo.Shared/WtmBlazorUtils/BasePage.cs
{ "start": 547, "end": 12421 }
public abstract class ____ : ComponentBase { [Inject] public WtmBlazorContext WtmBlazor { get; set; } [Inject] public IJSRuntime JSRuntime { get; set; } public List<string> DeletedFileIds { get; set; } [CascadingParameter] public LoginUserInfo UserInfo { get; set; } public object _userinfo; [CascadingParameter(Name = "BodyContext")] public object UserInfoForDialog { get { return _userinfo; } set { _userinfo = value; UserInfo = value as LoginUserInfo; } } [Parameter] public Action<DialogResult> OnCloseDialog { get; set; } protected void CloseDialog(DialogResult result = DialogResult.Close) { OnCloseDialog?.Invoke(result); } public async Task<DialogResult> OpenDialog<T>(string Title, Expression<Func<T, object>> Values = null, Size size = Size.ExtraExtraLarge, LoginUserInfo userinfo = null, bool isMax = false) { return await WtmBlazor.OpenDialog(Title, Values, size, userinfo??this.UserInfo, isMax); } public async Task<bool> PostsData(object data, string url, Func<string, string> Msg = null, Action<ErrorObj> ErrorHandler = null, HttpMethodEnum method = HttpMethodEnum.POST) { var rv = await WtmBlazor.Api.CallAPI(url, method, data); if (rv.StatusCode == System.Net.HttpStatusCode.OK) { if (Msg != null) { var m = Msg.Invoke(rv.Data); await WtmBlazor.Toast.Success(WtmBlazor.Localizer["Sys.Info"], WtmBlazor.Localizer[m]); } CloseDialog(DialogResult.Yes); return true; } else { if (rv.Errors == null) { await WtmBlazor.Toast.Error(WtmBlazor.Localizer["Sys.Error"], rv.StatusCode.ToString()); } else { var err = rv.Errors.GetFirstError(); if (string.IsNullOrEmpty(err) == false) { await WtmBlazor.Toast.Error(WtmBlazor.Localizer["Sys.Error"], err); } else { await WtmBlazor.Toast.Error(WtmBlazor.Localizer["Sys.Error"], rv.ErrorMsg); } ErrorHandler?.Invoke(rv.Errors); } return false; } } public async Task<bool> PostsForm(ValidateForm form, string url, Func<string, string> Msg = null, Action<ErrorObj> ErrorHandler = null, HttpMethodEnum method = HttpMethodEnum.POST) { if(form.Model is BaseVM bv) { bv.DeletedFileIds = this.DeletedFileIds; } var rv = await WtmBlazor.Api.CallAPI(url, method, form.Model); if (rv.StatusCode == System.Net.HttpStatusCode.OK) { if (Msg != null) { var m = Msg.Invoke(rv.Data); await WtmBlazor.Toast.Success(WtmBlazor.Localizer["Sys.Info"], WtmBlazor.Localizer[m]); } CloseDialog(DialogResult.Yes); return true; } else { if (rv.Errors == null) { await WtmBlazor.Toast.Error(WtmBlazor.Localizer["Sys.Error"], rv.StatusCode.ToString()); } else { SetError(form, rv.Errors); ErrorHandler?.Invoke(rv.Errors); } return false; } } public async Task<QueryData<T>> StartSearch<T>(string url, BaseSearcher searcher, QueryPageOptions options) where T : class, new() { if (searcher != null) { searcher.IsEnumToString = false; } var rv = await WtmBlazor.Api.CallSearchApi<T>(url, searcher, options); QueryData<T> data = new QueryData<T>(); if (rv.StatusCode == System.Net.HttpStatusCode.OK) { data.Items = rv.Data?.Data; data.TotalCount = rv.Data?.Count ?? 0; } if (rv.StatusCode == System.Net.HttpStatusCode.Forbidden) { await WtmBlazor.Toast.Error(WtmBlazor.Localizer["Sys.Error"], WtmBlazor.Localizer["Sys.NoPrivilege"]); } return data; } public async Task<QueryData<T>> StartSearchTree<T>(string url, BaseSearcher searcher, QueryPageOptions options) where T : class, new() { if (searcher != null) { searcher.IsEnumToString = false; } var rv = await WtmBlazor.Api.CallSearchApi<T>(url, searcher, options); QueryData<T> data = new QueryData<T>(); if (rv.StatusCode == System.Net.HttpStatusCode.OK) { var idpro = typeof(T).GetSingleProperty("ID"); if (rv.Data?.Data != null) { foreach (var item in rv.Data.Data) { string pid = idpro.GetValue(item)?.ToString(); item.SetPropertyValue("Children", new List<T>(rv.Data.Data.AsQueryable().CheckParentID(pid))); } } data.Items = rv.Data?.Data.AsQueryable().CheckParentID(null); data.TotalCount = rv.Data?.Count ?? 0; } if (rv.StatusCode == System.Net.HttpStatusCode.Forbidden) { await WtmBlazor.Toast.Error(WtmBlazor.Localizer["Sys.Error"], WtmBlazor.Localizer["Sys.NoPrivilege"]); } return data; } public async void SetError(ValidateForm form, ErrorObj errors) { if (errors != null) { foreach (var item in errors.Form) { Regex r = new Regex("(.*?)\\[(\\-?\\d?)\\]\\.(.*?)$"); var match = r.Match(item.Key); if (match.Success) { int index = 0; int.TryParse(match.Groups[2].Value, out index); await WtmBlazor.Toast.Error(WtmBlazor.Localizer["Sys.Error"], $"{index+1}:{item.Value}" ); } else { form.SetError(item.Key, item.Value); } } if (errors.Message != null && errors.Message.Count > 0) { await WtmBlazor.Toast.Error(WtmBlazor.Localizer["Sys.Error"], errors.Message[0]); } } } public async Task<string> GetFileUrl(string fileid, int? width = null, int? height = null) { var rv = await WtmBlazor.Api.CallAPI<byte[]>($"/api/_file/GetFile/{fileid}", HttpMethodEnum.GET, new Dictionary<string, string> { {"width", width?.ToString() }, {"height", height?.ToString() } }); if (rv.StatusCode == System.Net.HttpStatusCode.OK) { return $"data:image/jpeg;base64,{Convert.ToBase64String(rv.Data)}"; } else { return $"data:image/jpeg;base64,0"; } } public async Task<string> GetToken() { return await GetLocalStorage<string>("wtmtoken"); } public async Task<string> GetRefreshToken() { return await GetLocalStorage<string>("wtmrefreshtoken"); } public async Task SetToken(string token, string refreshtoken) { await SetLocalStorage("wtmtoken", token); await SetLocalStorage("wtmrefreshtoken", refreshtoken); } public async Task DeleteToken() { await DeleteLocalStorage("wtmtoken"); await DeleteLocalStorage("wtmrefreshtoken"); } public async Task SetUserInfo(LoginUserInfo userinfo) { await JSRuntime.InvokeVoidAsync("localStorageFuncs.set", "wtmuser", JsonSerializer.Serialize(userinfo)); } public async Task<LoginUserInfo> GetUserInfo() { var user = await GetLocalStorage<LoginUserInfo>("wtmuser"); JsonSerializerOptions options = new JsonSerializerOptions { PropertyNameCaseInsensitive = true }; user.Attributes["Actions"] = JsonSerializer.Deserialize<string[]>(user.Attributes["Actions"].ToString(), options).Where(x => x != null).ToArray(); user.Attributes["Menus"] = JsonSerializer.Deserialize<SimpleMenuApi[]>(user.Attributes["Menus"].ToString(), options); return user; } public async Task<T> GetLocalStorage<T>(string key) where T : class { string rv = ""; while (true) { string part = await JSRuntime.InvokeAsync<string>("localStorageFuncs.get", System.Threading.CancellationToken.None, key, rv.Length); if(part == null) { return null; } rv += part; if (part.Length < 20000) { break; } } if(typeof(T) == typeof(string)) { return rv as T; } var obj = JsonSerializer.Deserialize<T>(rv); return obj; } public async Task SetLocalStorage<T>(string key, T data) where T : class { if (typeof(T) == typeof(string)) { await JSRuntime.InvokeVoidAsync("localStorageFuncs.set", key, data); } else { await JSRuntime.InvokeVoidAsync("localStorageFuncs.set", key, JsonSerializer.Serialize(data)); } } public async Task DeleteLocalStorage(string key) { await JSRuntime.InvokeAsync<string>("localStorageFuncs.remove", key); } public bool IsAccessable(string url) { if (WtmBlazor.ConfigInfo.IsQuickDebug == true) { return true; } if (UserInfo != null) { var actions = UserInfo.Attributes["Actions"] as string[]; url = url.ToLower(); return actions.Any(x => x.ToLower() == url.ToLower()); } else if (WtmBlazor.PublicPages.Contains(url?.ToLower())) { return true; } return false; } public async Task Redirect(string path) { await JSRuntime.InvokeVoidAsync("urlFuncs.redirect", path); } public async Task Download(string url, object data, HttpMethodEnum method = HttpMethodEnum.POST) { url = WtmBlazor.GetServerUrl() + url; await JSRuntime.InvokeVoidAsync("urlFuncs.download", url, JsonSerializer.Serialize(data, CoreProgram.DefaultPostJsonOption), method.ToString()); } public string GetLanguageStr() { if (CultureInfo.CurrentUICulture.Name.Contains("zh")) { return "zh-CN"; } else return CultureInfo.CurrentUICulture.Name; } }
BasePage
csharp
DuendeSoftware__IdentityServer
bff/src/Bff.Blazor.Client/Internals/FetchUserService.cs
{ "start": 386, "end": 2430 }
internal class ____ : IDisposable { private readonly HttpClient _client; private readonly ILogger<FetchUserService> _logger; /// <summary> /// Internal service that retrieves user info from the /bff/user endpoint. /// </summary> /// <param name="clientFactory"></param> /// <param name="logger"></param> public FetchUserService(IHttpClientFactory clientFactory, ILogger<FetchUserService> logger) { _logger = logger; _client = clientFactory.CreateClient(BffClientAuthenticationStateProvider.HttpClientName); } /// <summary> /// Parameterless ctor for testing only. /// </summary> internal FetchUserService() { _client = new HttpClient(); #pragma warning disable CA2000 // This is a test-only ctor, so we don't want to dispose the client here. _logger = new Logger<FetchUserService>(new LoggerFactory()); #pragma warning restore CA2000 } public virtual async ValueTask<ClaimsPrincipal> FetchUserAsync() { try { _logger.FetchingUserInformation(); var claims = await _client.GetFromJsonAsync<List<ClaimRecord>>("bff/user?slide=false"); var identity = new ClaimsIdentity( nameof(BffClientAuthenticationStateProvider), "name", "role"); if (claims != null) { foreach (var claim in claims) { identity.AddClaim(new Claim(claim.Type, claim.Value.ToString() ?? "no value")); } } return new ClaimsPrincipal(identity); } catch (HttpRequestException ex) { _logger.FetchingUserFailed(ex); return new ClaimsPrincipal(new ClaimsIdentity()); } catch (JsonException ex) { _logger.FetchingUserFailed(ex); return new ClaimsPrincipal(new ClaimsIdentity()); } } public void Dispose() => _client.Dispose(); }
FetchUserService
csharp
nuke-build__nuke
source/Nuke.Common/CI/Jenkins/Jenkins.cs
{ "start": 477, "end": 5346 }
public class ____ : Host, IBuildServer { public new static Jenkins Instance => Host.Instance as Jenkins; [UsedImplicitly] internal static bool IsRunningJenkins => EnvironmentInfo.HasVariable("JENKINS_HOME"); internal Jenkins() { } string IBuildServer.Branch => GitBranch ?? BranchName; string IBuildServer.Commit => GitCommit; /// <summary> /// Name of the branch for which this Pipeline is executing, for example <em>master</em>. /// </summary> public string BranchName => EnvironmentInfo.GetVariable("BRANCH_NAME"); /// <summary> /// The current build display name, such as "#14". /// </summary> public string BuilDisplayName => EnvironmentInfo.GetVariable("BUILD_DISPLAY_NAME"); /// <summary> /// The current build number, such as "14". /// </summary> public int BuildNumber => EnvironmentInfo.GetVariable<int>("BUILD_NUMBER"); /// <summary> /// The current build tag, such as "jenkins-nuke-14". /// </summary> public string BuildTag => EnvironmentInfo.GetVariable("BUILD_TAG"); /// <summary> /// An identifier corresponding to some kind of change request, such as a pull request number. /// </summary> public string ChangeId => EnvironmentInfo.GetVariable("CHANGE_ID"); /// <summary> /// The number of the executor this build is running on, Equals '0' for first executor. /// </summary> public int ExecutorNumber => EnvironmentInfo.GetVariable<int>("EXECUTOR_NUMBER"); /// <summary> /// For Git-based projects, this variable contains the Git branch that was checked out for the build (normally origin/master) (all the Git* properties require git plugin). /// </summary> public string GitBranch => EnvironmentInfo.GetVariable("GIT_BRANCH"); /// <summary> /// For Git-based projects, this variable contains the Git hash of the commit checked out for the build (like ce9a3c1404e8c91be604088670e93434c4253f03) (all the Git* properties require git plugin). /// </summary> [CanBeNull] public string GitCommit => EnvironmentInfo.GetVariable("GIT_COMMIT"); /// <summary> /// For Git-based projects, this variable contains the Git hash of the previous build commit (like ce9a3c1404e8c91be604088670e93434c4253f03) (all the Git* properties require git plugin). /// </summary> [CanBeNull] public string GitPreviousCommit => EnvironmentInfo.GetVariable("GIT_PREVIOUS_COMMIT"); /// <summary> /// For Git-based projects, this variable contains the Git hash of the last successful build (like ce9a3c1404e8c91be604088670e93434c4253f03) (all the Git* properties require git plugin). /// </summary> [CanBeNull] public string GitPreviousSuccessfulCommit => EnvironmentInfo.GetVariable("GIT_PREVIOUS_SUCCESSFUL_COMMIT"); /// <summary> /// For Git-based projects, this variable contains the Git url (like git@github.com:user/repo.git or [https://github.com/user/repo.git]) (all the Git* properties require git plugin). /// </summary> [CanBeNull] public string GitUrl => EnvironmentInfo.GetVariable("GIT_URL"); /// <summary> /// The path to the jenkins home directory. /// </summary> public string JenkinsHome => EnvironmentInfo.GetVariable("JENKINS_HOME"); /// <summary> /// The jenkins server cookie. /// </summary> public string JenkinsServerCookie => EnvironmentInfo.GetVariable("JENKINS_SERVER_COOKIE"); /// <summary> /// The base name of the current job, such as "Nuke". /// </summary> public string JobBaseName => EnvironmentInfo.GetVariable("JOB_BASE_NAME"); /// <summary> /// The url to the currents job overview. /// </summary> public string JobDisplayUrl => EnvironmentInfo.GetVariable("JOB_DISPLAY_URL"); /// <summary> /// The name of the current job, such as "Nuke". /// </summary> public string JobName => EnvironmentInfo.GetVariable("JOB_NAME"); /// <summary> /// The labels of the node this build is running on, such as "win64 msbuild". /// </summary> public string NodeLabels => EnvironmentInfo.GetVariable("NODE_LABELS"); /// <summary> /// The name of the node this build is running on, such as "master". /// </summary> public string NodeName => EnvironmentInfo.GetVariable("NODE_NAME"); /// <summary> /// The url to the currents run changes page. /// </summary> public string RunChangesDisplayUrl => EnvironmentInfo.GetVariable("RUN_CHANGES_DISPLAY_URL"); /// <summary> /// The url to the currents run overview page. /// </summary> public string RunDisplayUrl => EnvironmentInfo.GetVariable("RUN_DISPLAY_URL"); /// <summary> /// The path to the folder this job is running in. /// </summary> public string Workspace => EnvironmentInfo.GetVariable("WORKSPACE"); }
Jenkins
csharp
dotnet__tye
src/Microsoft.Tye.Hosting.Diagnostics/DiagnosticsProvider.cs
{ "start": 2026, "end": 2164 }
public enum ____ { Logging, Metrics, Tracing, Unknown, }
ProviderKind
csharp
dotnet__aspnetcore
src/Http/Routing/src/Constraints/LengthRouteConstraint.cs
{ "start": 805, "end": 1393 }
class ____ constrains /// a route parameter to be a string of a given length. /// </summary> /// <param name="length">The length of the route parameter.</param> public LengthRouteConstraint(int length) { if (length < 0) { var errorMessage = Resources.FormatArgumentMustBeGreaterThanOrEqualTo(0); throw new ArgumentOutOfRangeException(nameof(length), length, errorMessage); } MinLength = MaxLength = length; } /// <summary> /// Initializes a new instance of the <see cref="LengthRouteConstraint" />
that
csharp
dotnet__orleans
src/Orleans.CodeGenerator/Model/ProxyInterfaceDescription.cs
{ "start": 3338, "end": 6227 }
interface ____. // At the calling side, the explicit implementation will be called if it was not overridden by a derived type. continue; } var methodDescription = CodeGenerator.GetProxyMethodDescription(InterfaceType, method: method); result.Add(methodDescription); } } return result; static IEnumerable<INamedTypeSymbol> GetAllInterfaces(INamedTypeSymbol s) { if (s.TypeKind == TypeKind.Interface) { yield return s; } foreach (var i in s.AllInterfaces) { yield return i; } } } public string Name { get; } public INamedTypeSymbol InterfaceType { get; } public List<ProxyMethodDescription> Methods => _methods ??= GetMethods(); public SemanticModel SemanticModel { get; } public string GeneratedNamespace { get; } public List<(string Name, ITypeParameterSymbol Parameter)> TypeParameters { get; } public INamedTypeSymbol ProxyBaseType { get; } private static void ValidateBaseClass(LibraryTypes l, INamedTypeSymbol baseClass) { ValidateGenericInvokeAsync(l, baseClass); ValidateNonGenericInvokeAsync(l, baseClass); static void ValidateGenericInvokeAsync(LibraryTypes l, INamedTypeSymbol baseClass) { var found = false; string complaint = null; ISymbol complaintMember = null; foreach (var member in baseClass.GetMembers("InvokeAsync")) { if (member is not IMethodSymbol method) { complaintMember = member; complaint = "not a method"; continue; } if (method.TypeParameters.Length != 1) { complaintMember = member; complaint = "incorrect number of type parameters (expected one type parameter)"; continue; } if (method.Parameters.Length != 1) { complaintMember = member; complaint = $"missing parameter (expected a parameter of type {l.IInvokable.ToDisplayString()})"; continue; } var paramType = method.Parameters[0].Type; if (!SymbolEqualityComparer.Default.Equals(paramType, l.IInvokable)) { var implementsIInvokable = false; foreach (var @
behavior
csharp
moq__moq4
src/Moq.Tests/Regressions/IssueReportsFixture.cs
{ "start": 126280, "end": 126936 }
public interface ____ { string this[int index] { get; set; } } } #endregion #region #52 [Fact] public void ShouldNotOverridePreviousExpectation() { var ids = Enumerable.Range(1, 10); var mock = new Mock<IOverwritingMethod>(MockBehavior.Strict); foreach (var id in ids) { mock.Setup(x => x.DoSomething(id)); } var component = mock.Object; foreach (var id in ids) { component.DoSomething(id); } }
ISomeInterface
csharp
FastEndpoints__FastEndpoints
Src/Library/Testing/HttpClientExtensions.cs
{ "start": 435, "end": 41754 }
public static class ____ { /// <summary> /// make a POST request using a request dto and get back a <see cref="TestResult{TResponse}" /> containing the <see cref="HttpResponseMessage" /> as well /// as the <typeparamref name="TResponse" /> DTO/>. /// </summary> /// <typeparam name="TRequest">type of the request dto</typeparam> /// <typeparam name="TResponse">type of the response dto</typeparam> /// <param name="requestUri">the route url to post to</param> /// <param name="request">the request dto</param> /// <param name="sendAsFormData">when set to true, the request dto will be automatically converted to a <see cref="MultipartFormDataContent" /></param> /// <param name="populateHeaders"> /// when set to false, headers will not be automatically added to the http request from request dto properties decorated with the /// [FromHeader] attribute. /// </param> /// <param name="populateCookies"> /// when set to false, cookies will not be automatically added to the http request from request dto properties decorated with the /// [FromCookie] attribute. /// </param> public static Task<TestResult<TResponse>> POSTAsync<TRequest, TResponse>(this HttpClient client, string requestUri, TRequest request, bool sendAsFormData = false, bool populateHeaders = true, bool populateCookies = true) where TRequest : notnull => client.SENDAsync<TRequest, TResponse>(HttpMethod.Post, requestUri, request, sendAsFormData, populateHeaders, populateCookies); /// <summary> /// make a POST request to an endpoint using auto route discovery using a request dto and get back a <see cref="TestResult{TResponse}" /> containing the /// <see cref="HttpResponseMessage" /> as well as the <typeparamref name="TResponse" /> DTO. /// </summary> /// <typeparam name="TEndpoint">the type of the endpoint</typeparam> /// <typeparam name="TRequest">the type of the request dto</typeparam> /// <typeparam name="TResponse">the type of the response dto</typeparam> /// <param name="request">the request dto</param> /// <param name="sendAsFormData">when set to true, the request dto will be automatically converted to a <see cref="MultipartFormDataContent" /></param> /// <param name="populateHeaders"> /// when set to false, headers will not be automatically added to the http request from request dto properties decorated with the /// [FromHeader] attribute. /// </param> /// <param name="populateCookies"> /// when set to false, cookies will not be automatically added to the http request from request dto properties decorated with the /// [FromCookie] attribute. /// </param> public static Task<TestResult<TResponse>> POSTAsync<TEndpoint, TRequest, TResponse>(this HttpClient client, TRequest request, bool sendAsFormData = false, bool populateHeaders = true, bool populateCookies = true) where TEndpoint : IEndpoint where TRequest : notnull => POSTAsync<TRequest, TResponse>(client, GetTestUrlFor<TEndpoint, TRequest>(request), request, sendAsFormData, populateHeaders, populateCookies); /// <summary> /// make a POST request to an endpoint using auto route discovery using a request dto that does not send back a response dto. /// </summary> /// <typeparam name="TEndpoint">the type of the endpoint</typeparam> /// <typeparam name="TRequest">the type of the request dto</typeparam> /// <param name="request">the request dto</param> /// <param name="sendAsFormData">when set to true, the request dto will be automatically converted to a <see cref="MultipartFormDataContent" /></param> /// <param name="populateHeaders"> /// when set to false, headers will not be automatically added to the http request from request dto properties decorated with the /// [FromHeader] attribute. /// </param> /// <param name="populateCookies"> /// when set to false, cookies will not be automatically added to the http request from request dto properties decorated with the /// [FromCookie] attribute. /// </param> public static async Task<HttpResponseMessage> POSTAsync<TEndpoint, TRequest>(this HttpClient client, TRequest request, bool sendAsFormData = false, bool populateHeaders = true, bool populateCookies = true) where TEndpoint : IEndpoint where TRequest : notnull { var (rsp, _) = await POSTAsync<TEndpoint, TRequest, EmptyResponse>(client, request, sendAsFormData, populateHeaders, populateCookies); return rsp; } /// <summary> /// make a POST request to an endpoint using auto route discovery without a request dto and get back a <see cref="TestResult{TResponse}" /> containing /// the <see cref="HttpResponseMessage" /> as well as the <typeparamref name="TResponse" /> DTO. /// </summary> /// <typeparam name="TEndpoint">the type of the endpoint</typeparam> /// <typeparam name="TResponse">the type of the response dto</typeparam> public static Task<TestResult<TResponse>> POSTAsync<TEndpoint, TResponse>(this HttpClient client) where TEndpoint : IEndpoint => POSTAsync<TEndpoint, EmptyRequest, TResponse>(client, new()); /// <summary> /// make a PATCH request using a request dto and get back a <see cref="TestResult{TResponse}" /> containing the <see cref="HttpResponseMessage" /> as /// well as the <typeparamref name="TResponse" /> DTO. /// </summary> /// <typeparam name="TRequest">type of the request dto</typeparam> /// <typeparam name="TResponse">type of the response dto</typeparam> /// <param name="requestUri">the route url to PATCH to</param> /// <param name="request">the request dto</param> /// <param name="sendAsFormData">when set to true, the request dto will be automatically converted to a <see cref="MultipartFormDataContent" /></param> /// <param name="populateHeaders"> /// when set to false, headers will not be automatically added to the http request from request dto properties decorated with the /// [FromHeader] attribute. /// </param> /// <param name="populateCookies"> /// when set to false, cookies will not be automatically added to the http request from request dto properties decorated with the /// [FromCookie] attribute. /// </param> public static Task<TestResult<TResponse>> PATCHAsync<TRequest, TResponse>(this HttpClient client, string requestUri, TRequest request, bool sendAsFormData = false, bool populateHeaders = true, bool populateCookies = true) where TRequest : notnull => client.SENDAsync<TRequest, TResponse>(HttpMethod.Patch, requestUri, request, sendAsFormData, populateHeaders, populateCookies); /// <summary> /// make a PATCH request to an endpoint using auto route discovery using a request dto and get back a <see cref="TestResult{TResponse}" /> containing the /// <see cref="HttpResponseMessage" /> as well as the <typeparamref name="TResponse" /> DTO. /// </summary> /// <typeparam name="TEndpoint">the type of the endpoint</typeparam> /// <typeparam name="TRequest">the type of the request dto</typeparam> /// <typeparam name="TResponse">the type of the response dto</typeparam> /// <param name="request">the request dto</param> /// <param name="sendAsFormData">when set to true, the request dto will be automatically converted to a <see cref="MultipartFormDataContent" /></param> /// <param name="populateHeaders"> /// when set to true, headers will be automatically added to the http request from request dto properties decorated with the [FromHeader] attribute. /// </param> public static Task<TestResult<TResponse>> PATCHAsync<TEndpoint, TRequest, TResponse>(this HttpClient client, TRequest request, bool sendAsFormData = false, bool populateHeaders = true, bool populateCookies = true) where TEndpoint : IEndpoint where TRequest : notnull => PATCHAsync<TRequest, TResponse>(client, GetTestUrlFor<TEndpoint, TRequest>(request), request, sendAsFormData, populateHeaders, populateCookies); /// <summary> /// make a PATCH request to an endpoint using auto route discovery using a request dto that does not send back a response dto. /// </summary> /// <typeparam name="TEndpoint">the type of the endpoint</typeparam> /// <typeparam name="TRequest">the type of the request dto</typeparam> /// <param name="request">the request dto</param> /// <param name="sendAsFormData">when set to true, the request dto will be automatically converted to a <see cref="MultipartFormDataContent" /></param> /// <param name="populateHeaders"> /// when set to false, headers will not be automatically added to the http request from request dto properties decorated with the /// [FromHeader] attribute. /// </param> /// <param name="populateCookies"> /// when set to false, cookies will not be automatically added to the http request from request dto properties decorated with the /// [FromCookie] attribute. /// </param> public static async Task<HttpResponseMessage> PATCHAsync<TEndpoint, TRequest>(this HttpClient client, TRequest request, bool sendAsFormData = false, bool populateHeaders = true, bool populateCookies = true) where TEndpoint : IEndpoint where TRequest : notnull { var (rsp, _) = await PATCHAsync<TEndpoint, TRequest, EmptyResponse>(client, request, sendAsFormData, populateHeaders, populateCookies); return rsp; } /// <summary> /// make a PATCH request to an endpoint using auto route discovery without a request dto and get back a <see cref="TestResult{TResponse}" /> containing /// the <see cref="HttpResponseMessage" /> as well as the <typeparamref name="TResponse" /> DTO. /// </summary> /// <typeparam name="TEndpoint">the type of the endpoint</typeparam> /// <typeparam name="TResponse">the type of the response dto</typeparam> public static Task<TestResult<TResponse>> PATCHAsync<TEndpoint, TResponse>(this HttpClient client) where TEndpoint : IEndpoint => PATCHAsync<TEndpoint, EmptyRequest, TResponse>(client, new()); /// <summary> /// make a PUT request using a request dto and get back a <see cref="TestResult{TResponse}" /> containing the <see cref="HttpResponseMessage" /> as well /// as the <typeparamref name="TResponse" /> DTO. /// </summary> /// <typeparam name="TRequest">type of the request dto</typeparam> /// <typeparam name="TResponse">type of the response dto</typeparam> /// <param name="requestUri">the route url to post to</param> /// <param name="request">the request dto</param> /// <param name="sendAsFormData">when set to true, the request dto will be automatically converted to a <see cref="MultipartFormDataContent" /></param> /// <param name="populateHeaders"> /// when set to false, headers will not be automatically added to the http request from request dto properties decorated with the /// [FromHeader] attribute. /// </param> /// <param name="populateCookies"> /// when set to false, cookies will not be automatically added to the http request from request dto properties decorated with the /// [FromCookie] attribute. /// </param> public static Task<TestResult<TResponse>> PUTAsync<TRequest, TResponse>(this HttpClient client, string requestUri, TRequest request, bool sendAsFormData = false, bool populateHeaders = true, bool populateCookies = true) where TRequest : notnull => client.SENDAsync<TRequest, TResponse>(HttpMethod.Put, requestUri, request, sendAsFormData, populateHeaders, populateCookies); /// <summary> /// make a PUT request to an endpoint using auto route discovery using a request dto and get back a <see cref="TestResult{TResponse}" /> containing the /// <see cref="HttpResponseMessage" /> as well as the <typeparamref name="TResponse" /> DTO. /// </summary> /// <typeparam name="TEndpoint">the type of the endpoint</typeparam> /// <typeparam name="TRequest">the type of the request dto</typeparam> /// <typeparam name="TResponse">the type of the response dto</typeparam> /// <param name="request">the request dto</param> /// <param name="sendAsFormData">when set to true, the request dto will be automatically converted to a <see cref="MultipartFormDataContent" /></param> /// <param name="populateHeaders"> /// when set to false, headers will not be automatically added to the http request from request dto properties decorated with the /// [FromHeader] attribute. /// </param> /// <param name="populateCookies"> /// when set to false, cookies will not be automatically added to the http request from request dto properties decorated with the /// [FromCookie] attribute. /// </param> public static Task<TestResult<TResponse>> PUTAsync<TEndpoint, TRequest, TResponse>(this HttpClient client, TRequest request, bool sendAsFormData = false, bool populateHeaders = true, bool populateCookies = true) where TEndpoint : IEndpoint where TRequest : notnull => PUTAsync<TRequest, TResponse>(client, GetTestUrlFor<TEndpoint, TRequest>(request), request, sendAsFormData, populateHeaders, populateCookies); /// <summary> /// make a PUT request to an endpoint using auto route discovery using a request dto that does not send back a response dto. /// </summary> /// <typeparam name="TEndpoint">the type of the endpoint</typeparam> /// <typeparam name="TRequest">the type of the request dto</typeparam> /// <param name="request">the request dto</param> /// <param name="sendAsFormData">when set to true, the request dto will be automatically converted to a <see cref="MultipartFormDataContent" /></param> /// <param name="populateHeaders"> /// when set to false, headers will not be automatically added to the http request from request dto properties decorated with the /// [FromHeader] attribute. /// </param> /// <param name="populateCookies"> /// when set to false, cookies will not be automatically added to the http request from request dto properties decorated with the /// [FromCookie] attribute. /// </param> public static async Task<HttpResponseMessage> PUTAsync<TEndpoint, TRequest>(this HttpClient client, TRequest request, bool sendAsFormData = false, bool populateHeaders = true, bool populateCookies = true) where TEndpoint : IEndpoint where TRequest : notnull { var (rsp, _) = await PUTAsync<TEndpoint, TRequest, EmptyResponse>(client, request, sendAsFormData, populateHeaders, populateCookies); return rsp; } /// <summary> /// make a PUT request to an endpoint using auto route discovery without a request dto and get back a <see cref="TestResult{TResponse}" /> containing the /// <see cref="HttpResponseMessage" /> as well as the <typeparamref name="TResponse" /> DTO. /// </summary> /// <typeparam name="TEndpoint">the type of the endpoint</typeparam> /// <typeparam name="TResponse">the type of the response dto</typeparam> public static Task<TestResult<TResponse>> PUTAsync<TEndpoint, TResponse>(this HttpClient client) where TEndpoint : IEndpoint => PUTAsync<TEndpoint, EmptyRequest, TResponse>(client, new()); /// <summary> /// make a GET request using a request dto and get back a <see cref="TestResult{TResponse}" /> containing the <see cref="HttpResponseMessage" /> as well /// as the <typeparamref name="TResponse" /> DTO. /// </summary> /// <typeparam name="TRequest">type of the request dto</typeparam> /// <typeparam name="TResponse">type of the response dto</typeparam> /// <param name="requestUri">the route url to post to</param> /// <param name="request">the request dto</param> /// <param name="populateHeaders"> /// when set to false, headers will not be automatically added to the http request from request dto properties decorated with the /// [FromHeader] attribute. /// </param> /// <param name="populateCookies"> /// when set to false, cookies will not be automatically added to the http request from request dto properties decorated with the /// [FromCookie] attribute. /// </param> public static Task<TestResult<TResponse>> GETAsync<TRequest, TResponse>(this HttpClient client, string requestUri, TRequest request, bool populateHeaders = true, bool populateCookies = true) where TRequest : notnull => client.SENDAsync<TRequest, TResponse>(HttpMethod.Get, requestUri, request, populateHeaders: populateHeaders, populateCookies: populateCookies); /// <summary> /// make a GET request to an endpoint using auto route discovery using a request dto and get back a <see cref="TestResult{TResponse}" /> containing the /// <see cref="HttpResponseMessage" /> as well as the <typeparamref name="TResponse" /> DTO. /// </summary> /// <typeparam name="TEndpoint">the type of the endpoint</typeparam> /// <typeparam name="TRequest">the type of the request dto</typeparam> /// <typeparam name="TResponse">the type of the response dto</typeparam> /// <param name="request">the request dto</param> /// <param name="populateHeaders"> /// when set to false, headers will not be automatically added to the http request from request dto properties decorated with the /// [FromHeader] attribute. /// </param> /// <param name="populateCookies"> /// when set to false, cookies will not be automatically added to the http request from request dto properties decorated with the /// [FromCookie] attribute. /// </param> public static Task<TestResult<TResponse>> GETAsync<TEndpoint, TRequest, TResponse>(this HttpClient client, TRequest request, bool populateHeaders = true, bool populateCookies = true) where TEndpoint : IEndpoint where TRequest : notnull => GETAsync<TRequest, TResponse>(client, GetTestUrlFor<TEndpoint, TRequest>(request), request, populateHeaders, populateCookies); /// <summary> /// make a GET request to an endpoint using auto route discovery using a request dto that does not send back a response dto. /// </summary> /// <typeparam name="TEndpoint">the type of the endpoint</typeparam> /// <typeparam name="TRequest">the type of the request dto</typeparam> /// <param name="request">the request dto</param> /// <param name="populateHeaders"> /// when set to false, headers will not be automatically added to the http request from request dto properties decorated with the /// [FromHeader] attribute. /// </param> /// <param name="populateCookies"> /// when set to false, cookies will not be automatically added to the http request from request dto properties decorated with the /// [FromCookie] attribute. /// </param> public static async Task<HttpResponseMessage> GETAsync<TEndpoint, TRequest>(this HttpClient client, TRequest request, bool populateHeaders = true, bool populateCookies = true) where TEndpoint : IEndpoint where TRequest : notnull { var (rsp, _) = await GETAsync<TEndpoint, TRequest, EmptyResponse>(client, request, populateHeaders, populateCookies); return rsp; } /// <summary> /// make a GET request to an endpoint using auto route discovery without a request dto and get back a <see cref="TestResult{TResponse}" /> containing the /// <see cref="HttpResponseMessage" /> as well as the <typeparamref name="TResponse" /> DTO. /// </summary> /// <typeparam name="TEndpoint">the type of the endpoint</typeparam> /// <typeparam name="TResponse">the type of the response dto</typeparam> public static Task<TestResult<TResponse>> GETAsync<TEndpoint, TResponse>(this HttpClient client) where TEndpoint : IEndpoint => GETAsync<TEndpoint, EmptyRequest, TResponse>(client, new()); /// <summary> /// make a DELETE request using a request dto and get back a <see cref="TestResult{TResponse}" /> containing the <see cref="HttpResponseMessage" /> as /// well as the <typeparamref name="TResponse" /> DTO. /// </summary> /// <typeparam name="TRequest">type of the request dto</typeparam> /// <typeparam name="TResponse">type of the response dto</typeparam> /// <param name="requestUri">the route url to post to</param> /// <param name="request">the request dto</param> /// <param name="populateHeaders"> /// when set to false, headers will not be automatically added to the http request from request dto properties decorated with the /// [FromHeader] attribute. /// </param> /// <param name="populateCookies"> /// when set to false, cookies will not be automatically added to the http request from request dto properties decorated with the /// [FromCookie] attribute. /// </param> public static Task<TestResult<TResponse>> DELETEAsync<TRequest, TResponse>(this HttpClient client, string requestUri, TRequest request, bool populateHeaders = true, bool populateCookies = true) where TRequest : notnull => client.SENDAsync<TRequest, TResponse>(HttpMethod.Delete, requestUri, request, populateHeaders: populateHeaders, populateCookies: populateCookies); /// <summary> /// make a DELETE request to an endpoint using auto route discovery using a request dto and get back a <see cref="TestResult{TResponse}" /> containing /// the <see cref="HttpResponseMessage" /> as well as the <typeparamref name="TResponse" /> DTO. /// </summary> /// <typeparam name="TEndpoint">the type of the endpoint</typeparam> /// <typeparam name="TRequest">the type of the request dto</typeparam> /// <typeparam name="TResponse">the type of the response dto</typeparam> /// <param name="request">the request dto</param> /// <param name="populateHeaders"> /// when set to false, headers will not be automatically added to the http request from request dto properties decorated with the /// [FromHeader] attribute. /// </param> /// <param name="populateCookies"> /// when set to false, cookies will not be automatically added to the http request from request dto properties decorated with the /// [FromCookie] attribute. /// </param> public static Task<TestResult<TResponse>> DELETEAsync<TEndpoint, TRequest, TResponse>(this HttpClient client, TRequest request, bool populateHeaders = true, bool populateCookies = true) where TEndpoint : IEndpoint where TRequest : notnull => DELETEAsync<TRequest, TResponse>(client, GetTestUrlFor<TEndpoint, TRequest>(request), request, populateHeaders, populateCookies); /// <summary> /// make a DELETE request to an endpoint using auto route discovery using a request dto that does not send back a response dto. /// </summary> /// <typeparam name="TEndpoint">the type of the endpoint</typeparam> /// <typeparam name="TRequest">the type of the request dto</typeparam> /// <param name="request">the request dto</param> /// <param name="populateHeaders"> /// when set to false, headers will not be automatically added to the http request from request dto properties decorated with the /// [FromHeader] attribute. /// </param> /// <param name="populateCookies"> /// when set to false, cookies will not be automatically added to the http request from request dto properties decorated with the /// [FromCookie] attribute. /// </param> public static async Task<HttpResponseMessage> DELETEAsync<TEndpoint, TRequest>(this HttpClient client, TRequest request, bool populateHeaders = true, bool populateCookies = true) where TEndpoint : IEndpoint where TRequest : notnull { var (rsp, _) = await DELETEAsync<TEndpoint, TRequest, EmptyResponse>(client, request, populateHeaders, populateCookies); return rsp; } /// <summary> /// make a DELETE request to an endpoint using auto route discovery without a request dto and get back a <see cref="TestResult{TResponse}" /> containing /// the <see cref="HttpResponseMessage" /> as well as the <typeparamref name="TResponse" /> DTO. /// </summary> /// <typeparam name="TEndpoint">the type of the endpoint</typeparam> /// <typeparam name="TResponse">the type of the response dto</typeparam> public static Task<TestResult<TResponse>> DELETEAsync<TEndpoint, TResponse>(this HttpClient client) where TEndpoint : IEndpoint => DELETEAsync<TEndpoint, EmptyRequest, TResponse>(client, new()); /// <summary> /// send a request DTO to a given endpoint URL and get back a <see cref="TestResult{TResponse}" /> containing the <see cref="HttpResponseMessage" /> as /// well as the <typeparamref name="TResponse" /> DTO /// </summary> /// <typeparam name="TRequest">type of the request dto</typeparam> /// <typeparam name="TResponse">type of the response dto</typeparam> /// <param name="method">the http method to use</param> /// <param name="requestUri">the route url of the endpoint</param> /// <param name="request">the request dto</param> /// <param name="sendAsFormData">when set to true, the request dto will be automatically converted to a <see cref="MultipartFormDataContent" /></param> /// <param name="populateHeaders"> /// when set to false, headers will not be automatically added to the http request from request dto properties decorated with the /// [FromHeader] attribute. /// </param> /// <param name="populateCookies"> /// when set to false, cookies will not be automatically added to the http request from request dto properties decorated with the /// [FromCookie] attribute. /// </param> public static async Task<TestResult<TResponse>> SENDAsync<TRequest, TResponse>(this HttpClient client, HttpMethod method, string requestUri, TRequest request, bool sendAsFormData = false, bool populateHeaders = true, bool populateCookies = true) where TRequest : notnull { var msg = new HttpRequestMessage { Method = method, RequestUri = new($"{client.BaseAddress}{requestUri.TrimStart('/')}"), Content = sendAsFormData ? request.ToForm() : new StringContent(JsonSerializer.Serialize(request, SerOpts.Options), Encoding.UTF8, "application/json") }; msg.Headers.Add(Constants.RoutelessTest, "true"); if (populateHeaders) PopulateHeaders(msg, request); if (populateCookies) PopulateCookies(msg, request); var rsp = await client.SendAsync(msg); var hasNoJsonContent = rsp.Content.Headers.ContentType?.MediaType?.Contains("json") is null or false; TResponse? res = default!; if (typeof(TResponse) == Types.EmptyResponse || hasNoJsonContent) return new(rsp, res); if (rsp.IsSuccessStatusCode) { //this disposes the content stream. test code doesn't need to read it again. res = await rsp.Content.ReadFromJsonAsync<TResponse>(SerOpts.Options); } else { //make a copy of the content stream to allow test code to read content stream. using var copy = new MemoryStream(); await rsp.Content.CopyToAsync(copy); //this doesn't dispose the original stream. copy.Position = 0; try { res = await JsonSerializer.DeserializeAsync<TResponse>(copy, SerOpts.Options); } catch { //do nothing } } return new(rsp, res!); } static readonly string[] contentHeaders = [ "Content-Encoding", "Content-Language", "Content-Length", "Content-Location", "Content-MD5", "Content-Range", "Content-Type" ]; static void PopulateHeaders<TRequest>(HttpRequestMessage reqMsg, TRequest req) where TRequest : notnull { var hdrProps = req.GetType() .BindableProps() .Where(p => p.GetCustomAttribute<FromHeaderAttribute>()?.IsRequired is true); foreach (var prop in hdrProps) { var headerName = prop.GetCustomAttribute<FromHeaderAttribute>()?.HeaderName ?? prop.FieldName(); var headerValue = prop.GetValueAsString(req); if (!contentHeaders.Contains(headerName, StringComparer.OrdinalIgnoreCase)) reqMsg.Headers.Add(headerName, headerValue); } } static void PopulateCookies<TRequest>(HttpRequestMessage reqMsg, TRequest req) where TRequest : notnull { if (reqMsg.RequestUri is null) return; var cookieProps = req.GetType() .BindableProps() .Where(p => p.GetCustomAttribute<FromCookieAttribute>()?.IsRequired is true); var cookieJar = new CookieContainer(); foreach (var prop in cookieProps) { var cookieName = prop.GetCustomAttribute<FromCookieAttribute>()?.CookieName ?? prop.FieldName(); var cookieValue = prop.GetValueAsString(req); cookieJar.Add(new Cookie(cookieName, cookieValue, "/", reqMsg.RequestUri.Host)); } if (cookieJar.Count == 0) return; reqMsg.Headers.Add("Cookie", cookieJar.GetCookieHeader(reqMsg.RequestUri)); } static string GetTestUrlFor<TEndpoint, TRequest>(TRequest req) where TRequest : notnull { // request with multiple repeating dtos, most likely not populated from route values. // we don't know which one to populate from anyway. if (req is IEnumerable) return IEndpoint.TestURLFor<TEndpoint>(); //get props and stick em in a dictionary for easy lookup //ignore props annotated with security/header/cookie attributes that has IsRequired set to true. var reqProps = req.GetType() .BindableProps() .Where( p => p.GetCustomAttribute<FromClaimAttribute>()?.IsRequired is not true && p.GetCustomAttribute<FromHeaderAttribute>()?.IsRequired is not true && p.GetCustomAttribute<HasPermissionAttribute>()?.IsRequired is not true && p.GetCustomAttribute<FromCookieAttribute>()?.IsRequired is not true) .ToDictionary(p => p.FieldName(), StringComparer.OrdinalIgnoreCase); //split url into route segments, iterate and replace param names with values from matching dto props //while rebuilding the url back up again into a string builder StringBuilder sb = new(); var routeSegments = IEndpoint.TestURLFor<TEndpoint>() .Split('/', StringSplitOptions.RemoveEmptyEntries); // group root endpoints are allowed to set string.empty #988 foreach (var segment in routeSegments) { if (!segment.StartsWith('{') && !segment.EndsWith('}')) { sb.Append(segment).Append('/'); continue; } //examples: {id}, {id?}, {id:int}, {ssn:regex(^\\d{{3}}-\\d{{2}}-\\d{{4}}$)} var segmentParts = segment.Split(':', StringSplitOptions.RemoveEmptyEntries); var isLastSegment = routeSegments.Last() == segment; var isOptional = segment.Contains('?'); var propName = (segmentParts.Length == 1 ? segmentParts[0][1..^1] : segmentParts[0][1..]).TrimEnd('?'); var propVal = reqProps.TryGetValue(propName, out var prop) ? prop.GetValueAsString(req) : segment; if (propVal is null) { switch (isOptional) { case true when isLastSegment: continue; case true when !isLastSegment: throw new InvalidOperationException($"Optional route parameter [{segment}] must be the last route segment."); case false: throw new InvalidOperationException($"Route param value missing for required param [{segment}]."); } } sb.Append(propVal); sb.Append('/'); } sb.Length--; //remove the last '/' //append query parameters if there's any props decorated with [QueryParam] var queryParamProps = reqProps.Where(p => p.Value.GetCustomAttribute<DontBindAttribute>()?.BindingSources.HasFlag(Source.QueryParam) is false).ToArray(); if (queryParamProps.Length > 0) { sb.Append('?'); foreach (var qp in queryParamProps) sb.Append(qp.Key).Append('=').Append(qp.Value.GetValueAsString(req)).Append('&'); sb.Length--; //remove the last '&' } return sb.ToString(); } static MultipartFormDataContent ToForm<TRequest>(this TRequest req) { var form = new MultipartFormDataContent(); foreach (var p in req!.GetType().BindableProps()) { if (p.PropertyType.GetUnderlyingType() == Types.IFormFile) AddFileToForm(p.GetValue(req) as IFormFile, p); else if (p.PropertyType.IsAssignableTo(Types.IEnumerableOfIFormFile)) { var files = p.GetValue(req) as IFormFileCollection; if (files?.Count is 0 or null) continue; foreach (var file in files) AddFileToForm(file, p); } else { var value = p.GetValueAsString(req); if (value is not null) form.Add(new StringContent(value), p.Name); } } return !form.Any() ? throw new InvalidOperationException("Converting the request DTO to MultipartFormDataContent was unsuccessful!") : form; void AddFileToForm(IFormFile? file, PropertyInfo prop) { if (file is null) return; var content = new StreamContent(file.OpenReadStream()); // ReSharper disable once ConditionalAccessQualifierIsNonNullableAccordingToAPIContract if (file.Headers?.ContainsKey(HeaderNames.ContentType) is true) content.Headers.ContentType = new(file.ContentType); form.Add(content, prop.FieldName(), file.FileName); } } static string? GetValueAsString(this PropertyInfo p, object req) { var value = p.GetValue(req); if (value is null) return null; var type = p.PropertyType; var toStringMethod = type.GetMethod("ToString", Type.EmptyTypes); var isRecord = type.GetMethod("<Clone>$") is not null; //use overridden ToString() method except for records if (toStringMethod is not null && toStringMethod.DeclaringType != Types.Object && isRecord is false) return value.ToString(); try { var json = JsonSerializer.Serialize(value, SerOpts.Options); //this is a json string literal if (json.StartsWith('"') && json.EndsWith('"')) return json.TrimStart('"').TrimEnd('"'); //this is either a json array or object return json; } catch { if (p.IsDefined(Types.FromFormAttribute)) { throw new NotSupportedException( "Automatically constructing MultiPartFormData requests for properties annotated with [FromForm] is not yet supported!"); } throw; } } }
HttpClientExtensions
csharp
MassTransit__MassTransit
tests/MassTransit.Azure.Cosmos.Tests/AzureCosmosTestTokenCredentialConfigurator.cs
{ "start": 83, "end": 451 }
public class ____ : IAzureCosmosTestAuthenticationConfigurator { public void Configure(ICosmosSagaRepositoryConfigurator configurator) { configurator.AccountEndpoint = Configuration.AccountEndpoint; configurator.TokenCredential = new DefaultAzureCredential(); } } }
AzureCosmosTestTokenCredentialConfigurator
csharp
abpframework__abp
modules/docs/src/Volo.Docs.Application/Volo/Docs/DocsApplicationMappers.cs
{ "start": 236, "end": 600 }
public partial class ____ : MapperBase<DocumentResource, DocumentResourceDto> { public override partial DocumentResourceDto Map(DocumentResource source); public override partial void Map(DocumentResource source, DocumentResourceDto destination); } [Mapper(RequiredMappingStrategy = RequiredMappingStrategy.Target)]
DocumentResourceToDocumentResourceDtoMapper
csharp
ServiceStack__ServiceStack
ServiceStack.OrmLite/tests/ServiceStack.OrmLite.Tests/Issues/SelectAliasIssue.cs
{ "start": 967, "end": 2134 }
public class ____(DialectContext context) : OrmLiteProvidersTestBase(context) { [Test] public void Does_populate_table_with_Aliases_having_same_name_as_alternative_field() { using var db = OpenDbConnection(); db.DropAndCreateTable<AddressAudit>(); db.Insert(new AddressAudit { AddressId = 11 }); db.Insert(new AddressAudit { AddressId = 12 }); db.Insert(new AddressAudit { AddressId = 13 }); var rows = db.Select<AddressAudit>(); Assert.That(rows.All(x => x.Id > 0)); var debtor = db.SingleById<AddressAudit>(2); var row = db.Single<AddressAudit>(audit => audit.AddressId == debtor.AddressId); row.PrintDump(); } [Test] public void Select_against_interface_in_generic_method() { using var db = OpenDbConnection(); db.CreateTable<TestLookup>(); var newRecord = new TestLookup {Name = "new"}; var lkp = db.Single<TestLookup>(r => r.Name == newRecord.Name); var lookup = db.Lookup(newRecord); Assert.That(lookup.Id != Guid.Empty); } }
SelectAliasIssue
csharp
mongodb__mongo-csharp-driver
src/MongoDB.Bson/Serialization/IBsonSerializer.cs
{ "start": 730, "end": 1762 }
public interface ____ { // properties /// <summary> /// Gets the type of the value. /// </summary> /// <value> /// The type of the value. /// </value> Type ValueType { get; } // methods /// <summary> /// Deserializes a value. /// </summary> /// <param name="context">The deserialization context.</param> /// <param name="args">The deserialization args.</param> /// <returns>A deserialized value.</returns> object Deserialize(BsonDeserializationContext context, BsonDeserializationArgs args); /// <summary> /// Serializes a value. /// </summary> /// <param name="context">The serialization context.</param> /// <param name="args">The serialization args.</param> /// <param name="value">The value.</param> void Serialize(BsonSerializationContext context, BsonSerializationArgs args, object value); } /// <summary> /// An
IBsonSerializer
csharp
dotnet__machinelearning
src/Microsoft.Data.Analysis/TextFieldParser.cs
{ "start": 3782, "end": 39331 }
internal class ____ : IDisposable { private delegate int ChangeBufferFunction(); private bool _disposed; private TextReader _reader; private string[] _commentTokens = null; private long _lineNumber = 1; private bool _endOfData; private string _errorLine = ""; private long _errorLineNumber = -1; private FieldType _textFieldType = FieldType.Delimited; private int[] _fieldWidths; private int[] _fieldWidthsCopy; private string[] _delimiters; private string[] _delimitersCopy; private Regex _delimiterRegex; private Regex _delimiterWithEndCharsRegex; private readonly int[] _whitespaceCodes = new int[] { '\u0009', '\u000B', '\u000C', '\u0020', '\u0085', '\u00A0', '\u1680', '\u2000', '\u2001', '\u2002', '\u2003', '\u2004', '\u2005', '\u2006', '\u2007', '\u2008', '\u2009', '\u200A', '\u200B', '\u2028', '\u2029', '\u3000', '\uFEFF' }; private Regex _beginQuotesRegex; private bool _trimWhiteSpace = true; private int _position; private int _peekPosition; private int _charsRead; private bool _needPropertyCheck = true; private const int DEFAULT_BUFFER_LENGTH = 4096; private char[] _buffer = new char[DEFAULT_BUFFER_LENGTH]; private bool _hasFieldsEnclosedInQuotes = true; private int _lineLength; private string _spaceChars; private readonly int _maxLineSize = 10000000; private readonly int _maxBufferSize = 10000000; private readonly bool _leaveOpen; private readonly char[] _newLineChars = Environment.NewLine.ToCharArray(); public string[] CommentTokens { get => _commentTokens; set { CheckCommentTokensForWhitespace(value); _commentTokens = value; _needPropertyCheck = true; } } public bool EndOfData { get { if (_endOfData) { return _endOfData; } if ((_reader == null) || (_buffer == null)) { _endOfData = true; return true; } if (PeekNextDataLine() != null) { return false; } _endOfData = true; return true; } } public long LineNumber { get { if (_lineNumber != -1 && ((_reader.Peek() == -1) && (_position == _charsRead))) { // Side effect of a property. Not great. Just leaving it in for now. CloseReader(); } return _lineNumber; } } public string ErrorLine => _errorLine; public long ErrorLineNumber => _errorLineNumber; public FieldType TextFieldType { get => _textFieldType; set { ValidateFieldTypeEnumValue(value, "value"); _textFieldType = value; _needPropertyCheck = true; } } public int[] FieldWidths { get => _fieldWidths; private set { if (value != null) { ValidateFieldWidthsOnInput(value); _fieldWidthsCopy = (int[])value.Clone(); } else { _fieldWidthsCopy = null; } _fieldWidths = value; _needPropertyCheck = true; } } public string[] Delimiters { get => _delimiters; private set { if (value != null) { ValidateDelimiters(value); _delimitersCopy = (string[])value.Clone(); } else { _delimitersCopy = null; } _delimiters = value; _needPropertyCheck = true; _beginQuotesRegex = null; } } public bool TrimWhiteSpace { get => _trimWhiteSpace; set { _trimWhiteSpace = value; } } public bool HasFieldsEnclosedInQuotes { get => _hasFieldsEnclosedInQuotes; set { _hasFieldsEnclosedInQuotes = value; } } private Regex BeginQuotesRegex { get { if (_beginQuotesRegex == null) { string pattern = string.Format(CultureInfo.InvariantCulture, "\\G[{0}]*\"", WhitespacePattern); _beginQuotesRegex = new Regex(pattern, RegexOptions.CultureInvariant); } return _beginQuotesRegex; } } private string EndQuotePattern => string.Format(CultureInfo.InvariantCulture, "\"[{0}]*", WhitespacePattern); private string WhitespaceCharacters { get { StringBuilder builder = new StringBuilder(); int[] whitespaceCodes = _whitespaceCodes; foreach (int code in whitespaceCodes) { char spaceChar = (char)code; if (!CharacterIsInDelimiter(spaceChar)) { builder.Append(spaceChar); } } return builder.ToString(); } } private string WhitespacePattern { get { StringBuilder builder = new StringBuilder(); int[] whitespaceCodes = _whitespaceCodes; for (int i = 0; i < whitespaceCodes.Length; i++) { int code = whitespaceCodes[i]; char spaceChar = (char)code; if (!CharacterIsInDelimiter(spaceChar)) { builder.Append("\\u" + code.ToString("X4", CultureInfo.InvariantCulture)); } } return builder.ToString(); } } public TextFieldParser(string path) { InitializeFromPath(path, Encoding.ASCII, detectEncoding: true); } public TextFieldParser(string path, Encoding defaultEncoding) { InitializeFromPath(path, defaultEncoding, detectEncoding: true); } public TextFieldParser(string path, Encoding defaultEncoding, bool detectEncoding) { InitializeFromPath(path, defaultEncoding, detectEncoding); } public TextFieldParser(Stream stream) { InitializeFromStream(stream, Encoding.ASCII, detectEncoding: true); } public TextFieldParser(Stream stream, Encoding defaultEncoding) { InitializeFromStream(stream, defaultEncoding, detectEncoding: true); } public TextFieldParser(Stream stream, Encoding defaultEncoding, bool detectEncoding) { InitializeFromStream(stream, defaultEncoding, detectEncoding); } public TextFieldParser(Stream stream, Encoding defaultEncoding, bool detectEncoding, bool leaveOpen) { _leaveOpen = leaveOpen; InitializeFromStream(stream, defaultEncoding, detectEncoding); } public TextFieldParser(TextReader reader) { _reader = reader ?? throw new ArgumentNullException(nameof(reader)); ReadToBuffer(); } public void SetDelimiters(params string[] delimiters) { Delimiters = delimiters; } public void SetFieldWidths(params int[] fieldWidths) { FieldWidths = fieldWidths; } public string ReadLine() { if ((_reader == null) || (_buffer == null)) { return null; } ChangeBufferFunction BufferFunction = ReadToBuffer; string line = ReadNextLine(ref _position, BufferFunction); if (line == null) { FinishReading(); return null; } _lineNumber++; return line.TrimEnd(_newLineChars); } public string[] ReadFields() { if ((_reader == null) || (_buffer == null)) { return null; } ValidateReadyToRead(); switch (_textFieldType) { case FieldType.FixedWidth: return ParseFixedWidthLine(); case FieldType.Delimited: return ParseDelimitedLine(); default: Debug.Fail("The TextFieldType is not supported"); return null; } } ///<summary> /// Peek at <paramref name="numberOfChars"/> characters of the next data line without reading the line ///</summary> ///<param name="numberOfChars">The number of characters to look at in the next data line.</param> ///<returns>A string consisting of the first <paramref name="numberOfChars"/> characters of the next line. >If numberOfChars is greater than the next line, only the next line is returned</returns> public string PeekChars(int numberOfChars) { if (numberOfChars <= 0) { throw new ArgumentException(string.Format(Strings.PositiveNumberOfCharacters, nameof(numberOfChars))); } if ((_reader == null) || (_buffer == null)) { return null; } if (_endOfData) { return null; } string line = PeekNextDataLine(); if (line == null) { _endOfData = true; return null; } line = line.TrimEnd(_newLineChars); if (line.Length < numberOfChars) { return line; } return line.Substring(0, numberOfChars); } public string ReadToEnd() { if ((_reader == null) || (_buffer == null)) { return null; } StringBuilder builder = new StringBuilder(_buffer.Length); builder.Append(_buffer, _position, _charsRead - _position); builder.Append(_reader.ReadToEnd()); FinishReading(); return builder.ToString(); } public void Close() { CloseReader(); } public void Dispose() { Dispose(disposing: true); GC.SuppressFinalize(this); } protected virtual void Dispose(bool disposing) { if (disposing) { if (!_disposed) { Close(); } _disposed = true; } } private void ValidateFieldTypeEnumValue(FieldType value, string paramName) { if (value < FieldType.Delimited || value > FieldType.FixedWidth) { throw new InvalidEnumArgumentException(paramName, (int)value, typeof(FieldType)); } } private void CloseReader() { FinishReading(); if (_reader != null) { if (!_leaveOpen) { _reader.Close(); } _reader = null; } } private void FinishReading() { _lineNumber = -1L; _endOfData = true; _buffer = null; _delimiterRegex = null; _beginQuotesRegex = null; } private void InitializeFromPath(string path, Encoding defaultEncoding, bool detectEncoding) { if (path == null) { throw new ArgumentNullException(nameof(path)); } if (defaultEncoding == null) { throw new ArgumentNullException(nameof(defaultEncoding)); } string fullPath = ValidatePath(path); FileStream fileStreamTemp = new FileStream(fullPath, (FileMode.Open), (FileAccess.Read), (FileShare.ReadWrite)); _reader = new StreamReader(fileStreamTemp, defaultEncoding, detectEncoding); ReadToBuffer(); } private void InitializeFromStream(Stream stream, Encoding defaultEncoding, bool detectEncoding) { if (stream == null) { throw new ArgumentNullException(nameof(stream)); } if (!stream.CanRead) { throw new ArgumentException(Strings.StreamDoesntSupportReading); } if (defaultEncoding == null) { throw new ArgumentNullException(nameof(defaultEncoding)); } _reader = new StreamReader(stream, defaultEncoding, detectEncoding); ReadToBuffer(); } private string ValidatePath(string path) { if (!File.Exists(path)) { throw new FileNotFoundException(Strings.FileNotFound); } return path; } private bool IgnoreLine(string line) { if (line == null) { return false; } string trimmedLine = line.Trim(); if (trimmedLine.Length == 0) { return true; } if (_commentTokens != null) { string[] commentTokens = _commentTokens; foreach (string Token in commentTokens) { if (Token == string.Empty) { continue; } if (trimmedLine.StartsWith(Token, StringComparison.Ordinal)) { return true; } if (line.StartsWith(Token, StringComparison.Ordinal)) { return true; } } } return false; } private int ReadToBuffer() { Debug.Assert(_buffer != null, "There's no buffer"); Debug.Assert(_reader != null, "There's no StreamReader"); _position = 0; int BufferLength = _buffer.Length; Debug.Assert(BufferLength >= DEFAULT_BUFFER_LENGTH, "Buffer shrunk to below default"); if (BufferLength > DEFAULT_BUFFER_LENGTH) { BufferLength = DEFAULT_BUFFER_LENGTH; _buffer = new char[BufferLength]; } _charsRead = _reader.Read(_buffer, 0, BufferLength); return _charsRead; } private int SlideCursorToStartOfBuffer() { Debug.Assert(_buffer != null, "There's no buffer"); Debug.Assert(_reader != null, "There's no StreamReader"); Debug.Assert((_position >= 0) && (_position <= _buffer.Length), "The cursor is out of range"); if (_position > 0) { int bufferLength = _buffer.Length; char[] tempArray = new char[bufferLength]; Array.Copy(_buffer, _position, tempArray, 0, bufferLength - _position); int charsRead = _reader.Read(tempArray, bufferLength - _position, _position); _charsRead = _charsRead - _position + charsRead; _position = 0; _buffer = tempArray; return charsRead; } return 0; } private int IncreaseBufferSize() { Debug.Assert(_buffer != null, "There's no buffer"); Debug.Assert(_reader != null, "There's no StreamReader"); _peekPosition = _charsRead; int bufferSize = _buffer.Length + DEFAULT_BUFFER_LENGTH; if (bufferSize > _maxBufferSize) { throw new Exception(Strings.ExceededMaxBufferSize); } char[] tempArray = new char[bufferSize]; Array.Copy(_buffer, tempArray, _buffer.Length); int charsRead = _reader.Read(tempArray, _buffer.Length, DEFAULT_BUFFER_LENGTH); _buffer = tempArray; _charsRead += charsRead; Debug.Assert(_charsRead <= bufferSize, "We've read more chars than we have space for"); return charsRead; } private string ReadNextDataLine() { ChangeBufferFunction BufferFunction = ReadToBuffer; string line; do { line = ReadNextLine(ref _position, BufferFunction); _lineNumber++; } while (IgnoreLine(line)); if (line == null) { CloseReader(); } return line; } private string PeekNextDataLine() { ChangeBufferFunction BufferFunction = IncreaseBufferSize; SlideCursorToStartOfBuffer(); _peekPosition = 0; string line; do { line = ReadNextLine(ref _peekPosition, BufferFunction); } while (IgnoreLine(line)); return line; } private string ReadNextLine(ref int cursor, ChangeBufferFunction changeBuffer) { Debug.Assert(_buffer != null, "There's no buffer"); Debug.Assert((cursor >= 0) && (cursor <= _charsRead), "The cursor is out of range"); if (cursor == _charsRead && changeBuffer() == 0) { return null; } StringBuilder Builder = null; // Consider replacing this do-while with a string search to take advantage of vectorization do { for (int i = cursor; i <= _charsRead - 1; i++) { char Character = _buffer[i]; if (!(Character.Equals('\r') || Character.Equals('\n'))) { continue; } if (Builder != null) { Builder.Append(_buffer, cursor, i - cursor + 1); } else { Builder = new StringBuilder(i + 1); Builder.Append(_buffer, cursor, i - cursor + 1); } cursor = i + 1; if (Character.Equals('\r')) { if (cursor < _charsRead) { if (_buffer[cursor].Equals('\n')) { cursor++; Builder.Append("\n"); } } else if (changeBuffer() > 0 && _buffer[cursor].Equals('\n')) { cursor++; Builder.Append("\n"); } } return Builder.ToString(); } // Searched the whole buffer and haven't found an end of line. Save what we have and read more to the buffer int Size = _charsRead - cursor; if (Builder == null) { Builder = new StringBuilder(Size + 10); } Builder.Append(_buffer, cursor, Size); } while (changeBuffer() > 0); return Builder.ToString(); } private string[] ParseDelimitedLine() { string line = ReadNextDataLine(); if (line == null) { return null; } long currentLineNumber = _lineNumber - 1; int index = 0; List<string> Fields = new List<string>(); int lineEndIndex = GetEndOfLineIndex(line); while (index <= lineEndIndex) { Match matchResult = null; bool quoteDelimited = false; if (HasFieldsEnclosedInQuotes) { matchResult = BeginQuotesRegex.Match(line, index); quoteDelimited = matchResult.Success; } string field; if (quoteDelimited) { // Move the Index beyond quote index = matchResult.Index + matchResult.Length; // Looking for the closing quote QuoteDelimitedFieldBuilder endHelper = new QuoteDelimitedFieldBuilder(_delimiterWithEndCharsRegex, _spaceChars); endHelper.BuildField(line, index); if (endHelper.MalformedLine) { _errorLine = line.TrimEnd(_newLineChars); _errorLineNumber = currentLineNumber; throw new Exception(string.Format(Strings.CannotParseWithDelimiters, currentLineNumber)); } if (endHelper.FieldFinished) { field = endHelper.Field; index = endHelper.Index + endHelper.DelimiterLength; } else { // We may have an embedded line end character, so grab next line do { int endOfLine = line.Length; string newLine = ReadNextDataLine(); if (newLine == null) { _errorLine = line.TrimEnd(_newLineChars); _errorLineNumber = currentLineNumber; throw new Exception(string.Format(Strings.CannotParseWithDelimiters, currentLineNumber)); } if (line.Length + newLine.Length > _maxLineSize) { _errorLine = line.TrimEnd(_newLineChars); _errorLineNumber = currentLineNumber; throw new Exception(string.Format(Strings.LineExceedsMaxLineSize, currentLineNumber)); } line += newLine; lineEndIndex = GetEndOfLineIndex(line); endHelper.BuildField(line, endOfLine); if (endHelper.MalformedLine) { _errorLine = line.TrimEnd(_newLineChars); _errorLineNumber = currentLineNumber; throw new Exception(string.Format(Strings.CannotParseWithDelimiters, currentLineNumber)); } } while (!endHelper.FieldFinished); field = endHelper.Field; index = endHelper.Index + endHelper.DelimiterLength; } if (_trimWhiteSpace) { field = field.Trim(); } Fields.Add(field); continue; } // Find the next delimiter Match delimiterMatch = _delimiterRegex.Match(line, index); if (delimiterMatch.Success) { field = line.Substring(index, delimiterMatch.Index - index); if (_trimWhiteSpace) { field = field.Trim(); } Fields.Add(field); index = delimiterMatch.Index + delimiterMatch.Length; continue; } field = line.Substring(index).TrimEnd(_newLineChars); if (_trimWhiteSpace) { field = field.Trim(); } Fields.Add(field); break; } return Fields.ToArray(); } private string[] ParseFixedWidthLine() { Debug.Assert(_fieldWidths != null, "No field widths"); string line = ReadNextDataLine(); if (line == null) { return null; } line = line.TrimEnd(_newLineChars); StringInfo lineInfo = new StringInfo(line); ValidateFixedWidthLine(lineInfo, _lineNumber - 1); int index = 0; int length = _fieldWidths.Length; string[] Fields = new string[length]; for (int i = 0; i < length; i++) { Fields[i] = GetFixedWidthField(lineInfo, index, _fieldWidths[i]); index += _fieldWidths[i]; } return Fields; } private string GetFixedWidthField(StringInfo line, int index, int fieldLength) { string field = (fieldLength > 0) ? line.SubstringByTextElements(index, fieldLength) : ((index < line.LengthInTextElements) ? line.SubstringByTextElements(index).TrimEnd(_newLineChars) : string.Empty); if (_trimWhiteSpace) { return field.Trim(); } return field; } private int GetEndOfLineIndex(string line) { Debug.Assert(line != null, "We are parsing null"); int length = line.Length; Debug.Assert(length > 0, "A blank line shouldn't be parsed"); if (length == 1) { Debug.Assert(!line[0].Equals('\r') && !line[0].Equals('\n'), "A blank line shouldn't be parsed"); return length; } checked { if (line[length - 2].Equals('\r') || line[length - 2].Equals('\n')) { return length - 2; } if (line[length - 1].Equals('\r') || line[length - 1].Equals('\n')) { return length - 1; } return length; } } private void ValidateFixedWidthLine(StringInfo line, long lineNumber) { Debug.Assert(line != null, "No Line sent"); if (line.LengthInTextElements < _lineLength) { _errorLine = line.String; _errorLineNumber = checked(_lineNumber - 1); throw new Exception(string.Format(Strings.CannotParseWithFieldWidths, lineNumber)); } } private void ValidateFieldWidths() { if (_fieldWidths == null) { throw new InvalidOperationException(Strings.NullFieldWidths); } if (_fieldWidths.Length == 0) { throw new InvalidOperationException(Strings.EmptyFieldWidths); } checked { int widthBound = _fieldWidths.Length - 1; _lineLength = 0; int num = widthBound - 1; for (int i = 0; i <= num; i++) { Debug.Assert(_fieldWidths[i] > 0, "Bad field width, this should have been caught on input"); _lineLength += _fieldWidths[i]; } if (_fieldWidths[widthBound] > 0) { _lineLength += _fieldWidths[widthBound]; } } } private void ValidateFieldWidthsOnInput(int[] widths) { Debug.Assert(widths != null, "There are no field widths"); int bound = widths.Length - 1; for (int i = 0; i <= bound - 1; i++) { if (widths[i] < 1) { throw new ArgumentException(Strings.InvalidFieldWidths); } } } private void ValidateAndEscapeDelimiters() { if (_delimiters == null) { throw new Exception(Strings.NullDelimiters); } if (_delimiters.Length == 0) { throw new Exception(Strings.EmptyDelimiters); } int length = _delimiters.Length; StringBuilder builder = new StringBuilder(); StringBuilder quoteBuilder = new StringBuilder(); quoteBuilder.Append(EndQuotePattern + "("); for (int i = 0; i <= length - 1; i++) { if (_delimiters[i] != null) { if (_hasFieldsEnclosedInQuotes && _delimiters[i].IndexOf('"') > -1) { throw new Exception(Strings.IllegalQuoteDelimiter); } string escapedDelimiter = Regex.Escape(_delimiters[i]); builder.Append(escapedDelimiter + "|"); quoteBuilder.Append(escapedDelimiter + "|"); } else { Debug.Fail("Delimiter element is empty. This should have been caught on input"); } } _spaceChars = WhitespaceCharacters; _delimiterRegex = new Regex(builder.ToString(0, builder.Length - 1), (RegexOptions)512); builder.Append("\r|\n"); _delimiterWithEndCharsRegex = new Regex(builder.ToString(), (RegexOptions)512); quoteBuilder.Append("\r|\n)|\"$"); } private void ValidateReadyToRead() { if (!(_needPropertyCheck || ArrayHasChanged())) { return; } switch (_textFieldType) { case FieldType.Delimited: ValidateAndEscapeDelimiters(); break; case FieldType.FixedWidth: ValidateFieldWidths(); break; default: Debug.Fail("Unknown TextFieldType"); break; } if (_commentTokens != null) { string[] commentTokens = _commentTokens; foreach (string token in commentTokens) { if (token != string.Empty && (_hasFieldsEnclosedInQuotes && (_textFieldType == FieldType.Delimited)) && string.Compare(token.Trim(), "\"", StringComparison.Ordinal) == 0) { throw new Exception(Strings.IllegalQuoteDelimiter); } } } _needPropertyCheck = false; } private void ValidateDelimiters(string[] delimiterArray) { if (delimiterArray == null) { return; } foreach (string delimiter in delimiterArray) { if (delimiter == string.Empty) { throw new Exception(Strings.EmptyDelimiters); } if (delimiter.IndexOfAny(_newLineChars) > -1) { throw new Exception(Strings.DelimiterCannotBeNewlineChar); } } } private bool ArrayHasChanged() { int lowerBound = 0; int upperBound = 0; switch (_textFieldType) { case FieldType.Delimited: { Debug.Assert(((_delimitersCopy == null) && (_delimiters == null)) || ((_delimitersCopy != null) && (_delimiters != null)), "Delimiters and copy are not both Nothing or both not Nothing"); if (_delimiters == null) { return false; } lowerBound = _delimitersCopy.GetLowerBound(0); upperBound = _delimitersCopy.GetUpperBound(0); int num3 = lowerBound; int num4 = upperBound; for (int i = num3; i <= num4; i++) { if (_delimiters[i] != _delimitersCopy[i]) { return true; } } break; } case FieldType.FixedWidth: { Debug.Assert(((_fieldWidthsCopy == null) && (_fieldWidths == null)) || ((_fieldWidthsCopy != null) && (_fieldWidths != null)), "FieldWidths and copy are not both Nothing or both not Nothing"); if (_fieldWidths == null) { return false; } lowerBound = _fieldWidthsCopy.GetLowerBound(0); upperBound = _fieldWidthsCopy.GetUpperBound(0); int num = lowerBound; int num2 = upperBound; for (int j = num; j <= num2; j++) { if (_fieldWidths[j] != _fieldWidthsCopy[j]) { return true; } } break; } default: Debug.Fail("Unknown TextFieldType"); break; } return false; } private void CheckCommentTokensForWhitespace(string[] tokens) { if (tokens == null) { return; } foreach (string token in tokens) { if (token.Length == 1 && char.IsWhiteSpace(token[0])) { throw new Exception(Strings.CommentTokenCannotContainWhitespace); } } } private bool CharacterIsInDelimiter(char testCharacter) { Debug.Assert(_delimiters != null, "No delimiters set!"); string[] delimiters = _delimiters; foreach (string delimiter in delimiters) { if (delimiter.IndexOf(testCharacter) > -1) { return true; } } return false; } } }
TextFieldParser
csharp
EventStore__EventStore
src/KurrentDB.Core.Tests/ClientAPI/connecting_to_a_persistent_subscription_async.cs
{ "start": 1420, "end": 2443 }
public class ____<TLogFormat, TStreamId> : SpecificationWithMiniNode<TLogFormat, TStreamId> { private EventStorePersistentSubscriptionBase _sub; private readonly string _stream = Guid.NewGuid().ToString(); private readonly PersistentSubscriptionSettings _settings = PersistentSubscriptionSettings.Create() .DoNotResolveLinkTos() .StartFromCurrent(); protected override async Task When() { await _conn.CreatePersistentSubscriptionAsync(_stream, "agroupname17", _settings, DefaultData.AdminCredentials) ; _sub = await _conn.ConnectToPersistentSubscriptionAsync(_stream, "agroupname17", (sub, e) => { Console.Write("appeared"); return Task.CompletedTask; }, (sub, reason, ex) => { }, DefaultData.AdminCredentials); } [Test] public void the_subscription_succeeds() { Assert.IsNotNull(_sub); } } [Category("LongRunning")] [TestFixture(typeof(LogFormat.V2), typeof(string))] [TestFixture(typeof(LogFormat.V3), typeof(uint))]
connect_to_existing_persistent_subscription_with_permissions_async
csharp
dotnet__efcore
test/EFCore.InMemory.FunctionalTests/Query/QueryBugsInMemoryTest.cs
{ "start": 24342, "end": 25954 }
private class ____ : DbContext { public DbSet<AppEntity21803> Entities { get; set; } protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) => optionsBuilder .UseInternalServiceProvider(InMemoryFixture.DefaultServiceProvider) .UseInMemoryDatabase("21803"); } #endregion #region Issue20729 [ConditionalFact] public virtual async Task Multiple_owned_references_at_same_level_maintains_valueBuffer_positions() { await using (await CreateScratchAsync<MyContext20729>(Seed20729, "20729")) { using var context = new MyContext20729(); var query = context.Set<Owner20729>() .Select(dtoOwner => new { dtoOwner.Id, Owned2 = dtoOwner.Owned2 == null ? null : new { Other = dtoOwner.Owned2.Other == null ? null : new { dtoOwner.Owned2.Other.Id } }, Owned1 = dtoOwner.Owned1 == null ? null : new { dtoOwner.Owned1.Value } } ).ToList(); var owner = Assert.Single(query); Assert.NotNull(owner.Owned1); Assert.NotNull(owner.Owned2); } } private static Task Seed20729(MyContext20729 context) { context.Owners.Add( new Owner20729 { Owned1 = new Owned120729(), Owned2 = new Owned220729(), }); return context.SaveChangesAsync(); }
MyContext21803
csharp
dotnet__maui
src/Controls/src/Core/Handlers/Items/SelectableItemsViewHandler.Windows.cs
{ "start": 6203, "end": 7379 }
partial class ____ : Microsoft.UI.Xaml.Data.IValueConverter { public object Convert(object value, Type targetType, object parameter, string language) { var formSelectionMode = (SelectionMode)value; switch (formSelectionMode) { case SelectionMode.None: return WASDKListViewSelectionMode.None; case SelectionMode.Single: return WASDKListViewSelectionMode.Single; case SelectionMode.Multiple: return WASDKListViewSelectionMode.Multiple; default: return WASDKListViewSelectionMode.None; } } public object ConvertBack(object value, Type targetType, object parameter, string language) { var uwpListViewSelectionMode = (WASDKListViewSelectionMode)value; switch (uwpListViewSelectionMode) { case WASDKListViewSelectionMode.None: return SelectionMode.None; case WASDKListViewSelectionMode.Single: return SelectionMode.Single; case WASDKListViewSelectionMode.Multiple: return SelectionMode.Multiple; case WASDKListViewSelectionMode.Extended: return SelectionMode.None; default: return SelectionMode.None; } } } } }
SelectionModeConvert
csharp
ServiceStack__ServiceStack
ServiceStack.OrmLite/tests/ServiceStack.OrmLite.Tests/Issues/ComplexJoinWithAlias.cs
{ "start": 152, "end": 316 }
public class ____ : IHasIntId { [AutoIncrement] [PrimaryKey] public int Id { get; set; } [Alias("A")] public string ColumnA { get; set; } }
ClassA
csharp
fluentassertions__fluentassertions
Src/FluentAssertions/Equivalency/Matching/MustMatchMemberByNameRule.cs
{ "start": 261, "end": 2018 }
internal class ____ : IMemberMatchingRule { public IMember Match(IMember expectedMember, object subject, INode parent, IEquivalencyOptions options, AssertionChain assertionChain) { IMember subjectMember = null; if (options.IncludedProperties != MemberVisibility.None) { PropertyInfo propertyInfo = subject.GetType().FindProperty( expectedMember.Subject.Name, options.IncludedProperties | MemberVisibility.ExplicitlyImplemented | MemberVisibility.DefaultInterfaceProperties); subjectMember = propertyInfo is not null && !propertyInfo.IsIndexer() ? new Property(propertyInfo, parent) : null; } if (subjectMember is null && options.IncludedFields != MemberVisibility.None) { FieldInfo fieldInfo = subject.GetType().FindField( expectedMember.Subject.Name, options.IncludedFields); subjectMember = fieldInfo is not null ? new Field(fieldInfo, parent) : null; } if (subjectMember is null) { assertionChain.FailWith( "Expectation has {0} that the other object does not have.", expectedMember.Expectation.AsNonFormattable()); } else if (options.IgnoreNonBrowsableOnSubject && !subjectMember.IsBrowsable) { assertionChain.FailWith( "Expectation has {0} that is non-browsable in the other object, and non-browsable " + "members on the subject are ignored with the current configuration", expectedMember.Expectation.AsNonFormattable()); } else { // Everything is fine } return subjectMember; } }
MustMatchMemberByNameRule
csharp
Cysharp__UniTask
src/UniTask/Assets/Plugins/UniTask/Runtime/Linq/CombineLatest.cs
{ "start": 138, "end": 19807 }
partial class ____ { public static IUniTaskAsyncEnumerable<TResult> CombineLatest<T1, T2, TResult>(this IUniTaskAsyncEnumerable<T1> source1, IUniTaskAsyncEnumerable<T2> source2, Func<T1, T2, TResult> resultSelector) { Error.ThrowArgumentNullException(source1, nameof(source1)); Error.ThrowArgumentNullException(source2, nameof(source2)); Error.ThrowArgumentNullException(resultSelector, nameof(resultSelector)); return new CombineLatest<T1, T2, TResult>(source1, source2, resultSelector); } public static IUniTaskAsyncEnumerable<TResult> CombineLatest<T1, T2, T3, TResult>(this IUniTaskAsyncEnumerable<T1> source1, IUniTaskAsyncEnumerable<T2> source2, IUniTaskAsyncEnumerable<T3> source3, Func<T1, T2, T3, TResult> resultSelector) { Error.ThrowArgumentNullException(source1, nameof(source1)); Error.ThrowArgumentNullException(source2, nameof(source2)); Error.ThrowArgumentNullException(source3, nameof(source3)); Error.ThrowArgumentNullException(resultSelector, nameof(resultSelector)); return new CombineLatest<T1, T2, T3, TResult>(source1, source2, source3, resultSelector); } public static IUniTaskAsyncEnumerable<TResult> CombineLatest<T1, T2, T3, T4, TResult>(this IUniTaskAsyncEnumerable<T1> source1, IUniTaskAsyncEnumerable<T2> source2, IUniTaskAsyncEnumerable<T3> source3, IUniTaskAsyncEnumerable<T4> source4, Func<T1, T2, T3, T4, TResult> resultSelector) { Error.ThrowArgumentNullException(source1, nameof(source1)); Error.ThrowArgumentNullException(source2, nameof(source2)); Error.ThrowArgumentNullException(source3, nameof(source3)); Error.ThrowArgumentNullException(source4, nameof(source4)); Error.ThrowArgumentNullException(resultSelector, nameof(resultSelector)); return new CombineLatest<T1, T2, T3, T4, TResult>(source1, source2, source3, source4, resultSelector); } public static IUniTaskAsyncEnumerable<TResult> CombineLatest<T1, T2, T3, T4, T5, TResult>(this IUniTaskAsyncEnumerable<T1> source1, IUniTaskAsyncEnumerable<T2> source2, IUniTaskAsyncEnumerable<T3> source3, IUniTaskAsyncEnumerable<T4> source4, IUniTaskAsyncEnumerable<T5> source5, Func<T1, T2, T3, T4, T5, TResult> resultSelector) { Error.ThrowArgumentNullException(source1, nameof(source1)); Error.ThrowArgumentNullException(source2, nameof(source2)); Error.ThrowArgumentNullException(source3, nameof(source3)); Error.ThrowArgumentNullException(source4, nameof(source4)); Error.ThrowArgumentNullException(source5, nameof(source5)); Error.ThrowArgumentNullException(resultSelector, nameof(resultSelector)); return new CombineLatest<T1, T2, T3, T4, T5, TResult>(source1, source2, source3, source4, source5, resultSelector); } public static IUniTaskAsyncEnumerable<TResult> CombineLatest<T1, T2, T3, T4, T5, T6, TResult>(this IUniTaskAsyncEnumerable<T1> source1, IUniTaskAsyncEnumerable<T2> source2, IUniTaskAsyncEnumerable<T3> source3, IUniTaskAsyncEnumerable<T4> source4, IUniTaskAsyncEnumerable<T5> source5, IUniTaskAsyncEnumerable<T6> source6, Func<T1, T2, T3, T4, T5, T6, TResult> resultSelector) { Error.ThrowArgumentNullException(source1, nameof(source1)); Error.ThrowArgumentNullException(source2, nameof(source2)); Error.ThrowArgumentNullException(source3, nameof(source3)); Error.ThrowArgumentNullException(source4, nameof(source4)); Error.ThrowArgumentNullException(source5, nameof(source5)); Error.ThrowArgumentNullException(source6, nameof(source6)); Error.ThrowArgumentNullException(resultSelector, nameof(resultSelector)); return new CombineLatest<T1, T2, T3, T4, T5, T6, TResult>(source1, source2, source3, source4, source5, source6, resultSelector); } public static IUniTaskAsyncEnumerable<TResult> CombineLatest<T1, T2, T3, T4, T5, T6, T7, TResult>(this IUniTaskAsyncEnumerable<T1> source1, IUniTaskAsyncEnumerable<T2> source2, IUniTaskAsyncEnumerable<T3> source3, IUniTaskAsyncEnumerable<T4> source4, IUniTaskAsyncEnumerable<T5> source5, IUniTaskAsyncEnumerable<T6> source6, IUniTaskAsyncEnumerable<T7> source7, Func<T1, T2, T3, T4, T5, T6, T7, TResult> resultSelector) { Error.ThrowArgumentNullException(source1, nameof(source1)); Error.ThrowArgumentNullException(source2, nameof(source2)); Error.ThrowArgumentNullException(source3, nameof(source3)); Error.ThrowArgumentNullException(source4, nameof(source4)); Error.ThrowArgumentNullException(source5, nameof(source5)); Error.ThrowArgumentNullException(source6, nameof(source6)); Error.ThrowArgumentNullException(source7, nameof(source7)); Error.ThrowArgumentNullException(resultSelector, nameof(resultSelector)); return new CombineLatest<T1, T2, T3, T4, T5, T6, T7, TResult>(source1, source2, source3, source4, source5, source6, source7, resultSelector); } public static IUniTaskAsyncEnumerable<TResult> CombineLatest<T1, T2, T3, T4, T5, T6, T7, T8, TResult>(this IUniTaskAsyncEnumerable<T1> source1, IUniTaskAsyncEnumerable<T2> source2, IUniTaskAsyncEnumerable<T3> source3, IUniTaskAsyncEnumerable<T4> source4, IUniTaskAsyncEnumerable<T5> source5, IUniTaskAsyncEnumerable<T6> source6, IUniTaskAsyncEnumerable<T7> source7, IUniTaskAsyncEnumerable<T8> source8, Func<T1, T2, T3, T4, T5, T6, T7, T8, TResult> resultSelector) { Error.ThrowArgumentNullException(source1, nameof(source1)); Error.ThrowArgumentNullException(source2, nameof(source2)); Error.ThrowArgumentNullException(source3, nameof(source3)); Error.ThrowArgumentNullException(source4, nameof(source4)); Error.ThrowArgumentNullException(source5, nameof(source5)); Error.ThrowArgumentNullException(source6, nameof(source6)); Error.ThrowArgumentNullException(source7, nameof(source7)); Error.ThrowArgumentNullException(source8, nameof(source8)); Error.ThrowArgumentNullException(resultSelector, nameof(resultSelector)); return new CombineLatest<T1, T2, T3, T4, T5, T6, T7, T8, TResult>(source1, source2, source3, source4, source5, source6, source7, source8, resultSelector); } public static IUniTaskAsyncEnumerable<TResult> CombineLatest<T1, T2, T3, T4, T5, T6, T7, T8, T9, TResult>(this IUniTaskAsyncEnumerable<T1> source1, IUniTaskAsyncEnumerable<T2> source2, IUniTaskAsyncEnumerable<T3> source3, IUniTaskAsyncEnumerable<T4> source4, IUniTaskAsyncEnumerable<T5> source5, IUniTaskAsyncEnumerable<T6> source6, IUniTaskAsyncEnumerable<T7> source7, IUniTaskAsyncEnumerable<T8> source8, IUniTaskAsyncEnumerable<T9> source9, Func<T1, T2, T3, T4, T5, T6, T7, T8, T9, TResult> resultSelector) { Error.ThrowArgumentNullException(source1, nameof(source1)); Error.ThrowArgumentNullException(source2, nameof(source2)); Error.ThrowArgumentNullException(source3, nameof(source3)); Error.ThrowArgumentNullException(source4, nameof(source4)); Error.ThrowArgumentNullException(source5, nameof(source5)); Error.ThrowArgumentNullException(source6, nameof(source6)); Error.ThrowArgumentNullException(source7, nameof(source7)); Error.ThrowArgumentNullException(source8, nameof(source8)); Error.ThrowArgumentNullException(source9, nameof(source9)); Error.ThrowArgumentNullException(resultSelector, nameof(resultSelector)); return new CombineLatest<T1, T2, T3, T4, T5, T6, T7, T8, T9, TResult>(source1, source2, source3, source4, source5, source6, source7, source8, source9, resultSelector); } public static IUniTaskAsyncEnumerable<TResult> CombineLatest<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, TResult>(this IUniTaskAsyncEnumerable<T1> source1, IUniTaskAsyncEnumerable<T2> source2, IUniTaskAsyncEnumerable<T3> source3, IUniTaskAsyncEnumerable<T4> source4, IUniTaskAsyncEnumerable<T5> source5, IUniTaskAsyncEnumerable<T6> source6, IUniTaskAsyncEnumerable<T7> source7, IUniTaskAsyncEnumerable<T8> source8, IUniTaskAsyncEnumerable<T9> source9, IUniTaskAsyncEnumerable<T10> source10, Func<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, TResult> resultSelector) { Error.ThrowArgumentNullException(source1, nameof(source1)); Error.ThrowArgumentNullException(source2, nameof(source2)); Error.ThrowArgumentNullException(source3, nameof(source3)); Error.ThrowArgumentNullException(source4, nameof(source4)); Error.ThrowArgumentNullException(source5, nameof(source5)); Error.ThrowArgumentNullException(source6, nameof(source6)); Error.ThrowArgumentNullException(source7, nameof(source7)); Error.ThrowArgumentNullException(source8, nameof(source8)); Error.ThrowArgumentNullException(source9, nameof(source9)); Error.ThrowArgumentNullException(source10, nameof(source10)); Error.ThrowArgumentNullException(resultSelector, nameof(resultSelector)); return new CombineLatest<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, TResult>(source1, source2, source3, source4, source5, source6, source7, source8, source9, source10, resultSelector); } public static IUniTaskAsyncEnumerable<TResult> CombineLatest<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, TResult>(this IUniTaskAsyncEnumerable<T1> source1, IUniTaskAsyncEnumerable<T2> source2, IUniTaskAsyncEnumerable<T3> source3, IUniTaskAsyncEnumerable<T4> source4, IUniTaskAsyncEnumerable<T5> source5, IUniTaskAsyncEnumerable<T6> source6, IUniTaskAsyncEnumerable<T7> source7, IUniTaskAsyncEnumerable<T8> source8, IUniTaskAsyncEnumerable<T9> source9, IUniTaskAsyncEnumerable<T10> source10, IUniTaskAsyncEnumerable<T11> source11, Func<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, TResult> resultSelector) { Error.ThrowArgumentNullException(source1, nameof(source1)); Error.ThrowArgumentNullException(source2, nameof(source2)); Error.ThrowArgumentNullException(source3, nameof(source3)); Error.ThrowArgumentNullException(source4, nameof(source4)); Error.ThrowArgumentNullException(source5, nameof(source5)); Error.ThrowArgumentNullException(source6, nameof(source6)); Error.ThrowArgumentNullException(source7, nameof(source7)); Error.ThrowArgumentNullException(source8, nameof(source8)); Error.ThrowArgumentNullException(source9, nameof(source9)); Error.ThrowArgumentNullException(source10, nameof(source10)); Error.ThrowArgumentNullException(source11, nameof(source11)); Error.ThrowArgumentNullException(resultSelector, nameof(resultSelector)); return new CombineLatest<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, TResult>(source1, source2, source3, source4, source5, source6, source7, source8, source9, source10, source11, resultSelector); } public static IUniTaskAsyncEnumerable<TResult> CombineLatest<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, TResult>(this IUniTaskAsyncEnumerable<T1> source1, IUniTaskAsyncEnumerable<T2> source2, IUniTaskAsyncEnumerable<T3> source3, IUniTaskAsyncEnumerable<T4> source4, IUniTaskAsyncEnumerable<T5> source5, IUniTaskAsyncEnumerable<T6> source6, IUniTaskAsyncEnumerable<T7> source7, IUniTaskAsyncEnumerable<T8> source8, IUniTaskAsyncEnumerable<T9> source9, IUniTaskAsyncEnumerable<T10> source10, IUniTaskAsyncEnumerable<T11> source11, IUniTaskAsyncEnumerable<T12> source12, Func<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, TResult> resultSelector) { Error.ThrowArgumentNullException(source1, nameof(source1)); Error.ThrowArgumentNullException(source2, nameof(source2)); Error.ThrowArgumentNullException(source3, nameof(source3)); Error.ThrowArgumentNullException(source4, nameof(source4)); Error.ThrowArgumentNullException(source5, nameof(source5)); Error.ThrowArgumentNullException(source6, nameof(source6)); Error.ThrowArgumentNullException(source7, nameof(source7)); Error.ThrowArgumentNullException(source8, nameof(source8)); Error.ThrowArgumentNullException(source9, nameof(source9)); Error.ThrowArgumentNullException(source10, nameof(source10)); Error.ThrowArgumentNullException(source11, nameof(source11)); Error.ThrowArgumentNullException(source12, nameof(source12)); Error.ThrowArgumentNullException(resultSelector, nameof(resultSelector)); return new CombineLatest<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, TResult>(source1, source2, source3, source4, source5, source6, source7, source8, source9, source10, source11, source12, resultSelector); } public static IUniTaskAsyncEnumerable<TResult> CombineLatest<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, TResult>(this IUniTaskAsyncEnumerable<T1> source1, IUniTaskAsyncEnumerable<T2> source2, IUniTaskAsyncEnumerable<T3> source3, IUniTaskAsyncEnumerable<T4> source4, IUniTaskAsyncEnumerable<T5> source5, IUniTaskAsyncEnumerable<T6> source6, IUniTaskAsyncEnumerable<T7> source7, IUniTaskAsyncEnumerable<T8> source8, IUniTaskAsyncEnumerable<T9> source9, IUniTaskAsyncEnumerable<T10> source10, IUniTaskAsyncEnumerable<T11> source11, IUniTaskAsyncEnumerable<T12> source12, IUniTaskAsyncEnumerable<T13> source13, Func<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, TResult> resultSelector) { Error.ThrowArgumentNullException(source1, nameof(source1)); Error.ThrowArgumentNullException(source2, nameof(source2)); Error.ThrowArgumentNullException(source3, nameof(source3)); Error.ThrowArgumentNullException(source4, nameof(source4)); Error.ThrowArgumentNullException(source5, nameof(source5)); Error.ThrowArgumentNullException(source6, nameof(source6)); Error.ThrowArgumentNullException(source7, nameof(source7)); Error.ThrowArgumentNullException(source8, nameof(source8)); Error.ThrowArgumentNullException(source9, nameof(source9)); Error.ThrowArgumentNullException(source10, nameof(source10)); Error.ThrowArgumentNullException(source11, nameof(source11)); Error.ThrowArgumentNullException(source12, nameof(source12)); Error.ThrowArgumentNullException(source13, nameof(source13)); Error.ThrowArgumentNullException(resultSelector, nameof(resultSelector)); return new CombineLatest<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, TResult>(source1, source2, source3, source4, source5, source6, source7, source8, source9, source10, source11, source12, source13, resultSelector); } public static IUniTaskAsyncEnumerable<TResult> CombineLatest<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, TResult>(this IUniTaskAsyncEnumerable<T1> source1, IUniTaskAsyncEnumerable<T2> source2, IUniTaskAsyncEnumerable<T3> source3, IUniTaskAsyncEnumerable<T4> source4, IUniTaskAsyncEnumerable<T5> source5, IUniTaskAsyncEnumerable<T6> source6, IUniTaskAsyncEnumerable<T7> source7, IUniTaskAsyncEnumerable<T8> source8, IUniTaskAsyncEnumerable<T9> source9, IUniTaskAsyncEnumerable<T10> source10, IUniTaskAsyncEnumerable<T11> source11, IUniTaskAsyncEnumerable<T12> source12, IUniTaskAsyncEnumerable<T13> source13, IUniTaskAsyncEnumerable<T14> source14, Func<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, TResult> resultSelector) { Error.ThrowArgumentNullException(source1, nameof(source1)); Error.ThrowArgumentNullException(source2, nameof(source2)); Error.ThrowArgumentNullException(source3, nameof(source3)); Error.ThrowArgumentNullException(source4, nameof(source4)); Error.ThrowArgumentNullException(source5, nameof(source5)); Error.ThrowArgumentNullException(source6, nameof(source6)); Error.ThrowArgumentNullException(source7, nameof(source7)); Error.ThrowArgumentNullException(source8, nameof(source8)); Error.ThrowArgumentNullException(source9, nameof(source9)); Error.ThrowArgumentNullException(source10, nameof(source10)); Error.ThrowArgumentNullException(source11, nameof(source11)); Error.ThrowArgumentNullException(source12, nameof(source12)); Error.ThrowArgumentNullException(source13, nameof(source13)); Error.ThrowArgumentNullException(source14, nameof(source14)); Error.ThrowArgumentNullException(resultSelector, nameof(resultSelector)); return new CombineLatest<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, TResult>(source1, source2, source3, source4, source5, source6, source7, source8, source9, source10, source11, source12, source13, source14, resultSelector); } public static IUniTaskAsyncEnumerable<TResult> CombineLatest<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, TResult>(this IUniTaskAsyncEnumerable<T1> source1, IUniTaskAsyncEnumerable<T2> source2, IUniTaskAsyncEnumerable<T3> source3, IUniTaskAsyncEnumerable<T4> source4, IUniTaskAsyncEnumerable<T5> source5, IUniTaskAsyncEnumerable<T6> source6, IUniTaskAsyncEnumerable<T7> source7, IUniTaskAsyncEnumerable<T8> source8, IUniTaskAsyncEnumerable<T9> source9, IUniTaskAsyncEnumerable<T10> source10, IUniTaskAsyncEnumerable<T11> source11, IUniTaskAsyncEnumerable<T12> source12, IUniTaskAsyncEnumerable<T13> source13, IUniTaskAsyncEnumerable<T14> source14, IUniTaskAsyncEnumerable<T15> source15, Func<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, TResult> resultSelector) { Error.ThrowArgumentNullException(source1, nameof(source1)); Error.ThrowArgumentNullException(source2, nameof(source2)); Error.ThrowArgumentNullException(source3, nameof(source3)); Error.ThrowArgumentNullException(source4, nameof(source4)); Error.ThrowArgumentNullException(source5, nameof(source5)); Error.ThrowArgumentNullException(source6, nameof(source6)); Error.ThrowArgumentNullException(source7, nameof(source7)); Error.ThrowArgumentNullException(source8, nameof(source8)); Error.ThrowArgumentNullException(source9, nameof(source9)); Error.ThrowArgumentNullException(source10, nameof(source10)); Error.ThrowArgumentNullException(source11, nameof(source11)); Error.ThrowArgumentNullException(source12, nameof(source12)); Error.ThrowArgumentNullException(source13, nameof(source13)); Error.ThrowArgumentNullException(source14, nameof(source14)); Error.ThrowArgumentNullException(source15, nameof(source15)); Error.ThrowArgumentNullException(resultSelector, nameof(resultSelector)); return new CombineLatest<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, TResult>(source1, source2, source3, source4, source5, source6, source7, source8, source9, source10, source11, source12, source13, source14, source15, resultSelector); } }
UniTaskAsyncEnumerable
csharp
dotnet__machinelearning
src/Microsoft.ML.TimeSeries/SlidingWindowTransform.cs
{ "start": 974, "end": 2599 }
internal sealed class ____ : SlidingWindowTransformBase<Single> { public const string Summary = "Returns the last values for a time series [y(t-d-l+1), y(t-d-l+2), ..., y(t-l-1), y(t-l)] where d is the size of the window, l the lag and y is a Float."; public const string LoaderSignature = "SlideWinTransform"; public const string UserName = "Sliding Window Transform"; public const string ShortName = "SlideWin"; private static VersionInfo GetVersionInfo() { return new VersionInfo( modelSignature: "SWINTRNS", verWrittenCur: 0x00010001, // Initial verReadableCur: 0x00010001, verWeCanReadBack: 0x00010001, loaderSignature: LoaderSignature, loaderAssemblyName: typeof(SlidingWindowTransform).Assembly.FullName); } public SlidingWindowTransform(IHostEnvironment env, Arguments args, IDataView input) : base(args, LoaderSignature, env, input) { } public SlidingWindowTransform(IHostEnvironment env, ModelLoadContext ctx, IDataView input) : base(env, ctx, LoaderSignature, input) { // *** Binary format *** // <base> } private protected override void SaveModel(ModelSaveContext ctx) { Host.CheckValue(ctx, nameof(ctx)); ctx.CheckAtModel(); ctx.SetVersionInfo(GetVersionInfo()); // *** Binary format *** // <base> base.SaveModel(ctx); } } }
SlidingWindowTransform
csharp
icsharpcode__SharpZipLib
src/ICSharpCode.SharpZipLib/Tar/TarException.cs
{ "start": 1125, "end": 1636 }
class ____ serialized data. /// </summary> /// <param name="info"> /// The System.Runtime.Serialization.SerializationInfo that holds the serialized /// object data about the exception being thrown. /// </param> /// <param name="context"> /// The System.Runtime.Serialization.StreamingContext that contains contextual information /// about the source or destination. /// </param> protected TarException(SerializationInfo info, StreamingContext context) : base(info, context) { } } }
with
csharp
xunit__xunit
src/xunit.v3.core/Runners/XunitTestAssemblyRunner.cs
{ "start": 231, "end": 1880 }
public class ____ : XunitTestAssemblyRunnerBase<XunitTestAssemblyRunnerContext, IXunitTestAssembly, IXunitTestCollection, IXunitTestCase> { /// <summary> /// Initializes a new instance of the <see cref="XunitTestAssemblyRunner"/> class. /// </summary> protected XunitTestAssemblyRunner() { } /// <summary> /// Gets the singleton instance of <see cref="XunitTestAssemblyRunner"/>. /// </summary> public static XunitTestAssemblyRunner Instance { get; } = new(); /// <summary> /// Runs the test assembly. /// </summary> /// <param name="testAssembly">The test assembly to be executed.</param> /// <param name="testCases">The test cases associated with the test assembly.</param> /// <param name="executionMessageSink">The message sink to send execution messages to.</param> /// <param name="executionOptions">The execution options to use when running tests.</param> /// <param name="cancellationToken">The cancellation token used to cancel test execution.</param> public async ValueTask<RunSummary> Run( IXunitTestAssembly testAssembly, IReadOnlyCollection<IXunitTestCase> testCases, IMessageSink executionMessageSink, ITestFrameworkExecutionOptions executionOptions, CancellationToken cancellationToken) { Guard.ArgumentNotNull(testAssembly); Guard.ArgumentNotNull(testCases); Guard.ArgumentNotNull(executionMessageSink); Guard.ArgumentNotNull(executionOptions); await using var ctxt = new XunitTestAssemblyRunnerContext( testAssembly, testCases, executionMessageSink, executionOptions, cancellationToken ); await ctxt.InitializeAsync(); return await Run(ctxt); } }
XunitTestAssemblyRunner
csharp
dotnetcore__Util
src/Util.Caching.EasyCaching/CacheManager.cs
{ "start": 87, "end": 12241 }
public class ____ : ICache { #region 字段 /// <summary> /// 缓存提供器 /// </summary> private readonly IEasyCachingProviderBase _provider; /// <summary> /// 缓存提供器 /// </summary> private readonly IEasyCachingProvider _cachingProvider; #endregion #region 构造方法 /// <summary> /// 初始化EasyCaching缓存服务 /// </summary> /// <param name="provider">EasyCaching缓存提供器</param> /// <param name="hybridProvider">EasyCaching 2级缓存提供器</param> public CacheManager( IEasyCachingProvider provider, IHybridCachingProvider hybridProvider = null ) { CachingOptions.Clear(); if ( provider != null ) { _provider = provider; _cachingProvider = provider; } if( hybridProvider != null ) _provider = hybridProvider; _provider.CheckNull( nameof( provider ) ); } #endregion #region Exists /// <inheritdoc /> public bool Exists( CacheKey key ) { key.Validate(); return Exists( key.Key ); } /// <inheritdoc /> public bool Exists( string key ) { return _provider.Exists( key ); } #endregion #region ExistsAsync /// <inheritdoc /> public async Task<bool> ExistsAsync( CacheKey key, CancellationToken cancellationToken = default ) { key.Validate(); return await ExistsAsync( key.Key, cancellationToken ); } /// <inheritdoc /> public async Task<bool> ExistsAsync( string key, CancellationToken cancellationToken = default ) { return await _provider.ExistsAsync( key, cancellationToken ); } #endregion #region Get /// <inheritdoc /> public T Get<T>( CacheKey key ) { key.Validate(); return Get<T>( key.Key ); } /// <inheritdoc /> public T Get<T>( string key ) { var result = _provider.Get<T>( key ); return result.Value; } /// <inheritdoc /> public List<T> Get<T>( IEnumerable<CacheKey> keys ) { return Get<T>( ToKeys( keys ) ); } /// <summary> /// 转换为缓存键字符串集合 /// </summary> private IEnumerable<string> ToKeys( IEnumerable<CacheKey> keys ) { keys.CheckNull( nameof( keys ) ); var cacheKeys = keys.ToList(); cacheKeys.ForEach( t => t.Validate() ); return cacheKeys.Select( t => t.Key ); } /// <inheritdoc /> public List<T> Get<T>( IEnumerable<string> keys ) { Validate(); var result = _cachingProvider.GetAll<T>( keys ); return result.Values.Select( t => t.Value ).ToList(); } /// <summary> /// 验证 /// </summary> private void Validate() { if ( _cachingProvider == null ) throw new NotSupportedException( "2级缓存不支持该操作" ); } /// <inheritdoc /> public T Get<T>( CacheKey key, Func<T> action, CacheOptions options = null ) { key.Validate(); return Get( key.Key, action, options ); } /// <inheritdoc /> public T Get<T>( string key, Func<T> action, CacheOptions options = null ) { var result = _provider.Get( key, action, GetExpiration( options ) ); return result.Value; } /// <summary> /// 获取过期时间间隔 /// </summary> private TimeSpan GetExpiration( CacheOptions options ) { var result = options?.Expiration; result ??= TimeSpan.FromHours( 8 ); return result.SafeValue(); } #endregion #region GetAsync /// <inheritdoc /> public async Task<object> GetAsync( string key, Type type, CancellationToken cancellationToken = default ) { return await _provider.GetAsync( key, type, cancellationToken ); } /// <inheritdoc /> public async Task<T> GetAsync<T>( CacheKey key, CancellationToken cancellationToken = default ) { key.Validate(); return await GetAsync<T>( key.Key, cancellationToken ); } /// <inheritdoc /> public async Task<T> GetAsync<T>( string key, CancellationToken cancellationToken = default ) { var result = await _provider.GetAsync<T>( key, cancellationToken ); return result.Value; } /// <inheritdoc /> public async Task<List<T>> GetAsync<T>( IEnumerable<CacheKey> keys, CancellationToken cancellationToken = default ) { return await GetAsync<T>( ToKeys( keys ), cancellationToken ); } /// <inheritdoc /> public async Task<List<T>> GetAsync<T>( IEnumerable<string> keys, CancellationToken cancellationToken = default ) { Validate(); var result = await _cachingProvider.GetAllAsync<T>( keys, cancellationToken ); return result.Values.Select( t => t.Value ).ToList(); } /// <inheritdoc /> public async Task<T> GetAsync<T>( CacheKey key, Func<Task<T>> action, CacheOptions options = null, CancellationToken cancellationToken = default ) { key.Validate(); return await GetAsync( key.Key, action, options, cancellationToken ); } /// <inheritdoc /> public async Task<T> GetAsync<T>( string key, Func<Task<T>> action, CacheOptions options = null, CancellationToken cancellationToken = default ) { var result = await _provider.GetAsync( key, action, GetExpiration( options ), cancellationToken ); return result.Value; } #endregion #region GetByPrefix /// <inheritdoc /> public List<T> GetByPrefix<T>( string prefix ) { if( prefix.IsEmpty() ) return new List<T>(); Validate(); return _cachingProvider.GetByPrefix<T>( prefix ).Where( t => t.Value.HasValue ).Select( t => t.Value.Value ).ToList(); } #endregion #region GetByPrefixAsync /// <inheritdoc /> public async Task<List<T>> GetByPrefixAsync<T>( string prefix, CancellationToken cancellationToken = default ) { if( prefix.IsEmpty() ) return new List<T>(); Validate(); var result = await _cachingProvider.GetByPrefixAsync<T>( prefix, cancellationToken ); return result.Where( t => t.Value.HasValue ).Select( t => t.Value.Value ).ToList(); } #endregion #region TrySet /// <inheritdoc /> public bool TrySet<T>( CacheKey key, T value, CacheOptions options = null ) { key.Validate(); return TrySet( key.Key, value, options ); } /// <inheritdoc /> public bool TrySet<T>( string key, T value, CacheOptions options = null ) { return _provider.TrySet( key, value, GetExpiration( options ) ); } #endregion #region TrySetAsync /// <inheritdoc /> public async Task<bool> TrySetAsync<T>( CacheKey key, T value, CacheOptions options = null, CancellationToken cancellationToken = default ) { key.Validate(); return await TrySetAsync( key.Key, value, options, cancellationToken ); } /// <inheritdoc /> public async Task<bool> TrySetAsync<T>( string key, T value, CacheOptions options = null, CancellationToken cancellationToken = default ) { return await _provider.TrySetAsync( key, value, GetExpiration( options ), cancellationToken ); } #endregion #region Set /// <inheritdoc /> public void Set<T>( CacheKey key, T value, CacheOptions options = null ) { key.Validate(); Set( key.Key, value, options ); } /// <inheritdoc /> public void Set<T>( string key, T value, CacheOptions options = null ) { _provider.Set( key, value, GetExpiration( options ) ); } /// <inheritdoc /> public void Set<T>( IDictionary<CacheKey, T> items, CacheOptions options = null ) { Set( ToItems( items ), options ); } /// <summary> /// 转换为缓存项集合 /// </summary> private IDictionary<string, T> ToItems<T>( IDictionary<CacheKey, T> items ) { items.CheckNull( nameof( items ) ); return items.Select( item => { item.Key.Validate(); return new KeyValuePair<string, T>( item.Key.Key, item.Value ); } ).ToDictionary( t => t.Key, t => t.Value ); } /// <inheritdoc /> public void Set<T>( IDictionary<string, T> items, CacheOptions options = null ) { _provider.SetAll( items, GetExpiration( options ) ); } #endregion #region SetAsync /// <inheritdoc /> public async Task SetAsync<T>( CacheKey key, T value, CacheOptions options = null, CancellationToken cancellationToken = default ) { key.Validate(); await SetAsync( key.Key, value, options, cancellationToken ); } /// <inheritdoc /> public async Task SetAsync<T>( string key, T value, CacheOptions options = null, CancellationToken cancellationToken = default ) { await _provider.SetAsync( key, value, GetExpiration( options ), cancellationToken ); } /// <inheritdoc /> public async Task SetAsync<T>( IDictionary<CacheKey, T> items, CacheOptions options = null, CancellationToken cancellationToken = default ) { await SetAsync( ToItems( items ), options, cancellationToken ); } /// <inheritdoc /> public async Task SetAsync<T>( IDictionary<string, T> items, CacheOptions options = null, CancellationToken cancellationToken = default ) { await _provider.SetAllAsync( items, GetExpiration( options ), cancellationToken ); } #endregion #region Remove /// <inheritdoc /> public void Remove( CacheKey key ) { key.Validate(); Remove( key.Key ); } /// <inheritdoc /> public void Remove( string key ) { _provider.Remove( key ); } /// <inheritdoc /> public void Remove( IEnumerable<CacheKey> keys ) { Remove( ToKeys( keys ) ); } /// <inheritdoc /> public void Remove( IEnumerable<string> keys ) { _provider.RemoveAll( keys ); } #endregion #region RemoveAsync /// <inheritdoc /> public async Task RemoveAsync( CacheKey key, CancellationToken cancellationToken = default ) { key.Validate(); await RemoveAsync( key.Key, cancellationToken ); } /// <inheritdoc /> public async Task RemoveAsync( string key, CancellationToken cancellationToken = default ) { await _provider.RemoveAsync( key, cancellationToken ); } /// <inheritdoc /> public async Task RemoveAsync( IEnumerable<CacheKey> keys, CancellationToken cancellationToken = default ) { await RemoveAsync( ToKeys( keys ), cancellationToken ); } /// <inheritdoc /> public async Task RemoveAsync( IEnumerable<string> keys, CancellationToken cancellationToken = default ) { await _provider.RemoveAllAsync( keys, cancellationToken ); } #endregion #region RemoveByPrefix /// <summary> /// 通过缓存键前缀移除缓存 /// </summary> /// <param name="prefix">缓存键前缀</param> public void RemoveByPrefix( string prefix ) { if( prefix.IsEmpty() ) return; _provider.RemoveByPrefix( prefix ); } #endregion #region RemoveByPrefixAsync /// <inheritdoc /> public async Task RemoveByPrefixAsync( string prefix, CancellationToken cancellationToken = default ) { if( prefix.IsEmpty() ) return; await _provider.RemoveByPrefixAsync( prefix, cancellationToken ); } #endregion #region RemoveByPattern /// <inheritdoc /> public void RemoveByPattern( string pattern ) { if( pattern.IsEmpty() ) return; _provider.RemoveByPattern( pattern ); } #endregion #region RemoveByPatternAsync /// <inheritdoc /> public async Task RemoveByPatternAsync( string pattern, CancellationToken cancellationToken = default ) { if( pattern.IsEmpty() ) return; await _provider.RemoveByPatternAsync( pattern, cancellationToken ); } #endregion #region Clear /// <inheritdoc /> public void Clear() { Validate(); _cachingProvider.Flush(); } #endregion #region ClearAsync /// <inheritdoc /> public async Task ClearAsync( CancellationToken cancellationToken = default ) { Validate(); await _cachingProvider.FlushAsync( cancellationToken ); } #endregion }
CacheManager
csharp
cake-build__cake
src/Cake.Common.Tests/Fixtures/IO/FileSystemFixture.cs
{ "start": 326, "end": 2412 }
internal sealed class ____ { public ICakeEnvironment Environment { get; set; } public IFileSystem FileSystem { get; set; } public FileSystemFixture() { Environment = FakeEnvironment.CreateUnixEnvironment(); FileSystem = CreateFileSystem(Environment); } private static FakeFileSystem CreateFileSystem(ICakeEnvironment environment) { var fileSystem = new FakeFileSystem(environment); fileSystem.CreateDirectory("/Temp"); fileSystem.CreateDirectory("/Temp/HasDirectories"); fileSystem.CreateDirectory("/Temp/HasDirectories/A"); fileSystem.CreateDirectory("/Temp/HasFiles"); fileSystem.CreateDirectory("/Temp/Hello"); fileSystem.CreateDirectory("/Temp/Hello/Empty"); fileSystem.CreateDirectory("/Temp/Hello/More/Empty"); fileSystem.CreateDirectory("/Temp/Hello/World"); fileSystem.CreateDirectory("/Temp/Goodbye"); fileSystem.CreateDirectory("/Temp/Hello/Hidden").Hide(); fileSystem.CreateDirectory("/HasReadonly"); fileSystem.CreateFile("/Presentation.ppt"); fileSystem.CreateFile("/Budget.xlsx"); fileSystem.CreateFile("/Text.txt"); fileSystem.CreateFile("/Temp"); fileSystem.CreateFile("/Temp/Hello/Document.txt"); fileSystem.CreateFile("/Temp/Hello/World/Text.txt"); fileSystem.CreateFile("/Temp/Hello/World/Picture.png"); fileSystem.CreateFile("/Temp/Hello/Hidden.txt").Hide(); fileSystem.CreateFile("/Temp/Goodbye/OtherText.txt"); fileSystem.CreateFile("/Temp/Goodbye/OtherPicture.png"); fileSystem.CreateFile("/Temp/HasFiles/A.txt"); fileSystem.CreateFile("/HasReadonly/Readonly.txt", FileAttributes.ReadOnly); fileSystem.CreateFile("/HasReadonly/Not-Readonly.txt"); fileSystem.CreateFile("/HasReadonly/Hidden.txt").Hide(); return fileSystem; } } }
FileSystemFixture
csharp
dotnet__machinelearning
test/Microsoft.ML.Tests/TrainerEstimators/MatrixFactorizationTests.cs
{ "start": 41902, "end": 42759 }
private class ____ { // Matrix column index. Its allowed range is from 0 to _synthesizedMatrixColumnCount - 1. [KeyType(_synthesizedMatrixColumnCount)] public uint MatrixColumnIndex { get; set; } // Matrix row index. Its allowed range is from 0 to _synthesizedMatrixRowCount - 1. [KeyType(_synthesizedMatrixRowCount)] public uint MatrixRowIndex { get; set; } // The value at the MatrixColumnIndex-th column and the MatrixRowIndex-th row. public float Value { get; set; } // The predicted value at the MatrixColumnIndex-th column and the MatrixRowIndex-th row. public float Score { get; set; } } // Create an in-memory matrix as a list of tuples (column index, row index, value). Notice that one-
OneClassMatrixElement
csharp
dotnet__extensions
test/Libraries/Microsoft.Extensions.AI.Abstractions.Tests/SpeechToText/SpeechToTextResponseTests.cs
{ "start": 280, "end": 9177 }
public class ____ { [Fact] public void Constructor_InvalidArgs_Throws() { Assert.Throws<ArgumentNullException>("contents", () => new SpeechToTextResponse((IList<AIContent>)null!)); } [Fact] public void Constructor_Parameterless_PropsDefaulted() { SpeechToTextResponse response = new(); Assert.Empty(response.Contents); Assert.Empty(response.Text); Assert.NotNull(response.Contents); Assert.Same(response.Contents, response.Contents); Assert.Empty(response.Contents); Assert.Null(response.RawRepresentation); Assert.Null(response.AdditionalProperties); Assert.Null(response.StartTime); Assert.Null(response.EndTime); Assert.Equal(string.Empty, response.ToString()); Assert.Null(response.Usage); } [Theory] [InlineData(null)] [InlineData("text")] public void Constructor_String_PropsRoundtrip(string? text) { SpeechToTextResponse response = new(text); Assert.Same(response.Contents, response.Contents); if (text is null) { Assert.Empty(response.Contents); } else { Assert.Single(response.Contents); TextContent tc = Assert.IsType<TextContent>(response.Contents[0]); Assert.Equal(text, tc.Text); } Assert.Null(response.RawRepresentation); Assert.Null(response.AdditionalProperties); Assert.Equal(text ?? string.Empty, response.ToString()); } [Fact] public void Constructor_List_InvalidArgs_Throws() { Assert.Throws<ArgumentNullException>("contents", () => new SpeechToTextResponse((IList<AIContent>)null!)); } [Theory] [InlineData(0)] [InlineData(1)] [InlineData(2)] public void Constructor_List_PropsRoundtrip(int contentCount) { List<AIContent> content = []; for (int i = 0; i < contentCount; i++) { content.Add(new TextContent($"text-{i}")); } SpeechToTextResponse response = new(content); Assert.Same(response.Contents, response.Contents); if (contentCount == 0) { Assert.Empty(response.Contents); Assert.Empty(response.Text); } else { Assert.Equal(contentCount, response.Contents.Count); for (int i = 0; i < contentCount; i++) { TextContent tc = Assert.IsType<TextContent>(response.Contents[i]); Assert.Equal($"text-{i}", tc.Text); } Assert.Equal(string.Concat(Enumerable.Range(0, contentCount).Select(i => $"text-{i}")), response.Text); Assert.Equal(string.Concat(Enumerable.Range(0, contentCount).Select(i => $"text-{i}")), response.ToString()); } } [Fact] public void Properties_Roundtrip() { SpeechToTextResponse response = new(); Assert.Null(response.ResponseId); response.ResponseId = "id"; Assert.Equal("id", response.ResponseId); Assert.Null(response.ModelId); response.ModelId = "modelId"; Assert.Equal("modelId", response.ModelId); Assert.Null(response.RawRepresentation); object raw = new(); response.RawRepresentation = raw; Assert.Same(raw, response.RawRepresentation); Assert.Null(response.AdditionalProperties); AdditionalPropertiesDictionary additionalProps = []; response.AdditionalProperties = additionalProps; Assert.Same(additionalProps, response.AdditionalProperties); Assert.Null(response.StartTime); TimeSpan startTime = TimeSpan.FromSeconds(1); response.StartTime = startTime; Assert.Equal(startTime, response.StartTime); Assert.Null(response.EndTime); TimeSpan endTime = TimeSpan.FromSeconds(2); response.EndTime = endTime; Assert.Equal(endTime, response.EndTime); List<AIContent> newContents = [new TextContent("text1"), new TextContent("text2")]; response.Contents = newContents; Assert.Same(newContents, response.Contents); Assert.Null(response.Usage); UsageDetails usageDetails = new(); response.Usage = usageDetails; Assert.Same(usageDetails, response.Usage); } [Fact] public void JsonSerialization_Roundtrips() { SpeechToTextResponse original = new() { Contents = [ new TextContent("Text1"), new TextContent("Text2"), new TextContent("Text3"), new TextContent("Text4"), ], ResponseId = "id", ModelId = "modelId", StartTime = TimeSpan.FromSeconds(1), EndTime = TimeSpan.FromSeconds(2), RawRepresentation = new(), AdditionalProperties = new() { ["key"] = "value" }, Usage = new() { InputTokenCount = 42, OutputTokenCount = 84, TotalTokenCount = 126 }, }; string json = JsonSerializer.Serialize(original, TestJsonSerializerContext.Default.SpeechToTextResponse); SpeechToTextResponse? result = JsonSerializer.Deserialize(json, TestJsonSerializerContext.Default.SpeechToTextResponse); Assert.NotNull(result); Assert.Equal(4, result.Contents.Count); for (int i = 0; i < original.Contents.Count; i++) { Assert.Equal($"Text{i + 1}", ((TextContent)result.Contents[i]).Text); } Assert.Equal("id", result.ResponseId); Assert.Equal("modelId", result.ModelId); Assert.Equal(TimeSpan.FromSeconds(1), result.StartTime); Assert.Equal(TimeSpan.FromSeconds(2), result.EndTime); Assert.NotNull(result.AdditionalProperties); Assert.Single(result.AdditionalProperties); Assert.True(result.AdditionalProperties.TryGetValue("key", out object? value)); Assert.IsType<JsonElement>(value); Assert.Equal("value", ((JsonElement)value!).GetString()); Assert.NotNull(result.Usage); Assert.Equal(42, result.Usage.InputTokenCount); Assert.Equal(84, result.Usage.OutputTokenCount); Assert.Equal(126, result.Usage.TotalTokenCount); } [Fact] public void ToString_OutputsText() { SpeechToTextResponse response = new("This is a test." + Environment.NewLine + "It's multiple lines."); Assert.Equal("This is a test." + Environment.NewLine + "It's multiple lines.", response.ToString()); } [Theory] [InlineData(false)] [InlineData(true)] public void ToSpeechToTextResponseUpdates_ReturnsExpectedUpdate(bool withUsage) { // Arrange: create a response with contents SpeechToTextResponse response = new() { Contents = [ new TextContent("Hello, "), new DataContent("data:image/png;base64,AQIDBA==", mediaType: "image/png"), new TextContent("world!") ], StartTime = TimeSpan.FromSeconds(1), EndTime = TimeSpan.FromSeconds(2), ResponseId = "12345", ModelId = "someModel", AdditionalProperties = new() { ["key1"] = "value1", ["key2"] = 42 }, Usage = withUsage ? new UsageDetails { InputTokenCount = 100, OutputTokenCount = 200, TotalTokenCount = 300 } : null }; // Act: convert to streaming updates SpeechToTextResponseUpdate[] updates = response.ToSpeechToTextResponseUpdates(); // Assert: should be a single update with all properties Assert.Single(updates); SpeechToTextResponseUpdate update = updates[0]; Assert.Equal("12345", update.ResponseId); Assert.Equal("someModel", update.ModelId); Assert.Equal(SpeechToTextResponseUpdateKind.TextUpdated, update.Kind); Assert.Equal(TimeSpan.FromSeconds(1), update.StartTime); Assert.Equal(TimeSpan.FromSeconds(2), update.EndTime); Assert.Equal(withUsage ? 4 : 3, update.Contents.Count); Assert.Equal("Hello, ", Assert.IsType<TextContent>(update.Contents[0]).Text); Assert.Equal("image/png", Assert.IsType<DataContent>(update.Contents[1]).MediaType); Assert.Equal("world!", Assert.IsType<TextContent>(update.Contents[2]).Text); Assert.NotNull(update.AdditionalProperties); Assert.Equal("value1", update.AdditionalProperties["key1"]); Assert.Equal(42, update.AdditionalProperties["key2"]); if (withUsage) { var usage = Assert.IsType<UsageContent>(update.Contents[3]); Assert.Equal(100, usage.Details.InputTokenCount); Assert.Equal(200, usage.Details.OutputTokenCount); Assert.Equal(300, usage.Details.TotalTokenCount); } } }
SpeechToTextResponseTests
csharp
unoplatform__uno
src/Uno.UWP/Generated/3.0.0.0/Windows.UI.Composition.Interactions/InteractionTrackerInertiaNaturalMotion.cs
{ "start": 310, "end": 3731 }
public partial class ____ : global::Windows.UI.Composition.Interactions.InteractionTrackerInertiaModifier { #if __ANDROID__ || __IOS__ || __TVOS__ || IS_UNIT_TESTS || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__ internal InteractionTrackerInertiaNaturalMotion() { } #endif #if __ANDROID__ || __IOS__ || __TVOS__ || IS_UNIT_TESTS || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__ [global::Uno.NotImplemented("__ANDROID__", "__IOS__", "__TVOS__", "IS_UNIT_TESTS", "__WASM__", "__SKIA__", "__NETSTD_REFERENCE__")] public global::Windows.UI.Composition.ScalarNaturalMotionAnimation NaturalMotion { get { throw new global::System.NotImplementedException("The member ScalarNaturalMotionAnimation InteractionTrackerInertiaNaturalMotion.NaturalMotion is not implemented. For more information, visit https://aka.platform.uno/notimplemented#m=ScalarNaturalMotionAnimation%20InteractionTrackerInertiaNaturalMotion.NaturalMotion"); } set { global::Windows.Foundation.Metadata.ApiInformation.TryRaiseNotImplemented("Windows.UI.Composition.Interactions.InteractionTrackerInertiaNaturalMotion", "ScalarNaturalMotionAnimation InteractionTrackerInertiaNaturalMotion.NaturalMotion"); } } #endif #if __ANDROID__ || __IOS__ || __TVOS__ || IS_UNIT_TESTS || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__ [global::Uno.NotImplemented("__ANDROID__", "__IOS__", "__TVOS__", "IS_UNIT_TESTS", "__WASM__", "__SKIA__", "__NETSTD_REFERENCE__")] public global::Windows.UI.Composition.ExpressionAnimation Condition { get { throw new global::System.NotImplementedException("The member ExpressionAnimation InteractionTrackerInertiaNaturalMotion.Condition is not implemented. For more information, visit https://aka.platform.uno/notimplemented#m=ExpressionAnimation%20InteractionTrackerInertiaNaturalMotion.Condition"); } set { global::Windows.Foundation.Metadata.ApiInformation.TryRaiseNotImplemented("Windows.UI.Composition.Interactions.InteractionTrackerInertiaNaturalMotion", "ExpressionAnimation InteractionTrackerInertiaNaturalMotion.Condition"); } } #endif // Forced skipping of method Windows.UI.Composition.Interactions.InteractionTrackerInertiaNaturalMotion.Condition.get // Forced skipping of method Windows.UI.Composition.Interactions.InteractionTrackerInertiaNaturalMotion.Condition.set // Forced skipping of method Windows.UI.Composition.Interactions.InteractionTrackerInertiaNaturalMotion.NaturalMotion.get // Forced skipping of method Windows.UI.Composition.Interactions.InteractionTrackerInertiaNaturalMotion.NaturalMotion.set #if __ANDROID__ || __IOS__ || __TVOS__ || IS_UNIT_TESTS || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__ [global::Uno.NotImplemented("__ANDROID__", "__IOS__", "__TVOS__", "IS_UNIT_TESTS", "__WASM__", "__SKIA__", "__NETSTD_REFERENCE__")] public static global::Windows.UI.Composition.Interactions.InteractionTrackerInertiaNaturalMotion Create(global::Windows.UI.Composition.Compositor compositor) { throw new global::System.NotImplementedException("The member InteractionTrackerInertiaNaturalMotion InteractionTrackerInertiaNaturalMotion.Create(Compositor compositor) is not implemented. For more information, visit https://aka.platform.uno/notimplemented#m=InteractionTrackerInertiaNaturalMotion%20InteractionTrackerInertiaNaturalMotion.Create%28Compositor%20compositor%29"); } #endif } }
InteractionTrackerInertiaNaturalMotion
csharp
dotnet__maui
src/Controls/tests/TestCases.HostApp/Issues/Issue15826.xaml.cs
{ "start": 2471, "end": 2537 }
internal class ____ { public string Text { get; set; } } }
ListData
csharp
dotnet__efcore
test/EFCore.Specification.Tests/ModelBuilding/GiantModel.cs
{ "start": 203046, "end": 203263 }
public class ____ { public int Id { get; set; } public RelatedEntity936 ParentEntity { get; set; } public IEnumerable<RelatedEntity938> ChildEntities { get; set; } }
RelatedEntity937
csharp
ServiceStack__ServiceStack
ServiceStack/tests/ServiceStack.WebHost.Endpoints.Tests/CommandsTests.cs
{ "start": 8303, "end": 8598 }
public class ____ : IAsyncCommand<FailedRequest> { public int Attempts { get; set; } public Task ExecuteAsync(FailedRequest request) { if (Attempts++ < 5) throw new Exception($"{Attempts} Attempt Failed"); return Task.CompletedTask; } }
FailTimes4Command
csharp
npgsql__npgsql
src/Npgsql/Internal/Converters/Primitive/PgNumeric.cs
{ "start": 3042, "end": 16685 }
struct ____ { const ushort SignPositive = 0x0000; const ushort SignNegative = 0x4000; const ushort SignNan = 0xC000; const ushort SignPinf = 0xD000; const ushort SignNinf = 0xF000; const uint NumericBase = 10000; const int NumericBaseLog10 = 4; // log10(10000) internal const int MaxDecimalNumericDigits = 8; // Fast access for 10^n where n is 0-9 static ReadOnlySpan<uint> UIntPowers10 => [ 1, 10, 100, 1000, 10000, 100000, 1000000, 10000000, 100000000, 1000000000 ]; const int MaxUInt32Scale = 9; const int MaxUInt16Scale = 4; public short Weight { get; } readonly ushort _sign; public short Sign => (short)_sign; public short Scale { get; } public Span<short> Digits { get; } readonly short[]? _digitsArray; public Builder(Span<short> digits, short weight, short sign, short scale) { Digits = digits; Weight = weight; _sign = (ushort)sign; Scale = scale; } public Builder(short[] digits, short weight, short sign, short scale) { Digits = _digitsArray = digits; Weight = weight; _sign = (ushort)sign; Scale = scale; } [Conditional("DEBUG")] static void AssertInvariants() { Debug.Assert(UIntPowers10.Length >= NumericBaseLog10); Debug.Assert(NumericBase < short.MaxValue); } static void Create(ref short[]? digitsArray, ref Span<short> destination, scoped Span<uint> bits, short scale, out short weight, out int digitCount) { AssertInvariants(); digitCount = 0; var digitWeight = -scale / NumericBaseLog10 - 1; var bitsUpperBound = (bits.Length * (MaxUInt32Scale + 1) + MaxUInt16Scale - 1) / MaxUInt16Scale + 1; if (bitsUpperBound > destination.Length) destination = digitsArray = new short[bitsUpperBound]; // When the given scale does not sit on a numeric digit boundary we divide once by the remainder power of 10 instead of the base. // As a result the quotient is aligned to a digit boundary, we must then scale up the remainder by the missed power of 10 to compensate. var scaleRemainder = scale % NumericBaseLog10; if (scaleRemainder > 0 && DivideInPlace(bits, UIntPowers10[scaleRemainder], out var remainder) && remainder != 0) { remainder *= UIntPowers10[NumericBaseLog10 - scaleRemainder]; digitWeight--; destination[destination.Length - 1 - digitCount++] = (short)remainder; } while (DivideInPlace(bits, NumericBase, out remainder)) { // Initial zero remainders are skipped as these present trailing zero digits, which should not be stored. if (digitCount == 0 && remainder == 0) digitWeight++; else // We store the results starting from the end so the final digits end up in big endian. destination[destination.Length - 1 - digitCount++] = (short)remainder; } weight = (short)(digitWeight + digitCount); } public Builder(decimal value, Span<short> destination) { Span<uint> bits = stackalloc uint[DecimalBits]; GetDecimalBits(value, bits, out var scale); bits = bits.Slice(0, DecimalBits - 1); Create(ref _digitsArray, ref destination, bits, scale, out var weight, out var digitCount); Digits = destination.Slice(destination.Length - digitCount); Weight = weight; _sign = value < 0 ? SignNegative : SignPositive; Scale = scale; } /// <summary> /// /// </summary> /// <param name="value"></param> /// <param name="destination">If the destination ends up being too small the builder allocates instead</param> public Builder(BigInteger value, Span<short> destination) { var absValue = BigInteger.Abs(value); // isUnsigned: true fails for negative values. var uintRoundedByteCount = (absValue.GetByteCount(isUnsigned: true) + (sizeof(uint) - 1)) / sizeof(uint) * sizeof(uint); byte[]? uintRoundedBitsFromPool = null; var uintRoundedBits = (uintRoundedByteCount <= StackAllocByteThreshold ? stackalloc byte[StackAllocByteThreshold] : uintRoundedBitsFromPool = ArrayPool<byte>.Shared.Rent(uintRoundedByteCount) ).Slice(0, uintRoundedByteCount); // Fill the last uint worth of bytes as it may only be partially written to. uintRoundedBits.Slice(uintRoundedBits.Length - sizeof(uint)).Fill(0); var success = absValue.TryWriteBytes(uintRoundedBits, out _, isUnsigned: true); Debug.Assert(success); var uintBits = MemoryMarshal.Cast<byte, uint>(uintRoundedBits); // Our calculations are all done in little endian, meaning the least significant *uint* is first, just like in BigInteger. // The bytes comprising every individual uint should still be converted to big endian though. // As a result an array of bytes like [ 0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8 ] should become [ 0x4, 0x3, 0x2, 0x1, 0x8, 0x7, 0x6, 0x5 ]. if (!BitConverter.IsLittleEndian) for (var i = 0; i < uintBits.Length; i++) uintBits[i] = BinaryPrimitives.ReverseEndianness(uintBits[i]); Create(ref _digitsArray, ref destination, uintBits, scale: 0, out var weight, out var digitCount); Digits = destination.Slice(destination.Length - digitCount); Weight = weight; _sign = value < 0 ? SignNegative : SignPositive; Scale = 0; if (uintRoundedBitsFromPool is not null) ArrayPool<byte>.Shared.Return(uintRoundedBitsFromPool); } public PgNumeric Build() { var digitsArray = _digitsArray is not null ? new ArraySegment<short>(_digitsArray, _digitsArray.Length - Digits.Length, Digits.Length) : new ArraySegment<short>(Digits.ToArray()); return new(digitsArray, Weight, Sign, Scale); } public decimal ToDecimal() => ToDecimal(Scale, Weight, _sign, Digits); public BigInteger ToBigInteger() => ToBigInteger(Weight, _sign, Digits); int DigitCount => Digits.Length; /// <summary> /// /// </summary> /// <param name="left"></param> /// <param name="right"></param> /// <param name="remainder"></param> /// <returns>Whether the input consists of any non zero bits</returns> static bool DivideInPlace(Span<uint> left, uint right, out uint remainder) => Divide(left, right, left, out remainder); /// <remarks>Adapted from BigInteger, to allow us to operate directly on stack allocated bits</remarks> static bool Divide(ReadOnlySpan<uint> left, uint right, Span<uint> quotient, out uint remainder) { Debug.Assert(quotient.Length == left.Length); // Executes the division for one big and one 32-bit integer. // Thus, we've similar code than below, but there is no loop for // processing the 32-bit integer, since it's a single element. var carry = 0UL; var nonZeroInput = false; for (var i = left.Length - 1; i >= 0; i--) { var value = (carry << 32) | left[i]; nonZeroInput = nonZeroInput || value != 0; var digit = value / right; quotient[i] = (uint)digit; carry = value - digit * right; } remainder = (uint)carry; return nonZeroInput; } internal static int GetDigitCountCore(Span<uint> bits, int scale) { AssertInvariants(); // When a fractional result is expected we must send two numeric digits. // When the given scale does not sit on a numeric digit boundary- // we divide once by the remaining power of 10 instead of the full base to align things. var baseLogRemainder = scale % NumericBaseLog10; var den = baseLogRemainder > 0 ? UIntPowers10[baseLogRemainder] : NumericBase; var digits = 0; while (DivideInPlace(bits, den, out var remainder)) { den = NumericBase; // Initial zero remainders are skipped as these present trailing zero digits, which should not be transmitted. if (digits != 0 || remainder != 0) digits++; } return digits; } internal static decimal ToDecimal(short scale, short weight, ushort sign, Span<short> digits) { const int MaxUIntScale = 9; const int MaxDecimalScale = 28; var digitCount = digits.Length; if (digitCount > MaxDecimalNumericDigits) throw new OverflowException("Numeric value does not fit in a System.Decimal"); if (Math.Abs(scale) > MaxDecimalScale) throw new OverflowException("Numeric value does not fit in a System.Decimal"); var scaleFactor = new decimal(1, 0, 0, false, (byte)(scale > 0 ? scale : 0)); if (digitCount == 0) return sign switch { SignPositive or SignNegative => decimal.Zero * scaleFactor, SignNan => throw new InvalidCastException("Numeric NaN not supported by System.Decimal"), SignPinf => throw new InvalidCastException("Numeric Infinity not supported by System.Decimal"), SignNinf => throw new InvalidCastException("Numeric -Infinity not supported by System.Decimal"), _ => throw new ArgumentOutOfRangeException() }; var numericBase = new decimal(NumericBase); var result = decimal.Zero; for (var i = 0; i < digitCount - 1; i++) { result *= numericBase; result += digits[i]; } var digitScale = (weight + 1 - digitCount) * NumericBaseLog10; var scaleDifference = scale < 0 ? digitScale : digitScale + scale; var digit = digits[digitCount - 1]; if (digitCount == MaxDecimalNumericDigits) { // On the max group we adjust the base based on the scale difference, to prevent overflow for valid values. var pow = UIntPowers10[-scaleDifference]; result *= numericBase / pow; result += new decimal(digit / pow); } else { result *= numericBase; result += digit; if (scaleDifference < 0) { // Doesn't look like we can loop even once, but just to be on a safe side while (scaleDifference < 0) { var scaleChunk = Math.Min(MaxUIntScale, -scaleDifference); result /= UIntPowers10[scaleChunk]; scaleDifference += scaleChunk; } } else { while (scaleDifference > 0) { var scaleChunk = Math.Min(MaxUIntScale, scaleDifference); scaleFactor *= UIntPowers10[scaleChunk]; scaleDifference -= scaleChunk; } } } result *= scaleFactor; return sign == SignNegative ? -result : result; } internal static BigInteger ToBigInteger(short weight, ushort sign, Span<short> digits) { var digitCount = digits.Length; if (digitCount == 0) return sign switch { SignPositive or SignNegative => BigInteger.Zero, SignNan => throw new InvalidCastException("Numeric NaN not supported by BigInteger"), SignPinf => throw new InvalidCastException("Numeric Infinity not supported by BigInteger"), SignNinf => throw new InvalidCastException("Numeric -Infinity not supported by BigInteger"), _ => throw new ArgumentOutOfRangeException() }; var digitWeight = weight + 1 - digitCount; if (digitWeight < 0) throw new InvalidCastException("Numeric value with non-zero fractional digits not supported by BigInteger"); var numericBase = new BigInteger(NumericBase); var result = BigInteger.Zero; foreach (var digit in digits) { result *= numericBase; result += new BigInteger(digit); } var exponentCorrection = BigInteger.Pow(numericBase, digitWeight); result *= exponentCorrection; return sign == SignNegative ? -result : result; } } }
Builder
csharp
MassTransit__MassTransit
src/MassTransit/Consumers/Configuration/IConsumerMessageSpecification.cs
{ "start": 62, "end": 454 }
public interface ____<TConsumer> : IPipeConfigurator<ConsumerConsumeContext<TConsumer>>, IConsumerConfigurationObserverConnector, ISpecification where TConsumer : class { Type MessageType { get; } bool TryGetMessageSpecification<TC, T>(out IConsumerMessageSpecification<TC, T> specification) where T :
IConsumerMessageSpecification
csharp
duplicati__duplicati
Duplicati/Library/Backend/GoogleServices/GoogleDrive.cs
{ "start": 16585, "end": 16699 }
private class ____ { public string? id { get; set; } }
GoogleDriveParentReference
csharp
duplicati__duplicati
Executables/Duplicati.CommandLine.SharpAESCrypt/Program.cs
{ "start": 1331, "end": 1615 }
public static class ____ { public static int Main(string[] args) => CrashlogHelper.WrapWithCrashLog(() => { global::SharpAESCrypt.Program.CommandLineMain(args); return Environment.ExitCode; }); } }
Program
csharp
dotnet__aspnetcore
src/Servers/Kestrel/Core/src/Internal/Http2/Http2StreamErrorException.cs
{ "start": 206, "end": 593 }
internal sealed class ____ : Exception { public Http2StreamErrorException(int streamId, string message, Http2ErrorCode errorCode) : base($"HTTP/2 stream ID {streamId} error ({errorCode}): {message}") { StreamId = streamId; ErrorCode = errorCode; } public int StreamId { get; } public Http2ErrorCode ErrorCode { get; } }
Http2StreamErrorException
csharp
dotnet__machinelearning
test/Microsoft.ML.Tokenizers.Tests/BertTokenizerTests.cs
{ "start": 416, "end": 31971 }
public class ____ { [Fact] public void TestWithLowerCasingExplicitSpecialTokens() { // Add [SPECIAL] token at end (to keep indices as is) // Ids: 0 1 2 3 4 5 6 7 8 9 10 11 12, 13 string[] vocabTokens = ["[PAD]", "[UNK]", "[CLS]", "[SEP]", "[MASK]", "!", ",", "?", "hello", "world", "how", "are", "you", "[SPECIAL]"]; string vocabFile = WordPieceTests.CreateVocabFile(vocabTokens); Dictionary<string, int> specialTokens = new() { { "[PAD]", 0 }, { "[UNK]", 1 }, { "[CLS]", 2 }, { "[SEP]", 3 }, { "[MASK]", 4 }, { "[SPECIAL]", 13 }, }; var bertOptions = new BertOptions() { SpecialTokens = specialTokens }; try { using Stream vocabStream = File.OpenRead(vocabFile); BertTokenizer[] bertTokenizers = [BertTokenizer.Create(vocabFile, bertOptions), BertTokenizer.Create(vocabStream, bertOptions)]; foreach (var tokenizer in bertTokenizers) { Assert.NotNull(tokenizer.PreTokenizer); Assert.Equal("[UNK]", tokenizer.UnknownToken); Assert.Equal(1, tokenizer.UnknownTokenId); Assert.NotNull(tokenizer.Normalizer); Assert.NotNull(tokenizer.PreTokenizer); Assert.True(tokenizer.SpecialTokens!.ContainsKey("[SPECIAL]")); string text = "Hello, How are you [SPECIAL]?"; var tokens = tokenizer.EncodeToTokens(text, out string? normalizedText); Assert.Equal("hello, how are you [special]?", normalizedText); Assert.Equal( [ new EncodedToken(8, "hello", new Range(0, 5)), new EncodedToken(6, ",", new Range(5, 6)), new EncodedToken(10, "how", new Range(7, 10)), new EncodedToken(11, "are", new Range(11, 14)), new EncodedToken(12, "you", new Range(15, 18)), new EncodedToken(13, "[SPECIAL]", new Range(19, 28)), new EncodedToken(7, "?", new Range(28, 29)) ], tokens); var ids = tokenizer.EncodeToIds(text); Assert.Equal([tokenizer.ClassificationTokenId, 8, 6, 10, 11, 12, 13, 7, tokenizer.SeparatorTokenId], ids); Assert.Equal("[CLS] hello, how are you [SPECIAL]? [SEP]", tokenizer.Decode(ids)); Assert.Equal("hello, how are you?", tokenizer.Decode(ids, skipSpecialTokens: true)); tokens = tokenizer.EncodeToTokens(tokenizer.Decode(ids), out normalizedText); Assert.Equal("[cls] hello, how are you [special]? [sep]", normalizedText); Assert.Equal( [ new EncodedToken(2, "[CLS]", new Range(0, 5)), new EncodedToken(8, "hello", new Range(6, 11)), new EncodedToken(6, ",", new Range(11, 12)), new EncodedToken(10, "how", new Range(13, 16)), new EncodedToken(11, "are", new Range(17, 20)), new EncodedToken(12, "you", new Range(21, 24)), new EncodedToken(13, "[SPECIAL]", new Range(25, 34)), new EncodedToken(7, "?", new Range(34, 35)), new EncodedToken(3, "[SEP]", new Range(36, 41)) ], tokens); ids = tokenizer.EncodeToIds(normalizedText!); Assert.Equal([tokenizer.ClassificationTokenId, tokenizer.ClassificationTokenId, 8, 6, 10, 11, 12, 13, 7, tokenizer.SeparatorTokenId, tokenizer.SeparatorTokenId], ids); } } finally { File.Delete(vocabFile); } } [Fact] public void TestWithLowerCasing() { // Ids: 0 1 2 3 4 5 6 7 8 9 10 11 12 string[] vocabTokens = ["[PAD]", "[UNK]", "[CLS]", "[SEP]", "[MASK]", "!", ",", "?", "hello", "world", "how", "are", "you"]; string vocabFile = WordPieceTests.CreateVocabFile(vocabTokens); try { using Stream vocabStream = File.OpenRead(vocabFile); BertTokenizer[] bertTokenizers = [BertTokenizer.Create(vocabFile), BertTokenizer.Create(vocabStream)]; foreach (var tokenizer in bertTokenizers) { Assert.NotNull(tokenizer.PreTokenizer); Assert.Equal("[UNK]", tokenizer.UnknownToken); Assert.Equal(1, tokenizer.UnknownTokenId); Assert.NotNull(tokenizer.Normalizer); Assert.NotNull(tokenizer.PreTokenizer); // Make sure the SpecialTokens dictionary contains the not-normalized tokens Assert.True(tokenizer.SpecialTokens!.ContainsKey(tokenizer.UnknownToken)); Assert.True(tokenizer.SpecialTokens!.ContainsKey(tokenizer.ClassificationToken)); string text = "Hello, How are you?"; var tokens = tokenizer.EncodeToTokens(text, out string? normalizedText); Assert.Equal("hello, how are you?", normalizedText); Assert.Equal( [ new EncodedToken(8, "hello", new Range(0, 5)), new EncodedToken(6, ",", new Range(5, 6)), new EncodedToken(10, "how", new Range(7, 10)), new EncodedToken(11, "are", new Range(11, 14)), new EncodedToken(12, "you", new Range(15, 18)), new EncodedToken(7, "?", new Range(18, 19)) ], tokens); var ids = tokenizer.EncodeToIds(text); Assert.Equal([tokenizer.ClassificationTokenId, 8, 6, 10, 11, 12, 7, tokenizer.SeparatorTokenId], ids); Assert.Equal("[CLS] hello, how are you? [SEP]", tokenizer.Decode(ids)); Assert.Equal("hello, how are you?", tokenizer.Decode(ids, skipSpecialTokens: true)); tokens = tokenizer.EncodeToTokens(tokenizer.Decode(ids), out normalizedText); Assert.Equal("[cls] hello, how are you? [sep]", normalizedText); Assert.Equal( [ new EncodedToken(2, "[CLS]", new Range(0, 5)), new EncodedToken(8, "hello", new Range(6, 11)), new EncodedToken(6, ",", new Range(11, 12)), new EncodedToken(10, "how", new Range(13, 16)), new EncodedToken(11, "are", new Range(17, 20)), new EncodedToken(12, "you", new Range(21, 24)), new EncodedToken(7, "?", new Range(24, 25)), new EncodedToken(3, "[SEP]", new Range(26, 31)) ], tokens); ids = tokenizer.EncodeToIds(normalizedText!); Assert.Equal([tokenizer.ClassificationTokenId, tokenizer.ClassificationTokenId, 8, 6, 10, 11, 12, 7, tokenizer.SeparatorTokenId, tokenizer.SeparatorTokenId], ids); } } finally { File.Delete(vocabFile); } } [Fact] public void TestWithNoLowerCasing() { // Ids: 0 1 2 3 4 5 6 7 8 9 10 11 12 string[] vocabTokens = ["[PAD]", "[UNK]", "[CLS]", "[SEP]", "[MASK]", "!", ",", "?", "hello", "world", "how", "are", "you"]; string vocabFile = WordPieceTests.CreateVocabFile(vocabTokens); try { using Stream vocabStream = File.OpenRead(vocabFile); BertTokenizer[] bertTokenizers = [BertTokenizer.Create(vocabFile, new BertOptions { LowerCaseBeforeTokenization = false }), BertTokenizer.Create(vocabStream, new BertOptions { LowerCaseBeforeTokenization = false })]; foreach (var tokenizer in bertTokenizers) { Assert.NotNull(tokenizer.PreTokenizer); Assert.Equal("[UNK]", tokenizer.UnknownToken); Assert.Equal(1, tokenizer.UnknownTokenId); Assert.NotNull(tokenizer.Normalizer); Assert.NotNull(tokenizer.PreTokenizer); string text = "Hello, How are you?"; var tokens = tokenizer.EncodeToTokens(text, out string? normalizedText); Assert.Equal("Hello, How are you?", normalizedText); Assert.Equal( [ new EncodedToken(1, "[UNK]", new Range(0, 5)), new EncodedToken(6, ",", new Range(5, 6)), new EncodedToken(1, "[UNK]", new Range(7, 10)), new EncodedToken(11, "are", new Range(11, 14)), new EncodedToken(12, "you", new Range(15, 18)), new EncodedToken(7, "?", new Range(18, 19)) ], tokens); var ids = tokenizer.EncodeToIds(text); Assert.Equal([tokenizer.ClassificationTokenId, 1, 6, 1, 11, 12, 7, tokenizer.SeparatorTokenId], ids); Assert.Equal("[CLS] [UNK], [UNK] are you? [SEP]", tokenizer.Decode(ids)); Assert.Equal(", are you?", tokenizer.Decode(ids, skipSpecialTokens: true)); } } finally { File.Delete(vocabFile); } } [Fact] public async Task TestWithAccentMarks() { // Ids: 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 string[] vocabTokens = ["[PAD]", "[UNK]", "[CLS]", "[SEP]", "[MASK]", "!", ",", "?", "Café", "cafe", "café", "Über", "über", "uber", "Ångström", "ångström", "angstrom", "Résumé", "résumé", "resume", // Ids: 20 21 22 23 "Cafe", "Uber", "Angstrom", "Resume"]; string vocabFile = WordPieceTests.CreateVocabFile(vocabTokens); try { using Stream vocabStream = File.OpenRead(vocabFile); BertTokenizer bertTokenizer = await BertTokenizer.CreateAsync(vocabStream); // lowercasing and no accent stripping string text = "Café Über Ångström Résumé!"; var tokens = bertTokenizer.EncodeToTokens(text, out string? normalizedText); Assert.Equal( [ new EncodedToken(10, "café", new Range(0, 4)), new EncodedToken(12, "über", new Range(5, 9)), new EncodedToken(15, "ångström", new Range(10, 18)), new EncodedToken(18, "résumé", new Range(19, 25)), new EncodedToken(5, "!", new Range(25, 26)), ], tokens); Assert.Equal("café über ångström résumé!", normalizedText); vocabStream.Position = 0; bertTokenizer = await BertTokenizer.CreateAsync(vocabStream, new BertOptions { LowerCaseBeforeTokenization = false }); // no lowercasing and no accent stripping tokens = bertTokenizer.EncodeToTokens(text, out normalizedText); Assert.Equal( [ new EncodedToken(8, "Café", new Range(0, 4)), new EncodedToken(11, "Über", new Range(5, 9)), new EncodedToken(14, "Ångström", new Range(10, 18)), new EncodedToken(17, "Résumé", new Range(19, 25)), new EncodedToken(5, "!", new Range(25, 26)), ], tokens); Assert.Equal("Café Über Ångström Résumé!", normalizedText); vocabStream.Position = 0; bertTokenizer = await BertTokenizer.CreateAsync(vocabStream, new BertOptions { RemoveNonSpacingMarks = true }); // lowercasing and accent stripping tokens = bertTokenizer.EncodeToTokens(text, out normalizedText); Assert.Equal("cafe uber angstrom resume!", normalizedText); Assert.Equal( [ new EncodedToken(9, "cafe", new Range(0, 4)), new EncodedToken(13, "uber", new Range(5, 9)), new EncodedToken(16, "angstrom", new Range(10, 18)), new EncodedToken(19, "resume", new Range(19, 25)), new EncodedToken(5, "!", new Range(25, 26)), ], tokens); vocabStream.Position = 0; bertTokenizer = await BertTokenizer.CreateAsync(vocabStream, new BertOptions { LowerCaseBeforeTokenization = false, RemoveNonSpacingMarks = true }); // no lowercasing and accent stripping tokens = bertTokenizer.EncodeToTokens(text, out normalizedText); Assert.Equal("Cafe Uber Angstrom Resume!", normalizedText); Assert.Equal( [ new EncodedToken(20, "Cafe", new Range(0, 4)), new EncodedToken(21, "Uber", new Range(5, 9)), new EncodedToken(22, "Angstrom", new Range(10, 18)), new EncodedToken(23, "Resume", new Range(19, 25)), new EncodedToken(5, "!", new Range(25, 26)), ], tokens); } finally { File.Delete(vocabFile); } } [Fact] public async Task TestChineseCharacters() { // Ids: 0 1 2 3 4 5 6 7 8 9 10 11 12 string[] vocabTokens = ["[PAD]", "[UNK]", "[CLS]", "[SEP]", "[MASK]", "!", "##驷", "##驸", "受", "叟", "叢", "驷", "驸"]; string vocabFile = WordPieceTests.CreateVocabFile(vocabTokens); try { using Stream vocabStream = File.OpenRead(vocabFile); BertTokenizer bertTokenizer = await BertTokenizer.CreateAsync(vocabStream); // tokenize Chinese characters string text = "叟驷 叢驸!"; var tokens = bertTokenizer.EncodeToTokens(text, out string? normalizedText); Assert.Equal(" 叟 驷 叢 驸 !", normalizedText); Assert.Equal( [ new EncodedToken(9, "叟", new Range(1, 2)), new EncodedToken(11, "驷", new Range(4, 5)), new EncodedToken(10, "叢", new Range(8, 9)), new EncodedToken(12, "驸", new Range(11, 12)), new EncodedToken(5, "!", new Range(13, 14)) ], tokens); IReadOnlyList<int> ids = bertTokenizer.EncodeToIds(text); Assert.Equal("[CLS] 叟 驷 叢 驸! [SEP]", bertTokenizer.Decode(bertTokenizer.EncodeToIds(text))); Assert.Equal("叟 驷 叢 驸!", bertTokenizer.Decode(bertTokenizer.EncodeToIds(text), skipSpecialTokens: true)); vocabStream.Position = 0; bertTokenizer = await BertTokenizer.CreateAsync(vocabStream, new BertOptions { IndividuallyTokenizeCjk = false }); // do not tokenize Chinese characters tokens = bertTokenizer.EncodeToTokens(text, out normalizedText); Assert.Equal("叟驷 叢驸!", normalizedText); Assert.Equal( [ new EncodedToken(9, "叟", new Range(0, 1)), new EncodedToken(6, "##驷", new Range(1, 2)), new EncodedToken(10, "叢", new Range(3, 4)), new EncodedToken(7, "##驸", new Range(4, 5)), new EncodedToken(5, "!", new Range(5, 6)) ], tokens); ids = bertTokenizer.EncodeToIds(text); Assert.Equal("[CLS] 叟驷 叢驸! [SEP]", bertTokenizer.Decode(bertTokenizer.EncodeToIds(text))); Assert.Equal("叟驷 叢驸!", bertTokenizer.Decode(bertTokenizer.EncodeToIds(text), skipSpecialTokens: true)); } finally { File.Delete(vocabFile); } } [Fact] public void TestBuildInputsWithSpecialTokens() { // Ids: 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 string[] vocabTokens = ["[PAD]", "[UNK]", "[CLS]", "[SEP]", "[MASK]", "!", ",", "?", "hello", "world", "how", "are", "you", "i", "am", "fine"]; string vocabFile = WordPieceTests.CreateVocabFile(vocabTokens); try { using Stream vocabStream = File.OpenRead(vocabFile); BertTokenizer bertTokenizer = BertTokenizer.Create(vocabFile); string text1 = "Hello, How are you?"; string text2 = "I am fine!"; var ids1 = bertTokenizer.EncodeToIds(text1); Assert.Equal([bertTokenizer.ClassificationTokenId, 8, 6, 10, 11, 12, 7, bertTokenizer.SeparatorTokenId], ids1); var ids2 = bertTokenizer.EncodeToIds(text2); Assert.Equal([bertTokenizer.ClassificationTokenId, 13, 14, 15, 5, bertTokenizer.SeparatorTokenId], ids2); Assert.Equal( [bertTokenizer.ClassificationTokenId, bertTokenizer.ClassificationTokenId, 8, 6, 10, 11, 12, 7, bertTokenizer.SeparatorTokenId, bertTokenizer.SeparatorTokenId], bertTokenizer.BuildInputsWithSpecialTokens(ids1)); Span<int> ids1Span = stackalloc int[1]; OperationStatus status = bertTokenizer.BuildInputsWithSpecialTokens(ids1, ids1Span, out int written); Assert.Equal(OperationStatus.DestinationTooSmall, status); Assert.Equal(0, written); ids1Span = stackalloc int[ids1.Count + 2]; status = bertTokenizer.BuildInputsWithSpecialTokens(ids1, ids1Span, out written); Assert.Equal(OperationStatus.Done, status); Assert.Equal(ids1.Count + 2, written); Assert.Equal(new int[] { bertTokenizer.ClassificationTokenId, bertTokenizer.ClassificationTokenId, 8, 6, 10, 11, 12, 7, bertTokenizer.SeparatorTokenId, bertTokenizer.SeparatorTokenId }, ids1Span.ToArray()); Assert.Equal( [bertTokenizer.ClassificationTokenId, bertTokenizer.ClassificationTokenId, 8, 6, 10, 11, 12, 7, bertTokenizer.SeparatorTokenId, bertTokenizer.SeparatorTokenId, bertTokenizer.ClassificationTokenId, 13, 14, 15, 5, bertTokenizer.SeparatorTokenId, bertTokenizer.SeparatorTokenId], bertTokenizer.BuildInputsWithSpecialTokens(ids1, ids2)); ids1Span = stackalloc int[1]; status = bertTokenizer.BuildInputsWithSpecialTokens(ids1, ids1Span, out written, ids2); Assert.Equal(OperationStatus.DestinationTooSmall, status); Assert.Equal(0, written); ids1Span = stackalloc int[ids1.Count + ids2.Count + 3]; status = bertTokenizer.BuildInputsWithSpecialTokens(ids1, ids1Span, out written, ids2); Assert.Equal(OperationStatus.Done, status); Assert.Equal(ids1Span.Length, written); Assert.Equal( new int[] { bertTokenizer.ClassificationTokenId, bertTokenizer.ClassificationTokenId, 8, 6, 10, 11, 12, 7, bertTokenizer.SeparatorTokenId, bertTokenizer.SeparatorTokenId, bertTokenizer.ClassificationTokenId, 13, 14, 15, 5, bertTokenizer.SeparatorTokenId, bertTokenizer.SeparatorTokenId }, ids1Span.ToArray()); ids1 = bertTokenizer.EncodeToIds(text1, addSpecialTokens: false); Assert.Equal([8, 6, 10, 11, 12, 7], ids1); ids2 = bertTokenizer.EncodeToIds(text2, addSpecialTokens: false); Assert.Equal([13, 14, 15, 5], ids2); Assert.Equal( [bertTokenizer.ClassificationTokenId, 8, 6, 10, 11, 12, 7, bertTokenizer.SeparatorTokenId], bertTokenizer.BuildInputsWithSpecialTokens(ids1)); ids1Span = stackalloc int[1]; status = bertTokenizer.BuildInputsWithSpecialTokens(ids1, ids1Span, out written); Assert.Equal(OperationStatus.DestinationTooSmall, status); Assert.Equal(0, written); ids1Span = stackalloc int[ids1.Count + 2]; status = bertTokenizer.BuildInputsWithSpecialTokens(ids1, ids1Span, out written); Assert.Equal(OperationStatus.Done, status); Assert.Equal(ids1Span.Length, written); Assert.Equal( new int[] { bertTokenizer.ClassificationTokenId, 8, 6, 10, 11, 12, 7, bertTokenizer.SeparatorTokenId }, ids1Span.ToArray()); Assert.Equal( [bertTokenizer.ClassificationTokenId, 8, 6, 10, 11, 12, 7, bertTokenizer.SeparatorTokenId, 13, 14, 15, 5, bertTokenizer.SeparatorTokenId], bertTokenizer.BuildInputsWithSpecialTokens(ids1, ids2)); ids1Span = stackalloc int[1]; status = bertTokenizer.BuildInputsWithSpecialTokens(ids1, ids1Span, out written, ids2); Assert.Equal(OperationStatus.DestinationTooSmall, status); Assert.Equal(0, written); ids1Span = stackalloc int[ids1.Count + ids2.Count + 3]; status = bertTokenizer.BuildInputsWithSpecialTokens(ids1, ids1Span, out written, ids2); Assert.Equal(OperationStatus.Done, status); Assert.Equal(ids1Span.Length, written); Assert.Equal( new int[] { bertTokenizer.ClassificationTokenId, 8, 6, 10, 11, 12, 7, bertTokenizer.SeparatorTokenId, 13, 14, 15, 5, bertTokenizer.SeparatorTokenId }, ids1Span.ToArray()); } finally { File.Delete(vocabFile); } } [Fact] public void TestGetSpecialTokensMask() { // Ids: 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 string[] vocabTokens = ["[PAD]", "[UNK]", "[CLS]", "[SEP]", "[MASK]", "!", ",", "?", "hello", "world", "how", "are", "you", "i", "am", "fine"]; string vocabFile = WordPieceTests.CreateVocabFile(vocabTokens); try { using Stream vocabStream = File.OpenRead(vocabFile); BertTokenizer bertTokenizer = BertTokenizer.Create(vocabFile); string text1 = "Hello, How are you?"; string text2 = "I am fine!"; var ids1 = bertTokenizer.EncodeToIds(text1); Assert.Equal([bertTokenizer.ClassificationTokenId, 8, 6, 10, 11, 12, 7, bertTokenizer.SeparatorTokenId], ids1); var ids2 = bertTokenizer.EncodeToIds(text2); Assert.Equal([bertTokenizer.ClassificationTokenId, 13, 14, 15, 5, bertTokenizer.SeparatorTokenId], ids2); Assert.Equal( [1, 0, 0, 0, 0, 0, 0, 1], bertTokenizer.GetSpecialTokensMask(ids1, additionalTokenIds: null, alreadyHasSpecialTokens: true)); Span<int> ids1Span = stackalloc int[1]; OperationStatus status = bertTokenizer.GetSpecialTokensMask(ids1, ids1Span, out int written, alreadyHasSpecialTokens: true); Assert.Equal(OperationStatus.DestinationTooSmall, status); Assert.Equal(0, written); ids1Span = stackalloc int[ids1.Count]; status = bertTokenizer.GetSpecialTokensMask(ids1, ids1Span, out written, alreadyHasSpecialTokens: true); Assert.Equal(OperationStatus.Done, status); Assert.Equal(ids1.Count, written); Assert.Equal(new int[] { 1, 0, 0, 0, 0, 0, 0, 1 }, ids1Span.ToArray()); Assert.Equal( [1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 1], bertTokenizer.GetSpecialTokensMask(ids1, additionalTokenIds: ids2, alreadyHasSpecialTokens: true)); ids1Span = stackalloc int[1]; status = bertTokenizer.GetSpecialTokensMask(ids1, ids1Span, out written, ids2, alreadyHasSpecialTokens: true); Assert.Equal(OperationStatus.DestinationTooSmall, status); Assert.Equal(0, written); ids1Span = stackalloc int[ids1.Count + ids2.Count]; status = bertTokenizer.GetSpecialTokensMask(ids1, ids1Span, out written, ids2, alreadyHasSpecialTokens: true); Assert.Equal(OperationStatus.Done, status); Assert.Equal(ids1.Count + ids2.Count, written); Assert.Equal(new int[] { 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 1 }, ids1Span.ToArray()); ids1 = bertTokenizer.EncodeToIds(text1, addSpecialTokens: false); Assert.Equal([8, 6, 10, 11, 12, 7], ids1); ids2 = bertTokenizer.EncodeToIds(text2, addSpecialTokens: false); Assert.Equal([13, 14, 15, 5], ids2); Assert.Equal( [1, 0, 0, 0, 0, 0, 0, 1], bertTokenizer.GetSpecialTokensMask(ids1, additionalTokenIds: null, alreadyHasSpecialTokens: false)); ids1Span = stackalloc int[1]; status = bertTokenizer.GetSpecialTokensMask(ids1, ids1Span, out written, alreadyHasSpecialTokens: false); Assert.Equal(OperationStatus.DestinationTooSmall, status); Assert.Equal(0, written); ids1Span = stackalloc int[ids1.Count + 2]; status = bertTokenizer.GetSpecialTokensMask(ids1, ids1Span, out written, alreadyHasSpecialTokens: false); Assert.Equal(OperationStatus.Done, status); Assert.Equal(ids1.Count + 2, written); Assert.Equal(new int[] { 1, 0, 0, 0, 0, 0, 0, 1 }, ids1Span.ToArray()); Assert.Equal( [1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1], bertTokenizer.GetSpecialTokensMask(ids1, additionalTokenIds: ids2, alreadyHasSpecialTokens: false)); ids1Span = stackalloc int[1]; status = bertTokenizer.GetSpecialTokensMask(ids1, ids1Span, out written, ids2, alreadyHasSpecialTokens: false); Assert.Equal(OperationStatus.DestinationTooSmall, status); Assert.Equal(0, written); ids1Span = stackalloc int[ids1.Count + ids2.Count + 3]; status = bertTokenizer.GetSpecialTokensMask(ids1, ids1Span, out written, ids2, alreadyHasSpecialTokens: false); Assert.Equal(OperationStatus.Done, status); Assert.Equal(ids1.Count + ids2.Count + 3, written); Assert.Equal(new int[] { 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1 }, ids1Span.ToArray()); } finally { File.Delete(vocabFile); } } [Fact] public void TestCreateTokenTypeIdsFromSequences() { // Ids: 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 string[] vocabTokens = ["[PAD]", "[UNK]", "[CLS]", "[SEP]", "[MASK]", "!", ",", "?", "hello", "world", "how", "are", "you", "i", "am", "fine"]; string vocabFile = WordPieceTests.CreateVocabFile(vocabTokens); try { using Stream vocabStream = File.OpenRead(vocabFile); BertTokenizer bertTokenizer = BertTokenizer.Create(vocabFile); string text1 = "Hello, How are you?"; string text2 = "I am fine!"; var ids1 = bertTokenizer.EncodeToIds(text1, addSpecialTokens: false); Assert.Equal([8, 6, 10, 11, 12, 7], ids1); var ids2 = bertTokenizer.EncodeToIds(text2, addSpecialTokens: false); Assert.Equal([13, 14, 15, 5], ids2); Assert.Equal( [0, 0, 0, 0, 0, 0, 0, 0], bertTokenizer.CreateTokenTypeIdsFromSequences(ids1)); Span<int> ids1Span = stackalloc int[1]; OperationStatus status = bertTokenizer.CreateTokenTypeIdsFromSequences(ids1, ids1Span, out int written); Assert.Equal(OperationStatus.DestinationTooSmall, status); Assert.Equal(0, written); ids1Span = stackalloc int[ids1.Count + 2]; status = bertTokenizer.CreateTokenTypeIdsFromSequences(ids1, ids1Span, out written); Assert.Equal(OperationStatus.Done, status); Assert.Equal(ids1.Count + 2, written); Assert.Equal(new int[] { 0, 0, 0, 0, 0, 0, 0, 0 }, ids1Span.ToArray()); Assert.Equal( [0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1], bertTokenizer.CreateTokenTypeIdsFromSequences(ids1, ids2)); ids1Span = stackalloc int[1]; status = bertTokenizer.CreateTokenTypeIdsFromSequences(ids1, ids1Span, out written, ids2); Assert.Equal(OperationStatus.DestinationTooSmall, status); Assert.Equal(0, written); ids1Span = stackalloc int[ids1.Count + ids2.Count + 3]; status = bertTokenizer.CreateTokenTypeIdsFromSequences(ids1, ids1Span, out written, ids2); Assert.Equal(OperationStatus.Done, status); Assert.Equal(ids1Span.Length, written); Assert.Equal(new int[] { 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1 }, ids1Span.ToArray()); } finally { File.Delete(vocabFile); } } } }
BertTokenizerTests
csharp
AvaloniaUI__Avalonia
src/Avalonia.Controls.ColorPicker/Helpers/ColorHelper.cs
{ "start": 266, "end": 9077 }
public static class ____ { private static readonly Dictionary<HsvColor, string> _cachedDisplayNames = new Dictionary<HsvColor, string>(); private static readonly Dictionary<KnownColor, string> _cachedKnownColorNames = new Dictionary<KnownColor, string>(); private static readonly object _displayNameCacheMutex = new object(); private static readonly object _knownColorCacheMutex = new object(); private static readonly KnownColor[] _knownColors = #if NET6_0_OR_GREATER Enum.GetValues<KnownColor>(); #else (KnownColor[])Enum.GetValues(typeof(KnownColor)); #endif /// <summary> /// Gets the relative (perceptual) luminance/brightness of the given color. /// 1 is closer to white while 0 is closer to black. /// </summary> /// <param name="color">The color to calculate relative luminance for.</param> /// <returns>The relative (perceptual) luminance/brightness of the given color.</returns> public static double GetRelativeLuminance(Color color) { // The equation for relative luminance is given by // // L = 0.2126 * Rg + 0.7152 * Gg + 0.0722 * Bg // // where Xg = { X/3294 if X <= 10, (R/269 + 0.0513)^2.4 otherwise } // // If L is closer to 1, then the color is closer to white; if it is closer to 0, // then the color is closer to black. This is based on the fact that the human // eye perceives green to be much brighter than red, which in turn is perceived to be // brighter than blue. double rg = color.R <= 10 ? color.R / 3294.0 : Math.Pow(color.R / 269.0 + 0.0513, 2.4); double gg = color.G <= 10 ? color.G / 3294.0 : Math.Pow(color.G / 269.0 + 0.0513, 2.4); double bg = color.B <= 10 ? color.B / 3294.0 : Math.Pow(color.B / 269.0 + 0.0513, 2.4); return (0.2126 * rg + 0.7152 * gg + 0.0722 * bg); } /// <summary> /// Determines if color display names are supported based on the current thread culture. /// </summary> /// <remarks> /// Only English names are currently supported following known color names. /// In the future known color names could be localized. /// </remarks> public static bool ToDisplayNameExists { get => CultureInfo.CurrentUICulture.Name.StartsWith("EN", StringComparison.OrdinalIgnoreCase); } /// <summary> /// Determines an approximate display name for the given color. /// </summary> /// <param name="color">The color to get the display name for.</param> /// <returns>The approximate color display name.</returns> public static string ToDisplayName(Color color) { var hsvColor = color.ToHsv(); // Handle extremes that are outside the below algorithm if (color.A == 0x00) { return GetDisplayName(KnownColor.Transparent); } // HSV ---------------------------------------------------------------------- // // There are far too many possible HSV colors to cache and search through // for performance reasons. Therefore, the HSV color is rounded. // Rounding is tolerable in this algorithm because it is perception based. // Hue is the most important for user perception so is rounded the least. // Then there is a lot of loss in rounding the saturation and value components // which are not as closely related to perceived color. // // Hue : Round to nearest int (0..360) // Saturation : Round to the nearest 1/10 (0..1) // Value : Round to the nearest 1/10 (0..1) // Alpha : Is ignored in this algorithm // // Rounding results in ~36_000 values to cache in the worse case. // // RGB ---------------------------------------------------------------------- // // The original algorithm worked in RGB color space. // If this code is every adjusted to work in RGB again note the following: // // Without rounding, there are 16_777_216 possible RGB colors (without alpha). // This is too many to cache and search through for performance reasons. // It is also needlessly large as there are only ~140 known/named colors. // Therefore, rounding of the input color's component values is done to // reduce the color space into something more useful. // // The rounding value of 5 is specially chosen. // It is a factor of 255 and therefore evenly divisible which improves // the quality of the calculations. var roundedHsvColor = new HsvColor( 1.0, Math.Round(hsvColor.H, 0), Math.Round(hsvColor.S, 1), Math.Round(hsvColor.V, 1)); // Attempt to use a previously cached display name lock (_displayNameCacheMutex) { if (_cachedDisplayNames.TryGetValue(roundedHsvColor, out var displayName)) { return displayName; } } // Build the KnownColor name cache if it doesn't already exist lock (_knownColorCacheMutex) { if (_cachedKnownColorNames.Count == 0) { for (int i = 1; i < _knownColors.Length; i++) // Skip 'None' so start at 1 { KnownColor knownColor = _knownColors[i]; // Some known colors have the same numerical value. For example: // - Aqua = 0xff00ffff // - Cyan = 0xff00ffff // // This is not possible to represent in a dictionary which requires // unique values. Therefore, only the first value is used. if (!_cachedKnownColorNames.ContainsKey(knownColor)) { _cachedKnownColorNames.Add(knownColor, GetDisplayName(knownColor)); } } } } // Find the closest known color by measuring 3D Euclidean distance (ignore alpha) // This is done in HSV color space to most closely match user-perception var closestKnownColor = KnownColor.None; var closestKnownColorDistance = double.PositiveInfinity; for (int i = 1; i < _knownColors.Length; i++) // Skip 'None' so start at 1 { KnownColor knownColor = _knownColors[i]; // Transparent is skipped since alpha is ignored making it equivalent to White if (knownColor != KnownColor.Transparent) { HsvColor knownHsvColor = KnownColors.ToColor(knownColor).ToHsv(); double distance = Math.Sqrt( Math.Pow((roundedHsvColor.H - knownHsvColor.H), 2.0) + Math.Pow((roundedHsvColor.S - knownHsvColor.S), 2.0) + Math.Pow((roundedHsvColor.V - knownHsvColor.V), 2.0)); if (distance < closestKnownColorDistance) { closestKnownColor = knownColor; closestKnownColorDistance = distance; } } } // Return the closest known color as the display name // Cache results for next time as well if (closestKnownColor != KnownColor.None) { string? displayName; lock (_knownColorCacheMutex) { if (!_cachedKnownColorNames.TryGetValue(closestKnownColor, out displayName)) { displayName = GetDisplayName(closestKnownColor); } } lock (_displayNameCacheMutex) { _cachedDisplayNames.Add(roundedHsvColor, displayName); } return displayName; } else { return string.Empty; } } /// <summary> /// Gets the human-readable display name for the given <see cref="KnownColor"/>. /// </summary> /// <remarks> /// This currently uses the <see cref="KnownColor"/>
ColorHelper
csharp
OrchardCMS__OrchardCore
src/OrchardCore.Modules/OrchardCore.Notifications/ViewModels/NotificationViewModel.cs
{ "start": 93, "end": 358 }
public class ____ : ShapeViewModel { public Notification Notification { get; set; } public NotificationViewModel() { } public NotificationViewModel(Notification notification) { Notification = notification; } }
NotificationViewModel
csharp
abpframework__abp
framework/src/Volo.Abp.AspNetCore.Mvc.UI.Widgets/Volo/Abp/AspNetCore/Mvc/UI/Widgets/WidgetAttribute.cs
{ "start": 161, "end": 1182 }
public class ____ : Attribute { public string[]? StyleFiles { get; set; } public Type[]? StyleTypes { get; set; } public string[]? ScriptFiles { get; set; } public Type[]? ScriptTypes { get; set; } public string? DisplayName { get; set; } public Type? DisplayNameResource { get; set; } public string[]? RequiredPolicies { get; set; } public bool RequiresAuthentication { get; set; } public string? RefreshUrl { get; set; } public bool AutoInitialize { get; set; } public static bool IsWidget(Type type) { return type.IsSubclassOf(typeof(ViewComponent)) && type.IsDefined(typeof(WidgetAttribute), true); } public static WidgetAttribute Get(Type viewComponentType) { return viewComponentType.GetCustomAttribute<WidgetAttribute>(true) ?? throw new AbpException($"Given type '{viewComponentType.AssemblyQualifiedName}' does not declare a {typeof(WidgetAttribute).AssemblyQualifiedName}"); } }
WidgetAttribute
csharp
microsoft__FASTER
cs/src/core/Index/FASTER/Implementation/TryCopyToReadCache.cs
{ "start": 257, "end": 1572 }
record ____ the disk to the read cache. /// </summary> /// <param name="pendingContext"></param> /// <param name="key"></param> /// <param name="input"></param> /// <param name="recordValue"></param> /// <param name="stackCtx">Contains the <see cref="HashEntryInfo"/> and <see cref="RecordSource{Key, Value}"/> structures for this operation, /// and allows passing back the newLogicalAddress for invalidation in the case of exceptions.</param> /// <param name="fasterSession"></param> /// <returns>True if copied to readcache, else false; readcache is "best effort", and we don't fail the read process, or slow it down by retrying. /// </returns> internal bool TryCopyToReadCache<Input, Output, Context, FasterSession>(FasterSession fasterSession, ref PendingContext<Input, Output, Context> pendingContext, ref Key key, ref Input input, ref Value recordValue, ref OperationStackContext<Key, Value> stackCtx) where FasterSession : IFasterSession<Key, Value, Input, Output, Context> { #region Create new copy in mutable region var (actualSize, allocatedSize) = hlog.GetRecordSize(ref key, ref recordValue); #region Allocate new
from
csharp
unoplatform__uno
src/Uno.UI.RemoteControl.Server.Processors/HotReload/MetadataUpdates/WatchHotReloadService.cs
{ "start": 685, "end": 5303 }
record ____ Update { public readonly Guid ModuleId; public readonly ImmutableArray<byte> ILDelta; public readonly ImmutableArray<byte> MetadataDelta; public readonly ImmutableArray<byte> PdbDelta; public readonly ImmutableArray<int> UpdatedTypes; public Update(Guid moduleId, ImmutableArray<byte> ilDelta, ImmutableArray<byte> metadataDelta, ImmutableArray<byte> pdbDelta, ImmutableArray<int> updatedTypes) { ModuleId = moduleId; ILDelta = ilDelta; MetadataDelta = metadataDelta; PdbDelta = pdbDelta; UpdatedTypes = updatedTypes; } } public WatchHotReloadService(HostWorkspaceServices services, string[] metadataUpdateCapabilities) { if (Assembly.Load("Microsoft.CodeAnalysis.Features") is { } featuresAssembly) { if (featuresAssembly.GetType("Microsoft.CodeAnalysis.ExternalAccess.Watch.Api.WatchHotReloadService", false) is { } watchHotReloadServiceType) { _targetInstance = Activator.CreateInstance( watchHotReloadServiceType, services, ImmutableArray<string>.Empty.AddRange(metadataUpdateCapabilities)); if (watchHotReloadServiceType.GetMethod(nameof(StartSessionAsync)) is { } startSessionAsyncMethod) { _startSessionAsync = (Func<Solution, CancellationToken, Task>)startSessionAsyncMethod .CreateDelegate(typeof(Func<Solution, CancellationToken, Task>), _targetInstance); } else { throw new InvalidOperationException($"Cannot find {nameof(StartSessionAsync)}"); } if (watchHotReloadServiceType.GetMethod(nameof(EmitSolutionUpdateAsync)) is { } emitSolutionUpdateAsyncMethod) { _emitSolutionUpdateAsync = async (s, ct) => { var r = emitSolutionUpdateAsyncMethod.Invoke(_targetInstance, new object[] { s, ct }); if (r is Task t) { await t; var resultPropertyInfo = r.GetType().GetProperty("Result") ?? throw new InvalidOperationException($"Unable to find Result property on [{r}]"); var value = resultPropertyInfo.GetValue(r, null); if (value is ITuple tuple) { return tuple; } } throw new InvalidOperationException(); }; } else { throw new InvalidOperationException($"Cannot find {nameof(EmitSolutionUpdateAsync)}"); } if (watchHotReloadServiceType.GetMethod(nameof(EndSession)) is { } endSessionMethod) { _endSession = (Action)endSessionMethod.CreateDelegate(typeof(Action), _targetInstance); } else { throw new InvalidOperationException($"Cannot find {nameof(EmitSolutionUpdateAsync)}"); } } } } internal Task StartSessionAsync(Solution currentSolution, CancellationToken cancellationToken) { if (_startSessionAsync is null) { throw new InvalidOperationException($"_startSessionAsync cannot be null"); } return _startSessionAsync(currentSolution, cancellationToken); } public async Task<(ImmutableArray<Update> updates, ImmutableArray<Diagnostic> diagnostics)> EmitSolutionUpdateAsync(Solution solution, CancellationToken cancellationToken) { if (_emitSolutionUpdateAsync is null) { throw new InvalidOperationException($"_emitSolutionUpdateAsync cannot be null"); } var ret = await _emitSolutionUpdateAsync(solution, cancellationToken); var updatesSource = (IEnumerable)ret[0]!; var diagnostics = (ImmutableArray<Diagnostic>)ret[1]!; var builder = ImmutableArray<Update>.Empty.ToBuilder(); foreach (var updateSource in updatesSource) { var updateType = updateSource.GetType(); var update = new Update( (Guid)GetField(updateType, nameof(Update.ModuleId)).GetValue(updateSource)! , (ImmutableArray<byte>)GetField(updateType, nameof(Update.ILDelta)).GetValue(updateSource)! , (ImmutableArray<byte>)GetField(updateType, nameof(Update.MetadataDelta)).GetValue(updateSource)! , (ImmutableArray<byte>)GetField(updateType, nameof(Update.PdbDelta)).GetValue(updateSource)! , (ImmutableArray<int>)GetField(updateType, nameof(Update.UpdatedTypes)).GetValue(updateSource)! ); builder.Add(update); } return (builder.ToImmutable(), diagnostics); FieldInfo GetField(Type type, string name) { if (type.GetField(name) is { } moduleIdField) { return moduleIdField; } else { throw new InvalidOperationException($"Failed to find {name}"); } } } public void EndSession() { if (_endSession is null) { throw new InvalidOperationException($"_endSession cannot be null"); } _endSession(); } } }
struct
csharp
ChilliCream__graphql-platform
src/HotChocolate/Core/test/Types.Analyzers.Tests/BindMemberAnalyzerTests.cs
{ "start": 4160, "end": 4751 }
public class ____ { public int Id { get; set; } public string Name { get; set; } } """], enableAnalyzers: true).MatchMarkdownAsync(); } [Fact] public async Task BindMember_WithNameof_InvalidMember_RaisesError() { await TestHelper.GetGeneratedSourceSnapshot( [""" using HotChocolate; using HotChocolate.Types; using System.Threading.Tasks; namespace TestNamespace; [ObjectType<Product>] public static
Brand
csharp
HangfireIO__Hangfire
src/Hangfire.Core/Common/MethodInfoExtensions.cs
{ "start": 1003, "end": 1281 }
interface ____ // https://stackoverflow.com/a/17854048/1398672 return methodInfo.Name.Contains('.') && methodInfo.IsFinal && methodInfo.IsPrivate ? methodInfo.Name.Split('.').Last() : methodInfo.Name; } } }
methods
csharp
unoplatform__uno
src/Uno.Foundation/Extensions/VectorExtensions.cs
{ "start": 317, "end": 1558 }
public static class ____ { /// <summary> /// Converts a <see cref="Vector2"/> to <see cref="Point"/> /// </summary> /// <param name="vector">The <see cref="Vector2"/> to convert</param> /// <returns>A <see cref="Point"/></returns> public static Point ToPoint(this Vector2 vector) => new Point(vector.X, vector.Y); /// <summary> /// Converts a <see cref="Vector2"/> to <see cref="Size"/> /// </summary> /// <param name="vector">The <see cref="Vector2"/> to convert</param> /// <returns>A <see cref="Size"/></returns> public static Size ToSize(this Vector2 vector) => new Size(vector.X, vector.Y); /// <summary> /// Converts a <see cref="Point"/> to <see cref="Vector2"/> /// </summary> /// <param name="point">The <see cref="Point"/> to Convert</param> /// <returns>A <see cref="Vector2"/></returns> public static Vector2 ToVector2(this Point point) => new Vector2((float)point.X, (float)point.Y); /// <summary> /// Converts a <see cref="Size"/> to <see cref="Vector2"/> /// </summary> /// <param name="point">The <see cref="Size"/> to Convert</param> /// <returns>A <see cref="Vector2"/></returns> public static Vector2 ToVector2(this Size size) => new Vector2((float)size.Width, (float)size.Height); }
VectorExtensions
csharp
dotnet__efcore
test/EFCore.InMemory.FunctionalTests/StoreGeneratedInMemoryTest.cs
{ "start": 56204, "end": 56450 }
protected class ____ { [DatabaseGenerated(DatabaseGeneratedOption.Identity)] public WrappedGuidStruct Id { get; set; } public WrappedGuidStructPrincipal? Principal { get; set; } }
WrappedGuidStructDependentShadow
csharp
unoplatform__uno
src/SourceGenerators/Uno.UI.SourceGenerators.Tests/XamlCodeGeneratorTests/Out/Given_Binding/TeAcAr/XamlCodeGenerator_MainPage_d6cd66944958ced0c513e0a04797b51d.cs
{ "start": 5826, "end": 6483 }
private interface ____ { void Initialize(); void Update(); void UpdateResources(); void StopTracking(); void NotifyXLoad(string name); } #pragma warning disable 0169 // Suppress unused field warning in case Bindings is not used. private IMainPage_Bindings Bindings; #pragma warning restore 0169 [global::System.Diagnostics.CodeAnalysis.UnconditionalSuppressMessage("Trimming", "IL2026", Justification = "Generated code")] [global::System.Diagnostics.CodeAnalysis.UnconditionalSuppressMessage("Trimming", "IL2111", Justification = "Generated code")] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
IMainPage_Bindings
csharp
CommunityToolkit__dotnet
tests/CommunityToolkit.Mvvm.SourceGenerators.UnitTests/Test_SourceGeneratorsDiagnostics.cs
{ "start": 42916, "end": 43668 }
public partial class ____ : ObservableObject { [ObservableProperty] public MyPropertyChangedEventArgs {|MVVMTK0024:property|}; } } """; await VerifyAnalyzerDiagnosticsAndSuccessfulGeneration<InvalidGeneratedPropertyObservablePropertyAttributeAnalyzer>(source, LanguageVersion.CSharp9); } [TestMethod] public void MissingObservableValidatorInheritanceForNotifyDataErrorInfoError() { string source = """ using System.ComponentModel.DataAnnotations; using CommunityToolkit.Mvvm.ComponentModel; namespace MyApp { [INotifyPropertyChanged]
MyViewModel
csharp
nunit__nunit
src/NUnitFramework/tests/TextOutputTests.cs
{ "start": 276, "end": 6932 }
public class ____ : ITestListener { private const string SOME_TEXT = "Should go to the result"; private const string ERROR_TEXT = "Written directly to console"; private static readonly string NL = Environment.NewLine; private static string CapturedOutput => TestExecutionContext.CurrentContext.CurrentResult.Output; [Test] public void ConsoleWrite_WritesToResult() { Console.Write(SOME_TEXT); Assert.That(TextOutputTests.CapturedOutput, Is.EqualTo(SOME_TEXT)); } [Test] public void ConsoleWriteLine_WritesToResult() { Console.WriteLine(SOME_TEXT); Assert.That(TextOutputTests.CapturedOutput, Is.EqualTo(SOME_TEXT + NL)); } [Test] public void ConsoleErrorWrite_WritesToListener() { var test = TestBuilder.MakeTestFromMethod(typeof(TextOutputFixture), nameof(TextOutputFixture.ConsoleErrorWrite)); var work = TestBuilder.CreateWorkItem(test, new TextOutputFixture()); work.Context.Listener = this; var result = TestBuilder.ExecuteWorkItem(work); Assert.Multiple(() => { Assert.That(result.ResultState, Is.EqualTo(ResultState.Success)); Assert.That(result.Output, Is.EqualTo(string.Empty)); }); Assert.That(_testOutput, Is.Not.Null, "No output received"); Assert.Multiple(() => { Assert.That(_testOutput.Text, Is.EqualTo(ERROR_TEXT)); Assert.That(_testOutput.Stream, Is.EqualTo("Error")); }); } [Test] public void ConsoleErrorWriteLine_WritesToListener() { var test = TestBuilder.MakeTestFromMethod(typeof(TextOutputFixture), nameof(TextOutputFixture.ConsoleErrorWriteLine)); var work = TestBuilder.CreateWorkItem(test, new TextOutputFixture()); work.Context.Listener = this; var result = TestBuilder.ExecuteWorkItem(work); Assert.Multiple(() => { Assert.That(result.ResultState, Is.EqualTo(ResultState.Success)); Assert.That(result.Output, Is.EqualTo(string.Empty)); }); Assert.That(_testOutput, Is.Not.Null, "No output received"); Assert.Multiple(() => { Assert.That(_testOutput.Text, Is.EqualTo(ERROR_TEXT + Environment.NewLine)); Assert.That(_testOutput.Stream, Is.EqualTo("Error")); }); } [Test] public void MultipleWrites() { // Test purely for display purposes TestContext.Progress.WriteLine("TestContext.Progress displays immediately"); TestContext.Error.WriteLine("TestContext.Error displays immediately as well"); Console.Error.WriteLine("Console.Error also displays immediately"); Console.WriteLine("This line is added to the result and displayed when test ends"); Console.WriteLine("As is this line"); } [Test] public void TestContextError_WritesToListener() { var test = TestBuilder.MakeTestFromMethod(typeof(TextOutputFixture), nameof(TextOutputFixture.TestContextErrorWriteLine)); var work = TestBuilder.CreateWorkItem(test, new TextOutputFixture()); work.Context.Listener = this; var result = TestBuilder.ExecuteWorkItem(work); Assert.Multiple(() => { Assert.That(result.ResultState, Is.EqualTo(ResultState.Success)); Assert.That(result.Output, Is.EqualTo(string.Empty)); }); Assert.That(_testOutput, Is.Not.Null, "No output received"); Assert.Multiple(() => { Assert.That(_testOutput.Text, Is.EqualTo(ERROR_TEXT + Environment.NewLine)); Assert.That(_testOutput.Stream, Is.EqualTo("Error")); }); } [Test] public void TestContextProgress_WritesToListener() { var test = TestBuilder.MakeTestFromMethod(typeof(TextOutputFixture), nameof(TextOutputFixture.TestContextProgressWriteLine)); var work = TestBuilder.CreateWorkItem(test, new TextOutputFixture()); work.Context.Listener = this; var result = TestBuilder.ExecuteWorkItem(work); Assert.Multiple(() => { Assert.That(result.ResultState, Is.EqualTo(ResultState.Success)); Assert.That(result.Output, Is.EqualTo(string.Empty)); }); Assert.That(_testOutput, Is.Not.Null, "No output received"); Assert.Multiple(() => { Assert.That(_testOutput.Text, Is.EqualTo(ERROR_TEXT + Environment.NewLine)); Assert.That(_testOutput.Stream, Is.EqualTo("Progress")); }); } [Test] public void TestContextOut_WritesToResult() { TestContext.Out.WriteLine(SOME_TEXT); Assert.That(TextOutputTests.CapturedOutput, Is.EqualTo(SOME_TEXT + NL)); } [Test] public void TestContextWrite_WritesToResult() { #pragma warning disable NUnit1033 // The Write methods on TestContext will be marked as Obsolete and eventually removed TestContext.Write(SOME_TEXT); #pragma warning restore NUnit1033 // The Write methods on TestContext will be marked as Obsolete and eventually removed Assert.That(TextOutputTests.CapturedOutput, Is.EqualTo(SOME_TEXT)); } [Test] public void TestContextWriteLine_WritesToResult() { #pragma warning disable NUnit1033 // The Write methods on TestContext will be marked as Obsolete and eventually removed TestContext.WriteLine(SOME_TEXT); #pragma warning restore NUnit1033 // The Write methods on TestContext will be marked as Obsolete and eventually removed Assert.That(Framework.Internal.TestExecutionContext.CurrentContext.CurrentResult.Output, Is.EqualTo(SOME_TEXT + NL)); } #region ITestListener Implementation void ITestListener.TestStarted(ITest test) { } void ITestListener.TestFinished(ITestResult result) { } private TestOutput? _testOutput; void ITestListener.TestOutput(TestOutput output) { _testOutput = output; } void ITestListener.SendMessage(TestMessage message) { } #endregion } }
TextOutputTests
csharp
reactiveui__ReactiveUI
src/ReactiveUI.Wpf/Rx/Concurrency/DispatcherScheduler.cs
{ "start": 743, "end": 8753 }
public class ____ : LocalScheduler, ISchedulerPeriodic { /// <summary> /// Gets the scheduler that schedules work on the current <see cref="System.Windows.Threading.Dispatcher"/>. /// </summary> [Obsolete(Constants_WindowsThreading.OBSOLETE_INSTANCE_PROPERTY)] public static DispatcherScheduler Instance => new(System.Windows.Threading.Dispatcher.CurrentDispatcher); /// <summary> /// Gets the scheduler that schedules work on the <see cref="System.Windows.Threading.Dispatcher"/> for the current thread. /// </summary> public static DispatcherScheduler Current { get { var dispatcher = System.Windows.Threading.Dispatcher.FromThread(Thread.CurrentThread); if (dispatcher == null) { throw new InvalidOperationException("There is no current dispatcher thread"); } return new DispatcherScheduler(dispatcher); } } /// <summary> /// Constructs a <see cref="DispatcherScheduler"/> that schedules units of work on the given <see cref="System.Windows.Threading.Dispatcher"/>. /// </summary> /// <param name="dispatcher"><see cref="DispatcherScheduler"/> to schedule work on.</param> /// <exception cref="ArgumentNullException"><paramref name="dispatcher"/> is <c>null</c>.</exception> public DispatcherScheduler(System.Windows.Threading.Dispatcher dispatcher) { Dispatcher = dispatcher ?? throw new ArgumentNullException(nameof(dispatcher)); Priority = System.Windows.Threading.DispatcherPriority.Normal; } /// <summary> /// Constructs a <see cref="DispatcherScheduler"/> that schedules units of work on the given <see cref="System.Windows.Threading.Dispatcher"/> at the given priority. /// </summary> /// <param name="dispatcher"><see cref="DispatcherScheduler"/> to schedule work on.</param> /// <param name="priority">Priority at which units of work are scheduled.</param> /// <exception cref="ArgumentNullException"><paramref name="dispatcher"/> is <c>null</c>.</exception> public DispatcherScheduler(System.Windows.Threading.Dispatcher dispatcher, System.Windows.Threading.DispatcherPriority priority) { Dispatcher = dispatcher ?? throw new ArgumentNullException(nameof(dispatcher)); Priority = priority; } /// <summary> /// Gets the <see cref="System.Windows.Threading.Dispatcher"/> associated with the <see cref="DispatcherScheduler"/>. /// </summary> public System.Windows.Threading.Dispatcher Dispatcher { get; } /// <summary> /// Gets the priority at which work items will be dispatched. /// </summary> public System.Windows.Threading.DispatcherPriority Priority { get; } /// <summary> /// Schedules an action to be executed on the dispatcher. /// </summary> /// <typeparam name="TState">The type of the state passed to the scheduled action.</typeparam> /// <param name="state">State passed to the action to be executed.</param> /// <param name="action">Action to be executed.</param> /// <returns>The disposable object used to cancel the scheduled action (best effort).</returns> /// <exception cref="ArgumentNullException"><paramref name="action"/> is <c>null</c>.</exception> public override IDisposable Schedule<TState>(TState state, Func<IScheduler, TState, IDisposable> action) { if (action == null) { throw new ArgumentNullException(nameof(action)); } var d = new SingleAssignmentDisposable(); Dispatcher.BeginInvoke( new Action(() => { if (!d.IsDisposed) { d.Disposable = action(this, state); } }), Priority ); return d; } /// <summary> /// Schedules an action to be executed after <paramref name="dueTime"/> on the dispatcher, using a <see cref="System.Windows.Threading.DispatcherTimer"/> object. /// </summary> /// <typeparam name="TState">The type of the state passed to the scheduled action.</typeparam> /// <param name="state">State passed to the action to be executed.</param> /// <param name="action">Action to be executed.</param> /// <param name="dueTime">Relative time after which to execute the action.</param> /// <returns>The disposable object used to cancel the scheduled action (best effort).</returns> /// <exception cref="ArgumentNullException"><paramref name="action"/> is <c>null</c>.</exception> public override IDisposable Schedule<TState>(TState state, TimeSpan dueTime, Func<IScheduler, TState, IDisposable> action) { if (action == null) { throw new ArgumentNullException(nameof(action)); } var dt = Scheduler.Normalize(dueTime); if (dt.Ticks == 0) { return Schedule(state, action); } return ScheduleSlow(state, dt, action); } private IDisposable ScheduleSlow<TState>(TState state, TimeSpan dueTime, Func<IScheduler, TState, IDisposable> action) { var d = new MultipleAssignmentDisposable(); var timer = new System.Windows.Threading.DispatcherTimer(Priority, Dispatcher); timer.Tick += (s, e) => { var t = Interlocked.Exchange(ref timer, null); if (t != null) { try { d.Disposable = action(this, state); } finally { t.Stop(); action = static (s, t) => Disposable.Empty; } } }; timer.Interval = dueTime; timer.Start(); d.Disposable = Disposable.Create(() => { var t = Interlocked.Exchange(ref timer, null); if (t != null) { t.Stop(); action = static (s, t) => Disposable.Empty; } }); return d; } /// <summary> /// Schedules a periodic piece of work on the dispatcher, using a <see cref="System.Windows.Threading.DispatcherTimer"/> object. /// </summary> /// <typeparam name="TState">The type of the state passed to the scheduled action.</typeparam> /// <param name="state">Initial state passed to the action upon the first iteration.</param> /// <param name="period">Period for running the work periodically.</param> /// <param name="action">Action to be executed, potentially updating the state.</param> /// <returns>The disposable object used to cancel the scheduled recurring action (best effort).</returns> /// <exception cref="ArgumentNullException"><paramref name="action"/> is <c>null</c>.</exception> /// <exception cref="ArgumentOutOfRangeException"><paramref name="period"/> is less than <see cref="TimeSpan.Zero"/>.</exception> public IDisposable SchedulePeriodic<TState>(TState state, TimeSpan period, Func<TState, TState> action) { if (period < TimeSpan.Zero) { throw new ArgumentOutOfRangeException(nameof(period)); } if (action == null) { throw new ArgumentNullException(nameof(action)); } var timer = new System.Windows.Threading.DispatcherTimer(Priority, Dispatcher); var state1 = state; timer.Tick += (s, e) => { state1 = action(state1); }; timer.Interval = period; timer.Start(); return Disposable.Create(() => { var t = Interlocked.Exchange(ref timer, null); if (t != null) { t.Stop(); action = static _ => _; } }); } }
DispatcherScheduler
csharp
mongodb__mongo-csharp-driver
tests/MongoDB.Driver.Tests/Jira/CSharp2622Tests.cs
{ "start": 770, "end": 2076 }
public class ____ { // public methods [Fact] public void InsertOne_to_oftype_collection_should_generate_id() { var collectionNamespace = CoreTestConfiguration.GetCollectionNamespaceForTestClass(typeof(CSharp2622Tests)); var databaseName = collectionNamespace.DatabaseNamespace.DatabaseName; var collectionName = collectionNamespace.CollectionName; var client = DriverTestConfiguration.Client; var database = client.GetDatabase(databaseName); var collection = database.GetCollection<C>(collectionName); var ofTypeCollection = collection.OfType<D>(); database.DropCollection(collectionName); var document = new D { X = 1 }; ofTypeCollection.InsertOne(document); var insertedDocuments = collection.FindSync("{}").ToList(); insertedDocuments.Count.Should().Be(1); insertedDocuments[0].Should().BeOfType<D>(); var insertedDocument = (D)insertedDocuments[0]; insertedDocument.Id.Should().NotBe(ObjectId.Empty); insertedDocument.X.Should().Be(1); } // nested types [BsonDiscriminator(RootClass = true)] [BsonKnownTypes(typeof(D))]
CSharp2622Tests
csharp
Cysharp__MemoryPack
src/MemoryPack.Generator/CoreEnums.cs
{ "start": 104, "end": 263 }
public enum ____ { Object, VersionTolerant, CircularReference, Collection, NoGenerate, // only used in Generator Union }
GenerateType
csharp
dotnet__efcore
src/EFCore.Relational/Metadata/Builders/OwnedNavigationTableBuilder.cs
{ "start": 501, "end": 8517 }
public class ____ : IInfrastructure<OwnedNavigationBuilder> { /// <summary> /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to /// the same compatibility standards as public APIs. It may be changed or removed without notice in /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// </summary> [EntityFrameworkInternal] public OwnedNavigationTableBuilder(in StoreObjectIdentifier? storeObject, OwnedNavigationBuilder ownedNavigationBuilder) { StoreObject = storeObject; OwnedNavigationBuilder = ownedNavigationBuilder; } /// <summary> /// The specified table name. /// </summary> public virtual string? Name => StoreObject?.Name; /// <summary> /// The specified table schema. /// </summary> public virtual string? Schema => StoreObject?.Schema; /// <summary> /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to /// the same compatibility standards as public APIs. It may be changed or removed without notice in /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// </summary> [EntityFrameworkInternal] protected virtual StoreObjectIdentifier? StoreObject { get; } /// <summary> /// The entity type being configured. /// </summary> public virtual IMutableEntityType Metadata => OwnedNavigationBuilder.OwnedEntityType; private OwnedNavigationBuilder OwnedNavigationBuilder { get; } /// <summary> /// Configures the table to be ignored by migrations. /// </summary> /// <remarks> /// See <see href="https://aka.ms/efcore-docs-migrations">Database migrations</see> for more information. /// </remarks> /// <param name="excluded">A value indicating whether the table should be managed by migrations.</param> /// <returns>The same builder instance so that multiple calls can be chained.</returns> public virtual OwnedNavigationTableBuilder ExcludeFromMigrations(bool excluded = true) { Metadata.SetIsTableExcludedFromMigrations(excluded); return this; } /// <summary> /// Configures a database trigger on the table. /// </summary> /// <param name="modelName">The name of the trigger.</param> /// <returns>A builder that can be used to configure the database trigger.</returns> /// <remarks> /// See <see href="https://aka.ms/efcore-docs-triggers">Database triggers</see> for more information and examples. /// </remarks> public virtual TableTriggerBuilder HasTrigger(string modelName) { var trigger = EntityTypeBuilder.HasTrigger(Metadata, modelName).Metadata; if (Name != null) { trigger.SetTableName(Name); trigger.SetTableSchema(Schema); } return new TableTriggerBuilder(trigger); } /// <summary> /// Configures a database check constraint when targeting a relational database. /// </summary> /// <remarks> /// See <see href="https://aka.ms/efcore-docs-check-constraints">Database check constraints</see> for more information and examples. /// </remarks> /// <param name="name">The name of the check constraint.</param> /// <param name="sql">The logical constraint sql used in the check constraint.</param> /// <returns>A builder to configure the check constraint.</returns> public virtual CheckConstraintBuilder HasCheckConstraint( string name, string? sql) { Check.NotEmpty(name); Check.NullButNotEmpty(sql); var checkConstraint = InternalCheckConstraintBuilder.HasCheckConstraint( (IConventionEntityType)Metadata, name, sql, ConfigurationSource.Explicit)!; return new CheckConstraintBuilder((IMutableCheckConstraint)checkConstraint); } /// <summary> /// Configures a comment to be applied to the table /// </summary> /// <remarks> /// See <see href="https://aka.ms/efcore-docs-modeling">Modeling entity types and relationships</see> for more information and examples. /// </remarks> /// <param name="comment">The comment for the table.</param> /// <returns>A builder to further configure the table.</returns> public virtual OwnedNavigationTableBuilder HasComment(string? comment) { Metadata.SetComment(comment); return this; } /// <summary> /// Maps the property to a column on the current table and returns an object that can be used /// to provide table-specific configuration if the property is mapped to more than one table. /// </summary> /// <param name="propertyName">The name of the property to be configured.</param> /// <returns>An object that can be used to configure the property.</returns> public virtual ColumnBuilder Property(string propertyName) => new(GetStoreObjectIdentifier(), OwnedNavigationBuilder.Property(propertyName)); /// <summary> /// Maps the property to a column on the current table and returns an object that can be used /// to provide table-specific configuration if the property is mapped to more than one table. /// </summary> /// <typeparam name="TProperty">The type of the property to be configured.</typeparam> /// <param name="propertyName">The name of the property to be configured.</param> /// <returns>An object that can be used to configure the property.</returns> public virtual ColumnBuilder<TProperty> Property<TProperty>(string propertyName) => new(GetStoreObjectIdentifier(), OwnedNavigationBuilder.Property<TProperty>(propertyName)); /// <summary> /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to /// the same compatibility standards as public APIs. It may be changed or removed without notice in /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// </summary> [EntityFrameworkInternal] protected virtual StoreObjectIdentifier GetStoreObjectIdentifier() => StoreObject ?? throw new InvalidOperationException(RelationalStrings.MappingFragmentMissingName); OwnedNavigationBuilder IInfrastructure<OwnedNavigationBuilder>.Instance => OwnedNavigationBuilder; #region Hidden System.Object members /// <summary> /// Returns a string that represents the current object. /// </summary> /// <returns>A string that represents the current object.</returns> [EditorBrowsable(EditorBrowsableState.Never)] public override string? ToString() => base.ToString(); /// <summary> /// Determines whether the specified object is equal to the current object. /// </summary> /// <param name="obj">The object to compare with the current object.</param> /// <returns><see langword="true" /> if the specified object is equal to the current object; otherwise, <see langword="false" />.</returns> [EditorBrowsable(EditorBrowsableState.Never)] public override bool Equals(object? obj) => base.Equals(obj); /// <summary> /// Serves as the default hash function. /// </summary> /// <returns>A hash code for the current object.</returns> [EditorBrowsable(EditorBrowsableState.Never)] public override int GetHashCode() => base.GetHashCode(); #endregion }
OwnedNavigationTableBuilder
csharp
dotnet__extensions
bench/Libraries/Microsoft.Extensions.Telemetry.PerformanceTests/ExtendedLoggerBench.cs
{ "start": 427, "end": 1805 }
public class ____ { private const string ConnectionId = "0x345334534678"; private const string Type = "some string"; private const string StreamId = "some string some string"; private const string Length = "some string some string some string"; private const string Flags = "some string some string some string some string"; private const string Other = "some string some string some string some string some string"; private const long Start = 42; private const long End = 123_456_789; private const int Options = 0x1234; private static readonly Guid _guid = new(new byte[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 }); private static readonly Action<ILogger, string, string, string, string, string, string, Exception?> _loggerMessage_refTypes = LoggerMessage.Define<string, string, string, string, string, string>( LogLevel.Error, eventId: 380, formatString: @"Connection id '{connectionId}' received {type} frame for stream ID {streamId} with length {length} and flags {flags} and {other}"); private static readonly Action<ILogger, long, long, int, Guid, Exception?> _loggerMessage_valueTypes = LoggerMessage.Define<long, long, int, Guid>( LogLevel.Error, eventId: 381, formatString: @"Range [{start}..{end}], options {options}, guid {guid}");
ExtendedLoggerBench
csharp
microsoft__PowerToys
src/modules/MouseWithoutBorders/MouseWithoutBorders.UnitTests/Core/LoggerTests.cs
{ "start": 755, "end": 6875 }
class ____ "Common" in "Common.Log.cs" // PrivateDump throws an ArgumentNullException if this is null Common.BinaryName = "MyBinary.dll"; // magic number from Settings.cs var dumpObjectsLevel = 6; // copied from DumpObjects in Common.Log.cs var sb = new StringBuilder(1000000); var result = Common.PrivateDump(sb, new Common(), "[Other Logs]\r\n===============\r\n", 0, dumpObjectsLevel, false); var output = sb.ToString(); } */ [TestMethod] [Ignore( "This test relies on internal details of the dotnet platform and is sensitive to " + "the specific version of dotnet being used. As a result it's likely to fail if the " + "\"expected\" result was generated with a different version to the version used to " + "run the test, so we're going to ignore it in the CI build process.")] public void PrivateDumpShouldGenerateExpectedOutput() { static string NormalizeLog(string log) { var lines = log.Split("\r\n"); // some parts of the PrivateDump output are impossible to reproduce - // e.g. random numbers, system timestamps, thread ids, etc., so we'll mask them var maskPrefixes = new string[] { "----_s0 = ", "----_s1 = ", "----_s2 = ", "----_s3 = ", "<LastResumeSuspendTime>k__BackingField = ", "--_dateData = ", "lastJump = ", "lastStartServiceTime = ", "InitialIV = ", "--_budget = ", }; for (var i = 0; i < lines.Length; i++) { foreach (var maskPrefix in maskPrefixes) { if (lines[i].StartsWith(maskPrefix, StringComparison.InvariantCulture)) { // replace the trailing text with "?" characters lines[i] = string.Concat( lines[i].AsSpan(0, maskPrefix.Length), new string('?', 12)); } } } // hide some of the internals of concurrent dictionary lock tables // as the size can vary across machines var removeLines = new string[] { "------[8] = 0", "------[9] = 0", "------[10] = 0", "------[11] = 0", "------[12] = 0", "------[13] = 0", "------[14] = 0", "------[15] = 0", "------[16] = 0", "------[17] = 0", "------[18] = 0", "------[19] = 0", }; lines = lines.Where(line => !removeLines.Contains(line)).ToArray(); return string.Join("\r\n", lines); } // PrivateDump throws an ArgumentNullException if this is null Common.BinaryName = "MyBinary.dll"; // default magic number from Settings.cs var settingsDumpObjectsLevel = 6; // get the expected test result from an embedded resource var assembly = Assembly.GetExecutingAssembly(); var resourceName = $"{typeof(LoggerTests).Namespace}.Logger.PrivateDump.expected.txt"; using var stream = assembly.GetManifestResourceStream(resourceName) ?? throw new InvalidOperationException(); using var streamReader = new StreamReader(stream); var expected = streamReader.ReadToEnd(); // copied from DumpObjects in Logger.cs var sb = new StringBuilder(1000000); Logger.DumpProgramLogs(sb, settingsDumpObjectsLevel); Logger.DumpOtherLogs(sb, settingsDumpObjectsLevel); Logger.DumpStaticTypes(sb, settingsDumpObjectsLevel); var actual = sb.ToString(); expected = NormalizeLog(expected); actual = NormalizeLog(actual); // Azure DevOps truncates debug output which makes it hard to see where // the expected and actual differ, so we need to write a custom error message // so we can just focus on the differences between expected and actual var expectedLines = expected.Split("\r\n"); var actualLines = actual.Split("\r\n"); for (var i = 0; i < Math.Min(expectedLines.Length, actualLines.Length); i++) { if (actualLines[i] != expectedLines[i]) { var message = new StringBuilder(); message.AppendLine(CultureInfo.InvariantCulture, $"{nameof(actual)} and {nameof(expected)} differ at line {i}:"); message.AppendLine(); message.AppendLine($"{nameof(actual)}:"); for (var j = i; j < Math.Min(i + 5, actualLines.Length); j++) { message.AppendLine(CultureInfo.InvariantCulture, $"[{j}]: {actualLines[j]}:"); } message.AppendLine(); message.AppendLine($"{nameof(expected)}:"); for (var j = i; j < Math.Min(i + 5, expectedLines.Length); j++) { message.AppendLine(CultureInfo.InvariantCulture, $"[{j}]: {expectedLines[j]}:"); } Assert.Fail(message.ToString()); } } // finally, throw an exception if the two don't match // just in case the above doesn't spot a difference // (e.g. different number of lines in the output) Assert.AreEqual(expected, actual); } } }
was
csharp
ChilliCream__graphql-platform
src/HotChocolate/Core/test/Types.Tests/ForbiddenRuntimeTypeTests.cs
{ "start": 104, "end": 931 }
public class ____ { [Fact] public async Task Executable_NotAllowed() { async Task SchemaError() => await new ServiceCollection() .AddGraphQL() .AddQueryType<Query1>() .BuildSchemaAsync(); var exception = await Assert.ThrowsAsync<SchemaException>(SchemaError); exception.Errors[0].Message.MatchSnapshot(); } [Fact] public async Task ExecutableList_NotAllowed() { async Task SchemaError() => await new ServiceCollection() .AddGraphQL() .AddQueryType<Query2>() .BuildSchemaAsync(); var exception = await Assert.ThrowsAsync<SchemaException>(SchemaError); exception.Errors[0].Message.MatchSnapshot(); }
ForbiddenRuntimeTypeTests
csharp
dotnet__aspnetcore
src/Framework/AspNetCoreAnalyzers/src/CodeFixes/PublicPartialProgramClassFixer.cs
{ "start": 557, "end": 1107 }
public class ____ : CodeFixProvider { public override ImmutableArray<string> FixableDiagnosticIds { get; } = [DiagnosticDescriptors.PublicPartialProgramClassNotRequired.Id]; public sealed override FixAllProvider GetFixAllProvider() => WellKnownFixAllProviders.BatchFixer; public sealed override Task RegisterCodeFixesAsync(CodeFixContext context) { foreach (var diagnostic in context.Diagnostics) { context.RegisterCodeFix( CodeAction.Create("Remove unnecessary
PublicPartialProgramClassFixer
csharp
AutoFixture__AutoFixture
Src/TestTypeFoundation/EmptyEnum.cs
{ "start": 36, "end": 116 }
public enum ____ { // this must not contain any values } }
EmptyEnum
csharp
serilog__serilog-sinks-console
test/Serilog.Sinks.Console.Tests/Rendering/ThemedMessageTemplateRendererTests.cs
{ "start": 349, "end": 625 }
class ____ { // ReSharper disable UnusedMember.Local public string Back => "straight"; public int[] Legs => new[] { 1, 2, 3, 4 }; // ReSharper restore UnusedMember.Local public override string ToString() => "a chair"; }
Chair
csharp
ShareX__ShareX
ShareX.HelpersLib/Native/NativeMethods.cs
{ "start": 1358, "end": 23974 }
partial class ____ { #region user32.dll [DllImport("user32.dll")] public static extern bool AnimateWindow(IntPtr hwnd, int time, AnimateWindowFlags flags); [DllImport("user32.dll")] public static extern bool BringWindowToTop(IntPtr hWnd); [DllImport("user32.dll")] public static extern IntPtr CopyIcon(IntPtr hIcon); [DllImport("user32.dll")] public static extern IntPtr DefWindowProc(IntPtr hWnd, uint uMsg, UIntPtr wParam, IntPtr lParam); [DllImport("user32.dll")] [return: MarshalAs(UnmanagedType.Bool)] public static extern bool DestroyIcon(IntPtr hIcon); [DllImport("user32.dll")] [return: MarshalAs(UnmanagedType.Bool)] public static extern bool EnumWindows(EnumWindowsProc lpEnumFunc, IntPtr lParam); [DllImport("user32.dll")] [return: MarshalAs(UnmanagedType.Bool)] public static extern bool EnumChildWindows(IntPtr hwndParent, EnumWindowsProc lpEnumFunc, IntPtr lParam); [DllImport("user32.dll")] [return: MarshalAs(UnmanagedType.Bool)] public static extern bool EnumThreadWindows(uint dwThreadId, EnumWindowsProc lpfn, IntPtr lParam); [DllImport("user32.dll", CharSet = CharSet.Auto)] public static extern int GetClassName(IntPtr hWnd, StringBuilder lpClassName, int nMaxCount); [DllImport("user32.dll")] public static extern bool GetLayeredWindowAttributes(IntPtr hwnd, out uint crKey, out byte bAlpha, out uint dwFlags); [DllImport("user32.dll")] public static extern bool SetLayeredWindowAttributes(IntPtr hwnd, uint crKey, byte bAlpha, uint dwFlags); [DllImport("user32.dll")] public static extern bool ClientToScreen(IntPtr hWnd, ref Point lpPoint); [DllImport("user32.dll")] public static extern bool DrawIcon(IntPtr hDC, int X, int Y, IntPtr hIcon); [DllImport("user32.dll")] public static extern bool DrawIconEx(IntPtr hdc, int xLeft, int yTop, IntPtr hIcon, int cxWidth, int cyHeight, int istepIfAniCur, IntPtr hbrFlickerFreeDraw, int diFlags); [DllImport("user32.dll")] public static extern IntPtr FindWindow(string lpClassName, string lpWindowName); [DllImport("user32.dll")] public static extern IntPtr FindWindowEx(IntPtr hwndParent, IntPtr hwndChildAfter, string lpszClass, string lpszWindow); [DllImport("user32.dll")] public static extern IntPtr FindWindowEx(IntPtr parentHwnd, IntPtr childAfterHwnd, IntPtr className, string windowText); [DllImport("user32.dll")] [return: MarshalAs(UnmanagedType.Bool)] public static extern bool FlashWindowEx(ref FLASHWINFO pwfi); [DllImport("user32.dll")] public static extern IntPtr GetActiveWindow(); [DllImport("user32.dll")] public static extern uint GetClassLong(IntPtr hWnd, int nIndex); [DllImport("user32.dll")] public static extern IntPtr GetClassLongPtr(IntPtr hWnd, int nIndex); [DllImport("user32.dll")] public static extern bool GetClientRect(IntPtr hWnd, out RECT lpRect); [DllImport("user32.dll")] public static extern bool GetCursorInfo(out CursorInfo pci); [DllImport("user32.dll")] [return: MarshalAs(UnmanagedType.Bool)] public static extern bool GetCursorPos(out POINT lpPoint); [DllImport("user32.dll")] public static extern IntPtr GetDC(IntPtr hWnd); [DllImport("user32.dll")] public static extern IntPtr GetDesktopWindow(); [DllImport("user32.dll")] public static extern IntPtr GetForegroundWindow(); [DllImport("user32.dll")] public static extern bool GetIconInfo(IntPtr hIcon, out IconInfo piconinfo); [DllImport("user32.dll")] public static extern IntPtr CreateIconIndirect([In] ref IconInfo piconinfo); [DllImport("user32.dll", CharSet = CharSet.Auto, ExactSpelling = true, CallingConvention = CallingConvention.Winapi)] public static extern short GetKeyState(int keyCode); [DllImport("user32.dll", CharSet = CharSet.Auto, ExactSpelling = true)] public static extern IntPtr GetParent(IntPtr hWnd); [DllImport("user32.dll")] [return: MarshalAs(UnmanagedType.Bool)] public static extern bool GetWindowPlacement(IntPtr hWnd, ref WINDOWPLACEMENT lpwndpl); /// <summary> /// The GetNextWindow function retrieves a handle to the next or previous window in the Z-Order. /// The next window is below the specified window; the previous window is above. /// If the specified window is a topmost window, the function retrieves a handle to the next (or previous) topmost window. /// If the specified window is a top-level window, the function retrieves a handle to the next (or previous) top-level window. /// If the specified window is a child window, the function searches for a handle to the next (or previous) child window. /// </summary> [DllImport("user32.dll")] public static extern IntPtr GetWindow(IntPtr hWnd, GetWindowConstants wCmd); [DllImport("user32.dll")] [return: MarshalAs(UnmanagedType.Bool)] public static extern bool GetScrollInfo(IntPtr hwnd, int fnBar, ref SCROLLINFO lpsi); [DllImport("user32.dll")] public static extern int GetSystemMetrics(int smIndex); [DllImport("user32.dll")] public static extern int GetSystemMetrics(SystemMetric smIndex); [DllImport("user32.dll")] public static extern IntPtr GetWindowDC(IntPtr hWnd); [DllImport("user32.dll", CharSet = CharSet.Auto, EntryPoint = "GetWindowLong")] public static extern IntPtr GetWindowLong32(IntPtr hWnd, int nIndex); [DllImport("user32.dll", CharSet = CharSet.Auto, EntryPoint = "GetWindowLongPtr")] public static extern IntPtr GetWindowLongPtr64(IntPtr hWnd, int nIndex); [DllImport("user32.dll", CharSet = CharSet.Auto, EntryPoint = "SetWindowLong")] public static extern IntPtr SetWindowLongPtr32(IntPtr hWnd, int nIndex, IntPtr dwNewLong); [DllImport("user32.dll", CharSet = CharSet.Auto, EntryPoint = "SetWindowLongPtr")] public static extern IntPtr SetWindowLongPtr64(IntPtr hWnd, int nIndex, IntPtr dwNewLong); [DllImport("user32.dll")] [return: MarshalAs(UnmanagedType.Bool)] public static extern bool GetWindowRect(IntPtr hWnd, out RECT lpRect); [DllImport("user32.dll")] public static extern int GetWindowRgn(IntPtr hWnd, IntPtr hRgn); [DllImport("user32.dll", CharSet = CharSet.Auto)] public static extern int GetWindowText(IntPtr hWnd, [Out] StringBuilder lpString, int nMaxCount); [DllImport("user32.dll", CharSet = CharSet.Auto)] public static extern int GetWindowTextLength(IntPtr hWnd); [DllImport("user32.dll")] public static extern uint GetWindowThreadProcessId(IntPtr hWnd, out uint lpdwProcessId); /// <summary>Determines the visibility state of the specified window.</summary> [DllImport("user32.dll")] [return: MarshalAs(UnmanagedType.Bool)] public static extern bool IsWindowVisible(IntPtr hWnd); /// <summary>Determines whether the specified window is minimized (iconic).</summary> [DllImport("user32.dll")] [return: MarshalAs(UnmanagedType.Bool)] public static extern bool IsIconic(IntPtr hWnd); /// <summary>Determines whether a window is maximized.</summary> [DllImport("user32.dll")] [return: MarshalAs(UnmanagedType.Bool)] public static extern bool IsZoomed(IntPtr hWnd); [DllImport("user32.dll")] public static extern IntPtr LoadCursor(IntPtr hInstance, int iconId); [DllImport("user32.dll")] [return: MarshalAs(UnmanagedType.Bool)] public static extern bool PrintWindow(IntPtr hwnd, IntPtr hDC, uint nFlags); [DllImport("user32.dll")] public static extern bool ReleaseCapture(); [DllImport("user32.dll")] public static extern bool ReleaseCapture(IntPtr hwnd); [DllImport("user32.dll")] public static extern int ReleaseDC(IntPtr hWnd, IntPtr hDC); [DllImport("user32.dll")] public static extern uint SendInput(uint nInputs, ref INPUT pInputs, int cbSize); [DllImport("user32.dll")] public static extern uint SendInput(uint nInputs, [MarshalAs(UnmanagedType.LPArray), In] INPUT[] pInputs, int cbSize); [DllImport("user32.dll", CharSet = CharSet.Auto)] public static extern IntPtr SendMessage(IntPtr hWnd, uint Msg, IntPtr wParam, IntPtr lParam); [DllImport("user32.dll", CharSet = CharSet.Auto)] public static extern IntPtr SendMessage(IntPtr hWnd, int Msg, int wParam, int lParam); [DllImport("user32.dll")] public static extern IntPtr SendMessage(IntPtr hWnd, int Msg, int wParam, [MarshalAs(UnmanagedType.LPWStr)] string lParam); [DllImport("user32.dll", CharSet = CharSet.Auto)] public static extern IntPtr SendMessageTimeout(IntPtr hWnd, uint Msg, IntPtr wParam, IntPtr lParam, SendMessageTimeoutFlags fuFlags, uint uTimeout, out UIntPtr lpdwResult); [DllImport("user32.dll", CharSet = CharSet.Auto)] public static extern IntPtr SendMessageTimeout(IntPtr hWnd, int Msg, int wParam, int lParam, SendMessageTimeoutFlags fuFlags, uint uTimeout, out IntPtr lpdwResult); [DllImport("user32.dll")] public static extern IntPtr SetActiveWindow(IntPtr hWnd); [DllImport("user32.dll")] public static extern bool SetCursorPos(int x, int y); [DllImport("user32.dll")] [return: MarshalAs(UnmanagedType.Bool)] public static extern bool SetForegroundWindow(IntPtr hWnd); [DllImport("user32.dll")] public static extern bool SetWindowPos(IntPtr hWnd, IntPtr hWndInsertAfter, int X, int Y, int cx, int cy, SetWindowPosFlags uFlags); [DllImport("user32.dll")] [return: MarshalAs(UnmanagedType.Bool)] public static extern bool SetWindowPlacement(IntPtr hWnd, [In] ref WINDOWPLACEMENT lpwndpl); [DllImport("user32.dll")] public static extern bool ShowWindow(IntPtr hWnd, int nCmdShow); [DllImport("user32.dll", ExactSpelling = true)] public static extern bool UpdateLayeredWindow(IntPtr hwnd, IntPtr hdcDst, ref POINT pptDst, ref SIZE psize, IntPtr hdcSrc, ref POINT pptSrc, uint crKey, [In] ref BLENDFUNCTION pblend, uint dwFlags); /// <summary> The RegisterHotKey function defines a system-wide hot key </summary> /// <param name="hWnd">Handle to the window that will receive WM_HOTKEY messages generated by the hot key.</param> /// <param name="id">Specifies the identifier of the hot key.</param> /// <param name="fsModifiers">Specifies keys that must be pressed in combination with the key /// specified by the 'vk' parameter in order to generate the WM_HOTKEY message.</param> /// <param name="vk">Specifies the virtual-key code of the hot key</param> /// <returns><c>true</c> if the function succeeds, otherwise <c>false</c></returns> /// <seealso cref="http://msdn.microsoft.com/en-us/library/ms646309(VS.85).aspx"/> [DllImport("user32.dll")] [return: MarshalAs(UnmanagedType.Bool)] public static extern bool RegisterHotKey(IntPtr hWnd, int id, uint fsModifiers, uint vk); [DllImport("user32.dll")] [return: MarshalAs(UnmanagedType.Bool)] public static extern bool UnregisterHotKey(IntPtr hWnd, int id); [DllImport("user32.dll")] [return: MarshalAs(UnmanagedType.Bool)] public static extern bool GetWindowInfo(IntPtr hwnd, ref WINDOWINFO pwi); [DllImport("user32.dll")] public static extern IntPtr SetWindowsHookEx(int idHook, HookProc lpfn, IntPtr hMod, uint dwThreadId); [DllImport("user32.dll")] [return: MarshalAs(UnmanagedType.Bool)] public static extern bool UnhookWindowsHookEx(IntPtr hhk); [DllImport("user32.dll")] public static extern IntPtr CallNextHookEx(IntPtr hhk, int nCode, IntPtr wParam, IntPtr lParam); #endregion user32.dll #region kernel32.dll [DllImport("kernel32.dll", CharSet = CharSet.Auto)] public static extern bool CreateProcess(string lpApplicationName, string lpCommandLine, ref SECURITY_ATTRIBUTES lpProcessAttributes, ref SECURITY_ATTRIBUTES lpThreadAttributes, bool bInheritHandles, uint dwCreationFlags, IntPtr lpEnvironment, string lpCurrentDirectory, [In] ref STARTUPINFO lpStartupInfo, out PROCESS_INFORMATION lpProcessInformation); [DllImport("kernel32.dll")] public static extern int ResumeThread(IntPtr hThread); [DllImport("kernel32.dll")] public static extern int SuspendThread(IntPtr hThread); [DllImport("kernel32.dll")] public static extern IntPtr OpenThread(ThreadAccess dwDesiredAccess, bool bInheritHandle, uint dwThreadId); [DllImport("kernel32.dll", CharSet = CharSet.Auto)] public static extern bool SetProcessWorkingSetSize(IntPtr handle, IntPtr min, IntPtr max); [DllImport("kernel32.dll", CharSet = CharSet.Auto)] public static extern ushort GlobalAddAtom(string lpString); [DllImport("kernel32.dll", CharSet = CharSet.Auto)] public static extern ushort GlobalDeleteAtom(ushort nAtom); [DllImport("kernel32.dll")] public static extern IntPtr GetModuleHandle(string lpModuleName); [DllImport("kernel32.dll", CallingConvention = CallingConvention.Winapi)] [return: MarshalAs(UnmanagedType.Bool)] public static extern bool IsWow64Process([In] IntPtr hProcess, [Out] out bool lpSystemInfo); [DllImport("kernel32.dll", PreserveSig = false)] public static extern void RegisterApplicationRestart(string pwzCommandline, RegisterApplicationRestartFlags dwFlags); #endregion kernel32.dll #region gdi32.dll [DllImport("gdi32.dll")] public static extern bool BitBlt(IntPtr hdc, int nXDest, int nYDest, int nWidth, int nHeight, IntPtr hdcSrc, int nXSrc, int nYSrc, CopyPixelOperation dwRop); [DllImport("gdi32.dll")] public static extern IntPtr CreateCompatibleBitmap(IntPtr hdc, int nWidth, int nHeight); [DllImport("gdi32.dll")] public static extern IntPtr CreateCompatibleDC(IntPtr hdc); [DllImport("gdi32.dll")] public static extern IntPtr CreateDC(string lpszDriver, string lpszDevice, string lpszOutput, IntPtr lpInitData); [DllImport("gdi32.dll")] public static extern IntPtr CreateRectRgn(int nLeftRect, int nTopRect, int nReghtRect, int nBottomRect); [DllImport("gdi32.dll")] public static extern IntPtr CreateRoundRectRgn(int nLeftRect, int nTopRect, int nReghtRect, int nBottomRect, int nWidthEllipse, int nHeightEllipse); [DllImport("gdi32.dll")] public static extern bool DeleteDC(IntPtr hDC); [DllImport("gdi32.dll")] public static extern bool DeleteObject(IntPtr hObject); [DllImport("gdi32.dll")] public static extern IntPtr SelectObject(IntPtr hdc, IntPtr hgdiobj); [DllImport("gdi32.dll")] public static extern IntPtr CreateDIBSection(IntPtr hdc, [In] ref BITMAPINFOHEADER pbmi, uint pila, out IntPtr ppvBits, IntPtr hSection, uint dwOffset); [DllImport("gdi32.dll")] public static extern int GetDeviceCaps(IntPtr hdc, int nIndex); [DllImport("gdi32.dll")] public static extern uint GetPixel(IntPtr hdc, int nXPos, int nYPos); #endregion gdi32.dll #region gdiplus.dll [DllImport("gdiplus.dll", CharSet = CharSet.Unicode, ExactSpelling = true)] public static extern int GdipGetImageType(HandleRef image, out int type); [DllImport("gdiplus.dll", CharSet = CharSet.Unicode, ExactSpelling = true)] public static extern int GdipImageForceValidation(HandleRef image); [DllImport("gdiplus.dll", CharSet = CharSet.Unicode, ExactSpelling = true)] public static extern int GdipLoadImageFromFile(string filename, out IntPtr image); [DllImport("gdiplus.dll", CharSet = CharSet.Unicode, ExactSpelling = true)] public static extern int GdipDisposeImage(HandleRef image); [DllImport("gdiplus.dll")] public static extern int GdipWindingModeOutline(HandleRef path, IntPtr matrix, float flatness); #endregion gdiplus.dll #region shell32.dll [DllImport("shell32.dll")] public static extern IntPtr SHAppBarMessage(uint dwMessage, [In] ref APPBARDATA pData); [DllImport("shell32.dll", EntryPoint = "#727")] public extern static int SHGetImageList(int iImageList, ref Guid riid, ref IImageList ppv); [DllImport("shell32.dll", CharSet = CharSet.Auto)] public static extern IntPtr SHGetFileInfo(string pszPath, uint dwFileAttributes, ref SHFILEINFO psfi, uint cbFileInfo, uint uFlags); [DllImport("shell32.dll")] public static extern int SHOpenFolderAndSelectItems(IntPtr pidlFolder, int cild, IntPtr apidl, int dwFlags); [DllImport("shell32.dll")] public static extern void SHChangeNotify(HChangeNotifyEventID wEventId, HChangeNotifyFlags uFlags, IntPtr dwItem1, IntPtr dwItem2); [DllImport("shell32.dll", CharSet = CharSet.Unicode)] public static extern IntPtr ILCreateFromPathW(string pszPath); [DllImport("shell32.dll")] public static extern void ILFree(IntPtr pidl); [DllImport("shell32.dll", CharSet = CharSet.Unicode, PreserveSig = false)] public static extern void SHCreateItemFromParsingName([In][MarshalAs(UnmanagedType.LPWStr)] string pszPath, IntPtr pbc, [In][MarshalAs(UnmanagedType.LPStruct)] Guid riid, [Out][MarshalAs(UnmanagedType.Interface)] out IShellItemImageFactory ppv); #endregion shell32.dll #region dwmapi.dll [DllImport("dwmapi.dll")] public static extern int DwmGetWindowAttribute(IntPtr hwnd, int dwAttribute, out RECT pvAttribute, int cbAttribute); [DllImport("dwmapi.dll")] public static extern int DwmGetWindowAttribute(IntPtr hwnd, int dwAttribute, out bool pvAttribute, int cbAttribute); [DllImport("dwmapi.dll")] public static extern int DwmGetWindowAttribute(IntPtr hwnd, int dwAttribute, out int pvAttribute, int cbAttribute); [DllImport("dwmapi.dll")] public static extern void DwmEnableBlurBehindWindow(IntPtr hwnd, ref DWM_BLURBEHIND blurBehind); [DllImport("dwmapi.dll", PreserveSig = false)] public static extern void DwmEnableComposition(DWM_EC uCompositionAction); [DllImport("dwmapi.dll")] public static extern int DwmExtendFrameIntoClientArea(IntPtr hwnd, ref MARGINS margins); [DllImport("dwmapi.dll", PreserveSig = false)] public static extern bool DwmIsCompositionEnabled(); [DllImport("dwmapi.dll")] public static extern int DwmSetWindowAttribute(IntPtr hwnd, int attr, ref int attrValue, int attrSize); [DllImport("dwmapi.dll")] public static extern int DwmQueryThumbnailSourceSize(IntPtr thumb, out SIZE size); [DllImport("dwmapi.dll")] public static extern int DwmRegisterThumbnail(IntPtr dest, IntPtr src, out IntPtr thumb); [DllImport("dwmapi.dll")] public static extern int DwmSetDxFrameDuration(IntPtr hwnd, uint cRefreshes); [DllImport("dwmapi.dll")] public static extern int DwmUnregisterThumbnail(IntPtr thumb); [DllImport("dwmapi.dll")] public static extern int DwmUpdateThumbnailProperties(IntPtr hThumb, ref DWM_THUMBNAIL_PROPERTIES props); #endregion dwmapi.dll #region winmm.dll [DllImport("winmm.dll", EntryPoint = "timeBeginPeriod")] public static extern uint TimeBeginPeriod(uint uMilliseconds); [DllImport("winmm.dll", EntryPoint = "timeEndPeriod")] public static extern uint TimeEndPeriod(uint uMilliseconds); [DllImport("winmm.dll", EntryPoint = "timeGetDevCaps")] public static extern uint TimeGetDevCaps(ref TimeCaps timeCaps, uint sizeTimeCaps); #endregion #region Other dll [DllImport("msvcrt.dll")] public static extern int memcmp(IntPtr b1, IntPtr b2, long count); /// <summary> /// Copy a block of memory. /// </summary> /// /// <param name="dst">Destination pointer.</param> /// <param name="src">Source pointer.</param> /// <param name="count">Memory block's length to copy.</param> /// /// <returns>Return's the value of <b>dst</b> - pointer to destination.</returns> [DllImport("ntdll.dll", CallingConvention = CallingConvention.Cdecl)] public static extern int memcpy(int dst, int src, int count); /// <summary> /// Initialize the AVIFile library. /// </summary> [DllImport("avifil32.dll")] public static extern void AVIFileInit(); /// <summary> /// Exit the AVIFile library. /// </summary> [DllImport("avifil32.dll")] public static extern void AVIFileExit(); /// <summary> /// Open an AVI file. /// </summary> /// /// <param name="aviHandler">Opened AVI file interface.</param> /// <param name="fileName">AVI file name.</param> /// <param name="mode">Opening mode (see <see cref="OpenFileMode"/>).</param> /// <param name="handler">Handler to use (<b>null</b> to use default).</param> /// /// <returns>Returns zero on success or error code otherwise.</returns> [DllImport("avifil32.dll", CharSet = CharSet.Unicode)] public static extern int AVIFileOpen(out IntPtr aviHandler, string fileName, OpenFileMode mode, IntPtr handler); /// <summary> /// Release an open AVI stream. /// </summary> /// /// <param name="aviHandler">Open AVI file interface.</param> /// /// <returns>Returns the reference count of the file.</returns> [DllImport("avifil32.dll")] public static extern int AVIFileRelease(IntPtr aviHandler); /// <summary> /// Get stream
NativeMethods
csharp
nunit__nunit
src/NUnitFramework/tests/Constraints/EqualConstraintTests.cs
{ "start": 24074, "end": 24645 }
private sealed class ____ : MyBasicDateTime, IEquatable<DateTimeOffset>, IEquatable<DateTime> { public MyDateTime(DateTimeOffset value) : base(value) { } public bool Equals(DateTimeOffset other) => Value.Equals(other); public bool Equals(DateTime other) => Value.UtcDateTime.Equals(other.ToUniversalTime()); } #pragma warning disable CS0659 // Type overrides Object.Equals(object o) but does not override Object.GetHashCode()
MyDateTime
csharp
OrchardCMS__OrchardCore
src/OrchardCore.Modules/OrchardCore.Users/Models/ResetPasswordSettings.cs
{ "start": 37, "end": 168 }
public class ____ { public bool AllowResetPassword { get; set; } public bool UseSiteTheme { get; set; } }
ResetPasswordSettings
csharp
aspnetboilerplate__aspnetboilerplate
src/Abp/AbpException.cs
{ "start": 220, "end": 1322 }
public class ____ : Exception { /// <summary> /// Creates a new <see cref="AbpException"/> object. /// </summary> public AbpException() { } /// <summary> /// Creates a new <see cref="AbpException"/> object. /// </summary> public AbpException(SerializationInfo serializationInfo, StreamingContext context) : base(serializationInfo, context) { } /// <summary> /// Creates a new <see cref="AbpException"/> object. /// </summary> /// <param name="message">Exception message</param> public AbpException(string message) : base(message) { } /// <summary> /// Creates a new <see cref="AbpException"/> object. /// </summary> /// <param name="message">Exception message</param> /// <param name="innerException">Inner exception</param> public AbpException(string message, Exception innerException) : base(message, innerException) { } } }
AbpException
csharp
dotnet__reactive
Rx.NET/Source/tests/Tests.System.Reactive/Tests/Linq/Observable/FirstAsyncTest.cs
{ "start": 416, "end": 6208 }
public class ____ : ReactiveTest { [TestMethod] public void FirstAsync_ArgumentChecking() { ReactiveAssert.Throws<ArgumentNullException>(() => Observable.FirstAsync(default(IObservable<int>))); ReactiveAssert.Throws<ArgumentNullException>(() => Observable.FirstAsync(default(IObservable<int>), _ => true)); ReactiveAssert.Throws<ArgumentNullException>(() => Observable.FirstAsync(DummyObservable<int>.Instance, default)); } [TestMethod] public void FirstAsync_Empty() { var scheduler = new TestScheduler(); var xs = scheduler.CreateHotObservable( OnNext(150, 1), OnCompleted<int>(250) ); var res = scheduler.Start(() => xs.FirstAsync() ); res.Messages.AssertEqual( OnError<int>(250, e => e is InvalidOperationException) ); xs.Subscriptions.AssertEqual( Subscribe(200, 250) ); } [TestMethod] public void FirstAsync_One() { var scheduler = new TestScheduler(); var xs = scheduler.CreateHotObservable( OnNext(150, 1), OnNext(210, 2), OnCompleted<int>(250) ); var res = scheduler.Start(() => xs.FirstAsync() ); res.Messages.AssertEqual( OnNext(210, 2), OnCompleted<int>(210) ); xs.Subscriptions.AssertEqual( Subscribe(200, 210) ); } [TestMethod] public void FirstAsync_Many() { var scheduler = new TestScheduler(); var xs = scheduler.CreateHotObservable( OnNext(150, 1), OnNext(210, 2), OnNext(220, 3), OnCompleted<int>(250) ); var res = scheduler.Start(() => xs.FirstAsync() ); res.Messages.AssertEqual( OnNext(210, 2), OnCompleted<int>(210) ); xs.Subscriptions.AssertEqual( Subscribe(200, 210) ); } [TestMethod] public void FirstAsync_Error() { var scheduler = new TestScheduler(); var ex = new Exception(); var xs = scheduler.CreateHotObservable( OnNext(150, 1), OnError<int>(210, ex) ); var res = scheduler.Start(() => xs.FirstAsync() ); res.Messages.AssertEqual( OnError<int>(210, ex) ); xs.Subscriptions.AssertEqual( Subscribe(200, 210) ); } [TestMethod] public void FirstAsync_Predicate() { var scheduler = new TestScheduler(); var xs = scheduler.CreateHotObservable( OnNext(150, 1), OnNext(210, 2), OnNext(220, 3), OnNext(230, 4), OnNext(240, 5), OnCompleted<int>(250) ); var res = scheduler.Start(() => xs.FirstAsync(x => x % 2 == 1) ); res.Messages.AssertEqual( OnNext(220, 3), OnCompleted<int>(220) ); xs.Subscriptions.AssertEqual( Subscribe(200, 220) ); } [TestMethod] public void FirstAsync_Predicate_None() { var scheduler = new TestScheduler(); var xs = scheduler.CreateHotObservable( OnNext(150, 1), OnNext(210, 2), OnNext(220, 3), OnNext(230, 4), OnNext(240, 5), OnCompleted<int>(250) ); var res = scheduler.Start(() => xs.FirstAsync(x => x > 10) ); res.Messages.AssertEqual( OnError<int>(250, e => e is InvalidOperationException) ); xs.Subscriptions.AssertEqual( Subscribe(200, 250) ); } [TestMethod] public void FirstAsync_Predicate_Throw() { var scheduler = new TestScheduler(); var ex = new Exception(); var xs = scheduler.CreateHotObservable( OnNext(150, 1), OnNext(210, 2), OnError<int>(220, ex) ); var res = scheduler.Start(() => xs.FirstAsync(x => x % 2 == 1) ); res.Messages.AssertEqual( OnError<int>(220, ex) ); xs.Subscriptions.AssertEqual( Subscribe(200, 220) ); } [TestMethod] public void FirstAsync_PredicateThrows() { var scheduler = new TestScheduler(); var ex = new Exception(); var xs = scheduler.CreateHotObservable( OnNext(150, 1), OnNext(210, 2), OnNext(220, 3), OnNext(230, 4), OnNext(240, 5), OnCompleted<int>(250) ); var res = scheduler.Start(() => xs.FirstAsync(x => { if (x < 4) { return false; } throw ex; }) ); res.Messages.AssertEqual( OnError<int>(230, ex) ); xs.Subscriptions.AssertEqual( Subscribe(200, 230) ); } } }
FirstAsyncTest
csharp
NLog__NLog
tests/NLog.UnitTests/LayoutRenderers/Wrappers/OnExceptionTests.cs
{ "start": 1775, "end": 2516 }
public class ____ : NLogTestBase { [Fact] public void OnExceptionTest1() { SimpleLayout l = @"${message}|${onexception:EXCEPTION\:${exception:format=message}:else=Success}|${logger}"; // no exception - ${onexception} is ignored completely var le = LogEventInfo.Create(LogLevel.Info, "logger", "message"); Assert.Equal("message|Success|logger", l.Render(le)); // have exception var le2 = LogEventInfo.Create(LogLevel.Info, "logger", "message"); le2.Exception = new InvalidOperationException("ExceptionMessage"); Assert.Equal("message|EXCEPTION:ExceptionMessage|logger", l.Render(le2)); } } }
OnExceptionTests
csharp
SixLabors__Fonts
src/SixLabors.Fonts/FontRectangle.cs
{ "start": 353, "end": 15359 }
struct ____ : IEquatable<FontRectangle> { /// <summary> /// Represents a <see cref="FontRectangle"/> that has X, Y, Width, and Height values set to zero. /// </summary> public static readonly FontRectangle Empty; /// <summary> /// Initializes a new instance of the <see cref="FontRectangle"/> struct. /// </summary> /// <param name="x">The horizontal position of the rectangle.</param> /// <param name="y">The vertical position of the rectangle.</param> /// <param name="width">The width of the rectangle.</param> /// <param name="height">The height of the rectangle.</param> public FontRectangle(float x, float y, float width, float height) { this.X = x; this.Y = y; this.Width = width; this.Height = height; } /// <summary> /// Initializes a new instance of the <see cref="FontRectangle"/> struct. /// </summary> /// <param name="point"> /// The <see cref="Vector2"/> which specifies the rectangles point in a two-dimensional plane. /// </param> /// <param name="size"> /// The <see cref="Vector2"/> which specifies the rectangles height and width. /// </param> public FontRectangle(Vector2 point, Vector2 size) : this(point.X, point.Y, size.X, size.Y) { } /// <summary> /// Initializes a new instance of the <see cref="FontRectangle"/> structure using the specified bounding box. /// </summary> /// <param name="bound">The bounding box that defines the position and size of the rectangle.</param> internal FontRectangle(in Bounds bound) { this.X = bound.Min.X; this.Y = bound.Min.Y; Vector2 size = bound.Max - bound.Min; this.Width = size.X; this.Height = size.Y; } /// <summary> /// Gets the x-coordinate of this <see cref="FontRectangle"/>. /// </summary> public float X { get; } /// <summary> /// Gets the y-coordinate of this <see cref="FontRectangle"/>. /// </summary> public float Y { get; } /// <summary> /// Gets the width of this <see cref="FontRectangle"/>. /// </summary> public float Width { get; } /// <summary> /// Gets the height of this <see cref="FontRectangle"/>. /// </summary> public float Height { get; } /// <summary> /// Gets the coordinates of the upper-left corner of the rectangular region represented by this <see cref="FontRectangle"/>. /// </summary> [EditorBrowsable(EditorBrowsableState.Never)] public readonly Vector2 Location { [MethodImpl(MethodImplOptions.AggressiveInlining)] get => new(this.X, this.Y); } /// <summary> /// Gets the size of this <see cref="FontRectangle"/>. /// </summary> [EditorBrowsable(EditorBrowsableState.Never)] public readonly Vector2 Size { [MethodImpl(MethodImplOptions.AggressiveInlining)] get => new(this.Width, this.Height); } /// <summary> /// Gets a value indicating whether this <see cref="FontRectangle"/> is empty. /// </summary> [EditorBrowsable(EditorBrowsableState.Never)] public readonly bool IsEmpty => (this.Width <= 0) || (this.Height <= 0); /// <summary> /// Gets the y-coordinate of the top edge of this <see cref="FontRectangle"/>. /// </summary> public readonly float Top => this.Y; /// <summary> /// Gets the x-coordinate of the right edge of this <see cref="FontRectangle"/>. /// </summary> public float Right { [MethodImpl(MethodImplOptions.AggressiveInlining)] get => this.X + this.Width; } /// <summary> /// Gets the y-coordinate of the bottom edge of this <see cref="FontRectangle"/>. /// </summary> public float Bottom { [MethodImpl(MethodImplOptions.AggressiveInlining)] get => this.Y + this.Height; } /// <summary> /// Gets the x-coordinate of the left edge of this <see cref="FontRectangle"/>. /// </summary> public float Left => this.X; /// <summary> /// Compares two <see cref="FontRectangle"/> objects for equality. /// </summary> /// <param name="left">The <see cref="FontRectangle"/> on the left side of the operand.</param> /// <param name="right">The <see cref="FontRectangle"/> on the right side of the operand.</param> /// <returns> /// True if the current left is equal to the <paramref name="right"/> parameter; otherwise, false. /// </returns> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool operator ==(in FontRectangle left, in FontRectangle right) => left.Equals(right); /// <summary> /// Compares two <see cref="FontRectangle"/> objects for inequality. /// </summary> /// <param name="left">The <see cref="FontRectangle"/> on the left side of the operand.</param> /// <param name="right">The <see cref="FontRectangle"/> on the right side of the operand.</param> /// <returns> /// True if the current left is unequal to the <paramref name="right"/> parameter; otherwise, false. /// </returns> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool operator !=(in FontRectangle left, in FontRectangle right) => !left.Equals(right); /// <summary> /// Creates a new <see cref="FontRectangle"/> with the specified location and size. </summary> /// <param name="left">The left coordinate of the rectangle.</param> /// <param name="top">The top coordinate of the rectangle.</param> /// <param name="right">The right coordinate of the rectangle.</param> /// <param name="bottom">The bottom coordinate of the rectangle.</param> /// <returns>The <see cref="FontRectangle"/>.</returns> [MethodImpl(MethodImplOptions.AggressiveInlining)] // ReSharper disable once InconsistentNaming public static FontRectangle FromLTRB(float left, float top, float right, float bottom) => new(left, top, right - left, bottom - top); /// <summary> /// Returns the center point of the given <see cref="FontRectangle"/>. /// </summary> /// <param name="rectangle">The rectangle.</param> /// <returns>The <see cref="Vector2"/>.</returns> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector2 Center(in FontRectangle rectangle) => new(rectangle.Left + (rectangle.Width / 2), rectangle.Top + (rectangle.Height / 2)); /// <summary> /// Creates a rectangle that represents the intersection between <paramref name="a"/> and /// <paramref name="b"/>. If there is no intersection, an empty rectangle is returned. /// </summary> /// <param name="a">The first rectangle.</param> /// <param name="b">The second rectangle.</param> /// <returns>The <see cref="FontRectangle"/>.</returns> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static FontRectangle Intersect(in FontRectangle a, in FontRectangle b) { float x1 = MathF.Max(a.X, b.X); float x2 = MathF.Min(a.Right, b.Right); float y1 = MathF.Max(a.Y, b.Y); float y2 = MathF.Min(a.Bottom, b.Bottom); if (x2 >= x1 && y2 >= y1) { return new FontRectangle(x1, y1, x2 - x1, y2 - y1); } return Empty; } /// <summary> /// Creates a new <see cref="FontRectangle"/> from the given <paramref name="rectangle"/> /// that is inflated by the specified amount. /// </summary> /// <param name="rectangle">The rectangle.</param> /// <param name="x">The amount to inflate the width by.</param> /// <param name="y">The amount to inflate the height by.</param> /// <returns>A new <see cref="FontRectangle"/>.</returns> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static FontRectangle Inflate(in FontRectangle rectangle, float x, float y) => rectangle.Inflate(x, y); /// <summary> /// Creates a new <see cref="FontRectangle"/> by transforming the given rectangle by the given matrix. /// </summary> /// <param name="rectangle">The source rectangle.</param> /// <param name="matrix">The transformation matrix.</param> /// <returns>A transformed <see cref="FontRectangle"/>.</returns> public static FontRectangle Transform(in FontRectangle rectangle, Matrix3x2 matrix) { Vector2 bottomRight = Vector2.Transform(new Vector2(rectangle.Right, rectangle.Bottom), matrix); Vector2 topLeft = Vector2.Transform(rectangle.Location, matrix); Vector2 size = bottomRight - topLeft; return new FontRectangle(topLeft, size); } /// <summary> /// Creates a rectangle that represents the union between <paramref name="a"/> and <paramref name="b"/>. /// </summary> /// <param name="a">The first rectangle.</param> /// <param name="b">The second rectangle.</param> /// <returns>The <see cref="FontRectangle"/>.</returns> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static FontRectangle Union(in FontRectangle a, in FontRectangle b) { float x1 = MathF.Min(a.X, b.X); float x2 = MathF.Max(a.Right, b.Right); float y1 = MathF.Min(a.Y, b.Y); float y2 = MathF.Max(a.Bottom, b.Bottom); return new FontRectangle(x1, y1, x2 - x1, y2 - y1); } /// <summary> /// Deconstructs this rectangle into four floats. /// </summary> /// <param name="x">The out value for X.</param> /// <param name="y">The out value for Y.</param> /// <param name="width">The out value for the width.</param> /// <param name="height">The out value for the height.</param> public void Deconstruct(out float x, out float y, out float width, out float height) { x = this.X; y = this.Y; width = this.Width; height = this.Height; } /// <summary> /// Creates a FontRectangle that represents the intersection between this FontRectangle and the <paramref name="rectangle"/>. /// </summary> /// <param name="rectangle">The rectangle.</param> /// <returns>New <see cref="FontRectangle"/> representing the intersections between the two rectangles.</returns> [MethodImpl(MethodImplOptions.AggressiveInlining)] public FontRectangle Intersect(in FontRectangle rectangle) => Intersect(rectangle, this); /// <summary> /// Creates a new <see cref="FontRectangle"/> inflated by the specified amount. /// </summary> /// <param name="width">The width.</param> /// <param name="height">The height.</param> /// <returns>New <see cref="FontRectangle"/> representing the inflated rectangle</returns> [MethodImpl(MethodImplOptions.AggressiveInlining)] public FontRectangle Inflate(float width, float height) => new( this.X - width, this.Y - height, this.Width + (2 * width), this.Height + (2 * height)); /// <summary> /// Creates a new <see cref="FontRectangle"/> inflated by the specified amount. /// </summary> /// <param name="size">The size.</param> /// <returns>New <see cref="FontRectangle"/> representing the inflated rectangle</returns> [MethodImpl(MethodImplOptions.AggressiveInlining)] public FontRectangle Inflate(Vector2 size) => this.Inflate(size.X, size.Y); /// <summary> /// Determines if the specified point is contained within the rectangular region defined by /// this <see cref="FontRectangle"/>. /// </summary> /// <param name="x">The x-coordinate of the given point.</param> /// <param name="y">The y-coordinate of the given point.</param> /// <returns>The <see cref="bool"/>.</returns> [MethodImpl(MethodImplOptions.AggressiveInlining)] public bool Contains(float x, float y) => this.X <= x && x < this.Right && this.Y <= y && y < this.Bottom; /// <summary> /// Determines if the specified point is contained within the rectangular region defined by this <see cref="FontRectangle"/> . /// </summary> /// <param name="point">The point.</param> /// <returns>The <see cref="bool"/>.</returns> [MethodImpl(MethodImplOptions.AggressiveInlining)] public bool Contains(Vector2 point) => this.Contains(point.X, point.Y); /// <summary> /// Determines if the rectangular region represented by <paramref name="rectangle"/> is entirely contained /// within the rectangular region represented by this <see cref="FontRectangle"/> . /// </summary> /// <param name="rectangle">The rectangle.</param> /// <returns>The <see cref="bool"/>.</returns> [MethodImpl(MethodImplOptions.AggressiveInlining)] public bool Contains(in FontRectangle rectangle) => (this.X <= rectangle.X) && (rectangle.Right <= this.Right) && (this.Y <= rectangle.Y) && (rectangle.Bottom <= this.Bottom); /// <summary> /// Determines if the specified <see cref="FontRectangle"/> intersects the rectangular region defined by /// this <see cref="FontRectangle"/>. /// </summary> /// <param name="rectangle">The other rectangle.</param> /// <returns>The <see cref="bool"/>.</returns> [MethodImpl(MethodImplOptions.AggressiveInlining)] public bool IntersectsWith(in FontRectangle rectangle) => (rectangle.X < this.Right) && (this.X < rectangle.Right) && (rectangle.Y < this.Bottom) && (this.Y < rectangle.Bottom); /// <summary> /// Adjusts the location of this rectangle by the specified amount. /// </summary> /// <param name="point">The point.</param> /// <returns>New <see cref="FontRectangle"/> representing the offset rectangle.</returns> [MethodImpl(MethodImplOptions.AggressiveInlining)] public FontRectangle Offset(Vector2 point) => this.Offset(point.X, point.Y); /// <summary> /// Adjusts the location of this rectangle by the specified amount. /// </summary> /// <param name="dx">The amount to offset the x-coordinate.</param> /// <param name="dy">The amount to offset the y-coordinate.</param> /// <returns>New <see cref="FontRectangle"/> representing the inflated rectangle.</returns> [MethodImpl(MethodImplOptions.AggressiveInlining)] public FontRectangle Offset(float dx, float dy) => new(this.X + dx, this.Y + dy, this.Width, this.Height); /// <inheritdoc/> public override int GetHashCode() => HashCode.Combine(this.X, this.Y, this.Width, this.Height); /// <inheritdoc/> public override string ToString() => $"FontRectangle [ X={this.X}, Y={this.Y}, Width={this.Width}, Height={this.Height} ]"; /// <inheritdoc/> public override bool Equals(object? obj) => obj is FontRectangle other && this.Equals(other); /// <inheritdoc/> [MethodImpl(MethodImplOptions.AggressiveInlining)] public bool Equals(FontRectangle other) => this.X.Equals(other.X) && this.Y.Equals(other.Y) && this.Width.Equals(other.Width) && this.Height.Equals(other.Height); }
FontRectangle