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 | dotnet__aspnetcore | src/Testing/test/ConditionalTheoryTest.cs | {
"start": 3440,
"end": 4022
} | public class ____ : IDisposable
{
public bool TestRan { get; set; }
public void Dispose()
{
}
}
[ConditionalTheory]
[MemberData(nameof(SkippableData))]
public void WithSkipableData(Skippable skippable)
{
Assert.Null(skippable.Skip);
Assert.Equal(1, skippable.Data);
}
public static TheoryData<Skippable> SkippableData => new TheoryData<Skippable>
{
new Skippable() { Data = 1 },
new Skippable() { Data = 2, Skip = "This row should be skipped." }
};
| ConditionalTheoryAsserter |
csharp | dotnetcore__WTM | demo/WalkingTec.Mvvm.Demo/ViewModels/SchoolVMs/SchoolImportVM.cs | {
"start": 304,
"end": 1410
} | public class ____ : BaseTemplateVM
{
[Display(Name = "Sys.Create")]
public ExcelPropety SchoolCode_Excel = ExcelPropety.CreateProperty<School>(x => x.SchoolCode);
[Display(Name = "学校名称")]
public ExcelPropety SchoolName_Excel = ExcelPropety.CreateProperty<School>(x => x.SchoolName);
[Display(Name = "学校类型")]
public ExcelPropety SchoolType_Excel = ExcelPropety.CreateProperty<School>(x => x.SchoolType);
[Display(Name = "备注")]
public ExcelPropety Remark_Excel = ExcelPropety.CreateProperty<School>(x => x.Remark);
[Display(Name = "专业编码")]
public ExcelPropety MajorCode_Excel = ExcelPropety.CreateProperty<School>(x => x.Majors[0].MajorCode);
[Display(Name = "专业名称")]
public ExcelPropety MajorName_Excel = ExcelPropety.CreateProperty<School>(x => x.Majors[0].MajorName);
[Display(Name = "专业类型")]
public ExcelPropety MajorType_Excel = ExcelPropety.CreateProperty<School>(x => x.Majors[0].MajorType);
protected override void InitVM()
{
}
}
| SchoolTemplateVM |
csharp | dotnet__maui | src/Core/src/Handlers/Border/BorderHandler.cs | {
"start": 804,
"end": 8814
} | public partial class ____ : IBorderHandler
{
public static IPropertyMapper<IBorderView, IBorderHandler> Mapper = new PropertyMapper<IBorderView, IBorderHandler>(ViewMapper)
{
#if __ANDROID__
[nameof(IBorderView.Height)] = MapHeight,
[nameof(IBorderView.Width)] = MapWidth,
#endif
[nameof(IBorderView.Background)] = MapBackground,
[nameof(IBorderView.Content)] = MapContent,
[nameof(IBorderView.Shape)] = MapStrokeShape,
[nameof(IBorderView.Stroke)] = MapStroke,
[nameof(IBorderView.StrokeThickness)] = MapStrokeThickness,
[nameof(IBorderView.StrokeLineCap)] = MapStrokeLineCap,
[nameof(IBorderView.StrokeLineJoin)] = MapStrokeLineJoin,
[nameof(IBorderView.StrokeDashPattern)] = MapStrokeDashPattern,
[nameof(IBorderView.StrokeDashOffset)] = MapStrokeDashOffset,
[nameof(IBorderView.StrokeMiterLimit)] = MapStrokeMiterLimit
};
public static CommandMapper<IBorderView, BorderHandler> CommandMapper = new(ViewCommandMapper)
{
};
private Size _lastSize;
public BorderHandler() : base(Mapper, CommandMapper)
{
}
public BorderHandler(IPropertyMapper? mapper)
: base(mapper ?? Mapper, CommandMapper)
{
}
public BorderHandler(IPropertyMapper? mapper, CommandMapper? commandMapper)
: base(mapper ?? Mapper, commandMapper ?? CommandMapper)
{
}
IBorderView IBorderHandler.VirtualView => VirtualView;
PlatformView IBorderHandler.PlatformView => PlatformView;
/// <inheritdoc />
public override void PlatformArrange(Rect rect)
{
base.PlatformArrange(rect);
if (_lastSize != rect.Size)
{
_lastSize = rect.Size;
UpdateValue(nameof(IBorderStroke.Shape));
}
}
/// <summary>
/// Maps the abstract <see cref="IView.Background"/> property to the platform-specific implementations.
/// </summary>
/// <param name="handler">The associated handler.</param>
/// <param name="border">The associated <see cref="IBorderView"/> instance.</param>
public static void MapBackground(IBorderHandler handler, IBorderView border)
{
((PlatformView?)handler.PlatformView)?.UpdateBackground(border);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private static bool ShouldSkipStrokeMappings(IBorderHandler handler)
{
#if __IOS__ || MACCATALYST || ANDROID
// During the initial connection, the `MapBackground` takes care of updating the stroke properties
// so we can skip the stroke mappings to avoid repetitive and useless updates.
return handler.IsConnectingHandler();
#else
return false;
#endif
}
/// <summary>
/// Maps the abstract <see cref="IBorderStroke.Shape"/> property to the platform-specific implementations.
/// </summary>
/// <param name="handler">The associated handler.</param>
/// <param name="border">The associated <see cref="IBorderView"/> instance.</param>
public static void MapStrokeShape(IBorderHandler handler, IBorderView border)
{
if (ShouldSkipStrokeMappings(handler))
{
return;
}
((PlatformView?)handler.PlatformView)?.UpdateStrokeShape(border);
MapBackground(handler, border);
}
/// <summary>
/// Maps the abstract <see cref="IStroke.Stroke"/> property to the platform-specific implementations.
/// </summary>
/// <param name="handler">The associated handler.</param>
/// <param name="border">The associated <see cref="IBorderView"/> instance.</param>
public static void MapStroke(IBorderHandler handler, IBorderView border)
{
if (ShouldSkipStrokeMappings(handler))
{
return;
}
((PlatformView?)handler.PlatformView)?.UpdateStroke(border);
MapBackground(handler, border);
}
/// <summary>
/// Maps the abstract <see cref="IStroke.StrokeThickness"/> property to the platform-specific implementations.
/// </summary>
/// <param name="handler">The associated handler.</param>
/// <param name="border">The associated <see cref="IBorderView"/> instance.</param>
public static void MapStrokeThickness(IBorderHandler handler, IBorderView border)
{
if (ShouldSkipStrokeMappings(handler))
{
return;
}
((PlatformView?)handler.PlatformView)?.UpdateStrokeThickness(border);
MapBackground(handler, border);
}
/// <summary>
/// Maps the abstract <see cref="IStroke.StrokeLineCap"/> property to the platform-specific implementations.
/// </summary>
/// <param name="handler">The associated handler.</param>
/// <param name="border">The associated <see cref="IBorderView"/> instance.</param>
public static void MapStrokeLineCap(IBorderHandler handler, IBorderView border)
{
if (ShouldSkipStrokeMappings(handler))
{
return;
}
((PlatformView?)handler.PlatformView)?.UpdateStrokeLineCap(border);
}
/// <summary>
/// Maps the abstract <see cref="IStroke.StrokeLineJoin"/> property to the platform-specific implementations.
/// </summary>
/// <param name="handler">The associated handler.</param>
/// <param name="border">The associated <see cref="IBorderView"/> instance.</param>
public static void MapStrokeLineJoin(IBorderHandler handler, IBorderView border)
{
if (ShouldSkipStrokeMappings(handler))
{
return;
}
((PlatformView?)handler.PlatformView)?.UpdateStrokeLineJoin(border);
}
/// <summary>
/// Maps the abstract <see cref="IStroke.StrokeDashPattern"/> property to the platform-specific implementations.
/// </summary>
/// <param name="handler">The associated handler.</param>
/// <param name="border">The associated <see cref="IBorderView"/> instance.</param>
public static void MapStrokeDashPattern(IBorderHandler handler, IBorderView border)
{
if (ShouldSkipStrokeMappings(handler))
{
return;
}
((PlatformView?)handler.PlatformView)?.UpdateStrokeDashPattern(border);
}
/// <summary>
/// Maps the abstract <see cref="IStroke.StrokeDashOffset"/> property to the platform-specific implementations.
/// </summary>
/// <param name="handler">The associated handler.</param>
/// <param name="border">The associated <see cref="IBorderView"/> instance.</param>
public static void MapStrokeDashOffset(IBorderHandler handler, IBorderView border)
{
if (ShouldSkipStrokeMappings(handler))
{
return;
}
((PlatformView?)handler.PlatformView)?.UpdateStrokeDashOffset(border);
}
/// <summary>
/// Maps the abstract <see cref="IStroke.StrokeMiterLimit"/> property to the platform-specific implementations.
/// </summary>
/// <param name="handler">The associated handler.</param>
/// <param name="border">The associated <see cref="IBorderView"/> instance.</param>
public static void MapStrokeMiterLimit(IBorderHandler handler, IBorderView border)
{
if (ShouldSkipStrokeMappings(handler))
{
return;
}
((PlatformView?)handler.PlatformView)?.UpdateStrokeMiterLimit(border);
}
/// <summary>
/// Maps the abstract <see cref="IContentView.Content"/> property to the platform-specific implementations.
/// </summary>
/// <param name="handler">The associated handler.</param>
/// <param name="border">The associated <see cref="IBorderView"/> instance.</param>
public static void MapContent(IBorderHandler handler, IBorderView border)
{
UpdateContent(handler);
}
static partial void UpdateContent(IBorderHandler handler);
#if __ANDROID__
/// <summary>
/// Maps the abstract <see cref="IView.Width"/> property to the platform-specific implementations.
/// </summary>
/// <param name="handler">The associated handler.</param>
/// <param name="border">The associated <see cref="IBorderView"/> instance.</param>
public static partial void MapWidth(IBorderHandler handler, IBorderView border);
/// <summary>
/// Maps the abstract <see cref="IView.Height"/> property to the platform-specific implementations.
/// </summary>
/// <param name="handler">The associated handler.</param>
/// <param name="border">The associated <see cref="IBorderView"/> instance.</param>
public static partial void MapHeight(IBorderHandler handler, IBorderView border);
#endif
}
}
| BorderHandler |
csharp | dotnet__maui | src/Controls/tests/Xaml.UnitTests/Issues/Issue1213.xaml.cs | {
"start": 141,
"end": 250
} | public partial class ____ : TabbedPage
{
public Issue1213() => InitializeComponent();
[TestFixture]
| Issue1213 |
csharp | EventStore__EventStore | src/KurrentDB.Transport.Http/Client/ClientOperationState.cs | {
"start": 294,
"end": 875
} | public class ____ {
public readonly HttpRequestMessage Request;
public readonly Action<HttpResponse> OnSuccess;
public readonly Action<Exception> OnError;
public HttpResponse Response { get; set; }
public ClientOperationState(HttpRequestMessage request, Action<HttpResponse> onSuccess,
Action<Exception> onError) {
Ensure.NotNull(request, "request");
Ensure.NotNull(onSuccess, "onSuccess");
Ensure.NotNull(onError, "onError");
Request = request;
OnSuccess = onSuccess;
OnError = onError;
}
public void Dispose() {
Request.Dispose();
}
}
| ClientOperationState |
csharp | unoplatform__uno | src/Uno.UI/Generated/3.0.0.0/Microsoft.UI.Xaml.Automation.Peers/GridViewItemDataAutomationPeer.cs | {
"start": 309,
"end": 1922
} | public partial class ____ : global::Microsoft.UI.Xaml.Automation.Peers.SelectorItemAutomationPeer, global::Microsoft.UI.Xaml.Automation.Provider.IScrollItemProvider
{
#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 GridViewItemDataAutomationPeer(object item, global::Microsoft.UI.Xaml.Automation.Peers.GridViewAutomationPeer parent) : base(item, parent)
{
global::Windows.Foundation.Metadata.ApiInformation.TryRaiseNotImplemented("Microsoft.UI.Xaml.Automation.Peers.GridViewItemDataAutomationPeer", "GridViewItemDataAutomationPeer.GridViewItemDataAutomationPeer(object item, GridViewAutomationPeer parent)");
}
#endif
// Forced skipping of method Microsoft.UI.Xaml.Automation.Peers.GridViewItemDataAutomationPeer.GridViewItemDataAutomationPeer(object, Microsoft.UI.Xaml.Automation.Peers.GridViewAutomationPeer)
#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 void ScrollIntoView()
{
global::Windows.Foundation.Metadata.ApiInformation.TryRaiseNotImplemented("Microsoft.UI.Xaml.Automation.Peers.GridViewItemDataAutomationPeer", "void GridViewItemDataAutomationPeer.ScrollIntoView()");
}
#endif
// Processing: Microsoft.UI.Xaml.Automation.Provider.IScrollItemProvider
}
}
| GridViewItemDataAutomationPeer |
csharp | dotnet__maui | src/Essentials/src/Gyroscope/Gyroscope.shared.cs | {
"start": 1254,
"end": 2848
} | partial class ____
{
/// <summary>
/// Occurs when the gyroscope reading changes.
/// </summary>
public static event EventHandler<GyroscopeChangedEventArgs> ReadingChanged
{
add => Current.ReadingChanged += value;
remove => Current.ReadingChanged -= value;
}
/// <summary>
/// Gets a value indicating whether the gyroscope is actively being monitored.
/// </summary>
public static bool IsMonitoring
=> Current.IsMonitoring;
/// <summary>
/// Gets a value indicating whether reading the gyroscope is supported on this device.
/// </summary>
public static bool IsSupported
=> Current.IsSupported;
/// <summary>
/// Start monitoring for changes to the gyroscope.
/// </summary>
/// <param name="sensorSpeed">The speed to listen for changes.</param>
public static void Start(SensorSpeed sensorSpeed)
=> Current.Start(sensorSpeed);
/// <summary>
/// Stop monitoring for changes to the gyroscope.
/// </summary>
public static void Stop()
=> Current.Stop();
static IGyroscope Current => Devices.Sensors.Gyroscope.Default;
static IGyroscope? defaultImplementation;
/// <summary>
/// Provides the default implementation for static usage of this API.
/// </summary>
public static IGyroscope Default =>
defaultImplementation ??= new GyroscopeImplementation();
internal static void SetDefault(IGyroscope? implementation) =>
defaultImplementation = implementation;
}
/// <summary>
/// Contains the current axis reading information from the <see cref="IGyroscope.ReadingChanged"/> event.
/// </summary>
| Gyroscope |
csharp | ChilliCream__graphql-platform | src/HotChocolate/Core/test/Types.Tests/Types/Scalars/DateTimeTypeTests.cs | {
"start": 167,
"end": 10945
} | public class ____
{
[Fact]
public void Serialize_Utc_DateTimeOffset()
{
// arrange
var dateTimeType = new DateTimeType();
DateTimeOffset dateTime = new DateTime(
2018,
6,
11,
8,
46,
14,
DateTimeKind.Utc);
const string expectedValue = "2018-06-11T08:46:14.000Z";
// act
var serializedValue = (string?)dateTimeType.Serialize(dateTime);
// assert
Assert.Equal(expectedValue, serializedValue);
}
[Fact]
public void Serialize_DateTimeOffset()
{
// arrange
var dateTimeType = new DateTimeType();
var dateTime = new DateTimeOffset(
new DateTime(2018, 6, 11, 8, 46, 14),
new TimeSpan(4, 0, 0));
const string expectedValue = "2018-06-11T08:46:14.000+04:00";
// act
var serializedValue = (string?)dateTimeType.Serialize(dateTime);
// assert
Assert.Equal(expectedValue, serializedValue);
}
[Fact]
public void Serialize_Null()
{
// arrange
var dateTimeType = new DateTimeType();
// act
var serializedValue = dateTimeType.Serialize(null);
// assert
Assert.Null(serializedValue);
}
[Fact]
public void Serialize_String_Exception()
{
// arrange
var dateTimeType = new DateTimeType();
// act
Action a = () => dateTimeType.Serialize("foo");
// assert
Assert.Throws<SerializationException>(a);
}
[Fact]
public void ParseLiteral_StringValueNode()
{
// arrange
var dateTimeType = new DateTimeType();
var literal = new StringValueNode(
"2018-06-29T08:46:14+04:00");
var expectedDateTime = new DateTimeOffset(
new DateTime(2018, 6, 29, 8, 46, 14),
new TimeSpan(4, 0, 0));
// act
var dateTime = (DateTimeOffset)dateTimeType.ParseLiteral(literal)!;
// assert
Assert.Equal(expectedDateTime, dateTime);
}
[Theory]
[MemberData(nameof(ValidDateTimeScalarStrings))]
public void ParseLiteral_StringValueNode_Valid(string dateTime, DateTimeOffset result)
{
// arrange
var dateTimeType = new DateTimeType();
var literal = new StringValueNode(dateTime);
// act
var dateTimeOffset = (DateTimeOffset?)dateTimeType.ParseLiteral(literal);
// assert
Assert.Equal(result, dateTimeOffset);
}
[Theory]
[MemberData(nameof(InvalidDateTimeScalarStrings))]
public void ParseLiteral_StringValueNode_Invalid(string dateTime)
{
// arrange
var dateTimeType = new DateTimeType();
var literal = new StringValueNode(dateTime);
// act
void Act()
{
dateTimeType.ParseLiteral(literal);
}
// assert
Assert.Equal(
"DateTime cannot parse the given literal of type `StringValueNode`.",
Assert.Throws<SerializationException>(Act).Message);
}
[InlineData("en-US")]
[InlineData("en-AU")]
[InlineData("en-GB")]
[InlineData("de-CH")]
[InlineData("de-de")]
[Theory]
public void ParseLiteral_StringValueNode_DifferentCulture(string cultureName)
{
// arrange
Thread.CurrentThread.CurrentCulture =
CultureInfo.GetCultureInfo(cultureName);
var dateTimeType = new DateTimeType();
var literal = new StringValueNode(
"2018-06-29T08:46:14+04:00");
var expectedDateTime = new DateTimeOffset(
new DateTime(2018, 6, 29, 8, 46, 14),
new TimeSpan(4, 0, 0));
// act
var dateTime = (DateTimeOffset)dateTimeType.ParseLiteral(literal)!;
// assert
Assert.Equal(expectedDateTime, dateTime);
}
[Fact]
public void Deserialize_IsoString_DateTimeOffset()
{
// arrange
var dateTimeType = new DateTimeType();
var dateTime = new DateTimeOffset(
new DateTime(2018, 6, 11, 8, 46, 14),
new TimeSpan(4, 0, 0));
// act
var deserializedValue = (DateTimeOffset)dateTimeType.Deserialize("2018-06-11T08:46:14+04:00")!;
// assert
Assert.Equal(dateTime, deserializedValue);
}
[Fact]
public void Deserialize_ZuluString_DateTimeOffset()
{
// arrange
var dateTimeType = new DateTimeType();
var dateTime = new DateTimeOffset(
new DateTime(2018, 6, 11, 8, 46, 14),
new TimeSpan(0, 0, 0));
// act
var deserializedValue = (DateTimeOffset)dateTimeType.Deserialize("2018-06-11T08:46:14.000Z")!;
// assert
Assert.Equal(dateTime, deserializedValue);
}
[Fact]
public void Deserialize_IsoString_DateTime()
{
// arrange
var dateTimeType = new DateTimeType();
var dateTime = new DateTime(
2018,
6,
11,
8,
46,
14,
DateTimeKind.Unspecified);
// act
var deserializedValue = ((DateTimeOffset)dateTimeType.Deserialize("2018-06-11T08:46:14+04:00")!).DateTime;
// assert
Assert.Equal(dateTime, deserializedValue);
Assert.Equal(DateTimeKind.Unspecified, deserializedValue.Kind);
}
[Fact]
public void Deserialize_ZuluString_DateTime()
{
// arrange
var dateTimeType = new DateTimeType();
DateTimeOffset dateTime = new DateTime(
2018,
6,
11,
8,
46,
14,
DateTimeKind.Utc);
// act
var deserializedValue = (DateTimeOffset)dateTimeType.Deserialize("2018-06-11T08:46:14.000Z")!;
// assert
Assert.Equal(dateTime, deserializedValue.UtcDateTime);
}
[Fact]
public void Deserialize_InvalidString_To_DateTimeOffset()
{
// arrange
var type = new DateTimeType();
// act
var success = type.TryDeserialize("abc", out _);
// assert
Assert.False(success);
}
[Fact]
public void Deserialize_DateTimeOffset_To_DateTimeOffset()
{
// arrange
var type = new DateTimeType();
var time = new DateTimeOffset(
new DateTime(2018, 6, 11, 8, 46, 14, DateTimeKind.Utc));
// act
var success = type.TryDeserialize(time, out var deserialized);
// assert
Assert.True(success);
Assert.Equal(time, deserialized);
}
[Fact]
public void Deserialize_DateTime_To_DateTimeOffset()
{
// arrange
var type = new DateTimeType();
var time = new DateTime(2018, 6, 11, 8, 46, 14, DateTimeKind.Utc);
// act
var success = type.TryDeserialize(time, out var deserialized);
// assert
Assert.True(success);
Assert.Equal(time,
Assert.IsType<DateTimeOffset>(deserialized).UtcDateTime);
}
[Fact]
public void Deserialize_NullableDateTime_To_DateTimeOffset()
{
// arrange
var type = new DateTimeType();
DateTime? time =
new DateTime(2018, 6, 11, 8, 46, 14, DateTimeKind.Utc);
// act
var success = type.TryDeserialize(time, out var deserialized);
// assert
Assert.True(success);
Assert.Equal(time,
Assert.IsType<DateTimeOffset>(deserialized).UtcDateTime);
}
[Fact]
public void Deserialize_NullableDateTime_To_DateTimeOffset_2()
{
// arrange
var type = new DateTimeType();
DateTime? time = null;
// act
var success = type.TryDeserialize(time, out var deserialized);
// assert
Assert.True(success);
Assert.Null(deserialized);
}
[Fact]
public void Deserialize_Null_To_Null()
{
// arrange
var type = new DateTimeType();
// act
var success = type.TryDeserialize(null, out var deserialized);
// assert
Assert.True(success);
Assert.Null(deserialized);
}
[Fact]
public void ParseLiteral_NullValueNode()
{
// arrange
var dateTimeType = new DateTimeType();
var literal = NullValueNode.Default;
// act
var value = dateTimeType.ParseLiteral(literal);
// assert
Assert.Null(value);
}
[Fact]
public void ParseValue_DateTimeOffset()
{
// arrange
var dateTimeType = new DateTimeType();
var dateTime = new DateTimeOffset(
new DateTime(2018, 6, 11, 8, 46, 14),
new TimeSpan(4, 0, 0));
const string expectedLiteralValue = "2018-06-11T08:46:14.000+04:00";
// act
var stringLiteral =
(StringValueNode)dateTimeType.ParseValue(dateTime);
// assert
Assert.Equal(expectedLiteralValue, stringLiteral.Value);
}
[Fact]
public void ParseValue_Utc_DateTimeOffset()
{
// arrange
var dateTimeType = new DateTimeType();
DateTimeOffset dateTime =
new DateTime(2018, 6, 11, 8, 46, 14, DateTimeKind.Utc);
const string expectedLiteralValue = "2018-06-11T08:46:14.000Z";
// act
var stringLiteral =
(StringValueNode)dateTimeType.ParseValue(dateTime);
// assert
Assert.Equal(expectedLiteralValue, stringLiteral.Value);
}
[Fact]
public void ParseValue_Null()
{
// arrange
var dateTimeType = new DateTimeType();
// act
var literal = dateTimeType.ParseValue(null);
// assert
Assert.IsType<NullValueNode>(literal);
}
[Fact]
public void EnsureDateTimeTypeKindIsCorrect()
{
// arrange
var type = new DateTimeType();
// act
var kind = type.Kind;
// assert
Assert.Equal(TypeKind.Scalar, kind);
}
[Fact]
public async Task Integration_DefaultDateTime()
{
// arrange
var executor = await new ServiceCollection()
.AddGraphQL()
.AddQueryType<DefaultDateTime>()
.BuildRequestExecutorAsync();
// act
var res = await executor.ExecuteAsync("{ test }");
// assert
res.ToJson().MatchSnapshot();
}
[Fact]
public void DateTime_Relaxed_Format_Check()
{
// arrange
const string s = "2011-08-30";
// act
var dateTimeType = new DateTimeType(disableFormatCheck: true);
var result = dateTimeType.Deserialize(s);
// assert
Assert.IsType<DateTimeOffset>(result);
}
| DateTimeTypeTests |
csharp | louthy__language-ext | LanguageExt.Core/Traits/Fallible/Fallible.Prelude.Partition.E.cs | {
"start": 124,
"end": 6434
} | partial class ____
{
/// <summary>
/// Partitions a foldable of effects into two lists.
/// All the `Fail` elements are extracted, in order, to the first
/// component of the output. Similarly, the `Succ` elements are extracted
/// to the second component of the output.
/// </summary>
/// <typeparam name="E">Error type</typeparam>
/// <typeparam name="F">Foldable type</typeparam>
/// <typeparam name="M">Fallible monadic type</typeparam>
/// <typeparam name="A">Bound value type</typeparam>
/// <param name="fma">Foldable of fallible monadic values</param>
/// <returns>A tuple containing an `Error` sequence and a `Succ` sequence</returns>
public static K<M, (Seq<E> Fails, Seq<A> Succs)> partitionFallible<E, F, M, A>(
K<F, K<M, A>> fma)
where M : Monad<M>, Fallible<E, M>
where F : Foldable<F> =>
fma.Fold(M.Pure((Fails: LanguageExt.Seq.empty<E>(), Succs: LanguageExt.Seq.empty<A>())),
ma => ms => from s in ms
from r in ma.Map(a => (s.Fails, s.Succs.Add(a)))
.Catch((E e) => M.Pure((s.Fails.Add(e), s.Succs)))
select r);
/// <summary>
/// Partitions a collection of effects into two lists.
/// All the `Fail` elements are extracted, in order, to the first
/// component of the output. Similarly, the `Succ` elements are extracted
/// to the second component of the output.
/// </summary>
/// <typeparam name="E">Error type</typeparam>
/// <typeparam name="M">Fallible monadic type</typeparam>
/// <typeparam name="A">Bound value type</typeparam>
/// <param name="fma">Collection of fallible monadic values</param>
/// <returns>A tuple containing an `Error` sequence and a `Succ` sequence</returns>
public static K<M, (Seq<E> Fails, Seq<A> Succs)> partitionFallible<E, M, A>(
Seq<K<M, A>> fma)
where M : Monad<M>, Fallible<E, M> =>
fma.Kind().PartitionFallible<E, Seq, M, A>();
/// <summary>
/// Partitions a collection of effects into two lists.
/// All the `Fail` elements are extracted, in order, to the first
/// component of the output. Similarly, the `Succ` elements are extracted
/// to the second component of the output.
/// </summary>
/// <typeparam name="E">Error type</typeparam>
/// <typeparam name="M">Fallible monadic type</typeparam>
/// <typeparam name="A">Bound value type</typeparam>
/// <param name="fma">Collection of fallible monadic values</param>
/// <returns>A tuple containing an `Error` sequence and a `Succ` sequence</returns>
public static K<M, (Seq<E> Fails, Seq<A> Succs)> partitionFallible<E, M, A>(
Iterable<K<M, A>> fma)
where M : Monad<M>, Fallible<E, M> =>
fma.Kind().PartitionFallible<E, Iterable, M, A>();
/// <summary>
/// Partitions a collection of effects into two lists.
/// All the `Fail` elements are extracted, in order, to the first
/// component of the output. Similarly, the `Succ` elements are extracted
/// to the second component of the output.
/// </summary>
/// <typeparam name="E">Error type</typeparam>
/// <typeparam name="M">Fallible monadic type</typeparam>
/// <typeparam name="A">Bound value type</typeparam>
/// <param name="fma">Collection of fallible monadic values</param>
/// <returns>A tuple containing an `Error` sequence and a `Succ` sequence</returns>
public static K<M, (Seq<E> Fails, Seq<A> Succs)> partitionFallible<E, M, A>(
Lst<K<M, A>> fma)
where M : Monad<M>, Fallible<E, M> =>
fma.Kind().PartitionFallible<E, Lst, M, A>();
/// <summary>
/// Partitions a collection of effects into two lists.
/// All the `Fail` elements are extracted, in order, to the first
/// component of the output. Similarly, the `Succ` elements are extracted
/// to the second component of the output.
/// </summary>
/// <typeparam name="E">Error type</typeparam>
/// <typeparam name="M">Fallible monadic type</typeparam>
/// <typeparam name="A">Bound value type</typeparam>
/// <param name="fma">Collection of fallible monadic values</param>
/// <returns>A tuple containing an `Error` sequence and a `Succ` sequence</returns>
public static K<M, (Seq<E> Fails, Seq<A> Succs)> partitionFallible<E, M, A>(
IEnumerable<K<M, A>> fma)
where M : Monad<M>, Fallible<E, M> =>
LanguageExt.Iterable.createRange(fma).PartitionFallible<E, Iterable, M, A>();
/// <summary>
/// Partitions a collection of effects into two lists.
/// All the `Fail` elements are extracted, in order, to the first
/// component of the output. Similarly, the `Succ` elements are extracted
/// to the second component of the output.
/// </summary>
/// <typeparam name="E">Error type</typeparam>
/// <typeparam name="M">Fallible monadic type</typeparam>
/// <typeparam name="A">Bound value type</typeparam>
/// <param name="fma">Collection of fallible monadic values</param>
/// <returns>A tuple containing an `Error` sequence and a `Succ` sequence</returns>
public static K<M, (Seq<E> Fails, Seq<A> Succs)> partitionFallible<E, M, A>(
HashSet<K<M, A>> fma)
where M : Monad<M>, Fallible<E, M> =>
fma.Kind().PartitionFallible<E, HashSet, M, A>();
/// <summary>
/// Partitions a collection of effects into two lists.
/// All the `Fail` elements are extracted, in order, to the first
/// component of the output. Similarly, the `Succ` elements are extracted
/// to the second component of the output.
/// </summary>
/// <typeparam name="E">Error type</typeparam>
/// <typeparam name="M">Fallible monadic type</typeparam>
/// <typeparam name="A">Bound value type</typeparam>
/// <param name="fma">Collection of fallible monadic values</param>
/// <returns>A tuple containing an `Error` sequence and a `Succ` sequence</returns>
public static K<M, (Seq<E> Fails, Seq<A> Succs)> partitionFallible<E, M, A>(
Set<K<M, A>> fma)
where M : Monad<M>, Fallible<E, M> =>
fma.Kind().PartitionFallible<E, Set, M, A>();
}
| Prelude |
csharp | CommunityToolkit__dotnet | tests/CommunityToolkit.Mvvm.UnitTests/Test_ObservablePropertyAttribute.cs | {
"start": 63425,
"end": 64260
} | public partial class ____ : ObservableObject
{
[ObservableProperty]
[set: MemberNotNull(nameof(B))]
private string a;
// This type validates forwarding attributes on generated accessors. In particular, there should
// be no nullability warning on this constructor (CS8618), thanks to 'MemberNotNullAttribute("B")'
// being forwarded to the generated setter in the generated property (see linked issue).
public ModelWithSecondaryPropertySetFromGeneratedSetter_DoesNotWarn()
{
A = "";
}
public string B { get; private set; }
[MemberNotNull(nameof(B))]
partial void OnAChanged(string? oldValue, string newValue)
{
B = "";
}
}
#endif
}
| ModelWithSecondaryPropertySetFromGeneratedSetter_DoesNotWarn |
csharp | dotnet__reactive | Rx.NET/Source/src/System.Reactive/Linq/Observable/Throttle.cs | {
"start": 6755,
"end": 8389
} | private sealed class ____ : SafeObserver<TThrottle>
{
private readonly _ _parent;
private readonly TSource _value;
private readonly ulong _currentid;
public ThrottleObserver(_ parent, TSource value, ulong currentid)
{
_parent = parent;
_value = value;
_currentid = currentid;
}
public override void OnNext(TThrottle value)
{
lock (_parent._gate)
{
if (_parent._hasValue && _parent._id == _currentid)
{
_parent.ForwardOnNext(_value);
}
_parent._hasValue = false;
Dispose();
}
}
public override void OnError(Exception error)
{
lock (_parent._gate)
{
_parent.ForwardOnError(error);
}
}
public override void OnCompleted()
{
lock (_parent._gate)
{
if (_parent._hasValue && _parent._id == _currentid)
{
_parent.ForwardOnNext(_value);
}
_parent._hasValue = false;
Dispose();
}
}
}
}
}
}
| ThrottleObserver |
csharp | dotnet__efcore | test/EFCore.SqlServer.FunctionalTests/SqlServerTypeAliasTest.cs | {
"start": 7664,
"end": 8520
} | private class ____
{
public int Id { get; set; }
[Column(TypeName = "datetimeAlias")]
public DateTime DateTimeAlias { get; set; }
[Column(TypeName = "datetimeoffsetAlias")]
public DateTimeOffset DateTimeOffsetAlias { get; set; }
[Column(TypeName = "timeAlias")]
public TimeOnly TimeAlias { get; set; }
[Column(TypeName = "decimalAlias")]
public decimal DecimalAlias { get; set; }
[Column(TypeName = "doubleAlias")]
public double DoubleAlias { get; set; }
[Column(TypeName = "floatAlias")]
public float FloatAlias { get; set; }
[Column(TypeName = "binaryAlias")]
public byte[]? BinaryAlias { get; set; }
[Column(TypeName = "stringAlias")]
public string? StringAlias { get; set; }
}
}
| TypeAliasEntityWithFacets |
csharp | microsoft__PowerToys | src/dsc/v3/PowerToys.DSC/DSCResources/BaseResource.cs | {
"start": 398,
"end": 4105
} | public abstract class ____
{
/// <summary>
/// Gets the name of the resource.
/// </summary>
public string Name { get; }
/// <summary>
/// Gets the module being used by the resource, if provided.
/// </summary>
public string? Module { get; }
public BaseResource(string name, string? module)
{
Name = name;
Module = module;
}
/// <summary>
/// Calls the get method on the resource.
/// </summary>
/// <param name="input">The input string, if any.</param>
/// <returns>True if the operation was successful; otherwise false.</returns>
public abstract bool GetState(string? input);
/// <summary>
/// Calls the set method on the resource.
/// </summary>
/// <param name="input">The input string, if any.</param>
/// <returns>True if the operation was successful; otherwise false.</returns>
public abstract bool SetState(string? input);
/// <summary>
/// Calls the test method on the resource.
/// </summary>
/// <param name="input">The input string, if any.</param>
/// <returns>True if the operation was successful; otherwise false.</returns>
public abstract bool TestState(string? input);
/// <summary>
/// Calls the export method on the resource.
/// </summary>
/// <param name="input"> The input string, if any.</param>
/// <returns>True if the operation was successful; otherwise false.</returns>
public abstract bool ExportState(string? input);
/// <summary>
/// Calls the schema method on the resource.
/// </summary>
/// <returns>True if the operation was successful; otherwise false.</returns>
public abstract bool Schema();
/// <summary>
/// Generates a DSC resource JSON manifest for the resource. If the
/// outputDir is not provided, the manifest will be printed to the console.
/// </summary>
/// <param name="outputDir"> The directory where the manifest should be
/// saved. If null, the manifest will be printed to the console.</param>
/// <returns>True if the manifest was successfully generated and saved,otherwise false.</returns>
public abstract bool Manifest(string? outputDir);
/// <summary>
/// Gets the list of supported modules for the resource.
/// </summary>
/// <returns>Gets a list of supported modules.</returns>
public abstract IList<string> GetSupportedModules();
/// <summary>
/// Writes a JSON output line to the console.
/// </summary>
/// <param name="output">The JSON output to write.</param>
protected void WriteJsonOutputLine(JsonNode output)
{
var json = output.ToJsonString(new() { WriteIndented = false });
WriteJsonOutputLine(json);
}
/// <summary>
/// Writes a JSON output line to the console.
/// </summary>
/// <param name="output">The JSON output to write.</param>
protected void WriteJsonOutputLine(string output)
{
Console.WriteLine(output);
}
/// <summary>
/// Writes a message output line to the console with the specified message level.
/// </summary>
/// <param name="level">The level of the message.</param>
/// <param name="message">The message to write.</param>
protected void WriteMessageOutputLine(DscMessageLevel level, string message)
{
var messageObj = new Dictionary<string, string>
{
[GetMessageLevel(level)] = message,
};
var messageJson = System.Text.Json.JsonSerializer.Serialize(messageObj);
Console.Error.WriteLine(messageJson);
}
/// <summary>
/// Gets the message level as a string based on the provided dsc message level | BaseResource |
csharp | kgrzybek__modular-monolith-with-ddd | src/Modules/Meetings/Tests/UnitTests/MeetingGroupProposals/MeetingGroupProposalTests.cs | {
"start": 680,
"end": 3707
} | public class ____ : TestBase
{
[Test]
public void ProposeNewMeetingGroup_IsSuccessful()
{
var proposalMemberId = new MemberId(Guid.NewGuid());
var meetingProposal = MeetingGroupProposal.ProposeNew(
"name",
"description",
MeetingGroupLocation.CreateNew("Warsaw", "PL"),
proposalMemberId);
var meetingGroupProposed = AssertPublishedDomainEvent<MeetingGroupProposedDomainEvent>(meetingProposal);
meetingGroupProposed.MeetingGroupProposalId.Should().Be(meetingProposal.Id);
}
[Test]
public void AcceptProposal_WhenIsNotAccepted_IsSuccessful()
{
var proposalMemberId = new MemberId(Guid.NewGuid());
var meetingProposal = MeetingGroupProposal.ProposeNew(
"name",
"description",
MeetingGroupLocation.CreateNew("Warsaw", "PL"),
proposalMemberId);
meetingProposal.Accept();
var meetingGroupProposalAccepted =
AssertPublishedDomainEvent<MeetingGroupProposalAcceptedDomainEvent>(meetingProposal);
meetingGroupProposalAccepted.MeetingGroupProposalId.Should().Be(meetingProposal.Id);
}
[Test]
public void AcceptProposal_WhenIsAlreadyAccepted_BreaksProposalCannotBeAcceptedMoreThanOnceRule()
{
var proposalMemberId = new MemberId(Guid.NewGuid());
var meetingProposal = MeetingGroupProposal.ProposeNew(
"name",
"description",
MeetingGroupLocation.CreateNew("Warsaw", "PL"),
proposalMemberId);
meetingProposal.Accept();
AssertBrokenRule<MeetingGroupProposalCannotBeAcceptedMoreThanOnceRule>(() => { meetingProposal.Accept(); });
}
[Test]
public void CreateMeetingGroup_IsSuccessful_And_CreatorIsAHost()
{
var proposalMemberId = new MemberId(Guid.NewGuid());
var name = "name";
var description = "description";
var meetingGroupLocation = MeetingGroupLocation.CreateNew("Warsaw", "PL");
var meetingProposal = MeetingGroupProposal.ProposeNew(
name,
description,
meetingGroupLocation,
proposalMemberId);
var meetingGroup = meetingProposal.CreateMeetingGroup();
var meetingGroupCreated = AssertPublishedDomainEvent<MeetingGroupCreatedDomainEvent>(meetingGroup);
var newMeetingGroupMemberJoined =
AssertPublishedDomainEvent<NewMeetingGroupMemberJoinedDomainEvent>(meetingGroup);
meetingGroupCreated.MeetingGroupId.Should().Be(meetingProposal.Id);
newMeetingGroupMemberJoined.MemberId.Should().Be(proposalMemberId);
newMeetingGroupMemberJoined.Role.Should().Be(MeetingGroupMemberRole.Organizer);
}
}
} | MeetingGroupProposalTests |
csharp | dotnet__aspnetcore | src/Servers/Kestrel/Core/src/Internal/Http/HttpResponseTrailers.cs | {
"start": 352,
"end": 1566
} | internal partial class ____ : HttpHeaders
{
public Func<string, Encoding?> EncodingSelector { get; set; }
public HttpResponseTrailers(Func<string, Encoding?>? encodingSelector = null)
{
EncodingSelector = encodingSelector ?? KestrelServerOptions.DefaultHeaderEncodingSelector;
}
public Enumerator GetEnumerator()
{
return new Enumerator(this);
}
protected override IEnumerator<KeyValuePair<string, StringValues>> GetEnumeratorFast()
{
return GetEnumerator();
}
[MethodImpl(MethodImplOptions.NoInlining)]
private void SetValueUnknown(string key, StringValues value)
{
ValidateHeaderNameCharacters(key);
Unknown[GetInternedHeaderName(key)] = value;
}
[MethodImpl(MethodImplOptions.NoInlining)]
private bool AddValueUnknown(string key, StringValues value)
{
ValidateHeaderNameCharacters(key);
Unknown.Add(GetInternedHeaderName(key), value);
// Return true, above will throw and exit for false
return true;
}
public override StringValues HeaderConnection { get => throw new NotSupportedException(); set => throw new NotSupportedException(); }
| HttpResponseTrailers |
csharp | neuecc__MessagePack-CSharp | tests/MessagePack.SourceGenerator.Tests/Resources/GenericsUnionFormatter/MessagePack.GeneratedMessagePackResolver.g.cs | {
"start": 1230,
"end": 3185
} | private static class ____
{
private static readonly global::System.Collections.Generic.Dictionary<global::System.Type, int> closedTypeLookup = new global::System.Collections.Generic.Dictionary<global::System.Type, int>(4)
{
{ typeof(global::System.Collections.Generic.IEnumerable<global::System.Guid>), 0 },
{ typeof(global::TempProject.Wrapper<int[]>), 1 },
{ typeof(global::TempProject.Wrapper<string>), 2 },
{ typeof(global::TempProject.Wrapper<global::System.Collections.Generic.IEnumerable<global::System.Guid>>), 3 },
};
private static readonly global::System.Collections.Generic.Dictionary<global::System.Type, int> openTypeLookup = new global::System.Collections.Generic.Dictionary<global::System.Type, int>(1)
{
{ typeof(global::TempProject.Wrapper<>), 0 },
};
internal static object GetFormatter(global::System.Type t)
{
if (closedTypeLookup.TryGetValue(t, out int closedKey))
{
switch (closedKey)
{
case 0: return new MsgPack::Formatters.InterfaceEnumerableFormatter<global::System.Guid>();
case 1: return new global::MessagePack.GeneratedMessagePackResolver.TempProject.WrapperFormatter<int[]>();
case 2: return new global::MessagePack.GeneratedMessagePackResolver.TempProject.WrapperFormatter<string>();
case 3: return new global::MessagePack.GeneratedMessagePackResolver.TempProject.WrapperFormatter<global::System.Collections.Generic.IEnumerable<global::System.Guid>>();
default: return null; // unreachable
};
}
if (t.IsGenericType && openTypeLookup.TryGetValue(t.GetGenericTypeDefinition(), out int openKey))
{
switch (openKey)
{
case 0: return global::System.Activator.CreateInstance(typeof(global::MessagePack.GeneratedMessagePackResolver.TempProject.WrapperFormatter<>).MakeGenericType(t.GenericTypeArguments));
default: return null; // unreachable
};
}
return null;
}
}
}
}
| GeneratedMessagePackResolverGetFormatterHelper |
csharp | microsoft__semantic-kernel | dotnet/src/SemanticKernel.Abstractions/Memory/DataEntryBase.cs | {
"start": 211,
"end": 279
} | class ____ data entries.
/// </summary>
[Experimental("SKEXP0001")]
| for |
csharp | dotnet__efcore | test/EFCore.InMemory.FunctionalTests/Query/QueryBugsInMemoryTest.cs | {
"start": 47551,
"end": 47682
} | private class ____
{
public int Id { get; set; }
public List<C18394> PropertyCList { get; set; }
}
| B18394 |
csharp | DapperLib__Dapper | tests/Dapper.Tests/NullTests.cs | {
"start": 362,
"end": 2375
} | public abstract class ____<TProvider> : TestBase<TProvider> where TProvider : DatabaseProvider
{
[Fact]
public void TestNullableDefault()
{
TestNullable(false);
}
[Fact]
public void TestNullableApplyNulls()
{
TestNullable(true);
}
private void TestNullable(bool applyNulls)
{
bool oldSetting = SqlMapper.Settings.ApplyNullValues;
try
{
SqlMapper.Settings.ApplyNullValues = applyNulls;
SqlMapper.PurgeQueryCache();
var data = connection.Query<NullTestClass>(@"
declare @data table(Id int not null, A int null, B int null, C varchar(20), D int null, E int null)
insert @data (Id, A, B, C, D, E) values
(1,null,null,null,null,null),
(2,42,42,'abc',2,2)
select * from @data").ToDictionary(_ => _.Id);
var obj = data[2];
Assert.Equal(2, obj.Id);
Assert.Equal(42, obj.A);
Assert.Equal(42, obj.B);
Assert.Equal("abc", obj.C);
Assert.Equal(AnEnum.A, obj.D);
Assert.Equal(AnEnum.A, obj.E);
obj = data[1];
Assert.Equal(1, obj.Id);
if (applyNulls)
{
Assert.Equal(2, obj.A); // cannot be null
Assert.Null(obj.B);
Assert.Null(obj.C);
Assert.Equal(AnEnum.B, obj.D);
Assert.Null(obj.E);
}
else
{
Assert.Equal(2, obj.A);
Assert.Equal(2, obj.B);
Assert.Equal("def", obj.C);
Assert.Equal(AnEnum.B, obj.D);
Assert.Equal(AnEnum.B, obj.E);
}
}
finally
{
SqlMapper.Settings.ApplyNullValues = oldSetting;
}
}
| NullTests |
csharp | EventStore__EventStore | src/KurrentDB.Projections.Core.Tests/Services/event_reader/event_reader_core_service/when_handling_subscribe_requests.cs | {
"start": 3777,
"end": 5169
} | private class ____ : IReaderStrategy {
private readonly bool _throwOnCreateSubscription;
private readonly bool _throwOnCreatePausedReader;
private FakeReaderStrategyThatThrows(bool throwOnCreateSubscription, bool throwOnCreatePausedReader) {
_throwOnCreateSubscription = throwOnCreateSubscription;
_throwOnCreatePausedReader = throwOnCreatePausedReader;
}
public static FakeReaderStrategyThatThrows ThrowOnCreateReaderSubscription() => new(true, false);
public static FakeReaderStrategyThatThrows ThrowOnCreatePausedReader() => new(false, true);
public bool IsReadingOrderRepeatable { get; }
public EventFilter EventFilter { get; }
public PositionTagger PositionTagger { get; }
public IReaderSubscription CreateReaderSubscription(IPublisher publisher, CheckpointTag fromCheckpointTag, Guid subscriptionId,
ReaderSubscriptionOptions readerSubscriptionOptions) {
if (_throwOnCreateSubscription)
throw new ArgumentException(nameof(FakeReaderStrategyThatThrows));
if (_throwOnCreatePausedReader)
return new FakeReaderSubscriptionThatThrows();
return new FakeReaderSubscription();
}
public IEventReader CreatePausedEventReader(Guid eventReaderId, IPublisher publisher, IODispatcher ioDispatcher,
CheckpointTag checkpointTag, bool stopOnEof, int? stopAfterNEvents) {
throw new NotImplementedException();
}
}
| FakeReaderStrategyThatThrows |
csharp | Cysharp__UniTask | src/UniTask/Assets/Plugins/UniTask/Runtime/Linq/ToObservable.cs | {
"start": 138,
"end": 449
} | partial class ____
{
public static IObservable<TSource> ToObservable<TSource>(this IUniTaskAsyncEnumerable<TSource> source)
{
Error.ThrowArgumentNullException(source, nameof(source));
return new ToObservable<TSource>(source);
}
}
| UniTaskAsyncEnumerable |
csharp | EventStore__EventStore | src/KurrentDB.Surge.Tests/Components/Consumers/SystemConsumerTests.cs | {
"start": 9118,
"end": 10402
} | class ____ : TestCaseGeneratorXunit<ConsumeFilterCases> {
protected override IEnumerable<object[]> Data() {
var streamId = Identifiers.GenerateShortId("stream");
yield return [streamId, ConsumeFilter.FromStreamId(streamId)];
streamId = Guid.NewGuid().ToString();
yield return [streamId, ConsumeFilter.FromRegex(ConsumeFilterScope.Stream, new Regex(streamId))];
}
}
[Fact]
public async Task consumes_all_stream_and_handles_caught_up() {
// Arrange
// var streamId = Identifiers.GenerateShortId("stream");
var filter = ConsumeFilter.FromRegex(ConsumeFilterScope.Stream, new Regex(Identifiers.GenerateShortId()));
var requests = await Fixture.ProduceTestEvents(Identifiers.GenerateShortId("stream"), 1, 1000);
using var cancellator = new CancellationTokenSource(TimeSpan.FromSeconds(30));
var consumedRecords = new List<SurgeRecord>();
await using var consumer = Fixture.NewConsumer()
// .ConsumerId($"{streamId}-csr")
.Filter(filter)
.InitialPosition(SubscriptionInitialPosition.Earliest)
.DisableAutoCommit()
.AutoCommit(options => options with { RecordsThreshold = 100 })
.Create();
// Act
await foreach (var | ConsumeFilterCases |
csharp | jellyfin__jellyfin | Emby.Server.Implementations/Images/BaseFolderImageProvider.cs | {
"start": 537,
"end": 2323
} | public abstract class ____<T> : BaseDynamicImageProvider<T>
where T : Folder, new()
{
private readonly ILibraryManager _libraryManager;
protected BaseFolderImageProvider(IFileSystem fileSystem, IProviderManager providerManager, IApplicationPaths applicationPaths, IImageProcessor imageProcessor, ILibraryManager libraryManager)
: base(fileSystem, providerManager, applicationPaths, imageProcessor)
{
_libraryManager = libraryManager;
}
protected override IReadOnlyList<BaseItem> GetItemsWithImages(BaseItem item)
{
return _libraryManager.GetItemList(new InternalItemsQuery
{
Parent = item,
Recursive = true,
DtoOptions = new DtoOptions(true),
ImageTypes = [ImageType.Primary],
OrderBy =
[
(ItemSortBy.IsFolder, SortOrder.Ascending),
(ItemSortBy.SortName, SortOrder.Ascending)
],
Limit = 1
});
}
protected override string CreateImage(BaseItem item, IReadOnlyCollection<BaseItem> itemsWithImages, string outputPathWithoutExtension, ImageType imageType, int imageIndex)
{
return CreateSingleImage(itemsWithImages, outputPathWithoutExtension, ImageType.Primary);
}
protected override bool Supports(BaseItem item)
{
return item is T;
}
protected override bool HasChangedByDate(BaseItem item, ItemImageInfo image)
{
if (item is MusicAlbum)
{
return false;
}
return base.HasChangedByDate(item, image);
}
}
}
| BaseFolderImageProvider |
csharp | dotnet__efcore | test/EFCore.SqlServer.FunctionalTests/Query/ComplexNavigationsQuerySqlServerFixture.cs | {
"start": 205,
"end": 414
} | public class ____ : ComplexNavigationsQueryRelationalFixtureBase
{
protected override ITestStoreFactory TestStoreFactory
=> SqlServerTestStoreFactory.Instance;
}
| ComplexNavigationsQuerySqlServerFixture |
csharp | unoplatform__uno | src/Uno.Foundation/Generated/2.0.0.0/Windows.Foundation.Metadata/LengthIsAttribute.cs | {
"start": 262,
"end": 543
} | public partial class ____ : global::System.Attribute
{
// Skipping already declared method Windows.Foundation.Metadata.LengthIsAttribute.LengthIsAttribute(int)
// Forced skipping of method Windows.Foundation.Metadata.LengthIsAttribute.LengthIsAttribute(int)
}
}
| LengthIsAttribute |
csharp | duplicati__duplicati | Duplicati/Library/Interface/IBackend.cs | {
"start": 1844,
"end": 5286
} | public interface ____ : IDynamicModule, IDisposable
{
/// <summary>
/// The localized name to display for this backend
/// </summary>
string DisplayName { get; }
/// <summary>
/// The protocol key, e.g. ftp, http or ssh
/// </summary>
string ProtocolKey { get; }
/// <summary>
/// Enumerates a list of files found on the remote location
/// </summary>
/// <param name="cancellationToken">Token to cancel the operation.</param>
/// <returns>The list of files</returns>
IAsyncEnumerable<IFileEntry> ListAsync(CancellationToken cancellationToken);
/// <summary>
/// Puts the content of the file to the url passed
/// </summary>
/// <param name="remotename">The remote filename, relative to the URL</param>
/// <param name="filename">The local filename</param>
/// <param name="cancellationToken">Token to cancel the operation.</param>
Task PutAsync(string remotename, string filename, CancellationToken cancellationToken);
/// <summary>
/// Downloads a file with the remote data
/// </summary>
/// <param name="remotename">The remote filename, relative to the URL</param>
/// <param name="filename">The local filename</param>
/// <param name="cancellationToken">Token to cancel the operation.</param>
Task GetAsync(string remotename, string filename, CancellationToken cancellationToken);
/// <summary>
/// Deletes the specified file
/// </summary>
/// <param name="remotename">The remote filename, relative to the URL</param>
/// <param name="cancellationToken">Token to cancel the operation.</param>
Task DeleteAsync(string remotename, CancellationToken cancellationToken);
/// <summary>
/// A localized description of the backend, for display in the usage information
/// </summary>
string Description { get; }
/// <summary>
/// The DNS names used to resolve the IP addresses for this backend
/// </summary>
/// <param name="cancelToken">Token to cancel the operation.</param>
/// <returns>The DNS names</returns>
Task<string[]> GetDNSNamesAsync(CancellationToken cancelToken);
/// <summary>
/// The purpose of this method is to test the connection to the remote backend.
/// If any problem is encountered, this method should throw an exception.
/// If the encountered problem is a missing target "folder",
/// this method should throw a <see cref="FolderMissingException"/>.
/// </summary>
/// <param name="cancellationToken">Token to cancel the operation.</param>
Task TestAsync(CancellationToken cancellationToken);
/// <summary>
/// The purpose of this method is to create the underlying "folder".
/// This method will be invoked if the <see cref="Test"/> method throws a
/// <see cref="FolderMissingException"/>.
/// Backends that have no "folder" concept should not throw
/// a <see cref="FolderMissingException"/> during <see cref="Test"/>,
/// and this method should throw a <see cref="MissingMethodException"/>.
/// </summary>
Task CreateFolderAsync(CancellationToken cancellationToken);
}
}
| IBackend |
csharp | getsentry__sentry-dotnet | test/Sentry.Tests/Internals/MainExceptionProcessorTests.verify.cs | {
"start": 35,
"end": 378
} | public partial class ____
{
[Fact]
public Task CreateSentryException_Aggregate()
{
var sut = _fixture.GetSut();
var aggregateException = BuildAggregateException();
var sentryException = sut.CreateSentryExceptions(aggregateException);
return Verify(sentryException);
}
}
| MainExceptionProcessorTests |
csharp | ChilliCream__graphql-platform | src/HotChocolate/Language/src/Language.SyntaxTree/ObjectTypeExtensionNode.cs | {
"start": 354,
"end": 5631
} | public sealed class ____ : ComplexTypeDefinitionNodeBase, ITypeExtensionNode
{
/// <summary>
/// Initializes a new instance of <see cref="ObjectTypeExtensionNode"/>.
/// </summary>
/// <param name="location">
/// The location of the syntax node within the original source text.
/// </param>
/// <param name="name">
/// The name that this syntax node holds.
/// </param>
/// <param name="directives">
/// The directives that are annotated to this syntax node.
/// </param>
/// <param name="interfaces">
/// The interfaces that this type implements.
/// </param>
/// <param name="fields">
/// The fields that this type exposes.
/// </param>
public ObjectTypeExtensionNode(
Location? location,
NameNode name,
IReadOnlyList<DirectiveNode> directives,
IReadOnlyList<NamedTypeNode> interfaces,
IReadOnlyList<FieldDefinitionNode> fields)
: base(location, name, directives, interfaces, fields)
{
}
/// <inheritdoc />
public override SyntaxKind Kind => SyntaxKind.ObjectTypeExtension;
/// <inheritdoc />
public override IEnumerable<ISyntaxNode> GetNodes()
{
yield return Name;
foreach (var interfaceName in Interfaces)
{
yield return interfaceName;
}
foreach (var directive in Directives)
{
yield return directive;
}
foreach (var field in Fields)
{
yield return field;
}
}
/// <summary>
/// Returns the GraphQL syntax representation of this <see cref="ISyntaxNode"/>.
/// </summary>
/// <returns>
/// Returns the GraphQL syntax representation of this <see cref="ISyntaxNode"/>.
/// </returns>
public override string ToString() => SyntaxPrinter.Print(this, true);
/// <summary>
/// Returns the GraphQL syntax representation of this <see cref="ISyntaxNode"/>.
/// </summary>
/// <param name="indented">
/// A value that indicates whether the GraphQL output should be formatted,
/// which includes indenting nested GraphQL tokens, adding
/// new lines, and adding white space between property names and values.
/// </param>
/// <returns>
/// Returns the GraphQL syntax representation of this <see cref="ISyntaxNode"/>.
/// </returns>
public override string ToString(bool indented) => SyntaxPrinter.Print(this, indented);
/// <summary>
/// Creates a new node from the current instance and replaces the
/// <see cref="Location"/> with <paramref name="location"/>.
/// </summary>
/// <param name="location">
/// The location that shall be used to replace the current location.
/// </param>
/// <returns>
/// Returns the new node with the new <paramref name="location"/>
/// </returns>
public ObjectTypeExtensionNode WithLocation(Location? location)
=> new(location, Name, Directives, Interfaces, Fields);
/// <summary>
/// Creates a new node from the current instance and replaces the
/// <see cref="NameNode"/> with <paramref name="name"/>
/// </summary>
/// <param name="name">
/// The name that shall be used to replace the current name.
/// </param>
/// <returns>
/// Returns the new node with the new <paramref name="name"/>
/// </returns>
public ObjectTypeExtensionNode WithName(NameNode name)
=> new(Location, name, Directives, Interfaces, Fields);
/// <summary>
/// Creates a new node from the current instance and replaces the
/// <see cref="NamedSyntaxNode.Directives"/> with <paramref name="directives"/>
/// </summary>
/// <param name="directives">
/// The directives that shall be used to replace the current directives.
/// </param>
/// <returns>
/// Returns the new node with the new <paramref name="directives"/>
/// </returns>
public ObjectTypeExtensionNode WithDirectives(IReadOnlyList<DirectiveNode> directives)
=> new(Location, Name, directives, Interfaces, Fields);
/// <summary>
/// Creates a new node from the current instance and replaces the
/// <see cref="ComplexTypeDefinitionNodeBase.Interfaces"/> with <paramref name="interfaces"/>
/// </summary>
/// <param name="interfaces">
/// The interfaces that shall be used to replace the current interfaces.
/// </param>
/// <returns>
/// Returns the new node with the new <paramref name="interfaces"/>
/// </returns>
public ObjectTypeExtensionNode WithInterfaces(IReadOnlyList<NamedTypeNode> interfaces)
=> new(Location, Name, Directives, interfaces, Fields);
/// <summary>
/// Creates a new node from the current instance and replaces the
/// <see cref="ComplexTypeDefinitionNodeBase.Fields"/> with <paramref name="fields"/>
/// </summary>
/// <param name="fields">
/// The fields that shall be used to replace the current fields.
/// </param>
/// <returns>
/// Returns the new node with the new <paramref name="fields"/>
/// </returns>
public ObjectTypeExtensionNode WithFields(IReadOnlyList<FieldDefinitionNode> fields)
=> new(Location, Name, Directives, Interfaces, fields);
}
| ObjectTypeExtensionNode |
csharp | dotnet__orleans | src/api/Orleans.Runtime/Orleans.Runtime.cs | {
"start": 71509,
"end": 73287
} | partial class ____ : global::Orleans.Serialization.Codecs.IFieldCodec<global::Orleans.Runtime.MembershipService.OrleansClusterConnectivityCheckFailedException>, global::Orleans.Serialization.Codecs.IFieldCodec
{
public Codec_OrleansClusterConnectivityCheckFailedException(global::Orleans.Serialization.Serializers.ICodecProvider codecProvider) { }
public void Deserialize<TReaderInput>(ref global::Orleans.Serialization.Buffers.Reader<TReaderInput> reader, global::Orleans.Runtime.MembershipService.OrleansClusterConnectivityCheckFailedException instance) { }
public global::Orleans.Runtime.MembershipService.OrleansClusterConnectivityCheckFailedException ReadValue<TReaderInput>(ref global::Orleans.Serialization.Buffers.Reader<TReaderInput> reader, global::Orleans.Serialization.WireProtocol.Field field) { throw null; }
public void Serialize<TBufferWriter>(ref global::Orleans.Serialization.Buffers.Writer<TBufferWriter> writer, global::Orleans.Runtime.MembershipService.OrleansClusterConnectivityCheckFailedException instance)
where TBufferWriter : System.Buffers.IBufferWriter<byte> { }
public void WriteField<TBufferWriter>(ref global::Orleans.Serialization.Buffers.Writer<TBufferWriter> writer, uint fieldIdDelta, System.Type expectedType, global::Orleans.Runtime.MembershipService.OrleansClusterConnectivityCheckFailedException value)
where TBufferWriter : System.Buffers.IBufferWriter<byte> { }
}
[System.CodeDom.Compiler.GeneratedCode("OrleansCodeGen", "9.0.0.0")]
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
[System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverage]
public sealed | Codec_OrleansClusterConnectivityCheckFailedException |
csharp | SixLabors__ImageSharp | tests/ImageSharp.Benchmarks/Color/ColorspaceCieXyzToCieLabConvert.cs | {
"start": 273,
"end": 1016
} | public class ____
{
private static readonly CieXyz CieXyz = new(0.95047F, 1, 1.08883F);
private static readonly XYZColor XYZColor = new(0.95047, 1, 1.08883);
private static readonly ColorProfileConverter ColorProfileConverter = new();
private static readonly IColorConverter<XYZColor, LabColor> ColourfulConverter = new ConverterBuilder().FromXYZ(Illuminants.D50).ToLab(Illuminants.D50).Build();
[Benchmark(Baseline = true, Description = "Colourful Convert")]
public double ColourfulConvert() => ColourfulConverter.Convert(XYZColor).L;
[Benchmark(Description = "ImageSharp Convert")]
public float ColorSpaceConvert() => ColorProfileConverter.Convert<CieXyz, CieLab>(CieXyz).L;
}
| ColorspaceCieXyzToCieLabConvert |
csharp | grpc__grpc-dotnet | src/Grpc.Core.Api/CallInvoker.cs | {
"start": 1876,
"end": 2333
} | class
____ TResponse : class;
/// <summary>
/// Invokes a client streaming call asynchronously.
/// In client streaming scenario, client sends a stream of requests and server responds with a single response.
/// </summary>
public abstract AsyncClientStreamingCall<TRequest, TResponse> AsyncClientStreamingCall<TRequest, TResponse>(Method<TRequest, TResponse> method, string? host, CallOptions options)
where TRequest : | where |
csharp | dotnet__extensions | test/Generators/Microsoft.Gen.Logging/Unit/ParserTests.LogMethod.cs | {
"start": 7036,
"end": 7733
} | partial class ____
{
public ILogger _logger;
[LoggerMessage]
public partial void M1(LogLevel level, Exception ex);
[LoggerMessage(LogLevel.Debug)]
public partial void M2(Exception ex);
[LoggerMessage]
public static partial void M3(ILogger logger, LogLevel level, Exception ex);
[LoggerMessage(LogLevel.Debug)]
public static partial void M4(ILogger logger, Exception ex);
}");
}
[Fact]
public async Task NotPartial()
{
const string Source = @"
| C |
csharp | abpframework__abp | framework/src/Volo.Abp.Ddd.Application.Contracts/Volo/Abp/Application/Services/ICreateUpdateAppService.cs | {
"start": 362,
"end": 593
} | public interface ____<TGetOutputDto, in TKey, in TCreateUpdateInput, in TUpdateInput>
: ICreateAppService<TGetOutputDto, TCreateUpdateInput>,
IUpdateAppService<TGetOutputDto, TKey, TUpdateInput>
{
}
| ICreateUpdateAppService |
csharp | dotnet__extensions | src/Libraries/Microsoft.Extensions.Options.Contextual/Internal/ConfigureContextualOptions.cs | {
"start": 468,
"end": 1588
} | internal sealed class ____<TOptions> : IConfigureContextualOptions<TOptions>
where TOptions : class
{
private readonly IOptionsContext _context;
/// <summary>
/// Initializes a new instance of the <see cref="ConfigureContextualOptions{TOptions}"/> class.
/// </summary>
/// <param name="configureOptions">The action to apply to configure options.</param>
/// <param name="context">The context used to configure the options.</param>
public ConfigureContextualOptions(Action<IOptionsContext, TOptions> configureOptions, IOptionsContext context)
{
ConfigureOptions = configureOptions;
_context = context;
}
/// <summary>
/// Gets the delegate used to configure options instances.
/// </summary>
public Action<IOptionsContext, TOptions> ConfigureOptions { get; }
/// <inheritdoc/>
public void Configure(TOptions options) => ConfigureOptions(_context, Throw.IfNull(options));
/// <summary>
/// Does nothing.
/// </summary>
public void Dispose()
{
// Method intentionally left empty.
}
}
| ConfigureContextualOptions |
csharp | AutoMapper__AutoMapper | src/IntegrationTests/ExplicitExpansion/MembersToExpandExpressions.cs | {
"start": 222,
"end": 341
} | public class ____
{
public int Desc { get; set; }
public int Id { get; set; }
}
| SourceDeepInner |
csharp | ChilliCream__graphql-platform | src/HotChocolate/Core/src/Validation/Rules/MaxAllowedFieldCycleDepthVisitor.cs | {
"start": 503,
"end": 2283
} | internal sealed class ____(
ImmutableArray<(SchemaCoordinate Coordinate, ushort MaxAllowed)> coordinateCycleLimits,
ushort? defaultCycleLimit)
: TypeDocumentValidatorVisitor
{
protected override ISyntaxVisitorAction Enter(
DocumentNode node,
DocumentValidatorContext context)
{
context.InitializeFieldDepth(coordinateCycleLimits, defaultCycleLimit);
return base.Enter(node, context);
}
protected override ISyntaxVisitorAction Enter(
FieldNode node,
DocumentValidatorContext context)
{
if (IntrospectionFieldNames.TypeName.Equals(node.Name.Value, StringComparison.Ordinal))
{
return Skip;
}
if (context.Types.TryPeek(out var type)
&& type.NamedType() is IComplexTypeDefinition ot
&& ot.Fields.TryGetField(node.Name.Value, out var of))
{
// we are ignoring introspection fields in this visitor.
if (of.IsIntrospectionField)
{
return Skip;
}
if (!context.FieldDepth().Add(of.Coordinate))
{
context.ReportMaxCoordinateCycleDepthOverflow(node);
return Break;
}
context.OutputFields.Push(of);
context.Types.Push(of.Type);
return Continue;
}
context.UnexpectedErrorsDetected = true;
return Skip;
}
protected override ISyntaxVisitorAction Leave(
FieldNode node,
DocumentValidatorContext context)
{
context.FieldDepth().Remove(context.OutputFields.Peek().Coordinate);
context.Types.Pop();
context.OutputFields.Pop();
return Continue;
}
}
file | MaxAllowedFieldCycleDepthVisitor |
csharp | ChilliCream__graphql-platform | src/HotChocolate/Fusion-vnext/src/Fusion.Execution/DependencyInjection/CoreFusionGatewayBuilderExtensions.Parser.cs | {
"start": 145,
"end": 609
} | partial class ____
{
public static IFusionGatewayBuilder ModifyParserOptions(
this IFusionGatewayBuilder builder,
Action<FusionParserOptions> configure)
{
ArgumentNullException.ThrowIfNull(builder);
ArgumentNullException.ThrowIfNull(configure);
return FusionSetupUtilities.Configure(
builder,
options => options.ParserOptionsModifiers.Add(configure));
}
}
| CoreFusionGatewayBuilderExtensions |
csharp | dotnetcore__CAP | src/DotNetCore.CAP/Internal/ISubscribeExector.Default.cs | {
"start": 566,
"end": 2632
} | internal class ____ : ISubscribeExecutor
{
// diagnostics listener
// ReSharper disable once InconsistentNaming
private static readonly DiagnosticListener s_diagnosticListener =
new(CapDiagnosticListenerNames.DiagnosticListenerName);
private readonly IDataStorage _dataStorage;
private readonly string? _hostName;
private readonly ILogger _logger;
private readonly CapOptions _options;
private readonly IServiceProvider _provider;
public SubscribeExecutor(
ILogger<SubscribeExecutor> logger,
IOptions<CapOptions> options,
IServiceProvider provider)
{
_provider = provider;
_logger = logger;
_options = options.Value;
_dataStorage = _provider.GetRequiredService<IDataStorage>();
Invoker = _provider.GetRequiredService<ISubscribeInvoker>();
_hostName = Helper.GetInstanceHostname();
}
private ISubscribeInvoker Invoker { get; }
public async Task<OperateResult> ExecuteAsync(MediumMessage message, ConsumerExecutorDescriptor? descriptor = null, CancellationToken cancellationToken = default)
{
if (descriptor == null)
{
var selector = _provider.GetRequiredService<MethodMatcherCache>();
if (!selector.TryGetTopicExecutor(message.Origin.GetName(), message.Origin.GetGroup()!, out descriptor))
{
var error =
$"Message (Name:{message.Origin.GetName()},Group:{message.Origin.GetGroup()}) can not be found subscriber." +
$"{Environment.NewLine} see: https://github.com/dotnetcore/CAP/issues/63";
_logger.LogError(error);
TracingError(DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(), message.Origin, null, new Exception(error));
var ex = new SubscriberNotFoundException(error);
await SetFailedState(message, ex);
return OperateResult.Failed(ex);
}
}
bool retry;
OperateResult result;
// | SubscribeExecutor |
csharp | icsharpcode__ILSpy | ICSharpCode.Decompiler.Tests/TestCases/Pretty/TypeMemberTests.cs | {
"start": 10318,
"end": 10484
} | public class ____ : T26_B_HideMembers4
{
public void M<T1, T2>()
{
}
public new void M1<R>()
{
}
public new void M2<R>(R r)
{
}
}
| T26_B1_HideMembers4 |
csharp | dotnet__orleans | src/Orleans.Runtime/Facet/Persistent/PersistentStateStorageFactory.cs | {
"start": 2069,
"end": 3151
} | internal sealed class ____<TState> : StateStorageBridge<TState>, IPersistentState<TState>, ILifecycleObserver
{
public PersistentState(string stateName, IGrainContext context, IGrainStorage storageProvider) : base(stateName, context, storageProvider)
{
var lifecycle = context.ObservableLifecycle;
lifecycle.Subscribe(RuntimeTypeNameFormatter.Format(GetType()), GrainLifecycleStage.SetupState, this);
lifecycle.AddMigrationParticipant(this);
}
public Task OnStart(CancellationToken cancellationToken = default)
{
if (cancellationToken.IsCancellationRequested)
{
return Task.CompletedTask;
}
// No need to load state if it has been loaded already via rehydration.
if (IsStateInitialized)
{
return Task.CompletedTask;
}
return ReadStateAsync();
}
public Task OnStop(CancellationToken cancellationToken = default) => Task.CompletedTask;
}
}
| PersistentState |
csharp | dotnet__maui | src/Controls/src/Core/Shell/MenuShellItem.cs | {
"start": 242,
"end": 2453
} | internal class ____ : ShellItem, IMenuItemController, IStyleSelectable
{
internal MenuShellItem(MenuItem menuItem)
{
MenuItem = menuItem;
MenuItem.Parent = this;
Shell.SetFlyoutItemIsVisible(this, Shell.GetFlyoutItemIsVisible(menuItem));
this.SetBinding(TitleProperty, static (MenuItem item) => item.Text, BindingMode.OneWay, source: menuItem);
this.SetBinding(IconProperty, static (MenuItem item) => item.IconImageSource, BindingMode.OneWay, source: menuItem);
this.SetBinding(FlyoutIconProperty, static (MenuItem item) => item.IconImageSource, BindingMode.OneWay, source: menuItem);
this.SetBinding(AutomationIdProperty, static (MenuItem item) => item.AutomationId, BindingMode.OneWay, source: menuItem);
MenuItem.PropertyChanged += OnMenuItemPropertyChanged;
}
IList<string> IStyleSelectable.Classes => ((IStyleSelectable)MenuItem).Classes;
public string Text => Title;
void OnMenuItemPropertyChanged(object sender, PropertyChangedEventArgs e)
{
if (e.PropertyName == Shell.MenuItemTemplateProperty.PropertyName)
Shell.SetMenuItemTemplate(this, Shell.GetMenuItemTemplate(MenuItem));
else if (e.PropertyName == TitleProperty.PropertyName)
OnPropertyChanged(MenuItem.TextProperty.PropertyName);
else if (e.PropertyName == Shell.FlyoutItemIsVisibleProperty.PropertyName)
Shell.SetFlyoutItemIsVisible(this, Shell.GetFlyoutItemIsVisible(MenuItem));
}
protected override void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
base.OnPropertyChanged(propertyName);
if (propertyName == nameof(Title))
OnPropertyChanged(nameof(Text));
else if (propertyName == Shell.FlyoutItemIsVisibleProperty.PropertyName && MenuItem != null)
Shell.SetFlyoutItemIsVisible(MenuItem, Shell.GetFlyoutItemIsVisible(this));
}
public MenuItem MenuItem { get; }
bool IMenuItemController.IsEnabled { get => MenuItem.IsEnabled; set => MenuItem.IsEnabled = value; }
void IMenuItemController.Activate()
{
(MenuItem as IMenuItemController).Activate();
}
protected override void OnBindingContextChanged()
{
base.OnBindingContextChanged();
SetInheritedBindingContext(MenuItem, BindingContext);
}
}
}
| MenuShellItem |
csharp | dotnetcore__FreeSql | FreeSql.Tests/FreeSql.Tests.DbContext/RepositoryTests02.cs | {
"start": 252,
"end": 2811
} | public class ____
{
[Fact]
public void TestMethod1()
{
using (IFreeSql fsql = new FreeSql.FreeSqlBuilder()
.UseConnectionString(FreeSql.DataType.Sqlite, @"Data Source=:memory:")
.UseMonitorCommand(cmd => Trace.WriteLine($"Sql:{cmd.CommandText}"))//监听SQL语句
.UseAutoSyncStructure(true) //自动同步实体结构到数据库,FreeSql不会扫描程序集,只有CRUD时才会生成表。
.Build())
{
fsql.GlobalFilter.ApplyIf<User>("TenantFilter", () => TenantManager.Current > 0, a => a.TenantId == TenantManager.Current);
fsql.Aop.AuditValue += (_, e) =>
{
if (TenantManager.Current > 0 && e.Property.PropertyType == typeof(int) && e.Property.Name == "TenantId")
{
e.Value = TenantManager.Current;
};
};
IBaseRepository<User> resp = fsql.GetRepository<User>();
resp.Delete(a => a.ID != null);
Assert.True(resp != null);
TenantManager.Current = 1;
resp.InsertOrUpdate(new User()
{
uname = "zhaoqin",
});
resp.InsertOrUpdate(new User()
{
uname = "wanghuan",
});
long cc = resp.Where(a => a.ID != null).Count();
Assert.True(cc == 2);
TenantManager.Current = 2;
resp.InsertOrUpdate(new User()
{
uname = "zhaoqin1",
});
resp.InsertOrUpdate(new User()
{
uname = "wanghuan1",
});
long c = resp.Where(a => a.ID != null).Count();
Assert.True(c == 2);
TenantManager.Current = 0;
Assert.True(resp.Where(a => a.ID != null).Count() == 4);
//多租户启用,但表达式想取消,这个可以成功
TenantManager.Current = 2;
long count1 = fsql.Select<User>().DisableGlobalFilter().Count();
Assert.True(count1 == 4);
Console.WriteLine("仓储的过滤器禁止,但不成功.");
//仓储的过滤器禁止,但不成功.
//using (resp.DataFilter.DisableAll())
//{
// long count2 = resp.Where(a => a.ID != null).Count();
// Assert.True(count2 == 4);
//}
}
}
| RepositoryTests02 |
csharp | ShareX__ShareX | ShareX.UploadersLib/FileUploaders/Dropbox.cs | {
"start": 19869,
"end": 20007
} | public class ____
{
public string id { get; set; }
public string name { get; set; }
}
| DropboxLinkMetadataTeamInfo |
csharp | dotnet__orleans | test/Orleans.Serialization.UnitTests/BuiltInCodecTests.cs | {
"start": 149186,
"end": 149610
} | public class ____(ITestOutputHelper output) : FieldCodecTester<FSharpOption<Guid>, FSharpOptionCodec<Guid>>(output)
{
protected override FSharpOption<Guid>[] TestValues => [null, FSharpOption<Guid>.None, FSharpOption<Guid>.Some(Guid.Empty), FSharpOption<Guid>.Some(Guid.NewGuid())];
protected override FSharpOption<Guid> CreateValue() => FSharpOption<Guid>.Some(Guid.NewGuid());
}
| FSharpOptionTests |
csharp | dotnet__aspnetcore | src/Identity/EntityFrameworkCore/test/EF.Test/UserOnlyCustomContextTest.cs | {
"start": 504,
"end": 640
} | public class ____ : IClassFixture<ScratchDatabaseFixture>
{
private readonly ApplicationBuilder _builder;
| UserOnlyCustomContextTest |
csharp | MassTransit__MassTransit | tests/MassTransit.Tests/SagaStateMachineTests/Automatonymous/AnyStateTransition_Specs.cs | {
"start": 995,
"end": 1283
} | class ____ :
SagaStateMachineInstance
{
public State CurrentState { get; set; }
public State LastEntered { get; set; }
public State LastLeft { get; set; }
public Guid CorrelationId { get; set; }
}
| Instance |
csharp | duplicati__duplicati | Duplicati/Library/Main/Operation/TestHandler.cs | {
"start": 1524,
"end": 25222
} | internal class ____
{
/// <summary>
/// The tag used for logging
/// </summary>
private static readonly string LOGTAG = Logging.Log.LogTagFromType<TestHandler>();
private readonly Options m_options;
private readonly TestResults m_result;
public TestHandler(Options options, TestResults results)
{
m_options = options;
m_result = results;
}
public async Task RunAsync(long samples, IBackendManager backendManager)
{
if (!System.IO.File.Exists(m_options.Dbpath))
throw new UserInformationException(LC.L("Database file does not exist: {0}", m_options.Dbpath), "DatabaseDoesNotExist");
await using var db = await LocalTestDatabase.CreateAsync(m_options.Dbpath, null, m_result.TaskControl.ProgressToken).ConfigureAwait(false);
await Utility.UpdateOptionsFromDb(db, m_options, m_result.TaskControl.ProgressToken)
.ConfigureAwait(false);
await Utility.VerifyOptionsAndUpdateDatabase(db, m_options, m_result.TaskControl.ProgressToken)
.ConfigureAwait(false);
await db
.VerifyConsistency(m_options.Blocksize, m_options.BlockhashSize, !m_options.DisableFilelistConsistencyChecks, m_result.TaskControl.ProgressToken)
.ConfigureAwait(false);
await FilelistProcessor.VerifyRemoteList(backendManager, m_options, db, m_result.BackendWriter, latestVolumesOnly: true, verifyMode: FilelistProcessor.VerifyMode.VerifyOnly, m_result.TaskControl.ProgressToken).ConfigureAwait(false);
await DoRunAsync(samples, db, backendManager).ConfigureAwait(false);
await db.Transaction
.CommitAsync("TestHandlerComplete")
.ConfigureAwait(false);
}
public async Task DoRunAsync(long samples, LocalTestDatabase db, IBackendManager backend)
{
var files = await db
.SelectTestTargets(samples, m_options, m_result.TaskControl.ProgressToken)
.ToListAsync(cancellationToken: m_result.TaskControl.ProgressToken)
.ConfigureAwait(false);
m_result.OperationProgressUpdater.UpdatePhase(OperationPhase.Verify_Running);
m_result.OperationProgressUpdater.UpdateProgress(0);
var progress = 0L;
if (m_options.FullRemoteVerification != Options.RemoteTestStrategy.False)
{
var faultyIndexFiles = new List<IRemoteVolume>();
await foreach (var (tf, hash, size, name) in backend.GetFilesOverlappedAsync(files, m_result.TaskControl.ProgressToken).ConfigureAwait(false))
{
var vol = new RemoteVolume(name, hash, size);
try
{
if (!await m_result.TaskControl.ProgressRendevouz().ConfigureAwait(false))
{
await backend.WaitForEmptyAsync(db, m_result.TaskControl.ProgressToken).ConfigureAwait(false);
m_result.EndTime = DateTime.UtcNow;
return;
}
progress++;
m_result.OperationProgressUpdater.UpdateProgress((float)progress / files.Count);
KeyValuePair<string, IEnumerable<KeyValuePair<TestEntryStatus, string>>> res;
using (tf)
res = await TestVolumeInternals(db, vol, tf, m_options, m_options.FullBlockVerification ? 1.0 : 0.2, m_result.TaskControl.ProgressToken)
.ConfigureAwait(false);
var parsedInfo = VolumeBase.ParseFilename(vol.Name);
if (parsedInfo.FileType == RemoteVolumeType.Index)
{
if (res.Value.Any(x => x.Key == TestEntryStatus.Extra))
{
// Bad hack, but for now, the index files sometimes have extra blocklist hashes
Logging.Log.WriteVerboseMessage(LOGTAG, "IndexFileExtraBlocks", null, LC.L("Index file {0} has extra blocks", vol.Name));
res = new KeyValuePair<string, IEnumerable<KeyValuePair<TestEntryStatus, string>>>(
res.Key, res.Value.Where(x => x.Key != TestEntryStatus.Extra).ToList()
);
}
if (res.Value.Any(x => x.Key == TestEntryStatus.Missing || x.Key == TestEntryStatus.Modified))
faultyIndexFiles.Add(vol);
}
m_result.AddResult(res.Key, res.Value);
if (!string.IsNullOrWhiteSpace(vol.Hash) && vol.Size > 0)
{
if (res.Value == null || !res.Value.Any())
{
var rv = await db
.GetRemoteVolume(vol.Name, m_result.TaskControl.ProgressToken)
.ConfigureAwait(false);
if (rv.ID < 0)
{
if (string.IsNullOrWhiteSpace(rv.Hash) || rv.Size <= 0)
{
if (m_options.Dryrun)
{
Logging.Log.WriteDryrunMessage(LOGTAG, "CaptureHashAndSize", LC.L("Successfully captured hash and size for {0}, would update database", vol.Name));
}
else
{
Logging.Log.WriteInformationMessage(LOGTAG, "CaptureHashAndSize", LC.L("Successfully captured hash and size for {0}, updating database", vol.Name));
await db
.UpdateRemoteVolume(vol.Name, RemoteVolumeState.Verified, vol.Size, vol.Hash, m_result.TaskControl.ProgressToken)
.ConfigureAwait(false);
}
}
}
}
}
await db
.UpdateVerificationCount(vol.Name, m_result.TaskControl.ProgressToken)
.ConfigureAwait(false);
}
catch (Exception ex)
{
m_result.AddResult(vol.Name, [new KeyValuePair<TestEntryStatus, string>(TestEntryStatus.Error, ex.Message)]);
Logging.Log.WriteErrorMessage(LOGTAG, "RemoteFileProcessingFailed", ex, LC.L("Failed to process file {0}", vol.Name));
if (ex.IsAbortException())
{
m_result.EndTime = DateTime.UtcNow;
throw;
}
}
}
if (faultyIndexFiles.Any())
{
if (m_options.ReplaceFaultyIndexFiles)
{
Logging.Log.WriteWarningMessage(LOGTAG, "FaultyIndexFiles", null, LC.L("Found {0} faulty index files, repairing now", faultyIndexFiles.Count));
await ReplaceFaultyIndexFilesAsync(faultyIndexFiles, backend, db, m_result.TaskControl.ProgressToken).ConfigureAwait(false);
}
else
Logging.Log.WriteWarningMessage(LOGTAG, "FaultyIndexFiles", null, LC.L("Found {0} faulty index files, remove the option {1} to repair them", faultyIndexFiles.Count, "--dont-replace-faulty-index-files"));
}
}
else
{
foreach (var f in files)
{
try
{
if (!await m_result.TaskControl.ProgressRendevouz().ConfigureAwait(false))
{
m_result.EndTime = DateTime.UtcNow;
return;
}
progress++;
m_result.OperationProgressUpdater.UpdateProgress((float)progress / files.Count);
if (f.Size <= 0 || string.IsNullOrWhiteSpace(f.Hash))
{
Logging.Log.WriteInformationMessage(LOGTAG, "MissingRemoteHash", LC.L("No hash or size recorded for {0}, performing full verification", f.Name));
KeyValuePair<string, IEnumerable<KeyValuePair<TestEntryStatus, string>>> res;
(var tf, var hash, var size) = await backend.GetWithInfoAsync(f.Name, f.Hash, f.Size, m_result.TaskControl.ProgressToken).ConfigureAwait(false);
using (tf)
res = await TestVolumeInternals(db, f, tf, m_options, 1, m_result.TaskControl.ProgressToken)
.ConfigureAwait(false);
m_result.AddResult(res.Key, res.Value);
if (!string.IsNullOrWhiteSpace(hash) && size > 0)
{
if (res.Value == null || !res.Value.Any())
{
if (m_options.Dryrun)
{
Logging.Log.WriteDryrunMessage(LOGTAG, "CapturedHashAndSize", LC.L("Successfully captured hash and size for {0}, would update database", f.Name));
}
else
{
Logging.Log.WriteInformationMessage(LOGTAG, "CapturedHashAndSize", LC.L("Successfully captured hash and size for {0}, updating database", f.Name));
await db
.UpdateRemoteVolume(f.Name, RemoteVolumeState.Verified, size, hash, m_result.TaskControl.ProgressToken)
.ConfigureAwait(false);
}
}
}
}
else
{
using (var tf = await backend.GetAsync(f.Name, f.Hash, f.Size, m_result.TaskControl.ProgressToken).ConfigureAwait(false))
{ }
}
await db
.UpdateVerificationCount(f.Name, m_result.TaskControl.ProgressToken)
.ConfigureAwait(false);
m_result.AddResult(f.Name, []);
}
catch (Exception ex)
{
m_result.AddResult(f.Name, [new KeyValuePair<TestEntryStatus, string>(TestEntryStatus.Error, ex.Message)]);
Logging.Log.WriteErrorMessage(LOGTAG, "FailedToProcessFile", ex, LC.L("Failed to process file {0}", f.Name));
if (ex.IsAbortOrCancelException())
{
m_result.EndTime = DateTime.UtcNow;
throw;
}
}
}
}
m_result.EndTime = DateTime.UtcNow;
// generate a backup error status when any test is failing - except for 'extra' status
// because these problems don't block database rebuilding.
var filtered = from n in m_result.Verifications where n.Value.Any(x => x.Key != TestEntryStatus.Extra) select n;
if (!filtered.Any())
{
Logging.Log.WriteInformationMessage(LOGTAG, "Test results", LC.L("Successfully verified {0} remote files", m_result.VerificationsActualLength));
}
else
{
Logging.Log.WriteErrorMessage(LOGTAG, "Test results", null, LC.L("Verified {0} remote files with {1} problem(s)", m_result.VerificationsActualLength, filtered.Count()));
}
}
/// <summary>
/// Tests the volume by examining the internal contents.
/// </summary>
/// <param name="db">The local test database to use for verification.</param>
/// <param name="vol">The remote volume being examined.</param>
/// <param name="tf">The path to the downloaded copy of the file.</param>
/// <param name="options">The options to use for the test.</param>
/// <param name="sample_percent">A value between 0 and 1 that indicates how many blocks are tested in a dblock file.</param>
/// <param name="cancellationToken">A cancellation token to cancel the operation.</param>
/// <returns>A task that when awaited returns a key-value pair where the key is the volume name and the value is a list of test results.</returns>
public static async Task<KeyValuePair<string, IEnumerable<KeyValuePair<TestEntryStatus, string>>>> TestVolumeInternals(LocalTestDatabase db, IRemoteVolume vol, string tf, Options options, double sample_percent, CancellationToken cancellationToken)
{
var hashsize = HashFactory.HashSizeBytes(options.BlockHashAlgorithm);
var parsedInfo = Volumes.VolumeBase.ParseFilename(vol.Name);
sample_percent = Math.Min(1, Math.Max(sample_percent, 0.01));
switch (parsedInfo.FileType)
{
case RemoteVolumeType.Files:
//Compare with db and see if all files are accounted for
// with correct file hashes and blocklist hashes
await using (var fl = await db.CreateFilelist(vol.Name, cancellationToken).ConfigureAwait(false))
{
using (var rd = new Volumes.FilesetVolumeReader(parsedInfo.CompressionModule, tf, options))
foreach (var f in rd.Files)
await fl
.Add(f.Path, f.Size, f.Hash, f.Metasize, f.Metahash, f.BlocklistHashes, f.Type, f.Time, cancellationToken)
.ConfigureAwait(false);
return new KeyValuePair<string, IEnumerable<KeyValuePair<TestEntryStatus, string>>>(vol.Name, await fl.Compare(cancellationToken).ToListAsync(cancellationToken: cancellationToken).ConfigureAwait(false));
}
case RemoteVolumeType.Index:
var blocklinks = new List<Tuple<string, string, long>>();
var combined = new List<KeyValuePair<Duplicati.Library.Interface.TestEntryStatus, string>>();
//Compare with db and see that all hashes and volumes are listed
using (var rd = new Volumes.IndexVolumeReader(parsedInfo.CompressionModule, tf, options, hashsize))
{
foreach (var v in rd.Volumes)
{
blocklinks.Add(new Tuple<string, string, long>(v.Filename, v.Hash, v.Length));
await using (var bl = await db.CreateBlocklist(v.Filename, cancellationToken).ConfigureAwait(false))
{
foreach (var h in v.Blocks)
await bl
.AddBlock(h.Key, h.Value, cancellationToken)
.ConfigureAwait(false);
combined.AddRange(
await bl
.Compare(cancellationToken)
.ToListAsync(cancellationToken: cancellationToken)
.ConfigureAwait(false)
);
}
}
if (options.IndexfilePolicy == Options.IndexFileStrategy.Full)
{
var hashesPerBlock = options.Blocksize / options.BlockhashSize;
await using (var bl = await db.CreateBlocklistHashList(vol.Name, cancellationToken).ConfigureAwait(false))
{
foreach (var b in rd.BlockLists)
await bl
.AddBlockHash(b.Hash, b.Length, cancellationToken)
.ConfigureAwait(false);
combined.AddRange(
await bl
.Compare(hashesPerBlock, options.BlockhashSize, options.Blocksize, cancellationToken)
.ToListAsync(cancellationToken: cancellationToken)
.ConfigureAwait(false)
);
}
}
}
// Compare with db and see that all blocklists are listed
await using (var il = await db.CreateIndexlist(vol.Name, cancellationToken).ConfigureAwait(false))
{
foreach (var t in blocklinks)
await il
.AddBlockLink(t.Item1, t.Item2, t.Item3, cancellationToken)
.ConfigureAwait(false);
combined.AddRange(
await il
.Compare(cancellationToken)
.ToArrayAsync(cancellationToken: cancellationToken)
.ConfigureAwait(false)
);
}
return new KeyValuePair<string, IEnumerable<KeyValuePair<TestEntryStatus, string>>>(vol.Name, combined);
case RemoteVolumeType.Blocks:
using (var blockhasher = HashFactory.CreateHasher(options.BlockHashAlgorithm))
await using (var bl = await db.CreateBlocklist(vol.Name, cancellationToken).ConfigureAwait(false))
using (var rd = new Volumes.BlockVolumeReader(parsedInfo.CompressionModule, tf, options))
{
//Verify that all blocks are in the file
foreach (var b in rd.Blocks)
await bl
.AddBlock(b.Key, b.Value, cancellationToken)
.ConfigureAwait(false);
//Select random blocks and verify their hashes match the filename and size
var hashsamples = new List<KeyValuePair<string, long>>(rd.Blocks);
var sampleCount = Math.Min(Math.Max(0, (int)(hashsamples.Count * sample_percent)), hashsamples.Count - 1);
var rnd = new Random();
while (hashsamples.Count > sampleCount)
hashsamples.RemoveAt(rnd.Next(hashsamples.Count));
var blockbuffer = new byte[options.Blocksize];
var changes = new List<KeyValuePair<Library.Interface.TestEntryStatus, string>>();
foreach (var s in hashsamples)
{
var size = rd.ReadBlock(s.Key, blockbuffer);
if (size != s.Value)
changes.Add(new KeyValuePair<Library.Interface.TestEntryStatus, string>(Library.Interface.TestEntryStatus.Modified, s.Key));
else
{
var hash = Convert.ToBase64String(blockhasher.ComputeHash(blockbuffer, 0, size));
if (hash != s.Key)
changes.Add(new KeyValuePair<Library.Interface.TestEntryStatus, string>(Library.Interface.TestEntryStatus.Modified, s.Key));
}
}
return new KeyValuePair<string, IEnumerable<KeyValuePair<TestEntryStatus, string>>>(
vol.Name,
changes.Union(
await bl
.Compare(cancellationToken)
.ToListAsync(cancellationToken: cancellationToken)
.ConfigureAwait(false)
)
);
}
}
Logging.Log.WriteWarningMessage(LOGTAG, "UnexpectedFileType", null, LC.L("Unexpected file type {0} for {1}", parsedInfo.FileType, vol.Name));
return new KeyValuePair<string, IEnumerable<KeyValuePair<TestEntryStatus, string>>>(vol.Name, null);
}
private async Task ReplaceFaultyIndexFilesAsync(List<IRemoteVolume> faultyIndexFiles, IBackendManager backendManager, LocalTestDatabase db, CancellationToken cancellationToken)
{
await using var repairdb =
await LocalRepairDatabase.CreateAsync(db, null, cancellationToken)
.ConfigureAwait(false);
foreach (var vol in faultyIndexFiles)
{
if (!await m_result.TaskControl.ProgressRendevouz().ConfigureAwait(false))
{
m_result.EndTime = DateTime.UtcNow;
return;
}
IndexVolumeWriter newEntry = null;
try
{
var w = newEntry = new IndexVolumeWriter(m_options);
await RepairHandler.RunRepairDindex(backendManager, repairdb, w, vol, m_options, cancellationToken).ConfigureAwait(false);
if (m_options.Dryrun)
{
Logging.Log.WriteDryrunMessage(LOGTAG, "ReplaceFaultyIndexFile", LC.L("Would replace faulty index file {0} with {1}", vol.Name, w.RemoteFilename));
}
else
{
await backendManager.DeleteAsync(vol.Name, vol.Size, true, m_result.TaskControl.ProgressToken).ConfigureAwait(false);
await backendManager.WaitForEmptyAsync(repairdb, m_result.TaskControl.ProgressToken).ConfigureAwait(false);
await repairdb.Transaction
.CommitAsync("ReplaceFaultyIndexFileCommit", token: cancellationToken)
.ConfigureAwait(false);
m_result.RemoveResult(vol.Name);
}
}
catch (Exception ex)
{
newEntry?.Dispose();
Logging.Log.WriteErrorMessage(LOGTAG, "FailedToReplaceFaultyIndexFile", ex, LC.L("Failed to replace faulty index file {0}", vol.Name));
if (ex.IsAbortException())
throw;
}
}
}
}
}
| TestHandler |
csharp | AvaloniaUI__Avalonia | src/Avalonia.Base/Input/DataFormatOfT.cs | {
"start": 778,
"end": 958
} | public sealed class ____<T> : DataFormat
where T : class
{
internal DataFormat(DataFormatKind kind, string identifier)
: base(kind, identifier)
{
}
}
| DataFormat |
csharp | abpframework__abp | modules/cms-kit/src/Volo.CmsKit.EntityFrameworkCore/Volo/CmsKit/EntityFrameworkCore/CmsKitEntityFrameworkCoreModule.cs | {
"start": 619,
"end": 1832
} | public class ____ : AbpModule
{
public override void ConfigureServices(ServiceConfigurationContext context)
{
context.Services.AddAbpDbContext<CmsKitDbContext>(options =>
{
options.AddRepository<CmsUser, EfCoreCmsUserRepository>();
options.AddRepository<UserReaction, EfCoreUserReactionRepository>();
options.AddRepository<Comment, EfCoreCommentRepository>();
options.AddRepository<Rating, EfCoreRatingRepository>();
options.AddRepository<Tag, EfCoreTagRepository>();
options.AddRepository<EntityTag, EfCoreEntityTagRepository>();
options.AddRepository<Page, EfCorePageRepository>();
options.AddRepository<Blog, EfCoreBlogRepository>();
options.AddRepository<BlogPost, EfCoreBlogPostRepository>();
options.AddRepository<BlogFeature, EfCoreBlogFeatureRepository>();
options.AddRepository<MediaDescriptor, EfCoreMediaDescriptorRepository>();
options.AddRepository<GlobalResource, EfCoreGlobalResourceRepository>();
options.AddRepository<UserMarkedItem, EfCoreUserMarkedItemRepository>();
});
}
}
| CmsKitEntityFrameworkCoreModule |
csharp | atata-framework__atata | test/Atata.IntegrationTests/Components/InputPage.cs | {
"start": 233,
"end": 375
} | enum ____ with type name
OptionA,
OptionB,
OptionC,
OptionD
#pragma warning restore CA1712 // Do not prefix | values |
csharp | JamesNK__Newtonsoft.Json | Src/Newtonsoft.Json/Serialization/JsonLinqContract.cs | {
"start": 1415,
"end": 1914
} | public class ____ : JsonContract
{
/// <summary>
/// Initializes a new instance of the <see cref="JsonLinqContract"/> class.
/// </summary>
/// <param name="underlyingType">The underlying type for the contract.</param>
[RequiresUnreferencedCode(MiscellaneousUtils.TrimWarning)]
public JsonLinqContract(Type underlyingType)
: base(underlyingType)
{
ContractType = JsonContractType.Linq;
}
}
} | JsonLinqContract |
csharp | PrismLibrary__Prism | tests/Avalonia/Prism.Avalonia.Tests/Mocks/MockClickableObject.cs | {
"start": 69,
"end": 219
} | internal class ____ : Button // : ButtonBase
{
public void RaiseClick()
{
OnClick();
}
}
}
| MockClickableObject |
csharp | dotnet__reactive | Ix.NET/Source/System.Linq.Async.SourceGenerator/AsyncOverloadsGenerator.cs | {
"start": 513,
"end": 926
} | public sealed class ____ : ISourceGenerator
{
private const string GenerateAsyncOverloadAttributeSource =
"using System;\n" +
"using System.Diagnostics;\n" +
"namespace System.Linq\n" +
"{\n" +
" [AttributeUsage(AttributeTargets.Method)]\n" +
" [Conditional(\"COMPILE_TIME_ONLY\")]\n" +
" | AsyncOverloadsGenerator |
csharp | AutoFixture__AutoFixture | Src/AutoFixtureUnitTest/QueryMock.cs | {
"start": 52,
"end": 347
} | public class ____<T, TResult>
{
public QueryMock()
{
this.OnQuery = x => default(TResult);
}
public Func<T, TResult> OnQuery { get; set; }
public TResult Query(T x)
{
return this.OnQuery(x);
}
}
| QueryMock |
csharp | unoplatform__uno | src/Uno.UI/Generated/3.0.0.0/Microsoft.UI.Input/PointerPoint.cs | {
"start": 253,
"end": 1908
} | public partial class ____
{
// Skipping already declared property FrameId
// Skipping already declared property IsInContact
// Skipping already declared property PointerDeviceType
// Skipping already declared property PointerId
// Skipping already declared property Position
// Skipping already declared property Properties
// Skipping already declared property Timestamp
// Forced skipping of method Microsoft.UI.Input.PointerPoint.IsInContact.get
// Forced skipping of method Microsoft.UI.Input.PointerPoint.FrameId.get
// Forced skipping of method Microsoft.UI.Input.PointerPoint.PointerDeviceType.get
// Forced skipping of method Microsoft.UI.Input.PointerPoint.PointerId.get
// Forced skipping of method Microsoft.UI.Input.PointerPoint.Position.get
// Forced skipping of method Microsoft.UI.Input.PointerPoint.Properties.get
// Forced skipping of method Microsoft.UI.Input.PointerPoint.Timestamp.get
#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::Microsoft.UI.Input.PointerPoint GetTransformedPoint(global::Microsoft.UI.Input.IPointerPointTransform transform)
{
throw new global::System.NotImplementedException("The member PointerPoint PointerPoint.GetTransformedPoint(IPointerPointTransform transform) is not implemented. For more information, visit https://aka.platform.uno/notimplemented#m=PointerPoint%20PointerPoint.GetTransformedPoint%28IPointerPointTransform%20transform%29");
}
#endif
}
}
| PointerPoint |
csharp | ChilliCream__graphql-platform | src/Nitro/CommandLine/src/CommandLine.Cloud/Commands/Schema/ValidateSchemaCommand.cs | {
"start": 426,
"end": 4782
} | internal sealed class ____ : Command
{
public ValidateSchemaCommand() : base("validate")
{
Description = "Validates a schema against a stage";
AddOption(Opt<StageNameOption>.Instance);
AddOption(Opt<ApiIdOption>.Instance);
AddOption(Opt<SchemaFileOption>.Instance);
this.SetHandler(
ExecuteAsync,
Bind.FromServiceProvider<IAnsiConsole>(),
Bind.FromServiceProvider<IApiClient>(),
Opt<StageNameOption>.Instance,
Opt<ApiIdOption>.Instance,
Opt<SchemaFileOption>.Instance,
Bind.FromServiceProvider<CancellationToken>());
}
private static async Task<int> ExecuteAsync(
IAnsiConsole console,
IApiClient client,
string stage,
string apiId,
FileInfo schemaFile,
CancellationToken ct)
{
console.Title($"Validate to {stage.EscapeMarkup()}");
var isValid = false;
if (console.IsHumanReadable())
{
await console
.Status()
.Spinner(Spinner.Known.BouncingBar)
.SpinnerStyle(Style.Parse("green bold"))
.StartAsync("Validating...", ValidateSchema);
}
else
{
await ValidateSchema(null);
}
return isValid ? ExitCodes.Success : ExitCodes.Error;
async Task ValidateSchema(StatusContext? ctx)
{
console.Log("Initialized");
console.Log($"Reading file [blue]{schemaFile.FullName.EscapeMarkup()}[/]");
var stream = FileHelpers.CreateFileStream(schemaFile);
var input = new ValidateSchemaInput
{
ApiId = apiId,
Stage = stage,
Schema = new Upload(stream, "operations.graphql")
};
console.Log("Create validation request");
var requestId = await ValidateAsync(console, client, input, ct);
console.Log($"Validation request created [grey](ID: {requestId.EscapeMarkup()})[/]");
using var stopSignal = new Subject<Unit>();
var subscription = client.OnSchemaVersionValidationUpdated
.Watch(requestId, ExecutionStrategy.NetworkOnly)
.TakeUntil(stopSignal);
await foreach (var x in subscription.ToAsyncEnumerable().WithCancellation(ct))
{
if (x.Errors is { Count: > 0 } errors)
{
console.PrintErrorsAndExit(errors);
throw Exit("No request id returned");
}
switch (x.Data?.OnSchemaVersionValidationUpdate)
{
case ISchemaVersionValidationFailed { Errors: var schemaErrors }:
console.Error.WriteLine("The schema is invalid:");
console.PrintErrorsAndExit(schemaErrors);
stopSignal.OnNext(Unit.Default);
break;
case ISchemaVersionValidationSuccess:
isValid = true;
stopSignal.OnNext(Unit.Default);
console.Success("Schema validation succeeded.");
break;
case IOperationInProgress:
case IValidationInProgress:
ctx?.Status("The validation is in progress.");
break;
default:
ctx?.Status(
"This is an unknown response, upgrade Nitro CLI to the latest version.");
break;
}
}
}
}
private static async Task<string> ValidateAsync(
IAnsiConsole console,
IApiClient client,
ValidateSchemaInput input,
CancellationToken ct)
{
var result = await client.ValidateSchemaVersion.ExecuteAsync(input, ct);
console.EnsureNoErrors(result);
var data = console.EnsureData(result);
console.PrintErrorsAndExit(data.ValidateSchema.Errors);
if (data.ValidateSchema.Id is null)
{
throw new ExitException("Could not create validation request!");
}
return data.ValidateSchema.Id;
}
}
| ValidateSchemaCommand |
csharp | ServiceStack__ServiceStack | ServiceStack/tests/ServiceStack.WebHost.Endpoints.Tests/PasswordHasherTests.cs | {
"start": 178,
"end": 271
} | public abstract class ____
{
protected ServiceStackHost appHost;
| PasswordHasherTestsBase |
csharp | xunit__xunit | src/xunit.v3.assert.tests/Asserts/SetAssertsTests.cs | {
"start": 5090,
"end": 6903
} | public class ____
{
[Fact]
public static void GuardClause()
{
Assert.Throws<ArgumentNullException>("expectedSuperset", () => Assert.ProperSuperset(null!, new HashSet<int>()));
}
[Fact]
public static void IsSupersetButNotProperSuperset()
{
var expectedSuperset = new HashSet<int> { 1, 2, 3 };
var actual = new HashSet<int> { 1, 2, 3 };
var ex = Record.Exception(() => Assert.ProperSuperset(expectedSuperset, actual));
Assert.IsType<ProperSupersetException>(ex);
Assert.Equal(
"Assert.ProperSuperset() Failure: Value is not a proper superset" + Environment.NewLine +
"Expected: [1, 2, 3]" + Environment.NewLine +
"Actual: [1, 2, 3]",
ex.Message
);
}
[Fact]
public static void IsProperSuperset()
{
var expectedSuperset = new HashSet<int> { 1, 2, 3 };
var actual = new HashSet<int> { 1, 2, 3, 4 };
Assert.ProperSuperset(expectedSuperset, actual);
}
[Fact]
public static void IsNotSuperset()
{
var expectedSuperset = new HashSet<int> { 1, 2, 3 };
var actual = new HashSet<int> { 1, 2, 7 };
var ex = Record.Exception(() => Assert.ProperSuperset(expectedSuperset, actual));
Assert.IsType<ProperSupersetException>(ex);
Assert.Equal(
"Assert.ProperSuperset() Failure: Value is not a proper superset" + Environment.NewLine +
"Expected: [1, 2, 3]" + Environment.NewLine +
"Actual: [1, 2, 7]",
ex.Message
);
}
[Fact]
public void NullActual()
{
var ex = Record.Exception(() => Assert.ProperSuperset(new HashSet<int>(), null));
Assert.IsType<ProperSupersetException>(ex);
Assert.Equal(
"Assert.ProperSuperset() Failure: Value is not a proper superset" + Environment.NewLine +
"Expected: []" + Environment.NewLine +
"Actual: null",
ex.Message
);
}
}
| ProperSuperset |
csharp | dotnet__maui | src/Core/tests/DeviceTests/Handlers/GraphicsView/GraphicsViewHandlerTests.Windows.cs | {
"start": 86,
"end": 272
} | public partial class ____
{
PlatformTouchGraphicsView GetPlatformGraphicsView(GraphicsViewHandler graphicsViewHandler) =>
graphicsViewHandler.PlatformView;
}
} | GraphicsViewHandlerTests |
csharp | ChilliCream__graphql-platform | src/HotChocolate/Data/src/Data/Sorting/Expressions/Extensions/QueryableSortExtensions.cs | {
"start": 227,
"end": 2587
} | public static class ____
{
/// <summary>
/// Sorts the selection set of the request onto the queryable.
/// </summary>
/// <param name="queryable">The queryable</param>
/// <param name="context">
/// The resolver context of the resolver that is annotated with UseSorting
/// </param>
/// <returns>The sorted queryable</returns>
public static IQueryable<T> Sort<T>(
this IQueryable<T> queryable,
IResolverContext context) =>
ExecuteSort(queryable, context, typeof(IQueryable<T>));
/// <summary>
/// Sorts the selection set of the request onto the enumerable.
/// </summary>
/// <param name="enumerable">The enumerable</param>
/// <param name="context">
/// The resolver context of the resolver that is annotated with UseSorting
/// </param>
/// <returns>The sorted enumerable</returns>
public static IEnumerable<T> Sort<T>(
this IEnumerable<T> enumerable,
IResolverContext context) =>
ExecuteSort(enumerable, context, typeof(IEnumerable<T>));
/// <summary>
/// Sorts the selection set of the request onto the enumerable.
/// </summary>
/// <param name="enumerable">The enumerable</param>
/// <param name="context">
/// The resolver context of the resolver that is annotated with UseSorting
/// </param>
/// <returns>The sorted enumerable</returns>
public static IQueryableExecutable<T> Sort<T>(
this IQueryableExecutable<T> enumerable,
IResolverContext context) =>
ExecuteSort(enumerable, context, typeof(IQueryableExecutable<T>));
private static T ExecuteSort<T>(
this T input,
IResolverContext context,
Type expectedType)
{
if (context.LocalContextData.TryGetValue(
QueryableSortProvider.ContextApplySortingKey,
out var applicatorObj)
&& applicatorObj is ApplySorting applicator)
{
var resultObj = applicator(context, input);
if (resultObj is T result)
{
return result;
}
throw ThrowHelper.Sorting_TypeMismatch(
context,
expectedType,
resultObj!.GetType());
}
throw ThrowHelper.Sorting_SortingWasNotFound(context);
}
}
| QueryableSortExtensions |
csharp | ServiceStack__ServiceStack | ServiceStack/src/ServiceStack.Interfaces/Jetbrains.Annotations.cs | {
"start": 37701,
"end": 37987
} | internal sealed class ____ : Attribute
{
public AspRequiredAttributeAttribute([NotNull] string attribute)
{
Attribute = attribute;
}
[NotNull] public string Attribute { get; private set; }
}
[AttributeUsage(AttributeTargets.Property)]
| AspRequiredAttributeAttribute |
csharp | dotnet__aspire | src/Aspire.Hosting.JavaScript/NodeAppResource.cs | {
"start": 500,
"end": 712
} | public class ____(string name, string command, string workingDirectory)
: JavaScriptAppResource(name, command, workingDirectory), IResourceWithServiceDiscovery, IContainerFilesDestinationResource;
| NodeAppResource |
csharp | dotnet__aspnetcore | src/Identity/UI/src/Areas/Identity/Pages/V4/Account/ResendEmailConfirmation.cshtml.cs | {
"start": 1383,
"end": 2424
} | public class ____
{
/// <summary>
/// This API supports the ASP.NET Core Identity default UI infrastructure and is not intended to be used
/// directly from your code. This API may change or be removed in future releases.
/// </summary>
[Required]
[EmailAddress]
public string Email { get; set; } = default!;
}
/// <summary>
/// This API supports the ASP.NET Core Identity default UI infrastructure and is not intended to be used
/// directly from your code. This API may change or be removed in future releases.
/// </summary>
public virtual void OnGet() => throw new NotImplementedException();
/// <summary>
/// This API supports the ASP.NET Core Identity default UI infrastructure and is not intended to be used
/// directly from your code. This API may change or be removed in future releases.
/// </summary>
public virtual Task<IActionResult> OnPostAsync() => throw new NotImplementedException();
}
| InputModel |
csharp | dotnet__orleans | test/DefaultCluster.Tests/GenericGrainTests.cs | {
"start": 11523,
"end": 31780
} | interface ____ by ConcreteGrainWith2GenericInterfaces
// will reference the same grain:
var grainRef2 = GetGrain<IGenericGrain<int, string>>(grainId);
// ConcreteGrainWith2GenericInterfaces returns a string representation of the current value multiplied by 10:
var floatResult = await grainRef2.MapT2U();
Assert.Equal("100", floatResult);
}
/// <summary>
/// Tests that grains can use the grain factory to create references to other generic grains.
/// Validates that grain factory operations work correctly within grain code for generic types.
/// </summary>
[Fact]
public async Task GenericGrainTests_UseGenericFactoryInsideGrain()
{
var grainId = GetRandomGrainId();
var grainRef1 = GetGrain<ISimpleGenericGrain<string>>(grainId);
await grainRef1.Set("JustString");
await grainRef1.CompareGrainReferences(grainRef1);
}
[Fact]
public async Task Generic_SimpleGrain_GetGrain()
{
var grain = this.GrainFactory.GetGrain<ISimpleGenericGrain1<int>>(grainId++);
await grain.GetA();
}
[Fact]
public async Task Generic_SimpleGrainControlFlow()
{
var a = Random.Shared.Next(100);
var b = a + 1;
var expected = a + "x" + b;
var grain = this.GrainFactory.GetGrain<ISimpleGenericGrain1<int>>(grainId++);
await grain.SetA(a);
await grain.SetB(b);
Task<string> stringPromise = grain.GetAxB();
Assert.Equal(expected, await stringPromise);
}
[Fact]
public void Generic_SimpleGrainControlFlow_Blocking()
{
var a = Random.Shared.Next(100);
var b = a + 1;
var expected = a + "x" + b;
var grain = this.GrainFactory.GetGrain<ISimpleGenericGrain1<int>>(grainId++);
// explicitly use .Wait() and .Result to make sure the client does not deadlock in these cases.
#pragma warning disable xUnit1031 // Do not use blocking task operations in test method
grain.SetA(a).Wait();
grain.SetB(b).Wait();
Task<string> stringPromise = grain.GetAxB();
Assert.Equal(expected, stringPromise.Result);
#pragma warning restore xUnit1031 // Do not use blocking task operations in test method
}
[Fact]
public async Task Generic_SimpleGrainDataFlow()
{
var a = Random.Shared.Next(100);
var b = a + 1;
var expected = a + "x" + b;
var grain = this.GrainFactory.GetGrain<ISimpleGenericGrain1<int>>(grainId++);
var setAPromise = grain.SetA(a);
var setBPromise = grain.SetB(b);
var stringPromise = Task.WhenAll(setAPromise, setBPromise).ContinueWith((_) => grain.GetAxB()).Unwrap();
var x = await stringPromise;
Assert.Equal(expected, x);
}
[Fact]
public async Task Generic_SimpleGrain2_GetGrain()
{
var g1 = this.GrainFactory.GetGrain<ISimpleGenericGrain1<int>>(grainId++);
var g2 = this.GrainFactory.GetGrain<ISimpleGenericGrainU<int>>(grainId++);
var g3 = this.GrainFactory.GetGrain<ISimpleGenericGrain2<int, int>>(grainId++);
await g1.GetA();
await g2.GetA();
await g3.GetA();
}
[Fact]
public async Task Generic_SimpleGrainGenericParameterWithMultipleArguments_GetGrain()
{
var g1 = this.GrainFactory.GetGrain<ISimpleGenericGrain1<Dictionary<int, int>>>(GetRandomGrainId());
await g1.GetA();
}
[Fact]
public async Task Generic_SimpleGrainControlFlow2_GetAB()
{
var a = Random.Shared.Next(100);
var b = a + 1;
var expected = a + "x" + b;
var g1 = this.GrainFactory.GetGrain<ISimpleGenericGrain1<int>>(grainId++);
var g2 = this.GrainFactory.GetGrain<ISimpleGenericGrainU<int>>(grainId++);
var g3 = this.GrainFactory.GetGrain<ISimpleGenericGrain2<int, int>>(grainId++);
string r1 = await g1.GetAxB(a, b);
string r2 = await g2.GetAxB(a, b);
string r3 = await g3.GetAxB(a, b);
Assert.Equal(expected, r1);
Assert.Equal(expected, r2);
Assert.Equal(expected, r3);
}
[Fact]
public async Task Generic_SimpleGrainControlFlow3()
{
ISimpleGenericGrain2<int, float> g = this.GrainFactory.GetGrain<ISimpleGenericGrain2<int, float>>(grainId++);
await g.SetA(3);
await g.SetB(1.25f);
Assert.Equal("3x1.25", await g.GetAxB());
}
[Fact]
public async Task Generic_BasicGrainControlFlow()
{
IBasicGenericGrain<int, float> g = this.GrainFactory.GetGrain<IBasicGenericGrain<int, float>>(0);
await g.SetA(3);
await g.SetB(1.25f);
Assert.Equal("3x1.25", await g.GetAxB());
}
[Fact]
public async Task GrainWithListFields()
{
string a = Random.Shared.Next(100).ToString(CultureInfo.InvariantCulture);
string b = Random.Shared.Next(100).ToString(CultureInfo.InvariantCulture);
var g1 = this.GrainFactory.GetGrain<IGrainWithListFields>(grainId++);
var p1 = g1.AddItem(a);
var p2 = g1.AddItem(b);
await Task.WhenAll(p1, p2);
var r1 = await g1.GetItems();
Assert.True(
(a == r1[0] && b == r1[1]) || (b == r1[0] && a == r1[1]), // Message ordering was not necessarily preserved.
string.Format("Result: r[0]={0}, r[1]={1}", r1[0], r1[1]));
}
[Fact]
public async Task Generic_GrainWithListFields()
{
int a = Random.Shared.Next(100);
int b = Random.Shared.Next(100);
var g1 = this.GrainFactory.GetGrain<IGenericGrainWithListFields<int>>(grainId++);
var p1 = g1.AddItem(a);
var p2 = g1.AddItem(b);
await Task.WhenAll(p1, p2);
var r1 = await g1.GetItems();
Assert.True(
(a == r1[0] && b == r1[1]) || (b == r1[0] && a == r1[1]), // Message ordering was not necessarily preserved.
string.Format("Result: r[0]={0}, r[1]={1}", r1[0], r1[1]));
}
[Fact]
public async Task Generic_GrainWithNoProperties_ControlFlow()
{
int a = Random.Shared.Next(100);
int b = Random.Shared.Next(100);
string expected = a + "x" + b;
var g1 = this.GrainFactory.GetGrain<IGenericGrainWithNoProperties<int>>(grainId++);
string r1 = await g1.GetAxB(a, b);
Assert.Equal(expected, r1);
}
[Fact]
public async Task GrainWithNoProperties_ControlFlow()
{
int a = Random.Shared.Next(100);
int b = Random.Shared.Next(100);
string expected = a + "x" + b;
long grainId = GetRandomGrainId();
var g1 = this.GrainFactory.GetGrain<IGrainWithNoProperties>(grainId);
string r1 = await g1.GetAxB(a, b);
Assert.Equal(expected, r1);
}
[Fact]
public async Task Generic_ReaderWriterGrain1()
{
int a = Random.Shared.Next(100);
var g = this.GrainFactory.GetGrain<IGenericReaderWriterGrain1<int>>(grainId++);
await g.SetValue(a);
var res = await g.GetValue();
Assert.Equal(a, res);
}
[Fact]
public async Task Generic_ReaderWriterGrain2()
{
int a = Random.Shared.Next(100);
string b = "bbbbb";
var g = this.GrainFactory.GetGrain<IGenericReaderWriterGrain2<int, string>>(grainId++);
await g.SetValue1(a);
await g.SetValue2(b);
var r1 = await g.GetValue1();
Assert.Equal(a, r1);
var r2 = await g.GetValue2();
Assert.Equal(b, r2);
}
[Fact]
public async Task Generic_ReaderWriterGrain3()
{
int a = Random.Shared.Next(100);
string b = "bbbbb";
double c = 3.145;
var g = this.GrainFactory.GetGrain<IGenericReaderWriterGrain3<int, string, double>>(grainId++);
await g.SetValue1(a);
await g.SetValue2(b);
await g.SetValue3(c);
var r1 = await g.GetValue1();
Assert.Equal(a, r1);
var r2 = await g.GetValue2();
Assert.Equal(b, r2);
var r3 = await g.GetValue3();
Assert.Equal(c, r3);
}
/// <summary>
/// Tests generic grains with non-primitive type arguments like Guid and byte arrays.
/// Validates that Orleans correctly differentiates grain activations based on complex
/// generic type arguments, ensuring proper type-based routing.
/// </summary>
[Fact]
public async Task Generic_Non_Primitive_Type_Argument()
{
IEchoHubGrain<Guid, string> g1 = this.GrainFactory.GetGrain<IEchoHubGrain<Guid, string>>(1);
IEchoHubGrain<Guid, int> g2 = this.GrainFactory.GetGrain<IEchoHubGrain<Guid, int>>(1);
IEchoHubGrain<Guid, byte[]> g3 = this.GrainFactory.GetGrain<IEchoHubGrain<Guid, byte[]>>(1);
Assert.NotEqual((GrainReference)g1, (GrainReference)g2);
Assert.NotEqual((GrainReference)g1, (GrainReference)g3);
Assert.NotEqual((GrainReference)g2, (GrainReference)g3);
await g1.Foo(Guid.Empty, "", 1);
await g2.Foo(Guid.Empty, 0, 2);
await g3.Foo(Guid.Empty, new byte[] { }, 3);
Assert.Equal(1, await g1.GetX());
Assert.Equal(2, await g2.GetX());
Assert.Equal(3m, await g3.GetX());
}
[Fact]
public async Task Generic_Echo_Chain_1()
{
const string msg1 = "Hello from EchoGenericChainGrain-1";
IEchoGenericChainGrain<string> g1 = this.GrainFactory.GetGrain<IEchoGenericChainGrain<string>>(GetRandomGrainId());
string received = await g1.Echo(msg1);
Assert.Equal(msg1, received);
}
[Fact]
public async Task Generic_Echo_Chain_2()
{
const string msg2 = "Hello from EchoGenericChainGrain-2";
IEchoGenericChainGrain<string> g2 = this.GrainFactory.GetGrain<IEchoGenericChainGrain<string>>(GetRandomGrainId());
string received = await g2.Echo2(msg2);
Assert.Equal(msg2, received);
}
[Fact]
public async Task Generic_Echo_Chain_3()
{
const string msg3 = "Hello from EchoGenericChainGrain-3";
IEchoGenericChainGrain<string> g3 = this.GrainFactory.GetGrain<IEchoGenericChainGrain<string>>(GetRandomGrainId());
string received = await g3.Echo3(msg3);
Assert.Equal(msg3, received);
}
[Fact]
public async Task Generic_Echo_Chain_4()
{
const string msg4 = "Hello from EchoGenericChainGrain-4";
var g4 = this.GrainFactory.GetGrain<IEchoGenericChainGrain<string>>(GetRandomGrainId());
string received = await g4.Echo4(msg4);
Assert.Equal(msg4, received);
}
[Fact]
public async Task Generic_Echo_Chain_5()
{
const string msg5 = "Hello from EchoGenericChainGrain-5";
var g5 = this.GrainFactory.GetGrain<IEchoGenericChainGrain<string>>(GetRandomGrainId());
string received = await g5.Echo5(msg5);
Assert.Equal(msg5, received);
}
[Fact]
public async Task Generic_Echo_Chain_6()
{
const string msg6 = "Hello from EchoGenericChainGrain-6";
var g6 = this.GrainFactory.GetGrain<IEchoGenericChainGrain<string>>(GetRandomGrainId());
string received = await g6.Echo6(msg6);
Assert.Equal(msg6, received);
}
[Fact]
public async Task Generic_1Argument_GenericCallOnly()
{
var grain = this.GrainFactory.GetGrain<IGeneric1Argument<string>>(Guid.NewGuid(), "UnitTests.Grains.Generic1ArgumentGrain");
var s1 = Guid.NewGuid().ToString();
var s2 = await grain.Ping(s1);
Assert.Equal(s1, s2);
}
[Fact]
public void Generic_1Argument_NonGenericCallFirst()
{
Assert.Throws<ArgumentException>(() => this.GrainFactory.GetGrain<INonGenericBase>(Guid.NewGuid(), "UnitTests.Grains.Generic1ArgumentGrain"));
}
[Fact]
public async Task Generic_1Argument_GenericCallFirst()
{
var id = Guid.NewGuid();
var grain = this.GrainFactory.GetGrain<IGeneric1Argument<string>>(id, "UnitTests.Grains.Generic1ArgumentGrain");
var s1 = Guid.NewGuid().ToString();
var s2 = await grain.Ping(s1);
Assert.Equal(s1, s2);
Assert.Throws<ArgumentException>(() => this.GrainFactory.GetGrain<INonGenericBase>(id, "UnitTests.Grains.Generic1ArgumentGrain"));
}
/// <summary>
/// Validates that grains with different generic type arguments create independent activations.
/// This is crucial for ensuring that IDbGrain<int> and IDbGrain<string> are treated as
/// completely separate grain types with independent state.
/// </summary>
[Fact]
public async Task DifferentTypeArgsProduceIndependentActivations()
{
var grain1 = this.GrainFactory.GetGrain<IDbGrain<int>>(0);
await grain1.SetValue(123);
var grain2 = this.GrainFactory.GetGrain<IDbGrain<string>>(0);
var v = await grain2.GetValue();
Assert.Null(v);
}
/// <summary>
/// Tests generic grains making calls to themselves.
/// Validates that self-referential calls work correctly in generic grain contexts.
/// </summary>
[Fact, TestCategory("Echo")]
public async Task Generic_PingSelf()
{
var id = Guid.NewGuid();
var grain = this.GrainFactory.GetGrain<IGenericPingSelf<string>>(id);
var s1 = Guid.NewGuid().ToString();
var s2 = await grain.PingSelf(s1);
Assert.Equal(s1, s2);
}
/// <summary>
/// Tests generic grains making calls to other generic grains of the same type.
/// Validates grain-to-grain communication for generic grain types.
/// </summary>
[Fact, TestCategory("Echo")]
public async Task Generic_PingOther()
{
var id = Guid.NewGuid();
var targetId = Guid.NewGuid();
var grain = this.GrainFactory.GetGrain<IGenericPingSelf<string>>(id);
var target = this.GrainFactory.GetGrain<IGenericPingSelf<string>>(targetId);
var s1 = Guid.NewGuid().ToString();
var s2 = await grain.PingOther(target, s1);
Assert.Equal(s1, s2);
}
/// <summary>
/// Tests complex call chains where a generic grain calls itself through another grain.
/// Validates that grain references remain valid when passed between generic grains.
/// </summary>
[Fact, TestCategory("Echo")]
public async Task Generic_PingSelfThroughOther()
{
var id = Guid.NewGuid();
var targetId = Guid.NewGuid();
var grain = this.GrainFactory.GetGrain<IGenericPingSelf<string>>(id);
var target = this.GrainFactory.GetGrain<IGenericPingSelf<string>>(targetId);
var s1 = Guid.NewGuid().ToString();
var s2 = await grain.PingSelfThroughOther(target, s1);
Assert.Equal(s1, s2);
}
/// <summary>
/// Tests scheduled operations and deactivation for generic grains.
/// Validates that Orleans' activation lifecycle management works correctly with generic grains,
/// including delayed operations and explicit deactivation.
/// </summary>
[Fact, TestCategory("ActivateDeactivate")]
public async Task Generic_ScheduleDelayedPingAndDeactivate()
{
var id = Guid.NewGuid();
var targetId = Guid.NewGuid();
var grain = this.GrainFactory.GetGrain<IGenericPingSelf<string>>(id);
var target = this.GrainFactory.GetGrain<IGenericPingSelf<string>>(targetId);
var s1 = Guid.NewGuid().ToString();
await grain.ScheduleDelayedPingToSelfAndDeactivate(target, s1, TimeSpan.FromSeconds(5));
await Task.Delay(TimeSpan.FromSeconds(6));
var s2 = await grain.GetLastValue();
Assert.Equal(s1, s2);
}
/// <summary>
/// Tests serialization of generic grains with circular references in their state.
/// Validates that Orleans' serialization system can handle complex object graphs
/// in generic grain contexts without infinite loops.
/// </summary>
[Fact, TestCategory("Serialization")]
public async Task SerializationTests_Generic_CircularReferenceTest()
{
var grainId = Guid.NewGuid();
var grain = this.GrainFactory.GetGrain<ICircularStateTestGrain>(primaryKey: grainId, keyExtension: grainId.ToString("N"));
_ = await grain.GetState();
}
/// <summary>
/// Tests generic grains with type constraints (where T : class, new(), etc.).
/// Validates that Orleans correctly enforces and works with C# generic type constraints,
/// including unmanaged constraints and reference type constraints.
/// </summary>
[Fact]
public async Task Generic_GrainWithTypeConstraints()
{
var grainId = Guid.NewGuid().ToString();
var grain = this.GrainFactory.GetGrain<IGenericGrainWithConstraints<List<int>, int, string>>(grainId);
var result = await grain.GetCount();
Assert.Equal(0, result);
await grain.Add(42);
result = await grain.GetCount();
Assert.Equal(1, result);
var unmanagedGrain = this.GrainFactory.GetGrain<IUnmanagedArgGrain<DateTime>>(Guid.NewGuid());
{
var echoInput = DateTime.UtcNow;
var echoOutput = await unmanagedGrain.Echo(echoInput);
Assert.Equal(echoInput, echoOutput);
echoOutput = await unmanagedGrain.EchoValue(echoInput);
Assert.Equal(echoInput, echoOutput);
}
{
var echoInput = "hello";
var echoOutput = await unmanagedGrain.EchoNonNullable(echoInput);
Assert.Equal(echoInput, echoOutput);
echoOutput = await unmanagedGrain.EchoReference(echoInput);
Assert.Equal(echoInput, echoOutput);
}
}
/// <summary>
/// Tests generic grains with value type state persistence.
/// Validates that Orleans' persistence system correctly handles value types (structs)
/// as grain state in generic grain contexts.
/// </summary>
[Fact, TestCategory("Persistence")]
public async Task Generic_GrainWithValueTypeState()
{
Guid id = Guid.NewGuid();
var grain = this.GrainFactory.GetGrain<IValueTypeTestGrain>(id);
var initial = await grain.GetStateData();
Assert.Equal(new ValueTypeTestData(0), initial);
var expectedValue = new ValueTypeTestData(42);
await grain.SetStateData(expectedValue);
Assert.Equal(expectedValue, await grain.GetStateData());
}
/// <summary>
/// Tests casting non-generic grain references to generic interfaces after activation.
/// Validates Orleans' support for late-bound | implemented |
csharp | dotnet__aspnetcore | src/Razor/Razor.Runtime/test/Runtime/TagHelpers/TestTagHelpers/TagHelperDescriptorFactoryTagHelpers.cs | {
"start": 5653,
"end": 5939
} | public class ____
{
public object BoundProperty { get; set; }
[HtmlAttributeNotBound]
public string NotBoundProperty { get; set; }
[HtmlAttributeName("unused")]
[HtmlAttributeNotBound]
public string NamedNotBoundProperty { get; set; }
}
| NotBoundAttributeTagHelper |
csharp | App-vNext__Polly | src/Polly/NoOp/NoOpSyntax.cs | {
"start": 36,
"end": 289
} | public partial class ____
{
/// <summary>
/// Builds a NoOp <see cref="Policy"/> that will execute without any custom behavior.
/// </summary>
/// <returns>The policy instance.</returns>
public static NoOpPolicy NoOp() => new();
}
| Policy |
csharp | ChilliCream__graphql-platform | src/HotChocolate/Core/src/Types/Types/Composite/Directives/Provides.cs | {
"start": 250,
"end": 840
} | public sealed class ____
{
public Provides(SelectionSetNode fields)
{
ArgumentNullException.ThrowIfNull(fields);
Fields = fields;
}
public Provides(string fields)
{
ArgumentNullException.ThrowIfNull(fields);
fields = $"{{ {fields.Trim('{', '}')} }}";
Fields = Utf8GraphQLParser.Syntax.ParseSelectionSet(fields);
}
[GraphQLType<NonNullType<FieldSelectionSetType>>]
public SelectionSetNode Fields { get; }
public override string ToString()
=> $"@provides(fields: {Fields.ToString(false)[1..^1]})";
}
| Provides |
csharp | spectreconsole__spectre.console | src/Spectre.Console.Tests/Unit/Rendering/Borders/TableBorderTests.cs | {
"start": 4520,
"end": 5258
} | public sealed class ____
{
[Fact]
public void Should_Return_Safe_Border()
{
// Given, When
var border = TableBorder.Square.GetSafeBorder(safe: true);
// Then
border.ShouldBeSameAs(TableBorder.Square);
}
}
[Fact]
[Expectation("SquareBorder")]
public Task Should_Render_As_Expected()
{
// Given
var console = new TestConsole();
var table = Fixture.GetTable().SquareBorder();
// When
console.Write(table);
// Then
return Verifier.Verify(console.Output);
}
}
| TheSafeGetBorderMethod |
csharp | abpframework__abp | framework/src/Volo.Abp.BlobStoring/Volo/Abp/BlobStoring/BlobProviderSelectorExtensions.cs | {
"start": 64,
"end": 375
} | public static class ____
{
public static IBlobProvider Get<TContainer>(
[NotNull] this IBlobProviderSelector selector)
{
Check.NotNull(selector, nameof(selector));
return selector.Get(BlobContainerNameAttribute.GetContainerName<TContainer>());
}
}
| BlobProviderSelectorExtensions |
csharp | dotnet__aspnetcore | src/Components/Components/src/EventCallback.cs | {
"start": 302,
"end": 3201
} | struct ____ : IEventCallback
{
/// <summary>
/// Gets a reference to the <see cref="EventCallbackFactory"/>.
/// </summary>
public static readonly EventCallbackFactory Factory = new EventCallbackFactory();
/// <summary>
/// Gets an empty <see cref="EventCallback"/>.
/// </summary>
public static readonly EventCallback Empty = new EventCallback(null, (Action)(() => { }));
internal readonly MulticastDelegate? Delegate;
internal readonly IHandleEvent? Receiver;
/// <summary>
/// Creates the new <see cref="EventCallback"/>.
/// </summary>
/// <param name="receiver">The event receiver.</param>
/// <param name="delegate">The delegate to bind.</param>
public EventCallback(IHandleEvent? receiver, MulticastDelegate? @delegate)
{
Receiver = receiver;
Delegate = @delegate;
}
/// <summary>
/// Gets a value that indicates whether the delegate associated with this event dispatcher is non-null.
/// </summary>
public bool HasDelegate => Delegate != null;
// This is a hint to the runtime that Receiver is a different object than what
// Delegate.Target points to. This allows us to avoid boxing the command object
// when building the render tree. See logic where this is used.
internal bool RequiresExplicitReceiver => Receiver != null && !object.ReferenceEquals(Receiver, Delegate?.Target);
/// <summary>
/// Invokes the delegate associated with this binding and dispatches an event notification to the
/// appropriate component.
/// </summary>
/// <param name="arg">The argument.</param>
/// <returns>A <see cref="Task"/> which completes asynchronously once event processing has completed.</returns>
public Task InvokeAsync(object? arg)
{
if (Receiver == null)
{
return EventCallbackWorkItem.InvokeAsync<object?>(Delegate, arg);
}
return Receiver.HandleEventAsync(new EventCallbackWorkItem(Delegate), arg);
}
/// <summary>
/// Invokes the delegate associated with this binding and dispatches an event notification to the
/// appropriate component.
/// </summary>
/// <returns>A <see cref="Task"/> which completes asynchronously once event processing has completed.</returns>
public Task InvokeAsync() => InvokeAsync(null!);
object? IEventCallback.UnpackForRenderTree()
{
return RequiresExplicitReceiver ? (object)this : Delegate;
}
/// <inheritdoc />
public override int GetHashCode()
=> HashCode.Combine(RuntimeHelpers.GetHashCode(Receiver), RuntimeHelpers.GetHashCode(Delegate));
/// <inheritdoc />
public override bool Equals(object? obj)
=> obj is EventCallback other
&& ReferenceEquals(Receiver, other.Receiver)
&& (Delegate?.Equals(other.Delegate) ?? (other.Delegate == null));
}
| EventCallback |
csharp | dotnet__aspnetcore | src/Http/Owin/src/OwinEnvironment.cs | {
"start": 7481,
"end": 7841
} | interface ____.</param>
/// <param name="getter">Value getter.</param>
public FeatureMap(Type featureInterface, Func<object, object> getter)
: this(featureInterface, getter, defaultFactory: null)
{
}
/// <summary>
/// Initializes a new instance of <see cref="FeatureMap"/> for the specified feature | type |
csharp | dotnet__efcore | test/EFCore.Specification.Tests/ModelBuilding/GiantModel.cs | {
"start": 352017,
"end": 352237
} | public class ____
{
public int Id { get; set; }
public RelatedEntity1614 ParentEntity { get; set; }
public IEnumerable<RelatedEntity1616> ChildEntities { get; set; }
}
| RelatedEntity1615 |
csharp | dotnet__machinelearning | src/Microsoft.ML.Data/Scorers/RowToRowScorerBase.cs | {
"start": 13503,
"end": 14144
} | internal abstract class ____
{
// Output columns.
[Argument(ArgumentType.AtMostOnce, HelpText = "Output column: The suffix to append to the default column names", ShortName = "ex")]
public string Suffix;
}
/// <summary>
/// Base bindings for a scorer based on an <see cref="ISchemaBoundMapper"/>. This assumes that input schema columns
/// are echoed, followed by zero or more derived columns, followed by the mapper generated columns.
/// The names of the derived columns and mapper generated columns have an optional suffix appended.
/// </summary>
[BestFriend]
| ScorerArgumentsBase |
csharp | ShareX__ShareX | ShareX/ImageData.cs | {
"start": 1151,
"end": 2290
} | public class ____ : IDisposable
{
public MemoryStream ImageStream { get; set; }
public EImageFormat ImageFormat { get; set; }
public bool Write(string filePath)
{
try
{
if (ImageStream != null && !string.IsNullOrEmpty(filePath))
{
return ImageStream.WriteToFile(filePath);
}
}
catch (Exception e)
{
DebugHelper.WriteException(e);
string message = $"{Resources.ImageData_Write_Error_Message}\r\n\"{filePath}\"";
if (e is UnauthorizedAccessException || e is FileNotFoundException)
{
message += "\r\n\r\n" + Resources.YourAntiVirusSoftwareOrTheControlledFolderAccessFeatureInWindowsCouldBeBlockingShareX;
}
MessageBox.Show(message, "ShareX - " + Resources.Error, MessageBoxButtons.OK, MessageBoxIcon.Error);
}
return false;
}
public void Dispose()
{
ImageStream?.Dispose();
}
}
} | ImageData |
csharp | dotnet__aspire | tests/Aspire.Hosting.Kafka.Tests/ConnectionPropertiesTests.cs | {
"start": 217,
"end": 971
} | public class ____
{
[Fact]
public void KafkaServerResourceGetConnectionPropertiesReturnsExpectedValues()
{
var resource = new KafkaServerResource("kafka");
var properties = ((IResourceWithConnectionString)resource).GetConnectionProperties().ToArray();
Assert.Collection(
properties,
property =>
{
Assert.Equal("Host", property.Key);
Assert.Equal("{kafka.bindings.tcp.host}", property.Value.ValueExpression);
},
property =>
{
Assert.Equal("Port", property.Key);
Assert.Equal("{kafka.bindings.tcp.port}", property.Value.ValueExpression);
});
}
} | ConnectionPropertiesTests |
csharp | SixLabors__ImageSharp | src/ImageSharp/Formats/SpecializedImageDecoder{T}.cs | {
"start": 193,
"end": 511
} | class ____ specialized image decoders.
/// Specialized decoders allow for additional options to be passed to the decoder.
/// Types that inherit this decoder are required to implement cancellable synchronous decoding operations only.
/// </summary>
/// <typeparam name="T">The type of specialized options.</typeparam>
| for |
csharp | smartstore__Smartstore | src/Smartstore.Web/Areas/Admin/Models/DataExchange/ImportProfileListModel.cs | {
"start": 85,
"end": 341
} | public partial class ____ : EntityModelBase
{
[LocalizedDisplay("Admin.Common.Entity")]
public ImportEntityType EntityType { get; set; }
public List<ImportProfileModel> Profiles { get; set; } = new();
}
}
| ImportProfileListModel |
csharp | ChilliCream__graphql-platform | src/HotChocolate/Core/test/Execution.Tests/RequestExecutorManagerTests.cs | {
"start": 8386,
"end": 8513
} | private sealed class ____ : TypeModule
{
public void TriggerChange() => OnTypesChanged();
}
}
| TriggerableTypeModule |
csharp | restsharp__RestSharp | src/RestSharp/Authenticators/IAuthenticator.cs | {
"start": 666,
"end": 770
} | public interface ____ {
ValueTask Authenticate(IRestClient client, RestRequest request);
} | IAuthenticator |
csharp | ShareX__ShareX | ShareX.ScreenCaptureLib/Forms/EditorStartupForm.cs | {
"start": 1209,
"end": 5119
} | public partial class ____ : Form
{
public RegionCaptureOptions Options { get; private set; }
public Bitmap Image { get; private set; }
public string ImageFilePath { get; private set; }
public EditorStartupForm(RegionCaptureOptions options)
{
Options = options;
InitializeComponent();
ShareXResources.ApplyTheme(this, true);
}
private void LoadImageFile(string imageFilePath)
{
if (!string.IsNullOrEmpty(imageFilePath))
{
Image = ImageHelpers.LoadImage(imageFilePath);
if (Image != null)
{
ImageFilePath = imageFilePath;
DialogResult = DialogResult.OK;
Close();
}
}
}
private void btnOpenImageFile_Click(object sender, EventArgs e)
{
string imageFilePath = ImageHelpers.OpenImageFileDialog(this);
LoadImageFile(imageFilePath);
}
private void btnLoadImageFromClipboard_Click(object sender, EventArgs e)
{
if (ClipboardHelpers.ContainsImage())
{
Image = ClipboardHelpers.GetImage();
if (Image != null)
{
DialogResult = DialogResult.OK;
Close();
}
}
else if (ClipboardHelpers.ContainsFileDropList())
{
string[] files = ClipboardHelpers.GetFileDropList();
if (files != null)
{
string imageFilePath = files.FirstOrDefault(x => FileHelpers.IsImageFile(x));
LoadImageFile(imageFilePath);
}
}
else
{
MessageBox.Show(Resources.EditorStartupForm_ClipboardDoesNotContainAnImage, "ShareX", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
private async void btnLoadImageFromURL_Click(object sender, EventArgs e)
{
string inputText = null;
string text = ClipboardHelpers.GetText(true);
if (URLHelpers.IsValidURL(text))
{
inputText = text;
}
string url = InputBox.Show(Resources.ImageURL, inputText);
if (!string.IsNullOrEmpty(url))
{
btnOpenImageFile.Enabled = btnLoadImageFromClipboard.Enabled = btnLoadImageFromURL.Enabled = btnCreateNewImage.Enabled = false;
Cursor = Cursors.WaitCursor;
try
{
Image = await WebHelpers.DownloadImageAsync(url);
if (IsDisposed)
{
Image?.Dispose();
return;
}
else if (Image != null)
{
DialogResult = DialogResult.OK;
Close();
return;
}
}
catch (Exception ex)
{
ex.ShowError();
}
Cursor = Cursors.Default;
btnOpenImageFile.Enabled = btnLoadImageFromClipboard.Enabled = btnLoadImageFromURL.Enabled = btnCreateNewImage.Enabled = true;
}
}
private void btnCreateNewImage_Click(object sender, EventArgs e)
{
Image = NewImageForm.CreateNewImage(Options, this);
if (Image != null)
{
DialogResult = DialogResult.OK;
Close();
}
}
private void btnCancel_Click(object sender, EventArgs e)
{
DialogResult = DialogResult.Cancel;
Close();
}
}
} | EditorStartupForm |
csharp | dotnet__BenchmarkDotNet | samples/BenchmarkDotNet.Samples/IntroHardwareCounters.cs | {
"start": 238,
"end": 1492
} | public class ____
{
private const int N = 32767;
private readonly int[] sorted, unsorted;
public IntroHardwareCounters()
{
var random = new Random(0);
unsorted = new int[N];
sorted = new int[N];
for (int i = 0; i < N; i++)
sorted[i] = unsorted[i] = random.Next(256);
Array.Sort(sorted);
}
private static int Branch(int[] data)
{
int sum = 0;
for (int i = 0; i < N; i++)
if (data[i] >= 128)
sum += data[i];
return sum;
}
private static int Branchless(int[] data)
{
int sum = 0;
for (int i = 0; i < N; i++)
{
int t = (data[i] - 128) >> 31;
sum += ~t & data[i];
}
return sum;
}
[Benchmark]
public int SortedBranch() => Branch(sorted);
[Benchmark]
public int UnsortedBranch() => Branch(unsorted);
[Benchmark]
public int SortedBranchless() => Branchless(sorted);
[Benchmark]
public int UnsortedBranchless() => Branchless(unsorted);
}
} | IntroHardwareCounters |
csharp | mongodb__mongo-csharp-driver | src/MongoDB.Driver/Core/WireProtocol/IWireProtocol.cs | {
"start": 954,
"end": 1222
} | internal interface ____<TResult>
{
bool MoreToCome { get; }
TResult Execute(OperationContext operationContext, IConnection connection);
Task<TResult> ExecuteAsync(OperationContext operationContext, IConnection connection);
}
}
| IWireProtocol |
csharp | ChilliCream__graphql-platform | src/HotChocolate/Core/test/Types.Analyzers.Tests/QueryContextConnectionAnalyzerTests.cs | {
"start": 2485,
"end": 3111
} | public class ____
{
}
"""],
enableAnalyzers: true).MatchMarkdownAsync();
}
[Fact]
public async Task TypeMismatch_WithInterfaceType_RaisesError()
{
await TestHelper.GetGeneratedSourceSnapshot(
["""
using HotChocolate;
using HotChocolate.Types;
using HotChocolate.Types.Pagination;
using GreenDonut.Data;
using System.Threading;
using System.Threading.Tasks;
namespace TestNamespace;
[InterfaceType<IProduct>]
public static | ProductService |
csharp | ServiceStack__ServiceStack | ServiceStack/tests/CheckMvc/CheckWebGlobalNamespace.dtos.cs | {
"start": 6938,
"end": 7081
} | public partial class ____
{
public virtual int Id { get; set; }
}
[Route("/matchroute/json")]
[Serializable]
| MatchesId |
csharp | MonoGame__MonoGame | MonoGame.Framework/Graphics/PackedVector/NormalizedByte2.cs | {
"start": 602,
"end": 4354
} | public struct ____ : IPackedVector<ushort>, IEquatable<NormalizedByte2>
{
private ushort _packed;
/// <summary>
/// Initializes a new instance of this structure.
/// </summary>
/// <param name="vector">
/// A <see cref="Vector2"/> value who's components contain the initial values for this structure.
/// </param>
public NormalizedByte2(Vector2 vector)
{
_packed = Pack(vector.X, vector.Y);
}
/// <summary>
/// Initializes a new instance of this structure.
/// </summary>
/// <param name="x">The initial x-component value for this structure.</param>
/// <param name="y">The initial y-component value for this structure.</param>
public NormalizedByte2(float x, float y)
{
_packed = Pack(x, y);
}
/// <summary>
/// Returns a value that indicates whether the two value are not equal.
/// </summary>
/// <param name="a">The value on the left of the inequality operator.</param>
/// <param name="b">The value on the right of the inequality operator.</param>
/// <returns>true if the two value are not equal; otherwise, false.</returns>
public static bool operator !=(NormalizedByte2 a, NormalizedByte2 b)
{
return a._packed != b._packed;
}
/// <summary>
/// Returns a value that indicates whether the two values are equal.
/// </summary>
/// <param name="a">The value on the left of the equality operator.</param>
/// <param name="b">The value on the right of the equality operator.</param>
/// <returns>true if the two values are equal; otherwise, false.</returns>
public static bool operator ==(NormalizedByte2 a, NormalizedByte2 b)
{
return a._packed == b._packed;
}
/// <inheritdoc />
public ushort PackedValue
{
get
{
return _packed;
}
set
{
_packed = value;
}
}
/// <inheritdoc />
public override bool Equals(object obj)
{
return (obj is NormalizedByte2) &&
((NormalizedByte2)obj)._packed == _packed;
}
/// <inheritdoc />
public bool Equals(NormalizedByte2 other)
{
return _packed == other._packed;
}
/// <inheritdoc />
public override int GetHashCode()
{
return _packed.GetHashCode();
}
/// <inheritdoc />
public override string ToString()
{
return _packed.ToString("X");
}
private static ushort Pack(float x, float y)
{
var byte2 = (((ushort) MathF.Round(MathHelper.Clamp(x, -1.0f, 1.0f) * 127.0f)) & 0xFF) << 0;
var byte1 = (((ushort) MathF.Round(MathHelper.Clamp(y, -1.0f, 1.0f) * 127.0f)) & 0xFF) << 8;
return (ushort)(byte2 | byte1);
}
void IPackedVector.PackFromVector4(Vector4 vector)
{
_packed = Pack(vector.X, vector.Y);
}
/// <inheritdoc />
public Vector4 ToVector4()
{
return new Vector4(ToVector2(), 0.0f, 1.0f);
}
/// <summary>
/// Expands the packed representation to a <see cref="Vector2"/>.
/// </summary>
/// <returns>The expanded value.</returns>
public Vector2 ToVector2()
{
return new Vector2(
((sbyte) ((_packed >> 0) & 0xFF)) / 127.0f,
((sbyte) ((_packed >> 8) & 0xFF)) / 127.0f);
}
}
}
| NormalizedByte2 |
csharp | unoplatform__uno | src/Uno.UI/UI/Xaml/Input/Internal/FocusSelection.cs | {
"start": 438,
"end": 4417
} | internal struct ____
{
public DirectionalFocusInfo(bool handled, bool shouldBubble, bool focusCandidateFound, bool directionalFocusEnabled)
{
Handled = handled;
ShouldBubble = shouldBubble;
FocusCandidateFound = focusCandidateFound;
DirectionalFocusEnabled = directionalFocusEnabled;
}
public static DirectionalFocusInfo Default => new DirectionalFocusInfo(false, true, false, false);
public bool Handled { get; set; }
public bool ShouldBubble { get; set; }
public bool FocusCandidateFound { get; set; }
public bool DirectionalFocusEnabled { get; set; }
}
internal static bool ShouldUpdateFocus(DependencyObject element, FocusState focusState)
{
return !(focusState == FocusState.Pointer && GetAllowFocusOnInteraction(element) == false);
}
internal static bool GetAllowFocusOnInteraction(DependencyObject element)
{
if (element is TextElement textElement)
{
return textElement.AllowFocusOnInteraction;
}
else if (element is FlyoutBase flyoutBase)
{
return flyoutBase.AllowFocusOnInteraction;
}
else if (element is FrameworkElement frameworkElement)
{
return frameworkElement.AllowFocusOnInteraction;
}
return true;
}
internal static FocusNavigationDirection GetNavigationDirection(VirtualKey key)
{
FocusNavigationDirection direction = FocusNavigationDirection.None;
switch (key)
{
case VirtualKey.GamepadDPadUp:
case VirtualKey.GamepadLeftThumbstickUp:
case VirtualKey.Up:
direction = FocusNavigationDirection.Up;
break;
case VirtualKey.GamepadDPadDown:
case VirtualKey.GamepadLeftThumbstickDown:
case VirtualKey.Down:
direction = FocusNavigationDirection.Down;
break;
case VirtualKey.GamepadDPadLeft:
case VirtualKey.GamepadLeftThumbstickLeft:
case VirtualKey.Left:
direction = FocusNavigationDirection.Left;
break;
case VirtualKey.GamepadDPadRight:
case VirtualKey.GamepadLeftThumbstickRight:
case VirtualKey.Right:
direction = FocusNavigationDirection.Right;
break;
}
return direction;
}
internal static FocusNavigationDirection GetNavigationDirectionForKeyboardArrow(VirtualKey key)
{
if (key is VirtualKey.Up)
{
return FocusNavigationDirection.Up;
}
else if (key is VirtualKey.Down)
{
return FocusNavigationDirection.Down;
}
else if (key is VirtualKey.Left)
{
return FocusNavigationDirection.Left;
}
else if (key is VirtualKey.Right)
{
return FocusNavigationDirection.Right;
}
return FocusNavigationDirection.None;
}
internal static DirectionalFocusInfo TryDirectionalFocus(IFocusManager focusManager, FocusNavigationDirection direction, DependencyObject searchScope)
{
var info = DirectionalFocusInfo.Default;
if (direction == FocusNavigationDirection.Next ||
direction == FocusNavigationDirection.Previous ||
direction == FocusNavigationDirection.None)
{
return info;
}
// We do not want to process direction focus if the element is not a UIElement (ie. Hyperlink)
if (!(searchScope is UIElement uiElement))
{
return info;
}
var mode = uiElement.XYFocusKeyboardNavigation;
if (mode == XYFocusKeyboardNavigationMode.Disabled)
{
info.ShouldBubble = false;
}
else if (mode == XYFocusKeyboardNavigationMode.Enabled)
{
info.DirectionalFocusEnabled = true;
var xyFocusOptions = XYFocusOptions.Default;
xyFocusOptions.SearchRoot = searchScope;
xyFocusOptions.ShouldConsiderXYFocusKeyboardNavigation = true;
var candidate = focusManager.FindNextFocus(new FindFocusOptions(direction), xyFocusOptions, null, true);
if (candidate != null)
{
FocusMovementResult result = focusManager.SetFocusedElement(new FocusMovement(candidate, direction, FocusState.Keyboard));
info.Handled = result.WasMoved;
info.FocusCandidateFound = true;
}
}
return info;
}
}
}
| DirectionalFocusInfo |
csharp | unoplatform__uno | src/Uno.UI.RuntimeTests/MUX/Input/KeyboardAccelerators/KeyboardAcceleratorTests.cs | {
"start": 163242,
"end": 164351
} | public partial class ____ : StackPanel
{
private readonly UnoAutoResetEvent resetEvent = new UnoAutoResetEvent(false);
public bool HasFired = false;
protected override void OnProcessKeyboardAccelerators(ProcessKeyboardAcceleratorEventArgs args)
{
foreach (UIElement current in this.Children)
{
current.TryInvokeKeyboardAccelerator(args);
}
args.Handled = true;
HasFired = true;
resetEvent.Set();
}
public async Task Wait()
{
await this.resetEvent.WaitOne(TimeSpan.FromSeconds(1));
}
public async Task WaitForNoThrow(TimeSpan timeout)
{
await this.resetEvent.WaitOne(timeout);
}
}
#pragma warning restore CS0108
public static void verifySelectedPivotItemChanged(
object sender,
int key)
{
Pivot senderAsPivot = sender as Pivot;
Verify.IsTrue(senderAsPivot != null);
Verify.AreEqual(senderAsPivot.SelectedIndex, key);
}
public static void verifyKaPlacementMode(KeyboardAcceleratorPlacementMode pMode)
{
Verify.AreEqual(pMode, KeyboardAcceleratorPlacementMode.Hidden);
}
#endregion
}
#endif
| StackPanelWithProcessKeyboardAcceleratorOverride |
csharp | Cysharp__UniTask | src/UniTask.NetCore/NetCore/AsyncEnumerableExtensions.cs | {
"start": 2438,
"end": 3104
} | sealed class ____ : IAsyncEnumerator<T>
{
readonly IUniTaskAsyncEnumerator<T> enumerator;
public Enumerator(IUniTaskAsyncEnumerator<T> enumerator)
{
this.enumerator = enumerator;
}
public T Current => enumerator.Current;
public ValueTask DisposeAsync()
{
return enumerator.DisposeAsync();
}
public ValueTask<bool> MoveNextAsync()
{
return enumerator.MoveNextAsync();
}
}
}
}
}
#endif | Enumerator |
csharp | dotnet__aspnetcore | src/Mvc/test/Mvc.FunctionalTests/AuthMiddlewareAndFilterTestBase.cs | {
"start": 435,
"end": 10561
} | public abstract class ____<TStartup> : LoggedTest where TStartup : class
{
protected override void Initialize(TestContext context, MethodInfo methodInfo, object[] testMethodArguments, ITestOutputHelper testOutputHelper)
{
base.Initialize(context, methodInfo, testMethodArguments, testOutputHelper);
Factory = new MvcTestFixture<TStartup>(LoggerFactory).WithWebHostBuilder(ConfigureWebHostBuilder);
Client = Factory.CreateDefaultClient();
}
public override void Dispose()
{
Factory.Dispose();
base.Dispose();
}
private static void ConfigureWebHostBuilder(IWebHostBuilder builder) => builder.UseStartup<TStartup>();
public WebApplicationFactory<TStartup> Factory { get; private set; }
public HttpClient Client { get; private set; }
[Fact]
public async Task AllowAnonymousOnActionsWork()
{
// Arrange & Act
var response = await Client.GetAsync("AuthorizedActions/ActionWithoutAllowAnonymous");
// Assert
await response.AssertStatusCodeAsync(HttpStatusCode.OK);
}
[Fact]
public async Task GlobalAuthFilter_AppliesToActionsWithoutAnyAuthAttributes()
{
var action = "AuthorizedActions/ActionWithoutAuthAttribute";
var response = await Client.GetAsync(action);
await AssertAuthorizeResponse(response);
// We should be able to login with ClaimA alone
var authCookie = await GetAuthCookieAsync("LoginClaimA");
var request = new HttpRequestMessage(HttpMethod.Get, action);
request.Headers.Add("Cookie", authCookie);
response = await Client.SendAsync(request);
await response.AssertStatusCodeAsync(HttpStatusCode.OK);
}
[Fact]
public async Task GlobalAuthFilter_CombinesWithAuthAttributeSpecifiedOnAction()
{
var action = "AuthorizedActions/ActionWithAuthAttribute";
var response = await Client.GetAsync(action);
await AssertAuthorizeResponse(response);
// LoginClaimA should be enough for the global auth filter, but not for the auth attribute on the action.
var authCookie = await GetAuthCookieAsync("LoginClaimA");
var request = new HttpRequestMessage(HttpMethod.Get, action);
request.Headers.Add("Cookie", authCookie);
response = await Client.SendAsync(request);
await AssertForbiddenResponse(response);
authCookie = await GetAuthCookieAsync("LoginClaimAB");
request = new HttpRequestMessage(HttpMethod.Get, action);
request.Headers.Add("Cookie", authCookie);
response = await Client.SendAsync(request);
await response.AssertStatusCodeAsync(HttpStatusCode.OK);
}
[Fact]
public async Task AllowAnonymousOnPageConfiguredViaConventionWorks()
{
// Arrange & Act
var response = await Client.GetAsync("AllowAnonymousPageViaConvention");
// Assert
await response.AssertStatusCodeAsync(HttpStatusCode.OK);
}
[Fact]
public async Task AllowAnonymousOnPageConfiguredViaModelWorks()
{
// Arrange & Act
var response = await Client.GetAsync("AllowAnonymousPageViaModel");
// Assert
await response.AssertStatusCodeAsync(HttpStatusCode.OK);
}
[Fact]
public async Task GlobalAuthFilterAppliedToPageWorks()
{
// Arrange & Act
var response = await Client.GetAsync("PagesHome");
// Assert
await AssertAuthorizeResponse(response);
// We should be able to login with ClaimA alone
var authCookie = await GetAuthCookieAsync("LoginClaimA");
var request = new HttpRequestMessage(HttpMethod.Get, "PagesHome");
request.Headers.Add("Cookie", authCookie);
response = await Client.SendAsync(request);
await response.AssertStatusCodeAsync(HttpStatusCode.OK);
}
[Fact]
public async Task CanLoginWithBearer()
{
var request = new HttpRequestMessage(HttpMethod.Get, "/Authorized/Api");
var response = await Client.SendAsync(request);
Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
var token = await GetBearerTokenAsync();
request = new HttpRequestMessage(HttpMethod.Get, "/Authorized/Api");
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", token);
response = await Client.SendAsync(request);
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
}
[Fact]
public async Task CanLoginWithBearerAfterAnonymous()
{
var request = new HttpRequestMessage(HttpMethod.Get, "/Authorized/AllowAnonymous");
var response = await Client.SendAsync(request);
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
request = new HttpRequestMessage(HttpMethod.Get, "/Authorized/Api");
response = await Client.SendAsync(request);
Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
var token = await GetBearerTokenAsync();
request = new HttpRequestMessage(HttpMethod.Get, "/Authorized/Api");
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", token);
response = await Client.SendAsync(request);
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
}
[Fact]
public async Task CanLoginWithCookie()
{
var request = new HttpRequestMessage(HttpMethod.Get, "/Authorized/Cookie");
var response = await Client.SendAsync(request);
await AssertAuthorizeResponse(response);
var cookie = await GetAuthCookieAsync("LoginDefaultScheme");
request = new HttpRequestMessage(HttpMethod.Get, "/Authorized/Cookie");
request.Headers.Add("Cookie", cookie);
response = await Client.SendAsync(request);
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
}
[Fact]
public async Task CanLoginWithCookieAfterAnonymous()
{
var request = new HttpRequestMessage(HttpMethod.Get, "/Authorized/AllowAnonymous");
var response = await Client.SendAsync(request);
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
request = new HttpRequestMessage(HttpMethod.Get, "/Authorized/Cookie");
response = await Client.SendAsync(request);
await AssertAuthorizeResponse(response);
var cookie = await GetAuthCookieAsync("LoginDefaultScheme");
request = new HttpRequestMessage(HttpMethod.Get, "/Authorized/Cookie");
request.Headers.Add("Cookie", cookie);
response = await Client.SendAsync(request);
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
}
[Fact]
public async Task CanLoginWithBearerAfterCookie()
{
var request = new HttpRequestMessage(HttpMethod.Get, "/Authorized/Cookie");
var response = await Client.SendAsync(request);
await AssertAuthorizeResponse(response);
var cookie = await GetAuthCookieAsync("LoginDefaultScheme");
request = new HttpRequestMessage(HttpMethod.Get, "/Authorized/Cookie");
request.Headers.Add("Cookie", cookie);
response = await Client.SendAsync(request);
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
request = new HttpRequestMessage(HttpMethod.Get, "/Authorized/Api");
request.Headers.Add("Cookie", cookie);
response = await Client.SendAsync(request);
Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
var token = await GetBearerTokenAsync();
request = new HttpRequestMessage(HttpMethod.Get, "/Authorized/Api");
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", token);
request.Headers.Add("Cookie", cookie);
response = await Client.SendAsync(request);
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
}
[Fact]
public Task GlobalAuthFilter_CombinesWithAuthAttributeOnPageModel()
{
// Arrange
var page = "AuthorizePageViaModel";
return LoginAB(page);
}
[Fact]
public Task GlobalAuthFilter_CombinesWithAuthAttributeSpecifiedViaConvention()
{
// Arrange
var page = "AuthorizePageViaConvention";
return LoginAB(page);
}
private async Task LoginAB(string url)
{
var response = await Client.GetAsync(url);
// Assert
await AssertAuthorizeResponse(response);
// ClaimA should be insufficient
var authCookie = await GetAuthCookieAsync("LoginClaimA");
var request = new HttpRequestMessage(HttpMethod.Get, url);
request.Headers.Add("Cookie", authCookie);
response = await Client.SendAsync(request);
await AssertForbiddenResponse(response);
authCookie = await GetAuthCookieAsync("LoginClaimAB");
request = new HttpRequestMessage(HttpMethod.Get, url);
request.Headers.Add("Cookie", authCookie);
response = await Client.SendAsync(request);
await response.AssertStatusCodeAsync(HttpStatusCode.OK);
}
private async Task AssertAuthorizeResponse(HttpResponseMessage response)
{
await response.AssertStatusCodeAsync(HttpStatusCode.Redirect);
Assert.Equal("/Account/Login", response.Headers.Location.LocalPath);
}
private async Task AssertForbiddenResponse(HttpResponseMessage response)
{
await response.AssertStatusCodeAsync(HttpStatusCode.Redirect);
Assert.Equal("/Account/AccessDenied", response.Headers.Location.LocalPath);
}
private async Task<string> GetAuthCookieAsync(string action)
{
var response = await Client.PostAsync($"Login/{action}", null);
await response.AssertStatusCodeAsync(HttpStatusCode.OK);
Assert.True(response.Headers.Contains("Set-Cookie"));
return response.Headers.GetValues("Set-Cookie").FirstOrDefault();
}
private async Task<string> GetBearerTokenAsync()
{
var response = await Client.GetAsync("/Login/LoginBearerClaimA");
return await response.Content.ReadAsStringAsync();
}
}
| AuthMiddlewareAndFilterTestBase |
csharp | ServiceStack__ServiceStack | ServiceStack/tests/ServiceStack.Server.Tests/ProxyFeatureTests.cs | {
"start": 506,
"end": 5020
} | class ____ : AppSelfHostBase
{
public AppHost()
: base(nameof(ProxyFeatureTests), typeof(ProxyFeatureTests).Assembly) { }
public override void Configure(Container container)
{
Plugins.Add(new ProxyFeature(
matchingRequests: req => req.PathInfo.StartsWith("/test"),
resolveUrl: req => "http://test.servicestack.net" + req.RawUrl.Replace("/test", "/"))
{
TransformRequest = TransformRequest,
TransformResponse = TransformResponse,
});
Plugins.Add(new ProxyFeature(
matchingRequests: req => req.PathInfo.StartsWith("/techstacks"),
resolveUrl: req => "https://www.techstacks.io" + req.RawUrl.Replace("/techstacks", "/"))
{
TransformRequest = TransformRequest,
TransformResponse = TransformResponse,
});
Plugins.Add(new ProxyFeature(
matchingRequests: req => req.PathInfo.StartsWith("/imgur-netcore"),
resolveUrl: req => "http://imgur.netcore.io" + req.RawUrl.Replace("/imgur-netcore", "/"))
);
Plugins.Add(new ProxyFeature(
matchingRequests: req => req.PathInfo.StartsWith("/chat"),
resolveUrl: req => "http://chat.servicestack.net" + req.RawUrl.Replace("/chat", "/"))
);
Plugins.Add(new ProxyFeature(
matchingRequests: req => req.PathInfo.StartsWith("/proxy"),
resolveUrl: req => req.RawUrl.Replace("/proxy/", ""))
{
IgnoreResponseHeaders = { "X-Frame-Options" },
TransformResponse = async (res, responseStream) => {
var enc = res.GetHeader(HttpHeaders.ContentEncoding);
var useStream = responseStream;
if (enc != null)
useStream = responseStream.Decompress(enc);
using (var reader = new StreamReader(useStream,Encoding.UTF8))
{
var responseBody = await reader.ReadToEndAsync();
var replacedBody = responseBody.Replace("http://","/proxy/http://");
replacedBody = replacedBody.Replace("https://", "/proxy/https://");
var bytes = replacedBody.ToUtf8Bytes();
return MemoryStreamFactory.GetStream(enc != null ? bytes.CompressBytes(enc) : bytes);
}
}
});
//Allow this proxy server to issue ss-id/ss-pid Session Cookies
//Plugins.Add(new SessionFeature());
}
private async Task<Stream> TransformRequest(IHttpRequest req, Stream reqStream)
{
var reqReplace = req.QueryString["reqReplace"];
if (reqReplace != null)
{
var reqBody = await reqStream.ReadToEndAsync();
var parts = reqReplace.SplitOnFirst(',');
var replacedBody = reqBody.Replace(parts[0], parts[1]);
return MemoryStreamFactory.GetStream(replacedBody.ToUtf8Bytes());
}
return reqStream;
}
private async Task<Stream> TransformResponse(IHttpResponse res, Stream resStream)
{
var req = res.Request;
var resReplace = req.QueryString["resReplace"];
if (resReplace != null)
{
var resBody = await resStream.ReadToEndAsync();
var parts = resReplace.SplitOnFirst(',');
var replacedBody = resBody.Replace(parts[0], parts[1]);
return MemoryStreamFactory.GetStream(replacedBody.ToUtf8Bytes());
}
return resStream;
}
}
private readonly ServiceStackHost appHost;
public ProxyFeatureTests()
{
appHost = new AppHost()
.Init()
.Start(ListeningOn);
}
[OneTimeTearDown] public void OneTimeTearDown() => appHost.Dispose();
[Route("/echo/types")]
| AppHost |
csharp | dotnet__aspnetcore | src/Tools/GetDocumentInsider/src/Commands/GetDocumentCommand.cs | {
"start": 5471,
"end": 5690
} | private sealed class ____
{
public AssemblyInfo(string path)
{
Path = path;
}
public string Path { get; }
public Assembly Assembly { get; set; }
}
}
| AssemblyInfo |
csharp | npgsql__efcore.pg | src/EFCore.PG/Query/ExpressionTranslators/Internal/NpgsqlFuzzyStringMatchMethodTranslator.cs | {
"start": 537,
"end": 4236
} | public class ____ : IMethodCallTranslator
{
private static readonly Dictionary<MethodInfo, string> Functions = new()
{
[GetRuntimeMethod(nameof(NpgsqlFuzzyStringMatchDbFunctionsExtensions.FuzzyStringMatchSoundex), typeof(DbFunctions), typeof(string))]
= "soundex",
[GetRuntimeMethod(nameof(NpgsqlFuzzyStringMatchDbFunctionsExtensions.FuzzyStringMatchDifference), typeof(DbFunctions), typeof(string), typeof(string))]
= "difference",
[GetRuntimeMethod(nameof(NpgsqlFuzzyStringMatchDbFunctionsExtensions.FuzzyStringMatchLevenshtein), typeof(DbFunctions), typeof(string), typeof(string))]
= "levenshtein",
[GetRuntimeMethod(nameof(NpgsqlFuzzyStringMatchDbFunctionsExtensions.FuzzyStringMatchLevenshtein), typeof(DbFunctions), typeof(string), typeof(string), typeof(int), typeof(int), typeof(int))]
= "levenshtein",
[GetRuntimeMethod(nameof(NpgsqlFuzzyStringMatchDbFunctionsExtensions.FuzzyStringMatchLevenshteinLessEqual), typeof(DbFunctions), typeof(string), typeof(string), typeof(int))]
= "levenshtein_less_equal",
[GetRuntimeMethod(nameof(NpgsqlFuzzyStringMatchDbFunctionsExtensions.FuzzyStringMatchLevenshteinLessEqual), typeof(DbFunctions), typeof(string), typeof(string), typeof(int), typeof(int), typeof(int), typeof(int))]
= "levenshtein_less_equal",
[GetRuntimeMethod(nameof(NpgsqlFuzzyStringMatchDbFunctionsExtensions.FuzzyStringMatchMetaphone), typeof(DbFunctions), typeof(string), typeof(int))]
= "metaphone",
[GetRuntimeMethod(nameof(NpgsqlFuzzyStringMatchDbFunctionsExtensions.FuzzyStringMatchDoubleMetaphone), typeof(DbFunctions), typeof(string))]
= "dmetaphone",
[GetRuntimeMethod(nameof(NpgsqlFuzzyStringMatchDbFunctionsExtensions.FuzzyStringMatchDoubleMetaphoneAlt), typeof(DbFunctions), typeof(string))]
= "dmetaphone_alt"
};
private static MethodInfo GetRuntimeMethod(string name, params Type[] parameters)
=> typeof(NpgsqlFuzzyStringMatchDbFunctionsExtensions).GetRuntimeMethod(name, parameters)!;
private readonly NpgsqlSqlExpressionFactory _sqlExpressionFactory;
private static readonly bool[][] TrueArrays =
[
[],
[true],
[true, true],
[true, true, true],
[true, true, true, true],
[true, true, true, true, true],
[true, true, true, true, true, true]
];
/// <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>
public NpgsqlFuzzyStringMatchMethodTranslator(NpgsqlSqlExpressionFactory sqlExpressionFactory)
{
_sqlExpressionFactory = sqlExpressionFactory;
}
/// <inheritdoc />
public virtual SqlExpression? Translate(
SqlExpression? instance,
MethodInfo method,
IReadOnlyList<SqlExpression> arguments,
IDiagnosticsLogger<DbLoggerCategory.Query> logger)
=> Functions.TryGetValue(method, out var function)
? _sqlExpressionFactory.Function(
function,
arguments.Skip(1),
nullable: true,
argumentsPropagateNullability: TrueArrays[arguments.Count - 1],
method.ReturnType)
: null;
}
| NpgsqlFuzzyStringMatchMethodTranslator |
csharp | reactiveui__ReactiveUI | src/ReactiveUI.AndroidX/ReactiveFragment.cs | {
"start": 807,
"end": 3080
} | public class ____ : global::AndroidX.Fragment.App.Fragment, IReactiveNotifyPropertyChanged<ReactiveFragment>, IReactiveObject, IHandleObservableErrors
{
private readonly Subject<Unit> _activated = new();
private readonly Subject<Unit> _deactivated = new();
/// <summary>
/// Initializes a new instance of the <see cref="ReactiveFragment"/> class.
/// </summary>
protected ReactiveFragment()
{
}
/// <inheritdoc/>
public event PropertyChangingEventHandler? PropertyChanging;
/// <inheritdoc/>
public event PropertyChangedEventHandler? PropertyChanged;
/// <inheritdoc/>
public IObservable<Exception> ThrownExceptions => this.GetThrownExceptionsObservable();
/// <summary>
/// Gets a signal when the fragment is activated.
/// </summary>
public IObservable<Unit> Activated => _activated.AsObservable();
/// <summary>
/// Gets a signal when the fragment is deactivated.
/// </summary>
public IObservable<Unit> Deactivated => _deactivated.AsObservable();
/// <inheritdoc />
public IObservable<IReactivePropertyChangedEventArgs<ReactiveFragment>> Changing => this.GetChangingObservable();
/// <inheritdoc />
public IObservable<IReactivePropertyChangedEventArgs<ReactiveFragment>> Changed => this.GetChangedObservable();
/// <inheritdoc/>
void IReactiveObject.RaisePropertyChanging(PropertyChangingEventArgs args) => PropertyChanging?.Invoke(this, args);
/// <inheritdoc/>
void IReactiveObject.RaisePropertyChanged(PropertyChangedEventArgs args) => PropertyChanged?.Invoke(this, args);
/// <inheritdoc />
public IDisposable SuppressChangeNotifications() => IReactiveObjectExtensions.SuppressChangeNotifications(this);
/// <inheritdoc/>
public override void OnPause()
{
base.OnPause();
_deactivated.OnNext(Unit.Default);
}
/// <inheritdoc/>
public override void OnResume()
{
base.OnResume();
_activated.OnNext(Unit.Default);
}
/// <inheritdoc/>
protected override void Dispose(bool disposing)
{
if (disposing)
{
_activated.Dispose();
_deactivated.Dispose();
}
base.Dispose(disposing);
}
}
| ReactiveFragment |
csharp | microsoft__semantic-kernel | dotnet/src/Functions/Functions.UnitTests/OpenApi/Serialization/OpenApiTypeConverterTests.cs | {
"start": 343,
"end": 7099
} | public class ____
{
[Fact]
public void ItShouldConvertString()
{
// Act & Assert
Assert.Equal("\"test\"", OpenApiTypeConverter.Convert("id", "string", "test").ToString());
Assert.Equal("test", OpenApiTypeConverter.Convert("id", "string", CreateJsonElement("test")).ToString());
}
[Fact]
public void ItShouldConvertNumber()
{
// Act & Assert - Basic numeric types
Assert.Equal("10", OpenApiTypeConverter.Convert("id", "number", (byte)10).ToString());
Assert.Equal("10", OpenApiTypeConverter.Convert("id", "number", (sbyte)10).ToString());
Assert.Equal("10", OpenApiTypeConverter.Convert("id", "number", (short)10).ToString());
Assert.Equal("10", OpenApiTypeConverter.Convert("id", "number", (ushort)10).ToString());
Assert.Equal("10", OpenApiTypeConverter.Convert("id", "number", (int)10).ToString());
Assert.Equal("10", OpenApiTypeConverter.Convert("id", "number", (uint)10).ToString());
Assert.Equal("10", OpenApiTypeConverter.Convert("id", "number", (long)10).ToString());
Assert.Equal("10", OpenApiTypeConverter.Convert("id", "number", (ulong)10).ToString());
Assert.Equal("10.5", OpenApiTypeConverter.Convert("id", "number", (float)10.5).ToString());
Assert.Equal("10.5", OpenApiTypeConverter.Convert("id", "number", (double)10.5).ToString());
Assert.Equal("10.5", OpenApiTypeConverter.Convert("id", "number", (decimal)10.5).ToString());
// String conversions
Assert.Equal("10", OpenApiTypeConverter.Convert("id", "number", "10").ToString());
Assert.Equal("10.5", OpenApiTypeConverter.Convert("id", "number", "10.5").ToString());
// JsonElement conversions
Assert.Equal("10", OpenApiTypeConverter.Convert("id", "number", CreateJsonElement(10)).ToString());
Assert.Equal("10.5", OpenApiTypeConverter.Convert("id", "number", CreateJsonElement(10.5)).ToString());
}
[Fact]
public void ItShouldConvertInteger()
{
// Act & Assert - Basic integer types
Assert.Equal("10", OpenApiTypeConverter.Convert("id", "integer", (byte)10).ToString());
Assert.Equal("10", OpenApiTypeConverter.Convert("id", "integer", (sbyte)10).ToString());
Assert.Equal("10", OpenApiTypeConverter.Convert("id", "integer", (short)10).ToString());
Assert.Equal("10", OpenApiTypeConverter.Convert("id", "integer", (ushort)10).ToString());
Assert.Equal("10", OpenApiTypeConverter.Convert("id", "integer", (int)10).ToString());
Assert.Equal("10", OpenApiTypeConverter.Convert("id", "integer", (uint)10).ToString());
Assert.Equal("10", OpenApiTypeConverter.Convert("id", "integer", (long)10).ToString());
Assert.Equal("10", OpenApiTypeConverter.Convert("id", "integer", (ulong)10).ToString());
// String conversion
Assert.Equal("10", OpenApiTypeConverter.Convert("id", "integer", "10").ToString());
// JsonElement conversion
Assert.Equal("10", OpenApiTypeConverter.Convert("id", "integer", CreateJsonElement(10)).ToString());
}
[Fact]
public void ItShouldConvertBoolean()
{
// Act & Assert - Basic boolean values
Assert.Equal("true", OpenApiTypeConverter.Convert("id", "boolean", true).ToString());
Assert.Equal("false", OpenApiTypeConverter.Convert("id", "boolean", false).ToString());
// String conversions
Assert.Equal("true", OpenApiTypeConverter.Convert("id", "boolean", "true").ToString());
Assert.Equal("false", OpenApiTypeConverter.Convert("id", "boolean", "false").ToString());
// JsonElement conversions
Assert.Equal("true", OpenApiTypeConverter.Convert("id", "boolean", CreateJsonElement(true)).ToString());
Assert.Equal("false", OpenApiTypeConverter.Convert("id", "boolean", CreateJsonElement(false)).ToString());
}
[Fact]
public void ItShouldConvertDateTime()
{
// Arrange
var dateTime = DateTime.ParseExact("06.12.2023 11:53:36+02:00", "dd.MM.yyyy HH:mm:sszzz", CultureInfo.InvariantCulture, DateTimeStyles.AdjustToUniversal);
// Act & Assert
Assert.Equal("\"2023-12-06T09:53:36Z\"", OpenApiTypeConverter.Convert("id", "string", dateTime).ToString());
}
[Fact]
public void ItShouldConvertDateTimeOffset()
{
// Arrange
var offset = DateTimeOffset.ParseExact("06.12.2023 11:53:36 +02:00", "dd.MM.yyyy HH:mm:ss zzz", CultureInfo.InvariantCulture);
// Act & Assert
Assert.Equal("\"2023-12-06T11:53:36+02:00\"", OpenApiTypeConverter.Convert("id", "string", offset).ToString());
}
[Fact]
public void ItShouldConvertCollections()
{
// Act & Assert - Basic collections
Assert.Equal("[1,2,3]", OpenApiTypeConverter.Convert("id", "array", new[] { 1, 2, 3 }).ToJsonString());
Assert.Equal("[1,2,3]", OpenApiTypeConverter.Convert("id", "array", new List<int> { 1, 2, 3 }).ToJsonString());
Assert.Equal("[1,2,3]", OpenApiTypeConverter.Convert("id", "array", new Collection() { 1, 2, 3 }).ToJsonString());
Assert.Equal("[1,2,3]", OpenApiTypeConverter.Convert("id", "array", "[1, 2, 3]").ToJsonString());
// JsonElement array conversion
Assert.Equal("[1,2,3]", OpenApiTypeConverter.Convert("id", "array", CreateJsonElement(new[] { 1, 2, 3 })).ToJsonString());
}
[Fact]
public void ItShouldConvertWithNoTypeAndNoSchema()
{
// Act
var result = OpenApiTypeConverter.Convert("lat", null!, 51.8985136);
// Assert
Assert.Equal(51.8985136, result.GetValue<double>());
}
[Fact]
public void ItShouldConvertWithNoTypeAndValidSchema()
{
// Arrange
var schema = KernelJsonSchema.Parse(
"""
{
"type": "number",
"format": "double",
"nullable": false
}
""");
// Act
var result = OpenApiTypeConverter.Convert("lat", null!, 51.8985136, schema);
// Assert
Assert.Equal(51.8985136, result.GetValue<double>());
}
[Fact]
public void ItShouldThrowExceptionWhenNoTypeAndInvalidSchema()
{
// Arrange
var schema = KernelJsonSchema.Parse(
"""
{
"type": "boolean",
"nullable": false
}
""");
// Act & Assert
Assert.Throws<ArgumentOutOfRangeException>(() => OpenApiTypeConverter.Convert("lat", null!, 51.8985136, schema));
}
private static JsonElement CreateJsonElement(object value)
{
var json = JsonSerializer.Serialize(value);
return JsonSerializer.Deserialize<JsonElement>(json)!;
}
}
| OpenApiTypeConverterTests |
csharp | microsoft__garnet | libs/server/ServerConfig.cs | {
"start": 1534,
"end": 16517
} | partial class ____ : ServerSessionBase
{
private bool NetworkCONFIG_GET()
{
if (parseState.Count == 0)
{
return AbortWithWrongNumberOfArguments($"{nameof(RespCommand.CONFIG)}|{nameof(CmdStrings.GET)}");
}
// Extract requested parameters
HashSet<ServerConfigType> parameters = [];
var returnAll = false;
for (var i = 0; i < parseState.Count; i++)
{
var parameter = parseState.GetArgSliceByRef(i).Span;
var serverConfigType = ServerConfig.GetConfig(parameter);
if (returnAll) continue;
if (serverConfigType == ServerConfigType.ALL)
{
parameters = ServerConfig.DefaultConfigType;
returnAll = true;
continue;
}
if (serverConfigType != ServerConfigType.NONE)
_ = parameters.Add(serverConfigType);
}
// Generate response for matching parameters
if (parameters.Count > 0)
{
WriteMapLength(parameters.Count);
foreach (var parameter in parameters)
{
var parameterValue = parameter switch
{
ServerConfigType.TIMEOUT => "$7\r\ntimeout\r\n$1\r\n0\r\n"u8,
ServerConfigType.SAVE => "$4\r\nsave\r\n$0\r\n\r\n"u8,
ServerConfigType.APPENDONLY => storeWrapper.serverOptions.EnableAOF ? "$10\r\nappendonly\r\n$3\r\nyes\r\n"u8 : "$10\r\nappendonly\r\n$2\r\nno\r\n"u8,
ServerConfigType.SLAVE_READ_ONLY => clusterSession == null || clusterSession.ReadWriteSession ? "$15\r\nslave-read-only\r\n$2\r\nno\r\n"u8 : "$15\r\nslave-read-only\r\n$3\r\nyes\r\n"u8,
ServerConfigType.DATABASES => GetDatabases(),
ServerConfigType.CLUSTER_NODE_TIMEOUT => Encoding.ASCII.GetBytes($"$20\r\ncluster-node-timeout\r\n${storeWrapper.serverOptions.ClusterTimeout.ToString().Length}\r\n{storeWrapper.serverOptions.ClusterTimeout}\r\n"),
ServerConfigType.NONE => throw new NotImplementedException(),
ServerConfigType.ALL => throw new NotImplementedException(),
_ => throw new NotImplementedException()
};
ReadOnlySpan<byte> GetDatabases()
{
var databases = storeWrapper.serverOptions.MaxDatabases.ToString();
return Encoding.ASCII.GetBytes($"$9\r\ndatabases\r\n${databases.Length}\r\n{databases}\r\n");
}
while (!RespWriteUtils.TryWriteDirect(parameterValue, ref dcurr, dend))
SendAndReset();
}
}
else
{
while (!RespWriteUtils.TryWriteDirect(CmdStrings.RESP_EMPTYLIST, ref dcurr, dend))
SendAndReset();
}
return true;
}
private bool NetworkCONFIG_REWRITE()
{
if (parseState.Count != 0)
{
return AbortWithWrongNumberOfArguments($"{nameof(RespCommand.CONFIG)}|{nameof(CmdStrings.REWRITE)}");
}
storeWrapper.clusterProvider?.FlushConfig();
while (!RespWriteUtils.TryWriteDirect(CmdStrings.RESP_OK, ref dcurr, dend))
SendAndReset();
return true;
}
private bool NetworkCONFIG_SET()
{
if (parseState.Count == 0 || parseState.Count % 2 != 0)
{
return AbortWithWrongNumberOfArguments($"{nameof(RespCommand.CONFIG)}|{nameof(CmdStrings.SET)}");
}
string certFileName = null;
string certPassword = null;
string clusterUsername = null;
string clusterPassword = null;
string memorySize = null;
string objLogMemory = null;
string objHeapMemory = null;
string index = null;
string objIndex = null;
var unknownOption = false;
var unknownKey = "";
for (var c = 0; c < parseState.Count; c += 2)
{
var key = parseState.GetArgSliceByRef(c).ReadOnlySpan;
var value = parseState.GetArgSliceByRef(c + 1).ReadOnlySpan;
if (key.EqualsLowerCaseSpanIgnoringCase(CmdStrings.Memory, allowNonAlphabeticChars: false))
memorySize = Encoding.ASCII.GetString(value);
else if (key.EqualsLowerCaseSpanIgnoringCase(CmdStrings.ObjLogMemory, allowNonAlphabeticChars: true))
objLogMemory = Encoding.ASCII.GetString(value);
else if (key.EqualsLowerCaseSpanIgnoringCase(CmdStrings.ObjHeapMemory, allowNonAlphabeticChars: true))
objHeapMemory = Encoding.ASCII.GetString(value);
else if (key.EqualsLowerCaseSpanIgnoringCase(CmdStrings.Index, allowNonAlphabeticChars: false))
index = Encoding.ASCII.GetString(value);
else if (key.EqualsLowerCaseSpanIgnoringCase(CmdStrings.ObjIndex, allowNonAlphabeticChars: true))
objIndex = Encoding.ASCII.GetString(value);
else if (key.EqualsLowerCaseSpanIgnoringCase(CmdStrings.CertFileName, allowNonAlphabeticChars: true))
certFileName = Encoding.ASCII.GetString(value);
else if (key.EqualsLowerCaseSpanIgnoringCase(CmdStrings.CertPassword, allowNonAlphabeticChars: true))
certPassword = Encoding.ASCII.GetString(value);
else if (key.EqualsLowerCaseSpanIgnoringCase(CmdStrings.ClusterUsername, allowNonAlphabeticChars: true))
clusterUsername = Encoding.ASCII.GetString(value);
else if (key.EqualsLowerCaseSpanIgnoringCase(CmdStrings.ClusterPassword, allowNonAlphabeticChars: true))
clusterPassword = Encoding.ASCII.GetString(value);
else
{
if (!unknownOption)
{
unknownOption = true;
unknownKey = Encoding.ASCII.GetString(key);
}
}
}
var sbErrorMsg = new StringBuilder();
if (unknownOption)
{
AppendError(sbErrorMsg, string.Format(CmdStrings.GenericErrUnknownOptionConfigSet, unknownKey));
}
else
{
if (clusterUsername != null || clusterPassword != null)
{
if (clusterUsername == null)
logger?.LogWarning("Cluster username is not provided, will use new password with existing username");
if (storeWrapper.clusterProvider != null)
storeWrapper.clusterProvider?.UpdateClusterAuth(clusterUsername, clusterPassword);
else
{
AppendError(sbErrorMsg, "ERR Cluster is disabled.");
}
}
if (certFileName != null || certPassword != null)
{
if (storeWrapper.serverOptions.TlsOptions != null)
{
if (!storeWrapper.serverOptions.TlsOptions.UpdateCertFile(certFileName, certPassword, out var certErrorMessage))
{
AppendError(sbErrorMsg, certErrorMessage);
}
}
else
{
sbErrorMsg.AppendLine("ERR TLS is disabled.");
}
}
if (memorySize != null)
HandleMemorySizeChange(memorySize, sbErrorMsg);
if (objLogMemory != null)
HandleMemorySizeChange(objLogMemory, sbErrorMsg, mainStore: false);
if (index != null)
HandleIndexSizeChange(index, sbErrorMsg);
if (objIndex != null)
HandleIndexSizeChange(objIndex, sbErrorMsg, mainStore: false);
if (objHeapMemory != null)
HandleObjHeapMemorySizeChange(objHeapMemory, sbErrorMsg);
}
if (sbErrorMsg.Length == 0)
{
while (!RespWriteUtils.TryWriteDirect(CmdStrings.RESP_OK, ref dcurr, dend))
SendAndReset();
}
else
{
while (!RespWriteUtils.TryWriteError(sbErrorMsg.ToString(), ref dcurr, dend))
SendAndReset();
}
return true;
}
private void HandleMemorySizeChange(string memorySize, StringBuilder sbErrorMsg, bool mainStore = true)
{
var option = mainStore ? CmdStrings.Memory : CmdStrings.ObjLogMemory;
if (!ServerOptions.TryParseSize(memorySize, out var newMemorySize))
{
AppendErrorWithTemplate(sbErrorMsg, CmdStrings.GenericErrIncorrectSizeFormat, option);
return;
}
// Parse the configured memory size
var confMemorySize = ServerOptions.ParseSize(
mainStore ? storeWrapper.serverOptions.MemorySize
: storeWrapper.serverOptions.ObjectStoreLogMemorySize, out _);
// If the new memory size is the same as the configured memory size, nothing to do
if (newMemorySize == confMemorySize)
return;
// Calculate the buffer size based on the configured memory size
confMemorySize = ServerOptions.NextPowerOf2(confMemorySize);
// If the new memory size is greater than the configured memory size, return an error
if (newMemorySize > confMemorySize)
{
AppendErrorWithTemplate(sbErrorMsg, CmdStrings.GenericErrMemorySizeGreaterThanBuffer, option);
return;
}
// Parse & adjust the configured page size
var pageSize = ServerOptions.ParseSize(
mainStore ? storeWrapper.serverOptions.PageSize : storeWrapper.serverOptions.ObjectStorePageSize,
out _);
pageSize = ServerOptions.PreviousPowerOf2(pageSize);
// Compute the new minimum empty page count and update the store's log accessor
var newMinEmptyPageCount = (int)((confMemorySize - newMemorySize) / pageSize);
if (mainStore)
{
storeWrapper.store.Log.MinEmptyPageCount = newMinEmptyPageCount;
}
else
{
storeWrapper.objectStore.Log.MinEmptyPageCount = newMinEmptyPageCount;
}
}
private void HandleIndexSizeChange(string indexSize, StringBuilder sbErrorMsg, bool mainStore = true)
{
var option = mainStore ? CmdStrings.Index : CmdStrings.ObjIndex;
if (!ServerOptions.TryParseSize(indexSize, out var newIndexSize))
{
AppendErrorWithTemplate(sbErrorMsg, CmdStrings.GenericErrIncorrectSizeFormat, option);
return;
}
// Check if the new index size is a power of two. If not - return an error.
var adjNewIndexSize = ServerOptions.PreviousPowerOf2(newIndexSize);
if (adjNewIndexSize != newIndexSize)
{
AppendErrorWithTemplate(sbErrorMsg, CmdStrings.GenericErrIndexSizePowerOfTwo, option);
return;
}
// Check if the index auto-grow task is running. If so - return an error.
if ((mainStore && storeWrapper.serverOptions.AdjustedIndexMaxCacheLines > 0) ||
(!mainStore && storeWrapper.serverOptions.AdjustedObjectStoreIndexMaxCacheLines > 0))
{
AppendErrorWithTemplate(sbErrorMsg, CmdStrings.GenericErrIndexSizeAutoGrow, option);
return;
}
var currIndexSize = mainStore ? storeWrapper.store.IndexSize : storeWrapper.objectStore.IndexSize;
// Convert new index size to cache lines
adjNewIndexSize /= 64;
// If the current index size is the same as the new index size, nothing to do
if (currIndexSize == adjNewIndexSize)
return;
// If the new index size is smaller than the current index size, return an error
if (currIndexSize > adjNewIndexSize)
{
AppendErrorWithTemplate(sbErrorMsg, CmdStrings.GenericErrIndexSizeSmallerThanCurrent, option);
return;
}
// Try to grow the index size by doubling it until it reaches the new size
while (currIndexSize < adjNewIndexSize)
{
var isSuccessful = mainStore
? storeWrapper.store.GrowIndexAsync().ConfigureAwait(false).GetAwaiter().GetResult()
: storeWrapper.objectStore.GrowIndexAsync().ConfigureAwait(false).GetAwaiter().GetResult();
if (!isSuccessful)
{
AppendErrorWithTemplate(sbErrorMsg, CmdStrings.GenericErrIndexSizeGrowFailed, option);
return;
}
currIndexSize *= 2;
}
}
private void HandleObjHeapMemorySizeChange(string heapMemorySize, StringBuilder sbErrorMsg)
{
if (!ServerOptions.TryParseSize(heapMemorySize, out var newHeapMemorySize))
{
AppendErrorWithTemplate(sbErrorMsg, CmdStrings.GenericErrIncorrectSizeFormat, CmdStrings.ObjHeapMemory);
return;
}
// If the object store size tracker is not running, return an error
if (storeWrapper.objectStoreSizeTracker == null)
{
AppendErrorWithTemplate(sbErrorMsg, CmdStrings.GenericErrHeapMemorySizeTrackerNotRunning, CmdStrings.ObjHeapMemory);
return;
}
// Set the new target size for the object store size tracker
storeWrapper.objectStoreSizeTracker.TargetSize = newHeapMemorySize;
}
private static void AppendError(StringBuilder sbErrorMsg, string error)
{
sbErrorMsg.Append($"{(sbErrorMsg.Length == 0 ? error : $"; {error.Substring(4)}")}");
}
private static void AppendErrorWithTemplate(StringBuilder sbErrorMsg, string template, ReadOnlySpan<byte> option)
{
var error = string.Format(template, Encoding.ASCII.GetString(option));
AppendError(sbErrorMsg, error);
}
}
} | RespServerSession |
csharp | ServiceStack__ServiceStack | ServiceStack.Text/src/ServiceStack.Text/DynamicNumber.cs | {
"start": 35173,
"end": 35538
} | internal static class ____
{
internal static object ParseString(this IDynamicNumber number, object value)
{
if (value is string s)
return number.TryParse(s, out object x) ? x : null;
if (value is char c)
return number.TryParse(c.ToString(), out object x) ? x : null;
return null;
}
} | DynamicNumberExtensions |
csharp | dotnet__aspnetcore | src/Shared/Nullable/NullableAttributes.cs | {
"start": 3035,
"end": 3846
} |
sealed class ____ : Attribute
{
/// <summary>Initializes the attribute with the specified return value condition.</summary>
/// <param name="returnValue">
/// The return value condition. If the method returns this value, the associated parameter will not be null.
/// </param>
public NotNullWhenAttribute(bool returnValue) => ReturnValue = returnValue;
/// <summary>Gets the return value condition.</summary>
public bool ReturnValue { get; }
}
/// <summary>Specifies that the output will be non-null if the named parameter is non-null.</summary>
[AttributeUsage(AttributeTargets.Parameter | AttributeTargets.Property | AttributeTargets.ReturnValue, AllowMultiple = true, Inherited = false)]
#if INTERNAL_NULLABLE_ATTRIBUTES
internal
#else
public
#endif | NotNullWhenAttribute |
csharp | files-community__Files | src/Files.App/Utils/Storage/Collection/GroupedCollection.cs | {
"start": 106,
"end": 1703
} | public sealed class ____<T> : BulkConcurrentObservableCollection<T>, IGroupedCollectionHeader
{
public GroupedHeaderViewModel Model { get; set; }
public GroupedCollection(IEnumerable<T> items) : base(items)
{
AddEvents();
}
public GroupedCollection(string key) : base()
{
AddEvents();
Model = new GroupedHeaderViewModel()
{
Key = key,
Text = key,
};
}
public GroupedCollection(string key, string text) : base()
{
AddEvents();
Model = new GroupedHeaderViewModel()
{
Key = key,
Text = text,
};
}
private void AddEvents()
{
PropertyChanged += GroupedCollection_PropertyChanged;
}
private void GroupedCollection_PropertyChanged(object sender, PropertyChangedEventArgs e)
{
if (e.PropertyName == nameof(Count))
{
Model.CountText = string.Format(
Count > 1
? Strings.GroupItemsCount_Plural.GetLocalizedResource()
: Strings.GroupItemsCount_Singular.GetLocalizedResource(),
Count);
}
}
public void InitializeExtendedGroupHeaderInfoAsync()
{
if (GetExtendedGroupHeaderInfo is null)
return;
Model.ResumePropertyChangedNotifications(false);
GetExtendedGroupHeaderInfo.Invoke(this);
Model.Initialized = true;
if (isBulkOperationStarted)
Model.PausePropertyChangedNotifications();
}
public override void BeginBulkOperation()
{
base.BeginBulkOperation();
Model.PausePropertyChangedNotifications();
}
public override void EndBulkOperation()
{
base.EndBulkOperation();
Model.ResumePropertyChangedNotifications();
}
}
}
| GroupedCollection |
csharp | ChilliCream__graphql-platform | src/StrawberryShake/CodeGeneration/src/CodeGeneration/Descriptors/TypeDescriptors/InterfaceTypeDescriptor.cs | {
"start": 71,
"end": 1052
} | public sealed class ____ : ComplexTypeDescriptor
{
public InterfaceTypeDescriptor(
string name,
TypeKind typeKind,
RuntimeTypeInfo runtimeType,
IReadOnlyCollection<ObjectTypeDescriptor> implementedBy,
IReadOnlyList<string> implements,
IReadOnlyList<DeferredFragmentDescriptor>? deferred,
string? description,
RuntimeTypeInfo? parentRuntimeType = null)
: base(
name,
typeKind,
runtimeType,
implements,
deferred,
description,
parentRuntimeType)
{
ImplementedBy = implementedBy;
}
/// <summary>
/// A list of types that implement this interface
/// This list must only contain the most specific, concrete classes (that implement this
/// interface), but no other interfaces.
/// </summary>
public IReadOnlyCollection<ObjectTypeDescriptor> ImplementedBy { get; }
}
| InterfaceTypeDescriptor |
csharp | grandnode__grandnode2 | src/Business/Grand.Business.Checkout/Queries/Handlers/Orders/CanPartiallyRefundQueryHandler.cs | {
"start": 213,
"end": 1557
} | public class ____ : IRequestHandler<CanPartiallyRefundQuery, bool>
{
private readonly IPaymentService _paymentService;
public CanPartiallyRefundQueryHandler(IPaymentService paymentService)
{
_paymentService = paymentService;
}
public async Task<bool> Handle(CanPartiallyRefundQuery request, CancellationToken cancellationToken)
{
var paymentTransaction = request.PaymentTransaction;
ArgumentNullException.ThrowIfNull(paymentTransaction);
var amountToRefund = request.AmountToRefund;
if (paymentTransaction.TransactionAmount == 0)
return false;
//uncomment the lines below in order to allow this operation for cancelled orders
//if (order.OrderStatus == OrderStatus.Cancelled)
// return false;
var canBeRefunded = paymentTransaction.TransactionAmount - paymentTransaction.RefundedAmount;
if (canBeRefunded <= 0)
return false;
if (amountToRefund > canBeRefunded)
return false;
return paymentTransaction.TransactionStatus is TransactionStatus.Paid or TransactionStatus.PartialPaid
or TransactionStatus.PartiallyRefunded &&
await _paymentService.SupportPartiallyRefund(paymentTransaction.PaymentMethodSystemName);
}
} | CanPartiallyRefundQueryHandler |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.